/******************************************************************************
 NetFanatics Standard Data Entry Validation Routines

 $Workfile: $    $Revision:  $

 Overview:  This file contains code for client side data type validation

         First in the file are functions names isXXX() the have no user interface
         but simply retrun true or false to indicate validity.
         You pass in a string only. These functions are intended to be called
         from the ValidXXX() functions (see below).

         Later in the file are functions named ValidXXX() that will inform the user
         with popup message box if data is in valid, and will set teh focus
         to the offeding input field. They also return true or false.
         You pass in a reference to a form input, value required flag, and
         displayable name for the field.

 Written by Charles Karow July 1999
 Modified by Christopher Karper, Jan 2000 for MileOne
 Modified by Christopher Karper, Apr 2000 for DealByNet
 Modified by Christopher Karper, Apr 2000 for MileOne
 Modified by Christopher Karper, May 2000 for DealByNet
 Modified by Shawn Tang,         Sep 2000 for HASP
 Copyright 1999-2000 by NetFanatics, Inc. All rights reserved

 Last changed: $Modtime: $ ($Date:  $ by $Author:  $)

Example usage:

1. Add this include to the <HEAD> section of your page:
<script LANGUAGE="JavaScript1.2" SRC="common/Validation.js"></script>

2. Create a function for form input validation. Include one call to a ValidXXX()
function for each input to be validated.

<script LANGUAGE="JavaScript1.2" SRC="common/Validation.js">
function ValidateForm(frm)
{
   if (!ValidCurrency(txtPayment, true, "Amount of Payment")) {return false;}
   if (!ValidDate(txtDate, true, "Date of Payment")) {return false;}
}
</script>

3. Call your validation function from the form's onSubmit event handler.
<FORM action="MyPage.asp" method="post" onSubmit="return ValidateForm(this)">
... inputs ...
</FORM>

******************************************************************************
Function Prototypes
******************************************************************************
   ValidTime(Field, bRequired, sFieldName)

   ValidText(Field, bRequired, sFieldName)

   ValidPositiveNumber(Field, bRequired, sFieldName, maxLen, maxDecimal)
    note: maxLen and maxDecimal are optional. Both must be supplied if needed

   ValidDate(Field, bRequired, sFieldName)
   
   ValidDateORText(Field, bRequired, sFieldName)

   ValidSSN(Field, bRequired, sFieldName)

   ValidPhoneNumber(Field, bRequired, sFieldName)

   ValidPositiveInteger(Field, bRequired, sFieldName)

   ValidInteger(Field, bRequired, sFieldName)

   ValidPostalCode(Field, bRequired, sFieldName)

   ValidEmail(Field, bRequired, sFieldName)

   ValidCurrency(Field, bRequired, sFieldName, maxLen)
    note: maxLen is optional
    
   ValidPercentage(Field, bRequired, sFieldName, maxLen)
    note: it is assumed that the percentage has two decimal numbers
    
   ValidSize(Field, bRequired, sFieldName, maxLen, maxDecimal)

   ValidTime(Field, bRequired, sFieldName)

   ValidSelect(Field, sFieldName)
   
   ValidTextArea(Field, bRequired, sFieldName, maxLen)
   
   CurrencyToNumber(iField)
   
   NumberToCurrency(num)
   
   PercentageToNumber(iField)
   
   NumberToPercentage(num)
   
   SizeToNumber(iField)
   
   NumberToSize(num)
   
   formatPhoneNumber(iField)

   formatPostalCode(iField)
******************************************************************************/

// general purpose function to see if a suspected numeric input
// is a positive integer
function isPosInteger(inputVal)
{
    inputStr = inputVal.toString()
    for (var i = 0; i < inputStr.length; i++)
        {
        var oneChar = inputStr.charAt(i)
        if (oneChar < "0" || oneChar > "9")
            {
            return false
            }
        }
    return true
}

// general purpose function to see if a suspected numeric input
// is a positive or negative integer
function isInteger(inputVal)
{
    inputStr = inputVal.toString()
    for (var i = 0; i < inputStr.length; i++)
        {
        var oneChar = inputStr.charAt(i)
        if (i == 0 && oneChar == "-")
            {
            continue
            }
        if (oneChar < "0" || oneChar > "9")
            {
            return false
            }
        }
    return true
}

// Determines whether a number is zero
function isZero(inputVal)
{
    return parseFloat(inputVal) == 0;
}

// general purpose function to see if a suspected numeric input
// is a positive or negative number
function isNumber(inputVal)
{
    oneDecimal = false
    inputStr = inputVal.toString()
    for (var i = 0; i < inputStr.length; i++)
        {
        var oneChar = inputStr.charAt(i)
            if (i == 0 && oneChar == "-")
            {
            continue
            }
        if (oneChar == "." && !oneDecimal)
            {
            oneDecimal = true
            continue
            }
        if (oneChar < "0" || oneChar > "9")
            {
            return false
            }
        }

    return true
}

// another general purpose function to see if a suspected numeric input
// is a positive or negative number
function isNumber2(inputValue)
{
    if (isNaN(parseFloat(inputValue)))
        {
        alert("The value you entered is not a number.")
        return false
        }
    return true
}

// general purpose function to see if a suspected numeric input
// is a positive number
function isPosNumber(inputVal)
{
    oneDecimal = false
    inputStr = inputVal.toString()
    for (var i = 0; i < inputStr.length; i++)
        {
        var oneChar = inputStr.charAt(i)

        if (oneChar == "." && !oneDecimal)
            {
            oneDecimal = true
            continue
            }
        if (oneChar < "0" || oneChar > "9")
            {
            return false
            }
        }

    return true
}

// function to see if the decimal place is <= maximum decimal number
function isDecimal(inputVal, maxDecimal)
{
    inputStr = inputVal.toString()
    var rArray = inputStr.split(".");
    if (rArray.length > 2){return false;}
    if (rArray.length == 2)
    {
        if (rArray[1].length > maxDecimal)
           return false;
    }
    return true;
}

// function to see if the number exceeds the maximum length 
// in the database, including decimal number
// Note: this function DOES NOT count the decimal point
function isDBNumber(inputVal, maxLen, maxDecimal)
{
    inputStr = inputVal.toString()
    var rArray = inputStr.split(".");
    if (rArray.length > 2){return false;}
    if (rArray.length <= 2)
    {
    if (rArray[0].length > (maxLen-maxDecimal)){return false;}
    }
    return true;
}

// function to see if input is a valid Tax ID number.
function isTaxID(strInput)
{
    // Tax id should be nn-nnnnnnn.
    // Be sure there is a dash.
    var dash1 = strInput.indexOf("-")
    if (dash1 == -1)
        {return false}

    // Extract the two parts of the tax id.
    if (dash1 == 2)
        {
        var taxid1 = parseInt(strInput.substring(0, dash1), 10)
        var taxid2 = parseInt(strInput.substring(dash1+2, strInput.length), 10)
        if (isNaN(taxid1) || isNaN(taxid2))
            {
            // There is a non-numeric character in one of the component values.
            alert("NaN: The Tax ID entry is not in an acceptable format.\n\nYou should enter the Tax ID number as nn-nnnnnnn.")
            return false
            }

        }
    else
        {
            // There are no dashes or they are in the wrong places.
            alert("Bad Dash: The Tax ID entry is not in an acceptable format.\n\nYou should enter the Tax ID number as nn-nnnnnnn.")
            return false
         }
    return true;
}

// function to see if input is valid US Social Security Number
function isSSN(strInput)
{
    // SSN should be nnn-nn-nnnn

    // Be sure there are two dashes
    var dash1 = strInput.indexOf("-")
    var dash2 = strInput.lastIndexOf("-")
    if (dash1 == -1 || dash1 == dash2)
        {return false}

    // Extract the tree paqrts of the SSN
    if (dash1 == 3 && dash2 == 6)
        {
        var SSN1 = parseInt(strInput.substring(0, dash1), 10)
        var SSN2 = parseInt(strInput.substring(dash1+2, dash2), 10)
        var SSN3 = parseInt(strInput.substring(dash2+2, strInput.length), 10)
        if (isNaN(SSN1) || isNaN(SSN2) || isNaN(SSN3))
            {
            // there is a non-numeric character in one of the component values
            alert("NaN: The SSN entry is not in an acceptable format.\n\nYou should enter SSN as nnn-nn-nnnn.")
            return false
            }

        }
    else
        {
            // there are no dashes or they are in the wrong places
            alert("Bad Dash: The SSN entry is not in an acceptable format.\n\nYou should enter SSN as nnn-nn-nnnn.")
            return false
         }
    return true;
}

// Replaces the first occurrance of chFind with chReplacement in strInput
// and returns the result.
//
// Used in isDate() and isPhone()
function replaceString(strInput, chFind, chReplacement)
{
    var i = strInput.indexOf(chFind)
    var str = strInput.substring(0, i) + chReplacement + strInput.substring(i + 1, strInput.length)

    return str;
}

// date field validation
function isDate(inputValue)
{
    var inputStr = inputValue.toString()

    if (isNaN(Date.parse(inputStr)))   {
       return(false);
    }
    var datInput = new Date(Date.parse(inputStr))

    // CMK - 22 MAY 2000 - Added check to disallow 5 or more digit years.
  // JWR - 23 AUG 2001 - Added check to ensure 4-digit year at least.
  var year = datInput.getFullYear();
    if ( (year > 9999) || (year < 1000) ) {
       return(false);
    }

    //cwbutler - 6/5/2000 - Added to handle "9/31/2000", etc
    //first thing - zap all leading zeros
    var sFixDate = inputStr;
    sFixDate = sFixDate.replace(/^0/,'');
    sFixDate = sFixDate.replace(/\/0+/,'/');
    sFixDate = sFixDate.replace(/\/0+/,'/');
    
    //second thing, get the date JavaScript THINKS it has
    // use getFullYear() instead of getYear() for Netscape and IE. modified 9/8/00 STang
    var sCompDate = (datInput.getMonth() + 1) + "/" + datInput.getDate() + "/" + datInput.getFullYear();

    //finally, make sure they're the same
    if (sCompDate != sFixDate)
    {
        //cuz if they're not, it's an error
        return(false);
    }

    return(true);
}

// Function to see  if input is valid US phone number
function isPhone(strInput) {
   //CMK - 20 Apr 2000 - Rewrote function to accept following formats:
   // (111) 111-1111 Parenthesis with dash
   // 111-111-1111 Dashes
   // 111 111 1111 Spaces
   // 1111111111 No separation characters
   // 111.111.1111 Dots
   // 111-111-1111, X1111 Extension

   var inputStr = strInput.toString();
   var strFormatMsg = "The phone entry is not in an acceptable format.\n\nPlease enter phone numbers in the following format ###-###-####.";

   //This RegExp removes all dashes, parens, spaces, and dots from the string.
   inputStr = inputStr.replace(/[\-\)\(\.\ ]/g, '');

   if (inputStr.length < 10) {return false;}

   var AreaCode = parseInt(inputStr.substr(0, 3), 10)
   var CO = parseInt(inputStr.substr(3, 3), 10)
   var Number = parseInt(inputStr.substr(6, 4), 10)

   if (isNaN(AreaCode) || isNaN(CO) || isNaN(Number)) {return false;}
   if (AreaCode < 100 || AreaCode > 999)  {return false;}
   if (CO < 100 || CO > 999)  {return false;}
   if (Number < 0 || Number > 9999) {return false;}

   return true;
}

// Check whether string s is empty.

function isEmpty(s)
{
   return ((s == null) || (s.length == 0))
}

// Returns true if string s is empty or
// whitespace characters only.

function isWhitespace (s)
{
    var i;

   // whitespace characters
   var whitespace = " \t\n\r";

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

// function to see if input is valid for US 
// function strips out certain chars and then validates the zip code
// for either 5 or 9 digits
function isPostalCode(s)
{
  var sPart1
  var sPart2
  var zipStr = s.toString();

  // Strip out characters that might be in zip code field 
  // Strip out dash, space, period, comma, slash, backslash, pound
  zipStr = zipStr.replace(/[\-\ \.\,\\\/\#]/g, '');
 
  if (zipStr.length == 5 && isPosInteger(zipStr)) {return true;}

  if (zipStr.length == 9) {

       // Is it an extended zip code
       sPart1 = zipStr.substring(0,5);
       sPart2 = zipStr.substring(5,9);

       if (isPosInteger(sPart1) == true && isPosInteger(sPart2) == true)
            {return true;
            }
       else
       {return false;}
  }

  // Otherwise its not OK!
  return false;
}

// Return true/false if given value is a valid 5-digit or 9-digit U.S. postal code;
//    allows partial values to enable querying; valid inputs are:
//    9????,   where ? == an optional numeric character
//    99999-9??? where ? == an optional numeric character
// All other combinations are not valid. Assumes input value contains no characters.
function isQueryPostalCode (val)
{ 
  // Don't let the string end in a Dash
  if (val.charAt(val.length-1) == '-')
  { return false;
  }
  
  // Tokenize around the 'dash' for a 9-digit #####-#### pc
  var pcParts = val.split (/[\-]/);
  
  if (pcParts.length == 2)
  {
    // First part MUST be 5 in length
    if (pcParts[0].length == 5 && isPosInteger (pcParts[0]))
    { // Second part may be 1-4 numeric characters
      if (pcParts[1].length > 0 && pcParts[1].length <= 4 && isPosInteger (pcParts[1]))
      { return true;
      }
      else
      { return false;
      }
    }
    else
    { return false;
    }
  }
  else if (pcParts.length == 1)
  { // There is no second part - first part may be 5 chars or less
    if (pcParts[0].length > 0 && pcParts[0].length <= 5 && isPosInteger (pcParts[0]))
    { return true;
    } 
    else
    { return false;
    }
  }
  else
  { // We're not sure what user entered but it wasn't what we expected
    return false;
  }
}

function isURL(s)
{
  // Is it empty?
  if (isWhitespace(s))
    return false;

  var Http = s.indexOf('http');
  var Ftp = s.indexOf('ftp');
  var Colon = s.indexOf(':');
  var Slashes = s.indexOf('//');
  var Space = s.indexOf(' ');

  if ( ((Http == 0) || (Ftp == 0)) &&
       (Colon != -1) &&
     (Slashes != -1) &&
       (Colon < Slashes) &&
       (Space == -1) )
    return true;
  else
    return false;
}

//
function isEmail (s)
{
    // is s whitespace?
    if (isWhitespace(s)) return false;

    // there must be >= 1 character before @, so we
    // start looking at character position 1
    // (i.e. second character)
    var i = 1;
    var nLength = s.length;

    // look for @
    while ((i < nLength) && (s.charAt(i) != "@"))
    { i++
    }
   // The must be something after the @
    if ((i >= nLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < nLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= nLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

//
// Function isTime()
// Returns true if the given string contains a valid 12 hour time.
//
function isTime(s)
{
   // HH:MM
   // HH = 1 - 12, MM = 0 - 59

   // Find colon and space -- be sure they're in the right places
    var iColon = s.indexOf(":")

   // h:mm am or hh:mm am
   if (iColon != 2 && iColon != 1) {return false;}

   // Get the hours, minutes and am/pm
    var hh = s.substring(0, iColon);
    var mm = s.substring(iColon + 1);
    
    if ((!isInteger(hh)) || (!isInteger(mm)))
        {
        // there is a non-numeric character in one of the component values
        return false
        }

   // Be sure values are in range
   if (hh < 1 || hh > 12) { return false; }
    if (mm < 0 || mm > 59) { return false; }

   return true;
}

function isCurrency(s)
{
   // Allow "$", ",", "_" -- ignore it
   for (i=0; i<s.length; i++){
      if((i == 0) && (s.charAt(i) == "-")){}
    else if((i == 1) && (s.charAt(i - 1) == "-") && (s.charAt(i) == "$")){}
    else if((i == 1) && (s.charAt(i - 1) == "$") && (s.charAt(i) == "-")){}
      else if ((i > 1) && (s.charAt(i) == "$"))
         return false;
      else if ((i > 1) && (s.charAt(i) == "-"))
       return false;
   }
   var cu = replaceString(s, "$", "");
   if (cu == ""){return false;}
   var nu = cu.replace(/,/g, "");
   if (!isNumber(nu)){return false;}
   if (!isDecimal(nu, 2)){return false;}
   return true;
}

function addComma(num){
   var str = num.toString();
   strArray = new Array();
   for (i=0; i<str.length; i++){
      strArray[i] = str.charAt(i);
   }
   for (j=(strArray.length-3); j>0; j--){
       strArray[j-1] = strArray[j-1]+"@";
       j=j-2;
   }
   return (strArray.toString().replace(/,/g, "").replace(/@/g, ","));
}

function addDollar(str){
   return ("$".concat(str));
}

function makeTwoDecimal(str){
   if (str.length == 1)
      return (str+"0");
   else
      return str;
}
//*****************************************************************************
//  User interface functions (ValidXXX())
//*****************************************************************************

function ValidText(Field, bRequired, sFieldName)
{
   if (bRequired && isWhitespace(Field.value))
   //if (bRequired && (Field.value == ""))
      {
      alert("Field '" + sFieldName + "' is required.");
      Field.focus();
      return false;
      }

   return true;
}

function ValidPositiveNumber(Field, bRequired, sFieldName, maxLen, maxDecimal)
{
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }

   if (!isPosNumber(Field.value))
      {
      alert("You must supply a valid number" + sName + ".");
      Field.focus();
      Field.select();
      return false;
      }
   if ((maxLen > 0) && (maxDecimal > 0))
   {
  if (!isDBNumber(Field.value, maxLen, maxDecimal))
  {
  alert("The number you supplied" + sName + " is too large.");
  Field.focus();
  Field.select();
  return false;
  }

  if (!isDecimal(Field.value, maxDecimal))
  {
  alert("You must supply a valid number" + sName + " with decimal place less than " + (maxDecimal+1));
  Field.focus();
  Field.select();
  return false;
  }
   }  
    
   return true;
}

function ValidDate(Field, bRequired, sFieldName)
{
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = "for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("You must supply a valid date " + sName + ".\nThe format is MM/DD/YYYY.");
      Field.focus();
      return false;
      }

   if (Field.value != "")
      {
      if (!isDate(Field.value))
         {
         alert("You must supply a valid date " + sName + " with a 4 digit year. The format is MM/DD/YYYY");
         Field.focus();
         Field.select();
         return false;
         }
      }
   return true;
}

// This function validates date or a text. The user can enter any text. If the text contains a '/'
// it is assumed that the user is entering a proper date. In that case the string is validated to a date.

function ValidDateORText(Field, bRequired, sFieldName)
{
   var sName = sFieldName;
   var sValue = Field.value;
   var bDate = false;
   if (sFieldName == "") {sName = ""} else {sName = "for " + sFieldName}

   if (bRequired && isWhitespace(Field.value)) {
      alert("You must supply a valid date or text" + sName + ".\nIf date, the format is MM/DD/YYYY.");
      Field.focus();
      return false;
   }
   if (sValue != ""){
      for (i=0; i<sValue.length; i++){
        if ((i != 0) && (sValue.charAt(i) == "/"))
         bDate = true
      }

      if ((bDate == true) && (!isDate(sValue))){
         alert("You must supply a valid date or text" + sName + ". If date, the format is MM/DD/YYYY");
         Field.focus();
         Field.select();
         return false;
      }
   }
   return true;
}

function ValidYear(Field, bRequired, sFieldName)
{
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
         if (!isPosInteger(Field.value) || Field.value.length < 4)
            {
            alert("You must supply a valid 4 digit year" + sName + ".");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidTaxID(Field, bRequired, sFieldName)
{
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
         if (!isTaxID(Field.value))
            {
            alert("You must supply a valid Tax ID or EIN number" + sName + ". The format is NN-NNNNNNN.");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidSSN(Field, bRequired, sFieldName)
{
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
         if (!isSSN(Field.value))
            {
            alert("You must supply a valid Social Security Number" + sName + ". The format is NNN-NN-NNNN.");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidPhoneNumber(Field, bRequired, sFieldName)
{
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
         if (!isPhone(Field.value))
            {
            //CMK - 13 Apr 2000 - changed error message to use more common dash format.
            alert("You must supply a valid phone number" + sName + ". \nThe format should be ###-###-####.");  //CMK - 13 Apr 2000
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidPositiveInteger(Field, bRequired, sFieldName)
{
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   // Added on 02/14/2002 by MK
   // If the field is required, the integer cannot be zero
   if (bRequired && (isWhitespace(Field.value) || isZero(Field.value)))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
         if (!isPosInteger(Field.value))
            {
            alert("You must supply a valid number" + sName + ".");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidInteger(Field, bRequired, sFieldName)
{
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
         if (!isInteger(Field.value))
            {
            alert("You must supply a valid number" + sName + ".");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidPostalCode(Field, bRequired, sFieldName)
{
   var sName = sFieldName

   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }
   if (Field.value != "")
         {
         if (!isPostalCode(Field.value))
            {
            alert("Invalid postal code entered "  + sName + ".  Valid Format is '99999' or '99999-9999'" + ".");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

// Given a list field delimited by spaces, commas, or semi-colons,
//   parse the list into tokens and verify that each token is a valid
//   PostalCode, suitable for querying against (i.e. allowing partial values).
// Whitespace input qualifies as a Positive result unless bRequired is specified as true.
function ValidPostalCodeQueryList(Field, bRequired, sFieldName)
{
  // Tokenize around these delimiters
  var zipArray = Field.value.split (/[\,,\ ]/);
  var i=0;
  
  if (zipArray.length == 0 && bRequired)
  { alert("A value is required for field " + sFieldName + ".");
        Field.focus();
        return false;
    }
  
  while (i < zipArray.length) 
  { // This positive clause is only necessary because the split() method returns 
    //    an empty first token when in fact no tokens exist in given Field
    if (isWhitespace(zipArray[i]))
      { 
      if (bRequired)
          { alert("A value is required for field " + sFieldName + ".");
            Field.focus();
            return false;
          }
    } 
    else
    { if (!isQueryPostalCode (zipArray[i]))
      { alert("Invalid postal code entered in field "  + sFieldName + 
            ".\nEach entry must use format '99999' or '99999-9999'." +
            "\nYou may use less digits to search by partial postal codes.");
              Field.focus();
              Field.select();
              return false;
      }
    }
    i++;
  }
    return true;
}

function ValidEmail(Field, bRequired, sFieldName)
{
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
         if (!isEmail(Field.value))
            {
            alert("You must supply a valid email address" + sName + ". <user>@<organization>.<domain>");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidURL(Field, bRequired, sFieldName)
{
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
         if (!isURL(Field.value))
            {
            alert("You must supply a valid URL" + sName + " in the form http://domainname.");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidCurrency(Field, bRequired, sFieldName, maxLen)
{
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }

   if (Field.value != "")
   {
      if (!isCurrency(Field.value))
         {
         alert("You must supply a valid currency value" + sName + ".");
         Field.focus();
         Field.select();
         return false;
         }
    
       if (maxLen > 0)
       {
           if (!isDBNumber(CurrencyToNumber(Field), maxLen, 2))
             {
             alert("The number you supplied" + sName + " is too large.");
             Field.focus();
             Field.select();
             return false;
             }
       }
    }  
   return true;
}

function ValidPercentage(Field, bRequired, sFieldName, maxLen)
{
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }

   if (Field.value != "")
   {
      var num = Field.value.replace(/%/g, "");
      if (!isPosNumber(num))
         {
         alert("You must supply a valid percentage value" + sName + ".");
         Field.focus();
         Field.select();
         return false;
         }
    
       if (maxLen > 0)
       {
           if (!isDBNumber(num, maxLen, 2))
             {
             alert("The number you supplied" + sName + " is too large.");
             Field.focus();
             Field.select();
             return false;
             }
       }
    }  
   return true;
}

function ValidSize(Field, bRequired, sFieldName, maxLen, maxDecimal)
{
   var tmpSize = Field.value;
   var num = SizeToNumber(Field);
   Field.value = num;
   if (!ValidPositiveNumber(Field, bRequired, sFieldName, maxLen, maxDecimal)) 
   {
      Field.value = tmpSize;
      return false;
   }
   return true;
}

function ValidTime(Field, bRequired, sFieldName)
{
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
         if (!isTime(Field.value))
            {
            alert("You must supply a valid time" + sName + ". (HH:MM)");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

// function added for common Netscape and IE behavior for Select 
function ValidSelect(Field, sFieldName){
    if (isWhitespace(Field.options[Field.selectedIndex].value) || Field.options[Field.selectedIndex].value == "") {
      alert("Please Select a " + sFieldName);
          Field.focus();
          return false;
    }
    return true;
}

function ValidTextArea(Field, bRequired, sFieldName, maxLen)
{  
   var sName = sFieldName
   if (sFieldName == "") {sName = ""} else {sName = " for " + sFieldName}

   if (bRequired && isWhitespace(Field.value))
      {
      alert("A value is required" + sName + ".");
      Field.focus();
      return false;
      }

   if (Field.value != "")
   {
      var textLength = Field.value.length;
      if (textLength > maxLen)
      {
         alert("Field '" + sFieldName + "' contains too many characters. \nThe maximum characters in this field is "+maxLen);
         Field.focus();
         Field.select();
         return false;
      }
    }  
   return true;
}

function isSelectionMade(field,  indexExcluded)
{
   // Contact Method Edit

   var i
   var bSelection = false
   var nEntries = field.length
   for (i=0;(i<nEntries);i++)
                        {
                                if (field[i].selected == true)
                                        {
                  if (i  != indexExcluded) {
                                              bSelection = true;
                     }
                                        }
                        }
   if (bSelection == false)
      {
      return false;
      }
   else
      {
      return true;
      }
}

// strip "$" and "," from currency
function CurrencyToNumber(iField)
{
   var n = replaceString(iField.value, "$", "");
   return n.replace(/,/g, "");
}

function NumberToCurrency(num){
   if (num == "")
      return num;
      
   newArray = new Array();
   var money = null;

   if (num.toString().indexOf("\.") > -1){
      newArray = num.split(".");
      money = addComma(newArray[0])+"."+makeTwoDecimal(newArray[1]);
      money = addDollar(money);
   }
   else{
      money = addComma(num);
      money = money.concat(".00");
      money = addDollar(money);
   }
   return money;
}

function NumberToCurrency2(num){
   if (num == "")
      return num;
      
   newArray = new Array();
   var money = null;

   if (num.toString().indexOf("\.") > -1){
      newArray = num.split(".");
      money = addComma(newArray[0])+"."+makeTwoDecimal(newArray[1]);
   }
   else{
      money = addComma(num);
      money = money.concat(".00");
   }
   return money;
}  

function PercentageToNumber(iField)
{
   var n = iField.value;
   return n.replace(/%/g, "");
}

function NumberToPercentage(num){
   if (num == "")
      return num;
      
   newArray = new Array();
   var perc = null;

   if (num.toString().indexOf("\.") > -1){
      newArray = num.split(".");
      if (newArray[1] == 0)
        perc = newArray[0];
      else
        perc = num;
   }
   
   return (perc + "%");
}   

function SizeToNumber(iField)
{
   var n = iField.value;
   return n.replace(/,/g, "");
}

function NumberToSize(num){
   if (num == "")
      return num;
      
   newArray = new Array();
   var size = null;

   if (num.toString().indexOf("\.") > -1){
      newArray = num.split(".");
      if (newArray[1] == 0)
        size = addComma(newArray[0]);
      else
        size = addComma(newArray[0])+"."+newArray[1];
   }
   else{
      size = addComma(num);
   }
   return size;
}   

// Function to highlight the current value in a Drop Down List Box

function selectListValue(list, value)
{
   for (var ctr=0;ctr<list.length;ctr++)
   {
      if (list.options[ctr].value==value)
      {
         list.options[ctr].selected=true;
      }
   }
}

function formatPhoneNumber(iField) {
// given a VALID phone number (one that has passed validation using ValidPhoneNumber() )
// strip "-", "(", ")", ".", " " from string
// and reformat using ###-###-####
   if (iField.value == "")
      return "";
   var inputStr = iField.value.toString();
 
   // This RegExp removes all dashes, parens, spaces, and dots from the string.
   inputStr = inputStr.replace(/[\-\)\(\.\ \,]/g, '');
 
   var AreaCode = inputStr.substr(0, 3);
   var CO = inputStr.substr(3, 3);
   var Number = inputStr.substr(6, 4);
   var Extra = inputStr.substr(10);  // Added 03/25/2002 by MK.  Used for extensions
 
   return (AreaCode + "-" + CO + "-" + Number + ((Extra != "") ? ", " + Extra : ""));
}

function ValidPositiveCurrency(Field, bRequired, sFieldName, maxLen) {
   if (!ValidCurrency(Field, bRequired, sFieldName, maxLen)) {
    return false;
  }
  else {
      var feeNumber = CurrencyToNumber(Field);
      if (!isPosNumber(feeNumber)) {
        alert("You must supply a positive " + sFieldName + " amount");
        Field.focus();
        Field.select();
        return false;
      } else 
        return true;
  }
}

// function accepts a field that has been validated by ValidPostalCode
// and formats it to either 5 digit ##### or 9 digit #####-#### zip code
function formatPostalCode(iField){
  var sPart1;
  var sPart2;
  var zipStr = iField.value.toString();

  // Strip out characters that might be in zip code field and leave numbers
  // Strip out dash, space, period, comma, slash, backslash, pound
  zipStr = zipStr.replace(/[\-\ \.\,\\\/\#]/g, '');

  if (zipStr.length == 5 ) 
    return(zipStr);

  if (zipStr.length == 9) {

     // its an extended zipStr code
     sPart1 = zipStr.substring(0,5);
     sPart2 = zipStr.substring(5,9);

     return(sPart1 + "-" + sPart2)
  }
}


// valid ssn search string
function ValidSSNSearchString(Field, bRequired, sFieldName)
{
	var sName = sFieldName;
	
	if (sFieldName == "") {sName = ""} else {sName = "for " + sFieldName}
	
	if (bRequired && isWhitespace(Field.value))
	{
	 
	
		alert("You must supply a valid number " + sName + ".");
		Field.focus();
		return false;
	}
	
	if (Field.value != "")
    {
		var ssnStr = Field.value;
		ssnStr = ssnStr.replace(/[\-\ \.\,\\\/\#]/g, '');
		if (!isNumber(ssnStr))
   		{
      		alert("You must supply a valid number " + sName + ssnStr +".");
			Field.focus();
         	Field.select();
			return false;
		}
	}
	return true;
}
// End of Validation.js


