var baseurl = "images/";

function pad(num) {
	if (typeof num == 'number') num = num.toString();
	if (num.length == 1) num = "0" + num;
	return num;
}

function loadImgs(from, to) {
	$("<img/>").attr("src", baseurl + pad(from) + ".jpg").load( function() { if (from < to) loadImgs(from+1, to); });
}

var switchPic = function() {
	var obj = $(this);
	switchPic.to = parseInt(obj.attr("rel"), 10);
	if (typeof switchPic.from == 'undefined') switchPic.from = 1;
	var path = baseurl + pad(switchPic.to.valueOf()) + ".jpg";
	
	obj.unbind("click");
	obj.bind("click", function() { return false; } );
	
	$("#big-pic")
		.fadeOut(300)
		.queue(function() { $(this).css("background-image", "url('"+path+"')").dequeue(); })
		.fadeIn(300);
	
	var w = $("#gallery").width();
	//var menuOffset = w/2 - (99/2) + (1 - switchPic.to) * 99;
	var menuOffset = parseInt($("#gallery-menu").css("left")) + (switchPic.from - switchPic.to) * 99
	$("#gallery-menu").animate(
		{ left: menuOffset + "px" },
		600,
		"swing",
		function () { obj.unbind("click"); obj.bind("click", switchPic); switchPic.from = switchPic.to; }
	);
	
	loadImgs(switchPic.to+1, switchPic.to+4);
	
	return false;
}

function reposition() {
	var w = $("#gallery").width();
	$("#gallery-menu").css({"left": w/2 - (99/2) + (1 - switchPic.to) * 99, "top": 10 + "px" });
	$("#img-frame").css({"left": w/2 - (99/2) - 3, "top": 7+"px" });
}

function initWGal() {
	$("#gallery-viewer").append("<div id=\"big-pic\">&nbsp;</div>\n<div id=\"img-frame\">&nbsp;</div>");
	$("#big-pic").css("background-image", "url('"+baseurl+"01.jpg')");
	switchPic.to = 1;

	$(window).resize(reposition).resize();
	//reposition();

	var i = 0;
	$(".gallery-img").each(function() {
		$(this).html("&nbsp;");
		$(this).css("background-position", "-" + i++ * 90 + "px 0");
	});

	$(".gallery-img").bind("click", switchPic);

	loadImgs(switchPic.to, switchPic.to+4);
}

$(document).ready(function() {
	initWGal();
});