$(document).ready( function() { initBuzzImage(); });

function initBuzzImage()
{
	//Hide the static image
	$(".projintro img").css("display", "none");
	
	//Render the list ready to do the fading
	$("#imageFader").html('<ul class="gallery"></ul>');
	
	//Grab all of the project images
	var projectList = $("#projectList li");
	$.each(projectList, function() {
		var imgSrc = $(this).find("img").attr("src");
		imgSrc = imgSrc.replace(/_s/g,"_l");
		var linkUrl = $(this).find("a").attr("href");
		$("#imageFader ul").append('<li><a href="' + linkUrl + '"><img src="' + imgSrc + '"/></a></li>');						 
	});
	
	initGallery();
	initCarousel(0);
}

var inTransition = false;
var pause = 0;
var elementTimer;
	
function initGallery()
{	
	//Fade all the images bar the first
	$(".gallery li").not("li:nth-child(1)").fadeTo(1,0);
	//Add the hover events
	$("#projectList li").hover(function() { pause = 1; showImage(this); },function() { pause = 0; hideImage(this); });
	update();
}

function showImage(what)
{
	inTransition = true
	var imageLis = $(".gallery li");
		
	var controllerLis = $("#projectList li");
	for (var i=0; i<imageLis.length; i++)
	{
		if (controllerLis[i] == what)
		{
			$(imageLis).fadeTo(1, 0);
			$(imageLis[i]).show();
			$(imageLis[i]).fadeTo(300, 1, function(){update();});
			
			$(controllerLis).css("background-color", "transparent");
			$(controllerLis[i]).css("background-color", "#eeeeee");
		}
	}
}

function hideImage(what)
{
	var imageLis = $(".gallery li");
		
	var controllerLis = $("#projectList li");
	for (var i=0; i<imageLis.length; i++)
	{
		if (controllerLis[i] == what)
		{
			currentElement = i;
		}
	}
}

function update()
{
	inTransition = false;
}
 
function initCarousel(what)
{
	//reset the element counter
	currentElement = -1; //0 to skip heading li		
	clearTimeout(elementTimer);
	changeElement(5000);
}

function changeElement(nextChange)
{	
	if (pause != 1)
	{
		var x = $(".gallery li");
		var spd = 1000;
		
		$(x[currentElement]).fadeTo(spd,0);
		$("#projectList li").css("background-color", "transparent");
		currentElement ++;
		if (currentElement >= x.length)
		{
			currentElement = 0;
		}
		$(x[currentElement]).fadeTo(spd,1);
		
		var projectList = $("#projectList li");
		$(projectList[currentElement]).css("background-color", "#eeeeee");
	}
	elementTimer = setTimeout("changeElement(" + nextChange + ")",nextChange);
}
