$(function(){
    var thisID = '';
    var numImages = 0;
    var i = 0;
    var maxImageHeight = 0;
    var maxCaptionHeight = 0;
    var thisHeight = 0;
    var thisWidth = 0;
    var vPosition = 0;
    var topMargins = [];
    var selectedImage = 1;
    
    function switchImage(k) {
      k = parseInt(k)
      var l = k + 1;
      
      // Show and hide the previous and next links as appropriate
      if (k > 1) $(".prev").fadeIn("fast");
      else $(".prev").fadeOut("fast");

      if (k < numImages) $(".next").fadeIn("fast");
      else $(".next").fadeOut("fast");

      
      // Change the current thumbnail to be selected
      $(".thumb-wrap .selected").removeClass("selected");
      $("#thumb_" + k).addClass("selected");

      // Put the image and larger link in place
      $(".imageBox:visible").hide(1, function(){
	  var imgURL = "";
	  var currentImage = $("#image_" + k);
	  var nextImage = "";
	  var prevImage = "";
	  var imgA = new Image();
	  var imgB = new Image();
	  var imgC = new Image();

	  currentImage
	    .css({
	      position: "relative",
		  left: "0"
		  })
	    .fadeIn(300);

	  $(window).scrollTop($(window).scrollTop());
	  
	  // Ajax load the image if appropriate
	  if ( currentImage.hasClass("ajaxLoad") ) {
	    imgURL = $(".medium a", currentImage).attr("href");

	    $(imgA)
	      .load(function() {
		$(".medium", currentImage)
		  .html(this)
		  .parent(".imageBox").removeClass("ajaxLoad");
	      })
	      .error(function() {
		  alert("The image could not be loaded.");
		})
	      .attr("src", imgURL)
	      .attr("alt", "Image " + k)
	      .css("margin-top",topMargins[k]);
	  }
	  
	  // Ajax load the next image if appropriate
	  if (k < numImages) {
	    nextImage = $("#image_" + l);
	    if ( nextImage.hasClass("ajaxLoad") ) {
	      imgURL = $(".medium a", nextImage).attr("href");
	      
	      $(imgB)
		.load(function() {
		    $(".medium", nextImage)
		      .html(this)
		      .parent(".imageBox").removeClass("ajaxLoad");
		  })
		.error(function() {
		    alert("The image could not be loaded.");
		  })
		.attr("src", imgURL)
		.attr("alt", "Image " + l)
		.css("margin-top",topMargins[l]);
	    }
	  }

	  // Ajax load the previous image if appropriate
	  if (k > 3) {
	    prevImage = $("#image_" + (l-2));
	    if ( prevImage.hasClass("ajaxLoad") ) {
	      imgURL = $(".medium a", prevImage).attr("href");
	      
	      $(imgC)
		.load(function() {
		    $(".medium", prevImage)
		      .html(this)
		      .parent(".imageBox").removeClass("ajaxLoad");
		  })
		.error(function() {
		    alert("The image could not be loaded.");
		  })
		.attr("src", imgURL)
		.attr("alt", "Image " + (l-2))
		.css("margin-top",topMargins[l-2]);
	    }
	  }
	});

      selectedImage = k;
      return false;
    }

    // Set caption container width to match the image width
    $(".medium a").each(function(){
	thisWidth = parseInt($(this).attr("width")); // Special CL attribute written to image anchors
	thisHeight = parseInt($(this).attr("height")); // Ditto
	$(this).height(thisHeight).width(thisWidth);
	$(this).parent().next(".larger").width(thisWidth);
      });

    $(".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(i){
	topMargins[i+1] = (maxImageHeight - $(this).height())/2;
	$(this).children("a").css("margin-top",topMargins[i+1]);
      });

    // Set the position of the Next and Previous buttons
    $(".next, .prev").css("top", ((maxImageHeight/2)-($(".next").height()/2)) + "px");
    
    // Get the height of the tallest caption container (called "larger")
    $(".larger").each(function(){
	thisHeight = $(this).height();
	if (thisHeight > maxCaptionHeight) {
	  maxCaptionHeight = thisHeight;
	}
      }); 
    
    // Set the height of all caption containers
    $(".larger").each(function(){
	$(this).height(maxCaptionHeight);
      });
    
    // Set the hieght of the whole panel
    $(".panel").height(maxImageHeight + maxCaptionHeight);
    
    // Select the first image
    $(".imageBox:first").siblings().hide();
    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.
    	switchImage(newImage);
	return false;
      });

    // Select the next image when user clicks Next
    $(".cl_gallery .next").click(function() {
    	switchImage(selectedImage + 1);
	return false;
      });

    // Select the next image when user clicks Next
    $(".cl_gallery .prev").click(function() {
    	switchImage(selectedImage - 1);
	return false;
      });

    // Capture arrow keys and select next or previous image
    $(document).keydown(function(e) {
	// Previous (left arrow keyCode = 37)
	if ((selectedImage > 1) && (e.keyCode == 37)) {
	  switchImage(selectedImage - 1);
	}
	// Next (right arrow keyCode = 39)
	if ((selectedImage < numImages) && (e.keyCode == 39)) {
	  switchImage(selectedImage + 1);
	}
      });

  });

