/**********************************************************
* 
* Home Page Slideshow
*
***********************************************************/


var Slideshow = Class.create({
	initialize: function(element_id, options){
		this.element_id = element_id;
		if (!$(this.element_id)) throw("Attempted to initialize slideshow with id: " + element_id + " which does not exist.");
		this.element = $(this.element_id);
		this.options = {
			delay: 7000,
			startSlide: options.startSlide
		};
		
		/* Get slides */
		this.slides = this.element.select('.slide');
		/* Get buttons */
		this.buttons = this.element.select('.buttons a');
		
		this.currentSlideIndex = this.options.startSlide;
		
		this.buttons.each(function(object, index) {
			object.observe('click', this.clickHandler.bind(this, object, index));
		}, this);
		
		this.fadeEffect = false;
		this.appearEffect = false;
		
		this.isNotPaused = true;
		
		if (this.slides.length > 1) {
			this.begin();
		}
		
	},
	clickHandler: function(element, index, event){
		Event.stop(event);
		element.blur();
			
			/* Clear effects */
			if (this.currentSlideIndex !== index) {
				if (this.fadeEffect) {
					this.fadeEffect.cancel();
				}
				if (this.appearEffect) {
					this.appearEffect.cancel();
				}
			}
			
			/* Pause and restart with large delay */
			if (typeof this.timeout !== 'undefined') {
				clearTimeout(this.timeout);
			}
			
			this.goToSlide(index);
			
			this.timeout = setTimeout(this.begin.bind(this), this.options.delay * 2);
		
	},
	goToSlide: function(index){

		if (index < 0 || index >= this.slides.length) {
			index = 0
		}
		
		if (this.currentSlideIndex !== index) {
			this.fadeEffect = Effect.Fade(this.slides[this.currentSlideIndex]);
			this.appearEffect = Effect.Appear(this.slides[index]);
			
			this.buttons.each(function(e, i) {
				if (i != index) {
					e.up(0).removeClassName('on');
				}
			});
			this.buttons[index].up(0).addClassName('on');
			
			this.currentSlideIndex = index;
		}

	},
	showNextSlide: function(){
		this.goToSlide(this.currentSlideIndex + 1);
		this.timeout = setTimeout(function(){
			this.showNextSlide();
		}.bind(this), this.options.delay);
	},
	begin: function(){
		this.timeout = setTimeout(this.showNextSlide.bind(this), this.options.delay);
	}
});
