//Funcao para passar para o proximo campo de um form
function AutoNext(who, maxLength){
   if (who.value.length == maxLength){
      var i=0,j=0, indice=-1;
      for (i=0; i<document.forms.length; i++){
         for (j=0; j<document.forms[i].elements.length; j++){
            if (document.forms[i].elements[j].name == who.name){
               indice=i;
               break;
            }
         }
         if (indice != -1)
         break;
      }
      for (i=0; i<=document.forms[indice].elements.length; i++) {
         if (document.forms[indice].elements[i].name == who.name) {
            while ( (document.forms[indice].elements[(i+1)].type == "hidden") && (i < document.forms[indice].elements.length) ) {
               i++;
            }
            document.forms[indice].elements[(i+1)].focus();
            break;
         }
      }
   }
}

//Funcao para textbox aceitar somente texto
function NumbersOnly(myfield, e, dec){
   var key;
   var keychar;
   if (window.event)
      key = window.event.keyCode;
	 else if (e)
      key = e.which;
   else
      return true;
   keychar = String.fromCharCode(key);
   // control keys
   if ((key==null) || (key==0) || (key==8) || (key==9) || (key==27) )
      return true;
   // numbers
   else if ((("0123456789").indexOf(keychar) > -1))
      return true;
   // decimal point jump
   else if (dec && (keychar == ".")){
      myfield.form.elements[dec].focus();
      return false;
   }else
      return false;
}

function Mascara (formato, objeto){
   campo = eval (objeto);

   // cep
   if (formato=='cep'){
      separador = '-';
      conjunto1 = 5;
      if (campo.value.length == conjunto1){
         campo.value = campo.value + separador;
				}
   }

   // cpf
   if (formato=='cpf'){
      separador1 = '.';
      separador2 = '-';
      conjunto1 = 3;
      conjunto2 = 7;
      conjunto3 = 11;
      if (campo.value.length == conjunto1){
         campo.value = campo.value + separador1;
      }
      if (campo.value.length == conjunto2){
         campo.value = campo.value + separador1;
      }
      if (campo.value.length == conjunto3){
         campo.value = campo.value + separador2;
      }
   }

   // nascimento
   if (formato=='nascimento'){
      separador = '/';
      conjunto1 = 2;
      conjunto2 = 5;
      if (campo.value.length == conjunto1){
         campo.value = campo.value + separador;
      }
      if (campo.value.length == conjunto2){
         campo.value = campo.value + separador;
      }
   }

   // telefone
   if (formato=='telefone'){
      separador1 = '(';
      separador2 = ') ';
      separador3 = '-';
      conjunto1 = 0;
      conjunto2 = 3;
      conjunto3 = 9;
      if (campo.value.length == conjunto1){
         campo.value = campo.value + separador1;
      }
      if (campo.value.length == conjunto2){
         campo.value = campo.value + separador2;
      }
      if (campo.value.length == conjunto3){
         campo.value = campo.value + separador3;
      }
   }
}
/******************************************************************/
function verifica(campos, formu){
   String.prototype.trim = function(){return this.replace(/^\s+|\s+$/, '');};
   dados = eval(campos);
   var erro = 0;
   for (n = 0; n < dados.length; n++) {
      valor = document.getElementById(dados[n]).value;
      valor = valor.trim();
      if (valor == '' || valor == '@'){
         erro = erro + 1;
      }
   }
   if (erro > 0){
      alert("Favor preencher todos os campos obrigatórios.");
      return false;
   }else{
      document.getElementById(formu).submit();
   }
}
/********************/
function validaCNPJ(campo) {
   CNPJ = document.getElementById(campo).value;
   erro = new String;
   if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! ";
   if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
      if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! ";
   }
   //substituir os caracteres que não são números
   if(document.layers && parseInt(navigator.appVersion) == 4){
      x = CNPJ.substring(0,2);
      x += CNPJ. substring (3,6);
      x += CNPJ. substring (7,10);
      x += CNPJ. substring (11,15);
      x += CNPJ. substring (16,18);
      CNPJ = x;
   } else {
      CNPJ = CNPJ. replace (".","");
      CNPJ = CNPJ. replace (".","");
      CNPJ = CNPJ. replace ("-","");
      CNPJ = CNPJ. replace ("/","");
   }
   var nonNumbers = /\D/;
   if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! ";
   var a = [];
   var b = new Number;
   var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
   for (i=0; i<12; i++){
       a[i] = CNPJ.charAt(i);
       b += a[i] * c[i+1];
   }
   if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
   b = 0;
   for (y=0; y<13; y++) {
      b += (a[y] * c[y]);
   }
   if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
   if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
      erro +="Número de CNPJ inválido!";
   }
   if (erro.length > 0){
      alert(erro);
      return false;
   }
   return true;
}

function validaCPF(campo) {
   cpf = document.getElementById(campo).value;
   erro = new String;
   if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! ";
   var nonNumbers = /\D/;
   if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! ";
   if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
      erro += "Número de CPF inválido!"
   }
   var a = [];
   var b = new Number;
   var c = 11;
   for (i=0; i<11; i++){
      a[i] = cpf.charAt(i);
      if (i < 9) b += (a[i] * --c);
   }
   if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
   b = 0;
   c = 11;
   for (y=0; y<10; y++) b += (a[y] * c--);
   if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
   if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
      erro +="Número de CPF inválido!";
   }
   if (erro.length > 0){
      alert(erro);
      return false;
   }
   return true;
}
function validaCPF_CNPJ(campo){
   cam = document.getElementById(campo);
   tamanho = cam.value.length;
	 if(tamanho == 11){
      if(validaCPF(campo))return true;
      else{
         cam.value = "";
         cam.focus();
         return false;
      }
   }else{ 
      if(tamanho == 14){
         if(validaCNPJ(campo))return true;
         else{
            cam.value = "";
            cam.focus();
            return false;
         }
      }else{
         alert('entrei');
         alert("Quantidade de números inválida.\nUse 14 números para CNPJ ou 11 para CPF");
         cam.value = "";
         cam.focus();
         return false;
      }
   }							
}


/********************/

var campos_cep = new Array('endereco','bairro','cidade','estado','status');

function ajax(){
   try {
      return new ActiveXObject("Microsoft.XMLHTTP");
   } catch(e) {
      try {
         return new ActiveXObject("Msxml2.XMLHTTP");
      } catch(ex) {
         try {
            return new XMLHttpRequest();
         } catch(exc) {
            alert("Esse browser não tem recursos para uso do AJAX");
            return false;
         }
      }
   }
}
var ajax2 = new ajax;
function busca(url){
   var cepDestino = document.getElementById('cep1').value + document.getElementById('cep2').value;
   if(cepDestino.length == 8){
      url = url + '?cep=' + cepDestino;

      ajax2.open("GET", url, true );
      ajax2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      ajax2.send(null);    
      ajax2.onreadystatechange = function() {
         if (ajax2.readyState == 4 && ajax2.status == 200) {
            var result2 = ajax2.responseXML;
            if(result2.getElementsByTagName('status')[0].childNodes[0].data == 2){
               for(n = 0; n < campos_cep.length-1; n++) {
                  var resultado2 = result2.getElementsByTagName(campos_cep[n]);
                  document.getElementById(campos_cep[n]).value = resultado2[0].childNodes[0].data;
               }
  	       document.getElementById('cep').value = document.getElementById('cep1').value + "-" + document.getElementById('cep2').value;
            }
         } 
      }
   }
}

var campos = new Array('nome','endereco','numero','bairro','cidade','estado','telefone','email');
function limpa() {
   for(n = 0; n < campos.length; n++) {
      document.getElementById(campos[n]).value = "";
   }		
}

var campos_final = new Array('nome','endereco','numero','bairro','cidade','estado','telefone','cep');
function check_final(){
   for(n = 0; n < campos_final.length; n++) {
      if(document.getElementById(campos_final[n]).value == "" || document.getElementById(campos_final[n]).value == " ") {
         document.getElementById('finalizar').style.display = "none";
	 return false;
      }
   }
   document.getElementById('finalizar').style.display = "block";
   return true;
}

function finaliza(){
   tempo = new Date();
   var codigo;
   cep = document.getElementById('cep').value;
   codigo = cep + tempo.getHours() + tempo.getYear() + tempo.getSeconds() + tempo.getMonth() + tempo.getMinutes() + tempo.getDate();
   document.getElementById('codigo').value = codigo;
   document.form_final.submit();
//alert("entrei");
}
