$(function()
{
	var switchFadeDuration = 'fast';
	
	// Convert to thumbnails.
	var projectLinks = $('#project-links a');
	projectLinks.each(function(index)
	{
		var projectId = getProjectId(this.id);
		$('li#project-' + projectId + '-gallery img').shadowGallery(
		{
			links: true,
			galleryId: projectId
		});
	});
	
	// Hide the galleries initially; must be done after thumbnail generation.
	var title = $('#gallery-title');
	var galleries = $('#galleries > li.gallery');
	galleries.hide();
	
	// Show the first gallery and first image thereof by default.
	$('#galleries > li.gallery:first-child').show().find('img');
	title.text($('#project-links li:first-child a').text());
	//title.textReplace();
	
	projectLinks.click(function()
	{
		// Look up the corresponding gallery list item and show it.
		var projectName = $(this).text();
		var projectId = getProjectId(this.id);
		var gallery = $('#galleries > li#project-' + projectId + '-gallery');
		if (gallery.is(':visible'))
		{
			// Already visible, so stop here.
			return false;
		}
		
		var callback = function()
		{
			gallery.find('img').renderThumbnails();
		};
		if (galleries.is(':visible'))
		{
			title.fadeOut(switchFadeDuration, function()
			{
				title.text(projectName);
				//title.textReplace();
				title.fadeIn(switchFadeDuration);
			});
			galleries.filter(':visible').fadeOut(switchFadeDuration, function()
			{
				title.text(projectName);
				//title.textReplace();
				gallery.fadeIn(switchFadeDuration, callback);
			});
		}
		else
		{
			title.text(projectName);
			//title.textReplace();
			gallery.fadeIn(switchFadeDuration, callback);
		}
		
		return false;
	});
});

function getProjectId(elementId)
{
	return /\d+/.exec(elementId)[0];
}