
//*************************************************************************
// If the message does not equal 'none', the alert the user the	message
// and return the user to the offending	field
//*************************************************************************
function errorMessage(theField,	message)
{
	if (message != "none")
	{
		alert(message);
		theField.focus();
    if (!(theField.type == "checkbox") && (! theField.type.match (/^[Ss]elect/))) // select fields cause an error with select() as well (TJH)
		{
			theField.select();
		}

	}

}


//*************************************************************************
// (for	list boxes)If the message does not equal 'none', the alert the user
// the message and return the user to the offending field
//*************************************************************************
function errorMessageB(theField, message)
{
	if (message != "none")
	{
		alert(message);
		theField.focus();
	}
}


//*************************************************************************
// Returns true	if at least one	of a group of text boxes hasn't been filled in
//*************************************************************************
function allEmpty(message, field1, field2, field3, field4, field5, field6, field7, field8, field9, field10)
{
	emptyFields = 0;
	if  ((field1) && (field1.value != "")) {emptyFields = 1}
	if	((field2) && (field2.value != "")) {emptyFields = 1}
	if	((field3) && (field3.value != "")) {emptyFields = 1}
	if	((field4) && (field4.value != "")) {emptyFields = 1}
	if	((field5) && (field5.value != "")) {emptyFields = 1}
	if	((field6) && (field6.value != "")) {emptyFields = 1}
	if	((field7) && (field7.value != "")) {emptyFields = 1}
	if	((field8) && (field8.value != "")) {emptyFields = 1}
	if	((field9) && (field9.value != "")) {emptyFields = 1}
	if	((field10) && (field10.value != "")) {emptyFields = 1}

	if (emptyFields == 0)
	{
		errorMessage(field1, message);
		return true;
	}
}



//*************************************************************************
// Returns true	if even	one of a group of text boxes has not been filled in
//*************************************************************************
function anyEmpty(message, field1, field2, field3, field4, field5, field6, field7, field8, field9, field10)
{
	if (((field1) && (field1.value == "")) ||
		((field2) && (field2.value == "")) ||
		((field3) && (field3.value == "")) ||
		((field4) && (field4.value == "")) ||
		((field5) && (field5.value == "")) ||
		((field6) && (field6.value == "")) ||
		((field7) && (field7.value == "")) ||
		((field8) && (field8.value == "")) ||
		((field9) && (field9.value == "")) ||
		((field10) && (field10.value == ""))    )

		{
			errorMessage(field1, message);
			return true;
		}
}


//*************************************************************************
// Returns true	if even	one of a group of option boxes has not been selected
//*************************************************************************
function anyEmptyListBox(message, field1, field2, field3, field4, field5, field6, field7, field8, field9, field10)
{
	if (((field1) && (field1.options[field1.selectedIndex].value == "")) ||
		((field2) && (field2.options[field2.selectedIndex].value == "")) ||
		((field3) && (field3.options[field3.selectedIndex].value == "")) ||
		((field4) && (field4.options[field4.selectedIndex].value == "")) ||
		((field5) && (field5.options[field5.selectedIndex].value == "")) ||
		((field6) && (field6.options[field6.selectedIndex].value == "")) ||
		((field7) && (field7.options[field7.selectedIndex].value == "")) ||
		((field8) && (field8.options[field8.selectedIndex].value == "")) ||
		((field9) && (field9.options[field9.selectedIndex].value == "")) ||
		((field10) && (field10.options[field10.selectedIndex].value == ""))     )
		{
			errorMessageB(field1, message);
			return true;
		}
}

//*************************************************************************
// Returns true	if at least one	of a group of option boxes hasn't been selected
//*************************************************************************
function allEmptyListBox(message, field1, field2, field3, field4, field5, field6, field7, field8, field9, field10)
{
	emptyFields = 0;
	if 	((field1) && (field1.options[field1.selectedIndex].value != "")) {emptyFields = 1}
	if	((field2) && (field2.options[field2.selectedIndex].value != "")) {emptyFields = 1}
	if	((field3) && (field3.options[field3.selectedIndex].value != "")) {emptyFields = 1}
	if	((field4) && (field4.options[field4.selectedIndex].value != "")) {emptyFields = 1}
	if	((field5) && (field5.options[field5.selectedIndex].value != "")) {emptyFields = 1}
	if	((field6) && (field6.options[field6.selectedIndex].value != "")) {emptyFields = 1}
	if	((field7) && (field7.options[field7.selectedIndex].value != "")) {emptyFields = 1}
	if	((field8) && (field8.options[field8.selectedIndex].value != "")) {emptyFields = 1}
	if	((field9) && (field9.options[field9.selectedIndex].value != "")) {emptyFields = 1}
	if	((field10) && (field10.options[field10.selectedIndex].value != "")) {emptyFields = 1}

	if (emptyFields == 0)
	{
		errorMessageB(field1, message);
		return true;
	}
}


//*************************************************************************
// Returns the value of	the selected radio button
//*************************************************************************
function whichRadioButton(buttons)

{
        var j = 0;

	chosenOption = -1;
	for(j = 0; j < buttons.length; j++)
	{
		if(buttons[j].checked)
		{
			chosenOption = j;
		}
	}

	if (chosenOption == -1)
	{
		return "none";
	}
	else
	{
		return buttons[chosenOption].value;
	}

}


//*************************************************************************
// Returns true if no radio buttons have been chosen
//*************************************************************************
function noRadioButtons(message, buttons)

{
        var j = 0;

	chosenOption = -1;
	for(j = 0; j < buttons.length; j++)
	{
		if(buttons[j].checked)
		{
			chosenOption = j;
		}
	}

	if (chosenOption == -1)
	{
		if (message != 'none')
		{
			alert(message);
			buttons[0].focus();
			return true;
		}
	}
}

//*************************************************************************
// Returns the value of	the selection from a listbox
//*************************************************************************
function listBoxValue(theField)
{
	return theField.options[theField.selectedIndex].value;
}



//*************************************************************************
// Returns true	if a text field	contains one of	two specified values
//*************************************************************************
function textMismatch4(option1,	option2, option3, option4, theField, message)
{
	if ((theField.value != option1)	&& (theField.value != option2) && (theField.value != option3) && (theField.value != option4))
	{
		errorMessage(theField, message);
		return true;
	}
}

//*************************************************************************
// Returns true	if the field contains a	correct	email address
//*************************************************************************
function invalidEmail(message, theField)
{

        var j = 0;

	invalidChars = '/:,;';

	for (j = 0; j < invalidChars.length; j++)
	{
		badChar	= invalidChars.charAt(j);
		if (theField.value.indexOf(badChar,0) >	-1)
		{
			errorMessage(theField, message);
			return true;
		}
	}

	atPos =	theField.value.indexOf(" ",1);
	if (atPos != -1)
	{
		errorMessage(theField, message);
		return true;
	}

	atPos =	theField.value.indexOf("@",1);
	if (atPos == -1)
	{
		errorMessage(theField, message);
		return true;
	}

	if (theField.value.indexOf("@",	atPos+1) > -1)
	{
		errorMessage(theField, message);
		return true;
	}

	periodPos = theField.value.indexOf(".",	atPos);
	if (periodPos == -1)
	{
		errorMessage(theField, message);
		return true;
	}

	if ((periodPos - 1) == atPos)
	{
		errorMessage(theField, message);
		return true;
	}

	if (periodPos +	3 > theField.value.length)
	{
		errorMessage(theField, message);
		return true;
	}
}


//*************************************************************************
// Populates a drop down list in ascending order
//*************************************************************************
function populateUp(first, last)
{
	for (num = first; num <= last; num++)
	{
    	document.write('<option value="',num,'">',num,'<\/option>');
	}
}


//*************************************************************************
// Populates a drop down list in descending order
//*************************************************************************
function populateDown(last, first)
{
	for (num = last; num >= first; num--)
	{
    	document.write('<option value="',num,'">',num,'<\/option>');
	}
}


//*************************************************************************
// Return true if the field contains less characters than the minLength
//*************************************************************************
function checkLength(message, theField, minLength)
{
	if (theField.value.length < minLength)
	{
		errorMessage(theField, message);
		return true;
	}
}


//*************************************************************************
// Return true if the field contains a space character
//*************************************************************************
function anySpaces(message, theField)
{
	if (theField.value.indexOf(' ') != -1)
	{
		errorMessage(theField, message);
		return true;
	}
}


//*************************************************************************
// Return true if the two fields are the same
//*************************************************************************
function theSame(message, theField1, theField2)
{
	if (theField1.value != theField2.value)
	{
		errorMessage(theField2, message);
		return false;
	}
	return true;
}


//*************************************************************************
// Return true if the fields value is within the bounds set by the limit
// and the comparator, where the field is on the right hand side of the equation,
// and the limit on the left.
//*************************************************************************
function valueCheck(message, theField, theComparator, theLimit)
{
	if (!(eval(theField.value + theComparator + theLimit)))
	{
		errorMessage(theField, message);
		return false;
	}
	return true;
}


//*************************************************************************
// Return true if the fields value is between the upper and lower values
//*************************************************************************
function valueInRange(message, theField, lowerLimit, upperLimit)
{
	if ((theField.value < lowerLimit) || (theField.value > upperLimit))
	{
		errorMessage(theField, message)
		return false;
	}
	return true;
}


//*************************************************************************
// Converts a string value for a month to a number
//*************************************************************************
function convertMonth(theMonth)
{
	switch(theMonth.toUpperCase())
	{
		case 'JAN': return '1';
		case 'FEB': return '2';
		case 'MAR': return '3';
		case 'APR': return '4';
		case 'MAY': return '5';
		case 'JUN': return '6';
		case 'JUL': return '7';
		case 'AUG': return '8';
		case 'SEP': return '9';
		case 'OCT': return '10';
		case 'NOV': return '11';
		case 'DEC': return '12';
	}
}


//*************************************************************************
// Return true if a numberField is all numbers and nothing else.
//*************************************************************************
function isNumbersOnly(numberValue)
{
	var tempString = numberValue.replace(/[0-9]/gi,'');
	return (tempString.length == 0);
}

//*************************************************************************
// Return true if a numberField is all numbers or dollar sign and
// nothing else.
//*************************************************************************
function isNumbersOrDollarSignOnly(numberDollarValue)
{
	var tempString = numberDollarValue.replace(/[$]|[0-9]/g,'');
	return (tempString.length == 0);
}


//*************************************************************************
// Returns true is a credit card is valid via the mod 10 check
//*************************************************************************
function creditCardCheck(message, field1, field2, field3, field4)
{

        var j = 0;

	answer = false;
	correct = 0;
	if ((field1.value.length < 4) || !(isNumbersOnly(field1.value)))	{correct = -1;}
	if ((field2.value.length < 4) || !(isNumbersOnly(field2.value)))	{correct = -1;}
	if ((field3.value.length < 4) || !(isNumbersOnly(field3.value)))	{correct = -1;}
	if ((field4.value.length < 3) || !(isNumbersOnly(field4.value)))	{correct = -1;}

	if (correct == 0)
	{
		var cardString = (field1.value + field2.value + field3.value + field4.value)
		var doubleDigit = cardString.length % 2 == 1 ? false:true;
		var checkDigit = 0;

		for (j = 0; j < cardString.length; j++)
		{
			tempDigit = eval(cardString.charAt(j));
			if (doubleDigit)
			{
				tempDigit *= 2;
				checkDigit += (tempDigit % 10);

				if ((tempDigit/10) >= 1.0)
				{
					checkDigit++
				}
				doubleDigit = false;
			}
			else
			{
				checkDigit += tempDigit;
				doubleDigit = true;
			}
		}
		var answer = (checkDigit % 10) == 0 ? true : false;
	}

	if (answer == true)
	{
		return true;
	}
	else
	{
		errorMessageB(field1, message);
		return false;
	}

}


//*************************************************************************
// Splits up a field into portions of 'theSize' number of characters
//*************************************************************************
function splitField(theField, theSize, portion)
{
	var answer;
	if (portion == 1) {answer = theField.substr(0, theSize)}
	if (portion == 2) {answer = theField.substr(theSize, theSize)}
	if (portion == 3) {answer = theField.substr(theSize * 2, theSize)}
	if (portion == 4) {answer = theField.substr(theSize * 3, theSize)}

	return answer;
}


/******************************************************************************
* Pre-populate checkbox fields with one or more selected items.
*
* Parameters:
*
* fieldArray (array of object)  Array of checkbox field objects
* defaultValue (string)         The value(s) to be selected
*
*********************************************************************************/

function populateCheckbox(fieldArray, defaultValue) {

   var j = 0;
   var jj = 0;

   for (j=0; j < fieldArray.length; j++) {

      if (defaultValue != '') {
         itemLength = fieldArray[j].length;
         if (itemLength == null) {                  // test if length is undefined
            itemLength = 1;
         }
         for (jj=0; jj < itemLength; jj++) {
            if (itemLength == 1) {                 // Single item
               str = fieldArray[j].value;
               if (defaultValue.indexOf(str) != -1) {
                  fieldArray[j].checked = true;
               }
            }else{                                 // Array item
               str = fieldArray[j][jj].value;
               if (defaultValue.indexOf(str) != -1) {
                  fieldArray[j][jj].checked = true;
               }
            }
         }
      }
   }
}


/********************************************************************************
* Pre-populate a radio button field with a selected item.
*
* Parameters:
*
* radioField (object)     The selection list field e.g. document.forms[0].gender
* defaultValue (string)  The value to be selected
*
*********************************************************************************/

function populateRadioButton(radioField, defaultValue) {

   var j = 0;

   if (defaultValue != '') {
      itemLength = radioField.length;
      if (itemLength == null) {                   // test if length is undefined
         itemLength = 1;
      }
      for (j=0; j < itemLength; j++) {
         if (itemLength == 1) {                  // Single item
            if (radioField.value == defaultValue) {
               radioField.checked = true;
            }
         }else{                                  // Array item
            if (radioField[j].value == defaultValue) {
               radioField[j].checked = true;
            }
         }
      }
   }
}


/*************************************************************************************
* Pre-populate a selection list field with one or more selected items.
*
* Parameters:
*
* listField (object)     The selection list field e.g. document.forms[0].occupations
* defaultValue (string)  The value(s) to be selected
*
**************************************************************************************/

function populateSelectionList(listField, defaultValue) {

   var j = 0;

   if (defaultValue != '') {
      itemLength = listField.length;
      if (itemLength == null) {                     // test if length is undefined
         itemLength = 1;
      }
      for (j=0; j < itemLength; j++) {
         if (itemLength == 1) {                     // Single item
            str = listField.value;
            if (defaultValue.indexOf(str) != -1) {
               listField.selected = true;
            }
         }else{                                     // Array item
            str = listField.options[j].value;
            if (defaultValue.indexOf(str) != -1) {
               listField.options[j].selected = true;
            }
         }
      }
   }
}


/*************************************************************************************
* This function checks to see if a field value contains any non alphanumeric
* characters (valid characters are: 0..9, A..Z, a..z).
*
* 0..9 = 48..57
* A..Z = 65..90
*
* Parameters:
*
* message (String)     Error message to be displayed
* theField (Object)    Field containg the value to be validated
* minNumeric (Number)  Minimum number of a numerics the field value should contain
* minAlpha (Number)    Minimum number of a alpha charcters the field value should contain
*
**************************************************************************************/

function invalidAlphaNumericFieldValue(message, theField, minNumeric, minAlpha) {

   var numCount = 0;
   var alphaCount = 0;
   var fieldValue = theField.value.toUpperCase();
   var j = 0;

   for (j=0; j < fieldValue.length; j++)
   {
      if ((fieldValue.charCodeAt(j) >= 48) && (fieldValue.charCodeAt(j) <= 57))      {  // Numeric (0..9)
         numCount++;
      }else{
         if ((fieldValue.charCodeAt(j) >= 65) && (fieldValue.charCodeAt(j) <= 90))   {  // Alpha (A..Z)
            alphaCount++;
         }else{
            errorMessage(theField, message)
            return true;
         }
      }
   }
   if ((minNumeric > 0) && (numCount < minNumeric)) {
      errorMessage(theField, message)
      return true;
   }else{
      if ((minAlpha > 0) && (alphaCount < minAlpha)) {
         errorMessage(theField, message)
         return true;
      }
   }
}


/*************************************************************************************
*
* This function limits the size of a text area to a specified number of characters
* (maxLength). This function is to be used inconjuction with a onKeyUp and onKeyDown
* events.
*
**************************************************************************************/

function textAreaLimit(field, maxLimit) {

   if (field.value.length > maxLimit) {
      field.value = field.value.substring(0, maxLimit);
   }
}


//*************************************************************************************
// This returns true if the field is too long. It requires parameters for the field,
// the maximum length the field can contain, and the name of the field as it is to
// appear in the error message.
//*************************************************************************************
function textAreaOversize(theField, maxLimit, fieldName)
{
	if (theField.value.length > maxLimit) {
		var message="The " + fieldName + " field has exceeded its length. It has a limit of " + maxLimit + " characters. It currently contains " + theField.value.length + " characters.  Please reduce the length of the text.";
		errorMessage(theField,	message);
		return true;
	}
	return false;
}


//*************************************************************************************
// This returns a string with leading zeros stripped out.  Used to workaround
// the Javascript feature where '011' is parsed as a base 8 number and returns
// the integer 9.
// NB The parseInt javaScript will also be screwed up by commas
//*************************************************************************************
function removeLeadingZeros(numberString) {
   var leadingZeroCount = 0;
   var charIndex = 0;
   var newNumberString = '';

   for (charIndex=0; charIndex<numberString.length; charIndex++) {
      if (numberString.charCodeAt(charIndex) == 48) {  // Numeric 0)
         leadingZeroCount++;
      } else {
         return numberString.substr(leadingZeroCount, numberString.length);
      }
   }
   return numberString;
}


//*************************************************************************************
// Returns a string that has had
//    1. any leading Zeros which Javascript would treat a number as Octal, removed
//    2. any commas removed, commas screw up parseInt if the commas are not in the right place
//*************************************************************************************

function removeCommasAndLeadingZeros( searchStr ){
  // pattern for ,, which screws up parseInt()
  var commasPattern = /,/g;
  var leadingZerosPattern = /^([ -])*[0]+([1-9]+)/;
  var replacePattern = "$1$2";
  var replaceStr = searchStr.replace( commasPattern, "" );
  replaceStr    = replaceStr.replace( leadingZerosPattern, replacePattern );
  //alert( 'replaced :' + searchStr + ' with :' + replaceStr );
  return replaceStr;
}



//*************************************************************************************
// returns either a ParsedInt or if characters out of the number set
//   (ie anything other than characters that could reasonably construed
//     as numbers not 0-9 or '-+.' )
// then unchanged string
//
//*************************************************************************************
function removeGarbageAndParseInt( searchStr ){
  // pattern for .. garbage
  var nanPattern = /[a-zA-Z\x00-\x01f\x7f-\xff!"#$%&'\(\)\*\/:;<=>\?@\\\]\^_`\{\|\}~]/
  // pattern for .. which screws up parseInt()
  var nanPattern2 = /(\.\.)+/
  if ( searchStr.match( nanPattern )  ){
    //alert( 'found non Number 1' );
    return searchStr;
  }
  if ( searchStr.match( nanPattern2 )  ){
    //alert( 'found non Number 2' );
    return searchStr;
  }
  str1 = removeCommasAndLeadingZeros( searchStr );
  return parseInt( str1 );

}

//************************************************

function concatenateRadioButtonValues(fieldArray, separator) {
   
   var concatList = '';  
   var j = 0;
   var fieldValue = '';

   for (j=0; j < fieldArray.length; j++) {
      fieldValue = whichRadioButton(fieldArray[j]);
      if (fieldValue != 'none') {
         concatList = concatList + whichRadioButton(fieldArray[j]) + separator; 
      }
   }
    
   if (concatList != '') {
      concatList = concatList.substr(0, (concatList.length-1)) 
   }

   return concatList;
}