// Image Rotation
// Dat Chu - Computation Biomedicine Lab - http://cbl.uh.edu
Element.extend({
	show : function() {
		this.setStyle("display","block");
	},

	hide : function() {
		this.setStyle("display","none");
	}
});

var Rotator = new Class({
	prev: '',
	next: '',
	targets: '', // targets to rotate (usually divs)
	activators: '', // clickable links that initiate the rotation
	effects: '',
	settings: '', // kept the lists of options for a rotator
	periodical: '', // kept the periodical object that start auto-rotation
	isRunning: false,
	options: {
		random : false,
		activators: false,
		delay: 6000,
		transition_duration: 1500,
		play_button: null,
		pause_button: null
	},
	initialize: function(targets, options){
		this.setOptions(options); // set default options

		this.activators = this.options.activators;
		this.targets = targets;
		
		// build the array of effects + hook up the activators
		this.buildEffects((this.options.random)?true:false);
	},
	start: function(){
		this.periodical = this.rotate.periodical(this.options.delay,this);
		this.isRunning = true;
		(this.options.play_button) && this.options.play_button.show();
		(this.options.pause_button) && this.options.pause_button.hide();
	},
	stop: function(){
		$clear(this.periodical);
		this.isRunning = false;
		(this.options.play_button) && this.options.play_button.hide();
		(this.options.pause_button) && this.options.pause_button.show();
	},
	buildEffects: function(isStartRandom){
		//random starting point
		this.prev = (!isStartRandom) ? 0 : (Math.floor(Math.random() * this.targets.length));
		this.next = (this.prev+1) % this.targets.length;
		eff = new Array;
		for(i=0;i<this.targets.length;i++)
		{
			eff[i] = this.targets[i].effect('opacity',{duration:this.options.transition_duration});
			
			// hook the activator
			this.activators[i].addEvent('click', function(index){
				if (index != this.prev){
					this.next=index; // if someone intentionally call i out-of-bound? :(
					this.stop();
					this.rotate();
				}
			}.pass(i,this)); // there is no other way to pass the right index
			
			if (i!=this.prev){
				eff[i].hide(); // hide all elements except current one
			} else {
				this.activators[i].addClass('active');
			}
		}
		this.effects = eff;
	},
	rotate: function(){
		this.effects[this.prev].start(1,0); //hide prev
		this.activators[this.prev].removeClass('active');
		this.effects[this.next].start(0,1); //show next
		this.activators[this.next].addClass('active');
		//repeat
		this.prev = this.next;
		this.next = (this.next +1) % this.effects.length;
	}
});

Rotator.implement(new Options, new Events);