/*
SCRIPT AJAX

Criado por: Bruno Augusto Ramon dos Santos

Empresa: ClickONE - Solucoes Inteligentes
Razao Social: SANTOS & VENTURA INFORMATICA LTDA-ME
Data Criação: 23/02/2007 - 18:27
Ultima Alteração: 26/02/2007 - 23:28
UA: 12/03/2007 - 18:56

Codigo protegido: GNU/CC
http://creativecommons.org/licenses/by-nc-nd/2.5/br/
Todos os direitos do codigo reservados

Este codigo somente podera ser utilizado para fins comerciais pelo seu criador,
em proteção ao intelecto. A distribuição está sendo feita pela Santos & Ventura
Informatica LTDA - ME sob autorização do criador, que nessa empresa possui sociedade.
A cópia desse código é de distribuição gratuita para fins educacionais desde de
que citada a fonte criadora.
*/

/* ===============================================================================================
	Faz a criacao do objeto ajax
==================================================================================================*/
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;   
            }   
        }   
    }   

}
Ajax2 = function (){   
    try{   
        xmlhttp2 = new XMLHttpRequest();		
    }catch(ee){   
        try{   
            xmlhttp2 = new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){   
            try{   
                xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
            }catch(E){   
                xmlhttp2 = 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;   
            }   
        }   
    }   

}
/* ==============================================================================================
	FUNCAO AJAXGET - Funcao responsavel por pegar as informacoes de uma url e coloca-la num div
================================================================================================= */
ajaxGet = 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;
				//alert(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');   
  
}
ajaxGet2 = function( nomeUrl2, divRetorno2 ){   
  
    divInsereResposta2 = document.getElementById( divRetorno2 );
	//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>";
	Ajax2(); 
    xmlhttp2.abort();
	//carregando(divRetorno2);
	divInsereResposta2.innerHTML = "Aguarde... Calculando!";
	nomeUrl3 = antiCacheRand(nomeUrl2);
    xmlhttp2.open("POST", nomeUrl3 ,true);
    xmlhttp2.onreadystatechange = function() {   
            if( xmlhttp2.readyState == 4 ){   
                   
                var valorRetorno2            = xmlhttp2.responseText;
                divInsereResposta2.innerHTML = valorRetorno2;
				apaga_carregando();
                       
            }   
    }   
    xmlhttp2.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    xmlhttp2.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
    xmlhttp2.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");
    xmlhttp2.send('1');   
  
}  
/* =========================================================================================
	Funcoes que gerenciam o DIV transparente do carregando quando busca via ajax
============================================================================================ */

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='120' border='0' cellspacing='0' cellpadding='0'><tr><td width='32'><img src='imagens/ajax/loading.gif'/></td><td width='88'><span class='loading'>CARREGANDO...</span></td></tr></table></center>";
	    div_carregando.style.width = "230px";
		div_carregando.style.height = "100px";
		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.top = "390px";
		/* ((parseint(document.body.clientWidth)/2)-115)-214 + "px"; */

}
/* =================================================================================
	Funcao para gerar sequencia aleatoria e não gerar cache
==================================================================================== */
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());}
}
/* =================================================================================
FUNCAO SPIN - UP/DOWN PARA BOTOES
==================================================================================== */
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);
}
/*==================================================================================
	Funcoes para mascara de objetos CEP, CNPJ, CPF, INDENTIDADE E TELEFONE
	Adaptação de Resource para fins especificos
==================================================================================== */
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;

	//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){
	
	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_cadastro.php?cep="+cep;
	//alert (nomeUrl);
	nomeUrl2 = antiCacheRand(nomeUrl);
    xmlhttp_cep.open("POST", nomeUrl2 ,true);
	xmlhttp_cep.onreadystatechange = handleResponse2;

	//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()
 {
    ajaxGet ('busca_produtos.php?criterio='+document.forms['form_busca'].elements['txt_busca'].value, 'conteudo');
	return false;
  }
  
function enviaContato()
 {
    ajaxGet ('envia_contato.php?nome='+document.forms['form_contato'].elements['nome'].value+'&telefone='+document.forms['form_contato'].elements['telefone'].value+'&email='+document.forms['form_contato'].elements['email'].value+'&cidade='+document.forms['form_contato'].elements['cidade'].value+'&departamento='+document.forms['form_contato'].elements['departamento'].value+'&assunto='+document.forms['form_contato'].elements['assunto'].value+'&mensagem='+document.forms['form_contato'].elements['mensagem'].value,'conteudo');
	return false;
  }

function MudaFoto(numero){

		thumbs = new Array(5);
		thumbs[1] = document.thumb_a;
		thumbs[2] = document.thumb_b;
		thumbs[3] = document.thumb_c;
		thumbs[4] = document.thumb_d;
		thumbs[5] = document.thumb_e;

		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 jsBusca()
 {
    ajaxGet ('busca.php?criterio='+document.forms['frm_busca'].elements['criterio'].value+'&categoria='+document.forms['frm_busca'].elements['categoria'].value+'&faixa_preco='+document.forms['frm_busca'].elements['faixa_preco'].value,'conteudo');
	return false;
  }
  
		
function abrir(pagina,largura,altura) {

		//pega a resolução do visitante
		w = screen.width;
		h = screen.height;
		
		//divide a resolução por 2, obtendo o centro do monitor
		meio_w = w/2;
		meio_h = h/2;
		
		//diminui o valor da metade da resolução pelo tamanho da janela, fazendo com q ela fique centralizada
		altura2 = altura/2;
		largura2 = largura/2;
		meio1 = meio_h-altura2;
		meio2 = meio_w-largura2;
		
		//abre a nova janela, já com a sua devida posição
		window.open(pagina,'','height=' + altura + ', width=' + largura + ', top='+meio1+', left='+meio2+''); 
}
