// FormChek.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)
//	- credit card numbers
//
// 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.
// checkDate(txtDate)					True if string arguments form a valid date.
// trim(myStr,model)					Trims the string values (model = both, left, right)
//
// 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.

// FUNCTIONS TO INTERACTIVELY CHECK FIELD CONTENTS:
//
// checkString (theField, s [,eok])    Check that theField.value is not empty or all whitespace.
// checkStateCode (theField)           Check that theField.value is a valid U.S. state code.
// checkZIPCode (theField [,eok])      Check that theField.value is a valid ZIP code.
// checkUSPhone (theField [,eok])      Check that theField.value is a valid US Phone.
// checkInternationalPhone (theField [,eok])  Check that theField.value is a valid International Phone.
// checkEmail (theField [,eok])        Check that theField.value is a valid Email.
// checkSSN (theField [,eok])          Check that theField.value is a valid SSN.
// checkYear (theField [,eok])         Check that theField.value is a valid Year.
// checkMonth (theField [,eok])        Check that theField.value is a valid Month.
// checkDay (theField [,eok])          Check that theField.value is a valid Day.
// checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
//                                     Check that field values form a valid date.
// DaysBetween(firstDate,secoundDate)  return number of days between todates
// getRadioButtonValue (radio)         Get checked value from radio button.
// checkCreditCard (radio, theField)   Validate credit card info.

// CREDIT CARD DATA VALIDATION FUNCTIONS
// 
// isCreditCard (st)              True if credit card number passes the Luhn Mod-10 test.
// isVisa (cc)                    True if string cc is a valid VISA number.
// isMasterCard (cc)              True if string cc is a valid MasterCard number.
// isAmericanExpress (cc)         True if string cc is a valid American Express number.
// isDinersClub (cc)              True if string cc is a valid Diner's Club number.
// isCarteBlanche (cc)            True if string cc is a valid Carte Blanche number.
// isDiscover (cc)                True if string cc is a valid Discover card number.
// isEnRoute (cc)                 True if string cc is a valid enRoute card number.
// isJCB (cc)                     True if string cc is a valid JCB card number.
// isAnyCard (cc)                 True if string cc is a valid card number for any of the accepted types.
// isCardMatch (Type, Number)     True if Number is valid for credic card of type Type.
//
// Other stub functions are retained for backward compatibility with LivePayment code.
// See comments below for details.
//
// Performance hint: when you deploy this file on your website, strip out the
// comment lines from the source code as well as any of the functions which
// you don't need.  This will give you a smaller .js file and achieve faster
// downloads.
//
// 18 Feb 97 created Eric Krock
//
// (c) 1997 Netscape Communications Corporation

// 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

// non-digit characters which are allowed in credit card numbers
var creditCardDelimiters = " "

// 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 sCreditCardNumber = "Credit Card 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 iCreditCardPrefix = "This is not a valid "
var iCreditCardSuffix = " credit card number. (Click the link on this form to see a list of sample numbers.) 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 pCreditCard = "valid credit card number."
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"

// 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++)
    {   
        // Check that current character is number or letter.
        var c = s.charAt(i);
        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }
    // All characters are numbers or letters.
    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);
   
   var sLength = s.length;
   var j = 0;
   var cnt = 0;

	//Check for more than one occurances of '@'
	while (j < sLength)
	{ 
	 if(s.charAt(j) == '@')
		cnt++;
	
		j++; 
	
		if (cnt > 1)
			return false; 	
	}
	
    // 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;
    
    
    

    // look for @
	while ((i < sLength) && (s.charAt(i) == ' '))
    { i++; }

	for(var j=0;j<sLength;j++)
	{
		ch = s.charAt(j);
		if(!((ch>='A' && ch<='Z') || (ch>='a' && ch<='z') || (ch>='0' && ch<='9') || (ch=='@')  || (ch=='-') || (ch=='_') || (ch=='.') || (ch=='@')))
			return false;
	}

	//included by pavani--check existence of spaces 05-Dec-2002
    while ((i < sLength) && (s.charAt(i) != '@'))
	{ i++; }

    if ((i >= sLength) || (s.charAt(i) != '@')) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++; }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

// isYear (STRING s [, BOOLEAN emptyOK])
// 
// isYear returns true if string s is a valid 
// Year number.  Must be 2 or 4 digits only.
// 
// For Year 2000 compliance, you are advised
// to use 4-digit year numbers everywhere.
//
// And yes, this function is not Year 10000 compliant, but 
// because I am giving you 8003 years of advance notice,
// I don't feel very guilty about this ...
//
// For B.C. compliance, write your own function. ;->
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function isYear (s)
{
  if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    if (s.length > 4) return false;
    if ((s.length == 2) || (s.length == 4))
    {
			 if  ((s.length == 4) && ((parseInt(s) > 2079) || (parseInt(s) < 1900)))
				{
					return false;
				}	
			
				 return true;
			
    }
}

// isIntegerInRange (STRING s, INTEGER a, INTEGER b [, BOOLEAN emptyOK])
// 
// isIntegerInRange returns true if string s is an integer 
// within the range of integer arguments a and b, inclusive.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function isIntegerInRange (s, a, b)
{   
	if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    
    var num = parseInt(s);
   
    return ((num >= a) && (num <= b));
}

// isMonth (STRING s [, BOOLEAN emptyOK])
// 
// isMonth returns true if string s is a valid 
// month number between 1 and 12.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function isMonth (s)
{   if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}

// isDay (STRING s [, BOOLEAN emptyOK])
// 
// isDay returns true if string s is a valid 
// day number between 1 and 31.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function isDay (s)
{	
	if (isEmpty(s)){ 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    }   
    return isIntegerInRange (s, 1, 31);
    
}

// daysInFebruary (INTEGER year)
// 
// Given integer argument year,
// returns number of days in February of that year.
function daysInFebruary (year)
{   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}

// isDate (STRING year, STRING month, STRING day)
//
// isDate returns true if string arguments year, month, and day 
// form a valid date.
// 

function isDate(year,month,day)
{
   var chk    = 0;
   var maxDay = 0;
      var dd = day; // day
   var mm = month; // month
   var yyyy = year; // year

// calling function to get maximum day for this month
maxDay = max_day(mm, yyyy);  

if((dd <= 0) || (dd > maxDay))
{ chk = 1;}
else if((mm <= 0) || (mm > 12))
{ chk = 1;}
else if((yyyy <= 0))
{ chk = 1;} 

if(chk == 1)
{ return false;}
else
{ return true;}
}

// function for calculating maximum day 
function max_day(mn, yr)
{
   var mDay;
	if((mn == 4) || (mn == 6) || (mn == 9) || (mn == 11))
	{ 
		mDay = 30;
	}
	else if(mn == 2)
	{
	//calling leap year function 
		mDay = isLeapYear(yr) ? 29 : 28;    
	}
	else
	{
		mDay = 31;
	}
		return mDay; 
	}

    // function to check leap year
function isLeapYear(yr)
{
	if (yr % 2 == 0) 
	 return true;
	 return false;
}

// function to restrict any non-numeric key pressing
function nn_Key()
{
	if ((event.keyCode<48) || (event.keyCode>57))
	event.keyCode = 0;
}

/* 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)
{   //theField.focus()
    //theField.select()
    alert(s)
    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 false;
       //return warnInvalid (theField, iEmail);
    else return true;
}

// takes SSN, a string of 9 digits
// and reformats as 123-45-6789
function reformatSSN (SSN)
{   return (reformat (SSN, "", 3, "-", 2, "-", 4))
}

// Check that string theField.value is a valid SSN.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function checkSSN (theField, emptyOK)
{   if (checkSSN.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  var normalizedSSN = stripCharsInBag(theField.value, SSNDelimiters)
       if (!isSSN(normalizedSSN, false)) 
          return warnInvalid (theField, iSSN);
       else 
       {  // if you don't want to reformats as 123-456-7890, comment next line out
          theField.value = reformatSSN(normalizedSSN)
          return true;
       }
    }
}

// Check that string theField.value is a valid Year.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function checkYear (theField, emptyOK)
{   if (checkYear.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isYear(theField.value, false)) 
       return warnInvalid (theField, iYear);
    else return true;
}

// Check that string theField.value is a valid Month.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function checkMonth (theField, emptyOK)
{   if (checkMonth.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isMonth(theField.value, false)) 
       return warnInvalid (theField, iMonth);
    else return true;
}

// Check that string theField.value is a valid Day.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function checkDay (theField, emptyOK)
{   if (checkDay.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isDay(theField.value, false)) 
       return warnInvalid (theField, iDay);
    else return true;
}

// checkDate (yearField, monthField, dayField, STRING labelString [, OKtoOmitDay==false])
//
// Check that yearField.value, monthField.value, and dayField.value 
// form a valid date.
//
// If they don't, labelString (the name of the date, like "Birth Date")
// is displayed to tell the user which date field is invalid.
//
// If it is OK for the day field to be empty, set optional argument
// OKtoOmitDay to true.  It defaults to false.
function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    
    if (checkDate.arguments.length == 4) OKtoOmitDay = false;
    if (!isYear(yearField.value)) return warnInvalid (yearField, iYear);
    if (!isMonth(monthField.value)) return warnInvalid (monthField, iMonth);
    if ( (OKtoOmitDay == true) && isEmpty(dayField.value) ) return true;
    else if (!isDay(dayField.value)) 
       return warnInvalid (dayField, iDay);
    if (isDate (yearField.value, monthField.value, dayField.value))
       return true;
    alert (iDatePrefix + labelString + iDateSuffix)
    return false
}

// Get checked value from radio button.
function getRadioButtonValue (radio)
{   for (var i = 0; i < radio.length; i++)
    {   if (radio[i].checked) { break }
    }
    return radio[i].value
}

// Validate credit card info.
function checkCreditCard (radio, theField)
{   var cardType = getRadioButtonValue (radio)
    var normalizedCCN = stripCharsInBag(theField.value, creditCardDelimiters)
    if (!isCardMatch(cardType, normalizedCCN)) 
       return warnInvalid (theField, iCreditCardPrefix + cardType + iCreditCardSuffix);
    else 
    {  theField.value = normalizedCCN
       return true
    }
}

/*  ================================================================
    Credit card verification functions
    Originally included as Starter Application 1.0.0 in LivePayment.
    20 Feb 1997 modified by egk:
           changed naming convention to initial lowercase
                  (isMasterCard instead of IsMasterCard, etc.)
           changed isCC to isCreditCard
           retained functions named with older conventions from
                  LivePayment as stub functions for backward 
                  compatibility only
           added "AMERICANEXPRESS" as equivalent of "AMEX" 
                  for naming consistency 
    ================================================================ */


/*  ================================================================
    FUNCTION:  isCreditCard(st)
 
    INPUT:     st - a string representing a credit card number

    RETURNS:  true, if the credit card number passes the Luhn Mod-10
		    test.
	      false, otherwise
    ================================================================ */
function isCreditCard(st) {
  // Encoding only works on cards with less than 19 digits
  if (st.length > 19)
    return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
// Uncomment the following line to help create credit card numbers
// 1. Create a dummy number with a 0 as the last digit
// 2. Examine the sum written out
// 3. Replace the last digit with the difference between the sum and
//    the next multiple of 10.

//  document.writeln("<BR>Sum      = ",sum,"<BR>");
//  alert("Sum      = " + sum);

  if ((sum % 10) == 0)
    return (true);
  else
    return (false);

} // END FUNCTION isCreditCard()

/*  ================================================================
    FUNCTION:  isVisa()
 
    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid VISA number.
		    
	      false, otherwise

    Sample number: 4111 1111 1111 1111 (16 digits)
    ================================================================ */

function isVisa(cc)
{
  if (((cc.length == 16) || (cc.length == 13)) &&
      (cc.substring(0,1) == 4))
    return isCreditCard(cc);
  return false;
}  // END FUNCTION isVisa()




/*  ================================================================
    FUNCTION:  isMasterCard()
 
    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid MasterCard
		    number.
		    
	      false, otherwise

    Sample number: 5500 0000 0000 0004 (16 digits)
    ================================================================ */

function isMasterCard(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 16) && (firstdig == 5) &&
      ((seconddig >= 1) && (seconddig <= 5)))
    return isCreditCard(cc);
  return false;

} // END FUNCTION isMasterCard()





/*  ================================================================
    FUNCTION:  isAmericanExpress()
 
    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid American
		    Express number.
		    
	      false, otherwise

    Sample number: 340000000000009 (15 digits)
    ================================================================ */

function isAmericanExpress(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 15) && (firstdig == 3) &&
      ((seconddig == 4) || (seconddig == 7)))
    return isCreditCard(cc);
  return false;

} // END FUNCTION isAmericanExpress()




/*  ================================================================
    FUNCTION:  isDinersClub()
 
    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid Diner's
		    Club number.
		    
	      false, otherwise

    Sample number: 30000000000004 (14 digits)
    ================================================================ */

function isDinersClub(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 14) && (firstdig == 3) &&
      ((seconddig == 0) || (seconddig == 6) || (seconddig == 8)))
    return isCreditCard(cc);
  return false;
}



/*  ================================================================
    FUNCTION:  isCarteBlanche()
 
    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid Carte
		    Blanche number.
		    
	      false, otherwise
    ================================================================ */

function isCarteBlanche(cc)
{
  return isDinersClub(cc);
}




/*  ================================================================
    FUNCTION:  isDiscover()
 
    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid Discover
		    card number.
		    
	      false, otherwise

    Sample number: 6011000000000004 (16 digits)
    ================================================================ */

function isDiscover(cc)
{
  first4digs = cc.substring(0,4);
  if ((cc.length == 16) && (first4digs == "6011"))
    return isCreditCard(cc);
  return false;

} // END FUNCTION isDiscover()





/*  ================================================================
    FUNCTION:  isEnRoute()
 
    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid enRoute
		    card number.
		    
	      false, otherwise

    Sample number: 201400000000009 (15 digits)
    ================================================================ */

function isEnRoute(cc)
{
  first4digs = cc.substring(0,4);
  if ((cc.length == 15) &&
      ((first4digs == "2014") ||
       (first4digs == "2149")))
    return isCreditCard(cc);
  return false;
}



/*  ================================================================
    FUNCTION:  isJCB()
 
    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid JCB
		    card number.
		    
	      false, otherwise
    ================================================================ */

function isJCB(cc)
{
  first4digs = cc.substring(0,4);
  if ((cc.length == 16) &&
      ((first4digs == "3088") ||
       (first4digs == "3096") ||
       (first4digs == "3112") ||
       (first4digs == "3158") ||
       (first4digs == "3337") ||
       (first4digs == "3528")))
    return isCreditCard(cc);
  return false;

} // END FUNCTION isJCB()



/*  ================================================================
    FUNCTION:  isAnyCard()
 
    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is any valid credit
		    card number for any of the accepted card types.
		    
	      false, otherwise
    ================================================================ */

function isAnyCard(cc)
{
  if (!isCreditCard(cc))
    return false;
  if (!isMasterCard(cc) && !isVisa(cc) && !isAmericanExpress(cc) && !isDinersClub(cc) &&
      !isDiscover(cc) && !isEnRoute(cc) && !isJCB(cc)) {
    return false;
  }
  return true;

} // END FUNCTION isAnyCard()



/*  ================================================================
    FUNCTION:  isCardMatch()
 
    INPUT:    cardType - a string representing the credit card type
	      cardNumber - a string representing a credit card number

    RETURNS:  true, if the credit card number is valid for the particular
	      credit card type given in "cardType".
		    
	      false, otherwise
    ================================================================ */

function isCardMatch (cardType, cardNumber)
{

	cardType = cardType.toUpperCase();
	var doesMatch = true;

	if ((cardType == "VISA") && (!isVisa(cardNumber)))
		doesMatch = false;
	if ((cardType == "MASTERCARD") && (!isMasterCard(cardNumber)))
		doesMatch = false;
	if ( ( (cardType == "AMERICANEXPRESS") || (cardType == "AMEX") )
                && (!isAmericanExpress(cardNumber))) doesMatch = false;
	if ((cardType == "DISCOVER") && (!isDiscover(cardNumber)))
		doesMatch = false;
	if ((cardType == "JCB") && (!isJCB(cardNumber)))
		doesMatch = false;
	if ((cardType == "DINERS") && (!isDinersClub(cardNumber)))
		doesMatch = false;
	if ((cardType == "CARTEBLANCHE") && (!isCarteBlanche(cardNumber)))
		doesMatch = false;
	if ((cardType == "ENROUTE") && (!isEnRoute(cardNumber)))
		doesMatch = false;
	return doesMatch;

}  // END FUNCTION CardMatch()




/*  ================================================================
    The below stub functions are retained for backward compatibility
    with the original LivePayment code so that it should be possible
    in principle to swap in this new module as a replacement for the  
    older module without breaking existing code.  (There are no
    guarantees, of course, but it should work.)

    When writing new code, do not use these stub functions; use the
    functions defined above.
    ================================================================ */

function IsCC (st) {
    return isCreditCard(st);
}

function IsVisa (cc)  {
  return isVisa(cc);
}

function IsVISA (cc)  {
  return isVisa(cc);
}

function IsMasterCard (cc)  {
  return isMasterCard(cc);
}

function IsMastercard (cc)  {
  return isMasterCard(cc);
}

function IsMC (cc)  {
  return isMasterCard(cc);
}

function IsAmericanExpress (cc)  {
  return isAmericanExpress(cc);
}

function IsAmEx (cc)  {
  return isAmericanExpress(cc);
}

function IsDinersClub (cc)  {
  return isDinersClub(cc);
}

function IsDC (cc)  {
  return isDinersClub(cc);
}

function IsDiners (cc)  {
  return isDinersClub(cc);
}

function IsCarteBlanche (cc)  {
  return isCarteBlanche(cc);
}

function IsCB (cc)  {
  return isCarteBlanche(cc);
}

function IsDiscover (cc)  {
  return isDiscover(cc);
}

function IsEnRoute (cc)  {
  return isEnRoute(cc);
}

function IsenRoute (cc)  {
  return isEnRoute(cc);
}

function IsJCB (cc)  {
  return isJCB(cc);
}

function IsAnyCard(cc)  {
  return isAnyCard(cc);
}

function IsCardMatch (cardType, cardNumber)  {
  return isCardMatch (cardType, cardNumber);
}

// Varifing date value
function checkDate(txtDate)
{	
	
	var str;
	var month;
	var date;
	var year;
	str = txtDate.split('/');
	if(str.length != 3 )
	{
	  return false;
	}
	if (isInteger(str[0],false)==false || isInteger(str[1],false)==false || isInteger(str[2],false)==false)
	  {
	    return false;
	  }
	month = eval(str[0]);
	date = eval(str[1]);
	year = str[2];
	if (year.length > 4) return false;
	if(year.length==3 || year.length==4)
		if(parseInt(year)<1750 || parseInt(year)>9999)
			return false;
	
	return isDate(year,month,date);
}

//trims the string values 
function trim(myStr,model)
	{
	 	var trimvalue = "";
	 	myStrlen = myStr.length;
	 	if (myStrlen < 1) return trimvalue;

	 	if (model == "left" || model== "both")
	 	    {
	 			i = 0;
	 			pos = -1;
	 			while (i < myStrlen)
	 			   {
	 					if (myStr.charCodeAt(i) != 32 && !isNaN(myStr.charCodeAt(i)))
	 					   {
	 							pos = i;
	 							break;
	 						}
	 					i++;
	 				}
	 			}

	 	if (model == "right" || model== "both")
	 	    {
	 			var lastpos = -1;
	 			i = myStrlen;
	 			while (i >= 0)
	 			  {
	 				if (myStr.charCodeAt(i) != 32 && !isNaN(myStr.charCodeAt(i)))
	 					 {
	 						lastpos = i;
	 						break;
	 					  }
	 					  i--;
	 				}
	 		}

	 	if (model == "left")
	 	   {
	 		trimvalue = myStr.substring(pos,myStrlen-1);
	 	   }
	 	else
	 		{
	 			if (model == "right")
	 			 {
	 			   trimvalue = myStr.substring(0,lastpos+1);
	 			 }
	 			else
	 				{
	 				  if (model == "both") 
	 				     {
	 						trimvalue = myStr.substring(pos,lastpos + 1);
	 					 }
	 				 }
	 		 }

	 	return  trimvalue;
}
//Format date to mm/dd/yyyy
function FormatDate(anyDate) {
	var lMonth
	lMonth = anyDate.getMonth();
	lMonth = lMonth + 1
	if(lMonth<10)
	{lMonth="0"+lMonth}
   return lMonth +"/"+anyDate.getDate()+"/"+anyDate.getFullYear()
}
function getCurrentDate(){
	var ldate = new Date();
	var lcurrentDate
	var lMonth
	
	lMonth = 0;
	lMonth = ldate.getMonth();
	lMonth = lMonth + 1;
	if (lMonth  < 10)
	{lMonth = "0"+lMonth;}
	lcurrentDate = lMonth + "/" + ldate.getDate() + "/" + ldate.getFullYear();
	return lcurrentDate;
}
function setAirgasWindowStatusDate()
{
	var dt = new Date()
	var strDay = ""
	switch (dt.getDay())
    {
		case 1: 
			strDay = "Mon";
			break;
		case 2: 
			strDay = "Tue";
			break;
		case 3: 
			strDay = "Wed";
			break;
		case 4: 
			strDay = "Thu";
			break;
		case 5: 
			strDay = "Fri";
			break;
		case 6: 
			strDay = "Sat";
			break;
		case 0: 
			strDay = "Sun";
			break;
    }
    var strMonth = ""
	switch (dt.getMonth())
    {
		case 0: 
			strMonth = "Jan";
			break;
		case 1: 
			strMonth = "Feb";
			break;
		case 2: 
			strMonth = "Mar";
			break;
		case 3: 
			strMonth = "Apr";
			break;
		case 4: 
			strMonth = "May";
			break;
		case 5: 
			strMonth = "Jun";
			break;
		case 6: 
			strMonth = "Jul";
			break;
		case 7: 
			strMonth = "Aug";
			break;
		case 8: 
			strMonth = "Sep";
			break;
		case 9: 
			strMonth = "Oct";
			break;
		case 10: 
			strMonth = "Nov";
			break;
		case 11: 
			strMonth = "Dec";
			break;
		
    }
    var strTime = ""
    strTime = dt.getHours()+ ":" + dt.getMinutes() + ":" + dt.getSeconds() 
	var str = "Credit & Collections Tool Application: [" + strDay + " "+ strMonth + " "+dt.getDate() + " "+strTime + " "+dt.getFullYear()  + "]";
	window.status = str;
}

function round(n)
{
  var pennies=n*100;    
  pennies=Math.round(pennies);
 
  var strPennies=""+pennies;
  if(pennies<10) strPennies = "0" + strPennies;
  len=strPennies.length;
  frststr=strPennies.substring(0,len-2);
  if (frststr.length ==0)
  frststr = 0;
  lststr=strPennies.substring(len-2,len);
  rounded=frststr+"."+lststr;
  return rounded;
}

function DateDiff( start, end, interval, rounding ) {

    var iOut = 0;
    
    // Create 2 error messages, 1 for each argument. 
    var startMsg = "Check the Start Date and End Date\n"
        startMsg += "must be a valid date format.\n\n"
        startMsg += "Please try again." ;
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var bufferA = Date.parse( start ) ;
    var bufferB = Date.parse( end ) ;
    	
    // check that the start parameter is a valid Date. 
    if ( isNaN (bufferA) || isNaN (bufferB) ) {
        alert( startMsg ) ;
        return null ;
    }
	
    // check that an interval parameter was not numeric. 
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }
    
    var number = bufferB-bufferA ;
    
    // what kind of add to do? 
    switch (interval.charAt(0))
    {
        case 'd': case 'D': 
            iOut = parseInt(number / 86400000) ;
            if(rounding) iOut += parseInt((number % 86400000)/43200001) ;
            break ;
        case 'h': case 'H':
            iOut = parseInt(number / 3600000 ) ;
            if(rounding) iOut += parseInt((number % 3600000)/1800001) ;
            break ;
        case 'm': case 'M':
            iOut = parseInt(number / 60000 ) ;
            if(rounding) iOut += parseInt((number % 60000)/30001) ;
            break ;
        case 's': case 'S':
            iOut = parseInt(number / 1000 ) ;
            if(rounding) iOut += parseInt((number % 1000)/501) ;
            break ;
        default:
        // If we get to here then the interval parameter
        // didn't meet the d,h,m,s criteria.  Handle
        // the error. 		
        alert(intervalMsg) ;
        return null ;
    }
    
    return iOut ;
}	
function dateAdd( start, interval, number ) {
	
    // Create 3 error messages, 1 for each argument. 
    var startMsg = "Sorry the start parameter of the dateAdd function\n"
        startMsg += "must be a valid date format.\n\n"
        startMsg += "Please try again." ;
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var numberMsg = "Sorry the number parameter of the dateAdd function\n"
        numberMsg += "must be numeric.\n\n"
        numberMsg += "Please try again." ;
		
    // get the milliseconds for this Date object. 
    var buffer = Date.parse( start ) ;
	
    // check that the start parameter is a valid Date. 
    if ( isNaN (buffer) ) {
        alert( startMsg ) ;
        return null ;
    }
	
    // check that an interval parameter was not numeric. 
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }

    // check that the number parameter is numeric. 
    if ( isNaN ( number ) )	{
        alert( numberMsg ) ;
        return null ;
    }

    // so far, so good...
    //
    // what kind of add to do? 
    switch (interval.charAt(0))
    {
        case 'd': case 'D': 
            number *= 24 ; // days to hours
            // fall through! 
        case 'h': case 'H':
            number *= 60 ; // hours to minutes
            // fall through! 
        case 'm': case 'M':
            number *= 60 ; // minutes to seconds
            // fall through! 
        case 's': case 'S':
            number *= 1000 ; // seconds to milliseconds
            break ;
        default:
        // If we get to here then the interval parameter
        // didn't meet the d,h,m,s criteria.  Handle
        // the error. 		
        alert(intervalMsg) ;
        return null ;
    }
    return new Date( buffer + number ) ;
} 

function formatNegativeValues(vString){
	var lstrString
	var lLength

	lLength=0
	lLength = vString.length;
	lstrString = vString.substring(2,lLength)
	lstrString = "(" + lstrString + ")"
	return lstrString;
}

function getNegativeValue(vString){
	var lstrString
	var lLength
	
	lLength=0
	lLength = vString.length - 1;
	if( vString.substring(1,1) == "(" && vString.substring(lLength,1) == ")"){
		lstrString = vString.substring(2,lLength)
		lstrString = "-" + lstrString
	}
	else
		lstrString = vString
	return lstrString;
}
//return number of days between todates
function DaysBetween(firstDate,secoundDate)
{
	var str=firstDate;
	var month;
	var date;
	var year;
	var arrstr;
	arrstr = str.split('/');
	month = eval(arrstr[0]);
	date = arrstr[1];
	year = arrstr[2];
	if (year.length == 2){
		if (year <= 50)
			year = 20 + year.toString();
		else
			year = 19 + year.toString();
	}
	var date1=new Date(year,month,date);
	str=secoundDate;
	arrstr = str.split('/');
	month = eval(arrstr[0]);
	date = arrstr[1];
	year = arrstr[2];
	if (year.length == 2){
		if (year <= 50)
			year = 20 + year.toString();
		else
			year = 19 + year.toString();
	}
	var date2=new Date(year,month,date);
	var ONE_DAY = 1000 * 60 * 60 * 24;
	var date1_ms = date1.getTime();
	var date2_ms = date2.getTime();
	
    var difference_ms =  (date2_ms - date1_ms)/ONE_DAY ;
    return difference_ms;
}

function monthLastDate(month,year)
{
	switch(month)
	{
		case 1 : case  3 : case 5 : case 7 : case 8 : case 10 : case 12 :
			return(31);
			break;
		case 4 : case 6 : case 9 : case 11 :
			return(30);
			break;
		case 2 :
			if ((((year % 4) == 0) && (year % 100) != 0) || ((year % 400) == 0))
				return(29); 		
			else
				return(28); 	
	}
}

function jsFormatCurrency(parCurValue)
{
/*  ** Convert a number to words for filling in the Amount of a check
    ** Example: NumWord(120.45) returns ONE HUNDRED TWENTY AND 45/100
    ** Can handle numbers from 0 to $999,999,999.99
    ** Created by Alan Simpson: Fax (619)756-0159
    ** First working version, not yet fully tuned for speed or brevity.
    ** The array below, and other variables, are dimensioned
    ** in the Declarations section.*/

	var DecimalValue;
	var PrecisionValue;
	var finalDecimalValue;
	var finalPrecisionValue;
	var TempArry;
	var TempText;
	var TempLen;
	var isNagitive;
	isNagitive=false;
	if(parCurValue.substr(0,1) == '(' && parCurValue.substr(parCurValue.length-1,1) == ')')
	{
		isNagitive=true;
		parCurValue=parCurValue.substr(1,parCurValue.length-2);
	}
		
	if(parCurValue.indexOf('$',0)>=0)
		parCurValue=parCurValue.substr(1);
		
	if(parCurValue.indexOf('.',0)>=0)
	{
		TempArry=parCurValue.split('.');
		if(TempArry.length>2)
			return false;

		if(TempArry.length==2)
		{
			PrecisionValue=TempArry[0];
			DecimalValue=TempArry[1];
			if(PrecisionValue == '') PrecisionValue=0;
			if(DecimalValue == '') DecimalValue=0;
		}
		else
		{
			PrecisionValue=parCurValue;
			DecimalValue=0;
		}
	}
	else
	{
		PrecisionValue=parCurValue;
		DecimalValue=0;
	}	
	finalPrecisionValue='';
	if(PrecisionValue.indexOf(',',0)>=0)
	{
		TempArry=PrecisionValue.split(',');
		for(var i=0;i<TempArry.length;i++)
			finalPrecisionValue=finalPrecisionValue + TempArry[i];
	}
	else
		finalPrecisionValue=PrecisionValue;
	
	if(finalPrecisionValue.substr(0,1) == '-')
	{
		isNagitive=true;
		finalPrecisionValue=finalPrecisionValue.substr(1);
	}
	
	if(finalPrecisionValue == '') finalPrecisionValue=0;
	
	if(isNaN(finalPrecisionValue) == true) return false;
	if(isNaN(DecimalValue) == true) return false;
		
	if(DecimalValue ==  0)
		DecimalValue= '00';
	else if(DecimalValue!=0 && DecimalValue.length == 1)
		DecimalValue= DecimalValue + '0';
	else if(DecimalValue.length > 2)
	{
		finalDecimalValue=DecimalValue.substr(2);
		DecimalValue=DecimalValue.substr(0,2);
		finalDecimalValue='0.' + finalDecimalValue;
		finalDecimalValue=Math.round(finalDecimalValue);
		DecimalValue= Math.abs(DecimalValue) + Math.abs(finalDecimalValue);
	}
	PrecisionValue='';
	for(var i=finalPrecisionValue.length;i>0;i-=3)
	{
		if(i>3)
			PrecisionValue=finalPrecisionValue.substr(i-3,3) + ',' + PrecisionValue;
		else
			PrecisionValue=finalPrecisionValue.substr(0,i) + ',' + PrecisionValue;
	}
	PrecisionValue=PrecisionValue.substr(0, PrecisionValue.length - 1);
	if(DecimalValue == 100) 
	{
		PrecisionValue = Math.abs(PrecisionValue) + 1
		DecimalValue='00';
	}
	PrecisionValue= '$' + PrecisionValue + '.' + DecimalValue;
	if(isNagitive == true)
		PrecisionValue= '(' + PrecisionValue + ')';
	return PrecisionValue;
}
//
function NumWord(TotalAmount)
{
	var TempArray;
	var EngNum =makeArray(90);
	var StringNum;
	var AmountPassed;
	var Pennies=0;
	var varNumWord='';
    EngNum[0] = '';
    EngNum[1] = 'One';
    EngNum[2] = 'Two';
    EngNum[3] = 'Three';
    EngNum[4] = 'Four';
    EngNum[5] = 'Five';
    EngNum[6] = 'Six';
    EngNum[7] = 'Seven';
    EngNum[8] = 'Eight';
    EngNum[9] = 'Nine';
    EngNum[10] = 'Ten';
    EngNum[11] = 'Eleven';
    EngNum[12] = 'Twelve';
    EngNum[13] = 'Thirteen';
    EngNum[14] = 'Fourteen';
    EngNum[15] = 'Fifteen';
    EngNum[16] = 'Sixteen';
    EngNum[17] = 'Seventeen';
    EngNum[18] = 'Eighteen';
    EngNum[19] = 'Nineteen';
    EngNum[20] = 'Twenty';
    EngNum[30] = 'Thirty';
    EngNum[40] = 'Forty';
    EngNum[50] = 'Fifty';
    EngNum[60] = 'Sixty';
    EngNum[70] = 'Seventy';
    EngNum[80] = 'Eighty';
    EngNum[90] = 'Ninety';

	TempArray=TotalAmount.split('.');
	if(TempArray.length>2)
	{ 
		return false;
	}
	else if(TempArray.length==2)
	{
		if(TempArray[0]!= '')
			AmountPassed=TempArray[0];
		else
			AmountPassed='00';
		if(TempArray[1] != '')
			Pennies=TempArray[1];
		else
			Pennies='00';
	}
	else if(TempArray.length==1)
	{
		AmountPassed=TempArray[0];
		Pennies='00';
	}
	if(isNaN(AmountPassed)== true) return false;
	if(isNaN(Pennies)== true) return false;
	
	StringNum=AmountPassed;
	for(var i=AmountPassed.length; i<10 ;i++) 
		StringNum='0' + StringNum;
	
    var English = '';
    var LoopCount = 1;
    var StartVal = 1;

    if(AmountPassed < 1)
        English = 'Zero';
    for(LoopCount = 1; LoopCount <= 3;LoopCount++)
    {
        Chunk = StringNum.substr(StartVal, 3);
        Hundreds = Math.abs(Chunk.substr(0, 1));
        Tens = Math.abs(Chunk.substr(1, 2));
        Ones = Math.abs(Chunk.substr(2, 1));
        //** Do the hundreds portion of 3-digit number
        if( Math.abs(Chunk) > 99 )
            English = English + EngNum[Hundreds] + ' Hundred ';
        //** Do the tens & ones portion of 3-digit number

        TensDone = false;
        //** Is it less than 10?
        if(Tens < 10 )
        {
            English = English + ' ' + EngNum[Ones];
            TensDone = true;
        }

       //** Is it a teen?
        if(Tens >= 11 && Tens <= 19) 
        {
            English = English + EngNum[Tens];
            TensDone = true;
        }
        //** Is it Evenly Divisible by 10?
        if((Tens / 10) == Math.floor(Tens / 10))
        {
           English = English + EngNum[Tens];
           TensDone = true;
        }
        //** Or is it none of the above?
        if(TensDone == false)
        {
            English = English + '' + EngNum[(Math.floor(Tens / 10)) * 10];	
            English = English + ' ' + EngNum[Ones];
        }

        //** Add the word "million" if necessary.
        if(LoopCount == 1 && Math.abs(Chunk) > 0)
            English = English + ' Million ';

        //** Add the word "thousand" if necessary.
        if(LoopCount == 2 &&  Math.abs(Chunk) > 0)
            English = English + ' Thousand ';
        
        //** Do pass through second three digits
        StartVal = StartVal + 3
    }
    //** Done: Return english with pennies tacked on.
    varNumWord = English + ' and ' +  Pennies + '/100 *********************************************************************************';
return varNumWord;

}



//To convert entered date

function ConvertDate(txtDate)
{
	var str;
	var month;
	var date;
	var year;
	
	str = txtDate.split('/');
	date = eval(str[1]);
	year = str[2];
	month = eval(str[0]);
	switch(month)
	{	
		case 1:
			month="January";
			break;
		case 2:
			month="February";
			break;
		case 3:
			month="March";
			break;
		case 4:
			month="April";
			break;
		case 5:
			month="May";
			break;
		case 6:
			month="June";
			break;
		case 7:
			month="July";
			break;
		case 8:
			month="August";
			break;
		case 9:
			month="September";
			break;
		case 10:
			month="October";
			break;
		case 11:
			month="November";
			break;
		case 12:
			month="December";
			break;
		default:
			month="Invalid month";
	}
	if (month != 'Invalid month'){
	return month + ' ' + date + ', ' + year;
	}
	else
	return false;
	
}

//End of conversion
//validate URL
function testURL(Ctrl) {
	if (Ctrl.value == "" || Ctrl.value.indexOf("http://",0) == -1) {
//		validatePrompt (Ctrl, "Please provide a valid URL")
		return (false);
	} else
		return (true);
}

//purpose of converts number value to US currency value
function NumberToCurrency(num,scale)
{
	var per=1;
	for(var i=1;i<=scale;i++)
		per=per*10;
	num = num.toString().replace(/\$|\,/g,'');
	if((num.substr(0,1) == '(' && num.substr(num.length-1,1) == ')'))
		num='-' + num.substr(1,num.length-2);
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*per+0.50000000001);
	cents = (num%per);
	num = Math.floor(num/per).toString();
	var temp=cents.toString().length;
	for(var cenlen=1;cenlen <= (scale - temp);cenlen++)
		cents="0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	if(scale==null || scale==0)
		return (((sign)?'':'(') + '$' + num  + ((sign)?'':')'));
	else
		return (((sign)?'':'(') + '$' + num + '.' + cents + ((sign)?'':')'));
}
//purpose of converts  US currency value to number value
function CurrencyToNumber(cur,scale)
{	
	var	sign=false;
	var per=1;
	for(var i=1;i<=scale;i++)
		per=per*10;
	cur = cur.toString().replace(/\$|\,/g,'');
	if((cur.substr(0,1) == '(' && cur.substr(cur.length-1,1) == ')'))
		cur='-' + cur.substr(1,cur.length-2);

	if(isNaN(cur))
		return cur;	

	sign = (cur == (cur = Math.abs(cur)));
	
	cur = Math.floor(cur*per+0.50000000001);
	cents = (cur%per);
	cur = Math.floor(cur/per).toString();
	var temp=cents.toString().length;
	for(var cenlen=1;cenlen <= (scale - temp);cenlen++)
		cents="0" + cents;

	if(scale==null || scale==0)
		return (((sign)?'':'-') + cur);
	else
		return (((sign)?'':'-') + cur + '.' + cents);

}
//converts number value to percentage value
function FormatPercentage(Percent)
{
var value='0.00%';
	if (Percent!='')
	{
		if (parseFloat(Percent.indexOf('%',0))< 0)
			if(isNaN(Percent)==false)
				value=(parseFloat(Percent)*100 + '.00%');
			else
				value='0.00%';
		else
		{	
			Percent=Percent.substr(0,Percent.length-1);
			if(isNaN(Percent)==true)
				value='0.00%';
			else
				if(Percent.indexOf('.',0)>=0)
				{
					var num=Percent;
					var cents;
					if(isNaN(num))
					num = "0";
					num = Math.floor(num*100+0.50000000001);
					cents = (num%100);
					num = Math.floor(num/100).toString();
					if(cents<10)
						value=num + '.0' + cents + '%';
					else
						value=num + '.' + cents + '%';
				}
				else
					value=Percent + '.00%';
		}
	}
	return value;
}
function NumberToScale(num,scale)
{
	var per=1;
	for(var i=1;i<=scale;i++)
		per=per*10;
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*per+0.50000000001);
	cents = (num%per);
	num = Math.floor(num/per).toString();
	var temp=cents.toString().length;
	for(var cenlen=1;cenlen <= (scale - temp);cenlen++)
		cents="0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	
	if(scale==null || scale==0)
		return (((sign)?'':'(')  + num  + ((sign)?'':')'));
	else
		return (((sign)?'':'(')  + num + '.' + cents + ((sign)?'':')'));
}

function checkValidEmail(email)
{		
		aflag=false;
		emailStr = email.value;
		if(emailStr=="") return true;
		var err=-1,cntAt=0,mailAt=0,cntDot=0,cntDotNum=-1; 
		var Atpos, Dotpos
			
		for (i=0;i<emailStr.length;i++)
		    {
		      val=emailStr.charAt(i);
		      if (val=='.')
		         {
		            if (i==emailStr.length-1)
		                {
		                  return false;
		                  break;
		                }
		         }
		    }
		for (i=0;i<emailStr.length;i++)    // Splitting the string with '@'
			{
				val=emailStr.charAt(i);    // val: to get each character from string
				if (val=='.')
					{
					  Dotpos=i;
					}
				if (val=='@')
				{	
					cntAt=1;mailAt=i;    // mailAt: to find the position of @
					aflag=true;
					break;
				}
			}
			
		if(!aflag)
			return false;
			
	if (mailAt!=0)
		{
		     befAtStr = emailStr.substring(0,mailAt);    // befAtStr: to store string before '@'
		     aftAtStr = emailStr.substring(mailAt+1,emailStr.length); // aftfAtStr: to store string before '@'
		     if ((befAtStr.length!=0) && (cntAt!=0) && (aftAtStr.length!=0))
			 {
				for (j=0;j<befAtStr.length;j++)	   // Checking the characters in befAtStr
				{
					val1 = befAtStr.charAt(j);
		            if ( (((val1>='a' && val1<='z')) || ((val1>='0' && val1<='9')) || ((val1>='A' && val1<='Z')) || (val1!=' ') && val1!='#') )                                   
						{
																  
						}
			         else
			           {					
							err=4;
							break;
						}
										
				 }	
				for (k=0;k<aftAtStr.length;k++)    // Checking the characters in aftAtStr
					{
						val2 = aftAtStr.charAt(k);
			  			if((!(val2>='a' && val2<='z')) && (!(val2>='0' && val2<='9')) && (!(val2>='A' && val2<='Z')) && (val2==' ') )
					    {					
					      err=4;
					      break;
					     }
											
						if (val2=='.' && k!=0)
						    {
						     cntDot++;   // setting cntDot=1 when dot encountered in aftAtStr
											     
						    }
						if (cntDot==1) 
						     cntDotNum++;   // numbers after dot in aftAtStr
					 }
				}
				else
					err=4;   // setting error if befAtStr and befAtStr are empty and if atleast one period doesn't present
			}
			else
				err=4;   // setting error if '@' is not present in the string
			
			
				if ( (cntDot<1) || (err==4) || (cntDotNum<0) || (cntDotNum>3) ||(cntDotNum<3))
						return false; // Calling errDisplay function with the error code
				else
					{
							return true;    // temporary: transfering the focus 
					}				
							
			return flag;
}
function whenIs(anyDate, n){
   //-- Returns the date that is n days from any date object.
   var newDate = new Date();
   newDate.setTime(anyDate.getTime()+(n*1000*60*60*24));
   return newDate;
}

// function switchDiv()
//  this function takes the id of a div
//  and calls the other functions required
//  to show that div
//
function switchDiv(div_id)
{
  var style_sheet = getStyleObject(div_id);
  if (style_sheet)
  {
    hideAll();
    changeObjectVisibility(div_id,"visible");
  }
  else 
  {
    alert("sorry, this only works in browsers that do Dynamic HTML");
  }
}

// function hideAll()
//  hides a bunch of divs
//
function hideAll()
{
   changeObjectVisibility("ez","hidden");
   changeObjectVisibility("full","hidden");
   changeObjectVisibility("superduper","hidden");
}

// function getStyleObject(string) -> returns style object
//  given a string containing the id of an object
//  the function returns the stylesheet of that object
//  or false if it can't find a stylesheet.  Handles
//  cross-browser compatibility issues.
//
function getStyleObject(objectId) {
  // checkW3C DOM, then MSIE 4, then NN 4.
  //
  if(document.getElementById && document.getElementById(objectId)) {
	return document.getElementById(objectId).style;
   }
   else if (document.all && document.all(objectId)) {  
	return document.all(objectId).style;
   } 
   else if (document.layers && document.layers[objectId]) { 
	return document.layers[objectId];
   } else {
	return false;
   }
}

function changeObjectVisibility(objectId, newVisibility) {
    // first get a reference to the cross-browser style object 
    // and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	styleObject.visibility = newVisibility;
	return true;
    } else {
	// we couldn't find the object, so we can't change its visibility
	return false;
    }
}

//script for roll over of the buttons
blankVar = ""

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);
// -->

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function ErrorControl(objectName,errorMessage)
{
	eval('document.' + objectName).className='ErrorControl';
	if(eval('document.' + objectName).type=='text')
		eval('document.' + objectName).select();
	eval('document.' + objectName).focus();
	alert(errorMessage); 
}
function NormalControl(objectName)
{
	eval('document.' + objectName).className='ValidControl';
}
function ErrorControlSelect(objectName,errorMessage)
{
	eval('document.' + objectName).className='ErrorControl';
	eval('document.' + objectName).select();
	eval('document.' + objectName).focus();
	alert(errorMessage); 
}
function SetBubbleHelp()
{

	var strHelpArray=new Array();
	var strHelpDescription=new String();
	var strHelpItem=new String();
	var obj;
	strHelpDescription=document.forms(0).hdnBubbleHelp.value;
	if(strHelpDescription!='')
	{
		strHelpArray=strHelpDescription.split('#$');
		for(i=0;i<strHelpArray.length;i++)
		{
		
			var arrHelp = new Array();
			strHelpItem = strHelpArray[i];
			arrHelp = strHelpItem.split('~');
			
			obj = eval('document.forms(0).imgHlp' + arrHelp[0]);
			if (obj != null)
			{
				obj.alt = arrHelp[1]; 
			}
		
		}
	}

}

function setWindowStatusMessage(strMessage)
{
	var getMessage = strMessage;
	window.status = getMessage;
}

function DateDiff( start, end, interval, rounding ) {

    var iOut = 0;
    
    // Create 2 error messages, 1 for each argument. 
    var startMsg = "Check the Start Date and End Date\n"
        startMsg += "must be a valid date format.\n\n"
        startMsg += "Please try again." ;
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var bufferA = Date.parse( start ) ;
    var bufferB = Date.parse( end ) ;
    	
    // check that the start parameter is a valid Date. 
    if ( isNaN (bufferA) || isNaN (bufferB) ) {
        alert( startMsg ) ;
        return null ;
    }
	
    // check that an interval parameter was not numeric. 
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }
    
    var number = bufferB-bufferA ;
    
    // what kind of add to do? 
    switch (interval.charAt(0))
    {
        case 'd': case 'D': 
            iOut = parseInt(number / 86400000) ;
            if(rounding) iOut += parseInt((number % 86400000)/43200001) ;
            break ;
        case 'h': case 'H':
            iOut = parseInt(number / 3600000 ) ;
            if(rounding) iOut += parseInt((number % 3600000)/1800001) ;
            break ;
        case 'm': case 'M':
            iOut = parseInt(number / 60000 ) ;
            if(rounding) iOut += parseInt((number % 60000)/30001) ;
            break ;
        case 's': case 'S':
            iOut = parseInt(number / 1000 ) ;
            if(rounding) iOut += parseInt((number % 1000)/501) ;
            break ;
        default:
        // If we get to here then the interval parameter
        // didn't meet the d,h,m,s criteria.  Handle
        // the error. 		
        alert(intervalMsg) ;
        return null ;
    }
    
    return iOut ;
}




// Script_Standards
function SetFocusOn(objectName) {
	objectName.focus();
}

function KeyPressDate() {
	if ((event.keyCode < 47 || event.keyCode > 57) && event.keyCode != 13) {
		event.returnValue = false;
	}
}

function KeyPressDecimal() {
	if ((event.keyCode < 45 || event.keyCode > 57 || event.keyCode == 47) &&
		event.keyCode != 13) 
		{
			event.returnValue = false;
	}
}
function clickButton(e, buttonid,isIntreq){ 

      var evt = e ? e : window.event;

      var bt = document.getElementById(buttonid);

      if (bt){ 

          if (evt.keyCode == 13){ 

                bt.click(); 
               
                return false; 
            
          } 
          else if(isIntreq)
          {

              KeyPressDecimal();
          }

      } 

}

//---------------------------------------  RAGHU ---------------------------------------------------------------
 function ValidateDecimal(Value) 
         {
        
	        if (Value.value != "")
	         {
	         
		        if (parseFloat(Value.value) != Value.value)
		         {
		        
			        alert("Invalid Number");
			       Value.focus();
			        return false;
			     }
			 }       
		} 
		
//---------------------------------- RAGHU  ------------------------------------------------------------------
function KeyPressInteger() {
	//if ((event.keyCode != 45) && (event.keyCode < 47 || event.keyCode > 57)&&
	if ((event.keyCode < 48 || event.keyCode > 57)&&
		  event.keyCode != 13) {
		event.returnValue = false;
	}
}
function KeyPressIndiaPhoneNo() {
	//if ((event.keyCode != 45) && (event.keyCode < 47 || event.keyCode > 57)&&
	if ((event.keyCode < 48 || event.keyCode > 57)&&
		  (event.keyCode != 13) &&(event.keyCode!= 43) &&(event.keyCode!= 45)){
		event.returnValue = false;
	}
}

function KeyPressCharacter() {
	if ((event.keyCode < 65 || event.keyCode > 90) &&
		 (event.keyCode < 97 || event.keyCode > 122) &&
		  (event.keyCode != 13) && (event.keyCode != 32)) {
		event.returnValue = false;
	}
}


function ValidateInt(IntVal) {
	if (IntVal.value != "") {
		if (parseInt(IntVal.value,10) != IntVal.value) {
			alert("Invalid Number");
			IntVal.focus();
			return false;
		} else {
			if (IntVal.value < 0) {
				IntVal.style.color = "Red";
			} else {
				IntVal.style.color = "Black";
			}
			return true;
		}
	}
}

function ValidateDecimal(Value) {
	if (Value.value != "") {
		if (parseFloat(Value.value) != Value.value) {
			alert("Invalid Number");
			Value.focus();
			return false;
		} else {
			Value.value = showDecimal(Value.value, 2);
			if (Value.value < 0) {
				Value.style.color = "Red";
			} else {
				Value.style.color = "Black";
			}

			return true;
		}
	}
}
function ValidateDecimal(Value,Places) {
	if (Value.value != "") {
		if (parseFloat(Value.value) != Value.value) {
			alert("Invalid Number");
			Value.focus();
			return false;
		} else {
			Value.value = showDecimal(Value.value, Places);
			if (Value.value < 0) {
				Value.style.color = "Red";
			} else {
				Value.style.color = "Black";
			}

			return true;
		}
	}
}

function ValidateDate(date) {
	if (date.value != "") {
		if (Date.parse(date.value) != Date.parse(date.value)) {
			alert("Invalid Date!\nPlease Select Date");
			date.focus();
			return false;
		} 
		else 
		{
			if (!checkDate(date.value))
			{
					alert("Invalid Date!");
					date.focus();
					return false;
			}
			else
			{
				return true;
			}
		}
	}
	
}

function ValidateEmail(email) {
	if (email.value != "") {
		if (!checkEmail(email.value)) {
			alert("Invalid Email!\nFormat: xxxxxxxxxxxx@xxxx.xxx");
			email.focus();
			return false;
		} 
		else 
		{
			return true;
		}
	}
}
function checkEmail(email) 
{
	if (email != "") 
	{
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))
			return (true);
		else
			return (false);
	}
	return (true);

}

function publicValidateArray(frm, fld, displayname, ctrMax) {

	if (ctrMax > 0) {
		tt = eval(frm + "." + fld);
		for (j = 0; j <= eval(parseFloat(ctrMax) + 1); j++) {
			if (j > ctrMax) { break; }
			if (trim(tt[j].value,'both') == "") {
				alert(displayname + " " + (j + 1) );
				tt[j].style.background = "Red";
				tt[j].style.color = "White";
				tt[j].focus();
				return false;
			}else {
				tt[j].style.color = "Black";
				tt[j].style.background = "White";
			}
		}
	} else {
		if (publicValidate(frm, fld, displayName) == false) {return false};
	}

}
function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

function publicValidate(frm, fld, displayname) {
	tt = eval(frm + "." + fld);
	if (trim(tt.value) == '') 
	{
		alert(displayname );
		//tt.className='ErrorControl';
		if(tt.type=='text')
			tt.select();
		tt.focus();
		return false;
	}
	else 
	{
		//tt.className='ValidControl';
		if(tt.type=='text')
			tt.value=trim(tt.value);
	}
}

function publicValidateLen10(frm, fld, displayname, message, criteria) {
	tt = eval(frm + "." + fld);

	if ((tt.value.length > 0) && (tt.value.length < 10)) {
		alert(displayname + " must be 10 digits.");
		tt.style.background = "Red";
		tt.style.color = "White";
		tt.focus();
		return false;
	} else {
		tt.style.color = "Black";
		tt.style.background = "White";
	}
}

function DateChange(inputdate){
	dt = eval(inputdate);
	newstring = "";

	if ((dt.value.length == 6) || (dt.value.length == 8)) {
	var NoSlash = true;
		for (xctr = 0; xctr < dt.value.length; xctr++) {
			if (dt.value.substring(xctr, 1) == "/") {
				NoSlash = false;
			}
		}
	}

	if (((dt.value.length == 6) || (dt.value.length == 8)) && (NoSlash == true)) {
		for (xctr = 0; xctr < dt.value.length; xctr++)
		{
			thisvalue = dt.value.substr(xctr, 1);

			if ((xctr == 2) || (xctr == 4)){
				if (thisvalue == "/")
					return true;
				else
					newstring += "/" + thisvalue;
			}
			else
 				newstring += thisvalue;
		}
	dt.value = newstring;
	}
}

function showDecimal(number, places) {
var ctr, sendBack;
sendBack = "";

	places = (!places ? 2: places);
	number = round(number, places);
	number = number.toString();

	if (number.indexOf('.') != -1) {
		if (number.length == (number.indexOf('.') + (places + 1))) {
			return number;
		} else {
			while (number.length < number.indexOf('.') + (places + 1)) {
				number = number.toString() + "0";
			}
			return number.toString();
		}
	} else {
		for (ctr = 0; ctr < places; ctr++) {
			sendBack = sendBack.toString() + "0";
		}
		return number + "." + sendBack;
	}
}

function round(number,X) {
	// rounds number to X decimal places, defaults to 2
	X = (!X ? 2 : X);
	return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}

function ClipBoard(varcopytext, close)
{
	strholdtext.innerText = varcopytext;
	Copied = strholdtext.createTextRange();
	Copied.execCommand("RemoveFormat");
	Copied.execCommand("Copy");

	if (close = true)
	{
		close = confirm("You have copied: " + varcopytext + ".\nClick OK to close this window.");
		if (close)
			self.close();
	}
}

function changeLinks(form) {

   var formindex = form.ActionLink.selectedIndex;
	//(formindex > 0) &&
   if ((form.ActionLink.options[formindex].value != "")) {
		parent.top.location = form.ActionLink.options[formindex].value;
		//window.open(form.ActionLink.options[formindex].value);
   } else {
		form.ActionLink.selectedIndex = 0;
   }
}

function replaceAll(strObj) {
	
	while (strObj.value.search(", ") != -1) {
		strObj.value = strObj.value.replace(", ", ", ");
	}
}
function pagingSubmit(strAction,form)
	{
		if (strAction != "")
		{	
			document.forms[0].action=strAction;
		}
		else
		{
			var formindex = form.ActionLink.selectedIndex;
			if ((form.ActionLink.options[formindex].value != "")) 
			{
				document.forms[0].action=form.ActionLink.options[formindex].value;
			} 
			else 
			{
				form.ActionLink.selectedIndex = 0;
			}
		}
		document.forms[0].method="post";
		document.forms[0].submit();
	}
//function for List Boxes
function moveListItmes(lstFrom,lstTo,sort)
{
	
	if (lstTo == null)
	{
		alert("Invalid To List Object");
		return false;
	}
	if (lstFrom == null)
	{
		alert("Invalid From List Object");
		return false;
	}
	if (lstFrom.options.selectedIndex != -1)
	{
		for(var cntr=lstFrom.options.length-1;cntr>=0;cntr--)
		{
			if (lstFrom.options[cntr].selected == true)
			{
				var selectedOption = new Option;
				selectedOption = lstFrom.options[lstFrom.options.selectedIndex];
				lstFrom.remove(lstFrom.selectedIndex);
				lstTo.add(selectedOption);
				//alert(selectedOption.text + ' - ' + selectedOption.value);
				lstTo.selectedIndex = -1;
			}
		}
	if (moveListItmes.arguments.length == 3) 	
	{
		//sortList(lstTo);	
	}
	
	}
	return false;
}
function sortList(lstObject)
{
	if (lstObject == null)
	{
		return false;
	}
	arrOptions = new Array();
	arrOptionsText = new Array();
	for (var cntr=0;cntr<lstObject.options.length;cntr++)
	{
		arrOptions[lstObject.options[cntr].text] = lstObject.options[cntr].value;
		arrOptionsText[cntr] =  lstObject.options[cntr].text;
	}
	arrOptionsText.sort();
	lstObject.options.length=0;
	
	for (var cntr=0;cntr<arrOptionsText.length;cntr++)
	{
		var lstOption = new Option();
		lstOption.text = arrOptionsText[cntr];
		lstOption.value = arrOptions[arrOptionsText[cntr]];
		lstObject.options.add(lstOption);
	}
}
//end functions for list box
//End Script_Standards
function displayHelpWindow()
{
	Help_window=window.open('Help.aspx?HelpId=' + document.all['hdnHelpId'].value,'Help_window','width=350,height=350,scrollbars=1');
	Help_window.focus();
	//"javascript:Help_window=window.open('Help.aspx?HelpId=' + document.all['hdnHelpId'].value,'Help_window','width=350,height=350,scrollbars=1');Help_window.focus();"
}
function AreDatesInSameFormat(StartDate,EndDate)
{
	var str;
	var startYear;
	var endYear;
	str = StartDate.split('/');
	startYear = str[2];
	str = EndDate.split('/');
	endYear = str[2];
	if(startYear.length==endYear.length)
		return true;
	else
		return false;
	
}
//to make the filed mandatory :- ensures the user to enter a value in a mandatory field
function CheckTrim(str) 
{ 
	return ((str.replace(/^\s+/,'')).replace(/\s+$/,'')); 
} 
function checkCharactorLength(str, len)
{
	if(str.length > len)
		return false;
	else
		return true;

}
function KeyPressAlphaNumeric() 
{
	if ((event.keyCode < 48) || (event.keyCode > 122) || 
	   ((event.keyCode > 57) && (event.keyCode < 65)) || 
	   ((event.keyCode > 90) && (event.keyCode < 97))   &&
		  event.keyCode != 13) {
		event.returnValue = false;
	} 
}
function ValidateAlphaNumeric(text) {
    text.value = text.value.replace(/([^0-9A-Za-z])/g,"");
}

function KeyPressLock() 
{
	if ((event.keyCode < 256) && (event.keyCode >= 0)) {
		event.returnValue = false;
	} 
}
function isValid(input) {
/* Initialise the previousValue property with the initial value
* of the control (specified with the value attribute).
*/
if('undefined' == typeof input.previousValue) {
input.previousValue = input.defaultValue;
}
/* Validate the control value.
*
* The first test ensures that the value only contains integers
* with no leading zeros. The second checks that the number is
* greater-than or equal to the minimum value.
*/
if(!/^(0|[1-9]\d*)$/.test(input.value)
|| (+input.value < minimumValue))
{
alert('Please enter a number greater than ' + minimumValue);
input.value = input.previousValue;
} else {
input.previousValue = input.value;
}
}

function keypress(cntrl) 
{ 
   var cntrl1 =document.getElementById('hiddencontrol'); 
   cntrl1.value = cntrl.value; 
} 
function propertychanged(cntrl) 
{ 
   var reg = /^\d+\.?\d{0,4}$/; 
   var val = cntrl.value; 
   var cntrl1 = document.getElementById('hiddencontrol'); 
   var val1 = cntrl1.value; 
   if (val.length > 0) 
   { 
       if (!reg.test(val)) 
       { 
         cntrl.value = val1; 
       } 
    } 
    else 
    { 
        cntrl1.value = ''; 
    } 
}

/*-------  VALIDATE PAN,TAN Using Javascript Regular Expressions
            MODIFIED BY RAGHU
             MODIFIED DATE:18-NOV-08
  DATE :17-OCT-08 
  */
 
      function ValidatePan(CientID)
{
  var PAN =CientID;  
      
	if (PAN.value != "") 
	{
	  
                 PAN.value=PAN.value.toUpperCase(); 
 
                var reExp = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/;
          if (!reExp.test(PAN.value)) 
	    {
              	alert( "Invalid PAN.");
      	        PAN.focus();
	            return false;
        }
        
   }
}

  function ValidateTan(CientID)
{
         var TAN =document.getElementById(CientID);  
	if (TAN.value != "") 
	{
	  
                 TAN.value=TAN.value.toUpperCase(); 
 
                var reExp = /^[A-Z]{4}[0-9]{5}[A-Z]{1}$/;
          if (!reExp.test(TAN.value)) 
	    {
              	alert( "Invalid TAN.");
      	        TAN.focus();
	            return false;
	            
        }
        else
        {
          return true;
        }
   }
}






 function checkFileExt(ctrl) 
{
    //set the name of our form
  //  var form = document.form1;
    //retrieve our control
    //alert(ctrl);
   var file = ctrl.value;
    var type = "";
    
    
    //create an array of acceptable files
    var validExtensions = new Array();
    validExtensions[0]=".pdf";
    validExtensions[1]=".xls";
    validExtensions[2]=".xml";
    var allowSubmit = false;
    //if our control contains no file then alert the user
    if (file.indexOf("\\") == -1)
    {
       
        alert("You must select a file before hitting the Upload button");
        return false;;
    }
    else
    {
        //get the file type
        type = file.slice(file.indexOf("\\") + 1);
        var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
        //loop through our array of extensions
        for (var i = 0; i < validExtensions.length; i++) 
        {
            //check to see if it's the proper extension
            if (validExtensions[i] == ext) 
            { 
                //it's the proper extension
                allowSubmit = true; 
            }
        }
    }
    //now check the final bool value
    if (allowSubmit == false)
    {
        //let the user know they selected a wrong file extension
        alert("Only files with extensions " + (validExtensions.join("  ").toUpperCase()) + " are allowed");
        return false;
    }
    else
    {
        return true
    }       
    return allowSubmit;
}

function checkFileExtOnlypdf(ctrl) {
    //set the name of our form
    //  var form = document.form1;
    //retrieve our control
    //alert(ctrl);
    var file = ctrl.value;
    var type = "";


    //create an array of acceptable files
    var validExtensions = new Array();
    validExtensions[0] = ".pdf";
    var allowSubmit = false;
    //if our control contains no file then alert the user
    if (file.indexOf("\\") == -1) {

        alert("You must select a file before hitting the Upload button");
        return false; ;
    }
    else {
        //get the file type
        type = file.slice(file.indexOf("\\") + 1);
        var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
        //loop through our array of extensions
        for (var i = 0; i < validExtensions.length; i++) {
            //check to see if it's the proper extension
            if (validExtensions[i] == ext) {
                //it's the proper extension
                allowSubmit = true;
            }
        }
    }
    //now check the final bool value
    if (allowSubmit == false) {
        //let the user know they selected a wrong file extension
        alert("Only files with extensions " + (validExtensions.join("  ").toUpperCase()) + " are allowed");
        return false;
    }
    else {
        return true
    }
    return allowSubmit;
}


var http ;
  var results;
  var req;
 var valueLabelPair;
var returnelements;
  var fldNum;
var mywindow1;
var panctrl;
    
     function StateChange1(paninput) 
     {
          // alert(paninput.value);
         paninput.value=paninput.value.toUpperCase(); 
          
      req = new ActiveXObject("Microsoft.XMLHTTP");
      panctrl=paninput;
      if (req) 
      {
        req.onreadystatechange = StateChange;
      
        req.open("POST", "https://onlineservices.tin.nsdl.com/etaxnew/PopulateBankServlet", true);
      
        req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        //var strToSend = "&AssessYear=Assessment%20Year&Add_State=State&Name=&Add_PIN=&Add_Line5=&Add_Line4=&Add_Line3=&Add_Line2=&Add_Line1=&PAN="+ paninput.value +"&ChallanNo=280&MinorHeadRadio=0&MajorHeadRadio=2"
        //alert(strToSend);
        var strToSend = "&AssessYear=2010-11&Add_State=ANDHRA%20PRADESH&Name=fdskfj&Add_PIN=432432&Add_Line5=fdsklfhsdjk&Add_Line4=&Add_Line3=&Add_Line2=&Add_Line1=&PAN="+ paninput.value +"&ChallanNo=280&MinorHeadRadio=1&MajorHeadRadio=2"
        req.send(strToSend);
        
      }

}
      

function StateChange() 
{

          
          if (req.readyState == 4) 
          {
              if (req.status == 200) 
              {
                   results = req.responseText.split("$");
                   if(results[1]!=null || results[1]=="")
                   {
                       
//                     alert('Before' + results[1]);
                        if(results[1]=='Invalid PAN')
                        {
                                          alert(results[1]);
                                          panctrl.focus();
                                          return false;
                                          
                       }
                               
                   }
                   else
                   {
                        returnelements = req.responseText.split("||");
                
                       // alert(req.responseText);

                        for ( var i=0; i<returnelements.length-1; i++ )
                        {
                            valueLabelPair = returnelements[i].split("|");
                        }
                    }
                }
        }
        else 
        {
     
            results = req.responseText.split("$");
            if(results[1]!=null || results[1]=="")
            {
                alert(results[1]);
                 if(results[1]=='Invalid PAN')
                        {
                       
                        panctrl.focus();
                         return false;
                       }
            }
            else
                alert("Site Under Maintenance:\n ");
      }
}




