function isValidEmail(emailAddress) {
	var pattern = new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/);
	return pattern.test(emailAddress);
}

$(document).ready( function() {
	$(".formError").hide();
	$("#name").focus();
	// Dynamic E-mail Address validation
	$("#email").keyup(function() {
		var email = $("#email").val();
		if(email != 0) {
			if(isValidEmail(email)) {
				$("#validEmail").css({ "background-image": "url('../images/validYes.png')", "background-repeat": "no-repeat"  });
			} else {
				$("#validEmail").css({ "background-image": "url('../images/validNo.png')", "background-repeat": "no-repeat" });			
			}		
		} else {
			$("#validEmail").css( "background-image", "none" );
		}
	}); // End E-mail validation
	
	// Form Processing
	$("#submit").click(function() {
		$(".formError").remove();
		var hasError = false;
		
		if(!$("#name").val()) {
			$("#mainForm").before("<div class = 'formError'>You must supply a name.</div>");
			hasError = true;
		}
		
		// Validate Email
		if(!isValidEmail($("#email").val())) {
			$("#mainForm").before("<div class = 'formError'>You Must enter a valid e-mail address.</div>").fadeIn("slow");
			hasError = true;
		}
		
		if(!$("#subject").val()) {
			$("#mainForm").before("<div class = 'formError'>You must enter a subject for your message.</div>");
			hasError = true;
		}
		
		if(!$("#message").val()) {
			$("#mainForm").before("<div class = 'formError'>You must enter a message.</div>");
			hasError = true;
		}
		
		if(!hasError) {
			var dataString = "name=" + $("#name").val() + "&subject=" + $("#subject").val() + "&email=" + $("#email").val() + "&message=" + $("#message").val();
			$.ajax({
				type: "POST",
				url: "doContact.php",
				//cache: false, 
				data: dataString,
				success: function(html) { 
					$(".formSuccess").remove();
					$("#mainForm").before("<div class = 'formSuccess'>" + html + "</div>");
					$(".formSuccess").hide().fadeIn("slow");
				}
			
			});
		} else {
			$(".formSuccess").hide();
			$(".formError").hide();
			$(".formError").fadeIn("slow");
		}
		
		return false;
	}); // End Form Processing
	
});