﻿var SimoneEsse = {
    init: function() {
        if ($('spotlight-photo')) {
            new SimoneEsse.Swapper({
                currentImage: 'image-rotator',
                images: window.photos.map(function(filename) {
                    return '/Slideshow/' + filename;
                })
            });
        }

        var A = $$("a").filter(function(B) {
            return B.rel && B.rel.test(/^lightbox/i);
        });

        if (typeof Slimbox != 'undefined') {
            $$(A).slimbox({}, null, function(B) {
                return (this == B) || ((this.rel.length > 8) && (this.rel == B.rel))
            });
        }
    }
};
SimoneEsse.Swapper = new Class({
	Implements: [Options],
    options: {
        autoStart: true,
        duration: 1500,
        timer: 5000
    },

    initialize: function(options) {
        this.index = 0;
        this.setOptions(this.options, options);
        this.currentImage = $(this.options.currentImage);

        this.images = this.options.images;
        if (this.options.autoStart) {
            this.index = 2;
            new Asset.images(this.images, {
                onComplete: function() {
                    this.rotate.delay(this.options.timer, this);
                } .bind(this)
            });
        }
    },
    rotate: function() {
        if (this.index >= this.images.length) {
            this.index = 0;
        } else if (this.index < 0) {
            this.index = this.images.length - 1;
        }
    
        var container = this.currentImage.getParent();
        
        this.nextImage = new Element('img')
                            .setProperties({
                                src: this.images[this.index]
                            })
                            .setStyle('opacity', 0)
                            .injectInside(container);
                            
        var duration = this.options.duration;
                            
        this.currentImage.set('tween', {duration: duration});
        this.nextImage.set('tween', {
            duration : duration,
            onComplete : function() {
                this.currentImage.destroy();
                this.currentImage = this.nextImage;
            }.bind(this)
        });
        
        this.currentImage.tween('opacity', 0);
        this.nextImage.tween('opacity', 1);   
        if (this.options.autoStart) {  
            this.index++;   
            this.rotate.delay(this.options.timer, this);
        }
    },
    showNext : function() {
        this.index++;
        this.rotate();
    },
    showPrev : function() {
        this.index--;
        this.rotate();
    }
});
window.addEvent('domready', SimoneEsse.init);