var Popup = new Class({

	Implements: [Options, Events],

	options: {
		/*
		onBeforeLoad: Function.from(),
		onLoad: Function.from(),
		onShow: Function.from(),
		onHide: Function.from(),
		onTransition: Function.from(),
		onCancel: Function.from(),
		multipleChildren: false,
		hideWhenEmpty: false
		*/
	},

	/*
	visible: false,
	enableBeforeLoad: false,
	enableLoad: false,
	*/
	children: [],

	initialize: function(element, options){
		this.element = document.id(element);
		if(options){
			if(options.holder){
				options.holder.addChild(this);
				delete options.holder;
			}
			if(options.onBeforeLoad)
				this.enableBeforeLoad = true;

			if(options.onLoad)
				this.enableLoad = true;
		}

		this.setOptions(options);
	},

	addChild: function(child){
		child.holder = this;
		this.children.include(child);
	},

	show: function(){
		if(this.holder)
			if(!this.holder.shown)
				this.holder.show();
			else if(!this.holder.options.multipleChildren){
				var th = this;
				this.holder.children.each(function(c){if(c != th) c._hide();});
			}

		if(this.enableBeforeLoad)
			this.call(this.onBeforeLoad.bind(this, arguments));

		if(this.enableLoad)
			this.call(this.onLoad.bind(this, arguments));
		else
			this.loadComplete.apply(this, arguments);
	},

	hide: function(){
		if(this.holder && this.holder.visible && this.holder.options.hideWhenEmpty){
			var c = this.holder.children;
			for(var i=0;i<c.length;i++)
				if(c[i].visible && c[i] != this){
					this._hide();
					return;
				}
			this.holder.hide();
			return;
		}
		this._hide();
	},

	_hide: function(){
		if(this.visible){
			this.children.each(function(c){ c._hide(); });
			this.visible = false;
			this.call(this.onHide);
		}
	},

	$next: Function.from(),

	requestQueue: function(popup){
		if(this.holder)
			this.holder.requestQueue(popup);
		else if(this.running){
			(this.$queue = (this.$queue || []).erase(popup)).push(popup);
		} else {
			this.running = true;
			popup.callNext();
		}
	},

	nextInQueue: function(){
		if(this.holder)
			this.holder.nextInQueue();
		else if(this.$queue && this.$queue.length > 0)
			this.$queue.shift().callNext();
		else
			this.running = false;
	},

	call: function(fn){
		// TODO: Check to see if event exists, so we can remove checks in initialize
		this.$next = fn;
		this.requestQueue(this);
	},

	callNext: function(){
		this.running = true;
		this.$next.apply(this);
		this.$next = Function.from();
	},

	cancel: function(){
		if(this.running){
			this.running = false;
			this.$next = false;
			if(this.$queue) this.$queue.empty();
			this.children.each(function(c){c.cancel();});
		}
	},

	complete: function(){
		this.running = false;
		this.nextInQueue();
	},

	loadComplete: function(){
		this.complete.apply(this);

		if(this.visible)
			this.call(this.onTransition.pass(arguments, this));
		else {
			this.visible = true;
			this.call(this.onShow.pass(arguments, this));
		}
	},

	onBeforeLoad: function(){ return this.fireEvent('onBeforeLoad', arguments); },
	onLoad: function(){ return this.fireEvent('onLoad', arguments); },
	onShow: function(){ return this.fireEvent('onShow', arguments); },
	onHide: function(){ return this.fireEvent('onHide', arguments); },
	onTransition: function(){ return this.fireEvent('onTransition', arguments); },
	onCancel: function(){ return this.fireEvent('onCancel', arguments); }
});

Popup.Overlay = new Class({

	Extends: Popup,

	options: {
		/*
		parentElement: false,
		parentPosition: 'bottom',
		className: null,
		*/
		injectWhere: 'bottom',
		fx: {
			duration: 100
		},
		styles: {
			position: 'fixed',
			width: '100%',
			height: '100%',
			top: '0',
			left: '0',
			backgroundColor: '#000000'
		},
		showStyle: {opacity: .8},
		hideStyle: {opacity: 0},
		hideWhenEmpty: true
	},

	initialize: function(options){
		this.setOptions(options);
		var pe = document.id(this.options.parentElement) || document.id(document.body);
		var element = new Element('div', {
			styles: {
				position: 'fixed',
				display: 'none',
				visibility: 'visible',
				width: '100%',
				height: '100%',
				overflow: 'hidden',
				top: 0,
				left: 0,
				margin: 0,
				padding: 0,
				border: 0,
				zIndex: 2
			}
		}).inject(pe, this.options.injectWhere);
		this.bg = new Element('div', {
			'class': this.options.className,
			styles: this.options.styles,
			events: { click: this.hide.bind(this) }
		}).inject(element);
		this.morph = new Fx.Morph(this.bg, Object.merge(this.options.fx, { link: 'cancel', onComplete: this.complete.bind(this) }));
		this.morph.set(this.options.hideStyle);

		this.parent(element, options);

		//(pe.get('tag') == 'body' ? window : pe).addEvent('scroll', this.posFix.bind(this, pe)).addEvent('resize', this.posFix.bind(this, pe));
		//this.posFix(pe);
	},

	posFix: function(pe){
		var p = pe.getScroll(), s = pe.getSize();
		this.element.set('styles', {top: p.y, left: p.x, height: s.y + 'px', width: s.x + 'px'});
	},

	onShow: function(){
		this.element.setStyle('display', 'block');
		document.body.setStyle('overflow', 'hidden');
		this.morph.start(this.options.showStyle);
		this.parent.apply(this, arguments);
	},

	onHide: function(){
		document.body.setStyle('overflow', 'auto');
		this.morph.start(this.options.hideStyle).chain(function(){
			this.element.setStyle('display', 'none');
		}.bind(this));
		this.parent.apply(this, arguments);
	},

	onTransition: function(){
		this.complete();
		this.parent.apply(this, arguments);
	},

	onCancel: function(){
		this.morph.cancel();
		this.parent.apply(this, arguments);
	}

});

Popup.Lightbox = new Class({

	Extends: Popup,

	options: {
		elementFx: { duration: 100 },
		contentFx: { duration: 100 }
	},
	/*
	content: null,
	image: null,
	title: null,
	*/
	images: [],
	titles: null,
	current: null,

	initialize: function(element, options){
		if(typeOf(element) == 'object' || typeOf(element) == 'undefined') {
			options = element;
			element = new Element('div', { 'class': 'lightbox', html: '<div class="content"><div class="image"><a class="next" href="javascript:void(0);"></a><a class="previous" href="javascript:void(0);"></a></div><div class="bottom"><a class="close" href="javascript:void(0);"></a><div class="title"></div></div></div>' });
		}
		if(options){
			if (options.elementFx) this.options.elementFx = options.elementFx;
			if (options.contentFx) this.options.contentFx = options.contentFx;
			this.setOptions(options);
		}
		var e = this.element = document.id(element);
		e.set('tabindex', -1);
		this.elementFx = new Fx.Morph(e, Object.merge(this.options.elementFx, {link: 'cancel'}));
		this.elementFx.set({'opacity': 0});
		var s = e.setStyle;
		e.setStyle = function() { s.apply(this, arguments); var z = this.getSize(); s.apply(s.apply(this, ['marginTop', -(z.y/2)]), ['marginLeft', -(z.x/2)]); };

		this.content = e.getElement('.content');
		this.contentFx = new Fx.Morph(this.content, Object.merge(this.options.contentFx, {link: 'cancel'}));
		this.contentFx.set({'opacity': 0});

		this.image = e.getElement('.image');
		var actions = {'.next': this.next, '.previous': this.previous, '.close': this.hide};
		var t = this;
		Object.each(actions, function(fn, k){
			var a = e.getElement(k);
			if(a) a.addEvent('click', function(e) { e.preventDefault(); fn.apply(t, arguments); });
		});
		this.titles = {};
		this.bottom = e.getElement('.bottom');
		this.title = e.getElement('.title');

		this.element.addEvent('keyup', this.keyboardListener.bind(this));

		this.parent(this.element, options);
	},

	onShow: function(uri, title){
		if(this.holder)
			this.holder.element.adopt(this.element);
		else
			this.element.inject(document.body);

		this.element.addClass('lightbox-loading');

		this.current = uri;
		if(title != undefined) this.titles[uri] = title;

		var loaded = false;
		var img = new Asset.image(uri, {onload: function(){ this.element.removeClass('lightbox-loading'); if(this.elementFx.timer || this.contentFx.timer) loaded = true; else this.animation(img); }.bind(this)});

		this.elementFx.start({'opacity': 1}).chain(function(){
			if(loaded)
				this.animation(img);
		}.bind(this));
		this.parent.apply(this, arguments);
	},

	onHide: function(){
		var self = this;
		this.elementFx.start({'opacity': 0}).chain(function(){
			this.contentFx.set({'opacity': 0});
			this.element.dispose();
			this.complete();
		}.bind(this));
		this.parent.apply(this, arguments);
	},

	onTransition: function(uri){
		this.contentFx.start({'opacity': 0}).chain(
			this.onShow.pass(arguments, this)
		);
		this.parent.apply(this, arguments);
	},

	onCancel: function(){
		this.elementFx.cancel();
		this.contentFx.cancel();
		this.parent.apply(this, arguments);
	},

	animation: function(img){
		if (this.title) this.title.set('html', this.titles[img.src]);
		
		var winSize = window.getSize();
		var bottomHeight = this.bottom.getScrollHeight();
		var w = img.width;
		if(w > winSize.x)
			w = winSize.x - 40;
			
		var h = img.height + bottomHeight;
		if(h > winSize.y)
			h = winSize.y - 40;
			
		this.image.setStyles({'background': '#fff url(' + img.src + ') center center no-repeat', width: w, height: h - bottomHeight});
		var self = this;
		this.elementFx.start({'width': w}).chain(function(){
			self.elementFx.start({'height': h}).chain(function(){
				self.contentFx.start({'opacity': 1}).chain(function(){
					self.element.focus();
					self.complete();
				});
			});
		});
	},

	add: function(uri, title){
		this.images.include(uri);
		this.titles[uri] = title;
		return this;
	},

	next: function(){
		if(this.images.length < 2) return;
		var i = this.images.indexOf(this.current);
		i = (i >= this.images.length-1) ? 0 : i+1;
		return this.show(this.current = this.images[i]);
	},

	previous: function(){
		if(this.images.length < 2) return;
		var i = this.images.indexOf(this.current);
		i = (i <= 0) ? this.images.length-1 : i-1;
		return this.show(this.current = this.images[i]);
	},

	keyboardListener: function(e){
		switch (e.key){
			case 'esc': case 'backspace': case 'delete': this.hide(); break;
			case 'left': case 'down': this.previous(); break;
			case 'right': case 'up': this.next();
		}
	}
});
