
Ajax = function (){   
    try{   
        xmlhttp = new XMLHttpRequest();
    }catch(ee){   
        try{   
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){   
            try{   
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }catch(E){   
                xmlhttp = false;   
            }   
        }   
    }   

}
Ajax_cep = function (){   
    try{   
        xmlhttp_cep = new XMLHttpRequest();
    }catch(ee){   
        try{   
            xmlhttp_cep = new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){   
            try{   
                xmlhttp_cep = new ActiveXObject("Microsoft.XMLHTTP");
            }catch(E){   
                xmlhttp_cep = false;   
            }   
        }   
    }   

}


ajaxHTML = function( nomeUrl, divRetorno ){   
  
    divInsereResposta = document.getElementById( divRetorno );
	//divInsereResposta.innerHTML = "<table width='120' border='0' cellspacing='0' cellpadding='0'><tr><td width='32'><img src='imgs/aero_light.gif'/></td><td width='88'><span class='loading'>CARREGANDO...</span></td></tr></table>";
	Ajax(); 
    xmlhttp.abort();
	carregando(divRetorno);
	nomeUrl2 = antiCacheRand(nomeUrl);
    xmlhttp.open("POST", nomeUrl2 ,true);
    xmlhttp.onreadystatechange = function() {   
            if( xmlhttp.readyState == 4 ){   
                   
                var valorRetorno            = xmlhttp.responseText;
                divInsereResposta.innerHTML = valorRetorno;
				apaga_carregando();
                       
            }   
    }   
    xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
    xmlhttp.setRequestHeader("Pragma", "no-cache");
    //xmlhttp.setRequestHeader("Content-Type", "text/html; charset=iso-8859-1");   
	//xmlhttp.setRequestHeader("Content-type: application/xml; charset=UTF-8");
	//xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send('1');   
  
}  

function ajaxUser( nomeUrl, divRetorno ){   
var divInsereResposta = document.getElementById( divRetorno );
  	
	divInsereResposta.innerHTML = "<img src='images/ajax-loader2.gif'> <font face='tahoma' size='2'>Verificando...</font>";
	document.form_cadastro.btn_verifica.disabled = true;
	document.form_cadastro.usuario.disabled = true;
	url2 = antiCacheRand(nomeUrl);
	Ajax(); 
	
	xmlhttp.open("GET", url2, true);
	xmlhttp.onreadystatechange=function() {
	    if (xmlhttp.readyState==4){
			
                divInsereResposta.innerHTML = xmlhttp.responseText;
				document.form_cadastro.btn_verifica.disabled = 0;	
				document.form_cadastro.usuario.disabled = 0;
	    }
	}
	 xmlhttp.send(null)
   
} 

function ajaxPHP( nomeUrl, divRetorno ){   
var divInsereResposta = document.getElementById( divRetorno );
  	
	divInsereResposta.innerHTML = "<center><font face='tahoma' size='2'><b>Carregando...</b></font></center>";
	url2 = antiCacheRand(nomeUrl);
	Ajax(); 
	
	xmlhttp.open("GET", url2, true);
	xmlhttp.onreadystatechange=function() {
	    if (xmlhttp.readyState==4){
			
                divInsereResposta.innerHTML = xmlhttp.responseText;

	    }
	}
	 xmlhttp.send(null)
   
} 


function apaga_carregando(){
		var div_carregando = document.getElementById("LayerCarregando");
		div_carregando.innerHTML = "";
		div_carregando.style.visibility = "hidden";
}
function carregando(divRetorno){
		var div_carregando = document.getElementById("LayerCarregando");
		div_carregando.style.visibility = "visible";
		div_carregando.innerHTML = "<center><table width='220' border='0' cellspacing='0' cellpadding='0'><tr><td><img src='images/ajax-loader.gif' width='220' height='19'></td></tr><tr><td><p align='center' class='loading'><strong>CARREGANDO...</strong></p></td></tr></table></center>";
	    div_carregando.style.width = "234px";
		div_carregando.style.height = "44px";
		div_carregando.style.top = "40px"; // Entrada manual. Entre com o valor da altura do menu ao conteudo onde aparece o carregando.
		tam_body = parseInt(document.body.clientWidth); // Tira o PX do tamanho da janela do browser cliente
		offset = parseInt("10"); // Define o OffSet da margem esquerda do site
		/* Divide Janela do cliente por 2. Subtrai da metade do tamanho do Layer. Soma o Offset do lado direito da pagina. Soma 20 que eh a margem de erro da borda do IE*/
		total_size = (((tam_body/2)-115)+offset)+20;
		total_size = total_size + "px";
    	//div_carregando.style.left = total_size;
		div_carregando.style.left = "250px";
		div_carregando.style.top = "580px";
		/* ((parseint(document.body.clientWidth)/2)-115)-214 + "px"; */

}

function antiCacheRand(aurl){
        var dt = new Date();
        if(aurl.indexOf("?")>=0){// já tem parametros ADAPTA RANDOM / SE NAO CRIA PARAM. RANDOM
            return aurl + "&" + encodeURI(Math.random() + "_" + dt.getTime());
        }else{ return aurl + "?" + encodeURI(Math.random() + "_" + dt.getTime());}
}

function spin(tipo, valor, objeto_form, objeto){
	objOp = document.forms[objeto_form].elements[objeto];
	valor = parseInt(valor);
	if(tipo=="up"){
		if (valor >= 999){
			valor = 999;
		}else{
			valor = parseInt(valor+1);
		}
	}else{
		if(valor <= 1){
			valor = 1;
		}else{
			valor = parseInt(valor-1);
		}
	}
	objOp.value = parseInt(valor);
}

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function telefonem(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function cpfm(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}

function cepm(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}

function cnpjm(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}


function site(v){
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
        caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}
/* =============================================================================================
	 FUNCAO PARA DESABILITAR O ENTER DE UM CAMPO TEXT
	 Adaptado para fins especicos de um Resource já criado
================================================================================================ */
function handleEnter (field, event) {
        var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
        if (keyCode == 13) {
            var i;
            for (i = 0; i < field.form.elements.length; i++)
                if (field == field.form.elements[i])
                    break;
            i = (i + 1) % field.form.elements.length;
            return false;
        } 
        else
        return true;
    }    
	
/*
	AJAX GET CEP - A mesma funcao do AjaxGet mas para CEP
*/
ajaxGet_cep = function(cep, retorno){
	document.getElementById("btn_busca_cep").disabled = true;
	document.forms['form_confirma'].elements["endereco"].value = "Carregando...";
	document.forms['form_confirma'].elements["bairro"].value = "Carregando...";
	document.forms['form_confirma'].elements["cidade"].value = "Carregando...";
	document.forms['form_confirma'].elements["uf"].value = "Carregando...";	
	//document.getElementById("resposta_cep").innerHTML = "<center>Carregando...</center>";
/*
document.forms['form_confirma'].cep_ent.value
*/
	Ajax_cep();
    xmlhttp_cep.abort();
	//carregando(divRetorno);
	nomeUrl = "buscaCEP.php?cep="+cep;
	//alert (nomeUrl);
	nomeUrl2 = antiCacheRand(nomeUrl);
    xmlhttp_cep.open("POST", nomeUrl2 ,true);
	xmlhttp_cep.onreadystatechange = handleResponse;
	document.getElementById("retorno").innerHTML = xmlhttp_cep.responseText;	
	//xmlhttp_cep.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    //xmlhttp_cep.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
    //xmlhttp_cep.setRequestHeader("Pragma", "no-cache");
	//xmlhttp_cep.setRequestHeader("Content-type: application/xml; charset=UTF-8");

    xmlhttp_cep.send('1');  

	document.forms['form_confirma'].elements["btn_busca_cep"].disabled = false;
}  

function handleResponse() { 
   if(xmlhttp_cep.readyState == 4) { 
      var response = xmlhttp_cep.responseText; 
		pega_endereco (response);
   } else {       
      //alert (xmlhttp_cep.readyState);
   } 
} 


function pega_endereco(req){
				var valorRetorno            = req ;
				str=valorRetorno; // extriar o string do controlador hidden
				nsep=4 // número do separador
				for (var i=0;i<nsep;i++){ 
					pos=str.indexOf("|"); 
					if (i==0){
						document.forms['form_confirma'].elements["endereco"].value = str.substring(0,pos);
					}else{
						if(i==1){
							document.forms['form_confirma'].elements["bairro"].value = str.substring(0,pos);
						}else{
							if(i==2){
								document.forms['form_confirma'].elements["cidade"].value = str.substring(0,pos);
							}else{
								if(i==3){
									document.forms['form_confirma'].elements["uf"].value = str.substring(0,pos);
								}
							}
						}
					}
					str=str.substring(pos+1,str.length);		
				}
}

/* ==============================================================================================
FUNCAO PARA PEGAR O ENDERECO DA PAGINA DE CADASTRO
=============================================================================================== */
ajaxGet_cep_cad = function(cep, retorno){
	var divInsereResposta = document.getElementById( retorno );
	document.forms['form_cadastro'].elements["endereco"].value = "Carregando...";
	document.forms['form_cadastro'].elements["bairro"].value = "Carregando...";
	document.forms['form_cadastro'].elements["cidade"].value = "Carregando...";
	document.forms['form_cadastro'].elements["uf"].value = "Carregando...";	

	Ajax_cep();
    xmlhttp_cep.abort();
	//carregando(divRetorno);
	nomeUrl = "buscaCEP.php?cep="+cep;
	//alert (nomeUrl);
	nomeUrl2 = antiCacheRand(nomeUrl);
    xmlhttp_cep.open("POST", nomeUrl2 ,true);
	xmlhttp_cep.onreadystatechange = handleResponse2;
	var valorRetorno = xmlhttp_cep.responseText;
    divInsereResposta.innerHTML = valorRetorno;
	//xmlhttp_cep.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    //xmlhttp_cep.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
    //xmlhttp_cep.setRequestHeader("Pragma", "no-cache");
	//xmlhttp_cep.setRequestHeader("Content-type: application/xml; charset=UTF-8");

    xmlhttp_cep.send('1');  

}  
function handleResponse2() { 
   if(xmlhttp_cep.readyState == 4) { 
      var response = xmlhttp_cep.responseText; 
		pega_endereco2 (response);
   } else {       
      //alert (xmlhttp_cep.readyState);
   } 
} 


function pega_endereco2(req){
				var valorRetorno            = req ;
				str=valorRetorno; // extriar o string do controlador hidden
				nsep=4 // número do separador
				for (var i=0;i<nsep;i++){ 
					pos=str.indexOf("|"); 
					if (i==0){
						document.forms['form_cadastro'].elements["endereco"].value = str.substring(0,pos);
					}else{
						if(i==1){
							document.forms['form_cadastro'].elements["bairro"].value = str.substring(0,pos);
						}else{
							if(i==2){
								document.forms['form_cadastro'].elements["cidade"].value = str.substring(0,pos);
							}else{
								if(i==3){
									document.forms['form_cadastro'].elements["uf"].value = str.substring(0,pos);
								}
							}
						}
					}
					str=str.substring(pos+1,str.length);		
				}
}

  function buscaRastreamentoHome()
 	{
		if(document.rastreamentohome.tipo[0].checked) {
			//nacional
			var theurl = "http://websro.correios.com.br/sro_bin/txect01$.QueryList" + "?" + "P_LINGUA=" + document.rastreamentohome.P_LINGUA.value + "&P_TIPO=" + document.rastreamentohome.P_TIPO.value + "&P_COD_UNI=" + document.rastreamentohome.P_COD_UNI.value ;
			//alert(theurl);
			//alert(document.rastreamentohome.tipo[0].checked)
			window.open(theurl);
			//document.rastreamentohome.submit();
			return (false);
		}
				
		if(document.rastreamentohome.P_COD_UNI.value.substr(0,2)=='XM' || document.rastreamentohome.P_COD_UNI.value.substr(0,2)=='VC'){
  				window.open("http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_COD_UNI="+document.rastreamentohome.P_COD_UNI.value.substr(0,13)+"&P_TIPO=001&P_LINGUA=001","SRO","width=550,height=400,scrollbars=yes,resizable=no,toolbar=no");
  				document.rastreamentohome.P_COD_UNI.value = "";
				return (false);
  		}
		
		if(document.rastreamentohome.tipo[1].checked) {
			//internacional
			var theurl = "http://www.correios.com.br/servicos/rastreamento/internacional/resultado.cfm" 
			//alert(theurl);
			document.rastreamentohome.method = "post";
			document.rastreamentohome.action = theurl;
			var pname = document.createElement("input");
			pname.type="hidden";
			pname.value="P";
			pname.name = "Idioma";
			document.rastreamentohome.appendChild(pname);
			
			pname = document.createElement("input");
			pname.type="hidden";
			pname.value="Pesquisar"
			pname.name = "Consultar";
			document.rastreamentohome.appendChild(pname);
			
			pname = document.createElement("input");
			pname.type="hidden";
			pname.value= document.rastreamentohome.P_COD_UNI.value
			pname.name = "Consulta";
			document.rastreamentohome.appendChild(pname);
			
			//alert(document.rastreamentohome.Consulta.value);
			//alert(document.rastreamentohome.tipo[1].checked)
			
			//document.rastreamentohome.submit();
			return (true);
		}
		
 	}
function enviaBusca()
 {
    ajaxHTML ('busca_produtos.php?criterio='+document.forms['form_busca'].elements['txt_busca'].value, 'conteudo');
	return false;
  }
  
function enviaContato()
 {
    ajaxHTML ('envia_contato.php?nome='+document.forms['form_contato'].elements['nome'].value+'&fone='+document.forms['form_contato'].elements['fone'].value+'&email='+document.forms['form_contato'].elements['email'].value+'&assunto='+document.forms['form_contato'].elements['assunto'].value+'&obs='+document.forms['form_contato'].elements['obs'].value,'conteudo');
	return false;
  }

function MudaFoto(numero){

		thumbs = new Array(5);
		thumbs[1] = document.thumb_a;
		thumbs[2] = document.thumb_b;

		aux = document.foto_principal.src;
		var urlAntiga = aux;
		var urlNova = urlAntiga.replace("tipo=G","tipo=P");
		
		var urlAntiga2 = thumbs[numero].src;
		var urlNova2 = urlAntiga2.replace("tipo=P", "tipo=G");
		
		document.foto_principal.src = urlNova2;
		
		thumbs[numero].src = urlNova;
}
 function MudaBotaoCSS(elemento){
	var eldesc = document.getElementById("btnDescricao"); 
	eldesc.setAttribute("className", ""); 
	var elgarant = document.getElementById("btnGarantia"); 
	elgarant.setAttribute("className", ""); 
	var elobs = document.getElementById("btnObs"); 
	elobs.setAttribute("className", ""); 
	
	var muda = document.getElementById(elemento);
	muda.setAttribute("className", "current");
	
	document.getElementById("divTextoDescricao").style.display="none";
	document.getElementById("divTextoGarantia").style.display="none";
	document.getElementById("divTextoObservacoes").style.display="none";
	
	if(elemento=="btnDescricao"){
		document.getElementById("divTextoDescricao").style.display="block";
	}else if(elemento=="btnGarantia"){
		document.getElementById("divTextoGarantia").style.display="block";
	}else{
		document.getElementById("divTextoObservacoes").style.display="block";
	}
 }
 
 function carBusca()
 {
    ajaxHTML ('busca.php?tipo='+document.forms['form1'].elements['tipo2'].value+'&fabricante='+document.forms['form1'].elements['fabricante'].value+'&modelo='+document.forms['form1'].elements['modelo'].value+'&anoini='+document.forms['form1'].elements['anoini'].value+'&anofim='+document.forms['form1'].elements['anofim'].value+'&precomin='+document.forms['form1'].elements['precomin'].value+'&precomax='+document.forms['form1'].elements['precomax'].value+'&cidade='+document.forms['form1'].elements['cidade'].value,'conteudo');
	return false;
  }
