WMCRotator = new Class({

	wrapper: null,
	width: null,
	height: null,
	interval: null,
	current: 0,
	timer: null,
	buttons: null,

	initialize: function(id, width, height, interval, show_buttons) {
		this.wrapper = $(id);
		this.width = width;
		this.height = height;
		this.interval = parseInt(interval) * 1000;

		this.elements = this.wrapper.getElements('.content_rotator');

		this.elements.setStyles({
		'width': width,
		'height': height
		});

		this.elements.each(function(el, eli) {
			if(eli > 0) {
				el.setStyle('opacity', 0);
			}
		});
		this.current_box = this.elements[0];

		if(show_buttons) {
			this.add_buttons();
		}
		this.init_timer();
	},

	add_buttons: function() {
		this.buttons = new Array();
		var buttons = this.wrapper.getElement('ul.buttons');

		this.elements.each(function(el, eli) {
			var li = new Element('li').injectInside(buttons);
			var a = new Element('a', {
				'html': eli + 1,
				'href': '#'
			}).injectInside(li);

			a.addEvent('click', this.button_click.bindWithEvent(this));
			this.buttons.push(a);
		}.bind(this));
		this.buttons[0].addClass('active');
	},

	button_click: function(e) {
		var element = e.target;

		this.reset_buttons();
		element.addClass('active');

		this.stop_timer();
		// this.init_timer();
		this.current = element.get('html').toInt() - 1;
		this.show_box();

		return false;
	},

	stop_timer: function(e) {
		$clear(this.timer);
	},

	init_timer: function(e) {
		this.timer = this.timer_loop.periodical(this.interval, this);
	},

	timer_loop: function() {
		if(this.current >= this.elements.length-1) {
			this.current = 0;
		} else {
			this.current++;
		}

		this.show_box();
	},

	reset_buttons: function() {
		this.buttons.each(function(el) {
			el.removeClass('active');
		});
	},

	show_box: function() {
		var next_box = this.elements[this.current];
		new Fx.Morph(this.current_box, {
			duration: 500
		}).start({
			'opacity': [1, 0]
		});

		if(this.buttons) {
			this.reset_buttons();
			this.buttons[this.current].addClass('active');
		}

		new Fx.Morph(next_box, {
			duration: 300
		}).start({
			'opacity': [0, 1]
		}).chain(function() {
			this.current_box = next_box;
		}.bind(this));
	}

});

