/***
module_cycle is an addon to toggleTab (may be replaced by mootools tabswapper) that cycles
through each tab automatically, then goes back the first one and stops. Each new tab "click"
is introduced by a fadeIn.
params:
-container: The id of the element that contains the tabbed elements
-modules: An array containing the ids of the modules that belong to each tab
***/

function moduleCycle(container) {
	// wait represents the time between clicks/fades
	var wait = 5000;
	var i = 1;
	timers = new Array();

	var modules = $(container).getElements('.section .body');

	timers.push(setInterval(
		function () {
			// fadeIn uses seconds, not milliseconds
			fadeIn(modules[i], (wait/6000));
			// toggleTab uses 1 as its initial tab, so go right to 2 at the beginning
			toggleTab(container, ++i);
		}, wait));

	// Return to the first tab
	timers.push(setTimeout(
		function () {
		fadeIn(modules[0], (wait/6000));
		toggleTab(container, 1);
		clearIntervals();
	}, (wait * modules.length)));
	
	delay (function () {
		clearIntervals();
	}, (wait * modules.length));
	
	$(container).getElements('li a').each( function(tab) {
		tab.addEvent('click', function(e) {
			clearIntervals();
		});
	});
	
	$$('a.btn').addEvent('click', function(e) {
		clearIntervals();
	});
}

function clearIntervals() {
	for (var j = 0; j < timers.length; j++) {
		clearInterval(timers[j]);
		clearTimeout(timers[j]);
	}
	timers = new Array();
}

// Example implementation, found in templates/modules/vital_stats/body.tpl
// module_cycle('vital_stats', new Array('meta_module_recent_buzz', 'meta_module_meta_score', 'meta_module_recent_topics'));
