var image_link;
var displayed_link;

var mainView = $(document.createElement('li')).append($(document.createElement('a')).text('main view').click( function() { display(image_link); } ))

function GalleryImage(link)
{
	this.root = $(link).parents('a > img')[0];
	this.src = link.src.split(thumbpath)[1];
	this.name = link.alt;
	this.description = $(link).siblings('.description');
}

function set_image(link,new_src)
{
	var galleryRoot = $(link).parents('.gallery')[0];
	
	$(galleryRoot).find(".viewingPane img").fadeOut('medium' , function() { swap_src(this , new_src); });
	function swap_src(image , new_src) 
	{ 
		$(image).attr('src' , new_src).animate(
		{
			opacity:1.0
		} 
		, 500 , function() 
			{ 
				$(this).fadeIn('medium');
			}
		); 
	}
}

function display(link)
{
	image_link = link;
	var galleryRoot = $(link).parents('.gallery')[0];
	var image = new GalleryImage($(link).parent().find('img')[0]);
	
	$(galleryRoot).find('.viewingPane img').attr('title' , image.name);
	
	displayed_link = null;
	
	set_image(link , imagepath + image.src);
	
	var descDiv = $(galleryRoot).children('.description');
	$(descDiv).replaceWith(image.description.clone(true));
	
	return true;
}

function  showDetail(link)
{
	if(displayed_link) $(displayed_link).removeClass('shown');
	else $(link).parents('ul.details').append(mainView.clone(true).hide().slideDown('slow'));
	displayed_link = link;
	$(displayed_link).addClass('shown');
	set_image(link , detailpath + $(link).children('span').text());
}
