$(function(){
    var thisID = '';
    var numImages = 0;
    var i = 0;
    var maxHeight = 0;
    var thisHeight = 0;
    var vPosition = 0;
    
    function switchImage(k,v) {
      // Change the current thumbnail to be selected
      $("#thumb_" + k).siblings().removeClass("selected");
      $("#thumb_" + k).addClass("selected");

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

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