/*
Slideshow.js
	a class for creating an simple image slideshow - documentation available at <http://projects.adamnfish.com/slideshow>

Author:
	adamnfish: see http://projects.adamnfish.com for more scripts and utilities
	Copyright 2007 Adam Fisher, <http://www.adamnfish.com>, MIT Style Licence
*/
var Slideshow = new Class({
	Implements: [Events, Options],
	options: {
		displayDuration: 15,
		transitionDuration: 2000,
		nextChoice: 'random',
		onTransitionStart: Class.empty,
		onTransitionEnd: Class.empty
	},
	initialize: function(el, paths, options) {
		this.setOptions(options);
		this.current = $(el);
		this.rubbishBin = new Element('div');
		this.imgs = this.options.nextChoice == 'randomOrder' ? paths.shuffle() : paths;
		this.count = 0;
		this.styles = this.current.style.cssText;
		this.attrs = this.current.getProperties('id', 'class', 'alt', 'title');
		this.start();
	},
	start: function() {
		this.timer =  this.change.bind(this).delay(this.options.displayDuration * 1000);
		this.loaded = this.waiting = 0;
		var nextKey = this.options.nextChoice == 'random' ? $random(0, this.imgs.length) : this.count;
		this.next = new Asset.image(this.imgs[nextKey % this.imgs.length], {onload: function(){
			this.next.setProperties(this.attrs);
			this.next.style.cssText = this.styles;
			this.loaded = 1;
			if(this.waiting) {this.change();}
		}.bind(this)});
		this.count += 1;
	},
	stop: function() {
		this.timer = $clear(this.timer);
	},
	change: function() {
		if (this.loaded) {
			this.transition = new Fx.Morph(this.current, {duration: this.options.transitionDuration, onComplete: function(){
				this.next.setStyle('z-index', '2');
				this.current.destroy();
				this.current = this.next;
				this.start();
				this.fireEvent('onTransitionEnd', 10);
			}.bind(this)});
			this.next.setStyle('z-index', 1);
			this.next.injectAfter(this.current);
			this.transition.start({'opacity': [1,0]});
			this.fireEvent('onTransitionStart', 10);
		}
		else {
			this.waiting = 1;
		}
	}
});

//	Mootools Extension - adamnfish
Array.implement({
    shuffle: function(){ 
        for(var i = 1, j = this.length; i < j; i++){
            var nextKey = $random(0, j - i);
            this.push(this[nextKey]);
            this.splice(nextKey, 1);//
        }
        return this; 
    }
});
Element.implement({
	destroy: function(){
		this.injectInside(Garbage.destructor);
		Garbage.destructor.empty();
	}
});
Garbage.destructor = new Element('div');
