$(function() {

var wrapper = $("body").children("#wrap"),
    content = wrapper.children("#content"),
	file = "bg.xml",
	doFadeIn = false,
	doCentering = false,
	imageWidth,
	imageHeight,
	ie = jQuery.browser.msie,
	de = document.documentElement;

if (!wrapper.length || !content.length) {
	alert("This library need 'wrap' 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"),
			$(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;
	
	$("#wrap")
		.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;
		}
		
		$("#bgimage")
			.css("width", ww)
			.css("height", hh)
			.css("left", x)
			.css("top", y);
	}
});

// load image file.
function loadImage(target, url) {
	
	$("<img src='" + url + "'/>")
		.attr("id", "bgimage")
		//.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();

});

