var illustrations = null;
var switchTimeout = null;
var currentItem = -1;
var delay = 7000; // msecs
var nav, prev, play, pause, next; // buttons

// switch

function switchToImage(number) {
	Effect.Fade("image-" + currentItem);
	Effect.Appear("image-" + number);
	currentItem = number;
}

function switchToPrevImage() {
	switchToImage(((currentItem - 1) < 1 ? illustrations.length : currentItem - 1));
}

function switchToNextImage() {
	switchToImage(((currentItem + 1) > illustrations.length ? 1 : currentItem + 1));
}

// button

function prevHandler() {
	pauseHandler();
	switchToPrevImage();
}

function playHandler() {
	advance();
	try {
		nav.replaceChild(pause, play);
	} catch (e) {;}
		
}

function pauseHandler() {
	window.clearTimeout(switchTimeout);
	try {
		nav.replaceChild(play, pause);
	} catch (e) {;}
}

function nextHandler() {
	pauseHandler();
	switchToNextImage();
}

// automatic

function advance() {
	switchToNextImage();	
	switchTimeout = window.setTimeout(advance, delay);
}

// init code ------------------------------------------------------------------

illustrations = document.getElementById("image-list").getElementsByTagName("li");
currentItem = 1; // explicitly restate that we're starting from the top
	
if (illustrations.length > 1) {
	for (i = 1; i < illustrations.length; i++) {
		illustrations[i].style.display = "none";
	}
	
	// spawn navigation...

	navLink = document.createElement("a");
	navLink.setAttribute("href", window.location + "#");
	
	prevLink = navLink.cloneNode(true);
	prevLink.textContent = "« prev";
	prevLink.id = "image-prev";
	prev = document.createElement("span");
	prev.appendChild(prevLink);
	
	playLink = navLink.cloneNode(true);
	playLink.textContent = "play";
	playLink.id = "image-play";
	play = document.createElement("span");
	play.appendChild(playLink);
	
	pauseLink = navLink.cloneNode(true);
	pauseLink.textContent = "pause";
	pauseLink.id = "image-pause";
	pause = document.createElement("span");
	pause.appendChild(pauseLink);
	
	nextLink = navLink.cloneNode(true);
	nextLink.textContent = "next »";
	nextLink.id = "image-next";
	next = document.createElement("span");
	next.appendChild(nextLink);
	
	nav = document.createElement("div");
	nav.className = "nav";
	nav.appendChild(prev);
//	nav.appendChild(play); // we start off playing
	nav.appendChild(pause);
	nav.appendChild(next);
	
	// event handlers must be defined down here, otherwise we get complaints
	// about how various objects have no properties, so on and so forth
	
	prevLink.onclick = prevHandler;
	playLink.onclick = playHandler;
	pauseLink.onclick = pauseHandler;
	nextLink.onclick = nextHandler;
	
	document.getElementById("illustration").appendChild(nav);
	
	// set timeout for image switch
	
	switchTimeout = window.setTimeout(advance, delay);
}
