/*
	Slimbox v1.41 - The ultimate lightweight Lightbox clone
	by Christophe Beyls (http://www.digitalia.be) - MIT-style license.
	Inspired by the original Lightbox v2 by Lokesh Dhakar.
*/

var Lightbox = {

	init: function(options){
		this.options = $extend({
			resizeDuration: 400,
			resizeTransition: false,	// default transition
			initialWidth: 100,
			initialHeight: 100,
			animateCaption: true,
			showCounter: true
		}, 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', {'id': 'lbOverlay'}).injectInside(document.body);

		this.center = new Element('div', {'id': 'lbCenter', 'styles': {'width': this.options.initialWidth, 'height': this.options.initialHeight, 'marginLeft': -(this.options.initialWidth/2), 'display': 'none'}}).injectInside(document.body);
		this.image = new Element('div', {'id': 'lbImage'}).injectInside(this.center);

		this.bottomContainer = new Element('div', {'id': 'lbBottomContainer', 'styles': {'display': 'none'}}).injectInside(document.body);
      this.bottomMid = new Element('div', {'id': 'bottomMid'}).injectInside(this.bottomContainer);
      this.bottomTop = new Element('div', {'id': 'bottomTop'}).injectInside(this.bottomMid);
      this.bottomBot = new Element('div', {'id': 'bottomBot'}).injectInside(this.bottomTop);
		this.bottom = new Element('div', {'id': 'lbBottom'}).injectInside(this.bottomBot);
		this.closeLink = new Element('a', {'id': 'lbCloseLink', 'href': '#'}).injectInside(this.bottom); //.onclick = this.overlay.onclick = this.close.bind(this);
		this.toggleLink = new Element('div', {'id': 'lbToggleLink', 'styles': {'cursor': 'pointer'}}).injectInside(this.bottom); //
		this.caption    = new Element('div', {'id': 'lbCaption'}).injectInside(this.bottom);
		this.number = new Element('div', {'id': 'lbNumber'}).injectInside(this.bottom);
		new Element('div', {'styles': {'clear': 'both'}}).injectInside(this.bottom);

		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} : {})),
			image: this.image.effect('opacity', {duration:500, onComplete:nextEffect}),
			bottom: this.bottom.effect('margin-top', {duration:400, onComplete:nextEffect})
		};

      this.setup(false);
      this.top = (window.getHeight() / 15);
		this.center.setStyles({top: this.top, display: 'none'});

		this.viewWidth  = this.getViewportWidth();
      this.viewHeight = this.getViewportHeight();

      if (window.innerHeight && window.scrollMaxY) // Firefox
      {
         this.docHeight = window.innerHeight + window.scrollMaxY;
         this.docWidth  = window.innerWidth + window.scrollMaxX;
      }
      else if (document.body.scrollHeight > document.body.offsetHeight) // all but Explorer Mac
      {
         this.docHeight = document.body.scrollHeight;
         this.docWidth  = document.body.scrollWidth;
      }
      else // works in Explorer 6 Strict, Mozilla (not FF) and Safari
      {
         this.docHeight = document.body.offsetHeight;
         this.docWidth  = document.body.offsetWidth;
      }

  	   this.overlay.setStyles({'top': "0px", 'height': this.docHeight});

      this.viewWidth  = this.getViewportWidth();
      this.viewHeight = this.getViewportHeight();
      this.bottomContainer.style.display = 'none';
		this.fx.image.hide();
		this.center.className = 'lbLoading';
		this.activeImage = 0;
		this.tmpCaption  = "<p style=\"font:12px verdana; \"><b>&nbsp;</b></p>";
		this.caption.setHTML(this.tmpCaption || '');
		this.preload = new Image();

    this.position();
	},

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

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

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

	open: function(images, imageNum){
		this.images = images;
		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);
		this.toggleLink.setStyles({backgroundImage: 'url(/ergo/js/images/enlarge.jpg)'});
		this.closeLink.setStyles({backgroundImage: 'url(/ergo/js/images/close.jpg)'});
		if (window.gecko) this.closeLink.onmouseover  = function () { doTooltip2('', '<p>Close image</p>'); };
		else this.closeLink.onmouseover  = function () { doTooltip2(event, '<p>Close image</p>'); };
		this.closeLink.onmouseout   = function () { hideTip(); };
		if (window.gecko) this.toggleLink.onmouseover = function () { doTooltip2('', '<p>Enlarge image</p>'); };
		else this.toggleLink.onmouseover = function () { doTooltip2(event, '<p>Enlarge image</p>'); };
		this.toggleLink.onmouseout  = function () { hideTip(); };
		return this.changeImage(imageNum, 1);
	},

	position: function(){
		var olHeight = this.docHeight;
		var lbHeight = this.center.offsetTop + this.center.offsetHeight + this.bottomContainer.offsetHeight + 10;
		if (lbHeight > this.docHeight) olHeight = lbHeight;
		this.overlay.setStyles({'top': "0px", 'height': olHeight});
	},

	setup: function(open){
		var elements = $A(document.getElementsByTagName('object'));
		elements.extend(document.getElementsByTagName(window.ie ? 'select' : 'embed'));
		elements.each(function(el){
			if (open) el.lbBackupStyle = el.style.visibility;
			el.style.visibility = open ? 'hidden' : el.lbBackupStyle;
		});
		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){
	  this.close();
		//switch (event.keyCode){
		//	case 27: case 88: case 67: this.close(); break;
		//}
	},

	getViewportHeight: function(){
      var height = window.innerHeight; // Safari
      var mode = document.compatMode;

      if((mode || window.ie) && !window.opera){
          height = document.documentElement.clientHeight;
      }

      return height;
  },

  getViewportWidth: function(){
      var width = window.innerWidth; // Safari
      var mode = document.compatMode;

      if(mode || window.ie){
          width = document.documentElement.clientWidth;
      }

      return width;
  },

	changeImage: function(imageNum, shrink){
    scroll(0,0);
    this.shrinkImage = shrink;

    this.viewWidth  = this.getViewportWidth();
    this.viewHeight = this.getViewportHeight();

		if (this.step || (imageNum < 0) || (imageNum >= this.images.length)) return false;
		this.step = 1;
		this.activeImage = imageNum;

		this.tmpCaption  = "<p style=\"font:12px verdana; \"><b>" + this.images[this.activeImage][1] + "</b></p>";
		this.tmpCaption += eval("imgText"+this.images[this.activeImage][2]);
		this.tmpCaption += "<p style=\"font:10px verdana;\"><a href=\""+this.images[this.activeImage][0]+"\" target=\"_blank\" style=\"font:10px verdana;\">View image [opens new window]</a> to print</p>";

		this.hugeImage = eval("imgHuge"+this.images[this.activeImage][2]);
		if (this.hugeImage != "0")
		{
		   this.tmpCaption += this.hugeImage;
		}

      this.caption.setHTML(this.tmpCaption || '');

		this.bottomContainer.style.display = 'none';
		this.fx.image.hide();
		this.center.className = 'lbLoading';

		this.preload = new Image();
		this.preload.onload = this.nextEffect.bind(this);
		this.preload.src = this.images[imageNum][0];
		return false;
	},

	nextEffect: function(){
		switch (this.step++){
		case 1:
		  this.newWidth  = this.preload.width;
		  this.newHeight = this.preload.height;

      if (this.shrinkImage)
      {
        this.bottomContainer.setStyles({height: 0, display: ''});
        this.tmpViewHeight = this.viewHeight - 16 - this.bottom.offsetHeight;
        this.tmpViewWidth  = this.viewWidth  - 6;

   			if (this.preload.height > this.tmpViewHeight)
   			{
   			  this.theDiff = this.preload.height / this.tmpViewHeight;
   			  this.newHeight = this.tmpViewHeight;
   			  this.newWidth  = this.preload.width / this.theDiff;
   			  this.toggleLink.setStyles({display: ''});
   			}
   			else if (this.preload.width > this.tmpViewWidth)
   			{
   			  this.theDiff = this.preload.width / this.tmpViewWidth;
   			  this.newWidth  = this.tmpViewWidth;
   			  this.newHeight = this.preload.height / this.theDiff;
   			  this.toggleLink.setStyles({display: ''});
   			}
   			else this.toggleLink.setStyles({display: 'none'});

   			this.toggleLink.onclick = this.toggle.bind(this);
   		}
   		this.closeLink.onclick = this.close.bind(this);

      this.center.className = '';
			this.image.innerHTML = "<img alt=\"\" width=\""+this.newWidth+"\" height=\""+this.newHeight+"\" src=\""+this.images[this.activeImage][0]+"\"/>";

      this.center.setStyles({'top': "0px"});

			this.number.setHTML((!this.options.showCounter || (this.images.length == 1)) ? '' : 'Image '+(this.activeImage+1)+' of '+this.images.length);

			if (this.center.clientHeight != this.image.offsetHeight){
				this.fx.resize.start({height: (this.image.offsetHeight - 0)});
				break;
			}
			this.step++;
		case 2:
			if (this.center.clientWidth != this.image.offsetWidth){
				this.fx.resize.start({width: (this.image.offsetWidth - 0), marginLeft: (0 - ((this.newWidth+8) / 2))});
				break;
			}
			this.step++;
		case 3:
			this.bottomContainer.setStyles({top: (this.center.offsetTop + this.center.offsetHeight + 10), height: 0, marginLeft: (0 - (650 / 2)), display: ''});
			this.fx.image.start(1);
			break;
		case 4:
			if (this.options.animateCaption){
				if (window.webkit) this.fx.bottom.set(0);
				else this.fx.bottom.set(-this.bottom.offsetHeight);
				this.bottomContainer.style.height = '';
				this.fx.bottom.start(0);
				break;
			}
			this.bottomContainer.style.height = '';
		case 5:
			this.step = 0;
			this.position();
		}
	},

	toggle: function(){
	   if (this.shrinkImage)
	   {
	    if (window.gecko) this.toggleLink.onmouseover = function () { doTooltip2('', '<p>Shrink image</p>'); };
	    else this.toggleLink.onmouseover = function () { doTooltip2(event, '<p>Shrink image</p>'); };
		  this.toggleLink.onmouseout  = function () { hideTip(); };
	    this.toggleLink.setStyles({backgroundImage: 'url(/ergo/js/images/shrink.jpg)'});
	    this.changeImage(this.activeImage, 0);
	  }
    else
    {
      if (window.gecko) this.toggleLink.onmouseover = function () { doTooltip2('', '<p>Enlarge image</p>'); };
      else this.toggleLink.onmouseover = function () { doTooltip2(event, '<p>Enlarge image</p>'); };
		  this.toggleLink.onmouseout  = function () { hideTip(); };
      this.toggleLink.setStyles({backgroundImage: 'url(/ergo/js/images/enlarge.jpg)'});
      this.changeImage(this.activeImage, 1);
    }
	},

	close: function(){
	  this.overlay.setStyles({'top': "0px", 'height': "0px"});
	  this.center.setStyles({'top': "0px", 'height': "0px"});
	  this.bottomContainer.setStyles({'top': "0px"});
	  scroll(0,0);
		if (this.step < 0) return;
		this.step = -1;
		if (this.preload){
			this.preload.onload = Class.empty;
			this.preload = null;
		}
		for (var f in this.fx) this.fx[f].stop();
		this.center.style.display = this.bottomContainer.style.display = 'none';
		this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
		return false;
	}
};

window.addEvent('domready', Lightbox.init.bind(Lightbox));
