$(function() {
  $('.error').hide();
  $('.message').hide();  
  
	function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
	}


  $("#form-submit").click(function() {
		// validate and process form
		// first hide any error messages
		var err = "There was an error in submitting your details. Please fill out all fields.";
		var emailerr = "You have supplied an invalid email address.";
	    $('.error').text(err).hide();
    
		
	  var name = $("input#name").val();
		if (name == "") {
       $(".error").fadeIn();
       setTimeout(function(){
  		$(".error").fadeOut("slow");
	
	}, 5000);
      $("input#name").focus();
      return false;
    }
    
    var phone = $("input#phone").val();
		if (phone == "") {
     $(".error").fadeIn();
       setTimeout(function(){
  		$(".error").fadeOut("slow");
	
	}, 5000);
      $("input#phone").focus();
      return false;
    }
    
	var email = $("input#email").val();
		if (!isValidEmailAddress(email)){
	$('.error').text(emailerr).fadeIn();
       setTimeout(function(){
  		$(".error").fadeOut("slow");
	
	}, 5000);
      $("input#email").focus();
      return false;
      
    } else if (email == "") {
     $(".error").fadeIn();
       setTimeout(function(){
  		$(".error").fadeOut("slow");
	
	}, 5000);
      $("input#email").focus();
      return false;
    }
    
    var msg = $("#msg").val();
		if (msg == "") {
     $(".error").fadeIn();
       setTimeout(function(){
  		$(".error").fadeOut("slow");
	
	}, 5000);
      $("#msg").focus();
      return false;
    }
		
	var dataString = $("#contact-form").serialize();
		
	
		$.ajax({
      type: "POST",
      url: "bin/process.php",
      data: dataString,
      success: function() {
        $('.message').fadeIn(1500);
        $("#name, #email, #phone, #msg").val("");
         setTimeout(function(){
  		$(".message").fadeOut("slow");
	
		}, 5000);
       }
         
     });
    return false;
	});
});

