// Created and set free in March of 2007 by Jenna Fox <blueberry@creativepony.com>
// Released as public domain, with the request that credit is given for my contribution
// Also, I'd love to here where you've used or changed this code to do other interesting things!
// Requires MooTools 1.0 or newer with Fx.Style

var Slides = new Class({
	initialize: function(slidelist, workingElement, options) {
		workingElement = $(workingElement);
		if(workingElement.getTag()=="img"){
			var divelement = new Element('div', 
				{
					'styles': {
						'width':workingElement.getSize().size.x, 
						'height':workingElement.getSize().size.y
					}
				}
			);
			if(workingElement.getProperty('align'))
				divelement.setStyle('float', workingElement.getProperty('align'));
			if(workingElement.getStyle('float'))
				divelement.setStyle('float', workingElement.getStyle('float'));
			workingElement.replaceWith(divelement);
			workingElement = divelement;
		} else 
			workingElement.innerHTML = "";			
		
		Object.extend(this, options);
		
		var slides = [];
		
		var size = workingElement.getSize().size;
		slidelist.each(function (slideinfo) {
			var element = new Element('img');
			workingElement.adopt(element);
			element.setStyles({
				opacity: 0,
				position: 'absolute',
				width: size.x + 'px',
				height: size.y + '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();
}

