// JavaScript Document

var FormValidation = 
{
	init: function()
	{
			  
	  //Form Validation init: script
	 // =======================================================================
	  
	  var forms = document.getElementsByTagName("form");
	  
	  for (var i = 0; i < forms.length; i++)
	  {
		  Core.addEventListener(forms[i], "submit", FormValidation.submitListener);
	  }
	  

	},
	
	rules:
	{
		required: /./,
		requiredNotWhitespace: /\S/,
		positiveInteger: /^\d*[1-9]\d*$/,
		positiveOrZeroInteger: /^\d+$/, 
		integer: /^-?\d+$/,
		decimal: /^-?\d+(\.\d+)?$/,
		email: /^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/,
		telephone: /^(\+\d+)?( |\-)?(\(?\d+\)?)?( |\-)?(\d+( |\-)?)*\d+$/,
		date: /^\d{2}\/\{2}\/(\d{2}|\d{4})$/
	},
	
	errors:
	{
		required: "Please fill in this required field.",
		requiredNotWhitespace: "Please fill in this required field.",
		positiveInteger: "This field may only contain a positive whole number.",
		positiveOrZeroIntedger: "This field may only contain a non-negative whole number.",
		integer: "This field may only contain a whole number.",
		email: "Please enter a valid email address into this field.",
		telephone: "Please enter a valid telephone number into this field.",
		date: "Please enter a valid date in this format (DD/MM/YYYY)"
	},
	
	submitListener: function(event)
	{
		var fields = this.elements; //Use the elements property of the Form object(ie this) to capture all controls(elements) within the Form control into array fields
		
		for (var i = 0; i < fields.length; i++)
		{
			var className = fields[i].className;
			var classRegExp = /(^| )(\S+)( |$)/g;
			var classResult;
			
			while (classResult = classRegExp.exec(className)) //exec checks the REgex with classname passed and stores as array in class Result
			{
				var oneClass = classResult[2]; //As per the Regex, we're looking for a match with the array index 2
				var rule = FormValidation.rules[oneClass]; // Checking for against classname stored in the oneClass variable hence [...] instead of dot...
				if (typeof rule != "undefined") // If we actually obtained a className and not a whitespace etc
				{
					if(!rule.test(fields[i].value)) // Test if our Regex (in rule) matches the value that the user supplied in the field
					{
						fields[i].focus(); //If not, set focus back to the field for the user to correct
						alert(FormValidation.errors[oneClass]); // display error message corresponding to that class name
						Core.preventDefault(event);// Prevent the defaults from executing ie the submission of the form
						return; // return immediately so user can be notified of error etc.
					}
				}
			}
		}
	}
};
	
Core.start(FormValidation);
