$(function(){

	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);
	}

	var postWorking = false;

	$("span.button.submit").click(function(){

		if (postWorking == true) {
			return;
		}

		var empty_vars = "";

		if ($("input[name=\"name\"]").val() == 0) {
			empty_vars = empty_vars + "\nFull Name";
		}

		if ($("input[name=\"email\"]").val() == 0) {
			empty_vars = empty_vars + "\nEmail Address";
		}

		if ($("select[name=\"department\"]").val() == 0) {
			empty_vars = empty_vars + "\nDepartment";
		}

		if ($("textarea[name=\"questions\"]").val() == 0) {
			empty_vars = empty_vars + "\nQuestion/Comments";
		}

		if (empty_vars == "") {

			if (isValidEmailAddress($("input[name=\"email\"]").val()) == true) {

				$("span.button.submit").css({ "background-image" : "url('/images/template/button_submit_grey.png')", "cursor" : "default" });
				//$("#contactform input, #contactform select, #contactform textarea").attr("disabled", "disabled");

				postWorking = true;

				$.post("/contact", $("#contactform").serialize(), function(data){

					if (data.code == "000") {

						$("span.button.submit").css({"background-image" : "url('/images/template/button_submit.png')", "cursor" : "default" });

						alert(data.message);

					} else {

						$("#contactform input, #contactform select, #contactform textarea").attr("disabled", "disabled");

						alert(data.message);

					}

				}, "json");

			} else {
				alert("The email you have entered is invalid.");
			}

		} else {
			alert("You must fill in all the required fields. The following were left blank:\n" + empty_vars);
		}

	});

});