// inc_validar.js
//
// SUMMARY
//
// This is a set of JavaScript functions for validating input on 
// an HTML form.  Functions are provided to validate:
//      - email addresses
//	- dates (entry of year, month, and day and validity of combined date)
//
// Supporting utility functions validate that:
//
//      - characters are Letter, Digit, or LetterOrDigit
//      - strings are a Signed, Positive, Negative, Nonpositive, or
//        Nonnegative integer
//      - strings are a Float or a SignedFloat
//      - strings are Alphabetic, Alphanumeric, or Whitespace
//      - strings contain an integer within a specified range
//
// Functions are also provided to interactively check the
// above kinds of data and prompt the user if they have
// been entered incorrectly.
//
// Other utility functions are provided to:
//
// 	- remove from a string characters which are/are not 
//	  in a "bag" of selected characters	
// 	- reformat a string, adding delimiter characters
//	- strip whitespace/leading whitespace from a string
//
// 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.
// 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.
// CPFValido(s)						   Retorna true se o CPF for válido. 

// 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.                                       

// 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.
// fn_proxima(obj)                     Seta o Focus do navegador no proximo campo quando o valor for igual ao maxlrngth


// FUNCTIONS TO INTERACTIVELY CHECK FIELD CONTENTS:
//
// checkString (theField, s [,eok])    Check that theField.value is not empty or all whitespace.
// checkEmail (theField [,eok])        Check that theField.value is a valid Email.
// checkYear (theField [,eok])         Check that theField.value is a valid Year.
// checkMonth (theField [,eok])        Check that theField.value is a valid Month.
// checkDay (theField [,eok])          Check that theField.value is a valid Day.
// checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
//                                     Check that field values form a valid date.
// getRadioButtonValue (radio)         Get checked value from radio button.



// VARIABLE DECLARATIONS

var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"

var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"


// whitespace characters
var whitespace = " \t\n\r";


// decimal point character differs by language and culture
var decimalPointDelimiter = ","


// CONSTANT STRING DECLARATIONS
// (grouped for ease of translation and localization)

// m is an abbreviation for "missing"

var mPrefix = "Voce nao entrou com o valor no campo "
var mSuffix = ". Este é um campo obrigatorio. Favor entrar com o valor do campo agora."

// s is an abbreviation for "string"

var sUSLastName = "Last Name"
var sUSFirstName = "First Name"
var sWorldLastName = "Family Name"
var sWorldFirstName = "Given Name"
var sTitle = "Cargo"
var sCompanyName = "Empresa"
var sUSAddress = "Rua"
var sWorldAddress = "Endereco"
var sCity = "Cidade"
var sCountry = "Pais"
var sWorldPostalCode = "Codigo Postal"
var sFax = "Fax"
var sDateOfBirth = "Data de Nascimento"
var sEmail = "E-mail"
var sOtherInfo = "Outras Informacoes"




// i is an abbreviation for "invalid"

var iEmail = "Este campo deve conter um E-mail válido."
var iDay = "Este campo deve conter um dia entre 1 e 31."
var iMonth = "Este campo deve conter um mês 1 e 12."
var iYear = "Este campo deve conter um ano com 2 ou 4 digitos."
var iDatePrefix = "O Dia, Mês e Ano para "
var iDateSuffix = " não compõem uma data vália."



// p is an abbreviation for "prompt"

var pEntryPrompt = "Por favor, forneça "
var pEmail = "um e-mail válido."
var pDay = "um dia entre 1 e 31."
var pMonth = "um mês entre 1 e 12"
var pYear = "um ano com 2 ou 4 dígitos."


// 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;


// Check whether string s is empty.

function isEmpty(s)
{   if ((s == null) || (s.length == 0))
	{
		return true;
	}
	else
	{
	    for (var i = 0 ; i < s.length ; i++) 
	    {
	        if (s.charAt(i) != ' ') 
		    {
			    return false;
			}
		}
    }
    return true;
}


// Returns true if string s is empty or 
// whitespace characters only.

function isWhitespace (s)

{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}



// Removes all characters which appear in string bag from string s.

function stripCharsInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}



// Removes all characters which do NOT appear in string bag 
// from string s.

function stripCharsNotInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}



// Removes all whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripWhitespace (s)

{   return stripCharsInBag (s, whitespace)
}




// WORKAROUND FUNCTION FOR NAVIGATOR 2.0.2 COMPATIBILITY.
//
// The below function *should* be unnecessary.  In general,
// avoid using it.  Use the standard method indexOf instead.
//
// However, because of an apparent bug in indexOf on 
// Navigator 2.0.2, the below loop does not work as the
// body of stripInitialWhitespace:
//
// while ((i < s.length) && (whitespace.indexOf(s.charAt(i)) != -1))
//   i++;
//
// ... so we provide this workaround function charInString
// instead.
//
// charInString (CHARACTER c, STRING s)
//
// Returns true if single character c (actually a string)
// is contained within string s.

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}



// Removes initial (leading) whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripInitialWhitespace (s)

{   var i = 0;

    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    
    return s.substring (i, s.length);
}


// Returns true if character c is an English letter 
// (A .. Z, a..z).
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}



// Returns true if character c is a digit 
// (0 .. 9).

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}



// Returns true if character c is a letter or digit.

function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}



// isInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if all characters in string s are numbers.
//
// Accepts non-signed integers only. Does not accept floating 
// point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// By default, returns defaultEmptyOK if s is empty.
// There is an optional second argument called emptyOK.
// emptyOK is used to override for a single function call
//      the default behavior which is specified globally by
//      defaultEmptyOK.
// If emptyOK is false (or any value other than true), 
//      the function will return false if s is empty.
// If emptyOK is true, the function will return true if s is empty.
//
// EXAMPLE FUNCTION CALL:     RESULT:
// isInteger ("5")            true 
// isInteger ("")             defaultEmptyOK
// isInteger ("-5")           false
// isInteger ("", true)       true
// isInteger ("", false)      false
// isInteger ("5", false)     true

function isInteger (s)

{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}


// isSignedInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if all characters are numbers; 
// first character is allowed to be + or - as well.
//
// Does not accept floating point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// EXAMPLE FUNCTION CALL:          RESULT:
// isSignedInteger ("5")           true 
// isSignedInteger ("")            defaultEmptyOK
// isSignedInteger ("-5")          true
// isSignedInteger ("+5")          true
// isSignedInteger ("", false)     false
// isSignedInteger ("", true)      true

function isSignedInteger (s)

{   if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}




// isPositiveInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is an integer > 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isPositiveInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isPositiveInteger.arguments.length > 1)
        secondArg = isPositiveInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a positive, not negative, number

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s, 10) > 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, 10) >= 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, 10) < 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, 10) <= 0) ) );
}





// isFloat (STRING s [, BOOLEAN emptyOK])
// 
// True if string s is an unsigned floating point (real) number. 
//
// Also returns true for unsigned integers. If you wish
// to distinguish between integers and floating point numbers,
// first call isInteger, then call isFloat.
//
// Does not accept exponential notation.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isFloat (s)

{   var i;
    var seenDecimalPoint = false;

    if (isEmpty(s)) 
       if (isFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isFloat.arguments[1] == true);

    if (s == decimalPointDelimiter) return false;

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if ((c == decimalPointDelimiter) && !seenDecimalPoint) seenDecimalPoint = true;
        else if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}







// isSignedFloat (STRING s [, BOOLEAN emptyOK])
// 
// True if string s is a signed or unsigned floating point 
// (real) number. First character is allowed to be + or -.
//
// Also returns true for unsigned integers. If you wish
// to distinguish between integers and floating point numbers,
// first call isSignedInteger, then call isSignedFloat.
//
// Does not accept exponential notation.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isSignedFloat (s)

{   if (isEmpty(s)) 
       if (isSignedFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedFloat.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedFloat.arguments.length > 1)
            secondArg = isSignedFloat.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isFloat(s.substring(startPos, s.length), secondArg))
    }
}




// isAlphabetic (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isAlphabetic (s)

{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-alphabetic character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }

    // All characters are letters.
    return true;
}




// isAlphanumeric (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) and numbers only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isAlphanumeric (s)

{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-alphanumeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number or letter.
        var c = s.charAt(i);

        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    // All characters are numbers or letters.
    return true;
}




// reformat (TARGETSTRING, STRING, INTEGER, STRING, INTEGER ... )       
//
// Handy function for arbitrarily inserting formatting characters
// or delimiters of various kinds within TARGETSTRING.
//
// reformat takes one named argument, a string s, and any number
// of other arguments.  The other arguments must be integers or
// strings.  These other arguments specify how string s is to be
// reformatted and how and where other strings are to be inserted
// into it.
//
// reformat processes the other arguments in order one by one.
// * If the argument is an integer, reformat appends that number 
//   of sequential characters from s to the resultString.
// * If the argument is a string, reformat appends the string
//   to the resultString.
//
// NOTE: The first argument after TARGETSTRING must be a string.
// (It can be empty.)  The second argument must be an integer.
// Thereafter, integers and strings must alternate.  This is to
// provide backward compatibility to Navigator 2.0.2 JavaScript
// by avoiding use of the typeof operator.
//
// It is the caller's responsibility to make sure that we do not
// try to copy more characters from s than s.length.
//
//
// 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;
}


// isEmail (STRING s [, BOOLEAN emptyOK])
// 
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}





// isYear (STRING s [, BOOLEAN emptyOK])
// 
// isYear returns true if string s is a valid 
// Year number.  Must be 2 or 4 digits only.
// 
// For Year 2000 compliance, you are advised
// to use 4-digit year numbers everywhere.
//
// And yes, this function is not Year 10000 compliant, but 
// because I am giving you 8003 years of advance notice,
// I don't feel very guilty about this ...
//
// For B.C. compliance, write your own function. ;->
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isYear (s)
{   if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}



// isIntegerInRange (STRING s, INTEGER a, INTEGER b [, BOOLEAN emptyOK])
// 
// isIntegerInRange returns true if string s is an integer 
// within the range of integer arguments a and b, inclusive.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.


function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseInt (s,10);
    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 );
}


/* 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)
{   
    alert(mPrefix + s + mSuffix)
    theField.focus()
    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;
}


// 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;
}





// 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 }
    }
    if(i==radio.length)
		return null;
	else
		return radio[i].value;
}

//limita o numero de caracteres do textarea. usar no evento onkeydown
function tamMax(ObjText,MaxSize)
{	
	if (ObjText.value.length > MaxSize)
	{
		ObjText.value = ObjText.value.substring(0,MaxSize);
	}	
}

//******************************************************************
function fnumero(S){
//******************************************************************
//
// Deixa só os digitos no numero.
// colocar no campo input a seguinte linha :
//  ondown="document.form.campo.value = fnumero(form.campo.value)"
//
var Digitos = "0123456789";
var temp = "";
var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}
//******************************************************************
function fvalor(S){
//******************************************************************
//
// Deixa so' os digitos no numero
//
var Digitos = "0123456789.,";
var temp = "";
var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}
//******************************************************************
function fhora(S){
//******************************************************************
//
// Deixa so' os digitos no numero
//
var Digitos = "0123456789:";
var temp = "";
var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}
//******************************************************************
function fdata(S){
//******************************************************************
//
// Deixa so' os digitos no numero
//
var Digitos = "0123456789/";
var temp = "";
var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}
//******************************************************************
function fcep(S){
//******************************************************************
//
// Deixa so' os digitos no numero
//
var Digitos = "0123456789-";
var temp = "";
var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}

//******************************************************************
function inverte(S){
//******************************************************************
//
// Inverte o string S
//
var temp="";
    for (var i=0; i<S.length; i++){
        temp=S.charAt(i)+temp
    }
    return temp
}

//******************************************************************
function resto(S){
//******************************************************************
//
// Retorna o digito verificador (entrar com S "limpo")
//
var invertido = Inverte(Limpa(S));
var soma = 0;
    for (var i=0; i<invertido.length; i++){
        soma=soma+(i+2)*eval(invertido.charAt(i))
    }
    soma*=10;
    //document.form.CPF.value="";
    return ((soma % 11) % 10)
}

//******************************************************************
function confere(){
//******************************************************************
//
// Confere se o CPF dado esta' OK
//
var result = "";
var ok = false;
var temp = Limpa(document.form.cpf.value);
    if (temp.length>10){
       var work=temp.substring(0,(temp.length)-2)
       var resto = Resto(work);
       OK = (resto==eval(temp.charAt((temp.length)-2)));
       if (OK){
          work=work+resto;
          resto= Resto(work);
          OK = (resto==eval(temp.charAt((temp.length)-1)));
       }
    }
    if (OK){result="CPF válido"}else{result="CPF inválido"  && window.alert ("CPF inválido"); document.form.CPF.value="";}   
      
    //document.form.CPF.value =result;
    //window.alert (result);
}

//******************************************************************
function FU_Modulo11 ( Arg_Val , Arg_Fator , Arg_Resto0 ) 
//******************************************************************
{
   var VL_Total=0;
   var VL_Fator=0;
   var VL_Numero=0;
   var VL_Tamanho=0;
   var VL_Resto=0;
   var VL_Digito=0;
   
   VL_Fator = 2;
   VL_Total = 0;
   for ( VL_Tamanho = Arg_Val.length; VL_Tamanho > 0; VL_Tamanho-- )
   {
      VL_Numero = Arg_Val.substring ( VL_Tamanho , VL_Tamanho - 1 );
      VL_Numero *= VL_Fator;
      VL_Total += VL_Numero;
      if ( VL_Fator == Arg_Fator )
         VL_Fator = 2;
      else
         ++VL_Fator;
   }
   VL_Resto = VL_Total % 11;
   if ( VL_Resto == 0 )
      VL_Digito = Arg_Resto0;
   else
      {
       if ( VL_Resto == 1 )
          VL_Digito = 0;
       else
          VL_Digito = 11 - VL_Resto;
       }
   return VL_Digito;  
}

//******************************************************************
function FU_CGC(Arg_Cgc)
//******************************************************************
{
    var VL_Digit1 ;
    var VL_Digit2 ;
	var X=0;
    if (Arg_Cgc.length == 14)
    {

       VL_Digit1 = " ";
       VL_Digit2 = " ";
       VL_Digit1 = FU_Modulo11(Arg_Cgc.substring ( 12 , 0 ), 9, 0);
       VL_Digit2 = FU_Modulo11(Arg_Cgc.substring ( 13 , 0 ), 9, 0);
       if ( VL_Digit1 == Arg_Cgc.substring ( 13 , 12 ) ) 
         if ( VL_Digit2 == Arg_Cgc.substring ( 14 , 13 ) )
          {
              // alert ("OK" , "CNPJ" ) ; // ( true ) ;
              return;
          }
     }
     alert ( "O número do CNPJ informado é inválido !"  , "CNPJ" ) ;
	 
     return (X) ; // ( false );
}
//******************************************************************
function FU_CGC2(Arg_Cgc)
//******************************************************************
{
    var VL_Digit1 ;
    var VL_Digit2 ;
	var X=0;
    if (Arg_Cgc.length == 14)
    {

       VL_Digit1 = " ";
       VL_Digit2 = " ";
       VL_Digit1 = FU_Modulo11(Arg_Cgc.substring ( 12 , 0 ), 9, 0);
       VL_Digit2 = FU_Modulo11(Arg_Cgc.substring ( 13 , 0 ), 9, 0);
       if ( VL_Digit1 == Arg_Cgc.substring ( 13 , 12 ) ) 
         if ( VL_Digit2 == Arg_Cgc.substring ( 14 , 13 ) )
          {
              // alert ("OK" , "CNPJ" ) ; // ( true ) ;
              return;
          }
     }
     return (X) ; // ( false );
}
//
//******************************************************************
function testaemail(campo)
//******************************************************************
	{
	if (campo!="" && campo.indexOf("@")==-1)
		{
		alert("O e-mail informado não é válido !"); 
		}
	}
//******************************************************************
function virgula(campo,antes1,antes2,depois1,depois2)
//******************************************************************
	{
	// virgula(xmen,"O campo ","Os campos "," é de preenchimento obrigatório."," são de preenchimento obrigatório.")
	var xmen=""
	xmen = campo.substring(2,campo.length);
	if(xmen.indexOf(",") == -1)
		{
		window.alert (antes1 + xmen + depois1);
		}
	else
		{
		window.alert (antes2 + xmen + depois2);
		}
	}	
//*************************************************************
function imprimir()
//*************************************************************
	{
	var da = (document.all) ? 1 : 0;
	var pr = (window.print) ? 1 : 0;
	var mac = (navigator.userAgent.indexOf("Mac") != -1); 
	if (pr) // NS4, IE5
		window.print()
	else if (da && !mac) // IE4 (Windows)
		vbPrintPage()
	else // other browsers
		return false;
	if (da && !pr && !mac) with (document)
		{
		writeln('<OBJECT ID="WB" WIDTH="0" HEIGHT="0" CLASSID="clsid:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>');
		writeln('<' + 'SCRIPT LANGUAGE="VBScript">');
		writeln('Sub window_onunload');
		writeln('  On Error Resume Next');
		writeln('  Set WB = nothing');
		writeln('End Sub');
		writeln('Sub vbPrintPage');
		writeln('  OLECMDID_PRINT = 6');
		writeln('  OLECMDEXECOPT_DONTPROMPTUSER = 2');
		writeln('  OLECMDEXECOPT_PROMPTUSER = 1');
		writeln('  On Error Resume Next');
		writeln('  WB.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER');
		writeln('End Sub');
		writeln('<' + '/SCRIPT>');
		}
	}
//*************************************************************
// passar uma string no formato aaaa/mm/dd
function transforma(chave,ordem)
//*************************************************************
	{
	var ydata,xdia,xmes,xano;
	ydata= new Date(chave);
	if(ydata.getDate()< 10)
		{
		xdia="0"+ydata.getDate();
		}
	else
		{
		xdia=ydata.getDate();
		}
	if(ydata.getMonth()+1< 10)
		{
		xmes="0"+(ydata.getMonth()+1);
		}
	else
		{
		xmes=(ydata.getMonth()+1);
		}
	xano=ydata.getYear();
	if(ordem == 1)  // mostra dd/mm/aaaa
		{
		ydata = xdia+"/"+xmes+"/"+xano;
		}
	else			// mostra aaaa/mm/dd
		{
		ydata = xano+"/"+xmes+"/"+xdia;
		}
	return ydata;

	}
//*************************************************************
function valida(chave,mensagem)
//*************************************************************
	{
	xdia=chave.substring(0,02);
	xmes=chave.substring(3,05);
	xano=chave.substring(6,10);
	var xerro="N";
	if(xmes == "04" || xmes == "06" || xmes == "09" || xmes == "11")
		{
		if(xdia > 30) 
			xerro="S";
		}
	else
		{
		if(xmes == "02") 
			{
			if(xano%4 == 0)
				{
				if(xdia > 29)
					xerro="S";
				}
			else
				{
				if(xdia > 28)
					xerro="S";
				}
			}			
		}
	if(xerro=="S")
		{
		alert(mensagem);
		return 0;
		}
	else
		{
		return 1
		}
	}
//*************************************************************
function tremer(n)
//*************************************************************
	{
	if (self.moveBy)
		{
		for (i = 10; i > 0; i--)
			{
			for (j = n; j > 0; j--)
				{
				self.moveBy( 0, i);
				self.moveBy( i, 0);
				self.moveBy( 0,-i);
				self.moveBy(-i, 0);
				}   
			}
		}
	}
//*************************************************************

//funcao q só permite a entrada de caracteres para preencher um campo para data, formato (dd/mm/yyyy)
//OBS: o size do campo deve ser igual ao maxlength

function fnVerCharData(objeto)
{	
	tam=objeto.size;
	s=objeto.value;
	
	// pega a posição atual do caracter dentro do array 
	for ( vlcont = 0 ; vlcont <= tam ; vlcont++ ) 
	{
		if (s.charAt(vlcont) == "") 
		{
			var vlPosAtual = vlcont-1;
			break;  
		}
	}
	
		
	var vlChar = s.charAt(vlPosAtual);						// pega caracter digitado
	var vaAux1 = ( ((vlChar >= "0") && (vlChar <= "9")) &&
			(! ((vlPosAtual ==2 || vlPosAtual == 5) && 
				(vlChar >= "0" && vlChar <= "9")) ) ) ||
			( ((vlPosAtual ==2 || vlPosAtual == 5) && (vlChar == "/")) );    // define range de valores permitidos
	
	
	// se não estiver dentro do range de valores permitidos
	if( ! vaAux1 ) 
	{	
			
		var vlNewChar = "";	
		
		// guarda os valores validos que foram digitados
		for ( vlcont = 0 ; vlcont <= vlPosAtual ; vlcont++ ) 
		{
																						
				if ( vlcont != vlPosAtual ) 
				{
					vlNewChar = vlNewChar + s.charAt(vlcont);
				}
		}
		
		
			
		// atualiza o controle no formulário
		objeto.value=vlNewChar;
		return false;		
	
	}			
	return true; 
}


//funcao que só permite a digitacao de números em campo text de uma form
//OBS: o size do campo input deve ser igual ao maxlength suportado

function fnVerChar(objeto) 
{
	tam=objeto.size;
	s=objeto.value;
	
	// pega a posição atual do caracter dentro do array 
	for ( vlcont = 0 ; vlcont <= tam ; vlcont++ ) 
	{
		if (s.charAt(vlcont) == "") 
		{
			var vlPosAtual = vlcont-1;
			break;  
		}
	}

	var vlChar = s.charAt(vlPosAtual);						// pega caracter digitado
	var vaAux1 = ( (vlChar >= 0) && (vlChar <= 9) ) // define range de valores permitidos

	// se não estiver dentro do range de valores permitidos
	if( ! vaAux1 ) 
	{	
		var vlNewChar = "";	
		// guarda os valores validos que foram digitados
		for ( vlcont = 0 ; vlcont <= vlPosAtual ; vlcont++ ) 
		{																		
			if ( vlcont != vlPosAtual ) 
			{
				vlNewChar = vlNewChar + s.charAt(vlcont);
			}
		}
		// atualiza o controle no formulário
		objeto.value=vlNewChar;
		return false;		
	}			
	return true; 
}



function fnTempoServicoChar(objeto) 
{
	tam=objeto.size;
	s=objeto.value;
	
	// pega a posição atual do caracter dentro do array 
	for ( vlcont = 0 ; vlcont <= tam ; vlcont++ ) 
	{
		if (s.charAt(vlcont) == "") 
		{
			var vlPosAtual = vlcont-1;
			break;  
		}
	}
		
	var vlChar = s.charAt(vlPosAtual);						// pega caracter digitado
	var vaAux1 = ( ( (vlChar >= 0) && (vlChar <= 9) && (vlPosAtual != 2) ) || 
				( (vlPosAtual==2) && (vlChar==',') ) )// define range de valores permitidos
	
	// se não estiver dentro do range de valores permitidos
	if( ! vaAux1 ) 
	{		
		var vlNewChar = "";	
		
		// guarda os valores validos que foram digitados
		for ( vlcont = 0 ; vlcont <= vlPosAtual ; vlcont++ ) 
		{																			
			if ( vlcont != vlPosAtual ) 
			{
				vlNewChar = vlNewChar + s.charAt(vlcont);
			}
		}
		
		// atualiza o controle no formulário
		objeto.value=vlNewChar;
		return false;		
	}			
	return true; 
}


//validação e comparação de datas tipo dd/mm/yyyy OBS: cada data é digitada em somente um campo
function fnValida_Data_2(data_inicio,data_fim)
{

	var combinacao;
	
	if (data_inicio!="")
	{
		if (data_inicio.length==10)
		{   //extrai o dia, mes e ano da data início
			dia_ini=data_inicio.substring(0,2);
			mes_ini=data_inicio.substring(3,5);
			ano_ini=data_inicio.substring(6);
			
			combinacao=dia_mes_ano(dia_ini,mes_ini,ano_ini);
			if (! combinacao)
			{				
				return false;	
			}										
		}	
		else
			{
				return false;
			}
	}
	
	
	if (data_fim!="")
	{
		if (data_fim.length==10)
		{	//extrai o dia, mes e ano da data fim
			dia_fim=data_fim.substring(0,2);
			mes_fim=data_fim.substring(3,5);
			ano_fim=data_fim.substring(6);
		
			combinacao=dia_mes_ano(dia_fim,mes_fim,ano_fim);
			if (! combinacao) 
			{				
				return false;		
			}									
		}	
		else
			{
			
			return false;
			}
	}
	
	if ( (data_inicio!="") && (data_fim!="") )
	{
		
		if (ano_fim < ano_ini)			
			return false;
		else			
			if (ano_fim == ano_ini)
			{				
				if (mes_fim < mes_ini)
					return false;
				else
					if ( (mes_fim == mes_ini) && (dia_fim < dia_ini) )
						return false;
			}					
	}
	
	return true;	
}	

//função para verificar se a combinação de dia,mês e ano estão corretas
function dia_mes_ano(dia,mes,ano)
{
	if ( (dia.length!=2) || (mes.length!=2) || (ano.length!=4) )
		return false; 
	
	if (mes<=00 || mes > 12)
		return false;
	else		
		//janeiro,março, maio, julho, agosto,outubro, dezembro
		if ( (mes==01 || mes==03 || mes==05 || mes==07 || mes==08 || mes==10 || mes==12) && (dia<=00 || dia>31) )			  
				return false;		
		else//demais meses (excluindo-se fevereiro)
			if ( (mes==04 || mes==06 || mes==09 || mes==11) && (dia<=00 || dia>30) )					 
					return false;				
			else 
				if ( (mes==02) && (dia<=00 || dia>29) )//fevereiro							
					return false;
				else
					if ( (dia==29) && ((ano%4)!=0) ) //ano bissexto	
						return false;
					else							
						if ( (ano.substring(2)==00) && ((ano%400)!=0) )
							return false;
						else							 										
							return true;		
																										return true;									
}

//******************************************************************
function fnumero(S){
//******************************************************************
//
// Deixa só os digitos no numero.
// colocar no campo input a seguinte linha :
//  onkeydown="document.form.campo.value = fnumero(form.campo.value)"
//
var Digitos = "0123456789";
var temp = "";
var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}
//******************************************************************
function fvalor(S){
//******************************************************************
//
// Deixa so' os digitos no numero
//
var Digitos = "0123456789.,";
var temp = "";
var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}
//******************************************************************
function fhora(S){
//******************************************************************
//
// Deixa so' os digitos no numero
//
var Digitos = "0123456789:";
var temp = "";
var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}
//******************************************************************
function fdata(S){
//******************************************************************
//
// Deixa so' os digitos no numero
//
var Digitos = "0123456789/";
var temp = "";
var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}
//******************************************************************
function fcep(S){
//******************************************************************
//
// Deixa so' os digitos no numero
//
var Digitos = "0123456789-";
var temp = "";
var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}

//******************************************************************
function inverte(S){
//******************************************************************
//
// Inverte o string S
//
var temp="";
    for (var i=0; i<S.length; i++){
        temp=S.charAt(i)+temp
    }
    return temp
}

//******************************************************************
function resto(S){
//******************************************************************
//
// Retorna o digito verificador (entrar com S "limpo")
//
var invertido = Inverte(Limpa(S));
var soma = 0;
    for (var i=0; i<invertido.length; i++){
        soma=soma+(i+2)*eval(invertido.charAt(i))
    }
    soma*=10;
    //document.form.CPF.value="";
    return ((soma % 11) % 10)
}

//******************************************************************
function confere(){
//******************************************************************
//
// Confere se o CPF dado esta' OK
//
var result = "";
var ok = false;
var temp = Limpa(document.form.cpf.value);
    if (temp.length>10){
       var work=temp.substring(0,(temp.length)-2)
       var resto = Resto(work);
       OK = (resto==eval(temp.charAt((temp.length)-2)));
       if (OK){
          work=work+resto;
          resto= Resto(work);
          OK = (resto==eval(temp.charAt((temp.length)-1)));
       }
    }
    if (OK){result="CPF válido"}else{result="CPF inválido"  && window.alert ("CPF inválido"); document.form.CPF.value="";}   
      
    //document.form.CPF.value =result;
    //window.alert (result);
}

//******************************************************************
function FU_Modulo11 ( Arg_Val , Arg_Fator , Arg_Resto0 ) 
//******************************************************************
{
   var VL_Total=0;
   var VL_Fator=0;
   var VL_Numero=0;
   var VL_Tamanho=0;
   var VL_Resto=0;
   var VL_Digito=0;
   
   VL_Fator = 2;
   VL_Total = 0;
   for ( VL_Tamanho = Arg_Val.length; VL_Tamanho > 0; VL_Tamanho-- )
   {
      VL_Numero = Arg_Val.substring ( VL_Tamanho , VL_Tamanho - 1 );
      VL_Numero *= VL_Fator;
      VL_Total += VL_Numero;
      if ( VL_Fator == Arg_Fator )
         VL_Fator = 2;
      else
         ++VL_Fator;
   }
   VL_Resto = VL_Total % 11;
   if ( VL_Resto == 0 )
      VL_Digito = Arg_Resto0;
   else
      {
       if ( VL_Resto == 1 )
          VL_Digito = 0;
       else
          VL_Digito = 11 - VL_Resto;
       }
   return VL_Digito;  
}

//******************************************************************
function FU_CGC(Arg_Cgc)
//******************************************************************
{
    var VL_Digit1 ;
    var VL_Digit2 ;
	var X=0;
    if (Arg_Cgc.length == 14)
    {

       VL_Digit1 = " ";
       VL_Digit2 = " ";
       VL_Digit1 = FU_Modulo11(Arg_Cgc.substring ( 12 , 0 ), 9, 0);
       VL_Digit2 = FU_Modulo11(Arg_Cgc.substring ( 13 , 0 ), 9, 0);
       if ( VL_Digit1 == Arg_Cgc.substring ( 13 , 12 ) ) 
         if ( VL_Digit2 == Arg_Cgc.substring ( 14 , 13 ) )
          {
              // alert ("OK" , "CNPJ" ) ; // ( true ) ;
              return;
          }
     }
     alert ( "O número do CNPJ informado é inválido !"  , "CNPJ" ) ;
	 
     return (X) ; // ( false );
}
//
//******************************************************************
function testaemail(campo)
//******************************************************************
	{
	if (campo!="" && campo.indexOf("@")==-1)
		{
		alert("O e-mail informado não é válido !"); 
		}
	}
//******************************************************************
function virgula(campo,antes1,antes2,depois1,depois2)
//******************************************************************
	{
	// virgula(xmen,"O campo ","Os campos "," é de preenchimento obrigatório."," são de preenchimento obrigatório.")
	var xmen=""
	xmen = campo.substring(2,campo.length);
	if(xmen.indexOf(",") == -1)
		{
		window.alert (antes1 + xmen + depois1);
		}
	else
		{
		window.alert (antes2 + xmen + depois2);
		}
	}	
//*************************************************************
function imprimir()
//*************************************************************
	{
	var da = (document.all) ? 1 : 0;
	var pr = (window.print) ? 1 : 0;
	var mac = (navigator.userAgent.indexOf("Mac") != -1); 
	if (pr) // NS4, IE5
		window.print()
	else if (da && !mac) // IE4 (Windows)
		vbPrintPage()
	else // other browsers
		return false;
	if (da && !pr && !mac) with (document)
		{
		writeln('<OBJECT ID="WB" WIDTH="0" HEIGHT="0" CLASSID="clsid:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>');
		writeln('<' + 'SCRIPT LANGUAGE="VBScript">');
		writeln('Sub window_onunload');
		writeln('  On Error Resume Next');
		writeln('  Set WB = nothing');
		writeln('End Sub');
		writeln('Sub vbPrintPage');
		writeln('  OLECMDID_PRINT = 6');
		writeln('  OLECMDEXECOPT_DONTPROMPTUSER = 2');
		writeln('  OLECMDEXECOPT_PROMPTUSER = 1');
		writeln('  On Error Resume Next');
		writeln('  WB.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER');
		writeln('End Sub');
		writeln('<' + '/SCRIPT>');
		}
	}
//*************************************************************
// passar uma string no formato aaaa/mm/dd
function transforma(chave,ordem)
//*************************************************************
	{
	var ydata,xdia,xmes,xano;
	ydata= new Date(chave);
	if(ydata.getDate()< 10)
		{
		xdia="0"+ydata.getDate();
		}
	else
		{
		xdia=ydata.getDate();
		}
	if(ydata.getMonth()+1< 10)
		{
		xmes="0"+(ydata.getMonth()+1);
		}
	else
		{
		xmes=(ydata.getMonth()+1);
		}
	xano=ydata.getYear();
	if(ordem == 1)  // mostra dd/mm/aaaa
		{
		ydata = xdia+"/"+xmes+"/"+xano;
		}
	else			// mostra aaaa/mm/dd
		{
		ydata = xano+"/"+xmes+"/"+xdia;
		}
	return ydata;

	}
//*************************************************************
function valida(chave,mensagem)
//*************************************************************
	{
	xdia=chave.substring(0,02);
	xmes=chave.substring(3,05);
	xano=chave.substring(6,10);
	var xerro="N";
	if(xmes == "04" || xmes == "06" || xmes == "09" || xmes == "11")
		{
		if(xdia > 30) 
			xerro="S";
		}
	else
		{
		if(xmes == "02") 
			{
			if(xano%4 == 0)
				{
				if(xdia > 29)
					xerro="S";
				}
			else
				{
				if(xdia > 28)
					xerro="S";
				}
			}			
		}
	if(xerro=="S")
		{
		alert(mensagem);
		return 0;
		}
	else
		{
		return 1
		}
	}
//*************************************************************
function tremer(n)
//*************************************************************
	{
	if (self.moveBy)
		{
		for (i = 10; i > 0; i--)
			{
			for (j = n; j > 0; j--)
				{
				self.moveBy( 0, i);
				self.moveBy( i, 0);
				self.moveBy( 0,-i);
				self.moveBy(-i, 0);
				}   
			}
		}
	}
//*************************************************************

//funcao q só permite a entrada de caracteres para preencher um campo para data, formato (dd/mm/yyyy)
//OBS: o size do campo deve ser igual ao maxlength

function fnVerCharData(objeto)
{	
	tam=objeto.size;
	s=objeto.value;
	
	// pega a posição atual do caracter dentro do array 
	for ( vlcont = 0 ; vlcont <= tam ; vlcont++ ) 
	{
		if (s.charAt(vlcont) == "") 
		{
			var vlPosAtual = vlcont-1;
			break;  
		}
	}
	
		
	var vlChar = s.charAt(vlPosAtual);						// pega caracter digitado
	var vaAux1 = ( ((vlChar >= "0") && (vlChar <= "9")) &&
			(! ((vlPosAtual ==2 || vlPosAtual == 5) && 
				(vlChar >= "0" && vlChar <= "9")) ) ) ||
			( ((vlPosAtual ==2 || vlPosAtual == 5) && (vlChar == "/")) );    // define range de valores permitidos
	
	
	// se não estiver dentro do range de valores permitidos
	if( ! vaAux1 ) 
	{	
			
		var vlNewChar = "";	
		
		// guarda os valores validos que foram digitados
		for ( vlcont = 0 ; vlcont <= vlPosAtual ; vlcont++ ) 
		{
																						
				if ( vlcont != vlPosAtual ) 
				{
					vlNewChar = vlNewChar + s.charAt(vlcont);
				}
		}
		
		
			
		// atualiza o controle no formulário
		objeto.value=vlNewChar;
		return false;		
	
	}			
	return true; 
}


//funcao que só permite a digitacao de números em campo text de uma form
//OBS: o size do campo input deve ser igual ao maxlength suportado

function fnVerChar(objeto) 
{
	tam=objeto.size;
	s=objeto.value;
	
	// pega a posição atual do caracter dentro do array 
	for ( vlcont = 0 ; vlcont <= tam ; vlcont++ ) 
	{
		if (s.charAt(vlcont) == "") 
		{
			var vlPosAtual = vlcont-1;
			break;  
		}
	}

	var vlChar = s.charAt(vlPosAtual);						// pega caracter digitado
	var vaAux1 = ( (vlChar >= 0) && (vlChar <= 9) ) // define range de valores permitidos

	// se não estiver dentro do range de valores permitidos
	if( ! vaAux1 ) 
	{	
		var vlNewChar = "";	
		// guarda os valores validos que foram digitados
		for ( vlcont = 0 ; vlcont <= vlPosAtual ; vlcont++ ) 
		{																		
			if ( vlcont != vlPosAtual ) 
			{
				vlNewChar = vlNewChar + s.charAt(vlcont);
			}
		}
		// atualiza o controle no formulário
		objeto.value=vlNewChar;
		return false;		
	}			
	return true; 
}



function fnTempoServicoChar(objeto) 
{
	tam=objeto.size;
	s=objeto.value;
	
	// pega a posição atual do caracter dentro do array 
	for ( vlcont = 0 ; vlcont <= tam ; vlcont++ ) 
	{
		if (s.charAt(vlcont) == "") 
		{
			var vlPosAtual = vlcont-1;
			break;  
		}
	}
		
	var vlChar = s.charAt(vlPosAtual);						// pega caracter digitado
	var vaAux1 = ( ( (vlChar >= 0) && (vlChar <= 9) && (vlPosAtual != 2) ) || 
				( (vlPosAtual==2) && (vlChar==',') ) )// define range de valores permitidos
	
	// se não estiver dentro do range de valores permitidos
	if( ! vaAux1 ) 
	{		
		var vlNewChar = "";	
		
		// guarda os valores validos que foram digitados
		for ( vlcont = 0 ; vlcont <= vlPosAtual ; vlcont++ ) 
		{																			
			if ( vlcont != vlPosAtual ) 
			{
				vlNewChar = vlNewChar + s.charAt(vlcont);
			}
		}
		
		// atualiza o controle no formulário
		objeto.value=vlNewChar;
		return false;		
	}			
	return true; 
}


//validação e comparação de datas tipo dd/mm/yyyy OBS: cada data é digitada em somente um campo
function fnValida_Data_2(data_inicio,data_fim)
{

	var combinacao;
	
	if (data_inicio!="")
	{
		if (data_inicio.length==10)
		{   //extrai o dia, mes e ano da data início
			dia_ini=data_inicio.substring(0,2);
			mes_ini=data_inicio.substring(3,5);
			ano_ini=data_inicio.substring(6);
			
			combinacao=dia_mes_ano(dia_ini,mes_ini,ano_ini);
			if (! combinacao)
			{				
				return false;	
			}										
		}	
		else
			{
				return false;
			}
	}
	
	
	if (data_fim!="")
	{
		if (data_fim.length==10)
		{	//extrai o dia, mes e ano da data fim
			dia_fim=data_fim.substring(0,2);
			mes_fim=data_fim.substring(3,5);
			ano_fim=data_fim.substring(6);
		
			combinacao=dia_mes_ano(dia_fim,mes_fim,ano_fim);
			if (! combinacao) 
			{				
				return false;		
			}									
		}	
		else
			{
			
			return false;
			}
	}
	
	if ( (data_inicio!="") && (data_fim!="") )
	{
		
		if (ano_fim < ano_ini)			
			return false;
		else			
			if (ano_fim == ano_ini)
			{				
				if (mes_fim < mes_ini)
					return false;
				else
					if ( (mes_fim == mes_ini) && (dia_fim < dia_ini) )
						return false;
			}					
	}
	
	return true;	
}	

//função para verificar se a combinação de dia,mês e ano estão corretas
function dia_mes_ano(dia,mes,ano)
{
	if ( (dia.length!=2) || (mes.length!=2) || (ano.length!=4) )
		return false; 
	
	if (mes<=00 || mes > 12)
		return false;
	else		
		//janeiro,março, maio, julho, agosto,outubro, dezembro
		if ( (mes==01 || mes==03 || mes==05 || mes==07 || mes==08 || mes==10 || mes==12) && (dia<=00 || dia>31) )			  
				return false;		
		else//demais meses (excluindo-se fevereiro)
			if ( (mes==04 || mes==06 || mes==09 || mes==11) && (dia<=00 || dia>30) )					 
					return false;				
			else 
				if ( (mes==02) && (dia<=00 || dia>29) )//fevereiro							
					return false;
				else
					if ( (dia==29) && ((ano%4)!=0) ) //ano bissexto	
						return false;
					else							
						if ( (ano.substring(2)==00) && ((ano%400)!=0) )
							return false;
						else							 										
							return true;		
																										return true;									
}

function popup(strJanela, strTarget, numAltura, numLargura, ynScroll)
{

	xposition=0; yposition=0; 
    if ((parseInt(navigator.appVersion,10) >= 4 ))
    { 
        xposition = (screen.width - numLargura) / 2; 
        yposition = (screen.height - numAltura) / 2; 
    } 
    args = "width=" + numLargura + "," 
    + "height=" + numAltura + "," 
    + "location=0," 
    + "menubar=0," 
    + "resizable=0," 
    + "scrollbars="+ynScroll+"," 
    + "status=0," 
    + "titlebar=0," 
    + "toolbar=0," 
    + "hotkeys=0," 
    + "directories=0,"
    + "copyhistory=0,"
    + "screenx=" + xposition + ","  //NN Only 
    + "screeny=" + yposition + ","  //NN Only 
    + "left=" + xposition + ","     //IE Only 
    + "top=" + yposition;           //IE Only 
    strJanela = window.open( strJanela , strTarget , args ); 
}

function CPFValido(s)
{
	if (s.length < 11)
		return false;
	else
	{
		var varFirstChr = s.charAt(0);
		var vaCharCPF = false;
		for ( var i=0; i<=10; i++ ) 
		{ 
			var c = s.charAt(i);
            if( ! (c>="0")&&(c<="9") ) 
				return false;
            if( c!=varFirstChr ) 
				vaCharCPF = true; 
		} 

        if( ! vaCharCPF ) 
			return false;
        
		soma=0;
		for ( i=0; i<9; i++ ) 
		{ 
			soma += (10-i) * ( eval(s.charAt(i)) );	
		} 
		digito_verificador = 11-(soma % 11);
		if ( (soma % 11) < 2 )
			digito_verificador = 0;
		if ( eval(s.charAt(9)) != digito_verificador ) 
			return false;
		soma=0;
		for ( i=0; i<9; i++ ) 
		{
			soma += (11-i) * ( eval(s.charAt(i)) ); 
		}
		soma += 2 * ( eval(s.charAt(9)) );
		digito_verificador = 11-(soma % 11);
		if ( (soma % 11) < 2 )
			digito_verificador = 0;
		if ( eval(s.charAt(10)) != digito_verificador ) 
			return false; 
		return true;
	}
}

//Inibir a digitacao de apostrofes

function BloquearAspas()
{
	//ATENCAO: este codigo eh compativel apenas com o Internet Explorer
	var strNavegador=navigator.appName;
	if(strNavegador.indexOf('Microsoft') > -1)
	{
		if(event.keyCode==34) //se for ' ou "
		{
			event.returnValue = false;
		}
	}
	else
	{
		if(Event.keyCode==34) //se for ' ou "
		{
			Event.returnValue = false;
		}
	}
}

//Inibir a digitacao de apostrofes ou aspas e emitir alerta

function BloquearCaracteres()
{
	//ATENCAO: este codigo eh compativel apenas com o Internet Explorer
	var strNavegador=navigator.appName;
	if(strNavegador.indexOf('Microsoft') > -1)
	{
		if((event.keyCode==39)|(event.keyCode==34)) //se for ' ou "
		{
			event.returnValue = false;
			alert('Este campo não pode conter apóstrofes ou aspas');
		}
	}
	else
	{
		if((Event.keyCode==39)|(Event.keyCode==34)) //se for ' ou "
		{
			Event.returnValue = false;
			alert('Este campo não pode conter apostrofes ou aspas');
		}
	}
}

var teclas='|8|,|9|,|16|,|17|,|18|,|33|,|34|,|35|,|36|,|45|,|46|,|37|,|38|,|39|,|40|';

//limitar o preenchimento do texta	rea como um textbox
function fnMaxChar(objTextarea, numTamanho)
{
	//ATENCAO: este codigo eh compativel apenas com o Internet Explorer
	var strConteudo;
	strConteudo = objTextarea.value;
	//alert(event.keyCode);

	if (strConteudo.length >= numTamanho)
	{
		/*var Cod = '|' + event.keyCode + '|';
		if(teclas.indexOf(Cod)==-1)
		{*/
			event.returnValue = false;
		//}
	}
}

function numberOnly()
{
	if(!isNonnegativeInteger(String.fromCharCode(event.keyCode)))
		event.returnValue = false;
}

function dateOnly()
{
	if (event.keyCode==47)
		event.returnValue = true;
	else
	{
		if(!isNonnegativeInteger(String.fromCharCode(event.keyCode)))
			event.returnValue = false;
	}

}

function fnPermitirMoney()
{
	if (event.keyCode==44)
		event.returnValue = true;
	else
	{
		if((event.keyCode<48)||(event.keyCode>57))
		event.returnValue = false;
	}
}
//*************************************************************
function fnPermitirNumerosePonto()
//*************************************************************
{
	if(!(isNonnegativeInteger(String.fromCharCode(event.keyCode))||String.fromCharCode(event.keyCode)=="."))
		event.returnValue = false;
}
function fn_PermitirNumeros()
{
	if((event.keyCode<48)||(event.keyCode>57))
	{
		event.returnValue = false;
	}
}
//*************************************************************
function fnPermitirNumeroseVirgula()
//*************************************************************
{
	if(!(isNonnegativeInteger(String.fromCharCode(event.keyCode))||String.fromCharCode(event.keyCode)==","))
		event.returnValue = false;
}

//Função que verifica se existe valores repetidos na string
function fnRepetidos(strValor, intQuantidade)
{
	var blnRetorno=false;
	var i;
	var intIguais=1;
	var strCharAnt=strValor.charAt(0);
	for (i = 1; i < strValor.length ;i++)
	{
		if(intIguais==intQuantidade)
		{
			blnRetorno=true;
			break;			
		}
		else
		{
			if(strValor.charAt(i)==strCharAnt)
			{
				intIguais++;
			}
			else
			{
				intIguais=1;
				strCharAnt=strValor.charAt(i);
			}
		}		
	}
	return blnRetorno;
}

//Função que verifica se existe sequencia na string
function fnSequencia(strValor,intQuantidade)
{
	var blnRetorno=false;
	var i;
	var intIguais=1;
	var strCharAnt=strValor.charAt(0);
	for (i = 0; i < strValor.length ;i++)
	{
		if (((strValor.charAt(i).charCodeAt() == (strValor.charAt(i+(intQuantidade-2)).charCodeAt()-1)) && (strValor.charAt(i).charCodeAt() == (strValor.charAt(i+(intQuantidade-1)).charCodeAt()-2)))	|| ((strValor.charAt(i).charCodeAt() == (strValor.charAt(i+(intQuantidade-2)).charCodeAt()+1)) && (strValor.charAt(i).charCodeAt() == (strValor.charAt(i+(intQuantidade-1)).charCodeAt()+2))))
		{
			blnRetorno=true;
			break;			
		}
	}
	return blnRetorno;
}
//Função que verifica se existe numero na string
function fn_numeros(strValor)
{
	var blnRetorno=false;

	for (i = 0; i < strValor.length ;i++)
	{
		if ((strValor.charAt(i).charCodeAt() >= 48) && (strValor.charAt(i).charCodeAt() <=57))
		{
			blnRetorno=true;
			break;			
		}
	}
	return blnRetorno;
}
//Função que verifica se existe caracteres na string
function fn_caracteres(strValor)
{
	var blnRetorno=false;

	for (i = 0; i < strValor.length ;i++)
	{
		if ((strValor.charAt(i).charCodeAt() >= 65) && (strValor.charAt(i).charCodeAt() <=90))
		{
			blnRetorno=true;
			break;			
		}
	}
	return blnRetorno;
}
function fnPermitirFone()
{
	if ((event.keyCode==40) || (event.keyCode==41) || (event.keyCode==45) || (event.keyCode==32))
		event.returnValue = true;
	else
	{
		if((event.keyCode<48)||(event.keyCode>57))
		event.returnValue = false;
	}
}

function isFloatNumber (s)
 
{   var x;
    //var seenDecimalPoint = false;

    if (isEmpty(s)) 
       if (isFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isFloat.arguments[1] == true);

    //if (s == decimalPointDelimiter) return false;

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (x = 0; x < s.length; x++)
    {   
        // Check that current character is number.
        var c = s.charAt(x);

        if (c == decimalPointDelimiter || c == '.') seenDecimalPoint = true;
        else if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}

  function fn_proxima(obj){
    if ((obj.value.length) == obj.maxLength){
      var nome;
      for (i = (obj.sourceIndex+1); i<document.all.length; i++){
        nome = document.all(i).tagName;
        if (nome =='INPUT'){
          if (document.all(i).type.toUpperCase() != 'HIDDEN'){
            document.all(i).focus();
            return;
          }
        }
        if (nome =='A' || nome == 'SELECT' || nome == 'TEXTAREA'){
          document.all(i).focus();
          return;
        }
      }
    }
  }
  
function bloq(obj, max)
{   
	if(event.keyCode == 9 || event.keyCode == 20 || event.keyCode == 8 || event.keyCode == 35 || event.keyCode == 36 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40 || event.keyCode == 16 || event.keyCode == 17)
	{
		return true;
	}
					    							
	if(obj.value.length > max - 1)
	{
		obj.value = obj.value.substr(0, max);
		alert('Máximo permitido de caracteres: ' + max);
		event.returnValue = false;
	}
}  


function isDate(sDate)
{
	var bRet
	var i
	bRet = true

	if (sDate.length != 10)
	    bRet = false
	
	if (bRet)
	{
		i = 0
		while (i < sDate.length && bRet)
		{
			if (i == 2 || i == 5)
			{
				if (sDate.charAt(i) != "/")
					bRet = false
			}
			else
			{
				if (!isNumeric(sDate.charAt(i), 0))
					bRet = false
			}
			i++
		}
	}
	
	if (bRet)
	{
		iDia = parseInt(sDate.substring(0, 2), 10)
		iMes = parseInt(sDate.substring(3, 5), 10)
		iAno = parseInt(sDate.substring(6, 10), 10) 
		
		if (iMes < 1 || iMes > 12)
			bRet = false
		if (iAno < 1)
			bRet = false
	}
	if (bRet)
	{
		if (iMes == 1 || iMes == 3 || iMes == 5 || iMes == 7 || iMes == 8 || iMes == 10 || iMes == 12)
		{
			if (iDia < 1 || iDia > 31)
				bRet = false
		}
		if (iMes == 2)
		{
			if (isBissexto(iAno))
			{
				if (iDia < 1 || iDia > 29)
					bRet = false
			}
			else
			{
				if (iDia < 1 || iDia > 28)
					bRet = false
			}
		}
		if (iMes == 4 || iMes == 6 || iMes == 9 || iMes == 11)
		{
			if (iDia < 1 || iDia > 30)
				bRet = false
		}
	}

	return bRet
}

function dateRange(sData1, sData2)
{
	if ( (!isDate(sData1)) || (!isDate(sData2)) )
		return (-1);
	else if (sData1 == sData2)
		return (0);
	else
	{
		var lData1 = parseFloat(sData1.substring(6, 10) + sData1.substring(3, 5) + sData1.substring(0, 2))
		var lData2 = parseFloat(sData2.substring(6, 10) + sData2.substring(3, 5) + sData2.substring(0, 2))
		if (lData1>lData2)
			return(1);
		else
			return(2);
	}
}

function isBissexto(iAno)
{
	var bRet
	bRet = false
	if (iAno % 4 == 0 && (iAno % 100 !=0 || iAno % 400 ==0 ))
		bRet = true
	return bRet
}

function isNumeric(Valor)
{
   var i
   
   for (i = 0; i < Valor.length; i++)
   {
	  if (Valor.charAt(i) < "0" || Valor.charAt(i) > "9")
		return false;
   }
   
	return true;
}

function isLessNow(args){
	oDay = new String(parseInt(args.substring(0, 2), 10));
	oMon = new String(parseInt(args.substring(3, 5), 10));
	oYar = new String(parseInt(args.substring(6, 10), 10));
	
	oDay	= (oDay.length == 1)? ('0' + oDay) : oDay;
	oMon	= (oMon.length == 1)? ('0' + oMon) : oMon;				

	var _date = new Date();
	var _day	= new String((_date.getDate()  + 1));
	var _month	= new String((_date.getMonth() + 1));

	_day	= (_day.length == 1)?   ('0' + _day)   : _day;
	_month	= (_month.length == 1)? ('0' + _month) : _month;

	var _dateArg = oYar + oMon + oDay;
	var _dateNow = _date.getFullYear().toString() +  _month + _day;

	if(_dateArg < _dateNow)
		return true;
	else
		return false;
}

function fullDate(){
	if(!isNonnegativeInteger(String.fromCharCode(event.keyCode)) &&
		event.keyCode != 32 &&
		event.keyCode != 47 &&
		event.keyCode != 58){
		event.returnValue = false;
	}		
}

function IpAddressOnly()
{
	if(!isNonnegativeInteger(String.fromCharCode(event.keyCode)) && event.keyCode != 46)
		event.returnValue = false;
}

function ValidateIp(args)
{
	var _range = args.split('.');
	
	if(_range.length != 4){
		return false
	}
	
	for(var i = 0; i < 4; i++){
		if(_range[i] < 0 || _range[i] >= 255){
			return false;
		}
	}
	
	return true;
}

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//	Função:		WDinamicModal()
//	Autor:		Adriano Ferreira Souza Pinto
//	Data:		21/07/2003
//	
//	Resumo Descritivo:
//		Função para abrir uma janela modal permitindo definir se 
//		o listbox será múltipla escolha ou não.
//
//	Parâmetros de Entrada:
//		ID		: objeto	- A página que será aberta na janela de modal.
//		multiple: objeto	- Se o list será de multipla escolha ou não
//		
//	Parâmetros de Saída:
//		objeto array com as opções selecionadas no listbox da janela modal.
//
//	Alterado Por:		
//	Data da Alteração:
//	Resumo das Alterações:
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
function WDinamicModal(loader){
	//var arrArgs		= new Array();
	//arrArgs[0]		= '../css/pv_ambev_bohemia.css';
	//arrArgs[1]		= multiple;
	//arrArgs[2]		= document.location.pathname.substr(document.location.pathname.lastIndexOf('/') + 1);
	window.status	= "Aguarde..."
	var vRetorno	= window.showModalDialog(loader, null, "Dialogwidth:18;Dialogheight:10;Center:1;help:0;Status:0");
	window.status	= "";
	return vRetorno;
}

function fnPermitirLetrasNumeros()
{   
	if(event.keyCode == 192)
	{
		event.returnValue = false;
	}
}



//-->

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//-->

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
//MM_reloadPage(true);

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function politica()
{
	window.open('../htm/politica.htm','politica','scrollbars=yes,width=480,height=400,left=150,top=100');
}

function QueroIrPara(psDrpName)
{
	s = new String();

	s = document.all.item(psDrpName)[document.all.item(psDrpName).selectedIndex].value;
	intInit = 0;
	intFim =  s.indexOf(",");
	if (intFim > 0)
	{
		comando = s.substr(intInit,intFim);
		//alert(comando);
		intInit = ++intFim;
		intFim =  s.indexOf(",",intFim);
		if (intFim > 0)
		{
			area = s.substr(intInit,intFim - intInit);
			//alert(area);
			intInit = ++intFim;
			intFim =  s.indexOf(",",intFim);
			if (intFim > 0)
			{
				pagina = s.substr(intInit,intFim - intInit);
				//alert(pagina);
				intInit = ++intFim;
				intFim =  s.indexOf(";",intFim);
				if (intFim > 0)
				{
					params = s.substr(intInit,intFim - intInit);
										
					switch (comando)
					{
						case 'LoadMain':
							if (params != '')
								LoadMain(area,pagina,params);
							else
								LoadMain(area,pagina);
						break;
						case 'Redirect':
						{
							self.location = area + pagina + params;
						}
						break;
						case 'Splash':
							window.open(area + pagina + params);
						break;
					}				
				}
			}
		}
	}	
	return false;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function safra(theURL)
{
	window.open('../htm/safras/' + theURL,'safra','scrollbars=yes,width=300,height=250');
}

function mostratermo(valor){
	MM_openBrWindow('/UserControls/GoodControls/wuPopTermo.aspx?intCd_Termo=' + valor,'safra','scrollbars=yes,width=355,height=150')
}

function janela(pageURL, pageName, larg, altu, top, left, status, location, scrollbars, toolbar, menubar, resizable) {
	pageURLSrc = pageURL;
	pageNameSrc = pageName;
	tamanhoSrc = "width=" + larg + ",height=" + altu + ",top=" + top + ",left=" + left + ",status=" + status + ",location=" + location + ",scrollbars=" + scrollbars + ",toolbar=" + toolbar + ",menubar=" + menubar +",resizable=" + resizable;
	window.open(pageURLSrc,pageNameSrc,tamanhoSrc)
}	

function comprar()
{
	window.open('../htm/pop_revista/index.htm','aviso_inscricao','status=no,width=420,height=201');
}


function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}


// funções coelho


function MM_preloadImagesCoelho() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImagesCoelho.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestoreCoelho() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObjCoelho(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObjCoelho(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImageCoelho() { //v3.0
  var i,j=0,x,a=MM_swapImageCoelho.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObjCoelho(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_reloadPageCoelho(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPageCoelho; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPageCoelho(true);

function MM_showHideLayersCoelho() { //v6.0
  var i,p,v,obj,args=MM_showHideLayersCoelho.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObjCoelho(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}


function MM_timelineGotoCoelho(tmLnName, fNew, numGotos) { //v2.0
  //Copyright 1997, 2000 Macromedia, Inc. All rights reserved.
  var i,j,tmLn,props,keyFrm,sprite,numKeyFr,firstKeyFr,lastKeyFr,propNum,theObj;
  if (document.MM_Time == null) MM_initTimelinesCoelho(); //if *very* 1st time
  tmLn = document.MM_Time[tmLnName];
  if (numGotos != null)
    if (tmLn.gotoCount == null) tmLn.gotoCount = 1;
    else if (tmLn.gotoCount++ >= numGotos) {tmLn.gotoCount=0; return}
  jmpFwd = (fNew > tmLn.curFrame);
  for (i = 0; i < tmLn.length; i++) {
    sprite = (jmpFwd)? tmLn[i] : tmLn[(tmLn.length-1)-i]; //count bkwds if jumping back
    if (sprite.charAt(0) == "s") {
      numKeyFr = sprite.keyFrames.length;
      firstKeyFr = sprite.keyFrames[0];
      lastKeyFr = sprite.keyFrames[numKeyFr - 1];
      if ((jmpFwd && fNew<firstKeyFr) || (!jmpFwd && lastKeyFr<fNew)) continue; //skip if untouchd
      for (keyFrm=1; keyFrm<numKeyFr && fNew>=sprite.keyFrames[keyFrm]; keyFrm++);
      for (j=0; j<sprite.values.length; j++) {
        props = sprite.values[j];
        if (numKeyFr == props.length) propNum = keyFrm-1 //keyframes only
        else propNum = Math.min(Math.max(0,fNew-firstKeyFr),props.length-1); //or keep in legal range
        if (sprite.obj != null) {
          if (props.prop2 == null) sprite.obj[props.prop] = props[propNum];
          else        sprite.obj[props.prop2][props.prop] = props[propNum];
      } }
    } else if (sprite.charAt(0)=='b' && fNew == sprite.frame) eval(sprite.value);
  }
  tmLn.curFrame = fNew;
  if (tmLn.ID == 0) eval('MM_timelinePlayCoelho(tmLnName)');
}



function MM_timelinePlayCoelho(tmLnName, myID) { //v1.2
 
  //Copyright 1997, 2000 Macromedia, Inc. All rights reserved.
  var i,j,tmLn,props,keyFrm,sprite,numKeyFr,firstKeyFr,propNum,theObj,firstTime=false;
  if (document.MM_Time == null) MM_initTimelinesCoelho(); //if *very* 1st time
  tmLn = document.MM_Time[tmLnName];
  if (myID == null) { myID = ++tmLn.ID; firstTime=true;}//if new call, incr ID
  if (myID == tmLn.ID) { //if Im newest
    setTimeout('MM_timelinePlayCoelho("'+tmLnName+'",'+myID+')',tmLn.delay);
    fNew = ++tmLn.curFrame;
    for (i=0; i<tmLn.length; i++) {
      sprite = tmLn[i];
      if (sprite.charAt(0) == 's') {
        if (sprite.obj) {
          numKeyFr = sprite.keyFrames.length; firstKeyFr = sprite.keyFrames[0];
          if (fNew >= firstKeyFr && fNew <= sprite.keyFrames[numKeyFr-1]) {//in range
            keyFrm=1;
            for (j=0; j<sprite.values.length; j++) {
              props = sprite.values[j]; 
              if (numKeyFr != props.length) {
                if (props.prop2 == null) sprite.obj[props.prop] = props[fNew-firstKeyFr];
                else        sprite.obj[props.prop2][props.prop] = props[fNew-firstKeyFr];
              } else {
                while (keyFrm<numKeyFr && fNew>=sprite.keyFrames[keyFrm]) keyFrm++;
                if (firstTime || fNew==sprite.keyFrames[keyFrm-1]) {
                  if (props.prop2 == null) sprite.obj[props.prop] = props[keyFrm-1];
                  else        sprite.obj[props.prop2][props.prop] = props[keyFrm-1];
        } } } } }
      } else if (sprite.charAt(0)=='b' && fNew == sprite.frame) eval(sprite.value);
      if (fNew > tmLn.lastFrame) tmLn.ID = 0;
  } }
}


function MM_initTimelinesCoelho() { //v4.0
    //MM_initTimelines() Copyright 1997 Macromedia, Inc. All rights reserved.
    var ns = navigator.appName == "Netscape";
    var ns4 = (ns && parseInt(navigator.appVersion) == 4);
    var ns5 = (ns && parseInt(navigator.appVersion) > 4);
    document.MM_Time = new Array(1);
    document.MM_Time[0] = new Array(6);
    document.MM_Time["pascoa"] = document.MM_Time[0];
    document.MM_Time[0].MM_Name = "pascoa";
    document.MM_Time[0].fps = 15;
    document.MM_Time[0][0] = new String("behavior");
    document.MM_Time[0][0].frame = 1;
    document.MM_Time[0][0].value = "MM_showHideLayersCoelho('patas','','show')";
    document.MM_Time[0][1] = new String("behavior");
    document.MM_Time[0][1].frame = 30;
    document.MM_Time[0][1].value = "MM_showHideLayersCoelho('patas','','hide','coelhorelha','','show')";
    document.MM_Time[0][2] = new String("behavior");
    document.MM_Time[0][2].frame = 115;
    document.MM_Time[0][2].value = "MM_showHideLayersCoelho('patas','','hide','coelhorelha','','hide','coelhoapresenta','','show')";
    document.MM_Time[0][3] = new String("behavior");
    document.MM_Time[0][3].frame = 175;
    document.MM_Time[0][3].value = "MM_showHideLayersCoelho('patas','','hide','coelhorelha','','hide','coelhoapresenta','','hide')";
    document.MM_Time[0][4] = new String("behavior");
    document.MM_Time[0][4].frame = 185;
    document.MM_Time[0][4].value = "MM_timelineGotoCoelho('pascoa','1')";
    document.MM_Time[0][5] = new String("behavior");
    document.MM_Time[0][5].frame = 120;
    document.MM_Time[0][5].value = "MM_swapImageCoelho('apresenta','','../images/pascoa/teaser_coelho_mensagem1.gif',1)";
    document.MM_Time[0].lastFrame = 185;
    for (i=0; i<document.MM_Time.length; i++) {
        document.MM_Time[i].ID = null;
        document.MM_Time[i].curFrame = 0;
        document.MM_Time[i].delay = 1000/document.MM_Time[i].fps;
    }
}



