(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, //default
        numMaxOfferte: 7   //default
    };

    $.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 .offerte_item:last').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,
            listaTitle: '',
            idArea: 1, //default
            numMaxOfferte: 7   //default
        };
    }

    function Init() {
        //I hide the container, until the data is loaded
        ShowContainer(false);

        //I load the html code for this plugin
        Config.Container.load(Config.ClientURL, function () {
            $.ajax({
                async: true,
                url: Config.ServerURL,
                data: { "action": "SelOfferteLista", "idArea": Config.idArea, "numMaxOfferte": Config.numMaxOfferte },
                success: function (data) {
                    var isError = false;

                    try{ 
                        if (data == '-1') throw '-1';
                        if (data == '') {
                            Config.Container.find('.offerte_lista_content:first').html('<p>Spiacenti, al momento non ci sono offerte disponibili.<p>');
                            throw ''
                        };

                        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');

//                        if (Config.Container.attr('id') == 'box_offerte_lista1') {
//                            offerte_lista_header.find('.offerte_lista_header_text:first').html('Offerte Esclusive');
//                        }
//                        else if (Config.Container.attr('id') == 'box_offerte_lista2') {
//                            offerte_lista_header.find('.offerte_lista_header_text:first').html('Offerte Esclusive');
//                        }
//                        else {
//                            offerte_lista_header.find('.offerte_lista_header_text:first').html('Offerte Esclusive');
//                        }

                        //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.addClass('offerte_odd');
                            else element.addClass('offerte_even');

                            //Add the informations for the offer

                            var maxLengthDestinazione = 38; //45 senza Struttura
                            if (obj.DestinazionePadre.length + obj.Destinazione.length + 3 <= maxLengthDestinazione) {
                                element.find('.offerte_item_text:first').html('<strong>' + obj.DestinazionePadre + '</strong> - ' + obj.Destinazione);
                            }
                            else {
                                element.find('.offerte_item_text:first').html('<strong>' + obj.DestinazionePadre + '</strong> - ' + obj.Destinazione.substring(0, maxLengthDestinazione - (obj.DestinazionePadre.length + 3)) + "...");
                            }

                            element.find('.offerte_item_struct:first').html(obj.Struttura);

                            element.find('.offerte_item_price:first').html('<strong>' + obj.Prezzo + '</strong>');

                            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 != '') {
                                        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 {
                                //Add the offer row in the list
                                offersVisible = true;
                                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();
                        }

                        Config.Container.find('.offerte_title_text').html(Config.listaTitle);
                        //Make the container for this plugin visible.
                        ShowContainer(true);

                    }
                    catch (err) {
                        isError = Config.Plugins_LoadedError = err != '';
                    }

                    ++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);
                }
            });
        });
    }

    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 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);
 
