var iSlideShow = new Class.create();

iSlideShow.prototype = {

	initialize : function (wrapper, options){
		this.wait        = options.wait ? options.wait : 8000;
		this.start       = options.start ? options.start : 0;
		this.duration    = options.duration ? options.duration : 0.5;
		this.autostart   = (typeof(options.autostart)=='undefined') ? true : options.autostart;
		this.pagination  = options.pagination ? options.pagination : "slider_pagination";
		
		this.iImageId    = this.start;
		this.wrapper     = $(wrapper);
		this.slides      = this.wrapper.getElementsBySelector("div.slide");
		this.paginations = $(this.pagination).getElementsBySelector("ul li");
		
		if ( this.slides ) {
			this.numOfImages	= this.slides.length;
			if ( !this.numOfImages ) {
				alert('No slides?');
			}
		}
		
		if ( this.autostart ) {
			this.startSlideShow();
		}
	},
	
	// The Fade Function
	swapImage: function (show, hide) {		
		$(this.slides[show]) && $(this.slides[show]).appear({ duration: this.duration });
		$(this.slides[hide]) && $(this.slides[hide]).fade({duration: this.duration });
		
		$(this.paginations[hide]) && $(this.paginations[hide]).removeClassName("active");
		$(this.paginations[show]) && $(this.paginations[show]).addClassName("active");
	},
	
	// the onload event handler that starts the fading.
	startSlideShow: function () {
		this.periodicallyUpdate();
	},
	
	periodicallyUpdate: function() { 
		if (this.timer != null) {
			clearTimeout(this.timer);
			this.goNext();
		}
		this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.wait);
	},
	
	stop: function  () {
		clearInterval(this.timer);
	},
	
	goTo: function (index) {
		var imageShow, imageHide;
		
		imageShow = parseInt(index, 10);
		imageHide = this.iImageId;

		if (imageShow != imageHide) {
			clearInterval(this.timer);
			
			this.swapImage(imageShow, imageHide);
			this.iImageId = imageShow;
			
			this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.wait);
		}
	},
	
	goNext: function () {
		var imageShow, imageHide;
	
		imageShow = this.iImageId + 1;
		imageHide = this.iImageId;
		
		if (imageShow == this.numOfImages) {
			this.swapImage(0, imageHide);	
			this.iImageId = 0;					
		} 
		else {
			this.swapImage(imageShow, imageHide);
			this.iImageId++;
		}
	},
	
	goPrevious: function () {
		var imageShow, imageHide;
					
		imageShow = this.iImageId - 1;
		imageHide = this.iImageId;
		
		if (this.iImageId == 0) {
			this.swapImage(this.numOfImages - 1, imageHide);	
			this.iImageId = this.numOfImages - 1;
		} 
		else {
			this.swapImage(imageShow, imageHide);
			this.iImageId--;
		}
	}
}
