(function($) {

	$.fn.gallery = function() {
		this.each(function() {
			var $imageHolder = $('<div class="image_holder"></div>');
			var $theGallery = $(this).addClass('js').prepend($imageHolder);
			var $thumbHolder = $theGallery.find('.thumbnails');
			var thumbnailsPerPage = 18;
			var $thumbGroup = $thumbHolder.find('li:lt('+thumbnailsPerPage+')').remove();
			var $pagination = $('<ul class="pagination"/>');

			$.fn.showImage = function() {
				$imageHolder.empty();
				this.each(function() {
						$(this).parent().addClass('current').siblings().removeClass('current');
						$(this).children('figure').clone().prependTo($imageHolder).show();
					});

					return this;
			};
			var i = 1;
			while($thumbGroup.length){
				$('<ol class="thumbnails"/>').append($thumbGroup).appendTo($theGallery);
				$pagination.append($('<li>'+i+'</li>').click(function(){
					$thumbHolder.hide();
					$thumbHolder.eq($(this).text()-1).show().find('li:first-child a').showImage();
				}));
				$thumbGroup = $thumbHolder.find('li:lt('+thumbnailsPerPage+')').remove();
				i++;
			}
			$thumbHolder.remove();
			$thumbHolder = $theGallery.find('.thumbnails').hide();
			$thumbHolder.first().show().find('li:first-child a').showImage();
			$thumbHolder.find('a').each(function(){
				$(this).click(function(e){
					e.preventDefault();
					$(this).showImage();
				});
			});
			$theGallery.append($pagination);
		});

		return this;

	};

})(jQuery);
