// 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.


// 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 );
}



// 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, 10);
    var intMonth = parseInt(month, 10);
    var intDay = parseInt(day, 10);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}




/* FUNCTIONS TO NOTIFY USER OF INPUT REQUIREMENTS OR MISTAKES. */


// Display prompt string s in status bar.

function prompt (s)
{   window.status = s
}



// Display data entry prompt string s in status bar.

function promptEntry (s)
{   window.status = pEntryPrompt + s
}




// Notify user that required field theField is empty.
// String s describes expected contents of theField.value.
// Put focus in theField and return false.

function warnEmpty (theField, s)
{   
    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 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 fnPermitirNumeros()
{
	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 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;
}

function Select(pCampo){
    pCampo.focus();
    pCampo.select();
} 
function CheckRadio(pForm,pNome){
	var i
	
	for(i=0;i<pForm.length;i++){
		var e = pForm.elements[i]
		
		if (e.name == pNome){
			if (e.checked == true){
				return true;
				break;
			}
		}		
	}
	return false;
}
function CheckTextBox(pForm,pNomeText){
	var e = pForm.elements[pNomeText];
	
	if (e.value == '' || e.value == null){
		Select(e);		
		return false;
	}
	return true;
}
function CheckSelect(pForm,pNomeSelect,pValorInvalido){
	var e = pForm.elements[pNomeSelect];
	
	if (e.options[e.selectedIndex].value == '' || e.options[e.selectedIndex].value == pValorInvalido){
		return false;
	}
	return true;
}
function RetornaRadioChecked(pForm,pNomeRadio){
	var i;
	var e = pForm.elements[pNomeRadio];
	
	for(i=0;i<e.length;i++){		
		if (e[i].checked == true){
			return e[i].value;
			break;
		}
	}
	return '';
}
function isEmail(string) {
    if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
        return true;
    else
        return false;
}


//-->
