var TimeToFade = 330.0;
var fading = 0;
var lastSelected = 1;
var autoRotate;

autoRotate = setTimeout("fade(2)", 4000);

function fade(eid) {
	if (lastSelected == eid) return;
	if (fading == 1) return;
	var element = document.getElementById('slide_' + eid);
	if (element == null) return;
	if (element.style.zIndex > 0) return;
	element.style.zIndex = 2;
	fading = 1;
	
	clearTimeout(autoRotate);
	
	document.getElementById('slide_' + lastSelected + '_button').style.background = "url('img/menu_back_off_" + lastSelected + ".jpg')";
	document.getElementById('slide_' + lastSelected + '_button').style.marginLeft = "14px";
	document.getElementById('slide_' + lastSelected + '_button').style.paddingLeft = "10px";
	lastSelected = eid;
	document.getElementById('slide_' + lastSelected + '_button').style.marginLeft = "0px";
	document.getElementById('slide_' + eid + '_button').style.paddingLeft = "24px";
	document.getElementById('slide_' + eid + '_button').style.background = "url('img/menu_back_on.jpg')";

	element.FadeState = 1;
	element.FadeTimeLeft = TimeToFade;
	setTimeout("animateFade(" + new Date().getTime() + ", 'slide_" + eid + "')", 33);
}

function forceFadeOn(eid) {
	if (lastSelected == eid) return;
	clearTimeout(autoRotate);
	i = parseInt(eid);
	if (fading == 1) {
		autoRotate = setTimeout("fade(" + i + ")", 500);
	}
	else {
		autoRotate = setTimeout("fade(" + i + ")", 100);
	}
	var element = document.getElementById('slide_' + eid);
	if (element == null) return;
	element.timerLock = true;
}

function forceFadeOff(eid) {
	var element = document.getElementById('slide_' + eid);
	if (element == null) return;
	element.timerLock = false;
}

function animateFade(lastTick, eid) {
	var curTick = new Date().getTime();
	var elapsedTicks = curTick - lastTick;

	var element = document.getElementById(eid);

	if (element.FadeTimeLeft <= elapsedTicks) {
		element.style.opacity = element.FadeState == 1 ? '1' : '0';
		element.style.filter = 'alpha(opacity = ' + (element.FadeState == 1 ? '100' : '0') + ')';

		for (var i = 1; i <= numOfSlides; i++) {
			if (eid != 'slide_' + i) {
				document.getElementById('slide_' + i).style.zIndex = 0;
				document.getElementById('slide_' + i).style.opacity = 0;
				document.getElementById('slide_' + i).style.filter = 'alpha(opacity=0)';
			}
		}
		element.style.zIndex = 1;
		fading = 0;
		var i;
		if (parseInt(lastSelected) == numOfSlides) {
			i = 1;
		}
		else {
			i = parseInt(lastSelected) + 1;
		}
		autoRotate = setTimeout("fade(" + i + ")", (element.timerLock) ? 10000000 : 4000);
	}
	else {
		element.FadeTimeLeft -= elapsedTicks;
		var newOpVal = 1 - (element.FadeTimeLeft / TimeToFade);
		element.style.opacity = newOpVal;
		element.style.filter = 'alpha(opacity=' + (newOpVal * 100) + ')';
		setTimeout("animateFade(" + curTick + ", '" + eid + "')", 33);
	}
}
