﻿// SLIDE ////////////////////////////////////////////////////////////////////////////////////////////////////
var Slide = new Class({

    Implements: Options,

    options: {
        container: 'gallery',   /* Contenitore immagini */
        delay: 5000,            /* Durata attesa prossima immagine */
        duration: 1500          /* Durata transizione */
    },

    initialize: function(element, options) {
        this.element = this.subject = $A(element);
        this.setOptions(options);
        this.options.container = $(this.options.container);
        this.period = null;
        this.images = null;
        this.currentImage = 0;
        this.preloadSlide();
    },

    showImage: function(index) {
        if (index >= 0 && index < this.images.length) {
            // Stop slideshow
            $clear(this.period);
            // Se immagine attuale != da index allora la mostro altrimenti è già li ;)
            if (this.currentImage != index) {
                this.images[this.currentImage].tween('opacity', 0);
                this.currentImage = index;
                this.images[this.currentImage].tween('opacity', 1);
            }
        }
    },

    changeImage: function() {
        this.images[this.currentImage].tween('opacity', 0);
        this.currentImage = (this.currentImage + 1) % this.images.length;
        this.images[this.currentImage].tween('opacity', 1);
    },

    runSlideshow: function() {
        this.images = this.options.container.getChildren('img');
        this.images.set('tween', { duration: this.options.duration });
        // Ciclo la gallery
        this.period = this.changeImage.periodical(this.options.delay + this.options.duration, this);
    },

    preloadOthers: function() {
        // La prima è già caricata
        this.element = $A(this.element.slice(1, this.element.length));
        var myClass = this;
        var myImgs = new Asset.images(this.element, {
            onComplete: function() {
                myImgs.setStyles({ 'opacity': 0 });
                myImgs.inject(myClass.options.container);
                myClass.runSlideshow.run([], myClass);
            }
        });
    },

    preloadSlide: function() {
        var myClass = this;
        // Preload della prima poi tutte le altre
        var myBase = new Asset.image(this.element[0], {
            onload: function() {
                myBase.inject(myClass.options.container);
                myClass.preloadOthers.run([], myClass);
            }
        });
    }

});
