(function ($) {
// plugin code
$.fn.gallery = function () {
	
	$('#divGalleryThumbs').prepend('<p class="instruction">Select another image to enlarge:</p>');
	
	this.each(function () {
    var $items = null,
        $gallery = $('<ul id="thumbGallery" />'),
        html = [],
        $viewing = $('#largeimage').css('overflow', 'hidden');
        
    // build the actual gallery - which isn't in the original markup (not sure why though...)
    $viewing.find('> div').each(function () {
      html.push('<li><a href="#' + this.id + '"><' + 'img src="' + $(this).find('img')[0].src.replace(/resourcelib/i, 'resourcelib/gallerythumbs') + '" alt="' + $(this).find('p').text() + '" height="99" /></a>');
    });
    
    // nuke the extra ones as we'll replace the first image each time
    $viewing.find('> div:gt(0)').remove();
    
    $gallery.append(html.join(''));

    $items = $gallery.find('a').click(function (event) {
      $items.removeClass('selected');
      $(this).addClass('selected');
      
      var img = $(this).find('img')[0];
      
      $viewing.find('img').attr('src', img.src.replace(/\/gallerythumbs/i, ''));
      $viewing.find('p').text(img.alt);
      
      // sadly we can't use the overflow, because the browser scrolls down :-(
      return false;
    });
    
    $gallery.appendTo(this);
  });
  
  
  	// Setup thumbnail set paging
  	
  	// var used to keep track of current displayed thumbnail set
   	var currentThumbSet = 0;
   	
   	// Get the number of thumbnails generated in the previous script
	var noThumbs = $('#thumbGallery > li').length;
	
	// If we have more that 4 thumbnails we need to add paging
	if(noThumbs > 4) {
		maxThumbset = noThumbs / 4 - 1;
		$('#thumbGallery').after("<p class='thumbsNav clearfix'><a href='#' class='previousSet left' style='display:none;'>&laquo; Previous set</a><a href='#' class='nextSet right'>Next set &raquo;</a></p>");
	
	
		$('a.previousSet').live('click', function(e){ 
			currentThumbSet = currentThumbSet - 1;
			updateThumbSet();
			e.preventDefault();
		});
	
		$('a.nextSet').live('click', function(e){ 
			currentThumbSet = currentThumbSet + 1;
			updateThumbSet();
			e.preventDefault();
		});
	
	}
	
	// function called after either of the next/previous links clicked.  Simply hides all thumbnails then shows current set.
	function updateThumbSet() {
      
      $('.thumbsNav a').hide();
      $('#thumbGallery li').hide();
            
      if(currentThumbSet>=0 && currentThumbSet<maxThumbset)
      	$('a.nextSet').show();
      	
      if(currentThumbSet>0)
      	$('a.previousSet').show(0);		
      		
       	for (i=1;i<=4;i++) 
     	 	$('#thumbGallery li:nth-child('+parseInt((currentThumbSet*4)+i)+')').show();

     	return false;
    }

    return this;
};

})(jQuery);

// initialise the gallery
jQuery(function ($) {
  $('#gallery').gallery();
});