if (jQuery) (function ($) {

    $.extend($.fn, {
        galleryShow: function (settings) {

            if (this.length == 0)
                return this;

            //=================================================================
            // Internal function per l'inizializzazione ai valori di
            // default dei parametri
            //-----------------------------------------------------------------
            // Parametri:
            //      options     Oggetto contenente l'insieme delle opzioni
            //-----------------------------------------------------------------
            var initOptions = function (options) {
                // Defaults
                if (options.mode == undefined) options.mode = 'horizontal';
                if (options.interval == undefined) options.interval = 2000;
                if (options.duration == undefined) options.duration = 'slow';
                if (options.loop == undefined) options.loop = true;
                if (options.classLoader == undefined) options.classLoader = 'loader';
                if (options.easing == undefined) options.easing = null;
                if (options.width == undefined) options.width = null;
                if (options.automaticScroll == undefined) options.automaticScroll = true;
            }
            //=================================================================

            function GalleryScroller(object, gallerySettings) {

                this.self = $(object);
                this.container = this.self.find('ul');
                this.timer = undefined;
                this.scrolling = false;
                this.lastEndingScrolling = new Date();
                this.settings = gallerySettings;

                //=================================================================
                // Internal function per la notifica del completamento dello step
                // di animazione di scrolling
                //-----------------------------------------------------------------
                this.stepCompleted = function () {
                    this.lastEndingScrolling = new Date();
                    this.scrolling = false;
                    if (this.settings.stepCompleted != undefined && typeof this.settings.stepCompleted == 'function') {
                        try {
                            this.settings.stepCompleted()
                        }
                        catch (e) { }
                    }
                }
                //=================================================================

                //=================================================================
                // Internal function che esegue lo scroll precedente
                //-----------------------------------------------------------------
                this.prev = function () {

                    if (this.scrolling)
                        return;

                    this.scrolling = true;

                    var animParam = {};

                    if (this.settings.loop) {
                        var newObj = this.self.find('li:last-child').clone();
                        this.container.prepend(newObj);
                        this.container.css('margin-left', "-" + this.container.find('li:first').innerWidth() + 'px');
                    }

                    if (this.settings.mode == "horizontal") {
                        animParam.marginLeft = 0;
                    }

                    var instance = this;
                    this.container.animate(
                        animParam,
                        {
                            duration: this.settings.duration,
                            easing: this.settings.easing,
                            queue: true,
                            complete: function () {
                                if (instance.settings.loop) {
                                    instance.container.find('li:last-child').remove();
                                }
                                instance.stepCompleted();
                            }
                        });
                }
                //=================================================================

                //=================================================================
                // Internal function che esegue lo scroll successivo
                //-----------------------------------------------------------------
                this.next = function () {

                    if (this.scrolling)
                        return;

                    this.scrolling = true;

                    if (this.settings.loop) {
                        var newObj = this.self.find('li:first-child').clone();
                        this.container.append(newObj);
                    }

                    var animParam = {};

                    if (this.settings.mode == "horizontal") {
                        animParam.marginLeft = '-' + this.container.find('li:first').outerWidth() + 'px'
                    }
                    var objectToRemove = this.container.find('li:first-child');
                    var instance = this;
                    objectToRemove.animate(
                        animParam,
                        {
                            duration: this.settings.duration,
                            easing: this.settings.easing,
                            queue: true,
                            complete: function () {
                                if (instance.settings.loop) {
                                    objectToRemove.remove();
                                }
                                instance.stepCompleted();
                            }
                        });
                }
                //=================================================================

                //=================================================================
                // Internal function che esegue lo scroll successivo
                //-----------------------------------------------------------------
                this.executeLoop = function () {
                }

                this.start = function () {
                    if (this.settings.loop && this.timer == undefined) {
                        var instance = this;
                        this.timer = setInterval(function () {
                            var now = new Date();
                            var elapsed = now.getTime() - instance.lastEndingScrolling.getTime();
                            if (elapsed >= instance.settings.interval) {
                                instance.next();
                            }
                        },
                        this.settings.interval);
                    }
                }
                //=================================================================

                //=================================================================
                // Internal function che esegue lo scroll successivo
                //-----------------------------------------------------------------
                this.stop = function () {
                    clearInterval(this.timer);
                    this.timer = undefined;
                }
                //=================================================================
            }


            ///////////////////////////////////////////////////////////////////
            //
            // imageSlideGallery implementation
            //
            ///////////////////////////////////////////////////////////////////

            //
            // Inizializza le impostazioni
            //
            if (!settings) var settings = {};
            initOptions(settings);

            return this.each(function (index, item) {

                //
                // Gestione dei metodi addizionali
                //
                if ($(item).data('galleryScroller') != undefined && typeof settings == "string") {
                    var method = settings;
                    var galleryInstance = $(item).data('galleryScroller');

                    if (method == "stop") {
                        galleryInstance.stop();
                    } else if (method == "resume") {
                        galleryInstance.start();
                    } else if (method == "prev") {
                        galleryInstance.prev();
                    } else if (method == "next") {
                        galleryInstance.next();
                    }

                    return;
                }

                gallery = new GalleryScroller($(item), settings);
                $(item).data('galleryScroller', gallery);

                var show = function () {
                    gallery.self.parent().removeClass("loader");
                    gallery.self.delay(500);
                    gallery.self.fadeIn('slow', function () {
                        gallery.stepCompleted();
                        if (settings.automaticScroll) {
                            gallery.start();
                        }
                    });
                }

                var galleryImages = $(item).find('img');
                gallery.self.parent().addClass("loader");
                gallery.self.fadeOut();

                var countImages = galleryImages.length;
                var totalWidth = 0;
                galleryImages.each(function (index, item) {
                    var img = new Image();
                    $(img).load(function () {
                        $(item).css('width', this.width + "px")
                                   .css('height', this.height + "px");

                        totalWidth += this.width;
                        if ((--countImages) == 0) {
                            if (settings.width == null)
                                gallery.container.css('width', totalWidth + "px")
                            else {
                                var w = settings.width;
                                if (typeof w != 'string')
                                    w = w + "px";
                                gallery.container.css('width', w);
                            }
                            show();
                        }
                    }).error(function () {
                        if ((--countImages) == 0) {
                            show();
                        }
                    }).attr('src', $(item).attr('src'));
                });
            });
        }
    });
})(jQuery);
