$(document).ready(function(){

$(".lightbox").each(function(){
	var lightbox = this;
	this.set = function(path){
		$(".lightbox_large img",this).remove();
		var img = document.createElement("img");
		img.className = "image_border";
		$(img).load(function(){
			this.originalWidth = this.width;
			this.originalHeight = this.height;
			lightbox.resize();
			$(this).fadeTo(250,1);
		});
		$(img).css("opacity",0);
		$(".lightbox_large",this).append(img);
		img.src = "image.php?width=1024&height=1024&path="+path;
		this.show();
	}
	this.show = function(){
		this.resize();
		$(".lightbox_background",this).css('opacity',0);
		$(".lightbox_background",this).fadeTo(250,0.8);
		$(this).css('opacity',1);
		$(this).css('display','block');
	};
	this.hide = function(){
		$(this).fadeTo(250,0,function(){
			$("img",this).remove();
			$(this).css('display','none');
		});
	};
	this.resize = function(){
		try{
			var ww = $(window).width();
			var wh = $(window).height();
			this.style.width = ww+"px";
			this.style.height = wh+"px";
			var m = 16;
			var img = $("img",this).get(0);
			if(!img) return;
			var ow = img.originalWidth;
			var oh = img.originalHeight;
			var cw = $(window).width()-m*2;
			var ch = $(window).height()-m*2;
			var w,h;
			if(ow>cw || oh>ch){
				var oa = ow/oh;
				var ca = cw/ch;
				if(oa>ca){
					w = cw;
					h = w/oa;
				}else{
					h = ch;
					w = h*oa;
				}
			}else{
				w = ow;
				h = oh;
			}
			if(w && h){
				img.style.width = w+"px";
				img.style.height = h+"px";
				
				var t = Math.round((ch-h)/2)+m;
				var l = Math.round((cw-w)/2)+m;
				img.style.top = t+"px";
				img.style.left = l+"px";
			}
		}catch(e){
			alert(e.message);
		}
	};
	$(this).click(function(event){
		lightbox.hide();
	});
	$(".lightbox_background",this).css('opacity',0);
	
	var img = $("img[lightbox]");
	img.click(function(){
		var src = $(this).attr('src');
		var path = unescape(src.match(/path=(.*?)[&$]/,src)[1]);
		lightbox.set(path);
	});
	img.css('cursor','pointer');
});
});

$(window).scroll(function() {
	$(".lightbox").css('top', $(this).scrollTop() + "px");
});
$(window).resize(function() {
	$(".lightbox").each(function(){ this.resize(); });
});