$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

$(function()
	{
		$("#contactform input:submit").click(function() {	
			
			// First, disable the form from submitting
			$('form#contactform').submit(function() { return false; });
			
			// Grab form action
			formAction = $("form#contactform").attr("action");
			
			emailId = "email";
			emailId = emailId.replace("/", "");
			
			
			if ($('form#contactform input#name').val() == "") {
								 $("#confirmation").hide();
								 $("#errormessage1").hide();
                 $("#errormessage2").hide();
                 $("#errormessage3").hide();
								 $("#errormessage4").hide();
                 $("#errormessage1").fadeIn("slow");
								 $('#name').focus(); 
            return;
      } 

      else if (!checkEmail(emailId))  
			{
					$("#confirmation").hide();
			    $("#errormessage1").hide();
					$("#errormessage2").hide();
			    $("#errormessage3").hide();
			    $("#errormessage4").hide();
			    $("#errormessage2").fadeIn("slow");
					$('#email').focus(); 
				return;
			}

			else if ($('form#contactform input#phone').val() == "") 
			{
					$("#confirmation").hide();
			    $("#errormessage1").hide();
			    $("#errormessage2").hide();
					$("#errormessage3").hide();
			    $("#errormessage4").hide();
			    $("#errormessage3").fadeIn("slow");
			    $('#phone').focus(); 
				return;
			}
			
			else if ($('form#contactform textarea#message').val() == "") 
			{			
					$("#confirmation").hide();
			    $("#errormessage1").hide();
			    $("#errormessage2").hide();
			    $("#errormessage3").hide();
					$("#errormessage4").hide();
			    $("#errormessage4").fadeIn("slow");
					$('#message').focus(); 
				return;
			}
			
			
			
			
			// Serialize form values to be submitted with POST
			var str = $("form#contactform").serialize();
			
			// Add form action to end of serialized data
			final = str + "&action=" + formAction;
			
			// Submit the form via ajax
			$.ajax({
				url: "contact.php",
				type: "POST",
				data: final,
				success: function(html){
					$('form').clearForm()
					$("#confirmation").hide();
					$("#errormessage1").hide();
			    $("#errormessage2").hide();
			    $("#errormessage3").hide();
					$("#errormessage4").hide();
					$("#confirmation").fadeIn("slow");  // Shows "Thanks for subscribing" div
					$('#name').focus();
				}
			});
		});
	});
	
	function checkEmail(email)
	{	
		var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		var emailVal = $("#" + email).val();
		return pattern.test(emailVal);
	}