var emailexp = /^[a-z][a-z_0-9\-\.]+@[a-z_0-9\.\-]+\.[a-z]{2,3}$/i
var phoneexp = /^\d{10}$/
var zipcode  = /^\d{5}$/
var postalcd = /^\D{1}\d{1}\D{1}\s\d{1}\D{1}\d{1}$/;
var alphabetexp = /^[A-Z]&/;
var alphaspaceexp = /^[A-Z ]&/;

var one_day   =1000*60*60*24
var one_month =1000*60*60*24*30
var one_year  =1000*60*60*24*30*12

function ageCalculator (yr, mon, day, unit, decimal, round) {
   today=new Date();
   var pastdate=new Date(yr, mon - 1, day);
   var agex;
   var countunit = unit;
   var decimals  = decimal;
   var rounding  = round;

   finalunit = (countunit == "days")? one_day : (countunit=="months")? one_month : one_year;
   decimals  = (decimals <= 0) ? 1 : decimals * 10;

   if (unit != "years") {
      if (rounding == "rounddown")
         agex = Math.floor((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals + " " + countunit;
      else
         agex = Math.ceil((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals + " " + countunit;
         }
   else {
      yearspast = today.getFullYear() - yr - 1;
      tail = (today.getMonth() > mon-1 || today.getMonth() == mon-1 && today.getDate( )>= day)? 1 : 0;
      pastdate.setFullYear(today.getFullYear());
      pastdate2 = new Date(today.getFullYear()-1, mon-1, day);
      tail = (tail == 1)? tail + Math.floor((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals :
		  Math.floor((today.getTime()-pastdate2.getTime())/(finalunit)*decimals)/decimals;
	  agex = yearspast + tail + " " + countunit;
      }
   return agex;
   }

function CRLF () {
	return String.fromCharCode(10) + String.fromCharCode(13);
}

function TAB(howMany) {
	var tempStr
	for (count = 0; count < howMany; count++) {
		tempStr = tempStr & String.fromCharCode(9);
	}
}

function validateEmail(str) {	
	return emailexp.test(str)
}
function validate_A_2_Z(str) {	
	return alphabetexp.test(str)
}
function validate_A_2_Z_Space(str) {
	return alphaspaceexp.test(str)
}
function validatePhone(str) {
	return phoneexp.test(str)
}
	
function validatePostalCode(str) {
	return postalcd.test(str)
}

function validateZipCode(str) {
	return zipcode.test(str)
}

function StripChars(ItemsToStrip, str) {
	returnString = "";
	for (i = 0; i < str.length; i++) {  
		var c = str.charAt(i);
		if (ItemsToStrip.indexOf(c) == -1)
			returnString += c;
	}
	return returnString;
}

function CountChars(str) {
	returnInt = str.length;
	return returnInt;
}

function AllSpace(str) {   //Makes String Blank if noting but spaces
	for (i=0; i < str.length; i++) {
		if (str.charAt(i) != " ") {
			return str;
		}
	}
	return "";
}

function SetDec(str, places) { //chops decimal places to max number of places	
	if (isNaN(str)) {
		return str;
	}
	if (str.indexOf(".") != -1) {
	    if (places > 0) {
		str = str.substring(0, eval(str.indexOf(".")) + eval(places) + eval(1));
	    } else {
		str = str.substring(0, str.indexOf("."));
	    }
	}
	return str;
}

function DateFormat(dateVal) {	
	DayVal = dateVal.getDate();
	MonthVal = dateVal.getMonth();
	YearVal = dateVal.getYear();
	if (YearVal < 1000){YearVal+= 1900;}

	tempStr = eval(MonthVal + 1) + "/" + DayVal + "/" + YearVal;	
	return tempStr;
}

function stripNonDigits(str) {
	return str.replace(/[^0-9]/g,"")
}

function checkABA(str) {
  var i, n, t;
// First, remove any non-numeric characters.
  t = "";
  for (i = 0; i < str.length; i++) {
    c = parseInt(str.charAt(i), 10);
    if (c >= 0 && c <= 9)
      t = t + c;
  }
// Check the length, it should be nine digits.
  if (t.length != 9)
    return false;
// Now run through each digit and calculate the total.
  n = 0;
  for (i = 0; i < t.length; i += 3) {
    n += parseInt(t.charAt(i),     10) * 3
      +  parseInt(t.charAt(i + 1), 10) * 7
      +  parseInt(t.charAt(i + 2), 10);
  }
// If the resulting sum is an even multiple of ten (but not zero),
// the aba routing number is good.
  if (n != 0 && n % 10 == 0)
    return true;
  else
    return false;
}

function checkStateCode(str) {
	var s2 = str.substr(0,2);
	if (s2 == "XX" || s2 == "xx")
		return false;
	else
		return true;
	}

function checkCountryCode(str) {
	var s2 = str.substr(0,2);
	if (s2 == "XX" || s2 == "xx")
		return false;
	else
		return true;
	}
function checkProvider(str) {
	var s2 = str.substr(0,2);
	if (s2 == "XX" || s2 == "xx")
		return false;
	else
		return true;
	}

function checkPrfix(str, len) {
  var s2 = str.substr(0,2);
  var s4 = str.substr(0,4);

  if (str.charAt(0) == "4" || str.charAt(0) == "5") {
	  if (len == 16) 
		  return true;
	  else
		  return false;
	  }

   if (s2 == "34" || s2 == "37") {
      if (len == 15)
          return true;
	  else
		  return false;
      }

   if (s2 == "51" || s2 == "52" || s2 == "53" || s2 == "54" || s2 == "55") {
      if (len == 16)
          return true;
      else
		  return false;
      }

   if (s4 == "3088" || s4 == "3096" || s4 == "3112" || s4 == "3158" || s4 == "3337" || s4 == "3528") {
      if (len == 16)
          return true;
	  else {
          if (s2 == "30" || s2 == "36" || s2 == "38") {
             if (len == 14)
                return true;
             else
		        return false;
			 }
		  }
      }
  }

function checkCC(str) {
  var i, n, c, r, t, len=0;
  // First, reverse the string and remove any non-numeric characters.
  r = "";
  len = str.length;
  for (i = 0; i < len; i++) {
    c = parseInt(str.charAt(i), 10);
    if (c >= 0 && c <= 9)
      r = c + r;
    }
  
  // Check for a bad string.
  if (len <= 1)
    return false;
  
  if (!checkPrfix(str, len)) 
	return false;

  // Now run through each single digit to create a new string. Even digits
  // are multiplied by two, odd digits are left alone.
  t = "";
  for (i = 0; i < r.length; i++) {
    c = parseInt(r.charAt(i), 10);
    if (i % 2 != 0)
      c *= 2;
    t = t + c;
    }
  // Finally, add up all the single digits in this string.
  n = 0;
  for (i = 0; i < t.length; i++) {
    c = parseInt(t.charAt(i), 10);
    n = n + c;
    }
  // If the resulting sum is an even multiple of ten (but not zero), the
  // card number is good.
  if (n != 0 && n % 10 == 0)
    return true;
  else
    return false;
}

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s) {
	var i;
	for (i = 0; i < s.length; i++) {   
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
		}
	// All characters are numbers.
	return true;
}

function stripCharsInBag(s, bag) {
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++){   
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function daysInFebruary (year) {
	// February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {
			this[i] = 30;
			}
		if (i==2) {
			this[i] = 29;
			}
	}
	return this;
}

function isDate(dtStr) {
	var return_str = "";
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strMonth=dtStr.substring(0,pos1);
	var strDay=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0) == "0" && strYr.length>1) 
			strYr=strYr.substring(1);
		}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1) {
		return_str = " format should be: mm/dd/yyyy"
		}
	if (strMonth.length<1 || month<1 || month>12){
		return_str = " has invalid month";
		}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]) {
		return_str = " has invalid day";
		}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return_str = " has invalid year";
		}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return_str = " is an invalid date or format";
		}
return return_str;
}

//*******************************************************************************
// Validations
//*******************************************************************************
function checkform(form, errColor, startColor, showAlert, showErrors, fontStyle) {
	Error = false;
	alertStr = "";
	for (x=0; x < form.elements.length; x++ ) {
	fieldError = false;
	if (form.elements[x].type == "text" || form.elements[x].type == "select-one" || form.elements[x].type == "password"  || form.elements[x].type == "checkbox") {
	    if (showErrors == true) {
		document.all[form.elements[x].name + 'Error'].innerHTML = "";
	    }
	    form.elements[x].value = AllSpace(form.elements[x].value);
	    if (x+1 < form.elements.length && form.elements[x+1].name.charAt(0) == "@") {
			aa = form.elements[x+1].value.charAt(0);
			if (aa != "@") {  // bypass when names, starting with @, have @ value!
				paramStr = form.elements[x+1].name.substring(1, form.elements[x+1].name.length);
				params = null;
				params = paramStr.split("_");
				if (params[7] != null) {
					backColor = params[7];
					}
				else {
					backColor = startColor;
					} 
	
		if (params[6] != null && AllSpace(params[6]) != "" ) {
			defaultValue = params[6];
		} else {
			defaultValue = "";
		}

		if (params[1] == "NoBlank" && form.elements[x].value == "" && defaultValue == "") {
			alertStr = alertStr + "The " + params[2] + " field must not be blank." + CRLF();
			if (showErrors == true) {
				document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>The " + params[2] + " field must not be blank.</font>";
			}
			Error = true;
			fieldError = true;
		
		} else if (params[1] == "NoBlank" && form.elements[x].value == "" && defaultValue != "") {
			form.elements[x].value = defaultValue;

		} else if (params[0] == "email") {
			if (!validateEmail(form.elements[x].value) && form.elements[x].value != "") {
				alertStr = alertStr + "The " + params[2] + " field does not contain a valid email address." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>The " + params[2] + " field does not contain a valid email address.</font>";
				}
				Error = true;
				fieldError = true;
			}
		} else if (params[0] == "state") {
			if (!checkStateCode(form.elements[x].value)) {
				alertStr = alertStr + "The " + params[2] + " field does not contain a valid State." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>The " + params[2] + " field does not contain a valid State.</font>";
				}
				Error = true;
				fieldError = true;
			}
		} else if (params[0] == "country") {
			if (!checkCountryCode(form.elements[x].value)) {
				alertStr = alertStr + "The " + params[2] + " field does not contain a valid Country." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>The " + params[2] + " field does not contain a valid Country.</font>";
				}
				Error = true;
				fieldError = true;
			}
		} else if (params[0] == "provider") {
			if (!checkProvider(form.elements[x].value)) {
				alertStr = alertStr + "The " + params[2] + " field does not contain a valid Provider." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>The " + params[2] + " field does not contain a valid Provider.</font>";
				}
				Error = true;
				fieldError = true;
			}
		} else if (params[0] == "province") {
			if (!checkStateCode(form.elements[x].value)) {
				alertStr = alertStr + "The " + params[2] + " field does not contain a valid Provice/Territory." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>The " + params[2] + " field does not contain a valid Provice/Territory.</font>";
				}
				Error = true;
				fieldError = true;
			}
		} else if (params[0] == "postalcd") {
			if (!validatePostalCode(form.elements[x].value) && form.elements[x].value != "") {
				alertStr = alertStr + "The " + params[2] + " field does not contain a valid Postal Code." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>The " + params[2] + " field does not contain a valid Postal Code.</font>";
				}
				Error = true;
				fieldError = true;
			}
		} else if (params[0] == "zipcode") {
			if (!validateZipCode(form.elements[x].value) && form.elements[x].value != "") {
				alertStr = alertStr + "The " + params[2] + " field does not contain a valid Zip Code." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>The " + params[2] + " field does not contain a valid Zip Code.</font>";
				}
				Error = true;
				fieldError = true;
			}
		} else if (params[0] == "agree") {
			if (!form.elements[x].checked) {
				alertStr = alertStr + "The Cardholder's Agreement must be read and accepted!" + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>The Cardholder's Agreement must be read and accepted!</font>";
				}
				Error = true;
				fieldError = true;
			}
		} else if (params[0] == "ABA") {
			if (!checkABA(form.elements[x].value) && form.elements[x].value != "") {
				alertStr = alertStr + "The " + params[2] + " field must be a valid 9 digit number." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>The " + params[2] + " field must be a valid 9 digit number.</font>";
				}
				Error = true;
				fieldError = true;
			}
		} else if (params[0] == "XCard" && form.elements[x].value != "") {
			form.elements[x].value = StripChars("-", form.elements[x].value);
			item_len = CountChars(form.elements[x].value);
			if (isNaN(form.elements[x].value)) {
			 	alertStr = alertStr + "Then " + params[2] + " field does not contain a valid numeric value." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>Then " + params[2] + " field does not contain a valid numeric value.</font>";
				}
				Error = true;
				fieldError = true;
			} else {
				if (params[4] != null && params[5] == null) {
					if (item_len != eval(params[4])) {
						alertStr = alertStr + "Then " + params[2] + " field must contain exactly " + params[4] + " numbers." + CRLF();
						if (showErrors == true) {
							document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>Then " + params[2] + " field must contain exactly " + params[4] + " numbers.</font>";
						}
						Error = true;
						fieldError = true;
					}
				}
				if (params[4] != null && params[5] != null) {
					if (item_len < eval(params[4]) || item_len > eval(params[5])) {
						alertStr = alertStr + "Then " + params[2] + " field must contain " + params[4] + " to " + params[5] + " numbers." + CRLF();
						if (showErrors == true) {
							document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>Then " + params[2] + " field must contain " + params[4] + " to " + params[5] + " numbers.</font>";
						}
						Error = true;
						fieldError = true;
					}
				}
			}
		} else if (params[0] == "CCard") {
			if (!checkCC(form.elements[x].value) && form.elements[x].value != "") {
				alertStr = alertStr + "The " + params[2] + " field must be a valid credit card number." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>The " + params[2] + " field must be a valid credit card number.</font>";
				}
				Error = true;
				fieldError = true;
			}
		} else if (params[0] == "number" && form.elements[x].value != "") {
			form.elements[x].value =  StripChars("$,%", form.elements[x].value);
			if (params[3] != null) {
				form.elements[x].value = SetDec(form.elements[x].value, params[3]);
			}
			if (isNaN(form.elements[x].value)) {
			 	alertStr = alertStr + "Then " + params[2] + " field does not contain a valid numeric value." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>Then " + params[2] + " field does not contain a valid numeric value.</font>";
				}
				Error = true;
				fieldError = true;
			} else {
				if (params[4] != null) {
					if (eval(form.elements[x].value) < eval(params[4])) {
						alertStr = alertStr + "Then " + params[2] + " field must be greater than " + params[4] + CRLF();
						if (showErrors == true) {
							document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>Then " + params[2] + " field must be greater than " + params[4] + "</font>";
						}
						Error = true;
						fieldError = true;
					}
				}
				if (params[5] != null) {
					if (eval(form.elements[x].value) > eval(params[5])) {
						alertStr = alertStr + "Then " + params[2] + " field must be less than " + params[5] + CRLF();
						if (showErrors == true) {
							document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>Then " + params[2] + " field must be less than " + params[5] + "</font>";
						}
						Error = true;
						fieldError = true;
					}
				}
			}
			
		} else if (params[0] == "age" && form.elements[x].value != "") {
			var mdy   = form.elements[x].value;
			var date_error = isDate(mdy);
			var datex = mdy.split("/");
			var years = parseInt(datex[2]);
			var months= parseInt(datex[0]);
			var days  = parseInt(datex[1]);
			var unit  = "years";
			var decimal= 0;
			var round = " ";
			if (date_error > "") {
				alertStr = alertStr + "The " + params[2] + date_error + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>Then " + params[2] + date_error + "</font>";
					}
				Error = true;
				fieldError = true;
				}
			else {
				var agex = ageCalculator (years, months, days, unit, decimal, round);
				if (parseInt(agex)  < 16) {
				   alertStr = alertStr + "Age must be 16 years or older." + CRLF();
				   Error = true;
				   fieldError = true;
				}
			}			
		} else if (params[0] == "date" && form.elements[x].value != "") {
			var mdy  = form.elements[x].value;
			var date_error = isDate(mdy);
			dateYear = new String();
			curDate  = new Date();
			tempDate = new Date(form.elements[x].value);
			if (form.elements[x].value != "") {
				if (date_error > "") {
					alertStr = alertStr + "The " + params[2] + date_error + CRLF();
					if (showErrors == true) {
						document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>Then " + params[2] + date_error + "</font>";
						}
					Error = true;
					fieldError = true;
					
					} else if (tempDate == "NaN") {
					alertStr = alertStr + "The " + params[2] + " field is not a valid date." + CRLF();
					if (showErrors == true) {
						document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>Then " + params[2] + " field is not a valid date.</font>";
					}
					Error = true;
					fieldError = true;
					
				} else if (params[4] != null && dateYear < eval(curDate.getYear()) - eval(params[4])) {
					alertStr = alertStr + "The " + params[2] + " field is too low." + CRLF();
					if (showErrors == true) {
						document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>Then " + params[2] + " field is too low.</font>";
					}
					Error = true;
					fieldError = true;
					
				} else if (params[5] != null && dateYear > eval(curDate.getYear()) + eval(params[5])) {
					alertStr = alertStr + "The " + params[2] + " field is too high." + CRLF();
					if (showErrors == true) {
						document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>Then " + params[2] + " field is too high.</font>";
					}
					Error = true;
					fieldError = true;
					
				} else {
					
					form.elements[x].value = DateFormat(tempDate);
				}
			}
		} else if (params[0] == "phone" && form.elements[x].value != "") {
			form.elements[x].value = stripNonDigits(form.elements[x].value)
			if (validatePhone(form.elements[x].value)) {
					tempP = form.elements[x].value	
					form.elements[x].value = "(" + tempP.substring(0, 3) + ") " + tempP.substring(3,6) + "-" + tempP.substring(6, 10)
			} else {
					alertStr = alertStr + "The " + params[2] + " field is invalid.  Please include the full phone number including area code." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>Then " + params[2] + " field is invalid.  Please include the full phone number including area code.</font>";
				}
				Error = true;
				fieldError = true;
			}
		} else if (params[1] == "FnameCol") {
			if (!validate_A_2_Z(form.elements[x].value) && form.elements[x].value != "") {
				alertStr = alertStr + "The " + params[2] + " must only be a valid Colum Designator letter form A to Z." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>The " + params[2] + " must only be a valid Colum Designator letter form A to Z.";
				}
			Error = true;
			fieldError = true;
			}
		} else if (params[1] == "LnameCol") {
			if (!validate_A_2_Z_space(form.elements[x].value) && form.elements[x].value != "") {
				alertStr = alertStr + "The " + params[2] + " must only be a valid Colum Designator letter form A to Z or a Blank." + CRLF();
				if (showErrors == true) {
					document.all[form.elements[x].name + 'Error'].innerHTML = "<font  style='" + fontStyle + "'>The " + params[2] + " must only be a valid Colum Designator letter form A to Z o Blank.";
				}
			Error = true;
			fieldError = true;
			}
		}
		if (fieldError == true) {
			form.elements[x].style.background = errColor;
			} 
		else {
			form.elements[x].style.background = backColor;
			}
		}
	}
	}
	}
	if (Error == true) {
		if (showAlert == true) {
			alert (alertStr);
			}
		return false;
		}
	else
		return true;
}