// JScript source code

var sections, index;
var interval, lock = false, paused = true;

function prepare()
{
	sections = new Array(
		document.getElementById("lockerroom"),
		document.getElementById("gym"),
		document.getElementById("relax"),
		document.getElementById("cafe")
	);
	index = 0;
	togglePlay();
}

function togglePlay()
{
	// Terminate this thread if another thread locks or if already playing 
	if (lock)
	{
		return;
	}
	
	lock = true;

	if (paused) {
	    next();
	    interval = window.setInterval("next()", 7000);
	    window.status = "Playing";
	    $('#buttonPlayPause').text('Pausa bildspel');
	    paused = false;
	} else {
	    window.clearInterval(interval);
	    window.status = "Paused";
	    $('#buttonPlayPause').text('Starta bildspel');
	    paused = true;
	    lock = false;
	}
}

function redirect(toLayer)
{
	// Terminate this thread if another thread locks
	if (lock)
	{
		return;
	}
	
	lock = true;

	// Change pause/play-icons, update statusbar and terminate possible thread
	window.clearInterval(interval);
	window.status = "Playing";
	
	shift(toLayer);

	// Start a new interval
	interval = window.setInterval("next()", 10000);
	paused = false;
}

function next()
{
	if (index == (sections.length - 1))
	{
		shift(0);
	}
	else
	{
		shift(index + 1);
	}
}

function shift(newIndex)
{
    $(sections[index]).fadeOut(1500, function() { $(sections[newIndex]).fadeIn(1500); lock = false; });
	index = newIndex;	
}
