$.fn.photoViewer = function(settings) {
	// global Variables
	var isSet = false; /* Total position in the array */
	var setCount = 0; /* Total images in the set */
	var setPosition = 0; /* Position in the set */
	var arrayPosition = 0; /* Total position in the array */
	var caller = 0;
	var doresize = true;
	var imagesArray = [];

	$(window).scroll(function(){ _centerPicture(); });
	$(window).resize(function(){ _centerPicture(); _resizeOverlay(); });
	$(document).keyup(function(e){
		switch(e.keyCode){
			case 37:
				if (setPosition == 1) return;
				changePicture('previous');
				break;
			case 39:
				if (setPosition == setCount) return;
				changePicture('next');
				break;
			case 27:
				close();
				break;
		};
	});


	settings = jQuery.extend({
		animationSpeed: 'normal', /* fast/slow/normal */
		opacity: 0.8, /* Value betwee 0 and 1 */
		padding: 40,
		allowresize: true, /* true/false */
		counter_separator_label: '/' /* The separator for the gallery counter 1 "of" 2 */
	}, settings);

	$(this).each(function(){
		imagesArray[imagesArray.length] = this;
		$(this).bind('click',function(){
			open(this); return false;
		});
	});
	
	var current = location.hash.slice(1);
	$(this).each(function(){
		if ($(this).attr('href') == current) { open(this) };
	});

	function open(el) {
		caller = $(el);
		location.hash = $(el).attr('href');
	
		// Find out the type of content
		contentType = "image";
		if($(caller).attr('href').indexOf('.swf') > 0){ contentType = 'flash'; };
	
		// Calculate the number of items in the set, and the position of the clicked picture.
		isSet = false;
		setCount = 0;
		for (i = 0; i < imagesArray.length; i++){
			setCount++;
			if(setCount > 1) isSet = true;

			if($(imagesArray[i]).attr('href') == $(el).attr('href')){
				setPosition = setCount;
				arrayPosition = i;
			};
		};
	
		_buildOverlay(isSet);

		// Display the current position
		$('div.pictureHolder p.currentTextHolder').text(setPosition + settings.counter_separator_label + setCount);

		// Position the picture in the center of the viewing area
		_centerPicture();
	
		$("div.pictureHolder .close").ifixpng();
		$("div.pictureHolder .next").ifixpng();
		$("div.pictureHolder .previous").ifixpng();
		$('div.pictureHolder .close').hide();	
		$('div.pictureHolder .next').hide();	
		$('div.pictureHolder .previous').hide();		
		$('div.pictureHolder #fullResImageContainer').hide();
		$('.loaderIcon').show();

		// Display the correct type of information
		(contentType == 'image') ? _preload() : _writeFlash();
	};

	showimage = function(width,height,containerWidth,containerHeight,contentHeight,contentWidth,resized){
		$('.loaderIcon').hide();
		var scrollPos = _getScroll();

		if($.browser.opera) {
			windowHeight = window.innerHeight;
			windowWidth = window.innerWidth;
		}else{
			windowHeight = $(window).height();
			windowWidth = $(window).width();
		};

		$('div.pictureHolder .content').animate({'height':contentHeight,'width':contentWidth},settings.animationSpeed);

		// Resize the holder
		$('div.pictureHolder').animate({
			'left': ((windowWidth/2) - (containerWidth/2)),
			'width': containerWidth
		},settings.animationSpeed,function(){
			$('#fullResImage').attr({
				'width':width,
				'height':height
			});

			$('div.pictureHolder').width(containerWidth);
			$('div.pictureHolder .hoverContainer').height(height).width(width);

			// Show the nav elements
			_shownav();

			// Fade the new image
			$('div.pictureHolder #fullResImageContainer').fadeIn(settings.animationSpeed);
			$("div.pictureHolder .close").fadeIn(settings.animationSpeed);
			$("div.pictureHolder .next").fadeIn(settings.animationSpeed);
			$("div.pictureHolder .previous").fadeIn(settings.animationSpeed);
		
			// Fade the resizing link if the image is resized
			if(resized) $('a.expand,a.contract').fadeIn(settings.animationSpeed);
		});
	};

	function changePicture(direction){
		if(direction == 'previous') {
			arrayPosition--;
			setPosition--;
		}else{
			arrayPosition++;
			setPosition++;
		};

		// Allow the resizing of the images
		if(!doresize) doresize = true;

		// Fade out the current picture
		$('div.pictureHolder .hoverContainer,div.pictureHolder .details,div.pictureHolder .close,div.pictureHolder .next,div.pictureHolder .previous').fadeOut(settings.animationSpeed);
		$('div.pictureHolder #fullResImageContainer').fadeOut(settings.animationSpeed,function(){
			$('.loaderIcon').show();
		
			// Preload the image
			_preload();
		});

		$('a.expand,a.contract').fadeOut(settings.animationSpeed,function(){
			$(this).removeClass('contract').addClass('expand');
		});
	};

	function close(){
		$('div.pictureHolder').fadeOut(settings.animationSpeed, function(){
			$('div.photoViewerOverlay').fadeOut(settings.animationSpeed, function(){
				$('div.photoViewerOverlay,div.pictureHolder').remove();
			
				// To fix the bug with IE select boxes
				if($.browser.msie && $.browser.version == 6){
					$('select').css('visibility','visible');
				};
				location.hash = "";
			});
		});
		
	};

	function _checkPosition(){
		// If at the end, hide the next link
		if(setPosition == setCount) {
			$('div.pictureHolder a.next').css('visibility','hidden');
			$('div.pictureHolder a.arrow_next').css('visibility','hidden');
		}else{ 
			$('div.pictureHolder a.next').css('visibility','visible');
			$('div.pictureHolder a.arrow_next').css('visibility','visible');
		};
	
		// If at the beginning, hide the previous link
		if(setPosition == 1) {
			$('div.pictureHolder a.previous').css('visibility','hidden');
			$('div.pictureHolder a.arrow_previous').css('visibility','hidden');
		}else{
			$('div.pictureHolder a.previous').css('visibility','visible');
			$('div.pictureHolder a.arrow_previous').css('visibility','visible');
		};
	
		// Change the current picture text
		$('div.pictureHolder p.currentTextHolder').text(setPosition + settings.counter_separator_label + setCount);
	
		(isSet) ? $c = $(imagesArray[arrayPosition]) : $c = $(caller);
		if($c.attr('rel')){
			$('div.pictureHolder .description').show().html(unescape($c.attr('rel')));
		}else{
			$('div.pictureHolder .description').hide().text('');
		};
	
	};

	function _fitToViewport(width,height){
		hasBeenResized = false;
	
		$('div.pictureHolder .details').width(width); /* To have the correct height */
		//$('div.pictureHolder .details p.description').width(width); /* To have the correct width */
	
		// Get the container size, to resize the holder to the right dimensions
		contentWidth = width;
		contentHeight = height + parseFloat($('div.pictureHolder .details').height());
		containerWidth = contentWidth + parseFloat($('div.pictureHolder .content').css("padding-left")) + parseFloat($('div.pictureHolder .content').css("padding-right"));
		containerHeight = contentHeight + parseFloat($('div.pictureHolder .content').css("padding-top")) + parseFloat($('div.pictureHolder .content').css("padding-bottom"));
	
		// Define them in case there's no resize needed
		imageWidth = width;
		imageHeight = height;

		if($.browser.opera) {
			windowWidth = window.innerWidth - 45;
			windowHeight = window.innerHeight - 45;
		}else{
			windowWidth = $(window).width() - 45;
			windowHeight = $(window).height() - 45;
		};
	
		if( ((containerWidth > windowWidth) || (containerHeight > windowHeight)) && doresize && settings.allowresize) {
			hasBeenResized = true;
			
			var xscale = containerWidth / windowWidth;
			var yscale = containerHeight / windowHeight;
			
			if (yscale > xscale) {
				imageWidth = Math.round(width * (1/yscale));
				imageHeight = Math.round(height * (1/yscale));
			} else {
				imageWidth = Math.round(width * (1/xscale));
				imageHeight = Math.round(height * (1/xscale));
			}
		
			// Define the new dimensions
			contentWidth = imageWidth;
			contentHeight = imageHeight + parseFloat($('div.pictureHolder .details').height());
			containerWidth = imageWidth + parseFloat($('div.pictureHolder .content').css("padding-left")) + parseFloat($('div.pictureHolder .content').css("padding-right"));
			containerHeight = imageHeight + parseFloat($('div.pictureHolder .content').css("padding-top")) + parseFloat($('div.pictureHolder .content').css("padding-bottom"));
			
			$('div.pictureHolder .details').width(contentWidth); /* To have the correct height */
			$('div.pictureHolder .details p.description').width(contentWidth); /* To have the correct width */
		};

		return {
			width:imageWidth,
			height:imageHeight,
			containerHeight:containerHeight,
			containerWidth:containerWidth,
			contentHeight:contentHeight,
			contentWidth:contentWidth,
			resized:hasBeenResized
		};
	};

	function _centerPicture(){
		//Make sure the gallery is open
		if($('div.pictureHolder').size() > 0){
		
			var scrollPos = _getScroll();
		
			if($.browser.opera) {
				windowWidth = window.innerWidth;
			}else{
				windowWidth = $(window).width();
			};
		
			if(doresize) {
				$('div.pictureHolder').css({
					'left': (windowWidth/2) + scrollPos['scrollLeft'] - ($('div.pictureHolder').width()/2)
				});
			};
		};
	};

	function _shownav(){
		if(isSet) $('div.pictureHolder .hoverContainer').fadeIn(settings.animationSpeed);
		$('div.pictureHolder .details').fadeIn(settings.animationSpeed);
		$('div.pictureHolder .close').fadeIn(settings.animationSpeed);
		$('div.pictureHolder .next').fadeIn(settings.animationSpeed);
		$('div.pictureHolder .previous').fadeIn(settings.animationSpeed);
	};

	function _preload(){
		// Hide the next/previous links if on first or last images.
		_checkPosition();
	
		// Set the new image
		imgPreloader = new Image();
	
		// Preload the neighbour images
		nextImage = new Image();
		if(isSet) nextImage.src = $(imagesArray[arrayPosition + 1]).attr('href');
		prevImage = new Image();
		if(isSet && imagesArray[arrayPosition - 1]) prevImage.src = $(imagesArray[arrayPosition - 1]).attr('href');

		$('div.pictureHolder .content').css('overflow','hidden');
	
		if(isSet) {
			$('div.pictureHolder #fullResImage').attr('src',$(imagesArray[arrayPosition]).attr('href'));
			location.hash = $(imagesArray[arrayPosition]).attr('href');
		}else{
			$('div.pictureHolder #fullResImage').attr('src',$(caller).attr('href'));
			location.hash = $(caller).attr('href');
		};

		imgPreloader.onload = function(){
			var correctSizes = _fitToViewport(imgPreloader.width,imgPreloader.height);
			imgPreloader.width = correctSizes['width'];
			imgPreloader.height = correctSizes['height'];
		
			// Need that small delay for the anim to be nice
			setTimeout('showimage(imgPreloader.width,imgPreloader.height,'+correctSizes["containerWidth"]+','+correctSizes["containerHeight"]+','+correctSizes["contentHeight"]+','+correctSizes["contentWidth"]+','+correctSizes["resized"]+')',500);
		};
	
		(isSet) ? imgPreloader.src = $(imagesArray[arrayPosition]).attr('href') : imgPreloader.src = $(caller).attr('href');
	};

	function _getScroll(){
		scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
		scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || 0;
		return {scrollTop:scrollTop,scrollLeft:scrollLeft};
	};

	function _resizeOverlay() {
		$('div.photoViewerOverlay').css({
			'height':$(document).height(),
			'width':$(window).width()
		});
	};

	function _writeFlash(){
		flashParams = $(caller).attr('rel').split(';');
		$(flashParams).each(function(i){
			// Define the width and height
			if(flashParams[i].indexOf('width') >= 0) flashWidth = flashParams[i].substring(flashParams[i].indexOf('width') + 6, flashParams[i].length);
			if(flashParams[i].indexOf('height') >= 0) flashHeight = flashParams[i].substring(flashParams[i].indexOf('height') + 7, flashParams[i].length);
			if(flashParams[i].indexOf('flashvars') >= 0) flashVars = flashParams[i].substring(flashParams[i].indexOf('flashvars') + 10, flashParams[i].length);
		});
	
		$('.pictureHolder #fullResImageContainer').append('<embed width="'+flashWidth+'" height="'+flashHeight+'" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" wmode="opaque" name="flashViewer" flashvars="'+flashVars+'" allowscriptaccess="always" bgcolor="#FFFFFF" quality="high" src="'+$(caller).attr('href')+'"/>');
		$('#fullResImage').hide();
	
		contentHeight = parseFloat(flashHeight) + parseFloat($('div.pictureHolder .details').height()) + parseFloat($('div.pictureHolder .details').css('margin-top')) + parseFloat($('div.pictureHolder .details').css('margin-bottom'));
		contentWidth = parseFloat(flashWidth)+ parseFloat($('div.pictureHolder .details').width()) + parseFloat($('div.pictureHolder .details').css('margin-left')) + parseFloat($('div.pictureHolder .details').css('margin-right'));
		containerHeight = contentHeight;
		containerWidth = parseFloat(flashWidth) + parseFloat($('div.pictureHolder .content').css("padding-left")) + parseFloat($('div.pictureHolder .content').css("padding-right"));
	
		setTimeout('showimage('+flashWidth+','+flashHeight+','+containerWidth+','+containerHeight+','+contentHeight+','+contentWidth+')',500);
	};

	function _buildOverlay(){
	
		// Build the background overlay div
		backgroundDiv = "<div class='photoViewerOverlay'></div>";
		$('body').append(backgroundDiv);
		$('div.photoViewerOverlay').css('height',$(document).height()).bind('click',function(){
			close();
		});
	
		// Basic HTML for the picture holder
		pictureHolder = '\n\
<div class="pictureHolder">\n\
	<a class="close" href="#"></a>\n\
	<a class="next" href="#"></a>\n\
	<a class="previous" href="#"></a>\n\
	<div class="content">\n\
		<a href="#" class="expand" title="Expand the image"></a>\n\
		<div class="loaderIcon"></div>\n\
		<div class="hoverContainer"><p>click the left and right buttons to navigate</p>\n\
		</div>\n\
		<div id="fullResImageContainer">\n\
			<img id="fullResImage" src="" />\n\
		</div>\n\
		<div class="details clearfix">\n\
			<p class="description"></p>\n\
			<div class="nav">\n\
				<a href="#" class="arrow_previous"></a>\n\
				<p class="currentTextHolder">0'+settings.counter_separator_label+'0</p>\n\
				<a href="#" class="arrow_next"></a>\n\
			</div>\n\
		</div>\n\
	</div>\n\
</div>\n';
	

		$('body').append(pictureHolder);

		$('.pictureHolder').css({'opacity': 0});
		$('a.close').bind('click',function(){ close(); return false; });
		$('a.expand').bind('click',function(){
		
			// Expand the image
			if($(this).hasClass('expand')){
				$(this).removeClass('expand').addClass('contract');
				doresize = false;
			}else{
				$(this).removeClass('contract').addClass('expand');
				doresize = true;
			};
		
			$('div.pictureHolder .hoverContainer,div.pictureHolder #fullResImageContainer').fadeOut(settings.animationSpeed);
			$('div.pictureHolder .close').fadeOut(settings.animationSpeed);
			$('div.pictureHolder .next').fadeOut(settings.animationSpeed);
			$('div.pictureHolder .previous').fadeOut(settings.animationSpeed);
			$('div.pictureHolder .details').fadeOut(settings.animationSpeed,function(){
				_preload();
			});
		
			return false;
		});
	
		$('.pictureHolder .previous,.pictureHolder .arrow_previous').bind('click',function(){
			changePicture('previous');
			return false;
		});
	
		$('.pictureHolder .next,.pictureHolder .arrow_next').bind('click',function(){
			changePicture('next');
			return false;
		});
	
		// If it's not a set, hide the links
		if(!isSet) {
			$('.hoverContainer,.nav').hide();
		};

		// To fix the bug with IE select boxes
		if($.browser.msie && $.browser.version == 6){
			$('select').css('visibility','hidden');
		};

		// Then fade it in
		$('div.photoViewerOverlay').css('opacity',0).fadeTo(settings.animationSpeed,settings.opacity, function(){
			$('div.pictureHolder').css('opacity',0).fadeIn(settings.animationSpeed,function(){
				// To fix an IE bug
				$('div.pictureHolder').attr('style','left:'+$('div.pictureHolder').css('left')+';');
			});
		});
	};
};