// li.js (from MCMIS.js)
//
// SUMMARY
//
// This is a set of JavaScript functions for validating input on 
// an HTML form.  Functions are provided to validate:
//
//      - U.S. and international phone/fax numbers
//      - U.S. ZIP codes (5 or 9 digit postal codes)
//      - U.S. Postal Codes (2 letter abbreviations for names of states)
//      - U.S. Social Security Numbers (abbreviated as SSNs)
//      - email addresses
//      - dates (entry of year, month, and day and validity of combined date)
//
// Supporting utility functions validate that:
//
//      - characters are Letter, Digit, or LetterOrDigit
//      - strings are a Signed, Positive, Negative, Nonpositive, or
//        Nonnegative integer
//      - strings are a Float or a SignedFloat
//      - strings are Alphabetic, Alphanumeric, or Whitespace
//      - strings contain an integer within a specified range
//
// Functions are also provided to interactively check the
// above kinds of data and prompt the user if they have
// been entered incorrectly.
//
// Other utility functions are provided to:
//
//      - remove from a string characters which are/are not 
//        in a "bag" of selected characters     
//      - reformat a string, adding delimiter characters
//      - strip whitespace/leading whitespace from a string
//      - reformat U.S. phone numbers, ZIP codes, and Social
//        Security numbers
//
//
// Many of the below functions take an optional parameter eok (for "emptyOK")
// which determines whether the empty string will return true or false.
// Default behavior is controlled by global variable defaultEmptyOK.
//
// BASIC DATA VALIDATION FUNCTIONS:
//
// isWhitespace (s)                    Check whether string s is empty or whitespace.
// isLetter (c)                        Check whether character c is an English letter 
// isDigit (c)                         Check whether character c is a digit 
// isLetterOrDigit (c)                 Check whether character c is a letter or digit.
// isInteger (s [,eok])                True if all characters in string s are numbers.
// isSignedInteger (s [,eok])          True if all characters in string s are numbers; leading + or - allowed.
// isPositiveInteger (s [,eok])        True if string s is an integer > 0.
// isNonnegativeInteger (s [,eok])     True if string s is an integer >= 0.
// isNegativeInteger (s [,eok])        True if s is an integer < 0.
// isNonpositiveInteger (s [,eok])     True if s is an integer <= 0.
// isFloat (s [,eok])                  True if string s is an unsigned floating point (real) number. (Integers also OK.)
// isSignedFloat (s [,eok])            True if string s is a floating point number; leading + or - allowed. (Integers also OK.)
// isAlphabetic (s [,eok])             True if string s is English letters 
// isAlphanumeric (s [,eok])           True if string s is English letters and numbers only.
// 
// isSSN (s [,eok])                    True if string s is a valid U.S. Social Security Number.
// isUSPhoneNumber (s [,eok])          True if string s is a valid U.S. Phone Number. 
// isInternationalPhoneNumber (s [,eok]) True if string s is a valid international phone number.
// isZIPCode (s [,eok])                True if string s is a valid U.S. ZIP code.
// isStateCode (s [,eok])              True if string s is a valid U.S. Postal Code
// isEmail (s [,eok])                  True if string s is a valid email address.
// isYear (s [,eok])                   True if string s is a valid Year number.
// isIntegerInRange (s, a, b [,eok])   True if string s is an integer between a and b, inclusive.
// isMonth (s [,eok])                  True if string s is a valid month between 1 and 12.
// isDay (s [,eok])                    True if string s is a valid day between 1 and 31.
// daysInFebruary (year)               Returns number of days in February of that year.
// isDate (year, month, day)           True if string arguments form a valid date.
// checkRequiredFieldsForNull(form)    True if all required text fields are filled in.


// FUNCTIONS TO REFORMAT DATA:
//
// stripCharsInBag (s, bag)            Removes all characters in string bag from string s.
// stripCharsNotInBag (s, bag)         Removes all characters NOT in string bag from string s.
// stripWhitespace (s)                 Removes all whitespace characters from s.
// stripInitialWhitespace (s)          Removes initial (leading) whitespace characters from s.
// reformat (TARGETSTRING, STRING,     Function for inserting formatting characters or
//   INTEGER, STRING, INTEGER ... )       delimiters into TARGETSTRING.                                       
// reformatZIPCode (ZIPString)         If 9 digits, inserts separator hyphen.
// reformatSSN (SSN)                   Reformats as 123-45-6789.
// reformatUSPhone (USPhone)           Reformats as (123) 456-789.


// FUNCTIONS TO PROMPT USER:
//
// prompt (s)                          Display prompt string s in status bar.
// promptEntry (s)                     Display data entry prompt string s in status bar.
// warnEmpty (theField, s)             Notify user that required field theField is empty.
// warnInvalid (theField, s)           Notify user that contents of field theField are invalid.
// checkRequiredFieldsForNull(form)    Notify user that empty required text fields must be filled in, and give their names.

// FUNCTIONS TO INTERACTIVELY CHECK FIELD CONTENTS:
//
// checkString (theField, s [,eok])    Check that theField.value is not empty or all whitespace.
// checkStateCode (theField)           Check that theField.value is a valid U.S. state code.
// checkZIPCode (theField [,eok])      Check that theField.value is a valid ZIP code.
// checkUSPhone (theField [,eok])      Check that theField.value is a valid US Phone.
// checkInternationalPhone (theField [,eok])  Check that theField.value is a valid International Phone.
// checkEmail (theField [,eok])        Check that theField.value is a valid Email.
// checkSSN (theField [,eok])          Check that theField.value is a valid SSN.
// checkYear (theField [,eok])         Check that theField.value is a valid Year.
// checkMonth (theField [,eok])        Check that theField.value is a valid Month.
// checkDay (theField [,eok])          Check that theField.value is a valid Day.
// checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
//                                     Check that field values form a valid date.
// getRadioButtonValue (radio)         Get checked value from radio button.


// VARIABLE DECLARATIONS

var digits = "0123456789";

var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"

var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"


// whitespace characters
var whitespace = " \t\n\r";


// decimal point character differs by language and culture
var decimalPointDelimiter = "."


// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";


// characters which are allowed in US phone numbers
var validUSPhoneChars = digits + phoneNumberDelimiters;


// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = digits + phoneNumberDelimiters + "+";


// non-digit characters which are allowed in 
// Social Security Numbers
var SSNDelimiters = "- ";



// characters which are allowed in Social Security Numbers
var validSSNChars = digits + SSNDelimiters;



// U.S. Social Security Numbers have 9 digits.
// They are formatted as 123-45-6789.
var digitsInSocialSecurityNumber = 9;



// U.S. phone numbers have 10 digits.
// They are formatted as 123 456 7890 or (123) 456-7890.
var digitsInUSPhoneNumber = 10;



// non-digit characters which are allowed in ZIP Codes
var ZIPCodeDelimiters = "-";



// our preferred delimiter for reformatting ZIP Codes
var ZIPCodeDelimeter = "-"


// characters which are allowed in Social Security Numbers
var validZIPCodeChars = digits + ZIPCodeDelimiters



// U.S. ZIP codes have 5 or 9 digits.
// They are formatted as 12345 or 12345-6789.
var digitsInZIPCode1 = 5
var digitsInZIPCode2 = 9


// CONSTANT STRING DECLARATIONS
// (grouped for ease of translation and localization)

// m is an abbreviation for "missing"

var mPrefix = "You did not enter a value into the "
var mSuffix = " field. This is a required field. Please enter it now."

// s is an abbreviation for "string"

var sUSLastName = "Last Name"
var sUSFirstName = "First Name"
var sWorldLastName = "Family Name"
var sWorldFirstName = "Given Name"
var sTitle = "Title"
var sCompanyName = "Company Name"
var sUSAddress = "Street Address"
var sWorldAddress = "Address"
var sCity = "City"
var sStateCode = "State Code"
var sWorldState = "State, Province, or Prefecture"
var sCountry = "Country"
var sZIPCode = "ZIP Code"
var sWorldPostalCode = "Postal Code"
var sPhone = "Phone Number"
var sFax = "Fax Number"
var sDateOfBirth = "Date of Birth"
var sExpirationDate = "Expiration Date"
var sEmail = "Email"
var sSSN = "Social Security Number"
var sOtherInfo = "Other Information"


// i is an abbreviation for "invalid"

var iStateCode = "This field must be a valid two character U.S. state abbreviation (like CA for California). Please reenter it now."
var iZIPCode = "This field must be a 5 or 9 digit U.S. ZIP Code (like 94043). Please reenter it now."
var iUSPhone = "This field must be a 10 digit U.S. phone number (like 415 555 1212). Please reenter it now."
//var iWorldPhone = "This field must be a valid international phone number. Please reenter it now."
var iWorldPhone = "This field must be a valid phone/fax number. Please reenter it now."
var iSSN = "This field must be a 9 digit U.S. social security number (like 123 45 6789). Please reenter it now."
var iEmail = "This field must be a valid email address (like foo@bar.com). Please reenter it now."

var iDay = "This field must be a day number between 1 and 31.  Please reenter it now."
var iMonth = "This field must be a month number between 1 and 12.  Please reenter it now."
var iYear = "This field must be a 2 or 4 digit year number.  Please reenter it now."
var iDatePrefix = "The Day, Month, and Year for "
var iDateSuffix = " do not form a valid date.  Please reenter them now."



// p is an abbreviation for "prompt"

var pEntryPrompt = "Please enter a "
var pStateCode = "2 character code (like CA)."
var pZIPCode = "5 or 9 digit U.S. ZIP Code (like 94043)."
var pUSPhone = "10 digit U.S. phone number (like 415 555 1212)."
var pWorldPhone = "international phone number."
var pSSN = "9 digit U.S. social security number (like 123 45 6789)."
var pEmail = "valid email address (like foo@bar.com)."

var pDay = "day number between 1 and 31."
var pMonth = "month number between 1 and 12."
var pYear = "2 or 4 digit year number."


// Global variable defaultEmptyOK defines default return value 
// for many functions when they are passed the empty string. 
// By default, they will return defaultEmptyOK.
//
// defaultEmptyOK is false, which means that by default, 
// these functions will do "strict" validation.  Function
// isInteger, for example, will only return true if it is
// passed a string containing an integer; if it is passed
// the empty string, it will return false.
//
// You can change this default behavior globally (for all 
// functions which use defaultEmptyOK) by changing the value
// of defaultEmptyOK.
//
// Most of these functions have an optional argument emptyOK
// which allows you to override the default behavior for 
// the duration of a function call.
//
// This functionality is useful because it is possible to
// say "if the user puts anything in this field, it must
// be an integer (or a phone number, or a string, etc.), 
// but it's OK to leave the field empty too."
// This is the case for fields which are optional but which
// must have a certain kind of content if filled in.

var defaultEmptyOK = false
// This function checks a dropdown menu to see if an option 
// has been selected before the "Go" button was clicked;
// If not, it alerts the user to make a selection.

function CheckMenu(pv_user_selection) 
   { 
   i = document.Dropdown.pv_choice.selectedIndex
   if (i == 0) 
      {
      return false;
      }
   return true;
   }

// Attempting to make this library run on Navigator 2.0,
// so I'm supplying this array creation routine as per
// JavaScript 1.0 documentation.  If you're using 
// Navigator 3.0 or later, you don't need to do this;
// you can use the Array constructor instead.

function makeArray(n) {
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}



var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
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;




// Valid U.S. Postal Codes for states, territories, armed forces, etc.
// See http://www.usps.gov/ncsc/lookups/abbr_state.txt.

var USStateCodeDelimiter = "|";
var USStateCodes = "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"




// Check whether string s is empty.

function isEmpty(s)
         {   
         return ((s == null) || (s.length == 0))
         }

function isCommentEmpty(v_comment)
         {
         if (v_comment.value == "")
           {
            alert( "Please Type Your Comments in the Comment Area." );
            v_comment.focus();
            return false;
           }
             return true;
         }

// Returns true if string s is empty or 
// whitespace characters only.

function isWhitespace (s)
         {   
         var i;
         // 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;
         }



// Removes all characters which appear in string bag from string s.

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++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}



// Removes all characters which do NOT appear in string bag 
// from string s.

function stripCharsNotInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}



// Removes all whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripWhitespace (s)

{   return stripCharsInBag (s, whitespace)
}




// WORKAROUND FUNCTION FOR NAVIGATOR 2.0.2 COMPATIBILITY.
//
// The below function *should* be unnecessary.  In general,
// avoid using it.  Use the standard method indexOf instead.
//
// However, because of an apparent bug in indexOf on 
// Navigator 2.0.2, the below loop does not work as the
// body of stripInitialWhitespace:
//
// while ((i < s.length) && (whitespace.indexOf(s.charAt(i)) != -1))
//   i++;
//
// ... so we provide this workaround function charInString
// instead.
//
// charInString (CHARACTER c, STRING s)
//
// Returns true if single character c (actually a string)
// is contained within string s.

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}



// Removes initial (leading) whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripInitialWhitespace (s)

{   var i = 0;

    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    
    return s.substring (i, s.length);
}







// Returns true if character c is an English letter 
// (A .. Z, a..z).
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isLetter (c)
         {   
         return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
         }



// Returns true if character c is a digit 
// (0 .. 9).

function isDigit (c)
         {   
         return ((c >= "0") && (c <= "9"))
         }



// Returns true if character c is a letter or digit.

function isLetterOrDigit (c)
         {   
         return (isLetter(c) || isDigit(c))
         }



// isInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if all characters in string s are numbers.
//
// Accepts non-signed integers only. Does not accept floating 
// point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// By default, returns defaultEmptyOK if s is empty.
// There is an optional second argument called emptyOK.
// emptyOK is used to override for a single function call
//      the default behavior which is specified globally by
//      defaultEmptyOK.
// If emptyOK is false (or any value other than true), 
//      the function will return false if s is empty.
// If emptyOK is true, the function will return true if s is empty.
//
// EXAMPLE FUNCTION CALL:     RESULT:
// isInteger ("5")            true 
// isInteger ("")             defaultEmptyOK
// isInteger ("-5")           false
// isInteger ("", true)       true
// isInteger ("", false)      false
// isInteger ("5", false)     true

function isInteger (s)
   {   
   var i;

   if (isEmpty(s)) 
      if (isInteger.arguments.length == 1) return defaultEmptyOK;
      else return (isInteger.arguments[1] == true);

   // Search through string's characters one by one
   // until we find a non-numeric character.
   // When we do, return false; if we don't, return true.

   for (i = 0; i < s.length; i++)
       {   
       // Check that current character is number.
       var c = s.charAt(i);

       if (!isDigit(c)) return false;
       }

   // All characters are numbers.
   return true;
   }



// isSignedInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if all characters are numbers; 
// first character is allowed to be + or - as well.
//
// Does not accept floating point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// EXAMPLE FUNCTION CALL:          RESULT:
// isSignedInteger ("5")           true 
// isSignedInteger ("")            defaultEmptyOK
// isSignedInteger ("-5")          true
// isSignedInteger ("+5")          true
// isSignedInteger ("", false)     false
// isSignedInteger ("", true)      true

function isSignedInteger (s)

{   if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) 
          return           defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}




// isPositiveInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is an integer > 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isPositiveInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isPositiveInteger.arguments.length > 1)
        secondArg = isPositiveInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a positive, not negative, number

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) > 0) ) );
}






// isNonnegativeInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is an integer >= 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number >= 0
    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) >= 0) ) );
}
//) 


// isNegativeInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is an integer < 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isNegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNegativeInteger.arguments.length > 1)
        secondArg = isNegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a negative, not positive, number

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) < 0) ) );
}






// isNonpositiveInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is an integer <= 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isNonpositiveInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonpositiveInteger.arguments.length > 1)
        secondArg = isNonpositiveInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number <= 0

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) <= 0) ) );
}





// isFloat (STRING s [, BOOLEAN emptyOK])
// 
// True if string s is an unsigned floating point (real) number. 
//
// Also returns true for unsigned integers. If you wish
// to distinguish between integers and floating point numbers,
// first call isInteger, then call isFloat.
//
// Does not accept exponential notation.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isFloat (s)

{   var i;
    var seenDecimalPoint = false;

    if (isEmpty(s)) 
       if (isFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isFloat.arguments[1] == true);

    if (s == decimalPointDelimiter) return false;

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if ((c == decimalPointDelimiter) && !seenDecimalPoint) seenDecimalPoint = true;
        else if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}
// isSignedFloat (STRING s [, BOOLEAN emptyOK])
// 
// True if string s is a signed or unsigned floating point 
// (real) number. First character is allowed to be + or -.
//
// Also returns true for unsigned integers. If you wish
// to distinguish between integers and floating point numbers,
// first call isSignedInteger, then call isSignedFloat.
//
// Does not accept exponential notation.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isSignedFloat (s)

{   if (isEmpty(s)) 
       if (isSignedFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedFloat.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedFloat.arguments.length > 1)
            secondArg = isSignedFloat.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isFloat(s.substring(startPos, s.length), secondArg))
    }
}




// isAlphabetic (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isAlphabetic (s)

{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-alphabetic character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }

    // All characters are letters.
    return true;
}




// isAlphanumeric (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) and numbers only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isAlphanumeric (s)
   {   
   var i;
   if (isEmpty(s)) 
      if (isAlphanumeric.arguments.length == 1) 
         return defaultEmptyOK;
      else 
         return (isAlphanumeric.arguments[1] == true);

   // Search through string's characters one by one
   // until we find a non-alphanumeric character.
   // When we do, return false; if we don't, return true.
   for (i = 0; i < s.length; i++)
       {   
       var c = s.charAt(i);
       if (! (isLetter(c) || isDigit(c) ) )
          return false;
       }

   // All characters are numbers or letters.
   return true;
   }


// Returns true if character c is a space

function isSpace (c)
         {   
         return (c == "\x20")
         }


// Returns true if character c is an ampersand

function isAmpersand (c)
         {   
         return (c == "\x26")
         }


// Returns true if character c is a hyphen

function isHyphen (c)
         {   
         return (c == "\x2D")
         }


// Returns true if character c is a single quote

function isSingleQuote (c)
         {   
         return (c == "\x27")
         }


// Returns true if character c is a pound sign

function isPoundSign (c)
         {   
         return (c == "\x23")
         }


// Returns true if character c is a forward slash

function isForwardSlash (c)
         {   
         return (c == "\x2F")
         }

// Returns true if character c is a Period or Decimal

function isPeriod (c)
         {   
         return (c == "\x2E")
         }

// Returns true if character c is a Open Parenthesis

function isOpenParen (c)
         {   
         return (c == "\x28")
         }

// Returns true if character c is a Close Parenthesis

function isCloseParen (c)
         {   
         return (c == "\x29")
         }



// Check for valid characters for a street address

function isStreetChars (s)
   {   
   var i;

   // Search through string's characters one by one
   // until we find a character that is invalid for a street address.
   // When we do, return false; if we don't, return true.

   for (i = 0; i < s.length; i++)
       {   
       var c = s.charAt(i);
       if (!(isLetter(c)       ||
             isDigit(c)        || 
             isSpace(c)        || 
             isAmpersand(c)    || 
             isHyphen(c)       || 
             isSingleQuote(c)  || 
             isForwardSlash(c) || 
             isPoundSign(c)    ||
             isEmpty(c)
            )
          )
       return false;
       }

   // All characters are valid for a street address.
   return true;
   }


// Check for valid characters for a company name

function isNameChars (s)
   {   
   var i;

   // Search through string's characters one by one
   // until we find a character that is invalid for a company name.
   // When we do, return false; if we don't, return true.

   for (i = 0; i < s.length; i++)
       {   
       var c = s.charAt(i);
       if (!(isLetter(c)       ||
             isDigit(c)        || 
             isSpace(c)        || 
             isAmpersand(c)    || 
             isHyphen(c)       || 
             isSingleQuote(c)  ||
             isEmpty(c)
            )
          )
       return false;
       }

   // All characters are valid for a company name.
   return true;
   }


// Check for valid characters for a city name

function isCityChars (s)
   {   
   var i;

   // Search through string's characters one by one
   // until we find a character that is invalid for a city name.
   // When we do, return false; if we don't, return true.

   for (i = 0; i < s.length; i++)
       {   
       var c = s.charAt(i);
       if (!(isLetter(c)       ||
             isDigit(c)        || 
             isSpace(c)        ||              
             isHyphen(c)       || 
             isSingleQuote(c)  ||
             isEmpty(c)
            )
          )
       return false;
       }

   // All characters are valid for a city name.
   return true;
   }


// Check for valid characters for a zip or postal code

function isZipChars (s)
   {   
   var i;

   // Search through string's characters one by one
   // until we find a character that is invalid for a zip or postal code.
   // When we do, return false; if we don't, return true.

   for (i = 0; i < s.length; i++)
       {   
       var c = s.charAt(i);
       if (!(isLetter(c)       ||
             isDigit(c)        || 
             isSpace(c)        ||             
             isHyphen(c)       ||
             isEmpty(c)
            )
          )
       return false;
       }

   // All characters are valid for a zip or postal code.
   return true;
   }

// Check for valid characters for a Violation Part Number

function isViolChars (s)
   {   
   var i;

   // Search through string's characters one by one
   // until we find a character that is invalid for a Violation Part Number.
   // When we do, return false; if we don't, return true.

   for (i = 0; i < s.length; i++)
       {   
       var c = s.charAt(i);
       if (!(isLetter(c)       ||
             isDigit(c)        || 
             isOpenParen(c)    ||
             isCloseParen(c)   ||
             isPeriod(c)       ||
             isEmpty(c)
            )
          )
       return false;
       }

   // All characters are valid for a Violation.
   return true;
   }




// reformat (TARGETSTRING, STRING, INTEGER, STRING, INTEGER ... )       
//
// Handy function for arbitrarily inserting formatting characters
// or delimiters of various kinds within TARGETSTRING.
//
// reformat takes one named argument, a string s, and any number
// of other arguments.  The other arguments must be integers or
// strings.  These other arguments specify how string s is to be
// reformatted and how and where other strings are to be inserted
// into it.
//
// reformat processes the other arguments in order one by one.
// * If the argument is an integer, reformat appends that number 
//   of sequential characters from s to the resultString.
// * If the argument is a string, reformat appends the string
//   to the resultString.
//
// NOTE: The first argument after TARGETSTRING must be a string.
// (It can be empty.)  The second argument must be an integer.
// Thereafter, integers and strings must alternate.  This is to
// provide backward compatibility to Navigator 2.0.2 JavaScript
// by avoiding use of the typeof operator.
//
// It is the caller's responsibility to make sure that we do not
// try to copy more characters from s than s.length.
//
// EXAMPLES:
//
// * To reformat a 10-digit U.S. phone number from "1234567890"
//   to "(123) 456-7890" make this function call:
//   reformat("1234567890", "(", 3, ") ", 3, "-", 4)
//
// * To reformat a 9-digit U.S. Social Security number from
//   "123456789" to "123-45-6789" make this function call:
//   reformat("123456789", "", 3, "-", 2, "-", 4)
//
// HINT:
//
// If you have a string which is already delimited in one way
// (example: a phone number delimited with spaces as "123 456 7890")
// and you want to delimit it in another way using function reformat,
// call function stripCharsNotInBag to remove the unwanted 
// characters, THEN call function reformat to delimit as desired.
//
// EXAMPLE:
//
// reformat (stripCharsNotInBag ("123 456 7890", digits),
//           "(", 3, ") ", 3, "-", 4)

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;
}




// isSSN (STRING s [, BOOLEAN emptyOK])
// 
// isSSN returns true if string s is a valid U.S. Social
// Security Number.  Must be 9 digits.
//
// NOTE: Strip out any delimiters (spaces, hyphens, etc.)
// from string s before calling this function.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isSSN (s)
{   if (isEmpty(s)) 
       if (isSSN.arguments.length == 1) return defaultEmptyOK;
       else return (isSSN.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInSocialSecurityNumber)
}




// isUSPhoneNumber (STRING s [, BOOLEAN emptyOK])
// 
// isUSPhoneNumber returns true if string s is a valid U.S. Phone
// Number.  Must be 10 digits.
//
// NOTE: Strip out any delimiters (spaces, hyphens, parentheses, etc.)
// from string s before calling this function.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isUSPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isUSPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isUSPhoneNumber.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInUSPhoneNumber)
}




// isInternationalPhoneNumber (STRING s [, BOOLEAN emptyOK])
// 
// isInternationalPhoneNumber returns true if string s is a valid 
// international phone number.  Must be digits only; any length OK.
// May be prefixed by + character.
//
// NOTE: A phone number of all zeros would not be accepted.
// I don't think that is a valid phone number anyway.
//
// NOTE: Strip out any delimiters (spaces, hyphens, parentheses, etc.)
// from string s before calling this function.  You may leave in 
// leading + character if you wish.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isInternationalPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isInternationalPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isInternationalPhoneNumber.arguments[1] == true);
    return (isPositiveInteger(s))
}




// isZIPCode (STRING s [, BOOLEAN emptyOK])
// 
// isZIPCode returns true if string s is a valid 
// U.S. ZIP code.  Must be 5 or 9 digits only.
//
// NOTE: Strip out any delimiters (spaces, hyphens, etc.)
// from string s before calling this function.  
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isZIPCode (s)
{  if (isEmpty(s)) 
       if (isZIPCode.arguments.length == 1) return defaultEmptyOK;
       else return (isZIPCode.arguments[1] == true);
   return (isInteger(s) && 
            ((s.length == digitsInZIPCode1) ||
             (s.length == digitsInZIPCode2)))
}





// isStateCode (STRING s [, BOOLEAN emptyOK])
// 
// Return true if s is a valid U.S. Postal Code 
// (abbreviation for state).
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isStateCode(s)
{   if (isEmpty(s)) 
       if (isStateCode.arguments.length == 1) return defaultEmptyOK;
       else return (isStateCode.arguments[1] == true);
    return ( (USStateCodes.indexOf(s) != -1) &&
             (s.indexOf(USStateCodeDelimiter) == -1) )
}




// isEmail (STRING s [, BOOLEAN emptyOK])
// 
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    // 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 sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}





// isYear (STRING s [, BOOLEAN emptyOK])
// 
// isYear returns true if string s is a valid 
// Year number.  Must be 2 or 4 digits only.
// 
// For Year 2000 compliance, you are advised
// to use 4-digit year numbers everywhere.
//
// And yes, this function is not Year 10000 compliant, but 
// because I am giving you 8003 years of advance notice,
// I don't feel very guilty about this ...
//
// For B.C. compliance, write your own function. ;->
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isYear (s)
{   if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}



// isIntegerInRange (STRING s, INTEGER a, INTEGER b [, BOOLEAN emptyOK])
// 
// isIntegerInRange returns true if string s is an integer 
// within the range of integer arguments a and b, inclusive.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.


function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseInt (s);
    return ((num >= a) && (num <= b));
}



// isMonth (STRING s [, BOOLEAN emptyOK])
// 
// isMonth returns true if string s is a valid 
// month number between 1 and 12.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isMonth (s)
{   if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}



// isDay (STRING s [, BOOLEAN emptyOK])
// 
// isDay returns true if string s is a valid 
// day number between 1 and 31.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isDay (s)
{   if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
}



// daysInFebruary (INTEGER year)
// 
// Given integer argument year,
// returns number of days in February of that year.

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 );
}



// isDate (STRING year, STRING month, STRING day)
//
// isDate returns true if string arguments year, month, and day 
// form a valid date.
// 

function isDate (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.
    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}




/* FUNCTIONS TO NOTIFY USER OF INPUT REQUIREMENTS OR MISTAKES. */


// Display prompt string s in status bar.

function prompt (s)
{   window.status = s
}



// Display data entry prompt string s in status bar.

function promptEntry (s)
{   window.status = pEntryPrompt + s
}




// Notify user that required field theField is empty.
// String s describes expected contents of theField.value.
// Put focus in theField and return false.

function warnEmpty (theField, s)
{   theField.focus()
    alert(mPrefix + s + mSuffix)
    return false
}



// Notify user that contents of field theField are invalid.
// String s describes expected contents of theField.value.
// Put select theField, pu focus in it, and return false.

function warnInvalid (theField, s)
{   alert(s)
    theField.focus()
    theField.select()
    return false
}




/* FUNCTIONS TO INTERACTIVELY CHECK VARIOUS FIELDS. */

// checkString (TEXTFIELD theField, STRING s, [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is not all whitespace.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkString (theField, s, emptyOK)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkString.arguments.length == 2) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (isWhitespace(theField.value)) 
       return warnEmpty (theField, s);
    else return true;
}



// checkStateCode (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid U.S. state code.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkStateCode (theField, emptyOK)
{   if (checkStateCode.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  theField.value = theField.value.toUpperCase();
       if (!isStateCode(theField.value, false)) 
          return warnInvalid (theField, iStateCode);
       else return true;
    }
}



// takes ZIPString, a string of 5 or 9 digits;
// if 9 digits, inserts separator hyphen

function reformatZIPCode (ZIPString)
{   if (ZIPString.length == 5) return ZIPString;
    else return (reformat (ZIPString, "", 5, "-", 4));
}




// checkZIPCode (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid ZIP code.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkZIPCode (theField, emptyOK)
{   if (checkZIPCode.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    { var normalizedZIP = stripCharsInBag(theField.value, ZIPCodeDelimiters)
      if (!isZIPCode(normalizedZIP, false)) 
         return warnInvalid (theField, iZIPCode);
      else 
      {  // if you don't want to insert a hyphen, comment next line out
         theField.value = reformatZIPCode(normalizedZIP)
         return true;
      }
    }
}



// takes USPhone, a string of 10 digits
// and reformats as (123) 456-789

function reformatUSPhone (USPhone)
{   return (reformat (USPhone, "(", 3, ") ", 3, "-", 4))
}



// checkUSPhone (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid US Phone.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkUSPhone (theField, emptyOK)
{  if (checkUSPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
   if ((emptyOK == true) && (isEmpty(theField.value))) return true;
   else
    {  var normalizedPhone = stripCharsInBag(theField.value, phoneNumberDelimiters)
       if (!isUSPhoneNumber(normalizedPhone, false)) 
          return warnInvalid (theField, iUSPhone);
       else 
       {  // if you don't want to reformat as (123) 456-789, comment next line out
          theField.value = reformatUSPhone(normalizedPhone)
          return true;
       }
    }
}



// checkInternationalPhone (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid International Phone.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkInternationalPhone (theField, emptyOK)
{   if (checkInternationalPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  if (!isInternationalPhoneNumber(theField.value, false)) 
          return warnInvalid (theField, iWorldPhone);
       else return true;
    }
}



// checkEmail (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid Email.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkEmail (theField, emptyOK)
{   if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else if (!isEmail(theField.value, false)) 
       return warnInvalid (theField, iEmail);
    else return true;
}



// takes SSN, a string of 9 digits
// and reformats as 123-45-6789

function reformatSSN (SSN)
{   return (reformat (SSN, "", 3, "-", 2, "-", 4))
}


// Check that string theField.value is a valid SSN.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkSSN (theField, emptyOK)
{   if (checkSSN.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  var normalizedSSN = stripCharsInBag(theField.value, SSNDelimiters)
       if (!isSSN(normalizedSSN, false)) 
          return warnInvalid (theField, iSSN);
       else 
       {  // if you don't want to reformats as 123-456-7890, comment next line out
          theField.value = reformatSSN(normalizedSSN)
          return true;
       }
    }
}




// Check that string theField.value is a valid Year.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkYear (theField, emptyOK)
{   if (checkYear.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isYear(theField.value, false)) 
       return warnInvalid (theField, iYear);
    else return true;
}


// Check that string theField.value is a valid Month.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkMonth (theField, emptyOK)
{   if (checkMonth.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isMonth(theField.value, false)) 
       return warnInvalid (theField, iMonth);
    else return true;
}


// Check that string theField.value is a valid Day.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkDay (theField, emptyOK)
{   if (checkDay.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isDay(theField.value, false)) 
       return warnInvalid (theField, iDay);
    else return true;
}



// checkDate (yearField, monthField, dayField, STRING labelString [, OKtoOmitDay==false])
//
// Check that yearField.value, monthField.value, and dayField.value 
// form a valid date.
//
// If they don't, labelString (the name of the date, like "Birth Date")
// is displayed to tell the user which date field is invalid.
//
// If it is OK for the day field to be empty, set optional argument
// OKtoOmitDay to true.  It defaults to false.
// this function validates seperate field that make up a date and not one date field.
//
function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkDate.arguments.length == 4) OKtoOmitDay = false;
    if (!isYear(yearField.value)) return warnInvalid (yearField, iYear);
    if (!isMonth(monthField.value)) return warnInvalid (monthField, iMonth);
    if ( (OKtoOmitDay == true) && isEmpty(dayField.value) ) return true;
    else if (!isDay(dayField.value)) 
       return warnInvalid (dayField, iDay);
    if (isDate (yearField.value, monthField.value, dayField.value))
       return true;
    alert (iDatePrefix + labelString + iDateSuffix)
    return false
}



// Get checked value from radio button.

function getRadioButtonValue (radio)
{   for (var i = 0; i < radio.length; i++)
    {   if (radio[i].checked) { break }
    }
    return radio[i].value
}





function getInputObject(divID)
         {
         var input = divID.all.tags("INPUT");
         if (input.length > 0)
            {
            return input[0];
            } 
         else 
            {
            return null;
            }
         }
 
function show(divID)
         {
         divID.style.visibility = "visible";
         divID.style.display = "block";
         }
 
function hide(divID)
         {
         divID.style.visibility = "hidden";
         divID.style.display = "none";
         }
 
function ShowSection(divID, subDivID)
         {
         var div = subDivID.tags("DIV");
         for (var i = 0; i < div.length; i++)
             {
             if ((div[i].id == divID) || 
                (divID == "show all data"))
                {
                show(div[i]);
                var inputObject = getInputObject(div[i]);
                if ( (inputObject != null) && 
                     (inputObject.type != "hidden") )
                   {
                   with (inputObject)
                        {
                        if (type == "text")
                           {
                           select()
                           } 
                //        else 
                //           {
                //           focus()
                //           }
                        }
                   }
                }
             else
                {
                hide(div[i]);
                }
             }
         }


function tabUp(tdID)
         {
         tdID.style.borderTop = "lightblue solid 3px";
         tdID.style.borderLeft = tdID.style.borderTop;
         tdID.style.borderBottom = "#000099 solid 3px";
         tdID.style.borderRight = tdID.style.borderBottom; 
         tdID.style.backgroundColor = "#336699"; 
         tdID.style.color = "white";  
         }
 
function tabDown(tdID)
         {
         tdID.style.borderTop = "#000099 solid 3px";
         tdID.style.borderLeft = tdID.style.borderTop;
         tdID.style.borderBottom = "lightblue solid 3px";
         tdID.style.borderRight = tdID.style.borderBottom;
         tdID.style.backgroundColor = "lightblue";   
         tdID.style.color = "black"; 
         }
 
function pressTab(tdID, subDivID)
         {
         document.body.style.cursor = "wait";
         if (subDivID == null)
            {
            subDivID = document.all;
            }
         var td = subDivID.tags("TD");
         for (var i = 0; i < td.length; i++)
             {
             if (td[i].className == "table_tab")
                {
                if (td[i].id == tdID)
                   {
                   tabDown(td[i]); 
                   ShowSection(tdID, subDivID);
                   }
                else
                   {
                   tabUp(td[i]);
                   }
                }
             }
         document.body.style.cursor = "default";

         }

function isInt(passedValue)
   {
   for (i=0; i<passedValue.length; ++i)
       {
       if (passedValue.charAt(i) < "0")
          { 
          return false
          }
       if (passedValue.charAt(i) > "9")
          {
          return false
          }  
       }
   return true
   }

function isIntNoBlank(passedValue)
   {
   for (i=0; i<passedValue.length; ++i)
       {
       if (passedValue.charAt(i) < "0")
          {  
          return false
          }
       if (passedValue.charAt(i) > "9")
          {
          return false
          }  
       }
   if ((passedValue) < "0" || (passedValue > "99999"))
      {
      return false;
      }
   else
      {
      return true;
      }
   }


function editInteger(elementName)
   {
   if (!isInt(elementName.value))
      {
      alert("\nValue entered must be an integer. \n") 
      elementName.focus()
      elementName.select()
      return false
      }  
   else
      {
      return true
      }
   }

function editIntegerDefault2Zero(elementName)
   {
   if (!isIntNoBlank(elementName.value))
      {
      alert("\nInvalid entry. Will default to zero. \n")
      return elementName.value = "0"
      }
   }

function editStreetChars(elementName)
   {   
   if (!(isStreetChars(elementName.value)))
      {
      alert("\nValue entered contains invalid character(s). \n")
      elementName.focus()
      elementName.select() 
      return false
      }  
   else
      {
      return true
      } 
   }


function editNameChars(elementName)
   {   
   if (!(isNameChars(elementName.value)))
      {
      alert("\nValue entered contains invalid character(s). \n")
      elementName.focus()
      elementName.select() 
      return false
      }  
   else
      {
      return true
      } 
   }


function editCityChars(elementName)
   {   
   if (!(isCityChars(elementName.value)))
      {
      alert("\nValue entered contains invalid character(s). \n")
      elementName.focus()
      elementName.select() 
      return false
      }  
   else
      {
      return true
      } 
   }


function editZipChars(elementName)
   {   
   if (!(isZipChars(elementName.value)))
      {
      alert("\nValue entered contains invalid character(s). \n")
      elementName.focus()
      elementName.select() 
      return false
      }  
   else
      {
      return true
      } 
   }

function editViolChars(elementName)
   {   
   if (!(isViolChars(elementName.value)))
      {
      alert("\nValue entered contains invalid character(s). \n")
      elementName.focus()
      elementName.select() 
      return false
      }  
   else
      {
      return true
      } 
   }



// This function checks or unchecks a series of checkboxes all with the same name.  It is used
// in the Review Violation system.

function check(field) {
if (document.VIOLUPD.all_ckbox.checked == true) {
for (i = 0; i < field.length; i++) {
field[i].checked = true;}
}
else {
for (i = 0; i < field.length; i++) {
field[i].checked = false; }
}
}

function uncheck(field) {
if (field.checked == false) {
  document.VIOLUPD.all_ckbox.checked = false;
}
} 

// This script checks a date for validity and puts it in MM/DD/YYYY format 
//Begin
function datecheck(objName,chkFuture) {
var datefield = objName;
if (chkdate(objName,chkFuture) == false) {
datefield.select();
alert("That date is invalid.  Please try again.");
datefield.focus();
return false;
}
else {
return true;
   }
}
function chkdate(objName,chkFuture) {
var strDatestyle = "US"; //United States date style
//var strDatestyle = "EU";  //European date style
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
var err = 0;
var strMonthArray = new Array(12);
strMonthArray[0] = "Jan";
strMonthArray[1] = "Feb";
strMonthArray[2] = "Mar";
strMonthArray[3] = "Apr";
strMonthArray[4] = "May";
strMonthArray[5] = "Jun";
strMonthArray[6] = "Jul";
strMonthArray[7] = "Aug";
strMonthArray[8] = "Sep";
strMonthArray[9] = "Oct";
strMonthArray[10] = "Nov";
strMonthArray[11] = "Dec";
strDate = datefield.value;
if (strDate.length < 1) {
return true;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
strDateArray = strDate.split(strSeparatorArray[intElementNr]);
if (strDateArray.length != 3) {
err = 1;
return false;
}
else {
strDay = strDateArray[0];
strMonth = strDateArray[1];
strYear = strDateArray[2];
}
booFound = true;
   }
}
if (booFound == false) {
if (strDate.length>5) {
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(2, 2);
strYear = strDate.substr(4);
   }
else {
return false;
   }
}
// tong wang add 0n 2/25/02
if ((!isInt(strDay))||(!isInt(strMonth))||(!isInt(strYear))){
 return false;
}
//else
//{ return false}
//alert(strDay);
//alert(strMonth);
//alert(strYear);

//end
if (strYear.length == 2) {
intYear = parseInt(strYear, 10);
if (intYear > 50){
   strYear = '19' + strYear;
   }
else
   {
   strYear = '20' + strYear;
   }
}
// US style
if (strDatestyle == "US") {
strTemp = strDay;
strDay = strMonth;
strMonth = strTemp;
}
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
for (i = 0;i<12;i++) {
if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
intMonth = i+1;
strMonth = strMonthArray[i];
i = 12;
   }
}
if (isNaN(intMonth)) {
err = 3;
return false;
   }
}
// Tong Wang changed on 08/31/01 for fixing bug on year.
if ((strYear.length != 2) && (strYear.length != 4)) {
return false;
}
//
intYear = parseInt(strYear, 10);

if (isNaN(intYear)) {
err = 4;
return false;
}

if (intMonth>12 || intMonth<1) {
err = 5;
return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
err = 6;
return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
err = 7;
return false;
}
if (intMonth == 2) {
if (intday < 1) {
err = 8;
return false;
}
if (LeapYear(intYear) == true) {
if (intday > 29) {
err = 9;
return false;
}
}
else {
if (intday > 28) {
err = 10;
return false;
}
}
}
if (strDatestyle == "US") {
datefield.value = intMonth + "/" + intday+"/" + strYear;
}
else {
datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
}

// Tong Wang changed on 08/31/01 for checking future date
if (chkFuture == "Y") {
chkGreaterToday(objName,datefield.value);}
else{
return true;}

}

//
function LeapYear(intYear) {
if (intYear % 100 == 0) {
if (intYear % 400 == 0) { return true; }
}
else {
if ((intYear % 4) == 0) { return true; }
}
return false;

}

  
// This function makes sure that all required text(or dropdown) fields have no null values (or spaces only).
// In case they do, it gives a message with the names of those text fields, and places the cursor 
// into the first one to be filled in.
// ***! Required text fields must be marked with id="required" in the form !***
// Tong Wang modified on 08/29/2001

 function checkRequiredFieldsForNull(form)
 {
 var requiredFieldNames = "\n";						//holds the names of the required text fields which have null values
 var formattedName;							//helps to format the name and stores it	
 var firstRequiredField;						//keeps the index of the first required text field to be filled in 
 for (i=0; i < form.elements.length; i++)
 	{
	//if (form.elements[i].type == "text")
	//	{
		if (form.elements[i].field == "required")		//if the text field is marked as "required" by its id
	  		{
			if (form.elements[i].value.replace(/ *$/,"") == "")
				{
				if (firstRequiredField == null)
				firstRequiredField = i;
			
				formattedName = form.elements[i].name.replace(/_/g, " ");
				formattedName = formattedName.substring(formattedName.indexOf(" "));  
				requiredFieldNames += "\n" + formattedName;
				}
			}
		}	
	//}
 if (requiredFieldNames != "\n")
 	{
	alert ("The following are required fields:" + requiredFieldNames);
	if(form.name == "REG")
	pressTab('show all data');
	
	form.elements[firstRequiredField].focus();
	return false;
	}
 else 
 //Tong Wang changed 0n 02/27/02 for disable enter button on submit
   form.submit();
 //return true;
 }
 
 //  Tong Wang: add this function to check null value. 08/03/01
 function notNullField(elementName)
    {   
    if (isEmpty(elementName.value))
       {
       alert("\nYou have to enter this field. \n")
       elementName.focus()
       elementName.select() 
       return false
       }  
    else
       {
       return true
       } 
    }
    
   
  function getForm(form)
      {   
      alert(form.name);
      for (i=0; i < form.elements.length; i++){
        if (form.elements[i].type == "text"){
      	alert(form.elements[i].name+form.elements[i].id);
      	}
      }
      return false;
    }
  function getValue(elementName)
    {    
      alert(elementName.value)
      return elementName.value      
    }

  function getID(elementName)
    {
      alert(elementName.id)
    }
  
  // Tong Wang create this function for checking future date
  function chkGreaterToday(elementName, inDateString)
    {
      var dateArray;
      var dateString;
      var vday;
      var vmonth;
      var vyear;
    
      dateString = inDateString;
      
      var now = new Date();
      var month = now.getMonth();      
      var day = now.getDate();
      var year = now.getYear();
      
      var intYear = parseInt(year);
      var intMonth = parseInt(month)+1;
      var intDay = parseInt(day);
          
      dateArray = dateString.split("/");
      
      vday = dateArray[1];
      vmonth = dateArray[0];
      vyear = dateArray[2];
           
     if (vyear == intYear){
          if (vmonth == intMonth){
            if (vday <= intDay){
             return true;
             }
             else {
             alert("\n Date can not be greater than today. \n");
	     	          elementName.focus();
	     	          elementName.select(); 
              return false;
             }
          
          
          }
          else if (vmonth < intMonth){
          return true;
          }
          else if (vmonth > intMonth){
          alert("\n Date can not be greater than today. \n");
	          elementName.focus();
	          elementName.select(); 
           return false;
          }
        
       
        }
       else if (vyear < intYear){
       return true;
       }
       else if (vyear > intYear)
       {
        alert("\n Date can not be greater than today. \n");
        elementName.focus();
        elementName.select(); 
        return false;
      }
           
    } 
    
// Tong Wang created this function for Border application 
//Bus phone/fax MX only  on 11/06/01
    function chkMexPhone(elementName)
       {
       if (!isInt(elementName.value))
          {
          alert("\nThis is invalid phone/fax number. \n") 
          elementName.focus()
          elementName.select()
          return false
          }  
       else
          {
          return true
          }
   }
       
  // Tong Wang created this function for Border application on 11/05/01
  
  function checkPhone (theField, emptyOK)
  {  if (checkPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
     if ((emptyOK == true) && (isEmpty(theField.value))) return true;
     else
      {  var normalizedPhone = stripCharsInBag(theField.value, phoneNumberDelimiters)
         if (!isPhoneNumber(normalizedPhone, false)) 
            return warnInvalid (theField, iWorldPhone);
         else 
         {  
            return true;
         }
      }
  }
  
  function isPhoneNumber (s)
  {   if (isEmpty(s)) 
         if (isPhoneNumber.arguments.length == 1) return defaultEmptyOK;
         else return (isPhoneNumber.arguments[1] == true);
      return isInteger(s)
  } 
  
 // Tong Wang created this function for Border application on 11/06/01
 // Bus Zip MX only, accept only 5 number
 function chkMexZip(elementName)
        {
        if (!isInt(elementName.value))
           {
           alert("\nThis is invalid Postal Code. \n") 
           elementName.focus()
           elementName.select()
           return false
           }  
        else
           { 
             if ((elementName.value.length ==5)||(elementName.value.length==0))
               return true
             else {
		alert("\nThis is invalid Postal Code. \n") 
		elementName.focus()
		elementName.select()
		return false }
           }
   } // end chkMexZip
 
// Tong Wang created this function for Border application on 11/06/01
// checkZipAll check all allowed zip, space, hyphen, digits, letter.
var space = " "
var ZIPCodeDelimitersAll = digits + ZIPCodeDelimiters + space + lowercaseLetters + uppercaseLetters
var iZIPCodeAll = "This is invalid Postal code"
function checkZipAll(theField, emptyOK)
   {   if (checkZipAll.arguments.length == 1) emptyOK = defaultEmptyOK;
       if ((emptyOK == true) && (isEmpty(theField.value))) return true;
       else
       { 
         if (!isZIPCodeAll(theField.value, ZIPCodeDelimitersAll)) 
            return warnInvalid (theField, iZIPCodeAll); 
         else 
           {
            return true;
           }
       }
}

function isZIPCodeAll(s, bag)
{
  var i;
  var invalidChar = false;
  for (i = 0; i < s.length; i++)
      {  
          var c = s.charAt(i);
          if (bag.indexOf(c) == -1) 
          { 
            invalidChar = true
            break
            }
          
      }
  if (invalidChar == true)
    return false
  else
    return true
}

  //Tong Wang 12/07/01 
  //for open DIY window credit card
  function diyWindow(trkType,trkVar,authVar,userVar){
   
	 if (trkType == 1) {
   //var w = window.open('https://diy.dot.gov:13001/cec/cstage?ecaction=ecwalkin&eccookie=@eccookie@&template=omc_op'+trkType+'mx.htm&trk_num='+trkVar+'&ecQty='+authVar+'&user_id='+userVar)
     var w = window.open('https://diy.dot.gov/cust/cdeploy?ecaction=ecwalkin&template=omc_op'+trkType+'mx.htm&trk_num='+trkVar+'&ecQty='+authVar+'&user_id='+userVar)
	 } 
	 if (trkType == 2) {
   //var w = window.open('https://diy.dot.gov:13001/cec/cstage?ecaction=ecwalkin&eccookie=@eccookie@&template=omc_op'+trkType+'.htm&trk_num='+trkVar+'&ecQty='+authVar+'&user_id='+userVar)
     var w = window.open('https://diy.dot.gov/cust/cdeploy?ecaction=ecwalkin&template=omc_op'+trkType+'.htm&trk_num='+trkVar+'&ecQty='+authVar+'&user_id='+userVar)
	 } 
  }//end function diyWindow()
  
   function updateParent(){
   opener.document.location = "http://ucrweb.volpe.dot.gov/internal/internal.html"
   //newWin = window.open(newURL, newWin);
  }
  
  
//Function added by Alla Ilchenko 10/11/2001 to check if all of the search fields are left blank
//Function is called by pkg_border_track_view.prc_main

	         function isEmptyFields(inputStr1, inputStr2, inputStr3,inputStr4,inputStr5,inputStr6)
	        {
	         if ((inputStr1.value == "" || inputStr1.value == null) &&
	             (inputStr2.value == "" || inputStr2.value == null) &&
	             (inputStr3.value == "~" || inputStr3.value == null) &&
		     (inputStr4.value == "" || inputStr4.value == null) &&
                     (inputStr5.value == "" || inputStr5.value == null) &&
		     (inputStr6.value == "" || inputStr6.value == null))							
	        {
	         
	 alert( "No search parameters were entered. Please enter a search parameter.");
    inputStr1.focus();
	         return false;
	        }
	         return true;
	        }
//Function added by Alla Ilchenko 10/3/2001 to check if a search field is left blank
		    function isEmptyField(inputStr1)
	        {
	         if ((inputStr1.value == "" || inputStr1.value == null))
	        {
	         
	 alert( "Please enter a search parameter.");
    inputStr1.focus();
	         return false;
	        }
	         return true;
	        }

      
//code added by Alla Ilchenko 10/30/2001 to check that menu item is selected

 //function CheckMenuItem(form) 
//   {
//   for (i=0; i < form.elements.length; i++){
//     if (form.elements[i].type == "select-one"){
//      j = form.elements[i].selectedIndex;
//       if (j == 0) {
//        alert( "Please Select a Menu Option." );
 //       form.elements[i].focus();
  //      return false;
  //     }
  //     else { 
   //    return true;
   //    }
   //   }
  // }
  //  } 
//  End 

function isDateGreater(inDateString1, inDateString2,fieldName1,fieldName2)
		    {
		     // Barb Millett Nov 8, 2001
			//this functions returns true if  inDateString1 is greater
			// than or equal to inDateString2
			
		    var dateArray1;
		    var dateArray2;
			
		    var dateString1 = inDateString1;
			var dateString2 = inDateString2;
		    dateArray1 = dateString1.split("/");
			dateArray2 = dateString2.split("/");
		   
		    var vday1 =   dateArray1[1];	
		    if (vday1.length==1) {vday1= "0"+vday1;}
		    		    
		    
		    var vmonth1 = dateArray1[0];
		    if (vmonth1.length == 1) {vmonth1="0"+vmonth1;}  
		    
		    
		    var vyear1 =  dateArray1[2];
 
		    var vday2 =   dateArray2[1];
		    
		    if (vday2.length ==1) {vday2= "0"+vday2;}
		    
		    
		    var vmonth2 =  dateArray2[0];		       
		    if (vmonth2.length == 1) {vmonth2="0"+ vmonth2;}
		    
		    
			var vyear2=   dateArray2[2];			
			
			var sMessage = "\n "+ fieldName1 + " must be greater than or equal to "+ fieldName2 + ". \n"
		     
		    var date1= vyear1+ vmonth1 + vday1;
		    var date2= vyear2 + vmonth2 + vday2;
		    
		     if (date1 >= date2) { return true; }
		     else {
		              alert(sMessage);
		              return false;
		          }		           
		    } 
			// end function isDateGreater
			
function limitTextarea(field, countfield, maxlimit) 
{
// Author:   Barb Millett
// Date:		 29 NOV 2001
// Purpose:  At the time of this scripts creation, there was no property of
//           the textarea (html) object that limits the maximum amount of data that a user
//           may enter. This function provides a method to limit the maximum amount 
//			 of text a user may enter in the textarea object.   
// Parameters:  text field, the count field, max length 
// 	field:       a complete reference to the textarea object that you want
//													 to limit.
//											     i.e. this.form.field
//	countfield:  a complete reference to the object (type = text)
//										 which will display the number of characters remaining that
//										 the user is able to enter before exceeding the max limit.
//	maxlimit:    a number that is the maximum amount of characters you wish
//										 the user to be able to enter. 
// How to use this function:
//	1.  This function needs to be called on the textarea*s events:
//							 			onKeyUp and onKeyDown
//	2.  You are required to include a text object in your form 
//		whose value is initially populated with  
//		maxlimit - field.value.length
//						
// Begin script

	 if (field.value.length > maxlimit)
	 	{ // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
		
		alert("You may enter only "+ maxlimit + " characters in the textbox. \n" +
		      "Whatever exceeded this limit has been omitted.\n"+
		     "Refer to the User Manual for instruction.");
		     countfield.value = maxlimit - field.value.length;
                 return false;
		  }
	else 
		// otherwise, update *characters left* counter
		countfield.value = maxlimit - field.value.length;
           return true;
}
// End function limitTextarea




//
// Author:   Carroll McMann
// Date:		  NOV 2002
// Purpose:   this validates the docket and dot numbers on the
//            Safety Monitoring for Mexican Carriers - Stop Action 
//                      Selection Criteria
// Parameters:  n_dotno, n_docketno 
//						
// Begin script


function is_dotno_docketno_Valid(n_dotno, n_docketno) 
{
 if ((isEmpty(n_dotno.value) && 
       isEmpty(n_docketno.value)
			 )
		 )
   {
    alert( "The Dot Number and Docket Number are both empty. \r Please try again." );
    return false;
   } else {
           if (!(isInteger(n_dotno) || isInteger(n_docketno))							) 
             {
              alert( "Sorry, entry Must Be a Valid Integer." );
              return false;
             }
		return true;
             }
   }

// Author:   Carroll McMann
// Date:		  NOV 2002
// Purpose:   verifystopsr validates the stop action screen
//  
// Notes:     The date function is unique to the date on stop action screen
// Parameters:  all input fileds 
//						
// Begin script
//

   function verifystopsr() {
            var themessage = "You are required to complete the following fields: ";
//  check stop type
            if (document.stopsr.pv_stop_type.value == "X") 
						{
               themessage = themessage + " - stop type";              
		document.stopsr.pv_stop_type.focus();
               alert( "You did not select a stop type. Please try again." );
		return false;
            }
// check stop date
     var chkFuture = "N";
     if (chkdate(document.stopsr.pd_stop_date,chkFuture) == false) 
       {
          alert("That Stop date is invalid.  Please try again.");
	  document.stopsr.pd_stop_date.focus();
          return false;
       }




// Check difference between carrier_action.effective_date and stop_date

            var var_stopdate = new Date(stopsr.pd_stop_date.value);
            var var_effdate  = new Date(stopsr.pd_effective_date.value);
            var var_entdate  = new Date(stopsr.pd_entered_date.value);
            var tstdate = var_effdate   - var_stopdate ;
                 tstdate  = var_stopdate - var_entdate;
             var tstdate2 = var_effdate - var_stopdate;

 
            if (tstdate == 0)
	      {
	       return true;
	      }
             
            if (tstdate2 == 0)
	      {
	       return true;
	      }

           if ((tstdate > 0) && (tstdate2 > 0))
	      {
	          return true;
	      }
 
              alert(
                     "\r\r                           Stop date is " + document.stopsr.pd_stop_date.value + 
                     "\r\r   Entered date: " + document.stopsr.pd_entered_date.value +
                     " and Effective date: " + document.stopsr.pd_effective_date.value +
                     "\r\rThe Stop Date must be between the Entered and Effective dates" +
		                 "\r\r                       Please re-enter Stop Date.");
	       document.stopsr.pd_stop_date.focus();
               return false;
            							 
}
//
//
// Author:   Carroll McMann
// Date:		  NOV 2002
// Purpose:  IsYornValid makes sure that the answer is A Y or N
//  
// Parameters:  
// 	field:       DROP DOWN OR TEXT
//													
//										 
// How to use this function:
//	1.  This function needs to be called on the DROP DOWN OR TEXT events:
//							 									
// Begin script
//
   function IsYornValid() 
   {                
            if ((stopscf.pv_confirm.value == "N") || (stopscf.pv_confirm.value == "Y"))
            {
               return true;
            };
            alert( "You must Select ''Y'' to confirm update or ''N'' to cancel update. Please try again." );
            stopscf.pv_confirm.value.focus();
            return false;
   } 

//
//
//         Author   Alla Ilchenko  
//         Date:  07/06/2001       
//
//                validate Insurance Cancellation field; 
//
         function isInsuranceCancellationVal(theDate)
        {

     var chkFuture = "N";
     if (chkdate(theDate,chkFuture) == false) 
       {
          alert("That Cancellation Effective date is invalid.  Please try again.");
          theDate.focus();
          return false;
       }
       else
           {
            return true;
           }

}



//
//        
// Author:   Yukie



   function CheckSaValue(form) 
   {
	 var numbr;
   for (icnt=0; icnt < form.elements.length; icnt++){
       if (form.elements[icnt].type == "text"){
			     numbr = icnt;
           if (!isInteger(form.elements[icnt].value))
              {
              alert( "Please Enter a Number.");
              form.elements[numbr].focus();
              return false;
           }else { 
              return true;
           }
        }
    }
   }


//Tong Wang create ths fuction for log_comment field can not be exceed 4000 char
//On 04/02/02

function chk_max_char(fieldName){
  
  if ((fieldName.value.length)>4000)
   {
    alert(" The maximum letter you can enter for comment is 4000. \n" +
          " We will only keep 4000 characters in the field. \n" +
          " You can enter comment again. ");
      fieldName.value=strip_char(fieldName.value);
      fieldName.focus();
      return true;
  }
} //chk_max_char(this)

function strip_char(s){
  return s.substring(1,4000);
}


//
// author: unkown  code is associated with with PKG_HAZMAT_INCIDENT.prc_menu
//
function checkCategory(Display) {
   for (i=0; i < Display.elements.length; i++)
 	{
	if ((Display.elements[i].type == "checkbox")	&&
            (Display.elements[i].checked == true))
		{
		Display.submit();
		return true;
		} 
 	}
	alert("Please check at least one of the Hazmat Incident Category." );
	return false;
}


   function isUsdotInt(passedValue)              {
      for (i=0; i<passedValue.value.length; ++i)  {
       if ((passedValue.value.charAt(i) < "0") ||
	        (passedValue.value.charAt(i) == " ") ||
	        (passedValue.value.charAt(i) > "9"))   {  
	             return false
          }
       }
   return true
   }

   
   function CheckValue(form) 
   {
	 var num;
   for (i=0; i < form.elements.length; i++)
   {
       if (form.elements[i].type == "text")
       {
           num = i;
           if ((form.elements[i].value ==null)||
               (form.elements[i].value =="")  ||
               (isUsdotInt(form.elements[i])==false))
           {
              alert( "Please Enter a Number.");
              form.elements[num].focus();
              return false;
           }else { 
              return true;
           }
        }
    }
   }      
//
//
// Tong Wang
// program: PKG_BORDER_TRACK_ENTRY

//
   function checkSelect(form) 
   {   
   var hasChecked = false;	
   //var chkValue;
   //var txtValue;
   //var match1 = true;
   //var match2 = true;
   
   for (i=0; i < form.elements.length; i++){
    if (form.elements[i].type == "radio"){    
      if (form.elements[i].checked == true){
      chkValue = form.elements[i].value;
      hasChecked = true;  
      }
     }
    //if (form.elements[i].type == "text"){
    // txtValue = form.elements[i].value;
    // txtName = form.elements[i].name;
    //}      
    } //end for loop
    
    if (hasChecked){
      form.pv_cc_approve_num.value=stripInitialWhitespace(form.pv_cc_approve_num.value);
      if (form.pv_cc_approve_num.value == ""){
        alert("You should enter credit card approval number.");
        form.pv_cc_approve_num.focus();
        return false;
      }
      else 
       {form.submit();}
     //if ((chkValue == "D") && (txtValue != "")) {
     //  alert("NOT AUTHORIZED status should not have credit card approval number.");
     //  form.pv_cc_approve_num.focus();
     //  form.pv_cc_approve_num.value = "";
     //    match1 = false;
     //    return false;   
     //  }
     
    // if ((chkValue == "A") && (txtValue == "")) { 
    //    alert("AUTHORIZED status should have credit card approval number.");
    //    form.pv_cc_approve_num.focus();
    //    match2 = false;
    //    return false; 
    //   } 
     
    // if (match1 && match2){
    //   form.submit();
    // }
    } // end if hasChecked
     // not check radio button
    else { 
    alert("Please check credit card status before update");
     return false;
     }
   }
   
   function stripInitialWhitespace (s)
      {   var i = 0;
    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    return s.substring (i, s.length);
   }

//
//  written by Carroll McMann for stop action
// pkg_stop_action
//

//function hidessbutton()
//               {
//                ssbutton.style.visibility = "hidden";
//                ssbutton.filters.revealTrans.transition=12;
//                stopsc.style.visibility = "visible";
//                stopsc.filters.revealTrans.transition=12;
//                return;
//               }


   function verify() {
            var themessage = "You are required to complete the following fields: ";
//  check stop type
            if (document.stopsr.pv_stop_type.value == "X") 
						{
               themessage = themessage + " - stop type";              
							 document.stopsr.pv_stop_type.focus();
               alert( "You did not select a stop type. Please try again." );
							 return false;
            }
// check stop date

            if (document.stopsr.pd_stop_date.value == "" || 
						   document.stopsr.pd_stop_date.value == null) 
            {
							 document.stopsr.pd_stop_date.focus();
               alert("You did not enter a Stop Date. Please try again.")
               return false;
            }


            var dateStr = document.stopsr.pd_stop_date.value;
            var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
            var matchArray = dateStr.match(datePat); // is the format ok?            month = matchArray[1]; // parse date into variables
            month = matchArray[1];
            day = matchArray[3];
            year = matchArray[4];
            if (month < 1 || month > 12)  // check month range
            {
						   document.stopsr.pd_stop_date.focus();
               alert("Stop Date Month must be between 1 and 12.");
               return false;
            }
            if (month == 2)
						{
               if (day == 29 && (year % 4) != 0)  // check for leap year
               {
                  alert("Day must be less then 29");
    							document.stopsr.pd_stop_date.focus();
                  return false;
                }
            }			 
            if (month == 4 || month ==  6 || month ==  9 || month == 11)
            {
               if (day < 1 || day > 30) 
               {
                  alert("Day must be between 1 and 30.");
		  document.stopsr.pd_stop_date.focus();
                  return false;
							  }
						}
            if (day < 1 || day > 31) 
            {
               alert("Day must be between 1 and 31.");
	       document.stopsr.pd_stop_date.focus();
               return false;
            }

// Check difference between carrier_action.effective_date and stop_date
//
           if (stopsr.pd_stop_date.value == stopsr.pd_effective_date.value)
		{
//		 hidessbutton();
		 return true;
		}
          if (stopsr.pd_stop_date.value == stopsr.pd_entered_date.value)
		{
//		 hidessbutton();
		 return true;
		}
// check if stopdate is between effdate and entdate

            var var_stopdate = new Date(stopsr.pd_stop_date.value);
            var var_effdate  = new Date(stopsr.pd_effective_date.value);
            var var_entdate  = new Date(stopsr.pd_entered_date.value);

            if ((var_stopdate > var_entdate) && (var_stopdate < var_effdate))
              {
//		 hidessbutton();
		 return true;
              }
              
               alert(
                     "\r\r                           Stop date is " + document.stopsr.pd_effective_date.value + 
                     "\r\r   Entered date: " + document.stopsr.pd_entered_date.value +
                     " and Effective date: " + document.stopsr.pd_effective_date.value +
                     "\r\rThe Stop Date must be between the Entered and Effective dates" +
		                 "\r\r                       Please re-enter Stop Date.");
	       document.stopsr.pd_stop_date.focus();
               return false;
            							 
} 
// Tong Wang added on 05/12/03 for open oracle report
function submitReportRequest(obj,reportForm)
{
obj.disabled = true;
reportForm.submit();
}

//Alice Campbell, 07/19/2004, Determine if Y(es),N(o) entered for a field.
function isNotYesNo(inputstr1) {
               
  var goodvalues = ["YES","Y","yes","y","NO","N","no","n"];

  for (var i = 0; i < goodvalues.length; i++) {
    if (inputstr1.value == goodvalues[i]) {
      return false;
    }
  }
  return true;                           
}

function checkeEnCategory(form) 
{
     var vn_count = 0;

     for (i=0; i < form.pa_category.length; i++) {
       if (form.pa_category[i].selected){
          vn_count++;
          switch(form.pa_category[i].value){
          case "All":
             break;
          default:  //Property  0  
             if (form.pa_category[0].selected == true) {
                alert("You selected all categories of enterprise authority.");
                form.pa_category[1].selected = false;
                form.pa_category[2].selected = false;
                form.pa_category[3].selected = false;
                form.pa_category[4].selected = false;
                form.pa_category[5].selected = false;
                return false;
             } else if (form.pa_category[3].selected == true) {
                if (form.pa_category[4].selected == true) {
                   alert("You selected all Passenger Authorities.  The Passenger Common category is included." );
                   form.pa_category[4].selected = false;
                   form.pa_category[5].selected = false;
                   return false;
                } else if (form.pa_category[5].selected == true) {
                   alert("You selected all passenger Authorities.  The Passenger Regular Route category category is included." );
                   form.pa_category[5].selected = false;
                   return false;
                }
             } else if ((form.pa_category[4].selected == true) && (form.pa_category[5].selected == true)) {
                    alert("You selected Passenger Common and Regular Route.  These are the same as Passenger All." );
                   form.pa_category[3].selected = true;
                   form.pa_category[4].selected = false;
                   form.pa_category[5].selected = false;
                   return false;
             }
             break;
          }
        }
    }
   
    if (vn_count == 0){
       alert("Please select at lease one category." );
       return false;
    }
}
//  The function CheckShareselection is used for Shared Insurance selection criteria purpose.  7/11/2005
   function CheckShareselection(pv_type) 
   {
      if ((pv_type.name == "pv_all") && (pv_type.checked == true)){
           document.criteria.pv_property.checked = false;
           document.criteria.pv_passenger.checked = false;
           document.criteria.pv_hhg.checked = false;
      } else if ((document.criteria.pv_property.checked == true)  &&
                 (document.criteria.pv_passenger.checked == true) && 
                 (document.criteria.pv_hhg.checked == true)) {
           alert("You have selected all categories. All will be checked");
           document.criteria.pv_property.checked = false;
           document.criteria.pv_passenger.checked = false;
           document.criteria.pv_hhg.checked = false;
           document.criteria.pv_all.checked = true;
      } else if (document.criteria.pv_property.checked == true){
           document.criteria.pv_all.checked = false;
      } else if (document.criteria.pv_passenger.checked == true) {
           document.criteria.pv_all.checked = false;
      } else if (document.criteria.pv_hhg.checked == true) {
           document.criteria.pv_all.checked = false;
      } else if ((document.criteria.pv_all.checked == true) &&
         ((document.criteria.pv_property.checked == true) ||
          (document.criteria.pv_passenger.checked == true) ||
          (document.criteria.pv_hhg.checked == true))) {
           alert("You have selected all categories. All will be checked");
           document.criteria.pv_property.checked = false;
           document.criteria.pv_passenger.checked = false;
           document.criteria.pv_hhg.checked = false;
      } else if ((document.criteria.pv_property.checked == false)  &&
                 (document.criteria.pv_passenger.checked == false) && 
                 (document.criteria.pv_all.checked == false) && 
                 (document.criteria.pv_hhg.checked == false)) {
           alert("You must select categorie(s). All will be checked");
           document.criteria.pv_all.checked = true;
      }
   }


function CheckOnlyOne(p1,p2,p3) {
  
 var errMsg = "Please select a username or category, but not both.";
 var errMsg2 = "You cannot change your own account.  Please see another account administrator.";
if (p1.value != "NONE" && p2.value != "NONE"  && p1.value != "" && p2.value != "") {
alert(errMsg);
return false;
}else {
if (p1.value == p3.value) {
alert(errMsg2);
return false;
}
 return true;
}
}