<!--
/*
 **********************************************************************************
 * Título.....: Funções de uso javascript para formulários                        * *
 * Autor......: Maurício Carvalho                                                 *   *
 * Versão.....: 1.0.0                                                             *     *
 * Data.......: Rio de Janeiro, 26/01/2006                                        *       *
 * Arquivo....: script.js                                                         **********
 * Função.....: Biblioteca de Funções Genéricas                                            *
 * Input......: Nenhum                                                                     *
 *******************************************************************************************
 * Biblioteca de Funções Genéricas                                                         *
 *******************************************************************************************
 *                                                                                         *
 * Funções neste arquivo:                                                                  *
 *                                                                                         *
 * FUNÇÃO                                 RETORNO   DESCRIÇÃO                              *
 * ------                                 -------   -------------------------------------- *
 * Popup(x,y,pagina,janela,w,h,scrolling) Janela    Gera uma Janela simples                *
 * Janela(pagina,janela,w,h)              Janela    Gera uma Janela simples                *
 * Saudacao()                             String    Gera uma saudação                      *
 * criaMascar(_RefObjeto, _Modelo)        String    Cria uma máscara                       *
 *                                                                                         *
 *******************************************************************************************
 */

/************************************************
* Function.: Confirma(URL,Operacao)
* Função...: Questiona o usuário sobre a operação
* Input....: URL
************************************************/
function Confirma(URL,Operacao){
  var Msg;
  if(!Operacao){
     Msg = "Tem certeza de que deseja realizar a operação?";
  }else{
     Msg = "Tem certeza de que deseja " + Operacao + "?";
  }
  var Opcao = confirm(Msg);
  if(Opcao){
    JanelaCentro(URL,'jOperacao',370,100);
  }
}

/*
 *******************************************************************************************
 * Function.: HideShow()
 * Função...: Verifica dos dados do formulário
 * Input....: campo a ser verificado
 *******************************************************************************************
 */
  function HideShow(_Id){
    if(document.getElementById(_Id).style.display == "none"){
      ShowID(_Id);
    }else{
      HideID(_Id);
    }
    return true;
  }

/************************************************
* Function.: HideID(_Id)
* Função...: Oculta o ID selecionado.
* Input....: Id
************************************************/
function HideID(_Id){
  var thisLevel           = document.getElementById(_Id);
  thisLevel.style.display = "none";
  //thisLevel.style.visibility = "hidden";
}

/************************************************
* Function.: ShowID(_Id)
* Função...: Mostra o ID selecionado.
* Input....: Id
************************************************/
function ShowID(_Id){
  var thisLevel           = document.getElementById(_Id);
  thisLevel.style.display = "block";
  //thisLevel.style.visibility = "visible";
}

/************************************************
* Function.: EnabledID(_Id)
* Função...: Oculta o ID selecionado.
* Input....: Id
************************************************/
function EnabledID(_Id){
  var thisLevel      = document.getElementById(_Id);
  thisLevel.disabled = false;
  thisLevel.style.color = '';
}

/************************************************
* Function.: DisabledID(_Id)
* Função...: Mostra o ID selecionado.
* Input....: Id
************************************************/
function DisabledID(_Id){
  var thisLevel      = document.getElementById(_Id);
  thisLevel.disabled = true;
  thisLevel.style.color = '#808080';
}

/************************************************
* Function.: Impressão()
* Função...: Imprimir conteúdo da página
* Input....: Sem input
************************************************/
function Impressao(URL){
  if(window.top.opener == null){
    Janela(URL,'jImpresao',785,500,'yes');
  }else {
    Imprimir();
  }
  return false;
}

/*
 *******************************************************************************************
 * Function.: Cancelar()
 * Função...: Mostra o formulário de inclusão
 * Input....: Sem input
 *******************************************************************************************
 */
 function Cancelar(){
   document.location.href = self.location.href;
 }

/************************************************
* Function.: ReSizeTo(w,h)
* Função...: Redimenciona uma Janela Automaticamente
* Input....: Largura (w) e Altura (h)
************************************************/
function ReSizeTo(w,h){
  if (!w) { w=640; }
  if (!h) { w=480; }
  self.resizeTo(w,h);
  window.focus();
  window.name = 'newWindow';
}

/************************************************
* Function.: UpCase(src)
* Função...: Returna letras Maiúsculas
* Input....: Campo a ser verificado
************************************************/
function UpCase(src){
  var Str
  Str = src.value;
  Str = Str.toUpperCase();
  src.value = Str;
}

/************************************************
* Function.: LoCase(src)
* Função...: Returna letras Minúsculas
* Input....: Campo a ser verificado
************************************************/
function LoCase(src){
  var Str
  Str = src.value;
  Str = Str.toLowerCase();
  src.value = Str;
}

/************************************************
* Function.: Labels(varLabel,ClassName)
* Função...: Mostra o erro formulário de inclusão em destaque vermelho
* Input....: Id do rótulo do campo a ser verificado e ClassName do campo
************************************************/
function Labels(varLabel,ClassName){
  Label = varLabel.split(",");
  for(i=0;i<Label.length;i++){
    document.getElementById(Label[i]).className = ClassName;
    //alert('Id: ' + Label[i]);
  }
}

/************************************************
* Function.: Destaque()
* Função...: Mostra o erro formulário de inclusão em destaque vermelho
* Input....: Id do rótulo do campo a ser verificado
************************************************/
function Destaque(Label){
  document.getElementById(Label).className = 'erro';
}

/************************************************
* Function.: CriarCookie(name,value,daes)
* Função...: Criar um cookie
* Input....: Nome, valor e quantidade de dias
************************************************/
function CriarCookie(name,value,daes){
  if (daes){
    var date = new Date();
    date.setTime(date.getTime()+(daes*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

/************************************************
* Function.: LerCookie(name)
* Função...: Ler um cookie criado pea função CriarCookie
* Input....: Nome do cookie
************************************************/
function LerCookie(name){
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++){
  var c = ca[i];
  while (c.charAt(0)==' ') c = c.substring(1,c.length);
  if (c.indexOf(nameEQ) == 0)
    return c.substring(nameEQ.length,c.length);
  }
  return null;
}

/************************************************
* Function.: TxtClear(_Obj,_Txt,_Alt)
* Função...: Verifica se o botão fechar deve aparecer
* Input....: Formulário
************************************************/
function TxtClear(_Obj,_Txt,_Alt){
  if(_Obj.value == _Txt){ 
    _Obj.value = _Alt;
  }
}

/************************************************
* Function.: AjustaFoto(_Id)
* Função...: Limpa os campos preenchidos
* Input....: Formulário
************************************************/
function AjustaFoto(_Id){
  var w,h,z,zh,za,tmx,zs,Objt;
  Objt = document.getElementById(_Id);
  zs   = 320/240;
  w    = Objt.width;
  h    = Objt.height;
  z    = w/h;
  tmx  = Math.max(w,h);
  zw   = 320/tmx;
  zh   = 240/tmx;
  
  if(z >= zs){
    za = zw;
    wz = Math.ceil(tmx*za);
    hz = Math.ceil(wz/z);
  }else{
    za = zh;    
    hz = Math.ceil(tmx*za);
    wz = Math.ceil(hz*z);
  }
  //Objt.style.zoom = za;
  Objt.width      = wz;
  Objt.height     = hz;
}

/************************************************
* Function.: Ampliar(Obj)
* Função...: Limpa os campos preenchidos
* Input....: Formulário
************************************************/
function Ampliar(Obj){
  var Objt;
  Objt = document[Obj];
  Janela('../include/fotos.asp?SRC='+Objt.src,null,645,530,'no',50,5);
}

/************************************************
* Function.: Mouse()
* Função...: Mostra um manzinha no ponteiro do mouse
* Input....: Formulário
* Exemplo..: onMouseOver=Mouse(id)
************************************************/
function Mouse(Obj){
  Obj.style.cursor = 'pointer';
}

/************************************************
* Function.: Imprimir()
* Função...: Chamar a caixa de dialogo de impressão.
* Input....: sem input
* Exemplo..: onClick=Imprimir();
************************************************/
function Imprimir() {
  window.print();
}

/************************************************
* Function.: BtFechar()
* Função...: Verifica se o botão fechar deve aparecer
* Input....: Formulário
************************************************/
function BtFechar(){
  if(top.opener == null){ 
    HideID("idBtFechar");
  }
}

/************************************************
* Function.: Fechar()
* Função...: Fecha a janela ativa.
* Input....: sem input
* Exemplo..: onClick=Fechar();
************************************************/
function Fechar() {
  window.close();
}

/************************************************
* Function.: mClk(src),mOvr(src,clrOver),mOut(src,clrIn)
* Função...: Ativa a tag <A> em celula de tabela e muda as cores da mesma ao passa o mouse
* Input....: pagina,janela,w,h,scrolling
* Exemplo..: <td onmouseover="mOvr(this,'#5397AF');" 
                 onmouseout ="mOut(this,'#98BDCA');"
                 onclick=mClk(this); bgcolor="#98BDCA"><a href="index.asp">Início</a>
             </td>
************************************************/
function mOvr(src,clrOver){
  if (!src.contains(event.fromElement)) {
    src.style.cursor = 'hand';
    src.bgColor = clrOver;
  }
}
function mOut(src,clrIn){
  if (!src.contains(event.toElement)) {
    src.style.cursor = 'default';
    src.bgColor = clrIn;
  }
}
function mClk(src){
  if(event.srcElement.tagName=='TD'){
    src.children.tags('A')[0].click();
  }
}
/************************************************
* Function.: Popup(x,y,pagina,janela,w,h,scrolling)
* Função...: Gera uma Janela simples
* Input....: pagina,janela,w,h,scrolling
* Exemplo..: Popup(100,100,pop.htm,Pop,200,200)
************************************************/
function Popup(x,y,pagina,janela,w,h,scrolling)
{
  if (!scrolling) { scrolling='auto' }
  window.open(pagina,janela,'width='+w+',height='+h+',left='+x+',top='+y+',scrollbars=no,toolbar=no,location=no,status=no,menubar=no,resizable=no')
}

/************************************************
* Function.: Dialogo(pagina,janela,w,h,l,t)
* Função...: Gera uma Janela simples
* Input....: pagina,janela,w,h,scrolling
* Exemplo..: Dialogo(h.htm,Janela,250,260,'yes')
************************************************/
function Dialogo(pagina,janela,w,h,l,t){
  //w = w + 18
  //h = h + 18
  window.showModelessDialog(pagina,janela,'dialogWidth: '+w+'px; dialogHeight: '+h+'px; dialogLeft: '+ l +'px; dialogTop: '+ t +'px; edge: Sunken; center: Yes; help: No; resizable: No; status: No;');
}

/************************************************
* Function.: Janela(pagina,janela,w,h,scrolling)
* Função...: Gera uma Janela simples
* Input....: pagina,janela,w,h,scrolling
* Exemplo..: Janela(h.htm,Janela,250,260,'yes')
************************************************/
function Janela(pagina,janela,w,h,scrolling,l,t){
  w = w + 5
  h = h + 5
  if (!scrolling) { scrolling='auto' }
  window.open(pagina,janela,'width='+w+',height='+h+',left='+l+',top='+t+',scrollbars='+scrolling+',toolbar=no,location=no,status=no,menubar=no,resizable=no');
}

/************************************************
* Function.: JanelaX(pagina,janela,w,h,scrolling)
* Função...: Gera uma Janela simples
* Input....: pagina,janela,w,h,scrolling
* Exemplo..: JanelaX(h.htm,Janela,250,260,'yes')
************************************************/
function JanelaX(pagina,janela,w,h,scrolling,l,t){
  w = w + 5
  h = h + 5
  if (!scrolling) { scrolling='auto' }
  window.open(pagina,janela,'width='+w+',height='+h+',left='+l+',top='+t+',scrollbars='+scrolling+',toolbar=no,location=no,status=no,menubar=no,resizable=yes');
}

/************************************************
* Function.: JanelaCentro(pagina,janela,w,h,scrolling)
* Função...: Gera uma Janela simples
* Input....: pagina,janela,w,h
* Exemplo..: JanelaCentro(h.htm,'Janela',250,260)
************************************************/
function JanelaCentro(url,name,width,height,scrolling) {
	if(!scrolling){ scrolling = "auto"; }
  str  = "height=" + height + ",innerHeight=" + height;
  str += ",width=" + width  + ",innerWidth="  + width;
  str += ",scrollbars=" + scrolling;
  if (window.screen) {
   ah   = screen.availHeight - 30;
   aw   = screen.availWidth  - 10;
   xc   = (aw - width)  / 2;
   yc   = (ah - height) / 2;
   str += ",left=" + xc + ",screenX=" + xc;
   str += ",top="  + yc + ",screenY=" + yc;
  }
  window.open(url, name, str);
}

/************************************************
* Function.: Saudacao()
* Função...: Gera uma saudação 
* Input....: Sem dados
* Exemplo..: Saudacao()
************************************************/
function Saudacao(){
  var dias      = new Array ('Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado');
  var meses     = new Array ('Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro');
  var saudacao  = new Array ('Bom Dia!','Boa Tarde!','Boa Noite!','Bem-vindo a bordo!');
  var now       = new Date();
  var day       = now.getDay();
  var month     = now.getMonth();
  var year      = now.getYear();
  var date      = now.getDate();  
  var horas     = now.getHours();
  year         += (year < 1900) ? 1900 : 0; // O problema do Bug do Mileno com Netscape
    
//  if (horas < 12) {document.write(saudacao[0])};
//  if ((horas >= 12) && (horas <18)) {document.write(saudacao[1])};
//  if (horas >= 18) {document.write(saudacao[2])};

  //document.write(saudacao[3])
  document.write(" " + dias[day] + ", " + date + " de " + meses[month] + " de " + year);
}

/************************************************
* Function.: Telefone(_Name)
* Função...: Cria uma máscara para número de telefone com 7 ou 8 dígitos
* Input....: _Name
* Exemplo..: <input type="text" size="24" name="txt_telrs" 
              OnKeyUp="Telefones(this);">
************************************************/
function Telefones(_Name){
  var Campo = _Name.value;
  if (Campo.length<=13){
     criaMascara(_Name, '(##) ###-####')
  } else {
     criaMascara(_Name, '(##) ####-####')
  }
}

/************************************************
* Function.: criaMascar(_RefObjeto, _Modelo)
* Função...: Cria uma máscara
* Input....: _RefObjeto, _Modelo
* Exemplo..: <input type="text" size="24" name="txt_telrs" 
              OnKeyUp="criaMascara(this, '(##) ####-####');">
************************************************/
function criaMascara(_RefObjeto, _Modelo){
  
   var valorAtual = _RefObjeto.value;        
   var valorNumerico = '';
   var nIndexModelo = 0;
   var nIndexString = 0;
   var valorFinal = '';
   var adicionarValor = true;
     
   // 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++;
     }}
   }
    
   //alert(valorFinal)
   _RefObjeto.value = valorFinal
 }

/************************************************
* Function..: FormataValor(campo,tammax,teclapres)
* Função....: Formata o valor numérico
* Input.....: Campo a ser verificado
* Exemplo...: <input type='text' name='VValor' size='10' value='" & varVValor &"' 
*              onkeydown=FormataValor(this,17,event)>
************************************************/
function FormataValor(campo,tammax,teclapres) 
{
  var tecla = teclapres.keyCode;
  var valorAtual = campo.value;
  vr = valorAtual
  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 ; 
  }

  if (tecla == 8 ){
    tam = tam - 1 ;
  }
    
  if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
    if ( tam <= 2 ){ 
      valorAtual.value = vr ;
    }
    if ( (tam > 2) && (tam <= 5) ){
      valorAtual = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; 
    }
    if ( (tam >= 6) && (tam <= 8) ){
      valorAtual = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; 
    }
    if ( (tam >= 9) && (tam <= 11) ){
      valorAtual = 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) ){
      valorAtual = 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) ){
      valorAtual = 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 ) ;
    }
  }   
  campo.value = valorAtual;
}

/************************************************
* Function.: isInteger
* Função...: Verifica se um campo é inteiro, inclui dígitos de 0 a 9, vírgula, ponto, espaços e -
* Input....: campo a ser verificado
* Exemplo..: isInteger(Form.Numero.value)
************************************************/
function isInteger(s){
  var i;
  if (isEmpty(s)) 
    return false;
  for (i = 0; i < s.length; i++)
  {   
    var c = s.charAt(i);
    if (!isNumber(c)) return false;
  }
  return true;
}

/************************************************
* Function.: verificaData
* Função...: Verifica se um campo data é válido.
* Input....: Campo do formulário que contém a data
*            Esta função pega o campo diretamente, pois assim
*            pode dar uma resposta melhor ao usuário.
* Exemplo..: if (isEmpty(Form.Dia.value) || isEmpty(Form.Mes.value) ||isEmpty(Form.Ano.value) || 
*               !verificaData(Form.Dia.value + "/" + Form.Mes.value + "/" + Form.Ano.value)){
*                warnInvalid(Form.Dia,"O campo 'NASCIMENTO' está vazio ou é inválido!",1);
*                return false;
*             }
*************************************************/
function verificaData(argData){
var Data = new String(argData);
var DataAtual = new Date();
var AnoAtual = DataAtual.getYear();
var Dia = "";
var Mes = "";
var Ano = "";
var i = 0;

  for (i=0;((i < Data.length) && (Data.charAt(i) != "/"));i++)
      Dia = Dia + Data.charAt(i);

    for (i=i+1;((i < Data.length) && (Data.charAt(i) != "/"));i++)
      Mes = Mes + Data.charAt(i);

    for (i=i+1;(i < Data.length);i++)
        Ano = Ano + Data.charAt(i);
  
  for(i=0;i<Data.length;i++)
  {
    NroAsc = asc(Data.substring(i,i+1));
    if (!(NroAsc >= 47 && NroAsc <= 57)) 
        return false;
    }  
    
    if ((parseInt(Dia,10) > 31) || (parseInt(Dia,10) < 1))
    return false;
  
    if ((parseInt(Mes,10) == 2) && (parseInt(Dia,10) == 29) && (!anobissexto(parseInt(Ano,10))))
    return false;
  
  if ((parseInt(Mes,10) == 2) && (parseInt(Dia,10) > 29))
    return false;
  
  if ((parseInt(Mes,10) > 12) || (parseInt(Mes,10) < 1))
    return false;
  
    if (parseInt(AnoAtual,10)< 2000) 
    AnoAtual = AnoAtual + 1900;         
          
  if((parseInt(Ano,10) < 1900) || (parseInt(Ano,10) >= AnoAtual))
    return false;
      
    return true;
}

/************************************************
* Function.: isNumeric
* Função...: Verifica se um campo é numérico. Se contém apenas dígitos de 0 a 9
* Input....: campo a ser verificado
* Exemplo..: if (isEmpty(Form.DDD.value) || !isNumeric(Form.DDD.value)){
*               warnInvalid(Form.DDD,"O campo 'DDD' está vazio ou é inválido!",1);
*               return false;
*            }
************************************************/
function isNumeric(s)
{
        var i;
        if (isEmpty(s)) 
                return false;
        for (i = 0; i < s.length; i++)
        {   
                var c = s.charAt(i);
                if (!isDigit(c)) return false;
        }
        return true;
}

/****************************************************
* Function.: erro(campo, texto, complemento)
* Função...: Mostra mensagem de erro na tela
* input....: Campos a serem verificados
* Exemplo..: if (Form.Tipo.value == "Selecione"){
*               erro(Form.Tipo, "" , "Selecione o TIPO DE ACESSO!");
*               return false;
*             }
*             Ou
*             if (Form.Lembrete.value == ""){
*               erro(Form.Lembrete, "LEMBRETE PARA SENHA" , "");
*               return false;
*             }
****************************************************/
function erro(campo, texto, complemento) {
  
   if (complemento == "") {
      alert("O campo " + texto + " deve estar preenchido!");
   }
   else {
      alert(complemento);
   }
   campo.focus();
   return false;
}

/************************************************
* Function.: warnInvalid
* Função...: Gera um alert para o usuário e volta o foco para o campo que está com problema
* Input....: theField - campo do formulário com problema  
*            warnText - texto a ser mostrado no alert
* Exemplo..: if (!Form.leituracont.checked){
*               erro(Form.leituracont,"","O campo referente à Leitura do Contrato não foi assinalado. Certifique-se de ter lido o contrato e assinale este campo !");
*               return false;
*            }
************************************************/
function warnInvalid (theField, warnText, temSelect)
{   
  theField.focus();
    if (temSelect) {
    theField.select();
  }
    alert(warnText);
    return false;
}

/************************************************
* Function.: isEmpty
* Função...: Verifica se um campo está vazio
* Input....: campo a ser verificado
* Exemplo..: if (isEmpty(Form.CEP.value) || !verificaCEP(Form.CEP.value)){
*                warnInvalid(Form.CEP,"O campo 'CEP' está vazio, não está completo ou contém caracteres inválidos!",1);
*                return false;
*            }
************************************************/               
function isEmpty(s) 
{
  return ((s == null) || (s.length == 0));
}

/****************************************************
* Function.: testatamenho(campo, tamanho)
* Função...: Mostra mensagem de erro na tela
* input....: Verifica o tamanho do dado do campo
* Exemplo..: if (!testatamanho(form.identificacao, 8)){
*                erro(form.identificacao, "Identificacao" , "O campo Identificação permite apenas 8 caracteres");
*                return false;
*            }
****************************************************/
function testatamanho(campo, tamanho){
    if (campo.value.length < tamanho){
      return false;
    }
    return true;
  }

/************************************************
* Function.: verificaCEP
* Função...: Verifica se o CEP está no formato correto
* Input....: CEP a ser verificado
* Exemplo..: if (isEmpty(Form.CEP.value) || !verificaCEP(Form.CEP.value)){
*                warnInvalid(Form.CEP,"O campo 'CEP' está vazio, não está completo ou contém caracteres inválidos!",1);
*                return false;
*            }
************************************************/
function verificaCEP (cep) 
{
  s = new String(cep);
  if (s.length != 9)
          return false;
  if (!isInteger(cep))
          return false;
  return true;
}

/************************************************
* Function.: verificaCNPJ
* Função...: Verifica se um CNPJ é válido
* Input....: CNPJ a ser verificado
* Exemplo..: if (isEmpty(Form.CNPJ.value)   || 
*               !isNumeric(Form.CNPJ.value) ||
*               !verificaCNPJ(Form.CNPJ.value)){
*               warnInvalid(Form.CNPJ,"O campo 'CNPJ' está vazio, possui conteúdo inválido ou contém caracteres inválidos!",1);
*               return false;
*             }
************************************************/
function verificaCNPJ(cnpj) {
  var erro = true; 
  var aux_cnpj = "";  
  var cnpj1=0,cnpj2=0;
  for(j=0;j<cnpj.length;j++)
    if(cnpj.substr(j,1)>="0" && cnpj.substr(j,1)<="9")
      aux_cnpj += cnpj.substr(j,1);
  if(aux_cnpj.length!=14)
    erro = false;
  else {
    cnpj1 = aux_cnpj.substr(0,12);
    cnpj2 = aux_cnpj.substr(aux_cnpj.length-2,2);
    fator = "543298765432";
    controle = "";
    for(j=0;j<2;j++) {
      soma = 0;
      for(i=0;i<12;i++) 
        soma += cnpj1.substr(i,1) * fator.substr(i,1);
      if(j==1) soma += digito * 2;
      digito = (soma * 10) % 11;
      if(digito==10) digito = 0;
      controle += digito;
      fator = "654329876543";
    } 
    if(controle!=cnpj2)
      erro = false;
  } 
  return erro;
}

/************************************************
* Function.: verificaCPF
* Função...: Verifica se um CPF é válido
* Input....: CPF a ser verificado
* Exemplo..: if (isEmpty(Form.CPFN.value)   || 
*                isEmpty(Form.CPFF.value)|| 
*               !isNumeric(Form.CPFN.value + Form.CPFD.value) ||
*               !verificaCPF(Form.CPFN.value + Form.CPFD.value)){
*               warnInvalid(Form.CPFN,"O campo 'CPF' está vazio, possui conteúdo inválido ou contém caracteres inválidos!",1);
*               return false;
*             }
************************************************/
function verificaCPF(cpf)
{
        var dac = "", inicio = 2, fim = 10, soma, digito, i, j
        for (j=1;j<=2;j++) {
                soma = 0
                for (i=inicio;i<=fim;i++) {
                        soma += parseInt(cpf.substring(i-j-1,i-j))*(fim+1+j-i)
                }
                if (j == 2) { soma += 2*digito }
                digito = (10*soma) % 11
                if (digito == 10) { digito = 0 }
                dac += digito
                inicio = 3
                fim = 11
        }
    
    if ((cpf == '00000000000') || (cpf == '11111111111') || (cpf == '22222222222') || 
                (cpf == '33333333333') || (cpf == '44444444444') || (cpf == '55555555555') || 
                (cpf == '66666666666') || (cpf == '77777777777') || (cpf == '88888888888') || 
                (cpf == '99999999999'))
    return false;
    
        return (dac == cpf.substring(cpf.length-2,cpf.length))
}

/************************************************
* Function.: verificaEmail (email)
* Função...: Verifica se um email é válido
* input....: E-mail a ser verificado
* Exemplo..: if (isEmpty(Form.Email.value) || !verificaEmail(Form.Email.value)){  
*                warnInvalid(Form.Email,"O campo 'E-MAIL' está vazio ou é inválido!",1);
*                return false;
*            }
************************************************/
function verificaEmail(email) {
    
  var s = new String(email);
       
     // { } ( ) < > [ ] | \ /
     if ((s.indexOf("{")>=0) || (s.indexOf("}")>=0)  || 
         (s.indexOf("(")>=0) || (s.indexOf(")")>=0)  || 
         (s.indexOf("<")>=0) || (s.indexOf(">")>=0)  || 
         (s.indexOf("[")>=0) || (s.indexOf("]")>=0)  || 
         (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || 
         (s.indexOf("/")>=0) )
         return false;
        
      if (vogalAcentuada(email))
          return false;
            
      // & * $ % ? ! ^ ~ ` ' "
      if ((s.indexOf("&")>=0) || (s.indexOf("*")>=0) || 
          (s.indexOf("$")>=0) || (s.indexOf("%")>=0) || 
          (s.indexOf("?")>=0) || (s.indexOf("!")>=0) || 
          (s.indexOf("^")>=0) || (s.indexOf("~")>=0) || 
          (s.indexOf("`")>=0) || (s.indexOf("'")>=0) )
          return false;
            
      // , ; : = #
      if ((s.indexOf(",")>=0) || (s.indexOf(";")>=0) || 
          (s.indexOf(":")>=0) || (s.indexOf("=")>=0) || 
          (s.indexOf("#")>=0) )
          return false;
            
      // procura se existe apenas um @
      if ((s.indexOf("@") < 0) || (s.indexOf("@") != s.lastIndexOf("@")) )
          return false;
            
      // verifica se tem pelo menos um ponto após o @
      if (s.lastIndexOf(".") < s.indexOf("@"))
          return false;
                
      return true;
}

/************************************************
* Function.: vogalAcentuada(s)
* Função...: Verifica se uma string tem vogais acentuadas
* input....: E-mail a ser verificado
************************************************/

  function vogalAcentuada(s) {
    ls = s.toLowerCase();
    if ((ls.indexOf("á")>=0) || (ls.indexOf("à")>=0) || 
        (ls.indexOf("ã")>=0) || (ls.indexOf("â")>=0) || 
        (ls.indexOf("é")>=0) || (ls.indexOf("ê")>=0) || 
        (ls.indexOf("í")>=0) || (ls.indexOf("ó")>=0) || 
        (ls.indexOf("õ")>=0) || (ls.indexOf("ô")>=0) || 
        (ls.indexOf("ú")>=0) || (ls.indexOf("ü")>=0))
    return true;
  }

/************************************************
* Function.: verificaID (id)
* Função...: Verifica se um id é válido
* input....: Id a ser verificado
* Exemplo..: if (isEmpty(Form.ID.value) || !verificaID(Form.ID.value)){ 
*                warnInvalid(Form.ID,"O campo 'IDENTIFICAÇÃO' está vazio ou é inválido!",1);
*                return false;
*            }
************************************************/
function verificaID(id) {
    
  var s = new String(id);
       
     // { } ( ) < > [ ] | \ /
     if ((s.indexOf("{")>=0) || (s.indexOf("}")>=0)  || 
         (s.indexOf("(")>=0) || (s.indexOf(")")>=0)  || 
         (s.indexOf("<")>=0) || (s.indexOf(">")>=0)  || 
         (s.indexOf("[")>=0) || (s.indexOf("]")>=0)  || 
         (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || 
         (s.indexOf("/")>=0) )
         return false;
            
      // & * $ % ? ! ^ ~ ` ' " 
      if ((s.indexOf("&")>=0) || (s.indexOf("*")>=0) || 
          (s.indexOf("$")>=0) || (s.indexOf("%")>=0) || 
          (s.indexOf("?")>=0) || (s.indexOf("!")>=0) || 
          (s.indexOf("^")>=0) || (s.indexOf("~")>=0) || 
          (s.indexOf("`")>=0) || (s.indexOf("'")>=0) )
          return false;
            
      // , ; : = # @ .
      if ((s.indexOf(",")>=0) || (s.indexOf(";")>=0) || 
          (s.indexOf(":")>=0) || (s.indexOf("=")>=0) || 
          (s.indexOf("#")>=0) || (s.indexOf("@")>=0) ||
          (s.indexOf(".")>=0) || (s.indexOf(" ")>=0) )
          return false;
            
      if (vogalAcentuada(id))
          return false;

      return true;
}

/************************************************
* Function..: checkField(s)
* Função....: Verificação básica de um campo de formulário por "coisas bobas": & < > | \ / ? ! @ # $ % ^ * ( ) - + _ = ; [ ] { } ` ' ~ . , "
* Input.....: Campo a ser verificado
* Exemplo...: if (isEmpty(Form.Nome.value) || !checkField(Form.Nome.value)){
*                 warnInvalid(Form.Nome,"O campo 'NOME' está vazio ou contém caracteres inválidos!",1);
*                 return false;
*             }
************************************************/
function checkField(s) 
{
  if ((s.indexOf("&")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("|")>=0) ||
      (s.indexOf("\\")>=0)|| (s.indexOf("/")>=0) || (s.indexOf("?")>=0) || (s.indexOf("!")>=0) ||
      (s.indexOf("@")>=0) || (s.indexOf("#")>=0) || (s.indexOf("$")>=0) || (s.indexOf("%")>=0) ||
      (s.indexOf("^")>=0) || (s.indexOf("*")>=0) || (s.indexOf("(")>=0) || (s.indexOf(")")>=0) ||
      (s.indexOf("-")>=0) || (s.indexOf("+")>=0) || (s.indexOf("_")>=0) || (s.indexOf("=")>=0) ||
      (s.indexOf(";")>=0) || (s.indexOf("[")>=0) || (s.indexOf("]")>=0) || (s.indexOf("{")>=0) ||
      (s.indexOf("}")>=0) || (s.indexOf("`")>=0) || (s.indexOf("'")>=0) || (s.indexOf("~")>=0) ||
      (s.indexOf(",")>=0) || (s.indexOf(".")>=0) || (s.indexOf("\"")>=0))
      return false;
    return true;
}

/************************************************
* Funções Auxiliares
* Conteúdo:
*  - function Trim(param).........: Elimina espaços em branco
*  - function isDigit(c)..........: Verifica se o caracter é um dígito de 0 a 9
*  - function isNumber(c).........: Verifica se o caracter pode fazer parte de um número: 0-9 , . ( ) - e espaço
*  - function makeCharsetString().: Gera uma string com os caracteres básicos na sequência de códigos ASC
*  - function asc(achar)..........: Retorna o código ASC do caracter passada por parâmetro
*  - function vogalAcentuada(s)...: Verifica se uma string tem vogais acentuadas 
*  - function anobissexto(argAno).: Verifica se o ano é bissexto
************************************************/
// Elimina espaços em branco
function Trim(param){
  var sFinal = "";
  
  for (x=0;x<param.length;x++)
  {
    if (param.charAt(x) != " ") 
      sFinal = sFinal + param.charAt(x);
  }
  
  return sFinal;
}

// Verifica se o caracter é um dígito de 0 a 9
function isDigit(c)
{ 
  return ((c >= "0") && (c <= "9")) 
}
    
// Verifica se o caracter pode fazer parte de um número: 0-9 , . ( ) - e espaço
function isNumber(c)
{ 
  return ((c >= "0") && (c <= "9") || (c=="-") || (c=="(") || (c==")") || (c==" ") || (c==".") || (c==",")) 
}
    
// Gera uma string com os caracteres básicos na sequência de códigos ASC
function makeCharsetString()
{
  var astr
  astr = ' !"#$%&\'()*+,-./0123456789:;<=>?@'
  astr+= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  astr+= '[\]^_`abcdefghijklmnopqrstuvwxyz'
  astr+= '{|}~'
  return astr
}
    
// Retorna o código ASC do caracter passada por parâmetro
function asc(achar)
{
  var n=0;
  var ascstr = makeCharsetString()
  for(i=0;i<ascstr.length;i++){
    if(achar==ascstr.substring(i,i+1)){
      n=i;
      break;
    }
  }
  return n+32
}

// Verifica se uma string tem vogais acentuadas
function vogalAcentuada(s) 
{
  ls = s.toLowerCase();
  if ((ls.indexOf("á")>=0) || (ls.indexOf("à")>=0) || 
      (ls.indexOf("ã")>=0) || (ls.indexOf("â")>=0) || 
      (ls.indexOf("é")>=0) || (ls.indexOf("í")>=0) || 
      (ls.indexOf("ó")>=0) || (ls.indexOf("õ")>=0) || 
      (ls.indexOf("ô")>=0) || (ls.indexOf("ú")>=0) || 
      (ls.indexOf("ü")>=0))
    return true;
}

// Verifica se o ano é bissexto
function anobissexto(argAno) 
{
  if ((argAno % 4) == 0)
    if ((argAno % 100) == 0)
      if ((argAno % 400) == 0)
        return true;
      else
        return false;   
    else
      return true;
  else
    return false;
}
//-->
