function Voltar() {
history.go(-1);
}

/*** 
* Descrição.: formata um campo do formulário de 
* acordo com a máscara informada... 
* Parâmetros: - objForm (o Objeto Form) 
* - strField (string contendo o nome 
* do textbox) 
* - sMask (mascara que define o 
* formato que o dado será apresentado, 
* usando o algarismo "9" para 
* definir números e o símbolo "!" para 
* qualquer caracter... 
* - evtKeyPress (evento) 
* Uso.......: <input type="textbox" 
* name="xxx"..... 
* onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);"> 
* Observação: As máscaras podem ser representadas como os exemplos abaixo: 
* CEP -> 99999-999 
* CPF -> 999.999.999-99 
* CNPJ -> 99.999.999/9999-99 
* Data -> 99/99/9999 
* Tel Resid -> (99) 9999-9999 
* Tel Cel -> (99) 9999-9999 
* Processo -> 99.999999999/999-99 
* C/C -> 999999-! 
* E por aí vai... 
***/

function txtBoxFormat(strField, sMask, evtKeyPress) {
     var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;
    
     nTecla = evtKeyPress.keyCode;
    
     sValue = strField.value;
	
     // Limpa todos os caracteres de formatação que
     // já estiverem no campo.
     sValue = sValue.toString().replace( "-", "" );
     sValue = sValue.toString().replace( "-", "" );
     sValue = sValue.toString().replace( ".", "" );
     sValue = sValue.toString().replace( ".", "" );
     sValue = sValue.toString().replace( "/", "" );
     sValue = sValue.toString().replace( "/", "" );
     sValue = sValue.toString().replace( "(", "" );
     sValue = sValue.toString().replace( "(", "" );
     sValue = sValue.toString().replace( ")", "" );
     sValue = sValue.toString().replace( ")", "" );
     sValue = sValue.toString().replace( " ", "" );
     sValue = sValue.toString().replace( " ", "" );
	 sValue = sValue.toString().replace( ",", "" );
	 sValue = sValue.toString().replace( ",", "" );
     fldLen = sValue.length;
     mskLen = sMask.length;

     i = 0;
     nCount = 0;
     sCod = "";
     mskLen = fldLen;

     while (i <= mskLen) {
       bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ","))
       bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

       if (bolMask) {
         sCod += sMask.charAt(i);
         mskLen++; }
       else {
         sCod += sValue.charAt(nCount);
         nCount++;
       }

       i++;
     }

     strField.value = sCod;

     if (nTecla != 8) { // backspace
       if (sMask.charAt(i-1) == "9") { // apenas números...
         return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
       else { // qualquer caracter...
         return true;
       } }
     else {
       return true;
     }
   }
   
/*
** Variáveis globais
*/
var gfShowAlert = true;


function OnlyNumber(Objeto, Event) {
	var strkeycode;
	var str;
	var fldLen;
	
	str = Objeto.value;
    fldLen = str.length;
    
	if (window.event) {
		strkeycode = window.event.keyCode;
		
	}
	else if (Event) {
		strkeycode = Event.which;
	}	
	else 
	{
		return true;
	}
	
	if (((strkeycode>47) && (strkeycode<58) ) || (strkeycode==44) || (strkeycode==8)) { 
		return true; 
	} else 	{
		window.event.keyCode=0
	}
}

function OnlyDecimal(Objeto, Event) {
	var strkeycode;
	
	if (window.event) {
		strkeycode = window.event.keyCode;
		
	}
	else if (Event) {
		strkeycode = Event.which;
	}	
	else 
	{
		return true;
	}
	
	if (((strkeycode>47) && (strkeycode<58) ) || (strkeycode==44) || (strkeycode==8)) { 
		return true; 
	} else 	{
  	  window.event.keyCode=0;
	}
}

function ToFloat(Value) {
	return parseFloat(Value.replace(",", "."));
}

/*
 * NumberFormat 1.5.0
 * v1.5.0 - 20-December-2002
 * v1.0.3 - 23-March-2002
 * v1.0.2 - 13-March-2002
 * v1.0.1 - 20-July-2001
 * v1.0.0 - 13-April-2000
 * http://www.mredkj.com
 *
 */

/*
 * NumberFormat -The constructor
 * num - The number to be formatted.
 *  Also refer to setNumber
 */
function NumberFormat(num)
{
	// constants
	this.COMMA = '.';
	this.PERIOD = ',';
	this.DASH = '-'; // v1.5.0 - new - used internally
	this.LEFT_PAREN = '('; // v1.5.0 - new - used internally
	this.RIGHT_PAREN = ')'; // v1.5.0 - new - used internally
	this.LEFT_OUTSIDE = 0; // v1.5.0 - new - currency
	this.LEFT_INSIDE = 1;  // v1.5.0 - new - currency
	this.RIGHT_INSIDE = 2;  // v1.5.0 - new - currency
	this.RIGHT_OUTSIDE = 3;  // v1.5.0 - new - currency
	this.LEFT_DASH = 0; // v1.5.0 - new - negative
	this.RIGHT_DASH = 1; // v1.5.0 - new - negative
	this.PARENTHESIS = 2; // v1.5.0 - new - negative

	// member variables
	this.num;
	this.numOriginal;
	this.hasSeparators = false;  // v1.5.0 - new
	this.separatorValue;  // v1.5.0 - new
	this.inputDecimalValue; // v1.5.0 - new
	this.decimalValue;  // v1.5.0 - new
	this.negativeFormat; // v1.5.0 - new
	this.negativeRed; // v1.5.0 - new
	this.hasCurrency;  // v1.5.0 - modified
	this.currencyPosition;  // v1.5.0 - new
	this.currencyValue;  // v1.5.0 - modified
	this.places;

	// external methods
	this.setNumber = setNumberNF;
	this.toUnformatted = toUnformattedNF;
	this.setInputDecimal = setInputDecimalNF; // v1.5.0 - new
	this.setSeparators = setSeparatorsNF; // v1.5.0 - new - for separators and decimals
	this.setCommas = setCommasNF;
	this.setNegativeFormat = setNegativeFormatNF; // v1.5.0 - new
	this.setNegativeRed = setNegativeRedNF; // v1.5.0 - new
	this.setCurrency = setCurrencyNF;
	this.setCurrencyPrefix = setCurrencyPrefixNF;
	this.setCurrencyValue = setCurrencyValueNF; // v1.5.0 - new - setCurrencyPrefix uses this
	this.setCurrencyPosition = setCurrencyPositionNF; // v1.5.0 - new - setCurrencyPrefix uses this
	this.setPlaces = setPlacesNF;
	this.toFormatted = toFormattedNF;
	this.toPercentage = toPercentageNF;
	this.getOriginal = getOriginalNF;

	// internal methods
	this.getRounded = getRoundedNF;
	this.preserveZeros = preserveZerosNF;
	this.justNumber = justNumberNF;

	// setup defaults
	this.setInputDecimal(this.PERIOD); // v1.5.0 - new
	this.setNumber(num); // make sure setInputDecimal is called before setNumber
	this.setCommas(true);
	this.setNegativeFormat(this.LEFT_DASH); // v1.5.0 - new
	this.setNegativeRed(false); // v1.5.0 - new
	this.setCurrency(true);
	this.setCurrencyPrefix('$');
	this.setPlaces(2);
}

/*
 * setInputDecimal
 * val - The decimal value for the input.
 *
 * v1.5.0 - new
 */
function setInputDecimalNF(val)
{
	this.inputDecimalValue = val;
}

/*
 * setNumber - Sets the number
 * num - The number to be formatted
 * 
 * If there is a non-period decimal format for the input,
 * setInputDecimal should be called before calling setNumber.
 *
 * v1.5.0 - modified
 */
function setNumberNF(num)
{
	this.numOriginal = num;
	this.num = this.justNumber(num);
}

/*
 * toUnformatted - Returns the number as just a number.
 * If the original value was '100,000', then this method will return the number 100000
 * v1.0.2 - Modified comments, because this method no longer returns the original value.
 */
function toUnformattedNF()
{
	return (this.num);
}

/*
 * getOriginal - Returns the number as it was passed in, which may include non-number characters.
 * This function is new in v1.0.2
 */
function getOriginalNF()
{
	return (this.numOriginal);
}

/*
 * setNegativeFormat - How to format a negative number.
 * 
 * format - The format. Use one of the following constants.
 * LEFT_DASH   example: -1000
 * RIGHT_DASH  example: 1000-
 * PARENTHESIS example: (1000)
 *
 * v1.5.0 - new
 */
function setNegativeFormatNF(format)
{
	this.negativeFormat = format;
}

/*
 * setNegativeRed - Format the number red if it's negative.
 * 
 * isRed - true, to format the number red if negative, black if positive;
 *  false, for it to always be black font.
 *
 * v1.5.0 - new
 */
function setNegativeRedNF(isRed)
{
	this.negativeRed = isRed;
}

/*
 * setSeparators - One purpose of this method is to set a
 *  switch that indicates if there should be separators between groups of numbers.
 *  Also, can use it to set the values for the separator and decimal.
 *  For example, in the value 1,000.00
 *   The comma (,) is the separator and the period (.) is the decimal.
 *
 * Both separator or decimal are not required.
 * The separator and decimal cannot be the same value. If they are, decimal with be changed.
 * Can use the following constants (via the instantiated object) for separator or decimal:
 *  COMMA
 *  PERIOD
 * 
 * isC - true, if there should be separators; false, if there should be no separators
 * separator - the value of the separator.
 * decimal - the value of the decimal.
 *
 * v1.5.0 - new
 */
function setSeparatorsNF(isC, separator, decimal)
{
	this.hasSeparators = isC;
	
	// Make sure a separator was passed in
	if (separator == null) separator = this.COMMA;
	
	// Make sure a decimal was passed in
	if (decimal == null) decimal = this.PERIOD;
	
	// Additionally, make sure the values aren't the same.
	//  When the separator and decimal both are periods, make the decimal a comma.
	//  When the separator and decimal both are any other value, make the decimal a period.
	if (separator == decimal)
	{
		this.decimalValue = (decimal == this.PERIOD) ? this.COMMA : this.PERIOD;
	}
	else
	{
		this.decimalValue = decimal;
	}
	
	// Since the decimal value changes if decimal and separator are the same,
	// the separator value can keep its setting.
	this.separatorValue = separator;

}

/*
 * setCommas - Sets a switch that indicates if there should be commas.
 * The separator value is set to a comma and the decimal value is set to a period.
 * isC - true, if the number should be formatted with separators (commas); false, if no separators
 *
 * v1.5.0 - modified
 */
function setCommasNF(isC)
{
	this.setSeparators(isC, this.COMMA, this.PERIOD);
}

/*
 * setCurrency - Sets a switch that indicates if should be displayed as currency
 * isC - true, if should be currency; false, if not currency
 */
function setCurrencyNF(isC)
{
	this.hasCurrency = isC;
}

/*
 * setCurrencyPrefix - Sets the symbol for currency.
 * val - The symbol
 */
function setCurrencyValueNF(val)
{
	this.currencyValue = val;
}

/*
 * setCurrencyPrefix - Sets the symbol for currency.
 * The symbol will show up on the left of the numbers and outside a negative sign.
 * cp - The symbol
 *
 * v1.5.0 - modified - This now calls setCurrencyValue and setCurrencyPosition(this.LEFT_OUTSIDE)
 */
function setCurrencyPrefixNF(cp)
{
	this.setCurrencyValue(cp);
	this.setCurrencyPosition(this.LEFT_OUTSIDE);
}

/*
 * setCurrencyPosition - Sets the position for currency,
 *  which includes position relative to the numbers and negative sign.
 * cp - The position. Use one of the following constants.
 *  This method does not automatically put the negative sign at the left or right.
 *  They are left by default, and would need to be set right with setNegativeFormat.
 *	LEFT_OUTSIDE  example: $-1.00
 *	LEFT_INSIDE   example: -$1.00
 *	RIGHT_INSIDE  example: 1.00$-
 *	RIGHT_OUTSIDE example: 1.00-$
 *
 * v1.5.0 - new
 */
function setCurrencyPositionNF(cp)
{
	this.currencyPosition = cp
}

/*
 * setPlaces - Sets the precision of decimal places
 * p - The number of places. Any number of places less than or equal to zero is considered zero.
 */
function setPlacesNF(p)
{
	this.places = p;
}

/*
 * toFormatted - Returns the number formatted according to the settings (a string)
 *
 * v1.5.0 - modified
 */
function toFormattedNF()
{
	var pos;
	var nNum = this.num; // v1.0.1 - number as a number
	var nStr;            // v1.0.1 - number as a string
	var splitString = new Array(2);   // v1.5.0

	// round decimal places
	nNum = this.getRounded(nNum);
	nStr = this.preserveZeros(Math.abs(nNum)); // this step makes nNum into a string. v1.0.1 Math.abs

	// the separator and decimal values have to be different
	// this is enforced in justNumber
	if (nStr.indexOf(this.COMMA) == -1)
	{
		splitString[0] = nStr;
		splitString[1] = '';
	}
	else
	{
		splitString = nStr.split(this.COMMA, 2);
	}
	

	// separators
	if (this.hasSeparators)
	{
		pos = splitString[0].length;
		while (pos > 0)
		{
			pos -= 3;
			if (pos <= 0) break;

			splitString[0] = splitString[0].substring(0,pos)
				+ this.separatorValue
				+ splitString[0].substring(pos, splitString[0].length);
		}
	}
	
	// decimal
	if (splitString[1].length > 0)
	{
		nStr = splitString[0] + this.decimalValue + splitString[1];
	}
	else
	{
		nStr = splitString[0];
	}
	
	// negative and currency
	// $[c0] -[n0] $[c1] -[n1] #.#[nStr] -[n2] $[c2] -[n3] $[c3]
	var c0 = '';
	var n0 = '';
	var c1 = '';
	var n1 = '';
	var n2 = '';
	var c2 = '';
	var n3 = '';
	var c3 = '';
	var negSignL = (this.negativeFormat == this.PARENTHESIS) ? this.LEFT_PAREN : this.DASH;
	var negSignR = (this.negativeFormat == this.PARENTHESIS) ? this.RIGHT_PAREN : this.DASH;
		
	if (this.currencyPosition == this.LEFT_OUTSIDE)
	{
		// add currency sign in front, outside of any negative. example: $-1.00	
		if (nNum < 0)
		{
			if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n1 = negSignL;
			if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n2 = negSignR;
		}
		if (this.hasCurrency) c0 = this.currencyValue;
	}
	else if (this.currencyPosition == this.LEFT_INSIDE)
	{
		// add currency sign in front, inside of any negative. example: -$1.00
		if (nNum < 0)
		{
			if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n0 = negSignL;
			if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n3 = negSignR;
		}
		if (this.hasCurrency) c1 = this.currencyValue;
	}
	else if (this.currencyPosition == this.RIGHT_INSIDE)
	{
		// add currency sign at the end, inside of any negative. example: 1.00$-
		if (nNum < 0)
		{
			if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n0 = negSignL;
			if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n3 = negSignR;
		}
		if (this.hasCurrency) c2 = this.currencyValue;
	}
	else if (this.currencyPosition == this.RIGHT_OUTSIDE)
	{
		// add currency sign at the end, outside of any negative. example: 1.00-$
		if (nNum < 0)
		{
			if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n1 = negSignL;
			if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n2 = negSignR;
		}
		if (this.hasCurrency) c3 = this.currencyValue;
	}

	//nStr = c0 + n0 + c1 + n1 + nStr + n2 + c2 + n3 + c3;
	nStr = n0 + c1 + n1 + nStr + n2 + c2 + n3 + c3;
	
	// negative red
	if (this.negativeRed && nNum < 0)
	{
		nStr = '<font color="red">' + nStr + '</font>';
	}

	return (nStr);
}

/*
 * toPercentage - Format the current number as a percentage.
 * This is separate from most of the regular formatting settings.
 * The exception is the number of decimal places.
 * If a number is 0.123 it will be formatted as 12.3%
 *
 * !! This is an initial version, so it doesn't use many settings.
 * !! should use some of the formatting settings that toFormatted uses.
 * !! probably won't want to use settings like currency.
 *
 * v1.5.0 - new
 */
function toPercentageNF()
{
	nNum = this.num * 100;
	
	// round decimal places
	nNum = this.getRounded(nNum);
	
	return nNum + '%';
}

/*
 * getRounded - Used internally to round a value
 * val - The number to be rounded
 */
function getRoundedNF(val)
{
	var factor;
	var i;

	// round to a certain precision
	factor = 1;
	for (i=0; i<this.places; i++)
	{	factor *= 10; }
	val *= factor;
	val = Math.round(val);
	val /= factor;

	return (val);
}

/*
 * preserveZeros - Used internally to make the number a string
 * 	that preserves zeros at the end of the number
 * val - The number
 */
function preserveZerosNF(val)
{
	var i;

	// make a string - to preserve the zeros at the end
	val = val + '';
	if (this.places <= 0) return val; // leave now. no zeros are necessary - v1.0.1 less than or equal
	
	var decimalPos = val.indexOf('.');
	if (decimalPos == -1)
	{
		val += '.';
		for (i=0; i<this.places; i++)
		{
			val += '0';
		}
	}
	else
	{
		var actualDecimals = (val.length - 1) - decimalPos;
		var difference = this.places - actualDecimals;
		for (i=0; i<difference; i++)
		{
			val += '0';
		}
	}
	
	return val;
}

/*
 * justNumber - Used internally to parse the value into a floating point number.
 * If the value is not set, then return 0.
 * If the value is not a number, then replace all characters that are not 0-9, a decimal point, or a negative sign.
 *
 *  Note: The regular expression cleans up the number, but doesn't get rid of - and .
 *  parseFloat will ignore all values after any character that is NaN.
 *
 *  A number can be entered using special notation.
 *  For example, the following is a valid number: 0.0314E+2
 *
 * This function is new in v1.0.2
 * v1.5.0 - modified
 */
function justNumberNF(val)
{

	val = (val==null) ? 0 : val;
	
	var newVal = val + ""; // to string for first round of parsing

	var isPercentage = false;
	var isFormattedNeg = false;

	// check for percentage
	// v1.5.0
	if (newVal.indexOf('%') != -1)
	{
		newVal = newVal.replace(/\%/g, '');
		
		// mark a flag
		isPercentage = true;
	}
	
	// check for negative
	// This logic does not figure out the real values for double negatives and other oddities.
	// If the value has any dash or both parenthesis, then it is counted as negative.
	// v1.5.0
	if (newVal.indexOf(this.DASH) != -1
	 || (newVal.indexOf(this.LEFT_PAREN) != -1 && newVal.indexOf(this.RIGHT_PAREN) != -1))
	{
		// get rid of the symbols
		// just hardcoding the regular expression to replace all dashes and parenthesis.
		// it's too much unnecessary work to use the constants in this situation.
		newVal = newVal.replace(/[\-\(\)]/g, '');
		
		// mark a flag to add back a negative sign later
		isFormattedNeg = true;
	}

	if (this.inputDecimalValue != this.PERIOD)
	{
		// then the separator might be a period
		// get rid of all periods, so they won't be evaluated as a decimal later
		newVal = newVal.replace(/\./g, '');
	}
	
	// replace the first decimal with a period and the rest with blank
	var itrDecimal;
	var tempVal = '';
	var foundDecimal = false;
	for (itrDecimal=0; itrDecimal<newVal.length; itrDecimal++)
	{
		if (newVal.charAt(itrDecimal) == this.inputDecimalValue)
		{
			if (foundDecimal)
			{
				// ignore the rest of the decimals
			}
			else
			{
				tempVal = tempVal + this.PERIOD;
				foundDecimal = true;
			}
		}
		else
		{
			tempVal = tempVal + newVal.charAt(itrDecimal);
		}
	}

  newVal = tempVal;
	
	// now that special input formatting is complete, add negative if applicable
	// v1.5.0
	if (isFormattedNeg) newVal = '-' + newVal;

	while (newVal.indexOf(this.COMMA)>=0)	{
		newVal = newVal.replace(this.COMMA, '');
	}
	newVal = newVal.replace(this.PERIOD, this.COMMA);


	// check if a number, otherwise try to figure out what number it is
	if (isNaN(newVal))
	{
		// try taking out non-number characters.
		newVal = parseFloat(newVal.replace(/[^\d\.\-]/g, ''));

		// check if still not a number. Might be undefined, '', etc., so just replace with 0.
		// v1.0.3
		newVal = (isNaN(newVal) ? 0 : newVal); 
	}
	// return 0 in place of infinite numbers.
	// v1.0.3
	else if (!isFinite(newVal))
	{
		newVal = 0;
  }
  
  // now that it's a number, adjust for percentage, if applicable.
  // example. if the number was formatted 24%, then divide by 100 to get 0.24
  // v1.5.0
  if (isPercentage)
  {
  	newVal = newVal / 100;
  }
	
	return newVal;
}

function FormatDecimal(Objeto) {

	var dblNumber = new NumberFormat(Objeto.value);
	dblNumber.setCommas(false);
	dblNumber.setSeparators(true);
	dblNumber.setPlaces(2);
	Objeto.value = dblNumber.toFormatted();
}

function IsDate(Data)
{
    var dma = -1;
    var data = Array(3);
    var ch = Data.charAt(0); 

    for (i=0; i < Data.length && (((ch >= '0') && (ch <= '9')) || ((ch == '/') && (i != 0 )));)
    {
         data[++dma] = '';
         if (ch!='/' && i != 0) return false;
         if (i != 0 ) ch = Data.charAt(++i);
         if (ch=='0') ch = Data.charAt(++i);

         while ((ch >= '0') && (ch <= '9'))
		{
			data[dma] += ch;
            ch = Data.charAt(++i);
        } 
    }

    if (ch != '') return false;

    if(data[0] == '' || isNaN(data[0]) || parseInt(data[0]) < 1) return false;
    if(data[1] == '' || isNaN(data[1]) || parseInt(data[1]) < 1 || parseInt(data[1]) > 12) return false;
    if(data[2] == '' || isNaN(data[2]) || ((parseInt(data[2]) < 0 || parseInt(data[2]) > 99 ) && (parseInt(data[2]) < 1900 || parseInt(data[2]) > 9999))) return false;
    if(data[2] < 50) data[2] = parseInt(data[2]) + 2000;
    else if(data[2] < 100) data[2] = parseInt(data[2]) + 1900;
                                   
    switch (parseInt(data[1]))
    {
		case 2: {
				if (((parseInt(data[2])%4!=0 || (parseInt(data[2])%100==0 && parseInt(data[2])%400!=0)) && parseInt(data[0]) > 28) || parseInt(data[0]) > 29 ) 
				return false;
				break;
		        }

		case 4: case 6: case 9: case 11: { 
				if(parseInt(data[0]) > 30) return false; break;
				}

		default: { 
				 if(parseInt(data[0]) > 31) return false;}
				 }
    return true;
}

function ValidaRG(rg) {
	if (Trim(rg) != "") {
		var c = rg.substr(0,1);
		var i;
		var nIguais = true;
				
		for (i=1; i<rg.length; i++) {
			if (c != rg.charAt(i)) {nIguais = false};
		}

		if (nIguais == true) {
			alert("RG Inválido");
			return false;
		}
	}
}

function ValidaCPF(cpf){		
	var i;
	var s = "";
	var nIguais = true;
				
	s = RetiraFormatacao(cpf);
	
	if (Trim(s) != "") {
		var c = s.substr(0,9); 
		var n = s.substr(0,1);
		
		for (i=1; i<9; i++) {
			if (n != c.charAt(i)) {nIguais = false};
		}
	
		if (nIguais == true) {
			alert("CPF Inválido");
			return false;
		}
	
		
		var dv = s.substr(9,2);
		var d1 = 0;
					
		for (i = 0; i<9; i++) {
			d1 += c.charAt(i)*(10-i);
		}
					
		if (d1 == 0){ 
			alert("CPF Inválido");
			return false;
		}
					
		d1 = 11 - (d1 % 11);
					
		if (d1>9) d1 = 0;
		if (dv.charAt(0) != d1) {
			alert("CPF Inválido");
			return false;
		}
					
		d1 *= 2;
		for (i = 0; i<9; i++) {
			d1 += c.charAt(i)*(11-i);
		}
		d1 = 11 - (d1 % 11);
					
		if (d1>9) d1 = 0;
		if (dv.charAt(1) != d1) {
			alert("CPF Inválido");
			return false;
		}
	}
					
	return true;
}

function FormataCPF(cpf) {
	var i;
	var strFormat = RetiraFormatacao(cpf);
	
	if (Trim(cpf) != "") {				
		strFormat = "00000000000" + RetiraFormatacao(cpf);
		strFormat = strFormat.substr(strFormat.length-11, 11);
					
		strFormat = strFormat.substr(0, 3) + "." + 
								strFormat.substr(3, 3) + "." + 
								strFormat.substr(6, 3) + "-" + 
								strFormat.substr(9, 2);
	}
	
	return strFormat;
}

function RetiraFormatacao(Valor) {
	
	var strUnformat="";
	
	for (i=0; i<Valor.length; i++) {
		if (isNaN(Valor.charAt(i)) == false) {
			strUnformat = strUnformat + Valor.charAt(i);
		}
	}
	
	return strUnformat;
}

function RTrim(str) {
	var whitespace = new String(" \t\n\r");

	var s = new String(str);

	if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
	    // We have a string with trailing blank(s)...

	    var i = s.length - 1;       // Get length of string

	    // Iterate from the far right of string until we
	    // don't have any more whitespace...
	    while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
	        i--;


	    // Get the substring from the front of the string to
	    // where the last non-whitespace character is...
	    s = s.substring(0, i+1);
	}

	return s;
}

function LTrim(str) {
    var whitespace = new String(" \t\n\r");

    var s = new String(str);

    if (whitespace.indexOf(s.charAt(0)) != -1) {
        // We have a string with leading blank(s)...

        var j=0, i = s.length;

        // Iterate from the far left of string until we
        // don't have any more whitespace...
        while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
            j++;


        // Get the substring from the first non-whitespace
        // character to the end of the string...
        s = s.substring(j, i);
    }

    return s;
}

function Trim(str) {
	return RTrim(LTrim(str));
}

function AutoTab(field) {

    var i;
    var idx;
    var next;        
    var docele;
	var keyCode;
        
    idx = -1;        

	if (window.event) {
		keyCode = window.event.keyCode;
	}
	else if (event) {
		keyCode = event.which;
	}	

	if (keyCode != 9 && keyCode != 16) {

		for (i = 0; i < document.forms(0).length; i ++) {
		    if (document.forms(0).elements[i].name == field.name)
				idx = i;
		}                
		if (idx != -1) {
		    // Find the next 'field'
		    next = idx + 1;
		    if (next >= document.forms(0).length)
		        next = 0 

		    // Figure out the length of the given element.                        
		    docele = document.forms(0).elements[idx].value;
		    
		    if (docele.length == field.maxLength) {
				if (document.forms(0).elements[next]) {
					try {
						document.forms(0).elements[next].focus()
						}
					catch(er) 
						{
						}	
				}
		    }
		}        
	}
}

function DateDiff(Interval, Date1, Date2) {

	var Ano1 = Date1.getYear();
	var Mes1 = Date1.getMonth();
	var Ano2 = Date2.getYear();
	var Mes2 = Date2.getMonth();
	var DiffMeses;

	if (Ano1 == Ano2) {
			DiffMeses = (Mes2 - Mes1);
	} else {
			if (Ano2 > Ano1) {
					DiffMeses = (((12 * (Ano2 - Ano1)) - Mes1) + Mes2);
			}
	}
	
	var DiffAno = parseInt(DiffMeses / 12);
	
	switch (Interval) {
			case "M": {
					return DiffMeses;
			}
			case "Y": {
					return DiffAno;
			}
			default: {
					return 0;
			}
	}	
}

function Right(str, n)
/***
        IN: str - the string we are RIGHTing
            n - the number of characters we want to return

        RETVAL: n characters from the right side of the string
***/
{
        if (n <= 0)     // Invalid bound, return blank string
           return "";
        else if (n > String(str).length)   // Invalid bound, return
           return str;                     // entire string
        else { // Valid bound, return appropriate substring
           var iLen = String(str).length;
           return String(str).substring(iLen, iLen - n);
        }
}

function fgFormatarCpfCnpj(strCpfCnpj,intTipoPessoa)
{
	var strDigito
	var strNumero
	var strFilial
	
	if (parseFloat("0" + intTipoPessoa) == 1)
	{
		strDigito = strCpfCnpj.substring(parseFloat(strCpfCnpj.length-2),strCpfCnpj.length)
		strNumero = strCpfCnpj.substring(0,parseFloat(strCpfCnpj.length-2))

		if (strNumero != "" && strDigito != "")
		{
			strNumero = fgReplace(fgNumberFormat(strNumero),",","")
			return strNumero + "-" + strDigito
		}	
		else
			return 0	
	}
	else
	{
		strDigito = strCpfCnpj.substring(parseFloat(strCpfCnpj.length-2),strCpfCnpj.length)
		strFilial = strCpfCnpj.substring(parseFloat(strCpfCnpj.length-6),parseFloat(strCpfCnpj.length-2))
		strNumero = strCpfCnpj.substring(0,parseFloat(strCpfCnpj.length-6))
	
		if (strNumero != "" && strFilial != "" && strDigito != "")
		{
			strNumero = fgReplace(fgNumberFormat(strNumero),",","")
			return strNumero + "/" + strFilial + "-" + strDigito
		}	
		else
			return 0	
	}		
}

/*
'[================================================================================================
'[= Nome		: fgVerificaCpfCnpj
'[= Descrição	: valida um CPF ou CNPJ de um campo ou string.
'[= Entrada		: str  - String Contendo o CPF ou CNPJ
'[=				  tipo - Identificador do CPJ ou CNPJ
'[=							1 - CPF
'[=							2 - CNPJ
'[=							3 - Autodetect
'[= Saida		: true  - se o CPF ou CNPJ for válido
'[=				  false - caso contrário
'[= Exemplo		: if(fgVerificaCpfCnpj(text3, 3))
'[= OBS			: 
'[================================================================================================
*/
function fgVerificaCpfCnpj(str, tipo)
{

	if(str.value==""){
		return false
	}
	/*
	** Verifica se str é um Objeto
	*/
	var lbObject = (str == '[object]');

	/*
	** Valida CPF
	*/

	if (tipo == 1)
	{
		if (!fgCheckCPF(str))
		{
			if (lbObject)
			{
				if (gfShowAlert)
					alert("CPF: "+ str.value + "\n\rCPF Inválido. Favor digitá-lo corretamente.");
					str.focus();
			}
			return false; 
		}
		return true;
	}


	/*
	** Valida CNPJ
	*/
	else if (tipo == 2)
	{
		if (!fgCheckCGC(str))
		{
			if (lbObject) 
			{
				if (gfShowAlert)
					alert("CNPJ: "+ str.value + " Inválido. Favor digitá-lo corretamente.");
				str.focus();
			}
			return false; 
		}
		return true;
	}
	/*
	** Autodetect (Valida os Dois, se um retornar verdadeiro...)
	*/
	else if(tipo == 3)
	{
		if (!fgCheckCPF(str) && !fgCheckCGC(str))
		{
			if (lbObject) 
			{
				if (gfShowAlert)
					alert("CNPJ: "+ str.value + " Inválido. Favor digitá-lo corretamente.");
				str.focus();
			}
			return false; 
		}
		return true;
	}
}


/*
'[======================================================================================
'[= Nome		: fgNumberFormat
'[= Descrição	: Formata um número com o seguinte formato #.##0,00
'[= Entrada		: pdblNumber - Número a ser formatado
'[=				  plDecimals - Número de casas Decimais
'[=				  plIntegers - Número de casas Interiras
'[= Saida		: Número formatado
'[= Exemplo		: <INPUT id=text11 name=text11 onblur="this.value = fgNumberFormat(this.value, 2, 6);">
'[= OBS			: Para utilizar esta função é necessário a inclusão do po_genericoFuncoes.js
'[= Manutenção	: 29/11/2001 - Gustavo Dian Leão
'[=					Correção para números negativos
'[======================================================================================
*/
function fgNumberFormat(pdblNumber, plDecimals, plIntegers)
{
	/*
	** Se assegura que é um número
	*/
	var ldblNumber = fgExactVal(pdblNumber + fgIIf(plDecimals == 0, '.', ''));

	/*
	** Verifica se plDecimals é um número positivo
	*/
	plDecimals = Math.abs(plDecimals);

	
	/*
	** Obtém a parte Inteira e Decimal do número
	*/
	var lsInteger = Math.floor(ldblNumber).toString();
	var lsDecimal = ldblNumber.toString().slice(lsInteger.length + 1);
		lsDecimal = lsDecimal.toString();


	// Mensagem de Erro
	var	lsMsgErro = "";
	
	/*
	** Soluciona um pequeno bug com números negativos
	**
	** Explicação do Bug:
	**		A função Math.floor() retorna o menor número inteiro do parâmetro passado,
	**		ou seja, para 1.5 retorna 1.
	**
	**		O bug ocorre quando o núemro é negativo, então para -1.5 retorna -2, que é
	**		o menor número inteiro mais próximo de -1.5 (para quem não lembra -1.5 > -2)
	**
	**		Então as duas linhas abaixo consertam este pequeno desvio.
	*/
	if ((ldblNumber < 0) && (lsDecimal > 0))
		lsInteger = Math.floor(ldblNumber + 1).toString();
	
	/*
	** Quando o número é negativo, não deve contar o sinal como algarismo 
	*/
	var liSinal = 0;
	if (lsInteger.substr(0,1) == '-')
		liSinal = 1;
	/*
	**
	*/

	/*
	** Verifica o tamanho da parte inteira, se for passado o parâmetro
	*/
	if (plIntegers != null)
		if ((lsInteger.length - liSinal) > plIntegers)
		{
			if (plDecimals > 0)
				lsMsgErro = ' números inteiros e ' + plDecimals + ' números decimais.';
			else
				lsMsgErro = ' números inteiros.';

			lsMsgErro = 'Campo permite apenas '+ plIntegers + lsMsgErro;

			if (gfShowAlert)
				alert (lsMsgErro);
			
			return ('');
		}

	/*
	** Coloca as casas decimais do tamanho certo
	*/
	if (lsDecimal.length < plDecimals)
		for (var liPos = lsDecimal.length; liPos < plDecimals; liPos++)
			lsDecimal += '0';
	else
		lsDecimal = fgLeft(lsDecimal, plDecimals);

	/*
	** Varre a string da direita para a esquerda, colocando o ponto como separador de milhar
	*/
	var lsAux = '';
	var liCount = 0;
	for (var liPos = lsInteger.length - 1; liPos >= 0; liPos--)
	{
		if ((Math.floor((liCount) / 3) * 3 == liCount) && (liCount != 0) && (lsInteger.charAt(liPos) != '-'))
			lsAux = '.' + lsAux;
		
		lsAux = lsInteger.charAt(liPos) + lsAux;
		liCount++;
	}
	
	if (plDecimals == 0)
		return (lsAux)
	else
		return (lsAux + ',' + lsDecimal);
}

/*
'[======================================================================================
'[= Nome		: fgReplace
'[= Descrição	: Pesquisa a string psSearch dentro da string psText, trocando por psReplace
'[= Entrada		: psText    - String a ser pesquisada
'[=               psSearch  - String a ser localizada
'[=				  psReplace - String a ser colocada no lugar de psSearch
'[= Saida		: String com psSearch trocada por psReplace
'[= Exemplo		: text25.value	= fgReplace(text24.value, ":", "?");
'[= OBS			:	
'[======================================================================================
*/
function fgReplace(psText, psSearch, psReplace)
{
	var liLen   = psSearch.length;
	var liPos   = psText.indexOf(psSearch);
	var lsLeft  = '';
	var lsRight = '';
	        
	while (liPos > (-1))
	{
		lsLeft  = psText.substring(0, liPos);
		lsRight = psText.substring(liPos + liLen , psText.length);
		psText  = lsLeft + psReplace + lsRight;
		liPos   = psText.indexOf(psSearch);
	}
	        
	return (psText);
}

/*
'[======================================================================================
'[= Nome		: fgExactVal
'[= Descrição	: Retorna o valor numérico de uma String
'[= Entrada		: psNumber - String Numérica
'[= Saida		: Valor Numérico
'[= OBS			: Tanto a vírgula quanto o ponto serão tratados como separador decimal,
'[=				  Sendo considerado o ponto ou a vírgula mais a direita.
'[=				  Retorna 0 se o valor passado não for numérico.
'[=	Manutenção	: 21/12/2001 - Gustavo Dian Leão
'[=					Correção para quando era um número como: 999999999999999,99, a função
'[=					arrendondava para 999999999999999,98.
'[= Exemplo		: text2.value	= fgExactVal(text1.value);
'[= OBS			: Para utilizar esta função é necessário a inclusão do po_genericoFuncoes.js
'[======================================================================================
*/
function fgExactVal(psNumber)
{
	/*
	** Verifica se o valor passado é um número
	*/
	if (!fgIsNumber(psNumber))
		return (0);

	var strAux  = new String('');
	var strChar = '';
	
	/*
	** Fica apenas com os números e um ponto decimal
	*/
	for (intCount = (psNumber.length - 1); intCount >= 0; intCount--)
	{
		if ( (psNumber.charAt(intCount) >= '0') && (psNumber.charAt(intCount) <= '9') )
		{
			strChar = psNumber.charAt(intCount);
			strAux = strChar + strAux;
		}
		else if ( (psNumber.charAt(intCount) == '-') && ( strAux.indexOf('-') < 0 ) )
		{
			strChar = psNumber.charAt(intCount);
			strAux = strChar + strAux;
		}
		else if ( (psNumber.charAt(intCount) == '.') && ( strAux.indexOf('.') < 0 ) )
		{
			strChar = psNumber.charAt(intCount);
			strAux = strChar + strAux;
		}
		else if ( (psNumber.charAt(intCount) == ',') && ( strAux.indexOf(',') < 0 ) )
			if (strAux.indexOf('.') == (-1))
				strAux = '.' + strAux;
	}
	
	/*
	** Se não foi achado um ponto decimal, retorna o valor
	*/
	if (strAux.indexOf(".") < 0)
		return parseFloat(strAux);
	
	/*
	** Obtém a parte inteira e a parte decimal
	*/
	strInt = strAux.substr(0, strAux.indexOf("."));
	strDec = strAux.substr(strAux.indexOf(".") + 1, (strAux.length - (strAux.indexOf(".") + 1)));

	
	if (strInt == '-' || strInt == '')
		strInt = strInt + '0';
		
	if (strDec == '')
		strDec = '0';


	// Recupera caractere decimal de acordo com o configurado na máquina.
	intAux = (2012/100);
	strCaracterDec = intAux.toString().substr((intAux.toString().length-3), 1);
	if (strCaracterDec == '')
		strCaracterDec = '.';

	/*
	** Retorna o valor correto
	*/
	if (parseFloat(strInt) < 0)
		return (parseFloat(strInt) - parseFloat(strDec) / Math.pow(10, strDec.length));
	else
	{
		// 21/12
		if (parseInt(strDec, 10) == 0)
		{
			return (parseFloat(strInt));
		}
		else
		{
			return (parseFloat(strInt+strCaracterDec+strDec));
		}
	}
}

/*
'[================================================================================================
'[= Nome		: fgCheckCGC
'[= Descrição	: Efetua a validação de CGC
'[= Entrada		: CGC - CGC a ser validado
'[= Saida		: true  - se o CGC for válido
'[=				  false - caso contrário
'[= OBS			: Para utilizar esta função é necessário a inclusão do po_genericoFuncoes.js
'[================================================================================================
*/
function fgCheckCGC(psCNPJ) 
{
	var liPeso = 2;
	var liSoma = 0;
	var lsAux  = '';
	var liTemp = 0;
	var liDigito = 0;
	var lsCNPJ = '';
	
	/*
	** Verifica se recebeu um objeto
	*/
	if (psCNPJ == '[object]')
		lsCNPJ = psCNPJ.value
	else
		lsCNPJ = psCNPJ;
	
	var liPos  = 0;

	/*
	** Remove qualquer caracter que não seja número
	*/
	for (liPos = lsCNPJ.length - 1; liPos >= 0; liPos--)
		if (!isNaN(lsCNPJ.charAt(liPos)))
			lsAux = lsCNPJ.charAt(liPos) + lsAux;
			
	/*
	** Cálculo do 1º dígito
	*/
	for (liPos = lsAux.length - 3; liPos >= 0; liPos--)
	{
		liSoma += parseInt(lsCNPJ.charAt(liPos)) * liPeso;
		liPeso  = fgIIf((liPeso == 9), 2, liPeso + 1);
	}
	
	liTemp   = (liSoma % 11);
	liDigito = fgIIf((liTemp < 2), 0, (11 - liTemp));
	
	/*
	** Compara o 1º dígito
	*/
	if (parseInt(lsCNPJ.charAt(lsCNPJ.length - 2)) != liDigito)
		return (false);
	
	/*
	** Limpa as Variáveis
	*/
	liPeso = 2;
	liSoma = 0;

	/*
	** Cálculo do 2º dígito
	*/
	for (liPos = lsAux.length - 2; liPos >= 0; liPos--)
	{
		liSoma += parseInt(lsCNPJ.charAt(liPos)) * liPeso;
		liPeso  = fgIIf((liPeso == 9), 2, liPeso + 1);
	}
	
	liTemp   = (liSoma % 11);
	liDigito = fgIIf((liTemp < 2), 0, (11 - liTemp));
	
	/*
	** Compara o 2º dígito
	*/
	if (parseInt(lsCNPJ.charAt(lsCNPJ.length - 1)) != liDigito)
		return (false);
	
	return (true);
}

/*
'[======================================================================================
'[= Nome		: fgIIf
'[= Descrição	: Caso a condição seja verdadeira assume o primeiro valor, senão o segundo.
'[= Entrada		: pbCond       - Condição a ser avaliada
'[=               pvValueTrue  - Valor caso pbCond for verdadeiro
'[=               pvValueFalse - Valor caso contrário
'[= Saida		: pvValueTrue ou pvValueFalse
'[= Exemplo		: text4.value	= fgIIf(text3.value == 'Teste', 'fgIIf true', 'fgIIf false')
'[= OBS			:	
'[======================================================================================
*/
function fgIIf(pbCond, pvValueTrue, pvValueFalse)
{
	if (pbCond)
		return (pvValueTrue)
	else
		return (pvValueFalse);
}

/*
'[================================================================================================
'[= Nome		: fgIsNumber
'[= Descrição	: Verifica se uma string é um número.
'[= Entrada		: psNumber
'[= Saida		: True  - se a string for um número
'[=				  False - caso contrário
'[= Exemplo		: if(fgIsNumber(text7.value))
'[= OBS			:	
'[================================================================================================
*/
function fgIsNumber(psNumber)
{
	var InvalidChar = fgIsEmpty(psNumber);
	
	for (var i = 0; i < psNumber.length; i++)
	{
		var Char = psNumber.charAt(i);
		if (Char != "." && Char != "," && Char != "-")
			if (isNaN(parseInt(Char)))
				InvalidChar = true  || InvalidChar
			else
				InvalidChar = false || InvalidChar;
	}
	
	return (!InvalidChar);
}

/*
'[======================================================================================
'[= Nome		: fgIsEmpty
'[= Descrição	: Verifica se uma string está vazia ou somente com caracteres nulos
'[= Entrada		: psString 
'[= Saida		: True  - se a string estiver vazia
'[=				  False - caso contrário
'[= Exemplo		: if(fgIsEmpty(text5.value))
'[= OBS			:	
'[======================================================================================
*/
function fgIsEmpty(psString)
{
	/*
	** Caracteres Inválidos
	*/
	var lsTab   = '\t', // Tab Char
		lsSpace = ' ' , // Space
        lsCRLF  = '\n', // CR LF
		lsCR    = '\r'; // CR
	
	/*
	** Procura por caracteres válidos
	*/
	for (var liPos = 0; liPos < psString.length; liPos++)
	{
		var lsChar = psString.charAt(liPos);
		if (lsChar != lsTab   &&
			lsChar != lsSpace && 
			lsChar != lsCRLF  && 
			lsChar != lsCR )
			return (false);
	}
	
	return (true);
}

/*
'[======================================================================================
'[= Nome		: fgLeft
'[= Descrição	: Retorna os n primeiros caracteres de uma string
'[= Entrada		: psString  - String
'[=               plLength  - Número de caracteres
'[= Saida		: Retorna os n primeiros caracteres de uma string
'[= OBS			:	
'[======================================================================================
*/
function fgLeft(psString, plLength)
{
	return (psString.substring (0, plLength));
}

/*
'[================================================================================================
'[= Nome		: fgCheckCPF
'[= Descrição	: Efetua a validação de CPF
'[= Entrada		: cpf - CPF a ser validado
'[= Saida		: true  - se o CPF for válido
'[=				  false - caso contrário
'[= OBS			: Para utilizar esta função é necessário a inclusão do po_genericoFuncoes.js
'[================================================================================================
*/
function  fgCheckCPF(psCPF) 
{
	var lsAux    = '';
	var lsCPF    = '';
	var liPeso   = 2;
	var liSoma   = 0;
	var liTemp   = 0;
	var liDigito = 0;
	

	/*
	** Verifica se recebeu um objeto
	*/
	if (psCPF == '[object]')
		lsCPF = psCPF.value
	else
		lsCPF = psCPF;
	
	var liPos  = 0;

	/*
	** Remove qualquer caracter que não seja número
	*/
	for (liPos = lsCPF.length - 1; liPos >= 0; liPos--)
		if (!isNaN(lsCPF.charAt(liPos)))
			lsAux = lsCPF.charAt(liPos) + lsAux;
			
	/*
	** Cálculo do 1º dígito
	*/
	for (liPos = lsAux.length - 3; liPos >= 0; liPos--)
	{
		liSoma += parseInt(lsCPF.charAt(liPos)) * liPeso;
		liPeso++;
	}
	
	liTemp   = (liSoma % 11);
	liDigito = fgIIf((liTemp < 2), 0, (11 - liTemp));
	
	/*
	** Compara o 1º dígito
	*/
	if (parseInt(lsCPF.charAt(lsCPF.length - 2)) != liDigito)
		return (false);
	
	/*
	** Limpa as Variáveis
	*/
	liPeso = 2;
	liSoma = 0;

	/*
	** Cálculo do 2º dígito
	*/
	for (liPos = lsAux.length - 2; liPos >= 0; liPos--)
	{
		liSoma += parseInt(lsCPF.charAt(liPos)) * liPeso;
		liPeso++;
	}
	
	liTemp   = (liSoma % 11);
	liDigito = fgIIf((liTemp < 2), 0, (11 - liTemp));
	
	/*
	** Compara o 2º dígito
	*/
	if (parseInt(lsCPF.charAt(lsCPF.length - 1)) != liDigito)
		return (false);
	
	return (true);
}


/*
'[======================================================================================
'[= Nome		: fgRight
'[= Descrição	: Retorna os n últimos caracteres de uma string
'[= Entrada		: psString  - String
'[=               plLength  - Número de caracteres
'[= Saida		: Retorna os n últimos caracteres de uma string
'[= OBS			:	
'[======================================================================================
*/
function fgRight(psString, plLength)
{
	return (psString.substr(psString.length - plLength, plLength));
}