/******************************************************************/
/*                        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)

var _ERROR_MESSAGE = "Oops.. there was a problem with your request.<br /><br />" +
					"Please try again.<br /><br />" +
					"<em>Click anywhere to close.</em>"; // the error message displayed when the request has a problem
var _RESIZE_DURATION 		= 1000; 		// Duration of height and width resizing (ms)
var _INITIAL_WIDTH			= 400;		// Initial width of the box (px)
var _INITIAL_HEIGHT			= 500;		// Initial height of the box (px)

var _CONTENTS_WIDTH 		= 400;		// Actual width of the box (px)
var _CONTENTS_HEIGHT		= 400;		// Actual height of the box (px)

var _DEF_CONTENTS_WIDTH		= 500;		// Default width of the box (px) - used for resetting when a different setting was used
var _DEF_CONTENTS_HEIGHT	= 400;		// Default height of the box (px) - used for resetting when a different setting was used

var _ANIMATE_CAPTION		= false;	// Enable/Disable caption animation
var _EVAL_SCRIPTS			= true;  	// Option to evaluate scripts in the response text
var _EVAL_RESPONSE			= false;	// Option to evaluate the whole response text


// The MOOdalBox object in its beauty
var MOOdalBox = {

	// init the MOOdalBox
	init: function (options) {
		// init default options
		this.options = Object.extend({
			resizeDuration: 	_RESIZE_DURATION,
			showDuration:       2000,
			fromWidth: 		_INITIAL_WIDTH,
			fromHeight: 		_INITIAL_HEIGHT,
			contentsWidth: 		$('MAINTEXT').getSize().size.x.toInt()-20,
			contentsHeight: 	_CONTENTS_HEIGHT,
			defContentsWidth: 	$('MAINTEXT').getSize().size.x.toInt()-20,
			defContentsHeight: 	_DEF_CONTENTS_HEIGHT,
			animateCaption: 	_ANIMATE_CAPTION,
			evalScripts: 		_EVAL_SCRIPTS,
			evalResponse: 		_EVAL_RESPONSE,
			fromX:              null,
			fromY:              null
		}, 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', 'mb_overlay').injectInside(document.body);

		// the caption
		this.caption  = new Element('div').setProperty('id', 'mb_caption').setStyles({width: 100+'px',height: 100+'px', display: 'none'}).injectInside(document.body);

		// the center element
		this.center = new Element('div').setProperty('id', 'mb_center').setStyles({width: this.options.fromWidth+'px', height: this.options.fromHeight+'px', 'top': (Window.getScrollTop() + (Window.getHeight() / 15)) + 'px', display: 'none'}).injectInside(document.body);
    this.center.addEvent('mousewheel', function(e) {
      e = new Event(e).stop();
      console.log('this.center.mousewheel');
    });

		// the actual page contents
		this.contents = new Element('div').setProperty('id', 'mb_contents').injectInside(this.center);
    this.contents.addEvent('mousewheel', function(e) {
      e = new Event(e).stopPropagation();
      console.log('this.contents.mousewheel');
    });


		// the close button
		this.close_link = new Element('div').setProperties({'id':'mb_close_link','title':'close'}).setStyles({display: 'none'}).injectInside(this.center);




		this.error    = new Element('div').setProperty('id', 'mb_error').setHTML(_ERROR_MESSAGE);

		// attach the close event to the close button / the overlay
		this.close_link.onclick = this.close.bind(this);
		//~ this.overlay.onclick = this.close.bind(this);
		//~ this.center.onclick = this.close.bind(this);
		this.error.onclick = this.close.bind(this);

		// init the effects
    if(typeof(console) != 'undefined')console.debug('init the effects');
		var nextEffect          = this.nextEffect.bind(this);
		var fxShowOnComplete    = this.fxShowOnComplete.bind(this);
		var fxHideOnComplete    = this.fxHideOnComplete.bind(this);
		var fxResizeOnComplete  = this.fxResizeOnComplete.bind(this);
		var fxOpacityOnComplete = this.fxOpacityOnComplete.bind(this);
		this.fx = {
			//~ overlay: 	this.overlay.effect('opacity', { duration: 500 }).hide(),
			resize: 	this.center.effects({ duration: this.options.resizeDuration,
                                      onComplete: fxResizeOnComplete }),
      adjust:   this.contents.effects({ duration: this.options.resizeDuration }),

			show: 	  this.center.effects({ duration: this.options.showDuration,
                                      transition:Fx.Transitions.circInOut,
                                      onComplete: fxShowOnComplete}), //, onComplete: this.loadContents.bind(this)
			hide: 	  this.center.effects({ duration: this.options.resizeDuration,
                                      transition:Fx.Transitions.circInOut,
                                      onComplete: fxHideOnComplete }),
			opacity: this.contents.effect('opacity', { duration: 500,
                                                  onComplete: fxOpacityOnComplete })
		};

		this.ajaxRequest = Class.empty;

	},

  fxHideOnComplete: function() {
    this.center.style.display = 'none';
  },

  fxShowOnComplete: function() {
    this.center.addClass('mb_loading');
  },

  fxResizeOnComplete: function() {
    if(typeof(console) != 'undefined') {
      console.debug('nextEffect called in this.fx.resize onComplete:');
    }
    this.nextEffect();
  },

  fxOpacityOnComplete: function() {
    if(typeof(console) != 'undefined')console.debug('nextEffect called in this.fx.opacity onComplete:');
    this.nextEffect();
  },

	click: function(link) {
		this.options.fromX      = link.getPosition().x.toInt();
		this.options.fromY      = link.getPosition().y.toInt();
		this.options.fromWidth  = link.getSize().size.x.toInt();
		this.options.fromHeight = link.getSize().size.y.toInt();


		return this.open (link.href, link.title, link.rel, link.innerHTML);
	},

	open: function(sLinkHref, sLinkTitle, sLinkRel, sLinkText) {
    this.close();

		this.href  = sLinkHref;
		this.title = sLinkTitle + sLinkText; //sLinkTitle;
		this.rel   = sLinkRel;

    this.position();
    this.setup(true);

		(function() {
      //~ this.fx.overlay.set(0.8);
      //~ this.fx.overlay.start(0.8);

      this.close_link.setStyle('display', '');
      this.caption.setStyle('display', '');
      this.center.setStyles({'display':'','height':this.options.contentsHeight+20,'background-color':'#E2E6EC'});

    }).bind(this).delay(100);

		return this.loadContents();
		//~ return false;
	},

	position: function() {
		//~ this.overlay.setStyles({top: Window.getScrollTop()+'px', height: Window.getHeight()+'px'});
    this.options.contentsWidth = $('MAINTEXT').getSize().size.x.toInt()-20;
		this.left_pos              = $('MAINTEXT').getPosition().x.toInt();

    maintext_top  = $('MAINTEXT').getPosition().y.toInt();
		this.top      = maintext_top<Window.getScrollTop()?Window.getScrollTop() + 20:maintext_top;

    this.caption.setStyles({top: this.options.fromY+'px', left: this.options.fromX-5 +'px', width: this.left_pos-this.options.fromX, height: this.options.fromHeight,'z-index':899});
    this.caption.setHTML(this.title);

		this.contents.setStyle('width', this.options.contentsWidth-20+'px');

		this.center.setStyles({top: this.top+'px', left: this.left_pos +'px', width: this.options.contentsWidth+20+'px', 'z-index':900});
	},

	setup: function(open) {
		var elements = $A($$('object'));
		elements.extend($$(window.ActiveXObject ? 'select' : 'embed'));
		elements.each(function(el){
      el.style.visibility = open ? 'hidden' : '';
      //~ if(typeof(console) != 'undefined')
      //~ console.debug(el + ' style.visibility = '+el.style.visibility);
    });
		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.ajaxRequest && this.ajaxRequest.cancel) {
      this.ajaxRequest.cancel();
    }
		this.step = 1;

		// check to see if there are specified dimensions
		// if not, fall back to default values
		var aDim = this.rel.match(/[0-9]+/g);
		this.options.contentsWidth  = (aDim && (aDim[0] > 0)) ? aDim[0] : this.options.defContentsWidth;
		this.options.contentsHeight = (aDim && (aDim[1] > 0)) ? aDim[1] : this.options.defContentsHeight;

		//~ this.fx.opacity.hide();
		//~ alert('Im ajax!!!');

		// AJAX call here
		var nextEffect   = this.nextEffect.bind(this);
		var ajaxFailure  = this.ajaxFailure.bind(this);
		var ajaxComplete = this.ajaxComplete.bind(this);
		var ajaxOptions = {
			method: 		'get',
			update: 		this.contents,
			evalScripts: 	this.options.evalScripts,
			evalResponse: this.options.evalResponse,
			onComplete: 	ajaxComplete,
			onFailure: 		ajaxFailure
			};

    this.center.addClass('mb_loading');
		//~ this.fx.show.start({'height': [this.options.fromHeight, this.options.contentsHeight+20], 'width': [this.options.fromWidth, this.options.contentsWidth+20], 'left': [this.options.fromX, this.left_pos], 'top': [this.options.fromY, this.top], 'background-color' : ['#ff6600', '#E2E6EC']}); //'opacity': [0.7,0.95],

		this.ajaxRequest = new Ajax(this.href, ajaxOptions).request();
		return false;
	},



	ajaxComplete: function () {
    if(typeof(console) != 'undefined') console.debug('nextEffect called in loadContents.ajaxRequest onComplete');
		this.nextEffect();
		//~ completer1 = new Autocompleter.Local($('country_auto'), $$('#diving_countries li a'), {
			//~ 'delay': 100,
			//~ 'filterTokens': function() {
			//~ var regex = new RegExp('^' + this.queryValue.escapeRegExp(), 'i');
			//~ return this.tokens.filter(function(token){
				//~ return (regex.test(token.innerHTML));
			//~ });
			//~ },
			//~ 'injectChoice': function(choice) {
			//~ var el = new Element('li')
				//~ .setHTML(this.markQueryValue(choice.innerHTML));
			//~ el.inputValue = choice.innerHTML;
			//~ this.addChoiceEvents(el).injectInside(this.choices);
			//~ },
			//~ 'zIndex':1000
		//~ });
  },

	ajaxFailure: function (){
		this.contents.setHTML('');
		this.error.clone().injectInside(this.contents);
    if(typeof(console) != 'undefined')console.debug('nextEffect called in loadContents.ajaxRequest onFailure:');
		this.nextEffect();
		this.center.setStyle('cursor', 'pointer');
		this.center.onclick = this.close.bind(this);
	},

  resetWindow: function () {
			// remove previous styling from the elements
			// (e.g. styling applied in case of an error)
			this.fx.show.clearTimer();
			this.center.removeClass('mb_loading');
			this.contents.setStyles({'width':this.options.contentsWidth-20,'background-color':'#fff','height':this.options.contentsHeight-20,'visibility':'visible'}); //'opacity':1,
			this.center.setStyles({'cursor':'default', top: this.top+'px', left: $('MAINTEXT').getCoordinates().left +'px', 'background-color':'#E2E6EC', 'height': this.options.contentsHeight+20}); //'opacity':0.95,
  },

	nextEffect: function() {
		switch(this.step++) {
		case 1:
      if(typeof(console) != 'undefined')console.debug('step 1');
      this.resetWindow();
      this.step++;

		case 2:
      if(typeof(console) != 'undefined') console.debug('step 2');

      this.contents.setStyle('visibility','visible');
      this.center.setStyle('cursor','default');

      var adjustments  = {'background-color': ['#E2E6EC','#556C90']};

      if(this.contents.getSize().size.y != this.contents.getSize().scrollSize.y) {
        //~ if(typeof(console) != 'undefined')
          //~ console.debug('step 2\r\n'+this.contents.getSize().size.y  + "\r\n" + (this.contents.getSize().scrollSize.y));
        //~ else alert('step 2\r\n'+this.contents.getSize().size.y  + "\r\n" + (this.contents.getSize().scrollSize.y));
        //~ this.contents.setStyle('height',(this.contents.getSize().scrollSize.y-20)+'px');
      }

			if(this.center.getTop() != this.top) {
				adjustments['top'] = [this.center.getTop(), this.top];
			}
			if(this.center.getLeft() != $('MAINTEXT').getCoordinates().left) {
				adjustments['left'] = [this.center.getLeft(), $('MAINTEXT').getCoordinates().left];
			}
			//~ if(this.center.getCoordinates().height != this.contents.scrollHeight+20) {
				//~ adjustments['height'] = [this.center.getCoordinates().height, this.contents.scrollHeight+20];
			//~ }
			if(this.center.getCoordinates().width != this.options.contentsWidth+20) {
				adjustments['width'] = [this.center.getCoordinates().width, this.options.contentsWidth+20];
			}

      this.fx.resize.start(adjustments);
		case 3:
      if(typeof(console) != 'undefined')console.debug('step 3');

      if(this.contents.getSize().size.y != this.contents.getSize().scrollSize.y) {
        //~ if(typeof(console) != 'undefined')
          //~ console.debug('step 3\r\n'+this.contents.getSize().size.y  + "!=" + (this.contents.getSize().scrollSize.y));
        //~ else alert('step 3\r\n'+this.contents.getSize().size.y  + "!=" + (this.contents.getSize().scrollSize.y));
        //~ this.fx.adjust.start({'height':[this.contents.getSize().size.y, this.contents.getSize().scrollSize.y-20]});
      }
			//~ if(this.center.getCoordinates().height < this.contents.scrollHeight+20) {
				//~ this.fx.resize.start({'height':[this.center.getCoordinates().height, this.contents.scrollHeight+20]});
        //~ break;
			//~ }
			//~ this.fx.opacity.start(0.7,1);
      this.step++;
			break;
    case 4:
      if(typeof(console) != 'undefined')console.debug('step 4');

      if(this.contents.getSize().size.y != this.contents.getSize().scrollSize.y) {
        //~ if(typeof(console) != 'undefined')
          //~ console.debug('step 4\r\n'+this.contents.getSize().size.y  + "!=" + (this.contents.getSize().scrollSize.y));
        //~ else alert('step 4\r\n'+this.contents.getSize().size.y  + "!=" + (this.contents.getSize().scrollSize.y));
        //~ this.fx.adjust.start({'height':[this.contents.getSize().size.y, this.contents.getSize().scrollSize.y-20]});
      }
			//~ if(this.center.getCoordinates().height < this.contents.scrollHeight+20) {
				//~ this.fx.resize.start({'height':[this.center.getCoordinates().height, this.contents.scrollHeight+20]});
        //~ break;
			//~ }
			this.step = 0;
		}
	},


	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() {
		this.center.onclick = null;
		this.contents.setHTML('');
		this.contents.setStyle('visibility','hidden');
		if(this.step < 0) return;
		this.step = -1;
		for(var f in this.fx) this.fx[f].clearTimer();
		this.center.removeClass('mb_loading');
		this.close_link.setStyle('display','none');
		this.caption.setStyle('display','none');
		this.contents.setStyles({'width':this.options.fromWidth-20,'height':this.options.fromHeight-20,'visibility':'hidden'});
		this.center.setStyles({top: this.options.fromY+'px', display: 'none', left: this.options.fromX +'px', width: this.options.fromWidth, height: this.options.fromHeight}); //
		//~ this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
    if(typeof(completer1) != 'undefined') completer1.destroy();
		return false;
	}

};

	// startup MOOdalBox
	window.addEvent('domready', MOOdalBox.init.bind(MOOdalBox));
