// JavaScript Document

var dsSlideshow = Class.create({
	initialize: function(slideClass) {
		this.options = $H({
		  wait: 5000,
		  fadetime: 1,
		  queue:'dsSlideQueue',
		  loop:true
		}).update(arguments[1] || {});
		this.slides = $$(slideClass);
		this.loop = this.options.get('loop');
		this.wait = this.options.get('wait');
		this.queue = this.options.get('queue');
		this.fadetime = this.options.get('fadetime');
		this.loopcount=0;
		this.initLinks();
		this.timer = setInterval(this.show.bind(this) , this.wait);
	},
	
	show: function() {
		Effect.Fade(this.slides[this.loopcount], { duration:this.fadetime, from:1.0, to:0.0, queue:{scope:this.queue, position:'end'}, afterFinish:function() {
				this.loopcount++;
				if ( this.loopcount == this.slides.length ) {
					if (this.loop) {
						this.loopcount=0; // Loop
					} else {
						//this.loopcount=0; //Reset to start
						this.loopcount=this.get_random_num(this.slides.length); //Reset to random
						clearInterval(this.timer); // Kill the Looping
					}
				}
				Effect.Appear(this.slides[this.loopcount], { duration:this.fadetime, from:0.0, to:1.0, queue:{scope:this.queue, position:'end'} });
			}.bind(this)
		});
	},
	
	jump: function(slide) {
		clearInterval(this.timer);
		Effect.Fade(this.slides[this.loopcount], { duration:this.fadetime, from:1.0, to:0.0, queue:{scope:this.queue, position:'end'}, afterFinish:function() {
				this.loopcount = --slide;
				if ( this.loopcount == this.slides.length ) this.loopcount=0;
				Effect.Appear(this.slides[this.loopcount], { duration:this.fadetime, from:0.0, to:1.0, queue:{scope:this.queue, position:'end'} });
			}.bind(this)
		});
		//setTimeout(this.restart.bind(this) , this.wait);
	},
	
	restart: function() {
		this.timer = setInterval(this.show.bind(this) , this.wait);
	},
	
	initLinks: function() {
		anchors = $$('a[rel]');
		for (var i=0; i<anchors.length; i++){
			linky = anchors[i];
			relAttribute = String(linky.getAttribute('rel'));
			if (relAttribute.toLowerCase().match('slideshow')){
				slidenum = relAttribute.toLowerCase().split("[",2);
				slidenum = slidenum[1].split("]");
				linky.removeAttribute('href');
				Event.observe(linky, 'click', function(obj,slide) {this.jump(slide);return false;}.bindAsEventListener(this,slidenum[0]) );
			}
		}

	},
	
	get_random_num: function(maxValue) {
	 day = new Date();
	 hour = day.getHours();
	 min = day.getMinutes();
	 sec = day.getSeconds();
	 return (((hour + 1) * (min + 1) * sec) % maxValue) + 1;
	}
	
});

Event.observe(window, 'load', function(){
	new dsSlideshow('#show .section',{wait:6000, fadetime:2, loop:true});
});