/*
* Class: Slideshow
* Written by: Andrew Tetlaw http://tetlaw.id.au
* Displays a cross-fading slideshow
* Option:default
* 	uri : [], // an array of image URIs
*		interval : 2.5, // seconds for each slide to be visible
*		duration : 1, // duration of fade efefct
*		fps : 50, // frames per second of slide effect; shouldn't need to adjust this
*		crossfade : true // if you don't want a cross-fade set this to false and it'll do a fade out - fade in , instead.
*/
var Slideshow = Class.create();

Slideshow.prototype = {
	initialize : function(elm, options) {
		this.elm = $(elm);
		this.counter = 0;
		this.loaded = false;
		this.options = Object.extend({
			uri : [],
			interval : 2.5,
			duration : 1,
			fps : 50,
			crossfade : true
		}, options || {})
		this.options.uri = $A(this.options.uri);
		if(FastInit) {
			FastInit.addOnLoad(this.start.bind(this));
		} else {
			Event.observe(window, 'load', this.start.bind(this));
		}
	},
	start: function() {
		//console.log('start... ' + this.options.uri.length + ' uris defined');
		var img = document.createElement('img');
		img.src = this.options.uri[0];
    this.cycle();

		new PeriodicalExecuter(this.cycle.bind(this), this.options.interval); 
	},
	cycle: function() {
		var elm = this.elm;
		var opt = this.options;
		if(this.counter++ == opt.uri.length) {
			this.counter = 1
			this.loaded = true;
		}
		count = this.counter;
		var next = document.createElement('img');
		next.src = this.options.uri[count-1];
		if(!this.loaded) {
			var preload = document.createElement('img');
			preload.src = this.options.uri[count]; 
		}
		//console.log(next.src);
		if(this.options.crossfade) {
			var currentSlide;
			if(elm.firstChild) {
				currentSlide = elm.firstChild;
			} else {
				currentSlide = document.createElement('div');
				elm.appendChild(currentSlide);
			}
			var nextSlide = $(document.createElement('div'));
			nextSlide.className = 'slide-image';
			nextSlide.style.backgroundImage = 'url('+next.src+')';
			nextSlide.setOpacity(0);
			elm.appendChild(nextSlide);
			new Effect.Parallel([new Effect.Fade(currentSlide,{sync:true}),
				new Effect.Appear(nextSlide,{sync:true})],
				{duration: opt.duration, fps: opt.fps, afterFinish : function() {Element.remove(currentSlide)}}
			);
		} else {
			new Effect.Fade(elm, { 
				duration: opt.duration, 
				fps: opt.fps, 
				afterFinish: function() {
					elm.style.backgroundImage = 'url('+next.src+')';
					new Effect.Appear(elm, {
							duration: opt.duration,
							fps: opt.fps,
							queue:'end'
					});
				} 
			})
		}
	}
};
