// Last Updated: 12/12/2002 by S. Tobias
// Added Signed Currency datatype
//
// Updated: 09/16/2002 by WMP
// Added SSN validation
//
// Updated: 08/19/2002 by WMP
// Added semicolons to those statements that didn't have any
//
// Updated: 08/15/2002 by WMP
// Updated the validate function to impose character limitations for text fields
//
// Updated: 09/17/2003 by SBT
// Copied over from MSHDA, Angie made a change that should be applied to WEGO (round negative numbers down instead of up)
//
// Updated: 09/25/2003 by SD
// Added date/time validation function (checkDateTime) & updated "validate" function
//
// Updated: 10/27/2003 by DJK
// Added percent validation function for allowing over 100%
// Updated: 01/13/2004 by GM
// Removed the alert for the date validation


var digits = "0123456789";
var lowercaseletters = "abcdefghijklmnopqrstuvwxyz";
var uppercaseletters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var positivenegative = "+-";
var whitespace = " \t\n\r";
var decimaldelimiter = ".";
var phonedelimiters = "()-. ";
var currencydelimiters = "$, ";
var percentdelimiters = "%, ";
var numberdelimiters = ", ";
var zipcodedelimiters = "-";
var ssndelimiters = "- ";
var statedelimiter = "|";
var phonecharacters = digits + phonedelimiters;
var zipcodecharacters = digits + zipcodedelimiters;
var mindigitsinphonenumber = 10;
var maxdigitsinphonenumber = 15;
var digitsinzipcode1 = 5;
var digitsinzipcode2 = 9;
var digitsinssn = 9;
var intmaxscore = 100;
var intminscore = 0;

var ValidationTypes = new Array(15);
ValidationTypes[0] = "Integer";
ValidationTypes[1] = "Alphabetic Value";
ValidationTypes[2] = "Alphanumeric Value";
ValidationTypes[3] = "Float";
ValidationTypes[4] = "Currency";
ValidationTypes[5] = "Date";
ValidationTypes[6] = "Phone or Fax Number";
ValidationTypes[7] = "Zipcode";
ValidationTypes[8] = "Email Address";
ValidationTypes[9] = "Social Security Number";
ValidationTypes[10] = "Signed Currency";
ValidationTypes[11] = "Long Year";
ValidationTypes[12] = "Whole Number Currency";
ValidationTypes[13] = "Percent";
ValidationTypes[14] = "Score";
ValidationTypes[16] = "DateTime";

function listtypes()
{
  var intloop = 0;
  var intloop2 = 0;
  var intspacelength = 0;
  var space = "";
  var newwindow = "";
  newwindow += "JavaScript Validation Data Types\npreceeded by the integer reference.\n\n";

  for(intloop=0; intloop < ValidationTypes.length; intloop++)
  {
    intspacelength = intloop.toString();
    space = "  ";
    if (intspacelength.length < 2) space += "  ";
    newwindow += intloop + space + ValidationTypes[intloop] + "\n";
  }

  newwindow += "\n\nfunction validate(inttype, field, strfieldname, blnautocorrect, blnautoformat, strcustomerrormessage, intminvalue, intmaxvalue, intnumberofdecimals )";

  alert(newwindow);
}

var daysinmonth = Array(12);
daysinmonth[1] = 31;
daysinmonth[2] = 29;
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;


var states = "AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|AE|AA|AE|AE|AP";
var defaultEmptyOK = false;

function givefocus()
{
  var blnFound = false;

  if(document.forms.length!=0)
  {
    for(i=0; i<document.forms.length; i++)
    {
      for(j=0; j<document.forms[i].length; j++)
      {
  if((document.forms[i].elements[j].type == "text" && !document.forms[i].elements[j].disabled) || document.forms[i].elements[j].type == "textarea" || document.forms[i].elements[j].type == "password" )
  {
    blnFound = true;
    document.forms[i].elements[j].focus();
    window.scrollTo(0,0);
    window.scroll(0,0);
    break;
  }
      }

      if( blnFound ) break;
    }
  }
}




/////////////////////////////////////////////////
// GROUPED IS FUNCTIONS
/////////////////////////////////////////////////

function isEmpty(s)
{
  return ((s == null) || (s.length == 0));
}

function isWhitespace (s)
{
  var intloop;
  if (isEmpty(s))
    return true;
  for (intloop = 0; intloop < s.length; intloop++)
  {
    var character = s.charAt(intloop);
    if (whitespace.indexOf(character) == -1)
      return false;
  }
  return true;
}

function isLetter(c)
{
  return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) );
}

function isDigit(c)
{
  return ((c >= "0") && (c <= "9"));
}

function isLetterOrDigit(c)
{
  return (isLetter(c) || isDigit(c));
}

function isInteger(s)
{
  var intloop;

  for (intloop = 0; intloop < s.length; intloop++)
  {
    var character = s.charAt(intloop);
    if (!isDigit(character))
      return false;
  }
  return true;
}

function isFloat(s)
{
  var intloop;
  var seenDecimalPoint = false;

  if (s == '.')
    return false;

  for (intloop = 0; intloop < s.length; intloop++)
  {
    var character = s.charAt(intloop);
    if ((character == '.') && !seenDecimalPoint)
      seenDecimalPoint = true;
    else if (!isDigit(character))
      return false;
  }
  return true;
}

function isAlphabetic(s)
{
  var intloop;

  for (intloop = 0; intloop < s.length; intloop++)
  {
    var character = s.charAt(intloop);
    if (!isLetter(character))
      return false;
  }
  return true;
}

function isAlphanumeric(s)
{
  var i;

    for (i = 0; i < s.length; i++)
    {
      var c = s.charAt(i);

      if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    return true;
}

function isSignedInteger(s)
{
  var startPos = 0;

  if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
     startPos = 1;

  return (isInteger(s.substring(startPos, s.length)));
}

function isPositiveInteger(theField)
{
  var normalizedint = RemoveCharacters(theField, numberdelimiters);

  return (isSignedInteger(normalizedint) && (parseInt (normalizedint) >= 0));
}

function isPositiveFloat(s)
{
  if (isFloat(s) && parseFloat(s) >= 0)
    return true;
  else
    return false;
}

function isSignedCurrency(s)
{
  var startPos = 0;

  s = convertParenthesis(s);
  if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
     startPos = 1;

  return (isFloat(unformatCurrency(s.substring(startPos, s.length))));
}

function isPositiveCurrency(s)
{
  if (!isPositiveFloat(unformatCurrency(s)))
    return false;
  else
    return true;
}

function isNonNegWholeCurrency(s)
{
  if (!isPositiveInteger(unformatCurrency(s)))
    return false;
  else
    return true;
}

function isPositivePercent(s)
{
  var normalizedpercent = unformatPercent(s);

  return (isPositiveFloat(normalizedpercent) && (parseFloat(normalizedpercent) >= 0) && (parseFloat(normalizedpercent) <= 1));

}

function isPositivePercentOver100(s)
{
  var normalizedpercent = unformatPercent(s);

  return (isPositiveFloat(normalizedpercent) && (parseFloat(normalizedpercent) >= 0) );

}

function isYear(s)
{
  if (!isPositiveInteger(s))
    return false;

  return ((s.length == 2) || (s.length == 4));
}

function isLongYear(s)
{
  if (!isPositiveInteger(s)) return false;
  return (s.length == 4);
}

function isIntegerInRange(s, a, b)
{
  if (!isInteger(s))
    return false;

  if (!isInteger(a) || !isInteger(b))
  {
    alert("Your upper and lower bounds were not integers./nPlease check your code.");
    return false;
  }

  var num = parseInt(s);

  if (a == null && b == null)
    return true;
  else if (a == null)
    return (num >= a);
  else if (b == null)
    return (num <= b);
  else
    return ((num >= a) && (num <= b));
}

function isMonth(s)
{
  return isIntegerInRange (s, 1, 12);
}

function isDay(s)
{
  return isIntegerInRange (s, 1, 31);
}

function isDate(year, month, day)
{
  if (! (isYear(year) && isMonth(month) && isDay(day)))
    return false;

  var intYear = parseInt(year);
  var intMonth = parseInt(month);
  var intDay = parseInt(day);

  if (intDay > daysinmonth[intMonth])
    return false;

  if ((intMonth == 2) && (intDay > daysInFebruary(intYear)))
    return false;

  return true;
}

function isZIPCode(s)
{
  return (isInteger(s) && ((s.length == digitsinzipcode1) || (s.length == digitsinzipcode2)));
}

function isSSN(s)
{
  var strNumericalSSN;
  strNumericalSSN = RemoveCharacters(s, ssndelimiters);

  return (isInteger(strNumericalSSN) && strNumericalSSN.length == digitsinssn);
}

function isEmail(s)
{
  if (isWhitespace(s))
    return false;

  var i = 1;
  var sLength = s.length;

  while ((i < sLength) && (s.charAt(i) != "@"))
  {
    i++;
  }

  if ((i >= sLength) || (s.charAt(i) != "@"))
    return false;
  else
    i += 2;

  while ((i < sLength) && (s.charAt(i) != "."))
  {
    i++;
  }

  if ((i >= sLength - 1) || (s.charAt(i) != "."))
    return false;
  else
    return true;
}

function isCurrency(s)
{
  return (isParenSignedFloat(s));
}

function isPhoneNumber(s)
{
  return (isInteger(s) && s.length >= mindigitsinphonenumber && s.length <= maxdigitsinphonenumber);
}



///////////////////////////////////////////////
// GROUPED FORMAT FUNCTIONS
///////////////////////////////////////////////

function RemoveCharacters (s, characters)
{
  var intcount;
  var returnString = "";
  for (intcount = 0; intcount < s.length; intcount++)
  {
    var c = s.charAt(intcount);
    if (characters.indexOf(c) == -1)
      returnString += c;
  }
  return returnString;
}

function RemoveOtherCharacters (s, characters)
{
  var intcount;
  var returnString = "";
  for (intcount = 0; intcount < s.length; intcount++)
  {
    var c = s.charAt(intcount);
    if (characters.indexOf(c) != -1)
      returnString += c;
  }
  return returnString;
}

function stripWhitespace(s)
{
  return RemoveCharacters (s, whitespace);
}

function trim(s)
{
  if (!isEmpty(s))
  {
    var intcount = 0;
    var intstringstart = 0;
    var intstringend = s.length;
    if (intstringend == null)
      intstringend = 0;

    for (intcount = 0; intcount < s.length; intcount++)
    {
      if (s.charAt(intcount) == " " || s.charAt(intcount) == "\t" || s.charAt(intcount) == "\n" || s.charAt(intcount) == "\r")
        intstringstart++;
      else
        break;
    }
    for (intcount = s.length - 1; intcount > 0; intcount--)
    {
      if (s.charAt(intcount) == " " || s.charAt(intcount) == "\t" || s.charAt(intcount) == "\n" || s.charAt(intcount) == "\r")
        intstringend--;
      else
        break;
    }
    if (s.length != null)
      s = s.substring(intstringstart, intstringend);
    return s;
  }
  else
    return s;

}

function RemoveLeadingZeros(value)
{
  var convertedvalue = '';
  var endremovezeros = false;

  for (i = 0; i < value.length; i++)
  {
    var c = value.charAt(i);

    if ((c != 0) && !endremovezeros)
    {
      endremovezeros = true;
      convertedvalue += c;
    }
    else if ((c == 0) && !endremovezeros && value.charAt(i + 1) == '.')
    {
      endremovezeros = true;
      convertedvalue += c;
    }
    else if ((c == 0) && !endremovezeros && value.length == 1)
    {
      endremovezeros = true;
      convertedvalue += c;
    }
    else if (endremovezeros)
      convertedvalue += c;
  }
return(convertedvalue);
}

function RemoveTrailingZeros(value)
{
  var convertedvalue = '';
  var endvalue = value.length;
  var endremovezeros = false;
  var decimalexists = false;

  if (value.indexOf('.') == -1)
  {
    return(value);
  }
  for (i = (value.length - 1); i > 0; i--)
  {
    //alert("loop = " + i);
    var c = value.charAt(i);
    //alert("char = " + c);

    if ((c != 0) && (c != '.') && !endremovezeros)
      endremovezeros = true;
    else if ((c == 0) && !endremovezeros && value.length == 1)
      endremovezeros = true;
    else
      endvalue -= 1;

    if (endremovezeros)
      break;
  }

  convertedvalue = value.substring(0, endvalue);
  return(convertedvalue);
}


function reformat(s)
{
  var arg;
  var sPos = 0;
  var resultString = "";

  for (var i = 1; i < reformat.arguments.length; i++) {
    arg = reformat.arguments[i];
    if (i % 2 == 1)
      resultString += arg;
    else
    {
      resultString += s.substring(sPos, sPos + arg);
      sPos += arg;
    }
  }
  return resultString;
}

function roundtodecimals(original_number, decimalplaces)
{
  var isNegative = false;
  var value1 = original_number * Math.pow(10, decimalplaces);

  var value2 = value1;
  if (value2 < 0) {
    isNegative = true;
    value2 = Math.abs(value2);
  }
  value2 = Math.round(value2);
  if (isNegative) {
    value2 = -value2;
  }
  var value3 = value2 / Math.pow(10, decimalplaces);
  return insertzeros(value3, decimalplaces);
}

function roundToPennies(n)
{
 pennies = n * 100;
 pennies = Math.round(pennies);

 strPennies = "" + pennies;
 len = strPennies.length;

 return strPennies.substring(0, len - 2) + "." + strPennies.substring(len - 2, len);
}

function insertzeros(rounded_value, decimal_places)
{
  var value_string = rounded_value.toString();
  var decimal_location = value_string.indexOf(".");
  if (decimal_location == -1)
  {
    decimal_part_length = 0;
    value_string += decimal_places > 0 ? "." : "";
  }
  else
    decimal_part_length = value_string.length - decimal_location - 1;

  var pad_total = decimal_places - decimal_part_length;
  if (pad_total > 0)
  {
    for (var counter = 1; counter <= pad_total; counter++)
      value_string += "0";
  }
  return value_string;
}

function insertcommas(s)
{
  var sPos;
  var start = s.length - 1;
  var resultString = s.charAt(start);

  for (sPos = start-1; sPos >= 0; sPos--)
  {
    if ((start - sPos) % 3 == 0)
      resultString = s.charAt(sPos) + ',' + resultString;
    else
      resultString = s.charAt(sPos) + resultString;
  }
  return resultString;
}

function reformatPercent(s, intnumberofdecimals)
{

  if (!isEmpty(intnumberofdecimals))
  {
    if (intnumberofdecimals.toString() == "NaN")
      intnumberofdecimals = 2; // default
  }
  else
    intnumberofdecimals = 2; // default

  var percent;
  var percentfirstcharacter = "";

  percent = convertParenthesis(s);
  if(percent.length > 0 && (percent.charAt(0) == "-" || percent.charAt(0) == "+")){
    percentfirstcharacter = percent.substring(0,1);
  }
  percent = RemoveOtherCharacters(percent, decimaldelimiter + digits);
  if(isFloat(percent)) {
    percent = parseFloat(percent);
    percent = percent * 100;
    percent = percent.toString();
  }
  percent = roundtodecimals(percent, intnumberofdecimals);
  percent = percentfirstcharacter + percent + '%';
  return (percent);
}

function reformatCurrency(s, intnumberofdecimals)
{

  if (!isEmpty(intnumberofdecimals))
  {
    if (intnumberofdecimals.toString() == "NaN")
      intnumberofdecimals = 2; // default
  }
  else
    intnumberofdecimals = 2; // default

  var length;
  var startPos = 0;
  var endPos;
  var currency;
  var currencyfirstcharacter;
  var decimalpointposition;

  currency = RemoveOtherCharacters(s, decimaldelimiter + digits + positivenegative);
  length = currency.length;
  currencyfirstcharacter = currency.substring(0,1);
  currency = currency.substring(1,length + 1);
  currency = RemoveCharacters(currency, positivenegative);
  length = currency.length;
  decimalpointposition = currency.indexOf(decimaldelimiter);
  if (decimalpointposition != -1)
    currency = RemoveCharacters(currency.substring(0,decimalpointposition + 1), decimaldelimiter) + "." + RemoveCharacters(currency.substring(decimalpointposition,length + 1), decimaldelimiter);

  currency = currencyfirstcharacter + currency;
  currency = roundtodecimals(currency, intnumberofdecimals);
  length = currency.length;

  //if (currency.substring(length - 3, length + 1) == ".00")
  //  currency = currency.substring(0, currency.indexOf("."));

  if ( (currency.charAt(0) == "-") || (currency.charAt(0) == "+") )
    startPos = 1;

  endPos = currency.indexOf(".");

  if (endPos == -1)
    endPos = s.length;

  if (currency.charAt(0) == "-") {
    return( '-' + '$' + insertcommas(currency.substring(startPos, endPos)) + currency.substring(endPos, s.length));
    //currency = ( '-' + '$' + insertcommas(currency.substring(startPos, endPos)) + currency.substring(endPos, s.length));
  } else {
    return( '$' + insertcommas(currency.substring(startPos, endPos)) + currency.substring(endPos, currency.length) );
    //currency = ( '$' + insertcommas(currency.substring(startPos, endPos)) + currency.substring(endPos, currency.length) );
  }

  currency = roundtodecimals(currency, 2);
  return( currency );


/*
  if (currency.charAt(0) == "-")
  {
    return( '-' + '$' + insertCurrencyCommas(currency.substring(startPos, endPos)) + currency.substring(endPos, s.length));
    //currency = '-' + insertCurrencyCommas(currency.substring(startPos, endPos)) + currency.substring(endPos, s.length);
  }
  else
  {
    return( '$' + insertCurrencyCommas(currency.substring(startPos, endPos)) + currency.substring(endPos, currency.length) );
    //currency = insertCurrencyCommas(currency.substring(startPos, endPos)) + currency.substring(endPos, currency.length);
  }

    currency = roundtodecimals(currency, 2)
    return( currency );
*/

}

function reformatPhone(Phone)
{
  var normalizedPhone = RemoveCharacters(Phone.value, phonedelimiters);
  if (normalizedPhone.length == 10)
    return (reformat (normalizedPhone, "(", 3, ") ", 3, "-", 4));
  else
    return (reformat (normalizedPhone, "(", 3, ") ", 3, "-", 4, " ", 5));
}

function reformatZipcode(Zipcode)
{
  if (Zipcode.length == 5)
    return Zipcode;
  else
    return (reformat (Zipcode, "", 5, "-", 4));
}

function reformatSSN(SSN)
{
  var strformattedSSN;
  strformattedSSN = RemoveOtherCharacters(SSN, digits);
  if (strformattedSSN.length == 9)
  {
    strformattedSSN = (reformat (strformattedSSN, "", 3, "-", 2, "-", 4));
  }
  return strformattedSSN;
}


function unformatCurrency(s)
{
  return RemoveCharacters(convertParenthesis(s), currencydelimiters);
}

function unformatPercent(s)
{
  var percent;
  percent = RemoveCharacters(s, percentdelimiters);
  if(isFloat(percent)) {
    percent = parseFloat(percent);
    percent = percent / 100;
    percent = percent.toString();
  }
  return percent;
}

function convertParenthesis(s)
{
  if ( (s.charAt(0) == "(") && (s.charAt( s.length - 1 ) == ")") )
    return ( '-' + s.substring(1, s.length - 1 ) );
  else
    return( s );
}

function selectField(field)
{
  field.focus();
  field.select();
}

function noFocus(field, text)
{
  var Errormessage;
  Errormessage = "You may not change this value.\nThe system automatically calculates this value";
  if (isEmpty(text))
    Errormessage = Errormessage + ".";
  else
    Errormessage = Errormessage + " by " + text;
  field.blur();
  alert(Errormessage);
}

function setToZeroIfBlank(field)
{
  if (field.value == "")
    field.value = "0";
}

function removeQuotes(field)
{
  var pattern = /"/g;
  var tempString = new String(field.value);
  field.value = tempString.replace(pattern, "");
}


function checkCurrency(theField)
{
  var normalizedCurrency = RemoveCharacters(theField.value, currencydelimiters);
  normalizedCurrency = convertParenthesis(normalizedCurrency);

  if (!isCurrency(normalizedCurrency))
     return false;
  else
  {
    theField.value = reformatCurrency(normalizedCurrency);
    return true;
  }
}


function checkPhone(theField)
{
  var normalizedPhone = RemoveCharacters(theField.value, phonedelimiters);
  if (!isPhoneNumber(normalizedPhone, false))
     return false;
  else
  {
     //theField.value = reformatPhone(normalizedPhone);
     return true;
  }

}

function checkZipcode(theField)
{
  var normalizedZIP = RemoveCharacters(theField.value, zipcodedelimiters);
  if (!isZIPCode(normalizedZIP))
     return false;
  else
  {
     theField.value = reformatZipcode(normalizedZIP);
     return true;
  }
}

function checkSSN(theField)
{
  var normalizedSSN = RemoveCharacters(theField.value, ssndelimiters);
  if (!isSSN(normalizedSSN))
     return false;
  else
  {
     theField.value = reformatSSN(normalizedSSN);
     return true;
  }
}

function checkEmail(theField)
{
  if (!isEmail(theField.value))
    return false;
  else
    return true;
}

function daysInFebruary(year)
{
  return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}

function checkYear(theField)
{
  if (!isYear(theField.value))
    return false;
  else
    return true;
}

function checkMonth(theField)
{
  if (!isMonth(theField.value))
     return false;
  else
    return true;
}

function checkDay (theField)
{
  if (!isDay(theField.value))
    return false;
  else
    return true;
}

function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
{
  if (checkDate.arguments.length == 4)
    OKtoOmitDay = false;
  if (!isYear(yearField.value))
    return false;
  if (!isMonth(monthField.value))
    return false;
  if ( (OKtoOmitDay == true) && isEmpty(dayField.value) )
    return true;
  else if (!isDay(dayField.value))
    return false;
  if (isDate (yearField.value, monthField.value, dayField.value))
    return true;

  return false;
}



function getRadioButtonValue (radio)
{
  for (var i = 0; i < radio.length; i++)
  {
    if (radio[i].checked)
      break;
  }
  return radio[i].value;
}

function checkDate(theField, emptyOK)
{
  var dateStr = theField.value;
  var datePat = /^(\d{1,2})(\/)(\d{1,2})\2(\d{4})$/;      // requires 4 digit year
  var datePat2 = /^(\d{1,2})(\/)(\d{1,2})\2(\d{2})$/;     // requires 2 digit year

  if (checkDate.arguments.length == 1)
    defaultEmptyOK = false;
  if ((emptyOK == true) && (isEmpty(theField.value)))
    return true;

  var matchArray;
  matchArray = (dateStr.match(datePat) || dateStr.match(datePat2)); // is the format ok?
  if (matchArray == null)
  {
    //alert(dateStr + " Date is not in a valid format.")
    return false;
  }

  month = matchArray[1]; // parse date into variables
  day = matchArray[3];
  year = matchArray[4];

  if (year.length == 2)
  {
    year = parseInt("20" + year);
    //alert("The date you have entered is going to be reformatted to have a four digit year.\nIf the resulting date is not what you intended than please change the value.");
    theField.value = month + "/" + day + "/" + year;
    theField.select();
    theField.focus();
  }

  if (month < 1 || month > 12)
    return false;
  if (day < 1 || day > 31)
    return false;
  if ((month==4 || month==6 || month==9 || month==11) && day==31)
    return false;
  if (month == 2)
  {
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day>29 || (day==29 && !isleap))
      return false;
  }
  return true;
}

function checkDateTime(theField) {

  var strDateTime = theField.value

  // date/time format: (m)m/(d)d/yyyy (h)h:mm am/pm
  //var re_DateTime = /^([1-9]|1[0-2])(\-|\/|\.)(\d{1,2})(\-|\/|\.)(\d{4})(\s+)([1-9]|1[0-2])(:|\.)([0-5]\d)(:|\.)?([0-5]\d)?(\s+)(A|a|P|p)(M|m)$/;
  var re_DateTime = /^([1-9]|1[0-2])(\-|\/|\.)(\d{1,2})(\-|\/|\.)(\d{4})(\s+)([1-9]|1[0-2])(:|\.)([0-5]\d)((:|\.)([0-5]\d))?(\s+)(A|a|P|p)(M|m)$/;


  //var re_DateTime = /^([1-9]|1[0-2])(\-|\/|\.)(\d{1,2})(\-|\/|\.)(\d{4})(\s+)([1-9]|1[0-2])(:|\.)([0-5]\d)(A|a|P|p)(M|m)$/;


  if (strDateTime != '' && !re_DateTime.test(strDateTime)) {
    return false;
  }

  var aryDateTime = strDateTime.match(re_DateTime);



  //for (var i=aryDateTime.length; i>0; i--) {
    //if (aryDateTime[i] == '') {
    //  return false;
    //}
  // alert(aryDateTime[i]);
  //}

  var strMonth = aryDateTime[1];
  var strDay = aryDateTime[3];
  var strYear = aryDateTime[5];

  if (strDay < 1 || strDay > 31)
    return false;
  if ((strMonth==4 || strMonth==6 || strMonth==9 || strMonth==11) && strDay==31)
    return false;
  if (strMonth == 2)
  {
    var blnLeapYear = (strYear % 4 == 0 && (strYear % 100 != 0 || strYear % 400 == 0));
    if (strDay>29 || (strDay==29 && !blnLeapYear))
      return false;
  }

  return true;
}

function checkTextLength(theField, minSize, maxSize)
{
  if (minSize != null)
  {
    if (theField.value.length < minSize)
      return false;
  }
  if (maxSize != null)
  {
    if (theField.value.length > maxSize)
      return false;
  }

  return true;
}

function checkNonNegInt(field)
{
  if (!isPositiveInteger(field.value))
    alert(strNonNegIntMsg);
}

function checkNonNegFloat(field)
{
  if (!isPositiveFloat(field.value))
    alert(strNonNegFloatMsg);
}

function checkNonNegCurrency(field)
{
  field.value = reformatCurrency(unformatCurrency(field.value));
}

function checkNonNegWholeCurrency(field)
{
  if (!isNonNegWholeCurrency(field.value))
    alert(strMoneyErrorMsg);
  else
    field.value = reformatCurrency(unformatCurrency(field.value));
}


function allowcharacters(s, inttype)
//, characters)
{
  //s.value = RemoveOtherCharacters (s.value, lowercaseletters + uppercaseletters)

  if( inttype == 0 )
    s.value = RemoveOtherCharacters(s.value, digits);
  else if( inttype == 1 )
    s.value = RemoveOtherCharacters(s.value, lowercaseletters + uppercaseletters + whitespace);
  else if( inttype == 2 )
    s.value = RemoveOtherCharacters(s.value, lowercaseletters + uppercaseletters + whitespace + digits);
  else if( inttype == 3 )
    s.value = RemoveOtherCharacters(s.value, digits + positivenegative + decimaldelimiter);
  else if( inttype == 4 )
    s.value = RemoveOtherCharacters(s.value, digits + positivenegative + decimaldelimiter);
  else if( inttype == 5 )
    s.value = RemoveOtherCharacters(s.value, digits + "/");
  else if( inttype == 6 )
    s.value = RemoveOtherCharacters(s.value, phonecharacters);
  else if( inttype == 7 )
    s.value = RemoveOtherCharacters(s.value, zipcodecharacters);
  else if( inttype == 8 )
    s.value = RemoveOtherCharacters(s.value, digits + positivenegative + decimaldelimiter + lowercaseletters + uppercaseletters + "@");
  else if( inttype == 11 )
    s.value = RemoveOtherCharacters(s.value, digits);
  else if( inttype == 14 )
    s.value = RemoveOtherCharacters(s.value, digits);    //added for Score

}







var strIntegerMsg = 'This field must be a whole number.  Please reenter it now.';
var strPositiveIntegerMsg = 'This field must be a non-negative whole number.  Please reenter it now.';
var strNegativeIntegerMsg = 'This field must be a negative whole number.  Please reenter it now.';
var strCurrencyMsg = 'This field must be a dollar amount.  Please reenter it now.';

var strValidPhoneMsg = "This field must be a valid phone number with area code.  Please reenter it now.";
var strValidFaxMsg = "This field must be a valid fax number with area code.  Please reenter it now.";
var strValidZipMsg = "This field must be a valid zip code.  Please reenter it now.";
var strValidDateMsg = "This field must be a valid date using the format: mm/dd/yyyy.  Please reenter it now.";

function validate(inttype, field, strfieldname, blnautocorrect, blnautoformat, strcustomerrormessage, intminvalue, intmaxvalue, intnumberofdecimals )
{
  var blnshowerror = true;
  var blntrim = true;
  var blnforcecorrection = true;
  var blnallowempty = true;

  var blnrange = false;
  var strpositivenegative = "";
  var strvaluebetween = "";

  if (isEmpty(strfieldname))
  {
    strfieldname = "This field";
  }
  if (isEmpty(strcustomerrormessage))
  {
    strcustomerrormessage = null;
  }
  if (!isEmpty(blnautocorrect))
  {
    blnautocorrect = blnautocorrect + "";
    if (blnautocorrect.toUpperCase() == "TRUE" || blnautocorrect.toUpperCase() == "1")
      blnautocorrect = 1;
    else
      blnautocorrect = 0;
  }
  else
      blnautocorrect = 0;

  if (!isEmpty(blnautoformat))
  {
    blnautoformat = blnautoformat + "";
    if (blnautoformat.toUpperCase() == "FALSE" || blnautoformat.toUpperCase() == "0")
      blnautoformat = 0;
    else
      blnautoformat = 1;
  }
  else
      blnautocorrect = 1;


  if (!isEmpty(intmaxvalue))
  {
    if (intmaxvalue.toString() == "NaN")
      intmaxvalue = null;
  }
  else
    intmaxvalue = null;

  if (!isEmpty(intminvalue) )
  {
    if (intminvalue.toString() == "NaN")
      intminvalue = null;
  }
  else
    intminvalue = null;

  if (intmaxvalue != null || intminvalue != null)
    blnrange = true;

  if (intmaxvalue == null && intminvalue == null)
    strpositivenegative = ""
  else if (!isNaN(parseFloat(intminvalue)) && intminvalue >= 0 && intmaxvalue == null)
    strpositivenegative = " positive";
  else if (!isNaN(parseFloat(intmaxvalue)) && intmaxvalue <= 0 && intminvalue == null)
    strpositivenegative = " negative";
  else if (intmaxvalue != null && intminvalue != null)
    strvaluebetween = " value between " + intminvalue + " and " + intmaxvalue;
  else if (intmaxvalue == null)
    strvaluebetween = " value greater than or equal to " + intminvalue;
  else if (intminvalue == null)
    strvaluebetween = " value less than or equal to " + intmaxvalue;

  if (strpositivenegative != " positive" && strpositivenegative != " negative" && inttype == 0)
    strpositivenegative = "n";

  if (blntrim)
    field.value = trim(field.value);

  if (blnallowempty && field.value == "")
    return true;

  if (blnautocorrect)
  {
    if ( inttype == 0 || inttype == 3 || inttype == 3 || inttype == 4 || inttype == 14)
      field.value = RemoveLeadingZeros(RemoveTrailingZeros(field.value));
  }

  if (blnrange && intminvalue == null)
    intminvalue = -3362500.08;
  if (blnrange && intmaxvalue == null)
    intmaxvalue = 3362500.08;

  var errormessage = "";

   // Validate an integer
  if( inttype == 0 )
  {
    if(field.value == "")
      return true;

    if( !isPositiveInteger(field.value) )
    {
      errormessage += strfieldname + " must be a" + strpositivenegative + " integer" + strvaluebetween + ".";
      errormessage += "\nPlease re-enter it now.";

      if (strfieldname == null)
        errormessage = strIntegerMsg;
    }
    else
    {
      if(blnrange)
      {
        if (!isIntegerInRange(field.value, intminvalue, intmaxvalue))
        {
          errormessage += strfieldname + " must be ";

          if ( intmaxvalue == 3362500.08 )
            errormessage += "greater than or equal to " + intminvalue + ".";
          else if ( intminvalue == -3362500.08 )
            errormessage += "less than or equal to " + intmaxvalue + ".";
          else
            errormessage += "between " + intminvalue + " and " + intmaxvalue + ".";

          errormessage += "\nPlease re-enter it now.";
        }
      }
    }

  if(blnautocorrect)
    {
      field.value = RemoveOtherCharacters(field.value, digits + positivenegative);
      if (errormessage != "")
        errormessage += "\nThe value entered will be changed to a proper data type";
    }

    if(blnautoformat && errormessage == "")
      field.value = insertcommas(RemoveLeadingZeros(RemoveOtherCharacters(field.value, digits + positivenegative)));

      //alert(blnautoformat + "\n" + errormessage);
      //alert(blnautoformat && errormessage == "");
  }


   // Validate an alphanumeric value
  else if( inttype == 2 )
  {
    var intcharacterdeficiency = 0;
    var strmessage = "";
    var intComparisonType;

  if (intminvalue == -3362500.08 )
    intminvalue = null;
  if (intmaxvalue == 3362500.08 )
    intmaxvalue = null;

    if(intminvalue != null || intmaxvalue != null)
    {
      //alert("test");
      if(!checkTextLength(field, intminvalue, intmaxvalue))
      {
        if (intminvalue != null && intmaxvalue == null)
        {
          intComparisonType = 1;
          intcharacterdeficiency = intminvalue - field.value.length;
        }
        else if (intminvalue == null && intmaxvalue != null)
        {
          intComparisonType = 2;
          intcharacterdeficiency = field.value.length - intmaxvalue;
        }
        else
        {
          intComparisonType = 3;
          intcharacterdeficiency = intminvalue - field.value.length;
          if (intcharacterdeficiency > 0)
            intComparisonType = 31;
          else
          {
            intcharacterdeficiency = field.value.length - intmaxvalue;
            intComparisonType = 32;
          }
        }

        errormessage += "The field";
        if(strfieldname != "")
          errormessage += " " + strfieldname;
        errormessage += " must be";

        if (intComparisonType == 1)
        {
          errormessage += " greater than or equal to " + intminvalue + " character";
          if (intminvalue != 1)
            errormessage += "s.\n";
          else
            errormessage += ".\n";
        }

        if (intComparisonType == 2)
        {
          errormessage += " less than or equal to " + intmaxvalue + " character";
          if (intmaxvalue != 1)
            errormessage += "s.\n";
          else
            errormessage += ".\n";
        }

        if (intComparisonType == 31 || intComparisonType == 32)
          errormessage += " between " + intminvalue + " and " + intmaxvalue + " characters.\n";

        errormessage += "Please";

        if (intComparisonType == 1 || intComparisonType == 31)
          errormessage += " add";
        else
          errormessage += " remove";

        errormessage += " " + intcharacterdeficiency;

        if (intcharacterdeficiency == 1)
          errormessage += " character";
        else
          errormessage += " characters";

        errormessage += " now.\n";

        errormessage += "Note: Characters include whitespaces.";
      }
    }
  }

   // Validate a float
  else if( inttype == 3 )
  {
    if( !isPositiveFloat(field.value) )
    {
      errormessage += strfieldname + " must be a" + strpositivenegative + " number" + strvaluebetween + ".";
      errormessage += "\nPlease re-enter it now.";
    }
    else
    {

    }
    if(blnautoformat && errormessage == "")
    {
      field.value = RemoveLeadingZeros(RemoveTrailingZeros(RemoveOtherCharacters(field.value, digits + positivenegative + decimaldelimiter)));
    }

  }
   // Validate a currency
  else if( inttype == 4 )
  {
    if( !isPositiveCurrency(field.value) )
    {
      errormessage += strfieldname + " must be a valid positive currency amount.";
      errormessage += "\nPlease re-enter it now.";
    }
    else
    {
      field.value = reformatCurrency(unformatCurrency(field.value),intnumberofdecimals);
    }
  }
  // Validate a date field
  else if( inttype == 5 )
  {
    if( !checkDate(field) )
    {
      errormessage += strfieldname+ " must be a valid date.";
      errormessage += "\nValid format:  MM/DD/YYYY";
    }
  }
  // Validate a datetime field
  else if( inttype == 16 ) {
    if( !checkDateTime(field) ) {
      errormessage += "Date/Time must be a valid date and time.";
      errormessage += "\nValid format:  MM/DD/YYYY HH:MM AM/PM";
    }
  }
  // Validate a phone field
  else if( inttype == 6 )
  {
    if( !checkPhone(field) )
    {
      errormessage += strfieldname + " must be a valid phone number.";
      errormessage += "\nValid format:  (123) 456-7890";
    }
    else
    {
      if(blnautoformat)
  field.value = reformatPhone(field);
    }
  }
  // Validate a zipcode
  else if( inttype == 7 )
  {
    if( !checkZipcode(field) )
    {
      errormessage += strfieldname + " must be a valid zipcode.";
      errormessage += "\nValid formats:  12345 or 12345-6789";
    }
  }
  else if( inttype == 8 )
  {
    if(!isEmail(field.value))
    {
      errormessage += strfieldname + " must be a valid email address.";
      errormessage += "\nPlease re-enter it now.";
    }
  }
  else if( inttype == 9 )
  {
    if(!isSSN(field.value))
    {
      if(blnautocorrect)
        field.value = RemoveOtherCharacters(field.value, digits);
      errormessage += strfieldname + " must be a valid Social Security Number.";
      errormessage += "\nPlease re-enter it now.";
    }
    if(blnautoformat && errormessage == "")
    {
      field.value = reformatSSN(field.value);
    }
  }
  else if( inttype == 10 )
  {
    if( !isSignedCurrency(field.value) )
    {
      errormessage += strfieldname + " must be a valid currency amount.";
      errormessage += "\nPlease re-enter it now.";
    }
    else
    {
      field.value = reformatCurrency(unformatCurrency(field.value),intnumberofdecimals);
    }
  }
  else if( inttype == 11 )
  {
    if( !isLongYear(field.value) )
    {
      errormessage += strfieldname + " must be a valid 4-digit year.";
      errormessage += "\nPlease re-enter it now.";
    }
  }
  // Validate a currency
  else if( inttype == 12 )
  {
    if( !isNonNegWholeCurrency(field.value) )
    {
      errormessage += strfieldname + " must be a positive whole number currency amount.";
      errormessage += "\nPlease re-enter it now.";
    }
    else
    {
      field.value = reformatCurrency(unformatCurrency(field.value),0);
    }
  }
  else if( inttype == 13 )
  {
    if( !isPositivePercent(field.value) )
    {
      errormessage += strfieldname + " must be a valid percent number.";
      errormessage += "\nPlease re-enter it now.";
    }
    else
    {
      field.value = reformatPercent(unformatPercent(field.value));
    }
  }
  else if( inttype == 17 )
  {
    if( !isPositivePercentOver100(field.value) )
    {
      errormessage += strfieldname + " must be a valid percent number.";
      errormessage += "\nPlease re-enter it now.";
    }
    else
    {
      field.value = reformatPercent(unformatPercent(field.value));
    }
  }
  else if( inttype == 14 )
  {

    intmaxscore = 100;
    intminscore = 0;
    if (!isEmpty(intmaxscore))
    {
      if (intmaxscore.toString() == "NaN")
        intmaxscore = null;
    }
    else
      intmaxscore = null;

    if (!isEmpty(intminscore) )
    {
      if (intminscore.toString() == "NaN")
        intminscore = null;
    }
    else
      intminscore = null;

    if (intmaxscore != null || intminscore != null)
      blnrange = true;

    if (intmaxscore == null && intminscore == null)
      strpositivenegative = ""
    else if (!isNaN(parseFloat(intminscore)) && intminscore >= 0 && intmaxscore == null)
      strpositivenegative = " positive";
    else if (!isNaN(parseFloat(intmaxscore)) && intmaxscore <= 0 && intminscore == null)
      strpositivenegative = " negative";
    else if (intmaxscore != null && intminscore != null)
      strvaluebetween = " value between " + intminvalue + " and " + intmaxvalue;
    else if (intmaxscore == null)
      strvaluebetween = " value greater than or equal to " + intminscore;
    else if (intminscore == null)
      strvaluebetween = " value less than or equal to " + intmaxscore;


      if(field.value == "")
        return true;

      if( !isPositiveInteger(field.value) )
      {
        errormessage += strfieldname + " must be a" + strpositivenegative + " integer" + strvaluebetween + ".";
        errormessage += "\nPlease re-enter it now.";

        if (strfieldname == null)
          errormessage = strIntegerMsg;
      }
      else
      {
        if(blnrange)
        {
          if (!isIntegerInRange(field.value, intminscore, intmaxscore))
          {
            errormessage += strfieldname + " must be ";

            if ( intmaxscore == 100 )
              errormessage += "greater than or equal to " + intminscore + ".";
            else if ( intminscore == 0 )
              errormessage += "less than or equal to " + intmaxscore + ".";
            else
              errormessage += "between " + intminscore + " and " + intmaxscore + ".";

            errormessage += "\nPlease re-enter it now.";
          }
        }
      }

    if(blnautocorrect)
      {
        field.value = RemoveOtherCharacters(field.value, digits + positivenegative);
        if (errormessage != "")
          errormessage += "\nThe value entered will be changed to a proper data type";
      }

      if(blnautoformat && errormessage == "")
        field.value = insertcommas(RemoveLeadingZeros(RemoveOtherCharacters(field.value, digits + positivenegative)));

        //alert(blnautoformat + "\n" + errormessage);
        //alert(blnautoformat && errormessage == "");
  }



  if( blnshowerror && errormessage != '' )
  {
    //alert(strcustomerrormessage);
    if (trim(strcustomerrormessage) != null && strcustomerrormessage != "")
      alert(strcustomerrormessage);
    else
      alert(errormessage);

    if (blnforcecorrection)
    {
      field.select();
      field.focus();
    }
  }


  return true;
}




function getMonthDifference(strFieldNameOne, strFieldNameTwo, answerField)
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function getMonthDifference
// Description: This function finds the difference, in Months, given 2 dates.
//
// input -  strFieldNameOne:  name of text field with start date
//          strFieldNameTwo:  name of text field with end date
//          answerField:      name of text field answer will be written to.
//
// output - writes out answer value
//
// March 4, 2002
// Created by:     Heath Cleland
///////////////////////////////////////////////////////////////////////////////////////////////////////////
  if (!isEmpty(strFieldNameOne.value))
  {
    if (!isEmpty(strFieldNameTwo.value))
    {
// First find out if month is required to be round up.
// This may need to be removed.
        var offset = new Array(0,31,59,90,121,151,181,212,243,273,304,334);   // array of total days in year by month
        var numDaysInMonth = new Array(31,28,31,30,31,30,31,31,30,31,30,31);  // array of days in each month

        dteStartDate = new Date(strFieldNameOne.value);                       // Get Start Date (example - employee start date)
        dteEndDate   = new Date(strFieldNameTwo.value);                       // Get End Date (example - an expiration date)

        intTempMS = dteEndDate.getTime() - dteStartDate.getTime();            // convert milliseconds
        intDays = (intTempMS/(1000*60*60*24*(numDaysInMonth[dteStartDate.getMonth()])));
        fltMonthsRounded = intDays.toString().substr(0,3);

        //alert(dteStartDate.getDate());


        numMonths = intDays / 30;
        decPos = numMonths.toString().indexOf(".");

        if (decPos == -1){
          totalNumMonths    = numMonths;
        } else {
          if (numMonths.toString().substring(decPos+1, decPos + 2) != 0){
                if (numMonths < 1){
                  totalNumMonths  = numMonths.toString().substring(decPos, decPos +2);
                } else {
                  totalNumMonths  = numMonths.toString().substring(0, decPos +2);
                }
          } else {
              totalNumMonths  = numMonths.toString().substr(0,decPos);
          }
        }
 /*
        var Sdays = offset[dteStartDate.getMonth()];                          // number of days in first month
        var Edays = offset[dteEndDate.getMonth()];                            // number of days in last month

        var intTotalDaysInMonths = 0;                                         // counts number of days in each month between Start and End date.

          for ( mnthCntr = 0; mnthCntr < 12; mnthCntr++){
            if (offset[mnthCntr] >= Sdays){
              if (offset[mnthCntr] < Edays){
                intTotalDaysInMonths += numDaysInMonth[mnthCntr];                 // add days in Month (in array) to intTotalDaysInMonths counter.
              }
            }
          }


          Sdays += dteStartDate.getDate();                    // adds number of days in current month to days in year.
          Edays += dteEndDate.getDate();
          totalDays = Edays - Sdays;


          var intAddExtraMonth = 0;                           // Decides whether or not to round month up or not.
            if (totalDays > intTotalDaysInMonths){
              intAddExtraMonth = 1;
            }
*/
// begin calc on Total number of months
// Finds Full month, does not find down to day.


      var dteEndYear = dteEndDate.getFullYear();         // Find Year for the end date
      var dteStartYear = dteStartDate.getFullYear();     // Find Year for the start date

      var dteEndMonth = dteEndDate.getMonth();           // Find Month of the end Date
      var dteStartMonth = dteStartDate.getMonth();       // Find Month of the Start Date

      // Find Total number of months in both years
      intDiffStartYear = dteStartYear * 12 + dteStartMonth;
      intDiffEndYear = dteEndYear * 12 + dteEndMonth;

      intTotalNumMonths = intDiffEndYear - intDiffStartYear;

      //write value to answer Text Field
      //answerField.value = intTotalNumMonths + intAddExtraMonth;
      //answerField.value = fltMonthsRounded;
      //answerField.value = totalNumMonths;

      if (dteStartDate.getDate() == dteEndDate.getDate()){
        answerField.value = intTotalNumMonths;
      } else {
        answerField.value = fltMonthsRounded;
      }

    } else {
    //  alert("A date is required for "+ messageNameTwo);
    }
  } else {
  //  alert("A date is required for "+ messageName);
  }
}

function getMonthExpDate(strFieldNameOne, strFieldNameTwo, answerField)
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function getMonthDifference
// Description: This function finds the difference, in Months, given 2 dates.

// input -  strFieldNameOne:  name of text field with start date
//          strFieldNameTwo:  name of text field with end date
//          answerField:      name of text field answer will be written to.

// output - writes out answer value

// March 4, 2002
// Created by:     Heath Cleland
///////////////////////////////////////////////////////////////////////////////////////////////////////////
  if (!isEmpty(strFieldNameOne.value))
  {
    if (!isEmpty(strFieldNameTwo.value))
    {

    dteStartDate = new Date(strFieldNameOne.value);                                   // Get Start Date (example - employee start date)

    dteStartDate.setMonth(dteStartDate.getMonth()+ parseInt(strFieldNameTwo.value))   // add months to date

    answerField.value = (dteStartDate.getMonth()+1) + "/" + dteStartDate.getDate() + "/" + dteStartDate.getYear();  // display answer


    }

  }

}
