﻿function ajaxInit() {
    var req;
    try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (ex) {
            try {
                req = new XMLHttpRequest();
            } catch (exc) {
                alert("Esse browser não tem recursos para uso do Ajax");
                req = null;
            }
        }
    }
    return req;
}

function AtualizaCidade(Objeto) {
    if (Objeto.value.length > 0) {
        ajax2 = ajaxInit();
        resultado = "";
        if (ajax2) {
            ajax2.open("GET", "ajax/atualiza_cidades.aspx?idEstado=" + Objeto.value + "&Rand=" + Math.ceil(Math.random() * 100000), true);
            ajax2.setRequestHeader("Content-type", "charset=iso-8859-1");
            ajax2.onreadystatechange = function() {
                if (ajax2.readyState == 4) {
                    if (ajax2.status == 200) {
                        resultado = ajax2.responseText;
                        if (resultado.length > 0) {
                            if (resultado == "erro") {
                                alert("ERRO:\n\nOcorreu um erro ao tentar carregar as Cidades. Tente novamente!");
                                document.getElementById("idSubLocalizacao").options.length = 0;
                                document.getElementById("idSubLocalizacao").options[0] = new Option("Selecione o Estado!", "");
                            } else {
                                splitResultado = resultado.split("|");
                                document.getElementById("idSubLocalizacao").options.length = 0;
                                //document.getElementById("Cidade").options[0] = new Option("Selecione", "");
                                for (x = 0; x < splitResultado.length - 1; x++) {
                                    valores = splitResultado[x].split("**");
                                    document.getElementById("idSubLocalizacao").options[x] = new Option(valores[0], valores[1]);
                                }
                            }
                        } else {
                            document.getElementById("idSubLocalizacao").options.length = 0;
                            document.getElementById("idSubLocalizacao").options[0] = new Option("Nenhuma Cidade encontrada!", "");
                        }
                    } else {
                        alert("ERRO:\n\nOcorreu um erro ao tentar carregar as Cidades. Tente novamente!");
                        document.getElementById("idSubLocalizacao").options.length = 0;
                        document.getElementById("idSubLocalizacao").options[0] = new Option("Nenhuma Cidade encontrada!", "");
                    }
                }
            }
            ajax2.send(null);
        }
    } else {
        alert("ERRO:\n\nSelecione um Estado!");
        document.getElementById("idSubLocalizacao").options.length = 0;
        document.getElementById("idSubLocalizacao").options[0] = new Option("Nenhuma Cidade encontrada!", "");
    }
}

function AtualizaEstado(Objeto, TextoEstado) {
    if (Objeto.value.length > 0) {
        ajax2 = ajaxInit();
        resultado = "";
        idSubOperacao = document.getElementById("idSubOperacao").value;
        if (Objeto.value == 2) {
            idSubOperacao = "";
        }
        if (ajax2) {
            ajax2.open("GET", "ajax/atualiza_estados.aspx?idOperacao=" + Objeto.value + "&idSubOperacao=" + idSubOperacao + "&Rand=" + Math.ceil(Math.random() * 100000), true);
            ajax2.setRequestHeader("Content-type", "charset=iso-8859-1");
            ajax2.onreadystatechange = function() {
                if (ajax2.readyState == 4) {
                    if (ajax2.status == 200) {
                        resultado = ajax2.responseText;
                        if (resultado.length > 0) {
                            if (resultado == "erro") {
                                alert("ERRO:\n\nOcorreu um erro ao tentar carregar os Estados. Tente novamente!");
                                document.getElementById("idLocalizacao").options.length = 0;
                                document.getElementById("idLocalizacao").options[0] = new Option("Selecione o Tipo!", "");
                                document.getElementById("idSubLocalizacao").options.length = 0;
                                document.getElementById("idSubLocalizacao").options[0] = new Option("Selecione o Estado!", "");
                            } else {
                                splitResultado = resultado.split("|");
                                document.getElementById("idLocalizacao").options.length = 0;
                                //document.getElementById("Cidade").options[0] = new Option("Selecione", "");
                                idSelecionaEstado = 0;
                                for (x = 0; x < splitResultado.length - 1; x++) {
                                    valores = splitResultado[x].split("**");
                                    if ((valores[0].indexOf(TextoEstado) >= 0) && (idSelecionaEstado == 0)) {
                                        idSelecionaEstado = x;
                                    }
                                    document.getElementById("idLocalizacao").options[x] = new Option(valores[0], valores[1]);                                    
                                }
                                document.getElementById("idLocalizacao").selectedIndex = idSelecionaEstado;
                                AtualizaCidade(document.getElementById("idLocalizacao"));
                            }
                        } else {
                            document.getElementById("idLocalizacao").options.length = 0;
                            document.getElementById("idLocalizacao").options[0] = new Option("Nenhum Estado encontrado!", "");
                            document.getElementById("idSubLocalizacao").options.length = 0;
                            document.getElementById("idSubLocalizacao").options[0] = new Option("Nenhuma Cidade encontrada!", "");
                        }
                    } else {
                        alert("ERRO:\n\nOcorreu um erro ao tentar carregar os Estados. Tente novamente!");
                        document.getElementById("idLocalizacao").options.length = 0;
                        document.getElementById("idLocalizacao").options[0] = new Option("Nenhum Estado encontrado!", "");
                        document.getElementById("idSubLocalizacao").options.length = 0;
                        document.getElementById("idSubLocalizacao").options[0] = new Option("Nenhuma Cidade encontrada!", "");
                    }
                }
            }
            ajax2.send(null);
        }
    } else {
        alert("ERRO:\n\nSelecione um Tipo!");
        document.getElementById("idLocalizacao").options.length = 0;
        document.getElementById("idLocalizacao").options[0] = new Option("Nenhum Estado encontrado!", "");
    }
}

function BuscarImoveis() {
    URL = "";
    Estado = document.getElementById("idLocalizacao").value;
    UF = "";
    if ((Estado >= 1) && (Estado <= 3)) {
        UF = "sp";
    }
    else if ((Estado >= 4) && (Estado <= 5)) {
        UF = "rj";
    } else {
        UF = document.getElementById("idLocalizacao")[document.getElementById("idLocalizacao").selectedIndex].text;
        UF = UF.substring(UF.lastIndexOf("(")+1, UF.lastIndexOf(")")).toLowerCase();
    }
    for (x = 0; x <= 2; x++) {
        if (document.frmPesquisa.idOperacaoBusca[x].checked) {
            idOperacaoBusca = document.frmPesquisa.idOperacaoBusca[x].value;
            break;
        }
    }
    if (document.getElementById("idSubOperacao").value == 1) {
        URL += "residenciais";
    } else if (document.getElementById("idSubOperacao").value == 2) {
        URL += "comerciais";
    } else if (document.getElementById("idSubOperacao").value == 4) {
        URL += "rurais";
    } else {
        URL += "terrenos";
    }
    if (idOperacaoBusca == 1) {
        URL += "-compra-venda";
    } else if (idOperacaoBusca == 4) {
        URL += "-locacao";
    } else {
        URL = "temporada";
    }
    if (idOperacaoBusca != 2) {
        URL += "/" + UF;
        Cidade = tiraAcento(document.getElementById("idSubLocalizacao")[document.getElementById("idSubLocalizacao").selectedIndex].text.toLowerCase());
        while (Cidade.indexOf(" ") >= 0) {
            Cidade = Cidade.replace(" ", "-");
        }
        URL += "/" + Cidade;
        URL += "/localidades.iw?";
        PrecoMaximo = document.getElementById("PrecoMaximo").value;
        if (PrecoMaximo.length > 0) {
            URL += "precomaximo=" + PrecoMaximo;
        }
        Quartos = document.getElementById("Quartos").value;
        if (Quartos == "*") {
            if (PrecoMaximo.length > 0) {
                URL += "&";
            }
            URL += "quartos=0,1,2,3,4,5";
        } else {
            if (PrecoMaximo.length > 0) {
                URL += "&";
            }
            URL += "quartos=" + Quartos;
        }
        URL += "&idlocalizacao=" + document.getElementById("idLocalizacao").value;
        URL += "&idsublocalizacao=" + document.getElementById("idSubLocalizacao").value;
        PrecoMaximo = document.getElementById("PrecoMaximo").value
    } else {
        Cidade = tiraAcento(document.getElementById("idSubLocalizacao")[document.getElementById("idSubLocalizacao").selectedIndex].text.toLowerCase());
        while (Cidade.indexOf(" ") >= 0) {
            Cidade = Cidade.replace(" ", "-");
        }
        URL += "/" + Cidade;
        URL += "/localidades.iw?";
        for (x = 0; x <= 3; x++) {
            if (document.frmPesquisa.idFinalidade[x].checked) {
                FinalidadeSelecionada = document.frmPesquisa.idFinalidade[x].value;
                break;
            }
        }
        URL += "&finalidade=" + FinalidadeSelecionada;
        URL += "&idlocalizacao=" + document.getElementById("idLocalizacao").value;
        URL += "&idsublocalizacao=" + document.getElementById("idSubLocalizacao").value;
        Quartos = "*";
        PrecoMaximo = "";
    }
    ajax2 = ajaxInit();
    resultado = "";
    if (ajax2) {
        if (Quartos == "*") {
            ajax2.open("GET", "ajax/verifica_busca.aspx?idOperacaoBusca=" + idOperacaoBusca + "&idSubOperacaoBusca=" + document.getElementById("idSubOperacao").value + "&idLocalizacaoBusca=" + document.getElementById("idLocalizacao").value + "&idSubLocalizacaoBusca=" + document.getElementById("idSubLocalizacao").value + "&Quartos=0,1,2,3,4,5&PrecoMaximo=" + PrecoMaximo + "&Rand=" + Math.ceil(Math.random() * 100000), true);
        } else {
            ajax2.open("GET", "ajax/verifica_busca.aspx?idOperacaoBusca=" + idOperacaoBusca + "&idSubOperacaoBusca=" + document.getElementById("idSubOperacao").value + "&idLocalizacaoBusca=" + document.getElementById("idLocalizacao").value + "&idSubLocalizacaoBusca=" + document.getElementById("idSubLocalizacao").value + "&Quartos=" + document.getElementById("Quartos").value + "&PrecoMaximo=" + document.getElementById("PrecoMaximo").value + "&Rand=" + Math.ceil(Math.random() * 100000), true);
        }
        ajax2.setRequestHeader("Content-type", "charset=iso-8859-1");
        ajax2.onreadystatechange = function() {
            if (ajax2.readyState == 4) {
                if (ajax2.status == 200) {
                    resultado = ajax2.responseText;
                    if (resultado.length > 0) {
                        if (resultado > 1) {
                            location.href = "http://www.imovelweb.com.br/" + URL;
                        } else {
                            if (resultado == 0) {
                                alert("Não existem imóveis disponíveis para essa seleção de busca, selecione novos critérios e refaça a busca.");
                            } else {
                                URL = URL.replace("localidades.iw", resultado.length + "/imoveis.iw");
                                location.href = "http://www.imovelweb.com.br/" + URL;
                            }
                        }
                    } else {
                        location.href = "http://www.imovelweb.com.br/" + URL;
                    }
                } else {
                    location.href = "http://www.imovelweb.com.br/" + URL;
                }
            }
        }
        ajax2.send(null);
    }    
}

function tiraAcento(text) {
    text = text.replace(new RegExp('[áàâã]', 'gi'), 'a');
    text = text.replace(new RegExp('[éèê]', 'gi'), 'e');
    text = text.replace(new RegExp('[íìî]', 'gi'), 'i');
    text = text.replace(new RegExp('[óòôõ]', 'gi'), 'o');
    text = text.replace(new RegExp('[úúû]', 'gi'), 'u');
    text = text.replace(new RegExp('[ç]', 'gi'), 'c');
    return text;
}

function VerificaTipo(Objeto, TextoEstado) {
    if ((Objeto.value == 1) || (Objeto.value == 4)) {
        document.getElementById("titulo_cidade").style.display = "block";
        document.getElementById("idSubLocalizacao").style.display = "block";
        document.getElementById("titulo_tipo").style.display = "block";
        document.getElementById("titulo_tipo_off").style.display = "none";
        document.getElementById("idSubOperacao").style.display = "block";
        document.getElementById("titulo_preco_maximo").style.display = "block";
        document.getElementById("titulo_preco_maximo_off").style.display = "none";
        document.getElementById("PrecoMaximo").style.display = "block";
        document.getElementById("titulo_quartos").style.display = "block";
        document.getElementById("titulo_quartos_off").style.display = "none";
        document.getElementById("Quartos").style.display = "block";
        document.getElementById("titulo_finalidades").style.display = "none";
        document.getElementById("valores_finalidades").style.display = "none";
    } else {
        document.getElementById("titulo_cidade").style.display = "none";
        document.getElementById("idSubLocalizacao").style.display = "none";
        document.getElementById("titulo_tipo").style.display = "none";
        document.getElementById("titulo_tipo_off").style.display = "block";
        document.getElementById("idSubOperacao").style.display = "none";
        document.getElementById("titulo_preco_maximo").style.display = "none";
        document.getElementById("titulo_preco_maximo_off").style.display = "block";
        document.getElementById("PrecoMaximo").style.display = "none";
        document.getElementById("titulo_quartos").style.display = "none";
        document.getElementById("titulo_quartos_off").style.display = "block";
        document.getElementById("Quartos").style.display = "none";
        document.getElementById("titulo_finalidades").style.display = "block";
        document.getElementById("valores_finalidades").style.display = "block";
    }
    AtualizaEstado(Objeto, TextoEstado);
}
