/******************************************************
	* jQuery plug-in
	* Easy Background Image Resizer
	* Developed by J.P. Given (http://johnpatrickgiven.com)
	* Useage: anyone so long as credit is left alone
******************************************************/

var containerObj;

(function(jQuery)
{
	// plugin definition
	jQuery.fn.ezBgResize = function(options)
	{
		containerObj = this;
		containerObj.css("visibility", "hidden");
		
		iw = containerObj.children('img').width();
		ih = containerObj.children('img').height();
		
		jQuery(window).load(function()
		{
			resizeImage();
		});
		
		jQuery(window).resize(function()
		{
			resizeImage();
		});
	};
	
	function resizeImage()
	{
		width = getWindowWidth();
		height = getWindowHeight();
		
		containerObj.css(
		{
			"position": "fixed",
			"top": "0px",
			"left": "0px",
			"z-index": "-1",
			"overflow": "hidden",
			"width": width + "px",
			"height": height + "px"
		});
		
		if (width > height)
		{
			scaleX = iw / width;
			scaleY = ih / height;
			
			new_width = Math.round(iw * (1 / scaleX));
			new_height = Math.round(ih * (1 / scaleX));
			
			if (new_height < height)
			{
				new_width = Math.round(iw * (1 / scaleY));
				new_height = Math.round(ih * (1 / scaleY));
			}
		}
		else
		{
			scaleY = ih / height;
			scaleX = iw / width;
			
			new_width = Math.round(iw * (1 / scaleY));
			new_height = Math.round(ih * (1 / scaleY));
			
			if (new_width < width)
			{
				new_width = Math.round(iw * (1 / scaleX));
				new_height = Math.round(ih * (1 / scaleX));
			}
		}
		
		containerObj.children('img').css("width", new_width + "px");
		containerObj.children('img').css("height", new_height + "px");
		
		containerObj.css("visibility", "visible");
	}
	
	function getWindowHeight()
	{
		var windowHeight = 0;
		
		if (typeof(window.innerHeight) == 'number') windowHeight = window.innerHeight;
		else
		{
			if (document.documentElement && document.documentElement.clientHeight) windowHeight = document.documentElement.clientHeight;
			else
			{
				if (document.body && document.body.clientHeight) windowHeight = document.body.clientHeight;
			}
		}
		
		return windowHeight;
	};
	
	function getWindowWidth()
	{
		var windowWidth = 0;
		
		if (typeof(window.innerWidth) == 'number') windowWidth = window.innerWidth;
		else
		{
			if (document.documentElement && document.documentElement.clientWidth) windowWidth = document.documentElement.clientWidth;
			else
			{
				if (document.body && document.body.clientWidth) windowWidth = document.body.clientWidth;
			}
		}
		
		return windowWidth;
	};
	
})(jQuery);
