
//troca o class do obj quando este est?? em 'edi????o'
//troca o class do obj quando este est? em 'edi????o'
var classAnterior;
function objFocus(campo){
    classAnterior    = campo.className;
    campo.className = eval("'"+campo.className+'Focus'+"'");
}

//troca o class do obj quando este n??o est?? mais em 'edi????o'
function objBlur(campo){
    campo.value = retiraCaracterAspas(campo.value);
	campo.className = classAnterior;
}

function retiraCaracterAspas(valor){
    while ( valor.indexOf("\"")!= -1 ){
       valor = valor.replace("\"","");
    }
    while ( valor.indexOf("'")!= -1 ){
       valor = valor.replace("'","");
    }
 return valor;
}


function validaNumerico( value ){
//NETSCAPE: YES
    var strValidos = "0123456789";
    var valor= new String(value);
    for( var i=0; i< valor.length; i++){
        if( strValidos.indexOf(valor.charAt(i)) == -1)
            return false;
    }
    return true;
}

function IsIE()
{
	return (this.name234 == 'IE');
}

function IsNetscape()
{
	return (this.name234 == 'Netscape');
}

var campoData;
var calendario;
var objeto
function abreCalendario(campo,campo2) {
	campoData =campo;
	showModalDialog('../utils/aprCalendario.html?random='+Math.random(),window,'unardorned:no;scroll:no;resizable:no;status:no;center=yes;help:no;dialogWidth:245px;dialogHeight:260px;');
	if(campo2 != undefined && campo2.value == ''){
		campo2.value = campoData.value;
	}
}

var campoTexto;
function abreSelectTexto(campo, tipo){
	if (campo.disabled == false) {
	    if (self.validarSelectTexto != undefined) {
		    if (!validarSelectTexto())
			    return;
	    }
	    campoTexto=campo;
	    openPopup('../cadastros/pesqtextos.do?TPTEXTOPREDEFINIDO='+tipo+'&random='+Math.random(),'pesq',750,500,'scroll=no')
    }
}


//Fecha a janela de selecao de textos pre-definidos antes de copiar o valor para o campo de destino
//Esse "gato" foi necessario pois o campo de destino perdia os estilos de outra forma
var janelaTexto;
function fechaSelectTexto(texto){	
	janelaTexto.close();
	janelaTexto = null;
	setTimeout('mostraValorCampoTexto(\''+texto+'\')', 100);
}

function mostraValorCampoTexto(texto){
	if (campoTexto.value != '')
		texto = '; ' + texto; 
		campoTexto.value += texto;
	campoTexto.focus();
}
function atualizarData(dataRetorno){
	campoData.value = dataRetorno;
	//campoData.onblur();
	if (campoData.onchange != null)
		campoData.onchange();
	//campoData.onfocus();
	//campoData.focus();
}

/**********************************************
*  VALIDA??ES DAS FUN??ES CONFORME O BROWSER **
**********************************************/
	//if (IsIE()){
		//window.alert 	= alerta;
		//window.confirm 	= confirma;
	//}


/**********************************************/
/********************************************************************
* M?todo: aviso()												   	*
* Funcionalidade: Abre mensagens de alert em uma janela espec?fico  *
* Descri??o:	-Recebe uma string que ser? apresentada			   	*
*********************************************************************/
function aviso(msg) {
	var re  = /\n/gi;
	msg = msg.replace(re, "<br>");
	msg = msg.replace('?', "<br>");
	msg = escape(msg);
	var titulo = ""; //vari?vel que receber? o titulo da p?gina que est? sendo exibida
	if(document.all.tituloPagina){
		titulo = escape(document.all.tituloPagina.innerText);
	}else if(parent.document.all.tituloPagina){
		titulo = escape(parent.document.all.tituloPagina.innerText);
	}
	showModalDialog(directoryDefault + '/lib/aviso.html?MENSAGEM='+msg + '&TITULO='+ titulo+"&random="+Math.random(),'','unardorned:no;scroll:no;resizable:no;status:no;center=yes;help:no;dialogWidth:350px;dialogHeight:150px;');
}

/********************************************************************
* M?todo: alerta()												   	*
* Funcionalidade: Abre mensagens de alert em uma janela espec?fico  *
* Descri??o:	-Recebe uma string que ser? apresentada			   	*
*********************************************************************/
/*function alerta(msg) {
	var re  = /\n/gi;
	msg = msg.replace(re, "<br>");
	msg = msg.replace('?', "<br>");
	msg = escape(msg);
	var titulo = ""; //vari?vel que receber? o titulo da p?gina que est? sendo exibida
	if(document.all.tituloPagina){
		titulo = escape(document.all.tituloPagina.innerText);
	}else if(parent.document.all.tituloPagina){
		titulo = escape(parent.document.all.tituloPagina.innerText);
	}
	showModalDialog(directoryDefault + '../lib/alert.html?MENSAGEM='+msg + '&TITULO='+ titulo+"&random="+Math.random(),'','unardorned:no;scroll:no;resizable:no;status:no;center=yes;help:no;dialogWidth:350px;dialogHeight:150px;');
}*/

function openExcel(pagina){
	if(pagina.indexOf("?")==-1){
		pagina += "?random="+Math.random();
	}else{
		pagina += "&random="+Math.random();
	}
	window.open(pagina, "excel", "width=750, height=400, window.toolbar=no, menubar=yes, resizable=yes");
}

function openPdf(pagina){
	if(pagina.indexOf("?")==-1){
		pagina += "?random="+Math.random();
	}else{
		pagina += "&random="+Math.random();
	}
	window.open(pagina, "PDF", "width=750, height=400, window.toolbar=no, resizable=yes");
}

//M?todo que abre um pdf dinamico, que s? existe no browser
function openRelatorioDinamico(oculto){
  if(oculto){
    var src = directoryDefault+"/aprRelDinamico.jsp?acao=ABRIR&oculto=true&random="+Math.random();
    document.body.insertAdjacentHTML("beforeEnd", "<iframe src=\""+src+"\" frameborder='0' name=ifrDownLoad width='0' height='0' marginheight='0' marginwidth='0'> </iframe>");
    // window.open(directoryDefault+"/aprRelDinamico.jsp?acao=ABRIR&oculto=true&random="+Math.random(), "RELATORIO", "width=1, height=1,left=0,top=0, window.toolbar=no, resizable=no");
  }else{
    window.open(directoryDefault+"/aprRelDinamico.jsp?acao=ABRIR&oculto=false&random="+Math.random(), "RELATORIO", "width=750, height=400, window.toolbar=no, resizable=yes");
  }
}

// utilizado para abrir duas janelas de PDF
function openPdf2(pagina){
	if(pagina.indexOf("?")==-1){
		pagina += "?random="+Math.random();
	}else{
		pagina += "&random="+Math.random();
	}
	window.open(pagina, "PDF2", "width=750, height=400, window.toolbar=no, resizable=yes");
}

/********************************************************************
* M?todo: confirma()												*
* Funcionalidade: Abre mensagens de confim em uma janela espec?fico *
* Descri??o:	-Recebe uma string que ser? apresentada	como msg   	*
*********************************************************************/
function confirma(msg) {
	var re  = /\n/gi;
	msg = msg.replace(re, "<br>");
	msg = escape(msg);
	var titulo = ""; //vari?vel que receber? o titulo da p?gina que est? sendo exibida
	var retorno = showModalDialog(directoryDefault + '../lib/confirm.html?MENSAGEM='+msg+ '&TITULO='+ titulo,'','unardorned:no;scroll:no;resizable:no;status:no;center=yes;help:no;dialogWidth:350px;dialogHeight:150px;');
	return retorno;
}

// chama o dialogo de impressao
function imprimeRel(url){
    printHidden(url);
}

function imprimir(){
//NETSCAPE = NO
// Descri??o: Fun??o de impress?o
	var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
	document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
	window.onerror=printerrortrap;  // Configura o tratamento de erros na impress?o do documento
	WebBrowser1.ExecWB(6, 2);
	window.onerror = null ;  //  Libera o tratamento de erros
	WebBrowser1.outerHTML = "";
}

function printerrortrap(){
//NETSCAPE = NO
// Descri??o: Fun??o de tratamento de erro de impress?o
	alert("Impressão do documento não ocorreu.");
	window.onerror = null ;
	WebBrowser1.outerHTML="";
	return true;
}


function setaFocoCampo(){
	if (self.clearFieldsCep){
		clearFieldsCep()
	}
	objeto.focus()
}

 
function adcionarandom(str) {
	var newstr = "";
	if(str.indexOf("?")==-1)
		newstr = str+"?random="+Math.random();
	else
		newstr = str+"&random="+Math.random();
	return newstr;
}

//VERIFICA SE UMA STRING ESTÁ NO ARRAY
function isInArrayObj(aObj, campo){
//NETSCAPE : YES
	if(aObj!=undefined){
		for(var i=0; i < aObj.length; i++){
			if(aObj[i]==campo){
				return true;
			}
		}
	}
	return false;
}

function clearFields(form,campos) {
//NETSCAPE : YES
	//campos: define os campos que n?o ser?o limpos ex: clearFields(document.frmTela,'txtCodigo,txtDescricao')
	var formulario = form;
	if(campos == undefined){
		campos = "";
	}
	var aObj = campos.split(",");
	for (iObjetosFormulario = 0; iObjetosFormulario < formulario.elements.length; iObjetosFormulario++) {
		if(!isInArrayObj(aObj, formulario.elements[iObjetosFormulario].name)) {
			if (formulario.elements[iObjetosFormulario].name.indexOf('CTX') != 0){
				switch(formulario.elements[iObjetosFormulario].type){
					case 'hidden':
						formulario.elements[iObjetosFormulario].value = '';
						break;
	
					case 'select-one':
							formulario.elements[iObjetosFormulario].value = formulario.elements[iObjetosFormulario].options[0].value;
						break;
	
					case 'password':
						formulario.elements[iObjetosFormulario].value = '';
						break;
	
					case 'text':
						formulario.elements[iObjetosFormulario].value = '';
						break;
					case 'textarea':
						formulario.elements[iObjetosFormulario].value = '';
						break;
	
					case 'checkbox':
						if(formulario.elements[iObjetosFormulario].length >= 2){
							for(var iObjetosFormularioCheckBox = 0; iObjetosFormularioCheckBox < formulario.elements[iObjetosFormulario].length; iObjetosFormularioCheckBox ++){
								formulario.elements[iObjetosFormulario][iObjetosFormularioCheckBox].checked=false;
							}
						} else {
							formulario.elements[iObjetosFormulario].checked=false;
						}
						break;
	
					case 'radio':					
						if(document.getElementsByName(formulario.elements[iObjetosFormulario].name).length >= 2){ // Se tiver mais de um radio com o mesmo nome){
							var length = document.getElementsByName(formulario.elements[iObjetosFormulario].name).length;
							for(var iObjetosFormularioRadio = 0; iObjetosFormularioRadio < length; iObjetosFormularioRadio++){
								document.getElementsByName(formulario.elements[iObjetosFormulario].name)[iObjetosFormularioRadio].checked=false;
							}
						} else {
							formulario.elements[iObjetosFormulario].checked=false;
						}
						break;
				}
			}
		}
	}

	//totalFrames = document.frames.length;
	//if (totalFrames > 0) {
	//	for (k=0; k<totalFrames; k++) {
	//		currFrame = document.frames[k];
	//		if(currFrame.restaurarLinha){
	//			currFrame.restaurarLinha();
	//		}
	//	}
	//}
	//setaFocoPrimeiroCampo();
}

function validaCpf(objEmFoco){
//NETSCAPE: YES
    var ok=false;

    var cpf = limpaParaMascara(objEmFoco.value,'numeros');
    formatCpf(objEmFoco);
    if(objEmFoco.value == ""){
        return true;
    }
    if (!isCPF(objEmFoco.value)
         || cpf == '00000000000000' || cpf == '00000000000'
         || cpf == '11111111111111' || cpf == '11111111111'
         || cpf == '22222222222222' || cpf == '22222222222'
         || cpf == '33333333333333' || cpf == '33333333333'
         || cpf == '44444444444444' || cpf == '44444444444'
         || cpf == '55555555555555' || cpf == '55555555555'
         || cpf == '66666666666666' || cpf == '66666666666'
         || cpf == '77777777777777' || cpf == '77777777777'
         || cpf == '88888888888888' || cpf == '88888888888'
         || cpf == '99999999999999' || cpf == '99999999999') {
        if(IsIE()){
            //objEmFoco.select();
        }else{
            objEmFoco.value="";
            objEmFoco.focus();
        }
        alert("CPF inválido!");
        objEmFoco.focus();
        ok=true;
        return ok;
    }
}

function isCPF( cpf){
//NETSCAPE: YES
    var result = "";
    var OK = false;
    var temp = limpaParaMascara(cpf,'numeros');

    if (temp.length>10)    {
        var work=temp.substring(0,(temp.length)-2)
        var resto = getVerificationDigit(work);
        OK = (resto==parseInt(temp.charAt((temp.length)-2)));
        if (OK)    {
            work=work+resto;
            resto= getVerificationDigit(work);
            OK = (resto==parseInt(temp.charAt((temp.length)-1)));
        }
    }
    return (OK)
}

function getVerificationDigit(S){
//NETSCAPE: YES
    // Retorna o digito verificador (entrar com S "limpo")
    var invertido = invertStr(limpaParaMascara(S,'numeros'));
    var soma = 0;
   for (var i=0; i<invertido.length; i++){
        soma=soma+(i+2)*parseInt(invertido.charAt(i))
   }
   soma*=10;
   return ((soma % 11) % 10)
}

function invertStr(str){
//NETSCAPE: YES
    // Inverte o string S
    var temp="";
    for (var i=0; i<str.length; i++){
        temp=str.charAt(i)+temp
    }
    return temp;
}

function limpaParaMascara(sujeira,filtro,tipo){
//NETSCAPE: YES
// 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 formatCpf(obj){
//NETSCAPE: YES
    retorno = limpaParaMascara(obj.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);
    obj.value = retorno;
}

/*****************************************
**    FUNCAO QUE FAZ O "SALTO" DO CAMPO    **
*****************************************/

function saltaCampo( el,tamanho,event){
//NETSCAPE: APARTIR DO 5.0
    if((IsNetscape() && GetVersion()>=5) || IsIE()){
        var tecla;
        if(IsIE()){
            tecla = event.keyCode;
        }else{
            tecla = event.which;
        }

        if ( el.value.length >= tamanho && tecla >= 48 ){
//            el.onblur();

            if(isAutoSkip){
                AutoSkip(el.name);
             }
        }
    }
}

///////////////////////////////////////////////////////////////////////
//M?todo: formataDate( obj )
//Funcionalidade: Formata e valida campos do tipo data
//Descri??o:    -Recebe um objeto com a data digitada
//        -Se poss?vel insere / e acrescenta caracteres
//        -Validade data gerada, impedindo que o campo seja deixado
//        se n?o for preenchido corretamente
///////////////////////////////////////////////////////////////////////
var nome = "";
function validaDate( el, noFocus ){
//NETSCAPE: YES
    var valor= new String(limpaParaMascara(el.value,'numeros'));
    LAST_FIELD= el;
    if (nome == "" || el.name == nome){
        vr = el.value;
        //minimo 6, maximo 10
        if (vr.length >= 6 && vr.length <= 10){
            token = new Array();
            i = 0;
            j = 0;
            nBar = 0;
            nDig = 0;

            while (i < vr.length)
            {
                if (vr.substring(i, i+1) >= '0' && vr.substring(i, i+1) <= '9'){
                    str = "" + vr.substring(i, i+1);
                    i++;
                    while (vr.substring(i, i+1) >= '0' && vr.substring(i, i+1) <= '9' && i < vr.length)
                    {

                        str = str + vr.substring(i, i+1);
                        i++;
                    }
                    token[j] = str;
                    j++;
                    nDig++;
                }else
                if (vr.substring(i, i+1) == "/"){
                    str = "" + vr.substring(i, i+1);
                    token[j] = str;
                    j++;
                    i++;
                    nBar++;

                }
                else{
                    i++;
                }
            }

            //verifica quantas barras e digitos foram reconhecidos
            //nBar == 0 e nDig == 1  - formato 01012000
            //nBar == 2 e nDig == 3  - formato 01/10/2000
            //para quaisquer outros formatos n?o faz formata??o, ocasionando em erro
            if ((nBar == 0 && nDig == 1) || (nBar == 2 && nDig == 3)){
                //alert("numero de tokens: " + token.length);

                if (token.length == 1){ //um token de tamanho minimo 6, maximo 8
                    dia = token[0].substring(0, 2);
                    mes = token[0].substring(2, 4);

                    if (token[0].length == 6){
                        if (eval(token[0].substring(4, 6)) < 30)
                            ano = "20" + token[0].substring(4, 6);
                        else
                            ano = "19" + token[0].substring(4, 6);
                    }
                    else
                    if (token[0].length == 8)
                        ano = token[0].substring(4, 8);
                    else
                        ano = token[0].substring(4, token[0].length);

                    //alert(dia + "/" + mes + "/" + ano);
                    el.value = dia + "/" + mes + "/" + ano;
                }else
                if (token.length == 5){ //5 tokens indicam data no formato dd/mm/aa
                    if (token[0].length == 1 && eval(token[0]) < 10)
                        dia = "0" + token[0];
                    else
                        //pega os dois primeiros digitos e ignora o restante se houver
                        dia = token[0].substring(0, 2);
                    barra1 = token[1]; //pega barra
                    if (token[2].length == 1 && eval(token[2]) < 10)
                        mes = "0" + token[2];
                    else
                        //pega os dois primeiros digitos e ignora o restante se houver
                        mes = token[2].substring(0, 2);

                    barra2 = token[3]; //pega barra

                    if (token[4].length == 2){
                        if (eval(token[4]) < 30)
                            ano = "20" + token[4];
                        else
                            ano = "19" + token[4];
                    }
                    else
                        ano = token[4];

                    //alert(dia + barra1 + mes + barra2 + ano);

                    el.value = dia + barra1 + mes + barra2 + ano;
                }
            }
        }

        var err=0;
        var psj=0;
        a = el.value;

        if (a.length != 10)
            err=4;
        else{

            dia = a.substring(0, 2); // day
            barra1 = a.substring(2, 3); // '/'
            mes = a.substring(3, 5); // month
            barra2 = a.substring(5, 6); // '/'
            ano = a.substring(6, 10); // year

            //basic error checking
            if (mes < 1 || mes >12) err = 1;
            if (barra1 != '/') err = 4;
            if (dia < 1 || dia > 31) err = 2;
            if (barra2 != '/') err = 4
            if (ano < 1900 || ano > 2100) err = 3
            if (mes == 4 || mes == 6 || mes == 9 || mes == 11){
                //advanced error checking
                // months with 30 days
                if (dia == 31) err=4
            }
            if (mes == 2){
                // february, leap year
                // feb
                var g = parseInt(ano/4)
                if (isNaN(g)) {
                    err=4
                }
                if (dia > 29) err=4

                if (dia == 29 && ((ano/4)!=parseInt(ano/4))) err=4
            }
        }

        if (err > 0 && a.length > 0){
            alert('Data inválida!');
            el.value = '';
            nome = el.name;
			if (noFocus == undefined || noFocus == false) {
	            el.focus();
    	        el.select();
			}
            return;
        }
        else
            nome = "";
    }
    ERRO= false;
	return true;
}

//Seta a mascara no compo 
function mask(obj,event,tipo){
//NETSCAPE: APARTIR DA VERS?O 5.0
    var tecla;
    if(IsIE()){
        tecla = event.keyCode;
    }else{
        tecla = event.which;
    }
    isNumberDate(obj,event);

    if(IsIE()){    //VALIDA??ES PARA INTERNET EXPLORER
        switch (tipo){
            case 'DATA':{
                obj.maxLength = 10;

                if(obj.value.length!=2 && obj.value.length!=5 && !validaNumerico(String.fromCharCode(tecla))){
                    return;
                }
                if(tecla != 8){
                    if(obj.value.length==2){
                        if(tecla!=47){
                            obj.value += "/";
                        }
                    }else if(obj.value.length==5){
                        obj.value += "/";
                    }
                }
                break;
            }
			case 'DATA-DD/MM': {
				obj.maxLength = 5;

				if(obj.value.length != 2 && !validaNumerico(String.fromCharCode(tecla)))
					return;

				if(tecla != 8 && obj.value.length == 2 && tecla!=47)
					obj.value += "/";

				break;
			}
            case 'CPF':{
                obj.maxLength=14;
                if(tecla != 8){
                    isNumber(obj,event);
                    if(obj.value.length==3){
                        obj.value += ".";
                    }else if(obj.value.length==7){
                        obj.value += ".";
                    }else if(obj.value.length==11){
                        obj.value += "-";
                    }

                }
                break;
            }
            case 'CNPJ':{
                obj.maxLength=18;
                if(tecla != 8){
                    isNumber(obj,event);
                    if(obj.value.length==2){
                        obj.value += ".";
                    }else if(obj.value.length==6){
                        obj.value += ".";
                    }else if(obj.value.length==10){
                        obj.value += "/";
                    }else if(obj.value.length==15){
                        obj.value += "-";
                    }
                }
                break;
            }
			case 'IE':{
				obj.maxLength = 14;

				if(tecla != 8) {
					isNumber(obj,event);

					if(obj.value.length == 3)
						obj.value += ".";
					else if(obj.value.length == 7)
						obj.value += ".";
					else if(obj.value.length == 10)
						obj.value += "-";
				}
				break;
			}
            case 'CEP':{
                obj.maxLength=18;
                if(tecla != 8){
                    isNumber(obj,event);
                    if(obj.value.length==2){
                        obj.value += ".";
                    }else if(obj.value.length==6){
                        obj.value += "-";
                    }
                }
                break;
            }
            case 'CEPWEB':{
                obj.maxLength=18;
                if(tecla != 8){
                    isNumber(obj,event);
                    if(obj.value.length==5){
                        obj.value += "-";
                    }
                }
                break;
            }
            case 'HORA':{
                obj.maxLength=5;
                if(tecla != 8){
                    isNumber(obj,event);
                    if(obj.value.length==2){
                        obj.value += ":";
                    }
                }
                break;
            }
            case 'COMPETENCIA':{
                obj.maxLength=7;
                if(tecla != 8){
                    isNumber(obj,event);
                    if(obj.value.length==2){
                        obj.value += "/";
                    }
                }
                break;
            }
			case 'DATA-HORA':{
                obj.maxLength = 16;
                if (obj.value.length!=2 && 
					obj.value.length!=5 && 
					obj.value.length!=10 && 
					obj.value.length!=13 && 
					!validaNumerico(String.fromCharCode(tecla))){
                   		return;
                }
                if(tecla != 8){
                    if(obj.value.length==2){
                        if(tecla!=47){
                            obj.value += "/";
                        }
                    }else if(obj.value.length==5){
                        obj.value += "/";
                    } else if(obj.value.length==10){
                        obj.value += " ";
                    } else if(obj.value.length==13){
                        obj.value += ":";
                    }
                }
                break;
			}
        }
    }else if((IsNetscape() && GetVersion()>=5)){
        switch (tipo){
            case 'DATA':{
                obj.maxLength = 10;

                if(obj.value.length!=2 && obj.value.length!=5 && !validaNumerico(String.fromCharCode(tecla))){
                    return;
                }

                if(tecla != 8 && tecla != 0){
                    if(obj.value.length==2){
                        if(tecla!=47){
                            obj.value += "/";
                        }
                    }else if(obj.value.length==5){
                        obj.value += "/";
                    }
                }
                break;
            }
			case 'DATA-DD/MM': {
				obj.maxLength = 5;

				if(obj.value.length!=2 && !validaNumerico(String.fromCharCode(tecla)))
					return;

				if(tecla != 8 && tecla != 0 && obj.value.length==2 && tecla!=47)
					obj.value += "/";

				break;
			}
            case 'CPF':{
                obj.maxLength=14;
                if(tecla != 8 && tecla!=0){
                    isNumber(obj,event);
                    formatCpf(obj);
                }
                break;
            }
            case 'CNPJ':{
                obj.maxLength=18;
                if(tecla != 8 && tecla!=0 ){
                    isNumber(obj,event);
                    formatCnpj(obj);
                }
                break;
            }
			case 'IE':{
				obj.maxLength=14;
				if(tecla != 8 && tecla!=0 ){
					isNumber(obj,event);
					formatIE(obj);
				}
				break;
			}
            case 'CEP':{
                obj.maxLength=18;
                if(tecla != 8 && tecla != 0){
                    isNumber(obj,event);
                    formatCepWeb(obj);
                }
                break;
            }
            case 'CEPWEB':{
                obj.maxLength=18;
                if(tecla != 8 && tecla != 0){
                    isNumber(obj,event);
                    if(obj.value.length==5){
                        obj.value += "-";
                    }
                }
                break;
            }
            case 'HORA':{
                obj.maxLength=5;
                if(tecla != 8){
                    isNumber(obj,event);
                    formatHora(obj);
                }
                break;
            }
            case 'COMPETENCIA':{
                obj.maxLength=7;
                if(tecla != 8){
                    isNumber(obj,event);
                    formatCompetencia(obj);
                }
                break;
            }
           case 'DATA-HORA':{
                obj.maxLength = 16;

                if(obj.value.length!=2 && 
				   obj.value.length!=5 && 
                   obj.value.length!=10 && 
				   obj.value.length!=13 && 
				   !validaNumerico(String.fromCharCode(tecla))){
                    return;
                }

                if(tecla != 8 && tecla != 0){
                    if(obj.value.length==2){
                        if(tecla!=47){
                            obj.value += "/";
                        }
                    }else if(obj.value.length==5){
                        obj.value += "/";
                    }else if(obj.value.length==10){
                        obj.value += " ";
                    } else if(obj.value.length==13){
                        obj.value += ":";
                    }
                }
                break;
		   }
        }
    }
}


function isNumber(campo,event) {
    var tecla;
    var caracter;
    if(IsIE()){
        tecla = event.keyCode;
    }else{
        tecla = event.which;
    }
    caracter = (String.fromCharCode(tecla));

    if (((tecla < 48) || (tecla > 57)) && (tecla != 0)){
        event.returnValue = false;
        if(!IsIE()){
            caracter = (String.fromCharCode(tecla));
            campo.value = limpaParaMascara(campo.value,'numeros');
        }
    }
}

function isNumberDate(campo,event) {
//NETSCAPE: APARTIR DA VERS?O 5.0
    var tecla;
    var caracter;
    if(IsIE()){
        tecla = event.keyCode;
    }else{
        tecla = event.which;
    }
    caracter = (String.fromCharCode(tecla));

    if (((tecla < 48) || (tecla > 57)) && (tecla != 0)){
        event.returnValue = false;
    }
}

function validaNumerico( value ){
//NETSCAPE: YES
    var strValidos = "0123456789";
    var valor= new String(value);
    for( var i=0; i< valor.length; i++){
        if( strValidos.indexOf(valor.charAt(i)) == -1)
            return false;
    }
    return true;
}

function validaEmail(obj){
	if(obj.value != ""){
		if(!obj.value.isEmail()){
			alert("E-mail inválido.");
			obj.focus();
			return false;
		}
	}
	return true;
}

function validaNumber(obj){
    obj.value = limpaParaMascara(obj.value,'numeros');
}

/*******************************
***** VALIDA??O DE CEP    ********
*******************************/
function validaCep(obj){
    formatCep(obj);
    var retorno = "";
    if(obj.value == ""){
        return;
    }

    retorno = limpaParaMascara(obj.value,'numeros');
    //if(retorno.length == 8){
    // existem valores de CEP VALIDOS com 9 caracteres (iniciam com ZERO)!!!
    if(retorno.length > 2){
        if (retorno.length >= 2) { retorno = retorno.substr(0,2)+"."+retorno.substr(2); }
        if (retorno.length >= 6) { retorno = retorno.substr(0,6)+"-"+retorno.substr(6); }
        retorno = retorno.substr(0,10);
        obj.value = retorno;
    }else{
        if(IsIE()){
            alert("CEP Inválido !");
            obj.select();
        }else{
            alert("CEP Inválido !");
            obj.value="";
            obj.focus();
        }
    }
}

function formatCep(obj){
//NETSCAPE: APARTIR DA VERS?O 5.0
    var retorno = "";
    if(obj.value == ""){
        return;
    }
    retorno = limpaParaMascara(obj.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); }
    retorno = retorno.substr(0,10);
    obj.value = retorno;
}

//document.onkeypress = anulaCaracter;
//function anulaCaracter(){
//	if(event.keyCode == 39 ||event.keyCode == 34 || event.keyCode == 124 || event.keyCode == 170){
//		return false;
//	}
//}

//Valida??o de nome completo
function validaNomeCompleto(obj){
	var str = obj.value.trim();
	if (str != "" && str.indexOf(" ") == -1){
		alert('Digite o seu Nome Completo!');
		obj.focus();
		return false;
		}
	if (str != "" && str.indexOf("  ") > -1){
		alert('Não são permitidos dois espaços em branco!!!');
		obj.focus();
		return false;
		}
	}


/************************************************************\
*
\************************************************************/
function showElement(el, isShow){	
	try{
	     el.style.visibility = (isShow ? "visible" : "hidden");
    } catch(e) {
		debugError(e, "Não foi possivel mostrar o elemento["+el+"].");
	}
}

function debugError(ex, strMessage){
	if(ParametrosScript.IS_ACTIVE_DEBUG_SCRIPT) alert("[NATIVE_ERROR]: "+ex+"\n[FRAMEWORK_JAVASCRIPT]: " + strMessage);
}

function ParametrosScript(){
	//Variaveis usadas para saber qual o browser do cliente
	var agt = navigator.userAgent.toLowerCase();
	this.IS_IE = (agt.indexOf("msie") != -1 && document.all);
	this.IS_IE5 = (agt.indexOf("msie 5")!=-1 && document.all);
	this.IS_SAFARI = (agt.indexOf("safari")!=-1);
	this.IS_NAV = !this.IS_IE && !this.IS_SAFARI && (agt.indexOf("mozilla")!=-1);

	//variavel que ativa o debug javascript
	this.IS_ACTIVE_DEBUG_SCRIPT = true;

	//Vari?veis usadas para defini??es de alinhamento
	this.ALIGN_BOTTOM = 'b';
	this.ALIGN_MIDDLE = 'm';
	this.ALIGN_TOP = 't';
}

/**************************************************************************\
  /**
   * Assorted Utility JavaScript Functions v1.0
   * Written by Diego Pires
   * Thanks to Jonas Galvez
   * Licensed under the GPL 2.0
   */

   var nav = navigator.userAgent.toLowerCase();
   var op  = nav.indexOf("opera") !=- 1;
   var ie  = nav.indexOf("msie") !=- 1;
   var ie5 = nav.indexOf("msie 5") !=- 1;
   var ko  = nav.indexOf("konqueror") !=- 1;
   var sa  = nav.indexOf("safari") !=- 1;
   var ca  = nav.indexOf("camino") !=- 1;
   var ge  = nav.indexOf("gecko") !=- 1;

  o = String.prototype;

  o.$_replace = o.replace;
  o.replace = function(a, b) {
    if(a instanceof RegExp) return this.$_replace(a, b);
    else return this.split(a).join(b);
  }

  o.trim = function() {
    return this.replace(/^\s*|\s*$/g,'');
  }

  o.ltrim = function() {
    return this.replace(/^\s*/g,'');
  }

  o.rtrim = function() {
    return this.replace(/\s*$/g,'');
  }

  o.removeSpaces = function() {
    return this.replace(' ','');
  }
   
  o.isEmail = function() {
    return (/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/).test(this);
  }

  o.isDate = function() {
    return (/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/).test(this);
  }

  o.isDateGreater = function (dF){
    if(this.substr(6,4) > dF.substr(6,4)) return false;
    else if (this.substr(6,4) == dF.substr(6,4)){ 
      if(this.substr(3,2) > dF.substr(3,2)) return false;
      else {if(this.substr(3,2) == dF.substr(3,2) && this.substr(0,2) > dF.substr(0,2)) return false;}
    }
  }

  o.isTime = function() {
    return (/^([0-1][0-9]|2[0-3]):[0-5][0-9]$/).test(this);
  }

  o.isCNPJ = function(){
    var d = this.split("");
    var m1 = [d[0]*5,d[1]*4,d[2]*3,d[3]*2,d[4]*9,d[5]*8,d[6]*7,d[7]*6,d[8]*5,d[9]*4,d[10]*3,d[11]*2];
    var s1 = 0;
    for(i in m1){ s1 += m1[i]; }
    var d1 = (s1%11<2)?0:11-(s1%11);
    var m2 = [d[0]*6,d[1]*5,d[2]*4,d[3]*3,d[4]*2,d[5]*9,d[6]*8,d[7]*7,d[8]*6,d[9]*5,d[10]*4,d[11]*3,d1*2];
    var s2 = 0;
    for(i in m2){ s2 += m2[i]; }
    var d2 = (s2%11<2)?0:11-(s2%11);
    return (d1 == d[12] && d2 == d[13])? true: false;
  } 
 
  o.isCPF = function(){
    var d = this.split("");
    var m1 = [d[0]*10,d[1]*9,d[2]*8,d[3]*7,d[4]*6,d[5]*5,d[6]*4,d[7]*3,d[8]*2];
    var s1 = 0;
    for(i in m1){ s1 += m1[i]; }
    var d1 = (s1%11<2)?0:11-(s1%11);
    var m2 = [d[0]*11,d[1]*10,d[2]*9,d[3]*8,d[4]*7,d[5]*6,d[6]*5,d[7]*4,d[8]*3,d1*2];
    var s2 = 0;
    for(i in m2){ s2 += m2[i]; }
    var d2 = (s2%11<2)?0:11-(s2%11);
    return (d1 == d[9] && d2 == d[10])? true: false;
  }
  delete o;

function $(id){
	return document.getElementById(id);
}