(function ($) {
	// Correctly sizes background image
	$.fn.sizeBackground = function (pageX, pageY, speed) {
	
		// Disable IE
		//if ($.browser.msie && $.browser.version < 7) return $(this);
		
		var $container = $(this).parent();

		// Make sure site conainer is hiding the overflizzle
		$container.css('overflow', 'hidden');
	
		// If no speed was set, this should happen instantly
		if (!speed) var speed = 0;
		
		// If speed is 0, we just disable animations to kill animation overhead
		if (!speed) jQuery.fx.off = true;
	
		// Remove constraining attributes
		$(this).removeAttr('width').removeAttr('height');
		
		// Get all the measurements
		var picX = $(this).width();
		var picY = $(this).height();

		// Make sure the picture is loaded and measureable
		if (!picX || !picY) return;
		
		// Get some more measurements and calculate some ish
		var picAR = picX / picY;
		var pageX = pageX || $container.width();
		var pageY = pageY || $container.height();
		var pageAR = pageX / pageY;
		
		// If the page's aspect ratio is taller than that of the image, stretch the image vertically
		if (pageAR < picAR) {
		
			// Calculate new dimensions
			var newPicY = pageY;
			var newPicX = Math.round(picX * (newPicY / picY));
			
			// Center the image
			var newPicOffset = (newPicX - pageX) / 2;
			$(this).animate({
				top: 0,
				left: -newPicOffset,
				height: newPicY,
				width: newPicX
			}, speed);
			
		// Otherwise it's wider (or exactly the same, I suppose), so stretch it horizontally
		} else {
			
			// Calculate new dimensions
			var newPicX = pageX;
			var newPicY = Math.round(picY * (newPicX / picX));
			
			// Set new dimensions
			$(this).height(newPicY).width(newPicX);
			
			// Vetically align the image
			var newPicOffset = (newPicY - pageY) / 2;
			$(this).animate({
				top: -newPicOffset,
				left: 0
			}, speed);
			
		}
		
		// Turn animations back on
		jQuery.fx.off = false;
		
		// Pass back object when done
		return $(this);
		
	}
}(jQuery));

