(function(window, $){

	var tbLightBox = function(el) {
		var self = this;
		
		this.el = el;
		this.content = null;
		
		this.isImage = this.el.hasClass("lightbox-image");
		
		var u = el.attr("href");
		u = u.split("?");
		this.url = u[0];
		this.offset = this.el.offset();
		
		u = u[1].split("&");
		u[0] = u[0].replace("x=", "");
		u[1] = u[1].replace("y=", "");
		
		this.x = parseInt(u[0], 10);
		this.y = parseInt(u[1], 10);
		
		var $body = $("body");

		var w = $(window);	
		var d = $(document);
		
		this.bg = $("<div />", {
			"class": "lightbox-content",
			width: w.width(),
			height: d.height()
		}).hide().appendTo($body);
		
		this.bg.click(function(){
			self.hide();
		});
		
		this.lightbox = $("<div />", {
			"class": "lightbox-body",
			width: self.x,
			height: self.y
		});
		
		this.closeButton = $("<div />", {
			"class": "lightbox-close",
			html: "&nbsp;"
		}).appendTo(this.lightbox);
		
		this.lightboxContent = $("<div />", {
			"class": "lightbox-content-box",
			html: "&nbsp;",
			width: self.x,
			height: self.y
		}).appendTo(this.lightbox);		
		
		this.lightbox.hide();
		
		$($body).append(this.lightbox);
		
		el.click(function() {
			if (self.isImage) {
				self.loadAndShowImage();				
			} else {
				self.loadAndShow();
			}
			return false;
		});
		
		this.closeButton.click(function(){
			self.hide();
		});
	}
	
	tbLightBox.prototype.show = function() {
		autoHideLightBox();
		var w = $(window);
		var d = $(document);
		var t = (w.height() - this.y) / 2+w.scrollTop();
		var l = (w.width() - this.x) / 2+w.scrollLeft()

		this.lightbox.css({left: l, top: t});
		this.lightbox.show();
		
		this.bg.css({height: d.height() + w.scrollTop()});
		this.bg.show();		
	}
	
	tbLightBox.prototype.hide = function() {
		this.bg.hide();
		this.lightbox.hide();
	}
	
	tbLightBox.prototype.loadAndShowImage = function() {
		if (this.content == null) {
			this.content = "<img src=" + this.url + " />";
			this.lightboxContent.html(this.content);
		}
		this.show();
	}
	
	tbLightBox.prototype.loadAndShow = function() {
		var self = this;
		if (this.content == null) {
			$.ajax({
				url: self.url,
				dataType: "html",
				
				success: function(result) {
					self.content = result;
					self.lightboxContent.html(result);
					self.show();
				}
			});
		} else {
			self.show();
		}
	}
	
	var lbList = [];
	
	window.initTbLightBox = function(links) {
		links.each(function(){
			var t = new tbLightBox($(this));
			lbList.push(t);
		});
	}
	
	var autoHideLightBox = function() {
		for (var i=0, l= lbList.length; i < l; i++) {
			lbList[i].hide();
		}		
	}
	
	$(document).click(function(){
		//autoHideLightBox();
	});
	
})(window, jQuery);
