jQuery(document).ready(function() {
	// Process the form when the "button" is clicked
	jQuery('form#Contact button').click(function() {
		submitForm();
		return false;
	});
	
	function submitForm() {
		var speed = 'fast';	// speed for animations
		// Slide the Error message up and out of the way, then remove it
		jQuery('#Errors').slideUp(speed, function(){
			jQuery('#Errors').remove();
		});
		
		// Fade the "Required" messages, then remove them
		jQuery('.fail').fadeOut(speed, function(){
			jQuery('.fail').remove();
		});
		
		jQuery('button').hide();		// Hide the Submit button
		
		// Show the Processing message
		jQuery('#ButtonContainer').append('<div id="Processing"><span>Processing request...</span></div>');
		
		jQuery.post(
			jQuery('form#Contact').attr('action'),				// Post the form to the PHP Mailer
			jQuery('input, textarea').serialize(),				// Turns the inputs into strings of data
			function(response) {
				if(response.indexOf('Message Sent Successfully') != -1) {
					// Add a message indicating the Email was sent successfully
					jQuery('form#Contact').after('<div id="Success">' + response + '</div>');
					jQuery('form#Contact').slideUp(speed);		// Slide the form up and out of the way
					jQuery('#Success').slideDown(speed);		// Slide the Success Message into place
				} else {
					// Empty Name
					if(response.indexOf('Empty name') != -1)
						jQuery("label[for='name']").append('<span class="fail">Required</span>');
					// Empty Email
					if(response.indexOf('Empty email') != -1)
						jQuery("label[for='email']").append('<span class="fail">Required</span>');
					// Invalid Email
					else if(response.indexOf('Invalid email') != -1)
						jQuery("label[for='email']").append('<span class="fail">Invalid Email</span>');
					// Empty Subject
					if(response.indexOf('Empty subject') != -1)
						jQuery("label[for='subject']").append('<span class="fail">Required</span>');
					//Empty Message
					if(response.indexOf('Empty message') != -1)
						jQuery("label[for='message']").append('<span class="fail">Required</span>');
					// Empty Captcha
					if(response.indexOf('Empty captcha') != -1)
						jQuery("label[for='captcha']").append('<span class="fail">Required</span>');
					// Incorrect Captcha
					else if(response.indexOf('Incorrect captcha') != -1)
						jQuery("label[for='captcha']").append('<span class="fail">Incorrect Answer</span>');
					
					// Change the text of the Submit button and show it
					jQuery('button').text('OK, try again now').show();
					
					// Add a message indicating the Email was not sent
					jQuery('form#Contact').append('<div id="Errors">' + response + '</div>');
					jQuery('#Errors').slideDown(speed);		// Slide the Error Message into place
				}
				jQuery('#Processing').remove();				// Hide the Processing message
			}
		);
	}
});