
	// This file contains the data validation JavaScript functions
	// It is included in the HTML pages with forms that need these
	// data validation routines.

	// Written by Richard Harris
	// http://www.adactus.co.uk
	// 2003-01-24

	// DEFINE VARIABLES

	// define whitespace as these characters
	var whitespace = " \t\n\r";
	// set error message string to blank
	var ErrorString = "";
	// set count of found errors to zero
	var ISError = 0;
	var MIN_CUSTOMER_NUMBER = 1;
	var MAX_CUSTOMER_NUMBER = 10000000000;
	
	// main Datavalidation function detects the following validation types:
	//
	//	EMAIL
	//	SAMEEMAIL
	//	PASS
	//	SAMEPASS
	//	TEXT
	//	NUMBER
	//	PHONE
	//	CNUM
	//	PCDE
	//  EVENS
	//	NONE


	// the functions called by the datavalidation loop are:
	//
	//	checkString - can detect multiple types date/letter or numbers/letters/names/numbers/basic string
	//	IsTime
	//	checkSame	- make sure fields to be checked follow each other on the form. Field 1 must be of type SAMEEMAIL or SAMEPASS
	//				  Field 2 can be any other check type, eg: TEXT. Both types of validation will be performed. AW 3/2/2003
	//	replaceAll
	//	sqlSafe		- delete?
	//	makeSafe		- delete?
	//	isEmpty
	//	isWhitespace
	//	isPassword
	//	isCustomerNumber
	//	isPostCode	- fails if no space in postcode - fix???
	//	isText		- replaced by checkString, delete?
	//	isEmail
	//  isEvens

/**********************************************************************************/
/* Changes:                                                                       */
/**********************************************************************************/
/* 16/12/08 PGD_001 Change to code to detect control having no validate parameter.
/**********************************************************************************/

// Expects to receive the name or the identifier for a form object (id)
// and a string (status) indicating what characters are permissible.
	function checkString(strToCheck,status) {
	  var bad = 0;
	  for (i = 0; i < strToCheck.length; i++) {
	    ch = strToCheck.substring(i, i + 1);
        if ( status == "a date in the format MM/DD/YY" ) { if (( ch < "0" || "9" < ch ) && (ch !="/" )) { bad = 1; } }
	    if ( status == "letters or numbers" ) { if ( (ch < "a" || "z" < ch) && (ch < "A" || "Z" < ch) && (ch < "0" || "9" < ch) ) { bad = 1; } }
	    if ( status == "letters" ) { if ( (ch < "a" || "z" < ch) && (ch < "A" || "Z" < ch) ) { bad = 1; } }
	    if ( status == "names" ) { if ( (ch < "a" || "z" < ch) && (ch < "A" || "Z" < ch) && (ch != " ") ) { bad = 1; } }
	    if ( status == "numbers" ) { if (ch != "0" && ch != "1" && ch != "2" && ch != "3" && ch != "4" && ch != "5" && ch != "6" && ch != "7" && ch != "8" && ch != "9" && ch != " " && ch != ".") { bad = 1; } }
		if ( status == "phone" ) { if ((ch < "0" || "9" < ch) && (ch != " ") && (ch != "(") && (ch != ")") && (ch != "-") && (ch != "x")) { bad = 1; } }
		// text contains [A-Z]||[a-z]||[0-9]||[,|;|:|]
		if ( status == "basic string" ) { if ( (ch < "a" || "z" < ch) && (ch < "A" || "Z" < ch) && (ch < "0" || "9" < ch) && (ch != " ") && (ch != "'") && (ch != ",") && (ch != ";") && (ch != ":") && (ch != "@") && (ch != ".") && (ch != "_") && (ch != "!") && (ch != "-") ) { bad = 1; } }
	  }
	  if (bad==1) return false;
	  else return true;
	}


/****************************************************************/
// PURPOSE:  Check to see if the string passed in is a valid time.
//	A valid time is defined as a string which is postfixed with either
//  "PM" or "AM".  Next it checks to see if there is a colon in the
//  string.  If there is, it makes sure that at least one digit preceeds
//  it and two proceed it.

	function IsTime(strTime)
	{
		var strTestTime = new String(strTime);
		strTestTime.toUpperCase();

		var bolTime = false;

		if (strTestTime.indexOf("PM",1) != -1 || strTestTime.indexOf("AM",1))
			bolTime = true;

		if (bolTime && strTestTime.indexOf(":",0) == 0)
			bolTime = false;

		var nColonPlace = strTestTime.indexOf(":",1);
		if (bolTime && ((parseInt(nColonPlace) + 5) < (strTestTime.length - 1) || (parseInt(nColonPlace) + 4) > (strTestTime.length - 1)))
			bolTime = false;


		return bolTime;
	}


/****************************************************************/
function checkSame (str1,str2)
{
	if (str1 == str2) return true;
	else return false;
}


/****************************************************************/
function replaceAll (s, fromStr, toStr)
{
	var new_s = s;
	for (i = 0; i < 100 && new_s.indexOf (fromStr) != -1; i++)
	{
		new_s = new_s.replace (fromStr, toStr);
	}
	return new_s;
}


/****************************************************************/
/* PURPOSE:  Since we are using the single tick mark as the
	string delimiter to construct our SQL queries, a string with
	a tick mark in it will cause a SQL error.  Therefore we replace
	all "'" with "''", which eliminates the possibility of a SQL error.
*/
function sqlSafe (s)
{
	var new_s = s;
	new_s = replaceAll (new_s, "'", "|");
	new_s = replaceAll (new_s, "|", "''");
	new_s = replaceAll (new_s, "\"", "|");
	new_s = replaceAll (new_s, "|", "''");
	return new_s;
}


/****************************************************************/
function makeSafe (i)
{
	i.value = sqlSafe (i.value);
}


/****************************************************************/
// Check whether string s is empty.
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}


/****************************************************************/
// Returns true if string s is empty or 
// whitespace characters only.
function isWhitespace (s)
{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
	// Check that current character isn't whitespace.
	var c = s.charAt(i);

	if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}


/****************************************************************/
// isPassword (STRING s [, BOOLEAN emptyOK])
// 
function isPassword (s,name)
{   
//alert("Check password");
if (isEmpty(s)) 
    {
       if (isPassword.arguments.length == 1) return false;
       else return checkstring(s,"basic string");	//(isPassword.arguments[1] == true);
    }
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    
    if (document.forms[name].elements["existingpassword"].value == "true") 
    {
		//alert("EXISTING PASSWORD OK LEN= " + s.length + " no matter what length");
		
    } else {
    	//alert("NORMAL PASSWORD LEN = " + s.length + " must be greater than 6 chars");
	
		if (s.length < 6) return false;
    }
    
    return (checkString(s,"basic string"));
return true;
}


/****************************************************************/
//
// Checks whether the number is a valid customer number or not.
// Customer number must be numeric and at least 7 digits. 
// (and not blank / empty / whitespace )
//
//
function isCustomerNumber (s)
{   
	if (isEmpty(s)) 
       if (isCustomerNumber.arguments.length == 1) return false;
    
    // is s whitespace?
    if (isWhitespace(s)) return false;

	//alert("String is :" + s + " VALUE - 10 = : " + (parseInt(s)-10) );
    
    if ( (parseInt(s) < MIN_CUSTOMER_NUMBER) || (parseInt(s) > MAX_CUSTOMER_NUMBER) )
    {
		//alert("FAIL");
		return false;	
    }
    
	if (isNaN(parseInt(s))) {
	//alert ("FAIL");
	return false;
	}
    
return true;
}


/****************************************************************/
function isPostCode (s)
{   
		 //alert("POSTCODE CHECK");

		 test = s; 
		 size = s.length
			
		 //alert("SIZE IS " + size);
		 
		 s = s.toUpperCase(); //Change to uppercase
		 
		 while (s.slice(0,1) == " ") //Strip leading spaces
		  {
			s = s.substr(1,s.length-1);s.length = s.length
		  }
		 while(s.slice(s.length-1,s.length)== " ") //Strip trailing spaces
		  {
			s = s.substr(0,s.length-1);s.length = s.length
		  }
		 
		 if (s.length < 6 || s.length > 8){ //Code length rule
		  //alert(s + " is not a valid postcode - wrong length");
		  return false;
		  }
		  
		 if (!(isNaN(s.charAt(0)))){ //leftmost character must be alpha character rule
		   //alert(s + " is not a valid postcode - cannot start with a number");
		   return false;
		  }
		  
		 if (isNaN(s.charAt(s.length-3))){ //first character of inward code must be numeric rule
		   //alert(s + " is not a valid postcode - alpha character in wrong position");
		   return false;
		  }
		  
		 if (!(isNaN(s.charAt(s.length-2)))){ //second character of inward code must be alpha rule
		   //alert(s + " is not a valid postcode - number in wrong position");
		   return false;
		  }
		  
		 if (!(isNaN(s.charAt(s.length-1))))
			{ 
			//third character of inward code must be alpha rule
			//alert(s + " is not a valid postcode - number in wrong position");
			document.details.pcode.focus();
			return false;
			}
		  
		 //if (!(s.charAt(s.length-4) == " "))
//			{
			////space in position length-3 rule
			////alert(s + " is not a valid postcode - no space or space in wrong position");
			//return false;
			//}
		   
		 count1 = s.indexOf(" ");
		 count2 = s.lastIndexOf(" ");
		 if (count1 != count2)
			{
			//only one space rule
			//alert(s + " is not a valid postcode - only one space allowed");
			return false;
			}
if (checkString(s,"basic string") == true) return true;
else return false;

//return true;

}


/****************************************************************/
// isText (STRING s [, BOOLEAN emptyOK])
// 
// text contains [A-Z]||[a-z]||[0-9]||[@]||[-|&|,|+|;|:|/|]
function isText (s)
{   if (isEmpty(s)) 
       if (isText.arguments.length == 1) return false;
       else return (isText.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
return true;
}


/****************************************************************/
// isEmail (VARCHAR s)
// 
// Email address must be of form [a-z||0-9||A-Z||_]@[a-z||0-9||A-Z||_].[a-z||0-9||A-Z||_]
function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return false;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

/****************************************************************/
// isEvens (VARCHAR str)
// 
// Luhn check to replace old version which didn't work

function isEvens(str) 
{
  var result = true;

  var sum = 0; 
  var mul = 1; 
  var strLen = str.length;
  
  for (i = 0; i < strLen; i++) 
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) != 0)
    result = false;
    
  return result;
}


/****************************************************************/
// Captures window events for ns4+ 
// nb:: FUNCTION doFormSubmitOnKeyPress IS LOCATED ON EACH PAGE
if (navigator.appName == 'Netscape') {
	if (document.layers) {
		document.captureEvents(Event.KEYPRESS);
		document.onkeypress = function (evt) { if (evt.target.constructor == Input){ doFormSubmitOnKeyPress(); }}
	}
}

/****************************************************************/
// Datavalidation
//
function DataValidation(name, button_name)
	{
	// initialise the error string
	ISError=0;
	mandbool = false;
	
	// set booleans for each message to ensure they all can appear only once.
	
	TEXT_bool = false;
	EMAIL_bool = false;
	EVENS_bool = false;
	CNUM_bool = false;
	PASS_bool = false;
	PCDE_bool = false;
	SAMEPASS_bool = false;
	SAMEEMAIL_bool = false;
	NONE_bool = false;
	PHONE_bool = false;
	NUMBER_bool = false;
	CCNUMBER_bool = false;
	//
	
	ErrorString = "";
	setphoneerror = false;
	//loop through form elements
	for(var i=0; i<document.forms[name].length; i++)
	{
	//alert("CHECKING FIELD : " + document.forms[name].elements[i].name + "\n" + " VALUE : " + document.forms[name].elements[i].value + " \n"+ " TYPE : " + document.forms[name].elements[i].validate + "\n"+ " MAND : " + document.forms[name].elements[i].mandatory + "\n" + " LENGTH : " + document.forms[name].elements[i].value.length );
	
	
		if (document.forms[name].elements[i].type != "hidden" )
		{
		//alert("Not Hidden");	
			if ( document.forms[name].elements[i].mandatory == "true")
				{
					if ( document.forms[name].elements[i].value.length == 0)
					{
						if (mandbool == false)
						{
						mandbool=true;
						if (button_name == "Sign In")
						{
							ErrorString += "Please enter both a Customer Number or Email Address and your Password, and click Sign-in again.\n"
						} else {
							ErrorString += "Please complete all fields with an *, and then "
							if (typeof button_name != "undefined") {
								ErrorString += "click " + button_name
								
							} else {
								ErrorString += "try"
							}
							ErrorString += " again.\n"
						}
						ISError = ISError + 1;
						} else {
						ISError = ISError + 1;
						}	
					}
				}

			if (document.forms[name].elements[i].value.length != 0)
				{
				
				tempstring = document.forms[name].elements[i].validate;
				// pgd_001
				if ((tempstring == null) || (tempstring == undefined))
				{
				tempstring = "none";
				}
				tempstring.toUpperCase;
				switch( tempstring )
					{
					case "TEXT":
						if (checkString(document.forms[name].elements[i].value,"basic string") != true )
							{
							ISError = ISError + 1;
								if (TEXT_bool == false)
								{
								ErrorString = ErrorString + "Please complete all fields with only letters (A to Z) or number values (0 to 9), and then "
								if (typeof button_name != "undefined") {
									ErrorString += "click " + button_name
								} else {
									ErrorString += "try"
								}
								ErrorString += "again\n"
								TEXT_bool = true;
								}
							}
						break;
						
					case "EMAIL":
						if (isEmail(document.forms[name].elements[i].value) != true )
							{
							ISError = ISError + 1;
								if (EMAIL_bool == false)
								{
								ErrorString = ErrorString + "The email address entered is not in the correct format.  Please enter your correct email address (e.g. myname@mydomain.co.uk), and then "
								if (typeof button_name != "undefined") {
									ErrorString += "click " + button_name
								} else {
									ErrorString += "try"
								}
								ErrorString += " again.\n"

								EMAIL_bool = true;
								}
							}
							
						break;
						
					case "PASS":
					//alert("check password");
						if (isPassword(document.forms[name].elements[i].value, name) != true )
							{
							ISError = ISError + 1;
							if (PASS_bool == false)
								{	
								if (checkString(document.forms[name].elements[i].value,"basic string") != true ) {
									ErrorString = ErrorString + "The password you entered is invalid. Please correct these details and then "
									if (typeof button_name != "undefined") {
										ErrorString += "click " + button_name
									} else {
										ErrorString += "try"
									}
									ErrorString += "again\n"
								}else{
									ErrorString = ErrorString + "The passwords you entered are either blank, shorter than the required 6 characters or do not match. Please correct these details and then "
									if (typeof button_name != "undefined") {
										ErrorString += "click " + button_name
									} else {
										ErrorString += "try"
									}
									ErrorString += "again\n"
								}
								PASS_bool = true;
								}
							}
						break;
						
					case "CNUM":
						if (isCustomerNumber(document.forms[name].elements[i].value) != true )
							{
							ISError = ISError + 1;
							if (PASS_bool == false)
								{
								ErrorString = ErrorString + "The entered Customer Number is incorrect.  Please enter the correct details and then "
								if (typeof button_name != "undefined") {
									ErrorString += "click " + button_name
								} else {
									ErrorString += "try"
								}
								ErrorString += "again\n"
								CNUM_bool = true;
								}
							}
						break;
						
					case "PCDE":
						if (isPostCode(document.forms[name].elements[i].value) != true )
							{
							ISError = ISError + 1;
								if (button_name == 'Register')
								{
									if (PASS_bool == false)
									{	
									ErrorString = ErrorString + "The entered Postcode is not valid for this Customer Number.  Please enter the correct Postcode (e.g. SW1A 1AA) and then "
									if (typeof button_name != "undefined") {
										ErrorString += "click " + button_name
									} else {
										ErrorString += "try"
									}
									ErrorString += "again\n"
									PASS_bool = true;
									}
								} else {
									if (PASS_bool == false)
									{
									ErrorString = ErrorString + "The post code entered is not correct.  Please enter your full postcode (e.g. SW1A 1AA),  and then "
									if (typeof button_name != "undefined") {
										ErrorString += "click " + button_name
									} else {
										ErrorString += "try"
									}
									ErrorString += "again\n"
									PASS_bool = true;
									}
								}
							}
						break;

					case "SAMEPASS":
						//alert("check same password");
						if (checkSame(document.forms[name].elements[i].value,document.forms[name].elements[i+1].value) != true )
							{
							ISError = ISError + 1;
							if (SAMEPASS_bool == false)
								{
								ErrorString = ErrorString + "The passwords entered do not match.  Please enter the same password in each field, and then "
								if (typeof button_name != "undefined") {
									ErrorString += "click " + button_name
								} else {
									ErrorString += "try"
								}
								ErrorString += "again\n"
								SAMEPASS_bool = true;
								}
							}
							
						break;

					case "SAMEEMAIL":
						if (checkSame(document.forms[name].elements[i].value,document.forms[name].elements[i+1].value) != true )
							{
							ISError = ISError + 1;
							if (SAMEEMAIL_bool == false)
								{
								ErrorString = ErrorString + "The email addresses entered do not match.  Please enter the same email address in each field, and then "
								if (typeof button_name != "undefined") {
									ErrorString += "click " + button_name
								} else {
									ErrorString += "try"
								}
								ErrorString += "again\n"
								SAMEEMAIL_bool = true;
								
								}
							}
							
						break;

					case "NUMBER":
						if (checkString(document.forms[name].elements[i].value,"numbers") != true )
							{
							ISError = ISError + 1;
							if (NUMBER_bool == false)
								{
								ErrorString = ErrorString + "Invalid characters in a field expecting numbers. \n";
								NUMBER_bool = true;
								}
							}
						break;

					case "CCNUMBER":
						if (checkString(document.forms[name].elements[i].value,"numbers") != true )
							{
							ISError = ISError + 1;
							if (CCNUMBER_bool == false)
								{
								ErrorString = ErrorString + "Please re-enter your payment details without spaces or other non-numeric characters in the card number and then "
								if (typeof button_name != "undefined") {
									ErrorString += "click " + button_name
								} else {
									ErrorString += "try"
								}
								ErrorString += "again\n"
								CCNUMBER_bool = true;
								}
							}
						break;

					case "DELINSTR":
						if (document.forms[name].elements['del_instr'].value.length == 0 )
							{
							ISError = ISError + 1;
							ErrorString = ErrorString + "Please be sure to provide some delivery instructions for this address.\n";
}
						if (document.forms[name].elements['del_instr'].value == " " )
							{
							ISError = ISError + 1;
							ErrorString = ErrorString + "In order that we be able to make deliveries safely and promptly, we do need you to provide us with delivery instructions. We have entered sample delivery instructions into the box provided and you may use these if you wish.\n";
}

						break;

					case "PHONE":
						if (checkString(document.forms[name].elements[i].value,"numbers") != true )
							{
							ISError = ISError + 1;
								if (setphoneerror != true) {
								ErrorString = ErrorString + "The telephone number entered is not in the correct format.  Please enter only numbers (not letters or other characters) in the telephone number fields, and then "
								if (typeof button_name != "undefined") {
									ErrorString += "click " + button_name
								} else {
									ErrorString += "try"
								}
								ErrorString += "again\n"
								setphoneerror = true;
								}
							}
						break;

					case "EVENS":
						if (isEvens(document.forms[name].elements[i].value) != true || checkString(document.forms[name].elements[i].value,"numbers") != true)
							{
							ISError = ISError + 1;
								if (EVENS_bool == false)
								{
								ErrorString = ErrorString + "The card number entered is not in the correct format.  Please enter your correct card number, and then "
								if (typeof button_name != "undefined") {
									ErrorString += "click " + button_name
								} else {
									ErrorString += "try"
								}
								ErrorString += "again\n"
								EVENS_bool = true;
								}
							}
							
						break;
						
					case "NONE":
						//
						break;
						
					default:
						// do not do anything when this happens, browsers like Opera do not pass the data we need - which is correct, this whole JavaScript validation routine is awful.
						//ISError = ISError + 1;
						//	ErrorString = ErrorString + " UNKNOWN TYPE ENCOUNTERED for ";
						//	ErrorString = ErrorString + document.forms[name].elements[i].value + " " + document.forms[name].elements[i].validate;
						break;
					}	// switch
			} // length != 0
		
		} // not hidden
	}	// for loop
		
		
		if (ISError >=1) {

			

			if (document.forms[name].elements['del_instr']){
				if (document.forms[name].elements['del_instr'].value == " "){
					document.forms[name].elements['del_instr'].value = "If out, leave with neighbour";
				}
				if (document.forms[name].elements['del_instr'].value == ""){
					document.forms[name].elements['del_instr'].value = " ";
					ErrorString = ErrorString + "Please note that we do require delivery instructions for this address to help ensure prompt and safe delivery of your order.\n";}
					ErrorList.style.display='';
					ErrorList.innerText = ErrorString;
				} 
			}
					
			
					
			if (ISError >= 1) {	
				//alert("FAIL");
				window.scrollTo(0,0);
				ErrorList.style.display='';
				ErrorList.innerText = ErrorString;
				return false; // validation failed, error message displayed 
				
			} 
			else{
				//alert("SUCCESS : " + ISError + "Errors");
				ErrorList.style.display='none'
				return true; //validation passed, returning true to OnSubmit means the data will be posted / (getted?) to it's intended destination specified in the form action attribute.
			}
		}
