// Speed of the automatic slideshow
var slideshowSpeed = 10000;
var initFadeDelay = 500;


// -------------------------------------------------------------------------------------------------------------------------

function setURL(url) {
	URL = url;
	}

// -------------------------------------------------------------------------------------------------------------------------

$(document).ready(function() {
	var interval;
	var interval2;
	var activeContainer = 1;	
	var currentImg = 0;
	var URL;
	var animating = false;
	$("#headerimg1").css({"display":"none"});	// hide the image (show when first is preloaded)
	$.preloadImages(photos); // preload them photos


	$('.clientimg').hide();
	$('.clientimg').delay(100).fadeIn('slow');


	$('#clickableregion').click(function(){
		if (URL!=undefined) window.location = URL;
		});
	
	
	var navigate = function(direction) {
		// Check if no animation is running. If it is, prevent the action
		if(animating) {
			return;
		}
			
		// Check which current image we need to show
		if(direction == "next") {
			currentImg++;
			if(currentImg == photos.length + 1) {
				currentImg = 1;
			}
		} else {
			currentImg--;
			if(currentImg == 0) {
				currentImg = photos.length;
			}
		}
		
		// Check which container we need to use
		var currentContainer = activeContainer;
		if(activeContainer == 1) {
			activeContainer = 2;
		} else {
			activeContainer = 1;
		}
		
		showImage(photos[currentImg - 1], currentContainer, activeContainer);
		
	};
	var currentZindex = -1;
	var showImage = function(photoObject, currentContainer, activeContainer) {
		animating = true;	
		currentZindex--;
		URL = photoObject.url;
		$("#headerimg" + activeContainer).css({
			"background-image" : "url(" + photoObject.image + ")",
			"display" : "block",
			"z-index" : currentZindex
		});	
		
		$("#headerimg" + currentContainer).fadeOut(function() {
			setTimeout(function() {
				// post animation stuff here
				animating = false;
			}, 500);
		});
	};
	
	
	
	interval = setInterval(function() {
		navigate("next");
	}, slideshowSpeed);

	interval2 = setInterval(function() {
		
		$("#headerimg1").fadeIn(1500, function () {
			$("#headerimg1").removeAttr("display")
			});
		clearInterval(interval2);
	}, initFadeDelay);
	

});

// -------------------------------------------------------------------------------------------------------------------------

jQuery.preloadImages = function(ph) {
	var cache = [];
	for(var item in ph) {
		var obj = ph[item];
		var cacheImage = document.createElement('img');
	    cacheImage.src = obj.image;
	    cache.push(cacheImage);
	}
	
}

