var popup = null;
var timer = null;

function showEmailForm(email, name, img_src)
{
	if (popup != null)
		popup.style.display = 'none';

	popup = document.getElementById('emailForm');

	document.getElementById('email_contact_name').innerHTML = name;
	document.send_email_form.email_to.value = email;
	document.send_email_form.name_to.value = name;
	document.send_email_form.image_to.value = img_src;
	document.getElementById('email_image').src = 'images/team/' + img_src;

	positionDiv(popup);
	timer = setInterval("positionDiv(popup)", 250);
	popup.style.display = 'block';
}

function hideEmailForm()
{
	if (popup != null)
		popup.style.display = 'none';

	if (timer != null)
		clearTimeout(timer);
}

function showEmailConfirmation(success)
{
	if (popup != null)
		popup.style.display = 'none';

	if (success)
		popup = document.getElementById('email_confirmation_success');
	else
		popup = document.getElementById('email_confirmation_error');

	positionDiv(popup);
	timer = setInterval("positionDiv(popup)", 250);
	popup.style.display = 'block';
}

function positionDiv(obj)
{
	if (obj.style.display != 'block') {
		return;
	}

	scrollTop = document.documentElement.scrollTop;
	if (scrollTop == 0)
		scrollTop = document.body.scrollTop;

	y = scrollTop + parseInt((document.body.clientHeight - 600) / 2);
	x = parseInt((document.body.clientWidth - 600) / 2);

	obj.style.top = y + 'px';
	obj.style.left = x + 'px';
}

function validEmail(email)
{
	return email.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i);
}

function email_removeChildren(elem)
{
	while (elem.childNodes.length)
		elem.removeChild(elem.childNodes[0]);
}

function email_showError(elem, text)
{
	var err_elem = document.createTextNode(text);

	email_removeChildren(elem)
	elem.appendChild(err_elem);
}

function validateEmailForm()
{
	var hasError = false;
	var fields = ['name', 'email', 'phone', 'captcha'];

	for (var i in fields) {
		err_elem = document.getElementById('err_client_' + fields[i]);
		email_removeChildren(err_elem);
		if (document.getElementById('client_' + fields[i]).value == "") {
			if (fields[i] != 'captcha') {
				email_showError(err_elem, '<< Please enter your ' + fields[i]);
			} else {
				email_showError(err_elem, '<< Please enter the web form code');
			}
			hasError = true;
		}
	}

	email = document.getElementById('client_email').value
	if (email != '' && !validEmail(email)) {
		email_showError(document.getElementById('err_client_email'), '<< Please enter a valid email address');
		return false;
	}

	return !hasError;
}
