(function ($) {

    var Config = {
        ServerURL: "/Controller/Ricerca.ashx",
        ClientURL: "/Plugins/modRicerca/Ricerca.htm",
        StyleURL: '/Plugins/modRicerca/Ricerca.css',
        ServerUtilityURL: "/Controller/Utility.ashx",
        Container: '',
        RicercaContainer: '#ricerca_container',
        FormRicerca: {
            Data: "",
            Range: "",
            DataDa: "",
            DataA: "",
            ListaIdDestinazioni: "",
            ListaIdAeroporti: "",
            Durata: "",
            TipoVacanza: "",
            TemaVacanza: "",
            Viaggiatori: "",
            TourOperator: "",
            Prezzo: ""

        },
        AgenziaInSessione: false,
        Agenzia: {},
        Plugins_Count: 3,
        Plugins_LoadedCount: 0,
        Plugins_LoadedError: false,
        DS_DestinazioniLeft: null,
        DS_DestinazioniRight: null,
        DS_TipoVacanza: null,
        DS_Durata: null,
        DS_Operatori: null,
        Open_OperatoriList: false,
        Open_DestinazioniList: false,
        SelectedTab: 0
    };



    $.fn.Ricerca = function (options) {
        //Extending the configuration
        if (options) {
            Config = $.extend({}, Config, options);
        }

        Config.Container = $(this);

        Init();

    };

    function CaricaAgenzia() {
        if ($.isEmptyObject(Config.Agenzia)) {
            var parameters = {};
            parameters.action = "SelAgenzia";
            $.ajax({
                async: false,
                cache: false,
                url: Config.ServerUtilityURL,
                data: parameters,
                success: function (returnData) {
                    if (returnData != "-1") {
                        Config.Agenzia = $.parseJSON(returnData);
                    }
                }
            });
        }
    }



    function Init() {



        //I load the html code for this plugin   
        Config.Container.load(Config.ClientURL, function () {
           

            Config.Plugins_LoadedCount = 0;
            Config.Plugins_LoadedError = false;

            //Initialize DatePicker
            $(Config.RicercaContainer + ' .ricerca_data_partenza input').datepicker({
                createButton: true,
                buttonImage: '/View/Images/Ricerca/datepicker.png',
                minDate: '1d',
                onSelect: function (date) {
                    Config.FormRicerca.Data = date;
                    $('.ricerca_semplice_data_partenzaformError').remove();
                    $('.ricerca_avanzata_data_partenzaformError').remove();
                }
            });
            $(Config.RicercaContainer + '  a.datepicker').click(function () {
                $(this).parent().find('.hasDatepicker').focus();
            });


            Ricerca_Init();




            //Initialize the destnations list for ricerca semplice and ricerca avanzata
            RicercaDestinazioni_Init();

            //Round corners
            $.fn.Ricerca.RoundCorners();

        });
    }


    //Initialize Ricerca Semplice controls
    function Ricerca_Init() {


        CaricaAgenzia();


        if (Config.FormRicerca.Data != '') {
            $('div#ricerca > div#ricerca_container > div#container_ricerca .ricerca_data_partenza > div:first > input').val(Config.FormRicerca.Data);
        }

        if (Config.FormRicerca.Range != '') {
            $('div#ricerca > div#ricerca_container > div#container_ricerca .ricerca_range > div:first > select').val(Config.FormRicerca.Range);
        }
        else {
            $('div#ricerca > div#ricerca_container > div#container_ricerca .ricerca_range > div:first > select option:first').attr('selected', 'selected');
        }

        $('div#ricerca > div#ricerca_container > div#container_ricerca .ricerca_range > div:first > select').change(function () {
            Config.FormRicerca.Range = $(this).val();
        });

        if (Config.FormRicerca.Durata != '') {

            $('div#ricerca > div#ricerca_container > div#container_ricerca_avanzata .ricerca_durata > div:first > select').val(Config.FormRicerca.Durata);
        }
        else {
            $('div#ricerca > div#ricerca_container > div#container_ricerca_avanzata .ricerca_durata > div:first > select').attr('selected', 'selected');
        }

        $(Config.RicercaContainer + ' .ricerca_destinazioni > div > input').click(function () {
            RicercaDestinazioni_Show($(Config.RicercaContainer + ' .ricerca_destinazioni > div > input'));
        });
        $(Config.RicercaContainer + ' .ricerca_destinazioni > a').click(function () {
            RicercaDestinazioni_Show($(Config.RicercaContainer + ' .ricerca_destinazioni > div > input'));
        });

        var cancelTraverse = false;
        if (Config.FormRicerca.TourOperator != '') {
            if (Config.FormRicerca.TourOperator.split(',').length > 1) {
                $('div#ricerca > div#ricerca_container > div#container_ricerca .ricerca_operatori > div:first > input').css('font-style', 'italic').val('Selezione Multipla');
            }
            else {
                jQuery.each(Config.DS_Operatori, function (index, obj) {
                    if (cancelTraverse) return false;
                    jQuery.each(obj.Lista, function (index2, obj2) {
                        if (obj2.Value == Config.FormRicerca.TourOperator) {
                            $('div#ricerca > div#ricerca_container > div#container_ricerca .ricerca_operatori > div:first > input').css('font-style', 'normal').val(obj2.Text);
                            cancelTraverse = true;
                            return false;
                        }
                    });
                });
            }
        }

        if (Config.DS_Operatori == null) {
            $.ajax({
                async: true,
                cache: false,
                url: Config.ServerURL,
                data: { "action": "SelOperatori", "idcanale": Config.Agenzia.Canale.Id },
                success: function (data) {
                    try {
                        //Test for errors
                        if (data == '-1') throw '-1';
                        if (data == '') {
                            Config.DS_Operatori = '';
                            throw '';
                        }

                        var dataArray = jQuery.parseJSON(data);
                        Config.DS_Operatori = dataArray;

                        if (Config.FormRicerca.TourOperator != '' && Config.FormRicerca.TourOperator.split(',').length == 1) {
                            var cancelTraverse = false;
                            jQuery.each(Config.DS_Operatori, function (index, obj) {
                                if (cancelTraverse) return false;
                                jQuery.each(obj.Lista, function (index2, obj2) {
                                    if (obj2.Value == Config.FormRicerca.TourOperator) {
                                        $('div#ricerca > div#ricerca_container > div#container_ricerca .ricerca_operatori > div:first > input').css('font-style', 'normal').val(obj2.Text);
                                        cancelTraverse = true;
                                        return false;
                                    }
                                });
                            });
                        }
                        if (Config.Open_OperatoriList) {
                            Operatori_Show($(Config.RicercaContainer + ' .ricerca_operatori > div > input'));
                            Config.Open_OperatoriList = false;
                        }
                    }
                    catch (err) {
                        Config.Plugins_LoadedError = err != '';
                        if (err != '') {
                            ShowMessage("Attenzione", "Si &egrave; verificato un errore di comunicazione con il server, vi preghiamo di riprovare in seguito, se il problema persiste contattate il supporto tmind a questo indirizzo: <a href=\"mailto:support@tmind.com\">support@tmind.com</a>");
                        }
                    }
                },
                error: function () {
                    Config.Plugins_LoadedError = true;
                },
                complete: function (jqXHR, textStatus) {
                    HideSmallLoader();
                    //Increment number of loaded sub-plugins
                    //If both types of destinations lists (on the left/on the right) are completed, launch 'ModuleLoaded' event
                }
            });
        }
        else {
            //If both types of destinations lists (on the left/on the right) are completed, launch 'ModuleLoaded' event
        }

        $(Config.RicercaContainer + ' .ricerca_operatori > div > input').click(function () {
            Operatori_Show(this);
        });
        $(Config.RicercaContainer + ' .ricerca_operatori > a').click(function () {
            Operatori_Show($(Config.RicercaContainer + ' .ricerca_operatori > div > input'));
        });

        //TIPO VACANZA
        //Get the container for the tipo vacanza list 
        //Set the default value for the first element   
        $(Config.RicercaContainer + ' .ricerca_tipo_vacanza select')
            .append($('<option/>', { "value": "" })
            .html('Scegli la tipologia'))
            .change(function () {
                Config.FormRicerca.TipoVacanza = $(this).val();
            });
        ;
        if (Config.DS_TipoVacanza == null) {
            //Lista tipo vacanza  

            var newTipoVacanza = '';
            $.ajax({
                async: true,
                cache: false,
                url: Config.ServerURL,
                data: { "action": "SelTipologie" },
                success: function (data) {
                    try {
                        //Test for errors
                        if (data == '-1') throw '-1';
                        if (data == '') throw '';

                        var dataArray = jQuery.parseJSON(data);
                        Config.DS_TipoVacanza = dataArray;
                        //Add each tipo vacanza to the list
                        jQuery.each(dataArray, function (index, obj) {
                            $(Config.RicercaContainer + ' .ricerca_tipo_vacanza select').append(
                                                                    $('<option/>', { "value": obj.Value, "selected": (Config.FormRicerca.TipoVacanza != '' && obj.Value == Config.FormRicerca.TipoVacanza) ? "selected" : "" }).html(obj.Text)
                              );
                        });
                    }
                    catch (err) {
                        Config.Plugins_LoadedError = err != '';
                    }
                },
                error: function () {
                    Config.Plugins_LoadedError = true;
                },
                complete: function (jqXHR, textStatus) {
                    //Increment number of loaded sub-plugins
                    ++Config.Plugins_LoadedCount;
                    //If both types of destinations lists (on the left/on the right) are completed, launch 'ModuleLoaded' event
                    if (Config.Plugins_LoadedCount == Config.Plugins_Count) {
                        Config.Container.trigger({ type: "ModuleLoaded", isError: Config.Plugins_LoadedError, PluginName: 'Ricerca-Tipo Vacanza' });
                    }
                }
            });
        }
        else {
            jQuery.each(Config.DS_TipoVacanza, function (index, obj) {
                $(Config.RicercaContainer + ' .ricerca_tipo_vacanza select').append(
                                                                    $('<option/>', { "value": obj.Value, "selected": (Config.FormRicerca.TipoVacanza != '' && obj.Value == Config.FormRicerca.TipoVacanza) ? "selected" : "" }).html(obj.Text)
                              );
            });

            //Increment number of loaded sub-plugins
            ++Config.Plugins_LoadedCount;
            //If both types of destinations lists (on the left/on the right) are completed, launch 'ModuleLoaded' event
            if (Config.Plugins_LoadedCount == Config.Plugins_Count) {
                Config.Container.trigger({ type: "ModuleLoaded", isError: Config.Plugins_LoadedError, PluginName: 'Ricerca-Tipo Vacanza' });
            }
        }

        //TEMA VACANZA
        //Get the container for the tema vacanza list 
        //Set the default value for the first element   
        $(Config.RicercaContainer + ' .ricerca_tema_vacanza select')
            .append($('<option/>', { "value": "" })
            .html('Scegli il tema vacanza'))
            .change(function () {
                Config.FormRicerca.TemaVacanza = $(this).val();
            });
        ;
        if (Config.DS_TemaVacanza == null) {
            //Lista tema vacanza  

            var newTemaVacanza = '';
            $.ajax({
                async: true,
                cache: false,
                url: Config.ServerURL,
                data: { "action": "SelSegmenti" },
                success: function (data) {
                    try {
                        //Test for errors
                        if (data == '-1') throw '-1';
                        if (data == '') throw '';

                        var dataArray = jQuery.parseJSON(data);
                        Config.DS_TemaVacanza = dataArray;
                        //Add each tema vacanza to the list
                        jQuery.each(dataArray, function (index, obj) {
                            $(Config.RicercaContainer + ' .ricerca_tema_vacanza select').append(
                                                                    $('<option/>', { "value": obj.Value, "selected": (Config.FormRicerca.TemaVacanza != '' && obj.Value == Config.FormRicerca.TemaVacanza) ? "selected" : "" }).html(obj.Text)
                              );
                        });
                    }
                    catch (err) {
                        Config.Plugins_LoadedError = err != '';
                    }
                },
                error: function () {
                    Config.Plugins_LoadedError = true;
                },
                complete: function (jqXHR, textStatus) {
                    //Increment number of loaded sub-plugins
                    ++Config.Plugins_LoadedCount;
                    //If both types of destinations lists (on the left/on the right) are completed, launch 'ModuleLoaded' event
                    if (Config.Plugins_LoadedCount == Config.Plugins_Count) {
                        Config.Container.trigger({ type: "ModuleLoaded", isError: Config.Plugins_LoadedError, PluginName: 'Ricerca-Tema Vacanza' });
                    }
                }
            });
        }
        else {
            jQuery.each(Config.DS_TemaVacanza, function (index, obj) {
                $(Config.RicercaContainer + ' .ricerca_tema_vacanza select').append(
                                                                    $('<option/>', { "value": obj.Value, "selected": (Config.FormRicerca.TemaVacanza != '' && obj.Value == Config.FormRicerca.TemaVacanza) ? "selected" : "" }).html(obj.Text)
                              );
            });

            //Increment number of loaded sub-plugins
            ++Config.Plugins_LoadedCount;
            //If both types of destinations lists (on the left/on the right) are completed, launch 'ModuleLoaded' event
            if (Config.Plugins_LoadedCount == Config.Plugins_Count) {
                Config.Container.trigger({ type: "ModuleLoaded", isError: Config.Plugins_LoadedError, PluginName: 'Ricerca-Tema Vacanza' });
            }
        }


        //DURATA
        //Get the container for the durata list 
        //Set the default value for the first element   
        $(Config.RicercaContainer + ' .ricerca_durata select')
            .append($('<option/>', { "value": "" })
            .html(''))
            .change(function () {
                Config.FormRicerca.Durata = $(this).val();
            });
        ;
        if (Config.DS_Durata == null) {
            //Lista durata  
            var newDurata = '';
            $.ajax({
                async: true,
                cache: false,
                url: Config.ServerURL,
                data: { "action": "SelDurataNotti" },
                success: function (data) {
                    try {
                        //Test for errors
                        if (data == '-1') throw '-1';
                        if (data == '') throw '';

                        var dataArray = jQuery.parseJSON(data);
                        Config.DS_Durata = dataArray;
                        //Add each durata to the list
                        jQuery.each(dataArray, function (index, obj) {
                            $(Config.RicercaContainer + ' .ricerca_durata select').append(
                                                                    $('<option/>', { "value": obj.Value, "selected": (Config.FormRicerca.Durata != '' && obj.Value == Config.FormRicerca.Durata) ? "selected" : "" }).html(obj.Text)
                              );
                        });
                    }
                    catch (err) {
                        Config.Plugins_LoadedError = err != '';
                    }
                },
                error: function () {
                    Config.Plugins_LoadedError = true;
                },
                complete: function (jqXHR, textStatus) {
                    //Increment number of loaded sub-plugins
                    ++Config.Plugins_LoadedCount;
                    //If both types of destinations lists (on the left/on the right) are completed, launch 'ModuleLoaded' event
                    if (Config.Plugins_LoadedCount == Config.Plugins_Count) {
                        Config.Container.trigger({ type: "ModuleLoaded", isError: Config.Plugins_LoadedError, PluginName: 'Ricerca-Durata' });
                    }
                }
            });
        }
        else {
            jQuery.each(Config.DS_Durata, function (index, obj) {
                $(Config.RicercaContainer + ' .ricerca_durata select').append(
                                                                    $('<option/>', { "value": obj.Value, "selected": (Config.FormRicerca.Durata != '' && obj.Value == Config.FormRicerca.Durata) ? "selected" : "" }).html(obj.Text)
                              );
            });

            //Increment number of loaded sub-plugins
            ++Config.Plugins_LoadedCount;
            //If both types of destinations lists (on the left/on the right) are completed, launch 'ModuleLoaded' event
            if (Config.Plugins_LoadedCount == Config.Plugins_Count) {
                Config.Container.trigger({ type: "ModuleLoaded", isError: Config.Plugins_LoadedError, PluginName: 'Ricerca-Durata' });
            }
        }

        //Declare the click event on the search button. 
        var searchButton = Config.RicercaContainer + ' .ricerca_right a.ricerca_button';
        if (jQuery(searchButton).data('events') == undefined || !jQuery(searchButton).data('events').click == undefined)
            $(searchButton).click(function () { Search(Config.RicercaContainer); });
    }

    function RicercaDestinazioni_Init() {

        if (Config.FormRicerca.ListaIdDestinazioni != '') {
            if (Config.FormRicerca.ListaIdDestinazioni.split(',').length > 1) {

                $(Config.RicercaContainer + ' .ricerca_destinazioni > div > input').css('font-style', 'italic').val('Selezione Multipla');
            }
            else {
                if (Config.DS_DestinazioniLeft != null && Config.DS_DestinazioniRight != null) {
                    jQuery.each(Config.DS_DestinazioniRight, function (index, obj) {
                        jQuery.each(Config.DS_DestinazioniRight[index].Lista, function (index2, obj2) {
                            if (Config.FormRicerca.ListaIdDestinazioni == obj2.Value) {
                                $(Config.RicercaContainer + ' .ricerca_destinazioni > div > input').css('font-style', 'normal').val(obj2.Text);
                            }
                        });
                    });
                }
            }
        }

        var isError = false;
        if (Config.DS_DestinazioniLeft == null) {
            $.ajax({
                async: true,
                cache: false,
                url: Config.ServerURL,
                data: { "action": "SelDestinazioniGeografiche" },
                success: function (data) {
                    try {
                        //Test for errors
                        if (data == '-1') throw '-1';
                        if (data == '') {
                            Config.DS_DestinazioniLeft = '';
                            throw '';
                        }

                        var dataArray = jQuery.parseJSON(data);
                        Config.DS_DestinazioniLeft = dataArray;

                        //Initialize destinations on the left for each type of ricerca
                        if (Config.DS_DestinazioniRight != null) {
                            if (Config.Open_DestinazioniList == true) {
                                RicercaDestinazioni_Show($(Config.RicercaContainer + ' .ricerca_destinazioni > div > input'));
                                Config.Open_DestinazioniList = false;
                            }
                        }
                    }
                    catch (err) {
                        Config.Plugins_LoadedError = err != '';
                        if (err != '') {
                            ShowMessage("Attenzione", "Si &egrave; verificato un errore di comunicazione con il server, vi preghiamo di riprovare in seguito, se il problema persiste contattate il supporto tmind a questo indirizzo: <a href=\"mailto:support@tmind.com\">support@tmind.com</a>");
                        }
                    }
                },
                error: function () {
                    Config.Plugins_LoadedError = true;
                },
                complete: function (jqXHR, textStatus) {
                    HideSmallLoader();
                    //Increment number of loaded sub-plugins
                    //If both types of destinations lists (on the left/on the right) are completed, launch 'ModuleLoaded' event
                }
            });
        }
        else {
            //Increment number of loaded sub-plugins
            //If both types of destinations lists (on the left/on the right) are completed, launch 'ModuleLoaded' event
        }

        //Destinations list on the right
        if (Config.DS_DestinazioniRight == null) {
            $.ajax({
                async: true,
                cache: false,
                url: Config.ServerURL,
                data: { "action": "SelDestinazioniPolitiche" },
                success: function (data) {
                    try {
                        //Test for errors
                        if (data == '-1') throw '-1';
                        if (data == '') {
                            Config.DS_DestinazioniRight = '';
                            throw '';
                        }

                        var dataArray = jQuery.parseJSON(data);
                        Config.DS_DestinazioniRight = dataArray;

                        if (Config.DS_DestinazioniLeft != null) {
                            if (Config.Open_DestinazioniList == true) {
                                RicercaDestinazioni_Show($(Config.RicercaContainer + ' .ricerca_destinazioni > div > input'));
                                Config.Open_DestinazioniList = false;
                            }
                        }
                    }
                    catch (err) {
                        Config.Plugins_LoadedError = err != '';
                        if (err != '') {
                            ShowMessage("Attenzione", "Si &egrave; verificato un errore di comunicazione con il server, vi preghiamo di riprovare in seguito, se il problema persiste contattate il supporto tmind a questo indirizzo: <a href=\"mailto:support@tmind.com\">support@tmind.com</a>");
                        }
                    }
                },
                error: function () {
                    Config.Plugins_LoadedError = true;
                },
                complete: function (jqXHR, textStatus) {
                    HideSmallLoader();
                    //Increment number of loaded sub-plugins
                    //If both types of destinations lists (on the left/on the right) are completed, launch 'ModuleLoaded' event
                }
            });
        }
        else {
            //Increment number of loaded sub-plugins
            //If both types of destinations lists (on the left/on the right) are completed, launch 'ModuleLoaded' event
        }
    }


    function RicercaDestinazioni_Create() {
        var objParent = $('<div/>', { "style": "position:relative; float:left; ", "class": "destinazioni_modal_holder" })
                    .append($('<div/>', { "class": "ricerca_left_destinazioni" }))
                    .append($('<div/>', { "class": "ricerca_right_destinazioni" }));


        RicercaDestinazioniLeft_Create(objParent.find('.ricerca_left_destinazioni'), Config.DS_DestinazioniLeft);
        RicercaDestinazioniRight_Create(objParent.find('.ricerca_right_destinazioni'), Config.DS_DestinazioniRight);
        return objParent;
    }

    function RicercaDestinazioniLeft_Create(objParent, dataArray) {
        //DESTINATIONS ON THE LEFT
        //I add all the destinations on the left
        if (Config.DS_DestinazioniLeft == '') return;
        var parentLink;
        var parentContainer;

        var objDestinazioniHolder = $('<ul/>', { "class": "margin_left_10 padding_bottom_10", "style": "width:150px" });

        jQuery.each(Config.DS_DestinazioniLeft, function (index, obj) {
            //Create the link for a destination
            parentLink = $("<a>", { 'href': 'javascript:void(0);', 'title': '', "class": "destinazione_parent_" + obj.Value });
            parentLink.html(obj.Text);

            //For each destination i add the click event. 
            parentLink.bind('click', function () {
                parentContainer = $(this).parent().parent().parent().parent();
                if ($(this).hasClass('isChecked')) {
                    $(this).removeClass('isChecked');
                    jQuery.each(obj.Lista, function (index2, obj2) {
                        CheckElement(parentContainer.find('input[type="checkbox"][value="' + obj2.Value + '"]').parent(), false, obj2.Value);
                    });
                }
                else {
                    $(this).addClass('isChecked');
                    jQuery.each(obj.Lista, function (index2, obj2) {
                        CheckElement(parentContainer.find('input[type="checkbox"][value="' + obj2.Value + '"]').parent(), true, obj2.Value);
                    });
                }
                return false;
            });
            objDestinazioniHolder.append($('<li/>', { "style": "width:100%" }).append(parentLink));
        });

        objParent.append($('<div/>', { "style": "position:relative; float:left; margin:15px 0 16px 6px; font-size:16px; color:white; font-weight:bold; width:150px;" }).html('Le migliori mete!')).append(objDestinazioniHolder);
    }

    function RicercaDestinazioniRight_Create(objParent, dataArray) {
        //DESTINATIONS ON THE RIGHT  

        //determine the number of destinations (including headers)

        var totalDestinazioni = 0;
        jQuery.each(dataArray, function (index, obj) {
            totalDestinazioni++;
            jQuery.each(dataArray[index].Lista, function (index2, obj2) {
                totalDestinazioni++;
            });
        });

        objParent.append($('<div/>', { "class": "ui-dialog-buttonpane ui-widget-content ui-helper-clearfix" })
                                .append($('<div/>', { "class": "ui-dialog-buttonset" })
                                    .append($('<button/>', { "tpe": "button", "class": "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only", "role": "button", "style": "-moz-border-radius: 5px 5px 5px 5px;" })
                                                    .bind('click', function () {
                                                        var listaDestinazioni = '';
                                                        var firstSelectedDestination = '';

                                                        jQuery.each($(msgBox).find('input[type="checkbox"]:checked'), function (index, obj) {
                                                            if ($(obj).val() != "0") {
                                                                firstSelectedDestination = $(obj).next().html();
                                                                listaDestinazioni = listaDestinazioni + ',' + $(obj).val();
                                                            }
                                                        });
                                                        if (listaDestinazioni.length > 1) {
                                                            listaDestinazioni = listaDestinazioni.substring(1, listaDestinazioni.length);
                                                        }
                                                        Config.FormRicerca.ListaIdDestinazioni = listaDestinazioni;
                                                        if (listaDestinazioni != '') {
                                                            if (listaDestinazioni.split(',').length > 1) {
                                                                $(inputDestinazioni).css('font-style', 'italic').val('Selezione Multipla');
                                                            }
                                                            else {
                                                                $(inputDestinazioni).css('font-style', 'normal').val(firstSelectedDestination);
                                                            }
                                                        }
                                                        else {
                                                            $(inputDestinazioni).val('');
                                                        }
                                                        $(msgBox).dialog("destroy");
                                                    })
                                                    .append($('<span/>', { "class": "ui-button-text" }).html('SE HAI SCELTO, CLICCA QUI!')
                                     )
                                 )
                             )
                         );

        var destinazioniHolder0 = $('<dl/>', { "class": "ricerca_right_dl0" });
        var destinazioniHolder1 = $('<dl/>', { "class": "ricerca_right_dl1" });
        var destinazioniHolder2 = $('<dl/>', { "class": "ricerca_right_dl2" });
        // var destinazioniHolder3 = $('<dl/>', { "class": "ricerca_right_dl3" });
        var currentDestinazioniHolder = destinazioniHolder0;
        var listaChildren = null;
        var currentCheckboxes = 0;
        var currentDivCheckboxes = 0;

        jQuery.each(dataArray, function (index, obj) {
            listaChildren = $('<div/>');

            var selectedDestinazioni = Config.FormRicerca.ListaIdDestinazioni.split(',');
            currentDivCheckboxes = 0;

            listaChildren.append(
                                $('<dt/>')
                                .append(
                                        $('<a/>', { "href": 'javascript:void(0);', "style": "position: relative; float: left; width: 12px; margin-top:1px;  height:11px; text-align: center; text-decoration: none;   font-size: 10px; border: 1px solid #B5C3DF; margin-right: 2px;" })
                                        .html("+")
                                        .click(function () {
                                            ExpandChildren($(this).parent().parent(), $(this));
                                            return false;
                                        })
                                )
                                .append($('<input/>', { "type": "checkbox", "value": obj.Value, /*"checked": ($.inArray(obj.Value, selectedDestinazioni) != -1) ? "checked" : "",*/"name": obj.Value, "style": "position:relative; float:left;" }).click(function () {
                                    CheckElement($(this).parent(), $(this).attr('checked'), $(this).val());
                                })
                                           )
                                          .append($('<span/>', { "style": "position:relative; float:left;" }).html(obj.Text.capitalize()))
                             )

            jQuery.each(dataArray[index].Lista, function (index2, obj2) {
                listaChildren.append(
                                    $('<dd/>').append($('<input/>', { "type": "checkbox", "value": obj2.Value, /*"checked": ($.inArray(obj2.Value, selectedDestinazioni) != -1) ? "checked" : "",*/"style": "position:relative; float:left;", "name": obj2.Value }).click(function () {
                                        CheckElement($(this).parent(), $(this).attr('checked'), $(this).val());
                                    })
                                               )
                                              .append($('<span/>', { "style": "position:relative; float:left;" }).html(obj2.Text.capitalize()))
                                  );
                currentCheckboxes++;
                currentDivCheckboxes++;
            });

            var hasCheckedElements = false;
            listaChildren.find('input[type="checkbox"]').each(function () {
                if ($.inArray($(this).val(), selectedDestinazioni) != -1) {
                    $(this).attr('checked', true);
                    hasCheckedElements = true;
                }
            });
            if (!hasCheckedElements) {
                listaChildren.find('dd').addClass('hidden');
            }
            else {
                listaChildren.find('dt>a:first').html('-');
            }

            currentCheckboxes++;
            currentDivCheckboxes++;

            if ((currentCheckboxes > totalDestinazioni / 3) && (currentDivCheckboxes <= totalDestinazioni / 3)) {
                if (currentDestinazioniHolder == destinazioniHolder0) {
                    currentDestinazioniHolder = destinazioniHolder1;
                    currentCheckboxes = currentDivCheckboxes;
                }
                else if (currentDestinazioniHolder == destinazioniHolder1) {
                    currentDestinazioniHolder = destinazioniHolder2;
                    currentCheckboxes = currentDivCheckboxes;
                }
            }
            currentDestinazioniHolder.append(listaChildren);
        });
        objParent.append(destinazioniHolder0).append(destinazioniHolder1).append(destinazioniHolder2); //.append(destinazioniHolder3);
        //objParent.prepend($('<div/>', { "class": "divSave" }).append($('<button/>', { "type": "button", "class": "buttonSave ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" })
        //  .append($('<span/>', { "class": "ui-button-text" }).html("Se hai scelto, clicca qui!"))));
    }

    function RicercaDestinazioniLeft_AdjustHeight() {
        if ($('.ricerca_left_destinazioni:first').height() < $('.ricerca_right_destinazioni:first').height())
            $('.ricerca_left_destinazioni:first').height($('.ricerca_right_destinazioni:first').height());

    }

    function RicercaDestinazioni_Show(inputDestinazioni) {
        Config.Open_DestinazioniList = true;
        if (Config.DS_DestinazioniLeft == null || Config.DS_DestinazioniRight == null) {

            if (!Config.Plugins_LoadedError) {
                ShowSmallLoader();
            }
            else {
                if (Config.Open_DestinazioniList == true) {
                    Config.Open_DestinazioniList = false;
                    HideSmallLoader();
                }
            }

            return;
        }
        else {
            if (Config.Open_DestinazioniList == true) {
                HideSmallLoader();
            }
            if (Config.DS_DestinazioniRight == '') { Config.Open_DestinazioniList = false; return; }
        }

        var msgBox = $("<div/>");
        $(Config.Container).append(msgBox);
        $(msgBox).html(RicercaDestinazioni_Create());

        //Add the top Save button for Destinazioni

        $(msgBox).dialog({
            width: 900,
            title: 'SCEGLI LE TUE DESTINAZIONI',
            modal: true,
            draggable: true,
            resizable: false,
            close: function () {
                $(this).dialog("destroy");
                $(this).remove();
                Config.Open_DestinazioniList = false;
            },
            buttons: [
                        {
                            text: "AVANTI",
                            click: function () {
                                DestinazioniSave(inputDestinazioni, msgBox);
                            }
                        }
                    ]
        });
        $(msgBox).dialog('open');

        RicercaDestinazioniLeft_AdjustHeight();

    }

    function DestinazioniSave(inputDestinazioni, msgBox) {
        var listaDestinazioni = '';
        var firstSelectedDestination = '';

        jQuery.each($(msgBox).find('input[type="checkbox"]:checked'), function (index, obj) {
            if ($(obj).val() != "0") {
                firstSelectedDestination = $(obj).next().html();
                listaDestinazioni = listaDestinazioni + ',' + $(obj).val();
            }
        });
        if (listaDestinazioni.length > 1) {
            listaDestinazioni = listaDestinazioni.substring(1, listaDestinazioni.length);
        }
        Config.FormRicerca.ListaIdDestinazioni = listaDestinazioni;
        if (listaDestinazioni != '') {
            if (listaDestinazioni.split(',').length > 1) {
                $(inputDestinazioni).css('font-style', 'italic').val('Selezione Multipla');
            }
            else {
                $(inputDestinazioni).css('font-style', 'normal').val(firstSelectedDestination);
            }
        }
        else {
            $(inputDestinazioni).val('');
        }
        $(msgBox).dialog("destroy");
        $(msgBox).remove();
        Config.Open_DestinazioniList = false;
    }


    //private
    //I don't pass the element, but it's value (id) because this function it is also used from the menu on the left where there are no checkboxes.
    function CheckElement(parentContainer, isChecked, elValue) {
        //Get the element
        var element = parentContainer.find('input[type="checkbox"][value="' + elValue + '"]:first');
        if (parentContainer.length == 0) return;
        var isParent = parentContainer[0].tagName == 'DT';
        if (isChecked) {
            if (isParent) {
                //If the parent is checked, check all the inputs of the parent.
                if (element.parent().parent().find('dd.hidden').length != 0) {
                    ExpandChildren(element.parent().parent(), element.parent().find('a:first'));
                }
                element.parent().parent().find('input[type="checkbox"]').attr('checked', 'checked');
            }
            else {
                if (element.hasClass('hidden'))
                    ExpandChildren(element.parent().parent(), element.parent().parent().find('dt>a:first'));

                if (!element.attr('checked')) element.attr('checked', 'checked');
                //Check if there is any element that is not checked
                if (element.parent().parent().find('dd input[type="checkbox"]:not(:checked)').length == 0) {
                    //If there is no unchecked element, check also the parent.
                    element.parent().parent().find('input[type="checkbox"]').attr('checked', 'checked');
                }
            }
        }
        else {
            if (isParent) {
                //If the parent is unchecked, uncheck all the inputs of the parent.
                if (element.parent().parent().find('dd.hidden').length == 0)
                    ExpandChildren(element.parent().parent(), element.parent().find('a:first'));
                element.parent().parent().find('input[type="checkbox"]').removeAttr('checked');
            }
            else {
                if (element.attr('checked')) element.removeAttr('checked', 'checked');
                //Check to see if there is any checked element
                if (element.parent().parent().find('dt input[type="checkbox"]').attr('checked')) {
                    //If there is no other checked element, uncheck the parent.
                    element.parent().parent().find('dt input[type="checkbox"]').removeAttr('checked');
                }
            }
        }
        if ($('.ricerca_right_destinazioni:first input[type="checkbox"]:not(:checked)').length == 0)
            $('.seleziona_tutte_destinazioni').attr('checked', 'checked');
        else
            $('.seleziona_tutte_destinazioni').removeAttr('checked');
    }


    function ExpandChildren(parentObj, triggerObj) {
        if ($(triggerObj).html() == "+") {
            $(triggerObj).html("-");
            $(parentObj).find('dd').removeClass('hidden');
        }
        else {
            $(triggerObj).html("+");
            $(parentObj).find('dd').addClass('hidden');
        }

        //$(parentObj).find('dd').toggle();
        RicercaDestinazioniLeft_AdjustHeight();
    }

    function Operatori_Create() {
        var operatoriSelezionati_Array = Config.FormRicerca.TourOperator.split(',');
        var noOfOperatori = Config.DS_Operatori[1].Lista.length;

        var aux = '';

        var html = $("<div/>", { "class": "operatori_holder" });

        html.append($("<div/>", { "class": "operatori_selezione_title" }).html('Seleziona uno o pi&ugrave; operatori'));
        html.append($('<div/>', { "style": "position:relative; float:left; width:100%; margin-top:5px;", "class": "operatori_categoria_content" })
                                                        .append($('<input/>', { "type": "checkbox", "value": "0", /* "checked": (Config.DS_AeroportiContainer != null && Config.DS_AeroportiContainer.find('input[type="checkbox"]:not(:checked)').length == 0) ? "checked" : "",*/"style": "position:relative; float:left; margin:4px 5px 0 0; padding:0 ", "class": "seleziona_tutte_operatori" }).click(function () {
                                                            if ($(this).attr('checked')) {
                                                                $('.operatori_holder input[type="checkbox"]').attr('checked', 'checked');
                                                            }
                                                            else {
                                                                $('.operatori_holder input[type="checkbox"]').removeAttr('checked');
                                                            }
                                                        })
                                                        )
                                                        .append($('<span/>', { "class": "operatori_childlist_content_text" }).html('Seleziona tutti gli operatori'))
                                                    );
        html.append($('<div/>', { "style": "position:relative; float:left; width:100%; margin-top:5px;", "class": "operatori_vacanze_mirate" })
.append($('<input/>', { "type": "checkbox", "value": "0", "style": "position:relative; float:left; margin:4px 5px 0 0; padding:0 ", "class": "operatori_mirate_checkbox" })
.click(function () {
    if ($(this).attr('checked')) {
        $('.operatori_mirate_checkbox input[type="checkbox"]').attr('checked', 'checked');
        jQuery.each(Config.DS_Operatori[0].Lista, function (index, obj) {
            html.find('input[type="checkbox"][value="' + obj.Value + '"]').attr('checked', 'checked');
        });
    }
    else {
        $('.operatori_mirate_checkbox input[type="checkbox"]').removeAttr('checked');
        jQuery.each(Config.DS_Operatori[0].Lista, function (index, obj) {
            html.find('input[type="checkbox"][value="' + obj.Value + '"]').removeAttr('checked');
        });
    }
}))
                                                        .append($('<span/>', { "class": "operatori_childlist_content_text" }).html('Vacanze Mirate')));

        //check Vacanze Mirante if present in TourOperator list
        html.find('input[type="checkbox"].operatori_mirate_checkbox').each(function () {
            if ($.inArray($(this).val(), operatoriSelezionati_Array) != -1) {
                $(this).attr('checked', true);
            }
        });

        if (noOfOperatori + 1 == operatoriSelezionati_Array.length) {
            html.find('input[type="checkbox"]:first').attr('checked', true);
        }
        aux = $("<div/>", { "class": "operatori_selezione_content" });

        html.append(aux);

        var allOperatoriChecked = false;
        var auxSubOperatori; // = $('<div/>');
        auxSubOperatori = $('<div/>');
        allOperatoriChecked = false;
        var numberOfHolders = 3;
        var currentHolder = 1;
        var currentHolderOperatori = 0;
        var totalAddedOperatori = 0;

        if (Config.DS_Operatori[1].Lista != undefined && Config.DS_Operatori[1].Lista != null) {
            jQuery.each(Config.DS_Operatori[1].Lista, function (index, obj) {

                auxSubOperatori.append(
                        $('<div/>', { "class": "operatori_childlist_content" })
                            .append(
                                            $('<input/>', { "type": "checkbox", "value": obj.Value, /*"checked": $.inArray(obj2.Value, aeroportiSelezionati_Array) == -1 ? '' : "checked",*/"class": "operatori_checkbox" })
                                                .click(function () {
                                                    if ($(this).attr('checked')) {
                                                        if ($(this).parent().parent().find('input[type="checkbox"]:not(.parent,:checked)').length == 0) {
                                                            $(this).parent().parent().find('input[type="checkbox"]').attr('checked', 'checked');
                                                        }
                                                    }
                                                    else {
                                                        if ($(this).parent().parent().find('input[type="checkbox"]:not(.parent):checked').length > 0) {
                                                            $(this).parent().parent().find('input[type="checkbox"].parent').removeAttr('checked');
                                                        }
                                                    }
                                                })
                                       )
                            .append($('<span/>', { "class": "operatori_childlist_content_text" }).html(obj.Text))
                    );

                //increment the number of added Operatori and check if it needs to be added to the next container
                currentHolderOperatori++;
                totalAddedOperatori++;

                if (currentHolder != 3) {
                    if (currentHolderOperatori == Math.floor(noOfOperatori / numberOfHolders)) {
                        currentHolderOperatori = 0;
                        currentHolder++;
                        aux = $('<div/>', { "class": "operatori_container_33" + " " + (index == 1 ? "first" : "") });

                        aux.append(auxSubOperatori.children());

                        html.append(aux);
                    }
                }
                else {
                    if (totalAddedOperatori == noOfOperatori) {
                        aux = $('<div/>', { "class": "operatori_container_33" + " " + (index == 1 ? "first" : "") });

                        aux.append(auxSubOperatori.children());

                        html.append(aux);
                    }
                }


            });

            //check which operators should be checked when reopeninh the modal
            html.find('input[type="checkbox"]').each(function () {
                if ($.inArray($(this).val(), operatoriSelezionati_Array) != -1) {
                    $(this).attr('checked', true);
                }
            });
            allOperatoriChecked = (html.find('input[type="checkbox"]:checked').length == Config.DS_Operatori[1].Lista.length);
        }


        return html;
    }

    function Operatori_Show(operatori_input) {

        if (Config.DS_Operatori == null) {
            Config.Open_OperatoriList = true;
            if (!Config.Plugins_LoadedError) {
                ShowSmallLoader();
            }
            else {
                if (Config.Open_OperatoriList == true) {
                    HideSmallLoader();
                }
            }

            return;
        }
        else {
            if (Config.Open_OperatoriList == true) {
                HideSmallLoader();
            }
            if (Config.DS_Operatori == '') return;
        }

        var msgBox = $("<div/>");
        $(Config.Container).append(msgBox);

        $(msgBox).html(Operatori_Create());


        $(msgBox).dialog({
            width: 575,
            title: 'SCEGLI IL TOUR OPERATOR',
            modal: true,
            draggable: true,
            dialogClass: "padding_left_15",
            resizable: false,
            close: function () {
                $(this).dialog("destroy");
                $(this).remove();
            },
            buttons: [
                        {
                            text: "AVANTI",
                            click: function () {
                                OperatoriSave(operatori_input, msgBox);
                            }
                        }]
        });
        $(msgBox).dialog('open');
    }

    function OperatoriSave(operatori_input, msgBox) {
        var listaOperatori = '';
        var firstSelectedOperator = '';

        jQuery.each($(msgBox).find('input[type="checkbox"]:checked'), function (index, obj) {
            if ($(obj).val() != "0") {
                firstSelectedOperator = $(obj).next().html();
                listaOperatori = listaOperatori + ',' + $(obj).val();
            }
        });
        if (listaOperatori.length > 1) {
            listaOperatori = listaOperatori.substring(1, listaOperatori.length);
        }
        Config.FormRicerca.TourOperator = listaOperatori;
        if (listaOperatori != '') {
            if (listaOperatori.split(',').length > 1) {
                $(operatori_input).css('font-style', 'italic').val('Selezione Multipla');
            }
            else {
                $(operatori_input).css('font-style', 'normal').val(firstSelectedOperator);
            }
        }
        else {
            $(operatori_input).val('');
        }
        $(msgBox).dialog("destroy");
        $(msgBox).remove();
    }

    //private 
    function Search(idParentContainer) {
        if ($.fn.validationEngine != undefined && $.fn.validationEngine != null) {
            if (!$(idParentContainer).validationEngine('validate')) return false;
        }

        //With this I know from which parent to read a certain input. Some input are repeated, and that is why I need to know the father element. 


        var dataPartenza = $(idParentContainer + ' .ricerca_data_partenza input').val();
        var range = $(idParentContainer + ' .ricerca_range select').val();

        Config.FormRicerca.Data = dataPartenza;
        Config.FormRicerca.Range = range;

        if (idParentContainer == Config.RicercaContainer) {
            Config.FormRicerca.Durata = $(idParentContainer + ' .ricerca_durata select').val();
            Config.FormRicerca.TipoVacanza = $(idParentContainer + ' .ricerca_tipo_vacanza select').val();
        }
        else {
            Config.FormRicerca.ListaIdDestinazioni = '';
            Config.FormRicerca.ListaIdOperatori = '';
        }
        $.fn.Travelmind.LoadPlugin("Risultati", Config.FormRicerca);
    }

    function ShowSmallLoader() {
        $("#page").fadeOut("fast", function () {
            $('#loaderSmall').css('margin-left', '900px');
            $("#loaderSmall").show();
        });
    }

    function HideSmallLoader() {
        $("#page").fadeIn("fast", function () {
            $("#loaderSmall").hide();
        });
    }

    function ShowMessage(title, msg) {
        var msgBox = $("<div/>");
        $(Config.Container).append(msgBox);
        $(msgBox).html(msg).dialog({
            width: 500,
            title: title,
            modal: true,
            draggable: true,
            buttons: {
                "Chiudi": function () { $(this).dialog("close"); }
            },
            close: function () {
                $(this).dialog("destroy");
            }
        });
        $(msgBox).dialog('open');
    }

    $.fn.Ricerca.RoundCorners = function () {
        $(".rounded").corner('5px');
    }

    $.fn.Ricerca.Destroy = function () {
        Config = {
            serverURL: "/Controller/Ricerca.ashx",
            clientURL: "/Plugins/modRicerca/Ricerca.htm",
            StyleURL: '/Plugins/modRicerca/Ricerca.css',
            Container: '',
            RicercaContainer: '#ricerca_container',
            RicercaContainer: '#container_ricerca_semplice',
            RicercaContainer: '#container_ricerca_avanzata',
            RWContainer: '#container_ricerca_wizard',
            FormRicerca: {
                Data: "",
                Range: "",
                DataDa: "",
                DataA: "",
                ListaIdDestinazioni: "",
                ListaIdAeroporti: "",
                Durata: "",
                TipoVacanza: "",
                TemaVacanza: "",
                Viaggiatori: "",
                TourOperator: "",
                Prezzo: ""
            },
            AgenziaInSessione: false,
            Agenzia: {},
            Plugins_Count: 3,
            Plugins_LoadedCount: 0,
            Plugins_LoadedError: false,
            DS_DestinazioniLeft: null,
            DS_DestinazioniRight: null,
            DS_TipoVacanza: null,
            DS_Durata: null,
            DS_Operatori: null,
            Open_OperatoriList: false,
            Open_DestinazioniList: false,
            SelectedTab: 0
        };
    }

})(jQuery);



