$(function () {
	$("#send_message").click(function (event) {
		event.preventDefault();

		$("#responsePrompt").hide();
		$("#responsePrompt").html("");

		$("#send_message").attr("disabled", "");

		var full_name = $("input#full_name").val();
		var email_address = $("input#email_address").val();
		var subject = $("input#subject").val();
		var message = $("#message").val();

		if (full_name == "") {
			$("input#full_name").focus();

			$("#responsePrompt").html(
				'<div class="alert alert-danger" role="alert">Please enter your full name.</div>'
			);
			$("#responsePrompt").show();

			$("#send_message").removeAttr("disabled");
			return false;
		}

		var email_pattern =
			/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		if (email_address == "" || !email_address.match(email_pattern)) {
			$("input#email_address").focus();

			$("#responsePrompt").html(
				'<div class="alert alert-danger" role="alert">Enter a valid email address.</div>'
			);
			$("#responsePrompt").show();

			$("#send_message").removeAttr("disabled");
			return false;
		}

		if (subject == "") {
			$("input#subject").focus();

			$("#responsePrompt").html(
				'<div class="alert alert-danger" role="alert">Please enter your subject.</div>'
			);
			$("#responsePrompt").show();

			$("#send_message").removeAttr("disabled");
			return false;
		}

		if (message == "") {
			$("#message").focus();

			$("#responsePrompt").html(
				'<div class="alert alert-danger" role="alert">Message cannot be empty!</div>'
			);
			$("#responsePrompt").show();

			$("#send_message").removeAttr("disabled");
			return false;
		}

		$(".button_spinner").show();
		$("input#full_name").prop("disabled", true);
		$("input#email_address").prop("disabled", true);
		$("input#subject").prop("disabled", true);
		$("#message").prop("disabled", true);

		var form_data =
			"full_name=" +
			full_name +
			"&email_address=" +
			email_address +
			"&subject=" +
			subject +
			"&message=" +
			encodeURIComponent(message);

		$.ajax({
			url: "email/send_feedback",
			type: "POST",
			data: form_data,
		}).done(function (response) {
			if (response == "success") {
				$("#responsePrompt").html(
					'<div class="alert alert-success" role="alert">Message sent! Thank you for the feedback.</div>'
				);
				$("input#full_name").val("");
				$("input#email_address").val("");
				$("input#subject").val("");
				$("#message").val("");
			} else {
				$("#responsePrompt").html(
					'<div class="alert alert-danger" role="alert">' +
						response +
						"</div>"
				);
			}
			$("#responsePrompt").show();
			$("#send_message").removeAttr("disabled");
			$(".button_spinner").hide();
			$("input#full_name").prop("disabled", false);
			$("input#email_address").prop("disabled", false);
			$("input#subject").prop("disabled", false);
			$("#message").prop("disabled", false);
		});

		return false;
	});
});
