
 /*  Documentação da FUNÇÂO
       valida_form();    para validação de qualquer tipo de formulário
 
  PARA UTILIZAR ESTA FUNÇÃO BASTA COLOCAR A CLASSE NO CAMPO DO FORMUARIO
  AS CLASSE SÃO:
  
  class='t'  valida de veio vasio ou preenchido
  class='d'  valida CPF / CNPJ  (´é necessario que tenha um input radio com name=doc com a opçoes CPF e CNPJ )
  class='e' Valida E-mail
  class='s' valida senha e senha repetida( verifica se foi preenchida asduas e compara elas)
  
  par="Nome que é exibido no alert() de erro
  
  Exemplo de utilização
  
  Campo texto
  <input type="text" name='campo' class='t' par='Campo:' id='campo' >
  
  
  CPF/CNPJ
  
  <input type='radio' name='doc' value='CPF'>CPF
  <input type='radio' name='doc' value='CNPJ'>CNPJ
  <input type='text' name='documento' class='d' value='' par='CPF/CNPJ:'>
  
  Campo E-mail
  <input type="text" name='email' class='e' par='E-mail:' id='email' >
  
  
   Campo Senhas
  <input type="text" name='senha1' class='s' par='Senha:' id='senha1' >
  <input type="text" name='senha2' class='s' par='Senha2:' id='senha2' >
 
 
 */
function valida_form( form_id ) {
 var e=""; // Verificador de erro

   var m="Os seguintes campos em amarelo são obrigatórios:\n\n";  // Variavel que armazena o erro
 
    var dd=0; // contador no caso de CPF ou CNPF
    var tipo_doc=new Array();
 
      // Valida class=t   para campos do tipo input , verifica se foi preenchido
        $('#'+form_id+' :input[@class="t"]').each(function ()
             {
               nome_campo=$(this).attr('name');
               n_campo=$(this).attr('par');
               id_campo=$(this).attr('id');
               

         
                if($(this).val() == '')
                     {
                        document.getElementById(id_campo).style.background="yellow";
                        m+=n_campo+" ( Não preenchido ) \n";
                        e+="e";
                     }
               else{
                        document.getElementById(id_campo).style.background="#fff";
                   }
          }
        )
        
        // Valida class=d para campo de CPF e CNPJ
        $('#'+form_id+' :input[@class="d"]').each(function () {

          dd++
           tipo_doc[dd]=$(this);
           

         nome_campo=$(this).attr('name');

         n_campo=$(this).attr('par');

         id_campo=$(this).attr('id');

         if($(this).val() == '')
         {

            document.getElementById(id_campo).style.background="yellow";
            m+=n_campo+" ( Não preenchido ) \n";
            e+="e";
         }
         else {
                   if(nome_campo=="documento")
                    {
                    
                           if(document.getElementById(form_id).doc[0].checked)
                             {
                                      if (!validaCPF( $(this).val() ))
                                        {
                                            m+=n_campo+" ( CPF Inválido ) \n";
                                           e+="e";
                                           
                                           document.getElementById(id_campo).style.background="red";
                                         }
                                          



                                      }
                           else
                            {
                                    if (!validaCNPJ( $(this).val() ))
                                        {
                                            m+=n_campo+" ( CNPJ Inválido ) \n";
                                            e+="e";
                                            document.getElementById(id_campo).style.background="red";
                                        }
                                        
                            }
                      }
                  }

           }

        )
        
        
        
        
        
        // Valida class=e   Valida e-mail
        $('#'+form_id+' :input[@class="e"]').each(function ()
             {
               nome_campo=$(this).attr('name');
               n_campo=$(this).attr('par');
               id_campo=$(this).attr('id');

                if($(this).val() == '')
                     {
                        document.getElementById(id_campo).style.background="yellow";
                        m+=n_campo+" ( Não preenchido ) \n";
                        e+="e";
                     }
               else{
                          if( !validaEMAIL($(this).val()) )
                           {
                            document.getElementById(id_campo).style.background="red";
                            m+=n_campo+"  ( e-mail inválido ) \n";
                            e+="e";
                           
                           }
                           else{
                           
                              document.getElementById(id_campo).style.background="#fff";
                           }

                   }
          }
        )
        
        
        
        
        var s=0;// contador das senhas
        var sen=new Array();
        // Valida class=s   valida SENHAS IGUAIS
        $('#'+form_id+' :input[@class="s"]').each(function ()
             {
             
                nome_campo=$(this).attr('name');
                n_campo=$(this).attr('par');
                id_campo=$(this).attr('id');
             

               if($(this).val() == '')
                     {

                        document.getElementById(id_campo).style.background="yellow";
                        m+=n_campo+" ( Não preenchido ) \n";
                        e+="e";
                     }
               else{
                        document.getElementById(id_campo).style.background="#fff";
                   }
             
             
             
             
                sen[s]=$(this).val();
                

                s++;
                
                if(s > 1)
                {
                
                   if(sen[0] != sen[1] )
                   {
                   

                     m+="As senhas estão diferentes\n";
                   
                   }
                
                }

            }
          )

        
        

        if(e!="")
        { alert(m);}
        else{
               envia_registro();
        }


    }



 
 
 
 
 
 
 




function validaCPF(cpf)
      {    cpf=cpf.replace(/\./g, "");
          cpf=cpf.replace(/\-/g, "");
           

      var numeros, digitos, soma, i, resultado, digitos_iguais;
      digitos_iguais = 1;
      if (cpf.length < 11)
            return false;
      for (i = 0; i < cpf.length - 1; i++)
            if (cpf.charAt(i) != cpf.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            numeros = cpf.substring(0,9);
            digitos = cpf.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--)
                  soma += numeros.charAt(10 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            numeros = cpf.substring(0,10);
            soma = 0;
            for (i = 11; i > 1; i--)
                  soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
            }
      else
            return false;
      }
      
      
      
 function validaCNPJ(cnpj)
      {
      var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
      digitos_iguais = 1;
      if (cnpj.length < 14 && cnpj.length < 15)
            return false;
      for (i = 0; i < cnpj.length - 1; i++)
            if (cnpj.charAt(i) != cnpj.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            tamanho = cnpj.length - 2
            numeros = cnpj.substring(0,tamanho);
            digitos = cnpj.substring(tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            tamanho = tamanho + 1;
            numeros = cnpj.substring(0,tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
            }
      else
            return false;
      }
      
      
      
      
      
      function validaEMAIL(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){ return true; }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){
                    return true;
                }
    }else{
        return false;
        }
}


function verifica_doc(doc)
{
     v=document.getElementById("documento").value;
   url="verifica_documento.php?documento="+v;
   ajaxGet(url,document.getElementById("resp_doc"),true);
}



function fecha2(id_div,id_campo)
{
    document.getElementById(id_div).innerHTML="";

    document.getElementById("documento").style.background="#9af3a1";

    document.getElementById("documento").value="";

}

function fecha3(id_div)
{
    document.getElementById(id_div).innerHTML="";


}

