(function ($) {

    var Config = {
        ServerURL: "/Controller/Ricerca.ashx",
        ClientURL: "/Plugins/modRicerca/Ricerca.htm",
        StyleURL: '/Plugins/modRicerca/Ricerca.css',
        Container: '',
        TabsContainer: '#ricerca_container',
        RicercaContainer: '#container_ricerca',
        FormRicerca: {
            Data: "",
            Range: "",
            DataDa: "",
            DataA: "",
            ListaIdDestinazioni: "",
            ListaIdAeroporti: "",
            Durata: "",
            TipoVacanza: "",
            TemaVacanza: "",
            Viaggiatori: "",
            TourOperator: "",
            Prezzo: ""
        },
        Plugins_Count: 1,
        Plugins_LoadedCount: 0,
        Plugins_LoadedError: false,
        DS_DestinazioniLeft: null,
        DS_DestinazioniRight: null,
        DS_Durata: null,
        DS_Aeroporti: null,
        Open_AeroportiList: false,
        Open_DestinazioniList: false
    };



    $.fn.Ricerca = function (options) {
        //Extending the configuration
        if (options) {
            Config = $.extend({}, Config, options);
        }

        Config.Container = $(this);

        Init();

    };


    function Init() {
        //I load the html code for this plugin   
        Config.Container.load(Config.ClientURL, function () {

            Bindings();

            Config.Plugins_LoadedCount = 0;
            Config.Plugins_LoadedError = false;

            //Initialize DatePicker
            $(Config.TabsContainer + ' .ricerca_data_partenza input').datepicker({
                createButton: true,
                buttonImage: '/View/Images/Ricerca/datepicker.png',
                minDate: '1d',
                numberOfMonths: 2,
                onSelect: function (date) {
                    Config.FormRicerca.Data = date;
                    $('.ricerca_semplice_data_partenzaformError').remove();
                    $('.ricerca_avanzata_data_partenzaformError').remove();
                    if ($(this).val() != "Data partenza") {
                        $(this).css({ "border": "2px #EB8443 solid" });
                    } else {
                        $(this).css({ "border": "1px #B7B7B7 solid" });
                    }
                }
            });
            $(Config.TabsContainer + '  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();

        });
    }


    function Bindings() {
        // cambio il colore del bordo ai campi tto dopo che sono stati compilati
        $("select#ricerca_range, select#txtDurata").bind("change", function () {
            if ($(this).val() != "") {
                $(this).css({ "border": "2px #EB8443 solid" });
            } else {
                $(this).css({ "border": "1px #B7B7B7 solid" });
            }
        });
    }


    //Initialize Ricerca Semplice controls
    function Ricerca_Init() {
        var selectedRange = Config.FormRicerca.Range;

        if (Config.FormRicerca.Data != '')
            $('div#ricerca > div#ricerca_container > div#container_ricerca .ricerca_data_partenza > div:first > input').val(Config.FormRicerca.Data);

        Config.FormRicerca.Range = '3'; //default
        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');
        }

        $(Config.TabsContainer + ' .ricerca_destinazioni > div > input').click(function () {
            RicercaDestinazioni_Show($(Config.TabsContainer + ' .ricerca_destinazioni > div > input'));
        });
        $(Config.TabsContainer + ' .ricerca_destinazioni > a').click(function () {
            RicercaDestinazioni_Show($(Config.TabsContainer + ' .ricerca_destinazioni > div > input'));
        });

        var cancelTraverse = false;
        if (Config.FormRicerca.ListaIdAeroporti != '') {
            if (Config.FormRicerca.ListaIdAeroporti.split(',').length > 1) {
                $('div#ricerca > div#ricerca_container > div#container_ricerca .ricerca_aeroporti > div:first > input').css('font-style', 'italic').val('Selezione Multipla');
            }
            else {
                jQuery.each(Config.DS_Aeroporti, function (index, obj) {
                    if (cancelTraverse) return false;
                    jQuery.each(obj.ListaDeep, function (index2, obj2) {
                        if (obj2.Value == Config.FormRicerca.ListaIdAeroporti) {
                            $('div#ricerca > div#ricerca_container > div#container_ricerca .ricerca_aeroporti > div:first > input').css('font-style', 'normal').val(obj2.Text);
                            cancelTraverse = true;
                            return false;
                        }
                    });
                });
            }
        }

        if (Config.DS_Aeroporti == null) {
            $.ajax({
                async: true,
                cache: false,
                url: Config.ServerURL,
                data: { "action": "SelAeroporti" },
                success: function (data) {
                    try {
                        //Test for errors
                        if (data == '-1') throw '-1';
                        if (data == '') {
                            Config.DS_Aeroporti = '';
                            throw '';
                        }

                        var dataArray = jQuery.parseJSON(data);
                        Config.DS_Aeroporti = dataArray;

                        if (Config.FormRicerca.ListaIdAeroporti != '' && Config.FormRicerca.ListaIdAeroporti.split(',').length == 1) {
                            var cancelTraverse = false;
                            jQuery.each(Config.DS_Aeroporti, function (index, obj) {
                                if (cancelTraverse) return false;
                                jQuery.each(obj.ListaDeep, function (index2, obj2) {
                                    if (obj2.Value == Config.FormRicerca.ListaIdAeroporti) {
                                        $('div#ricerca > div#ricerca_container > div#container_ricerca .ricerca_aeroporti > div:first > input').css('font-style', 'normal').val(obj2.Text);
                                        cancelTraverse = true;
                                        return false;
                                    }
                                });
                            });
                        }
                        if (Config.Open_AeroportiList) {
                            Aeroporti_Show($(Config.RicercaContainer + ' .ricerca_aeroporti > div > input'));
                            Config.Open_AeroportiList = 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_aeroporti > div > input').click(function () {
            Aeroporti_Show(this);
        });
        $(Config.RicercaContainer + ' .ricerca_aeroporti > a').click(function () {
            Aeroporti_Show($(Config.TabsContainer + ' .ricerca_aeroporti > div > input'));
        });

        //DURATA
        //Get the container for the durata list 
        //Set the default value for the first element   
        $(Config.RicercaContainer + ' .ricerca_notti select')
            .append($('<option/>', { "value": "" })
            .html('Durata Vacanza'))
            .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_notti 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_notti 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_bottom 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.TabsContainer + ' .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.TabsContainer + ' .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.TabsContainer + ' .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.TabsContainer + ' .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).find('.ricerca_right_destinazioni').prepend($('<div/>', { "class": "divSave" }).append($('<button/>', { "class": "buttonSave ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" })
            .append($('<span/>', { "class": "ui-button-text" }).html("Ok"))
            .click(function () { DestinazioniSave(inputDestinazioni, msgBox); })
            .hover(function () { $(this).addClass("ui-state-hover"); }, function () { $(this).removeClass("ui-state-hover"); })));


        $(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: "Ok",
                            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;

        if ($("input#ricerca_destinazione").val() != "Destinazione" && $("input#ricerca_destinazione").val() != "") {
            $("input#ricerca_destinazione").css({ "border": "2px #EB8443 solid" });
        } else {
            $("input#ricerca_destinazione").css({ "border": "1px #B7B7B7 solid" });
        }

    }


    //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 Aeroporti_Create() {
        var aeroportiSelezionati_Array = Config.FormRicerca.ListaIdAeroporti.split(',');
        var noOfAeroporti = 0;

        jQuery.each(Config.DS_Aeroporti, function (index, obj) {
            noOfAeroporti = noOfAeroporti + obj.ListaDeep.length;
        });

        var aux = '';

        var html = $("<div/>", { "class": "aeroporti_partenza_holder" });

        html.append($("<div/>", { "class": "aeroporti_partenza_selezione_title" }).html('Seleziona uno o pi&ugrave; aeroporti'));
        html.append($('<div/>', { "style": "position:relative; float:left; width:100%; margin-top:5px;", "class": "aeroporti_partenza_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:0 5px 0 0; padding:0 ", "class": "seleziona_tutte_destinazioni" }).click(function () {
                                                            if ($(this).attr('checked')) {
                                                                $('.aeroporti_partenza_holder input[type="checkbox"]').attr('checked', 'checked');
                                                            }
                                                            else {
                                                                $('.aeroporti_partenza_holder input[type="checkbox"]').removeAttr('checked');
                                                            }
                                                        })
                                                        )
                                                        .append($('<span/>', { "class": "aeroporti_partenza_childlist_content_text" }).html('Seleziona tutti gli aeroporti'))
                                                    );

        if (noOfAeroporti == aeroportiSelezionati_Array.length) {
            html.find('input[type="checkbox"]:first').attr('checked', true);
        }
        aux = $("<div/>", { "class": "aeroporti_partenza_selezione_content" });

        html.append(aux);

        var allAeroportiChecked = false;
        var auxSubAeroporti; // = $('<div/>');
        jQuery.each(Config.DS_Aeroporti, function (index, obj) {
            auxSubAeroporti = $('<div/>');
            allAeroportiChecked = false;

            if (Config.DS_Aeroporti[index].ListaDeep != undefined && Config.DS_Aeroporti[index].ListaDeep != null) {
                jQuery.each(Config.DS_Aeroporti[index].ListaDeep, function (index2, obj2) {
                    auxSubAeroporti.append(
                        $('<div/>', { "class": "aeroporti_partenza_childlist_content" })
                            .append(
                                            $('<input/>', { "type": "checkbox", "value": obj2.Value, /*"checked": $.inArray(obj2.Value, aeroportiSelezionati_Array) == -1 ? '' : "checked",*/"class": "aeroporti_partenza_checkbox" })
                                                .click(function () {
                                                    if ($(this).attr('checked')) {
                                                        jQuery.each($('.aeroporti_modal_dialogue').find('input[type="checkbox"][value="' + obj2.Value + '"]'), function (idx, ob) {
                                                            $(this).attr('checked', 'checked');
                                                        });
                                                        if (Config.DS_Aeroporti[index].ListaDeep[index2].Lista != undefined && Config.DS_Aeroporti[index].ListaDeep[index2].Lista != null) {

                                                            jQuery.each(Config.DS_Aeroporti[index].ListaDeep[index2].Lista, function (index3, obj3) {
                                                                jQuery.each($('.aeroporti_modal_dialogue').find('input[type="checkbox"][value="' + obj3.Value + '"]'), function (index4, obj4) {
                                                                    $(this).attr('checked', 'checked');
                                                                    if ($(this).parent().parent().find('input[type="checkbox"]:not(.parent,:checked)').length == 0) {
                                                                        $(this).parent().parent().find('input[type="checkbox"]').attr('checked', '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 {
                                                        jQuery.each($('.aeroporti_modal_dialogue').find('input[type="checkbox"][value="' + obj2.Value + '"]'), function (idx, ob) {
                                                            $(this).removeAttr('checked', 'checked');
                                                        });
                                                        if (Config.DS_Aeroporti[index].ListaDeep[index2].Lista != undefined && Config.DS_Aeroporti[index].ListaDeep[index2].Lista != null) {
                                                            jQuery.each(Config.DS_Aeroporti[index].ListaDeep[index2].Lista, function (index3, obj3) {
                                                                jQuery.each($('.aeroporti_modal_dialogue').find('input[type="checkbox"][value="' + obj3.Value + '"]'), function (index4, obj4) {
                                                                    $(this).removeAttr('checked');
                                                                    if ($(this).parent().parent().find('input[type="checkbox"]:not(.parent):checked').length > 0) {
                                                                        $(this).parent().parent().find('input[type="checkbox"].parent').removeAttr('checked');
                                                                    }
                                                                });
                                                            });
                                                        }
                                                        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": "aeroporti_partenza_childlist_content_text" }).html(obj2.Text))
                    );
                });

                auxSubAeroporti.find('input[type="checkbox"]').each(function () {
                    if ($.inArray($(this).val(), aeroportiSelezionati_Array) != -1) {
                        $(this).attr('checked', true);
                    }
                });
                allAeroportiChecked = (auxSubAeroporti.find('input[type="checkbox"]:checked').length == Config.DS_Aeroporti[index].ListaDeep.length);
            }

            aux = $('<div/>', { "class": "aeroporti_partenza_container_" + (index == 0 ? '100' : '33') + " " + (index == 1 ? "first" : "") })
                    .append(
                        $('<div/>', { "class": "aeroporti_partenza_categoria_title" }).append(
                $('<input/>', { "type": "checkbox", "value": "0", /* "checked": allAeroportiChecked ? "checked" : "", */"class": "parent aeroporti_partenza_checkbox" }).click(function () {
                    var isChecked = $(this).attr('checked');
                    if (isChecked) {
                        jQuery.each($(this).parent().parent().find('input[type="checkbox"]'), function (idx, ob) {
                            $(this).attr('checked', 'checked');
                            if (Config.DS_Aeroporti[0].ListaDeep != undefined && Config.DS_Aeroporti[0].ListaDeep != null) {
                                jQuery.each(Config.DS_Aeroporti[0].ListaDeep, function (idx2, ob2) {
                                    if (ob2.Value == $(ob).val()) {
                                        jQuery.each($('.aeroporti_modal_dialogue').find('input[type="checkbox"][value="' + $(ob).val() + '"]'), function (idx5, ob5) {
                                            $(this).attr('checked', 'checked');
                                        });
                                        if (Config.DS_Aeroporti[0].ListaDeep[idx2].Lista != undefined && Config.DS_Aeroporti[0].ListaDeep[idx2].Lista != null) {
                                            jQuery.each(Config.DS_Aeroporti[0].ListaDeep[idx2].Lista, function (idx3, ob3) {
                                                jQuery.each($('.aeroporti_modal_dialogue').find('input[type="checkbox"][value="' + ob3.Value + '"]'), function (idx4, ob4) {
                                                    $(this).attr('checked', '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 {
                        jQuery.each($(this).parent().parent().find('input[type="checkbox"]'), function (idx, ob) {
                            $(this).removeAttr('checked');
                            if (Config.DS_Aeroporti[0].ListaDeep != undefined && Config.DS_Aeroporti[0].ListaDeep != null) {
                                jQuery.each(Config.DS_Aeroporti[0].ListaDeep, function (idx2, ob2) {
                                    if (ob2.Value == $(ob).val()) {
                                        jQuery.each($('.aeroporti_modal_dialogue').find('input[type="checkbox"][value="' + $(ob).val() + '"]'), function (idx5, ob5) {
                                            $(this).removeAttr('checked');
                                        });
                                        if (Config.DS_Aeroporti[0].ListaDeep[idx2].Lista != undefined && Config.DS_Aeroporti[0].ListaDeep[idx2].Lista != null) {
                                            jQuery.each(Config.DS_Aeroporti[0].ListaDeep[idx2].Lista, function (idx3, ob3) {
                                                jQuery.each($('.aeroporti_modal_dialogue').find('input[type="checkbox"][value="' + ob3.Value + '"]'), function (idx4, ob4) {
                                                    $(this).removeAttr('checked');
                                                    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": "aeroporti_partenza_categoria_title_text" }).html(obj.Text))
            )
            if (allAeroportiChecked) {
                aux.find('input[type="checkbox"]:first').attr('checked', true);
            }
            aux.append(auxSubAeroporti.children());

            html.append(aux);
        });
        return html;
    }

    function Aeroporti_Show(aeroporti_input) {
        Config.Open_AeroportiList = true;
        if (Config.DS_Aeroporti == null) {

            if (!Config.Plugins_LoadedError) {
                ShowSmallLoader();
            }
            else {
                if (Config.Open_AeroportiList == true) {
                    HideSmallLoader();
                    Config.Open_AeroportiList = false;
                }
            }

            return;
        }
        else {
            if (Config.Open_AeroportiList == true) {
                HideSmallLoader();
            }
            if (Config.DS_Aeroporti == '') { Config.Open_AeroportiList = false; return; }
        }

        var msgBox = $("<div/>", { "class": "aeroporti_modal_dialogue" });
        $(Config.Container).append(msgBox);

        $(msgBox).html(Aeroporti_Create());


        $(msgBox).dialog({
            width: 500,
            title: 'SCEGLI LA CITT&#192; DI PARTENZA',
            modal: true,
            draggable: true,
            dialogClass: "padding_left_15",
            resizable: false,
            close: function () {
                $(this).dialog("destroy");
                $(this).remove();
                Config.Open_AeroportiList = false;
            },
            buttons: [
                        {
                            text: "AVANTI",
                            click: function () {
                                AeroportiSave(aeroporti_input, msgBox);
                            }
                        }]
        });
        $(msgBox).dialog('open');
    }

    function AeroportiSave(aeroporti_input, msgBox) {
        var listaAeroporti = '';
        var firstSelectedAirport = '';

        jQuery.each($(msgBox).find('input[type="checkbox"]:checked'), function (index, obj) {
            if ($(obj).val() != "0") {
                firstSelectedAirport = $(obj).next().html();
                listaAeroporti = listaAeroporti + ',' + $(obj).val();
            }
        });
        if (listaAeroporti.length > 1) {
            listaAeroporti = listaAeroporti.substring(1, listaAeroporti.length);
        }
        Config.FormRicerca.ListaIdAeroporti = listaAeroporti;
        if (listaAeroporti != '') {
            if (listaAeroporti.split(',').length > 1) {
                $(aeroporti_input).css('font-style', 'italic').val('Selezione Multipla');
            }
            else {
                $(aeroporti_input).css('font-style', 'normal').val(firstSelectedAirport);
            }
        }
        else {
            $(aeroporti_input).val('');
        }
        $(msgBox).dialog("destroy");
        $(msgBox).remove();
        Config.Open_AeroportiList = false;

        if ($("input#txtAeroporti").val() != "Aeroporto" && $("input#txtAeroporti").val() != "") {
            $("input#txtAeroporti").css({ "border": "2px #EB8443 solid" });
        } else {
            $("input#txtAeroporti").css({ "border": "1px #B7B7B7 solid" });
        }

    }

    //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. 


        Config.FormRicerca.Data = $(idParentContainer + ' .ricerca_data_partenza input').val(); ;
        Config.FormRicerca.Range = $(idParentContainer + ' .ricerca_range select').val(); ;
        Config.FormRicerca.Durata = $(idParentContainer + ' .ricerca_notti select').val();

        $.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 () {
        $("#ricerca .rounded").corner('5px');
    }

    $.fn.Ricerca.Destroy = function () {
        Config = {
            ServerURL: "/Controller/Ricerca.ashx",
            ClientURL: "/Plugins/modRicerca/Ricerca.htm",
            StyleURL: '/Plugins/modRicerca/Ricerca.css',
            Container: '',
            TabsContainer: '#ricerca_container',
            RicercaContainer: '#container_ricerca',
            FormRicerca: {
                Data: "",
                Range: "",
                DataDa: "",
                DataA: "",
                ListaIdDestinazioni: "",
                ListaIdAeroporti: "",
                Durata: "",
                TipoVacanza: "",
                TemaVacanza: "",
                Viaggiatori: "",
                TourOperator: "",
                Prezzo: ""
            },
            Plugins_Count: 1,
            Plugins_LoadedCount: 0,
            Plugins_LoadedError: false,
            DS_DestinazioniLeft: null,
            DS_DestinazioniRight: null,
            DS_Durata: null,
            DS_Aeroporti: null,
            Open_AeroportiList: false,
            Open_DestinazioniList: false
        };
    }

})(jQuery);



