// Contact Form Script for andrew.harrison.org
// Originally from Bit Repository http://www.bitrepository.com/
// customised in October 2008. Spacing cleaned up in May 2009 now that I understand how it works properly

//This script uses several files:

//     /js/jquery.js (vanilla jquery file)
//     /js/contactform.js (speaks to jquery and then sends the form to contactform.php then injects javascript into the page depending on what happens)
//     /scripts/contactform.php (PHP to process the form and generate error messages)
//     /scripts/contactfunctions.php (validates the email address submitted)


// load when the DOM is ready
$(document).ready(function(){
	//when the form is submitted
	$("form").submit(function(){
		//thanks to @joshsharp for help with this:
		//hide the error message [if there is one from before]
		$('#note').slideUp('fast');
		//slide up the "send" button
		$('#sendbutton').slideUp('fast');
		// and slide down the "sending..." note in its place
		$('#sendingmsg').slideDown('fast');
		  
		// then, get all the stuff in the form  
		var str = $("form").serialize();
		// and pass it to the php processor
		   $.ajax({
		   type: "POST",
		   url: "/scripts/contactform.php",
		   data: str,
		   success: function(msg){
			   
				//then talk to the #note div about what's happening:
				$("#note").ajaxComplete(function(event, request, settings){
					
					// if /scripts/contactform.php returns "OK" that means the email sent, so:
					if(msg == 'OK') 
								{
									// define the "success" message is [as an html div]
									result = '<div class="notification_ok"><h2>Message Sent!</h2><p>I should get back to you in the next few days.</p></div>';
									// (thanks to @praxxis for the help with this):
									// then first slide up the contact form [everything in #contact_form]
									$("#contact_form").slideUp('fast', function() {
									// then slide down the success message div
										$("#notification").html(result).slideDown('slow') })				
								} else {
									// However, if it didn't receive "OK" it means the email was not sent.
									// In that case, /scripts/contactform.php outputs an error message
									// Let's add a nice header, then get the error message that was sent
									msg = '<div class="notification_error_head"><h2>There\'s a problem: </h2></div>' + msg;
									// then slide up the "sending..." note
									$('#sendingmsg').slideUp('fast');
									// slide the "send" button back down [so the form can be sent after
									// the errors have been corrected]
									$('#sendbutton').slideDown('fast');
									// and slide down the error message with the nice header
									// so the user knows what to fix
									$(this).html(msg).slideDown('slow');
								}
				});
			}
		 });
		// so that the standard event (set to a JS alert) doesn't happen
		return false;
	});
});
					

