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 Trim(str) { return str.replace(/^\s+|\s+$/g, ""); }

function getFamilia( categoria ){
    //Verifico catetgoria para exibir mensagem do SAC
    
    if (Trim(categoria) == "Áudio e Vídeo" || Trim(categoria) == "Digital Home" || Trim(categoria) == "Iluminação") {		        
        $("#mensagemSac").show();	            
        $("#btnPesquisar").hide();
        $("#trFamilia").hide();
        $("#listaDeAssistencias").hide();
        $("#textoLojas").hide();
        $("#mensagemFiltro").hide();
    }
    else {
    
        $("#mensagemSac").hide();
        $("#btnPesquisar").show();
        $("#trFamilia").show();
        $("#listaDeAssistencias").show();
        $("#textoLojas").show();
        $("#mensagemFiltro").hide();

        var tdFamilia = document.getElementById("tdFamilia");

        xmlhttp.open("GET", "/aplicacoes/assistencia-tecnica/comboFamilia.asp?categoria=" + escape(categoria), true);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                var resposta = xmlhttp.responseText;
                tdFamilia.innerHTML = resposta;
            }
        }
        try {
            xmlhttp.send(null);
        }
        catch (e) {
            return false;
        }
        
    }
}

var ultimoUF;
		
function alteraCidades( UF, cidadeSelecionada ){
       

    if( UF.length==0 || ultimoUF==UF ) return false; 
    
	ultimoUF = UF;
	
	var divCidade = document.getElementById('divCidade');
	divCidade.innerHTML = " Carregando..."
	
	xmlhttp.open("GET", "/aplicacoes/assistencia-tecnica/cidadesCombo.asp?UF="+ UF,true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4){
			var resposta = xmlhttp.responseText;
			divCidade.innerHTML = resposta;
						
			if(cidadeSelecionada != ""){
			    $("#divCidade select option[value='" + cidadeSelecionada + "']").attr("selected", "selected");
			}			
		}
	}
	xmlhttp.send(null);
}

function pegarCep(){    				
    
    var CEP = document.formAssistencia.cep.value;
        
    if(!validaPesquisa()){
        return false;
    }
	
	$("#divLoad").html("Carregando...");
	
	$.get("/aplicacoes/assistencia-tecnica/ajaxCampos.asp?CEP=" + CEP, null, 
	    function(d){	        
            $("#divCamposHidden").html(d);
            mostraLatitudeLongitude()
        }
    );
}

function MM_formtCep(e,src,mask) {
    if(window.event) { _TXT = e.keyCode; }
    else if(e.which) { _TXT = e.which; }
    if(_TXT > 47 && _TXT < 58) {
    var i = src.value.length; var saida = mask.substring(0,1); var texto = mask.substring(i)
    if (texto.substring(0,1) != saida) { src.value += texto.substring(0,1); }
        return true; } else { if (_TXT != 8) { return false; }
    else { return true; }
    }
}
   
function validaPesquisa(){
    form = document.formAssistencia;
    
    //Verifico se o internauta escolheu alguma das opções: Por CEP ou Por Cidade
    if(form.rdbBusca[0].checked == false && form.rdbBusca[1].checked == false){
        alert("O campo Por Cep ou Por Cidade deve ser preenchido.")
        return false;
    }
    
    //Selecionou o radio Por Cep
    if(form.rdbBusca[0].checked){
        //Verifico se foi preenchido o campo cep
        if(form.cep.value == ""){
            alert("O campo Cep deve ser preenchido.")
            return false;
        }
    }
    
    //Selecionou o radio Por Cidade
    if(form.rdbBusca[1].checked){
        //Verifico se foi preenchido o campo Estado
        if(form.sel_uf.value == ""){
            alert("O campo Estado deve ser preenchido.")
            return false;
        }
        
        //Verifico se foi preenchido o campo Cidade
        if(form.cidadeCombo.value == ""){
            alert("O campo Cidade deve ser preenchido.")
            return false;
        }
    }
    
    return true;
}

function showHideTipoBusca(escolha){
    form = document.formAssistencia;
    form.sel_uf.selectedIndex=0;
    form.cidadeCombo.selectedIndex=0;
    form.cep.value="";
    if (escolha.value=="cepa"){
        $("#cepa").show();
        $("#uf").hide();
    }else{
        $("#cepa").hide();
        $("#uf").show();	            
    }
}

function onLoadAssistencia(){	     
    f = document.formAssistencia;	       
    //alert('<%=request.form("cidadeCombo")%>')
    if(f.rdbBusca[0].checked){
        $("#cep").show();
        $("#uf").hide();
    }
    else{
        if(f.rdbBusca[1].checked){
            $("#uf").show();
            $("#cep").hide();
            alteraCidades( f.sel_uf.value );   	                
            f.cidadeCombo.options[RecuperarIndice('<%=request.form("cidadeCombo")%>', f.cidadeCombo)].selected=true;	                
        }
    }
    
}

function RecuperarIndice(valor, combo){
    for(var i = 0; i < combo.options.length; i ++){
        if(combo.options[i].value == valor)
            return i;
    }
    return -1;
}

var geocoder = null;
var latitude = "";
var longitude = "";   
          
function mostraLatitudeLongitude() {                     
    var endereco = "";
    var cep = "";
    var cidade = "";
    var rua = "";
    var estado = "";
    cidade = document.formAssistencia.cidade.value;
    cep = document.formAssistencia.cep.value;
    endereco = document.formAssistencia.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, rua, estado);
                    } else {
                        document.formAssistencia.latitude.value = point.lat();
                        document.formAssistencia.longitude.value = point.lng();                        
                        document.formAssistencia._action.value = "listar";
                        document.formAssistencia.submit();
                    }
                }
            )
        }
    }
    else
    {
        alert("CEP Inválido.")
    }
}

function mostraLatitudeLongitudeCep(cep, cidade, rua, estado) {       
                           
    // 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(cep, cidade, rua, estado);
                    }   else   {                                
                        document.formAssistencia.latitude.value = point.lat();
                        document.formAssistencia.longitude.value = point.lng();
                        document.formAssistencia._action.value = "listar";
                        document.formAssistencia.submit();
                    }
                }
            }
        )
    }
}

function mostraLatitudeLongitudeCidade(cep, cidade, rua, estado) {                                   
    
    if (GBrowserIsCompatible()){    
        geocoder = new GClientGeocoder();          
    }
    if (geocoder){
        geocoder.getLatLng(
            cidade,
            function(point) {
                if (!point) {
                    alert(cidade + " Endereço inválido.");
                } else {                            
                    document.formAssistencia.latitude.value = point.lat();
                    document.formAssistencia.longitude.value = point.lng();
                    document.formAssistencia._action.value = "listar";
                    document.formAssistencia.submit();
                }
            }
        )
    }
}
