// Arquvo temporário, para se obter referência das funções de formatação de campos
// através de máscaras de valores.
//------------------------------------------------------------------------------------

/*
*	variavel com a cor que será mostrada nos campos quando os mesmos ganharem o foco
*/
	var inputColor = '#C0D5E9';
	var chrValidoAlfa = 'abcdefghijklmnopqrstuvwxyz';
	var chrValidoDigito = '0123456789';
	var chrValidoBinario = '01';
	var chrValidoEmail = chrValidoAlfa + chrValidoDigito + '@._-';
	var chrValidoListaEmail = chrValidoAlfa + chrValidoDigito + '@._-,; ';
	var chrValidoNumero = chrValidoDigito + ',.';
	var chrValidoCodigo = chrValidoNumero + '/-';
	var chrValidoFone = chrValidoDigito + '-() ';
	var chrValidoData = chrValidoDigito + '/';
	var chrValidoHora = chrValidoDigito + ':';
	var chrValidoDatahora = chrValidoDigito + '/:';
	var chrValidoConta = chrValidoDigito + 'Xx';

function trocaCheckboxes(oCheck){    
    todos = document.getElementsByTagName('input');    
    // Limpa todos os Checkbox.    
    for(x = 0; x < todos.length; x++) {
        if(todos[x].checked){
            todos[x].checked = false;
        }
    }
    //Seta o selecionado.
    oCheck.checked = true;
}

function JsConfirmacao(msg){
	if (confirm (msg))
		return true;
	else
		return false;
}

function remote(link){
        largura = 800;
        altura = 590;
        if(screen.width != 800){
         meiox = (screen.width-largura)/2;
         meioy = (screen.height-altura)/2;
        }
        else{
         meiox = (screen.width-largura)/2;
         meioy = 0;
        }

        win=window.open(''+ link +'','','width='+largura+',height='+altura+',top='+meioy+',left='+meiox+',scrollbars=yes,resizable=yes,status=yes');
        text = "Programa bloqueador de pop-ups!\nObservacao » O windows XP service pack 2\nbloqueia os pop-ups!";
        if(win == null) { alert(text); return; }

}

function criaMascara(_RefObjeto,_Modelo){
    var valorAtual = _RefObjeto.value;
    var valorNumerico = '';
    var nIndexModelo = 0;
    var nIndexString = 0;
    var valorFinal = '';
    var adicionarValor = true;
    for (i=0;i<_Modelo.length;i++){
      if (_Modelo.substr(i,1) != '#'){
          valorAtual = valorAtual.replace(_Modelo.substr(i,1),'');
      }
        }
    for (i=0;i<valorAtual.length;i++){
      if (!isNaN(parseFloat(valorAtual.substr(i,1)))){
          valorNumerico = valorNumerico + valorAtual.substr(i,1);
      }
        }
    for (i=0;i<_Modelo.length;i++){
      if (_Modelo.substr(i,1) == '#'){
        if (valorNumerico.substr(nIndexModelo,1) != ''){
          valorFinal = valorFinal + valorNumerico.substr(nIndexModelo,1);
          nIndexModelo++;nIndexString++;
        }
        else {
          adicionarValor = false;
        }
      }
      else {
        if (adicionarValor && valorNumerico.substr(nIndexModelo,1) != ''){
                valorFinal = valorFinal + _Modelo.substr(nIndexString, 1)
           nIndexString++;
        }
          }
    }
                _RefObjeto.value = valorFinal
}

function JsConfirma(msg)
{
	if (confirm (msg))
	{
		return true;
	}
	else
	{
		return false;
	}
}	
function validaTecla(campo, event)
{
  var BACKSPACE=8;
  var VIRGULA = 44;
  var MENOS = 45;
  var key;
  var tecla;
  CheckTAB=true;
  if(navigator.appName.indexOf("Netscape")!= -1) {
    tecla= event.which;
  } else {
    tecla= event.keyCode;
  }
  key = String.fromCharCode(tecla);
  if ( tecla == 13) {
    return false;
  }
  if (tecla == BACKSPACE || tecla == 0 || (tecla == VIRGULA &&
campo.value.indexOf(',') == -1 && campo.value.length > 0) || (tecla ==
MENOS && campo.value.length == 0))
    return true;
  if (isNum(key))
    return true;
  return false;
} 

/*
 * Verifica se o caracter informado é um número.
 * Retorna true ou false. 
 */
function isNum(caractere){
  var strValidos = "0123456789";
  if (strValidos.indexOf(caractere) == -1) 
  return false;
  return true;
}

/*
 * Mascara para campo tipo data , apenas para o dia.
 * Se o numero for maior que 31 ou menor que 1 exclui o último caracter do campo. 
 * Exemplo = onKeyUp="mascaraDia(this);"
*/
function mascaraDia(obj){
	mascara(obj,'numero');
	if(obj.value > 31 || obj.value < 1){
		if(obj.value.length > 1){
			auxValor = ''+obj.value;
			obj.value = auxValor.substring(0,1);
		}else{
			obj.value = "";
		}
	}
}

/*
 * Recebe um obj.
 * Exclui o último caracter digitado do valor do objeto. 
*/
function excluiUltCaracter(obj){
	valor = ''+obj.value;
	obj.value = valor.substring(0,((valor.length)-1));
}

/*
 * Mascara para campo tipo data , apenas para o mes.
 * Se o numero for maior que 12 ou menor que 1 exclui o último caracter do campo. 
 * Exemplo = onKeyUp="mascaraMes(this);"
*/
function mascaraMes(obj){
	mascara(obj,'numero');
	if(obj.value > 12 || obj.value < 1){
		if(obj.value.length > 1){
			auxValor = ''+obj.value;
			obj.value = auxValor.substring(0,1);
		}else{
			obj.value = "";
		}
	}
}

/*
 * Mascara para campo tipo percentual.
 * Só aceita números, ponto e virgula. Transforma os pontos em virgula
 * é aceito somente uma virgula.
 * Exemplo = onKeyUp="mascaraPercentual(this);"
*/
function mascaraPercentual(obj){
	var strValidos = "0123456789,.";
	var ultCarac = ''+obj.value;
	ultCarac = ultCarac.substring(((ultCarac.length)-1),ultCarac.length);
	if(strValidos.indexOf(ultCarac) > -1 ){ 
		
		valor = obj.value;
		valor = valor.replace(",",".");
		valor = parseFloat(valor);	
		if(valor > 100){
			tot = obj.value.length;
			tot = parseInt(tot) - 1;
			texto = ''+valor;
			texto = texto.substring(0,tot);
			texto = texto.replace(".","");
			obj.value = texto;
			for(x=0;x<obj.value.length;x++){
				if(parseInt(obj.value) > 100){
					tot = obj.value.length;
					tot = parseInt(tot) - 1;
					texto = ''+valor;
					texto = texto.substring(0,tot);
					texto = texto.replace(".","");
					obj.value = texto;
				}
			}
			
		}else{
			for(x=0;x<obj.value.length;x++){
				texto = obj.value;
				texto = texto.replace(".",",");
				obj.value = texto;
			}
		}
		virgulas = new Array();
		for(x=0;x<obj.value.length;x++){
			virgulas = texto.split(",");
			if(parseInt(virgulas.length-1) > 1){
				tot = obj.value.length;
				tot = parseInt(tot) - 1;
				texto = texto.substring(0,tot);
				obj.value = texto;
			}
		}
		if(parseInt(virgulas.length-1) > 1){
				tot = obj.value.length;
				tot = parseInt(tot) - 1;
				texto = texto.substring(0,tot);
				obj.value = texto;
		}
	}else{
		excluiUltCaracter(obj);
	
	}
}

function formataValor(campo,tammax,teclapres) {
 	var tecla = teclapres.keyCode;

 	vr = campo.value;
 	vr = vr.replace( "/", "" );
 	vr = vr.replace( "/", "" );
 	vr = vr.replace( ",", "" );
 	vr = vr.replace( ".", "" );
 	vr = vr.replace( ".", "" );
 	vr = vr.replace( ".", "" );
 	vr = vr.replace( ".", "" );
 	tam = vr.length;

 	if(tam < tammax && tecla != 8){
 		//tam = vr.length + 1 ;
 		tam = vr.length;
 	}

	if(tecla == 8 ){
		tam = tam - 1 ;
	}

	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if( tam <= 2 ){
			campo.value = vr;
		}
		if( (tam > 2) && (tam <= 5) ){
			campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam );
		}
		if( (tam >= 6) && (tam <= 8) ){
			campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
		}
		if ( (tam >= 9) && (tam <= 11) ){
			campo.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
		}
		if ( (tam >= 12) && (tam <= 14) ){
			campo.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
		}
		if ( (tam >= 15) && (tam <= 17) ){
			campo.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
		}
	}
} 


/**
 * Cria uma máscara para valores numericos
 *
 * Ex.: mascara para datas
 * <input type="text" name="modelo_4" OnKeyUp="criaMascara(this, '##/##/####');">
 *
 */
 
 
function criaMascara(_RefObjeto, _Modelo){
	var valorAtual = _RefObjeto.value;
	var valorNumerico = '';
	var nIndexModelo = 0;
	var nIndexString = 0;
	var valorFinal = '';
	var adicionarValor = true;

	//alert (valorAtual);

	// limpa a string valor atual para verificar
	// se todos os caracteres são números
	for (i=0;i<_Modelo.length;i++){
		if (_Modelo.substr(i,1) != '#'){
			valorAtual = valorAtual.replace(_Modelo.substr(i,1),'');
		}
	}

	// verifica se todos os caracteres são números
	for (i=0;i<valorAtual.length;i++){
		if (!isNaN(parseFloat(valorAtual.substr(i,1)))){
			valorNumerico = valorNumerico + valorAtual.substr(i,1);
		}
	}

	// aplica a máscara ao campo informado usando
	// o modelo de máscara informado no script
	for (i=0;i<_Modelo.length;i++){
		if (_Modelo.substr(i,1) == '#'){
			if (valorNumerico.substr(nIndexModelo,1) != ''){
				valorFinal = valorFinal + valorNumerico.substr(nIndexModelo,1);
				nIndexModelo++;nIndexString++;
			} else {
				adicionarValor = false;
			}
		} else {
			if (adicionarValor && valorNumerico.substr(nIndexModelo,1) != ''){
				valorFinal = valorFinal + _Modelo.substr(nIndexString,1)
				nIndexString++;
			}
		}
	}

_RefObjeto.value = valorFinal;

}

function parteFracao(resto) {
// Descrição: Requerida pela função formatoMonetario. Retorna a parte fracionária.
	 resto = Math.round( ( (resto) - Math.floor(resto) ) *100);
	 return (resto < 10 ? ',0' + resto : ',' + resto)};

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.
// 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.
// 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
// retornaFormatoMonetario("12345") -> 12.345,00
// retornaFormatoMonetario("12.345") -> 12,35
// retornaFormatoMonetario("12,345") -> NaN,NaN
// retornaFormatoMonetario("0",0) ->
// retornaFormatoMonetario("") ->
// retornaFormatoMonetario("0",1) -> 0,00
// retornaFormatoMonetario("0",true) -> 0,00
// retornaFormatoMonetario("0",false) ->
	 if((valor-0) != 0 || (tipo == 1 && (valor-0) == 0) ) {
		return parteInteira(Math.floor(valor-0) + '') + parteFracao(valor-0);
	}
	else return '';
}

function retornaFormatoMonetarioInteiro(valor) {
// Descrição: Retorna o parâmetro 'valor' formatado como um valor monetário inteiro.
// 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.
	 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 validaLengthData(oque,tipo){
// 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'
	switch (tipo) {
	/********************************************************************
	Completa o campo com zeros do cartao
	********************************************************************/
		case 'visa':
		{
			if(oque.value == '')
				return true;
			var StringVisa = limpaParaMascara(oque.value,'numeros');
			if(StringVisa.length < 16)
			{
				oque.value = limpaParaMascara(oque.value,'numeros');
				oque.value = incluiZerosAEsquerda(oque.value,16);
				if(digitoVisa(oque) != 1)
				{
					mascara(oque,'cartao');
					alert("Número do cartão inválido")
					oque.value = "";
					oque.focus();
					return false;
				}
				mascara(oque,'cartao',16);
			}
			return true;
			break;
		}
	/********************************************************************
	Completa o campo da Conta Corrente com zeros a direita e testa a CC
	********************************************************************/
		case 'cc': {
			if(oque.value == ''){
				return true;
			}
			retorno = '';
			retorno = limpaParaMascara(oque.value,'numeros');
			 if(retorno.length < 11) {
				zeros = '00000000000';
				retorno = retorno + zeros.substr(0,(11-retorno.length));
				oque.value = retorno;
				mascara(oque,'cc');
			}
			if(!isContaCorrente(limpaParaMascara(oque.value,'numeros'))) {
				alert(oque.value+"\n"+"Conta Corrente inválida.");
				oque.value = "";
				oque.focus();
				return false;
			}
			return true;
			break;
		}
		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) {
				alert(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(!validaCPF(retorno)) {
					alert(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)) {
					alert(oque.value+"\n"+"CNPJ inválido.");
					oque.value="";
					oque.focus();
					return false;
				}
			};
			break;
		}
	}
	return true;
}

function mascara(oque,tipo,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.
// tipos: cep,cpf,cgc,cnpj10,ddd,ramal,fone,celular,DD/MM/AA,DD/MM/AAAA,MM/AAAA,IE,caracter,numero,valor,percentual,cartao,cc,poupanca,unidade
// Exemplo: onKeyUp="mascara(this,'cep');"
// Exemplo: onKeyUp="mascara(this,'valor',13,2);"
// Exemplo: onKeyUp="mascara(this,'valor',13,2,1);"
	if( (event.keyCode == 8) || (event.keyCode == 13) || (event.keyCode == 37) || (event.keyCode == 39) || (event.keyCode == 46) || (event.keyCode == 16))
	{
		return;
	}

	if(tamanho1 != null) {tamanho1 = parseInt(tamanho1);}
	if(tamanho2 != null) {tamanho2 = parseInt(tamanho2);}

	retorno = '';
	switch (tipo) {
		case 'cep':
		{ // 99999-999
			oque.maxLength=9;
			retorno = limpaParaMascara(oque.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.");
				oque.value="";
				oque.focus();
				return;
			}
			if(retorno.length >= 5) { retorno = retorno.substr(0,5)+"-"+retorno.substr(5,7); }
			oque.value = retorno.substr(0,9);
			break;
		}
		case 'cpf':
		{  // 999.999.999-99
			oque.maxLength=14;
			retorno = limpaParaMascara(oque.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);}

			oque.value = retorno.substr(0,14);

			if(retorno.length >= 14) {
				if(!validaCPF(retorno))
				{
					alert(oque.value+"\n"+"CPF inválido.");
					oque.value="";
					oque.focus();
					return;
				}
			}
			break;
		}
		case 'cgc':
		{  // 99.999.999/9999-99
			oque.maxLength=18;

			retorno = limpaParaMascara(oque.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); }

			oque.value = retorno.substr(0,18);

			if(retorno.length >= 18)
			{
				if(!validaCGC(retorno))
				{
					alert(oque.value+"\n"+"CNPJ inválido.");
					//oque.value="";
					oque.focus();
					return;
				}
			}
			break;
		}

		case 'cnpj10':
		{  // 999.999.99
			oque.maxLength=10;
			retorno = limpaParaMascara(oque.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); }
			oque.value = retorno.substr(0,10);
			break;
		}

		case 'ddd': {  // 9999
			oque.maxLength=4;
			retorno = limpaParaMascara(oque.value,'numeros');
			retorno = retorno.substr(0,4);
			if(retorno.length >= 4 && (retorno-0 == 0) )  {
				alert("O DDD não pode ser "+retorno+".");
				oque.value="";
				oque.focus();
				return;
			}
			oque.value = retorno.substr(0,4);
		break;	}

		case 'ramal': {  // 9999
			oque.maxLength=4;
			retorno = limpaParaMascara(oque.value,'numeros');
			oque.value = retorno.substr(0,4);
		break;	}

		case 'fone': {  // 9999999999
			oque.maxLength=10;
			retorno = limpaParaMascara(oque.value,'numeros');
			//if(retorno.length >= 3)  { retorno = retorno.substr(0,3)+"."+retorno.substr(3); }
			oque.value = retorno.substr(0,10);
		break;	}

		case 'celular': {  // 9999999999
			oque.maxLength=10;
			retorno = limpaParaMascara(oque.value,'numeros');
			//if(retorno.length >= 4)  { retorno = retorno.substr(0,4)+"."+retorno.substr(4); }
			oque.value = retorno.substr(0,10);
		break;	}

		case 'DD/MM/AA':
		{  // 99/99/99
			oque.maxLength=8;
			retorno = limpaParaMascara(oque.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); }

			oque.value = retorno.substr(0,8);

			if(retorno.length >= 8)
			{
				dataEmTeste = retorno.substr(0,6)+'20'+retorno.substr(6,2) ;
				if(!retornaValidaData(dataEmTeste))
				{
					oque.value="";
					oque.focus();
					return;
				}
			}
			break;
		}

		case 'DD/MM/AAAA':
		{  // 99/99/9999
			oque.maxLength=10;
			retorno = limpaParaMascara(oque.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);
			}

			oque.value = retorno.substr(0,10);

			if(retorno.length >= 10)
			{
				if(!retornaValidaData(oque.value))
				{
					//oque.value="";
					oque.focus();
					return;
				}
			}
			break;
		}

		case 'MM/AAAA': {  // 99/9999
			oque.maxLength=7;
			retorno = limpaParaMascara(oque.value,'numeros');
			if(retorno.length >= 2) { retorno = retorno.substr(0,2)+"/"+retorno.substr(2); }
			oque.value = retorno.substr(0,7);
			if(retorno.length >= 7) {
				dataEmTeste = '01/'+retorno
				if(!retornaValidaData(dataEmTeste)) {
					oque.value="";
					oque.focus();
					return;
				}
				}
		break;	}

		case 'IE':
		{  // AAAAAAAAAAAAAA
			oque.maxLength=14;
			//retorno = limpaParaMascara(oque.value,'numeros');
			//if(retorno.length >= 3) { retorno = retorno.substr(0,3)+"/"+retorno.substr(3); }
			//oque.value = retorno ;
			break;
		}

		case 'caracter':
		{
			break;
		}

		case 'numero':
		{
			if(tamanho1 != null)
			oque.maxLength = tamanho1;
			retorno = limpaParaMascara(oque.value,'numeros');
			oque.value = retorno.substr(0,oque.maxLength);
			break;
		}

		case 'valor':
		{
			if( (tamanho1 != null) && (tamanho2 != null) )
			{
				if(tamanho2 == 0)
				{
					oque.maxLength = tamanho1;
				}
				else
				{
					oque.maxLength = tamanho1+1+tamanho2;
				}
			}

			retorno = limpaParaMascara(oque.value,'valores',sinal);
			retorno = limpaZerosAEsquerda(retorno,sinal);
			posicaoPrimeiraVirgula = retorno.indexOf(",");
			retorno = limpaParaMascara(retorno,'numeros',sinal);

			if(posicaoPrimeiraVirgula > -1)
			{
				retorno = retorno.substr(0,posicaoPrimeiraVirgula)+","+retorno.substr(posicaoPrimeiraVirgula,2);
			};

			oque.value = retorno.substr(0,oque.maxLength);

			break;
		}
		
		case 'valorDolar':
		{
			if( (tamanho1 != null) && (tamanho2 != null) )
			{
				if(tamanho2 == 0)
				{
					oque.maxLength = tamanho1;
				}
				else
				{
					oque.maxLength = tamanho1+1+tamanho2;
				}
			}

			retorno = limpaParaMascara(oque.value,'valores',sinal);
			retorno = limpaZerosAEsquerda(retorno,sinal);
			posicaoPrimeiraVirgula = retorno.indexOf(",");
			retorno = limpaParaMascara(retorno,'numeros',sinal);

			if(posicaoPrimeiraVirgula > -1)
			{
				retorno = retorno.substr(0,posicaoPrimeiraVirgula)+","+retorno.substr(posicaoPrimeiraVirgula,tamanho2);
			};

			oque.value = retorno.substr(0,oque.maxLength);

			break;
		}

		case 'percentual': {  // 999
			oque.maxLength=3;
			retorno = limpaParaMascara(oque.value,'numeros');
			oque.value = retorno.substr(0,3);
		break;	}

		case 'cartao': {  // 9999 9999 9999 9999
			oque.maxLength=19;
			retorno = limpaParaMascara(oque.value,'numeros');
			if(retorno.length >= 4) { retorno = retorno.substr(0,4)+" "+retorno.substr(4); }
			if(retorno.length >= 9) { retorno = retorno.substr(0,9)+" "+retorno.substr(9); }
			if(retorno.length >= 14) { retorno = retorno.substr(0,14)+" "+retorno.substr(14); }
			oque.value = retorno.substr(0,19);
		break;	}

		case 'cc': {  //  9999-99999-99
			oque.maxLength=13;
			retorno = limpaParaMascara(oque.value,"numeros");
			if(retorno.length >= 4) { retorno = retorno.substr(0,4) + "-" + retorno.substr(4); }
			if(retorno.length >= 10) { retorno = retorno.substr(0,10) + "-" + retorno.substr(10); }
			oque.value = retorno.substr(0,13);
		break;	}

		case 'poupanca': {  //  9999-999999-9
			oque.maxLength=13;
			retorno = limpaParaMascara(oque.value,"numeros");
			if(retorno.length >= 4) { retorno = retorno.substr(0,4) + "-" + retorno.substr(4); }
			//alert(retorno);
			if(retorno.length >= 11) { retorno = retorno.substr(0,11) + "-" + retorno.substr(11); }
			oque.value = retorno.substr(0,13);
		break;	}

		case 'unidade': { // 99999-99
			oque.maxLength=8;
			retorno = limpaParaMascara(oque.value,"numeros");
			if(retorno.length >= 5) { retorno = retorno.substr(0,5) + "-" + retorno.substr(5); }
			oque.value = retorno.substr(0,8);
		break; }
	}
}

function validaCPF(CPF) {
// Descrição : Função de validação de CPF.
	 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.
	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 chk_CPF(ti) {
// Descrição: Função de checar validação de CPF.
	if(!validaCPF(ti.value)) {
		alert("CPF inválido.");
		if(!ti.disabled) {
			ti.focus();
			ti.select();
		}
		return false;
	}
	return true;
}

function chk_CGC(ti) {
// Descrição: Função de checar validação de CGC.
	if(!validaCGC(ti.value)) {
		alert("CGC inválido.");
		if(!ti.disabled) {
			ti.focus();
			ti.select();
		}
		return false;
	}
	return true;
}

function calcMod11(field,start, finish) {
// Descrição : Cálculo do Módulo 11. Requerida pela validação de CGC.
	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 limpaCampo(field) {
// Descrição: Função para extrair caracteres indesejados de um campo. ( . - / , )
// limpaCampo("1.23/45,abc") -> 12345abc
t_field='';
	for (i=0;i<field.length;i++) {
		if( (field.charAt(i) != ".") && (field.charAt(i) != "-") && (field.charAt(i) != "/") && (field.charAt(i) != ",")) {
			t_field = t_field + field.charAt(i);
		}
	}
return t_field;
}

function formataCPF(paramCpf) {
// Descrição: Função de máscara para CPF
// 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.
// 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.
	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( falhou ) {
		  alert("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
// Exemplo: if(dataValida(document.form.txtData.value,'anterior')) {alert("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') {
		alert("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 '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) {
// Descrição: Recebe o value da data e retorna true se é data válida ou false caso contrário.
	falhou = false;
	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;
	if( falhou ) {
		return false;
	 }
	else
		return true;
}
function retornaValidaDataMes(t_data) {
// Descrição: Recebe o value da data tipo 'MM/AAAA' e retorna true se é data válida ou false caso contrário.
					if(t_data == ""){
							return false;
					}else{
									mes = ''+t_data;
									datas = new Array();
									achou = mes.indexOf("/");
									if(achou != -1){
										datas = mes.split("/");
										//mes = parseInt(mes.substring(0,2));
										mes = datas[0];
										ano = datas[1];
										//ano = parseInt(ano.substring(3,7));
										if(mes < 1 || mes > 12){
											return false;
										}else{
											if(ano.length < 4){
												return false;
											}
										} 
									}else{
										return false;									
									}
								
				}
				return true;
}
function desabilitaCampo(str) {
	arrDesabilita = new Array();
	arrDesabilita = str.split(",")
	for (i=0; i<arrDesabilita.length; i++) {
		obj = eval("document.form."+arrDesabilita[i])
		if(obj != null) {
		obj.disabled = true;
//			 obj.style.backgroundColor = "#E0E0E0";
		}
	}
}

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.
// 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('0','numeros') -> 0
//  ******
//  Filtros:
	numeros = "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 && 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;	}
	}
	if(tipo == 1) {
		if(sujeira.substring(0,1) == "-") retorno2 = "-" + retorno2;
	}
	return retorno2;
}
function limpaZerosAEsquerda(inputString,tipo) {
// Descrição: Retira 'zeros' à esquerda do 'inputString' (usar tipo = 1 para permitir zero)
// 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) != "-" && 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 rangeOk(val, inf, sup, tipo){
// Descrição: verifica se um valor pertence a uma faixa.
// val -> valor a ser verificado;
// sup -> limite superior da faixa a ser verificada;
// inf -> limite inferior da faixa a ser verificada;
// tipo -> tipo de teste: valor, data

	var retorno = false;

	if(tipo == null)
		{ tipo = 'valor';}

	switch (tipo)
	{
		case 'valor':
		{
			if(typeof(val) == 'string') val = strToNum(val);
			if(typeof(sup) == 'string') sup = strToNum(sup);
			if(typeof(inf) == 'string') inf = strToNum(inf);

			if((inf == 0) && !(sup == 0)){
				retorno = (val <= sup);
			}
			else if(!(inf == 0) && (sup == 0)){
				retorno = (val >= inf);
			}
			else if(!(inf == 0) && !(sup == 0)){
				retorno = ((val <= sup) && (val >= inf));
			}
			else if((inf == 0) && (sup == 0)){
				retorno = true;
			}

			break;
		}
		case 'data':
		{
			retorno = ((val <= sup) && (val >= inf));
			break;
		}
	}

	return retorno;
}

function addDays(data, dias){
//Descrição: adiciona dias a data informada
//data -> data inicial;
//dias -> nro de dias a serem adicionados;
	var base, ret;

	data.setHours(0);
	data.setMinutes(0);
	data.setSeconds(0);
	data.setMilliseconds(0);
	base = data.getTime();

	ret = new Date(base+(24*60*60*1000*dias));

	return ret;
}

function addYears(data, anos){
//Descrição: adiciona anos a data informada
//data -> data inicial;
//anos -> nro de anos a serem adicionados;
	var dia, mes, ano, ret;

	dia = data.getDate();
	mes = data.getMonth();
	ano = data.getFullYear();
	ret = new Date((ano+anos), mes, dia);

	return ret;
}

function addMonths(data, meses){
//Descrição: adiciona meses a data informada.
//data -> data inicial
//meses -> nro de meses a serem adicionados;
	var dia, mes, ano, ret, skipYears;

	dia = data.getDate();
	mes = data.getMonth();
	ano = data.getFullYear();

	mes = mes + meses;
	skipYears = floor(mes/12);

	skipMonths = mes - (12*skipYears);

	ret = new Date((ano+skipYears), skipMonths, dia);

	return ret;
}

function strToDate(str){
//Descrição: retorna um objeto date a partir de uma string
//str -> string a ser transformada, no formato DD/MM/AAAA

	var dia, mes, ano, ret;

	dia = str.substr(0,2);
	mes = str.substr(3,2) - 1;
	ano = str.substr(6,4);

	ret = new Date(ano, mes, dia, 0, 0, 0, 0);

	return ret;
}

function dateToStr(data){
//Descrição: retorna uma string a partir de um objeto Date numa string no formato DD/MM/AAAA
//data -> objeto date a ser transformado

	if(data == null){
		data = new Date();
	}

	d = data.getDate();
	d = (d<10?'0'+d:d);

	m = (data.getMonth()+1);
	m = (m<10?'0'+m:m);

	a = data.getFullYear()

	return (d+"/"+m+"/"+a)
}

function addDays(data, dias){
//Descrição: adiciona dias a data informada
//data -> data inicial;
//dias -> nro de dias a serem adicionados;
	var base, ret;

	data.setHours(0);
	data.setMinutes(0);
	data.setSeconds(0);
	data.setMilliseconds(0);
	base = data.getTime();

	ret = new Date(base+(24*60*60*1000*dias));

	off = ret.getTimezoneOffset() - data.getTimezoneOffset();

	diasMilli = (24*60*60*1000*dias)+(60*1000*off);

	ret = new Date(base+diasMilli);

	return ret;
}

function emFoco(obj, bg){
	obj.style.backgroundColor = bg;
}

//Descricao: formata um valor numerico
//valor -> valor a ser formatado
//d -> numero de casas decimais. default = 2
function retornaValorFormatado(valor, d){
	var deci;
	var inteiro;
	var retorno = '-';

	deci = '';

	if(!isNaN(valor))	{
		if(valor.indexOf('.') >= 0) {
			inteiro = valor.substr(0, valor.indexOf('.'));
			deci = valor.substr(valor.indexOf('.')+1);

		} else {
			inteiro = valor;
		}

		inteiro = retornaFormatoMonetarioInteiro(inteiro);

		if(typeof(d)=='undefined'){
			d = 2;
		}

		while(deci.length < d) {
			deci = deci + '0';
		}

		if (deci=='') {
			retorno = inteiro;
		} else {
			retorno = (inteiro+','+deci);
		}
	}

	return retorno;
}

function ajuda(paghelp){
	helpWin=window.open(paghelp,"Ajuda","width=500,height=400,top=25,left=10,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,status=no,location=no")
}

function testaData(oque){
	if((oque.value == '') || (oque.value == '00/00/0000')){ return; }

	var valida = retornaValidaData(oque.value);

	if(valida){
		oque.value = limpaCampo(oque.value);
		oque.value = oque.value.substr(0,2)+'/'+oque.value.substr(2,2)+'/'+oque.value.substr(4,4);

	} else {
		alert('Data Inválida!!');
		oque.focus();
		oque.select();
	}
}

function testaValor(oque, deci) {

	var strA;
	strA = String(oque.value);

	strA = String(strA.replace(/\./g,""));
	strA = String(strA.replace(/\,/g,"."));

	if (strA.indexOf('.') == -1) {
		inteiro = strA;
		decimal = '';
	} else {
		aString = strA.split('.');
		inteiro = aString[0];
		decimal = aString[1];
	}

	if(isNaN(deci)) {
		deci = 2;
	}

	for (i=decimal.length+1; i<=deci; i++) {
		decimal = decimal+'0';
	}

	if(oque.value == '') {
		if (deci > 0) {
			oque.value = '0,'+decimal;
		} else {
			oque.value = '0';
		}
	} else {
		if(isNaN(parseFloat(strA))) {
			alert('Valor Inválido!!');
			oque.focus();
			oque.select();
		} else {
			if (deci > 0) {
				oque.value = retornaValorFormatado(inteiro, 0)+','+decimal.substr(0, deci);
			} else {
				oque.value = retornaValorFormatado(inteiro, 0);
			}
		}
	}
}

function testaValorDolar(oque, deci) {

	var strA;
	strA = String(oque.value);

	strA = String(strA.replace(/\./g,""));
	strA = String(strA.replace(/\,/g,"."));

	if (strA.indexOf('.') == -1) {
		inteiro = strA;
		decimal = '';
	} else {
		aString = strA.split('.');
		inteiro = aString[0];
		decimal = aString[1];
	}

	if(isNaN(deci)) {
		deci = 2;
	}

	for (i=decimal.length+1; i<=deci; i++) {
		decimal = decimal;
	}

	if(oque.value == '') {
		if (deci > 0) {
			oque.value = '0,'+decimal;
		} else {
			oque.value = '0';
		}
	} else {
		if(isNaN(parseFloat(strA))) {
			alert('Valor Inválido!!');
			oque.focus();
			oque.select();	
		} else {
			if (deci > 0) {
				oque.value = retornaValorFormatado(inteiro, 0)+','+decimal.substr(0, deci);
			} else {
				oque.value = retornaValorFormatado(inteiro, 0);
			}
		}
	}
}

function limpaCampos(idForm) {

	var searchStr = new RegExp('\x160', 'g');
	for(i=0;i<idForm.length;i++)
	{
		idForm.elements[i].value = '';
	}
}

/*
	Sincroniza um objeto checkbox com um outro campo qquer

	objCheck  = Objeto checkbox a ser sincronizado
	objToSinc = Objeto que ira receber o valor
*/
function sincCheckBox(objCheck, objToSinc)
{
	objToSinc.value = ((objCheck.checked)?'S':'N');
}


/*
	Dados 2 valores calcula o percentual q V1 representa de V2
*/
function calcPercent(val1, val2)
{
	ret = 0.00;

	v1  = strToNum(val1);
	v2  = strToNum(val2);

	ret = (v1/v2)*100;

	return ret;
}

/*
*	Converte uma string formatada em valor numerico
*/
function strToNum(str) {
	num = "-0123456789";
	ret = "";
	if ((str == '') || (str.charCodeAt(0) == 160)) {
		ret = '0';
	}
	else
	{
		if (str.indexOf(',') > -1)
		{
			for (i=0; i<str.length; i++)
			{
				if (num.indexOf(str.charAt(i)) > -1)
				{
					ret += str.charAt(i);
				}
				else if ((str.charAt(i) == ','))
				{
					ret += '.';
				}
			}
		}
		else
		{
			return parseFloat(str);
		}
	}
	return parseFloat(ret);
}


/*
 * variavel que da um confirm
*/
	var confirm40anos = false; 
	
/*
 * variavel que verifica se ja foi dados um submit
*/
	var buscando = false; 
	
/*
 * variavel q verifica se há alguma validacao externa a ser feita
*/	
	var validacao = false; 
	
/*
 * Array com os nomes dos campos a serem validados
*/	
	var obrigatorios = new Array(); 
	
/*
 * Array com os nomes que apareceram no alert caso estejam invalidos
*/	
	var nomesObrigatorios = new Array(); 
	
/*
 * Array com os tipos dos campos. ex: data, literal, cpf, etc...
*/	
	var tipoObrigatorios = new Array(); 

/*
*	Descrição : pega todos os campos contidos no array obrigatorios e os valida
*   a cada obrigatorio valida conforme o seu tipo. Se o campo não estiver correto
*	Uma mensagem contendo o nome do campo sera concatenada numa string, que ao final 
*	será dado um alert com todos os campos inválidos.
*
*	Exemplo: obrigatorios("des_cli","cd_cli","nm_ger","dt_vencto");
*		 nomesObrigatorios("Descricao Cliente","Cód Cliente","Nome Gerente","Data Vencto");
*		 tipoObrigatorios("literal","numero","literal","data");
*
*	Retorno : String formatada com os campos inválidos
*
*/
function verificaObrigatorios(frm){
	var msg = "";
	
	for(x=0;x<obrigatorios.length;x++){
		aux = obrigatorios[x];
		if(aux != undefined || aux != null){
			aux2 = eval("document."+frm+"."+obrigatorios[x]+".value");
			if(aux2 == "" || aux2 == 0){
				msg = msg + "O campo "+nomesObrigatorios[x]+" é obrigatorio.\n";
			}else{
				switch(tipoObrigatorios[x]){
					case 'data':{
						if(!retornaValidaData(aux2)) {
							msg = msg + "A data do campo "+nomesObrigatorios[x]+" é inválida.\n";
						}
					break; }
					case 'dataMes':{	
						if(!retornaValidaDataMes(aux2)) {
							msg = msg + "A data do campo "+nomesObrigatorios[x]+" é inválida.\n";
						}
					break;}
					case 'dataIntervalo':{	
						if(!retornaValidaData(aux2)) {
							msg = msg + "A data do campo "+nomesObrigatorios[x]+" é inválida.\n";
						}
					break;}
					case 'dataIntervaloMes':{	
						if(!retornaValidaDataMes(aux2)) {
							msg = msg + "A data do campo "+nomesObrigatorios[x]+" é inválida.\n";
						}
					break;}
					case 'monetario':{	
						strValidos = "-0123456789.,";
						for(i=0;i<aux2.length;i++){
							caract = aux2.substring(i,i+1);
							if(strValidos.indexOf(caract) < 0){
								msg = msg + "O valor do campo "+nomesObrigatorios[x]+" é inválido.\n";
								break;
							}
						}
					break;}
				}
			}
		}
		
	}
	return msg;
}


/*
 *	Todos os links da pagina receberam '#'
*/
function desabilitaLinks(){
	for(x=0;x<document.links.length;x++){
		document.links[x].href = "#";
	}
}

/*
 *	Todos os campos de todos os formularios serão habilitados
*/
function habilitaCampos(){
	for(i=0;i<document.forms.length;i++){
		for(x=0;x<document.forms[i].length;x++){
			document.forms[i].elements[x].disabled = false;
		}
	}
}


/*
 *	Todos os campos de todos os formularios serão desabilitados
*/
function desabilitaCampos(){
	for(i=0;i<document.forms.length;i++){
		for(x=0;x<document.forms[i].length;x++){
			document.forms[i].elements[x].disabled = true;
		}
	}
}

/*
 *	Limita os caracteres num textarea
 *  ex: onKeyPress = "limitaDescricao(obj, 20, event)"
*/
function limitaTextArea(obj, max, event){
	if(max != ''){
		max = parseInt(max);
		valor = ''+obj.value;
		if(valor.length >= max){
			event.returnValue = false;
		}
	}
}

/*
 *	Esta função é usada nos campos onde não se sabe se é CPF ou CNPJ
 *  Então a função confere quantos digitos tem no valor e coloca a máscara apropriada
 *  ex: onKeyUp = "mascaraCpfCNPJ(this);"
*/
function mascaraCpfCNPJ(obj){
	if(obj.value.length <  15){
 		criaMascara(obj,"###.###.###-##");
 	}else{
 		criaMascara(obj,"##.###.###/####-##");
 	}
}


/*
 * Inicio da função selecionValor(this);
 */
	var tempo;
/*
 * Declaracao da variavel que recebera a funcao de tempo (setTimeout)
 */
 	var auxBusca = ""; 
 /*
 * Declaracao da variavel que recebera os valores digitados pelo usuario 
 * no campo tipo select
 */
 
 /*
 *	Esta função é usada nos campos tipo select
 *  É usada para fazer uma busca por valores, percorre os options e verifica o value
 *  Caso for igual ao valor digitado, seleciona o option.
 *  Exemplo: uma lista de estados, o usuário Digita "b" então "bahia" é selecionada 
 *  ex: onKeyUp="selecionaValor(this);"
*/
function selecionaValor(obj){
		clearTimeout(tempo);
		achou = false;
		maiorOption = 0;
		if(getCharPressed(event) != ""){
			for(x = 0; x < obj.length; x++){
				if(obj.options[x].value.length > maiorOption){
					maiorOption = obj.options[x].value.length;
				}
			}
			auxBusca = auxBusca + getCharPressed(event).toUpperCase();
			for(x = 0; x < obj.length; x++){
				strBus = ''+obj.options[x].text;
				strBus = strBus.substring(0,auxBusca.length);
				if(auxBusca.toUpperCase() == strBus.toUpperCase()){
					obj.options[x].selected = true;
					achou = true;
					break;
				}
			}
			tempo = setTimeout("auxBusca = '';",1500);
		}
		if(!achou || auxBusca.length == maiorOption){
			auxBusca = '';
		}
}

/*
*	fim da função selecionaValor
*/

/*
Função para colocar vírgulas a direita e zeros, preservando a formatação monetária com os pontos
Chamado no onblur
Falta somente controle de zeros à esquerda
*/
function zerosdireita(campo,valor) {
	tamanho = valor.length;
	valor_num = strToNum(valor);
	if(tamanho <= 3 && valor.indexOf(',')<0){
		valor = valor + ",00";
	}
	if(valor.substring(tamanho - 1,tamanho) == ",") {
		valor = valor + "00";
	}
	if(valor.substring(tamanho - 2,tamanho - 1) == ",") {
		valor = valor + "0";
	}
	if(valor.substring(tamanho - 4,tamanho - 3) == ".") {
		valor = valor + ",00";
	}
	if(valor.substring(tamanho - 5,tamanho - 4) == ".") {
		valor = valor.replace( "/", "" );
		valor = valor.replace( "/", "" );
		valor = valor.replace( ",", "" );
		valor = valor.replace( ".", "" );
		valor = valor.replace( ".", "" );
		valor = valor.replace( ".", "" );
		valor = valor.replace( ".", "" );
		tam = valor.length;
		if( tam <= 3 ){
			valor = vr;
		}
		if( (tam > 3) && (tam <= 6) ){
			valor = valor.substr( 0, tam - 3 ) + '.' + valor.substr( tam - 3, tam );
		}
		if( (tam >= 7) && (tam <= 9) ){
			valor = valor.substr( 0, tam - 6 ) + '.' + valor.substr( tam - 6, 3 ) + '.' + valor.substr( tam - 3, tam );
		}
		if ( (tam >= 10) && (tam <= 12) ){
			valor = valor.substr( 0, tam - 9 ) + '.' + valor.substr( tam - 9, 3 ) + '.' + valor.substr( tam - 6, 3 ) + '.' + valor.substr( tam - 3, tam );
		}
		if ( (tam >= 13) && (tam <= 15) ){
			valor = valor.substr( 0, tam - 12 ) + '.' + valor.substr( tam - 12, 3 ) + '.' + valor.substr( tam - 9, 3 ) + '.' + valor.substr( tam - 6, 3 ) + '.' + valor.substr( tam - 3, tam );
		}
		if ( (tam >= 16) && (tam <= 18) ){
			valor = valor.substr( 0, tam - 15 ) + '.' + valor.substr( tam - 15, 3 ) + '.' + valor.substr( tam - 12, 3 ) + '.' + valor.substr( tam - 9, 3 ) + '.' + valor.substr( tam - 6, 3 ) + '.' + valor.substr( tam - 3, tam );
		}
		valor = valor + ",00";
	}

/*	tamanho = valor.length;
	alert("valor inicial: "+valor+"\nTamanho: "+tamanho);
	espacosAntes = 0;
	for(0; i < tamanho ; i++){
		if(valor.charAt(i) == '0' || valor.charAt(i) != '.'){
			espacosAntes++; 
		}
		if(valor.charAt(i) == '.'){
			espacosAntes++; 
		}		
		else{
			break;
		}
	}
	alert("Espaços antes: "+espacosAntes+"\nSubstring: "+valor.substring(espacosAntes,tamanho)+"\nTamanho: "+tamanho);
	valor =  valor.substring(espacosAntes,tamanho);
	alert("Valor final:"+valor);
	//campo.value = limpaZerosAEsquerda(valor);
	*/
	
	campo.value = valor;
	formataValor2(campo);
	if(valor_num == 0) {
		valor = "0,00";
		campo.value = valor;
	}


}

/*
Função para pegar um campo, tirar todas as vírgulas e pontos e formatar para monetário.
Chamado no onblur
*/
function formataValor2(campo) {
 	vr = campo.value;
 	vr = vr.replace( "/", "" );
 	vr = vr.replace( "/", "" );
 	vr = vr.replace( ",", "" );
 	vr = vr.replace( ".", "" );
 	vr = vr.replace( ".", "" );
 	vr = vr.replace( ".", "" );
 	vr = vr.replace( ".", "" );
 	tam = vr.length;
	if( tam <= 2 ){
		campo.value = vr;
	}
	if( (tam > 2) && (tam <= 5) ){
		campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam );
	}
	if( (tam >= 6) && (tam <= 8) ){
		campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
	}
	if ( (tam >= 9) && (tam <= 11) ){
		campo.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
	}
	if ( (tam >= 12) && (tam <= 14) ){
		campo.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
	}
	if ( (tam >= 15) && (tam <= 17) ){
		campo.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
	}
}

/*
Função para formatar monetário sem os centavos.
Se o usuário colocar uma vírgula, ele permite fazer 2 casas decimais
Combinada com a função zerosdireita no onblur do campo do formulário, quando o usuário sair do campo, 
ele formata o campo para o valor monetário correto, caso o usuário tenta feito alguma alteração
na estrutara da máscara.
*/
function formataValor3(campo,tammax,teclapres) {
 	var tecla = teclapres.keyCode;
	vr = campo.value;	
	tamanho = vr.length;
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 || tecla == 44 ){
		if(vr.substring(tamanho - 4,tamanho - 3) == "," ) {
			campo.value = vr.substring(0,tamanho - 1);
		}
		else {
			if(vr.substring(tamanho - 1,tamanho) == "," ||
			   vr.substring(tamanho - 2,tamanho - 1) == "," ||
			   vr.substring(tamanho - 3,tamanho - 2) == "," ) {
	
				}
			else {
				vr = campo.value;
				vr = vr.replace( "/", "" );
				vr = vr.replace( "/", "" );
				vr = vr.replace( ",", "" );
				vr = vr.replace( ".", "" );
				vr = vr.replace( ".", "" );
				vr = vr.replace( ".", "" );
				vr = vr.replace( ".", "" );
				tam = vr.length;
			
				if(tam < tammax && tecla != 8){
					//tam = vr.length + 1 ;
					tam = vr.length;
				}
			
				if(tecla == 8 ){
					tam = tam - 1 ;
				}
				
				if( tam <= 3 ){
					campo.value = vr;
				}
				if( (tam > 3) && (tam <= 6) ){
					campo.value = vr.substr( 0, tam - 3 ) + '.' + vr.substr( tam - 3, tam );
				}
				if( (tam >= 7) && (tam <= 9) ){
					campo.value = vr.substr( 0, tam - 6 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, tam );
				}
				if ( (tam >= 10) && (tam <= 12) ){
					campo.value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, tam );
				}
				if ( (tam >= 13) && (tam <= 15) ){
					campo.value = vr.substr( 0, tam - 12 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, tam );
				}
				if ( (tam >= 16) && (tam <= 18) ){
					campo.value = vr.substr( 0, tam - 15 ) + '.' + vr.substr( tam - 15, 3 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, tam );
				}
		    }
		}
	}	
}

// Função que recebe a data em formato dd/mm/yyyy e devolve yyyymmdd, útil para soma de datas
function mudaFormatoData(data){
	ano = data.substr(6,4);
	mes = data.substr(3,2);
	dia = data.substr(0,2);
	data_nova = ano+""+mes+""+dia;
	return data_nova;
}

// Função chamada para fazer cálculo de dias
// Recebe a data inicial e a data final e se o resultado for maior que zero, a data inicial é maio que a final
function Calcula_Dias(data1_DDMMYYYY,data2_DDMMYYYY){
	Var_Dia1=Dia(data1_DDMMYYYY);
	Var_Mes1=Mes(data1_DDMMYYYY);
	Var_Mes1=Math.floor(Var_Mes1)-1;
	Var_Ano1=Ano(data1_DDMMYYYY);
	var data1 = new Date(Var_Ano1,Var_Mes1,Var_Dia1);
	
	Var_Dia2=Dia(data2_DDMMYYYY);
	Var_Mes2=Mes(data2_DDMMYYYY);
	Var_Mes2=Math.floor(Var_Mes2)-1;
	Var_Ano2=Ano(data2_DDMMYYYY);
	var data2 = new Date(Var_Ano2,Var_Mes2,Var_Dia2);
	
	var diferenca = data1.getTime() - data2.getTime();
	var diferenca = Math.floor(diferenca / (1000 * 60 * 60 * 24));
	
	return diferenca;
}

// Função necessária para a função Calcula_Dias
function Dia(Data_DDMMYYYY){
	string_data = Data_DDMMYYYY.toString();
	posicao_barra = string_data.indexOf("/");
	if (posicao_barra!= -1){
		dia = string_data.substring(0,posicao_barra);
		return dia;
	}else{
		return false;
	}
}

// Função necessária para a função Calcula_Dias
function Mes(Data_DDMMYYYY){
	string_data = Data_DDMMYYYY.toString();
	posicao_barra = string_data.indexOf("/");
	if (posicao_barra!= -1){
		dia = string_data.substring(0,posicao_barra);
		string_mes = string_data.substring(posicao_barra+1,string_data.length);
		posicao_barra = string_mes.indexOf("/");
		if (posicao_barra!= -1){
			mes = string_mes.substring(0,posicao_barra);
			mes = Math.floor(mes);
			return mes;
		}else{
			return false;
		}

	}else{
		return false;
	}
}

// Função necessária para a função Calcula_Dias
function Ano(Data_DDMMYYYY){
	string_data = Data_DDMMYYYY.toString();
	posicao_barra = string_data.indexOf("/");
	if (posicao_barra!= -1){
		dia = string_data.substring(0,posicao_barra);
		string_mes = string_data.substring(posicao_barra+1,string_data.length);
		posicao_barra = string_mes.indexOf("/");
		if (posicao_barra!= -1){
			mes = string_mes.substring(0,posicao_barra);
			mes = Math.floor(mes);
			ano = string_mes.substring(posicao_barra+1,string_mes.length);
			return ano;
		}else{
			return false;
		}
	}else{
		return false;
	}
}

function filtraNumero(event) 
{
  var chrPressionado = getCharPressed(event);

  event.returnValue = (chrPressionado.length = 0) ||
                      (chrValidoNumero.indexOf(chrPressionado) > -1);
}


function getCharPressed (e) {
  if (e.altKey || e.altLeft || e.crtlKey || e.ctrlLeft || e.repeat)
    return '';

  var codeKey = (e.shiftKey || e.shiftLeft) ? (e.keyCode + 1000) : e.keyCode;

  switch (codeKey) {
    case 49 : { return '1'; break; }
    case 50 : { return '2'; break; }
    case 51 : { return '3'; break; }
    case 52 : { return '4'; break; }
    case 53 : { return '5'; break; }
    case 54 : { return '6'; break; }
    case 55 : { return '7'; break; }
    case 56 : { return '8'; break; }
    case 57 : { return '9'; break; }
    case 48 : { return '0'; break; }

    case 65 : { return 'a'; break; }
    case 66 : { return 'b'; break; }
    case 67 : { return 'c'; break; }
    case 68 : { return 'd'; break; }
    case 69 : { return 'e'; break; }
    case 70 : { return 'f'; break; }
    case 71 : { return 'g'; break; }
    case 72 : { return 'h'; break; }
    case 73 : { return 'i'; break; }
    case 74 : { return 'j'; break; }
    case 75 : { return 'k'; break; }
    case 76 : { return 'l'; break; }
    case 77 : { return 'm'; break; }
    case 78 : { return 'n'; break; }
    case 79 : { return 'o'; break; }
    case 80 : { return 'p'; break; }
    case 81 : { return 'q'; break; }
    case 82 : { return 'r'; break; }
    case 83 : { return 's'; break; }
    case 84 : { return 't'; break; }
    case 85 : { return 'u'; break; }
    case 86 : { return 'v'; break; }
    case 87 : { return 'w'; break; }
    case 88 : { return 'x'; break; }
    case 89 : { return 'y'; break; }
    case 90 : { return 'z'; break; }

    case 96 : { return '0'; break; }
    case 97 : { return '1'; break; }
    case 98 : { return '2'; break; }
    case 99 : { return '3'; break; }
    case 100 : { return '4'; break; }
    case 101 : { return '5'; break; }
    case 102 : { return '6'; break; }
    case 103 : { return '7'; break; }
    case 104 : { return '8'; break; }
    case 105 : { return '9'; break; }

    case 106 : { return '*'; break; }
    case 107 : { return '+'; break; }
    case 109 : { return '-'; break; }
    case 110 : { return ','; break; }
    case 111 : { return '/'; break; }
    case 194 : { return '.'; break; }

    case 186 : { return String.fromCharCode(231); break; }   // 'ç'
    case 187 : { return '='; break; }
    case 188 : { return ','; break; }
    case 189 : { return '-'; break; }
    case 190 : { return '.'; break; }
    case 191 : { return ';'; break; }
    case 192 : { return '\''; break; }
    case 193 : { return '/'; break; }
    case 219 : { return '´'; break; }
    case 220 : { return ']'; break; }
    case 221 : { return '['; break; }
    case 222 : { return '~'; break; }
    case 226 : { return '\\'; break; }

    case 1049 : { return '!'; break; }
    case 1050 : { return '@'; break; }
    case 1051 : { return '#'; break; }
    case 1052 : { return '$'; break; }
    case 1053 : { return '%'; break; }
    case 1054 : { return '¨'; break; }
    case 1055 : { return '&'; break; }
    case 1056 : { return '*'; break; }
    case 1057 : { return '('; break; }
    case 1048 : { return ')'; break; }

    case 1065 : { return 'A'; break; }
    case 1066 : { return 'B'; break; }
    case 1067 : { return 'C'; break; }
    case 1068 : { return 'D'; break; }
    case 1069 : { return 'E'; break; }
    case 1070 : { return 'F'; break; }
    case 1071 : { return 'G'; break; }
    case 1072 : { return 'H'; break; }
    case 1073 : { return 'I'; break; }
    case 1074 : { return 'J'; break; }
    case 1075 : { return 'K'; break; }
    case 1076 : { return 'L'; break; }
    case 1077 : { return 'M'; break; }
    case 1078 : { return 'N'; break; }
    case 1079 : { return 'O'; break; }
    case 1080 : { return 'P'; break; }
    case 1081 : { return 'Q'; break; }
    case 1082 : { return 'R'; break; }
    case 1083 : { return 'S'; break; }
    case 1084 : { return 'T'; break; }
    case 1085 : { return 'U'; break; }
    case 1086 : { return 'V'; break; }
    case 1087 : { return 'W'; break; }
    case 1088 : { return 'X'; break; }
    case 1089 : { return 'Y'; break; }
    case 1090 : { return 'Z'; break; }

    case 1186 : { return String.fromCharCode(199); break; }   // 'Ç'
    case 1187 : { return '+'; break; }
    case 1188 : { return '<'; break; }
    case 1189 : { return '_'; break; }
    case 1190 : { return '>'; break; }
    case 1191 : { return ':'; break; }
    case 1192 : { return '"'; break; }
    case 1193 : { return '?'; break; }
    case 1219 : { return '`'; break; }
    case 1220 : { return '}'; break; }
    case 1221 : { return '{'; break; }
    case 1222 : { return '^'; break; }
    case 1226 : { return '|'; break; }

    default : { return ''; break; }
  }
}


function FmascTempoReal(ConteudoCampo)
{
if (((event.keyCode) > 47) && ((event.keyCode) < 58))
{
	NumDig = ConteudoCampo.value;
	TamDig = NumDig.length;
	Contador = 0;
	if (TamDig > 1)
		{
			numer = "";
			for (i = TamDig; (i >= 0); i--)
			{
				if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
			   {
					Contador++;
					if ((Contador == 2) && ((TamDig -i) < 4))
					{
						numer = ","+numer;
			         Contador = 0;
			       }
			       else if (Contador == 3)
			       {
						numer = "."+numer;
			         Contador = 0;
			       }
			       numer = NumDig.substr(i, 1)+numer;
				}
			}
			ConteudoCampo.value = numer;
		};
   return(true)}
   else return(false)
}


function filtraInteiro(event) {
  var chrPressionado = getCharPressed(event);

  event.returnValue = (chrPressionado.length = 0) ||
                      (chrValidoDigito.indexOf(chrPressionado) > -1);
}

