var Lightbox = {
	init: function(options){
	
		this.options = Object.extend({
			initialWidth: 0,
			initialHeight: 0,
			defaultIframeWidth : 500, 
			defaultIframeHeight: 300
		}, options || {});

		this.anchors = [];
		$each(document.links, function(el){
			if (el.rel && el.rel.test(/^lightbox/i)){
				el.onclick = this.click.pass(el, this);
				this.anchors.push(el);
			}
		}, this);
		this.eventKeyDown = this.keyboardListener.bindAsEventListener(this);
		this.eventPosition = this.position.bind(this);

		this.overlay = new Element('div').setProperty('id', 'mb_overlay').injectInside(document.body);

		// the center element
		this.center = new Element('div').setProperty('id', 'mb_center').setStyles({width: this.options.initialWidth+'px', height: this.options.initialHeight+'px', marginLeft: '-'+(this.options.initialWidth/2)+'px', display: 'none'}).injectInside(document.body);
		
		this.lbtop = new Element('div').setProperty('class', 'lbtop').injectInside(this.center);
		//new Element('a').setProperty('class', 'lbc02').injectInside(this.lbtop).onclick = this.close.bind(this);
		new Element('div').setProperty('class', 'lbc02').injectInside(this.lbtop);
		new Element('div').setProperty('class', 'lbc01').injectInside(this.lbtop);
		this.lbintTop = new Element('div').setProperty('class', 'lby01').injectInside(this.lbtop);

		this.lbcon = new Element('div').setProperty('class', 'lbcon').injectInside(this.center);

		// the actual page contents
		this.lbx02 = new Element('div').setProperty('class', 'lbx02').injectInside(this.lbcon);
		this.lbx01 = new Element('div').setProperty('class', 'lbx01').injectInside(this.lbcon);
		this.white = new Element('div').setProperty('class', 'lbWhite').injectInside(this.lbcon);
		this.canvas = new Element('div').setProperty('id', 'mb_contents').injectInside(this.white);


		this.lbbot = new Element('div').setProperty('class', 'lbbot').injectInside(this.center);
		new Element('div').setProperty('class', 'lbc03').injectInside(this.lbbot);
		new Element('div').setProperty('class', 'lbc04').injectInside(this.lbbot);
		this.lbintBot = new Element('div').setProperty('class', 'lby02').injectInside(this.lbbot);

		/* Build effects */
		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.effect('opacity', {duration: 0}).hide(),
			image: this.canvas.effect('opacity', {duration: 500, onComplete: nextEffect})
		};

		this.preloadPrev = new Image();
		this.preloadNext = new Image();
	},

	click: function(link){
		if (link.rel.length == 8) return this.show(link.href, link.title, link.rev);

		var j, itemNumber, items = [];
		this.anchors.each(function(el){
			if (el.rel == link.rel){
				for (j = 0; j < items.length; j++) if(items[j][0] == el.href && items[j][2] == el.rev) break;
				if (j == items.length){
					items.push([el.href, el.title, el.rev]);
					if (el.href == link.href && el.rev == link.rev) itemNumber = j;
				}
			}
		}, this);
		return this.open(items, itemNumber);
	},

	show: function(url, title, rev){
		return this.open([[url, title, rev]], 0);
	},

	open: function(items, itemNumber){
		this.items = items;
		this.position();
		this.setup(true);
		var wh = (window.getHeight() == 0) ? window.getScrollHeight() : window.getHeight();
		var st = document.body.scrollTop  || document.documentElement.scrollTop;
		this.top = st + (wh / 15);
		this.center.setStyles({top: this.top+'px', display: ''});
		this.fx.overlay.start(0.2);
		return this.changeItem(itemNumber);
	},

	position: function(){
		//IE6 - XML prolog problem.
		var ww = (window.getWidth() == 0) ? window.getScrollWidth()-22 : window.getWidth();
		var wh = (window.getHeight() == 0) ? window.getScrollHeight() : window.getHeight();
		var st = document.body.scrollTop  || document.documentElement.scrollTop;
		this.overlay.setStyles({top: st+'px', height: wh+'px', width:ww+'px'});
	},

	setup: function(open){
		var elements = $A(document.getElementsByTagName('object'));
		if (window.ie) elements.extend(document.getElementsByTagName('select'));
		elements.each(function(el){ el.style.visibility = open ? 'hidden' : ''; });
		var fn = open ? 'addEvent' : 'removeEvent';
		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
		document[fn]('keydown', this.eventKeyDown);
		this.step = 0;
	},

	keyboardListener: function(event){
		switch (event.keyCode){
			case 27: case 88: case 67: this.close(); break;
			case 37: case 80: this.previous(); break;	
			case 39: case 78: this.next();
		}
	},

	previous: function(){
		return this.changeItem(this.activeItem-1);
	},

	next: function(){
		return this.changeItem(this.activeItem+1);
	},

	changeItem: function(itemNumber){
		if (this.step || (itemNumber < 0) || (itemNumber >= this.items.length)) return false;
		this.step = 1;
		this.activeItem = itemNumber;

		this.fx.image.hide();
		this.center.className = 'lbLoading';

		// discard previous content by clicking
		this.removeCurrentItem();
		
		// check item type
		var url = this.items[this.activeItem][0];
		var rev = this.items[this.activeItem][2];
		
		var re_imageURL = /\.(jpe?g|png|gif|bmp)/i;
		if( url.match(re_imageURL) ) {
			this.preload = new Image();	// JavaScript native Object
			this.preload.datatype = 'image';
			this.preload.w = this.matchOrDefault(rev, new RegExp("width=(\\d+%?)", "i"), -1); //-1 if use original size.
			this.preload.h = this.matchOrDefault(rev, new RegExp("height=(\\d+%?)", "i"), -1);
			this.preload.onload = this.nextEffect.bind(this);
			this.preload.src = url;
		}else{
			this.preload = new Object ();	// JavaScript native Object
			this.preload.datatype = 'iframe';
			this.preload.w =  this.matchOrDefault(rev, new RegExp("width=(\\d+)", "i"), this.options.defaultIframeWidth);
			this.preload.h = this.matchOrDefault(rev, new RegExp("height=(\\d+)", "i"), this.options.defaultIframeHeight);
			this.preload.src = url;
			this.nextEffect(); //asynchronous loading
		}

		this.lbintTop.setStyle('width', this.preload.w + "px");
		this.lbintBot.setStyle('width', this.preload.w + "px");
		this.lbx02.setStyle('height', this.preload.h + "px");
		this.lbx01.setStyle('height', this.preload.h + "px");
		this.lbcon.setStyle('width', (parseInt(this.preload.w) + 70) + "px");

		return false;
	},

	nextEffect: function(){
		switch (this.step++){
		case 1:
			this.center.className = '';

			// create HTML element
			if( this.preload.datatype == 'image' ) {
				var ws = (this.preload.w == -1) ? this.preload.width.toString() : this.preload.w.toString();
				var hs = (this.preload.h == -1) ? this.preload.height.toString() : this.preload.h.toString();
				this.p_width = ( q = ws.match(/(\d+)%/) ) ? q[1] * this.preload.width * 0.01 : ws;
				this.p_height = ( q = hs.match(/(\d+)%/) ) ? q[1] * this.preload.height * 0.01 : hs;
				new Element('img').setProperties({id: 'lbImage', src:this.preload.src, width:this.p_width, height:this.p_height}).injectInside(this.canvas);
			}else{
				this.p_width = this.preload.w;
				this.p_height = this.preload.h;
				// Safari would not update iframe content that has static id.
				this.iframeId = "lbFrame_"+new Date().getTime();
				new Element('iframe').setProperties({id: this.iframeId, width: this.p_width, height: this.p_height, frameBorder:0, scrolling:'auto', src:this.preload.src}).injectInside(this.canvas);
			}
			this.canvas.style.width = this.p_width+'px';
			this.canvas.style.height = this.p_height+'px';

			if (this.activeItem) this.preloadPrev.src = this.items[this.activeItem-1][0];
			if (this.activeItem != (this.items.length - 1)) this.preloadNext.src = this.items[this.activeItem+1][0];
			if (this.center.clientHeight != this.canvas.offsetHeight){
				var oh = (this.p_height == this.canvas.clientHeight) ? parseInt(this.canvas.offsetHeight) + 70 : eval(this.p_height)+18; // fix for ie
				this.center.setStyle('height', oh);
				this.nextEffect();
				break;
			}

			this.step++;
		case 2:
			if (this.center.clientWidth != this.canvas.offsetWidth){
				var ow = (this.p_width == this.canvas.clientWidth) ? parseInt(this.canvas.offsetWidth) + 70 : eval(this.p_width)+18; // fix for ie
				this.center.setStyles({width: ow, marginLeft: -ow/2});
				this.nextEffect();
				break;
			}
			this.step++;
		case 3:
			this.fx.image.start(1);
			break;
		case 4:
		
			this.step = 0;
		}
	},

close: function(){
		if (this.step < 0) return;
		this.step = -1;
		this.removeCurrentItem();	// discard content
		for (var f in this.fx) this.fx[f].stop();
		this.center.style.display = 'none';
		this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
		this.center.setStyles({width: this.options.initialWidth+'px', height: this.options.initialHeight+'px'});
		return false;
	},

	removeCurrentItem: function(){
		if (this.preload){
			if( this.preload.datatype == 'image' ) {
				$('lbImage').remove();
				this.preload.onload = Class.empty;
			}else{
				$(this.iframeId).remove();
			}
			this.preload = null;
		}		
	},

	matchOrDefault: function(str, re, val){
		var hasQuery = str.match(re);
		return hasQuery ? hasQuery[1] : val;
	}

};
//window.addEvent('domready', Lightbox.init.bind(Lightbox));
var load_method = (window.ie ? 'load' : 'domready');
window.addEvent(load_method, Lightbox.init.bind(Lightbox));
