$(function () {
	var

		//----------------------------------
		//  object
		//----------------------------------
		body = document.body,
		container = document.createElement("div"),	//画像のコンテナ
		img = document.createElement("img"),	//画像

		//----------------------------------
		//  variable
		//----------------------------------
		src = $(body).css("background-image");	//背景画像


	//containerに画像を配置
	if(!src) {
		return;	//背景の指定がなければ終了
	}

	//背景画像の読み込み
	src = src.replace(/url\([\"]*|[\"]*\)/g, "");	//url("hoge.jpg") → hoge.jpg or url(hoge.jpg) → hoge.jpg
	img.src = src + "?" + new Date().getTime();	//キャッシュ回避しつつ読み込み
	$(img).bind("load", function () {
		//デフォルトの縦横サイズを保持
		img.defaultWidth = img.width;
		img.defaultHeight = img.height;

		img.style.width = "100%";
		img.style.height = "100%";

		fit();
		$(window).bind("resize", fit);
//		setInterval(fit, 5000);	//test用
		
		//デフォルトの背景をクリア
		$(body).css({
			backgroundImage: "url(null)"
		});
	});

	//コンテナ、画像の配置
	container.id = "backgroundFit";
	container.style.position = "fixed";
	container.style.top = 0;
	container.style.left = 0;
	container.style.width = "100%";
	container.style.height = "100%";
	container.style.overflow = "hidden";
	container.style.zIndex = -9999;
	container.appendChild(img);
	body.appendChild(container);

	if (typeof document.documentElement.style.maxHeight == "undefined") {
		//IE6の場合のposition: fixed指定
		container.style.position = "absolute";
		container.style.setExpression("top", "eval(documentElement.scrollTop)");
	}


	/**
	 * 画像を画面にフィット
	 *
	 */
	function fit() {
		var containerWidth = $(container).width(),
			containerHeight = $(container).height(),
			ratioH = containerWidth / img.defaultWidth,
			ratioV = containerHeight / img.defaultHeight,
			ratio;

		//縦横比率を保持
		if(ratioH < 1 && ratioV < 1) {
			ratio = 1;
			//等倍未満にはならないように
		}
		else if(ratioH < ratioV) {
			ratio = ratioV;
		}
		else if(ratioV < ratioH) {
			ratio = ratioH;
		}

//		setTimeout(function () {
			img.style.width = img.defaultWidth * ratio + "px";
			img.style.height = img.defaultHeight * ratio + "px";

//			console.log("img.style.width = " + img.style.width, "img.style.height = " + img.style.height);

			//縦はtop、横はcenterに配置
			img.style.left = Math.round((containerWidth - $(img).width()) / 2);
//		}, 0);

//		alert("width = " + img.style.width + ", height" + img.style.height);
//		alert(["ratioH = " + ratioH, "ratioV =" + ratioV].join(", "));
	}
});
