$(document).ready(function(){
    
    function initGallery() {
      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 = [];
      
      function switchImage(k, g) {
	var l = k + 1;
      
	// Show and hide the previous and next links as appropriate
	if (k > 0) $(".prev").fadeIn("fast");
	else $(".prev").fadeOut("fast");

	if (l < numImages) $(".next").fadeIn("fast");
	else $(".next").fadeOut("fast");
	
	// Change the current thumbnail to be selected
	$(".thumb-wrap .selected", g).removeClass("selected");
	$(".thumb-wrap:eq(" + k + ") img", g).addClass("selected");
	
	// Put the image and larger link in place
	$(".imageBox:visible").hide(1, function(){
	    var imgURL = "";
	    var currentImage = $(".imageBox:eq(" + k + ")", g);
	    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 = $(".imageBox:eq(" + l + ")", g);
	      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 > 2) {
	      prevImage = $(".imageBox:eq(" + (l-2) + ")", g);
	      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]);
	      }
	    }
	  });

	// Get index of current gallery
	selectedImage[g.index(".cl_gallery")] = 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 height of the whole panel
      $(".panel").height(maxImageHeight + maxCaptionHeight);
      
      // Select the first image
      $(".imageBox:first").siblings().hide();
      $(".cl_gallery").each(function() {
	  switchImage(0, $(this));
	});
	
      // 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(){
	  // Send index of target image and target gallery jQuery object
	  switchImage($(this).closest(".thumb-wrap").index(), $(this).closest(".cl_gallery"));
	  return false;
	});

      // Select the next image when user clicks Next
      $(".cl_gallery .next").click(function() {
	  var thisGallery = $(this).closest(".cl_gallery");
	  switchImage(selectedImage[thisGallery.index(".cl_gallery")] + 1, thisGallery);
	  return false;
	});

      // Select the previous button when user clicks Previous
      $(".cl_gallery .prev").click(function() {
	  var thisGallery = $(this).closest(".cl_gallery");
	  switchImage(selectedImage[thisGallery.index(".cl_gallery")] - 1, thisGallery);
	  return false;
	});
    }
    
    $('#tabs').tabs({ cookie: { expires: 1 } });
    $('#tabs ul').css('margin-left','0');
  
    $('table.padded th')
      .addClass('ui-state-default');
  
    $('.pager a, .button, a.controls, .children li a')
      .addClass('ui-state-default')
      .addClass('ui-corner-all');
  
    $('.pager span')
      .addClass('ui-state-highlight');
  
    //hover states on the static widgets
    $('.pager a, #dialog_link, ul#icons li, .button').hover(
							    function() { $(this).addClass('ui-state-hover'); },
							    function() { $(this).removeClass('ui-state-hover'); }
							    );
  
    // Error and alert text
  
    $('.cl_errorText').addClass('ui-state-error').addClass('ui-corner-all');
  
    // Accordion
    $(".accordion").accordion({ header: "h3" });
  
    // Dialog
    $('#dialog').dialog({
      autoOpen: false,
	  width: 600,
	  buttons: {
	  "Ok": function() {
	    $(this).dialog("close");
	  },
	    "Cancel": function() {
	      $(this).dialog("close");
	    }
	}
      });
  
    // Dialog Link
    $('#dialog_link').click(function(){
	$('#dialog').dialog('open');
	return false;
      });
  
    // Datepicker
    $('#datepicker').datepicker({
	inline: true
	  });
  
  // Slider
  $('#slider').slider({
    range: true,
	values: [17, 67]
	});
  
  // Progressbar
  $('#progressbar').progressbar({
    value: 20
	});
  
  // Drag and Drop Sorting
  $('.sortable').sortable({
    update: function(event, ui) {
	$('#' + $(this).attr('id') + 'Order').attr('value', $(this).sortable('toArray', {'attribute' : 'position'}));
      },
	placeholder: 'ui-state-highlight',
	forcePlaceholderSize: 'true'
	});
  
  // Select all
  $("A[href='#select_all']").click( function() {
      $("#" + $(this).attr('rel') + " INPUT[type='checkbox']").attr('checked', true);
      return false;
    });
  
  // Select none
  $("A[href='#select_none']").click( function() {
      $("#" + $(this).attr('rel') + " INPUT[type='checkbox']").attr('checked', false);
      return false;
    });
  
  // Invert selection
  $("A[href='#invert_selection']").click( function() {
      $("#" + $(this).attr('rel') + " INPUT[type='checkbox']").each( function() {
	  $(this).attr('checked', !$(this).attr('checked'));
	});
      return false;
    }); 
  
  $(".ajaxLink").live("click", function(){
      $(".container").load($(this).attr("href") + " .container", function() {
	  initGallery();
	  // Initialize thickbox
	  tb_init('a.popModal, a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	  imgLoader = new Image();// preload image
	  imgLoader.src = tb_pathToImage;
	});
      
      return false;
    });
  
  initGallery();
  
  // Comment management
  $(".commentReply").live("click",function() {
      var replyButton = $(this);
      var commentWrapper = $(this).closest(".comment-wrapLeft");
      $.ajax({
	url: $(this).attr("href"),
	    success: function(ajaxEdit) {
	    replyButton.hide();
	    replyButton.parent().after(getBody(ajaxEdit));
	    commentWrapper.find(".replyTo:first").slideDown("fast",function(){
		var theForm;

		theForm = commentWrapper.find("form:first");
		if (!theForm.attr("notLoggedIn"))
		  theForm.ajaxForm({
		    success: function(ajaxEditResult){
			// Place results into a hidden container to check for error state
			commentWrapper.find(".replyTo:first .commentAjaxResult").html(getBody(ajaxEditResult));
			commentWrapper.find(".replyTo:first .commentError")
			  .slideUp("fast");
			  
			if(commentWrapper.find(".replyTo:first .commentAjaxResult .error").length){
			  // Show the error
			  commentWrapper.find(".replyTo:first .commentError")
			    .html(getBody(ajaxEditResult))
			    .slideDown();
			} else {
			  // Remove the editor and place the comment
			  commentWrapper.find(".replyTo:first")
			    .slideUp(function(){
				replyButton.parent().after(getBody(ajaxEditResult));
				commentWrapper.find(".ajaxComment")
				  .slideDown()
				  .removeClass("ajaxComment");
				commentWrapper.find(".replyTo:first").remove();
			      })
			    replyButton.fadeIn();
			}
		      }
		    })
		    .find("textarea").focus();
		else
		  $("input.loginPrompt").each(function() {
		      installOverlay($(this));
		    });
	      });
	  }
	});
      return false;
    });

  $(".toggleComment").toggle(function(){
      $(this).removeClass("hideComment");
      $(this).addClass("showComment").fadeIn("slow");
    }, function () {
      $(this).removeClass("showComment");
      $(this).addClass("hideComment").fadeIn("slow");
    });

  $(".toggleComment").click(function() {
      $(this).parent().next(".commentBody-wrap").slideToggle();
    });
    
  $(".cancelComment").live("click", function() {
      var parentComment = $(this).closest(".comment-wrap");
      $(".replyTo:first",parentComment).slideUp(function(){$(this).remove()});
      $(".commentReply:first",parentComment).fadeIn();
      return false;
    });

  $(".newCommentForm").ajaxForm({
    success: function(newComment){
	$(".newComment .commentError").slideUp("fast");
	$(".newComment .commentAjaxResult").html(getBody(newComment));
	if($(".newComment .commentAjaxResult .error").length){
	  $(".newComment .commentError")
	    .html(getBody(newComment))
	    .slideDown("fast");
	} else {
	  $(".newComment").before(getBody(newComment));
	  $(".ajaxComment")
	    .slideDown("fast",function(){
		$(".ajaxComment").removeClass("ajaxComment");
	      })
	    }
      },
	clearForm: true
	});
    
  // AJAX comment voting
  $(".commentVotes-wrap a.commentVote").live("click",function(){
      var commentVotes = $(this).parent();
      $.ajax({
	url: $(this).attr("href"),
	    cache: false,
	    success: function(voteBlock){
	    commentVotes.fadeTo(50,0.05,function(){
		commentVotes.html(getBody(voteBlock));
		commentVotes.fadeTo(400,1);
	      });
	  }
	});
      return false;
    });
  
  });


