window.resizeBgImg = {options: null};
var resizeBgImg = function(){
	this.setConfig = function(){
		window.resizeBgImg.options = { }
		this.setContainerOptions();
		this.setImageOptions();
	}
	
	this.setContainerOptions = function(){
		window.resizeBgImg.options.container = {
			element: $('#background-image'), 
			width: $(window).width(), 
			height: $(window).height() 
		}
	
	}
	this.setImageOptions = function(){
		var img = new Image();
		var lc = $('<div style="height:0px;width:0px;overflow:hidden;"></div>').appendTo('body');
		$(img).appendTo(lc);
		img.src = '';
		window.resizeBgImg.options.image = { 
			element: $('#background-image img'),
			width: $('#background-image img').width(),
			height: $('#background-image img').height()
		}
	
		$(img).load(function(){
			window.resizeBgImg.options.image.width = $(img).width();
			window.resizeBgImg.options.image.height = $(img).height();
				
			$(lc).remove();
		});
		img.src = $('#background-image img').attr('src')+'?'+Math.random();
	}
	
	this.resize = function(){
		if(window.resizeBgImg.options == null) this.setConfig();
		else this.setContainerOptions();
		/*
			script has 3 possible initialization points: body, window load, and image load.
		*/
		if(window.resizeBgImg.options.image.height == 0){
			this.setImageOptions();
			window.resizeBgImg.options.image.element.css({width: window.resizeBgImg.options.container.width+'px', top: '0px', left: '0px'});
			return;
		}
		// ratio
		// ceil is used as fix for precision problems, since the image should always be larger then or equal to the container, ceil can be used.
		var rPrecisionModifier  = Math.pow(10, 4);
		var rw = Math.ceil((window.resizeBgImg.options.image.width/window.resizeBgImg.options.image.height) * rPrecisionModifier) / rPrecisionModifier;
		var rh = Math.ceil((window.resizeBgImg.options.image.height/window.resizeBgImg.options.image.width) * rPrecisionModifier) / rPrecisionModifier;

		var h = Math.ceil(window.resizeBgImg.options.container.height);
		var w = Math.ceil((window.resizeBgImg.options.container.height*rw));
		if(window.resizeBgImg.options.container.width>w){
			w = Math.ceil(window.resizeBgImg.options.container.width);
			h = Math.ceil(window.resizeBgImg.options.container.width*rh);
		}
		var x = Math.ceil(((window.resizeBgImg.options.container.width-w)/2));
		var y = Math.ceil(((window.resizeBgImg.options.container.height-h)/2));
		
		window.resizeBgImg.options.image.element.css({height: h+'px', width: w+'px', top: y+'px', left: x+'px'});
	
	}
	this.resize();

}

$(window).load(function(){ resizeBgImg();  }).resize(function(){ resizeBgImg(); });
$(function(){ $('#background-image img').load(function(){ resizeBgImg(); }); });


