jQuery.fn.gallery = function(s,slideshow,styling){
	var gallery = this;
	var img = [];
	var speed = 500; if(s) speed = parseInt(s,10);
	var ssOption = '';
	var galleryTimeout = 5000;
	var slideShowTimeOut = 5000;
	var galleryStructure = '<div id="img-gallery"><img style="display:none" /><ul>'+ssOption+'</ul></div>';
	var started = false;
	
	$(gallery).each(function(i){
		$(this).hide();
		img[i] = [this.src,this.alt,$(this).attr('longdesc')];
		$(this).remove();
	});
	
	start();
	function start(){
		$("body").prepend(galleryStructure);
		$(img).each(function(i){
			$("#img-gallery ul").append('<li><a href="#img' + (i + 1) + '">' + (i + 1) + '</a><div id="img-description"></div></li>');
		});
		firstImage = img.length;
		firstImage = firstImage - 1;
		changeImage(firstImage);
		changeImage(0);
		startSlideShow();
		$("#img-gallery ul a").click(function(){
			var imgToLoad = $(this).attr("href");
			imgToLoad = imgToLoad.split("#");
			imgToLoad = parseInt(imgToLoad[1].substr(3)) - 1;
			changeImage(imgToLoad);
			//$("#img-gallery ul a").each(function(){ $(this).removeClass("active"); });
			//$(this).addClass("active");
			stopSlideShow();
			return false;
		});
		function changeImage(n, callback){
			$("#img-gallery img").fadeOut(speed / 4, function(){
				var originalWidth = $("#img-gallery img").width();
				$("#img-gallery img").attr("src",img[n][0]).attr("alt",img[n][1]);
				var width = $("#img-gallery img").width();
				var height = $("#img-gallery img").height();
				fadeInAll();
				function fadeInAll(fromAnimate){
					var localSpeed = speed;
					if (!fromAnimate){ localSpeed = speed / 2; }
					if(img[n][1] != ""){
						$('#img-gallery #img-description').html('<p>' + img[n][1] + '</p>');
						$('#img-gallery #img-description').fadeIn(localSpeed / 2);
					}
					$("#img-gallery img").fadeIn(localSpeed / 2);
					$("#img-gallery ul").fadeIn(localSpeed / 2);
					$("#img-gallery ul a").each(function(){ $(this).removeClass("active"); });
					$("#img-gallery ul a:eq("+n+")").addClass("active");
					if (callback) callback();
					if (styling) styling();
				}
			});
		}
		function startSlideShow(){
			// gets the next image to load
			var imgToLoad = $('#img-gallery ul a.active:eq(0)').attr('href');
			imgToLoad = imgToLoad.split('#');
			imgToLoad = parseInt(imgToLoad[1].substr(3));
			
			// cancels the slideshow if there is only one image
			if(gallery.length == 1){
				stopSlideShow();
			}
			
			// start again when we reach the end
			if(imgToLoad == gallery.length){
				imgToLoad = 0;
			}
			
			// set the timer running that will control the transition
			window['galleryTimeout'] = setTimeout(function(){startSlideShow()},slideShowTimeOut);
			
			// change the image
			changeImage(imgToLoad, function(){
				eval(galleryTimeout);
			});
		}
		function stopSlideShow(){
			clearTimeout(eval(galleryTimeout));
		}
	}
}
