$(function(){
	
	var options = {
	beforeSubmit: validate,
	dataType: 'json',
	success:  entryResponse
	
	}
	$('#entryForm').ajaxForm(options); 
});

function validate(){ 
	$('#entryForm input').removeClass("error");
	$('#entryForm .errMsg').css('visibility','hidden');
	
	$('#entryForm input.required').each( function(){
		if($(this).attr("value") == "")
		{
			$(this).addClass("error");
		}
	})
	
	
	if($('#entryForm .error').size() > 0 )
	{
		$('#entryForm .errMsg').text("Please ensure all required fields are completed");
		$('#entryForm .errMsg').css('visibility','visible');
		return false;
	}
	if(! isValidEmailAddress($('#contact_email').attr("value")))
	{
		$('#contact_email').addClass("error");
		$('#entryForm .errMsg').text("Please enter a valid email address");
		$('#entryForm .errMsg').css('visibility','visible');
		return false;
	}
	
	$('#entryForm .submit').attr("value","submitting");
	$('#entryForm .submit').attr("disabled","disabled");

}
function entryResponse(data){  
	if(data.success == "true"){
		$("#entryFormWrap").html("<h3>Registration Successful</h3><p>Thank you for registering for the Little Tiger Press Young Writer and Illustrator Awards 2010. We are delighted you will be participating in this national competition aimed at inspiring a life-long love of books and reading in children.</p><p>Once we have checked your registration details and located the competition banner on your website we will email you, sending the link to the full information pack for the competition.</p><p>Good luck and kind regards</p><p>All at Little Tiger Press</p>");
	} else {
	
		for(i=0; i < data.error_fields.length; i++)
			$("#"+data.error_fields[i]).addClass("error");
			
		$('#entryForm .errMsg').text(data.errMsg);
		$('#entryForm .errMsg').css('visibility','visible');
		
		$('#entryForm .submit').attr("value","Submit");
		$('#entryForm .submit').attr("disabled",false);

	
	}

 }
 
 function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
	}
