$(function() {
	
	// load the modal window
	$('a.modal').click(function(){
		
		// scroll to top
		$('html, body').animate({scrollTop:0}, 'fast');

		// before showing the modal window, reset the form incase of previous use.
		$('.success, .error').hide();
		$('form#contactForm').show();
		
		//show the mask and contact divs
		$('#mask').show().fadeTo('', 0.8);
		$('div#contact').fadeIn();

		// stop the modal link from doing its default action
		return false;
	});

	// close the modal window is close div or mask div are clicked.
	$('div#close, div#mask').click(function() {
		$('div#contact, div#mask').stop().fadeOut('fast');

	});

	

	// when the Submit button is clicked...
	$('input#submit').click(function() {
		$('.error').hide().remove();
		$('#contact_header').hide();
		
		//Inputed Strings
		var name = $('#name').val(),
			email = $('#email').val(),
			email = email.toLowerCase();
			comment = $('#comment').val();
		
	
		//Error Count
		var error_count = 0;
		
		//Regex Strings
		var email_regex = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
	
		//Test name
		if(name == '') {
			$('#contact_header').after('<p class=error>Please enter your name.</p>');
			error_count += 1;
			$('.error').fadeIn('slow');
		}
		
		//Test Email
		if(!email_regex.test(email)) {
			$('#contact_header').after('<p class=error>You entered an invalid email.</p>');
			error_count += 1;
			$('.error').fadeIn('slow');
		}
		
		//Blank Comment?
		if(comment == '') {
			$('#contact_header').after('<p class=error>No message was entered!</p>');
			error_count += 1;
			$('.error').fadeIn('slow');
		}
		
		//No Errors?
		if(error_count == 0) {
			$.ajax({
				type: "POST",
				url: "http://www.gravitate.ie/gravmess.php",
				data: "name=" + name + "&email=" + email + "&comment=" + comment,
				error: function() {
					$('.error').hide();
					$('#sendError').slideDown('slow');
				},
				success: function (data) {
					$('.error').hide();
					$('.success').slideDown('slow');
					$('form#contactForm').slideUp('slow');
				}				
			});	
		}
		
		else {
			$('.error').show();
		}
			
		return false;
	});
	
});
