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

		//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" || fieldName=="Parent Email") && !$(this).val().match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)) {
				alertMessage += fieldName+" is not a valid email address\n";
			}
		});

		$(this).find("select.required").each(function()
		{
			var fieldName = $(this).attr("rel");
			if ($(this).val()=="") {
				alertMessage += fieldName+" is required\n";
			}
		});


		//Check the value of each input with class="confirm"
		//Will look for extra field named confirm_[original_field_name]
		$(this).find("input.confirm").each(function()
		{	
			var confirmField = $("#confirm_"+$(this).attr("name"));			
			var fieldName = $(this).attr("rel");
			// check that the confirm field actually exists
			if(confirmField.length > 0){
				if((confirmField.val()!="") && (confirmField.val()!=$(this).val())){
					//fields do not match
					alertMessage += "Please ensure " + fieldName + " and Confirm " +fieldName+" match.\n";
						
				}
			}
			
		});

		if ($(this).find("input[name=paymethod]").length > 0 && $(this).find("input[name=paymethod]:checked").length != 1) {
			alertMessage += "Payment Method is Required\n";
		}
		if ($(this).find("#finalPostageCost").length == 1 && $(this).find("#finalPostageCost").html()=="")
		{
			alertMessage += "You must select valid Postage Options\n";
		}

		if ($(this).find("#postal_country").val()=="Australia" && $(this).find("#postageOptions").val() > 3)
		{
			alertMessage += "Your Postal Address is Australia, but your Postage Method is International. Please correct one of these.";
		}
		if ($(this).find("#postal_country").length==1 && $(this).find("#postal_country").val()!="Australia" && $(this).find("#postageOptions").val() < 4)
		{
			alertMessage += "Your Postal Address is outside Australia, but your Postage Method is for within Australia. Please correct one of these.";
		}
		
		//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, ""));
	});



});