
$( function() {

    var opened = null;
    var heightdefaultlf = 115;
    var conteudohtml = {};
    var htmllista = "";
    var valmin = "";
    var valmax = "";
    var itensordem = [];

    $.fn.comboFiltroSelecionaAnoValor = function() {
        return this.each(function(){
            $("#parm1 input, #parm2 input").click(function(){
                //$(this).toggleClass("selected");
                $(this).parent().parent().find("input").not($(this)).each(function(){
                    $(this).removeAttr("checked");
                });
            });
        });
    }


    $.comboFiltroRecuperaSelecao = function() {
        var itemselecionados = [];
        var filtro = $(opened).attr("id").substr(2);
        if ( filtro == "ano" || filtro == "valor" ) {
            itemselecionados[0] = 0;
            itemselecionados[1] = 0;
            $("#lfconteudo input:checked").each( function(){
                index = ( $(this).parent().parent().attr("id") == "parm1" ) ? 0 : 1;
                itemselecionados[index] = $(this).val();
            });

        } else {
            $("#lfconteudo li input:checked").each(function(i,objinput){
                if ( $(objinput).val() > 0 )
                    itemselecionados[i] = $(objinput).val();
            });
        }
        return itemselecionados;

    }


    $.fn.comboFiltroAcertaAltura = function() {
        return this.each(function(){
                /*

                // acerta a altura da div "conteudo"
                heighttotal = 0;
                $("#lfconteudo li").each( function(i) {
                    heighttotal += $(this).height();
                });
                if ( heighttotal < $("#lfconteudo").height() ) $("#lfconteudo").height( heighttotal + 7 );

                if ( heighttotal+30 < $(this).height() ) {
                    $(this).height( heighttotal + 38 );//.redrawShadow();
                } else if ( $("#listafiltro").height() != heightdefaultlf ) {
                    $(this).height( heightdefaultlf );//.redrawShadow();
                }

             */

        });
    }


    $.fn.comboFiltro = function( options ) {
        var opts = $.extend({
            label: '',
            lfwidth: 170
        }, options );

        return this.each(function(){
            var obj = this;

            var itematual = $(this).attr("id").substr(2);
            var flgtemfiltro = false;
            $.each( $.jqURL.qs({ret:'object'}), function(i,val) {
                if ( i.indexOf(itematual) == 0 ) {
                    if ( itematual == 'ano' ) {
                        if ( $.jqURL.get('ano1') > 0 || $.jqURL.get('ano2') > 0 ) {
                            flgtemfiltro = true;
                            return false;
                        }
                    } else {
                        flgtemfiltro = true;
                        return false;
                    }
                }
            });


            if ( flgtemfiltro ) {
                $(this).addClass("filtro").css("cursor","default");
                $(this).height(20);
                $(this).html( '<div class="cantoesq"></div><div class="conteudo"><div class="label">'+ opts.label +'</div><div class="removefiltro"><span>X</span></div></div><div class="cantodir"></div>' );
                $(this).find(".conteudo").width( $(obj).width() - 10 );
                $(".removefiltro").click( function() {
                    var novaurl = '';
                    itemremove = $(this).parent().parent().attr("id").substr(2);
                    $.each( $.jqURL.qs({ret:'object'}), function(i,val) {
                        if ( !i.indexOf(itemremove) == 0 && val != undefined ) novaurl += i + "=" + val + "&";
                    });
                    location.href = "?" + novaurl;
                });
            } else {
                $(this).height(20);
                $(this).html( '<div class="cantoesq"></div><div class="conteudo">'+ opts.label +'</div><div class="btn"><span>&raquo;</span></div>' );
                $(this).find(".conteudo").width( $(obj).width() - 27 );


                // desabilita o combo se tiver apenas um veiculo
                if ( $("#veiculos .item").length <= 1 ) {
                    
                    $(this).after("<div class=\"fpdisabled\">&nbsp;</div>");
                    var position = $(this).offset();
                    $(this).css( {color: '#b6b6b6'});
                    $(this).next().css( {left: position.left, top: position.top} ).width( $(this).width() ).opacity(.1);

                } else {
                    $(this).click( function() {

                        if ( $("#listafiltro").is(":visible") ) {
                            itemselecionados = $.comboFiltroRecuperaSelecao();
                            filtro = $(opened).attr("id").substr(2);
                            flgtemfiltro = false;
                            if ( itemselecionados.length > 0 ) {
                                flgtemfiltro = true;
                                if ( filtro == "ano" || filtro == "valor" ) {
                                   if ( itemselecionados[0] <= 0 && itemselecionados[1] <= 0 ) flgtemfiltro = false;
                                }
                            }
                            if ( flgtemfiltro ) {
                                if ( confirm("Para aplicar o filtro das opções selecionadas, você deve antes clicar em OK.\nDeseja aplicar o filtro?") ) {
                                    $("#lfok").trigger("click");
                                    return false;
                                }
                            }
                        }

                        // troca o botao de abrir e fechar do dropdown
                        $(".btn").css("backgroundPosition", "0 0"); // deixa todos como fechado
                        if ( $("#listafiltro").is(":visible") ) {
                            if ( opened != obj ) {
                                $(this).find(".btn").css("backgroundPosition", "-20px 0");
                            }
                        }

                        if ( opened != obj ) {
                            $("#lfconteudo").remove();
                            $("#listafiltro").hide().prepend("<div id=\"lfconteudo\"><img src=\"/imgs/loading.gif\"></div>");
                            var htmllista = "";
                            var htmllista1 = "";
                            var htmllista2 = "";
                            if ( conteudohtml[opts.label] == undefined ) {
                                $.getJSON(
                                    "/ajax/pesquisafiltro.php?" + $.jqURL.qs(),
                                    {item: itematual, ns: new Date().getTime() },
                                    function(data) {
                                        if (data.records > 0 ) {
                                            if ( opts.label == 'Ano' || opts.label == 'Valor' ) {
                                                htmlextra = '';
                                                $.each( data.rows, function(i,item){
                                                    if ( item['valor'] <= 0 || item['valor'] == "" ) {
                                                        valor = item['valor'];
                                                        if ( valor == "" ) {
                                                            txtextra = "A negociar";
                                                            valor = -1;
                                                        } else {
                                                            txtextra = "Parcelados";
                                                            valor = -2;
                                                        }
                                                        htmlextra += "<li><input type=\"checkbox\" name=\"" + itematual + "[]\" id=\"v" + valor + "\" value=\"" + valor + "\" />  <label for=\"v" + valor + "\">" + txtextra + " (" + item['total'] + ")</label></li>";
                                                    } else {
                                                        valor1 = valor2 = item['valor'];
                                                        txtextralabel = "";
                                                        if ( itematual == "valor" ) {
                                                            txtextralabel = " mil";
                                                            valor1 = valor1-9;
                                                        }
                                                        htmllista1 += "<li><input type=\"checkbox\" name=\"" + itematual + "[]\" id=\"v1" + valor1 + "\" value=\"" + valor1 + "\" />  <label for=\"v1" + valor1 + "\">" + valor1 + txtextralabel + " (" + item['total'] + ")</label></li>";
                                                        htmllista2 += "<li><input type=\"checkbox\" name=\"" + itematual + "[]\" id=\"v2" + item['valor'] + "\" value=\"" + valor2 + "\" />  <label for=\"v2" + item['valor'] + "\">" + valor2 + txtextralabel + " (" + item['total'] + ")</label></li>";
                                                    }
                                                });
                                                htmllista = "<ul id=\"parm1\"><li class=\"min\">M&iacute;nimo</li>" + htmllista1 + htmlextra + "</ul><ul id=\"parm2\"><li class=\"max\">M&aacute;ximo</li>" + htmllista2 + "</ul>";
                                            } else {
                                                htmllista += "<ul>";
                                                $.each( data.rows, function(i,item){
                                                    htmllista += "<li><input type=\"checkbox\" name=\"" + itematual + "[]\" id=\"v" + item['codigo'] + "\" value=\"" + item['codigo'] + "\" /> <label for=\"v" + item['codigo'] + "\">" + item['nome'] + " (" + item['total'] + ")</label></li>";
                                                });
                                                htmllista += "</ul>";
                                            }
                                        }
                                        $("#lfconteudo").html(htmllista);
                                        $("#lfconteudo").comboFiltroSelecionaAnoValor();
                                        conteudohtml[opts.label] = htmllista;
                                        $("#listafiltro").comboFiltroAcertaAltura();
                                     });

                            } else {
                                $("#lfconteudo").html(conteudohtml[opts.label]);
                                $("#lfconteudo").comboFiltroSelecionaAnoValor();
                                $("#listafiltro").comboFiltroAcertaAltura();
                            }
                        }
                        // x e y do objeto clicado
                        var position = $(this).offset();
                        $("#listafiltro").css( {left: position.left, top: position.top+19} ).width( opts.lfwidth );

                        $("#listafiltro").removeShadow().toggle( function(){
                            $(this).css( {left: position.left, top: position.top+19} );
                            if ( $(this).is(":visible") ) {
                                $(this).dropShadow( {left: 2, top: 2, opacity: .3});
                                opened = obj;
                            }
                        });
                    });
                }
            }
        });
    }


    $("#lfok").click( function() {
        var itemselecionados = $.comboFiltroRecuperaSelecao();
        var filtro = $(opened).attr("id").substr(2);
        var url = "";

        if ( filtro == "ano" || filtro == "valor" ) {
            if ( parseInt(itemselecionados[0]) > parseInt(itemselecionados[1]) ) {
                alert("O " + filtro + " mínimo deve ser menor que o " + filtro + " máximo!");
                return false;
            } else if ( parseInt(itemselecionados[0]) == 0 && parseInt(itemselecionados[1]) == 0 ) {
                    alert( "Selecione ao menos uma opção ou clique em fechar!" );
                    return false;
            } else {
                if ( itemselecionados[0] != 0 ) url += filtro + "1=" + itemselecionados[0] + "&";
                if ( itemselecionados[1] != 0 ) url += filtro + "2=" + itemselecionados[1] + "&";
            } 

        } else {
            if ( itemselecionados.length <= 0 ) {
                alert( "Selecione ao menos uma opção ou clique em fechar!" );
                return false;
            }

            url += filtro + "=" + itemselecionados.join( "|" ) + "&";

        }

        $.each($.jqURL.qs({ ret:'object' }), function(i,val) {
            if ( val != undefined && !i.indexOf(filtro) == 0 && i != "pg" ) url += i + "=" + val + "&";
        });

        url = url.substr(0, url.length - 1);
        
        window.location.href = $.jqURL.strip() + "?" + url;
    });


    $("#lffechar").click( function(){
        $(opened).trigger("click");
    });





    $("#fpcidade").comboFiltro( { label: "Cidade", lfwidth: 240 } );
    $("#fpano").comboFiltro( { label: "Ano", lfwidth: 210 } );
    $("#fpvalor").comboFiltro( { label: "Valor", lfwidth: 210 } );
    $("#fpcombustivel").comboFiltro( { label: "Combustível" } );
    $("#fpcor").comboFiltro( { label: "Cor", lfwidth: 150 } );


    $(".lnk_refazerbusca").click( function() {
        var url ="";
        var keyurldis = [ 'x','y','pg' ];
        $.each($.jqURL.qs({ ret:'object' }), function(i,val){
            url += ( $.inArray(i, keyurldis) == -1 ) ? "&" + i + "=" + val : "";
        });

        location.href = "/buscaavancada.php?" + url;
    });

    $("#c_ano, #c_valor").click( function () {
        var colspermitidas = [ 'valor','ano' ];
        var colsordem      = [ 'ano', 'valor' ];
        var ordem          = [ 'desc', 'asc' ];
        var keyurlordem    = [ 'order','orderby' ];
        var urlordenacao   = "";
        var urlorder       = "&order="
        var urlorderby     = "&orderby=";
        var arrorder       = [];
        var arrorderby     = [];
        var arrnovoorderby = [];
        var arrnovoorder   = [];

        //percorre a URL em busca dos parametros contidos no array {keyurlordem}
        $.each($.jqURL.qs({ ret:'object' }), function(i,val) {
            //os que nao estiverem no array sao colocados novamente na URL
            if ( $.inArray(i, keyurlordem) == -1 ) {
                urlordenacao += ( urlordenacao != "" ) ? "&" : "";
                urlordenacao += i + "=" + val;
            } else {
                //para os que estao no array
                //sao montados novos arrays usando o caracter (,) como marcador
                if ( i == 'order' ) {
                    arrorder = val.split("|");
                } else if ( i == 'orderby' ) {
                    arrorderby = val.split("|");
                }
            }
        });

        if ( arrorder.length > 0 ) {
            for( i=0; i<arrorder.length; i++ ) {
                //os que nao estiverem no array(colspermitidas) sao apagados do mesmo
                if ( arrorder[i].match('/[asc|desc]i/') ) {
                    arrorder[i] = 0;
                }
            }
        } else { arrorder = ordem; }

        if ( arrorderby.length > 0 ) {
            for( i=0; i<arrorderby.length; i++ ) {
                //os que nao estiverem no array(colspermitidas) sao apagados do mesmo
                if ( $.inArray(arrorderby[i], colspermitidas) == -1 ) {
                    arrorderby.splice(i, 1);
                    arrorder.splice(i, 1);
                }
            }
        } else { arrorderby = colsordem; }


        // verifica diferenca entre order e orderby
        if ( arrorder.length != arrorderby.length ) {
            var orderdefault = ( arrorder.length > 0 ) ? arrorder[0] : 'asc' ;
            var novoorder = '';

            for( i=0; i<arrorderby.length; i++ ) {
                novoorder += orderdefault + '|';
            }
            arrorder = novoorder.split("|");
        }

        // inverte order do item clicado
        i = 1;
        for(c=0; c<arrorderby.length; c++) {
            if ( $(this).text().toLowerCase() == arrorderby[c] ) {
                arrnovoorderby[0] = arrorderby[c];
                arrnovoorder[0] = ( arrorder[c] == 'asc' ) ? 'desc' : 'asc';
            } else {
                arrnovoorder[i] = arrorder[c];
                arrnovoorderby[i] = arrorderby[c];
                i++;
            }
        }

        // junta os elementos de order e orderby
        for(c=0; c<arrnovoorderby.length; c++) {
            urlorder    += ( (arrnovoorder.length - 1) > c ) ? arrnovoorder[c] + "|" : arrnovoorder[c];
            urlorderby  += ( (arrnovoorderby.length - 1) > c ) ? arrnovoorderby[c] + "|" : arrnovoorderby[c];
        }

        location.href = "?" + urlordenacao + urlorder + urlorderby;

    });


    $(".comp input").show();
    $(".comp input").click( function (){
        var acao = ( $(this).is(":checked") ) ? "marcar" : "desmarcar";
        codigoatual = $(this).val();
        $.getJSON(
            "/ajax/comparacao.php",{codigo:codigoatual,acao:acao},
            function(data) {
                if ( data.erro != '' ) {
                    if ( data.confirm == 'C' ) {
                        if ( confirm(data.erro) ) {
                            location.href = "/comparacao.php?urlback=" + escape($.jqURL.qs());
                        }
                    } else {
                        alert(data.erro);
                    }
                }
                // desmarca todos
                $("input:checked[name^='veiculo']").each( function() { this.checked = false; });
                // marca apenas os q estao em sessao
                $.each( data.rows, function(i,n) { $("input[value=" + n + "]").attr("checked",true); });
            }
        );
    });


    // --telefone
    $("#bl_lnkFone").click( function() {
        obj = this;
        if ( _cliente > 0 ) {
            html = '<p class="t' + _phcefanx.length + '">';
            html+= _phcefanx.join('<br />')+'</p>';
            $(obj).parent().empty().html( html );
            $.ajax({
                type: "GET",
                url: "/ajax/vertelefone.php",
                data: { clicod:_cliente }
            });
        }
    });


});


function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function PosicionaLegenda(obj, tppos) {
	div = 'legendaopcionais';
	divseta = 'legendaopcionaisseta';
	var coors = findPos(obj);
	//if (div == 'testP') coors[1] -= 50;
	var x = document.getElementById(div);
	var xseta = document.getElementById(divseta);
	posx = coors[0]+20;
	possx = coors[0]+30;
	if ( tppos == 'down' ) {
		posy = coors[1]+30;
		xseta.innerHTML = '<img src="/imgs/legendaopcional_setaup.gif" />';
		possy = coors[1]+38;
	} else if ( tppos == 'up' ) {
		posy = (coors[1]-19)-x.offsetHeight;
		xseta.innerHTML = '<img src="/imgs/legendaopcional_setadown.gif" />';
		var coorslegenda = findPos(div);
		possy = (coors[1]);//coorslegenda[1]+x.offsetHeight;
	} else {
		return false;
	}
	x.style.top = posy + 'px';
	x.style.left = posx + 'px';
	xseta.style.top = possy + 'px';
	xseta.style.left = possx + 'px';
	// troca a seta de apontamento para o icone de legenda

}


function ShowHideLegenda(acao)
{
	var x = document.getElementById('legendaopcionais');
	var xseta = document.getElementById('legendaopcionaisseta');
	x.style.visibility = (acao=='show') ? 'visible' : 'hidden' ;
	xseta.style.visibility = (acao=='show') ? 'visible' : 'hidden' ;
}

