;(function($){
	var _image,
		_layout = function($background) {
			if ($background.is(':visible')) {
				$background.css({
					display: 'none',
					position: 'fixed',
					'z-index': -1
				});
			} else {
				$background.fadeIn('fast');
			}
		},
		_resize = function($background) {
			var _pageWidth = $(window).width(),
				_pageHeight = $(window).height(), 
				_toWidth, _toHeight;
			_toWidth = _pageWidth;
			_toHeight = _toWidth / $background.data('originalratio');

			if (_toHeight < _pageHeight) {
				_toHeight = _pageHeight;
				_toWidth = _toHeight * $background.data('originalratio');
			}

			$background.css({
				height: _toHeight.toFixed(2) + 'px',
				width: _toWidth.toFixed(2) + 'px'
			});
		},
		_center = function($background) {
			$background.css({
				left: (-1 * ($background.width() - $(window).width()) / 2).toFixed(2) + 'px',
				top: (-1 * ($background.height() - $(window).height()) / 2).toFixed(2) + 'px'
			});
		}
	  ;

	$.fn.bgimage = function() {
		if (!$(this).length) {
			return this;
		}

		var $background = $(this);

		_image = new Image();
		_image.onload = function() {
			$background.data('originalwidth', this.width);
			$background.data('originalheight', this.height);
			$background.data('originalratio', (this.width / this.height).toFixed(2));

			_layout($background);
			_resize($background);
			_center($background);
			$background.attr('src', this.src);
			_layout($background);
		}
		_image.src = $(this).attr('src');
		if (_image.src.indexOf('?') > -1) {
			_image.src = unescape(_image.src.substring(_image.src.indexOf('?') + 1));
		}

		$(window).bind('resize', function() {
			_resize($background);
			_center($background);
		});

		return this;
	}
})(jQuery);

