$(function(){
	// optional images array, if empty will use just the elements already in slideshow div.
	var imgs = ['img/gallery/9.jpg','img/gallery/2.jpg','img/gallery/3.jpg','img/gallery/4.jpg','img/gallery/5.jpg','img/gallery/6.jpg','img/gallery/7.jpg','img/gallery/8.jpg'];
	var delay = 4000; /* Delay between animations */
	var fade = 2800; /* Duration of fade in animation */
	var curLayer = 0; /* start from layer number */
	var zIndex = 2; /* z-index value. layers will use this value +/- 1 either side */
	/**
	 * Add additional images to slideshow div
	 */
	$.each(imgs, function(i, url){
		$('<img/>').attr('src',url).appendTo($('#slideshow'));
	});
	/**
	 * Get childNode elements to be cycled though. Initialize with lowest zindex and 0 opacity.
	 */
	var layers = $('#slideshow').children().each(function(){
		$(this).css({zIndex: zIndex, opacity:0});
	});
	/**
	 * Bring Layer to front and Fade in Animation with callback to cycleLayers.
	 */
	var fadeInLayer = function(i){
		$(layers[i]).css({zIndex:zIndex+1}).animate({'opacity':1}, fade, cycleLayers);
	}
	/**
	 * Calculate next image, current image and previous image and layer zindex and opacity accordingly
	 */
	var cycleLayers = function(){
		var l = layers.length, c = curLayer;
		$(layers[c<=0?l-1:c-1]).css({opacity:0, zIndex:zIndex-1});
		$(layers[c=curLayer=c>=l?0:c]).css({opacity:1,zIndex:zIndex});
		setTimeout(function(){ fadeInLayer(c+1==l?0:c+1); ++curLayer;}, delay);
	}
	/**
	 * Start the cycle layer process.
	 */
	cycleLayers();
});
