// AJAX contact form
$(document).ready(function() {
	//form submission
	$("#ajax-contact-form").submit(function(){
	  
		var str = $(this).serialize();		
			
		$.ajax({
			type: "POST",
			url: "lib/form.validation.php",
			dataType: 'json',
			data: str,
			success: function(result) {			  
			  // Message Sent? Show the 'Thank You' message and hide the form
			  if(result.status == 'OK') {			  
				  results = '<h2 align="center">Your message has been sent</h2>';
				  //$("#ajax-contact-form").css('border-bottom', 'solid 1px #b3b3b3')
				  
				  $('form :input')
				  .not(':button, :submit, :reset, :hidden')
				  .val('')
				  .removeAttr('checked')
				  .removeAttr('selected');
				  
				  $("#ajax-contact-form").hide();
				  //$("#note").hide().html(results).show();
				  $("#note").hide();
				  $("div#ok_message").show();
			  } else {	
				  //reloads the captach if there was an error
				  if(typeof(Recaptcha) != "undefined") {
					  Recaptcha.reload();
				  }	
				  showError(result);				 
			  } //end results status check			  
			} //end success			
		 }); //end $.ajax
		
		return false;
	
	}); //end submit

	$(".jqmClose").click(function(){
	
		$("p.err").remove();
		//$("div#note").hide();
		$("div#ok_message").hide();
		$("div#note").show();		
		
		$('form :input')
		.not(':button, :submit, :reset, :hidden')
		.val('')
		.removeAttr('checked')
		.removeAttr('selected');
		$("#ajax-contact-form").show();		
	});
	
}); // end on load

//checks to see if there was an error
function showError(j) {	
	appendError(j.name, "#name_p");
	if(!j.name) { appendError(j.name_length, "#name_p"); }
	
	appendError(j.email, "#email_p");
	if(!j.email) { appendError(j.valid_email, "#email_p"); }
	
	appendError(j.phone, "#phone_p");
	if(!j.phone) { appendError(j.valid_phone, "#phone_p"); }
	
	appendError(j.website, "#website_p");
	if(!j.website) { appendError(j.valid_website, "#website_p"); }
	
	appendError(j.subject, "#subject_p");
	
	appendError(j.message, "#message_p");
	
	appendError(j.captcha, "#captcha_p");
}

//if error, append it to the form
function appendError(err_msg, p_name) {
	var p = p_name+" .err";
	if(err_msg) {		
		if($(p).length == 0) {$(p_name).prepend('<p class="err"></p>')};
		if($(p).length != 0) {
			$(p).slideUp(0 , function() {
				$(p).html('').append(err_msg).slideDown(0)
			});
		}
	} else {
		$(p).slideUp(0);
	}
}
