
var Rotator = new Class({
Implements: Options,
options: {
	'delay': 7000,
	'holder': $$('.items')[0],
	'elements': 'li',
	'buttonHolder': $$('.buttons')[0],
	'buttons': 'li',
	'shown_z_index': 5,
	'hidden_z_index': 3,
	'transition_length': 1700,
	'morph_styles': ['backgroundColor','color']
},
started: false,
pointer: 0,
shownElement: null,
initialize: function(opts) {
	this.setOptions(opts);
	this.holder = $(this.options.holder);
	this.elements = this.holder.getElements(this.options.elements);
	this.buttonHolder = $(this.options.buttonHolder);
	this.buttons = this.buttonHolder.getElements(this.options.buttons);
	this.buttonMorph = [];
	this.buttons.each(function(el, i) {
        el.addEvent("click", function(ev) {
            var n = this.pointer - 1;
            if(n < 0) n = this.buttons.length-1;

            if(n != i) new Event(ev).stop( );
            this.pointer = i;
            $clear(this.timer);
            this.rotateImage( );
        }.bind(this));
		this.buttonMorph.push(new Fx.Morph(el, {'duration': this.options.transition_length}));
	}.bind(this));
	var selEl = this.buttonHolder.getElement('.selected');
	var unselEl = this.buttonHolder.getElement('.unselected');
	this.selStyles = {};
	this.options.morph_styles.each(function(s) {
		this.selStyles[s] = selEl.getStyle(s);
	}.bind(this));
	this.unselStyles = {};
	this.options.morph_styles.each(function(s) {
		this.unselStyles[s] = unselEl.getStyle(s);
	}.bind(this));								
	
	this.elements.set('tween', {'duration': this.options.transition_length});
	this.elements.setOpacity(0);
	
},
start: function( ) {
	if(!this.started) {
		this.started = true;
		this.timer = this.rotateImage.periodical(this.options.delay, this);
		this.rotateImage();
	}
},
rotateImage: function( ) {										
	var nextElement = this.elements[this.pointer];
	nextElement.setStyle("z-index", this.options.shown_z_index);
	if(this.shownElement) {
		this.shownElement.setStyle("z-index", this.options.hidden_z_index);
		this.shownElement.tween("opacity", 0);
        this.elements.each(function(el, i) {
            if(el == this.shownElement) {
                this.buttonMorph[i].cancel();
                this.buttonMorph[i].start(this.unselStyles);
            }
        }.bind(this));
	}

	nextElement.tween("opacity", 1);
	this.shownElement = nextElement;
    this.buttonMorph[this.pointer].cancel();
	this.buttonMorph[this.pointer].start(this.selStyles);

	this.pointer++;
	if(this.pointer >= this.elements.length) this.pointer = 0;
}
});
						

