/*************************************************************
   The validate() function validates a single fields.  It looks
   for one or all of the following attributes in the element:
	dtype, isReq, label, reg
	dtype="alpha" isReq="true" label="Last Name" reg="d[6]"
	
	**dtype: one of three custom-defined datatypes: 
		alpha, num, and date.
		alpha: any alphanumeric, but cannot be all numbers
		num: all numbers
		date: 11/11/2005 or 1/1/05

	**isReq: indicates if the field is required. true, false
		If the attribute doesn't exist in the tag, 
		then it's considered false

	**label: a friendly name of the control that will be displayed 
		in an alertbox when there's a problem.
		E.G: label="Username"  would appear as "Username cannot 
		be left blank." if the user left the field blank

	**reg: a regular expression pattern for further validation of entries.

To validate every field in a form, call the goValidate() function.

*/

// JScript source code
function validateMe(elem) {
  var reg, label, dtype, required, blnValid, err, canSelect, isSelect
  blnValid = true
	
  //Get the attribute values (attributes support in IE 5.0+ (Win/Mac) & Gecko)
  //reg = any regular expression validation
  reg = (elem.attributes["valid"])?elem.attributes["valid"].nodeValue:null
  
  //label = the friendly display name of the field
  label = (elem.attributes["label"])?elem.attributes["label"].nodeValue:null
  
  //dtype = the broad data type for general validation (alpha vs. numeric, etc)
  dtype = (elem.attributes["dtype"])?elem.attributes["dtype"].nodeValue:null
  
  //required = is the field required?
  required = false
  if (elem.attributes["isReq"]) {
	required = (elem.attributes["isReq"].nodeValue == "true")?true:false
  }
  //sample = what the data in the field should look like (date format, money format, etc.)
  sample = (elem.attributes["sample"])?elem.attributes["sample"].nodeValue:null
	
  
  isSelect = (elem.tagName.toLowerCase() == "select")?true:false
  
  if (!isSelect) {
  	value = elem.value
  } else {
	value = elem.options[elem.selectedIndex].value
  }
  
  //Only validate enabled fields
  if(!elem.disabled) {
	//Check for empty required fields
	if(required) {
	  if(isSelect) {
		if(value == "" && elem.disabled==false) {
			blnValid = false
			err = "Please select a "
		}
	  } else if(value=="" && elem.disabled==false) {
			blnValid = false
			err = " cannot be left blank."
	  }
	} 
	//Check against data type conformity
	if (blnValid) {
	if (dtype) {
     switch (dtype) {
       case "alpha":
         blnValid = isNaN(value) || (value=="")
         err = " cannot contain all numbers."
         break
       case "num":
          blnValid = !isNaN(value)
		  err = " must contain numbers only."
          break
       case "ccnum":
		  //ccnum fields should have assoc. cctype field to indicate cctype
		  var cctype = document.personalInfo.x_card_type.value
		  blnValid = CheckCC(value,cctype)
		  err = " contains an invalid CC number."
		  break
        case "date":
				  var valReg = new RegExp("^[01]\\d\\W[0123]\\d\\W\\d{4}$")
        	blnValid = valReg.test(value)
					err = " must be a date in the format: " + sample
					break
				case "email":
					var valReg = new RegExp ("^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$")
      		blnValid = valReg.test(value)
      		err = " must be in the format: " + sample
      }
   } else if(reg) {
      var valReg = new RegExp(reg)
        blnValid = valReg.test(value)
		err = " contains incorrect entry. \nEnter values like so: " + sample
   }
   }
   if (!blnValid) {
      if (isSelect) {
		alert(err + label + ".")
		elem.focus()
	  } else {
		alert(label + err +"\nPlease make the appropriate changes.")
		elem.select()
      }
   }
   }
	 return blnValid
}

function goValidate(button) {
var elem, att, tag, dtype, isValid
var f = button.form

for (var i=0;i < f.elements.length; i++) {
		elem = f.elements[i]
		isValid = validateMe(elem)
		if (!isValid) { break; }
}
return isValid
}

function enablePKSelect(elemName, enable) {
	var elem = document.getElementById(elemName)
	elem.disabled = !enable
}

function updateChildSelect(selElem, childElemName) {
var childElem = document.getElementById(childElemName)
var ids = selElem.value.split(":")
for (var x=0;x < childElem.length; x++) {
	var val = childElem[x].value
	childElem[x].selected = false
	for (var i=1;i < ids.length;i++) {
		if (ids[i] == val) {
			childElem[x].selected = true
			break;
		}
	}
}
}

function CheckCC(CC_NUMBER,formCC_TYPE)
// #####################################
	{

// CCN_digits is where we store just the digits from the Card Number
	var CCN_digits = ""

// ------------------------------------------------------------------------------------------------------
// remove everything but the digits from the entered Card Number
// ------------------------------------------------------------------------------------------------------
	for (var i = 0; i < CC_NUMBER.length; i++)
		{
			if ((!isNaN(CC_NUMBER.charAt(i))) && (CC_NUMBER.charAt(i) != " "))
			{
				CCN_digits = CCN_digits + CC_NUMBER.charAt(i);
			}
		}
		
		//document.acctForm.ccNumber.value = CCN_digits;

// *** debug -----------------------------------------------------------------------
// alert ("CCN_digits.length = " + CCN_digits.length + " CCN_digits = " + CCN_digits);
// *** debug -----------------------------------------------------------------------

// ------------------------------------------------------------------------------------------------------
// validcard is the true/false indicator for a valid card - it is returned to the caller
// ------------------------------------------------------------------------------------------------------
	var validcard = false;

// ------------------------------------------------------------------------------------------------------
// msgind is used to communicate the type of alert to post in case of a problem
//	1=invalid prefix (prefix does not match card type)
//	2=invalid number of digits in card number for the card type selected
// ------------------------------------------------------------------------------------------------------
	var msgind = 0;

// ------------------------------------------------------------------------------------------------------
// Check the card for having a valid prefix and number of digits (length) for the card type.
// Note - the if, else if construct was used here because switch/case is not supported by JavaScript 1.0
// ------------------------------------------------------------------------------------------------------
//							AMEX(a)		DISCOVER(d)		MASTERCARD(m)	VISA(v)
// ------------------------------------------------------------------------------------------------------
//		VALID LENGTHS		 15				  16			16			13/16
// ------------------------------------------------------------------------------------------------------
//		VALID PREFIXES	 34				6011			51			  4
//							 37								52
//							 								53
//							 								54
//							 								55
// ------------------------------------------------------------------------------------------------------
	var cctype_name
			
	if (formCC_TYPE == "a") {
		cctype_name = "American Express"
		if (CCN_digits.length == 15) {
			if ((CCN_digits.substring (0, 2) == "34") || (CCN_digits.substring (0, 2) == "37")) {
				validcard = true;
			}
			else {
				msgind = 1;
			}
		}
		else {	
			msgind = 2;
		}
	}
	else if (formCC_TYPE == "d") {
		cctype_name = "Discover"
		if (CCN_digits.length == 16) {
			if (CCN_digits.substring (0, 4) == "6011") {
				validcard = true;
			}
			else {
				msgind = 1;
			}
		}
		else {	
			msgind = 2;
		}
	}
	else if (formCC_TYPE == "m") {
		cctype_name = "Mastercard"
		if (CCN_digits.length == 16) {
			if ((CCN_digits.substring (0, 2) >= "51") && (CCN_digits.substring (0, 2) <= "55")) {
				validcard = true;
			}
			else {
				msgind = 1;
			}
		}
		else {	
			msgind = 2;
		}
	}
	else if (formCC_TYPE == "v") {
		cctype_name = "Visa"
		if ((CCN_digits.length == 16)  || (CCN_digits.length ==13)) {
			if (CCN_digits.substring (0, 1) == "4") {
				validcard = true;
			}
			else {
				msgind = 1;
			}
		}
		else {
			msgind = 2;
		}
	}
	else {
// ------------------------------------------------------------------------------------------------------
// this should be impossible to reach as long as all valid card types are in the list above....
// ------------------------------------------------------------------------------------------------------
		alert ("Sorry, "+ cctype_name + " is not currently being accepted - please contact us by phone or email.");

	}
	if (!validcard)
		{
		if (msgind == 1)
// ------------------------------------------------------------------------------------------------------
//			Invalid prefix
// ------------------------------------------------------------------------------------------------------
			alert ("The Card Number ("+CC_NUMBER + ") and the Card Type (" + cctype_name + ") do not match.");

		else if (msgind == 2)
// ------------------------------------------------------------------------------------------------------
//			Invalid number of digits (length)
// ------------------------------------------------------------------------------------------------------
			alert ("The Card Number ("+CC_NUMBER + ") is not the right length for the Card Type (" + cctype_name + ").");
		}

	if (!validcard)
		return (validcard);

var DebugOn = false;
var CheckSum = 0;
// for loop
	for (var x = 1; x <= CCN_digits.length; x++)
		{
// BUG-FIX 1999.12.21
//		var CurrentDigit = CCN_digits.charAt(CC_NUMBER.length - x); CHANGED TO:
		var CurrentDigit = CCN_digits.charAt(CCN_digits.length - x);
// BUG-FIX THANKS TO Curt Cloninger
// x is subtracted from the length of the CCN to point at the digits from RIGHT to LEFT
		if (x % 2 == 0)
			{
// even position in credit card number (2nd, 4th, etc. from RIGHT of Credit Card Number)
			var WorkDigit = CurrentDigit * 2;	
			if (WorkDigit > 9)
				{ 
				CheckSum = CheckSum + (1 - 0);
				CheckSum = CheckSum + (WorkDigit % 10 - 0);
				if (DebugOn)
					{
					alert ("CurrentDigit = " + CurrentDigit + " even position - WorkDigit=" + WorkDigit + " > 9 - Checksum = Checksum + WorkDigit mod10 + 1 = " + CheckSum);
					}
				}
			else
				{
				CheckSum = CheckSum + (WorkDigit - 0);
				if (DebugOn)
					{
					alert ("CurrentDigit = " + CurrentDigit + " even position - WorkDigit = " + WorkDigit + " NOT > 9 - Checksum = Checksum + WorkDigit = " + CheckSum);
					}
				}	
			}
		else
			{
// odd position in credit card number (1st, 3rd, etc. from RIGHT of Credit Card Number)
			CheckSum = CheckSum + (CurrentDigit - 0);
			if (DebugOn)
				{
				alert ("CurrentDigit = " + CurrentDigit + " odd position " + "Checksum = Checksum + CurrentDigit = " + CheckSum);
				}
			}
		}
// end for loop

	if (CheckSum % 10) 
		{ 
		validcard = false; 
		alert ("We're sorry, the Card Number ("+ CC_NUMBER +") is not correct - perhaps there is a typo or two numbers are reversed?"); 
		} 
	
	return (validcard); 
	}

//-->