var backgroundWidth = 0;
var backgroundHeight = 0;
var backgroundEnabled = false;
var backgroundCssKey = "backgroundAttachment";
var backgroundCssValue = "fixed";

/*
 * Gets the height of the document.
 */
function getDocHeight(){
	return Math.max(
		$(document).height(),
		$(window).height(),
		/* For opera: */
		document.documentElement.clientHeight
	);
};

/*
* Gets the width of the document.
*/
function getDocWidth(){
	return Math.max(
		$(document).width(),
		$(window).width(),
		/* For opera: */
		document.documentElement.clientWidth
	);
};

function SetBackgroundProperties(key, value) 
{
	backgroundCssKey = key;
	backgroundCssValue = value;
}

/*
 * Initizes the background.
 */
function BackgroundInit() {
   backgroundEnabled = $("body").css(backgroundCssKey).toLowerCase() == (backgroundCssValue);

   if(backgroundEnabled == true) {
		var imageSource = $("body").css("backgroundImage");
	
		imageSource = imageSource.substring(4);
		imageSource = imageSource.substring(0, imageSource.length-1);
		imageSource = imageSource.replace(/\"/g, '');
		
		var image = new Image();
		image.src = imageSource;

		backgroundWidth = image.width;
		backgroundHeight = image.height;

		$("body").prepend('<div id="bgholder" style="width:1px;height:1px;left: 0px;top: 0px;position: absolute;z-index: -1;overflow:hidden"><img id="bg" src="' + imageSource + '" style="width:1px;height:1px;left: 0px;top: 0px;position: absolute;z-index: -1;overflow:hidden" /></div>');
		
		BackgroundResize();
	}
}

/*
 * Invokes an action on the background on a window resize.
 */
function BackgroundWindowResize() {
	if(backgroundEnabled == true) {
			BackgroundReset();
   }
}

/*
 * Resets the background.
 */
function BackgroundReset() {
	var element = $("#bg");		
	element.css("width", "1px");
	element.css("height", "1px");
	
	element = $("#bgholder");	
	element.css("width", "1px");
	element.css("height", "1px");
	
	setTimeout(BackgroundResize, 0);
}

/*
 * Resizes the background.
 */
function BackgroundResize() {
   var docWidth = getDocWidth();
	var docHeight = getDocHeight();

	var imgWidth = backgroundWidth;
	var imgHeight = backgroundHeight;
	
	var scale = 1;

	var scaleWidth = docWidth / imgWidth;
	var scaleHeight = docHeight / imgHeight;
	
	if(scaleWidth > scaleHeight) 
	{
		scale = scaleWidth
	}
	else {
		scale = scaleHeight
	}
	
	var widthValue = (imgWidth * scale) + "px";
	var heightValue = (imgHeight * scale)  + "px";

	var element = $("#bg");		
	element.css("width", widthValue);
	element.css("height", heightValue);
	
	element = $("#bgholder");	
	element.css("width", docWidth + "px");
	element.css("height", docHeight + "px");
 }
 
 // Hook a background resize to the window resize event.
$(window).resize(BackgroundWindowResize);

// Hook a background init tot the document ready event.
$(document).ready(BackgroundInit);
