// 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.
// checkMilitaryTime(theField)         Check that theField.value is a valid military time.
// 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 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

// 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"


/******************************* END PASSWORD CHECKER *******************************/
// This is the main password checking function
function checkPassword() {
var pw1eqpw2 = true;
var pw1;
var pw2;
 pw1 = document.pwform.password1.value;
 pw2 = document.pwform.password2.value;

	if(checkPasswordfirstcharalpha(pw1)){
	 if(checkPasswordLength(pw1)){
    if(checkPasswordCharsAllowed(pw1)){
     if(checkMinPasswordChars(pw1)){
		  if(checkPasswordpw1eqpw2(pw1,pw2)){
         document.pwform.submit();
				 return true;
			}  else {return false;}
    }  else {return false;}
   }  else {return false;}
  }  else {return false;}
 }  else {return false;}
}
// Check to make sure the first position of the password is alphabetic.
function checkPasswordfirstcharalpha(pw1) {
 var alpha = 0;

 if(isAlpha(pw1.charAt(0)))
   { 
	 	alpha = 1;
		};	
 var errMsg = "Your password does not start with a letter."
 if(alpha < 1) {
  alert(errMsg);
  return false;
 }
 return true;
}
// Check to make sure the password is at least minChars characters long.
function checkPasswordLength(pw1) {
var minChars = 8;
 if(pw1.length<minChars) {
  alert("You must choose a password that is at least "+minChars+" characters in length.")
  return false
 }
 return true
}

// Check to make sure that all of the characters in the password are allowed.
function checkPasswordCharsAllowed(pw1) {
var lettersAllowed = true;
var numbersAllowed = true;
var specialAllowed = false;
 for(var i=0;i<pw1.length;++i) {
  var ch = pw1.charAt(i);
  if((isAlpha(ch) && !lettersAllowed)) {
   alert("Your password contains a letter! \nLetters are not allowed in passwords.")
   return false
  }else if(isNumber(ch) && !numbersAllowed) {
   alert("Your password contains a number! \nNumbers are not allowed in passwords.")
   return false
  }else if(isSpecial(ch) && !specialAllowed) {
   alert("Your password contains a special character! \nSpecial characters are not allowed in passwords.")
   return false
  }else if(!isAlpha(ch) && !isNumber(ch) && !isSpecial(ch)) {
   alert("Your password contains a nonprintable character! \nNonprintable characters are not allowed in passwords.")
   return false
  }
 }
 return true
}

// Check to make sure the password has the required number of alphabetic, numeric, and
// special characters.
function checkMinPasswordChars(pw1) {
 var alpha = 0;
 var numeric = 0;
 var special = 0;
 var minLetters = 1;
 var minNumbers = 2;
 var minSpecial = 0;
 for(var i=0;i<pw1.length;++i) {
  var ch = pw1.charAt(i)
  if(isAlpha(ch)) ++alpha
  else if(isNumber(ch)) ++numeric
  else if(isSpecial(ch)) ++special
 }
 var errMsg = "Your password does not contain the minimum number "
 if(alpha < minLetters) {
  errMsg += "(" + minLetters + ") "
  errMsg += "of alphabetic characters!"
  alert(errMsg)
  return false
 }else if(numeric < minNumbers) {
  errMsg += "(" + minNumbers + ") "
  errMsg += "of numeric characters!"
  alert(errMsg)
  return false
 }else if(special < minSpecial) {
  errMsg += "(" + minSpecial + ") "
  errMsg += "of special characters!"
  alert(errMsg)
  return false
 } 
 return true
}
 
// Functions used for character identification.
function isAlpha(ch) {
  if(ch >= "a" && ch <= "z") return true
  if(ch >= "A" && ch <= "Z") return true
  return false
}

function isNumber(ch) {
  if(ch >= "0" && ch <= "9") return true
  return false
}

function isSpecial(ch) {
 var special = new Array("!","\"","#","$","%","&","''","(",")","*","+",",","-",".","/",
 ":",";","<","=",">","?","@","[","\\","]","^","_","`","{","|","}","~")
 for(var i=0;i<special.length;++i)
  if(ch == special[i]) return true
 return false
}

function checkPasswordpw1eqpw2(pw1,pw2)
{
 var errMsg = "Sorry, Your Entries Must Be Equal.";
				
				if (pw1 == pw2)
				{
				return true;
				}else
				alert(errMsg);
				return false;
}

function confirmDeleteUser(form){
   var message="Delete  " + form.pv_mcmis_user_id.value + " ? ";
      if (confirm(message)){
          form.pv_action.value = "Delete";
          return form.submit();
      }
      
      return false;	        
   }
   // end confirmDelete function
   
function ClearUserFilter()
   {
     for (i=0; i < document.user_search.elements.length; i++)
     {
         if (document.user_search.elements[i].type == "text")
         {
         document.user_search.elements[i].value = "";
         }
     }
     return false;
   }
  
function CheckUserValue(form) 
{
   if ((form.pv_action.value == "Modify")  &&
       (form.pv_status_code.value.toUpperCase() == "I")) {
      for (i=0; i < form.elements.length; i++) {
          if ((form.elements[i].name == "pa_group_id") &&
              (form.elements[i].checked == true)) {
                if (confirm("Inactivate the user ?")){
                    break;
                }else {
                form.elements[i].focus();
	                	return false;
                		  }
           }
     }
   }
   
   if ((form.pv_action.value == "Modify") || (form.pv_action.value == "Insert")) {
   for (i=0; i < form.elements.length; i++){
     if (!((form.elements[i].size  == null) || (form.elements[i].size  == ""))){
        if (form.elements[i].value.length > form.elements[i].maxlength){
		alert( "You entered " + form.elements[i].value.length + " /n Please enter no more than " + form.elements[i].maxlength + " characters.");
		form.elements[i].focus();
		return false;
	}else
        if ((form.elements[i].req=="y")&&  
	    ((form.elements[i].value  == null) || 
	     (form.elements[i].value  == ""  ))){
		alert( "You entered the empty value in required field.");
		form.elements[i].focus();
		return false;
	}
      }
   }
   }
   for (i=0; i < form.elements.length; i++){
      if (((form.elements[i].value ==null) ||(form.elements[i].value  =="")) && 
        (form.elements[i].name=="pa_cols")){
        form.elements[i].value = "~";
        }
   }
       return form.submit();
}

/******************************* END PASSWORD CHECKER *******************************/






// Check whether string s is empty.

function isEmpty(s)
         {   
         return ((s == null) || (s.length == 0))
         }



// Returns true if string s is empty or 
// whitespace characters only.

function isWhitespace (s)
         {   
         var i;
         // 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;
}

/****************          DATE FUNCTIONS          ****************/

// Main date function that calls the other functions.
// Checks the date and its format (must be MM/DD/YYYY, adds zeros to month/day if they're missing. Ex: 1/2/2001 -> 01/02/2001).
// Alerts the user and returns false if the date or the format is invalid.

function datecheck(dateField)
{
 if (isEmpty(dateField.value))
   return true;

 splitedDate = dateField.value.split("/");
 
 if (splitedDate.length == 3)
 {
  mm = splitedDate[0];  
  dd = splitedDate[1];
  yyyy = splitedDate[2];
        
     if (isYear(yyyy) && isMonth(mm) && isDay(dd) && 
         isDayofMonth(mm, dd) && isFebOk(mm, dd, yyyy) && isFebLeap(mm, dd, yyyy))
     {
        if (mm.length == 1)
          mm = 0 + mm;
        if (dd.length == 1)
          dd = 0 + dd;  
          
        dateField.value = mm + "/" + dd + "/" + yyyy;
        return true;
     }
 }

 alert ("The date or its format is invalid. Please try again.");
 dateField.focus();
 dateField.select();
 return false;

} 
	           
               // Returns false if the year is not valid
               function isYear(yyyy)
               {       
                if (yyyy.length == 4)
                  return isInteger(yyyy);

                return false;  
               }	
        
        
               // Returns false if the month is not valid
               // (must be a number between 1 and 12)
               function isMonth(mm)
               {
                  if (mm.length == 1 || mm.length == 2)
                    if (isInteger(mm))
                    {
                     mm = parseInt(mm, 10);  
                     if (mm >= 1 && mm <= 12)
                       return true;
                    }

                return false;
               }	

               // Returns false if the day is not valid
               // (must be a number between 1 and 31)
               function isDay(dd)
               {
                  if (dd.length == 1 || dd.length == 2)
                    if (isInteger(dd))
                    {    
                     dd = parseInt(dd, 10);
                     if (dd >= 1 && dd <= 31)
                       return true;
                    }

               return false;
               }
        
               // Returns false if the day = 31 and the month = April, June, Sept or Nov
               function isDayofMonth(mm, dd)
               {
                mm = parseInt(mm, 10);
                dd = parseInt(dd, 10);

                  if ((mm == 4) || (mm == 6) || (mm == 9) || (mm == 11))
                      if (dd == 31)
                        return false;

                return true;
               }
        
               // Returns false if the day is not valid for February 
               function isFebOk(mm, dd, yyyy)
               {
                mm = parseInt(mm, 10);
                dd = parseInt(dd, 10);
                
                if (mm == 2 && dd > 29)
                  return false;        
                else 
                  if (mm == 2 && !isFebLeap(mm, dd, yyyy)) 
                    return false;

                return true;
               }
        
               // Returns true if this is a leap year
               function isFebLeap(mm, dd, yyyy)
               {
                mm = parseInt(mm, 10);
                dd = parseInt(dd, 10);
                yyyy = parseInt(yyyy, 10);

                var year4 = yyyy/4;
                var year4rnd = Math.round(year4);
        
                  if (mm == 2 && dd == 29)
                      if (year4rnd != year4)
                        return false;    

                return true;
               }    

/****************          END OF DATE FUNCTIONS          ****************/   
///////////////////////////////////////////////////////////////////////////

//This function suppresses the Enter key when the cursor is inside a textbox.
//Needed for the pages with textboxes which use onblur() event for data validation
//The call to this function should be put inside the <body> tag to suppress the Enter key on all the textboxes on the page
//    or inside the <input type="Text"> to suppress the Enter key on a specific textbox

function suppressEnter()
{
 if (window.event.keyCode == 13)
   if(window.event.srcElement.type == "text")
      return false;

 return true;
}  

//This function performs forwarding to the log-off page
//It is called from the body of every document, but won't execute on the log-off page itself
function logOff() 
{
 if (window.location.href.substring(window.location.href.lastIndexOf("/")+1).toLowerCase != "pkg_mcmis_gui_common.prc_farewell_page")
 window.location.href = "pkg_mcmis_gui_common.prc_farewell_page";
}

//This function displays a warning in case the user's browser is different from IE 5.5 and up.
function checkBrowser()
{
var lowerCaseString = navigator.appVersion.toLowerCase();
var ieIndex = lowerCaseString.indexOf('msie');
if ((ieIndex == -1) || 
    (parseFloat(lowerCaseString.substring(ieIndex+5,lowerCaseString.indexOf(';',ieIndex))) < 5.5))
  {    
  document.write('<br><table align="center" width="80%" border="1" cellspacing="1">');
  document.write('<tr>');
  document.write('	<td align="center"><img src="warning_sign.gif" width="20" height="20" border="0" align="absmiddle" alt="Browser Compatibility Warning">  <font color="#ff0000" size="2"><b>WARNING:</b> The MCMIS application is compatible with Internet Explorer 5.5 and up, and may not work correctly with your browser.');
  document.write('        <br><a href="http://www.microsoft.com/downloads/search.aspx?displaylang=en" target="_blank" title="Microsoft download center">Click here to visit the Microsoft download center and get the latest version of Internet Explorer.</a></font></td>');
  document.write('</tr>');
  document.write('</table>');
  }
}


//This function disabled the object passed in as a parameter
function disableObject(obj)
{
obj.disabled = true;
}

function submitReportRequest(obj)
{
obj.disabled = true;
reportForm.submit();
}

function checkReqFields_disableSubmit(formObj, submitButton)
{
 if (checkRequiredFieldsForNull(formObj))
   {
   submitButton.disabled = true;
   return true;
   }
 return false;
}

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));
}


/* 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 theField.value is a valid military time
function checkMilitaryTime(theField)
{
counter = 0;
valueWithoutSpaces = theField.value.replace(/ /g, "");               //delete spaces if any found

if(valueWithoutSpaces.length==4)
{    
  for (i=0; i<4; i++)
  {
   if(isNaN(parseInt(valueWithoutSpaces.substr(counter, ++counter)))){  //if any of the 4 chars is not a number
     alertMilitaryTime();
     return;
     }
  }

     hours = parseInt(valueWithoutSpaces.substr(0,2));
     minutes = parseInt(valueWithoutSpaces.substr(2,2));
     
     if (hours >= 0 && hours < 24) {
       if (minutes < 0 || minutes > 59) {
         alertMilitaryTime();
         }
       }
  
     else {
       alertMilitaryTime();
       }
 }

 else if (valueWithoutSpaces=="")
    null;                                         //do nothing - let the user go  
 else { 
   alertMilitaryTime(); 
   }
  
   function alertMilitaryTime(){                  //inner function that pops up the alert box
   alert("That military time is invalid. Please try again.");
   theField.focus();
   theField.select();
   }
}



// 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;
            }
         }
         
//This function makes a hidden row visible, beginning with nextID (id of the next hidden row)
//Rows need to have unique ids in the following format: varName_nextSeqNo
//    where varName is any name that's unique on the page, and 
//          nextSeqNo is the next sequential number (a subscript)
//PS. If rows need to be hidden, use the hideRow() function
function showNextRow(nextID)
{
 var prefix = nextID.id.substring(0,nextID.id.lastIndexOf('_')+1);
 var startId = parseInt(nextID.id.substring(nextID.id.lastIndexOf('_')+1));
 for (i = startId; i < startId+200; i++)
 {
   if(document.all.item(prefix+i) == null)
   {
     alert("You reached the limit of additinal rows");
     return;
   }
   else if (eval(prefix+i).style.visibility == "")
   {
     show(eval(prefix+i));
     return;
   }  
 }
}

//This function hides a row
//Beside the decralred rowID argument, you'll need to pass all the form elements that this row contains
//   - the function will disable them so that they wouldn't be passed to the next screen
function hideRow(rowID)
{
 hide(rowID);
 for (i=1; i<arguments.length; i++)
 { 
   arguments[i].disabled = true;
 }
}

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") &&
                     (inputObject.disabled == false))
                     {
                      if (inputObject.type == "text")
                        inputObject.select();
                      else 
                        inputObject.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.pn_inspection_id.focus;
//         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";

         }

//Shows nextDIV and hides thisDIV
function showNextDiv(thisDivID, nextDivID)
{
 var divs = document.all.tags("DIV");
 var thisDivObject = divs[thisDivID-1];
 var nextDivObject = divs[nextDivID-1];

 show(nextDivObject);
 hide(thisDivObject);
 
 var inputObject = getInputObject(nextDivObject);
     if ((inputObject != null) && 
         (inputObject.type != "hidden") &&
         (inputObject.disabled == false))
     {
        if (inputObject.type == "text")
          inputObject.select();
        else 
          inputObject.focus();
     }
}

//Shows all the tabs on the page (by applying table_tab style to them)
function showAllTabs()
{
 var td = document.all.tags("TD");
 for (var i = 0; i < td.length; i++)
 {
  if (td[i].className == "table_tab")
      tabUp(td[i]); 
 }
}
         
         
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 > "999999999"))
      {
      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 the Header 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 checkHeaderdropdown(pv_header_choice) 
   { 
   i = headerDropdown.pv_header_choice.selectedIndex
   if (headerDropdown.pv_header_choice.options[i].value == "") 
      {
      alert("You must select an option");
      return false;
      }
   return true;      
   }


// This function checks the Registration 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 checkRegdropdown(pv_user_selection) 
   { 
   i = registrationDropdown.pv_user_selection.selectedIndex
   if (registrationDropdown.pv_user_selection.options[i].value == "") 
      {
      alert("You must select an option");
      return false;
      }
   return true;      
   }

// The following function calculates the total drivers in the Drivers tab area of Registration

function chk_drivers(elementname)
   {
//    editIntegerDefault2Zero(elementname);
    editInteger(elementname);
    calc_tot_drivers()
   }

function calc_tot_drivers()
   {
   document.REG.pv_total_drivers.value =       ((isIntNoBlank(document.REG.pv_interstate_within_100_miles.value)?parseInt(document.REG.pv_interstate_within_100_miles.value):0) 
                                      +         (isIntNoBlank(document.REG.pv_interstate_beyond_100_miles.value)?parseInt(document.REG.pv_interstate_beyond_100_miles.value):0)
                                      +         (isIntNoBlank(document.REG.pv_intrastate_within_100_miles.value)?parseInt(document.REG.pv_intrastate_within_100_miles.value):0)
                                      +         (isIntNoBlank(document.REG.pv_intrastate_beyond_100_miles.value)?parseInt(document.REG.pv_intrastate_beyond_100_miles.value):0)
                                      +         (isIntNoBlank(document.REG.pv_avg_drivers_leased_per_mo.value)?parseInt(document.REG.pv_avg_drivers_leased_per_mo.value):0) );
   }

// The following function protects the total drivers element because it is 
// automatically generated

function tot_drivers_protect()
   {
   alert('Total drivers is automatically calculated!');
   calc_tot_drivers();
   }


// The following function calculates the total drivers in the Review screen

function rev_calc_tot_drivers()
   {
   document.REV.pn_total_drivers.value =       ((isIntNoBlank(document.REV.pn_inter_within_100_miles.value)?parseInt(document.REV.pn_inter_within_100_miles.value):0) 
                                      +         (isIntNoBlank(document.REV.pn_inter_beyond_100_miles.value)?parseInt(document.REV.pn_inter_beyond_100_miles.value):0)
                                      +         (isIntNoBlank(document.REV.pn_intra_within_100_miles.value)?parseInt(document.REV.pn_intra_within_100_miles.value):0)
                                      +         (isIntNoBlank(document.REV.pn_intra_beyond_100_miles.value)?parseInt(document.REV.pn_intra_beyond_100_miles.value):0)
                                      +         (isIntNoBlank(document.REV.pn_avg_drivers_per_month.value)?parseInt(document.REV.pn_avg_drivers_per_month.value):0) );
   }

// The following function protects the review total drivers element because it is 
// automatically generated

function rev_tot_drivers_protect()
   {
   alert('Total drivers is automatically calculated!');
   rev_calc_tot_drivers();
   }

// The following function compares total CDL drivers and total drivers to assure that
// the total CDL drivers is not greater than the total drivers

function check_cdl(elementname)
   {
//    editIntegerDefault2Zero(elementname)
    editInteger(elementname);
	if (isIntNoBlank(document.REG.pv_total_cdl.value))
      if (parseInt(document.REG.pv_total_cdl.value) > parseInt(document.REG.pv_total_drivers.value))
           {
           alert('Total CDL drivers cannot be greater than the Total Drivers.')
           document.REG.pv_total_cdl.focus()
           document.REG.pv_total_cdl.select()
           }
   }

// This function makes sure that only one checkbox of a series of checkboxes, all with the same
// name, is checked.  It also makes sure that the user can't choose the modify AND delete 
// checkboxes together.  It is used in the Review Violation system.

function OnlyOne() {
var passed = true;
var total = 0;
var max = document.VIOLUPD.pn_rev_viol_temp_id.length;
var selection = 0;
for (var idx = 0; idx < max; idx++) {
if (eval("document.VIOLUPD.pn_rev_viol_temp_id[" + idx + "].checked") == true) {
  total += 1;
 }
}
if (total > 1) {
    alert("You selected " + total + " to Modify. Only one selection allowed for Modification.");
    passed = false;
    return passed;
  }
for (var idx = 0; idx < max; idx++) {
if (eval("document.VIOLUPD.pn_rev_viol_temp_id[" + idx + "].checked") == true && eval("document.VIOLUPD.ptv_delete_viol_ids[" + idx + "].checked") == true) {
  alert("Only one action allowed per violation. Please select either Modify or Delete.");
    passed = false;
    return passed;
 }
}


  return passed;
}

// 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 function checks the Review dropdown menu to see if an option 
// has been selected when the "Go" button was clicked;
// If not, it alerts the user to make a selection.

function checkRevdropdown(rev_option) 
   { 
   i = rev_option.pv_action.selectedIndex
   if (rev_option.pv_action.options[i].value == "") 
      {
      alert("You must select an option");
      return false;
      }
   return true;      
   }

// This function checks the Activity Page 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 checkActdropdown(activityForm) 
   { 
   if (activityForm.pv_selected_year.selectedIndex == 0) 
      {
      alert("You must select an option");
      return false;
      }
   return true;      
   }


function editIntegerReview(elementName)
   {
   if (!isIntNoBlank(elementName.value))
      {
      alert("\nValue entered must be an integer. \n");
      elementName.value="0";
      elementName.focus();
      elementName.select();
      return false
      }  
   else
      {
      rev_crash_rate();
      rev_oos_veh_rate();
      return true
      }
   }


function rev_oos_veh_rate()
   {
   var num_veh_total = (parseFloat(document.REV.pn_site_check_veh.value)
           +         parseFloat(document.REV.pn_carr_profile_veh.value));
   if(num_veh_total==0)
     {
      document.REV.pn_combined_oos_veh_rate.value="0";
      return;
     }
   else
     {
       var oos_rate =   (parseFloat(document.REV.pn_site_check_oos_veh.value) 
           +         parseFloat(document.REV.pn_carr_profile_oos_veh.value))
           /         num_veh_total;

       var valid = oos_rate.toString()
       var c = valid.indexOf(".")
            if(c==-1)
		{	
		totstr=valid
		}
            else
		{
		valsubstr1=valid.substring(0,c)						
		valsubstr2=valid.substring(c,c+4)
		totstr=valsubstr1+valsubstr2
		}
		oos_rate = totstr
        document.REV.pn_combined_oos_veh_rate.value=oos_rate
        checkOOSvehRate();  
      }
   }

// The following function protects the combined oos vehicle rate element because it is 
// automatically calculated

function oos_veh_rate_protect()
   {
   alert('Out of Service Vehicle Rate is automatically calculated!');
   rev_oos_veh_rate();
   }

//The following function does not allow values greater than 99.999 for combined oos 
//vehicle rate element

function checkOOSvehRate()
{
 if (parseFloat(document.REV.pn_combined_oos_veh_rate.value) > 99.999)
  {
   alert('OOS Veh Rate cannot be greater than 99.999')
   document.REV.pn_site_check_veh.value = "0";
   document.REV.pn_site_check_oos_veh.value = "0";
   document.REV.pn_carr_profile_veh.value = "0";
   document.REV.pn_carr_profile_oos_veh.value = "0";
   document.REV.pn_combined_oos_veh_rate.value = "0";
   document.REV.pn_site_check_oos_veh.focus()
   document.REV.pn_site_check_oos_veh.select()
  }
}

function calc_power_units()
{ var equip_count = document.REG.ptv_equipment_count;
  var own_type = document.REG.ptv_ownership_type;
  var equip_type = document.REG.ptv_equipment_type;
  var tot_trucks = 0;
  var tot_buses = 0;
  var tot_power_units = 0;
  if (equip_type != null)
  {
   for (i=1; i<equip_type.length; i++)
     { if ((equip_type[i].value == "A")||(equip_type[i].value == "B")||(equip_type[i].value == "E"))
        {
//		 if (isIntNoBlank(equip_count[i].value))
         tot_trucks = tot_trucks + parseInt(equip_count[i].value);
        }
      if ((equip_type[i].value == "F")||(equip_type[i].value == "G")||(equip_type[i].value == "H")||(equip_type[i].value == "I"))
        {
//		 if (isIntNoBlank(equip_count[i].value))
         tot_buses = tot_buses + parseInt(equip_count[i].value);
        }
      }
   document.REG.pn_tot_trucks.value = tot_trucks;
   document.REG.pn_tot_buses.value = tot_buses;
   tot_power_units = tot_trucks + tot_buses;
   document.REG.pn_power_units.value = tot_power_units;}
}


function checkEquipment()
{ var equip_count = document.REG.ptv_equipment_count;
  var own_type = document.REG.ptv_ownership_type;
  var equip_type = document.REG.ptv_equipment_type;
  var tot_trucks = 0;
  var tot_buses = 0;
  var tot_power_units = 0;
  var temp = "";
  if (equip_type != null)
  {
    for (x=1; x<equip_type.length; x++)
      {
      if (!editInteger(equip_count[x]))
        {
        return false;
        }
      else
        {
        if (isIntNoBlank(equip_count[x].value))
	        {
  	      if ((equip_type[x].value == "A")||(equip_type[x].value == "B")||(equip_type[x].value == "E"))
            {
            tot_trucks = tot_trucks + parseInt(equip_count[x].value);
            }
          if ((equip_type[x].value == "F")||(equip_type[x].value == "G")||(equip_type[x].value == "H")||(equip_type[x].value == "I"))
            {
            tot_buses = tot_buses + parseInt(equip_count[x].value);
            }
          
          }
        } //end if
      } //end loop
   document.REG.pn_tot_trucks.value = tot_trucks;
   document.REG.pn_tot_buses.value = tot_buses;
   tot_power_units = tot_trucks + tot_buses;
   document.REG.pn_power_units.value = tot_power_units;
  } //end if
  return true;
}

function rev_crash_rate()
   {
   var crash_rate = 0;
   var total_miles = parseFloat(document.REV.pn_total_miles.value);
   if(total_miles == 0)
     {
      if (document.REV.pv_rev_version_number.value == 60)      
        {  
         document.REV.pn_prev_record_crash_million.value="0";
         return;
        }
      if ((document.REV.pv_rev_version_number.value == 80)||(document.REV.pv_rev_version_number.value == 90))
        {  
         document.REV.pn_record_crash_million.value="0";
         return;
        }         
     }
   else
     {
      if (document.REV.pv_rev_version_number.value == 60)
        {
         crash_rate = ((parseFloat(document.REV.pn_prev_record_crash.value)*1000000)/total_miles);
        }
      if ((document.REV.pv_rev_version_number.value == 80)||(document.REV.pv_rev_version_number.value == 90))
        {
         crash_rate = ((parseFloat(document.REV.pn_record_crash.value)*1000000)/total_miles);
        }
         
      var crash_rate_str = crash_rate.toString()
      var c = crash_rate_str.indexOf(".")
        if(c==-1)
	  {	
	   totstr=crash_rate_str
	  }
        else
	  {
	   valsubstr1=crash_rate_str.substring(0,c)						
	   valsubstr2=crash_rate_str.substring(c,c+4)
	   totstr=valsubstr1+valsubstr2
	  }
	crash_rate = totstr
      if (document.REV.pv_rev_version_number.value == 60)
        {
         document.REV.pn_prev_record_crash_million.value=crash_rate
        }
      if ((document.REV.pv_rev_version_number.value == 80)||(document.REV.pv_rev_version_number.value == 90))
        {
         document.REV.pn_record_crash_million.value=crash_rate
        }
     checkCrashesMillionMiles()
      }
   }

//The following function does not allow values greater than 999.999 for preventable recordable
//crashes per million miles element and recordable crashes per million miles element

function checkCrashesMillionMiles()
{
 if (document.REV.pv_rev_version_number.value == 60)
   { 
    if (parseFloat(document.REV.pn_prev_record_crash_million.value) > 999.999)
      {
       alert('Preventable recordable crashes per million miles cannot be greater than 999.999')
       document.REV.pn_total_miles.value = "0";
       document.REV.pn_prev_record_crash.value = "0";
       document.REV.pn_prev_record_crash_million.value = "0";
       document.REV.pn_total_miles.focus()
       document.REV.pn_total_miles.select()
      }
   }

 if ((document.REV.pv_rev_version_number.value == 80)||(document.REV.pv_rev_version_number.value == 90))
   {
    if (parseFloat(document.REV.pn_record_crash_million.value) > 999.999)
      {
       alert('Recordable crashes per million miles cannot be greater than 999.999')
       document.REV.pn_total_miles.value = "0";
       document.REV.pn_record_crash.value = "0";
       document.REV.pn_record_crash_million.value = "0";
       document.REV.pn_total_miles.focus()
       document.REV.pn_total_miles.select()
      }
   }
}

//This function enables all disabled fields for submission. This was needed because
//apparently, disabled fields do not get submitted

function enablefields()
{ var coll = document.all;
  if (coll != null)
    {
     for (i=0; i<coll.length; i++)
       {
       if(coll.item(i).disabled==true)
         {coll.item(i).disabled=false;}

       if (coll.item(i).type == "submit")
              coll.item(i).disabled=true;
       }
       
     return;
    }
}


function checkReviewdate(addReviewForm)
{
   if (checkRequiredFieldsForNull(addReviewForm))
       return (datecheck(addReviewForm.pv_review_date));
   else   
       return false;
}

function study4()
{
  if (parseInt(document.REV.pv_rev_version_number.value) >= 90)
  {
  var unfit1 = document.REV.pv_transport_passenger.value;
  if (isEmpty(unfit1))
    { 
     unfit1 = ' ';
    }
  var unfit2 = document.REV.pv_transport_hm_placard.value;
  if (isEmpty(unfit2))
    {
     unfit2 = ' ';
    }
  document.REV.pv_study4.value =  unfit1 + unfit2 + document.REV.pv_unsat_unfit_rule.value;
  }
}

// These three functions check the dropdown menus on the Inspection selection page
// to see if an option has been selected before the "Go" button was clicked;
// If not, they alert the user to make a selection. (Each function is specific
// to one dropdown menu.)

function checkInspection1() 
   { 
   i = inspection1.pv_choose1.selectedIndex
   if (inspection1.pv_choose1.options[i].value == "") 
      {
      alert("You must select an option");
      return false;
      }
   return true;      
   }

function checkInspection2() 
   { 
   i = inspection2.pv_choose2.selectedIndex
   if (inspection2.pv_choose2.options[i].value == "") 
      {
      alert("You must select an option");
      return false;
      }
   return true;      
   }

function checkInspection3() 
   { 
   i = inspection3.pv_choose3.selectedIndex
   if (inspection3.pv_choose3.options[i].value == "") 
      {
      alert("You must select an option");
      return false;
      }
   return true;      
   }


//This function checks for nulls and invalid characters and defaults them to zero.  
//If there are no errors, then it calls the total driver's function to calculate the 
//total drivers.  This is written on 06-04-01 to take care of the NaNs.

function editIntegerRevDrivers(elementName)
   {
//New version - Al Belsky 06/18/2003
if (editInteger(elementName))   
     {
      rev_calc_tot_drivers();
      return true;
     }
return false;   

/*  old version
   if (!isIntNoBlank(elementName.value))
      {
      alert("\nInvalid entry. Will default to zero. \n");
      elementName.value="0";
      elementName.focus();
      elementName.select();
      return false
      }
      else
     {
      rev_calc_tot_drivers();
      return true
     }
*/	 
   }

   
// This function makes sure that all required text fields have no null values (or spaces only).
// In case they do, it alerts the user 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 !***
   
 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].req == "true")		//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 return true;
 }


//---------------------------------------------------
 
  function validateEnfReassign(theForm) 
    { 
     if (checkRequiredFieldsForNull(theForm) == false)
     return false;
     
      if (document.all.pn_chosen_enf_id)                                  //if at least one checkbox exists
          if (isCheckboxSelected(theForm)==false)                         //check if at least one checkbox is checked
            {  
              alert("You must check at least one Enforcement to process");
              theForm.pn_chosen_enf_id[1].focus();  
              return false;  
             } 
      
      //check if a Reason for Change is selected
      if (isReasonCodeSelected(theForm) == false)  
        { 
          alert("You must select Reason for Change");  
          return false;  
         }  
       return true;        
     } 
 
//---------------------------------------------------

  function ValidateInspReassign(insp_reassign_list) 
    {  
      if (document.all.pn_chosen_inspection_id)                           //if at least one checkbox exists
          if (isCheckboxSelected(insp_reassign_list)==false)              //check if at least one checkbox is checked
            {  
              alert("You must check at least one Inspection to process");
              insp_reassign_list.pn_chosen_inspection_id[0].focus();  
              return false;  
             } 
      
      //check if a Reason for Change is selected
      if (isReasonCodeSelected(insp_reassign_list) == false)  
        { 
          alert("You must select Reason for Change");  
          return false;  
         }  
       return true;        
     } 

   function checkAll(list_length,page_length)  
     {  
       var i;  
       for (i = list_length - page_length ; i < list_length; i++)  
         document.insp_reassign_list.pn_chosen_inspection_id[i].checked = true;  
      }  
  
  function uncheckAll(list_length,page_length) 
    { 
      var i; 
      for (i = list_length - page_length ; i < list_length; i++) 
        document.insp_reassign_list.pn_chosen_inspection_id[i].checked = false;  
     } 

  function clickCancel() 
    {  
      parent.history.go(-1);  
     } 

function clickSubmit ()  
  {  
    if (document.insp_update.pv_action.value == "Modify") 
     {  
       document.insp_update.action = "PKG_INSP_ONLINE_DB_MANIP.PRC_INSPECTION_UPDATE" ;  
      }   
   else  
     {   
       document.insp_update.action = "PKG_INSP_ONLINE_DB_MANIP.PRC_INSPECTION_DELETE" ;  
      }   
   }  

  
  function isAllZero (s)  
    {  
      var i;  
      for (i = 0; i < s.length; i++)  
        {     
          var c = s.charAt(i);  
          if ( c != "0" )  
          return false;  
        } 
      return true;  
     }  

  function ValidateInspDetail(insp_detail_form)  
    {  
      i = insp_detail_form.pv_reason_code.selectedIndex;
      if (checkRequiredFieldsForNull(insp_detail_form)==false)
        {
         return false;
        } 
      if (isReasonCodeSelected(insp_detail_form)==false)
        {
         alert("You must select Reason for Reassign");
         return false;
        }
      return true;
     }   

//This function is specific to Crash reassign screen
function checkCrashForm(form)
{
  if (document.all.pn_chosen_crash_id)           //if there's at least one checkbox
      if (isCheckboxSelected(form)==false)       //check if at least one checkbox is checked
      {
       alert("You must select at least one Crash to process");
       form.pn_chosen_crash_id[0].focus();
       return false;
      }

  if (isReasonCodeSelected(form)==false)
  {
   alert("You must select Reason for Reassign");
   return false;
  }
  return true;
}

//This function checks month/year dropdowns in the Crash/Inspection Narrow Search
function checkNarrowSearch(form)
{
 if (form.pv_month.selectedIndex == 0)
  {
   alert("You must select Month"); 
   form.pv_month.focus();
   return false;
  }
 if (form.pv_year.selectedIndex == 0)
  {
   alert("You must select Year"); 
   form.pv_year.focus();
   return false;
  }
  return true;
}

//This function is specific to Reassign screens
function checkReasonCode(form)
{
  if (isReasonCodeSelected(form)==false)
  {
   alert("You must select Reason for Reassign");
   return false;
  }
  return true;
}

//Generic function. Returns false if there's no Reason for Change selected.
//No message alert box.
//(works with the dropdown object generated by PKG_MCMIS_GUI_COMMON.PRC_REASON_CHANGE_DROPDOWN)
function isReasonCodeSelected(form)
{
  if (form.pv_reason_code.selectedIndex == 0)
    {
     form.pv_reason_code.focus(); 
     return false;
    }
  return true;  
}

//Generic function. Returns false if there's no Reason for Change selected.
//This one pops up a message
//(works with the dropdown object generated by PKG_MCMIS_GUI_COMMON.PRC_REASON_CHANGE_DROPDOWN)
function CheckReasonCodeGen(form)
{
  if (form.pv_reason_code.selectedIndex == 0)
    {
     alert("You must select a Reason");
     form.pv_reason_code.focus(); 
     return false;
    }
  return true;  
}

//Generic function. Returns true if at least one required checkbox is checked.
// ***! Required checkboxes must be marked with id="required" in the form !***
function isCheckboxSelected(form)
{
 var isFound = false;
  for (i=1; i<form.elements.length; i++)
  {
    if (form.elements[i].type == "checkbox")
    if (form.elements[i].req == "true")		//if the text field is marked as "required"
    {
     isFound = true;
     if (form.elements[i].checked == true)
     return true;
    }
  }
 if (isFound == true)
  return false;
 else
  return true;
}

//This function is used in Registration Selections to warn users that they are
//editing a secondary carrier.

function isSecondary()
{
 if (PlaceHolder.SecondaryIndicator.value == "Y")
 {
  var msg = "You are attempting to edit a secondary carrier. \n" +
            "The carrier status cannot be changed to ACTIVE. \n" +
            "Are you sure you want to edit this carrier?";
 
  if (confirm(msg))
     return true;
  else
     return false;
 }
  return true;
}

// The following functions check and calculate the total drivers in the Drivers area on MCS150s

function chk_ADD150_drivers(elementname)
   {
//    editIntegerDefault2Zero(elementname);
    if (editInteger(elementname))
      calc_ADD150_tot_drivers(); 
   }

function calc_ADD150_tot_drivers()
   {
       document.MCS150P2.pv_total_drivers.value = ((isIntNoBlank(document.MCS150P2.pv_interstate_within_100_miles.value)?parseInt(document.MCS150P2.pv_interstate_within_100_miles.value):0)
                                      + (isIntNoBlank(document.MCS150P2.pv_interstate_beyond_100_miles.value)?parseInt(document.MCS150P2.pv_interstate_beyond_100_miles.value):0)
                                      + (isIntNoBlank(document.MCS150P2.pv_intrastate_within_100_miles.value)?parseInt(document.MCS150P2.pv_intrastate_within_100_miles.value):0)
                                      + (isIntNoBlank(document.MCS150P2.pv_intrastate_beyond_100_miles.value)?parseInt(document.MCS150P2.pv_intrastate_beyond_100_miles.value):0) );
   }


function chk_MOD150_drivers(elementname)
   {
//    editIntegerDefault2Zero(elementname);
    if (editInteger(elementname))
      calc_MOD150_tot_drivers();
   }

function calc_MOD150_tot_drivers()
   {
   document.MCS150P2.pv_total_drivers.value = ((isIntNoBlank(document.MCS150P2.pv_interstate_within_100_miles.value)?parseInt(document.MCS150P2.pv_interstate_within_100_miles.value):0) 
                                      + (isIntNoBlank(document.MCS150P2.pv_interstate_beyond_100_miles.value)?parseInt(document.MCS150P2.pv_interstate_beyond_100_miles.value):0) 
                                      + (isIntNoBlank(document.MCS150P2.pv_intrastate_within_100_miles.value)?parseInt(document.MCS150P2.pv_intrastate_within_100_miles.value):0) 
                                      + (isIntNoBlank(document.MCS150P2.pv_intrastate_beyond_100_miles.value)?parseInt(document.MCS150P2.pv_intrastate_beyond_100_miles.value):0) 
                                      + (isIntNoBlank(document.MCS150P2.pv_avg_drivers_leased_per_mo.value)?parseInt(document.MCS150P2.pv_avg_drivers_leased_per_mo.value):0) );
   }


// The following function protects the total drivers element on MCS150s because it is 
// automatically generated

function tot_MCS150_drivers_protect()
   {
   alert('Total drivers is automatically calculated!');
   calc_MCS150_tot_drivers();
   }


// The following function compares total CDL drivers and total drivers on MCS150s to assure that
// the total CDL drivers is not greater than the total drivers

function check_MCS150_cdl(elementname)
   {
//    editIntegerDefault2Zero(elementname)
    editInteger(elementname)
	if (isIntNoBlank(document.MCS150P2.pv_total_cdl.value))
      if (parseInt(document.MCS150P2.pv_total_cdl.value) > parseInt(document.MCS150P2.pv_total_drivers.value))
           {
           alert('Total CDL drivers cannot be greater than the Total Drivers.')
           document.MCS150P2.pv_total_cdl.focus()
           document.MCS150P2.pv_total_cdl.select()
           }
   }

// The following function checks the DOT Number field on MCS150 adds (both public and internal) 
// and generates an alert if a DOT Number is entered

function ckDOTNumber(s)
   {
   if (s.value.replace(/ *$/,"") == "")
       return true;
   else
        alert('If you already have a DOT Number, you cannot add another MCS-150. \n' +
                 'For more information, contact Computer Technologies at 1-800-832-5660.');
   }

//The following function checks the Federal part no fields to not exceed more than 3 characters

function ckfpPARTNO(elementName)
   {
   if ((elementName.value.indexOf('.')) > 3) 
      {
      alert('Part No must be three characters or less');
      elementName.select();
      elementName.focus();
      }
   else if ((((elementName.value.indexOf('.')) == -1) ||
((elementName.value.indexOf('.')) < 3)) &&
      (((elementName.value.replace(/^.*\./,"").length) > 40)) &&
      (((elementName.value.length) > 0)))
      {
      alert('Part No Section must be forty characters or less');
      elementName.select();
      elementName.focus();
      }
//AD20030624 added the for loop below to prevent special characters in part no section
   for(var i=0;i<elementName.value.length;++i) 
      {
      var ch = elementName.value.charAt(i);
      
      //Al Belsky 07/03/2003: added the line below to allow a space in the first position
      if ((i==0) && (ch==" "))
        continue;
        
      if(!isAlpha(ch)) 
         {
         if (!isNumber(ch))
           {
           if (ch != "." && ch != "(" && ch != ")")
              {
              alert('Special Characters not allowed in Part No/Section');
              elementName.select();
              elementName.focus();
              return;
              }
           }
         }
      }
   }    
   
   

//The following function checks Modify/Add OOS Record screen
function checkOosForm(form)
{
if (checkRequiredFieldsForNull(form) == false)
return false;

today = new Date();
s_date = new Date(form.pv_oos_date.value.substr(6), form.pv_oos_date.value.substr(0,2)-1, form.pv_oos_date.value.substr(3,2));

if(form.pv_rescinded_date.value != "")
  r_date = new Date(form.pv_rescinded_date.value.substr(6), form.pv_rescinded_date.value.substr(0,2)-1, form.pv_rescinded_date.value.substr(3,2));
else
  r_date = "";

if (today.getTime() >= s_date.getTime())
 { 
 if (r_date != "")
   {
    if (today.getTime() < r_date.getTime())
       {
       alert("Rescind Date must be earlier or the same as today's date");
       form.pv_rescinded_date.select();
       form.pv_rescinded_date.focus();
       return false;
       }
    else if (r_date.getTime() < s_date.getTime())
       {
       alert("Rescind Date must be later than OOS Date");
       form.pv_rescinded_date.select();
       form.pv_rescinded_date.focus();
       return false;
       }
   }
 }
else 
 { 
 alert("OOS Date must be earlier or the same as today's date");
 return false;
 }

if (form.pv_oos_reason.selectedIndex == 0)
 {
 alert("You must select OOS Reason");
 form.pv_oos_reason.focus();
 return false; 
 }

return true;
}

//This function is specific to Docket screen
function checkDocket(form)
{
  if (isPrefixSelected(form)==false)
    {
     alert("You must select a Prefix for the Docket Number");
     return false;
    }
  else if (checkRequiredFieldsForNull(form)==false)
    {
     return false;
    }
  return true;
}

//For Docket Screen. Returns false if there's no Prefix selected.
function isPrefixSelected(form)
{
  if (form.pv_prefix.selectedIndex == 0)
    {
     form.pv_prefix.focus(); 
     return false;
    }
  return true;  
}

function editZipCharsSearch(elementName) 
{ 
if (!(isZipChars(elementName.value))) 
{ 
alert("\nValue entered contains invalid character(s). \n") 
elementName.value = "" 
elementName.focus() 
return false 
} 
else 
{ 
return true 
} 
} 


function editIntegerSearch(elementName) 
{ 
if (!isInt(elementName.value)) 
{ 
alert("\nValue entered must be an integer. \n") 
elementName.value = "" 
elementName.focus() 
return false 
} 
else 
{ 
return true 
} 
} 

//This function sets dropdown selection to #1/#2 (Approve/Reject, for example) 
//based on the first letter of the name of the clicked object (button, checkbox)
function selectApproveRejectAll(objectClicked, elementArray)
{
   //Multiple drop-downs on the page
   if (elementArray.name == null)
   {
      for (i = 0; i < elementArray.length; i++)
      {
       if (objectClicked.name.substr(0,1) == "A")
         elementArray[i].selectedIndex = 1
       else
         elementArray[i].selectedIndex = 2
      }
   }
   //Single drop-down on the page
   else 
      {
       if (objectClicked.name.substr(0,1) == "A")
         elementArray.selectedIndex = 1
       else
         elementArray.selectedIndex = 2
      }
}

//This function sets checkbox selection to checked 
//based on the first letter of the name of the clicked object (checkbox)
function RemoveAll(objectClicked, elementArray)
{

  for (i = 0; i < elementArray.length; i++)
  { 
     
   if (objectClicked.name.substr(0,1) == "R")
   
   elementArray(i).checked = true;
     
  }
}


// This function change text to ~ if the text field is null.
function changeTextNullToTilda(form) {
	for (i=0; i < form.elements.length; i++)
	{	
		if (form.elements[i].type == "text")  
		{
			if ((form.elements[i].value == null) ||
				(form.elements[i].value == "")) 
			{
				form.elements[i].value = "~";
			}
		}
	}
	return true;
}

//This function is generic. It checks the specified dropdown object selection.
//Will alert the user with the value of the MESSAGE parameter, or the default message
function checkDropdown(objDropDown, message)
{
 if (objDropDown.selectedIndex == 0)
  {
   if (message == null)
     alert("You must select an option"); 
   else
     alert(message); 
   objDropDown.focus();
   return false;
  }
  
  return true;
}


// function is specific to cargo_tanks's pkg_ct_review_appl_detail
//
function ct_review_appl_detail_validate()
{
  var index;
  var index2;

  for (index=0; index < document.forms[1].pv_rev_action.length; index++)
  {

    if (document.forms[1].pv_rev_action[index].checked) 
    {
     if (document.forms[1].pv_rev_action[index].value == 'R') 
       { 
         for (index2=0; index2 < document.forms[1].ptv_reject_message.length; index2++)
         {
            if (document.forms[1].ptv_reject_message[index2].checked)
            {
              return true;
            }
         }
         alert('A rejected application must have at least one reason for rejection.')
         return false;
       }
     else
       {
        return true;
       }
    }
  }   
alert('An application must be approved or rejected to be processed.')
return false;
}


//Generic function used in the footer of all pages
//Override the onSubmit handler of the form by appending disableSubmitButtons() function call
function onSubmit_disableSubmitButtons()
{
  for (i=0; i<document.forms.length; i++)
  {
    strOldHandler = document.forms[i].onsubmit + "";
    if (strOldHandler != "null")
    {
      //If the function called onSubmit returns a value
      if (strOldHandler.substring(23,29).toLowerCase() == "return")
      { 
         //Get the call itself (strip off "function {....}" from the string)
         strOldCall = strOldHandler.substring(30, strOldHandler.length-2);
         //Strip off the possible semi-colon at the end of the call
         strOldCall = strOldCall.replace(/;*$/, "");
         document.forms[i].onsubmit = new Function(
                "if ("+strOldCall+") {disableSubmitButtons(); return true;} " +
                "else return false;");
      }
      //Straight call
      else
      {
        document.forms[i].onsubmit = new Function(strOldHandler.substring(23,strOldHandler.length-2)+"; disableSubmitButtons(window.event.srcElement);");
      }
    }
    else
      document.forms[i].onsubmit = new Function("disableSubmitButtons(window.event.srcElement);");    
  }
}

function disableSubmitButtons()
{
  //Loop through all the forms
  for (i=0; i<document.forms.length; i++)
  {
    for (ii=0; ii < document.forms[i].elements.length; ii++)
    {
      if (document.forms[i].elements[ii].type == "submit" || document.forms[i].elements[ii].type == "button")
      {
        document.forms[i].elements[ii].disabled = true;
      } 
    }
  }
}

//Generic function. Checks or unchecks all the checkboxes passed in based on the object calling the function
//You can pass in an unlimited number of parameters. The parameters could be arrays or stand-alone checkboxes.
//If no parameters provided, all the checkboxes on the screen will be checked/unchecked.
function checkUncheckAll()
{ 
 var blnChecked;
 //Determine if the checkboxes should be checked or unchecked
 if ((window.event.srcElement.value.substring(0,5).toUpperCase() == "CHECK")||
     (window.event.srcElement.type == "checkbox"
      && window.event.srcElement.checked == true))
      blnChecked = true;
 else 
      blnChecked = false;

 //If no arguments were passed it, check all the checkboxes in the screen
 if (arguments.length == 0)
   {
   for (i=0; i<document.forms.length; i++)
     for (ii=0; ii < document.forms[i].elements.length; ii++)
       if (document.forms[i].elements[ii].type == "checkbox" && !document.forms[i].elements[ii].disabled)
         document.forms[i].elements[ii].checked = blnChecked;
   } 
 else
   //Loop through the arguments passed in
   for (i=0; i<arguments.length; i++)
     {
     if (arguments[i].length > 0)
       //Loop through the array of checkboxes
       {
       for (ii=0; ii<arguments[i].length; ii++)
         if (arguments[i][ii].type == "checkbox" && !arguments[i][ii].disabled)
           arguments[i][ii].checked = blnChecked;
       }
     else
         //Single checkbox
         if (arguments[i].type == "checkbox" && !arguments[i].disabled)
           arguments[i].checked = blnChecked;
     }
}

// 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
function limitTextarea(field, countfield, maxlimit) 
{
	 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;
		  }
	else 
		// otherwise, update *characters left* counter
		countfield.value = maxlimit - field.value.length;
}
// End function limitTextarea

//copy functions from PKG_SI by Tong Wang 10/16/2007 
function confirmDelete(form){
  var message="Delete  " + form.pv_first.value + " " + form.pv_last.value + " ? ";
  if (confirm(message)){
     form.pv_action.value = "Delete";
     return form.submit();
   }

   return false;
}
   // end confirmDelete function


//  End -->
