﻿
//Crio Objeto "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;
		}
	}
}

function OndeComprarTeclaEnter(e, src, tipo) {
    //IE    
    if (window.event) {
        _TXT = e.keyCode;
    }
    //Firefox
    else if (e.which) {
        _TXT = e.which;
    }    
    if (_TXT == 13) {

        if (src.value.length > 7) {
            if (tipo == '1' ){
                BuscaPotencia();
            }
            pegarCep();
        }
    }
}

function validaCampos(){

    //Guardo campos a serem validados
	var CEP = document.form.cep.value;
	var potencia = document.form.potenciaEquipamento;
	
	var endereco = location.href 	
		
        
    //Essa validação é apenas para a parte de Revendas
    if(endereco.indexOf("revenda") > -1){
        //Independentemente de qual página vier eu tento validar o campo de potência.        
        try{
            //Valido campo de potência
            if( (!potencia[0].checked) && (!potencia[1].checked) && (!potencia[2].checked) && (!potencia[3].checked) ){
                alert("- Por favor escolha a potência do equipamento.");
                return false;
            }
        
        }
            catch(err){
        }
    }      
    
	
	//Valido campo do CEP
	if(CEP.length == 0){
	    alert("- Por favor preencha o CEP.");
	    return false;
	}
	
	return true;
}

//Busco CEP e escrevo campos hidden utilizando componente da Locaweb
function pegarCep(){

    if (validaCampos()){
    
        var CEP = document.form.cep.value;
    
        //Div onde serão escritos os campos hidden
	    var divCamposHidden = $("#camposHidden");
	    $("#ajaxCarregando").html("Carregando...");
    	
	    //Busco resultado por ajax			
	    xmlhttp.open("GET", "/onde-comprar/01sql07/br/ajaxCampos.asp?CEP=" + CEP,true);
	    xmlhttp.onreadystatechange=function() {
		    if (xmlhttp.readyState == 4){		    
			    var resposta = xmlhttp.responseText;			    
			    divCamposHidden.html(resposta);
			    mostraLatitudeLongitude();
			    $("#ajaxCarregando").html("");
		    }
	    }	    	
	    xmlhttp.send(null);    
    }
}

var geocoder = null;
var latitude = "";
var longitude = "";

//Busca latitude e longitude
function mostraLatitudeLongitude() {

    var endereco = "";
    var cep = "";
    var cidade = "";
    
    cidade = document.form.cidade.value;
    cep = document.form.cep.value;   
               
    endereco = document.form.rua.value + ", " + cidade + ", Brasil";
                
    // incluir hífen se o endereço vier sem hifén  
    cep = cep.replace("-","");
    cep = cep.substring(0, 5) + "-" + cep.substring(5,8);    
                                                  
    if (GBrowserIsCompatible()){                        
        geocoder = new GClientGeocoder();          
    }
    
    if(cidade != ""){
        if (geocoder){                
            geocoder.getLatLng(
                endereco,
                function(point) {
                    if (!point) {                        
                        mostraLatitudeLongitudeCep(cep, cidade);
                    } 
                    else {                        
                        document.form.latitude.value = point.lat();
                        document.form.longitude.value = point.lng();
                        document.form.submit();
                    }
                }
            )
        }
    }
    else
    {
        alert("CEP Inválido.")
    }
}

//Busca por cep
function mostraLatitudeLongitudeCep(cep, cidade) {
            
    // incluir hífen se o endereço vier sem hifén  
    cep = cep.replace("-","");
    cep = cep.substring(0, 5) + "-" + cep.substring(5,8);
    cep = cep + ",BR";
               
    if (GBrowserIsCompatible()){    
        geocoder = new GClientGeocoder();          
    }
    if (geocoder){
        geocoder.getLatLng(
            cep,
            function(point) {
                if (!point) {
                    alert(cep + " Endereço inválido.");                            
                } else {
                    latitude = point.lat().toString();
                    longitude = point.lng().toString();     
                    if (latitude.indexOf("-") == -1 || longitude.indexOf("-") == -1){
                        mostraLatitudeLongitudeCidade(cidade, cep);
                    }   else   {                                
                        document.form.latitude.value = point.lat();
                        document.form.longitude.value = point.lng();
                        document.form.submit();
                    }
                }
            }
        )
    }
}

//Busca por cidade
function mostraLatitudeLongitudeCidade(cidade,  cep) {                                   
    
    if (GBrowserIsCompatible()){    
        geocoder = new GClientGeocoder();          
    }
    if (geocoder){
        geocoder.getLatLng(
            cidade,
            function(point) {
                if (!point) {
                    alert(cidade + " Endereço inválido.");
                } else {                            
                    document.form.latitude.value = point.lat();
                    document.form.longitude.value = point.lng();
                    document.form.submit();
                }
            }
        )
    }
}

//Se busca foi por estado, exibe divs abaixo
function exibeBuscaEstado(){
    //Exibo mensagem de busca    
    $("#listaDeLojas").show();
    $("#textoOrdemAlfa").show();
}


function ValidaPotencia(valorCombo, AudioVideo){
    
    var divCep = $("#campoCep");
    var divFaleConosco = $("#divMsgFaleConosco");
    var divResultado = $("#listaDeLojas");
    
    if(AudioVideo) {
		divResultado = $("#divResultAudioVideo");
    }
	else {
		divResultado = $("#divResultAteDois");
    }

    if (valorCombo == 1 || valorCombo == 5 || valorCombo == 6) {        
        //Exibo CEP e escondo mensagens
        divCep.show();
        divFaleConosco.hide();
        divResultado.hide();

        if (!AudioVideo && valorCombo == 1 || valorCombo == 5 || valorCombo == 6) {
			divResultado.show();
        }							
    }
    else if(valorCombo == 2) {
        divFaleConosco.show();
        divCep.hide();
        divResultado.hide();        
    }
    else if(valorCombo == 4 || valorCombo == 3){
        window.open('https://www.dhsms.com.br/como-comprar', 'Comprar', 'scrollbars=yes, status=yes, toolbar=yes, menubar=yes, location=yes, resizable=yes');
        
    }
}

