var galleryCurrent = 0;
var slideshowInterval;
var slideshowDelay = 5000;
var transitionDuration = 750;
var totalImages = 0;
var loadedImages = 0;

$(document).ready(function()
{
	$('#home_gallery_rounded').append('<ul id="home_gallery"></ul>').hide();
		
	if(gallery.length <= 1) return;
	
	$('#home_gallery_rounded').show().css({'opacity':0});
	
	for(var i=0; i < gallery.length; i++)
	{
		$('#home_gallery').append('<li id="gallery_'+i+'"><a href="#"></a><ul><li><img src="'+gallery[i].thumb+'" alt="" /></li></ul></li>');
	}
	
	$('#home_gallery > li:first a').addClass("active");
	$('#home_gallery > li a').mouseover(function()
	{
		$(this).next("ul").fadeIn();
	})
	.mouseout(function()
	{
		$(this).next("ul").hide();
	})
	.click(function(e)
	{
		e.preventDefault();
		clearInterval(slideshowInterval);
		slideshowInterval = setInterval(gallery_next, slideshowDelay+transitionDuration);
		gallery_select(parseInt($(this).parent().attr('id').match(/\d+/)[0]));
	});
	
	$('#home_gallery > li > ul').hide();
	
	$('#home_gallery_rounded').width(
		gallery.length * $('#home_gallery > li').width()
	);
	
	preloadImages();
});

function preloadImages()
{
	totalImages = $('#photoshow_pictures li > img').length;
	loadedImages = 0;
	$('#photoshow_pictures li > img').each(function()
	{
		var img = new Image();
		$(img).load(imageLoaded);
		img.src = $(this).attr('src');
	});
}

function imageLoaded()
{
	if(++loadedImages == totalImages)
	{
		$('#home_gallery_rounded').css({'opacity':1}).hide().fadeIn('fast');
		slideshowInterval = setInterval(gallery_next, slideshowDelay+transitionDuration);
	}
}

function gallery_next()
{
	galleryCurrent++;
	if(galleryCurrent == gallery.length) galleryCurrent = 0;
	
	gallery_select(galleryCurrent);
}

function gallery_select(id)
{
	$('#home_gallery > li a').removeClass('active');
	$('#gallery_'+id+' a').addClass('active');
	
	$('#photoshow_right > ul').animate({
		'left': -(543*id)+'px'
	}, transitionDuration);
	
	$('#photoshow_caption').fadeOut('fast', function()
	{
		$('#photoshow_caption').fadeIn().html(gallery[id].caption);
	});
	
	galleryCurrent = id;
}