(function(){
	
	var slideshowplaying = true,
		timeout = 0;
	
	// Adding classes for first child and last child.   Using native pseudo classes meant pie stopped working properly.
	$('ul#main li:first-child').addClass("first");
	$('ul#main li:last-child').addClass("last");
	
	// IMAGE GALLERY
	
	// Create holder
	$('<div class="holder"></div><div class="controls"><div class="credit"></div></div><div class="overlay"></div>').prependTo($('section#image'));
	
	drawimage(0);
	
	function drawimage(i) {
		
		var divContainer = $('div.ngg-galleryoverview div.ngg-gallery-thumbnail-box').eq(i),
			aTag = divContainer.find("a");
				
		// Switch off old item.
		$('div.ngg-gallery-thumbnail a.on').removeClass("on")
		
		// Switch on this item				
		aTag.addClass("on");
								
		// credit off
		creditOff();
				
		// Renders image i on stack
		$("<img />")
		.load(function () {
			
			var size,
				credit;
						
			// Add the new loaded one
			$(this)
			.appendTo("div.holder")
			.hide()
			.fadeIn("fast", function() { 
				if (aTag.attr("title").length > 1){
					credit = aTag.attr("title").replace("\n", "<br>");
					creditOn(credit);
				} 
			});
								
			size = $("div.holder img").size() ;
			if (size >= 3) {
				$("div.holder img:eq(" + (size- 3) + ")").remove();
			}	
								
			if (slideshowplaying) {
				slideShowStart();
			}
			
			})
		.error(function () {  alert("Image large load error: " + img); }) 
		.attr({src :  aTag.attr("href")})			
	}
	function creditOff() {
		$("div.credit").animate({left:"-300px"}, 200);
	}
	function creditOn(content) {
		$("div.credit")
		.animate( {left: "0px" }, 200)
		.html(content);		
	}
	function slideShowStart()
	{
		slideShowStop();
		timeout = window.setTimeout(slideShowAdvance,5000);
	}
	function slideShowStop()
	{
		window.clearTimeout(timeout);	
	}
	function slideShowAdvance()
	{
		var currentpic = $('div.ngg-gallery-thumbnail').index( $('a.on').parent() ),
			nextpic = currentpic + 1;
		if (nextpic == $('div.ngg-gallery-thumbnail').size() ) {
			nextpic = 0;
		}	
		drawimage(nextpic);	
	}	
}());
