$(function () {

    transacao_avc = '1';
    v_tipo = '';
    v_estado = '';
    v_cidade = '';
    v_bairro = ''

    v_tipoDesc = '';
    v_estadoDesc = '';
    v_cidadeDesc = '';
    v_bairroDesc = '';

    aux_count_tipo = 0;
    aux_count_bairro = 0;

    max_tipos = 4;
    max_bairros = 10;

    once = 0;

    
    host = 'http://www.netimoveis.com/';

    // DEFINIÇÃO DE ÍCONES PERSONALIZADOS PARA ACCORDION
    var icons = {
        header: "icone_desativado",
        headerSelected: "icone_ativado"
    };

    // CONFIGURAÇÃO DO ACCORDION
    $("#accordion").accordion({
        collapsible: false,
        autoHeight: false,
        icons: icons,
        active: false
    });


    // INICIA TIPOS DE IMÓVEIS
    //carrega_tipos();

    // ATUALIZA LISTAS AO ALTERAR O TIPO DE TRANSAÇÃO
    $('.radio_transacao').change(function () {
        transacao_avc = $(this).attr('value');

        v_tipo = '';
        v_estadoDesc = '';

        aux_count_tipo = 0;

        v_estado = '';
        v_estadoDesc = '';

        v_cidade = '';
        v_cidadeDesc = '';

        v_bairro = '';
        v_bairroDesc = '';

        aux_count_bairro = 0;

        $('#step_header_2 > span').text('');
        $('#step_header_3 > span').text('');
        $('#step_header_4 > span').text('');
        $('#step_header_5 > span').text('');

        $('#step_header_2').click();
        carrega_tipos();

    });

    // EVENTO DE MUDANÇA DE ACCORDION
    $('.ui-accordion').bind('accordionchangestart', function (event, ui) {

        scroolDown();

        // ALTERA ÍCONE
        $(ui.newHeader).children('.step').css('color', '#f47b1d');
        $(ui.oldHeader).children('.step').css('color', '#fff');

        // ALTERA ESTILO DE FONTE DE NUMERAÇÃO
        $(ui.oldHeader).children('.seta').children('img').attr('src', 'java/js_busca/jquery-ui/development-bundle/themes/base/images/seta_desce.jpg');
        $(ui.newHeader).children('.seta').children('img').attr('src', 'java/js_busca/jquery-ui/development-bundle/themes/base/images/seta_sobe.jpg');

        // CAPTURA O ID DO ACCORDION CLICADO
        step_clicado = $(ui.newHeader).find('a').attr('id');

        // CARREGA A LISTA PARA O ACCORDIO CLICADO
        if (step_clicado == 'step_header_2') {

            $('#step_1').css("background-image", "url('java/js_busca/jquery-ui/development-bundle/themes/base/images/icone_header_des.jpg')");
            $('#step_1').css('color', '#fff');
            $('#transacao_busca_pp').css('background-image', 'none');
            $('#transacao_radios').css('color', '#46413d');
            $('#transacao_radios span').css('font-weight', 'normal');


            carrega_tipos();
        }
        else if (step_clicado == 'step_header_3') {
            carrega_estados();
        }
        else if (step_clicado == 'step_header_4') {
            carrega_cidades();
        }
        else if (step_clicado == 'step_header_5') {
            carrega_bairros();
        }

    });

    // CAPTURA TIPOS SELECIONADOS
    $('#lista_tipo').find('input').live('click', function () {

        if ($(this).is(':checked')) {
            aux_count_tipo++;
        }
        else {
            aux_count_tipo--;
        }

        if (aux_count_tipo <= max_tipos) {

            v_tipoDesc = '';
            v_tipo = '';

            captura_tipos_marcados();

            //ZERA FILTROS DESCENDENTES
            v_estado = '';
            v_estadoDesc = '';

            v_cidade = '';
            v_cidadeDesc = '';

            v_bairro = '';
            v_bairroDesc = '';

            aux_count_bairro = 0;

            $('#step_header_3 > span').text('');
            $('#step_header_4 > span').text('');
            $('#step_header_5 > span').text('');
            $('#bt_buscar_pp').attr('src', 'images/geral/bt_buscar_novo_des.jpg');

        }
        else {
            $(this).attr('checked', false);
            aux_count_tipo--;
            alert('VocÃª pode selecionar atÃ© ' + max_tipos + ' tipos de imÃ³veis.');
        }
    });


    // CAPTURA TIPOS SELECIONADOS
    //Busca rápida content_box_filter_list_rapido
    $('.content_box_filter_list_rapido').find('input').live('click', function () {

        if ($(this).is(':checked')) {
            aux_count_tipo++;
        }
        else {
            aux_count_tipo--;
        }

        if (aux_count_tipo <= max_tipos) {

            v_tipoDesc = '';
            v_tipo = '';

            captura_tipos_marcados();

            //ZERA FILTROS DESCENDENTES
            v_estado = '';
            v_estadoDesc = '';

            v_cidade = '';
            v_cidadeDesc = '';

            v_bairro = '';
            v_bairroDesc = '';

            aux_count_bairro = 0;

            $('#step_header_3 > span').text('');
            $('#step_header_4 > span').text('');
            $('#step_header_5 > span').text('');
            $('#bt_buscar_pp').attr('src', 'images/geral/bt_buscar_novo_des.jpg');

        }
        else {
            $(this).attr('checked', false);
            aux_count_tipo--;
            alert('VocÃª pode selecionar atÃ© ' + max_tipos + ' tipos de imÃ³veis.');
        }
    });
    



    // CAPTURA ESTADO SELECIONADO
    $('#lista_estado').find('input').live('click', function () {

        v_estadoDesc = $(this).next('label').text();
        v_estado = $(this).parent('span').attr('class');

        mostra_estado = v_estadoDesc;
        mostra_estado = ' - ' + mostra_estado;

        $('#step_header_3 > span').text(mostra_estado);

        //ZERA FILTROS DESCENDENTES
        v_cidade = '';
        v_cidadeDesc = '';

        v_bairro = '';
        v_bairroDesc = '';

        aux_count_bairro = 0;

        $('#step_header_4 > span').text('');
        $('#step_header_5 > span').text('');
        $('#bt_buscar_pp').attr('src', 'images/geral/bt_buscar_novo_des.jpg');

    });

    // CAPTURA CIDADE SELECIONADA
    $('#lista_cidade').find('input').live('click', function () {

        v_cidadeDesc = $(this).next('label').text();
        v_cidade = $(this).parent('span').attr('class');

        mostra_cidade = v_cidadeDesc;
        mostra_cidade = ' - ' + mostra_cidade;

        $('#step_header_4 > span').text(mostra_cidade);

        //ZERA FILTROS DESCENDENTES
        v_bairro = '';
        v_bairroDesc = '';

        aux_count_bairro = 0;

        $('#step_header_5 > span').text('');
        $('#bt_buscar_pp').attr('src', 'images/geral/bt_buscar_novo_des.jpg');

    });


    // CAPTURA BAIRROS SELECIONADOS
    //Busca Rápida Add: Leandro Davi de Freitas
    $('.content_box_filter_list_rapido_regiao').find('input').live('click', function () {

        $('#bt_buscar_pp').attr('src', 'images/geral/bt_buscar_novo.jpg');

        if ($(this).is(':checked')) {
            aux_count_bairro++;
        }
        else {
            aux_count_bairro--;
        }

        if (aux_count_bairro <= max_bairros) {

            captura_bairros_marcados();

        }
        else {
            $(this).attr('checked', false);
            aux_count_bairro--;
            alert('VocÃª pode selecionar atÃ© ' + max_bairros + ' Bairros.');
        }

        if (aux_count_bairro == 0) {
            $('#bt_buscar_pp').attr('src', 'images/geral/bt_buscar_novo_des.jpg');
        }
    });




    // CAPTURA BAIRROS SELECIONADOS
    $('#lista_bairro').find('input').live('click', function () {

        $('#bt_buscar_pp').attr('src', 'images/geral/bt_buscar_novo.jpg');

        if ($(this).is(':checked')) {
            aux_count_bairro++;
        }
        else {
            aux_count_bairro--;
        }

        if (aux_count_bairro <= max_bairros) {

            captura_bairros_marcados();

        }
        else {
            $(this).attr('checked', false);
            aux_count_bairro--;
            alert('VocÃª pode selecionar atÃ© ' + max_bairros + ' Bairros.');
        }

        if (aux_count_bairro == 0) {
            $('#bt_buscar_pp').attr('src', 'images/geral/bt_buscar_novo_des.jpg');
        }
    });

    //INCLUI EVENTO DO BOTÃO PRÓXIMO PASSO
    $('.bt_proximo_passo').click(function () {

        id_botao = $(this).attr('id');

        if (id_botao == 'bt_proximo_passo_tipo') {
            $('#step_header_3').click();
        }
        if (id_botao == 'bt_proximo_passo_estado') {
            $('#step_header_4').click();
        }
        if (id_botao == 'bt_proximo_passo_cidade') {
            $('#step_header_5').click();
        }
    });

    //INCLUI EVENTO DO BOTÃO VOLTAR
    $('.bt_voltar').click(function () {

        id_botao = $(this).attr('id');

        if (id_botao == 'bt_voltar_estado') {
            $('#step_header_2').click();
        }
        if (id_botao == 'bt_voltar_cidade') {
            $('#step_header_3').click();
        }
        if (id_botao == 'bt_voltar_bairro') {
            $('#step_header_4').click();
        }
    });

    //INCLUI EVENTO DO BOTÃO LIMPAR
    $('.bt_limpar').click(function () {

        $('.lista input:checked').each(function () {
            $(this).attr('checked', false);
        });

        id_bt_limpar = $(this).attr('id');

        if (id_bt_limpar == 'bt_limpar_tipo') {
            v_tipo = '';
            v_tipoDesc = '';
            aux_count_tipo = 0;
            $('#step_header_2 > span').text('');
            $('#bt_buscar_pp').attr('src', 'images/geral/bt_buscar_novo_des.jpg');
        }

        if (id_bt_limpar == 'bt_limpar_estado') {
            v_estado = '';
            v_estadoDesc = '';
            $('#step_header_3 > span').text('');
            $('#bt_buscar_pp').attr('src', 'images/geral/bt_buscar_novo_des.jpg');
        }

        if (id_bt_limpar == 'bt_limpar_cidade') {
            v_cidade = '';
            v_cidadeDesc = '';
            $('#step_header_4 > span').text('');
            $('#bt_buscar_pp').attr('src', 'images/geral/bt_buscar_novo_des.jpg');
        }

        if (id_bt_limpar == 'bt_limpar_bairro') {
            v_bairro = '';
            v_bairroDesc = '';
            aux_count_tipo = 0;
            aux_count_bairro = 0;
            $('#step_header_5 > span').text('');
            $('#bt_buscar_pp').attr('src', 'images/geral/bt_buscar_novo_des.jpg');
        }

    });

    //INCLUI EVENTO DO CAMPO DE FILTRO
    $(".campo_procura").keyup(function () {
        filter($(this), '.lista:visible label');
    });


    // ## FUNÇÕES ##
    function carrega_tipos() {

        $('#lista_tipo').empty();
        $('.campo_procura').val('');

        $.post(
			host + 'montaBuscaAvancada.aspx?home=sim',
			{
			    consulta: 'tipo',
			    transacao: transacao_avc
			},
			function (data) {
			    $('#lista_tipo').html(data);

			    tipo_array = v_tipo.split(',');

			    $('#lista_tipo input').each(function () {

			        for (i = 0; i < tipo_array.length; i++) {
			            if ($(this).parent('span').attr('class') == tipo_array[i]) {
			                $(this).attr('checked', true);
			            }
			        }

			    });
			},
			'html'
		);
    }

    function carrega_estados() {

        $('#lista_estado').empty();
        $('.campo_procura').val('');

        $.post(
			host + 'montaBuscaAvancada.aspx?home=sim',
			{
			    consulta: 'estado',
			    transacao: transacao_avc,
			    tipo: v_tipo
			},
			function (data) {
			    aux_count_tipo = 0;
			    $('#lista_estado').html(data);

			    $('#lista_estado input').each(function () {

			        if ($(this).parent('span').attr('class') == v_estado) {
			            $(this).attr('checked', true);
			        }

			    });
			},
			'html'
		);
    }

    function carrega_cidades() {

        $('#lista_cidade').empty();
        $('.campo_procura').val('');

        $.post(
			host + 'montaBuscaAvancada.aspx?home=sim',
			{
			    consulta: 'cidade',
			    transacao: transacao_avc,
			    tipo: v_tipo,
			    estado: v_estado
			},
			function (data) {
			    $('#lista_cidade').html(data);

			    $('#lista_cidade input').each(function () {

			        if ($(this).parent('span').attr('class') == v_cidade) {
			            $(this).attr('checked', true);
			        }

			    });
			},
			'html'
		);
    }

    function carrega_bairros() {

        var colunas;

        $('#lista_bairro').empty();
        $('.campo_procura').val('');

        $('#div_mapa_bh').hide();
        $('#div_mapa_sp').hide();

        if (v_cidade == '2754') {
            colunas = 1;
            $('#lista_bairro').css('margin-left', '260px');
            $('#div_mapa_bh').show();
        }
        else if (v_cidade == '6680') {
            colunas = 1;
            $('#lista_bairro').css('margin-left', '260px');
            $('#div_mapa_sp').show();
        }
        else {
            $('#lista_bairro').css('margin-left', '0px');
            colunas = 2;
        }

        $.post(
			host + 'montaBuscaAvancada.aspx?home=sim',
			{
			    consulta: 'bairro',
			    transacao: transacao_avc,
			    tipo: v_tipo,
			    estado: v_estado,
			    cidade: v_cidade,
			    coluna: colunas
			},
			function (data) {
			    $('#lista_bairro').html(data);
			     
			    marca_bairros();
			},
			'html'
		);
    }

    function marca_bairros() {
        bairro_array = v_bairro.split(',');

        $('#lista_bairro input').each(function () {

            for (i = 0; i < bairro_array.length; i++) {
                if ($(this).parent('span').attr('class') == bairro_array[i]) {
                    $(this).attr('checked', true);
                }
            }

        });
    }

    function captura_bairros_marcados() {

        v_bairroDesc = '';
        v_bairro = '';

        $('#lista_bairro input:checked').each(function () {
            v_bairroDesc = v_bairroDesc + $(this).next('label').text() + ',';
            v_bairro = v_bairro + $(this).parent('span').attr('class') + ',';
        });

        mostra_bairros = v_bairroDesc;
        mostra_bairros = mostra_bairros.replace(/,/gi, " | ");
        mostra_bairros = mostra_bairros.substr(0, mostra_bairros.length - 3);

        if (mostra_bairros.length > 70) {
            mostra_bairros = mostra_bairros.substr(0, 70);
            mostra_bairros = mostra_bairros + '...'
        }

        if (mostra_bairros != '') {
            mostra_bairros = ' - ' + mostra_bairros;
        }

        $('#step_header_5 > span').text(mostra_bairros);
    }

    function captura_tipos_marcados() {
        $('#lista_tipo input:checked').each(function () {
            v_tipoDesc = v_tipoDesc + $(this).next('label').text() + ',';
            v_tipo = v_tipo + $(this).parent('span').attr('class') + ',';
        });

        mostra_tipos = v_tipoDesc.replace(/Apartamento/gi, "Ap.");
        mostra_tipos = mostra_tipos.replace(/,/gi, " | ");
        mostra_tipos = mostra_tipos.replace(/condomínio/gi, "cond.");
        mostra_tipos = mostra_tipos.replace(/geminada/gi, "germ.");
        mostra_tipos = mostra_tipos.substr(0, mostra_tipos.length - 3);

        if (mostra_tipos.length > 57) {
            mostra_tipos = mostra_tipos.substr(0, 57);
            mostra_tipos = mostra_tipos + '...'
        }

        if (mostra_tipos != '') {
            mostra_tipos = ' - ' + mostra_tipos;
        }

        $('#step_header_2 > span').text(mostra_tipos);
    }

    function filter(inputSelector, listSelector) {

        // Sanity check  
        var inp, rgx = new RegExp(), titles = $(listSelector), keys;

        if (titles.length === 0) {
            return false;
        }
        // The list with keys to skip (esc, arrows, return, etc)
        // 8 is backspace, you might want to remove that for better usability
        keys = [13, 27, 32, 37, 38, 39, 40];

        // binding keyup to the unordered list
        $(inputSelector).bind('keyup', function (e) {
            if (jQuery.inArray(e.keyCode, keys) >= 0) {
                return false;
            }

            // Building the regex from our user input, 'inp' should be escaped
            inp = $(this).val();
            rgx.compile(inp, 'im');
            titles.each(function () {
                if (rgx.source !== '' && !rgx.test($(this).html())) {
                    $(this).parent().parent('td').hide();
                } else {
                    $(this).parent().parent('td').show();
                }
            });
        });
    }

    function scroolDown() {
        if (window.location == host + 'default.aspx') {
            if (once != 1) {
                $('html,body').animate({ scrollTop: 230 }, 1600);
                once = 1
            }
        }
    }

});
