$(document).ready(function() {
	
	// Enforce required fields
	$("form").submit(function(event) {
		var alertMessage = "";

		var searchterm = $("#searchTerm").val();

		// Check search form at least 3 chars
		if (searchterm.length<3 && searchterm.length>0) {
			alertMessage += "Your search term must be at least 3 characters long.\n";
		}	
		

		//Check the value of each input with class="required"
		$(this).find("input.required").each(function()
		{
			var fieldName = $(this).attr("rel");
			if ($(this).val()=="") {
				alertMessage += fieldName+" is required\n";
			}
			if (fieldName=="Email" && !$(this).val().match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)) {
				alertMessage += fieldName+" is not a valid email address\n";
			}
		});

		if ($(this).find("#country").val()=="Australia" && $(this).find("#postcode").val()=="0000")
		{
			alertMessage += "Invalid Australian Postcode\n";
		}

		if ($(this).find("#delivery_method") && $(this).find("#delivery_method").val()=="")
		{
			alertMessage += "Delivery Method is Required\n";
		}
		
		if ($(this).find("input[name=paymethod]").length>0 && $(this).find("input[type=radio]:checked").length==0)
		{
			alertMessage += "You must select a payment method\n";
		}
				


		//If there is an error message, alert it and stop form submission
		if (alertMessage.length > 0) {
			alert(alertMessage);
			return false;
		}
		else return true;
	});



	// Enforce only numbers in a number field
	$("input.number").blur(function() {
		$(this).val($(this).val().replace(/[^0-9\.]/gi, ""));
	});

});
