// Quiz Results page functions

function sendMessage(contactForm)
{
	var errors = '';
	if ($F('name').length == 0)
	{	
		errors += '* You must enter your name\n';
	}
	if ($F('email').length == 0 || !isValidEmail($F('email')))
	{	
		errors += '* You must enter a valid e-mail address\n';
	}
	if ($F('message').length == 0)
	{	
		errors += '* You must enter a message\n';
	}
	if (errors.length > 0)
	{
		alert('The following errors have occurred:\n\n' + errors);
		return false;
	}

	var elements = Form.getInputs(contactForm);
	elements = elements.concat($('message'));
	var postStr = Form.serializeElements(elements);

	$('submit_form').disabled = 'true';
	$('waiting').style.display = 'inline';
	$('errors').style.display = 'none';
	
	for (i=0; i<elements.length; i++)
	{
		elements[i].disabled = 'true';
	}

	var url = '/method/contact';
	// notice the use of a proxy to circumvent the Same Origin Policy.
	
	new Ajax.Request(url, {
		method: 'post',
		parameters: postStr,
		onSuccess: function(transport) {
			var json = transport.responseText.evalJSON();
			if (json.result.error)
			{
				$('errors').innerHTML = 'ERROR: ' + json.result.error;
				$('errors').style.display = 'block';
				enableForm(contactForm);
			}
			else if (json.result.success)
			{
				$('contact_form_block').style.display = 'none';
				$('contact_form_confirm').style.display = 'block';
			}
			else
			{
				enableForm(contactForm);
			}
		},
		onFailure: function(transport) {
			$('errors').innerHTML = 'ERROR: An unknown error occurred when trying to submit your information';
			enableForm(contactForm);	
		}
	});
}

function enableForm(contactForm)
{
	var elements = Form.getInputs(contactForm);
	elements = elements.concat($('message'));
	var postStr = Form.serializeElements(elements);

	$('submit_form').disabled = '';
	$('waiting').style.display = 'none';
	for (i=0; i<elements.length; i++)
	{
		elements[i].disabled = '';
	}
}

function isValidEmail(address) {
	if (address !== "")
	{
		var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
		if (regex.test(address)) 
		{
			return true;
		}
		else 
		{
			return false;
		}
	}
}
