// ultima alteracao:
// 18/09/2004 11:00

// variavies utilizadas para destacar o foco do controle em edicao 
var corAnterior;
var corFonteAnterior;
var corfoco  = "#F8F8F8";//"lightyellow";
var corfoco  = "#FFFFF2";
var corfonte = "blue";//"blue";
var isNS4 = (navigator.appName=="Netscape")?1:0;
var isIE  = (navigator.appName=="Netscape")?0:1;
var nomeAbaAnterior="";
var abaAnterior=0;
var calendarioCampoAtual="";
var iframeConsultaAberto="";
var nj;

// NS6 = (document.getElementById&&!document.all)
// IE = (document.all)
// NS = (navigator.appName=="Netscape" && navigator.appVersion.charAt(0)=="4")
  

// var isIE  = document.getElementById ? 1:0;

function FiltraCampo(codigo) {
    var s = "";
	tam = codigo.length;
	for (i = 0; i < tam ; i++) {
		if (codigo.substring(i,i + 1) == "0" ||
           	codigo.substring(i,i + 1) == "1" ||
            codigo.substring(i,i + 1) == "2" ||
            codigo.substring(i,i + 1) == "3" ||
            codigo.substring(i,i + 1) == "4" ||
            codigo.substring(i,i + 1) == "5" ||
            codigo.substring(i,i + 1) == "6" ||
            codigo.substring(i,i + 1) == "7" ||
            codigo.substring(i,i + 1) == "8" ||
            codigo.substring(i,i + 1) == "9"  )
		 	s = s + codigo.substring(i,i + 1);
	}
	return s;
}

function DvCnpjOk(e) {
    var dv = false;

    controle = "";
    s = FiltraCampo(e.value);
    tam = s.length
    if ( tam  == 14 ) {
        dv_cnpj = s.substring(tam-2,tam);
        for ( i = 0; i < 2; i++ ) {
            soma = 0;
            for ( j = 0; j < 12; j++ )
                soma += s.substring(j,j+1)*((11+i-j)%8+2);
            if ( i == 1 ) soma += digito * 2;
            digito = 11 - soma  % 11;
            if ( digito > 9 ) digito = 0;
            controle += digito;
        }
        if ( controle == dv_cnpj )
            dv = true;

        if ( ! dv && tam > 0) {
            mensagem = "           Erro de digitação:\n";
            mensagem+= "          ===============\n\n";
            mensagem+= " O CNPJ: " + e.value + " não existe!!\n";
            mensagem+= " CONTROLE " +controle +"\n";
            alert(mensagem);
            e.focus();
        }
     } else  {
         e.value = '';
         }
     return dv;
}

function DvCpfOk(e,evento ) {
    var dv = false;

    controle = "";
    s = FiltraCampo(e.value);
    tam = s.length;
    if ( tam == 11 ) {
        dv_cpf = s.substring(tam-2,tam);
        for ( i = 0; i < 2; i++ ) {
            soma = 0;
            for ( j = 0; j < 9; j++ )
                soma += s.substring(j,j+1)*(10+i-j);
            if ( i == 1 ) soma += digito * 2;
            digito = (soma * 10) % 11;
            if ( digito == 10 ) digito = 0;
            controle += digito;
        }
        if ( controle == dv_cpf )
            dv = true;

        if ( ! dv && tam > 0) {
            mensagem = "           Erro de digitação:\n";
            mensagem+= "          ===============\n\n";
            mensagem+= " O CPF: " + e.value + " não existe!!\n";
            mensagem+= " O DV: " + controle + "\n";
            alert(mensagem);
			//evento.returnValue = false;
			//evento.stopPropagation();
			e.focus();
            
            
        }
     } else  {
         e.value = '';
        }
    return dv;
}

function DvCpfCnpjOk(e,numPessoa) {
    var s = "";
    s = FiltraCampo( e.value );
    tam = s.length;
    if ( tam < 12 ) {
    	if ( tam == 11 || !numPessoa ) 
        	DvCpfOk(e);
    } else
        DvCnpjOk(e);
}


function FormataCpf(e,cpf) {
    var s = "";
    if(e) 
       s = FiltraCampo(e.value);
    else
      s = FiltraCampo(cpf );
      
    tam =  s.length;
    r = s.substring(0,3) + "." + s.substring(3,6) + "." + s.substring(6,9)
    r += "-" + s.substring(9,11);
    if ( tam < 4 )
        s = r.substring(0,tam);
    else if ( tam < 7 )
        s = r.substring(0,tam+1);
    else if ( tam < 10 )
        s = r.substring(0,tam+2);
    else
        s = r.substring(0,tam+3);
    if( e ) {
    	e.value = s;
    }
    return s;
}

function FormataCnpj(e) {
    var s = "";
    var r = "";

    s = FiltraCampo(e.value);
    tam =  s.length;
    r = s.substring(0,2) + "." + s.substring(2,5) + "." + s.substring(5,8)
    r += "/" + s.substring(8,12) + "-" + s.substring(12,14);
    if ( tam < 3 )
        s = r.substring(0,tam);
    else if ( tam < 6 )
        s = r.substring(0,tam+1);
    else if ( tam < 9 )
        s = r.substring(0,tam+2);
    else if ( tam < 13 )
        s = r.substring(0,tam+3);
    else
        s = r.substring(0,tam+4);
    e.value = s;
    return s;
}


function FormataCpfCnpj(e) {
   var s = "";
    s = FiltraCampo(e.value);
    tam =  s.length;
    if (tam < 12 ) {
       FormataCpf(e)
       }
    else
       {
       FormataCnpj(e);
       }
}


function DataOk(e,mascara) {
var strDia="";
var strMes="";
var strAno="";
var Dia=0;
var Mes=0;
var Ano=0;
var Texto=""; //VALOR A SER TESTADO
var Msg=""; // MENSAGEM A SER EXIBIDA NA TELA SE HOUVER ERRO
var Erro = false;

Texto = FormataData(e,mascara); // COLOCAR AS BARRAS

if (Texto!="") {
   //EXISTE VALOR

   switch (mascara) {
    case 'dm':
    	Texto +='/2000';
    break;
    case 'my':
    	Texto ='01/' + Texto;
    break;
   }
   
   window.status = Texto;
   // DATA ESTÁ DIGITADA INCOMPLETA
   if ( Texto.length < 10 && Texto.length != 8 ) {
      e.value = '';
      return true;
      }
      
      

   strDia = Texto.substring(0,2);
   strMes = Texto.substring(3,5);
   strAno = Texto.substring(6);


   Dia=parseInt(strDia,10);
   Mes=parseInt(strMes,10);
   Ano=parseInt(strAno,10);

   // colocar o ano com 4 digitos se o usuario informar com 2
   if ( Ano < 100 ) {
      if (Ano > 40 )
          Ano += 1900
      else
         Ano += 2000;
   }
   
   switch (mascara) {
    case 'dm':
    	e.value = strDia+'/'+strMes;
    	exemplo = 'Informe o dia e o mês. Ex. 01/10 01/08 20/05...';
    break;
    case 'my':
	   e.value = strMes+'/'+Ano;
    	exemplo = 'Informe o mês e ano. Ex. 10/2004 05/2002 01/2004...';
    break;
    default:
    	exemplo = 'Informe a data no formato DD/MM/YYYY. Ex. 01/01/2004 ou 01/01/04.';
	   e.value = strDia+'/'+strMes+'/'+Ano;
   }
   
   
   

   if ((Dia<1) || (Dia>31) || isNaN(Dia)) {
      Msg = Msg + 'Dia '+Dia+' inválido\n';
      Erro = true;
      }
   if ((Mes<1) || (Mes>12) || isNaN(Mes)) {
      Msg = Msg + 'Mês '+Mes+' inválido\n';
      Erro = true;
      }
   if (isNaN(Ano)) {
      Msg = Msg + 'Ano '+Ano+' inválido\n';
      Erro = true;
      }
   if ((Dia>=31) && ((Mes==4) || (Mes==6) || (Mes==9) || (Mes==11))) {
      Msg = Msg + 'Dia inválido para este mês\n';
      Erro = true;
      }
   if (Mes==2) {
      //MES DE FEVEREIRO
      if (Dia>=30) {
         Msg = Msg + 'Dia inválido para fevereiro\n';
         Erro = true;
        }
      if ((Dia==29) && (((Ano % 4) != 0) || (((Ano % 100) == 0) && ((Ano % 400) != 0)))) {           Msg = Msg + 'Dia inválido para fevereiro. '+ Ano +' não é bisexto\n';
         Erro = true;
         }
      }
   }
  if ( Erro ) {
    alert(Msg + exemplo);
    e.focus();
    }
  return true;
}

function FormataData(e,mascara) {
    var s = "";

    s = FiltraCampo(e.value);
    tam =  s.length;

    r = s.substring(0,2) + "/" + s.substring(2,4) + "/"+s.substring(4,8);
    if ( tam < 3 )
        s = r.substring(0,tam);
    else if ( tam < 5 )
        s = r.substring(0,tam+1);
    else
        s = r.substring(0,tam+2);
    e.value = s;
    return s;
}

function FormataHora(e) {
    var s = "";

    s = FiltraCampo(e.value);
    tam =  s.length;

    r = s.substring(0,2) + ":" + s.substring(2,4) + ":";
    r+= s.substring(4,6);
    if ( tam < 3 )
        s = r.substring(0,tam);
    else if ( tam < 5 )
        s = r.substring(0,tam+1);
    else
        s = r.substring(0,tam+2);
    e.value = s;
    return s;
}

function HoraOk(e) {
	var Hor=0;
	var Min=0;
	var Seg=0;
	var Texto=""; //VALOR A SER TESTADO
	var Msg=""; // MENSAGEM A SER EXIBIDA NA TELA SE HOUVER ERRO
	var Erro = false;
	var s = "";

	Texto = FormataHora(e);

	if (Texto.length < 5){
		e.value = '';
		return true;
	}
	if (Texto!="") {
		Hor = Texto.substring(0,2);
		Min = Texto.substring(3,5);
		Seg = Texto.substring(6,8);

		Msg = "Informe ";
		if (Hor>24) {
			Msg = Msg + 'Hora menor que 25\n';
			Erro = true;
		}
		if (Min>59) {
			Msg = Msg + 'Minuto menor que 60\n';
			Erro = true;
		}
		if (Seg>59) {
			Msg = Msg + 'Segundo menor que 60\n';
			Erro = true;
		}
		if ( Seg.length < 2) {
			e.value = Texto.substr(0,5);
            if (Texto.length == 5) {
               e.value += ':00';}
		}
}
	if ( Erro ) {
		alert(Msg);
		e.focus();
		}
	return true;
}


function FormataDecimal(e) {

    s = e.value;
    if ( s == '0,00-'){
      s = '- ';
      }
    negativo = ( s.substring(0,1) == '-');

    // retirar os caractes inválidos
    s = FiltraCampo(e.value);
    // completar com zeros quando o valor for menor que  1,00
	if (s.length == 0) s = "000" + s
      else if (s.length == 1) s = "00" + s
         else if (s.length == 2) s = "0" + s;
    // numero de caracteres digitados
	tam =  s.length;
	if ( tam > 2 ) {
        // a posição da vírgula será sempre o tamanho meno 2
        posvirg = tam - 2;
        // retirar os zeros da esquerda da parte inteira e colocar a virgula na parte decimal
        s = eval(s.substring(0,posvirg)) + "," + s.substring(posvirg);
        // colocar pontos de 3 em 3 digitos se a parte inteira ja tiver tamanho > 3
        parteInteira = s.substring(0,posvirg);
        if ( parteInteira.length > 3 )  {
           j = 0;
           //
           r = '';
           // ler a parte inteira de traz para frente colocando os pontos e guardando em r
           for( i = parteInteira.length; i > 0 ; i-- ) {
              j++;
              if (j == 4) {
                 j = 1;
                 r = '.' + r;
                }
              r = parteInteira.substring(i-1,i) + r;
              }
           // devolver para o resultado a parte inteira formatada concatenada com a parte decimal
           s = r + s.substring(posvirg);
         }
        }
    if ( negativo ) {
         e.value = '-'+e.value+'';
         s = '-'+s+'';
         }
    e.value = s;
    return s;
}

function FormataInteiro(e) {
    s = e.value;

    if ( s == '0-')
      s = '- ';
    negativo = ( s.substring(0,1) == '-');

    s = FiltraCampo(e.value); // retirar os caractes inválidos

    tam =  s.length; // numero de caracteres digitados

    if ( tam > 0  )
        // retirar os zeros da esquerda
        s = eval(s.substring(0))+'';

 	if ( tam > 3 ) {
        // retirar os zeros da esquerda
        //s = eval(s.substring(0))+'';
        j = 0;
        r = '';
        // ler os digitos de traz para frente colocando os pontos e guardando em r
        for( i = tam; i > 0 ; i-- ) {
           j++;
           if ( j == 4 ) {
              j = 1;
              r = '.' + r;
             }
           r = s.substring(i-1,i) + r;
           }
       // devolver para o resultado a parte inteira formatada
       s = r;
      }
    e.value =  s;
    if ( negativo ) {
         e.value = '-'+e.value+'';
         s = '-'+s+'';
         }
    if ( e.value.length == 0 )
       e.value = '';
    return s;
}


function formDinConfirmar( texto,novaAcao,submeter,formulario, campoFoco ) {
if (formulario == null)
    formulario = document.formdin;
if ( confirm(texto) ) {
	if (novaAcao != null ) {
		formulario.formDinAcao.value=novaAcao;
		}
	if (campoFoco != null ) {
		formulario.campoFoco.focus();
		}
	if ( submeter != null && submeter==true) {
		formulario.submit();
		return false;
		}
	return true;
  } else {
     return false;
  }
}


function formDinFazer( acao,formulario ){
	if (formulario == null)
	    formulario = document.formdin;
	try{	    
	formulario.formDinAcao.value=acao;
	formulario.submit();
	} catch(e){
		alert('coloque um campo hidden com id=formdinAcao no formulário\npara qua a acao '+acao+' possa ser submetida!');
	}
}

function autotab(origem,destino,evento) {
	ok=1;
	if (isNS4) {
		ok=!( evento.which == 16 || evento.which == 9 || evento.which == 8 || evento.which == 37 || evento.which == 38 || evento.which == 39 || evento.which == 40 ||evento.which == 36 || evento.which == 35 || evento.which == 45 || evento.which == 17 || evento.which == 18);
	} else {
		ok=!( evento.keyCode == 16 || evento.keyCode == 9 || evento.keyCode == 8 || evento.keyCode == 37 || evento.keyCode == 38 || evento.keyCode == 39 || evento.keyCode == 40 || evento.keyCode == 36 || evento.keyCode == 35 || evento.keyCode == 45 || evento.keyCode == 17 || evento.keyCode == 18);
	}
	if ( ok && origem.getAttribute && origem.value.length == origem.getAttribute("maxlength") )  
			{
	     	setFocus(destino);
			}
}

function setFocus( destino ){
  obj = document.getElementById(destino);
  if ( obj )
  	try {
     obj.focus();
  	} catch(e){}
}

function mudaCor(controle,cor,corFonte)
{
	if ( !cor ) {
	   	controle.style.backgroundColor = corAnterior;
   		controle.style.color = corFonteAnterior;
	}
	else {
   		corAnterior = controle.style.backgroundColor;
   		corFonteAnterior = controle.style.color;
   		controle.style.backgroundColor = cor;
   		controle.style.color = corFonte;
		}
}


function formDinOpcaoDinamicaSelecionar(obj,campo,valor,campoFocar){
	objFrm=isNS4 ? document.getElementById(obj):document.all[obj]
	if( valor != '') {
	   objcampo=isNS4 ? document.getElementById(campo):document.all[campo]
	   if( objcampo ) {
	      objcampo.value = valor;
	      objcampo.focus();
	    }
	   if(campoFocar) {
	   		objcampo=isNS4 ? document.getElementById(campoFocar):document.all[campoFocar];
	   		if( objcampo ) {
			   objcampo.focus();
		   		}
	   }
	}
  objFrm.style.visibility="hidden";
}

	
function formDinOpcaoDinamicaMostrar(event,obj,centralizado,campoAtual,campoIframe){
	objFrm=isNS4 ? document.getElementById(obj) : document.all[obj];
	if( iframeConsultaAberto != "" && iframeConsultaAberto != obj) {
		f=isNS4 ? document.getElementById(iframeConsultaAberto) : document.all[iframeConsultaAberto];
		f.style.visibility="hidden";
		iframeConsultaAberto='';
	}
	
	iframeConsultaAberto=obj;
	if(centralizado==null)
	   centralizado=false;
	   
	if ( objFrm.style.visibility=="visible") {
		objFrm.style.visibility="hidden";
   		iframeConsultaAberto='';
	} else {
		if( centralizado==false ) {
			objFrm.style.top=event.clientY-18;
			objFrm.style.left=event.clientX-15;
		}
		if( campoAtual ) {
			window.frames[obj].centralizar(event);
		}
	   		
	    objFrm.style.visibility="visible";
	    if( campoAtual && obj && campoIframe ){
	    	try {
	    	window.frames[obj].document.getElementById(campoIframe).value = document.getElementById(campoAtual).value;
	    	if( document.getElementById(campoAtual).value)
 	    		window.frames[obj].pesquisar();//document.getElementById('Pesquisar').click();
	    	} catch(e) {}
	    	
	    }
	}
}

function formDinImprimirTela(){  
	if (window.print) {
    	window.print() ;  
	} else {
    	var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
	document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
    WebBrowser1.ExecWB(6, 2);//Use a 1 vs. a 2 for a prompting dialog box    WebBrowser1.outerHTML = "";  
	}
}

function formDinCheckUpload(campo,extensoes,campoOculto){
	var f=campo.value.toLowerCase().split('.');
	if ( campo.value=='')
	    return true;
	extensoes=extensoes.toLowerCase();
	if ( f.length < 2 && extensoes != null ) {
		alert('Nome de Arquivo Inválido!');
		return false;
		}
	else if ( extensoes != null && extensoes.indexOf( f[ f.length-1] ) == -1) {
		alert('Tipo de arquivo nao permitido!\nSelecione arquivo do tipo:'+extensoes);
		return false;
		}
	if (campoOculto != null){
		campoOculto.value=campo.value;
	}
return true;
}

function formDinLimitaTamanho(maximo,campo,contador) {
	var dif, valor;
	total 	= eval(maximo)
	if( campo.type == undefined )
		campo = document.getElementById(campo);
	tamanho = eval(campo.value.length)
	faltam  = eval(total - tamanho)
	if (faltam <= "-1") {
		valor = campo.value.substr(0,maximo);
		campo.value = valor;
		faltam='0';
		}
	if(isNS4)
		contador = document.getElementById(contador);
	else
		contador = document.all[contador];
	 
	if( contador ){
		contador.innerHTML=faltam+'/'+maximo;
//		if (faltam != maximo )
//			contador.innerHTML=faltam+'/'+maximo;
//		else
//			contador.innerHTML=faltam;
	}
}


function formDinMudarAba(nomeAbaClicada) {
	//alert( 'aqui..');
	//alert('Aba AbaAnterior:'+nomeAbaAnterior+'\n Nome abaClicada:' + nomeAbaClicada);
	
	if ( nomeAbaClicada != nomeAbaAnterior) {
		if (nomeAbaAnterior=="")
		   nomeAbaAnterior=nomeAbaClicada;
		if( isNS4 ){
		  document.getElementById('frmDinBtAba_'+nomeAbaAnterior).className='formDinAba';
		  document.getElementById('frmDinBtAba_'+nomeAbaClicada).className='formDinAbaAtual';
		  document.getElementById('formDinAba').value=nomeAbaClicada;
		  document.getElementById('formDinAbaDados'+nomeAbaAnterior).style.display='none';
		  document.getElementById('formDinAbaDados'+nomeAbaClicada).style.display='';
		}
		else{
		  document.all['frmDinBtAba_'+nomeAbaAnterior].className='formDinAba';
		  document.all['frmDinBtAba_'+nomeAbaClicada ].className='formDinAbaAtual';
		  document.all['formDinAba'].value=nomeAbaClicada;
		  document.all['formDinAbaDados'+nomeAbaAnterior].style.display='none';
		  document.all['formDinAbaDados'+nomeAbaClicada].style.display='';
		}
	nomeAbaAnterior=nomeAbaClicada;
	}
}

function formDinMostraEsconderCampoOutro(obj,textoAtual,textoMostrar){
	divNome = obj.name+'_outro';
	if (textoAtual == textoMostrar)
		disp='';
	 else 
		disp='none';
		
	if( isNS4 ) 
		document.getElementById(divNome).style.display=disp;
	else
		document.all[divNome].style.display=disp;
	// focar o campo outro	
	if (disp=='') {
		eval('document.'+obj.form.name+'.'+obj.name+'outro.focus();');
		}
}

function arredondar(val)
	{	
		tval = Math.floor(val);
		fraction = Math.round(val*100)%100;
		if(fraction<10){
			fraction = "0" + fraction	
		}
		val=tval+"."+fraction		
		return val;
	}

function formataCampoMascara(object, evento, mascara ) {
	var tecla;
    var valor, temp, temp2;
    
	if (isNS4) {
		tecla=evento.which;
	} else {
		tecla=evento.keyCode;
	}
	
	valor = object.value;
	window.status = tecla + '->'+valor;
	//Permitindo apenas numérico
	if( tecla < 96 || tecla >105 ) {
		evento.returnValue = false;
		if ( tecla==8 )
			valor=valor+ '';
		if ( tecla != 37 && tecla != 39 && tecla != 35 && tecla != 36 && tecla != 46 )
			tecla=8;
	}    	
	temp  = "";
	temp2 = "";
	if ( tecla ==8 || tecla == 88 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105) {
        if ( tecla==8 )  
           valor = valor.substring(0, valor.length-1 );
        for (i=0;i<valor.length;i++){
          if ( valor.substring(i,i+1) != "." && valor.substring(i,i+1) != "," && valor.substring(i,i+1) != "-" && valor.substring(i,i+1) != "/" && valor.substring(i,i+1) != "(" && valor.substring(i,i+1) != ")" && valor.substring(i,i+1) != ":"  && valor.substring(i,i+1) != "º" && valor.substring(i,i+1) != "\"" && valor.substring(i,i+1) != "M" && valor.substring(i,i+1) != "S")
            temp = temp + valor.substring(i,i+1);
        }
        temp2 = "";
        j = 0;
        for (i=0; i<temp.length;i++){
          if (mascara.substring(j,j+1)=="#"){
            temp2 = temp2 + temp.substring(i,i+1);
            j = j + 1;
          }
          else{
            temp2 = temp2 + mascara.substring(j,j+1) + temp.substring(i,i+1);
            j = j + 2;
          }
        }
      
      object.value = temp2;
    }
}

//-------------------------------------------------------------------------------------------------------------------------
function emailOk(obj) {
  // verificar se existe suporte para expressao regular;
  var supported = 0;
  var str=obj.value;
  if (str=='')
     return true;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = 1;
  }
  if (!supported) {
  	alert('nao suportado');
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
    
  }
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  var r = !r1.test(str) && r2.test(str);
  if (!r) {
  	alert('Email inválido!');
  }
  return r;
}

//-------------------------------------------------------------------------------------------------------------------------
function formDinCepOk(e){
    var s = "";
    s = FiltraCampo(e.value);
    tam =  s.length;
	if(tam!=8 ) {
		e.value=''
	}
	return true;
}
//------------------------------------------------------------------------------------------------------------------------
function formDinFormataCep(e) {
    var s = "";
    s = FiltraCampo(e.value);
    tam =  s.length;
	if(tam>2 && tam<6 ) {
		s = s.substring(0,2)+'.'+s.substring(2,5);
	} else if ( tam > 5 ) {
		s = s.substring(0,2)+'.'+s.substring(2,5)+'-'+s.substring(5,8);
	}
    e.value = s;
    return s;
}

function formDinFormataFoneFax(e) {
    var s = "";
    var res = "";

    s = FiltraCampo(e.value);
    while ( s.substring(0,1) == "0" ) {
        s1 = s.substring(1,s.length);
        s = s1;
    }
    if ( s.length == 14 || s.length == 12 )
        s = s.substring(s.length-10,s.length);
    if ( s.length == 13 || s.length == 11 )
        s = s.substring(s.length-9,s.length);

    res = s.substring(s.length-4,s.length);
    if ( s.length > 4  && s.length < 9 )
        res = s.substring(0,s.length-4)+"-"+res;
    if ( s.length > 8  )
        res = "(0XX" + s.substring(0,2) + ") " +
                   s.substring(2,s.length-4) + "-" + res;
    e.value = res;
    return res;
}

function CalendarioMostrar(event,campo){
	//calendarioCampoAtual = eval(campo);
	if (isNS4){
		calendarioCampoAtual=document.getElementById(campo);
		document.getElementById('iframeCalendario').style.display='';
		document.getElementById('iframeCalendario').style.left=event.clientX + document.body.scrollLeft;
		document.getElementById('iframeCalendario').style.top =event.clientY + document.body.scrollTop;
	} else {
		calendarioCampoAtual=document.all[campo];
		document.all.iframeCalendario.style.display='';
		document.all.iframeCalendario.style.left=event.clientX + document.body.scrollLeft;
		document.all.iframeCalendario.style.top=event.clientY + document.body.scrollTop;
	}
}
function calendarioEscolher(data){
	if ( data != 'fecha' )
		calendarioCampoAtual.value = data;
	calendarioCampoAtual.focus();
	if (isNS4)
		document.getElementById('iframeCalendario').style.display='none';
	else
		document.all.iframeCalendario.style.display='none';
}

//-------------------------------------------------------------------------------------------------------------------------
function formDinAtualizarCampoIframe( campoFormDin,
                                valorFiltro, 
                                nomePacote, 
                                nomePacoteParametro,
                                valorInicial,
                                arquivo) {
	eval( 'iframe_'+campoFormDin+'.location.href="'+arquivo + '?valorFiltro=' + valorFiltro + '&nomePacote=' + nomePacote + '&nomePacoteParametro=' + nomePacoteParametro + '&valorInicial=' + valorInicial + '&campoFormDin='+campoFormDin+'"');
}
//-------------------------------------------------------------------------------------------------------------------------

// javascript utilizado para trocar o rotulo de um campo sem submeter o formulario
// campo 		-> Nome do campo do formulario dinamico
// novoValor 	-> valor para o qual deverá ser trocado
// valorTestar 	-> [opcional] é um valor que deverá ser comparado com o valorVerdadeiro, se forem iguais
// o rotulo será trocado para o novoValor senao para o valorFalso;
function formDinSetValorRotulo(campo,novoValor,valorTestar,valorVerdadeiro,valorFalso){
	if ( valorTestar !='' ){
		if( valorTestar != valorVerdadeiro )
			novoValor=valorFalso;
	}
document.getElementById(campo+'Rotulo').innerHTML = novoValor;
}

//-------------------------------------------------------------------------------------------------------------------------
function formDinEsconderMostrarDiv(nomeDiv,esconder) {
		if( isNS4 ){
			if( esconder )
		    	 document.getElementById(nomeDiv).style.display='none';
			else
		    	 document.getElementById(nomeDiv).style.display='';
		} else {
			if (esconder)
		  		document.all[nomeDiv].style.display='none';
		 	else
		  		document.all[nomeDiv].style.display='';
		}
}

function formDinSetVisivel(id,visivel ) {
		if( isNS4 ){
			if( visivel ) {
		    	 document.getElementById(id).style.display='';
			}
			else
		    	 document.getElementById(id).style.display='none';
		} else {
			if (visivel)
		  		document.all[id].style.display='';
		 	else
		  		document.all[id].style.display='none';
		}
}


function grideSelecionar(acao,campoFormulario, valor){
	if (acao.toLowerCase().indexOf('excluir')> -1 && !confirm("Confirma exclusão ?" ))
		return;
	if (acao.toLowerCase().indexOf('cancelar')> -1 && !confirm("Confirma camcelamento ?" ))
		return;
	if( campoFormulario ) {
		atualizarCampos(campoFormulario,valor);
	}
	if( acao ){
		formDinFazer( acao );
		}
}

function atualizarCampos(campos,valores){
	var aCampo = campos.split('|');
	var aValor = valores.split('|');
	var i;
	for(i=0;i<aCampo.length;i++){
		try {
			if (isNS4) { 
				campo = document.getElementById(aCampo[i]);
			} else {
				campo=document.all[aCampo[i]];
			}
			// se nao encontrou o campo, converter para minuscula e tentar de novo
			if(!campo) {
				if (isNS4) {
					campo = document.getElementById(aCampo[i].toLowerCase()); 
				} else {
					campo = document.all[aCampo[i].toLowerCase()];
				}
			}
			if( campo ) {
				//campo.value=aValor[i].replace('“','"');
				// se for campo cpf, formatar.
                //if( ( aCampo[i].toLowerCase().indexOf('cpf') >-1) && ( aCampo[i].toLowerCase().indexOf('cnpj')< 0) )  
                	//aValor[i] = FormataCpf(null,aValor[i]);
				if( campo.type == undefined )
					campo.innerHTML= aValor[i]; // para campos label que não possuem value;
				else
				  campo.value=aValor[i];
			}
		} catch(e){}
	}
}

function hightab(what,e,edge){
	if ( document.getElementById ) {
//    	color = (e.type.toLowerCase()=="mouseover") ? "#B5BED6" : '';
    	color = (e.type.toLowerCase()=="mouseover") ? "#ffffff" : '';
	    what.style.backgroundColor =color;
	    
	    //what.bgColor=document.getElementById("rightedge"+edge).bgColor=color;
	}
}
function formDinAbaClick(obj, abaNumero ) {
	if ( abaNumero != abaAnterior ) {
		if ( abaAnterior == 0 )
		   abaAnterior = abaNumero;
		obj.className='formDinAbaAtual';
		if( isNS4 ){
		  try {document.getElementById('frmDinBtAba'+abaAnterior).className = 'formDinAba';} catch(e){}
		  document.getElementById('formDinAba').value=abaNumero;
		  document.getElementById('formDinAbaDados'+abaAnterior).style.display='none';
		  document.getElementById('formDinAbaDados'+abaNumero).style.display='';
		}
		else{
		  try { document.all['frmDinBtAba'+abaAnterior].className = 'formDinAba';} catch(e){}
		  document.all['formDinAba'].value=abaNumero;
		  document.all['formDinAbaDados'+abaAnterior].style.display='none';
		  document.all['formDinAbaDados'+abaNumero].style.display='';
		}
	abaAnterior=abaNumero;
	}
}

function formDinMostrarErros(erros){
	aErros = erros.split('|');
	if( aErros.length > 1 )
		saida=aErros.length+' erros encontrados!\n'
	else
		saida=aErros.length+' erro encontrado!\n'
	
	for(i=0 ; i < aErros.length ; i++){
		saida += aErros[i]+'.\n';
	}
	alert(saida);
}

function formDinLimparCampos(campos,iframe,url){
	aCampo = campos.split(',');
	for(i=0;i<aCampo.length;i++){
		try {
		document.getElementById(aCampo[i]).value='';
		} catch(e){}
	}
	if(iframe!=null && url!=null) {
		try {eval( iframe+'.location.href="'+url+'"');} catch(e) {};
	}
}

function travaTeclaF5(e) {
	var tecla;
	
	if (isNS4) {
		tecla = e.which;
	} else {
		tecla = window.event.keyCode;
	}	
	if (tecla==116) { 
	  	if (isNS4){ 
	  		e.cancelBubble=true;
	  		e.preventDefault();
	  		return false;
	  	}
	  	else {
	  		window.event.keyCode=0; 
			window.event.returnValue=false;
			return false;
	  	}
	}
	return true;
}


function formDinProcessoOk(e) {
    var dv = false;

    s = FiltraCampo(e.value);
    tam = s.length
    if ( tam == 15 || tam == 17 ) {
        num = s.substring(0,tam-2);
        for ( i = 0; i < 2; i++ ) {
            soma = 0;
            mult = num.length + 1;
            for ( k = 0; k < num.length ; k++ )
                soma += num.substring(k,k+1)*(mult-k);
            mod11 = 11 - (soma % 11);
            if ( mod11 < 10 )  dv_proc="0"+mod11;
            else  dv_proc = mod11 + "";
            dv_proc = dv_proc.substring(1,2);
            num+= dv_proc;
        }
        if ( num == s )
            dv = true;
    }
    if ( ! dv && tam > 0 ) {
        mensagem = "           Erro de digitação:\n";
        mensagem+= "          ===============\n\n";
        mensagem+= " O Processo: " + e.value + " não existe!!\n";
        alert(mensagem);
        e.focus();
    }
    return dv;
}

function formDinFormataProcesso(e) {
    var s = "";
	s = FiltraCampo(e.value);
    tam =  s.length;
    if ( tam >15 ) // && s.substring(0,5) == "02000" && s.substring(11,13) == "20" )
        ano_dig = 4;
    else 
        ano_dig = 2;

    r = s.substring(0,5) + "." + s.substring(5,11) + "/";
    r+= s.substring(11,11+ano_dig)  + "-" + s.substring(11+ano_dig,13+ano_dig);
    window.status = r + 'tam:'+tam;
    if ( tam < 6 )
        s = r.substring(0,tam);
    else if ( tam < 12 )
        s = r.substring(0,tam+1);
    else if ( tam < 12 + ano_dig )
        s = r.substring(0,tam+2);
    else
        s = r.substring(0,tam+3);
    
    e.value = s;
    return s;
}

function formDinMostrarImagem(e,iframe,abrirJanela) {
	var ext, v = urlencode(e.value);
	var e=v.toLowerCase().split('.');
	ext = e[ e.length-1]
	while ( v.indexOf('%5C') > -1 ) {
		v=v.replace('%5C','//');
	}
	if (!v)
	   return;
	v='file://'+v;
	if ( abrirJanela ) {
		if (isNS4 )
       		nj=window.open('iframe_imagem.php?valor='+v+'&extensao='+ext,'nj','toolbar=no,location=no,scrollbars=yes,resizable=yes,width=400,height=400,top=100,left=180,alwaysRaised=yes,dependent=yes');
        else {
			if( nj ) { 
			   //nj.navigate('iframe_imagem.php?valor='+v+'&extensao='+ext);
				//nj.location.href="iframe_imagem.php?valor="+v+"&extensao="'+ext;
			    nj.close();
			    nj=null;
			}
		   else
	       	   	nj = window.showModelessDialog('iframe_imagem.php?valor='+v+'&extensao='+ext,'nj','status:no;resizable:yes;scrollbars:yes;width:400;height:400;top:100;left:180;');
        }
	} else
	  eval( iframe+'.location.href="iframe_imagem.php?valor='+v+'&extensao='+ext+'"');
}


function urlencode(plaintext)
{
   var SAFECHARS = "0123456789" + // Numeric
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
   "abcdefghijklmnopqrstuvwxyz" +
   "-_.!~*'()"; // RFC2396 Mark characters
   var HEX = "0123456789ABCDEF";
   var encoded = "";
   for (var i = 0; i < plaintext.length; i++ ) {
   		var ch = plaintext.charAt(i);
   		if (ch == " ") {
      		encoded += "+"; // x-www-urlencoded, rather than %20
   		} else if (SAFECHARS.indexOf(ch) != -1) {
      		encoded += ch;
   		} else {
      		var charCode = ch.charCodeAt(0);
      		if (charCode > 255) {
      		   	alert( "Caractere unicode '" + ch + "' não pode ser codificado utilizando o padrão de codificaçao de URL.\n" + "(Codificaçao URL suporta somente caracteres de 8-bit.)\n" + "Será colocado um (+) no lugar." );
         		encoded += "+";
      		} else {
         		encoded += "%";
         		encoded += HEX.charAt((charCode >> 4) & 0xF);
		        encoded += HEX.charAt(charCode & 0xF);
      		}
   		}
	} // for

return encoded;
} 
function abrirJanela(url,altura,largura,posicaoX,posicaoY) {
	var conf;
	if( !altura )
		altura = 400;
	if(!largura )
		largura = 400;
	if(!posicaoX )
		posicaoX=0;
	if(!posicaoY)
	   posicaoY=0;
	if(!url)
	   url='about:blank';
	if ( isNS4 ) {
	   conf = 'toolbar=no,location=no,scrollbars=yes,resizable=yes,width='+largura+',height='+altura+',top='+posicaoY+',left='+posicaoX+',alwaysRaised=yes,dependent=yes';
		window.open(url,null,conf);
	} else {
		conf = 'center:no;status:no;resizable:yes;scrollbars:yes;width:'+altura+';height:'+largura+';top:'+posicaoY+';left:'+posicaoX+';'
		window.showModelessDialog(url,null,conf);
	}
}

function formDinExibirAjuda(arquivo,iframe){
	var hTotal = document.body.clientHeight;
	var t = parseInt( hTotal - document.body.scrollTop );
	t = t-15; 
	if( iframe ) {
		if(isNS4)
			obj=document.getElementById('iframe_ajuda_online');
		else
		   obj =documen.all['iframe_ajuda_online'];
		if(obj) {
			if (obj.style.display == '') {
				obj.style.display='none';
			} else {
				// posicionar o iframe ocupando toda a area da esquerda do formulario
	            obj.style.top = 5;
	            obj.style.left= 5;
    	        obj.style.height=t;
				obj.style.display='';
				try {eval( 'iframe_ajuda_online.location.href="'+arquivo+'"'); 
	    		} catch( e ) { 
	    			alert('Não foi possível exibir o arquivo de ajuda:'+arquivo);
	    		 };
			}
		} else {
			alert('iframe: ifram_ajuda_online, não localizado no formulario!');
		}
	} else {
		abrirJanela('ajuda/mostrar_ajuda.php?arquivo='+arquivo,t,500,10,30);
	}
}
//---------------------------------------------------------------------------------------
function retirarMascara(val) {
	var strCheck = "'[](){}<>=+-*/_|\~`!?@#$%^&:;,.";
	var aux="";
	var i;
	
	for(i=0; i<val.length; i++) {
		if(strCheck.indexOf(val.charAt(i))==-1) {
			aux+=val.charAt(i);
		}
	}
	return aux;
}
//-----------------------------------------------------------------------------------------
function colocarMascara(field, _mascara, event) {
	var key ='';
	var aux='';
	var len=0;
	var i=0;
	var strCheck = '0123456789';
	var rcode = (window.Event) ? event.which : event.keyCode;
	// se trocar o evento onKeypress por onKeyUp, tem que diminuir 48 para achar o codigo certo.
	rcode-=48;
	aux=field.value;
	aux=retirarMascara(aux); 
	aux=mascara(_mascara,aux);
	if( (rcode < 1 ) || ( field.value.length >= _mascara.length )  ) {
		if( rcode < 0 ) {
			return false;
		}
	}
	key=String.fromCharCode(rcode);
	if(strCheck.indexOf(key)==-1) {
		key=String.fromCharCode(rcode+48);
		if(strCheck.indexOf(key)==-1) {
			i = field.value.toUpperCase().indexOf(key);
			aux = field.value.substr(0,i) + field.value.substr(i+1,1000);
			aux=mascara(_mascara,aux);
			field.value=aux;
			return false;
		}
	}
	field.value=aux;	
	field.value = aux.substr(0,_mascara.length);
	return false;
}
//-----------------------------------------------------------------------------------------
function mascara(_mascara, val) {
	var i, mki;
	var aux="";
	
	for(i=mki=0; i<val.length; i++, mki++) {
		if(_mascara.charAt(mki)=='' || _mascara.charAt(mki)=='#' || _mascara.charAt(i)==val.charAt(i)) {
			aux+=val.charAt(i);
		} else {
			aux+=_mascara.charAt(mki)+val.charAt(i);
			mki++;
		}
	}
	return aux;
}
//-----------------------------------------------------------------------------------------------
function formDinAlterarBotao(nomeBotao, novoValor){
	var obj;
	if(isNS4)
		obj=document.getElementById(nomeBotao);
	else
		obj=document.all[nomeBotao];
	if( !obj ) {
		alert('função formDinAlterarBotao: Nome do botão '+nomeBotao+' não existe no formulário.');
	} else {
		obj.value=novoValor;
	}
}
//-------------------------------------------------------------------------------------------
function formDinDesabilitarBotao(botao,form,rotulo){
	var obj=document.getElementById(botao);
	if(!obj)
		var obj=document.getElementById('btn'+botao);
	if(obj) {
		if(rotulo!=null)
			obj.value = rotulo;
		obj.disabled=true;
		if( form!=null ){
			var acao = botao.substring(0,3);
			if( acao=='btn' ) {
			    acao=botao.substring(3,100);
			}
		   formDinFazer(acao);
	    }
    }
}

