var containerObj;

(function($) {
	
	$.fn.ezBgResize = function(options) {
		// First position object
		containerObj = this;
		
		containerObj.css("visibility","hidden");
		
		$(window).load(function() {
			resizeImage();
		});


        $(window).bind("resize",function() {
            resizeImage();
        });
	};
	
	function resizeImage() {
		
		containerObj.css({
			"position":"fixed",
			"top":"0px",
			"left":"0px",
			"z-index":"-1",
			"overflow":"hidden",
			"width":getWindowWidth() + "px",
			"height":getWindowHeight() + "px"
		});
		
	
		var iw = containerObj.children('img').width();
		var ih = containerObj.children('img').height();

        var windowHeight = getWindowHeight();
        var windowWidth  = getWindowWidth();

		if (windowWidth > windowHeight) {
			if (iw > ih) {
				var fRatio = iw/ih;
				containerObj.children('img').css("width",windowWidth + "px");
				containerObj.children('img').css("height",Math.round(windowWidth * (1/fRatio)));

				var newIh = Math.round(windowWidth * (1/fRatio));

				if(newIh < windowHeight) {
					var fRatio = ih/iw;
					containerObj.children('img').css("height",windowHeight);
					containerObj.children('img').css("width",Math.round(windowHeight * (1/fRatio)));
				}
			} else {
				var fRatio = ih/iw;
				containerObj.children('img').css("height",windowHeight);
				containerObj.children('img').css("width",Math.round(windowHeight * (1/fRatio)));
			}
		} else {
			var fRatio = ih/iw;
			containerObj.children('img').css("height",windowHeight);
			containerObj.children('img').css("width",Math.round(windowHeight * (1/fRatio)));
		}
		containerObj.css("visibility","visible");
	}

	
	function getWindowHeight() {
        return $(document).height();
	}
	
	function getWindowWidth() {
		return $(document).width();
	}
})(jQuery);

