<!--
// 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.
// isDateString (stringValue)		   True if string form a valid date (Mimic IsDate)
// isTimeString (stringValue)		   True if string form a valid time (Mimic IsDate)
// dateDiff (intervalo,data1,data2)    Similar a função dateDiff do VB
// dateAdd (intervalo,numero,data1)    Similar a função dateAdd do VB
// formatDate(data,formato)
// today()							   Retorna a data de hoje no format dd/mm/yyyy	
// FormatNumber(Numero, sDigitoDecimalEntrada,sDigitoDecimalSaida,iCasasDecimais,bExibeMilhar)
// ltrim (s)
// rtrim (s)
// trim (s)
// string$(sCaracter,iTamanho)
// round(Numero,iCasasDecimais)

// 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.
// replace (expressao, encontrar, substituir)
// right(expressao,tamanho){
// left(expressao,tamanho){

// 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.
// 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 = ","


// Ponto de milhar
var milharPointDelimiter = "."

// 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)
}


function replace(expressao, encontrar, substituir){

	var sExpressaoRetorno = "";
	expressao = expressao + "";
	
	var arrExpressao = expressao.split(encontrar);
	
	for (var cont=0;cont<arrExpressao.length;cont++){
		sExpressaoRetorno = sExpressaoRetorno + arrExpressao[cont] + substituir;
	}
	
	return sExpressaoRetorno.substring(0,sExpressaoRetorno.length - substituir.length);
}

function right(expressao,tamanho){
	
	var inicio = expressao.length - tamanho;
	return expressao.substring(inicio,expressao.length);
	
}

function left(expressao,tamanho){
	
	return expressao.substring(0,tamanho);
	
}



// 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;

	if (s.indexOf(milharPointDelimiter) != -1) {
		var arrCasas = s.split(milharPointDelimiter);

		var count;
		for (count = 0;count < arrCasas.length;count++){
			if (count == 0){
				if (arrCasas[count].length > 3 || arrCasas[count].length == 0){
					return false;
				}
			}
			else if (count == arrCasas.length - 1){
				if (arrCasas[count].indexOf(decimalPointDelimiter) == -1){
					if (arrCasas[count].length != 3){
						return false;
					}
				}
				else if (arrCasas[count].indexOf(decimalPointDelimiter) != 3){
					return false;
				}
			}
			else{
				if (arrCasas[count].length != 3 || !isInteger(arrCasas[count])){
					return false;
				}
			}				
		}
		s = stripCharsInBag(s,milharPointDelimiter);
	}

    // 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;
}



//function que verifica se um caracter esta em um determinado range
//par:valor - valor do objeto
//range - range de valores permitidos pelo objeto
//msg - msg a ser mostrada em caso de erro
//mostra - '1' se mostra msg 
//retorno:boleano
//
function verificaValor(valor,range,msg,mostra){
  var resp=true;
  for(var i=0;i<valor.length;i++){
    if (range.indexOf(valor.charAt(i))==-1){
      resp=false;
      i=valor.length;
    }
  }
  if (!resp && mostra=='1')
    alert(msg);
  
  return resp;
}



// 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))
    }
}

function fnConsisteTamanhoDecimal(Numero,iQtdInteiros,iQtdDecimais){
	
	var sDigitoDecimalEntrada = "";
	var aNumero;
	
	//Converte o numero para string
	Numero =  Numero + "";
	
	if (Numero.indexOf(",") < Numero.indexOf(".") && Numero.indexOf(".") < Numero.lastIndexOf(",")) return false;
	if (Numero.indexOf(".") < Numero.indexOf(",") && Numero.indexOf(",") < Numero.lastIndexOf(".")) return false;

	//Obtem o caracter separador de decimal e retira os de milhar
	var iPosVirgula = Numero.indexOf(",");
	var iPosPonto = Numero.indexOf(".");
	if (iPosVirgula > iPosPonto && iPosPonto != -1){
		Numero = replace(Numero,".","")
		sDigitoDecimalEntrada = ",";
	}else if (iPosVirgula < iPosPonto && iPosVirgula != -1){
		Numero = replace(Numero,",","")
		sDigitoDecimalEntrada = ".";
	}else if (iPosVirgula > -1 && iPosPonto == -1){
		sDigitoDecimalEntrada = ",";
	}else if (iPosPonto > -1 && iPosVirgula == -1){
		sDigitoDecimalEntrada = ".";
	}else{
		sDigitoDecimalEntrada = "";
	}
	
	//Subistitui o caracter separador decimal por "."
	if (sDigitoDecimalEntrada !=""){
		Numero = replace(Numero,sDigitoDecimalEntrada,"."); 
	}

	//Verifica se é um numero
	if (isNaN(parseFloat(Numero))) return false;

	//Retira zeros a esquerda e a direita desnecessários
	Numero = Numero - 0;
	//Converte o numero para string
	Numero =  Numero + "";

	//Verifica se ainda existe separador de decimal
	if (Numero.indexOf(".") == -1) sDigitoDecimalEntrada = "";
	
	//Verifica se existe digito decimal de entrada
	if (sDigitoDecimalEntrada != ""){
		//Separa as partes do número
		aNumero = Numero.split(".");
		//Verifica o tamanho das partes
		if (aNumero[0].length > iQtdInteiros || aNumero[1].length > iQtdDecimais)
			return false;
	//Senão verifica o tamanho do numero
	}else if (Numero.length > iQtdInteiros)
		return false;
		
	return true;

}

function fnValidaCEP(sCEP){

	var aCEP;
	
	sCEP = sCEP + "";
	aCEP = sCEP.split("-");
	
	if (sCEP.length != 9) return false;
	if (aCEP.length != 2) return false;
	if (aCEP[0].length != 5 || !isInteger(aCEP[0])) return false;
	if (aCEP[1].length != 3 || !isInteger(aCEP[1])) return false;
	
	return true;
}

// 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;
}

function ltrim(s) {
	var i = 0;
    while ( (i < s.length) && charInString(s.charAt(i), " ") )
       i++;
    return s.substring(i, s.length);
}

function rtrim(s) {
	var i = s.length - 1;
    while ( (i > 0) && s.charAt(i) == " " )
       i--;
    return s.substring(0, (i==0)?s.length:++i)
}

function trim(s) {
	return ltrim(rtrim(s));
}


function mid(str, start, len)
/***
        IN: str - the string we are LEFTing
            start - our string's starting position (0 based!!)
            len - how many characters from start we want to get

        RETVAL: The substring from start to start+len
***/
{
        // Make sure start and len are within proper bounds
        if (start < 0 || len < 0) return "";

        var iEnd, iLen = String(str).length;
        if (start + len > iLen)
                iEnd = iLen;
        else
                iEnd = (start -1) + len;

        return String(str).substring(start -1,iEnd);
}


function len(str)
/***
        IN: str - the string whose length we are interested in

        RETVAL: The number of characters in the string
***/
{  return String(str).length;  }


// reformat (TARGETSTRING, STRING, INTEGER, STRING, INTEGER ... )       
//
// Handy function for arbitrarily inserting formatting characters
// or delimiters of various kinds within TARGETSTRING.
//
// reformat takes one named argument, a string s, and any number
// of other arguments.  The other arguments must be integers or
// strings.  These other arguments specify how string s is to be
// reformatted and how and where other strings are to be inserted
// into it.
//
// reformat processes the other arguments in order one by one.
// * If the argument is an integer, reformat appends that number 
//   of sequential characters from s to the resultString.
// * If the argument is a string, reformat appends the string
//   to the resultString.
//
// NOTE: The first argument after TARGETSTRING must be a string.
// (It can be empty.)  The second argument must be an integer.
// Thereafter, integers and strings must alternate.  This is to
// provide backward compatibility to Navigator 2.0.2 JavaScript
// by avoiding use of the typeof operator.
//
// It is the caller's responsibility to make sure that we do not
// try to copy more characters from s than s.length.
//
// EXAMPLES:
//
// * To reformat a 10-digit U.S. phone number from "1234567890"
//   to "(123) 456-7890" make this function call:
//   reformat("1234567890", "(", 3, ") ", 3, "-", 4)
//
// * To reformat a 9-digit U.S. Social Security number from
//   "123456789" to "123-45-6789" make this function call:
//   reformat("123456789", "", 3, "-", 2, "-", 4)
//
// HINT:
//
// If you have a string which is already delimited in one way
// (example: a phone number delimited with spaces as "123 456 7890")
// and you want to delimit it in another way using function reformat,
// call function stripCharsNotInBag to remove the unwanted 
// characters, THEN call function reformat to delimit as desired.
//
// EXAMPLE:
//
// reformat (stripCharsNotInBag ("123 456 7890", digits),
//           "(", 3, ") ", 3, "-", 4)

function reformat (s)

{   var arg;
    var sPos = 0;
    var resultString = "";

    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}




// isSSN (STRING s [, BOOLEAN emptyOK])
// 
// isSSN returns true if string s is a valid U.S. Social
// Security Number.  Must be 9 digits.
//
// NOTE: Strip out any delimiters (spaces, hyphens, etc.)
// from string s before calling this function.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isSSN (s)
{   if (isEmpty(s)) 
       if (isSSN.arguments.length == 1) return defaultEmptyOK;
       else return (isSSN.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInSocialSecurityNumber)
}




// isUSPhoneNumber (STRING s [, BOOLEAN emptyOK])
// 
// isUSPhoneNumber returns true if string s is a valid U.S. Phone
// Number.  Must be 10 digits.
//
// NOTE: Strip out any delimiters (spaces, hyphens, parentheses, etc.)
// from string s before calling this function.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isUSPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isUSPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isUSPhoneNumber.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInUSPhoneNumber)
}




// isInternationalPhoneNumber (STRING s [, BOOLEAN emptyOK])
// 
// isInternationalPhoneNumber returns true if string s is a valid 
// international phone number.  Must be digits only; any length OK.
// May be prefixed by + character.
//
// NOTE: A phone number of all zeros would not be accepted.
// I don't think that is a valid phone number anyway.
//
// NOTE: Strip out any delimiters (spaces, hyphens, parentheses, etc.)
// from string s before calling this function.  You may leave in 
// leading + character if you wish.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isInternationalPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isInternationalPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isInternationalPhoneNumber.arguments[1] == true);
    return (isPositiveInteger(s))
}




// isZIPCode (STRING s [, BOOLEAN emptyOK])
// 
// isZIPCode returns true if string s is a valid 
// U.S. ZIP code.  Must be 5 or 9 digits only.
//
// NOTE: Strip out any delimiters (spaces, hyphens, etc.)
// from string s before calling this function.  
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isZIPCode (s)
{  if (isEmpty(s)) 
       if (isZIPCode.arguments.length == 1) return defaultEmptyOK;
       else return (isZIPCode.arguments[1] == true);
   return (isInteger(s) && 
            ((s.length == digitsInZIPCode1) ||
             (s.length == digitsInZIPCode2)))
}





// isStateCode (STRING s [, BOOLEAN emptyOK])
// 
// Return true if s is a valid U.S. Postal Code 
// (abbreviation for state).
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isStateCode(s)
{   if (isEmpty(s)) 
       if (isStateCode.arguments.length == 1) return defaultEmptyOK;
       else return (isStateCode.arguments[1] == true);
    return ( (USStateCodes.indexOf(s) != -1) &&
             (s.indexOf(USStateCodeDelimiter) == -1) )
}




// isEmail (STRING s [, BOOLEAN emptyOK])
// 
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}





// isYear (STRING s [, BOOLEAN emptyOK])
// 
// isYear returns true if string s is a valid 
// Year number.  Must be 2 or 4 digits only.
// 
// For Year 2000 compliance, you are advised
// to use 4-digit year numbers everywhere.
//
// And yes, this function is not Year 10000 compliant, but 
// because I am giving you 8003 years of advance notice,
// I don't feel very guilty about this ...
//
// For B.C. compliance, write your own function. ;->
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isYear (s)
{   if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}



// isIntegerInRange (STRING s, INTEGER a, INTEGER b [, BOOLEAN emptyOK])
// 
// isIntegerInRange returns true if string s is an integer 
// within the range of integer arguments a and b, inclusive.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.


function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseFloat (s);
    return ((num >= a) && (num <= b));
}



// isMonth (STRING s [, BOOLEAN emptyOK])
// 
// isMonth returns true if string s is a valid 
// month number between 1 and 12.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isMonth (s)
{   if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}



// isDay (STRING s [, BOOLEAN emptyOK])
// 
// isDay returns true if string s is a valid 
// day number between 1 and 31.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isDay (s)
{   if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
}



// daysInFebruary (INTEGER year)
// 
// Given integer argument year,
// returns number of days in February of that year.

function daysInFebruary (year)
{   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}



// isDate (STRING year, STRING month, STRING day)
//
// isDate returns true if string arguments year, month, and day 
// form a valid date.
// 

function isDate (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.
    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}


function isDateString(stringValue) {

	// this function is designed to mimic the "date" portion of the
	// VBScript IsDate() function, allowing dates to be validated
	// with JavaScript in browsers before you run into a problem
	// in ASP pages with date database columns or the VBScript
	// CDate() function; an exception is that string months
	// ("Jan," etc.) are not accepted
		
	// this function does not handle BC dates or dates past 12/31/9999
		
	// you obviously want to strip the comments from production scripts
		
	// create a String object
	var theString = new String(trim(stringValue));
		
	// determine the delimiter character (must be "/" "-" or space)
	var delimiterCharacter;
	
	if ( theString.indexOf('/') > 0 )
		delimiterCharacter = '/';
	else
		if ( theString.indexOf('-') > 0 )
			delimiterCharacter = '-';
		else
			if ( theString.indexOf(' ') > 0 )
				delimiterCharacter = ' ';
			else
				return false;
					
	// split the string into an array of tokens
	var theTokens = theString.split(delimiterCharacter);
		
	// there must be either two or three tokens
	//if (theTokens.length < 2 || theTokens.length > 3 )
	if (theTokens.length != 3)
		return false;
		
	// convert the tokens to String objects, which will be needed later,
	// stripping a single leading 0
	var tokenIndex;
	for ( tokenIndex = 0; tokenIndex < theTokens.length; tokenIndex++ ) {
		theTokens[tokenIndex] = new String(theTokens[tokenIndex])			
		if ( theTokens[tokenIndex].charAt(0) == '0' )
			theTokens[tokenIndex] = theTokens[tokenIndex].substring(1, theTokens[tokenIndex].length);
	}

	// all of the tokens must be positive integers
	for ( tokenIndex = 0; tokenIndex < theTokens.length; tokenIndex++ ) {
		if ( ! isNonnegativeInteger(theTokens[tokenIndex]) )
			return false;
	}

	// we need to identify the year, month, and day tokens
	var numericValue;
	var yearTokenIndex = -1;
	var monthTokenIndex = -1;
	var dayTokenIndex = -1;
					
	for ( tokenIndex = 0; tokenIndex < theTokens.length; tokenIndex++ ) {
		// convert the value
		numericValue = parseInt(theTokens[tokenIndex], 10);
					
		if ( tokenIndex == 0 && numericValue <= 31 ) 
			dayTokenIndex = tokenIndex;
		if ( tokenIndex == 1 && numericValue <= 12 ) 
			monthTokenIndex = tokenIndex;
		if ( tokenIndex == 2 && numericValue <= 9999 ) 
			yearTokenIndex = tokenIndex;
	}	// end of for loop
		
	// evaluate, based on the number of tokens
	if ( theTokens.length == 2 ) {
			
		// two tokens can be either a month/year combination or a month/day
		// combination with the current year assumed; either way, we must have
		// a month
		if ( monthTokenIndex == -1 )
				
			// no month
			return false;
				
		// do we have a year?
		if ( ! (yearTokenIndex == -1) ) {
			
			// yes; month/year combination; must be okay
			return true;
		}
		else
				
			// no year; do we have a day?
			if ( ! (dayTokenIndex == -1) ) {
				
				// yes; month/day combination; get the current year
				var today = new Date();
				var currentYear = today.getYear();

				// make sure it's a valid date (we were testing days using
				// 31, and that might be too many for the month)
				return isDate(currentYear, theTokens[monthTokenIndex], theTokens[dayTokenIndex]);
			}
			else
				
				// we have neither a year nor a day
				return false;
	}
	else {
			
		// three tokens; we should have found tokens for year, month, and day
		if ( yearTokenIndex == -1 || monthTokenIndex == -1 || dayTokenIndex == -1 )
				
			// missing one or more
			return false;
		else
				
			// found all; however, VBScript can only handle the following sequences
			if ( monthTokenIndex == 0 ) {
				
				// must be m/d/y
				if ( dayTokenIndex != 1 || yearTokenIndex != 2)
					return false;
			}
			else
				if ( dayTokenIndex == 0 ) {
				
					// must be d/m/y
					if ( monthTokenIndex != 1 || yearTokenIndex != 2)
						return false;
				}
				else
					if ( yearTokenIndex == 0 ) {
				
						// must be y/m/d
						if ( monthTokenIndex != 1 || dayTokenIndex != 2)
							return false;
					}
					else
						
						// something is wrong
						return false;
				
			// make sure it's a valid date (we were testing days using a value
			// of 31, and that might be too many for the actual month)
			return isDate(theTokens[yearTokenIndex], theTokens[monthTokenIndex], theTokens[dayTokenIndex]);
	}
}

function isTimeString(stringValue) {

	// this function is designed to mimic the "time" portion of the
	// VBScript IsDate() function, allowing times to be validated
	// with JavaScript in browsers before you run into a problem
	// in ASP pages with date database columns or the VBScript
	// CDate() function
		
	// you obviously want to strip the comments from production scripts
	// and place this function in the library file

	// create a String object
	var theString = new String(stringValue);
		
	// the string must have either two (hours and minutes) or three
	// (hours, minutes and seconds) tokens, delimited by ":";
	// split the string into an array of tokens
	var theTokens = theString.split(':');
	if ( theTokens.length < 2 || theTokens.length > 3 )
		return false;
		
	// convert the tokens to String objects, which will be needed later,
	// stripping whitespace
	var firstToken = new String(theTokens[0])
	firstToken = trim(firstToken);
	var middleToken;
	if ( theTokens.length == 3 ) {
		middleToken = new String(theTokens[1])
		middleToken = trim(middleToken);
	}
	var lastToken = new String(theTokens[theTokens.length - 1])
	lastToken = trim(lastToken);

	// the first token (hours) must be an integer between 0 and 23
	if ( ! isInteger(firstToken) )
		return false;
	if ( ! isIntegerInRange(firstToken, 0, 23) )
		return false;
		
	// are there three tokens?
	if ( theTokens.length == 3 ){
		
		// the middle token (minutes) must be an integer between 0 and 59
		if ( ! isInteger(middleToken) )
			return false;
		if ( ! isIntegerInRange(middleToken, 0, 59) )
			return false;
	}
			
	// the first one or two characters of the last token (either minutes
	// and optional am/pm indicator or seconds and am/pm indicator) must
	// be digits
	if ( ! isDigit(lastToken.charAt(0)) )
		return false;
		
	// the first character is a digit; split the last token into the minutes
	// or seconds value and the indicator; depending on the second character
	var lastValue;
	var ampmIndicator;
	if ( isDigit(lastToken.charAt(1)) ) {
		lastValue = new String(lastToken.substring(0, 2));
		if ( lastToken.length >= 3 )
			ampmIndicator = new String(trim(lastToken.substring(2, lastToken.length)));
		else
			ampmIndicator = new String();
	}
	else {
		lastValue = new String(lastToken.substring(0, 1));
		if ( lastToken.length >= 2 )
			ampmIndicator = new String(trim(lastToken.substring(1, lastToken.length)));
		else
			ampmIndicator = new String();
	}
	ampmIndicator = ampmIndicator.toUpperCase();
		
	// the last value must be between 0 and 59
	if ( ! isIntegerInRange(lastValue, 0, 59) )
		return false;
		
	// check the am/pm indicator, if there is one
	if ( ampmIndicator.length > 0 )
		if ( ! ( ampmIndicator == "AM" || ampmIndicator == "PM" ) )
			return false;
				
	// valid time
	return true;
}

function dateDiff(intervalo,data1,data2) {

	date1 = new Date();
	date2 = new Date();
	diff  = new Date();

	if (isDateString(data1)) { // Validates first date 
		data1 = formatDate (data1,"mm/dd/yyyy")
		date1 = new Date(data1);
	}
	else return false; // otherwise exits

	if (isDateString(data2)) { // Validates second date 
		data2 = formatDate (data2,"mm/dd/yyyy")
		date2 = new Date(data2);
	}
	else return false; // otherwise exits

	// sets difference date to difference of first date and second date
	timediff = date2.getTime() - date1.getTime();
	
	switch(intervalo){
		case "y" :
			return date2.getYear() - date1.getYear();
		case "m" :
			return (((date2.getYear() - date1.getYear()) * 12) + (date2.getMonth() - date1.getMonth()))
		case "w" :
			return Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
		case "d" :
			return Math.floor(timediff / (1000 * 60 * 60 * 24)); 
		case "h" :
			return Math.floor(timediff / (1000 * 60 * 60)); 
		case "n" :
			return Math.floor(timediff / (1000 * 60)); 
		case "s" :
			return Math.floor(timediff / 1000); 
		case "ms" :
			return timediff;
		default :
			return false;
	}		
}

function dateAdd(intervalo,numero,data1){

	date1 = new Date();

	if (isDateString(data1)) { // Validates first date 
		data1 = formatDate (data1,"mm/dd/yyyy")
		date1 = new Date(data1);
	}
	else return false;
	
//	if (!isSignedInteger(numero)) return false;

	switch(intervalo){
		case "y" :
			var year = parseFloat(date1.getYear() + parseFloat(numero));
			return formatDate(date1.getDate() + "/" + parseFloat(date1.getMonth() + 1) + "/" + year,"dd/mm/yyyy")
		case "m" :
			date1.setMonth(date1.getMonth() + parseFloat(numero));
			var month = new String(parseFloat(date1.getMonth() + 1));
			return formatDate(date1.getDate() + "/" + month + "/" + date1.getYear(),"dd/mm/yyyy");
		case "d" :
			date1.setDate(date1.getDate() + parseFloat(numero));
			var day = new String(date1.getDate());
			return formatDate(day + "/" + parseFloat(date1.getMonth() + 1) + "/" +  date1.getYear(),"dd/mm/yyyy");
		default :
			return false;
	}		
}

function formatDate(data,formato){
	
	var arrData1;
	var dia;
	var mes;
	var ano;

	var sSubistitui;

	if (!isDateString(data)) return false;
	
	data = trim(data);
	data = replace(data,".","/");
	data = replace(data,"-","/");
	data = replace(data," ","/");
	
	arrData1 = data.split("/");
	try{
		dia = arrData1[0];
		mes = arrData1[1];
		ano = arrData1[2];

	}catch(Erro){
		return false;
	}

	sSubistitui = replace(formato, "dd", right("0"+dia,2))
	sSubistitui = replace(sSubistitui, "d", dia);
		
	sSubistitui = replace(sSubistitui, "mm", right("0"+mes,2))
	sSubistitui = replace(sSubistitui, "m", mes);

	sSubistitui = replace(sSubistitui, "yyyy", right("0000" + ano,4))
	return replace(sSubistitui, "yy", right(ano,2));

}

function today(){
	
	var data = new Date();

	return right("0" + data.getDate(),2) + "/" + right("0" + parseFloat(data.getMonth() + 1),2) + "/" + data.getYear() 

}

function weekDayName(data)
{
	date1 = new Date();

	if (isDateString(data)) { // Validates first date 
		data = formatDate (data,"mm/dd/yyyy")
		date1 = new Date(data);
	}
	else return false;

    var weekday=new Array("domingo","segunda-feira","terça-feira","quarta-feira","quinta-feira","sexta-feira","sábado")
    
    return weekday[date1.getDay()];
}

function string$(sCaracter,iTamanho){
	var sRetorno = '';
	for (var iCont=1;iCont<=iTamanho;iCont++){
		sRetorno = sRetorno + sCaracter;
	}
	return sRetorno;
}

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 FormatNumber(Numero,sDigitoDecimalSaida,iCasasDecimais,bExibeMilhar){

	var sDigitosPermitidos = "-.-,";
	var sDigitoMilhar;
	var sSinal = "";
	var aNumeroSeparado;

	var sDigitoDecimalEntrada = "";
	var iPosVirgula = -1;
	var iPosPonto = -1;

	Numero = Numero + "";
	
	if (sDigitosPermitidos.indexOf(sDigitoDecimalSaida)== -1) return false;
	if (sDigitosPermitidos.indexOf(sDigitoDecimalEntrada)== -1) return false;
	if (Numero.indexOf(",") < Numero.indexOf(".") && Numero.indexOf(".") < Numero.lastIndexOf(",")) return "NaN";
	if (Numero.indexOf(".") < Numero.indexOf(",") && Numero.indexOf(",") < Numero.lastIndexOf(".")) return "NaN";
	if (iCasasDecimais < 0) return false;
	
	iPosVirgula = Numero.indexOf(",");
	iPosPonto = Numero.indexOf(".");
	if (iPosVirgula > iPosPonto && iPosPonto != -1){
		Numero = replace(Numero,".","")
		sDigitoDecimalEntrada = ",";
	}else if (iPosVirgula < iPosPonto && iPosVirgula != -1){
		Numero = replace(Numero,",","")
		sDigitoDecimalEntrada = ".";
	}else if (iPosVirgula > -1 && iPosPonto == -1){
		sDigitoDecimalEntrada = ",";
	}else if (iPosPonto > -1 && iPosVirgula == -1){
		sDigitoDecimalEntrada = ".";
	}else{
		sDigitoDecimalEntrada = "";
	}

	if (sDigitoDecimalEntrada != ""){
		Numero = replace(Numero,sDigitoDecimalEntrada,".");
	}

	if (sDigitoDecimalSaida == "."){
		sDigitoMilhar = ",";
	}else{
		sDigitoMilhar = ".";
	}
			
	if (isNaN(parseFloat(Numero))) return "NaN";
	
	if (left(Numero,1) == "-"){
		Numero = right(Numero,Numero.length - 1);
		sSinal = "-";
	}else
		sSinal = "";

	if (Numero.indexOf(".") == -1){
		if (iCasasDecimais != 0)
			Numero = Numero + sDigitoDecimalSaida + string$(0,iCasasDecimais);
	}else{
		var sDecimal = right(Numero,Numero.length - Numero.indexOf(".") - 1);
		if (sDecimal.length <= iCasasDecimais){
			Numero = Numero + string$(0,iCasasDecimais - sDecimal.length);
		}else{
			Numero = round(Numero,iCasasDecimais) + ""
		}
	}

	Numero = replace(Numero,".",sDigitoDecimalSaida);

	if (bExibeMilhar){

		aNumeroSeparado = Numero.split(sDigitoDecimalSaida);

		Numero = aNumeroSeparado[0];
		if (Numero.length > 3){
			aNumeroSeparado[0] = "";
			while (Numero.length > 0){
				aNumeroSeparado[0] = sDigitoMilhar + right(Numero,3) + aNumeroSeparado[0];
				Numero = left(Numero,Numero.length - 3);
			}
			aNumeroSeparado[0] = right(aNumeroSeparado[0],aNumeroSeparado[0].length - 1); 
		}

		if (aNumeroSeparado.length == 1)
			Numero = aNumeroSeparado[0];
		else
			Numero = aNumeroSeparado[0] + sDigitoDecimalSaida + aNumeroSeparado[1];
	}
	
	return sSinal + Numero;		
}


//no evento onkeyPress passar os parametros this, this.value
//Consiste a data na digitação
function putdata(Control,Value)
{
	var Caracteres="0123456789";
    var Keyascii = event.keyCode;
                                
	if (Caracteres.indexOf(String.fromCharCode(Keyascii))==-1){
		event.returnValue = 0;
		return;
	}

    switch (Value.length)
        {
        case 2: //dia
            {
				if (isDate('2000','01',Value)){
	                Control.value = Value + "/";
					event.returnValue = true;
			        break;
				}else{
				    event.returnValue = false;
					break;
				}
			}
        case 5:
            {
				if (isDate('2000',mid(Value,4,2),left(Value,2))){
                    Control.value = Value + "/";
				    event.returnValue = true;
					break;
				}else{
					event.returnValue = false;
					break;
				}
			}
        case 9:
            {
				var sData = Value + String.fromCharCode(Keyascii);
				if (isDate(mid(sData,7,4),mid(sData,4,2),left(sData,2))){
				    event.returnValue = true;
				    break;
				}else{
				    Control.value = Value;
				    event.returnValue = false;
				    break;
                }
            }
//        case 10:
//            event.returnValue = false
	}
}


function MascaraDataHora(Control,Value)
{
	var Caracteres="0123456789";
    var Keyascii = event.keyCode;
                                
	if (Caracteres.indexOf(String.fromCharCode(Keyascii))==-1){
		event.returnValue = 0;
		return;
	}

    switch (Value.length)
        {
        case 2: //dia
            {
				if (isDate('2000','01',Value)){
	                Control.value = Value + "/";
					event.returnValue = true;
			        break;
				}else{
				    event.returnValue = false;
					break;
				}
			}
        case 5:
            {
				if (isDate('2000',mid(Value,4,2),left(Value,2))){
                    Control.value = Value + "/";
				    event.returnValue = true;
					break;
				}else{
					event.returnValue = false;
					break;
				}
			}
        case 9:
            {
				var sData = Value + String.fromCharCode(Keyascii);
				if (isDate(mid(sData,7,4),mid(sData,4,2),left(sData,2))){
				    event.returnValue = false;
				    Control.value = sData + " - ";
				    break;
				}else{
				    Control.value = Value;
				    event.returnValue = false;
				    break;
                }
            }
        case 13:
            {
				var sHora = String.fromCharCode(Keyascii);
				if (parseFloat(sHora) <= 2){
				    event.returnValue = true;
				    break;
				}else{
				    Control.value = Value;
				    event.returnValue = false;
				    break;
                }
				   
            }
        case 14:
            {
				var sData = left(Control.value,13)
				var sHora = right(Control.value,1) + String.fromCharCode(Keyascii);
				if (parseFloat(sHora) <= 23){
				    event.returnValue = false;
				    Control.value = sData + sHora + ":";
				    break;
				}else{
				    Control.value = Value;
				    event.returnValue = false;
				    break;
                }
				   
            }
        case 16:
            {
				var sData = left(Control.value,13)
				var sHora = right(Control.value,3) + String.fromCharCode(Keyascii);
				if (isTimeString(sHora + "0")){
				    event.returnValue = false;
				    Control.value = sData + sHora;
				    break;
				}else{
				    Control.value = Value;
				    event.returnValue = false;
				    break;
                }
				   
            }
        case 17:
            {
				var sData = left(Control.value,13)
				var sHora = right(Control.value,4) + String.fromCharCode(Keyascii);
				if (isTimeString(sHora)){
				    event.returnValue = false;
				    Control.value = sData + sHora + ":";
				    break;
				}else{
				    Control.value = Value;
				    event.returnValue = false;
				    break;
                }
				   
            }
        case 19:
            {
				var sData = left(Control.value,13)
				var sHora = right(Control.value,6) + String.fromCharCode(Keyascii);
				if (isTimeString(sHora + "0")){
				    event.returnValue = false;
				    Control.value = sData + sHora;
				    break;
				}else{
				    Control.value = Value;
				    event.returnValue = false;
				    break;
                }
				   
            }
        case 20:
            {
				var sData = left(Control.value,13)
				var sHora = right(Control.value,7) + String.fromCharCode(Keyascii);
				if (isTimeString(sHora)){
				    event.returnValue = false;
				    Control.value = sData + sHora;
				    break;
				}else{
				    Control.value = Value;
				    event.returnValue = false;
				    break;
                }
				   
            }
		case 21:
			event.returnValue = false;
	}
}

//no evento onKeyPress passar os parametros this, this.value
//Consiste a hora na digitação
function puthora(Control,Value)
{
	var Caracteres="0123456789";
    var Keyascii = event.keyCode;
                                
	if (Caracteres.indexOf(String.fromCharCode(Keyascii))==-1){
		event.returnValue = 0;
		return;
	}

	if(Value.length < 5){
		switch (Value.length)
		    {
		    case 1:
				{
					if (Value >= 0 && Value <= 2){
						event.returnValue = true;
				        break;
					}else{
					    event.returnValue = false;
						break;
					}
				}
		    case 2:
		        {	
					if (Value.substring(1,0) == 1 || Value.substring(1,0) == 0){
						if (Value.substring(2,1) >= 0 && Value.substring(2,1) <= 9){
						    Control.value = Value + ":";
							event.returnValue = true;
						    break;
						}else{
						    event.returnValue = false;
							break;
						}
					}
					if (Value.substring(1,0) == 2){
						if (Value.substring(2,1) >= 0 && Value.substring(2,1) <= 4){
						    Control.value = Value + ":";
							event.returnValue = true;
						    break;
						}else{
						    event.returnValue = false;
							break;
						}
					}
				}
			case 4:
		        {
					if (Value.substring(4,3) >= 0 && Value.substring(4,3) <= 5){
					    event.returnValue = true;
						break;
					}else{
						event.returnValue = false;
						break;
					}
				}
			case 5:
		        {
					if (Value.substring(5,4) >= 0 && Value.substring(5,4) <= 9){
					    event.returnValue = true;
						break;
					}else{
						event.returnValue = false;
						break;
					}
				}
		}
	}else{
		event.returnValue = false;
	}
}
function MascaraHora (objeto){

	var keypress = event.keyCode; 
	var campo = eval (objeto);

	var caracteres = '01234567890';
	var separacoes = 1;
	var separacao1 = ':';
	var conjuntos = 3;
	var conjunto1 = 2;
	var conjunto2 = 4;
	var conjunto3 = 2;

	campo.maxLength = 8;
	if ((caracteres.indexOf(String.fromCharCode (keypress))!=-1) && campo.value.length  < 
	(conjunto1 + conjunto2 + conjunto3 + 1)){
	
		if (campo.value.length == conjunto1)
		   campo.value = campo.value + separacao1;
		if (campo.value.length == conjunto2+1)
		   campo.value = campo.value + separacao1;
		   
	}
		
	else 
		event.returnValue = false;
}


function MascaraAnoMes (objeto){

	var keypress = event.keyCode; 
	var campo = eval (objeto);

	var caracteres = '01234567890';
	var separacoes = 1;
	var separacao1 = '-';
	var conjuntos = 2;
	var conjunto1 = 4;
	var conjunto2 = 2;

	campo.maxLength = 7;
	if ((caracteres.indexOf(String.fromCharCode (keypress))!=-1) && campo.value.length  < 
	(conjunto1 + conjunto2 + 1)){
		if (campo.value.length == conjunto1)
		   campo.value = campo.value + separacao1;
		}
	else 
		event.returnValue = false;
}

function fnMascaraCEP (objeto){

	var keypress = event.keyCode; 
	var campo = eval (objeto);

	var caracteres = '01234567890';
	var separacoes = 1;
	var separacao1 = '-';
	var conjuntos = 2;
	var conjunto1 = 5;
	var conjunto2 = 3;

	campo.maxLength = 9;
	if ((caracteres.indexOf(String.fromCharCode (keypress))!=-1) && campo.value.length  < 
	(conjunto1 + conjunto2 + 1)){
		if (campo.value.length == conjunto1)
		   campo.value = campo.value + separacao1;
		}
	else 
		event.returnValue = false;
}

function fnMascaraInteiro(objeto){
	var keypress = event.keyCode; 
	var campo = eval (objeto);

	var sCaracteres = '0123456789';

	if (sCaracteres.indexOf(String.fromCharCode(keypress))!=-1){
		event.returnValue = true;
    }else 
		event.returnValue = false;
}

function fnMascaraValor(Objeto,iNumDecimais){

	var sCaracteres = "0123456789";
    var Keyascii = event.keyCode;

	var sCaracter = String.fromCharCode(Keyascii)
                                    
	document.selection.clear();
	
	if (sCaracteres.indexOf(sCaracter)==-1){
        event.returnValue = false;
		return;
    }
                                
	if (trim(Objeto.value)=="")
		var Numero = "";
    else{
		var Numero = replace(Objeto.value,".","");
		var Numero = replace(Numero,",","");
	}

	Numero = Numero + sCaracter;
	
	if (Numero.length <= Objeto.maxLength - 1 || left(Numero, 1)=="0"){

		if (Numero.length <= iNumDecimais) 
			 Numero = "0," + string$(0, iNumDecimais - Numero.length) + Numero;
		else{
			if (left(Numero, iNumDecimais)==string$(0,iNumDecimais)){
				if (iNumDecimais == 1)
					Numero = mid(Numero,2,1) + "," + right(Numero, iNumDecimais);
				else
					Numero = "0," + right(Numero, iNumDecimais);
			}else if (left(Numero, 1)=="0")
				Numero = mid(Numero,2,1) + "," + right(Numero, iNumDecimais);
			else
				Numero = left(Numero,Numero.length - iNumDecimais) + "," + right(Numero, iNumDecimais);
		}
		Objeto.value = FormatNumber(Numero,",",iNumDecimais,true);
		event.returnValue = false;
	}
		
}

/* 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 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);
}

//Aqui estam sendo colocados as rotinas que antes pertenciam ao tratardados.js
//


// ------------------------------------------------------------------------------------------ //
// Acrescenta algumas propriedades aos controles:
// .Indice			: indica o índice na tela para o controle
// .IndiceAnterior	: indica o índice do controle anterior
// .IndicePosterior	: indica o índice para o controle posterior
// .Tam				: tamanho máximo para digitação
// .AutoSkip		: indica se pula para o próximo campo após completar o tamanho do campo
// .Tipo			: indica o tipo de dado
//						'D' -> só dígitos de 0(zero) a 9(nove)
//						'N' -> dígitos de 0(zero) a 9(nove), "."(ponto) e ","(vírgula)
//						'C' -> caracteres de 'a' até 'z' e de 'A' até 'Z'
//						'E' -> Especial - BackSpace
//						outro -> qualquer caracter entre ascii 32 e ascii 127
// .Saltar			: (reservado) indica o momento de saltar de campo
// ------------------------------------------------------------------------------------------ //

// Carrega índices para o próximo controle e controle anterior
function InicializarIndices()
{
	if (document.CargaInicial==null)
	{
		document.CargaInicial=false;		// Seta para só fazer uma vez por documento
		var ctrlAnterior=null;
		var IndAnt=0;
		for ( var i=0; i<document.forms[0].elements.length;i++)
		{
			var e=document.forms[0].elements[i];
			if ( e.type!="hidden" && e.type!="image" )		
			{
				if ( ctrlAnterior != null )
					ctrlAnterior.IndicePosterior=i;
				ctrlAnterior=e;
				e.Indice=i;
				e.IndiceAnterior=IndAnt;
			}
		}
		//if ( ctrlAnterior!=null )
		//{
		//	ctrlAnterior.IndicePosterior=i-1;
		//}
	}
}

// Colocar o foco em determinado campo
function SetarFoco ( ind )
	{
	InicializarIndices();
	if ( isNaN(ind) && document.forms[0].elements[ind].type!="hidden" )
		document.forms[0].elements[ind].focus();
	else
		for (;ind<document.forms[0].elements.length;ind++)
			if ( document.forms[0].elements[ind].type!="hidden" )
				break;
		if ( ind<=document.forms[0].elements.length )
			document.forms[0].elements[ind].focus();
	}

// Limpar o conteúdo do(s) campo(s)
function LimparCampo ( ind )
	// Para -1, limpa todos os elementos
	{
	if (isNaN(ind))			// Limpa pelo nome
		document.forms[0].elements[ind].value="";
	else if (ind != -1 )	// Limpa o elemento "ind" ( só considera "text" e "password" )
		for ( var i=ind; i < document.forms[0].elements.length;i++ )
			if ( document.forms[0].elements[i].type=="text" || document.forms[0].elements[i].type=="password")		// Só limpa campo "text"
				{
				document.forms[0].elements[i].value="";
				break;
				}
	else					// Limpa todos os elementos "text" e "password"
		for ( var i=0; i < document.forms[0].elements.length; i++ )
			if ( document.forms[0].elements[i].type=="text" || document.forms[0].elements[i].type=="password" )
				document.forms[0].elements[i].value="";
		
	}

// Verificar qual navegador
function QualNavegador() 
{
	var s = navigator.appName;
	if ( s == "Microsoft Internet Explorer" )
		return "IE";
	else if ( s == "Netscape" )
		return "NE";
	else
		return "";
}

// Verificar qual a versão do navegador
function QualVersao()
{
	var s = navigator.appVersion;
	if ( QualNavegador() == "IE" )
	{
		var i = s.search("MSIE");
		s=s.substring(i+5);
		i=s.search(".");
		return parseInt(s.substring(0,i+1));
	}
	else if ( QualNavegador() == "NE" )
		return parseInt(s.substring(0,1));
	else
		return 0;
}


// Setar o evento
function SetarEvento(ctrl, Tam, Tipo, AutoSkip )
{
	// Filtra navegadores conhecidos
	var s = QualNavegador();
	if ( s.length==0 )
		return;
	if ( s=="IE" && QualVersao()>5 )
		return;
	if ( s=="NE" && QualVersao()>4 )
		return;

	if (ctrl.onkeypress==null)
	{
		if (AutoSkip==null)
			AutoSkip=true;
		if (Tipo!=null)
			Tipo.toUpperCase();
		ctrl.Tam=Tam;
		ctrl.Tipo=Tipo;
		ctrl.AutoSkip=true;
		ctrl.Saltar=false;
		InicializarIndices();
		ctrl.onkeypress=ValidarTecla;
		if (QualNavegador()=="IE" && QualVersao()==5)
			ctrl.onkeyup=SaltarCampo;
	}
}

function SaltarCampo(ctrl)
{
	if (ctrl==null)
		ctrl=this;
	if ( ctrl.AutoSkip && ctrl.Saltar)
		if (ctrl.Saltar)
		{
			ctrl.Saltar=false;
			if ( ctrl.IndicePosterior != null )
				SetarFoco(ctrl.IndicePosterior);
		}
}

// Fazer o salto de campo
function ValidarTecla (evnt)
{
	var tk;
    var c;
	// Recebe a tela pressionada
	tk = ( (QualNavegador()=="IE") ? event.keyCode : evnt.which);
    c=String.fromCharCode(tk);
	c=c.toUpperCase();
	
	// -- Este trecho faz com que o <Enter> tenha a função de <Tab>, mas acho inviável, pois não é possível
	//       colocar o foco em campos do Tipo "image", e, neste caso, nunca seria possível fazer a submissão
	//       do formulário
	// if ( tk == 13 )
	// {
	//	this.Saltar=true;
	//	SaltarCampo(this);
	//	return false;
	// }
	
	// Só aceita teclas alfanuméricas. Não aceita teclas de controle
    if ( tk == 59)
		return false;
    if ( tk == 39 )
		return false;
	if ( tk == 34 )
		return false
    if ( tk < 32 )
		return true;
	if ( tk > 127 )
		return false;
	switch ( this.Tipo )
	{
	case "D":
		if ( c<"0" || c>"9" )
			return false;
		break;
	case "N":
		
		if ( (c<"0" || c>"9") && (c!=",") )
			return false;
		if ( (c==",") && ((this.value.search(",")>-1) || (this.value.length==0)) )
			return false;
		if ( (c==",") && (this.value.length==0) )
			return false;
		break;
	case "C":
		if ( c<"A" || c>"Z" )
			return false;
		break;
	case "E":
		if ( tk == 8)
			return false;
		break;
	default:
		break;
	}

	this.Saltar=(this.value.length==this.Tam-1);
	if ( ((QualNavegador()=="IE") && QualVersao()<5) || (QualNavegador()!="IE") )
		SaltarCampo(this);

	return true;
}


// Rotina : Validação de CGC/CNPJ
// Retorno: Retorna TRUE se o CGC/CNPJ for válido e FALSE caso contrário. 
//
function fnValidaCNPJ(strCNPJ) 
{ 
       if (strCNPJ == ""){ 
          return false; 
       } 
       // REMOVER
       //if (strCNPJ == "00000000000000"){ 
       //   return false; 
       //} 
		        
       var strDV = strCNPJ.substr(12, 2), 
	                intSoma, 
	                intDigito = 0, 
	                strControle = "", 
	                strMultiplicador = "543298765432"; 
	                
		strCNPJ = strCNPJ.substr(0, 12); 
		   	         
	   for(var j = 1; j <= 2; j++) 
	   { 
	       intSoma = 0; 
	       for(var i = 0; i <= 11; i++) 
	       { 
	           intSoma += (parseInt(strCNPJ.substr(i, 1), 10) * parseInt(strMultiplicador.substr(i, 1), 10))

	       } 
           if(j == 2){ intSoma += (2 * intDigito) } 
           intDigito = (intSoma * 10) % 11; 
           if(intDigito == 10){intDigito = 0} 
           strControle += intDigito.toString(); 
           strMultiplicador = "654329876543"; 
      } 
      return(strControle == strDV); 
} 

function fnValidaCPF(sCPF){
var frase="1234567890-.";
var fcerta=true;

  for (i=0;i<sCPF.length;i++)
	 fcerta&=frase.indexOf(sCPF.charAt(i))!=-1;

  //var mascara=/\d{9,9}+[-]+\d{2,2}/;
  if (!fcerta){
    return false;
  }
  else{
    var ls_num_cpf= replace(sCPF, ".", "");
    ls_num_cpf= replace(ls_num_cpf, "-", "");
  
    //Existem casos que o CPF tem um ou menos dígitos
    //nestes casos são adicionados um zeros a esquerda
    if (parseInt(ls_num_cpf.length)<11)
	  ls_num_cpf += string$("0",11 - ls_num_cpf.length); 
     
    //Calcula o primeiro digito de ls_num_cpf
    var li_conta1=0;
    for(i=1;i<=9;i++)
      li_conta1+=parseInt(ls_num_cpf.charAt(i-1))*(11-i);
	
    var li_conta2 = 11 - (li_conta1 % 11);
    if (li_conta2>9)
      li_conta2=0;

    if (li_conta2 != ls_num_cpf.charAt(ls_num_cpf.length-2)){
      return false;
    }
 
    //Calcula o segundo digito de ls_num_cpf
    var li_conta1=0;
    for(i=1;i<=9;i++)
      li_conta1+=parseInt(ls_num_cpf.charAt(i))*(11-i);
	
    var li_conta2 = 11 - (li_conta1 % 11);
    if (li_conta2 > 9)
     li_conta2 = 0;

    if (li_conta2 == ls_num_cpf.charAt(ls_num_cpf.length-1)){
	  return true;
    }
 }
 return false;
}

function fnMascaraCNPJCPF(objCampo)
{
//	objCampo = eval (objCampo);
	valor = objCampo.value;
//	objCampo.objCampo = valor;
	
//	valor = right("00000000000000" + valor,14);

	if (valor.length == 11)
	{
		mask=valor.substring(0,3)+"."+valor.substring(3,6)+"."+valor.substring(6,9)+"-"+valor.substring(9,11);
		objCampo.value = mask;
	}
	if (valor.length == 14)
	{
		mask=valor.substring(0,2)+"."+valor.substring(2,5)+"."+valor.substring(5,8)+"/"+valor.substring(8,12)+"-"+valor.substring(12,15);
		objCampo.value = mask;
	}
	
}

function fnTiraMascaraCNPJCPF(objCampo)
{
	valor = objCampo.value;

	if (valor.length == 14)
	{
		mask=valor.substring(0,3)+valor.substring(4,7)+valor.substring(8,11)+valor.substring(12,14);
		objCampo.value=mask
	}
	if (valor.length == 18)
	{
		mask=valor.substring(0,2)+valor.substring(3,6)+valor.substring(7,10)+valor.substring(11,15)+valor.substring(16,18);
		objCampo.value=mask;
	}
}

//Funções de Data **************************************************
function fnConsisteData(strConteudo,sFormatoSaida){

	if (trim(strConteudo) == "") return null;
	
	if (isDateString(strConteudo))
		return formatDate(strConteudo,sFormatoSaida);
	else
		return false;
	
}

function fnConsisteAnoMes(strConteudo,sFormatoSaida){
	if (trim(strConteudo) == "") return null;
}

function fnConsisteHora(strConteudo,sFormatoSaida){
	if (trim(strConteudo) == "") return null;
}

function fnConsisteDataHora(strConteudo,sFormatoSaidaData){

	if (trim(strConteudo) == "") return null;
	
	
	var sData = left(strConteudo,10);
	var sHora = right(strConteudo,8);
	var aHora;
	
	if (isDateString(sData) && isTimeString(sHora)){
		aHora = sHora.split(":");
		return formatDate(sData,sFormatoSaidaData) + 'T' +  aHora[0] + ':' +  aHora[1] + ':' + aHora[2];
	}
	else
		return false;
	
}

function fnConsisteComparaData(strConteudo,sComparacao,dData2,sPeriodo,sFormatoSaida){

	if (trim(strConteudo) == "") return null;

	if (!isDateString(strConteudo)) return false;
	if (!isDateString(dData2)) return false;
	
	var lRetorno = parseFloat(dateDiff(sPeriodo,strConteudo,dData2))
	
	if (eval(0 + sComparacao + lRetorno))
		return formatDate(strConteudo,sFormatoSaida);
	else
		return false;
	
}

function fnConsisteDtRetroativa(strConteudo,dDataAtual,sFormatoSaida){

	try{
		var bytFL_RESERVA = frmNovaMensagem.hidFL_RESERVA.value; //flag de afeta Reserva
	}catch(oErro){
		var bytFL_RESERVA = frmAlteracao.hidFL_RESERVA.value; //flag de afeta Reserva
	}

	if (trim(strConteudo) == "") 
		return null;
			
	if (isDateString(strConteudo)){
		
		if(bytFL_RESERVA=="1"){

			try{
				var strDebCred = frmNovaMensagem.cboDC.value;		
			}catch(oErro){
				var strDebCred = frmAlteracao.cboDC.value;		
			}

			if(strDebCred!="N"){
				if (dateDiff("d",strConteudo,dDataAtual) > 0){
					alert("Preencha o campo data de Movimento com uma data maior ou igual a data do Sistema.");
					return "***FALSE S/ MSG***";
				}
			}	
		}	

		return formatDate(strConteudo,sFormatoSaida);	

	}else
		return false;
}

//Fim Funções de Data **************************************************


//Funções Numéricas **************************************************
function fnConsisteInteiro(strConteudo){
	
	if (trim(strConteudo) == "") return null;

	if (isSignedInteger(strConteudo))
		return strConteudo;
	else
		return false;
	
}

function fnConsisteComparaInteiro(strConteudo,sComparacao,lValorComparado){
	
	if (trim(strConteudo) == "") return null;

	if (!isSignedInteger(strConteudo)) return false;
	if (!isSignedInteger(lValorComparado)) return false;

	if (eval("parseFloat(" + strConteudo + ")" + " " + sComparacao + " " + "parseFloat(" + lValorComparado + ")"))
		return strConteudo;
	else
		return false;
	
}

function fnConsisteDecimal(strConteudo,iQtdInteiros,iQtdDecimais, strNomeCampo){
	
	if (isSignedFloat(strConteudo) && fnConsisteTamanhoDecimal(strConteudo,iQtdInteiros,iQtdDecimais))
		return true;
	else
	{
		alert ("O campo " + strNomeCampo + " não está preenchido com um número válido.");
		return false;
	}
	
}

function fnConsisteComparaDecimal(strConteudo,sComparacao,lValorComparado,iCasasDecimais){
	
	if (trim(strConteudo) == "") return null;

	if (!isSignedFloat(strConteudo)) return false;
	if (!isSignedFloat(lValorComparado)) return false;

	strConteudo = replace(strConteudo,".","")
	strConteudo = replace(strConteudo,",",".")

	if (eval("parseFloat(" + strConteudo + ")" + " " + sComparacao + " " + "parseFloat(" + lValorComparado + ")"))
		return FormatNumber(strConteudo,",",iCasasDecimais,false);
	else
		return false;
	
}

function fnConsisteComparaPercentual(strConteudo,sComparacaoMenor,sComparacaoMaior,iQtdInteiros,iQtdDecimais){
	
	if (trim(strConteudo) == "") return null;

	if (!isSignedFloat(strConteudo) || !fnConsisteTamanhoDecimal(strConteudo,iQtdInteiros,iQtdDecimais)) return false;

	strConteudo = replace(strConteudo,".","")
	strConteudo = replace(strConteudo,",",".")

	if (eval("parseFloat(" + strConteudo + ")" + " " + sComparacaoMenor) &&
		eval("parseFloat(" + strConteudo + ")" + " " + sComparacaoMaior))
		return FormatNumber(strConteudo,",",iQtdDecimais,false);
	else
		return false;
	
}

//Fim Funções Numéricas **************************************************


//Funções de Texto **************************************************
function fnConsisteTexto(strConteudo){
	
	if (trim(strConteudo) == "") return null;
	else return strConteudo
	
}

function fnMascaraTexto(){
	
	var sChar;
	var sCaracteres = new String();

	sChar = String.fromCharCode(event.keyCode); 
	//sCaracteres = 'áàãäâÁÀÃÄÂéèêëÉÈÊËìíîïÌÍÎÏòóôõöÒÓÔÕÖùúûüÙÚÛÜýÝçÇñÑ=&+'
	sCaracteres = '0123456789abcdefghijklmnopqrstuvxwyzABCDEFGHIJKLMNOPQRSTUVXWYZ\\/-_. ';

	if (sCaracteres.indexOf(sChar) == -1)
		event.returnValue = 0;
	
}

//Fim Funções de Texto **************************************************


//Funções Especificas **************************************************

//ISPB
function fnConsisteISPB(strConteudo){
	
	if (trim(strConteudo) == "") return null;
	
	if (isInteger(strConteudo) && strConteudo.length == 8)
		return strConteudo;
	else
		return false;
	
}

//CNPJ
function fnConsisteCNPJCPF(strConteudo){

	if (trim(strConteudo) == "") return null;
	
	if (strConteudo.length == 18)
	{	
		strConteudo=strConteudo.substring(0,2)+strConteudo.substring(3,6)+strConteudo.substring(7,10)+strConteudo.substring(11,15)+strConteudo.substring(16,18);
		if (fnValidaCNPJ(strConteudo)){
			return strConteudo;
		}else
			
			return false;
	}
	if (strConteudo.length == 14)
	{
		strConteudo=strConteudo.substring(0,3)+strConteudo.substring(4,7)+strConteudo.substring(8,11)+strConteudo.substring(12,14);
		if (fnValidaCPF(strConteudo)){
			return strConteudo;
		}else
			return false;
	}
	else
		return false;
}
//Fim Funções Especificas **************************************************

function fnValidaObrigatoriedade(objCampo, strNomeCampo)
{
	if (trim(objCampo.value)==""){
		alert("O campo " + strNomeCampo + " tem preenchimento obrigatório.")
		objCampo.focus();
		return false;
	}

	return true;

}

function fnValidaHexadecimal(txtCampo, strNomeCampo){
	
	var strPossiveis = "0123456789ABCDEF";
	
	var strValor = txtCampo.value.toUpperCase();
	
	if (strValor.length != 6){
		alert("O campo " + strNomeCampo + " deve possuir 6 caracteres");
		return false;
	}
	
	for(var intContador=0;intContador < strValor.length;intContador++){
		if(strPossiveis.indexOf(strValor.charAt(intContador)) == -1){
			alert("O campo " + strNomeCampo + " não possui um hexadecimal válido");
			return false;
		}
	
	}

	return true;

}

function fnTrocaCor(objItem, strCor)
{
<!--
	objItem.style.color=strCor;
//-->
}	

function fnRedimensionaImagem(objImagem, lngLarguraMaxima, lngAlturaMaxima, blnExibir)
{
	var lngWidth = objImagem.width;
	var lngHeight = objImagem.height;

	if (lngWidth > lngHeight)
	{
		objImagem.width = lngLarguraMaxima;
		objImagem.height = lngHeight * lngLarguraMaxima / lngWidth;
	}else
	{
		objImagem.height = lngAlturaMaxima;
		objImagem.width = lngWidth * lngAlturaMaxima / lngHeight;
	}
	
	if (blnExibir)
	{
		objImagem.style.display='';
		objImagem.style.visibility='visible';
	}

}

function fnCriarElementoInput(strElemento, strTipo, strNome, strValor)
{
	var objElemento = document.createElement(strElemento);
	objElemento.type = strTipo;
	objElemento.name = strNome;
	objElemento.value = strValor;
	
	return objElemento;
}

function fnCriarElementoIFrame(strElemento, strId, strSrc, strWidth, strHeight, strFrameBorder)
{
	var objElemento = document.createElement(strElemento);
	objElemento.setAttribute("id", strId);
	objElemento.setAttribute("src", strSrc);
	objElemento.setAttribute("width", strWidth);
	objElemento.setAttribute("height", strHeight);
	objElemento.setAttribute("frameborder", strFrameBorder);

	return objElemento;
}

function fnLimitaTextoTextArea(objTextArea, lngMaxLength)
{
	if (objTextArea.value.length > lngMaxLength - 1)
	{
		objTextArea.value = left(objTextArea.value, lngMaxLength - 1);
	}
}

function fnSelecionaItemCombo(objCombo, strValue)
{
	var intNumItens = objCombo.length;
	
	for(var intContador = 0; intContador < intNumItens; intContador++)
	{
		if (objCombo.options[intContador].value == strValue)
		{
			objCombo.value = strValue;
			return;
		}
	}
}

function fnConverterValor(strValor)
{
	strValor = new String(strValor);
	strValor = replace(strValor, ",", ".");
	return parseFloat(strValor);
}

function AbrePopupRTE(objCampo)
{
	var hwdPopupRTE;
	hwdPopupRTE = window.open("../RTE/default.asp?Sessao=" + objCampo.Sessao,"RTE","scrollbars=no,location=no,directories=no,status=no,menubar=no,resizable=no,toolbar=no,top=50,left=50,width=820,height=565");
	return hwdPopupRTE;
}

function escapeHTML (str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}; 

function executaAjax(parametros, action){

	try { 
	    objHTTP = new ActiveXObject("Msxml2.XMLHTTP");
	    isIE = true;
	} catch (e) { 
	    try { 
	        objHTTP = new ActiveXObject("Microsoft.XMLHTTP"); 
		    isIE = true;
	    } catch (E) { 
	        objHTTP = false; 
	    } 
	} 

	if  (!objHTTP && typeof  XMLHttpRequest != 'undefined' ) { 
	    try  { 
	        objHTTP = new  XMLHttpRequest(); 
		    isIE = false;
	    } catch  (e) { 
	        objHTTP = false ; 
	    } 
	} 

	try {
		if (isIE){
			objHTTP.Open('POST', action, false);
			objHTTP.Send(parametros);
		}else{
			objHTTP.open('POST', action, false);
			objHTTP.send(parametros);
		}

		var retorno = new String(objHTTP.responseText);

//document.write(retorno);
//return;		
		if(retorno.indexOf("Sucesso") > 0 || retorno == "Sucesso" || retorno == "SucessoSucesso"){
			return true;
		}else{
			return false;
		}
	} catch (e) {
		return false;
	}
}

function executaAjax2(parametros, action){

	try { 
	    objHTTP = new ActiveXObject("Msxml2.XMLHTTP");
	    isIE = true;
	} catch (e) { 
	    try { 
	        objHTTP = new ActiveXObject("Microsoft.XMLHTTP"); 
		    isIE = true;
	    } catch (E) { 
	        objHTTP = false; 
	    } 
	} 

	if  (!objHTTP && typeof  XMLHttpRequest != 'undefined' ) { 
	    try  { 
	        objHTTP = new  XMLHttpRequest(); 
		    isIE = false;
	    } catch  (e) { 
	        objHTTP = false ; 
	    } 
	} 

	try {
		if (isIE){
			objHTTP.Open('POST', action, false);
			objHTTP.Send(parametros);
		}else{
			objHTTP.open('POST', action, false);
			objHTTP.send(parametros);
		}

		var retorno = new String(objHTTP.responseText);
//document.write(retorno);
//return;		
		return retorno;

	} catch (e) {
		return e.description;
	}
}

function htmlEncode(s){
	var elm = document.createElement("div");
	elm.innerText = elm.textContent = s;
	s = elm.innerHTML;
	delete elm;
	return s.replace(/\<BR\>/g, "<BR/>");
}

function keepSessionAlive(pagina){
	var retorno = executaAjax2("", pagina);
}