(function($)
{
	var images = [];
	
	function ImageInfo(container, image)
	{
		this.container = container;
		this.image = image;
		this.loaded = false;
		this.ratio = 1;
	}
	
	$(function()
	{
		$(window).resize(windowResized);
		findFullscreenImage();
	});
	
	window.fullscreenimage_findFullscreenImage = findFullscreenImage;
	function findFullscreenImage()
	{
		var containers, container, a, img, imageInfo, el;
		
		images = [];
		containers = $('.fsimg');
		
		for (a = 0; a < containers.length; a++)
		{
			container = containers.eq(a);
			img = $('img', container);
			
			if (!img.length)
				continue;
			
			container.css({
				position: 'absolute',
				overflow: 'hidden',
				left: 0,
				top: 0,
				width: '100%',
				height: '100%',
				'z-index': -1
			});
			
			img.css({
				position: 'absolute'
			});
			
			images.push(imageInfo = new ImageInfo(container, img));
			el = img.get(0);
			imageInfo.loaded = !!(el.naturalHeight ? el.naturalHeight : imageInfo.image.height()); // if the image has a height, it is loaded
			imageInfo.ratio = (el.naturalWidth ? el.naturalWidth : imageInfo.image.width()) / (el.naturalHeight ? el.naturalHeight : imageInfo.image.height());
			if (imageInfo.loaded)
			{
				updateImageSize(imageInfo);
			}
			else
			{
				el.style.visibility = 'hidden'; // hide the image until it is done loading
				img.bind('load', imageInfo, fullScreenImageLoaded);
			}
		}	
	}
	
	function fullScreenImageLoaded(e)
	{
		var imageInfo, el;
		imageInfo = e.data;
		
		imageInfo.loaded = true;
		el = imageInfo.image.get(0);
		imageInfo.ratio = (el.naturalWidth ? el.naturalWidth : imageInfo.image.width()) / (el.naturalHeight ? el.naturalHeight : imageInfo.image.height());
		updateImageSize(imageInfo);
		imageInfo.image.unbind('load', fullScreenImageLoaded);
		el.style.visibility = null;
	}
	
	
	
	function updateImageSize(/*ImageInfo*/ imageInfo)
	{
		var minWidth, minHeight, newWidthBasedOnHeight, newHeightBasedOnWidth;

		if (!imageInfo.loaded)
			return;
		
		minWidth  = imageInfo.container.width();
		minHeight = imageInfo.container.height();
		
		newHeightBasedOnWidth = parseInt(minWidth / imageInfo.ratio, 10);
		newWidthBasedOnHeight = parseInt(minHeight * imageInfo.ratio, 10);
		
		if (newHeightBasedOnWidth >= minHeight)
		{
			imageInfo.image.css({
				left: 0,
				top: (minHeight - newHeightBasedOnWidth) / 2,
				width: minWidth,
				height: newHeightBasedOnWidth
			});
			
		}
		else //if (newWidthBasedOnHeight >= minWidth)
		{
			imageInfo.image.css({
				left: (minWidth - newWidthBasedOnHeight) / 2,
				top: 0,
				width: newWidthBasedOnHeight,
				height: minHeight
			});
		}
		
	}
	
	function windowResized()
	{
		var a;
		for (a = 0; a < images.length ;a++)
		{
			if (images[a].loaded)
				updateImageSize(images[a]);
		}
	}
	
})(jQuery);

