/*
editscript form validation library
(c) Copyright 2007 Tempo Consulting, All rights reserved
Version 2010-09-01

9/1/2010 3:56PM
Added checkValue()

8/21/2007 9:21AM
Simplified checkEmail() to accomodate more complex email addresses

9/21/2007 8:24PM
Updated checkEmail() to return true if no email is provided
*/

// *** VARIABLE DEFINITIONS ***

var pageChanged = false;
var arrFormChecks = new Array(); //array used to hold all the checks passed in the from the html
var checkStatus, checkMessage, checkFirstObject;
var isNN = (document.layers);
var isIE = (document.all);
var restoreColorValues = new Array(); //an array that holds original color values prior to checkError changing them
var elementCounter; //used to allow us to index through an array
var isMac = navigator.appVersion.indexOf("Mac") != -1;
var isMacPPC = isMac && (navigator.appVersion.indexOf("PPC") != -1 || navigator.appVersion.indexOf("PowerPC") != -1);


// *** BASIC FUNCTIONS ***

function addCheck(formCheck)
{
	arrFormChecks[arrFormChecks.length] = formCheck;
}

function addNewFormCheck(formCheck)
{
	var checkExists = false

	for (var i = 0; i <= arrFormChecks.length; i++)
	{
		if (arrFormChecks[i] == formCheck)
		{
			checkExists = true;
		}
	}

	if (!checkExists)
	{
		addCheck(formCheck);
	}
}

function removeNewFormCheck(formCheck)
{
	for (var i = 0; i <= arrFormChecks.length; i++)
	{
		if (arrFormChecks[i] == formCheck)
		{
			arrFormChecks[i] = "";
		}
	}
}

function checkError(fieldObj, errText)
{

	if (checkStatus) checkFirstObject = fieldObj;


		var re1 = /fieldObj.name/
 		var original = 1;
 		var stringMatch; //used to hold array's contents per element
 		/*
 			 - Walk through entire array
 			 - Look for fieldObj.name inside each array element
 			 - if not found, add to array, otherwise it will naturally fall out
 		*/
 		for (elementCounter = 0; elementCounter <= restoreColorValues.length; elementCounter++){

 			//needed to catch if we are on the last element of the array, since it is undefined

 			if (!(restoreColorValues[elementCounter])) //if null or undefined, we've made it through the array, fall into the loop
 			{
 				//Get current colors from fields
 				if (isIE){

					//used to identify radio buttons differently because otherwise object doesn't exist.
					//Example: fieldObj.name will cause undefined to return if the object is a radio button, but not a text field
					var radioButton = 0

 					//must case out radio buttons and select lists because we need to specify array index or we can't get object properties
 					//If its undefined, it isn't a radio button and therefore we need to treat it differently
 					if (fieldObj[0]){


 						if (fieldObj.type == "select-one") {

 							var borderColorTemp	 = fieldObj[0].style.borderColor;
				 			var backgroundColorTemp = fieldObj[0].style.backgroundColor;
 							//Remove radioButton as a flag, because we can't call fieldObj[0].name. It will
 							//return undefined and we'll get problems when we go to set the color back

 						}
 						else {

	 						var borderColorTemp	 = fieldObj[0].style.borderColor;
				 			var backgroundColorTemp = fieldObj[0].style.backgroundColor;
	 						radioButton			 = 1

	 					}

 					}
	 				else
	 				{
	 					var borderColorTemp		 = fieldObj.style.borderColor;
				 		var backgroundColorTemp	 = fieldObj.style.backgroundColor;
 				 	}

				 	if (borderColorTemp != "#ff0000") //if already an error color, leave for loop
 					{
 					 	var arrayLength = restoreColorValues.length + 1;
	 				 	if (radioButton == 0){

		 				 			//All objects are included in here except radio buttons.
			 				 		restoreColorValues[arrayLength] = fieldObj.name + ',' + borderColorTemp + ',' + backgroundColorTemp;
									break;

							}
							else{

									//This captures radio buttons and retrieves their name
									restoreColorValues[arrayLength] = fieldObj[0].name + ',' + borderColorTemp + ',' + backgroundColorTemp;
									break;

							}
						}

					else
				 	{
				 		//catching error colors and we do not want that
 				 		break;
 				 	}
 				}//is IE?


 			}//fill array if possible

 			  else
 			  {

 					stringMatch = restoreColorValues[elementCounter];

					if(stringMatch.search(re1))
 					{
 						//Leave the loop because the object is in the array
 						break;
 					}

 					else
 					{
 						continue;
 					}

 			 }
 	 }//end of for loop

	if (isIE)
	{
		//If the object is a radio button or checkbox then, set the buttons to error colors, otherwise set the object itself to error colors
		if (fieldObj[0] && (fieldObj[0].type == 'radio' || fieldObj[0].type == 'checkbox')){
		// Set all selections for the radio button to error colors
	 		 for (var x=0; x < fieldObj.length; x++) {
	 		 	fieldObj[x].style.borderColor = '#ff0000';
				fieldObj[x].style.backgroundColor = '#ffff99';
	 		 }
	 	}
		else
		{
			fieldObj.style.borderColor = '#ff0000';
			fieldObj.style.backgroundColor = '#ffff99';
		}
	}
		checkMessage += errText;
}//End of function CheckError()

function checkForm(formName)
{
	checkStatus = true;
	checkFirstObject = "";
	checkMessage = 'There is a problem with some of the information you entered.\nPlease fix the following items and try submitting the form again.\n\n';

	var formsName = formName.name;

	//Clean out prior color values in array and let checkError maintain list
	for ( var x = 0; x <= restoreColorValues.length; x++ ){

	//alert("array restoreColorValues " + x + ": " + restoreColorValues[x] + "\n");


				///***Note radio buttons don't make it past here **/
				if (restoreColorValues[x] == "" || !(restoreColorValues[x]))
				{
					continue;
				}
				/*
				 Break up the array restoreColorValues, into element:
				   - object name	 0
				   - borderColor	 1
				   - backgroundColor 2
				 Then pass them to restoreColorToCell which actually changes the value back
				*/

				var newArray = restoreColorValues[x].split(",");


				var fieldObjTEMP	= newArray[0];
				var borderColor	 = newArray[1];
				var backgroundColor = newArray[2];


				//Means the object isn't a radio button
				restoreColorToCell(formsName, fieldObjTEMP, borderColor, backgroundColor);


				//Clean array element after finishing color change
				restoreColorValues[x] = "";


	}	//end of for loop


	for (var i = 0; i < arrFormChecks.length; i++)
	{

		if (arrFormChecks[i] != "" ){

			//search for whether or not we're on the same form as the one we submitted.
			//If so lets eval it, otherwise skip

			var temp = arrFormChecks[i]
			var test = (temp =  arrFormChecks[i].indexOf(formName.name));

			//Skip because we can't find the string in the form name
			/*
			if(test == "-1"){
				continue;
			}

			else {
			*/
				if(!eval(arrFormChecks[i]))
				{
					checkStatus = false;

				};
			//}
		}

	}

	if(!checkStatus)
	{
		//If the object is not a button, which will return an undefined status due to index issues, set the focus to it


		if(checkFirstObject.type == 'radio') {
		//if(eval(checkFirstObject.focus())){
			checkFirstObject.focus();
		}
	}
	return checkStatus;
} //end of function checkForm()


function editCancel()
{
	pageChanged = false;
	self.close();
}

function editClose()
{
	if (pageChanged)
	{
		var closewarning = newWindow('warning.asp','closewarning',400,100);
	}
}


function editSave(formName)
{
	pageChanged = false;

	if (!formName) var formName = document.editform;
	var submitForm = "document." ;
	submitForm += formName.name;
	submitForm += ".submit()";

	checkForm(formName) ? eval(submitForm) : alert(checkMessage);
}

function restoreColorToCell(formName, fieldObjName, borderColor, backgroundColor )
{
	/*
	   If borderColorRestore and backgroundColorRestore aren't passed in, they'll be null by default
	   and we'll simply set the borderColor and backgroundColor to white, otherwise we set it to the
	   values passed in.
	*/
	var tempObject;

	tempObject = 'document.' + formName + '.' + fieldObjName;

	if (isIE)
	{
		//only change the style back if its a windows machine, don't do it on Macs because it doesn't work
		if ( !(isMac) && !(isMacPPC) ) {
			if (eval(tempObject).name && eval(tempObject).style) {
				//alert("not box: " + eval(tempObject).style.borderColor);
				//Assigning old values back to object
			 	eval(tempObject).style.borderColor = borderColor;
		 		eval(tempObject).style.backgroundColor = backgroundColor;
			} else {
				//alert("box: " + eval(tempObject)[0].style.borderColor);
				var objField = eval(tempObject);
				if (objField[0].style) {
					for(var x=0; x < objField.length; x++) {
						objField[x].style.borderColor = borderColor;
						objField[x].style.backgroundColor = backgroundColor;
						//objField[x].style.backgroundColor = "#ffffff";
					}
				}
			}
			return true;
		}
	}


	else
	{
		return true;
	}
}//End of restoreColorToCell

function setSelectOption (objList, strValue) {
	for (var i = 0; i < objList.length; i++) {
		if(strValue == objList[i].value) {
			objList.options[i].selected = true;
//		alert(objList.options[objList.options.selectedIndex].value);
		}
	}
}//End setSelectedOption()

// *** CHECK FUNCTIONS ***

function checkDate(fieldObj,fieldName)
{
	/*
	Date: 9-24-01 3:23pm
	Author: Sam Chehab
	Check to ensure the value passed is in a date format.
		1 - check to see if the formatting of the date is proper, using regex to do that.
		2 - checking to make sure the month and day values aren't too high or 0
		3 - comparing the month value to the day value to see if its legit.
	*/


	//Variable Declarations
	var reDate = /^[0-1]?[0-9][\/-][0-3]?[0-9][\/-][0-9]{4}$/
 	var arrDate = fieldObj.value.match(reDate);

	//if nothing was passed in return true and exit function
	if (fieldObj.value.length == 0){
		return true;
  	}
	//if value matches regex, then we dig deeper to see if there are that many days in the month
	if (arrDate) {

		var temp = fieldObj.value;
		var dateArray = temp.split(temp.charAt(temp.length - 5));

		var month	= dateArray[0];
		var day		= dateArray[1];
		var year	= dateArray[2];

		//Declare an array and compare the month values to the arguments
		var daysInMonth = new Array(12);
		daysInMonth[1]  = 31;
		var isLeapYear = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		isLeapYear ? daysInMonth[2] = 29 : daysInMonth[2] = 28;
		daysInMonth[3]  = 31;
		daysInMonth[4]  = 30;
		daysInMonth[5]  = 31;
		daysInMonth[6]  = 30;
		daysInMonth[7]  = 31;
		daysInMonth[8]  = 31;
		daysInMonth[9]  = 30;
		daysInMonth[10] = 31;
		daysInMonth[11] = 30;
		daysInMonth[12] = 31;

		//Converting to int so mac IE doesn't get upset with us
		var dayInt = parseInt(day,10);
		var monthInt = parseInt(month,10);
		var yearInt = parseInt(year);

		if (monthInt > 12 || monthInt == 0) {
			checkError(fieldObj, fieldName + ' has an invalid entry for month.\n');
			return false;
		}

		//Make sure they don't have bad day
		else if (dayInt > daysInMonth[monthInt] || dayInt == 0) {
			checkError(fieldObj, fieldName + ' has an invalid entry for day.\n');
			return false;
		}

		else {
			//return true;
			return new Date(yearInt, (monthInt - 1), dayInt);
		}
	}

	//if value entered doesn't match the regex
	else {
		checkError(fieldObj, fieldName + ' must be a date in mm/dd/yyyy format.\n');
		return false;
	}

}// end of functionCheckDate


function checkDecimal(fieldObj,fieldName)
{
	var reDecimal = /^[-]?[0-9]*([,][0-9]{3})*[.]*[0-9]{0,2}$/
	var arrDecimal = fieldObj.value.match(reDecimal);

	if (arrDecimal || fieldObj.value.length == 0)
	{
		return true;
	}
	else
	{
		checkError(fieldObj, fieldName + ' must be a number (e.g. 7.50).\n');
		return false;
	}

}//End of Check Decimal


function checkCompareDates(objDate1, objDate2, strDate1, strDate2)
//Checks that two dates are not the same and the first date preceeds the second
{
	if (checkDate(objDate1, strDate1) && checkDate(objDate2, strDate2))
	{
		if (objDate1.value != "" && objDate2.value != "")
		{
			var d1 = checkDate(objDate1, strDate1);
			var d2 = checkDate(objDate2, strDate2);
//			alert(d1);
//			alert(d2);
			if (d1 >= d2) {
				checkError(objDate2, strDate2 + ' must be after ' + strDate1 + '.\n');
				return false;
			}
			else {
				return true;
			}
		}
		else {
			return true;
		}
	}
	else {
		return true;
	}
}//End of function checkCompareDates()

function checkEmail(fieldObj, fieldName) {
// Last modified: 8/21/2007 9:21AM

	var str = fieldObj.value;
	if (str == "") {
		return true;
	}
	else {
		var filter = /^.+@.+\..{2,3}$/;
		if (!filter.test(str)) {
			checkError(fieldObj, fieldName + ' is not a properly formatted email address.\n');
			return false;
		}
		else {
			return true;
		}
	}
} // checkEmail()

function checkValue(fieldObj, fieldName, checkValue) {
	if (fieldObj.value != checkValue) {
		checkError(fieldObj, fieldObj.value + ' is not a valid ' + fieldName + '.\n');
		return false;
	}
	else {
		return true;
	}
} // checkValue

function checkDiffer(fieldObj1, fieldName1, fieldObj2, fieldName2) {
	if (fieldObj1.value == fieldObj2.value) {
		checkError(fieldObj1, fieldName1 + ' and ' + fieldName2 + ' must be different.\n');
		return false;
	}
	else {
		return true;
	}
}// End of checkDiffer

function checkMatch(fieldObj1, fieldName1, fieldObj2, fieldName2) {
	if (fieldObj1.value != fieldObj2.value) {
		checkError(fieldObj1, fieldName1 + ' and ' + fieldName2 + ' do not match.\n');
		return false;
	}
	else {
		return true;
	}
}// End of checkMatch

function checkFile(fieldObj, fieldName, extension)
{
	var reFile = new RegExp () // empty constructor
	reFile.compile(extension + '$', 'i');
	var arrFile = fieldObj.value.match(reFile);
	if (arrFile || fieldObj.value.length == 0)
	{
		return true;
	}
	else
	{
		checkError(fieldObj, fieldName + ' is not a ' + extension.toUpperCase() + ' file.\n');
		return false;
	}
}

function checkInteger(fieldObj,fieldName)
{
	var reInteger = /^[-]?[0-9]*([,][0-9]{3})*$/
	var arrInteger = fieldObj.value.match(reInteger);

	if (arrInteger || fieldObj.value.length == 0)
	{
		return true;
	}
	else
	{
		checkError(fieldObj, fieldName + ' should be a number with no decimal places. (e.g. 500)\n');
		return false;
	}

}//End of checkInteger()

function checkLength(fieldObj, fieldName, minlength, maxlength) {
//checks that length of response is within bounds, bounds = 0 are ignored

	var charlabel = 'character';
	if (minlength > 1 || maxlength > 1) {
		charlabel = charlabel+'s';
	}

	//bypass if bounds are invalid
	if ((minlength <= 0 && maxlength <= 0) || (minlength > 0 && maxlength > 0 && minlength > maxlength) || (fieldObj.value == "")) {
		return true;
	}
	else if (minlength > 0 && maxlength > 0) {
		if (fieldObj.value.length >= minlength && fieldObj.value.length <= maxlength) {
			return true;
		}
		else {
			if (minlength == maxlength) {
				checkError(fieldObj, fieldName + ' must be ' + minlength + ' ' + charlabel + ' long. (Length: ' + fieldObj.value.length + ')\n');
			}
			else {
				checkError(fieldObj, fieldName + ' must be between ' + minlength + ' and ' + maxlength + ' characters long. (Length: ' + fieldObj.value.length + ')\n');
			}
			return false;
		}
	}
	else if (maxlength > 0) {
		if (fieldObj.value.length <= maxlength) {
			return true;
		}
		else {
			checkError(fieldObj, fieldName + ' must be no more than ' + maxlength + ' ' + charlabel + ' long. (Length: ' + fieldObj.value.length + ')\n');
			return false;
		}
	}
	else {
		if (fieldObj.value.length >= minlength) {
			return true;
		}
		else {
			checkError(fieldObj, fieldName + ' must be at least ' + minlength + ' ' + charlabel + ' long. (Length: ' + fieldObj.value.length + ')\n');
			return false;
		}
	}
}//End of checkLength

function checkMoney(fieldObj,fieldName)
{
	var reMoney = /^[$]?[-]?[0-9]*([,][0-9]{3})*[.]*[0-9]{0,2}$/
	var arrMoney = fieldObj.value.match(reMoney);

	if (arrMoney || fieldObj.value.length == 0)
	{
			return true;
	}

	else
	{
			checkError(fieldObj, fieldName + ' is not a properly formatted U.S. currency value.\n');
			return false;
	}
} //end of checkMoney


function checkRange(fldObj, fldName, fldMinValue, fldMaxValue, blnVerbose)
{
	if ((parseFloat(fldObj.value) >= parseFloat(fldMinValue) && parseFloat(fldObj.value) <= parseFloat(fldMaxValue)) || (fldObj.value == ""))
	{
		return true;
	}
	else
	{
		if (blnVerbose)
		{
			checkError(fldObj, fldName + ' must be between ' + fldMinValue + ' and ' + fldMaxValue + '.\n');
			return false;
		}
		else
		{
			checkError(fldObj, fldName + ' does not appear to be a valid entry.\n');
			return false;
		}
	}
} //end of checkRange

function checkNotLower(fieldObj, fieldName, fieldOriginalValue)
{
	if ((parseFloat(fieldObj.value) >= parseFloat(fieldOriginalValue)) || (fieldObj.value == ""))
	{
		return true;
	}
	else
	{
		checkError(fieldObj, fieldName + ' cannot be less than ' + fieldOriginalValue + '.\n');
		return false;
	}
} //end of checkNotLower

function checkNotHigher(fieldObj, fieldName, fieldOriginalValue)
{
	if ((parseFloat(fieldObj.value) <= parseFloat(fieldOriginalValue)) || (fieldObj.value == ""))
	{
		return true;
	}
	else
	{
		checkError(fieldObj, fieldName + ' cannot be higher than ' + fieldOriginalValue + '.\n');
		return false;
	}
} //end of checkNotHigher


function checkPhone(fieldObj, fieldName, countryID)
{
	if (countryID == 840)
	{
		var rePhone = /^[(]?[2-9]\d\d[)-\/]?\s?[2-9]\d\d-?\d\d\d\d$/
		var arrPhone = fieldObj.value.match(rePhone);

		if (arrPhone || fieldObj.value.length == 0)
		{
			return true;
		}
		else
		{
			checkError(fieldObj, fieldName + ' is not a properly formatted 10-digit phone number.\n');
			return false;
		}
	}
	else
	{

		return true;
	}
}

function checkPostalCode(fieldObj, fieldName, countryID)
{
	if (countryID == 840)
	{
		var reZip = /^\d{5}$/
		var reZipplus4 = /^\d{5}-\d{4}$/
		var arrZip = fieldObj.value.match(reZip);
		var arrZipplus4 = fieldObj.value.match(reZipplus4);

		if (arrZip || arrZipplus4 || fieldObj.value.length == 0)
		{
			return true;
		}
		else
		{
			checkError(fieldObj, fieldName + ' is not a properly formatted U.S. postal code.\n');
			return false;
		}
	}
	else
	{
		return true;
	}
}

function checkRequired(fieldObj, fieldName)
{
	var fieldType

	fieldType = fieldObj.type ? fieldObj.type : fieldObj[0].type;

	switch (fieldType)
	{
	case "text":
		if (fieldObj.value.length > 0)
		{
			return true;
		}
		else
		{
			checkError(fieldObj, fieldName + ' is required.\n');
			return false;
		}
		break;
	case "textarea":
		if (fieldObj.value.length > 0)
		{
			return true;
		}
		else
		{
			checkError(fieldObj, fieldName + ' is required.\n');
			return false;
		}
		break;
	case "password":
		if (fieldObj.value.length > 0)
		{
			return true;
		}
		else
		{
			checkError(fieldObj, fieldName + ' is required.\n');
			return false;
		}
		break;
	case "hidden":
		if (fieldObj.value.length > 0)
		{
			return true;
		}
		else
		{
			checkError(fieldObj, fieldName + ' is required.\n');
			return false;
		}
		break;
	case "file":
		if (fieldObj.value.length > 0)
		{
			return true;
		}
		else
		{
			checkError(fieldObj, fieldName + ' is required.\n');
			return false;
		}
		break;

	case "select-one":
		if (fieldObj.selectedIndex > -1 && fieldObj[fieldObj.selectedIndex].value != "")
		{
			return true;
		}
		else
		{
			checkError(fieldObj, fieldName + ' is required.\n');
			return false;
		}
		break;

	case "select-multiple":

		var isSelected = false;

		for (var i=0 ; i < fieldObj.length; i++) {
			if (fieldObj.options[i].selected)
			{
				isSelected = true;
				break;
			}
		}

		if (isSelected)
		{
			return true;
		}
		else
		{
			checkError(fieldObj, fieldName + ' is required.\n');
			return false;
		}
		break;

	 case "checkbox":

	 	var isChecked = false;

		//check multiple check boxes with same name
		if (fieldObj[0])
		{
			for (var i=0; i < fieldObj.length; i++)
			{
				if (fieldObj[i].checked)
				{
					isChecked = true;
					break;
				}
			}
		}
		// check a single check box
		else
		{
			if (fieldObj.checked)
			{
				isChecked = true;
			}
		}

		if (isChecked)
		{
			return true;
		}
		else
		{
			checkError(fieldObj, 'Please select an option for ' + fieldName + '.\n');
			return false;
		}
		break;

	 case "radio":

		var isChecked = false;

		for (var i=0 ; i < fieldObj.length; i++) {
			if (fieldObj[i].checked)
			{
				isChecked = true;
				break;
			}
		}

		if (isChecked)
		{
			return true;
		}
		else
		{
			checkError(fieldObj, fieldName + ' is required.\n');
			return false;
		}
		break;

	}//end of switch


}//end of function checkRequired

function checkSSN(fieldObj, fieldName)
{
	var reSSN = /^\d{3}-\d{2}-\d{4}$/
	var arrSSN = fieldObj.value.match(reSSN);

	if (arrSSN || fieldObj.value.length == 0)
	{
		return true;
	}
	else
	{
		checkError(fieldObj, fieldName + ' is not a properly formatted social security number.\n');
		return false;
	}
}

function checkStateOrProvince(stateObj, country)
{
	if (parseInt(country) == 840 || parseInt(country) == 124 || country == "US" || country == "CA") {
		return checkRequired(stateObj,"State/Province");
	}
	else {
	return true;
	}
} // End of checkStateOrProvince

function checkURL(fieldObj,fieldName)
{

	 /*
	   Date: 9-14-01 4:33pm
	   Author: Sam Chehab

	   Search through string and ensure a proper url has been given.
	   If it doesn't already have "http://" or "https://" return and error
	 */

	var reURL = /^https?:\/\/[a-zA-Z0-9\-]+[.][a-zA-Z]/
	var arrURL = fieldObj.value.match(reURL);

	if (arrURL || fieldObj.value.length == 0)
	{
		return true;
	}
	else{
 		checkError(fieldObj, fieldName + ' is not a properly formatted URL. (Ex: http://www.yourwebsite.com)\n');
		return false;
	}

} // end of checkUrlFunction

function checkCreditCard (fldCardType, fldCardNumber) {

	//alert('Debug: cc validation is being run');
	var cardtype = '';
	for (var i=0; i<fldCardType.length; i++) {
		//alert('Debug: checking ' + fldCardType[i].value + ': ' + fldCardType[i].checked);
		if (fldCardType[i].checked)
		{
			cardtype = fldCardType[i].value;
		}
	}
	var cardnumber = fldCardNumber.value;
	//alert('Debug: Card Type ' + cardtype);
	//alert('Debug: Card Number ' + cardnumber);

	if (cardtype != "" && cardnumber != "")
	{

	  // Array to hold the permitted card properties
	  var cards = new Array();
	  cards [0] = {name: "AX", length: "15", prefixes: "34,37", checkdigit: true};
	  cards [1] = {name: "VS", length: "13,16", prefixes: "4", checkdigit: true};
	  cards [2] = {name: "MC", length: "16", prefixes: "51,52,53,54,55", checkdigit: true};
	  cards [3] = {name: "DC", length: "16", prefixes: "6011", checkdigit: true};
	  //cards [4] = {name: "CarteBlanche", length: "14", prefixes: "300,301,302,303,304,305,36,38", checkdigit: true};
	  //cards [5] = {name: "DinersClub", length: "14,", prefixes: "300,301,302,303,304,305,36,38", checkdigit: true};
	  //cards [6] = {name: "JCB", length: "15,16", prefixes: "3,1800,2131", checkdigit: true};
	  //cards [7] = {name: "Enroute", length: "15", prefixes: "2014,2149", checkdigit: true};

	  // Establish card type
		var thisCard = -1;
		for (var i=0; i<cards.length; i++) {
		  if (cardtype.toLowerCase () == cards[i].name.toLowerCase()) {
			 thisCard = i;
			 break;
		  }
		}
		if (thisCard == -1) {
			checkError(fldCardType, 'The selected Credit Card Type is not recognized.\n');
			return false;
		}

	  // Check format
	  var cardNo = cardnumber
	  var cardexp = /^([0-9]{4})\s?([0-9]{4})\s?([0-9]{4})\s?([0-9]{1,4})$/;
	  if (!cardexp.exec(cardNo)) {
			checkError(fldCardType, 'Credit Card Number is not valid. Please check that the card type and number are correct.\n');
			return false;
	  }

	  // Now remove any spaces from the credit card number
	  cardexp.exec(cardNo);
	  cardNo = RegExp.$1 + RegExp.$2 + RegExp.$3 + RegExp.$4;

	  // Now check the modulus 10 check digit - if required
	  if (cards[thisCard].checkdigit) {
	    var checksum = 0;												    // running checksum total
	    var mychar = "";														// next char to process
	    var j = 1;																 // takes value of 1 or 2

	    // Process each digit one by one starting at the right
	    var calc;
	    for (i = cardNo.length - 1; i >= 0; i--) {

			 // Extract the next digit and multiply by 1 or 2 on alternative digits.
			 calc = Number(cardNo.charAt(i)) * j;

			 // If the result is in two digits add 1 to the checksum total
			 if (calc > 9) {
			   checksum = checksum + 1;
			   calc = calc - 10;
			 }

			 // Add the units element to the checksum total
			 checksum = checksum + calc;

			 // Switch the value of j
			 if (j ==1) {j = 2} else {j = 1};
	    }

	    // All done - if checksum is divisible by 10, it is a valid modulus 10.
	    // If not, report an error.
	    if (checksum % 10 != 0)  {
			checkError(fldCardType, 'Credit Card Number is not valid. Please check that the card type and number are correct.\n');
			return false;
	    }
	  }

	  // The following are the card-specific checks we undertake.
	  var LengthValid = false;
	  var PrefixValid = false;
	  var undefined;

	  // We use these for holding the valid lengths and prefixes of a card type
	  var prefix = new Array ();
	  var lengths = new Array ();

	  // Load an array with the valid prefixes for this card
	  prefix = cards[thisCard].prefixes.split(",");

	  // Now see if any of them match what we have in the card number
	  for (i=0; i<prefix.length; i++) {
	    var exp = new RegExp ("^" + prefix[i]);
	    if (exp.test (cardNo)) PrefixValid = true;
	  }

	  // If it isn't a valid prefix there's no point at looking at the length
	  if (!PrefixValid) {
			checkError(fldCardType, 'Credit Card Number is not valid. Please check that the card type and number are correct.\n');
			return false;
	  }

	  // See if the length is valid for this card
	  lengths = cards[thisCard].length.split(",");
	  for (j=0; j<lengths.length; j++) {
	    if (cardNo.length == lengths[j]) LengthValid = true;
	  }

	  // See if all is OK by seeing if the length was valid. We only check the
	  // length if all else was OK.
	  if (!LengthValid) {
			checkError(fldCardType, 'Credit Card Number is not the correct length.\n');
			return false;
	  };

	  // The credit card is in the required format.
	  return true;
	}
}// End of checkCreditCard
