
/* A collection of Timers, the index is the id of the element being rotated */
var timers = new Array();
/* The intervals for the timers */
var timerIntervals = new Array();
/* A default interval to go with if none is set */
var defaultInterval = 10;

function debug(texty) {
	var debugbox = document.getElementById("debug");
	if (debugbox) {
		debugbox.innerHtml=texty;
	} else if (window.console !== undefined) {
		window.console.log(texty);
	}
}

function clearDebugConsole() {
	debugbox = document.getElementById("debugconsole");
	debugbox.innerHTML = "Debug Console\n"+Date();
}

function setHighlight() {}

function startRotation(elementId, interval) {
	debug("Setting timerInterval for " + elementId + " at " + interval + " seconds");
	timerIntervals[elementId] = interval;
	return goRotate(elementId);
}

function goRotate(elementId) {
	/* Make sure we don't wind up with 2 (or more) timers running */
	if (timers[elementId] != null) {
		clearInterval(timers[elementId]);
		timers[elementId] = null;
	}
	/* Make sure the interval has been set */
	if ((typeof timerIntervals[elementId])!='number') {
		timerIntervals[elementId] = defaultInterval;
	}
	/* Start the timer */
	debug("Starting a Rotation timer at " + timerIntervals[elementId] + " seconds for " + elementId);
	timers[elementId] = setInterval("rotationTick('"+elementId+"')",1000*timerIntervals[elementId]);
}

function rotationTick(elementId) {
	//clearDebugConsole();
	debug("Doing rotation for " + elementId);
	// Do it
	var divs = document.getElementById(elementId).getElementsByTagName("div");
	var i;
	var n;
	var found=false;
	for (i=0 ; i < divs.length ; i++) {
		if (divs[i].className == "highlighted") {
			found=true;
			divs[i].className="regular";
			n = (i+1)%divs.length;
			debug("Setting position "+n+" to the new highlighted position.");
			divs[n].className = "highlighted";
			i = divs.length+1;
		}
	}
		if (!found) { // No highlighted div was found, setting the first div highlighted
			divs[0].className = "highlighted";
		}
}

function rotationHighlight(elementId) {
	var element = document.getElementById(elementId);
	if (element) {
		highlightMe(element);
	}
}

function highlightMe(element) {
	var tagName = element.tagName;
	var siblings = element.parentNode.getElementsByTagName(tagName);
	var i;
	for (i=0 ; i < siblings.length ; i++) {
		siblings[i].className="regular";
	}
	element.className="highlighted";
}

function pauseRotation(element) {
	debug("Pausing rotation for " + element.id);
	clearInterval(timers[element.id]);
}

function resumeRotation(element) {
	debug("Resuming rotation for " + element.id);
	goRotate(element.id);
}

