if(typeof(VAUGHN) == 'undefined')
	VAUGHN = {};

VAUGHN.slideshow = {};

VAUGHN.slideshow = function (){
	
	function Slideshow() {
		this.imgsrcs = [];
		this.img;
		this.current = 0;
		
		this.pe; 
		this.bar;
	}
	
	Slideshow.prototype.initialize = function (divelt, imgs) {
		//Create selector holder

		this.bar = new Element('div');
		this.bar.addClassName('bar');
		this.imgsrcs = [];

		var obj = this;
		
		this.img = $(divelt).down('img');
		imgs.each(function(s, i) {
			r = new Element('div');
			r.addClassName('slide_item');
			if(i==0) r.addClassName('selected');
			r.writeAttribute({id: i});
			r.observe('click', obj.onItemClick.bind(obj));
			obj.bar.insert(r);
			im = new Image();
			im.src = s;
			obj.imgsrcs.push(im);
		});
		
		$(divelt).insert(this.bar);
		this.img.src=this.imgsrcs[0].src;
		this.pe = new PeriodicalExecuter(this.nextSlide.bind(this), 4);
		
	}
	
	Slideshow.prototype.onItemClick = function (e) {
		var elt = e.element();
		if(elt.tagName != 'DIV') {
			return;
		}
		//Stop, and resume only when mouse is out of the image area
		if(this.pe != null) this.pe.stop();
		this.setImage(elt.id);
		this.pe = new PeriodicalExecuter(this.nextSlide.bind(this), 4);
	}
	
	Slideshow.prototype.setImage = function (index) {
		var obj = this;
		new Effect.Fade(this.img, { duration: 0.5,
			afterFinish: function() {
				obj.img.src=obj.imgsrcs[index].src;
				obj.current = index;
				obj.bar.select('div').each(function(s,i) { 
						s.removeClassName('selected');
						if(s.id == index) s.addClassName('selected');
					});
				
				new Effect.Appear(obj.img, { duration: 0.5 });
			}
		});
	}
	
	Slideshow.prototype.nextIndex = function () {
		this.current++;
		if(this.current >= this.imgsrcs.length ) {
			this.current = 0;
		}
		return this.current;
	}
		
	Slideshow.prototype.nextSlide = function () {
		var index = this.nextIndex();
		this.setImage(index);
	}
	
	Slideshow.prototype.clear = function() {
		if(this.pe != null) this.pe.stop();
	}
	
	return {
		Slideshow: Slideshow
	}
}();