$(document).ready(function(){
	
	if($('#gallery').length > 0) {
		// Initialise body
		/* DO NOT USE - BREAKS PRINTING IN IE6 $('body').css({opacity: .9999});  Fixes Firefox Mac opacity bug */
	
		// initialise main image
		$("#gallery li:not(:first)").hide(); /* Hide all but the first image (need for smooth transition) */
		$("#gallery li:first").fadeIn("slow"); /* Bring the first gallery image to the front */
	
		// initilase thumbs
		$("#thumbnails").css('display', 'block'); /* Show thumbnails (hidden for non JS users) */	
		$("#thumbnails li:first").addClass("on"); /* Highlight currently active thumbnail */
	
		// initialise gallery nav 
		$("#gallery-navigation").css('display', 'block'); /* Show thumbnails (hidden for non JS users) */
	
		// condition : more than one thumbnail? show the next arrow
		if ($("#thumbnails li").length > 1) {
			$("#gallery-navigation li.next").fadeIn("slow"); /* Fade in next arrow */ 
		}

		// clicking on thumbnail event
		$("#thumbnails li").click(function() {
		
			// Highlight clicked thumbnail
			$("#thumbnails li").removeClass("on");
			$(this).addClass("on")
			.gallery();
		});
	
		// clicking on next arrow event
		$("#gallery-navigation li.next").click(function() {

			// Highlight the next thumbnail		
			$("#thumbnails li.on")
				.removeClass("on")
				.next().addClass("on")
				.gallery(); 
		});
	
		// clicking on previous arrow event
		$("#gallery-navigation li.previous").click(function() {

			// Highlight previous thumbnail	
			$("#thumbnails li.on")
				.removeClass("on")
				.prev().addClass("on")
				.gallery();
		});
	
		// load in new gallery state
		jQuery.fn.gallery = function() {
		
			// condition : toggle prev/next button states depending on selected thumb
			if ($("#thumbnails li.on").is(":last-child")) {
	    		$("#gallery-navigation li.next").fadeOut("fast");
				$("#gallery-navigation li.previous").fadeIn("fast");
	  		} else if ($("#thumbnails li.on").is(":first-child")) {
				$("#gallery-navigation li.next").fadeIn("fast");
				$("#gallery-navigation li.previous").fadeOut("fast");			
			} else {
				$("#gallery-navigation li.next").fadeIn("fast");
				$("#gallery-navigation li.previous").fadeIn("fast");
			}
		
			// fade in corresponding main image
			$("#gallery li")
				.fadeOut("slow")
				.animate({opacity: 1.0}, 500)
				.eq($("#thumbnails li.on").prevAll().length)
				.fadeIn("slow");
		};
	};
});