// JavaScript Document

$(document).ready(function($){
	 $("#valor_min").maskMoney({symbol:"",decimal:",",thousands:"."});  
	 $("#valor_max").maskMoney({symbol:"",decimal:",",thousands:"."}); 
    $.fn.radioSel = function(valueToSel){
        if(arguments.length>0){
            if(valueToSel!=''){
                return this.each(function(){
                    if($(this).val()==valueToSel)this.checked = true;
                })
            }else{
                return this.each(function(){ this.checked = false; })
            }
        }else{
            valorSelecionado = false;
            this.each(function(){
                if(this.checked){
                    valorSelecionado = $(this).val();
                    return valorSelecionado;
                }
            });
            return valorSelecionado;
        }
    };

    $("input[name=transacao]").click(function() {
        carregaTipos();
    });

    $("#btnPesquisar").click(function() {
        enviaPesquisa();
    });

    function carregaTipos(){
        $.ajax({
            type: "POST",
            url: "/includes/ajax_tipo_imovel.php",
            data: getFormValues() + gets,
            dataType: "html",
            beforeSend: function() {
                $("#tipo_imovel").multiselect("destroy");
                $("#estado").multiselect("destroy");
                $("#cidade").multiselect("destroy");
                $("#bairros").multiselect("destroy");

                $("#td_select_tipo_imovel").html("carregando...");
                $("#td_select_estado").html("carregando...");
                $("#td_select_cidade").html("carregando...");
                $("#td_select_bairros").html("carregando...");
            },
            success: function(html) {
                $("#td_select_tipo_imovel").html(html);
                $("#tipo_imovel").multiselect({
					selectedList: 3,
                    close: function() {
                        carregaEstados();
                    }
                }).multiselectfilter();
                carregaEstados();
            }
        });
    }

    function carregaEstados(){
        $.ajax({
            type: "POST",
            url: "/includes/ajax_estado.php",
            data: getFormValues() + gets,
            dataType: "html",
            beforeSend: function() {
                $("#estado").multiselect("destroy");
                $("#cidade").multiselect("destroy");
                $("#bairros").multiselect("destroy");

                $("#td_select_estado").html("carregando...");
                $("#td_select_cidade").html("carregando...");
                $("#td_select_bairros").html("carregando...");
            },
            success: function(html) {
                $("#td_select_estado").html(html);
                $("#estado").multiselect({
                    header:false,
                    multiple:false,
					selectedList: 1,
                    click: function() {
                        $(this).multiselect("close");
                    },
                    close: function() {
                        carregaCidades();
                    }
                });

                carregaCidades();
            }
        });
    }

    function carregaCidades(){
        $.ajax({
            type: "POST",
            url: "/includes/ajax_cidade.php",
            data: getFormValues() + gets,
            dataType: "html",
            beforeSend: function() {
                $("#cidade").multiselect("destroy");
                $("#select_bairros").multiselect("destroy");

                $("#td_select_cidade").html("carregando...");
                $("#td_select_bairros").html("carregando...");
            },
            success: function(html) {
                $("#td_select_cidade").html(html);
                $("#cidade").multiselect({
                    header:false,
					selectedList: 1,
                    multiple:false,
                    click: function() {
                        $(this).multiselect("close");
                    },
                    close: function() {
                        carregaBairros();
                    }
                });

                carregaBairros();
            }
        });
    }

    function carregaBairros(){
        $.ajax({
            type: "POST",
            url: "/includes/ajax_bairros.php",
            data: getFormValues() + gets,
            dataType: "html",
            beforeSend: function() {
                $("#bairros").multiselect("destroy");
                $("#td_select_bairros").html("carregando...");
            },
            success: function(html) {
                $("#td_select_bairros").html(html);
                $("#bairros").multiselect({selectedList: 3}).multiselectfilter();
            }
        });
    }

    function getFormValues()
    {
        var values = "transacao=" + $('input[name=transacao]').radioSel();
        values    += "&num_quarto_min=" + $("#num_quarto_min").val();
        values    += "&num_quarto_max=" + $("#num_quarto_max").val();
        values    += "&valor_max=" + $("#valor_max").val() + "&valor_min=" + $("#valor_min").val();
		values    += "&codigo_imovel=" + $("#codigo_imovel").val();

        // Tipos
        var checkeds = $("#tipo_imovel").multiselect("getChecked").map(function(){
            return this.value;
        });

        for (var i = 0; i < checkeds.length; i++) {
            values += "&tipo_imovel[]=" + checkeds[i];
        }

        // Estado
        var checkeds = $("#estado").multiselect("getChecked").map(function(){
            return this.value;
        });

        for (var i = 0; i < checkeds.length; i++) {
            values += "&estado=" + checkeds[i];
        }

        // Cidade
        var checkeds = $("#cidade").multiselect("getChecked").map(function(){
            return this.value;
        });

        for (var i = 0; i < checkeds.length; i++) {
            values += "&cidade=" + checkeds[i];
        }

        // Bairros
        var checkeds = $("#bairros").multiselect("getChecked").map(function(){
            return this.value;
        });

        for (var i = 0; i < checkeds.length; i++) {
            values += "&bairros[]=" + checkeds[i];
        }

        return values;
    }

    function enviaPesquisa()
    {
		if($("#codrede").val() != ""){ 
					$.ajax({
					type: "POST",
					url: "/includes/ajax_busca_codigo.php",
					data: "codrede="+$("#codrede").val(),
					dataType: "html",
					success: function(msg) {
						if(msg=='ok') {
							window.location="/detalhe-do-imovel?codigo="+$("#codrede").val();
							return true;					
						}
						else{
							alert('O imóvel '+$("#codrede").val()+' não foi encontrado, para obter mais detalhes entre em contato conosco.');
							}
					}
				});
			return false;
		} 
        window.location = base_url + '/resultado-da-busca?' + getFormValues();
    }

    carregaTipos();
});


/*
function carregaTipos(){
        $.ajax({
            type: "POST",
            url: "/includes/ajax_tipo_imovel.php",
            data: $("#formBusca").serialize() + gets,
            dataType: "html",
            success: function(html) {
                $("#td_select_tipo_imovel").html(html);
                $("#tipo_imovel").multiselect({close: function(){
                                                               $("#estado").multiselect("disable");
                                                               $("#cidade").multiselect("disable");
                                                               $("#bairro").multiselect("disable");
                                                               carregaEstado();
                                                               }}).multiselectfilter();
                carregaEstado();

            }
        });
}

function carregaEstado(){
     $.ajax({
        type: "POST",
        url: "/includes/ajax_estado.php",
        data: $("#formBusca").serialize() + gets,
        dataType: "html",
        success: function(html) {
            $("#td_select_estado").html(html);
            $("#estado").multiselect({
                                         header:false,
                                         multiple:false,
                                         click: function(){
                                                        $(this).multiselect("close")
                                                        },
                                         close: function(){
                                                       $("#cidade").multiselect("disable");
                                                       $("#bairro").multiselect("disable");
                                             carregaCidade();
                                             }
                                    });
            carregaCidade();
                }
    })

}

function carregaCidade() {
    $.ajax({
        type: "POST",
        url: "/includes/ajax_cidade.php",
        data: $("#formBusca").serialize() + gets,
        dataType: "html",
        success: function(html) {
                    $("#td_select_cidade").html(html);
                    $("#cidade").multiselect({
                                             header:false,
                                             multiple:false,
                                             click: function(){
                                                    $(this).multiselect("close");
                                                    },
                                            close: function(){
                                               $("#bairro").multiselect("disable");
                                                carregaBairro();
                                                }
                    });
                    carregaBairro();
        }
    });

}


function carregaBairro(){
        $.ajax({
            type: "POST",
            url: "/includes/ajax_bairros.php",
            data: $("#formBusca").serialize() + gets,
            dataType: "html",
            success: function(html) {
                $("#td_select_bairros").html(html);
            }
        })
}

$(document).ready(function($){
    $("input[name=transacao]").click(function() {
        carregaTipos();
    });

    carregaTipos();
});*/
