$(function() {  	
  $photo = $('#photo');
  
  $thumbnails = $('#thumbnails');
  
  var swapPhoto = function()
  {			
  	var fadeInPhoto = function()
  	{
  		$photo.fadeTo(750, 1.0);
  		$('#main_content .img_caption').text(lgImgCaption);
  		$photo.unbind('load');
  	};
  	
  	//clearTimeout(rotation);
  	//rotation = setTimeout(function()
  	//{
  	//	$('#nextButton').trigger('click');
  	//}, rotationTime);
  
  	lgImg = $(this).addClass('current').siblings().removeClass('current')
  										   .end().attr('rel');
  	lgImgCaption = $(this).find('img').attr('alt');
  				
  	$photo.fadeTo(750, 0.0, function()
  	{
  		$photo.attr('src', lgImg);
  		if($photo.complete)
  		{
  			fadeInPhoto();
  		}
  		else
  		{
  			$photo.bind('load', fadeInPhoto);
  		}
  	});
  	return false;
  };
  
  //RUN THIS AFTER CLICKING A GALLERY
  $('#gallery_list li a').bind('click', function()
  {			
  	$thumbnails.addClass('invisible');
  	
  	$('#gallery_list li.active').removeClass('active');
  	$(this).parent().addClass('active');
  	
  	var galleryID = $(this).attr('rel');
  
  	$thumbnails.load('../../index.php/ajax/getImages', {theGal : galleryID}, function()
  	{
  		$thumbnails.find('a').setSiblingHover().bind('click', swapPhoto);
  		$thumbnails.removeClass('invisible');
  		$thumbnails.find('a:first').trigger('click');
  	});
  	
  	return false;
  });
  
  //RUN THIS AFTER CLICKING A THUMBNAIL
  $thumbnails.find('a').setSiblingHover().bind('click', swapPhoto);
  
  //INITIALIZE FIRST PHOTO ON PAGELOAD
  $thumbnails.find('a:first').trigger('click');
  
  //SETUP PREV BUTTON
  $('#previousButton').bind('click', function()
  {
  	if ($thumbnails.find('a:first-child').hasClass('current'))
  	{
  		$thumbnails.find('a:last-child').trigger('click');
  	}
  	else
  	{
  		$thumbnails.find('a.current').prev().trigger('click');
  	}
  });
  
  //SETUP NEXT BUTTON
  $('#nextButton').add('#photo').add('#gal_frame').bind('click', function()
  {
  	if ($thumbnails.find('a:last-child').hasClass('current'))
  	{
  		$thumbnails.find('a:first-child').trigger('click');
  	}
  	else
  	{
  		$thumbnails.find('a.current').next().trigger('click');
  	}
  });
});

