<!--

/**

File:     utils.js

Created:  June 5, 2001 by Malessa Korotnicki

Purpose:  Contains various utility functions (eg validation and confirmations) 

          used throughout the web site

Modified: Oct 9, 2001 by Malessa

            - changed the validation scripts error messages

Modified: March 6-8, 2002 by Robin Craig
		- added and modified some functions to complete the job

**/



//----------------------------------------------------------------------------



/*

trimSpaces trims the leading and trailing spaces from a given string

*/

function trimSpaces(vString){

	var newString = "";



	//split the string into words using spaces as the delimiter

	splitstring = vString.split(" ");



    //start with the first word (substring)

    var i = 0;

	//skip over the leading spaces	

    while(i < splitstring.length && splitstring[i] == ""){

 	   i++;

    }//end while



    //attach the first real word to the new string

    if(i < splitstring.length){

	   newString += splitstring[i];

	   i++;

    }//end if

	

    //attach the rest of the words to the new string, delimited by spaces

	for(; i < splitstring.length; i++){

	   if(splitstring[i] != ""){

 	      newString += " " + splitstring[i];

	   }//end if

	}//end for

	

	//return the trimmed new string

	return newString;

}//trimSpaces



//-------------------------------------------------------------------



/*

fieldNotEmpty returns true if the specified form textfield 

contains text, otherwise returns false.

*/

function fieldNotEmpty(vField){

   //trim the leading and trailing spaces in the textfield's text

   var trimmedValue = trimSpaces(vField.value);

   //save the new textfield value

   vField.value = trimmedValue;

   

   //after trimming, does the field contain any text?

   if(trimmedValue.length == 0){

	  return false;

   }//end if


   //field contains text, return true

   return true;

}//fieldNotEmpty



//-------------------------------------------------------------------



/*

fieldContainsText returns true if the specified form textfield 

contains text. Otherwise returns false and alerts an error message.

*/

function fieldContainsText(vField, vFieldType ){

  var hasData = fieldNotEmpty(vField);

   if(hasData == 0){

      alert("Missing Field: You need to enter " + vFieldType + ".");

	  vField.focus();

	  return false;

   }//end if

   

   //field contains text, return true

   return true;

}//fieldContainsText

function fieldHasTextNoHyperlink(vField, vFieldType ){

  var hasData = fieldNotEmpty(vField);

   if(hasData == 0){

      alert("Missing Field: You need to enter " + vFieldType + ".");

	  vField.focus();

	  return false;
   }//end if
		var teststr = vField.value;
		var capsstr = teststr.toUpperCase();
		var forbidden = "<A HREF";
		var hasit = capsstr.indexOf(forbidden);
		if(hasit == -1){
			return true;
		}else{
			alert("Sorry, for security reasons you can't include hyperlinks in your submission: please remove from " + vFieldType + " and try again.");
			return false;
		}
   //field contains text, return true
   return true;

}//fieldHasTextNoHyperlink



//-------------------------------------------------------------------



/*

optionSelected returns true if the specified form selection list 

has an option selected. If includeZero is true, includes the 

selection of the first item in the list as an option selection.

If no option is selected, returns false and alerts an error message

*/

function optionSelected(vSelect, vSelectType, includeZero){

	//is an option selected?

	if(includeZero && vSelect.selectedIndex >= 0){

		return true;

	} else if(!includeZero && vSelect.selectedIndex > 0){

		return true;



	//no option selected

	} else {

        alert("Missing Selection: You need to select " + vSelectType + ".");

		vSelect.focus();

		return false;

	}//endif

}//optionSelected



//-------------------------------------------------------------------



/*

fieldContainsNumber returns true if the specified form textfield 

contains a nuumber. Otherwise returns false and alerts 

an error message.

*/

function fieldContainsNumber(vNumberField, vNumberType){

   //is the field a number

   if(isNaN(vNumberField.value) || vNumberField.value.length == 0){

      alert("The " + vNumberType + " is not a valid number. Try again.");

      vNumberField.focus();

	  return false;

   } else {

      return true;

   }//endif

}//fieldContainsNumber



//-------------------------------------------------------------------



/*

fieldContainsPosNumber returns true if the specified form textfield 

contains a positive nuumber. Otherwise returns false and alerts 

an error message.

*/

function fieldContainsPosNumber(vPosNumberField, vPosNumberType){

   //is the field a number, and is it greater than zero?

   if(!fieldContainsNumber(vPosNumberField, vPosNumberType)){

      return false;

   } else if (vPosNumberField.value < 1){

      alert("Invalid Number: " + vPosNumberType + " must be more than zero. Try again.");

      vPosNumberField.focus();

	  return false;

   } else {

      return true;

   }//endif

}//fieldContainsPosNumber



//-------------------------------------------------------------------



/*

fieldContainsDigits returns true if the specified form textfield 

contains a digits. Otherwise returns false and alerts 

an error message.

*/

function fieldContainsDigits(vDigitsField, vDigitsType){

   var digitstext = vDigitsField.value;

   //regular expression matching a four digit postcode

   digitsRE = /^\d+$/

   if(!digitsRE.test(digitstext)){

      alert("Invalid Field: " + vDigitsType + " must contain numbers only.");

      vDigitsField.focus();

	  return false;

   }//endif

   return true;

}//fieldContainsDigits



//-------------------------------------------------------------------



/*

fieldContainsPostcode returns true if the specified form textfield 

contains a valid postcode (four digits). Otherwise returns false and alerts 

an error message.

*/

function fieldContainsPostcode(vPostcodeField, vPostcodeType){

   //check the field contains a value

   if(!fieldContainsText(vPostcodeField, vPostcodeType)){

      return false;

   }//end if



   var postcodetext = vPostcodeField.value;

   //regular expression matching a four digit postcode

   postcodeRE = /^\d{4}$/

   if(!postcodeRE.test(postcodetext)){

      alert("Invalid Field: The " + vPostcodeType + " must contain four digits.");

      vPostcodeField.focus();

	  return false;

   }//endif

   return true;

}//fieldContainsPostcode


//-------------------------------------------------------------------



/*

fieldContainsSpacedNumber returns true if the specified form textfield 

contains a valid spaced number, defined as numbers + spaces with the number of numerals in the specified range.

Otherwise returns false and alerts an error message.

*/

function fieldContainsSpacedNumber(vNumberField, vFieldType,mindigits,maxdigits){
	//check the field contains a value
	
	if(!fieldContainsText(vNumberField, vFieldType)){
		 return false;
	}
	var phoneNum = trimSpaces(vNumberField.value);
	var counter = 0;

	vNumberField.value = phoneNum;
	if(!fieldContainsText(vNumberField, vFieldType)){
		 return false;
	}

	var chars = phoneNum.length;
	
	var digit = "";
	var i = 0;	// if don't explicitly declare this, its value overrides i in caller!!!!
	for(i=0; i < chars; i++){
		digit = phoneNum.substr(i, 1);
		if((digit<"0" || digit>"9") &&  digit != " "){
			alert("Invalid entry: " + vFieldType + " can contain only numbers and spaces.");
			return false;
		} else {
			if(digit != " "){counter ++;}
		}
	}

	if(counter>maxdigits){
		alert("Invalid entry: " + vFieldType + " can have at most "+maxdigits+" numerals.");
			return false;
	} else {
		if(counter<mindigits){
			alert("Invalid entry: " + vFieldType + " needs at least "+mindigits+" numerals.");
			return false;
		}
	}
   return true;
}

//-------------------------------------------------------------------


/*

fieldContainsEmailAddress returns true if the specified form textfield

contains a valid email address.

Based on "emailCheck" by Sandeep V. Tamhankar

http://javascript.internet.com/forms/email-address-validation.html

*/

function fieldContainsEmailAddress(vEmailField, vEmailType) {

		

	/* The following pattern is used to check if the entered e-mail address

	fits the user@domain format.  It also is used to separate the username

	from the domain. */

	var emailPat=/^(.+)@(.+)$/;

	

	/* The following string represents the pattern for matching all special

	characters.  We don't want to allow special characters in the address. 

	These characters include ( ) < > @ , ; : \ " . [ ] */

	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

	

	/* The following string represents the range of characters allowed in a 

	username or domainname.  It really states which chars aren't allowed.*/

	var validChars="\[^\\s" + specialChars + "\]";

	

	/* The following pattern applies if the "user" is a quoted string (in

	which case, there are no rules about which characters are allowed

	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com

	is a legal e-mail address. */

	var quotedUser="(\"[^\"]*\")";

	

	/* The following pattern applies for domains that are IP addresses,

	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal

	e-mail address. NOTE: The square brackets are required. */

	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

	

	/* The following string represents an atom (basically a series of non-special characters.) */

	var atom=validChars + '+';

	

	/* The following string represents one word in the typical username.

	For example, in john.doe@somewhere.com, john and doe are words.

	Basically, a word is either an atom or quoted string. */

	var word="(" + atom + "|" + quotedUser + ")";

	

	/* The following pattern describes the structure of the user */

	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

	

	/* The following pattern describes the structure of a normal symbolic

	domain, as opposed to ipDomainPat, shown above. */

	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

	

	/* Finally, let's start trying to figure out if the supplied address is valid. */



	/* get the email address from the text field */

	emailAddress = trimSpaces(vEmailField.value);

	vEmailField.value = emailAddress;

	/* is the email address field blank? */

	if(emailAddress.length == 0){

		alert("Missing Email: You need to enter " + vEmailType);

		vEmailField.focus();

		return false;

	}//end if

	

	/* Begin with the coarse pattern to simply break up user@domain into

	different pieces that are easy to analyze. */

	var matchArray=emailAddress.match(emailPat);

	if (matchArray==null) {

	/* Too many/few @'s or something; basically, this address doesn't

	even fit the general mould of a valid e-mail address. */

		alert("Invalid Email: " + vEmailType + " seems incorrect (check @ and .'s)");

		vEmailField.focus();

		return false;

	}//end if email doesn't match x@y.com pattern

	

	var user=matchArray[1];

	var domain=matchArray[2];

	/* Start by checking that only basic ASCII characters are in the strings (0-127). */

	//for each chearacter in the user name
	var i = 0;
	for (i=0; i<user.length; i++) {

		//is the char an ASCII char?

		if (user.charCodeAt(i)>127) {

			alert("Invalid Email: The username of " + vEmailType + " contains invalid characters.");

			vEmailField.focus();

			return false;

		}//end if ASCII

	}//end for each char in user name




	//for each char in domain

	for (i=0; i<domain.length; i++) {

		//is the char an ASCII char?

		if (domain.charCodeAt(i)>127) {

			alert("Invalid Email: The domain name of " + vEmailType + " contains invalid characters.");

			vEmailField.focus();

			return false;

		}//end if ASCII

	}//edn for each char in domain

	

	/* see if "user" is valid  */

	if (user.match(userPat)==null) {

		// user is not valid

		alert("Invalid Email: The username of " + vEmailType + " doesn't seem to be valid.");

		vEmailField.focus();

		return false;

	}//end if user name invalid

	

	/* if the e-mail address is at an IP address (as opposed to a symbolic

	host name) make sure the IP address is valid. */

	var IPArray=domain.match(ipDomainPat);

	//is the domain an IP address?

	if(IPArray!=null) {

		//for each part of the IP address

		for (var i=1;i<=4;i++) {

			//check address part is a valid number - ie. less than 255

			if (IPArray[i]>255) {

				alert("Invalid Email: The destination IP address of " + vEmailType + " is invalid!");

				vEmailField.focus();

				return false;

			}//end if address part not valid

		}//end for each part of IP address

		//valid IP address type email

		return true;

	}//end if an IP address email

	

	/* Domain is symbolic name.  Check if it's valid. */

	var atomPat=new RegExp("^" + atom + "$");

	//split the domain up into segments using its .'s

	var domArr=domain.split(".");

	//len equals the number of array segments

	var len=domArr.length;

	//for each segment of the domain

	for (i=0;i<len;i++) {

	//does the segment contain valid characters?

		if (domArr[i].search(atomPat)==-1) {

			//segment contains invalid characters

			alert("Invalid Email: The domain name of " + vEmailType + " does not seem to be valid.");

			vEmailField.focus();

			return false;

		}//end if sement contains valid chars

	}//end for each segment

	

	/* Make sure there's a host name preceding the domain. */

	//are there less than two segments in the domain?

	if (len<2) {

		alert("Invalid Email: " + vEmailType + " is missing a hostname!");

		vEmailField.focus();

		return false;

	}//end if

	

	/* If we've gotten this far, everything's valid! */

	return true;

}//fieldContainsEmailAddress



//-------------------------------------------------------------------



/*

fieldContainsCreditCardNr returns true if the specified form textfield contains a valid credit card number.

Otherwise returns false and alerts an error message.

*/

function fieldContainsCreditCardNr(vCreditCardNrField, vCreditCardNrType){

	var result = fieldContainsSpacedNumber(vCreditCardNrField, vCreditCardNrType,16,16);
      return result;

}//fieldContainsCreditCardNr



//-------------------------------------------------------------------


function fieldContainsPhoneNum(vPhoneNrField, vPhoneNrType){

	var result = fieldContainsSpacedNumber(vPhoneNrField, vPhoneNrType,6,8);
      return result;

}//fieldContainsPhoneNum

//-------------------------------------------------------------------


/*

fieldContainsCreditCardDate returns true if the specified form textfield 

contains a valid credit card date (ie. date in the format mm/yy).

Otherwise returns false and alerts an error message.

*/

function fieldContainsCreditCardDate(vDateField, vDateType){

   //check the field contains a value

   if(!fieldContainsText(vDateField, vDateType)){

      return false;

   }//end if



   var datetext = vDateField.value;

   //regular expression matching a date in mm/yy format

   dateRE = /^[0|1][0-9]\/0[1-9]$/

   if(!dateRE.test(datetext)){

      alert("Invalid Date: " + vDateType + " must be in the format mm/yy with valid month and day values.");

      vDateField.focus();

	  return false;

   }//endif

   return true;

}//fieldContainsCreditCardDate



//-->