/*
Created 09/27/09										
Questions/Comments: jorenrapini@gmail.com						
COPYRIGHT NOTICE		
Copyright 2009 Joren Rapini
*/

	

$(document).ready(function(){
	// Place ID's of all required fields here.
	required = ["FirstName", "LastName", "Email", "Address", "Town", "PaymentMethod"];
	// If using an ID other than #email or #error then replace it here
	email = $("#Email");
	// The text to show up within a field when it is incorrect
	emptyerror = "Please fill out this field.";
	emailerror = "Please enter a valid e-mail address.";

	$("#details").submit(function(){
		$("div.terms_error").remove();	
		$("div.pm_error").remove();	
		//Validate required fields
		for (i=0;i<required.length;i++) {
			var input = $('#'+required[i]);
			if ((input.val() == "") || (input.val() == emptyerror)) {
				input.addClass("needsfilled");
				input.val(emptyerror);
				if(input.attr("id") == "PaymentMethod") {
					input.after('<div class="pm_error">Please choose a payment method</div>');
				}
			} else {
				input.removeClass("needsfilled");
			}
		}
		// Validate the e-mail.
		if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
			email.addClass("needsfilled");
			email.val(emailerror);
		}
		// validate the Terms checkbox
		if (!$("#Terms").attr("checked")) {
			$("#Terms").addClass("needsfilled")
					   .after('<div class="terms_error">Please confirm that you agree to the terms and conditions</div>');
		};

		//if any inputs on the page have the class 'needsfilled' the form will not submit
		if ($(":input").hasClass("needsfilled")) {
			return false;
		} else {
			return true;
		}
	});
	
	// Clears any fields in the form when the user clicks on them
	$(":input").focus(function(){		
	   if ($(this).hasClass("needsfilled") ) {
			$(this).val("");
			$(this).removeClass("needsfilled");
	   }
	});
	// remove Terms checkbox error message
	$("#Terms").change(function(){	// using change() and not focus() because it doesn't work in webkit for checkboxes	
			$("div.terms_error").remove();
			$(this).removeClass("needsfilled");
	});
	$("#PaymentMethod").change(function(){
			$("div.pm_error").remove();
			$(this).removeClass("needsfilled");
	});
	
});	
