// #####################################
// Funções feita por Ápice Internet
// Contato: contato@apiceinternet.com.br
// #####################################

function ajaxInit() {
	var xmlhttp ;
	try {
		xmlhttp = new XMLHttpRequest() ;
	} catch (ee) {
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
		try {
			 xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}
	}
	return xmlhttp ;
}

function include(url,id,parametros) {
	mostra = document.getElementById(id) ? document.getElementById(id) : document.all[id];
	ajax = ajaxInit();
	if (ajax) {
		parametros = "?" + Math.ceil(Math.random() * 100000) + (parametros != null ? parametros : '');
		ajax.open('GET',url,true);
		ajax.onreadystatechange = function() {
			if (ajax.readyState == 4) {
				if (ajax.status == 200) {
					texto=unescape(ajax.responseText.replace(/\+/g," "));
					mostra.innerHTML = texto;
					extraiScript(texto);
				}
			}
		}
		ajax.send(null);
	}
}


function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- Informe um endereço de e-mail válido.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' é obrigatório.\n'; }
  } if ((document.formulario.declaro.checked) == false) errors+='- É obrigatório estar de acordo com os termos de contrato.\n';
  if (errors) alert('Os seguintes erros foram encontrados:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function envia_form(url,id,id2,parametros) {
	var mostra = document.getElementById(id2);
	var formulario = document.getElementById(id);
	
	var valores = "?" + formulario.elements[0].name + "=" + formulario.elements[0].value;
	for (var i=0; i < formulario.length; i++) {
		valores += "&" + formulario.elements[i].name + "=" + formulario.elements[i].value;
	}
	
	var ajax = ajaxInit();
	mostra.innerHTML = 'Aguarde por favor...';
	if (ajax) {
		parametros = "?" + Math.ceil(Math.random() * 100000) + (parametros != null ? parametros : '');
		ajax.open('GET',url + valores,true);
		ajax.onreadystatechange = function() {
			if (ajax.readyState == 4) {
				if (ajax.status == 200) {
					var texto = unescape(ajax.responseText.replace(/\+/g," "));
					mostra.innerHTML = texto;
					extraiScript(texto);
				}
			}
		}
		ajax.send(null);
	}
}

function extraiScript(texto){   
    var ini, pos_src, fim, codigo;   
    var objScript = null;   
    ini = texto.indexOf('<script', 0)   
    while (ini!=-1){   
        var objScript = window.document.createElement("script");   
        pos_src = texto.indexOf(' src', ini)   
        ini = texto.indexOf('>', ini) + 1;   
        if (pos_src < ini && pos_src >=0){
            ini = pos_src + 4;    
            fim = texto.indexOf('.', ini)+4; 
            codigo = texto.substring(ini,fim);   
            codigo = codigo.replace("=","").replace(" ","").replace("\"","").replace("\"","").replace("\'","").replace("\'","").replace(">",""); 
            objScript.src = codigo;   
        }else{ 
            fim = texto.indexOf('</script>', ini);   
            codigo = texto.substring(ini,fim);    
            objScript.text = codigo;   
        }   
        window.document.body.appendChild(objScript);   
        ini = texto.indexOf('<script', fim);   
 
        objScript = null;   
    }   
}
function mudabg(div,bg,url){
	window.document.getElementById(div).style.background = bg;
	include(url,div);
}


// INICIO VERIFICAÇÃO SENHA
 function verificaForca( campo ) {  
     var valor = campo.value;  
     var contemNumeros = /[0-9]/;  
     var contemLetras = /[a-z]/;  
     var contemEspecial = /[@#$%&amp;amp;*]/;  
     var contagem = 0;  
     var mensagem = "";  
   
     if ( valor.length > 0 ) {  
         if ( contemNumeros.test( valor ) ) contagem++;  
         if ( contemLetras.test( valor ) ) contagem++;  
         if ( contemEspecial.test( valor ) ) contagem++;  
   
         switch ( contagem ) {  
             case 1: mensagem = "Senha de baixa segurança!";
			 document.getElementById('bg_forca_senha').style.background = 'red';
                         break;  
             case 2: mensagem = "Senha de média segurança!";  
			 document.getElementById('bg_forca_senha').style.background = 'yellow';
                         break;  
             case 3: mensagem = "Senha de alta segurança!";
			 document.getElementById('bg_forca_senha').style.background = 'green';
                         break;  
             default: mensagem = "Ocorreu algum erro inesperado!";  
         }  
   
         document.getElementById('div_forca_senha').innerHTML = mensagem;  
     }  
 } 
 
 // FIM VERIFICAÇÃO SENHA
 
 // VALIDA CPF
 
 function validarCPF(){
   var cpf = document.registro.cpf.value;
   var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
   if(!filtro.test(cpf)){
     window.alert("CPF inválido. Tente novamente.");
	 return false;
   }
   
   cpf = remove(cpf, ".");
   cpf = remove(cpf, "-");
    
   if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
	  cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	  cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	  cpf == "88888888888" || cpf == "99999999999"){
	  window.alert("CPF inválido. Tente novamente.");
	  return false;
   }

   soma = 0;
   for(i = 0; i < 9; i++)
   	 soma += parseInt(cpf.charAt(i)) * (10 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(9))){
	 window.alert("CPF inválido. Tente novamente.");
	 return false;
   }
   soma = 0;
   for(i = 0; i < 10; i ++)
	 soma += parseInt(cpf.charAt(i)) * (11 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(10))){
     window.alert("CPF inválido. Tente novamente.");
	 return false;
   }
   return true;
 }
 
 function remove(str, sub) {
   i = str.indexOf(sub);
   r = "";
   if (i == -1) return str;
   r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
   return r;
 }

 
 // FIM VALIDA CPF
 
 // VALIDA CPF2
 
 function validarCPF2(){
   var cpf = document.registro.cpf.value;
   var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
   if(!filtro.test(cpf)){
     window.alert("CPF inválido. Tente novamente.");
	 return false;
   }
   
   cpf = remove(cpf, ".");
   cpf = remove(cpf, "-");
    
   if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
	  cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	  cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	  cpf == "88888888888" || cpf == "99999999999"){
	  window.alert("CPF inválido. Tente novamente.");
	  return false;
   }

   soma = 0;
   for(i = 0; i < 9; i++)
   	 soma += parseInt(cpf.charAt(i)) * (10 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(9))){
	 window.alert("CPF inválido. Tente novamente.");
	 return false;
   }
   soma = 0;
   for(i = 0; i < 10; i ++)
	 soma += parseInt(cpf.charAt(i)) * (11 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(10))){
     window.alert("CPF inválido. Tente novamente.");
	 return false;
   }
   return validaCNPJ();
   return true;
}
 
 function remove(str, sub) {
   i = str.indexOf(sub);
   r = "";
   if (i == -1) return str;
   r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
   return r;
 }

 
 // FIM VALIDA CPF
 
 // CONTROLE DE NUMEROS FORM

function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;
    if((tecla > 47 && tecla < 58)) return true;
    else{
    if (tecla != 8) return false;
    else return true;
    }
}
 
 // FIM CONTROLE DE NUMEROS FORM
 // VALIDA CNPJ
 
function validaCNPJ() {
CNPJ = document.registro.cnpj.value;
erro = new String;
if (CNPJ.length < 18) erro += "É necessarios preencher corretamente o numero do CNPJ! \n\n";
if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
if (erro.length == 0) erro += "É necessarios preencher corretamente o numero do CNPJ! \n\n";
}
//substituir os caracteres que não são numeros
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 verificacao de CNPJ suporta apenas numeros! \n\n";
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 +="Digito verificador com problema, corrija o CNPJ!";
}
if (erro.length > 0){
alert(erro);
return false;
}
return true;
}
 // FIM VALIDAÇÃO CNPJ
