(function($) {
    $.fn.placeholder = function(options) {
        var defaults = {css_class: "placeholder"};
        var options = $.extend(defaults, options);
        this.each(function() {
            if ($(this).attr('placeholder') !== undefined) {
            var phvalue = $(this).attr("placeholder");
            var currvalue = $(this).attr("value");
            if (phvalue == currvalue) {
                $(this).addClass(options.css_class);
            }
            if (currvalue == "") {
                $(this).addClass(options.css_class);
                $(this).val(phvalue);
            }
            $(this).focusin(function(){
                var ph = $(this).attr("placeholder");
                if (ph == $(this).val()) {
                    $(this).val("").removeClass(options.css_class);
                }
            });

            $(this).focusout(function(){
                var ph = $(this).attr("placeholder");
                if ($(this).val() == "") {
                    $(this).val(ph).addClass(options.css_class);
                }
            });
            }
        });
return this;
    };
})(jQuery);
function rawurlencode(str){
    var hex_chars = "0123456789ABCDEF";
    var noEncode = /^([a-zA-Z0-9\_\-\.])$/;
    var n, strCode, hex1, hex2, strEncode = "";
    for(n = 0; n < str.length; n++) {
            if (noEncode.test(str.charAt(n))){
                                       strEncode += str.charAt(n);
            }else{
                    strCode = str.charCodeAt(n);
                    hex1 = hex_chars.charAt(Math.floor(strCode / 16));
                    hex2 = hex_chars.charAt(strCode % 16);
                    strEncode += "%" + (hex1 + hex2);
            }
    }
    return strEncode;
}
function rawurldecode(str){
    var n, strCode, strDecode = "";
    for (n = 0; n < str.length; n++) {
        if (str.charAt(n) == "%"){
                strCode = str.charAt(n + 1) + str.charAt(n + 2);
                strDecode += String.fromCharCode(parseInt(strCode, 16));
                n += 2;
        }else{
                strDecode += str.charAt(n);
        }
    }
    return strDecode;
}
function abrirCombo(div, pagina){
    var list = ['lista_tipos_filtro','lista_localidades_filtro','lista_bairros_filtro',
        'lista_zona_filtro','lista_cidades','lista_estados'];
    if (pagina == "principal") {
        list.concat(['lista_categorias','lista_dormitorios','lista_valor_maximo']);
    }
    if (pagina == "resultado"){}
    for(var i in list){
        if(list[i] == div){continue;}
        $('#'+list[i]).hide();
    }
    if($('#'+div).css('display') != 'block'){$('#'+div).fadeIn();} else {$('#'+div).hide();}
    $('img[original]').each(function(){$(this).attr('src',$(this).attr('original'));})
}
function selecionarCategoria(categoria, pagina){
	document.getElementById("categorias").innerHTML = $("#lista_categorias div.opcao_combo[tcateg='"+categoria+"']").html();
	document.getElementById("lista_categorias").style.display = "none";
	if (pagina == "principal") {document.getElementById("busca_inicial_categoria").value = categoria;}
	if (pagina == "resultado") {document.getElementById("busca_lateral_categoria").value = categoria;}
}
function selecionarDormitorio(dormitorio){
	if(dormitorio == "INDIFERENTE"){
		document.getElementById("dormitorios").innerHTML = dormitorio;
	}else{
		document.getElementById("dormitorios").innerHTML = dormitorio + "<div id=\"mais\" style=\"float:right;margin-right:66px;*margin-right:65px;*margin-top:-13px;\"> OU +\</div>";
	}
	document.getElementById("lista_dormitorios").style.display = "none";
	document.getElementById("busca_inicial_dormitorios").value = dormitorio;
}
function selecionarValorMaximo(valor_maximo, valor_maximo_busca){
	document.getElementById("valor_maximo").innerHTML = valor_maximo;
	document.getElementById("lista_valor_maximo").style.display = "none";
	document.getElementById("busca_inicial_valor_maximo").value = valor_maximo_busca;
}
function capitalEstado(estado){
    switch(estado){
        case "SP":return "SÃO PAULO";break;
        case "AC":return "RIO BRANCO";break;
        case "AL":return "MACEIÓ";break;
        case "AM":return "MANAUS";break;
        case "AP":return "MACAPÁ";break;
        case "BA":return "SALVADOR";break;
        case "CE":return "FORTALEZA";break;
        case "DF":return "BRASÍLIA";break;
        case "ES":return "VITÓRIA";break;
        case "GO":return "GOIÂNIA";break;
        case "MA":return "SÃO LUÍS";break;
        case "MG":return "BELO HORIZONTE";break;
        case "MS":return "CAMPO GRANDE";break;
        case "MT":return "CUIABÁ";break;
        case "PA":return "BELÉM";break;
        case "PB":return "JOÃO PESSOA";break;
        case "PE":return "RECIFE";break;
        case "PI":return "TERESINA";break;
        case "PR":return "CURITIBA";break;
        case "RJ":return "RIO DE JANEIRO";break;
        case "RN":return "NATAL";break;
        case "RO":return "PORTO VELHO";break;
        case "RR":return "BOA VISTA";break;
        case "RS":return "PORTO ALEGRE";break;
        case "SC":return "FLORIANÓPOLIS";break;
        case "SE":return "ARACAJU";break;
        case "TO":return "PALMAS";break;
        default:return "SÃO PAULO";
    }   
}
function selecionarEstado(estado, pagina){
        $("#carregando").show();
        document.getElementById("carregando").style.top = $(document).scrollTop() + 10 + "px";
        if (pagina == "resultado"){
            $.post("/controllers/ResultadoBuscaControl.php",{acao: "carregar_cidades", estado: estado},function(data){
                $("#lista_cidades").html(data);
                var capital = "";
                capital = capitalEstado(estado);
                var cap = 0;
                var tot = ($("#lista_cidades div.opcao_combo").length);
                var cidade;
                var cidade_val;
                if (tot == 1){
                    cidade = ($("#lista_cidades div.opcao_combo:first").html());
                    cidade_val = $("#lista_cidades div.opcao_combo:first").attr('tcidade');
                }else{
                    for (k=1; k <= tot; k++){
                        if ($("#lista_cidades div.opcao_combo:eq("+k+")").html() == capital){
                            cap = 1;
                            cidade = capital;
                            cidade_val = $("#lista_cidades div.opcao_combo:eq("+k+")").attr('tcidade');
                        }
                    }
                    if (cap != 1){
                        cidade = ($("#lista_cidades div.opcao_combo:first").html());
                        cidade_val = $("#lista_cidades div.opcao_combo:first").attr('tcidade');
                    }
                }
                document.getElementById("estados").innerHTML = estado;
                document.getElementById("lista_estados").style.display = "none";
                document.getElementById("busca_lateral_estado").value = estado;
                document.getElementById("busca_lateral_cidade").value = cidade_val;
                document.getElementById("busca_lateral_zona").value = "";
                document.getElementById("zona").innerHTML = "ZONA";
                document.getElementById("busca_lateral_localidade").value = '';
                document.getElementById("localidades").innerHTML = "LOCALIDADE";
                document.getElementById("busca_lateral_bairro").value = "";
                document.getElementById("bairros").innerHTML = "BAIRRO";
                if (cidade.length >= 12) {
                    $("#cidades").html(cidade.substr(0, 12) + "...");
                }else{
                    $("#cidades").html(cidade);
                }
                $("#carregando").hide();
                filtrarResultado(1);
            });
        }else{
            var uso,desejo;
            uso = document.getElementById("busca_inicial_uso").value;
            desejo = document.getElementById("busca_inicial_desejo").value;
            $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_cidades", uso: uso, desejo: desejo, estado: estado},function(data){
		$("#lista_cidades").html(data);
                var capital = "";
                capital = capitalEstado(estado);
                var cap = 0;
                var tot = ($("#lista_cidades div.opcao_combo").length);
                var cidade;
                var cidade_val;
                if (tot == 1) {
                    cidade = ($("#lista_cidades div.opcao_combo:first").html());
                    cidade_val = $("#lista_cidades div.opcao_combo:first").attr('tcidade');
                }else{
                    for (k=1; k <= tot; k++){
                        if ($("#lista_cidades div.opcao_combo:eq("+k+")").html() == capital){
                            cap = 1;
                            cidade = capital;
                            cidade_val = $("#lista_cidades div.opcao_combo:eq("+k+")").attr('tcidade');
                        }
                    }
                    if (cap != 1){
                        cidade = ($("#lista_cidades div.opcao_combo:first").html());
                        cidade_val = $("#lista_cidades div.opcao_combo:first").attr('tcidade');
                    }
                }
                document.getElementById("estados").innerHTML = estado;
                document.getElementById("lista_estados").style.display = "none";
                if (cidade.length >= 12){
                    $("#cidades").html(cidade.substr(0, 12) + "&hellip;");
                }else{
                    $("#cidades").html(cidade);
                }
                document.getElementById("busca_inicial_estado").value = estado;
                selecionarCidade(cidade_val,estado,pagina);
                $("#carregando").hide();
            });
        }
}
function selecionarCidade(cidade, estado, pagina){
    $("#carregando").show();
    document.getElementById("carregando").style.top = $(document).scrollTop() + 10 + "px";
    if (pagina == "principal"){
        if(estado == 'SP' && cidade == 'sao paulo'){
            $("#carregando").hide();  
            $(".selecao-zona").show();
            $(".selecao-localidade").show();
            $(".selecao-bairro").hide();
        }else{
            var loc = "";
            var zon = "";
            $.post("/controllers/BuscaInicialControl.php",{acao: "verifica_combos", estado: estado, cidade: cidade},function(data){
                loc = data[0];
                zon = data[1];
                if (zon > 0){
                    $(".selecao-zona").show();
                }else{
                    $(".selecao-zona").hide();
                }
                if (loc > 0){
                    $("#carregando").hide();
                    $(".selecao-localidade").show();
                    $(".selecao-bairro").hide();
                }else{
                    $("#carregando").hide();
                    $(".selecao-bairro").show();
                    $(".selecao-localidade").hide();
                }
            });
        }
        document.getElementById("zona").innerHTML = "SELECIONE";
        document.getElementById("localidades").innerHTML = "SELECIONE";
        document.getElementById("bairros").innerHTML = "SELECIONE";
    }else{
        if(estado == 'SP' && cidade == 'sao paulo'){
            $("#zona").show();
            $("#localidades").show();
            $("#bairros").hide();
        }else{
            $("#zona").hide();
            $("#localidades").hide();
            $("#bairros").show();
        }
    }
    document.getElementById("estados").innerHTML = estado;
    document.getElementById("lista_estados").style.display = "none";
    var _cidadeText = $("#lista_cidades div.opcao_combo[tcidade='"+cidade+"']").html();
    if (cidade.length >= 12) {
            _cidadeText = _cidadeText.substr(0, 12) +"&hellip;";
    }
    $("#cidades").html(_cidadeText);
    document.getElementById("lista_cidades").style.display = "none";
    if (pagina == "principal") {
        document.getElementById("busca_inicial_alterada").value = 1;
        document.getElementById("busca_inicial_cidade").value = cidade;
        document.getElementById("busca_inicial_zona").value = '';
        document.getElementById("busca_inicial_localidade").value = '';
        document.getElementById("busca_inicial_bairro").value = '';
    }
    if (pagina == "resultado") {
        document.getElementById("busca_lateral_estado").value = estado;
        document.getElementById("busca_lateral_cidade").value = cidade;
        document.getElementById("busca_lateral_zona").value = '';
        document.getElementById("busca_lateral_localidade").value = '';
        document.getElementById("busca_lateral_bairro").value = '';
    }
}
function listarZonas(pagina){
    if (pagina == "principal"){
        var alterada = $("#busca_inicial_alterada").val();
        if (alterada == 1){
            var uso = $("#busca_inicial_uso").val();
            var desejo = $("#busca_inicial_desejo").val();
            var estado = $("#busca_inicial_estado").val();
            var cidade = $("#busca_inicial_cidade").val();
            var zona = $("#busca_inicial_zona").val();
            $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_zonas", uso: uso, desejo: desejo, estado: estado, cidade: cidade},function(data){
                $("#lista_zona_conteudo").html(data);
            });
            $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_localidades", uso: uso, desejo: desejo, estado: estado, cidade: cidade, zona: zona},function(data){
                    $("#lista_localidades_conteudo").html(data);
            });
        }
        document.getElementById("busca_inicial_alterada").value = 0;
        abrirCombo('lista_zona', 'principal');
    }else{
        $.post("/controllers/FiltroResultadoBuscaControl.php",{acao: "carregar_zonas"},function(data){
            $("#lista_zona_conteudo").html(data);
        });
        abrirCombo('lista_zona_filtro', 'resultado');
    }
}
function listarLocalidades(pagina){
    if (pagina == "principal"){
        var alterada = $("#busca_inicial_alterada").val();
        if (alterada == 1){
            var uso = $("#busca_inicial_uso").val();
            var desejo = $("#busca_inicial_desejo").val();
            var estado = $("#busca_inicial_estado").val();
            var cidade = $("#busca_inicial_cidade").val();
            var zona = $("#busca_inicial_zona").val();
            $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_zonas", uso: uso, desejo: desejo, estado: estado, cidade: cidade},function(data){
                $("#lista_zona_conteudo").html(data);
            });
            $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_localidades", uso: uso, desejo: desejo, estado: estado, cidade: cidade, zona: zona},function(data){
                    $("#lista_localidades_conteudo").html(data);
            });
        }
        document.getElementById("busca_inicial_alterada").value = 0;
        abrirCombo('lista_localidades', 'principal');
    }else{
        $.post("/controllers/FiltroResultadoBuscaControl.php",{acao: "carregar_localidades"},function(data){
            $("#lista_localidades_conteudo").html(data);
        });
        abrirCombo('lista_localidades_filtro', 'resultado');
    }
}
function listarBairros(pagina){
    if (pagina == "principal"){
        var alterada = $("#busca_inicial_alterada").val();
        if (alterada == 1){
            var uso = $("#busca_inicial_uso").val();
            var desejo = $("#busca_inicial_desejo").val();
            var estado = $("#busca_inicial_estado").val();
            var cidade = $("#busca_inicial_cidade").val();
            $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_bairros", uso: uso, desejo: desejo, estado: estado, cidade: cidade},function(data){
                $("#lista_bairros_conteudo").html(data);
            });
        }
        document.getElementById("busca_inicial_alterada").value = 0;
        abrirCombo('lista_bairros', 'principal');
    }else{
        $.post("/controllers/FiltroResultadoBuscaControl.php",{acao: "carregar_bairros"},function(data){
            $("#lista_bairros_conteudo").html(data);
        });
        abrirCombo('lista_bairros_filtro', 'resultado');
    }
}    
function selecionarZonas(pagina){
	var qtdZonas = $("input[name='zona_imoveis']:checked").length;
	var zonas_lista = $("input[name='zona_imoveis']:checked").eq(0).val();
        var zonas_lista_html = $("input[name='zona_imoveis']:checked").eq(0).attr('tzona');
        if (qtdZonas > 1) {
            for (var i = 1; i < qtdZonas; i ++) {
                zonas_lista = zonas_lista + ", " + $("input[name='zona_imoveis']:checked").eq(i).val();
                zonas_lista_html = zonas_lista_html + ", " + $("input[name='zona_imoveis']:checked").eq(i).attr('tzona');
            }
        }
        if (pagina == "principal") {
            if (zonas_lista != undefined && zonas_lista.substr(0, 12) != "") {
                    document.getElementById("busca_inicial_zona").value = zonas_lista;
                    document.getElementById("zona").innerHTML = zonas_lista_html.substr(0, 12) +"&hellip;";
                    document.getElementById("busca_inicial_localidade").value = '';
                    document.getElementById("localidades").innerHTML = "SELECIONE";
            }else{
                    document.getElementById("busca_inicial_zona").value = "";
                    document.getElementById("zona").innerHTML = "SELECIONE";
                    document.getElementById("busca_inicial_localidade").value = '';
                    document.getElementById("localidades").innerHTML = "SELECIONE";
            }
            var desejo = document.getElementById("busca_inicial_desejo").value;
            var uso = document.getElementById("busca_inicial_uso").value;
            var estado = document.getElementById("busca_inicial_estado").value;
            var cidade = document.getElementById("busca_inicial_cidade").value;
            var zona = document.getElementById("busca_inicial_zona").value;
            $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_localidades", uso: uso, desejo: desejo, estado: estado, cidade: cidade, zona: zona},function(data){
                $("#lista_localidades_conteudo").html(data);
            });
	}
	if (pagina == "resultado") {
            if (zonas_lista != undefined && zonas_lista.substr(0, 12) != "") {
                    document.getElementById("busca_lateral_zona").value = zonas_lista;
                    document.getElementById("zona").innerHTML = zonas_lista_html.substr(0, 12) +"&hellip;";
                    document.getElementById("busca_lateral_localidade").value = '';
                    document.getElementById("localidades").innerHTML = "LOCALIDADE";
            }else{
                    document.getElementById("busca_lateral_zona").value = "";
                    document.getElementById("zona").innerHTML = "ZONA";
                    document.getElementById("busca_lateral_localidade").value = '';
                    document.getElementById("localidades").innerHTML = "LOCALIDADE";
            }
	}
}
function selecionarLocalidades(pagina){
	var qtdLocalidades = $("input[name='localidades_imoveis']:checked").length;
	var localidades_lista = $("input[name='localidades_imoveis']:checked").eq(0).val();
        var localidades_lista_html = $("input[name='localidades_imoveis']:checked").eq(0).attr('tlocalidade');
        if (qtdLocalidades > 1) {
            for (var i = 1; i < qtdLocalidades; i ++) {
                localidades_lista = localidades_lista + ", " + $("input[name='localidades_imoveis']:checked").eq(i).val();
                localidades_lista_html = localidades_lista_html + ", " + $("input[name='localidades_imoveis']:checked").eq(i).attr('tlocalidade');
            }
        }
        if (pagina == "principal") {
            if (localidades_lista != undefined && localidades_lista.substr(0, 12) != "") {
                    document.getElementById("busca_inicial_localidade").value = localidades_lista;
                    document.getElementById("localidades").innerHTML = localidades_lista_html.substr(0, 12) +"&hellip;";
            }else{
                    document.getElementById("busca_inicial_localidade").value = "";
                    document.getElementById("localidades").innerHTML = "SELECIONE";
            }
	}
	if (pagina == "resultado") {
            if (localidades_lista != undefined && localidades_lista.substr(0, 12) != "") {
                    document.getElementById("busca_lateral_localidade").value = localidades_lista;
                    document.getElementById("localidades").innerHTML = localidades_lista_html.substr(0, 12) +"&hellip;";
            }else{
                    document.getElementById("busca_lateral_localidade").value = "";
                    document.getElementById("localidades").innerHTML = "SELECIONE";
            }
	}
}
function selecionarBairros(pagina){
	var qtdBairros = $("input[name='bairros_imoveis']:checked").length;
	var bairros_lista = $("input[name='bairros_imoveis']:checked").eq(0).val();
        var bairros_lista_html = $("input[name='bairros_imoveis']:checked").eq(0).attr('tbairro');
        if (qtdBairros > 1) {
            for (var i = 1; i < qtdBairros; i ++) {
                bairros_lista = bairros_lista + ", " + $("input[name='bairros_imoveis']:checked").eq(i).val();
                bairros_lista_html = bairros_lista_html + ", " + $("input[name='bairros_imoveis']:checked").eq(i).attr('tbairro');
            }
        }
        if (pagina == "principal") {
            if (bairros_lista != undefined && bairros_lista.substr(0, 12) != "") {
                    document.getElementById("busca_inicial_bairro").value = bairros_lista;
                    document.getElementById("bairros").innerHTML = bairros_lista_html.substr(0, 12) +"&hellip;";
            }else{
                    document.getElementById("busca_inicial_bairro").value = "";
                    document.getElementById("bairros").innerHTML = "SELECIONE";
            }
	}
	if (pagina == "resultado") {
            if (bairros_lista != undefined && bairros_lista.substr(0, 12) != "") {
                    document.getElementById("busca_lateral_bairro").value = bairros_lista;
                    document.getElementById("bairros").innerHTML = bairros_lista_html.substr(0, 12) +"&hellip;";
            }else{
                    document.getElementById("busca_lateral_bairro").value = "";
                    document.getElementById("bairros").innerHTML = "SELECIONE";
            }
	}
}
function selecionarTipos(pagina){
        var qtdTipos = $("input[name='tipos_imoveis']:checked").length;
	var tipos_lista = $("input[name='tipos_imoveis']:checked").eq(0).val();
        var tipos_lista_html = $("input[name='tipos_imoveis']:checked").eq(0).attr('ttipo');
        if (qtdTipos > 1) {
            for (var i = 1; i < qtdTipos; i ++) {
                tipos_lista = tipos_lista + ", " + $("input[name='tipos_imoveis']:checked").eq(i).val();
                tipos_lista_html = tipos_lista_html + ", " + $("input[name='tipos_imoveis']:checked").eq(i).attr('ttipo');
            }
        }
	if (pagina == "principal") {
            if (tipos_lista != undefined && tipos_lista.substr(0, 8) != "") {
		document.getElementById("busca_inicial_tipo").value = tipos_lista;
		document.getElementById("tipos").innerHTML = tipos_lista_html.substr(0, 8) +"&hellip;";
            }else{
		document.getElementById("busca_inicial_tipo").value = "";
		document.getElementById("tipos").innerHTML = "SELECIONE";
            }
	}
	if (pagina == "resultado"){
            if (tipos_lista != undefined && tipos_lista.substr(0, 8) != "") {
		document.getElementById("busca_lateral_tipo").value = tipos_lista;
		document.getElementById("tipos").innerHTML = tipos_lista_html.substr(0, 8) +"&hellip;";
            }else{
		document.getElementById("busca_lateral_tipo").value = "";
		document.getElementById("tipos").innerHTML = "SELECIONE";
            }
	}
}
function alterarDesejo(desejo){
	document.getElementById("busca_inicial_desejo").value = desejo;
	if (desejo == "comprar") {
        document.getElementById("lista_valor_maximo").innerHTML = '\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'SEM LIMITE\',\'9999999999999\');">SEM LIMITE</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 100.000\',\'100000\');">R$ 100.000</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 150.000\',\'150000\');">R$ 150.000</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 200.000\',\'200000\');">R$ 200.000</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 250.000\',\'250000\');">R$ 250.000</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 300.000\',\'300000\');">R$ 300.000</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 400.000\',\'400000\');">R$ 400.000</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 500.000\',\'500000\');">R$ 500.000</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 600.000\',\'600000\');">R$ 600.000</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 800.000\',\'800000\');">R$ 800.000</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 1.000.000\',\'1000000\');">R$ 1.000.000</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 3.000.000\',\'3000000\');">R$ 3.000.000</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 5.000.000\',\'5000000\');">R$ 5.000.000</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 10.000.000\',\'10000000\');">R$ 10.000.000</div>\
        <div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 20.000.000\',\'20000000\');">R$ 20.000.000</div>';
	} else {
		document.getElementById("lista_valor_maximo").innerHTML = '<div class="opcao_combo" onclick="selecionarValorMaximo(\'INDIFERENTE\',99999999999);">INDIFERENTE</div><div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 300\', \'300\');">R$ 300</div><div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 500\', \'500\');">R$ 500</div><div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 700\', \'700\');">R$ 700</div><div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 1.000\', \'1000\');">R$ 1.000</div><div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 3.000\', \'3000\');">R$ 3.000</div><div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 5.000\', \'5000\');">R$ 5.000</div><div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 10.000\', \'10000\');">R$ 10.000</div><div class="opcao_combo" onclick="selecionarValorMaximo(\'R$ 20.000\', \'20000\');">R$ 20.000</div>';
	}
        var uso = "residencial";
        var estado = "SP";
        document.getElementById("estados").innerHTML = estado;
        var cidade = "SÃO PAULO";
        var cidade_val = "sao paulo";
        document.getElementById("cidades").innerHTML = cidade;
        document.getElementById("zona").innerHTML = "SELECIONE";
        document.getElementById("localidades").innerHTML = "SELECIONE";
        document.getElementById("categorias").innerHTML = "SELECIONE";
        document.getElementById("tipos").innerHTML = "SELECIONE";
        document.getElementById("dormitorios").innerHTML = "SELECIONE";
        document.getElementById("busca_inicial_dormitorios").value = "";
        document.getElementById("valor_maximo").innerHTML = "SELECIONE";
        document.getElementById("busca_inicial_valor_maximo").value = "";
	$.ajaxSetup({async:false});
        $.post("/controllers/BuscaInicialControl.php",
            {"acao": "carregar_uso", "desejo": desejo},
            function(_data){
		$("#lista_tipos_uso").html(_data);
		$.ajaxSetup({async:true});
            }
        );
        $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_categoria", uso: uso, desejo: desejo},function(data){
		$("#lista_categorias").html(data);
	});
        $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_tipos", uso: uso, desejo: desejo},function(data){
		$("#lista_tipos_conteudo").html(data);
	});
        $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_estados", uso: uso, desejo: desejo},function(data){
		$("#lista_estados").html(data);
	});
        $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_cidades", uso: uso, desejo: desejo, estado: estado},function(data){
		$("#lista_cidades").html(data);
	});
        $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_zonas", uso: uso, desejo: desejo, estado: estado, cidade: cidade_val},function(data){
		$("#lista_zona_conteudo").html(data);
        });
        $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_localidades", uso: uso, desejo: desejo, estado: estado, cidade: cidade_val},function(data){
		$("#lista_localidades_conteudo").html(data);
        });
        $(".selecao-zona").show();
        $(".selecao-localidade").show();
        $(".selecao-bairro").hide();
}
function alterarUso(uso){
        document.getElementById("busca_inicial_uso").value = uso;
        if (uso == "residencial") {
                $("#dormitorios_salas").html("Dormit&oacute;rios:");
        }
        else if (uso == "comercial" || uso == "industrial") {
                $("#dormitorios_salas").html("Salas:");
        }
        else {
                $("#dormitorios_salas").html("Dormit&oacute;rios:");
        }
        var desejo = $("#busca_inicial_desejo").val();
        var estado = "SP";
        document.getElementById("estados").innerHTML = estado;
        var cidade = "SÃO PAULO";
        var cidade_val = "sao paulo";
        document.getElementById("cidades").innerHTML = cidade;
        document.getElementById("zona").innerHTML = "SELECIONE";
        document.getElementById("localidades").innerHTML = "SELECIONE";
        document.getElementById("categorias").innerHTML = "SELECIONE";
        document.getElementById("tipos").innerHTML = "SELECIONE";
        document.getElementById("dormitorios").innerHTML = "SELECIONE";
        document.getElementById("busca_inicial_dormitorios").value = "";
        document.getElementById("valor_maximo").innerHTML = "SELECIONE";
        document.getElementById("busca_inicial_valor_maximo").value = "";
        $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_categoria", uso: uso, desejo: desejo},function(data){
		$("#lista_categorias").html(data);
	});
        $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_tipos", uso: uso, desejo: desejo},function(data){
		$("#lista_tipos_conteudo").html(data);
	});
        $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_estados", uso: uso, desejo: desejo},function(data){
		$("#lista_estados").html(data);
	});
        $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_cidades", uso: uso, desejo: desejo, estado: estado},function(data){
		$("#lista_cidades").html(data);
	});
        $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_zonas", uso: uso, desejo: desejo, estado: estado, cidade: cidade_val},function(data){
		$("#lista_zona_conteudo").html(data);
        });
        $.post("/controllers/BuscaInicialControl.php",{acao: "carregar_localidades", uso: uso, desejo: desejo, estado: estado, cidade: cidade_val},function(data){
		$("#lista_localidades_conteudo").html(data);
        });
        $(".selecao-zona").show();
        $(".selecao-localidade").show();
        $(".selecao-bairro").hide();
}
function realizar_busca(){
	var busca_inicial_estado = document.getElementById("busca_inicial_estado").value;
	var busca_inicial_desejo = document.getElementById("busca_inicial_desejo").value;
	var busca_inicial_uso = document.getElementById("busca_inicial_uso").value;
	var busca_inicial_categoria = document.getElementById("busca_inicial_categoria").value;
	var busca_inicial_tipo = document.getElementById("busca_inicial_tipo").value;
	var busca_inicial_dormitorios = document.getElementById("busca_inicial_dormitorios").value;
	var busca_inicial_valor_maximo = document.getElementById("busca_inicial_valor_maximo").value;
	var busca_inicial_cidade = document.getElementById("busca_inicial_cidade").value;
	var busca_inicial_zona = document.getElementById("busca_inicial_zona").value;
        var busca_inicial_localidade = document.getElementById("busca_inicial_localidade").value;
        var busca_inicial_bairro = document.getElementById("busca_inicial_bairro").value;
	var area_comum_lista = "";
	var atributos_lista = "";
	if (document.getElementById("form_consulta_inicial").action.match(/^.*\/avancada$/)) {
		var checkAtributos = document.getElementsByName("atributos_especiais");
		for (var i = 0; i < checkAtributos.length; i ++) {
			if (checkAtributos[i].checked == true) {
				if (atributos_lista == "") {
					atributos_lista = checkAtributos[i].id;
				} else {
					atributos_lista = atributos_lista + "," + checkAtributos[i].id;
				}
			}
		}
		var checkAreaComum = document.getElementsByName("area_comum");
		for (var j = 0; j < checkAreaComum.length; j ++) {
			if (checkAreaComum[j].checked == true) {
				if (area_comum_lista == "") {
					area_comum_lista = checkAreaComum[j].id;
				} else {
					area_comum_lista = area_comum_lista + "," + checkAreaComum[j].id;
				}
			}
		}
	}
	var parametro_busca;
	if(busca_inicial_estado != "" && busca_inicial_estado != "SELECIONE" && busca_inicial_estado != "INDIFERENTE"){
		parametro_busca = "/"+busca_inicial_estado+"-uf";
	}
	if(busca_inicial_cidade != "" && busca_inicial_cidade != "SELECIONE" && busca_inicial_cidade != "INDIFERENTE"){
		parametro_busca += "/"+busca_inicial_cidade+"-cidade";
	}
	if(busca_inicial_zona != "" && busca_inicial_zona != "SELECIONE" && busca_inicial_zona != "INDIFERENTE"){
		parametro_busca += "/"+busca_inicial_zona+"-zona";
	}
        if(busca_inicial_localidade != "" && busca_inicial_localidade != "SELECIONE" && busca_inicial_localidade != "INDIFERENTE"){
		parametro_busca += "/"+busca_inicial_localidade+"-localidade";
	}
	if(busca_inicial_bairro != "" && busca_inicial_bairro != "SELECIONE" && busca_inicial_bairro != "INDIFERENTE"){
		parametro_busca += "/"+busca_inicial_bairro+"-bairro";
	}
	if(busca_inicial_desejo != "" && busca_inicial_desejo != "SELECIONE" && busca_inicial_desejo != "INDIFERENTE"){
		parametro_busca += "/"+busca_inicial_desejo+"-desejo";
	}
	if(busca_inicial_uso != "" && busca_inicial_uso != "SELECIONE" && busca_inicial_uso != "INDIFERENTE"){
		parametro_busca += "/"+busca_inicial_uso+"-uso";
	}
	if(busca_inicial_categoria != "" && busca_inicial_categoria != "SELECIONE" && busca_inicial_categoria != "INDIFERENTE"){
		parametro_busca += "/"+busca_inicial_categoria+"-categoria";
	}
	if(busca_inicial_tipo != "" && busca_inicial_tipo != "SELECIONE" && busca_inicial_tipo != "INDIFERENTE"){
		parametro_busca += "/"+busca_inicial_tipo+"-tipo";
	}
	if(busca_inicial_dormitorios != "" && busca_inicial_dormitorios != "SELECIONE" && busca_inicial_dormitorios != "INDIFERENTE"){
		parametro_busca += "/"+busca_inicial_dormitorios+"-dorms";
	}
	if(busca_inicial_valor_maximo != "" && busca_inicial_valor_maximo != "SELECIONE" && busca_inicial_valor_maximo != "INDIFERENTE"){
		parametro_busca += "/0-"+busca_inicial_valor_maximo+"-valor";
	}
	if (document.getElementById("form_consulta_inicial").action.match(/^.*\/avancada$/)) {
		if(area_comum_lista != ""){
			parametro_busca += "/"+area_comum_lista+"-comum";
		}
		if(atributos_lista != ""){
			parametro_busca += "/"+atributos_lista+"-atributos";
		}
	}
	parametro_busca = parametro_busca.replace(/[ ]+/g,'+');
        if (busca_inicial_valor_maximo == 'SELECIONE' || busca_inicial_valor_maximo == ''){
            jAlert("Favor selecionar o valor m&aacute;ximo para pesquisar.", "Alerta");
        } else {
            limpa_parametros_busca();
            document.location=document.getElementById("form_consulta_inicial").action+parametro_busca.toLowerCase();
        }
}
function limpa_parametros_busca(){
        document.getElementById("busca_inicial_estado").value = "SP";
	document.getElementById("busca_inicial_desejo").value = "comprar";
	document.getElementById("busca_inicial_uso").value = "residencial";
	document.getElementById("busca_inicial_categoria").value = "";
	document.getElementById("busca_inicial_tipo").value = "";
	document.getElementById("busca_inicial_dormitorios").value = "";
	document.getElementById("busca_inicial_valor_maximo").value = "";
	document.getElementById("busca_inicial_cidade").value = "sao paulo";
	document.getElementById("busca_inicial_zona").value = "";
	document.getElementById("busca_inicial_localidade").value = "";
        document.getElementById("busca_inicial_bairro").value = "";
}
function selecionarOrdenacao(ordem){
	var ordenacao = "";
	if (ordem == "valor_crescente") {ordenacao = "VALOR CRESCENTE";}
	if (ordem == "valor_decrescente") {ordenacao = "VALOR DECRESCENTE";}
	if (ordem == "area_crescente") {ordenacao = "&Aacute;REA CRESCENTE";}
	if (ordem == "area_decrescente") {ordenacao = "&Aacute;REA DECRESCENTE";}
        if (ordem == "data_decrescente") {ordenacao = "MAIS RECENTES";}
	document.getElementById("ordenacao_resultado").value = ordem;
	document.getElementById("ordem").innerHTML = ordenacao;
	document.getElementById("lista_ordenacao").style.display = "none";
	filtrarResultado(1);
}
function mascara(o,f){
    v_obj=o;
    v_fun=f;
    setTimeout("execmascara()",1);
}
function execmascara(){
    v_obj.value=v_fun(v_obj.value);
}
function telefone(v){
    v=v.replace(/\D/g,"");
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2");
    v=v.replace(/(\d{4})(\d)/,"$1-$2");
    return v;
}
function buscarCodigo(){
	var codigo = document.getElementById("busca_codigo_valor").value;
	$("#carregando").show();
	document.getElementById("carregando").style.top = $(document).scrollTop() + 10 + "px";
	$.post("/controllers/ImovelControl.php",{acao: "procurar_codigo", codigo: rawurlencode(codigo)},function(data){
		if (data != "") {
			window.location.href = data;
		}else{
			jAlert("Nenhum im&oacute;vel encontrado.");
		}
		$("#carregando").hide();
	});
}
function filtrarResultado(pagina) {
	$("#pagina_anterior").val(parseInt($("#pagina_atual").val()));
	$("#pagina_atual").val(pagina);
	var busca_avancada = $("#busca_avancada").val();
	var lancamentos    = $("#lancamentos").val();
	var virtual_tour = $("#virtual_tour").val();
	var ordenacao_resultado = $("#ordenacao_resultado").val();
	var busca_lateral_uso = $("#busca_lateral_uso").val();
        var busca_lateral_desejo = $("#busca_lateral_desejo").val();
	var busca_lateral_tipo = $("#busca_lateral_tipo").val();
	var busca_lateral_estado = $("#busca_lateral_estado").val();
	var busca_lateral_cidade = $("#busca_lateral_cidade").val();
	var busca_lateral_zona = $("#busca_lateral_zona").val();
      	var busca_lateral_localidade = $("#busca_lateral_localidade").val();
	var busca_lateral_bairro = $("#busca_lateral_bairro").val();
        var busca_lateral_anunciante = $("#busca_lateral_anunciante").val()
	var busca_lateral_categoria = $("#busca_lateral_categoria").val();
	var busca_lateral_faixa_valor = $("#busca_lateral_faixa_valor").val();
	var busca_lateral_faixa_vagas = $("#busca_lateral_faixa_vagas").val();
	var busca_lateral_faixa_suites = $("#busca_lateral_faixa_suites").val();
	var busca_lateral_faixa_area_util = $("#busca_lateral_faixa_area_util").val();
	var busca_lateral_faixa_dormitorios = $("#busca_lateral_faixa_dormitorios").val();
	var area_comum_lista = "";
	var atributos_lista = "";
	if (busca_avancada == 1) {
		var checkAtributos = document.getElementsByName("atributos_especiais");
		for (var i = 0; i < checkAtributos.length; i ++) {
			if (checkAtributos[i].checked == true) {
				if (atributos_lista == "") {
					atributos_lista = checkAtributos[i].id;
				}else{
					atributos_lista = atributos_lista + "," + checkAtributos[i].id;
				}
			}
		}
		var checkAreaComum = document.getElementsByName("area_comum");
		for (var j = 0; j < checkAreaComum.length; j ++) {
			if (checkAreaComum[j].checked == true) {
				if (area_comum_lista == "") {
					area_comum_lista = checkAreaComum[j].id;
				}else{
					area_comum_lista = area_comum_lista + "," + checkAreaComum[j].id;
				}
			}
		}
	}
	$("#carregando").show();
	document.getElementById("carregando").style.top = $(document).scrollTop() + 10 + "px";
	var parametro_busca = "";
	if (busca_avancada == 1) {
		parametro_busca = "/avancada";
	}
	if (lancamentos == 1) {
		parametro_busca = "/lancamentos";
	}
	if (virtual_tour == 1) {
		parametro_busca = "/virtual_tour";
	}
	if(busca_lateral_estado != "" && busca_lateral_estado != "SELECIONE" && busca_lateral_estado != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_estado+"-uf";
	}
	if(busca_lateral_cidade != "" && busca_lateral_cidade != "SELECIONE" && busca_lateral_cidade != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_cidade+"-cidade";
	}
	if(busca_lateral_zona != "" && busca_lateral_zona != "SELECIONE" && busca_lateral_zona != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_zona+"-zona";
	}
        if(busca_lateral_localidade != "" && busca_lateral_localidade != "SELECIONE" && busca_lateral_localidade != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_localidade+"-localidade";
        }
	if(busca_lateral_bairro != "" && busca_lateral_bairro != "SELECIONE" && busca_lateral_bairro != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_bairro+"-bairro";
	}
	if(busca_lateral_desejo != "" && busca_lateral_desejo != "SELECIONE" && busca_lateral_desejo != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_desejo+"-desejo";
	}
	if(busca_lateral_uso != "" && busca_lateral_uso != "SELECIONE" && busca_lateral_uso != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_uso+"-uso";
	}
	if(busca_lateral_categoria != "" && busca_lateral_categoria != "SELECIONE" && busca_lateral_categoria != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_categoria+"-categoria";
	}
	if(busca_lateral_tipo != "" && busca_lateral_tipo != "SELECIONE" && busca_lateral_tipo != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_tipo+"-tipo";
	}
	if(busca_lateral_faixa_dormitorios != "" && busca_lateral_faixa_dormitorios != "SELECIONE" && busca_lateral_faixa_dormitorios != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_faixa_dormitorios+"-dorms";
	}
	busca_lateral_faixa_valor = busca_lateral_faixa_valor.replace("/", "-");
	if(busca_lateral_faixa_valor != "" && busca_lateral_faixa_valor != "SELECIONE" && busca_lateral_faixa_valor != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_faixa_valor+"-valor";
	}
	if(busca_lateral_faixa_vagas != "" && busca_lateral_faixa_vagas != "SELECIONE" && busca_lateral_faixa_vagas != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_faixa_vagas+"-vagas";
	}
	if(busca_lateral_faixa_suites != "" && busca_lateral_faixa_suites != "SELECIONE" && busca_lateral_faixa_suites != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_faixa_suites+"-suites";
	}
	if(busca_lateral_faixa_area_util != "" && busca_lateral_faixa_area_util != "SELECIONE" && busca_lateral_faixa_area_util != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_faixa_area_util+"-area";
	}
        if(busca_lateral_anunciante != "" && busca_lateral_anunciante != "SELECIONE" && busca_lateral_anunciante != "INDIFERENTE"){
		parametro_busca += "/"+busca_lateral_anunciante+"-anunciante";
	}
	if(area_comum_lista != "" ){
		parametro_busca += "/"+area_comum_lista+"-comum";
	}
	if(atributos_lista != "" ){
		parametro_busca += "/"+atributos_lista+"-atributos";
	}
	if(ordenacao_resultado != ""){
		parametro_busca += "/"+ordenacao_resultado+"-ordem";
	}
	parametro_busca = parametro_busca.replace(/[ ]+/g,'+');
	window.location.href = "/imoveis"+parametro_busca.toLowerCase();
}
function limparFaleConosco(){
    $("#nome").val("");
    $("#email").val("");
    $("#telefone").val("");
    $("#assunto").val("");
    $("#mensagem").val("");
    $("#captcha_text_fc").val("Digite o código ao lado");
}
function enviarFaleConosco(){
    var nome = document.getElementById("nome").value;
    var email = document.getElementById("email").value;
    var telefone = document.getElementById("telefone").value;
    var assunto = document.getElementById("assunto").value;
    var mensagem = document.getElementById("mensagem").value;
    var captcha = document.getElementById("captcha_text_fc").value;
    if($.trim(nome) == ""){
        jAlert("Favor preencher o nome.");
    }else if($.trim(email) == ""){
        jAlert("Favor preencher o email.");
    }else if($.trim(telefone) == ""){
        jAlert("Favor preencher o telefone.");
    }else if($.trim(assunto) == ""){
        jAlert("Favor preencher o assunto.");
    }else if ($.trim(mensagem) == ""){
        jAlert("Favor preencher a mensagem.");
    }else if ($.trim(captcha) == ""){
        jAlert("Favor preencher o c&oacute;digo.");
    }else{
        $("#status_enviar").html("");
        $.post("/controllers/FormularioControl.php",{acao: "enviar_fale_conosco", nome: rawurlencode(nome),
                                                        email: rawurlencode(email),
                                                        telefone: rawurlencode(telefone),
                                                        assunto: rawurlencode(assunto),
                                                        mensagem: rawurlencode(mensagem),
                                                        captcha: rawurlencode(captcha)},function(data){
                jAlert(data, "Alerta", function() {
                    if(data == "C&oacute;digo inv&aacute;lido. Favor tentar novamente." || data == "Favor inserir um e-mail v&aacute;lido!")
                        $("#status_enviar").html("<img src=\"/images/btn_enviar.png\" border=\"0\" style=\"cursor:pointer;\" onclick=\"enviarFaleConosco();\" />");
                    else
                        window.location = "/";
                });
        });
    }
}
function verificarInternauta(pagina) {
	$("#carregando").show();
	document.getElementById("carregando").style.top = $(document).scrollTop() + 10 + "px";
	$.post("/controllers/InternautaControl.php",{acao: "verificar_internauta", email: rawurlencode($("#email_internauta_login").val()), senha: rawurlencode($("#senha_internauta_login").val())},function(data){
		if (pagina == "resultado") {$("#meu_tique_imoveis").load("/views/painel_internauta_lateral.php");}
		if (data == "senha_invalida") {
                        jAlert("E-mail ou senha inv&aacute;lidos. Favor verificar e-mail e senha.");
                }
		else if (data == "internauta_invalido") {
			if (pagina == "principal") {$("#form_login").submit();}
			if (pagina != "principal") {
				$("#email_internauta_cadastro").val($("#email_internauta_login").val());
				$("#senha_internauta_cadastro").val($("#senha_internauta_login").val());
				$("#email_internauta_login").val("");
				$("#senha_internauta_login").val("");
				$("#nome_internauta").focus();
			}
		}else {
			if (pagina == "principal") {
				document.location.href="/";
			}else {
				if ((pagina == "") || (pagina == "/cadastrar_nosso_portal/") || (pagina == "/cadastrar_nosso_portal")) {
					document.location.href = "/";
				} else if (pagina == "resultado"){}
				else {
                                        document.location.href = pagina;
				}
			}
		}
		$("#carregando").hide();
	});
}
function limparCadastroInternauta(){
	$("#nome_internauta").val("");
	$("#sobrenome_internauta").val("");
	$("#email_internauta_cadastro").val("");
	$("#tipo_internauta").val("");
	$("#telefone_internauta").val("");
	$("#como_conheceu_internauta").val("");
	$("#senha_internauta_cadastro").val("");
	$("#sexo").val("");
}
function enviarCadastroInternauta(pagina){
        if ($("#nome_internauta").val() == ""){
                jAlert("Favor preencher o nome.");
        }else if ($("#sobrenome_internauta").val() == ""){
                jAlert("Favor preencher o sobrenome.");
        }else if (document.getElementById("sexo_masculino").checked == false && document.getElementById("sexo_feminino").checked == false){
                jAlert("Favor preencher o sexo.");
        }else if ($("#email_internauta_cadastro").val() == ""){
                jAlert("Favor preencher o e-mail.");
        }else if ($("#telefone_internauta").val() == "" || $("#telefone_internauta").val().length != 14){
                jAlert("Favor preencher o telefone.");
        }else if ($("#senha_internauta_cadastro").val() == ""){
                jAlert("Favor preencher a senha.");
	}else{
		$("#carregando").show();
                document.getElementById("carregando").style.top = $(document).scrollTop() + 10 + "px";
                if (document.getElementById("sexo_masculino").checked == true) {sexo = "Masculino";}
                if (document.getElementById("sexo_feminino").checked == true) {sexo = "Feminino";}
                $.post("/controllers/FormularioControl.php",{acao: "cadastrar_internauta",
                    nome_internauta: rawurlencode($("#nome_internauta").val() + " " + $("#sobrenome_internauta").val()),
                    email_internauta: rawurlencode($("#email_internauta_cadastro").val()),
                    tipo_internauta: rawurlencode($("#tipo_internauta").val()),
                    telefone_internauta: rawurlencode($("#telefone_internauta").val()),
                    como_conheceu_internauta: rawurlencode($("#como_conheceu_internauta").val()),
                    senha_internauta: rawurlencode($("#senha_internauta_cadastro").val()),
                    sexo: sexo},function(data){
                        jAlert(data, "Alerta");
                        $("#carregando").hide();
                        if(data != "E-Mail j&aacute; cadastrado em nosso banco de dados, favor escolher outro." && data != "Favor inserir um e-mail v&aacute;lido.") {
                                if($.trim(pagina) != ""){document.location.href = pagina;}
                                else{document.location.href = 'http://'+document.location.host;} 
                        }
                });
        }
}
function salvarImovelSessao(imovel) {
	$.post("/controllers/XHRControl.php",{
        acao: "adicionar_favorito_sessao",
        codigo_imovel: imovel
    }, function(data) {
        jConfirm("&Eacute; necess&aacute;rio fazer login no portal para realizar a opera&ccedil;&atilde;o.<br/>Deseja faz&ecirc;-lo agora?","Aviso",
            function(_confirm){
                if(_confirm){
                    document.location.href='/cadastrar_nosso_portal/'
                }
            }
        )
    });
}
function salvarImovelFicha(icone, acao, imovel) {
    if (acao == "adicionar") {
        $.post("/controllers/InternautaControl.php", {acao: "adicionar_favorito", codigo_imovel: imovel}, function(data) {
            $(icone)
                .attr({src: "/images/salvar_anuncio_ficha_remover.png"})
                .unbind('click').click(function(){
                    salvarImovelFicha(icone, 'remover',imovel);
                });
            jAlert("Im&oacute;vel adicionado ao perfil com sucesso!", "Alerta");
        });
    } else if (acao == "remover") {
        $('#confirmar_favorito_ficha').open(imovel, '');
    }
}
function removerImovelFicha(imovel) {
	$.post("/controllers/InternautaControl.php", {acao: "remover_favorito", codigo_imovel: imovel}, function(data) {
        $("#icone_salvar")
            .attr({src: "/images/salvar_anuncio_ficha.png"})
            .unbind('click').click(function(){
                salvarImovelFicha(this, 'adicionar',imovel);
            });
		jAlert("Im&oacute;vel removido do perfil com sucesso!", "Alerta", function() {$('#confirmar_favorito_ficha').close();});
	});
}
function enviarSenhaInternauta() {
	$("#carregando").show();
	document.getElementById("carregando").style.top = $(document).scrollTop() + 10 + "px";
	$.post("/controllers/InternautaControl.php", {acao: "enviar_senha", email: $("#email_internauta").val()}, function(data) {
		if (data != "A sua nova senha foi enviada para o e-mail informado.") {
			jAlert("E-Mail n&atilde;o cadastrado em nosso banco de dados.");
		} else {
			jAlert(data);
			$("#enviar_senha").hide();
		}
		$("#carregando").hide();
	});
}
function validarEmail(email) {
	if (email.value != "") {
		if ((email.value.indexOf("@") < 1) || (email.value.indexOf("teste") != -1) || (email.value.indexOf(".") < 1) || (email.value.indexOf(" ") > 0)) {
			jAlert("Favor inserir um e-mail v&aacute;lido.", "Alerta");
			email.value = "";
		}
	}
}
function cadastrarBusca(sid,url_busca) {
	if (sid != "") {
		$.post("/controllers/ResultadoBuscaControl.php", {acao: "salvar_consulta", url_busca: url_busca},function(data){
			jAlert(data, "Alerta", function() {
				$("#carregando").hide();
			});
		});
	} else {
		jAlert("Favor efetuar o login para cadastrar esta busca.", "Alerta");
	}
}
function alterarFoto(url, codigo) {
    var _drctn = (codigo > ultima_foto)?'right':'left';
    $("#foto_atual_imovel").css('bagckground-image','url('+$("#foto_atual_imovel IMG").attr('src')+')');
    $("#foto_atual_imovel IMG").unbind('load').load(function(){$(this).hide().show('slide',{direction:_drctn})})
        .attr('src',url)
        .attr('alt',$(vetor_fotos[codigo]).attr('alt'))
        .attr('title',$(vetor_fotos[codigo]).attr('title'));
    foto_atual = ultima_foto = codigo;
}
var foto_atual = 0;var ultima_foto = 0;
function proximaFoto() {
    var _total = $('#fotos_imovel DIV IMG').length
    if (foto_atual != (_total - 1)) {
        foto_atual++;
        alterarFoto($(vetor_fotos[foto_atual]).attr('src'),foto_atual)
    }
}
function fotoAnterior() {
    if (foto_atual > 0) {
        foto_atual = parseInt(foto_atual) - 1;
        alterarFoto($(vetor_fotos[foto_atual]).attr('src'),foto_atual)
    }
}
function proximaAba() {
	if (aba_atual < total_abas) {
		document.getElementById(aba_atual + "_pagina_fotos").style.display = "none";
		aba_atual = aba_atual + 1;
		document.getElementById(aba_atual + "_pagina_fotos").style.display = "block";
	}
}
function abaAnterior() {
	if (aba_atual != 1) {
		document.getElementById(aba_atual + "_pagina_fotos").style.display = "none";
		aba_atual = aba_atual - 1;
		document.getElementById(aba_atual + "_pagina_fotos").style.display = "block";
	}
}
function popularEstatisticas(cod_imovel, cod_anunciante, cod_imovel_anunciante, tipo){
	$.post("/controllers/EstatisticasControl.php", {acao: "popular_" + tipo, cod_imovel: cod_imovel, cod_anunciante: cod_anunciante, cod_imovel_anunciante: cod_imovel_anunciante},function(data){});
}
function estatisticaBanner(id, local){
	$.post("/controllers/EstatisticasControl.php", {acao: "popular_banner", id: id, local: local});
}
String.prototype.reverse = function(){
    return this.split('').reverse().join('');
};
function enviarAnuncioIncorreto(codigo_imovel, codigo_anunciante, referencia) {
	var nome = $("#relatar_anuncio_nome").val();
        var email = $("#relatar_anuncio_email").val();
        var telefone = $("#relatar_anuncio_telefone").val();
        var mensagem = $("#relatar_anuncio_mensagem").val();
        if (nome == ""){
                jAlert("Favor preencher o nome.");
        }else if (email == ""){
                jAlert("Favor preencher o e-mail.");
        }else if (telefone == "" || telefone.length != 14){
                jAlert("Favor preencher o telefone.");
        }else if (mensagem == ""){
                jAlert("Favor preencher a mensagem.");
        }else{
                $.post("/controllers/FormularioControl.php",{acao: "relatar_anuncio_ficha", codigo_imovel: rawurlencode(codigo_imovel), referencia: rawurlencode(referencia), codigo_anunciante: rawurlencode(codigo_anunciante), nome: rawurlencode(nome), email: rawurlencode(email), telefone: rawurlencode(telefone), mensagem: rawurlencode(mensagem)}, function(data) {
                        if (data == "E-Mail enviado com sucesso. Aguarde contato."){
                                $('#status_envio').html('Enviando...');
                                jAlert(data, "Alerta", function() {
                                        $('#relatar_anuncio').close();
                                });
                        }else{
                                jAlert(data, "Alerta");
                        }
                });
        }
}
function logout() {
    $.post("/views/logout.php",{}, function(data) {
            window.location.reload();
    });
}
function verTelefone (telefone_contato){
    jAlert('Telefone para contato com o anunciante: '+telefone_contato, 'Telefone para contato');
}
var conversao = {
    type:{2:'usado',3:'lancamento'},
    modalidade:['aluguel','venda'],
    chat:function(tipo,anunciante){conversao._track(tipo,'chat_ficha',anunciante);},
    chatEmail:function(tipo,anunciante){conversao._track(tipo,'chat_email',anunciante);},
    emailFicha:function(tipo,anunciante){conversao._track(tipo,'email_ficha',anunciante);},
    emailBusca:function(tipo,anunciante){conversao._track(tipo,'email_busca',anunciante);},
    telefoneBusca:function(tipo,anunciante){conversao._track(tipo,'telefone_busca',anunciante);},
    telefoneFicha:function(tipo,anunciante){conversao._track(tipo,'telefone_ficha',anunciante);},
    _track:function(tipo,evento,anunciante){
        var convtipo = 'lancamento';
        if(tipo[0] == 2){
            convtipo = 'usado'+conversao.modalidade[tipo[1]];
        }
        pageTracker._trackEvent(convtipo,evento,''+anunciante);
        ggads(convtipo);
        if(convtipo == 'lancamento'){
            ggads('usadolancamento');
        }
    }
};
var ggads = function(convtipo){
    var cvt = {
        "lancamento":{
            "label"  :"WSZfCMfpwQIQsbWX1gM",
            "codurl" :"986045105"
        },
        "usadolancamento":{
            "label"  :"Il2GCI6J-wEQrILO6QM",
            "codurl" :"1026785580"
        },
        "usadovenda":{
            "label"  :"qNOeCOaF_AEQrILO6QM",
            "codurl" :"1026785580"
        },
        "usadoaluguel":{
            "label"  :"TLmKCNaH_AEQrILO6QM",
            "codurl" :"1026785580"
        }
    }
    var ads_image = new Image(1,1);
    ads_image.src = 'http://www.googleadservices.com/pagead/conversion/'+cvt[convtipo].codurl+'/?label='+cvt[convtipo].label+'&amp;guid=ON&amp;script=0';
}
var conversaoBairro = function(_imoveis){
    if(!$.isArray(_imoveis)){
        _imoveis = [_imoveis];
    }
    $.post('/controllers/XHRControl.php',{imoveis:_imoveis,acao:'bairro-get'},function(data){
        if(data){
            for(var i in data){
                pageTracker._trackPageview('/contato/'+data[i]+'/');
            }
        }
    })
}
var conversaoLancamento = function(_imoveis){
    if(!$.isArray(_imoveis)){
        _imoveis = [_imoveis];
    }
    $.post('/controllers/XHRControl.php',{imoveis:_imoveis,acao:'bairro-get'},function(data){
        if(data){
            for(var i in data){
                setTimeout(function(){},(250));
            }
        }
    })
}
var ImovelMail = {
    store:[],
    _logged:false,
    add:function(){
        $.post('/controllers/XHRControl.php',{
            acao:'imovel-mail-add',
            id:$(this).attr('iid'),
            url:$(this).attr('url')
            },function(data){
                    if(data && data.ok){
                            ImovelMail.store.push(data.id);
                            $(".imovel-mail-off[iid='"+data.id+"']")
                                .removeClass('imovel-mail-off')
                                .addClass('imovel-mail')
                                .unbind('click').click(ImovelMail.remove);
                    } else if (data && data.limite){
                        jAlert('Você atingiu o limite máximo de imóveis selecionados.\nPor favor envie os e-mails antes de selecionar outros imóveis.');
                        ImovelMail.openForm();
                    } else {
                        jAlert('Ocorreu um erro ao marcar o imóvel\nTente novamente');
                    }
            }
        );
    },
    addEnviar:function(){
        $.post('/controllers/XHRControl.php',{
            acao:'imovel-mail-add',
            id:$(this).attr('iid'),
            url:$(this).attr('url')
            },function(data){
                    if(data && data.existe){
                        ImovelMail.openForm();
                    } else {
                        if(data && data.ok){
                                ImovelMail.store.push(data.id);
                                $(".imovel-mail-off[iid='"+data.id+"']")
                                    .removeClass('imovel-mail-off')
                                    .addClass('imovel-mail')
                                    .unbind('click').click(ImovelMail.remove);
                                    ImovelMail.openForm();
                        } else if (data && data.limite){
                            jAlert('Você atingiu o limite máximo de imóveis selecionados.\nPor favor envie os e-mails antes de selecionar outros imóveis.');
                            ImovelMail.openForm();
                        } else {
                            jAlert('Ocorreu um erro ao marcar o imóvel\nTente novamente');
                        }
                    }
            }
        );
    },
    remove:function(){
        $.post('/controllers/XHRControl.php',{
            acao:'imovel-mail-rm',
            id:$(this).attr('iid')
            },function(data){
                if(data && data.ok){
                    var tmp = [];
                    for(var i in ImovelMail.store){
                        if(data.id != ImovelMail.store[i]){
                            tmp.push(ImovelMail.store[i]);
                        }
                    }
                    ImovelMail.store = tmp;
                    $(".imovel-mail[iid='"+data.id+"']")
                        .removeClass('imovel-mail')
                        .addClass('imovel-mail-off')
                        .unbind('click').click(ImovelMail.add);
                }
            },'json'
        );
    },
    canMail:function(){
        return ($('#imovel-mail-nome').val() == '' ||
                $('#imovel-mail-email').val() == '' ||
                $('.imovel-mail-assunto[value=1]').length < 1 ||
                $('#imovel-mail-tel').val().length < 14);
    },
    mailIt:function(){
        if(ImovelMail.canMail()){
            $('.botao_enviar').show();
            jAlert('Preencha corretamente os campos Nome, E-mail, Telefone e Assunto');
        } else {
            $.post('/controllers/XHRControl.php',{
                acao:'imovel-mail-send',
                nome:$('#imovel-mail-nome').val(),
                email:$('#imovel-mail-email').val(),
                tel:$('#imovel-mail-tel').val(),
                desejo:$('#imovel-mail-desejo').val(),
                assunto:subjectCombined(),
                save:$('#imovel-mail-save').val(),
                imoveis:ImovelMail.store.join(',')
                },function(data){
                    if(data.ok){
                        ImovelMail.removeAll(ImovelMail.store);
                        if(data.extra){
                            for(var i in data.extra){
                                conversao.emailBusca([data.extra[i].condicao,data.extra[i].venda],data.extra[i].anunciante);
                                pageTracker._trackPageview('/Busca/Email/Enviado');
                            }
                        }
                        conversaoBairro(ImovelMail.store.join(','));

                        ImovelMail.store = [];
                        if(data.save){
                            if(ImovelMail._logged){
                                jAlert(data.msg[0],'Aviso',function(){window.document.location.reload()});
                            } else {
                                jConfirm(data.msg[0]+'<br />É necessário estar logado para salvar os imóveis. Deseja fazê-lo agora?','Confirmação',function(_confirm){
                                    if(_confirm){
                                        document.location.href='/meu_tique_imoveis';
                                    }
                                });
                            }
                            $('#imovel-mail-form').dialog("close");
                        } else {
                            jAlert(data.msg[0],'Aviso');
                            $('#imovel-mail-form').dialog("close");
                        }
                    } else {
                        $('.botao_enviar').show();
                        jAlert(data.msg.join('<br />'));
                    }
                },'json'
            );
        }
    },
    reset:function(){
        $('.imovel-mail').each(function(){
            $(this).removeClass('imovel-mail').addClass('imovel-mail-off').click(ImovelMail.add)
        });
    },
    openForm:function(){
        if(ImovelMail.store.length){
            $('#imovel-mail-form').dialog("open");
            $('.botao_enviar').show();
            $.post('/controllers/XHRControl.php',{
                acao:'imovel-mail-get'
            },function(data){
                $('#imovel-mail-url-list').html('');
                if(data){
                    $.each(data,function(idx,item){
                        $('#imovel-mail-url-list')
                        .append('<li><input type="hidden" class="imovel-mail-list" value="'+idx+'"/>'+
                            item.replace('http://','').replace(document.location.host,'')
                            +'</li>');
                    })
                }
            },'json');
        } else {
            jAlert('Não existem imóveis selecionados para o envio de email.','Aviso');
        }
    },
    sessionControl:function(){
        $.post('/controllers/XHRControl.php',{
            acao:'imovel-mail-get'
        },function(data){
            if(data){
                $.each(data,function(idx){
                    ImovelMail.store.push(idx);
                })
            }
        },'json');
    },
    removeAll:function(cod_imoveis){
        if(!$.isArray(cod_imoveis)){
            cod_imoveis = [cod_imoveis];
        }
        for(var i in cod_imoveis){
            $(".imovel-mail[iid='"+cod_imoveis[i]+"']")
            .removeClass('imovel-mail')
            .addClass('imovel-mail-off')
            .unbind('click').click(ImovelMail.add)

            $(".imovel-mail-enviar[iid='"+cod_imoveis[i]+"']")
            .replaceWith('<label class="imovel-mail-enviado" iid="'+cod_imoveis[i]+'" url="'+$(".imovel-mail-enviar[iid='"+cod_imoveis[i]+"']").attr("url")+'" alt="Enviar E-mails" title="Enviar E-mails">E-mail Enviado</label>')
            .unbind('click').click(ImovelMail.add)
        }
    }
}
function TiqueAd(ad_id){
    $.ajax(
        {url:'/views/boximovel.php?id='+ad_id,dataType:'html',success:function(h){$('#ad_imovel_'+ad_id).html(h)}}
    )
}
function TiqueFlyOpen(local, id, url, width, height){
        $('#fly_'+local).load('/views/fly.php?local='+local+'&id='+id+'&url='+url+'&width='+width+'&height='+height);
        $('#fly_'+local).show();
        setTimeout(function(){TiqueFlyClose(local)}, 15000);
}
function TiqueFlyClose(local){
    $('#fly_'+local).hide();
}
function TiqueView(uri){
    $.post("/controllers/EstatisticasControl.php", {acao: "page_view", uri: uri});
}
var geo = {
    client:{},
    _counter:0,
    set:function(city,region){
        $.post('/controllers/XHRControl.php',
               {"acao":"geo-set","geo-city":city,"geo-region":region},function(d){geo.client = d;geo.setSubtitle()})
    },
    setGoogle:function(){
        if(google.loader.ClientLocation){
            geo.set(google.loader.ClientLocation.address.city,google.loader.ClientLocation.address.region);
        } else {
            geo.set('São Paulo','SP');
        }
    },
    get:function(){
        $.post('/controllers/XHRControl.php',
               {"acao":"geo-get"},function(d){geo.client = d;geo.setSubtitle()})
    },
    setSubtitle:function(){
        if(geo.client.city){
            $('#tique_sub DIV.subtext').html(geo.client.city)
            $('#tique_sub').unbind('click').click(geo.selectCity).css('visibility','visible').fadeIn();
            $('#tique_sub SPAN').html('Estou em')
            if($('#busca_inicial_cidade').length){
                geo.doSearch();
            }
        }
    },
    doSearch:function(){
        $('#lista_estados DIV:contains('+geo.client.region+')').click();
        setTimeout(geo._changeCity,1000);
    },
    selectCity:function(){
        $('#busca-cidade').dialog('open');
    },
    _changeCity:function(){
        if($("#lista_cidades DIV[tcidade='"+geo.client.cityPlain.toLowerCase()+"']").length){
            geo._counter=0;
            $("#lista_cidades DIV[tcidade='"+geo.client.cityPlain.toLowerCase()+"']").click();
            return void(0);
        } else {
            geo._counter++;
        }
        if(geo._counter < 3){
            setTimeout(geo._changeCity,1000);
        } else {
            geo._counter=0;
        }
    },
    _finderInit:function(){
        $('#busca-cidade').dialog({
            autoOpen:false,
            modal:true,
            width:440,
            resizable:false,
            draggable:false,
            title:'Localize sua cidade',
            buttons:{'Alterar':function(){
                geo.set($('#geo-cidade').val(),$('#geo-uf').val());
                $('#busca-cidade').dialog('close');
                }
            }
        });
        $('THEAD TD',$('#busca-cidade')).css('font-weight','bold');
        $('TABLE SELECT,TABLE INPUT',$('#busca-cidade'))
            .css({'border':'1px solid #DDD'}).addClass('ui-corner-all');
        $('#geo-cidade').autocomplete({
            source:'/controllers/CEPControl.php?acao=cidades&uf='+$('geo-uf').val(),
            minLength: 3,
            delay:500,
            select: function(event, ui) {
                $("#geo-cidade-real").val(ui.item.id)
            }
        })
        $('#geo-uf').change(function(){
            $('#geo-cidade').autocomplete('option','source','/controllers/CEPControl.php?acao=cidades&uf='+$(this).val()).focus();
        });
    }
};
/**
 * jQuery-Plugin "preloadCssImages"
 * by Scott Jehl, scott@filamentgroup.com
 * http://www.filamentgroup.com
 * reference article: http://www.filamentgroup.com/lab/update_automatically_preload_images_from_css_with_jquery/
 * demo page: http://www.filamentgroup.com/examples/preloadImages/index_v2.php
 * 
 * Copyright (c) 2008 Filament Group, Inc
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 *
 * Version: 5.0, 10.31.2008
 * Changelog:
 * 	02.20.2008 initial Version 1.0
 *    06.04.2008 Version 2.0 : removed need for any passed arguments. Images load from any and all directories.
 *    06.21.2008 Version 3.0 : Added options for loading status. Fixed IE abs image path bug (thanks Sam Pohlenz).
 *    07.24.2008 Version 4.0 : Added support for @imported CSS (credit: http://marcarea.com/). Fixed support in Opera as well. 
 *    10.31.2008 Version: 5.0 : Many feature and performance enhancements from trixta
 * --------------------------------------------------------------------
 */

;jQuery.preloadCssImages = function(settings){
	settings = jQuery.extend({
		statusTextEl: null,
		statusBarEl: null,
		errorDelay: 999, // handles 404-Errors in IE
		simultaneousCacheLoading: 2
	}, settings);
	var allImgs = [],
		loaded = 0,
		imgUrls = [],
		thisSheetRules,	
		errorTimer;
	
	function onImgComplete(){
		clearTimeout(errorTimer);
		if (imgUrls && imgUrls.length && imgUrls[loaded]) {
			loaded++;
			if (settings.statusTextEl) {
				var nowloading = (imgUrls[loaded]) ? 
					'Now Loading: <span>' + imgUrls[loaded].split('/')[imgUrls[loaded].split('/').length - 1] : 
					'Loading complete'; // wrong status-text bug fixed
				jQuery(settings.statusTextEl).html('<span class="numLoaded">' + loaded + '</span> of <span class="numTotal">' + imgUrls.length + '</span> loaded (<span class="percentLoaded">' + (loaded / imgUrls.length * 100).toFixed(0) + '%</span>) <span class="currentImg">' + nowloading + '</span></span>');
			}
			if (settings.statusBarEl) {
				var barWidth = jQuery(settings.statusBarEl).width();
				jQuery(settings.statusBarEl).css('background-position', -(barWidth - (barWidth * loaded / imgUrls.length).toFixed(0)) + 'px 50%');
			}
			loadImgs();
		}
	}
	
	function loadImgs(){
		//only load 1 image at the same time / most browsers can only handle 2 http requests, 1 should remain for user-interaction (Ajax, other images, normal page requests...)
		// otherwise set simultaneousCacheLoading to a higher number for simultaneous downloads
		if(imgUrls && imgUrls.length && imgUrls[loaded]){
			var img = new Image(); //new img obj
			img.src = imgUrls[loaded];	//set src either absolute or rel to css dir
			if(!img.complete){
				jQuery(img).bind('error load onreadystatechange', onImgComplete);
			} else {
				onImgComplete();
			}
			errorTimer = setTimeout(onImgComplete, settings.errorDelay); // handles 404-Errors in IE
		}
	}
	
	function parseCSS(sheets, urls) {
		var w3cImport = false,
			imported = [],
			importedSrc = [],
			baseURL;
		var sheetIndex = sheets.length;
		while(sheetIndex--){//loop through each stylesheet
			
			var cssPile = '';//create large string of all css rules in sheet
			
			if(urls && urls[sheetIndex]){
				baseURL = urls[sheetIndex];
			} else {
				var csshref = (sheets[sheetIndex].href) ? sheets[sheetIndex].href : 'window.location.href';
				var baseURLarr = csshref.split('/');//split href at / to make array
				baseURLarr.pop();//remove file path from baseURL array
				baseURL = baseURLarr.join('/');//create base url for the images in this sheet (css file's dir)
				if (baseURL) {
					baseURL += '/'; //tack on a / if needed
				}
			}
			if(sheets[sheetIndex].cssRules || sheets[sheetIndex].rules){
				thisSheetRules = (sheets[sheetIndex].cssRules) ? //->>> http://www.quirksmode.org/dom/w3c_css.html
					sheets[sheetIndex].cssRules : //w3
					sheets[sheetIndex].rules; //ie 
				var ruleIndex = thisSheetRules.length;
				while(ruleIndex--){
					if(thisSheetRules[ruleIndex].style && thisSheetRules[ruleIndex].style.cssText){
						var text = thisSheetRules[ruleIndex].style.cssText;
						if(text.toLowerCase().indexOf('url') != -1){ // only add rules to the string if you can assume, to find an image, speed improvement
							cssPile += text; // thisSheetRules[ruleIndex].style.cssText instead of thisSheetRules[ruleIndex].cssText is a huge speed improvement
						}
					} else if(thisSheetRules[ruleIndex].styleSheet) {
						imported.push(thisSheetRules[ruleIndex].styleSheet);
						w3cImport = true;
					}
					
				}
			}
			//parse cssPile for image urls
			var tmpImage = cssPile.match(/[^\("]+\.(gif|jpg|jpeg|png)/g);//reg ex to get a string of between a "(" and a ".filename" / '"' for opera-bugfix
			if(tmpImage){
				var i = tmpImage.length;
				while(i--){ // handle baseUrl here for multiple stylesheets in different folders bug
					var imgSrc = (tmpImage[i].charAt(0) == '/' || tmpImage[i].match('://')) ? // protocol-bug fixed
						tmpImage[i] : 
						baseURL + tmpImage[i];
					
					if(jQuery.inArray(imgSrc, imgUrls) == -1){
						imgUrls.push(imgSrc);
					}
				}
			}
			
			if(!w3cImport && sheets[sheetIndex].imports && sheets[sheetIndex].imports.length) {
				for(var iImport = 0, importLen = sheets[sheetIndex].imports.length; iImport < importLen; iImport++){
					var iHref = sheets[sheetIndex].imports[iImport].href;
					iHref = iHref.split('/');
					iHref.pop();
					iHref = iHref.join('/');
					if (iHref) {
						iHref += '/'; //tack on a / if needed
					}
					var iSrc = (iHref.charAt(0) == '/' || iHref.match('://')) ? // protocol-bug fixed
						iHref : 
						baseURL + iHref;
					
					importedSrc.push(iSrc);
					imported.push(sheets[sheetIndex].imports[iImport]);
				}
				
				
			}
		}//loop
		if(imported.length){
			parseCSS(imported, importedSrc);
			return false;
		}
		var downloads = settings.simultaneousCacheLoading;
		while( downloads--){
			setTimeout(loadImgs, downloads);
		}
	}
	parseCSS(document.styleSheets);
	return imgUrls;
};
// jQuery Alert Dialogs Plugin
//
// Version 1.1
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 14 May 2009
//
// Visit http://abeautifulsite.net/notebook/87 for more information
//
// Usage:
//		jAlert( message, [title, callback] )
//		jConfirm( message, [title, callback] )
//		jPrompt( message, [value, title, callback] )
// 
// History:
//
//		1.00 - Released (29 December 2008)
//
//		1.01 - Fixed bug where unbinding would destroy all resize events
//
// License:
// 
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC. 
//
(function($) {
	
	$.alerts = {
		
		// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time
		
		verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .01,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: '&nbsp;Sim&nbsp;',         // text for the OK button
		cancelButton: '&nbsp;N&atilde;o&nbsp;', // text for the Cancel button
		dialogClass: null,                  // if specified, this class will be applied to all dialogs
		
		// Public methods
		
		alert: function(message, title, callback) {
			if( title == null ) title = 'Alerta';
			$.alerts._show(title, message, null, 'alert', function(result) {
				if( callback ) callback(result);
			});
		},
		
		confirm: function(message, title, callback) {
			if( title == null ) title = 'Alerta';
			$.alerts._show(title, message, null, 'confirm', function(result) {
				if( callback ) callback(result);
			});
		},
			
		prompt: function(message, value, title, callback) {
			if( title == null ) title = 'Prompt';
			$.alerts._show(title, message, value, 'prompt', function(result) {
				if( callback ) callback(result);
			});
		},
		
		// Private methods
		
		_show: function(title, msg, value, type, callback) {
			
			$.alerts._hide();
			$.alerts._overlay('show');
			
			$("BODY").append(
			  '<div id="popup_container">' +
			    '<h1 id="popup_title"></h1>' +
			    '<div id="popup_content">' +
			      '<div id="popup_message"></div>' +
				'</div>' +
			  '</div>');
			
			if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);
			
			// IE6 Fix
			var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; 
			
			$("#popup_container").css({
				position: pos,
				zIndex: 99999,
				padding: 0,
				margin: 0
			});
			
			$("#popup_title").text(title);
			$("#popup_content").addClass(type);
			$("#popup_message").text(msg);
			$("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );
			
			$("#popup_container").css({
				minWidth: $("#popup_container").outerWidth(),
				maxWidth: $("#popup_container").outerWidth()
			});
			
			$.alerts._reposition();
			$.alerts._maintainPosition(true);
			
			switch( type ) {
				case 'alert':
					$("#popup_message").after('<div id="popup_panel"><input type="button" value="OK" id="popup_ok" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
				break;
				case 'confirm':
					$("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
				break;
				case 'prompt':
					$("#popup_message").append('<br /><input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_prompt").width( $("#popup_message").width() );
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					if( value ) $("#popup_prompt").val(value);
					$("#popup_prompt").focus().select();
				break;
			}
			
			// Make draggable
			if( $.alerts.draggable ) {
				try {
					$("#popup_container").draggable({ handle: $("#popup_title") });
					$("#popup_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},
		
		_hide: function() {
			$("#popup_container").remove();
			$.alerts._overlay('hide');
			$.alerts._maintainPosition(false);
		},
		
		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$("BODY").append('<div id="popup_overlay"></div>');
					$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99998,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
				break;
				case 'hide':
					$("#popup_overlay").remove();
				break;
			}
		},
		
		_reposition: function() {
			var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;
			
			// IE6 fix
			if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
			
			$("#popup_container").css({
				top: top + 'px',
				left: left + 'px'
			});
			$("#popup_overlay").height( $(document).height() );
		},
		
		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', $.alerts._reposition);
					break;
					case false:
						$(window).unbind('resize', $.alerts._reposition);
					break;
				}
			}
		}
		
	}
	
	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	}
	
	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};
		
	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};
	
})(jQuery);
var fundoSetado=0;

jQuery.fn.extend({ 
    setFundo: function()
    {
        var script = '<div id="fundo" style="position:fixed; width:100%; height:100%; background-color:#000000;opacity: 0.20;filter:alpha(opacity=20); left:0; top:0; display:none;">&nbsp;</div>';
        this.append(script);
    }
});


jQuery.fn.extend({ 
    janela: function(NewOptions)
    {
        this.options = {
            id:'ID da Div',
            title:'T&iacute;tulo da Janela',
            img:'Imagem do topo da Janela',
            width:795,
            height: 544,
            url: 'URL que vai abrir a janela',
            animateOpen: true,
            modal: true
        };
			
        $.extend(this.options, NewOptions);
        var opt= this.options;
			
        if(fundoSetado == 0)
        {
            $("body").setFundo();
            fundoSetado = 1;
        }
			
        var margin_left = opt.width / 2;
        var margin_top = opt.height / 2;
			
        var script = '<div id="'+opt.id+'" class="janela" style="width:'+opt.width+'px; height:'+opt.height+'px; position:absolute; top: 50%; left: 50%; margin-top: -'+margin_top+'px; margin-left: -'+margin_left+'px; background-color:#B9D1EA; border:1px solid #000000; display:none; overflow:hidden;">';
        script += '<div id="'+opt.id+'_titulo" class="titulo_da_janela" style="height:20px; background-image:url(/images/bg_janela.png); padding: 5px 7px 5px 7px; cursor: default;" >';
        script += '	<div style="float:left">';
        script += '   	<img src="'+opt.img+'" /> &nbsp;&nbsp;'+ opt.title;
        script += '   </div>';
        script += '   <div style="float:right">';
        script += '   	<img  border="0" src="/images/btn_fechar.gif" onmouseover="this.src=\'/images/btn_fechar2.gif\'" onmouseout="this.src=\'/images/btn_fechar.gif\'" onclick="$(\'#'+opt.id+'\').close();" />';
        script += '   </div>';
        script += '</div>';
        script += '<div id="'+opt.id+'_conteudo" style="height:'+(opt.height-45)+'px; padding: 0px 7px 7px 7px; overflow: hidden;">';
        script += ' </div> ';
        script += ' <input type="hidden" id="'+opt.id+'_url" value="'+opt.url+'" />';
        script += ' <input type="hidden" id="'+opt.id+'_width" value="'+opt.width+'" />';
        script += ' <input type="hidden" id="'+opt.id+'_height" value="'+opt.height+'" />';
        script += ' <input type="hidden" id="'+opt.id+'_animateopen" value="'+opt.animateOpen+'" />';
        script += ' <input type="hidden" id="'+opt.id+'_modal" value="'+opt.modal+'" />';
        script += ' </div>';
			
        this.append(script);
			
    }
});

jQuery.fn.extend({ 
    close: function()
    {
        this.hide();
        $('#fundo').hide();
        $('#'+this.attr("id")+'_conteudo').html("");
    //this.animate({width: 0, height: 0 },500, function(){});
    }
});
	
jQuery.fn.extend({ 
    open: function(codigo_imovel, codigo_anunciante)
    {
        if(typeof(this.attr("id")) != "undefined")
        {
            var margin_left = parseInt($('#'+this.attr("id")+'_width').val()) / 2;
            var margin_top = parseInt($('#'+this.attr("id")+'_height').val()) / 2;
            var animateOpen = $('#'+this.attr("id")+'_animateopen').val();
            var modal = $('#'+this.attr("id")+'_modal').val();
	
            $('.box_menu').hide();
            $(".item_menu_titulo").removeClass('item_menu_titulo_selecionado');
				
            //$("html, body").animate({scrollTop:0 }, function(){});
            this.css({
                top: $("html, body").scrollTop() + 330
            });
				
            $('#'+this.attr("id")+'_conteudo').html('<div style="text-align:center; font-size: 12px; background: #F0F0F0; width: 100%; padding-top: '+ (margin_top - 80)+'px; height: 1000px"><img src="/images/load2.gif" /><br><b>Carregando...</b></div>');
            $('#'+this.attr("id")+'_conteudo').load($('#'+this.attr("id")+'_url').val() + "?imovel=" + codigo_imovel + "&anunciante=" + codigo_anunciante);
            this.show();
            if(modal == "true")
                $('#fundo').show();
            if(animateOpen == "true")
            {
                this.css({
                    width:"0px",
                    height:"0px",
                    marginLeft:"0px",
                    marginTop:"0px"
                });
					
                this.animate({
                    marginLeft: "-"+margin_left,
                    marginTop: "-"+margin_top,
                    width: $('#'+this.attr("id")+'_width').val(),
                    height: $('#'+this.attr("id")+'_height').val()
                    }, function(){});

            }
				
        }
    }
});
jQuery.fn.extend({
    openX: function(_obj)
    {
        if(typeof(this.attr("id")) != "undefined")
        {
            var margin_left = parseInt($('#'+this.attr("id")+'_width').val()) / 2;
            var margin_top = parseInt($('#'+this.attr("id")+'_height').val()) / 2;
            var animateOpen = $('#'+this.attr("id")+'_animateopen').val();
            var modal = $('#'+this.attr("id")+'_modal').val();

            $('.box_menu').hide();
            $(".item_menu_titulo").removeClass('item_menu_titulo_selecionado');

            //$("html, body").animate({scrollTop:0 }, function(){});
            this.css({
                top: $("html, body").scrollTop() + 330
            });

            $('#'+this.attr("id")+'_conteudo').html('<div style="text-align:center; font-size: 12px; background: #F0F0F0; width: 100%; padding-top: '+ (margin_top - 80)+'px; height: 1000px"><img src="/images/load2.gif" /><br><b>Carregando...</b></div>');
            var url = [];
            for(var i in _obj){
                url.push(i+'='+_obj[i]);
            }
            $('#'+this.attr("id")+'_conteudo').load($('#'+this.attr("id")+'_url').val()+'?'+url.join('&'));
            
            this.show();
            if(modal == "true")
                $('#fundo').show();
            if(animateOpen == "true")
            {
                this.css({
                    width:"0px",
                    height:"0px",
                    marginLeft:"0px",
                    marginTop:"0px"
                });

                this.animate({
                    marginLeft: "-"+margin_left,
                    marginTop: "-"+margin_top,
                    width: $('#'+this.attr("id")+'_width').val(),
                    height: $('#'+this.attr("id")+'_height').val()
                    }, function(){});

            }

        }
    }
});
/*
	Masked Input plugin for jQuery
	Copyright (c) 2007-2009 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) 
	Version: 1.2.2 (03/09/2009 22:39:06)
*/
(function(a){var c=(a.browser.msie?"paste":"input")+".mask";var b=(window.orientation!=undefined);a.mask={definitions:{"9":"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"}};a.fn.extend({caret:function(e,f){if(this.length==0){return}if(typeof e=="number"){f=(typeof f=="number")?f:e;return this.each(function(){if(this.setSelectionRange){this.focus();this.setSelectionRange(e,f)}else{if(this.createTextRange){var g=this.createTextRange();g.collapse(true);g.moveEnd("character",f);g.moveStart("character",e);g.select()}}})}else{if(this[0].setSelectionRange){e=this[0].selectionStart;f=this[0].selectionEnd}else{if(document.selection&&document.selection.createRange){var d=document.selection.createRange();e=0-d.duplicate().moveStart("character",-100000);f=e+d.text.length}}return{begin:e,end:f}}},unmask:function(){return this.trigger("unmask")},mask:function(j,d){if(!j&&this.length>0){var f=a(this[0]);var g=f.data("tests");return a.map(f.data("buffer"),function(l,m){return g[m]?l:null}).join("")}d=a.extend({placeholder:"_",completed:null},d);var k=a.mask.definitions;var g=[];var e=j.length;var i=null;var h=j.length;a.each(j.split(""),function(m,l){if(l=="?"){h--;e=m}else{if(k[l]){g.push(new RegExp(k[l]));if(i==null){i=g.length-1}}else{g.push(null)}}});return this.each(function(){var r=a(this);var m=a.map(j.split(""),function(x,y){if(x!="?"){return k[x]?d.placeholder:x}});var n=false;var q=r.val();r.data("buffer",m).data("tests",g);function v(x){while(++x<=h&&!g[x]){}return x}function t(x){while(!g[x]&&--x>=0){}for(var y=x;y<h;y++){if(g[y]){m[y]=d.placeholder;var z=v(y);if(z<h&&g[y].test(m[z])){m[y]=m[z]}else{break}}}s();r.caret(Math.max(i,x))}function u(y){for(var A=y,z=d.placeholder;A<h;A++){if(g[A]){var B=v(A);var x=m[A];m[A]=z;if(B<h&&g[B].test(x)){z=x}else{break}}}}function l(y){var x=a(this).caret();var z=y.keyCode;n=(z<16||(z>16&&z<32)||(z>32&&z<41));if((x.begin-x.end)!=0&&(!n||z==8||z==46)){w(x.begin,x.end)}if(z==8||z==46||(b&&z==127)){t(x.begin+(z==46?0:-1));return false}else{if(z==27){r.val(q);r.caret(0,p());return false}}}function o(B){if(n){n=false;return(B.keyCode==8)?false:null}B=B||window.event;var C=B.charCode||B.keyCode||B.which;var z=a(this).caret();if(B.ctrlKey||B.altKey||B.metaKey){return true}else{if((C>=32&&C<=125)||C>186){var x=v(z.begin-1);if(x<h){var A=String.fromCharCode(C);if(g[x].test(A)){u(x);m[x]=A;s();var y=v(x);a(this).caret(y);if(d.completed&&y==h){d.completed.call(r)}}}}}return false}function w(x,y){for(var z=x;z<y&&z<h;z++){if(g[z]){m[z]=d.placeholder}}}function s(){return r.val(m.join("")).val()}function p(y){var z=r.val();var C=-1;for(var B=0,x=0;B<h;B++){if(g[B]){m[B]=d.placeholder;while(x++<z.length){var A=z.charAt(x-1);if(g[B].test(A)){m[B]=A;C=B;break}}if(x>z.length){break}}else{if(m[B]==z[x]&&B!=e){x++;C=B}}}if(!y&&C+1<e){r.val("");w(0,h)}else{if(y||C+1>=e){s();if(!y){r.val(r.val().substring(0,C+1))}}}return(e?B:i)}if(!r.attr("readonly")){r.one("unmask",function(){r.unbind(".mask").removeData("buffer").removeData("tests")}).bind("focus.mask",function(){q=r.val();var x=p();s();setTimeout(function(){if(x==j.length){r.caret(0,x)}else{r.caret(x)}},0)}).bind("blur.mask",function(){p();if(r.val()!=q){r.change()}}).bind("keydown.mask",l).bind("keypress.mask",o).bind(c,function(){setTimeout(function(){r.caret(p(true))},0)})}p()})}})})(jQuery);
(function($){$.fn.lazyload=function(options){var settings={threshold:0,failurelimit:0,event:"scroll",effect:"show",container:window};if(options){$.extend(settings,options);}
var elements=this;if("scroll"==settings.event){$(settings.container).bind("scroll",function(event){var counter=0;elements.each(function(){if($.abovethetop(this,settings)||$.leftofbegin(this,settings)){}else if(!$.belowthefold(this,settings)&&!$.rightoffold(this,settings)){$(this).trigger("appear");}else{if(counter++>settings.failurelimit){return false;}}});var temp=$.grep(elements,function(element){return!element.loaded;});elements=$(temp);});}
this.each(function(){var self=this;if(undefined==$(self).attr("original")){$(self).attr("original",$(self).attr("src"));}
if("scroll"!=settings.event||undefined==$(self).attr("src")||settings.placeholder==$(self).attr("src")||($.abovethetop(self,settings)||$.leftofbegin(self,settings)||$.belowthefold(self,settings)||$.rightoffold(self,settings))){if(settings.placeholder){$(self).attr("src",settings.placeholder);}else{$(self).removeAttr("src");}
self.loaded=false;}else{self.loaded=true;}
$(self).one("appear",function(){if(!this.loaded){$("<img />").bind("load",function(){$(self).hide().attr("src",$(self).attr("original"))
[settings.effect](settings.effectspeed);self.loaded=true;}).attr("src",$(self).attr("original"));};});if("scroll"!=settings.event){$(self).bind(settings.event,function(event){if(!self.loaded){$(self).trigger("appear");}});}});$(settings.container).trigger(settings.event);return this;};$.belowthefold=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).height()+$(window).scrollTop();}else{var fold=$(settings.container).offset().top+$(settings.container).height();}
return fold<=$(element).offset().top-settings.threshold;};$.rightoffold=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).width()+$(window).scrollLeft();}else{var fold=$(settings.container).offset().left+$(settings.container).width();}
return fold<=$(element).offset().left-settings.threshold;};$.abovethetop=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).scrollTop();}else{var fold=$(settings.container).offset().top;}
return fold>=$(element).offset().top+settings.threshold+$(element).height();};$.leftofbegin=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).scrollLeft();}else{var fold=$(settings.container).offset().left;}
return fold>=$(element).offset().left+settings.threshold+$(element).width();};$.extend($.expr[':'],{"below-the-fold":"$.belowthefold(a, {threshold : 0, container: window})","above-the-fold":"!$.belowthefold(a, {threshold : 0, container: window})","right-of-fold":"$.rightoffold(a, {threshold : 0, container: window})","left-of-fold":"!$.rightoffold(a, {threshold : 0, container: window})"});})(jQuery);
var toLoadAfter = [];
toLoadAfter.push(
    function(){
        $(".combo_box").click(function() { return false; });
        $().click(function() {
            $(".lista_combo").hide();
        });
        $(document).bind("keydown", function(event) {
            var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
            if (keycode == 27) {
                $(".lista_combo").hide();
            }
        });
        $(".combo_box_menor").click(function() { return false; });
        $().click(function() {
            $(".lista_combo").hide();
        });
        $(".combo_box_medio").click(function() { return false; });
        $().click(function() {
            $(".lista_combo").hide();
        });
        $("#fundo_ficha").click(function() {
            $("#fundo_ficha").hide();
            $("#ficha").hide();
            $("#ficha").html("");
            var url = window.location.href;
            if (url.indexOf("#ficha") != -1) {
                history.go(-1);
            }
        });
    }
);
var pagina_navegacao_lancamentos = 1;
var pagina_navegacao_destaques = 1;

document.oncontextmenu = function() { return false };

function abrir_tab(numero)
{
    // Colocar 4 para busca no mapa
    $("#conteudo_tabs > div").hide();
    $("#aba_busca_livre").css('display','none');
    if (numero == 3) {
        $("#aba_busca_livre").css('display','block');
        $("#conteudo_tabs > div:eq(1)").show();
    } else {
        $("#conteudo_tabs > div:eq(0)").show();
    }
    $("#tabs > a").css("background", "url(/images/tabs.png) no-repeat");
    $("#tabs > a").css("color", "#666666");
    $("#tabs > a:eq(" + (numero - 1) + ")").css("background", "url(/images/tabs-atual.png) no-repeat");
    $("#tabs > a:eq(" + (numero - 1) + ")").css("color", "#FFF");
    $("#busca_avancada_opcoes").hide();

    if (numero == 1) {
        document.getElementById("form_consulta_inicial").action = "/imoveis";
    }
    if (numero == 2) {
        document.getElementById("form_consulta_inicial").action = "/imoveis/avancada";
    }
}
function abrirFicha(codigo)
{
    $("#fundo_ficha").show();
    $("#carregando").show();
    $('html, body').animate({scrollTop:0}, function() {});
    $("#ficha").load("/views/ficha.php?codigo=" + codigo + "&amp;tipo=janela", function() { $("#carregando").hide(); $("#ficha").show(); });
}
function abrirFichaResultado(codigo, aba)
{
    $("#fundo_ficha").show();
    $("#carregando").show();
    $('html, body').animate({scrollTop:0}, function() {});
    $("#ficha").load("/views/ficha.php?codigo=" + codigo + "&amp;aba=" + aba + "&amp;tipo=janela", function() { $("#carregando").hide(); $("#ficha").show(); });
}
function abrirBuscaAvancada() {
    $("#busca_avancada_opcoes").fadeIn();
}
var ysm_accountid = "20890180970";


