function LightBoxFactory(selector) {
	$(selector).each(function() {
		new LightBox(this);
	});
}

function LightBox(el) {
	this.el = $(el);
	this.width = this.el.width();
	this.height = this.el.height();
	
	this.initialized = false;
	
	var lightBox = this;
	this.el.click(function() {
		page_view($(this).attr('id'));
		lightBox.onClick.apply(lightBox);
	});
}

LightBox.prototype = {
	padding: 10,
	overlayTemplate: '<div class="overlay"></div>',
	containerTemplate: '<div class="lightbox"></div>',
	headTemplate: '<div class="hd"></div>',
	bodyTemplate: '<div class="bd"><span class="wrap"><img /></span></div>',
	footerTemplate: '<div class="ft"><button>关闭</button></div>',
	initialize: function() {	
		if (this.initialized) {
			return;
		}	
		this.container = $(this.containerTemplate);
		
		this.head = $(this.headTemplate);
		
		this.head.text(this.el.attr('title'));
		
		this.body = $(this.bodyTemplate);
		$('img', this.body).attr('src', this.el.attr('src'));
		this.footer = $(this.footerTemplate);
		var lightBox = this;
		$('button', this.footer).click(function() { lightBox.hide(); } );
		
		this.container.append(this.head);
		this.container.append(this.body);
		this.container.append(this.footer);
		
		this.overlay = $(this.overlayTemplate);
		
		$('body').append(this.container);
		$('body').append(this.overlay);
		
		this.width = this.container.width();
		
		this.container.hide();
		this.overlay.hide();
		
		this.overlay.width(this.width + this.padding * 2);
		this.overlay.height(this.container.height() + this.padding * 2);
		
		this.initialized = true;
	},
	adjustPosition: function() {
		var de = document.documentElement;
		var db = document.body;
		
		var width = de.clientWidth;
		var height = de.clientHeight;

		var underlay = this.overlay;
		var el = this.container;
		
		if (width == 0) {
			width = db.clientWidth;
			underlay.width(el.width() + this.padding * 2);
		}
		
		if (height == 0) {
			height = db.clientHeight;
			underlay.height(el.height() + this.padding * 2);
		}

		var top = (height- el.height()) / 2 + de.scrollTop;
		var left = (width - el.width()) / 2;
		
		this.container.css('top', top + 'px');
		this.container.css('left', left + 'px');
		
		this.overlay.css('top', (top - this.padding) + 'px');
		this.overlay.css('left', (left - this.padding) + 'px');
	},
	show: function() {
		if (!this.initialized) {
			this.initialize();
		}
		this.adjustPosition();
		this.overlay.show();
		this.container.fadeIn();
	},
	hide: function() {
		this.overlay.hide();
		this.container.fadeOut();
	},
	onClick: function() {
		this.show();
	}
}

