var Slideshow = Class.create();
var slideshows = [];

Slideshow.prototype = {
	images : [],
	image1 : '',
	image2 : '',
	currentIndex : 0,
	timer : null,
	
	initialize : function(options, images) {
		this.options = Object.extend( {
			container : 'slideshow',
			width : 300,
			height : 200,
			interval : 3000 //interval between changing images
			
		}, options || {});
		
		if (images){
			this.images = images;
		}
		
		this.image1 = this.options.container + '_image_1';
		this.image2 = this.options.container + '_image_2'
		
		slideshows[this.options.container] = this;
		
	},
	
	addImage : function(image){
		this.images.push(image);
	},
	
	setup : function(){
		
		//make sure we have some images
		if (this.images && this.images.length > 0){
			
			//insert images into html
			$(this.options.container).insert({'top':
				new Element('img',{
					'src' : this.images[0].src,
					'id' : this.image1,
					'alt' : this.images[0].alt,
					'width' : this.options.width,
					'height' : this.options.height,
					'style' : 'position:absolute;left:0px;right:0px;z-index:2'
				})
			});
			
			$(this.options.container).insert({'top':
				new Element('img',{
					'src' : this.images[0].src,
					'id' : this.image2,
					'alt' : this.images[0].alt,
					'width' : this.options.width,
					'height' : this.options.height,
					'style' : 'position:absolute;left:0px;right:0px;z-index:1'
				})
			});
			
			//load images
			this.images.each(function(image){
				htmlImage = new Image();
				htmlImage.src = image.src;
			});
			
			//make sure container is relative
			$(this.options.container).setStyle({
				'position': 'relative'
			});
		}
	},
		
	start : function(){
		
		this.timer = setTimeout('slideshows["' + this.options.container + '"].changeImages();', this.options.interval);
	},
	
	pause : function(){
		clearTimeout(this.timer);
	},		
	
	changeImages : function(){
		
		var _self = this;
		
		this.currentIndex++;
		
		//wrap around
		if (this.currentIndex > this.images.length - 1){
			this.currentIndex = 0;
		}
		
		
		$(this.image2).src = this.images[this.currentIndex].src; 
		$(this.image2).alt = this.images[this.currentIndex].alt;
		//$(this.image2).show();
		
		$(this.image1).fade({from: 1, to: 0, duration: 2, afterFinish : function(){
			$(_self.image1).src = _self.images[_self.currentIndex].src;
			$(_self.image1).alt = _self.images[_self.currentIndex].alt;
			$(_self.image1).show();
			
			_self.timer = setTimeout('slideshows["' + _self.options.container + '"].changeImages();', _self.options.interval);
		}});
	}
		
}