$(function() {

	// load the modal window
	$('a.modal').click(function(){
            
		// scroll to top
		$('div#contact-container').animate({scrollTop:0}, 'slow');

		// 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
		$('#name').val('Your name');
		$('#email').val('Your email address');
		$('#comment').val('Enter your comment or query...');

		//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;
	});

	// 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, #contactForm textarea').focus(function() {
		if(this.name!="submit")$(this).val('');
	});

	// when the form is submitted...
	$('#contactForm').submit(function() {
		//Inputed Strings
		var username = $('#name').val(),
		email = $('#email').val(),
		comment = $('#comment').val();

		//Error Count
		var error_count = 0;

                //Hide Existing Errors
                $('.error').remove();

		//Regex Strings
		var username_regex = /^[A-Za-z0-9_-]{3,16}$/,
		email_regex = /^([A-Za-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;

		//Blank Comment?
		if(comment==(''||'Enter your comment or query...')) {
			$('#contact_header').after('<p class="error">Please enter your enquiry.</p>');
			error_count ++;
		}

		//Test Email
		if(!email_regex.test(email)) {
			$('#contact_header').after('<p class="error">Please enter a valid email address.</p>');
			error_count ++;
		}
                
		//Test Username
		if(!username_regex.test(username)) {
			$('#contact_header').after('<p class="error">Please enter your name.</p>');
			error_count ++;
		}
		//No Errors?
		if(error_count === 0) {
                    $('.wait').slideDown('slow');
                    $.ajax({
			type: "post",
			url: "send.php",
			data: "name=" + username + "&email=" + email + "&comment=" + comment,
			error: function() {
				$('.error').hide();
				$('#sendError').slideDown('slow');
                        },
                        success: function () {
				/*$('.error').hide();
				$('.success').slideDown('slow');
				$('form#contactForm').fadeOut('slow');*/

                            //hide the mask and contact divs
                            $('#mask').hide();
                            $('div#contact').fadeOut();
                            $('.wait').hide();
			}
		});
	}

	else {
            $('.error').show();
        }
        return false;
    });
});

