<!--
//* USAGE GUIDLINES
//* ---------------
//* This script validates required field form input. To work, it needs to be invoked by a form 
//* (such as on the onSubmit event handler e.g. onSubmit="return validateForm(this)".
//* It requires:-
//* -|- <DIV> tags with id values matching the associated form field name prepended with '_' 
//*    (innerText of <DIV> displays user input error messages in IE. NN 'writes' to layer)
//* -|- Hidden form field with commma seperated required (mandatory) field names
//* -|- Hidden form field with validation rule (see below) in '|ValidationRule' format
//*  
//* It should work in all browsers version 4+. 
//* Tested in Mozilla 1.1 and IE 6

// CONSTANTS
// Validation mapping constants

var phoneNo = "phone";
var emailAd = "email";
var postcode = "postcode";
var integer = "integer";
var match = "match";

// Form fields to be matched are suffixed with
var strMatchSuffix = "Confirm";

// Required field name
var strReqFld = "required";

// Validation mapping field name
var strValFld = "validation";

// Failed fields array
var failedFields = new Array();

// Browser compatibility layer code
var isDHTML = 0;
var isLayers = 0;
var isAll = 0;
var isID = 0;
var isBusy = false;

if (document.getElementById) {
	isID = 1; isDHTML = 1;
} else {
	browserVersion = parseInt(navigator.appVersion);
	if ((navigator.appName.indexOf('Netscape') != -1) && (browserVersion == 4)) {
		isLayers = 1; isDHTML = 1;
	} else {
		if (document.all) {
			isAll = 1; isDHTML = 1;
		}
	}
}

// Function to control validation
// Param f is a form object
// Returns true if form has valid user input. False stops form from being submitted.
function validateForm(f) {

	var gotErrors = false;
	
	// Make an array of required field names
	var strRequired = eval('f.' + strReqFld + '.value');
	var reqItems = new Array();
	reqItems = strRequired.split(',');

	// Loop through all required fields in the form
	for(i=0; i < reqItems.length; i++) {
		var fieldName = eval('f.elements.' + reqItems[i] + '.name')
		var fieldValue = eval('f.elements.' + reqItems[i] + '.value')
		//alert('Required field loop: ' + fieldName + ':' + fieldValue);
		if (fieldValue.replace(/\s/g, '') == "") { // Its an empty field
			gotErrors = true;
			if (!writeToLayer ('_' + reqItems[i], '<font color=red>You have not supplied this required field.</font>')) {
				alert('You have not supplied a required value for ' + fieldName)
			}
		}
		else {
			if (!writeToLayer ('_' + reqItems[i], '<font color=green>Thank you!</font>')) {
				alert('Thank you!')
			}
		}
	}
	
	// Return false if there are is no validation to do and fields are empty
	if (!eval('f.' + strValFld) && gotErrors) {return false;}
	
	var strValidation = eval('f.' + strValFld + '.value');
	var valItems = new Array();
	valItems = strValidation.split(',');
	
	// Loop through validation candidates
	for(j=0; j < valItems.length; j++) {
		// Get the parts
		
		var valItem = new Array();
		valItem = valItems[j].split('|'); 
		var valFieldName = eval('f.elements.' + valItem[0] + '.name');
		var valFieldValue = eval('f.elements.' + valItem[0] + '.value');
		//alert('Validation loop: ' + valFieldName + ':' + valFieldValue);
		var vType = valItem[1];
		if (valFieldValue.replace(/\s/g, '') != "") { // Its not an empty field
			if (vType == phoneNo) {
				if (!isPhone(valFieldValue)) {
					gotErrors = true;
					if (!writeToLayer ('_' + valFieldName, '<font color=red>Please remove illegal characters such as parentheses, dashes, spaces or dots from the beginning of the number.</font>')) {
						alert('Please remove illegal characters such as parentheses, dashes, spaces or dots from ' + valFieldName);
					}
				}
				else {
					if (!writeToLayer ('_' + valFieldName, '<font color=green>Thank you!</font>')) {
				alert('Thank you!')
					}
				}
			}
			else if (vType == emailAd) {
				if (!isEmail(valFieldValue)) {
					gotErrors = true;
					if (!writeToLayer ('_' + valFieldName, '<font color=red>We checked this email address and it seems to be invalid.</font>')) {
						alert(valFieldName + ' contains an invalid email address');
					}
				}
				else {
					if (!writeToLayer ('_' + valFieldName, '<font color=green>Thank you!</font>')) {
				alert('Thank you!')
					}
				}
			}

			else if (vType == postcode && f.elements.COUNTRY.value == "United Kingdom") {
				if (!isUkPostcode(valFieldValue)) {
					gotErrors = true;
					//alert('ar size:'+failedFields.push([valFieldName]));
					if (!writeToLayer ('_' + valFieldName, '<font color=red>We checked this UK postcode and it seems to be invalid.</font>')) {
						alert(valFieldName + ' contains an invalid UK postcode');

					}
				}
				else {
					if (!writeToLayer ('_' + valFieldName, '<font color=green>Thank you!</font>')) {
				alert('Thank you!')
					}
				}
			}
			else if (vType == integer) {
				if (!isInteger(valFieldValue)) {
					gotErrors = true;
					if (!writeToLayer ('_' + valFieldName, '<font color=red>Please enter only numbers in this field.</font>')) {
						alert(valFieldName + ' contains an invalid number');
					}
				}
				else {
					if (!writeToLayer ('_' + valFieldName, '<font color=green>Thank you!</font>')) {
				alert('Thank you!')
					}
				}
			}
			else if (vType == match) {
				if (!isMatch(valFieldValue,valFieldName,f)) {
					gotErrors = true;
					if (!writeToLayer ('_' + valFieldName + strMatchSuffix, '<font color=red>This field does not match!</font>')) {
						alert(valFieldName + ' contains an invalid number');
					}
				}
				else {
					if (!writeToLayer ('_' + valFieldName, '<font color=green>Thank you!</font>')) {
				alert('Thank you!')
					}
				}
			}

		}
	}	
	// See if we have picked up any errors
	if (gotErrors) {
		return false;
	}
	else {
		alert('no errors...');
			// Disable the form buttons to prevent duplicate submissions
			if (document.all||document.getElementById){
			//screen thru every element in the form, and hunt down "submit" and "reset"
			for (i=0;i<f.length;i++){
			var tempobj=f.elements[i]
			if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="reset")
			//disable em
			tempobj.disabled=true
			}
			}
		return true;
	}
}

// Function to test for matches
// Param userValue is user input
// Param userField is field name to check
// Param form is form object
// Returns true if its valid

function isMatch(usersValue,userField,f) {
	var fieldToMatch = userField + strMatchSuffix
	if (eval('f.elements.' + userField + '.value') == eval('f.elements.' + fieldToMatch + '.value')) {
	//alert('they match!');
	return true;
}
	else {
		//alert('no match!');
		return false;
	}
}


// Function to check for integers
// Param userValue is user input
// Returns true if its valid
function isInteger(usersValue) {
	var re = /^[0-9,]+$/g;
	if (re.test(usersValue)) { 
		return true;
	}
	else {
		return false;
	}
}

// Function to check for valid phone/fax numbers
// Param userValue is user input
// Returns true if its valid
function isPhone(usersValue) {
	var strippedPhone = usersValue.replace(/[\(\)\.\-\ ]/g, '');
	if (strippedPhone != '') {
		if (isNaN(parseInt(strippedPhone))) {
			return false;
		}
		else {
			return true;
		}
	}
}

// Function to check for valid email address
// Param userValue is user input
// Returns true if its valid
function isEmail(userValue) {
	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
	if (re.test(userValue)) { 
		return true;
	}
	else {
		return false;
	}
}

// Function to check for valid uk postcode
// Param userValue is user input
// Returns true if its valid
function isUkPostcode(userValue) {
	var re = /^[a-z]{1,2}\d{1,2}(\s?\d[a-z]{2})?$/i
	if (re.test(userValue)) { 
		return true;
	}
	else {
		return false;
	}
}

// Sub to display warnings
// Param id is the layer ID, text is the text to display
function writeToLayer (id, text)
{
	// first we get a reference to the layer we want
	// to modify
	x = findDOM(id, 0);
	if (!x)
		return false;
	if (isLayers) {
					alert('this is NN')
		// NS4 only allows you to have
		// one output stream open at a time
		// so if we are already writing to one
		// we will try this again in 250 ms.
		if (isBusy) {
			setTimeout ("writeToLayer( '" + id + "', '" + text + "' )", 250 );
		} else {
			isBusy = true;
			// write does open for us
			x.document.write(text);
			x.document.close();
			isBusy = false;
			return true;
		}
	} else {
		x.innerHTML = text;
		return true;
	}
}

function getObjNN4(obj,name)
{
	var l = obj.layers;
	for (var k=0;k<l.length;k++)
	{
		if (l[k].id == name)
			return l[k];
		else if (l[k].layers.length)
			var tmp = getObjNN4(l[k],name);
		if (tmp) return tmp;
	}
	return null;
}

function findDOM(objectID,withStyle) {
	if (withStyle == 1) {
		if (isID) {
			return (document.getElementById(objectID).style);
		} else {
			if (isAll) {
				return (document.all[objectID].style);
			} else {
				return getObjNN4(top.document,objectID);
			}
		}
	} else {
		if (isID) {
			return (document.getElementById(objectID));
		} else {
			if (isAll) {
				return (document.all[objectID]);
			} else {
				if (isLayers) {
					return getObjNN4(top.document,objectID);
				}
			}
		}
	}
}

