$(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.7);
		$('div#contact').fadeIn();

		$('#captchaImg').attr("src","/captcha/image.php?r=" + Math.floor(Math.random()*99999));

		
		
		// 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('slow');

	});

	// when the Submit button is clicked...
	$('input#submit').click(function() 
	{
	
		$('.error').hide().remove();
		
		//Inputed Strings
		var username = $('#name').val();
		var	email = $('#email').val();
		var	subject = $('#subject').val();
		var comment = $('#comment').val();
		var captcha = $('#captcha').val();
		
	
		//Error Count
		var error_count = 0;
		
		var email_regex = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
		
		
			//Test Username
			if(username == "") {
				$('#contact_header').after('<p class=error>Invalid username entered!</p>');
				error_count += 1;
			}
			
			//Test Email
			if(!email_regex.test(email)) {
				$('#contact_header').after('<p class=error>Invalid email entered!</p>');
				error_count += 1;
			}
			
			//Test Username
			if(subject == "") {
				$('#contact_header').after('<p class=error>Invalid subject entered!</p>');
				error_count += 1;
			}
			
			//Blank Comment?
			if(comment == '') {
				$('#contact_header').after('<p class=error>No Comment was entered!</p>');
				error_count += 1;
			}
			
			//No Errors?
			if(error_count == 0) 
			{
				$.ajax({
					type: "post",
					url: "/send.php",
					data: "name=" + name + "&email=" + email + "&comment=" + comment + "&subject=" + subject + "&captcha=" + captcha,
					success: function (response) 
					{
						if (response == "1")
						{
							$('.success').slideDown('slow');
							$('form#contactForm').fadeOut('slow');
						}
						else
						{
							$('#contact_header').after('<p class=error>'+response+'</p>');
							$('.error').show();
						}
					}				
				});	
			}
			
			else {
                $('.error').show();
            }
			
		return false;
	});
	
});
