$(document).ready(function(){
	
	/* Form Submission Handler */
	$("#contact-form input[type=submit]").click(function(event){
	//$("#contact-form form").submit(function(event){
		event.preventDefault();
		$(this)
			.attr("value", "Please Wait...")
			.attr("disabled", "disabled"); 
		
		/* Get data from the form and set ajax=1, this tells the 
			 php form handler to send json back as the result */	
		var data = $("#contact-form form").serialize() + "&ajax=1";
			
		/* Build an ajax call the the form handler. 
			 The absolute url variable is defined in 
			 the contact-form.php template */
		$.ajax({
			type: "POST",
			dataType: "json",
			url: url,
			data:data,
			success: handleResponse,
     	fail: handleFail
		})
	});

	/* Form Reset Handler */
	$("#contact-form input[type=reset]").click(function(){
		$("#contact-form span").removeClass();
		$("#errors").css({'display':'none'});
	});      			
});

/*
*	JSON Response Handler
* Reads the response from the php form handler
* and updates the DOM accordingly
*/
function handleResponse(json){
	if(json.response == "success"){	
		$("#contact-form").fadeOut(100, function(){
			$("#contact-form")
				.html("<p>Thanks! We’ve sent your comment or question to Rob!</p>")
				.fadeIn(200);
		});
	}else{
		$("#contact-form input[type=text],#contact-form textarea").each(function(){
			var vclass = json.valid[$(this).attr("name")];
			$(this)
				.prev('label')
				.children('span')
				.removeClass()
				.addClass(vclass);
		});
		$("#contact-form input[type=submit]")
			.attr("value", "Submit")
			.removeAttr("disabled");
		$("#errors").css({'display':'block'});
	}
}

/* Error Handler */
function handleFail(msg){
	alert( "An error occured: " + msg );
}
