$(function() {

	// load the modal window
	$('a#modal').toggle(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();
		
		// Reset all the default values in the form fields
		$('#mname').val('Your name');
		$('#memail').val('Your email');
		$('#mcomment').val('Your message');

		//show the mask and contact divs
		$('#mask').show().fadeTo('', 0.7);
		$('div#contact').fadeIn();

		// stop the modal link from doing its default action
		return false;
	},function(){
  		
		$('div#contact').fadeOut();
		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');

	});

	$('#contactForm input').focus(function() {
		$(this).val('');
	});
	
	$('#contactForm textarea').focus(function() {
        $(this).val('');
    });

	// when the Submit button is clicked...
	$('input#submit').click(function() {
	$('.error').hide().remove();
		//Inputed Strings
		var name = $('#mname').val(),
			email = $('#memail').val(),
			comment = $('#mcomment').val();
		
	
		//Error Count
		var error_count = 0;
		
		//Regex Strings
		var username_regex = /^([ \u00c0-\u01ffa-zA-Z'\-]){3,16}$/;
		var	email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		
			//Test Username
			if(!username_regex.test(name)||name=='Your name') {
				$('#mname').after('<span class=error>!</span>');
				error_count += 1;
			}
			
			//Test Email
			if(!email_regex.test(email)) {
				$('#memail').after('<span class=error>!</span>');
				error_count += 1;
			}
			
			//Blank Comment?
			if(comment == ''||comment=='Your message') {
				$('#mcomment').after('<span class=error>!</span>');
				error_count += 1;
			}
			
			
			//No Errors?
			if(error_count === 0) {
				
				$.ajax({
					type: "post",
					url: "send.php",
					data: "name=" + name + "&email=" + email + "&comment=" + comment,
					error: function() {
						$('.error').hide();
						$('#sendError').slideDown('slow');
					},
					success: function () {
						$('.error').hide();
						$('.success').slideDown('slow');
						$('form#contactForm').fadeOut('slow');
					}				
				});	
			}
			
			else {
                $('.error').show();
            }
			
		return false;
	});
	
});
