$(function()
{
    $("a[class='galleryLink']").click(function() {
          var imageSource = $(this).attr("rel");
		  var id = $(this).attr("title");
          $("#gallery").addClass("loading");
          showImage(imageSource, id);
          return false;
     });
});

function showImage(src, id) {
	var captionNode = $(".galleryCaption");
	if (captionNode!=null) captionNode.fadeOut("normal");

	$("#gallery #photo img").fadeOut("normal", function(){
		$("#gallery #photo img").remove(); 
		captionNode = $(".galleryCaption div");
		if (captionNode!=null) captionNode.remove(); 
					
		var newImg = new Image();
		$(newImg)
			.load(function() {
				$("#gallery").removeClass("loading");
				$("#gallery #photo")
					.hide()
					.prepend(newImg);		// We 'prepend' in case the caption div is in the same #photo container.
				
				var caption = getCaption(id);
				if (caption != null) {
					$(".galleryCaption").append("<div>" + caption + "</div>")
						.find("div")
						.addClass("caption");
					$(".galleryCaption").fadeIn("normal");
				}
				$("#gallery #photo").fadeIn("normal");
			})
			.error(function() {
				alert("Error loading image...");
			}) 
			.attr("src", src);
	});                                                                 
}

function getCaption(id) {
	if (typeof captions != "undefined") {
		for (var item in captions) {
			if (captions[item].id == id) {
				return captions[item].txt;
			}
		}
	}
	return null;
};