function initImageBox(){
	var bpadding = 20;
	$("body").append('<div id="overlay"></div><img id="ibpic" src="" alt="" title="" /><div id="ibloading"></div>');
	
	$('a[@rel=lightbox]').click(function(){
		$(this).blur();
		$("#ibloading").fadeIn(300);
		$("#overlay").fadeIn();
		var pagesize = getPageSize();
		
		preload_image = new Image();
		preload_image.src = $(this).attr('href');
		
		preload_image.onload = function(){
			$("#ibpic").attr({ src: preload_image.src });
			
			var pwidth = preload_image.width;
			var pheight = preload_image.height;
			var pwidth2 = 0;
			var pheight2 = 0;
			
			function fixdimensions(){
				if(pwidth > pagesize[0]){
					pwidth2 = pagesize[0]-150;
					if(pwidth2 <= 200) {pwidth2 = 200};
					pheight2 = (pheight*pwidth2)/pwidth;
					pwidth = pwidth2;
					pheight = pheight2;
				}else if(pheight > pagesize[1]){
					pheight2 = pagesize[1]-150;
					if(pheight2 <= 200) {pheight2 = 200};
					pwidth2 = (pwidth*pheight2)/pheight;
					pwidth = pwidth2;
					pheight = pheight2;
				}
				$("#ibpic").attr({ width: pwidth, height: pheight });
			}
			
			fixdimensions();
			
			var marginleft = (pwidth+2*bpadding)/2;
			var margintop = (pheight+2*bpadding)/2;

			$("#ibloading").fadeOut(100, function(){
				$("#ibpic").css({ padding: bpadding+"px", marginLeft: -marginleft+"px", marginTop: -margintop+"px" });
				$("#ibpic").fadeIn(300);
			});
		}
		return false;
	});
	$("#overlay").click(function(){ ibclose(); });
	$("#ibpic").click(function(){ ibclose(); });
	$("#ibloading").click(function(){ ibclose(); });
}

function ibclose(){
	$("#ibloading").hide();
	$("#ibpic").fadeOut(500);
	$("#overlay").fadeOut(500);
	$("#ibpic").attr({ src: '' });
}

function getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
	arrayPageSize = new Array(w,h) 
	return arrayPageSize;
}

$(document).ready(function() {
	initImageBox();
});