(function ($) {

    var Config = {
        ClientURL: '/Plugins/modOfferteLista/OfferteLista.htm',
        ServerURL: '/Controller/Offerte.ashx',
        StyleURL: '/Plugins/modOfferteLista/OfferteLista.css',
        Container: '',
        Plugins_LoadedCount: 0,
        Plugins_LoadedError: false,
        listaTitle: '',
        idArea: 1,
        numMaxOfferte: 4,
        DS_LastMinute: null,
        DS_Offerte: null,
        listaType: "LM"
    };

    $.fn.OfferteLista = function (options) {
        //Extending the configuration
        if (options) {
            Config = $.extend({}, Config, options);
        }

        Config.Container = $(this);

        Init();
    };


    $.fn.OfferteLista.RoundCorners = function () {
        Config.Container.find('#offerte_lista').corner('10px');
        Config.Container.find('.offerte_title:first').corner('top 8px');
        Config.Container.find('.offerte_lista_content:first').corner('bottom 8px');
    }

    $.fn.OfferteLista.Destroy = function () {
        Config = {
            ServerURL: '/Controller/Offerte.ashx',
            ClientURL: '/Plugins/modOfferteLista/OfferteLista.htm',
            StyleURL: '/Plugins/modOfferteLista/OfferteLista.css',
            RoundCorners: false,
            Container: '',
            Plugins_LoadedCount: 0,
            Plugins_LoadedError: false,
            idArea: 1,
            numMaxOfferte: 4,
            DS_LastMinute: null,
            DS_Offerte: null,
            listaType: "LM"
        };
    }

    function Init() {
        //I hide the container, until the data is loaded
        //ShowContainer(false);
        CreateContainer();
    }

    function CreateLista(data) {
        //Get the holder for the offer list
        var lista_holder = Config.Container.find('.offerte_lista_content:first');

        if (lista_holder == undefined || lista_holder == null) throw 'OfferteLista: Can\'t find element ".offerte_lista_content:first"';

        //Offerte header
        var offerte_lista_header = lista_holder.find('.offerte_lista_header:first');

        //Get the template for each element
        var html = lista_holder.find('.offerte_item:first');

        if (html == undefined || html == null) throw 'OfferteLista: Can\'t find element ".offerte_item:first"';

        //Clone the html code, because we will delete the template html from the page, later..

        html = html.clone();

        //Clone the list_header (in IE, the list_header gets cleared along with the list_holder);

        offerte_lista_header = offerte_lista_header.clone();

        //Delete the template html from the page
        lista_holder.html('');

        //ADD THE LIST HEADER
        lista_holder.append(offerte_lista_header);

        //The template element is first invisible. We make it visible so we can use it.
        html.removeClass('hidden');

        var offersVisible = false;
        //show the elements
        var element;
        jQuery.each(jQuery.parseJSON(data), function (index, obj) {
            element = html.clone();
            if (index % 2 != 0) {
                element.removeClass('offerte_odd');
                element.removeClass('offerte_even');
                element.addClass('offerte_odd');
            }
            else {
                element.removeClass('offerte_odd');
                element.removeClass('offerte_even');
                element.addClass('offerte_even');
            }

            //Add the informations for the offer 

            var temp_text = obj.Destinazione;
            var temp_width = 120;

            if (obj.Destinazione != '') {
                element.find('.offerte_item_destinazione:first').html(ResizeText(temp_text, temp_width));
            }
            else {
                element.find('.offerte_item_destinazione:first').html('&nbsp;');
            }

            temp_text = obj.Struttura;
            temp_width = 195;

            if (obj.Struttura != '') {
                element.find('.offerte_item_struttura:first').html(ResizeText(temp_text, temp_width));
            }
            else {
                element.find('.offerte_item_struttura:first').html('&nbsp;');
            }

            element.find('.offerte_item_data:first').html(obj.DataPartenza.substring(8, 10) + '/' + obj.DataPartenza.substring(5, 7) + '/' + obj.DataPartenza.substring(0, 4));
            element.find('.offerte_item_prezzo:first').html('<strong>' + obj.Prezzo + '</strong> &euro;');

            element.find('div:first').removeAttr('onClick');

            if (obj.Link.toLowerCase().match("^preventivo") == "preventivo") {
                var _idProdotto = obj.Link.match(/idProdotto=.*?(&|$)/ig);
                if (_idProdotto != null) {
                    jQuery.each(_idProdotto, function (index2, obj2) {
                        _idProdotto = obj2.replace(/(idProdotto|&|=)/ig, '');
                    });
                }
                else _idProdotto = '';

                var _idAeroporti = obj.Link.match(/idAeroporti=.*?(&|$)/ig);
                if (_idAeroporti != null) {
                    jQuery.each(_idAeroporti, function (index2, obj2) {
                        _idAeroporti = obj2.replace(/(idAeroporti|&|=)/ig, '');
                    });
                }
                else _idAeroporti = '';

                var _DataPartenza = obj.Link.match(/DataPartenza=.*?(&|$)/ig);
                if (_DataPartenza != null) {
                    jQuery.each(_DataPartenza, function (index2, obj2) {
                        _DataPartenza = obj2.replace(/(DataPartenza|&|=)/ig, '');
                    });
                }
                else _DataPartenza = '';

                if (_idProdotto != '' && _idAeroporti != '' && _DataPartenza) {
                    element.find('div:first').attr('onClick', 'return $.fn.OfferteLista.ShowOfferta(1,\'' + _idProdotto + '\',\'' + _idAeroporti + '\',\'' + _DataPartenza + '\')');
                }
            }
            else {
                if (obj.Link.toLowerCase().match("^risultati") == "risultati") {
                    var _DataDa = obj.Link.match(/DataDa=.*?(&|$)/ig);
                    if (_DataDa != null) {
                        jQuery.each(_DataDa, function (index2, obj2) {
                            _DataDa = obj2.replace(/(DataDa|&|=)/ig, '');
                        });
                    }
                    else _DataDa = '';

                    var _DataA = obj.Link.match(/DataA=.*?(&|$)/ig);
                    if (_DataA != null) {
                        jQuery.each(_DataA, function (index2, obj2) {
                            _DataA = obj2.replace(/(DataA|&|=)/ig, '');
                        });
                    }
                    else _DataA = '';

                    var _ListaIdDestinazioni = obj.Link.match(/ListaIdDestinazioni=.*?(&|$)/ig);
                    if (_ListaIdDestinazioni != null) {
                        jQuery.each(_ListaIdDestinazioni, function (index2, obj2) {
                            _ListaIdDestinazioni = obj2.replace(/(ListaIdDestinazioni|&|=)/ig, '');
                        });
                    }
                    else _ListaIdDestinazioni = '';


                    var _idProdotto = obj.Link.match(/idProdotto=.*?(&|$)/ig);
                    if (_idProdotto != null) {
                        jQuery.each(_idProdotto, function (index2, obj2) {
                            _idProdotto = obj2.replace(/(idProdotto|&|=)/ig, '');
                        });
                    }
                    else _idProdotto = '';

                    if (_DataDa != '' && _DataA != ''/* && _ListaIdDestinazioni != ''*/) {
                        //element.find('div:first').attr('onClick', 'return $.fn.OfferteBanners.ShowOfferta(2,\'' + _DataDa + '\',\'' + _DataA + '\',\'' + _ListaIdDestinazioni + '\')');
                        if (_ListaIdDestinazioni != '') {
                            element.find('div:first').attr('onClick', 'return $.fn.OfferteBanners.ShowOfferta(2,\'' + _DataDa + '\',\'' + _DataA + '\',\'' + _ListaIdDestinazioni + '\')');
                        }
                        else {
                            if (_idProdotto != '') {
                                element.find('div:first').attr('onClick', 'return $.fn.OfferteBanners.ShowOfferta(3,\'' + _DataDa + '\',\'' + _DataA + '\',\'' + _idProdotto + '\')');
                            }
                        }
                    }
                }
            }

            if (typeof element.find('div:first').attr('onClick') == 'undefined') {
                element.css('display', 'none');
            }
            else {
                offersVisible = true;
                element.css('display', 'block');
            }
            //Add the offer row in the list
            lista_holder.append(element);
        });

        //Remove the margin-bottom from the last element of the list
        lista_holder.find('.offerte_item:last').css('margin-bottom', '0');


        if (offersVisible == false) {
            Config.Container.find('.offerte_lista_content:first').append('<p>Spiacenti, al momento non ci sono offerte disponibili.<p>');
        }

        Config.Container.find('.offerte_lista_content:first').html(lista_holder.html());
        if (Config.RoundCorners == true) {
            $.fn.OfferteLista.RoundCorners();
        }

        //Make the container for this plugin visible.
        ShowContainer(true);
    }


    function CreateContainer() {
        //I load the html code for this plugin
        Config.Container.load(Config.ClientURL, function () {

            if ((Config.DS_LastMinute == null) || (Config.DS_Offerte == null)) {
                $.ajax({
                    async: true,
                    cache: false,
                    url: Config.ServerURL,
                    data: { "action": "SelOfferteLista", "idArea": Config.idArea, "numMaxOfferte": Config.numMaxOfferte },
                    success: function (data) {
                        ShowSmallLoader();
                        var isError = false;

                        try {
                            if (data == '-1') throw '-1';
                            if (data == '') {
                                throw '';
                            }
                            var dataArray = data;
                            if (Config.listaType == "LM") {
                                Config.DS_LastMinute = dataArray;
                            }
                            else {
                                Config.DS_Offerte = dataArray;
                            }

                            CreateLista(data);
                            HideSmallLoader();

                        }
                        catch (err) {
                            isError = Config.Plugins_LoadedError = err != '';
                            Config.Container.find('.offerte_lista_content:first').append('<p>Spiacenti, al momento non ci sono offerte disponibili.<p>');
                            HideSmallLoader();
                        }

                        ++Config.Plugins_LoadedCount;
                        //Trigger the event 'ModuleLoaded' for this plugin
                        Config.Container.trigger({ type: "ModuleLoaded", isError: isError, PluginName: 'OfferteLista' });
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        //alert("errore lato server: " + textStatus + " - " + errorThrown);
                    }
                });
            }
            else if (Config.listaType == "OF") {
                CreateLista(Config.DS_Offerte);
                ++Config.Plugins_LoadedCount;
                //Trigger the event 'ModuleLoaded' for this plugin
                Config.Container.trigger({ type: "ModuleLoaded", isError: Config.Plugins_LoadedError, PluginName: 'OfferteLista' });
            }

            else if (Config.listaType == "LM") {

                CreateLista(Config.DS_LastMinute);
                ++Config.Plugins_LoadedCount;
                //Trigger the event 'ModuleLoaded' for this plugin
                Config.Container.trigger({ type: "ModuleLoaded", isError: Config.Plugins_LoadedError, PluginName: 'OfferteLista' });
            }
        });

    }

    function ResizeText(text, container_width) {

        var temp_item = ('<span class="_temp" style="display:none;">' + text + '</span>');
        $(temp_item).appendTo('body');
        var text_width = $('span._temp').width();
        var smaller_text = text;

        if (text_width > container_width) {
            while (text_width > container_width) {
                smaller_text = smaller_text.substr(0, (smaller_text.length - 1));
                $('span._temp').html(smaller_text);
                text_width = $('span._temp').width();
            }
            smaller_text += '..'
        }
        $('span._temp').remove();
        return smaller_text;
    }

    function ShowSmallLoader() {
        $("#page").fadeOut("fast", function () {
            $("#loader").dialog({
                width: 610,
                title: "Caricamento...",
                modal: true,
                draggable: false,
                close: function () {
                    $(this).dialog("destroy");
                }
            });
            $("#loader").dialog('open');
        });
    }

    function HideSmallLoader() {
        $("#page").fadeIn("fast", function () {
            $("#loader").dialog("close");
        });
    }

    function ShowContainer(isVisible) {
        if (isVisible)
            Config.Container.show('fast');
        else
            Config.Container.hide('fast');
    }

    $.fn.OfferteLista.ShowOfferta = function (tipo, var1, var2, var3) {
        switch (tipo) {
            case 1:
                var FormData = {
                    IdProdotto: var1,
                    IdAeroporti: var2,
                    DataPartenza: var3
                };
                $.fn.Travelmind.LoadPlugin('Preventivo', FormData);
                break;
            case 2:
                var FormData = {
                    DataDa: var1,
                    DataA: var2,
                    ListaIdDestinazioni: var3
                };
                $.fn.Travelmind.LoadPlugin('Risultati', FormData);
                break;
            case 3:
                var FormData = {
                    DataDa: var1,
                    DataA: var2,
                    IdProdotto: var3
                };
                $.fn.Travelmind.LoadPlugin('Risultati', FormData);
                break;
        }
        return false;
    }


})(jQuery);
 
