$(document).ready(function(){
	var bgimageloaded = false;
	var orgx = $("#tiledbgwidth").text();
	var orgy = $("#tiledbgheight").text();
	var tiles = new Array();
	var maxi = 0;
	var loadorder = new Array(3, 5, 6, 8, 7, 0, 2, 4, 1);
	$(".bg_3x3").each(function(){
		var i = tiles.length;
		maxi = i;
		tiles[i] = new Array();
		tiles[i]["ref"] = $(this);
		tiles[i]["loaded"] = false;
	});
	var tilecounter = 0;
	$(".tiledata").each(function(){
		tiles[tilecounter]["orgx"] = $(this).find(".tilewidth").text();
		tiles[tilecounter]["orgy"] = $(this).find(".tileheight").text();
		tiles[tilecounter]["src"] = $(this).find(".tilesrc").text();
		tilecounter++;
	});
	$("#bgimage").one('load', function(){
		bgimageloaded = true;
		setBGSize($(this));
		loadHighResBG(0);
		return true;
	}).each(function(){
		if(this.complete){
			$(this).load();
		}
	});

	$(window).resize(function(){
		if(bgimageloaded){
			setBGSize($("#bgimage"));
		}
		return true;
	});

	function loadHighResBG(i){
		var thumbname = "images/public/thumb/"+tiles[loadorder[i]]["ref"].width()+"/"+tiles[loadorder[i]]["ref"].height()+"/"+tiles[loadorder[i]]["src"]+"_thumb_"+tiles[loadorder[i]]["ref"].width()+"_"+tiles[loadorder[i]]["ref"].height()+".jpeg";
		tiles[loadorder[i]]["ref"].attr("src", thumbname);
		tiles[loadorder[i]]["ref"].attr("alt", i);
		tiles[loadorder[i]]["ref"].load(function(){
			var thisi = parseInt($(this).attr("alt"));
			var nexti = thisi + 1;
			if(nexti <= maxi){
				loadHighResBG(nexti);
			}
		});
	}

	function setBGSize(target){
		var wdx = $(window).width();
		var wdy = $(window).height();
	//	$("#bgimage").addClass(wdx+"x"+wdy);
	//	$("#bgimage").removeClass(wdx+"x"+wdy);
		var idx = target.width();
		var idy = target.height();
		var aspect = idx / idy;
		var newdx = wdx;
		var newdy = newdx / aspect;
		if(newdy < wdy){
			newdy = wdy;
			newdx = newdy * aspect;
		}
		var scale = orgx / newdx;
		target.css("width", newdx+"px");
		target.css("height", newdy+"px");
		$("#tiledbg").css("width", newdx+"px");
		$("#tiledbg").css("height", newdy+"px");
		var n = tiles.length;
		var i = 0;
		var tmpdx = 0;
		var tmpdy = 0;
		for(i=0;i<n;i++){
			tmpdx = Math.floor(tiles[i]["orgx"] / scale);
			tmpdy = Math.floor(tiles[i]["orgy"] / scale);
			tiles[i]["ref"].css("width", tmpdx+"px");
			tiles[i]["ref"].css("height", tmpdy+"px");
		}
		var offsetx = (wdx / 2) - (newdx / 2);
		var offsety = (wdy / 2) - (newdy / 2);
		$("#bgimage").css("left", offsetx+"px");
		$("#bgimage").css("top", offsety+"px");
		$("#tiledbg").css("left", offsetx+"px");
		$("#tiledbg").css("top", offsety+"px");
	}
});

