// Master application JS

// Modal window implementation.
$(function(){
	
	$(document.body).append($("#competition_form")); // IE fix
	
	// Hide all modals
	$('.modal').hide();
	
	//select all the a tag with name equal to modal
	$('a.modal_trigger').click(function(e){
		e.preventDefault();
		
		// Get the modal element
		var id = $(this).attr('href');
		
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
		$(document.body).append($('#mask'));
		$('#mask').css({ 'width':maskWidth, 'height':maskHeight });
		$('#mask').fadeIn(800);	
		$('#mask').fadeTo("slow",0.8);
		
		$(id).css('top', $(window).height() / 2 - $(id).height() / 2);
		$(id).css('left', "30%");
		$(id).fadeIn(1000);
	});
	
	$('.modal .close').click(function (e){
		e.preventDefault();
		$('#mask, .modal').fadeOut(300);
	});
	
	$('#mask').click(function (){
		$(this).fadeOut(300);
		$('.modal').fadeOut(300);
	});
	
	// Clear default text in forms
	$("input:text").each(function(){
		$(this).val($(this).attr("alt"));
	});
	$("input:text").focus(function() {
		if($(this).val()==$(this).attr("alt"))
			$(this).val("");
	});
	$("input:text").blur(function() {
		if($(this).val()=="")
			$(this).val($(this).attr("alt"));
	});
	
	// Competition form validations
	$("#competition_remote_form").submit(function(event){
		event.preventDefault;
		
		if(!$("#terms_checkbox").is(":checked"))
		{
			alert("Please agree to the Terms and Conditions.");
			return false;
		}
		
		if(!isValidEmailAddress($("#email_address").val()))
		{
			alert("Please check your email address is valid.");
			return false;
		}
		
		$.post("competition_form_handler.php",
					 $("#competition_remote_form").serialize(),
					 function(data){
						 $("#competition_form .inner .wrapper").empty().append(data);
						 setTimeout(function(){
						 	 $("#mask").fadeOut(300);
							 $('.modal').fadeOut(300);
						 }, 3000);
					 }
		);
		
		return 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);
	}

});