$(function() {
	
	var speed = 5000; 											//rotatie snelheid in MS
	var afbeeldingen = new Array("1.jpg", "2.jpg", "3.jpg");	//array van afbeeldingen
	var imagefolder = siteRoot + "images/visuals/" + getHeaderType();			//map van de afbeeldingen
	
	afbeeldingen.sort(function() {return 0.5 - Math.random()}); //randomize afbeeldingen

	/* INIT */
	if($("body").hasClass('vervolgpagina')){
		return ;
	}
	
	$("body .header-foto").append("<div class='header-foto-container-2'></div><div class='header-foto-container-1'></div>");

	var activeContainer = 2;
	var currentImg = 0;
	var animating = false;
	
	setTimeout(function(){
		navigate();
		preload();
	}, 300);
	interval = setInterval(function() {
		navigate();
		preload();
	}, speed);
	
	
	function navigate() {
		// Check if no animation is running. If it is, prevent the action
		if(animating) {
			return;
		}
		currentImg++;
		if(currentImg == afbeeldingen.length + 1) {
			currentImg = 1;
		}	
		// Check which container we need to use
		var currentContainer = activeContainer;
		if(activeContainer == 1) {
			activeContainer = 2;
		} else {
			activeContainer = 1;
		}
		showImage(afbeeldingen[currentImg - 1], currentContainer, activeContainer);
	};
	
	function preload(){
		preloadImg = currentImg+1;
		if(preloadImg == afbeeldingen.length + 1) {
			preloadImg = 1;
		}
		if($(".preload-"+preloadImg).length == 0){
			$("<img src='"+imagefolder+"/"+(afbeeldingen[preloadImg-1])+"' class='preload-"+preloadImg+"' />").css({'visibility':'hidden','position':'absolute','top':'0px','left':'0px','width':'1px'}).appendTo("body");
		}
	}
	
	var currentZindex = -1;
	function showImage(photoObject, currentContainer, activeContainer) {
		animating = true;
		// Make sure the new container is always on the background
		currentZindex = $(".header-foto-container-" + currentContainer).css("z-index");
		activeZindex = $(".header-foto-container-" + activeContainer).css("z-index");
		
		// Set the background image of the new active container
		$(".header-foto-container-" + activeContainer).css({
			"background-image" : "url("+imagefolder+"/" + photoObject + ")",
			"display" : "block",
			"z-index" : currentZindex
		});
		
		$(".header-foto-container-" + currentContainer).css("z-index", activeZindex);
		
		// Fade out the current container
		// and display the header text when animation is complete
		$(".header-foto-container-" + currentContainer).fadeOut(3000, function() {
			animating = false;
		});
	};
	
	function getHeaderType(){
		var names = $("body").attr('class').split(' ');
		var len = names.length;
		for(var i=0; i<len; i++){
			if(names[i].substr(0,5) == "body_"){
				var newName = (names[i].split('_'))[1];
				if(newName != 'home'){ //voor de verwarring
					return newName;
				}
			}
		}
		return 'overons';
	}
	
});
