// Created and set free in March of 2007 by Jenna Fox <blueberry@creativepony.com>
// Requires MooTools 1.0 or newer with Fx.Style (HD note: actually also requires Window.DomReady, and all Elements except for Element.Form)

var Slides = new Class({
	initialize: function(slidelist, workingElement, options) {
		workingElement = $(workingElement);
		workingElement.innerHTML = "";

		Object.extend(this, options);

		var slides = [];

		var size = workingElement.getSize();
		slidelist.each(function (slideinfo) {
			var element = $(workingElement.appendChild(document.createElement('img')));
			element.setStyles({
				opacity: 0,
				position: 'absolute',
				width: size.width + 'px',
				height: size.height + 'px',
				zIndex: 0
			});
			element.addEvent('load', function() { this.loaded = true });
			Object.extend(element, slideinfo);
			slides.push(element);
		})

		this.slides = slides;
		this.workingElement = workingElement;
	},

	start: function() {
		this.displaySlide(this.slides[0], true);
		return this;
	},

	// display a slide (or display it after it's loaded if it isn't ready yet)
	displaySlide: function(slide, autorotate) {
		slide = $(slide);

		if (slide.loaded == true) {
			this.forceDisplaySlide(slide, autorotate);
		} else {
			slide.addEvent('load', this.forceDisplaySlide.pass([slide, autorotate], this))
		}

		return this;
	},

	// force a slide to display, even if it isn't loaded
	forceDisplaySlide: function(slide, autorotate) {
		slide = $(slide);

		if (this.activeSlide) {
			this.activeSlide.setStyle.delay(this.transitionFor, this.activeSlide, ['opacity', 0]);
			this.activeSlide.setStyle('z-index', 0);
		}

		this.activeSlide = slide;
		slide.setStyle('z-index', 1);
		this.fadeFx = new Fx.Style(slide, 'opacity', {duration: this.transitionFor}).start(0, 1);

		if (autorotate) {
			this.displaySlide.delay(this.transitionFor + this.showFor, this, [this.nextSlide(), autorotate])
		}

		return this;
	},

	// return the slide which will show next
	nextSlide: function() {
		var result = this.slides.indexOf(this.activeSlide) + 1;
		if (result >= this.slides.length) result = 0;
		return this.slides[result];
	}
})

Slides.start = function(slides, target, options) {
	return new Slides(slides, target, options).start();
}
