SlideShow = Class.create();
SlideShow.prototype = {
	initialize: function(slideContainer,slideClass,slideControlsClass,slideInterval) {
		this.container = $(slideContainer);
		this.elements = this.container.select('.'+slideClass);
		this.currentIndex = this.elements.length - 1;
		this.execInterval = slideInterval;
		var ul = new Element('ul');
		for (var i = this.elements.length - 1; i >= 0; i-- ) {
			var num = this.elements.length-i;			
			var li = new Element('li').insert(new Element('a',{href: 'javascript:void(0);', id: 'slidebutton-'+num}).update(num));
			switch(num) {
				case 1:
					li.addClassName('first');
					break;
				case this.elements.length: 
					li.addClassName('last');					
			}
			li.observe('click', this.setElement.bind(this));
			ul.insert(li);
		}
		this.controls = new Element('div');
		this.controls.addClassName(slideControlsClass);
		this.controls.insert(ul);
		this.container.insert(this.controls);
		this.start();
	},
	start: function() {
		this.switchButton();
		this.executor = new PeriodicalExecuter(this.roll.bind(this), this.execInterval);
	},
	stop: function() {
		if (this.executor) this.executor.stop(); 
	},
	setElement: function(event) {
		this.stop();
		var elementNum = event.element().id.split('-')[1];
		var current = this.currentElement();
		current.style.zIndex = 1;
		this.currentIndex = this.elements.length - elementNum;
		current = this.currentElement();
		current.style.zIndex = 5;
		current.show();
		this.start();
	},
	switchButton: function() {
		var buttonNum = this.elements.length - this.currentIndex;
		var buttons = this.controls.select('a'); 
		for (var i=0; i < buttons.length; i++) {
			if (buttons[i].id == ('slidebutton-'+buttonNum)) 
				buttons[i].addClassName('active');
			else
				buttons[i].removeClassName('active');
		} 
	},
	currentElement: function() {
		return this.elements[this.currentIndex];
	},		
	nextElement: function() {
		this.currentIndex--;
		if (this.currentIndex < 0) this.currentIndex = this.elements.length - 1;
		return this.elements[this.currentIndex];
	},
	roll: function() {
		var current = this.currentElement();
		var next = this.nextElement();
		current.style.zIndex = 5;
		next.style.zIndex = 4;
		next.show();
		Effect.Fade(current);
		this.switchButton();
	}	
}

var slideShow = new SlideShow('slideshow','slideshow-banner','slideshow-controls',5);


