var P21Slideshow = new Class({
	options: {
		delay: 2000,			// duration to show the slide
		duration: 1000,	// duration to transition the image
		transition: Fx.Transitions.Cubic.easeOut,
		width: 250,
		height: 150
	},
	initialize: function(element, data, options) {
		this.setOptions(options);
		
		var preloadImages = new Array();
				
		this._index = -1;
		this._element = element;
		this._data = data;
		this._slides = new Array();
		this._timeoutSlideOut = null;
		this._state = "running";
		
		for(var i = 0; i < this._data.length; i++) {
			// push img urls into array for preload via Asset.images
			preloadImages.push(data[i]); 
		}
		
		this._elementLoading = new Element("div", {
			"class": "ssElementLoading"
		}).inject(this._element);
		
		// Preload Images 		
		new Asset.images(preloadImages, {
			onComplete: function() {
				for(var i = 0; i < this._data.length; i++) {
					var container = new Element("div", {
						"styles": {
							"opacity": "0",
							"position": "absolute",
							"left": "0px",
							"top": "0px",
							"margin": "0px",
							"border": "0px"
						},
						"class": "ssElement"
					}).inject(this._element);
					
					var img = new Element("img", {
						"src": data[i],
						"styles": {
							"width": this.options.width,
							"height": this.options.height
						}						
					}).inject(container);
					
					this._slides.push(container);
				}
			
				this._elementLoading.style.display = "none";
				this.slideIn();
			}.bind(this)
		});
	},
	slideIn: function() {
		var Slideshow = this;
	
		// clear slideOut 
		if(this._timeoutSlideOut) {
			clearTimeout(this._timeoutSlideOut);
		}
	
		this._index++;
		if(this._index >= this._data.length) {
			this._index = 0;
		}

		// fade in the slide
		this._slides[this._index].get('tween', {property: 'opacity', 
			duration: this.options.duration,
			transition: this.options.transition
		}).start(0, 1).chain(
			function() {
				this.slideOut();
			}.bind(this)
		);
	},
	slideOut: function() {
		if(this._state == "running") {
			this._timeoutSlideOut = setTimeout(
				function() {
					// fade OUT the current slide
					this._slides[this._index].get('tween', {property: 'opacity', 
						duration: this.options.duration,
						transition: this.options.transition
					}).start(1, 0)
					// call the next slide
					this.slideIn();	
				}.bind(this), 
				this.options.delay
			);
		}
	}
});
P21Slideshow.implement(new Options);

