var _ERROR_MESSAGE = "Oops.. there was a problem with your request.<br /><br />" +
					"Please try again.<br /><br />"; // the error message displayed when the request has a problem
// The MOOdalBox object in its beauty
var MOOdalBox = {
	
	// init the MOOdalBox
	init: function (options) {
		// init default options
		this.options = $merge({
			closeable:			true,
			width:				700,
			height:				400,
			resizeDuration: 	400,
			backgroundOpacity:	0.7,
			evalScripts: 		true,
			evalResponse: 		false
		}, options || {});
		this.defaultOptions = this.options;
		// scan anchors for those opening a MOOdalBox
		/*this.anchors = [];
		$A($$('a')).each(function(el){
			// we use a regexp to check for links that 
			// have a rel attribute starting with "moodalbox"
			if(el.rel && el.href && el.rel.test('^moodalbox', 'i')) {
				el.onclick = this.click.pass(el, this);
				this.anchors.push(el);
			}
		}, this);*/
		
		// add event listeners
		this.eventKeyDown = this.keyboardListener.bindWithEvent(this);
		this.eventPosition = this.position.bind(this);
		
		// init the HTML elements
		// the overlay (clickable to close)
		this.overlay = new Element('div').setProperty('id', 'popOver').injectInside(document.body);
		// the center element
		this.center = new Element('div').setProperty('id', 'poBox').setStyles({width: this.options.width+'px', height: this.options.height+'px', left:(window.getWidth()/2)-(this.options.width/2)+'px'}).injectInside(document.body);
		
		this.closeButton = new Element('div').setProperty('id', 'poClose').injectInside(this.center);
		 // closeLink = new Element('a').injectInside(this.closeButton);
		  //closeLink.setHtml('&nbsp;');
		var top = new Element('div').setProperty('id', 'poTop').injectInside(this.center);
		  var topLeft = new Element('div').setProperty('id', 'poTopLeft').injectInside(top);
		  var topRight = new Element('div').setProperty('id', 'poTopRight').injectInside(top);
		  var topCenter = new Element('div').setProperty('id', 'poTopCenter').injectInside(top);
		var middle = new Element('div').setProperty('id', 'poMiddle').injectInside(this.center);
		  var middleLeft = new Element('div').setProperty('id', 'poMiddleLeft').injectInside(middle);
		    var middleRight = new Element('div').setProperty('id', 'poMiddleRight').injectInside(middleLeft);
		      this.middle = new Element('div').setProperty('id', 'poMiddleCenter').injectInside(middleRight);
		var bottom = new Element('div').setProperty('id', 'poBottom').injectInside(this.center);
		  var bottomLeft = new Element('div').setProperty('id', 'poBottomLeft').injectInside(bottom);
		  var bottomRight = new Element('div').setProperty('id', 'poBottomRight').injectInside(bottom);
		  var bottomCenter = new Element('div').setProperty('id', 'poBottomCenter').injectInside(bottom);
		
		// the actual page contents
		this.contents = new Element('div').setProperty('id', 'poContents').injectInside(this.middle);

	
		this.error = new Element('div').setProperty('id', 'poError').set('html',_ERROR_MESSAGE);
		
		// attach the close event to the close button / the overlay
		this.overlay.onclick = this.close.bind(this);
		this.closeButton.onclick = this.close.bind(this);
		
		// init the effects
		var nextEffect = this.nextEffect.bind(this);
		//var showContent = this.showContents.bind(this);
		
		this.fx = {
			overlay: 	new Fx.Morph(this.overlay).set({'opacity':0}),
			center: 	new Fx.Morph(this.center,{duration: this.options.resizeDuration}).addEvent('complete',nextEffect),
			middle: 	new Fx.Morph(this.middle,{duration: this.options.resizeDuration}),
			contents: 	new Fx.Morph(this.contents)
		};
		
		this.ajaxRequest = Class.empty;
		
		window.addEvent('resize',this.position.bind(this));
	},
	
	click: function(link) {
		return this.open (link.href, link.title, link.rel);
	},

	open: function(href, options) {
		if(options){
			this.options = $merge(this.options,options);
		}else{
			this.options = $merge(this.options,this.defaultOptions); //reset options
		}
		//console.log(this.options);
		this.href = href;
		this.title = "";//this.options.title;
		this.rel = "";//this.options.rel;
		this.position();
		this.setup(true);
		this.overlay.setStyle('display','block');
		//this.top = Window.getScrollTop() + (Window.getHeight() / 15);
		//this.center.setStyles({top: this.top+'px', display: ''});
		this.fx.overlay.start({opacity:this.options.backgroundOpacity});
		//this.center.setStyles({visibility:'visible',opacity:1});
		return this.loadContents(href);
	},
	
	position: function() {
		this.overlay.setStyles({top: '0px', height: window.getScrollSize().y+'px'});
		
		height = this.contents.getSize().y;
		if(height > window.getSize().y){
			top=50;
		}else{
			var top=(window.getSize().y/2 - height/2)+window.getScroll().y;
		}
		var left = (window.getSize().x/2)-(this.options.width/2);
		
		this.center.setStyles({'left':left, 'top':top});
	},
	
	setup: function(open) {
		var elements = $A($$('object'));
		elements.extend($$(window.ActiveXObject ? 'select' : 'embed'));
		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;
	},
	
	loadContents: function() {		
		if(this.step) return false;
		this.step = 1;
		
		//console.log('Loading: '+this.href);
		
		this.fx.contents.set({opacity: 0});
		
		// AJAX call here
		//var showBox = this.showBox.bind(this);
		var nextEffect = this.nextEffect.bind(this);
		var ajaxFailure = this.ajaxFailure.bind(this);
		var ajaxOptions = {
			url:			this.href,
			method: 		'get',
			update: 		this.contents, 
			evalScripts: 	this.options.evalScripts,
			evalResponse: 	this.options.evalResponse,
			onComplete: 	nextEffect, 
			onFailure: 		ajaxFailure
			};
		this.ajaxRequest = new Request.HTML(ajaxOptions).send();
				
		return false;
	},
	
	ajaxFailure: function (){
		this.contents.set('html','');
		this.error.clone().injectInside(this.contents);
		this.nextEffect();
		this.center.setStyle('cursor', 'pointer');
		this.center.onclick = this.close.bind(this);
	},
	
	fitToContent: function(){
		//this.fx.resize.custom({height: [this.center.clientHeight, this.contents.offsetHeight]});
		effect = new Fx.Morph(this.center,{duration: this.options.resizeDuration });
		effect.set({height: [this.center.clientHeight, this.contents.offsetHeight]});
	},
	
	/*showContents: function(){
		this.contents.style.display='';
		this.fx.contents.custom(0,1);
	},
	
	showBox: function(){
	},*/
	
	
	nextEffect: function() {
		//console.log('nextEffect called - '+this.step);
		switch(this.step++) {
		case 1:
			
			this.center.setStyles({opacity:0,
								   display:'block'})
			this.contents.setStyles({display:'block'});//show to get the width
			
		//	var top = window.getScroll().y+50;//(window.getScroll().y/2)+(this.contents.getScrollSize().y/2);
			
			height = this.contents.getSize().y;
			
			if(height > window.getSize().y){
				top=50;
			}else{
				var top=(window.getSize().y/2 - height/2)+window.getScroll().y;
			}
			
			/*if(top < 0){
				top = 50;
			}*/
			
			this.transTo = {width:	this.options.width,
						   height:	height,
						   top:		top,
						   left:	(window.getSize().x/2)-(this.options.width/2)};
			this.transFrom ={width:	this.transTo.width-(this.transTo.width/10),
							height:	this.transTo.height-(this.transTo.height/10),
							top:	this.transTo.top+((this.transTo.height/10)/2),
							left:	this.transTo.left+((this.transTo.width/10)/2)};
							
			//console.log(this.transTo);
			//console.log(this.transFrom);
			
			this.fx.center.start( {width:	this.transFrom.left,
								   height:	this.transFrom.height,
								   top:		this.transFrom.top,
								   left:	this.transFrom.left})
			//this.nextEffect();
			break;
		case 2:
			this.center.setStyle('opacity',1)
			this.contents.setStyles({display:'none'});//hide to speed things up
			
			//this.center.className = '';
			this.center.setStyle('cursor', 'default');
			this.center.onclick = '';
			
			this.fx.center.start({height: [this.transFrom.height, this.transTo.height],
								  width:[this.transFrom.width,this.transTo.width],
								  top:[this.transFrom.top,this.transTo.top],
								  left:[this.transFrom.left,this.transTo.left]
								  });
			this.fx.middle.start({height: [this.transFrom.height, this.transTo.height]});
			
			
			break;
		case 3:
			this.contents.setStyle('display','');
			this.fx.contents.start({'opacity':[0,1]});
			this.step = 0;
			//window.fireEvent('modalcomplete',this,100);
			break;
		case 4:
			break;
		}
	},
	
	
	keyboardListener: function(event) {
		// close the MOOdalBox when the user presses CTRL + W, CTRL + X, ESC
		if ((event.control && event.key == 'w') || (event.control && event.key == 'x') || (event.key == 'esc')) {
			this.close();
			event.stop();
		}		
	},
	
	close: function() {
		if(this.step < 0) return;
		this.step = -1;
		for(var f in this.fx) this.fx[f].cancel();
		this.contents.set('html','');
		this.center.style.display = 'none';
		//this.content.style.display = 'none';
		//this.center.className = 'mb_loading';
		this.fx.overlay.start({'opacity':0}).chain(this.setup.pass(false, this));
		return false;
	}
		
};

// startup
window.addEvent('domready',MOOdalBox.init.bind(MOOdalBox));

/******************************************************************/
/*                        MOOdalBox 1.2.1                         */
/* A modal box (inline popup), used to display remote content     */
/* loaded using AJAX, written for the mootools framework          */
/*         by Razvan Brates, razvan [at] e-magine.ro              */
/******************************************************************/
/*               http://www.e-magine.ro/moodalbox                 */
/******************************************************************/
/*                                                                */
/* MIT style license:                                             */
/* http://en.wikipedia.org/wiki/MIT_License                       */
/*                                                                */
/* mootools found at:                                             */
/* http://mootools.net/                                           */
/*                                                                */
/* Original code based on "Slimbox", by Christophe Beyls:         */
/* http://www.digitalia.be/software/slimbox                       */
/******************************************************************/

// Constants defined here can be changed for easy config / translation
// (defined as vars, because of MSIE's lack of support for const)

// Heavily customized by Andru
