var lastFadedIn;
var isFadingIn;

var headerText;
var headerButton;

var fadeInTimeout = new Array();
var nextHeaderTimeout = new Array();

var fadingTimeout;
var documentLocation = '';

function init() {
	headerText = document.getElementById('headerText');
	headerButton = document.getElementById('headerButton');
	setHeaderPlaying();
}

function setHeaderPlaying(fadeInHeader, fadeOutHeader) {
	clearAllTimeouts();
	fadeAllOut();
	
	if(fadeInHeader == undefined) fadeInHeader = 0;
	if(fadeOutHeader == undefined && lastFadedIn != null) fadeOutHeader = lastFadedIn;
	
	if(fadeOutHeader == undefined) {
		headerFadeIn(fadeInHeader);
	} else {
		fadeAllOut();
		fadeInTimeout.push(setTimeout(function() { headerFadeIn(fadeInHeader) }, 200));
	}
	
	var nextHeader = (fadeInHeader < headerText.children.length - 1) ? fadeInHeader + 1 : 0;
	fadeInTimeout.push(setTimeout(function() { setHeaderPlaying(nextHeader, fadeInHeader) }, 10000));
	
	setDocumentLocation(fadeInHeader);
	setButtonSelected(fadeInHeader);
}

function setDocumentLocation(childIndex) {
	var location = headerText.children[childIndex].id;
	location = location.replace("page:", "");
	location = location.replace(":", "/");
	documentLocation = 'http://www.printkiosk.nl/' + location;
}

function clickHeader() {
	document.location = documentLocation;
}

function setButtonSelected(childIndex) {
	for(var i = 0; i < headerText.children.length; i++) {
		var className = (i <= childIndex) ? 'button_selected' : '';
		headerButton.children[i].className = className;
	}
}

function fadeElement(childIndex, from, to, steps, i) {
	if(i == undefined) i = 0;
	var element = headerText.children[childIndex];
	var difference = (from < to) ? to - from : from - to;
	var perStep = difference / steps;
	var value = perStep * i;
	if(to < from) value = Math.max(1 - value, 0);
	setOpacity(element, value);
	i++;
	if(i <= steps && lastFadedIn == childIndex) {
		fadingTimeout = setTimeout(function() { fadeElement(childIndex, from, to, steps, i) }, 20);
	} else if(lastFadedIn != childIndex) {
		setOpacity(headerText.children[childIndex], 0);
	}
}

function setOpacity(element, opacity) {
	element.style.opacity = opacity;
	element.style.filter = 'alpha(opacity='+ opacity * 100 +')';
}

function headerFadeIn(childIndex) {
	clearTimeout(fadingTimeout);
	lastFadedIn = childIndex;
	isFadingIn = childIndex;
	fadeElement(childIndex, 0, 1, 15);
}

function headerFadeOut(childIndex) {
	fadeElement(childIndex, 1, 0, 15);
}

function fadeAllOut() {
	for(var i = 0; i < headerText.children.length; i++) {
		if(headerText.children[i].style.opacity > 0) {
			headerFadeOut(i);
		}
	}
}

function clearAllTimeouts() {
	for(var i = 0; i < fadeInTimeout.length; i++) {
		clearTimeout(fadeInTimeout[i]);
		fadeInTimeout.splice(i, 1);
	}
	for(var i = 0; i < nextHeaderTimeout.length; i++) {
		clearTimeout(nextHeaderTimeout[i]);
		nextHeaderTimeout.splice(i, 1);
	}
}
