// -- AJAX -------------------------------------------------------------------------------
function inc(url, destino, parametros){
	
	var dest = '#'+destino;
	
	if ($(dest).is(":hidden")) {
		//$(dest).slideDown("slow");
	} else {
		$(dest).slideUp("slow");
	};
	
    var req = null;
    if (!parametros) 
        parametros = '';
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        requesita();
    }
    else 
        if (window.ActiveXObject) {
            req = new ActiveXObject("Microsoft.XMLHTTP");
            requesita();
        }
    
    function requesita(){
        req.open("POST", url, true);
        req.onreadystatechange = processa_pagina;
        req.setRequestHeader('Content-Type', "application/x-www-form-urlencoded; charset=iso-8859-1");
        req.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        req.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
        req.setRequestHeader("Pragma", "no-cache");
        req.setRequestHeader("expires", "0");
        req.send(parametros);
    }
    
    function processa_pagina(){
		
		//escreve na tela enquanto esta carregando
		//$(dest).html("<div>Carregando...</div>");
		
        if (req.readyState == 4) {
            if (req.status == 200) {
				
				$(dest)
				.html(req.responseText)
				.slideDown('slow');
                
                //ScriptOnload(req.responseText);
				
            }
            else {
                //alert("Houve um problema ao obter os dados:\n" + req.statusText + "\n" + url);
            }
        }
    }
}

function ScriptOnload(texto){
    var Emular = document.createElement('script');
    var encontrou = texto.indexOf('onload', "0");
    if (encontrou != -1) {
        dividir = texto.split('onload="');
        fim = dividir[1].split('"');
        Emular.setAttribute('language', 'Javascript');
        Emular.text = fim[0];
        document.body.appendChild(Emular);
    }
}

function txtBoxFormat(objeto, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;


if(document.all) { 
    nTecla = evtKeyPress.keyCode;
} else if(document.layers) { 
    nTecla = evtKeyPress.which;
} else {
    nTecla = evtKeyPress.which;
    if (nTecla == 8) {
        return true;
    }
}

    sValue = objeto.value;

    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) {
      bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
      bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

      if (bolMask) {
        sCod += sMask.charAt(i);
        mskLen++; }
      else {
        sCod += sValue.charAt(nCount);
        nCount++;
      }

      i++;
    }

    objeto.value = sCod;

    if (nTecla != 8) {
      if (sMask.charAt(i-1) == "9") {
        return ((nTecla > 47) && (nTecla < 58)); } 
      else { 
        return true;
      } 
    }
    else {
      return true;
    }
  }
 function verificaCaracter(objnome){
  caracter = objnome.value;
  if (caracter.length == 0){
    return true;
  }
  return false;
}
function verificaEmail(objnome){
  invalid = Array("ç","~","!","@","#","$","%","^","&","*","(",")","+","=","[","]",":",";",",","\"","'","|","{","}","\\","/","<",">","?"," ");
  xemail = objnome.value;
  if (xemail.indexOf("@")==-1){
    return true;
  }else{
    partes=xemail.split("@");
    if(partes[0]=="" || partes[0].length < 2){
      return true;
    }else{
      for(i=0;i < invalid.length;i++){
        if(partes[0].indexOf(invalid[i])!=-1){ return true }
      }
    }
    if(partes[1]==""){
      return true;
    }else{
      if (partes[1].indexOf(".")==-1){
        return true;
      }else{
        ponto=partes[1].split(".")
        if(ponto[0]=="" || ponto[0].length < 2){
          return true;
        }else{
          for(i=0;i < invalid.length;i++){
            if(ponto[0].indexOf(invalid[i])!=-1){ return true }
          }
        }
        if(ponto[1]==""){ return true; }
      }
    }
  }
  return false
}
function SomenteNumeros(input){
	if ((event.keyCode<48)||(event.keyCode>57))
		event.returnValue = false;
}
function FormataValor(campo,tammax,teclapres) {

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

function envia_contato(form){ //realiza a captura dos dados do post para o acesso
	var valor = 'destinatario='+form.destinatario.value+'&copia='+form.copia.value+'&assunto='+form.assunto.value+'&nome='+form.nome.value+'&email='+form.email.value+'&telefone='+form.telefone.value+'&mensagem='+form.mensagem.value+'&cidade='+form.cidade.value+'&uf='+form.uf.value;
	inc('contato_envia.php','formEnvia',valor);
	camposLimpa(form);
}

function camposLimpa(form){
	if(form.mensagem.value != '' && form.nome.value != '' && form.email.value != ''){
		form.mensagem.value = '';
		form.nome.value = '';
		form.email.value = '';
		form.assunto.value = '';
		form.telefone.value = '';
		form.cidade.value = '';
		form.uf.value = '';
		
		form.nome.focus();
	}
	return true;
}

function popUp(URL, largura, altura) {
  w = largura;
  h = altura;
  if(screen.width){
  var winl = (screen.width-w)/2;
  var wint = (screen.height-h)/2;
  }else{winl = 0;wint =0;}
  if (winl < 0) winl = 0;
  if (wint < 0) wint = 0;
  var settings = 'height=' + h + ',';
  settings += 'width=' + w + ',';
  settings += 'top=' + wint + ',';
  settings += 'left=' + winl + ',';
  settings += 'toolbar=no,location=no,status=no,scrollbars=yes,resizable=no';
  win = window.open(URL, "pagina",  settings);
  win.window.focus();
}

function abre(id){
	
	var div = document.getElementById(id);
		
	$(div).slideDown("slow");
	
	return true;
	
}
function fecha(id){
	
	var div = document.getElementById(id);
		
	$(div).slideUp("slow");
	
	return true;
	
}

function logar(form){
	
	var valor = 'senha='+form.senha.value+'&tipo='+form.tipo.value;
	
	inc('logar.php', 'formEnvia', valor);	
	
}

function delay(reLoad, time){
	setTimeout(function reloader(){
				top.location.href = reLoad;
				}, time);
}

//VALIDAÇÃO DE CPF OU CNPJ
function validar(obj) { // recebe um objeto
	var s = (obj.value).replace(/\D/g,'');
	var tam=(s).length; // removendo os caracteres não numéricos
	if (!(tam==11 || tam==14)){ // validando o tamanho
		alert("'"+s+"' Não é um CPF ou um CNPJ válido!" ); // tamanho inválido
		obj.focus();
		return false;
	}
	
// se for CPF
	if (tam==11 ){
		if (!validaCPF(s)){ // chama a função que valida o CPF
			alert("'"+s+"' Não é um CPF válido!" ); // se quiser mostrar o erro
			obj.select();  // se quiser selecionar o campo em questão
			obj.focus();
			return false;
		}
		//alert("'"+s+"' É um CPF válido!" ); // se quiser mostrar que validou		
		obj.value=maskCPF(s);	// se validou o CPF mascaramos corretamente
		return true;
	}
	
// se for CNPJ			
	if (tam==14){
		if(!validaCNPJ(s)){ // chama a função que valida o CNPJ
			alert("'"+s+"' Não é um CNPJ válido!" ); // se quiser mostrar o erro
			obj.select();	// se quiser selecionar o campo enviado
			obj.focus();
			return false;			
		}
		//alert("'"+s+"' É um CNPJ válido!" ); // se quiser mostrar que validou				
		obj.value=maskCNPJ(s);	// se validou o CNPJ mascaramos corretamente
		return true;
	}
}
// fim da funcao validar()

// função que valida CPF
// O algorítimo de validação de CPF é baseado em cálculos
// para o dígito verificador (os dois últimos)
// Não entrarei em detalhes de como funciona
function validaCPF(s) {
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	for (var i=0; i<9; i++) {
		d1 += c.charAt(i)*(10-i);
 	}
	if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1){
		return false;
	}
	d1 *= 2;
	for (var i = 0; i < 9; i++)	{
 		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1){
		return false;
	}
    return true;
}

// Função que valida CNPJ
// O algorítimo de validação de CNPJ é baseado em cálculos
// para o dígito verificador (os dois últimos)
// Não entrarei em detalhes de como funciona
function validaCNPJ(CNPJ) {
	var a = new Array();
	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])){
		return false;
	}
	return true;
}


//	função que mascara o CPF
function maskCPF(CPF){
	return CPF.substring(0,3)+"."+CPF.substring(3,6)+"."+CPF.substring(6,9)+"-"+CPF.substring(9,11);
}

//	função que mascara o CNPJ
function maskCNPJ(CNPJ){
	return CNPJ.substring(0,2)+"."+CNPJ.substring(2,5)+"."+CNPJ.substring(5,8)+"/"+CNPJ.substring(8,12)+"-"+CNPJ.substring(12,14);	
}
