$(function() {

var wrapper = $("body").children("#wrapper"),
	content = wrapper.children("#content"),
	bg = $("#liquidbg"),
	file = "shared/xml/background.xml",
	doFadeIn = false,
	doCentering = false,
	stageMinWidth = 930,
	stageMinHeight = 600,
	imageWidth,
	imageHeight,
	ie = jQuery.browser.msie,
	de = document.documentElement;



if (!wrapper.length || !content.length || !bg.length) {
	alert("This library need 'wrapper', 'liquidbg' and 'content' id in the body.");
	return;
}

// load xml file.
$.ajax({
	url: file,
	type: "GET",
	dataType: "xml",
	error: function() {
		alert("Error: fail to open file '" + file + "'.");
	},
	success: function(xml) {
		
		// get the setting to do fadein at boot time.
		doFadeIn = ($(xml).find("background").attr("fadein") == "true");
		
		// get the setting to do centering or not.
		doCentering = ($(xml).find("background").attr("centering") == "true");
		
		// get random file.
		var files = $(xml).find("file"),
			rnd = Math.floor(Math.random() * files.length);
		
		loadImage(
			bg[0],
			$(files[rnd]).attr("url")
		);
	}
});

// resize.
$(window).resize(function() {
	
	var w = ie ? de.clientWidth : window.innerWidth,
		h = ie ? de.clientHeight : window.innerHeight,
		rw, rh, ww, hh, x, y;

	if (stageMinWidth && w < stageMinWidth) w = stageMinWidth;
	if (stageMinHeight && h < stageMinHeight) h = stageMinHeight;
	
	wrapper
		.css("width", w)
		.css("height", h);
	
	bg
		.css("width", w)
		.css("height", h);
	
	if (imageWidth && imageHeight) {
		
		// get ratio
		rw = imageWidth / w;
		rh = imageHeight / h;
		
		// resize stage size.
		if (rw < rh) {
			ww = w;
			hh = imageHeight * w / imageWidth;
		} else {
			ww = imageWidth * h / imageHeight;
			hh = h;
		}
		
		if (doCentering) {
			x = (w - ww) / 2;
			y = (h - hh) / 2;
		} else {
			x = 0;
			y = 0;
		}
		
		$("#LiquidBGImage")
			.css("width", ww)
			.css("height", hh)
			.css("left", x)
			.css("top", y);
	}
});

// load image file.
function loadImage(target, url) {
	
	$("<img src='" + url + "'/>")
		.attr("id", "LiquidBGImage")
		//.attr("src", url)	// opera cannot work this src attribute!!
		.css("left", -5000)	// avoid appearing boot noise for safari & chrome.
		.load(function(){
			imageWidth = $(this).attr("width");
			imageHeight = $(this).attr("height");
			
			$(this)
				.hide()
				.css("left", 0);
				
			if (doFadeIn)
				$(this).fadeIn("slow");
			else
				$(this).show();
			
			$(window).resize();
		})
		.appendTo(target);
}

// initial resize of content for opera.
$(window).resize();

});

