(function($) {
	$.setFullscreenImage = function(url) {
		var $window = $(window);
		var $bg, bg_width, bg_height, aspectRatio;
		
		// create bg image
		var $bg = $('#bg');
		if ($bg.length == 0) {
			var $bg = $('<img />', { id: 'bg', alt: '', css: { position: 'fixed', top: 0, left: 0 }	}).prependTo('body'); // create image if not already done
		}
		
		if (url == $bg.attr('src')) return;
		
		var update = function() {
			var window_width = $window.width();
			var window_height = $window.height();
			aspectRatio = bg_width/bg_height;
			
			if ( (window_width / window_height) < aspectRatio ) {
				var new_width = Math.ceil(window_height*aspectRatio);
				$bg.css({
					width: new_width,
					height: window_height,
					marginTop: 0,
					marginLeft: (window_width-new_width)/2 // center the image horizontally
				});
			} else {
				var new_height = Math.ceil(window_width/aspectRatio);
				$bg.css({
					width: window_width,
					height: new_height,
					marginTop: (window_height-new_height)/2, // center the image vertically
					marginLeft: 0
				}); 
			}
		}

		var onpreload = function() {
			// src has to be set after attaching the onload handler
			// otherwise the image could be loaded from cache before the onload handler is attached
			// so the onload event will not be triggered (in IE the case)
			$bg.load(function(){
				// reset CSS because we would get wrong dimensions
				$bg.css({ width: 'auto', height: 'auto' });
				
				bg_width = $bg.width();
				bg_height = $bg.height();
				update();
				$bg.show();
			}).attr('src', url); // set new image url
		}
		
		$bg.hide();

		// add event on trigger on load
		$window.unbind('resize', update).bind('resize', update);

		// wait for image loading completed
		$('<img />').load(onpreload).attr({ src: url });
	};
})(jQuery);


