/*
	AjaxBox v0.2 - The ajax version of Christophe Beyls's slimbox
	by Aymeric Levaux
*/

var AjaxBox = {

	init: function(options){
		this.options = $extend({
			resizeDuration: 500,
			resizeTransition: false,
			initialWidth: 250,
			initialHeight: 250,
			finalWidth: 550,
			finalHeight: 500,
			extraParams: {
				smdecorator: 'ajaxbox',
				smconfirm: true
			}
		}, options || {});

		this.anchors = [];
		$each(document.links, function(el){
			if (el.rel && el.rel.test(/^ajaxbox/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', {'id': 'abOverlay'}).injectInside(document.body);

		this.center = new Element('div', {'id': 'abCenter', 'styles': {'display': 'none'}}).injectInside(document.body);
		
		this.content = new Element('div', {'id': 'abContent'}).injectInside(this.center);
		this.bottomContainer = new Element('div', {'id': 'abBottomContainer', 'styles': {'display': 'none'}}).injectInside(document.body);
		(new Element('a', {'id': 'abCloseLink', 'href': '#'})).injectInside(this.bottomContainer).onclick = this.overlay.onclick = this.close.bind(this);
		
		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
			resize: this.center.effects($extend({duration: this.options.resizeDuration, onComplete: nextEffect}, this.options.resizeTransition ? {transition: this.options.resizeTransition} : {})),
			content: this.content.effect('opacity', {
				duration: 500, 
				onComplete: function(){
					this.center.setStyle('overflow', 'auto');
					this.evalContent();
				}.bind(this)
			})
		};

	},

	click: function(link){
		var aDim = link.rel.match(/[0-9]+/g);
		if(aDim){
			if(aDim.length === 2 || aDim.length === 4){
				this.options.finalWidth = (aDim[0].toInt() > 0) ? aDim[0].toInt() : this.options.finalWidth;
				this.options.finalHeight = (aDim[1].toInt() > 0) ? aDim[1].toInt() : this.options.finalHeight;
			}
			if(aDim.length === 4){
				this.options.initialWidth = (aDim[2].toInt() > 0) ? aDim[2].toInt() : this.options.initialWidth;
				this.options.initialHeight = (aDim[3].toInt() > 0) ? aDim[3].toInt() : this.options.initialHeight;
			}
		}
		
		this.position();
		this.setup(true);
		this.top = window.getScrollTop() + (window.getHeight() / 15);
		this.center.setStyles({top: this.top, display: ''});
		this.fx.overlay.start(0.8);
		return this.loadContent(link.href);
	},

	position: function(){
		this.overlay.setStyles({'top': window.getScrollTop(), 'height': window.getHeight()});
	},

	setup: function(open){
		this.center.setStyles({'width': this.options.initialWidth, 'height': this.options.initialHeight, 'marginLeft': -(this.options.initialWidth/2)});
		var elements = $A(document.getElementsByTagName('object'));
		elements.extend(document.getElementsByTagName(window.ie ? 'select' : 'embed'));
		elements.each(function(el){
			if (open){
				 el.abBackupStyle = el.style.visibility;
			}
			el.style.visibility = open ? 'hidden' : el.abBackupStyle;
		});
		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){
		if (event.keyCode === 27){
			this.close();
		}
	},

	loadContent: function(link){
		if (this.step){
			 return false;
		}
		this.step = 1;
		this.fx.content.hide();
		
		this.nextEffect();
		
		this.ajaxReq = new Ajax(link, {
			method: 'get', 
			update: this.content, 
			data: this.options.extraParams, 
			onComplete : function(){
				this.evalContent();
			}.bind(this)
		});
		this.ajaxReq.request();
		return false;
	},
	
	evalContent : function(){
		//we have to wait for both the ajax request to finish and the effect to be completed
		//this is a quick and dirty join inplementation for those to ansynchronious operation  
		if(!this.oneOfEffectOrRequestEnded){
			this.oneOfEffectOrRequestEnded = true;
			return;
		}
		this.oneOfEffectOrRequestEnded = false;
		this.ajaxReq.evalScripts();
		$A($ES('a', this.content)).each(function(el){
			if (el.rel && el.rel.test(/^closeajaxbox/i)){
				el.onclick = this.close.bind(this);
			}
		}, this);
		this.step=0;
	},

	nextEffect: function(){
		switch (this.step++){
		case 1:
			this.content.style.height = (this.options.finalHeight-20)+'px';

			if (this.options.initialHeight != this.options.finalHeight){
				this.fx.resize.start({height: this.options.finalHeight});
				break;
			}
			this.step++;
		case 2:
			if (this.options.initialWidth != this.options.finalWidth){
				this.fx.resize.start({width: this.options.finalWidth, marginLeft: -this.options.finalWidth/2});
				break;
			}
			this.step++;
		case 3:
			this.bottomContainer.setStyles({'top': this.top + this.center.clientHeight, 'width': this.options.finalWidth, 'marginLeft': this.center.style.marginLeft, 'display': ''});
			this.fx.content.start(1);
			break;
		}
	},

	close: function(functionToCallWhenHidden){
		if (this.step < 0){
			 return;
		}
		this.step = -1;
		for (var f in this.fx){
			this.fx[f].stop();
		}		
		this.center.style.display = 'none';
		this.center.setStyle('overflow', 'hidden');
		this.bottomContainer.style.display = 'none';
		var whenHiddenSteps = function(){
			this.setup(false);
			this.content.setHTML('');
			if($type(functionToCallWhenHidden) === 'function'){
				functionToCallWhenHidden();
			}
		}.bind(this);
		this.fx.overlay.chain(whenHiddenSteps).start(0);
		return false;
	}
};


window.addEvent(window.ie ? 'load' : 'domready', AjaxBox.init.bind(AjaxBox));
