function incluiZerosAEsquerda(str,tamanho,permiteZero) {
// Descrição: Retorna 'str' preenchido com zeros à esquerda até o 'tamanho' especificado
// Autor: João Batista
// Data: 04/01/2001
// incluiZerosAEsquerda("123",6) -> 000123
// incluiZerosAEsquerda(" 123",6) -> 00 123
// incluiZerosAEsquerda("abc",6) -> 
// incluiZerosAEsquerda(" 1 3 ",6) -> 013
	retorno = str;
	if ( (str.length > 0) && (str.length < tamanho) && ( (toFloat(str) != 0) || permiteZero ) ) {
		for (i=(tamanho - str.length) ; i>0 ; i--) {
			retorno = '0' + retorno;
		}
		return retorno;
	}
	if (toFloat(str) == 0 && !permiteZero) {
		return "";
	} else {
		return str;
	}
}

function limpaZerosAEsquerda(inputString,tipo) {
// Descrição: Retira 'zeros' à esquerda do 'inputString' (usar tipo = 1 para permitir zero)
// Autor: João Batista
// Data: 04/01/20001
// limpaZerosAEsquerda("000123") -> 123
// limpaZerosAEsquerda(" 000123") -> 000123
// limpaZerosAEsquerda("000123",1) -> 123
// limpaZerosAEsquerda("000123",0) -> 123
// limpaZerosAEsquerda("-000123",1) -> 0123
// limpaZerosAEsquerda("-000123",0) -> -000123
// limpaZerosAEsquerda("000abc") -> abc
	outputString  = '';
	espacosAntes  = 0;
	if (tipo == 1) {
		re = /^0*$/;
		res = inputString.match(re);
//		if (inputString.substr(0,1) != "-" && inputString.substr(0,inputString.length) != "0") inic = 0;
		if (inputString.substr(0,1) != "-" && res == null) inic = 0;
		else  inic = 1;
	}
	else inic = 0;
	for(i = inic ; i < inputString.length ; i++){
		if(inputString.charAt(i) == '0'){ espacosAntes++; }
		else {	break;	}
	}
	outputString =  inputString.substr(espacosAntes);
	return outputString;
}

function toFloat( strValor ) {
// Descrição: Garante retorno numérico para entradas de strings
// Autor: João Batista
// Data: 04/01/2001
// toFloat('-12,345') -> -12.345
// toFloat('') -> 0
// toFloat('12.3') -> 12.3
// toFloat('-12.3') -> -12.3
// toFloat() -> 0
// toFloat('12,3') -> 12.3
// toFloat('-12,3') -> -12.3
// toFloat('abc') -> 0
	if ( (strValor == null) || (strValor.length == 0) ) {
		return 0;
	}
	if (!isNaN(strValor)) {
		return parseFloat(strValor);
	}
	retorno = limpaParaMascara(strValor,'valores');
    procurado = /,/;
    retorno = retorno.replace(procurado, ".");
	if ( (retorno == "") || (isNaN(retorno)) ) {
		return 0;
	}
	return parseFloat(retorno);
}

function trimString(inputString,trimLeft,trimRight){
// Descrição: Remove espaços em branco à direita e/ou à esquerda de 'inputString'
// Autor: João Batista
// Data: 04/01/2001
// trimString("  123  ",true,true) -> '123'
// trimString("  123  ",true,false) -> '123  '
// trimString("  123  ",false,true) -> '  123'
// trimString("  123  ",false,false) ->'  123  '
	outputString  = '';
	espacosAntes  = 0;
	espacosDepois = 0;
	if(trimLeft){
		for(i = 0 ; i < inputString.length ; i++){
			if(inputString.charAt(i) == ' '){ espacosAntes++; }
			else {	break;	}
		}
	}
	if(trimRight){
		for(i = inputString.length-1 ; i>0 ; i--){
			if(inputString.charAt(i) == ' '){ espacosDepois++; }
			else {	break;	}
		}
	}
	outputString =  inputString.substr(espacosAntes);
	outputString = outputString.substr(0,(outputString.length-espacosDepois));
	return outputString;
}

function formatoMonetario(oque,tipo){
// Descrição: Formata um campo de formulário como um valor monetário no evento onblur. 
//            Usar tipo = true para permitir "0,00". Se não informado este parâmetro, não permite.
// Autor: João Batista
// Data: 04/01/2001
// onblur = "formatoMonetario(this,true)"
	if (oque.value == "-" || oque.value == "") {
		oque.value = ""
		return;
	}
    retorno = '';
    for (contador=0;contador < oque.value.length;contador++) {
    	if( (oque.value.charAt(contador) != ".")) {retorno += oque.value.charAt(contador);}
    }
    procurado = /,/;
    retorno = retorno.replace(procurado, ".");
    retorno = retornaFormatoMonetario(retorno-0,tipo);
    oque.value = retorno;
}

function formatoMonetarioSemCentavos(oque,tipo){
// Descrição: Formata um campo de formulário como um valor monetário sem os centavos no evento onblur. 
//            Usar tipo = true para permitir "0". Se não informado este parâmetro, não permite.
// Autor: João Batista
// Data: 04/01/2001
// onblur = "formatoMonetarioSemCentavos(this,true)"
	if (oque.value == "-" || oque.value == "") {
		oque.value = ""
		return;
	}
    retorno = '';
    for (contador=0;contador < oque.value.length;contador++) {
    	if( (oque.value.charAt(contador) != ".")) {retorno += oque.value.charAt(contador);}
    }
    procurado = /,/;
    retorno = retorno.replace(procurado, ".");
    retorno = retornaFormatoMonetario(retorno-0,tipo);
	oque.value = retorno.substr(0,(retorno.length-3));
}

function retornaFormatoMonetario(valor,tipo) {
// Descrição: Retorna o parâmetro 'valor' formatado como um valor monetário. 
//            Usar tipo = true para permitir "0,00". Se não informado este parâmetro, não permite.
// requerida pela função formatoMonetario
// Autor: João Batista
// Data: 04/01/2001
// retornaFormatoMonetario("12345") -> 12.345,00
// retornaFormatoMonetario("12.345") -> 12,35
// retornaFormatoMonetario("12,345") -> 12,35
// retornaFormatoMonetario("-12345") -> -12.345,00
// retornaFormatoMonetario("-12.345") -> -12,35
// retornaFormatoMonetario('-12,345') -> -12,35
// retornaFormatoMonetario("0",0) -> 
// retornaFormatoMonetario("") -> 
// retornaFormatoMonetario("0",1) -> 0,00
// retornaFormatoMonetario("0",true) -> 0,00
// retornaFormatoMonetario("0",false) -> 
	valorNegativo = false;
	retorno = '';
	valor = toFloat(valor);
	if (valor < 0) {
		valorNegativo = true;
		valor = valor*(-1);
	}
    if(valor != 0 || (tipo == 1 && valor == 0) ) { 
		retorno = parteInteira(Math.floor(valor) + '') + parteFracao(valor); 
		if (valorNegativo) {
			retorno = '-'+retorno;
		}
	}
	return retorno;
}

function retornaFormatoMonetarioInteiro(valor) {
// Descrição: Retorna o parâmetro 'valor' formatado como um valor monetário inteiro. 
// Autor: João Batista
// Data: 04/01/2001
// retornaFormatoMonetarioInteiro("12345") -> 12.345
// retornaFormatoMonetarioInteiro("12.345") -> 12
// retornaFormatoMonetarioInteiro("12,345") -> NaN
// retornaFormatoMonetarioInteiro("") -> 
    if((valor-0) != 0) { 
		return parteInteira(Math.floor(valor-0) + ''); 
	}
	else return '';
}

function parteInteira(valor) {
// Descrição: Requerida pela função formatoMonetario. Retorna a parte inteira formatada.
// Autor: João Batista
// Data: 04/01/2001
    if (valor.length <= 3)
        return (valor == '' ? '0' : valor);
    else {
        vezes = valor.length % 3;
        retorno = (vezes == 0 ? '' : (valor.substring(0,vezes)));
        for (i=0 ; i < Math.floor(valor.length/3) ; i++) {
            if ( (vezes ==0) && (i ==0) )
                retorno += valor.substring(vezes + 3 * i,vezes + 3 * i + 3);
            else
                retorno += '.' + valor.substring(vezes + 3 * i,vezes + 3 * i + 3);
        }
		retorno = retorno.replace(/-\./,"-");
        return (retorno);
    }
}

function parteFracao(resto) {
// Descrição: Requerida pela função formatoMonetario. Retorna a parte fracionária.
// Autor: João Batista
// Data: 04/01/2001
    resto = Math.round( ( (resto) - Math.floor(resto) ) *100);
    return (resto < 10 ? ',0' + resto : ',' + resto); }


function validaLengthData(oque,tipo,permiteZero){
// Descrição: Testa o tamanho de um campo de formulário, preenche-o com zeros e valida o conteúdo, no evento onblur.
// tipos: 'cc','cep','cpf','cgc'
// Autor: João Batista
// Data: 04/01/2001
	switch (tipo) {
		case 'cep': {
			if(oque.value == ''){
				return true;
			}
			retorno = '';
			retorno = limpaParaMascara(oque.value,'numeros');
		  if (retorno.length < 8) {
				zeros = '00000000';
				retorno = retorno+zeros.substr(0,(8-retorno.length));
				if (retorno.length >= 5) { retorno = retorno.substr(0,5)+"-"+retorno.substr(5,7); }
				oque.value = retorno ;
			};
			if ( (limpaParaMascara(oque.value,'numeros') - 0) == 0) {
				alerta(oque.value+"\n"+"CEP inválido.");
				oque.value="";
				oque.focus();
				return false;
			}
			break;	
		}
		case 'cpf': {
			if(oque.value == ''){
				return true;
			}
			retorno = '';
			retorno = limpaParaMascara(oque.value,'numeros');
		    if (retorno.length < 11) {
				cpf_zeros = '00000000000';
				retorno = cpf_zeros.substr(0,(11-retorno.length))+retorno;
				if (retorno.length >= 3) { retorno = retorno.substr(0,3)+"."+retorno.substr(3); }
				if (retorno.length >= 7) { retorno = retorno.substr(0,7)+"."+retorno.substr(7); }
				if (retorno.length >= 11) { retorno = retorno.substr(0,11)+"-"+retorno.substr(11); }
				oque.value = retorno ;
				if (retorno == '000.000.000-00' && permiteZero) return true;
				if (!validaCPF(retorno)) {
					alerta(oque.value+"\n"+"CPF inválido.");
					oque.value="";
					oque.focus();
					return false;
				}
			};
			break;	
		}
		case 'cgc': {
			if(oque.value == ''){
				return true;
			}
			retorno = '';
			retorno = limpaParaMascara(oque.value,'numeros');
		    if (retorno.length < 14) {
				cgc_zeros = '00000000000000';
				retorno = cgc_zeros.substr(0,(14-retorno.length))+retorno;
				if (retorno.length >= 2)  { retorno = retorno.substr(0,2)+"."+retorno.substr(2); }
				if (retorno.length >= 6)  { retorno = retorno.substr(0,6)+"."+retorno.substr(6); }
				if (retorno.length >= 10) { retorno = retorno.substr(0,10)+"/"+retorno.substr(10); }
				if (retorno.length >= 15) { retorno = retorno.substr(0,15)+"-"+retorno.substr(15); }
				oque.value = retorno ;
	            if (!validaCGC(retorno)) {
					alerta(oque.value+"\n"+"CNPJ inválido.");
					oque.value="";
					oque.focus();
					return false;
				}
			};
			break;	
		}
	}
	return true;
}


function mascara(objEmFoco,tipo,e,tamanho1,tamanho2,sinal){
// Descrição: Máscaras para edição de campos de formulário. 
// usar sinal = 1 para valores positivos/negativos. tamanho1 e tamanho2 são opcionais e determinam o tamanho máximo de um campo numérico e suas casas decimais.
// e: "event" do obejto
// tipos: cep,cpf,cgc,cnpj10,ddd,ramal,fone,celular,DD/MM/AA,DD/MM/AAAA,MM/AAAA,IE,caracter,numero,valor,percentual,HH:MM
// Autor: João Batista
// Data: 04/01/2001
// Exemplo: onKeyUp="mascara(this,'cep');"
// Exemplo: onKeyUp="mascara(this,'valor',13,2);"
// Exemplo: onKeyUp="mascara(this,'valor',13,2,1);"


    if (
		(e.keyCode == 8) || 
		(e.keyCode == 13) || 
		(e.keyCode == 37) || 
		(e.keyCode == 39) || 
		(e.keyCode == 46) || 
		(e.keyCode == 16) || 
		(e.keyCode == 17)
		)
        return ;

	tamanho1 = toFloat(tamanho1);
	tamanho2 = toFloat(tamanho2);
	retorno = '';
	if (tipo == 'cpf') {
			objEmFoco.maxLength=14;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			if (retorno.length >= 3) { retorno = retorno.substr(0,3)+"."+retorno.substr(3); }
			if (retorno.length >= 7) { retorno = retorno.substr(0,7)+"."+retorno.substr(7); }
			if (retorno.length >= 11) { retorno = retorno.substr(0,11)+"-"+retorno.substr(11); }
			retorno = retorno.substr(0,14);
			objEmFoco.value = retorno;
			if (retorno == '000.000.000-00' && tamanho1 == 1) return true;
			if (retorno.length >= 14) {
				if (!validaCPF(retorno) || retorno == '00000000000000') {
					alert(objEmFoco.value+"\n"+"CPF inválido.");
//					objEmFoco.value="";
					objEmFoco.focus();
					return;
				}
			}
	}
	switch (tipo) {
		case 'cep': {  // 99999-999
			objEmFoco.maxLength=9;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			retorno = retorno.substr(0,9);
			if (retorno.length >= 8 && (retorno-0 == 0) )  {
				alert(retorno.substr(0,5)+"-"+retorno.substr(5,7)+"\n"+"CEP inválido.");
				objEmFoco.value="";
				objEmFoco.focus();
				return;
			}
			if (retorno.length >= 5) { retorno = retorno.substr(0,5)+"-"+retorno.substr(5,7); }
			objEmFoco.value = retorno.substr(0,9);
		break;	}
		case 'cpf': {  // 999.999.999-99

			objEmFoco.maxLength=14;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			if (retorno.length >= 3) { retorno = retorno.substr(0,3)+"."+retorno.substr(3); }
			if (retorno.length >= 7) { retorno = retorno.substr(0,7)+"."+retorno.substr(7); }
			if (retorno.length >= 11) { retorno = retorno.substr(0,11)+"-"+retorno.substr(11); }
			retorno = retorno.substr(0,14);
			objEmFoco.value = retorno;
			if (retorno == '000.000.000-00' && tamanho1 == 1) return true;
			if (retorno.length >= 14) {
				if (!validaCPF(retorno) || retorno == '00000000000000') {
					alert(objEmFoco.value+"\n"+"CPF inválido.");
//					objEmFoco.value="";
					objEmFoco.focus();
					return;
				}
			}
		break;	}
		case 'cgc': {  // 99.999.999/9999-99
			objEmFoco.maxLength=18;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			if (retorno.length >= 2)  { retorno = retorno.substr(0,2)+"."+retorno.substr(2); }
			if (retorno.length >= 6)  { retorno = retorno.substr(0,6)+"."+retorno.substr(6); }
			if (retorno.length >= 10) { retorno = retorno.substr(0,10)+"/"+retorno.substr(10); }
			if (retorno.length >= 15) { retorno = retorno.substr(0,15)+"-"+retorno.substr(15); }
			objEmFoco.value = retorno.substr(0,18);
			if (retorno.length >= 18) {
                if (!validaCGC(retorno)) {
					alert(objEmFoco.value+"\n"+"CNPJ inválido.");
//					objEmFoco.value="";
					objEmFoco.focus();
					return;
				}
            }
		break;	}
		case 'cnpj10': {  // 999.999.99
			objEmFoco.maxLength=10;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			if (retorno.length >= 2)  { retorno = retorno.substr(0,2)+"."+retorno.substr(2); }
			if (retorno.length >= 6)  { retorno = retorno.substr(0,6)+"."+retorno.substr(6); }
			objEmFoco.value = retorno.substr(0,10);
		break;	}
		case 'ddd': {  // 999
			objEmFoco.maxLength=3;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			retorno = retorno.substr(0,3);
			if (retorno.length >= 3 && (retorno-0 == 0) )  {
				alert("O DDD não pode ser "+retorno+".");
				objEmFoco.value="";
				objEmFoco.focus();
				return;
			}
			objEmFoco.value = retorno.substr(0,4);
		break;	}
		case 'ramal': {  // 9999
			objEmFoco.maxLength=4;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			objEmFoco.value = retorno.substr(0,4);
		break;	}
		case 'fone': {  // 999999999
			objEmFoco.maxLength=9;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			//if (retorno.length >= 3)  { retorno = retorno.substr(0,3)+"."+retorno.substr(3); }
			objEmFoco.value = retorno.substr(0,9);
		break;	}
		case 'celular': {  // 9999999999
			objEmFoco.maxLength=10;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			//if (retorno.length >= 4)  { retorno = retorno.substr(0,4)+"."+retorno.substr(4); }
			objEmFoco.value = retorno.substr(0,10);
		break;	}
		case 'DD/MM/AA': {  // 99/99/99
			objEmFoco.maxLength=8;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			if (retorno.length >= 2) { retorno = retorno.substr(0,2)+"/"+retorno.substr(2); }
			if (retorno.length >= 5) { retorno = retorno.substr(0,5)+"/"+retorno.substr(5); }
			objEmFoco.value = retorno.substr(0,8);
			if (retorno.length >= 8) {
				dataEmTeste = retorno.substr(0,6)+'20'+retorno.substr(6,2) ;
                if (!retornaValidaData(dataEmTeste)) {
					objEmFoco.value="";
					objEmFoco.focus();
					return;
				}
            }
		break;	}
		case 'DD/MM/AAAA': {  // 99/99/9999
			objEmFoco.maxLength=10;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			if (retorno.length >= 2) { retorno = retorno.substr(0,2)+"/"+retorno.substr(2); }
			if (retorno.length >= 5) { retorno = retorno.substr(0,5)+"/"+retorno.substr(5); }
			objEmFoco.value = retorno.substr(0,10);
			if (retorno.length >= 10) {
//				if (!retornaValidaData(objEmFoco.value,tamanho1)) {
				if (!testaData(objEmFoco.value)) {
					objEmFoco.value="";
					objEmFoco.focus();
					return;
				}
			}
		break;	}
		case 'MM/AAAA': {  // 99/9999
			objEmFoco.maxLength=7;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			if (retorno.length >= 2) { retorno = retorno.substr(0,2)+"/"+retorno.substr(2); }
			objEmFoco.value = retorno.substr(0,7);
			if (retorno.length >=8) {
				dataEmTeste = '01/'+retorno
                if (!retornaValidaData(dataEmTeste)) {
					objEmFoco.value="";
					objEmFoco.focus();
					return;
				}
            }
		break;	}
		case 'MM': {  // 99
			objEmFoco.maxLength=2;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			//if (retorno.length >= 2) { retorno = retorno.substr(0,2)+"/"+retorno.substr(2); }
			//objEmFoco.value = retorno.substr(0,7);
			if (retorno.length > 0) {
				dataEmTeste = '01/'+retorno + '/2005'
               	if (!retornaValidaData(01,retorno,2005)) {
					objEmFoco.value="";
					objEmFoco.focus();
					return;
				}
            }
		break;	}
		case 'AAAA': {  // 9999
			objEmFoco.maxLength=4;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			//if (retorno.length >= 2) { retorno = retorno.substr(0,2)+"/"+retorno.substr(2); }
			//objEmFoco.value = retorno.substr(0,7);
			if (retorno.length == 4) {
				dataEmTeste = '01/01/'+retorno 
               	if (!retornaValidaData(01,01,retorno,3)) {
					objEmFoco.value="";
					objEmFoco.focus();
					return;
				}
            }
		break;	}
		case 'IE': {  // AAAAAAAAAAAAAA
			objEmFoco.maxLength=14;
			//retorno = limpaParaMascara(objEmFoco.value,'numeros');
			//if (retorno.length >= 3) { retorno = retorno.substr(0,3)+"/"+retorno.substr(3); }
			//objEmFoco.value = retorno ;
		break;	}
		case 'caracter': {
		break;	}
		case 'numero': {
			if(tamanho1 != 0){
				objEmFoco.maxLength = tamanho1;
			}
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			objEmFoco.value = retorno.substr(0,objEmFoco.maxLength);
		break;	}
		case 'inteiro': {
			if(tamanho1 != 0){
				objEmFoco.maxLength = tamanho1;
			}
			retorno = limpaZerosAEsquerda(limpaParaMascara(objEmFoco.value,'numeros'));
			objEmFoco.value = retorno.substr(0,objEmFoco.maxLength);
		break;	}
		case 'valor': {
			retorno = objEmFoco.value;
			if (tamanho1+tamanho2 >0) {
				objEmFoco.maxLength = tamanho1 + 1 + tamanho2 + Math.floor(tamanho1/3);
			}
			var isNeg = false;
			//if (retorno.charAt(0) == '-') {
			//	isNeg = true;
			//	retorno = retorno.substring(1);
			//	objEmFoco.maxLength++;
			//}
			retorno = limpaParaMascara(retorno,'valores');
			var posPrimVirgula = retorno.indexOf(",");
			retorno = limpaParaMascara(retorno,'numeros');
			if (posPrimVirgula > 0) {
				valorInteiro = retorno.substr(0,posPrimVirgula);
				valorCentavo = retorno.substring(posPrimVirgula);
				if (retorno.charAt(0) == '0') {
					retorno = "0,"+valorCentavo.substr(0,tamanho2);
				} else {
					valorInteiro = retornaFormatoMonetarioInteiro(valorInteiro);
					valorCentavo = valorCentavo.substr(0,tamanho2);
					retorno = valorInteiro+","+valorCentavo;
				}
			} else { 
				retorno = retorno.substr(0,tamanho1);
				retorno = retornaFormatoMonetarioInteiro(retorno);
			}
			if (retorno == "" && (e.keyCode == 48 || e.keyCode == 96)) { retorno = '0'; }
			//if (isNeg) { retorno = "-"+retorno; }
			objEmFoco.value = retorno;
		break;	}
		case 'percentual': {  // 999
			objEmFoco.maxLength=3;
			retorno = limpaParaMascara(objEmFoco.value,'numeros');
			objEmFoco.value = retorno.substr(0,3);
		break;	}
		case 'HH:MM': { // 12:00
			objEmFoco.maxLength=5;
			retorno = limpaParaMascara(objEmFoco.value,"numeros");
			if ( retorno.substr(0,1) > 2 ) { retorno = ''; }
			if ( retorno.substr(0,2) > 23 ) { retorno = retorno.substr(0,1); }
			if ( retorno.substr(2,1) > 5 ) { retorno = retorno.substr(0,2); }
			if (retorno.length >= 2) { retorno = retorno.substr(0,2) + ":" + retorno.substr(2); }
			objEmFoco.value = retorno.substr(0,5);
		break; }
		case 'S/N': {
			if (objEmFoco.value.length > 1) objEmFoco.value = objEmFoco.value.substr(0,1);
			if (objEmFoco.value == "S" || objEmFoco.value == "s") objEmFoco.value = "S";
			else if (objEmFoco.value == "N" || objEmFoco.value == "n") objEmFoco.value = "N";
			else objEmFoco.value = '';
		break;
		} case 'telefoneDDD': { //(99)9999-9999 
			objEmFoco.maxLength=13;
			var value = objEmFoco.value;
			if(value.length > 4) { 
				retorno = limpaParaMascara(value.substr(0,4),'numeros');
				retorno += limpaParaMascara(value.substr(4,value.length),'telefone');
			} else {
				retorno = limpaParaMascara(value,'numeros');
			}
			if (retorno.length >= 0) { retorno = "("+retorno; }
			if (retorno.length >= 3) { retorno = retorno.substr(0,3)+")"+retorno.substr(3); }
			objEmFoco.value = retorno.substr(0,13);
			if (retorno.length >= 13) {
				if (!testaTelefoneDDD(objEmFoco.value)) {
					objEmFoco.value="";
					objEmFoco.focus();
					return;
				}
			}
		break;	
		}
	}
}


function limpaParaMascara(sujeira,filtro,tipo){
// Descrição: Recebe um string e retorna somente os caracteres que pertencem ao filtro. Usar tipo = 1 para valores positivo/negativo.
// Autor: João Batista
// Data: 04/01/2001
// limpaParaMascara('12.3ABC -def456','valores') -> 123456
// limpaParaMascara('12,3ABC -def456','valores') -> 12,3456
// limpaParaMascara('-12,3ABC -def456','valores') -> -12,3456
// limpaParaMascara('12,3ABC -def456','letras') -> 12,3ABC -def456
// limpaParaMascara('12,3ABC -def456','numeros') -> 123456
// limpaParaMascara('12,3ABC-1235','telefone') -> 123-1235
// limpaParaMascara('0','numeros') -> 0
//  ******
//  Filtros:
	numeros = "0123456789";
	telefone = "0123456789-";
	valores = "0123456789,";
	letras  = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzÁÉÍÓÚÀÈÌÒÙÄËÏÖÜÂÊÎÔÛÃÕáéíóúàèìòùäëïöüâêîôûãõçÇ&ªº'\"\|@_<>!#$%&*()={[}]?:+-.,;/\\0123456789 ";
//  ******
	retorno2 = '';
	if (tipo == 1) {
		if (sujeira.substring(0,1) == "-") ind = 1;
		else ind = 0;
	}
	else ind = 0;
	switch (filtro){
		case 'numeros': {
			for ( i=ind; i < sujeira.length; i++ ) {
				if( numeros.indexOf(sujeira.charAt(i))>-1 ) { 
					retorno2 += sujeira.charAt(i);
				}
			}
		break;	}
		case 'valores': {
			for ( i=ind; i < sujeira.length; i++ ) {
				if( valores.indexOf(sujeira.charAt(i))>-1 ) { 
					retorno2 += sujeira.charAt(i);
				}
			}
			if (sujeira.charAt(0)=='-') {
				retorno2 = "-"+retorno2;
			}
		break;	}
		case 'letras': {
			for ( i=0; i < sujeira.length; i++ ) {
				if( letras.indexOf(sujeira.charAt(i))>-1 ) { 
					retorno2 += sujeira.charAt(i);
				}
			}
		break;	}
		case 'telefone': {
			for ( i=0; i < sujeira.length; i++ ) {
				if( telefone.indexOf(sujeira.charAt(i))>-1 ) { 
					retorno2 += sujeira.charAt(i);
				}
			}
		break;	}
	}
	if (tipo == 1) {
		if (sujeira.substring(0,1) == "-") retorno2 = "-" + retorno2;
	}
	return retorno2;
}

function validaCPF (CPF) {
// Descrição : Função de validação de CPF.
// Autor: João Batista
// Data: 04/01/2001
    CPF = limpaParaMascara(CPF,'numeros');    
    if (CPF.length != 11) { for(countZeros=0 ; countZeros < ((11-CPF.length)+2) ; countZeros++){ CPF = "0"+CPF; } };
	if(CPF == '00000000000'){ return false; }
    soma = 0;
    for(i=0 ; i<9 ; i++) {
        soma = soma + eval(CPF.charAt(i) * (10 - i));
    }
    Resto = 11 - ( soma - (parseInt(soma / 11) * 11) );
    if ( (Resto == 10) || (Resto == 11) ) { Resto = 0; }
    if ( Resto != eval( (CPF.charAt(9) ) ) ) { return false; }
	soma = 0;
    for (i = 0;i<10;i++) {
        soma = soma + eval(CPF.charAt(i) * (11 - i));
	} 
    Resto = 11 - ( soma - (parseInt(soma / 11) * 11) );
    if ( (Resto == 10) || (Resto == 11)) {
		Resto = 0;
	}
    if ( Resto != eval( (CPF.charAt(10)) )) {
		return false;
	}
	return true;
}

function validaCGC(field) {
// Descrição: Função de validação de CGC.
// Autor: João Batista
// Data: 04/01/2001
   field = limpaParaMascara(field,'numeros');    
   if ( (field == "") || (field == " ") || (field == '00000000000000')) return false;
   if (field.length != 14) {
        return false;
    }
	first_digit  = field.charAt(12);
	second_digit = field.charAt(13);
	field = field.substring(0,12);
	first_verified  = calcMod11(field,5,2);  // Através do modulo 11 descobre qual é o primeiro digito do final
	second_verified = calcMod11(field + first_verified,6,2);  // Através do modulo 11 descobre qual é o segundo digito do final
	/*
	Se os dois digitos gerados pelo modulo11 forem iguais aos dois últimos
	digitos digitados pelo usuário, validação de CGC OK.
	*/	
	if( (first_verified == first_digit) && (second_verified==second_digit) ) { return true; } 
	else {
        return false;
	}
}

function calcMod11(field,start, finish) {
// Descrição : Cálculo do Módulo 11. Requerida pela validação de CGC.
// Autor: João Batista
// Data: 04/01/2001
	t_i      = 0;
	t_sum    = 0;
	t_aux    = 0;
	t_digito = 0;
	t_peso   = 0;
	t_tam    = 0;
	t_char   = 'z';
	t_peso = start;
	t_tam = field.length >= 13 ? t_tam = 13 : t_tam = 12;
	for(t_i=0 ; t_i< t_tam ; t_i++) {
		t_char = field.charAt(t_i);
		t_sum = t_sum + ( (parseInt(t_char)) * t_peso);
		t_peso = t_peso > finish ? --t_peso : (start + (9 - start));
	}
	t_aux = t_sum % 11;
	t_aux = 11 - t_aux;
	t_digito = (t_aux >= 10 ? 0 : t_aux);
	return t_digito;
}

function formataCPF(paramCpf) {
// Descrição: Função de máscara para CPF
// Autor: João Batista
// Data: 04/01/2001
// formataCPF("99999999999") -> 999.999.999-99
// formataCPF("abc99999999") -> abc99999999
// formataCPF("9999999999") -> 9999999999
// formataCPF("999999999990") -> 999999999990
	cpfSemMascara = limpaParaMascara(paramCpf,'numeros');
	if (cpfSemMascara.length == 11) {
		cpfRetorno = '';
		cpfRetorno += cpfSemMascara.substr(0,3);
		cpfRetorno += ".";
		cpfRetorno += cpfSemMascara.substr(3,3);
		cpfRetorno += ".";
		cpfRetorno += cpfSemMascara.substr(6,3);
		cpfRetorno += "-";
		cpfRetorno += cpfSemMascara.substr(9,2);
		return cpfRetorno;
	} else {
		return paramCpf;
	}
}

function formataCGC(paramCgc) {
// Descrição: Função de máscara para CGC. 
// Autor: João Batista
// Data: 04/01/2001
// formataCGC("99999999999999") -> 99.999.999/9999-99
// formataCGC("abc99999999999") -> abc99999999999
// formataCGC("9999999999999") -> 9999999999999
// formataCGC("999999999999990") -> 999999999999990
    cgcSemMascara = limpaParaMascara(paramCgc,'numeros');
    if (cgcSemMascara.length == 14) {
		cgcRetorno = '';
    	cgcRetorno = cgcSemMascara.substr(0,2);
    	cgcRetorno += '.';
    	cgcRetorno += cgcSemMascara.substr(2,3);	
    	cgcRetorno += '.';
    	cgcRetorno += cgcSemMascara.substr(5,3);	
    	cgcRetorno += '/';
    	cgcRetorno += cgcSemMascara.substr(8,4);	
    	cgcRetorno += '-';		
    	cgcRetorno += cgcSemMascara.substr(12,2);
    	return cgcRetorno;
    }
    else {
        return paramCgc;
    }
}

function alertaDataInvalida(data,tipoTratamento) {
// !!! Veja a função dataValida() com vários tipos de teste
// Descrição : Verifica se a data informada é válida. Se não, emite alerta.
// Autor: João Batista
// Data: 04/01/2001
	falhou = false;
	t_data = data.value;
	t_data = limpaCampo(t_data);
	dia = t_data.substr(0,2);
	mes = t_data.substr(2,2) - 1;
	ano = t_data.substr(4,4);
	dataCorr = new Date();
	dataObj = new Date(ano,mes,dia);
	diaObj = dataObj.getDate();
	mesObj = dataObj.getMonth();
	anoObj = dataObj.getFullYear();
	if ( ( t_data.length < 8 ) || (dia != diaObj) || (mes != mesObj) || (ano != anoObj) )
		falhou = true;
    // Data não maior ou igual a data do dia
	if (tipoTratamento == 0 ) {
		if (dataObj >= dataCorr) {
			falhou = true;
		}
	}
	// Data não maior a data do dia
	if (tipoTratamento == 1) {
		if (dataObj > dataCorr) {
			falhou = true;
		}
	}
	if (tipoTratamento == 2 && data.value == '00/00/0000') falhou = false;
	if ( falhou ) {
		alerta("Data inválida");
		data.value = '';
		if (!data.disabled) {
			data.focus();
		}
	}
}
	
function dataValida(dataValor,tipoTeste){
// Descrição: Retorna false caso o string 'dataValor' não passe no 'tipoTeste', ou true no caso de passar no teste.
// Tipos de teste: anterior,ult120anos,futura,futuraOUigual,anteriorOUigual,2mesesMMAAAA
// Autor: João Batista
// Data: 04/01/2001
// Exemplo: if(dataValida(document.form.txtData.value,'anterior')) {alerta("a data é anterior à atual e é válida")}
	dataValor = limpaCampo(dataValor);

	dia = dataValor.substr(0,2);
	mes = dataValor.substr(2,2) - 1;
	ano = dataValor.substr(4,4);

	dataObj = new Date(ano,mes,dia);
	diaObj = dataObj.getDate();
	mesObj = dataObj.getMonth();
	anoObj = dataObj.getFullYear();
	dataObj.setHours(0);
	dataObj.setMinutes(0);
	dataObj.setSeconds(0);
	dataObj.setMilliseconds(0);

	dataCorr = new Date();
	diaCorr = dataCorr.getDate();
	mesCorr = dataCorr.getMonth();
	anoCorr = dataCorr.getFullYear();
	dataCorr.setHours(0);
	dataCorr.setMinutes(0);
	dataCorr.setSeconds(0);
	dataCorr.setMilliseconds(0);

	data120 = new Date(anoCorr-120,mesCorr,diaCorr);
	data120.setHours(0);
	data120.setMinutes(0);
	data120.setSeconds(0);
	data120.setMilliseconds(0);

	if ( ( dataValor.length < 8 ) || (dia != diaObj) || (mes != mesObj) || (ano != anoObj) )
		return false;
/*
	if(tipoTeste != null && tipoTeste != 'anterior' && tipoTeste != 'ult120anos' && tipoTeste != 'futura' && tipoTeste != 'anteriorOUigual' && tipoTeste != '2mesesMMAAAA' && tipoTeste != 'futuraOUigual') {
		alerta("parâmetro de teste de data inválido");
		return false;
	}
*/
	switch (tipoTeste){
		case 'anterior':{
			if (dataObj >= dataCorr) {
				return false; }
		break; }
		case 'ult120anos':{
			if (dataObj < data120) {
				return false; }
			if (dataObj >= dataCorr) {
				return false; }
		break; }
		case 'ult120anosFutura':{
			if (dataObj < data120) {
				return false; }
		break; }
		case 'futura':{
			if (dataObj <= dataCorr) {
				return false; }
		break; }
		case 'futuraOUigual':{
			if (dataObj < dataCorr) {
				return false; }
		break; }
		case 'anteriorOUigual':{
			if (dataObj > dataCorr) {
				return false; }
		break; }
		case '2mesesMMAAAA':{
			dia = '01';
			dataObj = new Date(ano,mes,dia);
			dataObj.setHours(0);
			dataObj.setMinutes(0);
			dataObj.setSeconds(0);
			dataObj.setMilliseconds(0);
			if( mesCorr >= 2) {mesCorr -= 2;} // mes a partir de março
			else {
				anoCorr -= 1;
				if(mesCorr == 0){mesCorr = 10};
				if(mesCorr == 1){mesCorr = 11};
			}
			data2meses = new Date(anoCorr,mesCorr,dia);
			data2meses.setHours(0);
			data2meses.setMinutes(0);
			data2meses.setSeconds(0);
			data2meses.setMilliseconds(0);
			if (dataObj < data2meses) {
				return false; }
		break; }
	}
	return true;
}

function retornaValidaData(t_data,tipoTratamento) {
// Descrição: Recebe o value da data e retorna true se é data válida ou false caso contrário.
// Autor: João Batista
// Data: 04/01/2001
    falhou = false;
//    t_data = limpaCampo(t_data);
	dia = t_data.substr(0,2);
	mes = t_data.substr(2,4) - 1;
	ano = t_data.substr(4,4);
	dataCorr = new Date();
    dataObj = new Date(ano,mes,dia);
	diaObj = dataObj.getDate();
	mesObj = dataObj.getMonth();
	anoObj = dataObj.getFullYear();
	if ( ( t_data.length < 8 ) || (dia != diaObj) || (mes != mesObj) || (ano != anoObj) )
		falhou = true;
	if (tipoTratamento && tipoTratamento == 2 && t_data == '00000000') falhou = false;
	if ( falhou ) {
		return false;
  }
	else return true;
}

function retornaValidaData(dia,mes,ano,tipoTratamento) {
// Descrição: Recebe o value da data e retorna true se é data válida ou false caso contrário.
// Autor: João Batista
// Data: 04/01/2001
    falhou = false;
	dataCorr = new Date();
    dataObj = new Date(ano,mes,dia);
	diaObj = dataObj.getDate();
	mesObj = dataObj.getMonth();
	anoObj = dataObj.getFullYear();
	t_data = dia + '/' + mes + '/' + ano
	if ( ( t_data.length < 8 ) || (dia != diaObj) || (mes != 12 && mes != mesObj) || (mes != 12 && ano != anoObj) || (mes == 0))
		falhou = true;
	if (tipoTratamento && tipoTratamento == 2 && t_data == '00000000') falhou = false;

	if (tipoTratamento && tipoTratamento == 3) {
	//Testa se ano é maior que o atual
		if(anoObj < dataCorr.getFullYear()) {
			falhou = true;
			alert('A data informada deve ser maior ou igual a atual')
		}
	}
	if ( falhou ) {
		return false;
  }
	else return true;
}
function openModalAutorizacao(pagina,w,h) { //v2.0
// Descrição: Abre uma janela modal
// Data: 04/01/2001
	if (w == null) w = 320;
	if (h == null) h = 210;
	return showModalDialog(pagina, '', 'unardorned:no;scroll:no;resizable:no;status:no;center=yes;help:no;dialogWidth:'+w+'px;dialogHeight:'+h+'px;');
}


function periodoDatas(dataFimPeriodo,dataInicioPeriodo) {
// Descrição: Subtrai datas
// Autor: João Batista
// Data: 
	dateFim = new Date(dataFimPeriodo.substring(6,10),dataFimPeriodo.substring(3,5)-1,dataFimPeriodo.substring(0,2));
	dateInicio = new Date(dataInicioPeriodo.substring(6,10),dataInicioPeriodo.substring(3,5)-1,dataInicioPeriodo.substring(0,2));
	return ((dateFim - dateInicio)/86400000);
}

function dateToddmmaaaa(objDate) {
// Descrição: recebe um objeto Date e retorna ele formatado como DD/MM/AAAA
// Autor: João Batista
// Data: 27/12/2000
	var dia = objDate.getDate();
	var mes = objDate.getMonth()+1;
	if (dia < 10) { dia = '0'+dia; }
	if (mes < 10) { mes = '0'+mes; }
	return dia+"/"+mes+"/"+objDate.getFullYear();
}

function toData(stringData){
// Descrição: Gera um objeto data a partir de um string no formato dd/mm/aaaa
// Autor: João Batista
// Data: 
	if (stringData.substr(0,1) == "0") dia = stringData.substr(1,1);
	else dia = stringData.substr(0,2);
	if (stringData.substr(3,1) == "0") mes = (stringData.substr(4,1)-1);
	else  mes = (stringData.substr(3,2)-1);
	ano = stringData.substr(6,4);
	tmp_Data = new Date(ano,mes,dia,0,0,0,0);
	return (tmp_Data);
}


/*function abreModal(sistema,gif,codigo,mensagem,url) {
// Descrição: Abre uma janela modal que se for clicado em "Continuar" direciona a página para a url especificada
// Autor: João Batista
// Data: 15/03/2001
// Parâmetros:
// 	sistema: o que deve aparecer no início do título da modal
// 	gif: o arquivo .gif  que aparece na modal. Se não especificado, será o img_ok.gif
// 	codigo: o código do erro que vai aparecer no título da modal
// 	mensagem: Mensagem que será exibida no corpo da modal
// 	url: a url que ocupará a página que abriu a modal, caso seja clicado no continuar na modal
	var retorno = false;
	retorno = showModalDialog('/BAS/bas5010.jsp?sistema='+sistema+'&gif='+gif+'&codigo='+codigo+'&mensagem='+mensagem, '', 'unardorned:no;scroll:no;resizable:no;status:no;center=yes;help:no;dialogWidth:400px;dialogHeight:200px;');
	if ( (retorno == true) && (url.length > 0) ) {
		self.location = url;
	}
}
*?




/********************************************************************************************************
* Biblioteca de Funções Genéricas 									* 
* 													* 
* Funções neste arquivo: 										* 
* 													* 
* FUNÇÂO RETORNO DESCRIÇÂO 										* 
* ------ ------- --------- 										* 
* testaString(str, descricao) Boolean checa string nula ou com brancos 					* 
* testaCombo(combo, descricao) Boolean checa se existe opção selecinada 				* 
* testaComboValor(combo, descricao) Boolean checa se existe opção selecinada testando valor 		* 
* diferente -1 												* 
* testaCep(campoCep) Boolean Testa se o Cep é valido 							* 
* testaCgc(campoCgc) Boolean Testa se o CGC é valido 							* 
* checa_cpf (numcpf) Boolean Testa se o Cpf é valido 							* 
* mod(ini,fim) Number Calcula o resto de ini/fim 							* 
* emailCheck(emailStr) Boolean Testa se o E-mail é valido 						* 
* trim(str) String comprime espaços da string 								* 
* testaData(dateStr) Boolean Testa se a data é valida 							* 
* formatCurrency(num) String Formata número separando por (.) e (,) 					* 
* Ex: formatCurrency(1000.5) = "1.000,50" 								* 
* testaValor(str, descricao) Boolean checa se o valor numérico e valido e não nulo 			* 
* testaRadioGroup(radioObj, descricao) Boolean checa se existeb alguma opção selecionada 		* 
* testaAno(str, descricao) Boolean Testa ano com 4 algarismo 						* 
* isDigit(c) Boolean Testa se o caracter c é numero (0 a 9) 						* 
* isInteger (s) Boolean Testa se a string só contem numeros 						* 
* isFloat (s) Boolean Testa se a string só contem float (0 a 9 e .) 					* 
* testaFloat(numero, descricao) Boolean Testa se a string só contem float (0 a 9 e .) 			* 
* testaTelefone(numero, descricao) Boolean Testa se a string só contem numeros(0 a 9 e -) 		*	 
* data(strData) Number Valor Numerico da Data, permitindo comparar datas 				* 
* dataAtual() String data atual formato dd/mm/yyyy 							* 
* strZero(numero, tam) String numero com zeros a esquerda até preencher o tam 				* 
*													*
********************************************************************************************************/ 



var hoje = new Date(); 

var AnoCorrente = parseInt(hoje.getFullYear()); 


function isLetter (c) { 
	return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) ) 
} 


function isLetterOrDigit (c) {
	return (isLetter(c) || isDigit(c) || (c == " ")) 
} 


function soNumeroLetra(str) { 
	var resposta = true; 
	for (i = 0; i <= str.length - 1; i++) { 
		if (!isLetterOrDigit(str.substr(i,1))) 
		resposta = false; 
	} 
	return resposta; 
} 


function data(strData) { 
	//formato esperado: dd/mm/yyyy 	
	var ano = strData.substring(6,10); 	
	var mes = strData.substring(3,5); 	
	var dia = strData.substring(0,2); 	
	var dtData = Date.parse(mes + "/" + dia + "/" + ano); 
	
	return dtData; 	
} 


function dataAtual() { 

	var d; 
	var s = ""; 
	d = new Date(); 
	s += strZero(d.getDate(),2) + "/"; 
	s += strZero((d.getMonth() + 1),2) + "/"; 
	s += d.getFullYear(); 
	
	return(s); 
} 

function strZero(numero, tam) { 
	
	var numero = trim(numero); 
	while(numero.length < tam) { 
		numero = "0" + numero; 
	} 

	return numero; 
} 

function testaString(str, descricao) { 
	if (trim(str) == "") { 
		alert(descricao + " é Campo Obrigatório !"); 
		return false; 
	} 
	return true; 
} 


function testaCombo(combo, descricao) { 
	
	if (combo.selectedIndex == -1 || combo.selectedIndex == 0) { 	
		if (trim(descricao) != "" && trim(descricao) != " "){ 
			alert(descricao + " deve ter uma Opção Selecionada"); 
		} 
		return false; 
	}  else 
		return true; 
} 


function testaComboValor(combo, descricao) { 
	if (combo.options[combo.selectedIndex].value == -1) { 	
		if (trim(descricao) != "" && trim(descricao) != " "){ 
			alert(descricao + " deve ter uma Opção Selecionada"); 
		} 
		return false; 
	} else 
		return true; 
} 


function testaValor_(str) { 
	var inp = ""; 	
	var decimal = -1; 	
	var milhar = -1; 	
	var chr; 	
	var negativo = false; 	
	var texto = trim(str);
		
	for (i = 1; i <= texto.length; i++) { 
		chr = texto.charAt(texto.length - i); 
		if (negativo) return 0; 
		else if (chr == '-') { 
			inp = '-' + inp; 
			negativo = true; 
		} 
		else if (",.".indexOf(chr) >= 0) { 
			if (chr == decimal) return 0; 
			if (i <= 3) { 
				if (decimal != -1) return 0; 
				decimal = chr; 
				inp = '.' + inp; 
			} 
			else if (milhar == -1) milhar = chr; 
			if (chr != milhar && chr != decimal) return 0; 
		}	 
		else if ("0123456789".indexOf(chr) >= 0) inp = chr + inp; 
		else return 0; 
	} 
	
	return parseFloat(inp); 
} 



function testaValor(str, descricao) { 
	if (str.length > 13) { 
		alert(descricao + " deve ter no máximo 13 posições"); 
		return false; 
	} 
	if (testaValor_(str) == 0 && trim(descricao) != "" && trim(descricao) != " ") { 
		alert(descricao + " Deve ser Preenchido Corretamente"); 
		return false; 
	} 
	return true; 
} 


function testaRadioGroup(radioObj, descricao)
{
  if(radioObj){
      if(radioObj.form){
        if(radioObj.checked){
           return true;
        }
     }
     else{
         for(i = 0; i < radioObj.length; i++) {
           if (radioObj[i].checked)
           return true;
         }
     }
  }
  else{
     alert("Nenhuma opção a ser selecionada!")
      return false;
  }
  if (trim(descricao) != "" && trim(descricao) != " "){
                  alert("Deve ser selecionada uma opção de " + descricao);
                  return false;
  }
}


function isDigit (c) { 
	return ((c >= "0") && (c <= "9")) 
} 


function isInteger (s) { 
	var i; 
	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; 
} 

function isFloat (s) { 
	var i; 
	var decimalPointDelimiter = "."; 
	if (s == decimalPointDelimiter) return false; 
	for (i = 0; i < s.length; i++) { 
		// Check that current character is number. 
		var c = s.charAt(i); 
		if (!((c == decimalPointDelimiter) || (isDigit(c)))) 
		return false; 
	} 
	return true; 
} 

function testaFloat(numero, descricao) { 
	if (!isFloat(numero)) { 
		alert(descricao + " Deve ser Preenchido Corretamente"); 
		return false; 
	} 
	return true; 
} 

function testaTelefone (numero, descricao) { 
	var i; 
	var traco = "-"; 
	var branco = " "; 
	s = trim(numero); 
	if (s == traco) { 
		alert(descricao + " Não é um Numero de Telefone de Válido"); 
		return false; 
	} 
	for (i = 0; i < s.length; i++) 	{ 
		// Check that current character is number. 
		var c = s.charAt(i); 
		if (!((c == traco) || (c == branco) || (isDigit(c)))) { 
			alert(descricao + " Não é um Numero de Telefone de Válido"); 
			return false; 
		} 
	} 
	return true; 
} 

function testaTelefoneDDD (numero) { 
	var i; 
	var traco = "-"; 
	var ddd1 = "("; 
	var ddd2 = ")"; 
	var branco = " "; 
	s = trim(numero); 
	if (s == traco || s == ddd1 || s == ddd2) { 
		alert(numero + "  não é um telefone válido"); 
		return false; 
	} 
	var temTraco = false;
	for (i = 0; i < s.length; i++) 	{ 
		// Check that current character is number. 
		var c = s.charAt(i); 
		if(c == traco) {
			temTraco = true;
		}
		if (!((c == ddd1) || (c == ddd2) || (c == traco) || (c == branco) || (isDigit(c)))) { 
			alert(numero + "  não é um telefone válido"); 
			return false; 
		} 
	} 
	if(s.length == 13 && !temTraco){
		alert(numero + "  não é um telefone válido"); 
		return false;
	}
	return true; 
} 

function testaAno(ano, descricao) { 
	var tam = ano.length; 
	if (tam < 4) { 
		alert(descricao + " Deve ter 4 (quatro) posições"); 
		return false; 
	} 
	if (!isInteger(ano)) { 
		alert(descricao + " Deve ser Numero Inteiro"); 
		return false; 
	} 
	if (parseInt(ano) < parseInt(AnoCorrente - 8)) { 
		alert(descricao + " Ano deve ser Maior que " + parseInt(AnoCorrente - 9)); 
		return false; 
	} 
	return true; 
} 


function testaInteiro(numero, descricao) { 
	if (trim(numero) == "") { 
		alert(descricao + " é Campo Obrigatório"); 
		return false; 
	} 
	var numero = trim(numero); 
	var tam = numero.length; 
	if (tam > 8) { 
		alert(descricao + " deve ter no máximo 8 (oito) posições"); 
		return false; 
	} 
	if (!isInteger(numero)) { 
		alert(descricao + " deve ser Numero Inteiro"); 
		return false; 
	} 
	return true; 
} 


function testaCep(campoCep) { 
	/* Critica de CEP - função principal */ 
	var dblNum; 
	var num1 = new initArrayCep(8); 
	if((campoCep == null) || (campoCep == "00000000")) { 
		alert("CEP nulo"); 
		return false; 
	} 
	if(campoCep.length != 8) { 
		alert("CEP diferente de 8 posições"); 
		return false; 
	} 
	if((campoCep.substr(5,1) < "0") || (campoCep.substr(5,1) > "9") 
		|| (campoCep.substr(6,1) < "0") || (campoCep.substr(6,1) > "9") 
		|| (campoCep.substr(7,1) < "0") || (campoCep.substr(7,1) > "9")) { 
		alert("CEP não deve conter caracteres diferentes de números"); 
		return false; 
	} 
	
	dblNum = 0.1; 
	if(!isNaN(campoCep)) { 
		dblNum = campoCep; 
		return true; 
	} 
	else { 
		alert("CEP tem que ser numérico"); 
		return false; 
	} 
} 


function initArrayCep() { 
	/* Critica de Cep - Sub-funcao */ 
	this.length = initArrayCep.arguments.length; 
	for (var i = 0 ; i < 8 ; i++) { 
		this[i] = " "; 
	} 
} 

function testaCgc(campoCgc) { 
	var num1 = new initArray(14); 
	if(campoCgc == null) { 
		alert("CNPJ nulo"); 
		return false; 
	} 
	if(campoCgc.length != 14) { 
		alert("CNPJ diferente de 14 posições"); 
		return false; 
	} 
	for (var i = 0 ; i < 14 ; i++) { 
		num1[i] = campoCgc.substring(i, i+1); 
	} 
	
	digito13 = calculaDigito(13, num1); 
	digito14 = calculaDigito(14, num1); 
	if (num1[12]==(digito13) && num1[13]==(digito14)){ 
		return true; 
	} 
	else { 
		alert("CNPJ incorreto"); 
		return false; 
	} 
} 


function initArray() { 
	this.length = initArray.arguments.length; 
	for (var i = 0 ; i < 14 ; i++) { 
		this[i] = " "; 
	} 
} 


function calculaDigito( cgc_limite, num) { 
	cgc_soma = 0; 
	cgc_ind = 1; 
	cgc_peso = cgc_limite - 7 - cgc_ind; 
	while(cgc_ind < cgc_limite) { 
		cgc_soma += num[cgc_ind - 1] * cgc_peso; 
		cgc_ind++; 
		if(cgc_peso == 2) 
			cgc_peso = 9; 
		else 
			cgc_peso--; 
	} 
	cgc_resto = mod(cgc_soma, 11); 
	if(cgc_resto == 0 || cgc_resto == 1) 
		{cgc_digito = 0;} 
	else 
		cgc_digito = 11 - cgc_resto;
	return cgc_digito; 

} 


function mod(ini, fim) { 
	t = ini % fim; 
	return t; 
} 

function temRepeticao(str, num) { 
	var cont = 0; 
	var num = parseInt(num); 
	for (i = 0; i <= str.length - 1; i++) { 
		cont = 0; 
		for (j = i + 1; j <= str.length - 1; j++) { 
			if (str.substr(i,1) == str.substr(j,1)) 
				cont++; 
			else 
				break; 
		} 
		if (cont >= num) 
			break; 
	} 
	return (cont >= num); 
} 


function checa_cpf (numcpf) { 
	// teste se o cpf tem 11 numeros repetidos (iguais) 
	if (temRepeticao(numcpf,10)) 
		return false; 
	x = 0; 
	soma = 0; 
	dig1 = 0; 
	dig2 = 0; 
	texto = ""; 
	numcpf1=""; 
	len = numcpf.length; x = len -1; 
	
	// var numcpf = "12345678909"; 
	for (var i=0; i <= len - 3; i++) { 
		y = numcpf.substring(i,i+1); 
		soma = soma + ( y * x); 
		x = x - 1; 
		texto = texto + y; 
	} 
	
	dig1 = 11 - (soma % 11); 
	if (dig1 == 10) dig1=0 ; 
	if (dig1 == 11) dig1=0 ; 
	numcpf1 = numcpf.substring(0,len - 2) + dig1 ; 
	x = 11; soma=0; 
	for (var i=0; i <= len - 2; i++) { 
		soma = soma + (numcpf1.substring(i,i+1) * x); 
		x = x - 1; 
	} 
	
	dig2= 11 - (soma % 11); 
	if (dig2 == 10) dig2=0; 
	if (dig2 == 11) dig2=0; 
	//alert ("Digito Verificador : " + dig1 + "" + dig2); 
	
	if ((dig1 + "" + dig2) == numcpf.substring(len,len-2)) { 
		return true; 
	} 
	alert ("Número do CPF inválido !!!"); 
	falso = "F"; 
	return false; 

} 


function testa_CPF(numcpf) { 
	if(checa_cpf(numcpf)) { 
		return true; 
	} else { 
		return false; 
	} 

} 


function emailCheck (emailStr) { 
	//remove espaços antes da verificação 
	var emailStr = trim(emailStr) 
	/* Critica de e-mail */ 
	var emailPat=/^(.+)@(.+)$/ 
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]" 
	var validChars="\[^\\s" + specialChars + "\]" 
	var quotedUser="(\"[^\"]*\")" 
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/ 
	var atom=validChars + '+' 
	var word="(" + atom + "|" + quotedUser + ")" 
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$") 
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$") 
	
	var matchArray=emailStr.match(emailPat) 
	
	if (matchArray==null) { 
		alert("O endereço de e-mail parece incorreto (verifique @ e .'s)") 
		return false 
	} 
	
	var user=matchArray[1] 
	var domain=matchArray[2] 
	
	if (user.match(userPat)==null) { 
		alert("O nome de usuário do e-mail não parece ser válido.") 
		return false 
	} 
	
	var IPArray=domain.match(ipDomainPat) 
	if (IPArray!=null) { 
		for (var i=1;i<=4;i++) { 
			if (IPArray[i]>255) { 
				alert("O endereço IP de destino do e-mail é inválido!") 
				return false 
			} 
		} 
		return true 
	} 
	
	var domainArray=domain.match(domainPat) 
	if (domainArray==null) { 
		alert("O nome do domínio do e-mail não parece ser válido.") 
		return false 
	} 

	var atomPat=new RegExp(atom,"g") 
	var domArr=domain.match(atomPat) 
	var len=domArr.length 
	if (domArr[domArr.length-1].length<2 
			|| domArr[domArr.length-1].length>3) { 
		alert("O endereço de e-mail deve terminar com um domínio de 3 letras ou um país com 2 letras.") 
		return false 
	} 
	
	if (len<2) { 
		var errStr="Este endereço de e-mail não possui um nome de Host!" 
		alert(errStr) 
		return false 
	} 
	return true; 
} 


function trim(str) { 
	str = str.toString().replace(/\$|\ /g,''); 
	return str; 
} 


function testaData(dateStr) { 
	// testa data em branco -> usa função trim 
	if (trim(dateStr) == "") { 
		alert("Data é Campo Obrigatório"); 
		return false; 
	} 
	// Checks for the following valid date formats: 
	// DD/MM/YY DD/MM/YYYY DD-MM-YY DD-MM-YYYY 
	// Also separates date into month, day, and year variables 
	// To require a 2 digit year entry, use this line instead: 
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/; 
	// To require a 4 digit year entry, use this line instead: 
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; 
	var matchArray = dateStr.match(datePat); // is the format ok? 
	if (matchArray == null) { 
		alert("Data deve estar no formato DD/MM/AAAA") 
		return false; 
	} 
	
	day = matchArray[1]; 
	month = matchArray[3]; // parse date into variables 
	year = matchArray[4]; 
	if (month < 1 || month > 12) { // check month range 
		alert("Mês deve ser entre 1 e 12."); 
		return false; 
	} 
	
	if (day < 1 || day > 31) { 
		alert("Dia deve ser entre 1 e 31."); 
		return false; 
	} 
	
	if ((month==4 || month==6 || month==9 || month==11) && day==31) { 
		alert("Mês "+month+" não tem 31 dias!") 
		return false 
	} 

	if (month == 2) { // check for february 29th 
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); 
		if (day>29 || (day==29 && !isleap)) { 
			alert("Fevereiro " + year + " não tem " + day + " dias!"); 
			return false; 
		} 
	} 
	return true; // date is valid 
} 


function formatCurrency(num) { 
	num = num.toString().replace(/\$|\./g,''); 
	num = num.toString().replace(/\$|\,/g,'.'); 
	if(isNaN(num)) num = "0"; 
	cents = Math.floor((num*100+0.5)%100); 
	num = Math.floor(num).toString(); 
	if(cents < 10) cents = "0" + cents; 
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) 
		num = num.substring(0,num.length-(4*i+3))+'.'+num.substring(num.length-(4*i+3)); 
	return (num + ',' + cents); 
} 


function valorCurrency(num) { 
	num = num.toString().replace(/\$|\./g,''); 
	num = num.toString().replace(/\$|\,/g,'.'); 
	valor = parseFloat(num); 
	return valor; 
} 


function roundOff(value, precision) { 
	value = "" + value //convert value to string 
	precision = parseInt(precision); 
	var whole = "" + Math.round(value * Math.pow(10, precision)); 
	var decPoint = whole.length - precision; 
	if(decPoint != 0) { 
		result = whole.substring(0, decPoint); 
		result += "."; 
		result += whole.substring(decPoint, whole.length); 
	} else { 
		result = whole; 
	} 
	return result; 
} 

function validaCartaoCredito(cardNumber, cardType) {
  cardType = cardType.toLowerCase();
  var isValid = false;
  var ccCheckRegExp = /[^\d ]/;
  isValid = !ccCheckRegExp.test(cardNumber);

  if (isValid)
  {
    var cardNumbersOnly = cardNumber.replace(/ /g,"");
    var cardNumberLength = cardNumbersOnly.length;
    var lengthIsValid = false;
    var prefixIsValid = false;
    var prefixRegExp;

    switch(cardType)
    {
      case "mastercard":
        lengthIsValid = (cardNumberLength == 16);
        prefixRegExp = /^5[1-5]/;
        break;

      case "visa":
        lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
        prefixRegExp = /^4/;
        break;

      case "amex":
        lengthIsValid = (cardNumberLength == 15);
        prefixRegExp = /^3(4|7)/;
        break;
      case "dinners":
        lengthIsValid = (cardNumberLength == 14);
        prefixRegExp = /^3/;
        break;
      case "dinners":
        lengthIsValid = (cardNumberLength == 17);
        prefixRegExp = /^5/;
        break;

	default:
        prefixRegExp = /^$/;
    }

    prefixIsValid = prefixRegExp.test(cardNumbersOnly);
    isValid = prefixIsValid && lengthIsValid;
  }

  if (isValid)
  {
    var numberProduct;
    var numberProductDigitIndex;
    var checkSumTotal = 0;

    for (digitCounter = cardNumberLength - 1; 
      digitCounter >= 0; 
      digitCounter--)
    {
      checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
      digitCounter--;
      numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
      for (var productDigitCounter = 0;
        productDigitCounter < numberProduct.length; 
        productDigitCounter++)
      {
        checkSumTotal += 
          parseInt(numberProduct.charAt(productDigitCounter));
      }
    }

    isValid = (checkSumTotal % 10 == 0);
  }

  return isValid;
}

