/** valCustomForm(f)
 * Field validation based on form elements in the 'valflds' array, which is set on the page containing the 
 * form (so that it can easily change from form to form. Format: "fldname(0) | Display Name(1) | maxlength(2) (opt)"
 * f = obj; form object being validated
 * Returns boolean true or false 
 **/
function valCustomForm(f) {
	//first, disable the submit button to keep user from submitting twice
	//f.elements['submit'].disabled = true;
	
	//execute validation routines on all fields in array
	for (i=0; i<valflds.length; i++) {
		/** Separate piped values **/
		fld = valflds[i].split("|");
		fldname		= fld[0];
		fldLabel	= fld[1];
		fldMaxLen	= fld[2];
		
		//alert(fldname);
		
		if (f.elements[fldname].type=='IMAGE') { continue; };
	
		//determine the element type
		if (!f.elements[fldname][0]) {
			//anything but radios and checkboxes
			elType = f.elements[fldname].type;
		} else {
			//radio and checkbox sets
			elType = f.elements[fldname][0].type;
		}
		//alert(elType);
		
		/** check element to ensure a value has been entered **/
		hasValue = false;
		//any element other than radio or checkbox
		if (elType!=='radio' && elType!=='checkbox') {
			if (f.elements[fldname].value!=='') {
				hasValue = true;
			}
		}
		//radio and checkbox groups
		if (elType=='radio') {
			if (!f.elements[fldname].length) {
				if (f.elements[fldname].checked) {
					hasValue = true;
					break;
				}
			} else {
				for (ii=0; ii < f.elements[fldname].length; ii++) {
					if (f.elements[fldname][ii].checked==true) {
						hasValue = true;
						break;
					}
				}
			}
		}
		
		//checkbox
		if (elType=='checkbox') {
			hasValue = (f.elements[fldname].checked) ? true : false;
		}
			
		/** CHECK FOR EMPTY REQUIRED FIELDS **/
		if (!hasValue) {
			//Reenable Submit button
			//f.elements['submit'].disabled = false;
			
			//Show Alert Message
			if (fldname=='agreetoterms') {
				//custom field alerts
				alert("You may not continue until you agree to the Terms and Conditions.");
			} else {
				//general field alert
				alert("A value is required for \'" + fldLabel + "\'.");
			}
			//Place focus on empty element; if an array or group for the 
			//element, put focus on the first element in the group.
			if (elType!=='hidden') { 
				if (!f.elements[fldname][0]) {
					f.elements[fldname].focus();
				} else {
					f.elements[fldname][0].focus();
				}
			}
			return false;
		}
		
		/** CUSTOM FIELD DATA CHECKS **/
		//validate Contact E-mail Address fields
		if (fldname.indexOf('email') > -1) {
			if (!isEmail(f.elements[fldname].value)) {
				alert("The e-mail address you entered in \'" + fldLabel + "\' appears to be invalid. Please check your entry.");
				f.elements[fldname].focus();
				//f.elements['submit'].disabled = false;
				return false;
			}
		}
		
		//validate CC Number fields
		if (fldname.indexOf('ccnum') > -1) {
			if (!ccValid(f.elements[fldname])) {
				alert ("The credit card number you entered appears to be invalid. Please check your entry and try again.");
				f.elements[fldname].focus();
				//f.elements['submit'].disabled = false;
				return false;
			}
		}
		
		/** FIELD LENGTH CHECKS **/
		if (fldMaxLen.length>0) {
			if (f.elements[fldname]) {
				fldMaxLen = parseInt(fldMaxLen);
				fldOver = f.elements[fldname].value.length - fldMaxLen;
				if ( fldOver > 0 ) {
					alert(fldLabel + " must not exceed " + fldMaxLen + " characters. Please shorten it by " + fldOver + " characters.");
					f.elements[fldname].focus();
					//f.elements['submit'].disabled = false;
					return false;
				}
			}
		}
	} //flds loop
	return true;
}

/** isEmail()
Validates e-mail addresses
val = string; e-mail address
returns true or false */
function isEmail(val) {
	if (val.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) {
		return true;
	}
	return false;
}

/** 
 * MONEY VALIDATION
 **/
function moneyFormat(textObj) {
   var newValue = textObj.value;
   var decAmount = "";
   var dolAmount = "";
   var decFlag = false;
   var aChar = "";
   
   // ignore all but digits and decimal points.
   for(i=0; i < newValue.length; i++) {
      aChar = newValue.substring(i,i+1);
      if(aChar >= "0" && aChar <= "9") {
         if(decFlag) {
            decAmount = "" + decAmount + aChar;
         }
         else {
            dolAmount = "" + dolAmount + aChar;
         }
      }
      if(aChar == ".") {
         if(decFlag) {
            dolAmount = "";
            break;
         }
         decFlag=true;
      }
   }
   
   // Ensure that at least a zero appears for the dollar amount.
   if(dolAmount == "") {
      dolAmount = "0";
   }
   // Strip leading zeros.
   if(dolAmount.length > 1) {
      while(dolAmount.length > 1 && dolAmount.substring(0,1) == "0") {
         dolAmount = dolAmount.substring(1,dolAmount.length);
      }
   }
   
   // Round the decimal amount.
   if(decAmount.length > 2) {
      if(decAmount.substring(2,3) > "4") {
         decAmount = parseInt(decAmount.substring(0,2)) + 1;
         if(decAmount < 10) {
            decAmount = "0" + decAmount;
         }
         else {
            decAmount = "" + decAmount;
         }
      }
      else {
         decAmount = decAmount.substring(0,2);
      }
      if (decAmount == 100) {
         decAmount = "00";
         dolAmount = parseInt(dolAmount) + 1;
      }
   }
   
   // Pad right side of decAmount
   if(decAmount.length == 1) {
      decAmount = decAmount + "0";
   }
   if(decAmount.length == 0) {
      decAmount = decAmount + "00";
   }
   
   // Check for negative values and reset textObj
   if(newValue.substring(0,1) != '-' ||
         (dolAmount == "0" && decAmount == "00")) {
      textObj.value = dolAmount + "." + decAmount;

   }
   else{
      textObj.value = '-' + dolAmount + "." + decAmount;
   }
}


/**
 * DATE VALIDATION FUNCTIONS
 * The functions below all work together to validate a date string (mm/dd/yyyy)
 */
function checkdate(control) {
	var dateStr = control.value;
	
	if (dateStr.length > 0) {
		/* Checks for the following valid date formats:
		   MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
		   Also separates date into month, day, and year variables*/
		//var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
	
		/* To require a 4 digit year entry, use this line instead: */
		// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
		
		/* to allow a date plus a time, use this. Year must be YYYY. */
		var datePat = /(?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))([-.\/])(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$/;
		
		/* check for matches to the date pattern */
		var matchArray = dateStr.match(datePat); // is the format ok?
		
		if (matchArray == null) {
			alert("Date is not in a valid format.");
			control.focus();
			return false;
		} else {
			month	= matchArray[1]; // parse date into variables
			day		= matchArray[3];
			year	= matchArray[4];
			if (month < 1 || month > 12) { // check month range
				alert("Month must be between 1 and 12.");
				control.focus();
				return false;
			}
			if (day < 1 || day > 31) { //check day range
				alert("Day must be between 1 and 31.");
				control.focus();
				return false;
			}
			if ((month==4 || month==6 || month==9 || month==11) && day==31) { //check number of days
				alert("Month "+month+" doesn't have 31 days!");
				control.focus();
				return false;
			}
			if (month == 2) { // check for february 29th
				var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
				if (day>29 || (day==29 && !isleap)) {
					alert("February " + year + " doesn't have " + day + " days!");
					control.focus();
					return false;
				}
			}
		}
	}
	
	// all checks passed -- date is valid
	return true;  
}

/** valPasswordFormat()
 * Checks to see that all password fields have a value, and that the new password fields match. All 
 * other checks are performed during form processing via the valPassword() vbscript function. Requires 
 * specifically named objects to be present in the form to operate correctly.
 * no parameters
 * returns boolean
 **/
function valPasswordFormat() {
	var f = document.updatePassword;
	var oOldPass = f.elements['oldpass'];
	var oNewPass = f.elements['newpass'];
	var oNewConfirm = f.elements['newpass_confirm'];
	//if (oOldPass.value!=='' || oNewPass.value!=='' || oNewConfirm.value!=='') {
		//check for existance of values
		if (oOldPass.value=='') { 
			alert('If you would like to update your password, the "Old Password" field needs a value.');
			oOldPass.focus();
			return false;
		}
		if (oNewPass.value=='') { 
			alert('If you would like to update your password, the "New Password" field needs a value.');
			oNewPass.focus();
			return false;
		}
		if (oNewConfirm.value=='') { 
			alert('If you would like to update your password, the "Confirm New Password" field needs a value.');
			oNewConfirm.focus();
			return false;
		}
		
		//compare new pass fields
		if (oNewPass.value!==oNewConfirm.value) {
			alert('The value you entered in the "New Password" and "Confirm New Password" fields do not match. Please check your entry and try again.');
			oNewPass.focus();
			return false;
		}
	//}
	return true;
}

/** ccValid(val)
 * Validates format of CC number
 * obj = obj; form field object
 * returns boolean
 **/
function ccValid(control) {
	var f			= control.form;
	var cardNumber	= control.value;
	var cardType	= '';
	var isValid		= false;
	
	if (cardNumber == "") { return false; }
	if (cardNumber == "4222222222222222" || cardNumber == "4111111111111111") { 
		cardType = 'TEST';
		isValid = true;
	}
  
	var cardNumbersOnly = cardNumber.replace(/ /g,"");
	cardNumbersOnly = cardNumbersOnly.replace(/-/g,"");
	var cardNumberLength = cardNumbersOnly.length;
	var prefixRegExp, prefixIsValid;
	
	//Use the prefix to determine card type, then check the length. Update isValid during testing -- 
	//card must pass one of these 4 tests to be a valid cardnumber.
	prefixRegExp = /^5[1-5]/;
	prefixIsValid = prefixRegExp.test(cardNumbersOnly);
	if (prefixIsValid && cardNumberLength == 16) {
		cardType = 'MC';
		isValid = true;
	}
	
	prefixRegExp = /^4/;
	prefixIsValid = prefixRegExp.test(cardNumbersOnly);
	if (prefixIsValid && (cardNumberLength == 16 || cardNumberLength == 13)) {
		cardType = 'VISA';
		isValid = true;
	}
	
	prefixRegExp = /^6011/;
	prefixIsValid = prefixRegExp.test(cardNumbersOnly);
	if (prefixIsValid && (cardNumberLength == 16 || cardNumberLength == 13)) {
		cardType = 'DISC';
		isValid = true;
	}
	
	prefixRegExp = /^3(4|7)/;
	prefixIsValid = prefixRegExp.test(cardNumbersOnly);
	if (prefixIsValid && (cardNumberLength == 15)) {
		cardType = 'AMEX';
		isValid = true;
	}
	
	//If the object exists, update the cctype object's value:
	if (f.cctype && cardType!=='') { f.cctype.value = cardType; }
	
	//Validate the card number
	if (isValid) {
		var numberProduct;
		var numberProductDigitIndex;
		var checkSumTotal = 0;

		for (digitCounter = cardNumberLength - 1; digitCounter >= 0; digitCounter--) {
			checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
			digitCounter--;
			numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
			for (var productDigitCounter = 0; productDigitCounter < numberProduct.length; productDigitCounter++) {
				checkSumTotal += 
				parseInt(numberProduct.charAt(productDigitCounter));
			}
		}
		isValid = (checkSumTotal % 10 == 0);
	}
  
	if (!isValid) { return false; }
	return true;
}

/** forceJavascript()
 * replaces the DIV container's default text with the submissions buttons *ONLY* if the user 
 * has javascript enabled. Runs on window load, and requires specifically named objects 
 * to be present on the page.
 * no parameters
 * returns nothing
 **/
function forceJavascript() {
	arrdiv = new Array();
	arrdiv[0] = document.getElementById("jsalert");
	arrdiv[1] = document.getElementById("jsalert2");
	buttons	  = document.getElementById("formsubmitcontrols");
	
	//hide alert div if js is enabled
	for (i=0; i<arrdiv.length; i++) {
		arrdiv[i].style.visibility = 'hidden';
		arrdiv[i].style.display = 'none';
	}
	
	//write profile elements
	if (buttons) {
		buttons.style.visibility = 'visible';
		buttons.style.display = 'block';
	}
}