$(function(){
    var thisID = '';
    var numImages = 0;
    var i = 0;
    var maxImageHeight = 0;
    var maxCaptionHeight = 0;
    var thisHeight = 0;
    var vPosition = 0;
    
    function switchImage(k,v) {
      // Change the current thumbnail to be selected
      $(".thumb-wrap").each(function(){
	  $("img", this).removeClass("selected");
	});
      $("#thumb_" + k).addClass("selected");

      // Put the image and larger link in place
      $(".imageBox").fadeOut(100, function(){
	  $(".imageBox").css({
	    position: "absolute",
		left: "-9999px",
		top: "0"
		});
	  $("#image_" + k).css({
	    position: "relative",
		left: "0"
		});
	  $(".imageBox").fadeIn(500);
	  $(window).scrollTop(v);
	});
    }

    $(".medium").each(function(){
	numImages++;
	
	// Get the height of the image container (this will include any image padding or border)
	thisHeight = $(this).height();
	if (thisHeight > maxImageHeight) {
	  maxImageHeight = thisHeight;
      	}
      }); 
    
    // Set the height and margin to center each image vertically
    $(".medium").each(function(){
	$(this).children("img").css("margin-top",(maxImageHeight - $(this).height())/2);
	$(this).height(maxImageHeight);

      });

    // Set caption container width to match the image width
    $(".medium img").each(function(){
	$(this).parent().next().width($(this).width());
      });
    
    // Get the height of the tallest caption container (called "larger")
    $(".larger").each(function(){
	thisHeight = $(this).height();
	if (thisHeight > maxCaptionHeight) {
	  maxCaptionHeight = thisHeight;
	}
      }); 

    // Set the height and padding to center each image vertically
    $(".larger").each(function(){
	$(this).height(maxCaptionHeight);
      });

    // Set the hieght of the whole panel
    $(".panel").height(maxImageHeight + maxCaptionHeight);
    
    // Select the first image
    switchImage(1);

    // Remove the thumbnails if there is only one image
    if (numImages < 2) {
      $(".thumbnails").remove();
    }

    //Remove the gallery if there are no images

    if (numImages == 0) {
      $("cl_gallery").remove();
    }
    
    // Switch images when a user clicks the thumbnail
    $(".thumbnails img").click(function(){
    	thisID = $(this).attr("id");
    	newImage = thisID.slice(thisID.search("_") + 1); // Finds the index of the thumbnail the user clicked on.
	vPosition = $(window).scrollTop();
    	switchImage(newImage,vPosition);
      });
  });
