/*
 * Smoothbox v20070814 by Boris Popoff (http://gueschla.com)
 *
 * Based on Cody Lindley's Thickbox, MIT License
 *
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// on page load call TB_init
window.addEvent('domready', TB_init);

// prevent javascript error before the content has loaded
TB_WIDTH = 0;
TB_HEIGHT = 0;
var TB_doneOnce = 0 ;

// add smoothbox to href elements that have a class of .smoothbox
function TB_init(){
    
  $$("a").each( function(el) { 
    if(el.className.match(/smoothbox|lightbox|slimbox|thickbox/) 
    || el.rel && el.rel.match(/smoothbox|lightbox|slimbox|thickbox/i)
    ) 
    { 
      el.onclick=TB_bind; 
      el.addClass('smoothbox');      
    };
  });
	// $$("a.smoothbox").each(function(el){el.onclick=TB_bind});
}

function TB_bind(event) {
	var event = new Event(event);
  
	// stop default behaviour
	event.preventDefault();
  
	// remove click border
	this.blur();	
	
  // display the box for the elements href
	TB_show(this);
  
  // Dunno why this is here?
	// this.onclick=TB_bind;
  
	return false;
}

function TB_ShowLoading()
{
  if ( !$("TB_load") )
  {
    new Element('div').setProperty('id', 'TB_load').injectInside(document.body);
      
    // FIXME
    $('TB_load').innerHTML = "<img src='/__classpath/mootools/lightbox/loading.gif' />";
    
    TB_load_position();
  }
}

function TB_ShowOverlay()
{
  // create iframe, overlay and box if non-existent

	if ( !$("TB_overlay") )
	{
		new Element('iframe').setProperty('id', 'TB_HideSelect').injectInside(document.body);
		$('TB_HideSelect').setOpacity(0);
		

    new Element('div').setProperty('id', 'TB_overlay').injectInside(document.body);
    TB_overlaySize();
    
		$('TB_overlay').setOpacity(0.6);
		$("TB_overlay").onclick=TB_remove;
    
    // Fading is too slow
    // new Fx.Style('TB_overlay', 'opacity',{duration: 400, transition: Fx.Transitions.sineInOut}).start(0,0.6);		        		
	}
}

function TB_RemoveOverlay()
{
  $('TB_overlay').setOpacity(0);
  $('TB_overlay').remove();
  
  // Fading is too slow
	//new Fx.Style('TB_overlay', 'opacity',{duration: 400, transition: Fx.Transitions.sineInOut, onComplete:function(){$('TB_overlay').remove();} }).start(0.6,0);
  
  $('TB_HideSelect').remove();
}

// called when the user clicks on a smoothbox link
// opt { type: '[iframe|image|ajax|inline|auto]' }
// 
// For type inline, href = "#id-of-the-inline-thing-to-use"
// For auto (default), you can use the following classes on the anchor 
//   smoothbox-iframe, smoothbox-image, smoothbox-ajax, smoothbox-inline
// or it will try to detect the best one to use otherwise.
//
// For all, you may use a query string to specify w/h width=123&height=456


function TB_show(el, opt, preload) {
  if(!opt) opt = { }
  
  // default options
  var defopt = 
  { 
    'type'   : 'auto',
    
    'caption': (el.title || el.name || ''),
    'url'    : el.href,
    'rel'    : (el.rel || false)        
  }
  
  opt = $merge(defopt, opt);
  
  if(!opt.width) 
  {
    opt.width = opt.url.match(/[?&]width=([^&]+)/) ? RegExp.$1  : Math.floor(window.getWidth() - 60);
  }
  
  if(!opt.height) 
  {
    opt.height = opt.url.match(/[?&]height=([^&]+)/) ? RegExp.$1 : Math.floor(window.getHeight() - 60);
  }
	  
	var imageURL  = /\.(jpe?g|png|gif|bmp)([?#].*)?$/i;
  var htmlURL   = /\.(s?html?)([?#].*)?$/i;
  var inlineURL = /^#([a-z0-9_.-]+)([?].*)?$/i;
  
  if(opt.type == 'auto') 
  {
    if(el.hasClass('smoothbox-image'))
    {
      opt.type = 'image';
    }
    else if (el.hasClass('smoothbox-iframe'))
    {
      opt.type = 'iframe';
    }
    else if (el.hasClass('smoothbox-ajax'))
    {
      opt.type = 'ajax';
    }
    else if (el.hasClass('smoothbox-inline'))
    {
      opt.type = 'inline';
    }
    else if(el.href.match(imageURL))
    {
      opt.type = 'image';
    }
    else if (el.href.match(/TB_iframe/i))
    {
      opt.type = 'iframe';
    }
    else if (el.href.match(htmlURL))
    {
      opt.type = 'iframe';
    }
    else if (el.href.match(inlineURL))
    {
      opt.type = 'inline';
    }
    else
    {
      opt.type = 'iframe';        
    }
  }
  
	TB_ShowOverlay();
	TB_ShowLoading();
  
  // Preload image
  if(opt.type == 'image' && !preload)
  {
    preload = new Image();
    preload.onload = function()
    {
      TB_show(el, opt, this);
    }
    preload.src = opt.url;
    return false;
  }
	
  // Preload ajax
  if(opt.type == 'ajax' && !preload)
  {
    var myRequest = new Ajax(opt.url, {method: 'get', onComplete: function(rt, rx) { TB_show(el, opt, rt); } }).request();
  }
  

		// if an image group is given
  var dummy = { element: null, caption: "", url: "", html: "" };
  var prev = dummy,
			next = dummy,
			imageCount = "";
  if ( opt.rel ) {
    function getInfo(image, id, label) {
      return {
        element: image,
        caption: image.title,
        url: image.href,
        html: "<span id='TB_" + id + "'>&nbsp;&nbsp;<a href='#'>" + label + "</a></span>"
      }
    }
  
    // find the anchors that point to the group
    var imageGroup = [] ;
    $$("a.smoothbox").each(function(el){
      if (el.rel==opt.rel) {imageGroup[imageGroup.length] = el ;}
    })

    var foundSelf = false;
    
    // loop through the anchors, looking for ourself, saving information about previous and next image
    for (var i = 0; i < imageGroup.length; i++) {
      var image = imageGroup[i];
      var urlTypeTemp = image.href.match(imageURL);
      
      // look for ourself
      if ( image.href == opt.url ) {
        foundSelf = true;
        imageCount = "Image " + (i + 1) + " of "+ (imageGroup.length);
      } else {
        // when we found ourself, the current is the next image
        if ( foundSelf ) {
          next = getInfo(image, "next", "Next &gt;");
          // stop searching
          break;
        } else {
          // didn't find ourself yet, so this may be the one before ourself
          prev = getInfo(image, "prev", "&lt; Prev");
        }
      }
    }
  }
    
  function buildClickHandler(anchor) {
    return function() {
      if(!anchor) return false;
      
      $("TB_window").remove();
      new Element('div').setProperty('id', 'TB_window').injectInside(document.body);
      
      TB_show(anchor, $merge(opt,{ url: anchor.href, caption: (anchor.title || anchor.name || ''), rel: anchor.rel, type: 'auto' }));
      return false;
    };
  }
  var goPrev = buildClickHandler(prev.element);
  var goNext = buildClickHandler(next.element);
    
  // Calculate the content dimensions
  var cDim = { width: opt.width - 30, height: opt.height - 60 } // cDim = content dimension
  
	if ( opt.type == 'image' ) 
  {
    // We have it in preload
    preload.onload = null;
    
    // Resizing large images
    var x = cDim.width;
    var y = cDim.height;
    var imageWidth = preload.width;
    var imageHeight = preload.height;
    if (imageWidth > x) {
      imageHeight = imageHeight * (x / imageWidth); 
      imageWidth = x; 
      if (imageHeight > y) { 
        imageWidth = imageWidth * (y / imageHeight); 
        imageHeight = y; 
      }
    } else if (imageHeight > y) { 
      imageWidth = imageWidth * (y / imageHeight); 
      imageHeight = y; 
      if (imageWidth > x) { 
        imageHeight = imageHeight * (x / imageWidth); 
        imageWidth = x;
      }
    }
    // End Resizing
    
    // TODO don't use globals
    cDim.width = imageWidth;
    cDim.height = imageHeight;
  }
  
  // Calculate the containing smoothbox window dimensions
  var wDim = { width: (cDim.width + 30), height: (cDim.height + 60) } // wDim = window dimension  
  TB_WIDTH = wDim.width;
  TB_HEIGHT= wDim.height;
  
  // Create the smoothbox window html
  if ( !$("TB_window") )
	{
		new Element('div').setProperty('id', 'TB_window').injectInside(document.body);
		$('TB_window').setOpacity(0);
	}
		
	window.onscroll=TB_positionEffect;
  
  if(opt.type == 'image')
  {
    $("TB_window").innerHTML += "<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+opt.url+"' width='"+cDim.width+"' height='"+cDim.height+"' alt='"+opt.caption+"'/></a>";
  }
  else if(opt.type == 'iframe')
  {							
    $("TB_window").innerHTML += "<iframe frameborder='0' hspace='0' src='"+opt.url+"' id='TB_iframeContent' name='TB_iframeContent' style='width:"+(cDim.width + 29)+"px;height:"+(cDim.height + 17)+"px;' onload='TB_showWindow()'> </iframe>";          
  } 
  else if (opt.type == 'ajax')
  {
    $("TB_window").innerHTML += "<div id='TB_ajaxContent' style='width:"+cDim.width+"px;height:"+cDim.height+"px;'>"+preload+"</div>";
  }
  else if (opt.type == 'inline')
  {
    opt.url.match(inlineURL);
    preload = $(RegExp.$1).innerHTML;
    
    $("TB_window").innerHTML += "<div id='TB_ajaxContent' style='width:"+cDim.width+"px;height:"+cDim.height+"px;'>"+preload+"</div>";
  }
  
  $("TB_window").innerHTML += "<div id='TB_caption'>"+opt.caption+"<div id='TB_secondLine'>" + imageCount + prev.html + next.html + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a></div>";
    
  // Hook up the click handlers (close, next, prev
  $("TB_closeWindowButton").onclick = TB_remove;
  
  if ( $('TB_prev') ) {
    $("TB_prev").onclick = goPrev;
  }
  
  if ( $('TB_next') ) {		
      $("TB_next").onclick = goNext;
    }
    
  // Not sure what this is for
  if(opt.type == 'iframe')
  {    
    if(frames['TB_iframeContent'] == undefined){//be nice to safari
      $(document).keyup( function(e){ var key = e.keyCode; if(key == 27){TB_remove()} });      
    }
  }
   
  TB_position();
  TB_showWindow();
  
  if(opt.onshow)
  {
    opt.onshow($("TB_ajaxContent"));
  }
	window.onresize=function(){ TB_position(); TB_load_position(); TB_overlaySize();}  
	
	document.onkeyup = function(event){ 	
		var event = new Event(event);
		if(event.code == 27){ // close
			TB_remove();
		}	
	}
		
}

//helper functions below

function TB_showWindow(){
	//$("TB_load").remove();
	//$("TB_window").setStyles({display:"block",opacity:'0'});
	
	if (TB_doneOnce==0) {
		TB_doneOnce = 1;
		var myFX = new Fx.Style('TB_window', 'opacity',{duration: 250, transition: Fx.Transitions.sineInOut, onComplete:function(){if ($('TB_load')) { $('TB_load').remove();}} }).start(0,1);
	} else {
		$('TB_window').setStyle('opacity',1);
		if ($('TB_load')) { $('TB_load').remove();}
	}
}

function TB_remove() {
 	$("TB_overlay").onclick=null;
	document.onkeyup=null;
	document.onkeydown=null;
	
	if ($('TB_imageOff')) $("TB_imageOff").onclick=null;
	if ($('TB_closeWindowButton')) $("TB_closeWindowButton").onclick=null;
	if ( $('TB_prev') ) { $("TB_prev").onclick = null; }
	if ( $('TB_next') ) { $("TB_next").onclick = null; }

	new Fx.Style('TB_window', 'opacity',{duration: 250, transition: Fx.Transitions.sineInOut, onComplete:function(){$('TB_window').remove(); TB_RemoveOverlay();} }).start(1,0);
  
 
  
	window.onscroll=null;
	window.onresize=null;	
	
	
	TB_init();
	TB_doneOnce = 0;
	return false;
}

function TB_position() {
	$("TB_window").setStyles({width: TB_WIDTH+'px', 
				 left: (window.getScrollLeft() + (window.getWidth() - TB_WIDTH)/2)+'px',
				 top: (window.getScrollTop() + (window.getHeight() - TB_HEIGHT)/2)+'px'});
}

function TB_positionEffect() {
	new Fx.Styles('TB_window', {duration: 75, transition: Fx.Transitions.sineInOut}).start({
		'left':(window.getScrollLeft() + (window.getWidth() - TB_WIDTH)/2)+'px',
		'top':(window.getScrollTop() + (window.getHeight() - TB_HEIGHT)/2)+'px'});
}

function TB_overlaySize(){
	// we have to set this to 0px before so we can reduce the size / width of the overflow onresize 
	$("TB_overlay").setStyles({"height": '0px', "width": '0px'});
	$("TB_HideSelect").setStyles({"height": '0px', "width": '0px'});
	$("TB_overlay").setStyles({"height": window.getScrollHeight()+'px', "width": window.getScrollWidth()+'px'});
	$("TB_HideSelect").setStyles({"height": window.getScrollHeight()+'px',"width": window.getScrollWidth()+'px'});
}

function TB_load_position() {
	if ($("TB_load")) { $("TB_load").setStyles({left: (window.getScrollLeft() + (window.getWidth() - 56)/2)+'px', top: (window.getScrollTop() + ((window.getHeight()-20)/2))+'px',display:"block"}); }
}

function TB_parseQuery ( query ) {
	// return empty object
	if( !query )
		return {};
	var params = {};
	
	// parse query
	var pairs = query.split(/[;&]/);
	for ( var i = 0; i < pairs.length; i++ ) {
		var pair = pairs[i].split('=');
		if ( !pair || pair.length != 2 )
			continue;
		// unescape both key and value, replace "+" with spaces in value
		params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, ' ');
   }
   return params;
}

// Compatability function for Slimbox, lightbox, slimbox_ex
var Lightbox = {
  show: function(url, title, rev)
{
  if(rev)
  {
    if(!url.match(/[?&]/))
    {
      url += '?';
    }
    else
    {
      url += '&';
    }
    
    if(rev.match(/width=([0-9]+%?)/i))
    {
      url += 'width=' + encodeURIComponent(RegExp.$1) + '&';
    }
    
    if(rev.match(/height=([0-9]+%?)/i))
    {
      url += 'height=' + encodeURIComponent(RegExp.$1) + '&';
    }
  }
  
  var a = document.createElement('a');
  
    
  if(url.match(/\.s?html?/))
  {
    a.className = 'smoothbox smoothbox-iframe';
  }
  else
  {
    a.className = 'smoothbox';  
  }
  
  a.href = url;
  a.title = title;
  TB_show($(a));
}}