/**
 * Rotating Teaser
 * 
 * emjot[mh] 2009
 */
var RotatingTeaser = Class.create( {
	
	/** 
	 *  - name: the name of the RotatingTeaser (ID and IDs of sub-elements depend on this)
	 *  - cycleSeconds: how many seconds to stay on one specific content
	 *  - pauseCycles:  how many cycles to stay on a content before continuing cycling when a content was explicitly navigated to
	 *  - showControls: set to false if you just want the rotation, without any UI controls
	 */
	initialize: function(name, cycleSeconds, pauseCycles, showControls) {
		this.name        = name;
		this.index       = 0;
		this.showControls= showControls;
		this.pauseCycles = Number(pauseCycles);
		this.remainingPauseCycles = 0;
		
		this.contents_id       = this.name + "-contents";
		this.controls_id       = this.name + "-controls";
		this.content_id_prefix = this.name + "-content-";
		this.control_id_prefix = this.name + "-control-"; // if you change this, you need to change the regex in controlClickHandler! (FIXME)

		contents = $(this.contents_id).getElementsBySelector("[class~='rotating-teaser-content']");
		contents.each( function(content){ content.hide(); } );
		
		if (this.showControls) {
			controls = $(this.controls_id).getElementsBySelector("[class~='rotating-teaser-control']");
			for (var i=0; i<controls.length; i++) { this.prepare_control( controls[i] ); };
		}
		
		this.switchTo(0);
		if (Number(cycleSeconds) > 0) {
			this.switchingPE = new PeriodicalExecuter(this.switchToNext.bind(this), Number(cycleSeconds));
		}
	},
	
	prepare_control: function(c) {
		c.removeClassName("active");
		a      = c.down("a");
		a.href = "javascript:void(0);";
		a.observe("click", this.controlClickHandler.bind(this));
	},
	
	controlClickHandler: function(event) {
		id = Selector.findElement(event.element().ancestors(), "[class~='rotating-teaser-control']").readAttribute('id');
		id.scan(/(.+)-control-(\d+)/, 
			function(match){
				index = Number(match[2]);
		});
		this.pauseSwitching(this.pauseCycles);
		this.switchTo(index);
	},
	
	pauseSwitching: function(number_of_cycles) {
		this.remainingPauseCycles = number_of_cycles;
	},
	
	switchToNext: function() {
		if (this.remainingPauseCycles > 0) {
			this.remainingPauseCycles--;
		} else {
			this.switchTo(this.index + 1);
		}
	},

	switchTo: function(index) {
		// possibly correct index so it's not out of range
		contentsCount = $(this.contents_id).getElementsBySelector("[class~='rotating-teaser-content']").length;
		if (index >= contentsCount){
			index = 0;
		} else if (index < 0) {
			index = contentsCount - 1;
		}
		// handle old active elements
		$(this.content_id_prefix + this.index).hide();
		if (this.showControls) {
			$(this.control_id_prefix + this.index).removeClassName("active");
		}
		// set & handle new active elements
		this.index = index;
		$(this.content_id_prefix + this.index).show();
		if (this.showControls) {
			$(this.control_id_prefix + this.index).addClassName("active");
		}
	}
	
});
