(function ($) {

    var Config = {
        ClientURL: '/Plugins/modOfferteBanners/OfferteBanners.htm',
        ServerURL: '/Controller/Offerte.ashx',
        StyleURL: '/Plugins/modOfferteBanners/OfferteBanners.css',
        Container: '',
        Plugins_LoadedCount: 0,
        Plugins_LoadedError: false,
        idArea: 3, //default
        numMaxOfferte: 7 //default
    };

    $.fn.OfferteBanners = function (options) {
        //Extending the configuration
        if (options) {
            Config = $.extend({}, Config, options);
        }

        Config.Container = $(this);

        Init();
    };


    $.fn.OfferteBanners.RoundCorners = function () {
        Config.Container.find('.offerte_banners_box').corner('10px');
        Config.Container.find('.offerte_banners_box .offerte_banners_text').css('margin', '0 2px 2px 2px').corner('8px bottom');
    }

    $.fn.OfferteBanners.Destroy = function () {
        Config = {
            ClientURL: '/Plugins/modOfferteBanners/OfferteBanners.htm',
            ServerURL: '/Controller/Offerte.ashx',
            StyleURL: '/Plugins/modOfferteBanners/OfferteBanners.css',
            RoundCorners: false,
            Container: '',
            Plugins_LoadedCount: 0,
            Plugins_LoadedError: false,
            idArea: 3, //default
            numMaxOfferte: 7 //default
        };
    }


    function Init() {
        //I hide the container, until the data is loaded
        ShowContainer(false);
        Config.Container.html('');
        //I load the html code for this plugin
        Config.Container.load(Config.ClientURL, function () {
            $.ajax({
                async: true,
                cache: false,
                url: Config.ServerURL,
                data: { "action": "SelOfferteBanner", "idArea": Config.idArea, "numMaxOfferte": Config.numMaxOfferte },
                success: function (data) {
                    var isError = false;
                    try {
                        if (data == '-1') throw '-1';
                        if (data == '') throw '';

                        //Get the holder for the offer list
                        var lista_holder = Config.Container.find('#offerte_banners_container:first');

                        if (lista_holder == undefined || lista_holder == null) throw 'OfferteBanners: Can\'t find element "#offerte_banners_container:first"';

                        //Get the template for each element
                        var html = lista_holder.find('.offerte_banners_box');

                        if (html == undefined || html == null) throw 'OfferteBanners: Can\'t find element ".offerte_banners_box"';

                        //Clone the html code, because we will delete the template html from the page, later..
                        html = html.clone();

                        //The template element is first invisible. We make it visible so we can use it.
                        html.removeClass('hidden');

                        //Delete the template html from the page
                        Config.Container.find('#offerte_banners_container').html('');


                        var element;
                        var text;
                        var img;
                        var numberVisible = 0;
                        var idx = 0;
                        var tempHTML4 = $('<div/>', { "style": "position:relative; float:left; width:100%;" });
                        var tempHTML8 = $('<div/>', { "style": "position:relative; float:left; width:100%;" });
                        jQuery.each(jQuery.parseJSON(data), function (index, obj) {
                            if (idx == 8) return false;
                            element = html.clone();

                            title = element.find('.offerte_banners_title:first');
                            text = element.find('.offerte_banners_text:first');
                            img = element.find('img:first');

                            if (img == undefined || img == null) throw 'OfferteBanners: Can\'t find element "img:first"';
                            if (text == undefined || text == null) throw 'OfferteBanners: Can\'t find element ".offerte_banners_text:first"';
                            if (title == undefined || title == null) throw 'OfferteBanners: Can\'t find element ".offerte_banners_title:first"';

                            //Set the title above the image
                            //title.append(ResizeText('<p><strong>' + obj.Destinazione + '</strong>, ' + obj.DestinazionePadre + '</p>',240));
                            title.append('<p><strong>' + obj.Destinazione + '</strong></p>');
                            title.append('<p><font size="10">' + obj.DestinazionePadre + '</font></p>');

                            //Set the banner image src                            
                            img.attr('src', obj.Immagine);

                            //Set the text under the picture                    

                            // text.append('<p>7 Notti - All inclusive </p>');
                            text.append('<p>' + obj.Partenza + '</p>');
                            text.append('<p>' + obj.Prezzo + '</p>');

                            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.OfferteBanners.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 {
                                ++numberVisible;
                            }

                            //Add the banner to the list
                            if (++idx <= 4) tempHTML4.append(element);
                            else tempHTML8.append(element);
                        });
                        Config.Container.find('#offerte_banners_container').append(tempHTML4).append(tempHTML8);

                        if (numberVisible == 0) Config.Container.find('#offerte_banners_container').html('').append('<p>Spiacenti, al momento non ci sono offerte disponibili.<p>');

                        if (Config.RoundCorners == true) {
                            $.fn.OfferteBanners.RoundCorners();
                        }

                        //Make the container for this plugin visible.
                        ShowContainer(true);
                    }
                    catch (err) {
                        isError = Config.Plugins_LoadedError = err != '';
                        Config.Container.find('#offerte_banners_container').html('').append('<p>Spiacenti, al momento non ci sono offerte disponibili.<p>');
                    }

                    ++Config.Plugins_LoadedCount;
                    //Trigger the event 'ModuleLoaded' for this plugin                    
                    Config.Container.trigger({ type: "ModuleLoaded", isError: isError, PluginName: 'OfferteBanners' });
                },
                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;font-size:16px; font-weight:bold; text-transform:uppercase; padding-left:15px;">' + 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.OfferteBanners.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);
 
  
