/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var searchBox = new Object();
$(document).ready(function() {
    searchBox = function()
    {
        return {
            destinations     : new Array(),
            types            : new Object(),
            brochure         : new Object(),
            departures       : new Object(),
            pricesIntervales : new Object(),
            transport        : new Object(),
            trips            : new Array(),
            menuList         : ['departures', 'types', 'destinations', 'pricesIntervales'],
            titleMenu        : __('Choissisez'),
            maxItems         : 20, // Nombre d'element à afficher dans un menu au de là on affiche un autocomplite
            minTrips         : 30, // Nombre des vogayes à afficher ou on affiche les brochures
            items_per_page   : 30,
            nb_result        : 0,
            nbPromo          : 0,
            nbOffice         : 0,
            searchExp        : '',
            selectedTrans    : new Array(),
            reset            : false,

            init : function()
            {
                $.post(SEARCH_REF, {}, function(data)
                {
                    $("#search-box").html(data);
                });
            },
            _init : function()
            {
                $("#lastSelected").val('');
                var pointer = this;
                // Destination
                $.getJSON(SEARCH_ACT,
                    function(data){
                        pointer.destinations.data = data.destinations;
                        pointer.types.data = data.types;
                        pointer.departures.data = data.departures;
                        pointer.pricesIntervales.data = data.pricesIntervales;
                        pointer.brochure.data = data.brochure;
                        pointer.transport.data = data.transport;
                        pointer.getAllTrips('pricesIntervales');
                    //                        pointer.render();
                    });
                 
                 
            },
            getAllTrips: function(select)
            {
                var pointer = this;
                pointer.trips = new Array();
                var obj = new Object();
                eval("obj = this."+select);
                $.each(obj.data, function(i, item){
                    pointer.trips = pointer.trips.union(item.trips);
                });
            },
            getLastSelectedTrips : function()
            {
                var pointer = this;
                var tab = this.trips;
                var lastSelected = $("#lastSelected").val();
                if ($("#lastSelected").val() != '')
                {
                    tab = new Array();
                    var obj = new Object;
                    eval("obj = this."+$("#lastSelected").val());
                    if(obj.data)
                        tab = obj.data[$("#"+lastSelected+"_customselect").val()].trips;

                }
                return tab;
            },
            getSelectedTrips : function()
            {
                var pointer = this;
                var tab = new Array();
                pointer.searchExp = '';
                $.each(this.menuList, function(i, select){
                    var obj = new Object;
                    eval("obj = pointer."+select);
                    if ($("#"+select+"_customselect").val() != '')
                    {
                        pointer.searchExp += select+'='+$("#"+select+"_customselect").val()+"&";
                    }
                });

                // Transportations
                var tabTrans = new Array();
                if (this.selectedTrans.length != 0)
                {
                    var searchTransExp = ''; //tabTrans.join("-");
                    $.each(this.selectedTrans, function(i, id){
                        searchTransExp += id+'-';
                    
                    });
                    pointer.searchExp += "trans="+searchTransExp;
                }
                $.ajax({
                    type: "POST",
                    async: false,
                    url:  SEARCH_ACT+'?trips=1',
                    data: pointer.searchExp,
                    success: function(data){
                        //data = eval("("+data+")");
                        $.each(data, function(i,v){
                            tab.push(v);
                        });
                    }
                });
                
                
                return tab;
            },
            renderSelect : function(select)
            {
                var pointer = this;
                var option = $("#"+select+"_customselect").val();
                var doAnimate = false;
                if (option)
                    doAnimate = true;
                if (select == 'destinations')
                {
                    var params = {
                        destinations : 1,
                        render : 1,
                        lastSelected : $("#lastSelected").val(),
                        val : $("#"+$("#lastSelected").val()+"_customselect").val()
                    }
                    renderDestinationList(params);
                    return false;
                }
                var params = {
                    render : 1,
                    lastSelected : $("#lastSelected").val(),
                    val : $("#"+$("#lastSelected").val()+"_customselect").val()
                };
                
                //$.post(SEARCH_ACT+'?'+select+'=1', params,
                $.ajax({
                    url : SEARCH_ACT+'?'+select+'=1', 
                    data : params,
                    type : 'POST',
                    dataType : 'html',
                    success : function(data) {
                        
                        html = '<select class="select" id="'+select+'" title="'+pointer.titleMenu+'" name="'+select+'">'+data+'</select>';
                        $("#"+select+"_td").html(html);
                        $("#"+select).SelectCustomizer({
                            callback : pointer.onSearch,
                            selectedOption   : option
                        });
                    } // success
                }); // ajax
                    
                
                return;
            
            },
            doAnimate : function(elem)
            {
                $("#"+elem).show( 'pulsate');
            },
            renderTransportHtml : function()
            {
                return '';
                
                var trips = this.getSelectedTrips();
                if ($('#picto').length !=0 ) $('#picto').remove();
                var $transport_html = $('<div id="picto">');
                var $ul = $('<ul>');
                $transport_html.append($ul);
                if ($('#picto').length !=0 )
                    $transport_html.after('<div class="clear"></div>');
                $.each(this.transport.data, function(i, item){
                    if (item.trips.intersect(trips).length > 0)
                        $ul.append('<li id="'+item.id+'" class="'+item.className+'" onclick="searchBox.runSearchWithTransport(this);return false;"><a href="javascript:void(0)">'+item.trips.intersect(trips).length+'</a></li>');
                });
                return $transport_html;
                return '';
            },
            runSearchWithTransport : function (elem)
            {
                var id = $(elem).attr('id');
                $(elem).toggleClass('over');
                if (!in_array(id, this.selectedTrans))
                    this.selectedTrans.push(id);
                else
                    this.selectedTrans = $.grep(this.selectedTrans, function(n, i){
                        return (n != id);
                    });
                
                $("#lastSelected").val('transport');
                this.runSearch('transport');
            },
            onSearch : function()
            {
                var pointer = searchBox;
                pointer.render();
            },
            render : function()
            {
                var pointer = this;
                var lastSelected = $("#lastSelected").val();
                var j = 0;
                $.each(pointer.menuList, function(i, select){
                    if (lastSelected != select)
                    {
                        pointer.renderSelect(select);
                    }
                });
                if ($("#picto").length != 0){
                    this.selectedTrans = new Array();
                    $("#page_title").after(this.renderTabNav());
                    pointer.reset = false;
                }
            },
            renderTabNav : function()
            {
                var $tabNav = null;
                if ($('#nav').length == 0)
                {
                    $tabNav = $('<div id="nav">');
                    var $ul = $('<ul>');
                    $ul.append('<li id="tab_trips_result" class="over result-tabs"><a href="#"><span id="nb_trips">Voyages</span></a></li>');
                    $ul.append('<li id="tab_brochures_result" class="result-tabs"><a href="#"><span id="nb_brochures">Brochures</span></a></li>');
                    $ul.append('<li style="display:none" id="tab_promos_result" class="result-tabs"><a href="#"><span id="nb_promos">Promotions</span></a></li>');
                    $ul.append('<li style="display:none" id="tab_office_result" class="result-tabs"><a href="#"><span id="nb_office">InfoPays</span></a></li>');
                    $tabNav.append($ul);
                }else
                    $tabNav = $('#tab_nav');
                $tabNav.append(this.renderTransportHtml());
                return $tabNav;
            },
            switchTabs : function(tab)
            {
                $(".result-tabs").removeClass('over');
                $("#tab_"+tab+"_result").addClass('over');
            },
            renderNbResultsTabs : function(nbPromo, nbOffice, nbTrips, nbBrochures)
            {
                var pointer = this;
                $("#nb_promos").html(__('Promotions')+' ('+nbPromo+')');
                $("#nb_office").html(__('InfoPays')+' ('+nbOffice+')');
                $("#nb_trips").html(__('Voyages')+' ('+nbTrips+')');
                $("#nb_brochures").text(__('Brochures')+' ('+nbBrochures+')');
                
                
                if ($("#resultat").length == 0)
                {
                    $("#left").prepend('<h3 id="resultat"></h3>');
                }
                $('#resultat').html(__('Nous avons trouv&eacute; pour vous dans nos brochures...'));
            },
            runSearch : function(from)
            {
               // console.log('runSearch');
                
                if (!from) from = '';
                var pointer = this;
                var trips = this.getSelectedTrips();

                if (trips.length == 0)
                    return false;
                if (from != 'transport'){
                    this.selectedTrans = new Array();
                }
                
                
                if ($("#resultat").length == 0)
                    $("#left").empty();
                
                if ($("#listing").length == 0)
                {
                    $("#left").prepend('<h3 id="resultat"></h3>');
                    $("#left").append(this.renderTabNav());
                    $("#left").append($('<div id="listing">'));
                }else
                    $("#listing").empty();
                
                
                $('#resultat').html(__('Calcul de résultat <img src="/images/loadinggigatour.gif"/>'));
                
                $.ajax({
                    type: "POST",
                    async: false,
                    url:  NB_PROMO,
                    data: pointer.searchExp,
                    success: function(data){
                        pointer.nbPromo = data;
                    }
                });

                // office de tourism
                pointer.nbOffice = 0;
                if (pointer.searchExp.indexOf('destinations') >= 0){
                    $.ajax({
                        type: "POST",
                        async: false,
                        url:  NB_OFFICE,
                        data: pointer.searchExp,
                        success: function(data){
                            pointer.nbOffice = data;
                        }
                    });
                }
                if (pointer.nbOffice == 0)
                {
                    $("#tab_office_result").hide();
                    if ($('#display').val() == 'office')
                        $('#display').val('trip');
                }else
                    $("#tab_office_result").show();
                // promotion
                if (pointer.nbPromo == 0)
                {
                    $("#tab_promos_result").hide();
                    if ($('#display').val() == 'promos')
                        $('#display').val('trip');
                }else
                    $("#tab_promos_result").show();
                
                if ($('#display').val() == 'office')
                {
                    pointer.switchTabs('office');
                    $.ajax({
                        type: "POST",
                        async: false,
                        url:  OFFICE,
                        data: pointer.searchExp,
                        success: function(data){
                            if ($("#list_brochures").length == 0)
                                $("#listing").html( '<div id="list_brochures"></div>' );
                            $('#listing').find('.thumb').each(function(i){
                                $(this).remove();
                            });
                            var nb_brochures = 0;
                            $.each(pointer.brochure.data, function(i, item){
                                if (item.trips.intersect(trips).length > 0)
                                {
                                    nb_brochures++;
                                }
                            });
                            $("#list_brochures").append(data);
                            pointer.nb_result = nb_brochures;
                            $('#nb_result').val(pointer.nb_result);
                            pointer.renderNbResultsTabs(pointer.nbPromo, pointer.nbOffice, trips.length, nb_brochures);
                            pointer.renderPagination();
                        }
                    });
                }else if ($('#display').val() == 'promos')
                {
                    pointer.switchTabs('promos');
                    $.ajax({
                        type: "POST",
                        async: false,
                        url:  PROMO,
                        data: pointer.searchExp,
                        success: function(data){
                            if ($("#list_voyages").length == 0)
                                $("#listing").html( '<div id="list_voyages"></div>' );
                            $('#listing').find('.thumb').each(function(i){
                                $(this).remove();
                            });
                            var nb_brochures = 0;
                            $.each(pointer.brochure.data, function(i, item){
                                if (item.trips.intersect(trips).length > 0)
                                {
                                    nb_brochures++;
                                }
                            });
                            $("#list_voyages").append(data);
                            pointer.nb_result = nb_brochures;
                            $('#nb_result').val(pointer.nb_result);
                            pointer.renderNbResultsTabs(pointer.nbPromo, pointer.nbOffice, trips.length, nb_brochures);
                            pointer.renderPagination();
                        }
                    });
                }
                
                else if ($('#display').val() == 'brochure') // affichage des brochures
                {
                    pointer.switchTabs('brochures');
                    var nb_brochures = 0;
                    var brs = new Array();
                    $.each(this.brochure.data, function(i, item){
                        if (item.trips.intersect(trips).length > 0)
                        {
                            nb_brochures++;
                            brs.push(item.id);
                        }else
                            $("#result_"+item.id).remove();
                    });
                    var arg = brs.join('&brochures[]=');
                    $.ajax({
                        type: "POST",
                        url:  BROCHURE_PHOTO,
                        data: "brochures[]="+arg,
                        success: function(data){
                            if ($("#list_brochures").length == 0)
                                $("#listing").html( '<div id="list_brochures"></div>' );
                            $('#listing').find('.thumb').each(function(i){
                                $(this).remove();
                            });
                            $("#list_brochures").append(data);
                            pointer.nb_result = nb_brochures;
                            $('#nb_result').val(pointer.nb_result);
                            pointer.renderNbResultsTabs(pointer.nbPromo, pointer.nbOffice, trips.length, nb_brochures);
                          
                            pointer.renderPagination();
                        }
                    });

                    
                }
                else
                {
                    pointer.switchTabs('trips');
                    var arg = trips.join('&trips[]=');
                    $.ajax({
                        type: "POST",
                        url:  LIST_TRIPS_ACT,
                        data: "trips[]="+arg,
                        success: function(data){
                            if ($("#list_voyages").length == 0)
                                $("#listing").html( '<div id="list_voyages"></div>' );
                            $('#listing').find('.thumb').each(function(i){
                                $(this).remove();
                            });
                            $("#list_voyages").append(data);
                            var nb_brochures = 0;
                            $.each(pointer.brochure.data, function(i, item){
                                if (item.trips.intersect(trips).length > 0)
                                {
                                    nb_brochures++;
                                }
                            });
                            pointer.nb_result = trips.length;
                            $('#nb_result').val(pointer.nb_result);
                            pointer.renderNbResultsTabs(pointer.nbPromo, pointer.nbOffice, trips.length, nb_brochures);
                            pointer.renderPagination();
                        }
                    });
                    
                }
                $('#contact').remove();
                $('#reservation').remove();
                $('#select_box').remove();
                $('.formError').remove();
                    
                $("#move_div").slideUp(2000, pointer.renderResult );


            },
            renderPagination : function()
            {
                var pointer = this;
                if (pointer.nb_result <= pointer.items_per_page)
                {
                    $(".nav_page").remove();
                    $('#listing').find('.thumb').each(function(i){

                        $(this).show();
                    })
                    return false;
                }
                if ($(".nav_page").length == 0)
                {
                    $("#listing").append('<div class="nav_page"><p id="pagination"></p></div>');
                }
                this.pageselectCallback(0);
                $("#pagination").pagination(pointer.nb_result, {
                    items_per_page: pointer.items_per_page,
                    prev_text : 'Precedent',
                    next_text : 'Suivante',
                    num_display_entries : 5,
                    callback : pointer.pageselectCallback
                });
            },
            pageselectCallback : function(page_index)
            {
                var pointer = this;
                var nb_result = $('#nb_result').val();
                var max_elem = Math.min((page_index+1) * this.items_per_page, nb_result);
                var toShow = new Array()
                for(var i=page_index*this.items_per_page;i<max_elem;i++)
                {
                    toShow.push(i);
                }
                $('#listing').find('.thumb').each(function(i){
                    if (in_array(i, toShow))

                        $(this).show();
                    else
                        $(this).hide();
                })
            },
            renderResult : function()
            {
                $('#wrap_inside').slideDown(4000);
            }

        };

    }();

});




function renderDestinationList(params)
{
    var dataToSearch = new Array();
    var option = $("#destinations_customselect").val();
    $.ajax({
        url: SEARCH_ACT,
        cache: true,
        async: true,
        data: params,
        success: function(data)
        {
            var options;
            $.each(data, function(i, item){
                var obj = new Object();
                obj.id = item.id;
                obj.name = item.name;
                options += '<option value="'+item.id+'">'+item.name+'</option>;'+"\n";
                dataToSearch.push(obj);
            });
            if (dataToSearch.length <= searchBox.maxItems){
                
                var html = '<select class="select" id="destinations" title="'+searchBox.titleMenu+'" name="destinations">'+options+'</select>';
                $("#destinations_td").html(html);
                $("#destinations").SelectCustomizer({
                    callback : searchBox.onSearch,
                    selectedOption   : option
                });
            }else{
                var value = '';
                var id = '';
                if ($('#destinations_customselect').length > 0)
                    id = $('#destinations_customselect').val();
                if ($('#destinations_input').length > 0)
                    value = $('#destinations_input').val();
                html = '<input type="hidden" id="destinations_customselect" name="destinations" value="'+id+'"/>';
                $.each(dataToSearch, function(i, obj){
                    if (obj.id == option)
                        value = obj.name;
                });
                html += '<input class="champ" type="text" id="destinations_input" name="destinations" value="'+value+'" />';
                $("#destinations_td").html(html);
                var opts = {
                    data:dataToSearch,
                    varname:"input",
                    timeout:false,
                    json:true,
                    callback: function (obj) {
                        $("#destinations_customselect").val(obj.id);
                        $("#lastSelected").val('destinations');
                        searchBox.onSearch();
                    }
                };
                new AutoSuggest('destinations_input', opts);
            }
        }
    });
}
