var current = 0;
var createSlideShowId;
var delay = 8500;
var max;
var pause = false;
var imgpause = false;

function linkClicked(l, manual) {
	if (!l) return;
	
	n = l.id.replace(/featuredlink/, '');
	
	if (current == n) return;
	
	if (manual) {
		clearInterval(createSlideShowId);
		var queue = Effect.Queues.get('txtq');
		queue.each(function(effect) { effect.cancel(); });
		queue = Effect.Queues.get('imgq');
		queue.each(function(effect) { effect.cancel(); });
	}
	
	$('featuredlink'+current).style.color = '';
	$('featuredlink'+n).style.color = '#f93';
	
	new Effect.Fade('featuredimage'+current, { duration: 0.8, queue: { position: 'end', scope: 'imgq' } });
	new Effect.Appear('featuredimage'+n,     { duration: 0.8, queue: { position: 'end', scope: 'imgq' } });
	
	new Effect.Appear('featuredtextwhite',   { duration: 0.8, queue: { position: 'end', scope: 'txtq' } });
	new Effect.Fade('featuredtext'+current,  { duration: 0.1, queue: { position: 'end', scope: 'txtq' } });
	new Effect.Appear('featuredtext'+n,      { duration: 0.1, queue: { position: 'end', scope: 'txtq' } });
	new Effect.Fade('featuredtextwhite',     { duration: 0.8, queue: { position: 'end', scope: 'txtq' } });

	current = n;
	
	// restart the slideshow
	if (manual) createSlideShowId = setInterval(createSlideShow, delay);
}

function initSlideshow() {
	if (!$('featuredlinkcontainer')) return;
	
	var as = $('featuredlinkcontainer').getElementsByTagName('a');
	max = as.length - 4;
	
	if (max < 1) return;
	
	// start the slideshow
	createSlideShowId = setInterval(createSlideShow, delay);
}

function createSlideShow() {
	if (pause || imgpause) {
		return;
	}

	var next = parseInt(current) + 1;
	if (next > max) next = 0;
	linkClicked($('featuredlink'+next));
}

function backClicked() {
	// loop around instead
	//if (current == 0) return;
	//var next = parseInt(current) - 1;
	var next = (current == 0) ? max : parseInt(current) - 1;
	
	linkClicked($('featuredlink'+next), true);
}

function forwardClicked() {
	// loop around instead
	//if (current == max) return;
	//var next = parseInt(current) + 1;
	var next = (current == max) ? 0 : parseInt(current) + 1;
	
	linkClicked($('featuredlink'+next), true);
}

function pauseClicked(a) {
	pause = !pause;
	a.innerHTML = pause ? 'play' : 'pause';
}

function imageOver() {
	if (pause) return;
	
	imgpause = true;
	$('pauselink').innerHTML = 'paused...';
}

function imageOut() {
	if (!imgpause) return;
	
	imgpause = pause = false;
	$('pauselink').innerHTML = 'pause';
}

window.onload = initSlideshow;
