(function ($) {

    var Config = {
        ClientURL: '/Plugins/modOfferteBox/OfferteBox.htm',
        ServerURL: '/Controller/Offerte.ashx',
        StyleURL: '/Plugins/modOfferteBox/OfferteBox.css',
        Container: '',
        Plugins_LoadedCount: 0,
        Plugins_LoadedError: false,
        idArea: 3,  //default 
        numMaxOfferte: 7,  //default
        numOfferte: 0,
        currentOfferta: 0,
        DS_OfferteLista: null,
        BoxInterval: null,
        BoxTimer: 5000
    };

    $.fn.OfferteBox = function (options) {
        //Extending the configuration
        if (options) {
            Config = $.extend({}, Config, options);
        }

        Config.Container = $(this);

        Init();
    };


    $.fn.OfferteBox.RoundCorners = function () {
        Config.Container.find('.offerte_box_box').corner('10px');
    }

    $.fn.OfferteBox.Destroy = function () {
        Config = {
            ClientURL: '/Plugins/modOfferteBox/OfferteBox.htm',
            ServerURL: '/Controller/Offerte.ashx',
            StyleURL: '/Plugins/modOfferteBox/OfferteBox.css',
            RoundCorners: false,
            Container: '',
            Plugins_LoadedCount: 0,
            Plugins_LoadedError: false,
            idArea: 3,  //default 
            numMaxOfferte: 7,  //default
            numOfferte: 0,
            currentOfferta: 0,
            DS_OfferteLista: null,
            BoxInterval: null
        };
    }


    function Init() {
        //I hide the container, until the data is loaded
        ShowContainer(false);

        //I load the html code for this plugin
        Config.Container.html('');
        Config.Container.load(Config.ClientURL, function () {
            Config.Container.find('.navigation_forward').attr('onClick', 'return  $.fn.OfferteBox.ChangeOfferteBox("avanti",true,event)');
            Config.Container.find('.navigation_back').attr('onClick', 'return  $.fn.OfferteBox.ChangeOfferteBox("indietro",true,event)');

            if (Config.DS_OfferteLista == null) {
                $.ajax({
                    async: true,
                    url: Config.ServerURL,
                    data: { "action": "SelOfferteBanner", "idArea": Config.idArea, "numMaxOfferte": Config.numMaxOfferte },
                    success: function (data) {
                        try {
                            if (data == '-1') throw '-1';
                            if (data == '') {
                                Config.Container.find('#offerte_box:first *').css('display', 'none');
                                throw '';
                            }

                            Config.DS_OfferteLista = jQuery.parseJSON(data);
                            jQuery.each(Config.DS_OfferteLista, function () {
                                Config.numOfferte++;
                            });

                            $.fn.OfferteBox.ChangeOfferteBox("avanti", false);
                            if (Config.numOfferte > 1) {
                                Start();
                            }
                            //Make the container for this plugin visible.
                            ShowContainer(true);
                        }
                        catch (err) {
                            Config.Plugins_LoadedError = Config.Plugins_LoadedError = err != '';
                            Config.Container.find('#offerte_box').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: Config.Plugins_LoadedError, PluginName: 'OfferteBox' });
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        // alert("errore lato server: " + textStatus + " - " + errorThrown);
                    }
                });
            }
            else {
                //Make the container for this plugin visible.
                ShowContainer(true);
                $.fn.OfferteBox.ChangeOfferteBox("avanti", false);
                if (Config.numOfferte > 1) {
                    Start();
                }
                ++Config.Plugins_LoadedCount;
                //Trigger the event 'ModuleLoaded' for this plugin                    
                Config.Container.trigger({ type: "ModuleLoaded", isError: Config.Plugins_LoadedError, PluginName: 'OfferteBox' });
            }
        });
    }

    function Start() {
        Config.BoxInterval = clearInterval(Config.BoxInterval);
        Config.BoxInterval = setInterval(function () { $.fn.OfferteBox.ChangeOfferteBox("avanti", false) }, Config.BoxTimer);
    }


    $.fn.OfferteBox.ChangeOfferteBox = function (direction, intervalClear, evt) {


        if (intervalClear) {
            evt.cancelBubble = true;
            if (evt.stopPropagation) evt.stopPropagation();
            Config.BoxInterval = clearInterval(Config.BoxInterval);
            Config.BoxInterval = setInterval(function () { $.fn.OfferteBox.ChangeOfferteBox("avanti", false) }, Config.BoxTimer);
        }

        if (direction == "avanti") {
            Config.currentOfferta++;
        }
        else {
            Config.currentOfferta--;
        }
        if (Config.currentOfferta > Config.numOfferte - 1) {
            Config.currentOfferta = 0;
        };
        if (Config.currentOfferta < 0) {
            Config.currentOfferta = Config.numOfferte - 1;
        }



        Config.Container.find('.offerte_box_parent').hide();

        //Get the holder for the offer list
        var lista_holder = Config.Container.find('#offerte_box:first');

        if (lista_holder == undefined || lista_holder == null) throw 'OfferteBox: Can\'t find element "#offerte_box:first"';

        //Get the template for each element
        var html = lista_holder.find('.offerte_box_box');

        if (html == undefined || html == null) throw 'OfferteBox: Can\'t find element ".offerte_box_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_box').html('');

        var element;
        var text;
        var img;
        var numberVisible = 0;
        jQuery.each(Config.DS_OfferteLista, function (index, obj) {
            if (Config.currentOfferta == index) {
                element = html.clone();

                title = element.find('.offerte_box_title:first');
                description = element.find('.offerte_box_description:first');
                price = element.find('.offerte_box_price:first');
                img = element.find('.offerte_box_img:first');

                if (title == undefined || img == null) throw 'OfferteBanners: Can\'t find elements "offerte_box_title:first"';
                if (img == undefined || img == null) throw 'OfferteBanners: Can\'t find element "img:first"';
                if (description == undefined || description == null) throw 'OfferteBanners: Can\'t find element ".offerte_box_description:first"';
                if (price == undefined || price == null) throw 'OfferteBanners: Can\'t find element ".offerte_box_price:first"';

                //Set banner destination

                //Set the banner image src                            
                img.css('background', 'url(' + obj.Immagine + ') no-repeat center');
                //img.attr('src', '/Plugins/comHome/Images/offerta_big.png');

                title.html('');

                title.append('<p class="destinazione">' + obj.Destinazione + '</i>' + '</p>');
                title.append('<p class="destinazionePadre">' + obj.DestinazionePadre + '</p>');
                title.append('<p class="struttura"><strong>' + obj.Struttura + '</strong><p>');


                description.html('<p class="partenza">' + obj.Partenza + '</p>');


                price.html('');
                price.append('<p class="price">' + obj.Prezzo + '</p>');
                price.append('<p class="costiextra">' + obj.CostiExtra + ' ' + '</p>');


                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.OfferteBox.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
                Config.Container.find('#offerte_box').append(element);
            }
        });

        if (numberVisible == 0) Config.Container.find('#offerte_box').html('')
        else {
            Config.Container.find('#box_offerte_box').removeClass('hidden');
            Config.Container.find('#offerte_box').removeClass('hidden'); //.append('<p>Spiacenti, al momento non ci sono offerte disponibili.<p>');
        }

        if (Config.RoundCorners == true) {
            $.fn.OfferteBox.RoundCorners();
        }

        Config.Container.find('.offerte_box_parent').fadeIn(700);
    }

    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 ResizeContainer(text) {
        var temp_item = ('<span class="_temp" style="display:none;font-size:26pt; font-weight:bold; text-transform:uppercase;">' + text + '</span>');
        $(temp_item).appendTo('body');
        var text_width = $('span._temp').width();
        $('span._temp').remove();
        return text_width;
    }

    function ShowContainer(isVisible) {
        if (isVisible)
            Config.Container.show('slow');
        else
            Config.Container.hide('slow');
    }



    $.fn.OfferteBox.SlideShow = function () {


    }

    $.fn.OfferteBox.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);
 
  
