var Rotator = new Class(
{
    currentIndex: 0,
    nextIndex: 1,
    period: 5000,
    duration: 1000,

    initialize: function(element, caption, photos, nextIndex) {
        this.element = $(element);
        if (caption) this.caption = $(caption);
        this.image = this.element.getElement('img');
        this.photos = photos;

        if (nextIndex != undefined) {
            this.nextIndex = nextIndex;
        }

        this.triggerNextPhoto();

        var duration = this.duration;
        this.image.set('tween',
		{
		    duration: duration,
		    link: 'chain'
		});
    },

    triggerNextPhoto: function() {
        this.currentIndex = this.nextIndex++;
        if (this.nextIndex >= this.photos.length)
            this.nextIndex = 0;
        new Asset.image(this.photos[this.nextIndex].url);
        this.nextPhoto.bind(this).delay(this.period);
    },

    nextPhoto: function() {
        var image = this.image;
        var url = this.photos[this.currentIndex].url;
        var loaded = new Asset.image(url, { onload: function() {
            var fadeIn = function() {
                image.src = loaded.src;
                image.tween('opacity', 0, 1);
                if (this.caption)
                    this.caption.set('html', this.photos[this.currentIndex].caption);
                this.triggerNextPhoto.bind(this).delay(this.duration);
            }
			.bind(this);
            image.tween('opacity', 1, 0);
            fadeIn.delay(this.duration);
        }
		.bind(this)
        });
    }
});