$(document).ready(function()
{
	$("form[name='request_samples']").submit(function()
	{
		/**
		 * Hide & empty the error box in case there are any left over errors
		 */
		$("div.ajax_errors").hide().empty();

		/**
		 * Store a reference to the current form element in this variable
		 */
		var form = $(this);

		/**
		 * Loop through all the checked samples and store their ID in an array
		 */
		var business_samples = new Array();
		$("div#bs input:checked").each(function() {
			business_samples.push( $(this).attr('id') );
		});

		/**
		 * If they are not a business, fill the samples variable with their
		 * new-line delimited list of requested samples
		 */
		if($("input#business_samples").is(":not(:checked)")) {
			var samples = $("textarea#samples").val();
		}

		/**
		 * Here we make an AJAX request to the request_samples.php script, which
		 * processes the input we give it and checks that it's valid.  If the
		 * input does not pass validation it returns an error, otherwise it
		 * returns true.
		 */
		$.post("/request_samples.php", {
			contact_name: form.find("input#contact_name").val(),
			company_name: form.find("input#company_name").val(),
			company_size: form.find("select#company_size").val(),
			address: form.find("input#address").val(),
			city: form.find("input#city").val(),
			state: form.find("select#state").val(),
			zip: form.find("input#zip").val(),
			phone: form.find("input#phone").val(),
			email: form.find("input#email").val(),
			samples: samples,
			'business_samples[]': business_samples
		}, function(r) {

			/**
			 * Check if the request was a success or if we have any errors to display.
			 * If there are no errors, we replace the curren page's HTML with some thank you
			 * text.
			 * If there are errors, we loop through them and display them in the error box.
			 */
			if(r.success == true) {
				$("div#sub-content").empty().append("<p>Thank you for your interest.  Your sample request has been sent and one of our representative will get back to you shortly.</p>");
			} else {
				var errors = r.errors;
				for(var x in errors) {
					$("div.ajax_errors").append("<p>" + errors[x] +"</p>");
				}
				$("div.ajax_errors").show();
			}
		}, 'json');

		/**
		 * We have to return false here so the browser doesn't submit
		 * the form when we hit the submit button.  We don't want the browser
		 * to submit the form because we just did via AJAX.
		 */
		return false;
	});

	/**
	 * We catch the click event on the "I am a business" checkbox to show/hide
	 * the extra samples checkboxes, but only if it is being checked, otherwise
	 * we hide the extra ones.
	 */
	$("input#business_samples").click(function() {
		if($(this).is(':checked')) {
			$("div#samples_input").hide();
			$("div#bs").show();
		} else {
			$("div#bs").hide();
			$("div#samples_input").show();
		}
	});
});
