$(document).ready(function(){

    //$("#debug_console").css('background-color','#FFFFFF')
	
    var valores = new Array();
    var campos = new Array();
    var textos = new Array();
    var comboGlobal = new Array();
    var tcampos = "";
    var vals = "";
    var txts = "";
    var xmlGlobal = "";
    var action = $("#PesquisaComboBoxForm #response_action").val();
	

    //alert(action);
    $("select.pesquisaComboBox").each(function(i){
	
        $("select").eq(i).attr('disabled','disabled');
        arr_chave = $("select").eq(i).attr("name");
        tcampos+=$("select").eq(i).attr("name")+"|";
        valores[$("select").eq(i).attr("name")]=[];
        textos[$("select").eq(i).attr("name")]=[];
        $.each($("select:eq("+i+") option"), function(nv){
            vals+=$("select").eq(i).attr("name")+"[value][]="+$(this).val()+"&";
            txts+=$("select").eq(i).attr("name")+"[text][]="+$(this).text()+"&";
            valores[$("select").eq(i).attr("name")][nv]=$(this).val();
            textos[$("select").eq(i).attr("name")][nv]=$(this).text();
        });
        $("select").eq(i).attr('tabindex',i);
        campos[i] = $("select").eq(i).attr("name");
    });
	
    //$("#debug_console").css('background-color','#FFFFFF');
    //$("#debug_console").append(vals+txts);
	
    $.ajax({
		
        type:"POST",
        url:action,
        data:vals+txts,
        dataType:"xml",
        success: function(xml)
        {
			
            //alert('teste1');
            xmlGlobal = xml;
            $("select.pesquisaComboBox").each(function(i){
                var combo = new Array();
                combo[""] = $("select:eq("+i+") option:eq(0)").text();
                var tagnamesel = $(this).attr("name");
                $($(this).attr("name"), xml).each(function(i){
                    $(this).children().each(function(){
                        combo[$(this).attr("value")] = $(this).text();
                        comboGlobal[tagnamesel] = [$(this).attr("value")];
                        comboGlobal[tagnamesel][$(this).attr("value")]=$(this).text();
                    })
                })
                $("#"+$(this).attr("name")).html("");
                $("#"+$(this).attr("name")).addOption(combo, false);
                $(this).removeAttr("disabled");
            })
			
			
			
            //alert($("select").html());
			
            $("select.pesquisaComboBox:enabled:not(.lastItem)").change( function(){
				
                setLoadingLabel(this);
				
                var tagSel = new Array();
                var selecoes = new Array();
                var vals = "";
                var txts = "";
                var nome_campo = $(this).attr("name");
                var php_selected = "";
                var initial = jQuery.inArray(nome_campo, campos);
                var c = initial + 1;
				
                //alert($("select:not(:enabled) option:eq(1)").text());
				
                $("select.pesquisaComboBox:gt("+ initial +")").each(function(i){
				
                    //$("select.pesquisaComboBox").each(function(i){
					
                    var combo = new Array();
                    combo[""] = $("select:eq("+c+") option:eq(0)").text();
					
                    $($(this).attr("name"), xmlGlobal).each(function(i){
                        $(this).children().each(function(){
                            combo[$(this).attr("value")] = $(this).text();
                        })
                    })
					
                    $("#"+$(this).attr("name")).html("");
                    $("#"+$(this).attr("name")).addOption(combo, false);
                    c++;
					
                });
				
				
                $("select.pesquisaComboBox:gt("+initial+")").each(function(i){
                    //$("select.pesquisaComboBox").each(function(i){
                    $("#"+$(this).attr("name")).selectOptions($("#"+$(this).attr("name")).selectedValues(),true);
                    $(this).children().each(function(){
						
                        vals+= campos[initial+1] +"[value][]="+$(this).val()+"&";
                        txts+= campos[initial+1] +"[text][]="+$(this).text()+"&";
					
                    //vals+= campos[initial] +"[value][]="+$(this).val()+"&";
                    //txts+= campos[initial] +"[text][]="+$(this).text()+"&";
						
                    })
					
                    initial++;
					
                });

                var selecteds = $("select.pesquisaComboBox").selectedValues();
				
                if($("select.pesquisaComboBox:eq(0):not(:enabled) option:eq(1)").text()!="")
                {
                    selecteds[0] = $("select:not(:enabled) option:eq(1)").text();
                }
				
                //alert(selecteds);
                //alert($("select:not(:enabled)").selectedValues());

                jQuery.each(selecteds, function(i){
                    if(this!="")
                    {
                        //						php_selected+=$("select:not(:enabled) option:eq(1)").text()+"&";
                        php_selected+=campos[i]+"[selected]="+this+"&";
                    }
                });
				
                //alert(vals);
                //$("#debug_console").html(php_selected+vals+txts);
                $.ajax({
				
                    type:"POST",
                    url:action,
                    data:php_selected+vals+txts,
                    dataType:"xml",
                    success: function(xml2)
                    {
						
						
                        //alert(php_selected+vals+txts);
                        var child = "";
                        var valSel = new Array();
                        var comboSel = new Array();
						
                        numSel = $("select:enabled").size();
                        //alert(numSel);
						
                        $("selected", xml2).children().each(function(i) {
                            tagSel[i] = this.tagName;
                            selecoes[this.tagName] = $(this).text();
                        });
						
                        jQuery.each(tagSel, function(i) {
							
                            //alert(tagSel[i]);
                            var comboTmp = new Array();
                            var tagAtual = tagSel[i];
						
                            comboSel[tagAtual]=[];
                            $(tagSel[i], xmlGlobal).children().each(function(){
                                comboTmp[$(this).attr("value")] = $(this).text();
                                //alert($(this).attr("value"));
                                comboSel[tagAtual] = comboTmp;
                            })
                        })
						

                        var initial = jQuery.inArray(nome_campo, campos);

                        $("select.pesquisaComboBox:gt("+initial+")").each(function(i){
							
                            var combo2 = new Array();
                            var firstText = '';
                            var fieldId = $(this).attr("id");

                            if(fieldId == 'TRANSACAO' || fieldId == 'CIDADE') {
                                firstText = 'Todas'; 
                            } else if(fieldId == 'DORMS' || fieldId == 'BAIRRO' || fieldId == 'VALOR_VENDA' || fieldId == 'VALOR_LOCACAO') {
                                firstText = 'Todos'; 
                            } else {
                                firstText = $("select.pesquisaComboBox:eq("+i+") option[value='']").text();
                            }


                            combo2['0']=firstText;
							
                            var depura = $(this).attr("name");
                            var condition = false;
							
                            $($(this).attr("name"),xml2).each(function(i){
                                $(this).children().each(function(){
                                    combo2[$(this).attr("value")] = $(this).text();
                                })
                                if($(this).children().size()=="1")
                                {
                                    condition=true;
                                }
                                valSel[depura] = $("#"+depura+" option:selected").text();
                            })
							
                            $("#"+$(this).attr("name")).html("");
							
                            //alert($(this).attr("name")+"\n"+vardump(combo2));
                            $("#"+$(this).attr("name")).addOption(combo2, condition);
							
                            /*if(condition){
								$("#"+$(this).attr("name")).trigger("change");
							}*/
							
			
                            $("#"+$(this).attr("name")).selectOptions(valSel[$(this).attr("name")]);
                            //$("#"+$(this).attr("name")).sortOptions(); 
                            if(typeof(selecoes[$(this).attr("name")])!="undefined")
                            {
                                //alert($(this).attr("name"));
                                $("#"+$(this).attr("name")).addOption(comboSel[$(this).attr("name")], false);
                                $("#"+$(this).attr("name")).selectOptions(selecoes[$(this).attr("name")]);
                            //$("#"+$(this).attr("name")).selectOptions(selecoes[$(this).attr("name")]);
                            }
                            $(this).children().each(function(){
                                //alert($(this).val());
                                if($(this).text()=="") $(this).remove();
                            })
							
                            //habilita os selectecs
                            $(this).removeAttr('disabled');

                        })
						
                        //certifica se a opção Finalidade existe para definir qual Valor será usado
                        if($("#PesquisaComboBoxForm #TRANSACAO.pesquisaComboBox ").length > 0) {
							
                            $("#PesquisaComboBoxForm #TRANSACAO.pesquisaComboBox ").each(function(){
                                if($(this).selectedValues() == "locacao")
                                {
                                    $("#PesquisaComboBoxForm #VALOR_VENDA").attr("disabled","disabled");
                                    $("#PesquisaComboBoxForm #VALOR_VENDA").hide();
                                    $("#PesquisaComboBoxForm #VALOR_LOCACAO").removeAttr("disabled");
                                    $("#PesquisaComboBoxForm #VALOR_LOCACAO").show();
                                }
                                else
                                {
                                    $("#PesquisaComboBoxForm #VALOR_VENDA").removeAttr("disabled");
                                    $("#PesquisaComboBoxForm #VALOR_VENDA").show();
                                    $("#PesquisaComboBoxForm #VALOR_LOCACAO").attr("disabled","disabled");
                                    $("#PesquisaComboBoxForm #VALOR_LOCACAO").hide();
                                }
								
                            })
                        }
						
                        //caso Finalidade não exista defini os Valores para Venda
                        else {
						
                            $("#PesquisaComboBoxForm #VALOR_VENDA").removeAttr("disabled");
                            $("#PesquisaComboBoxForm #VALOR_VENDA").show();
                            $("#PesquisaComboBoxForm #VALOR_LOCACAO").attr("disabled","disabled");
                        }
                    }
                });
            })
        }
    })
	
	
    function setLoadingLabel(obj){
	
        _index = $("select.pesquisaComboBox").index(obj);
        option = "<option>Carregando ... </option>";
		
        //seta o label
        $("select.pesquisaComboBox:gt(" +_index +")").html(option);
		
        //desabilita os selects
        $("select.pesquisaComboBox:gt(" +_index +")").attr("disabled","disabled");
    }
})

