/*
  Lightbox JS: Fullsize Image Overlays 
  by Lokesh Dhakar - http://www.huddletogether.com

  For more information on this script, visit:
  http://huddletogether.com/projects/lightbox/

  Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
  (basically, do anything you want, just leave my name and link)
  
  Table of Contents
  -----------------
  Configuration
  
  htLightBox Object
  - _addevnt()
  - _delevnt()
  - _docCheck()
  - _pause()
  - _show()
  - _hide()
  - _prepare()
  - _listen()
  
*/

// Create a Lightbox Object
new htLightBox();

// The Lightbox Object Class
function htLightBox(){

  // ----------------------------------------------------------------------
  // configuration
  // ----------------------------------------------------------------------

    // 0908: Webuddha.com Maximum Dimensions
    // If you would like to restrict the lightbox image size
    // Images smaller than specified values are not affected
    // -1 = none, 0 = screen, or specify X value
    this.maxImgWidth   = 0;
    this.maxImgHeight  = 0; 

  // ----------------------------------------------------------------------
  // _addevnt
  // add an event to an object
  // ----------------------------------------------------------------------

    this._addevnt = function(oN,eF){
      if(typeof oN != 'string')
        return false;
      if(typeof eF == 'function'){
        eF = "'"+eF+"'";
        eF = eF.replace(/^\'.*?\{/,'');
        eF = eF.replace(/\}\'$/,'');
      }
      if(eval('typeof '+oN) != 'function')
        return eval(oN+'= function(e){ '+eF+' }');  
      var oF = "'"+eval( oN )+"'";
      oF = oF.replace(/^\'.*?\{/,'');
      oF = oF.replace(/\}\'$/,'');
      return eval(oN+'=function(e){'+oF+' '+eF+'}');
    }

  // ----------------------------------------------------------------------
  // _delevnt
  // delete an event from an object
  // ----------------------------------------------------------------------

    this._delevnt = function(oN,eF){
      if(typeof oN != 'string')
        return false;
      if(eval('typeof '+oN) != 'function')
        return true;
      if(typeof eF == 'function'){
        eF = "'"+eF+"'";
        eF = eF.replace(/^\'.*?\{/,'');
        eF = eF.replace(/\}\'$/,'');
      }
      oD = "'"+eval(oN)+"'";
      oD = oD.replace(/^\'.*?\{/,'');
      oD = oD.replace(/\}\'$/,'');
      oD = oD.replace(eF,'');
      if( oD.replace(/\s+/,'').length > 0 )
        return eval(oN+' = function(e){'+oD+'}');
      else 
        return eval(oN+' = function(){}');
    }

  // ----------------------------------------------------------------------
  // _docCheck()
  // check document for scroll position and workspace dimensions
  // ----------------------------------------------------------------------

    this._docCheck = function(){
      var xScroll, yScroll, xWin, yWin, xView, yView;  
      // scroll position    
      if (self.pageYOffset) {
        xScroll = self.pageXOffset;
        yScroll = self.pageYOffset;
      } else if (document.documentElement && document.documentElement.scrollTop){  // Explorer 6 Strict
        xScroll = document.documentElement.scrollLeft;
        yScroll = document.documentElement.scrollTop;
      } else if (document.body) {// all other Explorers
        xScroll = document.body.scrollLeft;
        yScroll = document.body.scrollTop;
      }
      this.pageScroll = new Array( xScroll, yScroll); 
      // viewport dimensions
      if(window.innerHeight && window.scrollMaxY){  
        xView = document.body.scrollWidth;
        yView = window.innerHeight + window.scrollMaxY;
      } else if(document.body.scrollHeight > document.body.offsetHeight){
        xView = document.body.scrollWidth;
        yView = document.body.scrollHeight;
      } else {
        xView = document.body.offsetWidth;
        yView = document.body.offsetHeight;
      }  
      // document dimensions
      if(self.innerHeight){
        xWin = self.innerWidth;
        yWin = self.innerHeight;
      } else if (document.documentElement && document.documentElement.clientHeight) {
        xWin = document.documentElement.clientWidth;
        yWin = document.documentElement.clientHeight;
      } else if (document.body) {
        xWin = document.body.clientWidth;
        yWin = document.body.clientHeight;
      }   
      // small pages - total less than viewport
      if(yView < yWin) pageHeight = yWin;
        else pageHeight = yView;
      if(xView < xWin) pageWidth = xWin;
        else pageWidth = xView;
      // check max dimensions
      if( this.maxImgWidth == 0 ) this.maxDX = (xWin*.80);
        else this.maxDX = this.maxImgWidth;
      if( this.maxImgHeight == 0 ) this.maxDY = (yWin*.80);
        else this.maxDY = this.maxImgHeight;
      this.pageSize = new Array(pageWidth,pageHeight,xWin,yWin) 
    }

  // ----------------------------------------------------------------------
  // pause(numberMillis)
  // Pauses code execution for specified time. Uses busy code, not good.
  // Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
  // ----------------------------------------------------------------------

    this._pause = function(n) {
      var now = new Date();
      var exitTime = now.getTime() + n;
      while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
          return;
      }
    }

  // ----------------------------------------------------------------------
  // show()
  // Preloads images. Pleaces new image in lightbox then centers and displays.
  // ----------------------------------------------------------------------

    this._show = function(objLink){

      // prep objects
      var objOverlay = document.getElementById('htLightBoxOverlay');
      var objLightbox = document.getElementById('htLightBox');
      var objCaption = document.getElementById('htLightBoxCaption');
      var objImage = document.getElementById('htLightBoxImg');
      var objLoadingImage = document.getElementById('htLightBoxLoading');
      var objLightboxDetails = document.getElementById('htLightBoxDetail');

      // load screen dimensions
      this._docCheck();

      // center loadingImage if it exists
      if(objLoadingImage){
        objLoadingImage.style.top     = (this.pageScroll[1] + (this.pageSize[3] / 2) + 'px');
        objLoadingImage.style.left    = ((this.pageSize[0] / 2) + 'px');
        objLoadingImage.style.display = 'block';
      }

      // set height of Overlay to take up whole page and show
      objOverlay.style.height = (this.pageSize[1] + 'px');
      objOverlay.style.display = 'block';

      // preload image
      imgPreload = new Image();
      imgPreload.src = objLink.href;
      imgPreload._htLbObj = this;
      imgPreload.onload=function(){
        objImage.src = objLink.href;

        // 0908: Webuddha.com Maximum Dimensions
        if( this._htLbObj.maxDX && this._htLbObj.maxDY ){
          imgWidth  = (imgPreload.width * 1);
          imgHeight = (imgPreload.height * 1);
          imgScale  = (imgPreload.width * 1) / (imgPreload.height * 1); 
          if( imgWidth > imgHeight ){
            if( imgHeight > this._htLbObj.maxDY ){
              imgHeight = this._htLbObj.maxDY;
              imgWidth  = imgHeight * imgScale;
            }
            if( imgWidth > this._htLbObj.maxDX ){
              imgWidth  = this._htLbObj.maxDX;
              imgHeight = imgWidth / imgScale;
            }
          } else {
            if( imgWidth > this._htLbObj.maxDX ){
              imgWidth  = this._htLbObj.maxDX;
              imgHeight = imgWidth / imgScale;
            }
            if( imgHeight > this._htLbObj.maxDY ){
              imgHeight = this._htLbObj.maxDY;
              imgWidth  = imgHeight * imgScale;
            }
          }
          objImage.width = imgPreload.width = imgWidth;
          objImage.height = imgPreload.height = imgHeight;
        }  

        // center lightbox and make sure that the top and left values are not negative
        // and the image placed outside the viewport
        var lightboxTop = this._htLbObj.pageScroll[1] + ((this._htLbObj.pageSize[3] - 35 - imgPreload.height) / 2);
        var lightboxLeft = ((this._htLbObj.pageSize[0] - 20 - imgPreload.width) / 2);

        objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
        objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
        objLightboxDetails.style.width = imgPreload.width + 'px';

        if(objLink.getAttribute('title')){
          // objCaption.style.width = imgPreload.width + 'px';
          objCaption.style.display = 'block';
          objCaption.innerHTML = objLink.getAttribute('title');
        } else 
          objCaption.style.display = 'none';

        // A small pause between the image loading and displaying is required with IE,
        // this prevents the previous image displaying for a short burst causing flicker.
        if (navigator.appVersion.indexOf("MSIE")!=-1)
          this._htLbObj._pause(250);
        if(objLoadingImage)
          objLoadingImage.style.display = 'none';

        // Hide select boxes as they will 'peek' through the image in IE
        selects = document.getElementsByTagName("select");
        for (i = 0; i != selects.length; i++)
          selects[i].style.visibility = "hidden";
        
        // Show Lightbox
        objLightbox.style.display = 'block';

        // After image is loaded, update the overlay height as the new image might have
        // increased the overall page height.
        this._htLbObj._docCheck();
        objOverlay.style.height = (this._htLbObj.pageSize[1] + 'px');

        // Add Keypress Listener
        this._htLbObj._addevnt('document.onkeypress','this._htLbObj._listen(e);');

        return false;
      }

    }

  // ----------------------------------------------------------------------
  // hide()
  // ----------------------------------------------------------------------

    this._hide = function(){
      // get objects
      objOverlay = document.getElementById('htLightBoxOverlay');
      objLightbox = document.getElementById('htLightBox');
      // hide lightbox and overlay
      objOverlay.style.display = 'none';
      objLightbox.style.display = 'none';
      // make select boxes visible
      selects = document.getElementsByTagName("select");
        for (i = 0; i != selects.length; i++) {
        selects[i].style.visibility = "visible";
      }
      // Strip Keypress Listener
      this._delevnt('document.onkeypress','this._htLbObj._listen(e);');
    } // end - _prepare Function

  // ----------------------------------------------------------------------
  // _prepare()
  // Function runs on window load, going through link tags looking for rel="lightbox".
  // These links receive onclick events that enable the lightbox display for their targets.
  // The function also inserts html markup at the top of the page which will be used as a
  // container for the overlay pattern and the inline image.
  // ----------------------------------------------------------------------

    this._prepare = function(){

      // Loop Through Anchors
      if( !document.getElementsByTagName )
        return;
      var aLinks = document.getElementsByTagName("a");
      for (var i=0; i<aLinks.length; i++){
        var lnk = aLinks[i];
        if (lnk.getAttribute("href") && (lnk.getAttribute("rel") == "lightbox")){
          lnk.onclick = function(){this._htLbObj._show(this);return false;}
          lnk._htLbObj = this;
        }  
      }

      var objBody = document.getElementsByTagName("body").item(0);

      // create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
      var objOverlay = document.createElement("div");
      objOverlay.setAttribute('id','htLightBoxOverlay');
      objOverlay.onclick = function(){this._htLbObj._hide();return false;}
      objOverlay.style.display = 'none';
      objOverlay.style.position = 'absolute';
      objOverlay.style.top = '0';
      objOverlay.style.left = '0';
      objOverlay.style.zIndex = '90';
      objOverlay.style.width = '100%';
      objOverlay._htLbObj = this;
      objBody.insertBefore(objOverlay, objBody.firstChild);

      this._docCheck();

      // load progress image
      var objLoadingImg = document.createElement("div");
      objLoadingImg.onclick = function(){this._htLbObj._hide();return false;}
      objLoadingImg.setAttribute('id','htLightBoxLoading');
      objLoadingImg._htLbObj = this;
      objOverlay.appendChild(objLoadingImg);

      // create lightbox div
      var objLightbox = document.createElement("div");
      objLightbox.setAttribute('id','htLightBox');
      objLightbox.style.display = 'none';
      objLightbox.style.position = 'absolute';
      objLightbox.style.zIndex = '100'; 
      objBody.insertBefore(objLightbox, objOverlay.nextSibling);

      // create link
      var objLink = document.createElement("a");
      objLink.setAttribute('href','#');
      objLink.setAttribute('title','Click to close');
      objLink.onclick = function(){this._htLbObj._hide();return false;}
      objLink._htLbObj = this;
      objLightbox.appendChild(objLink);

      // create image
      var objImage = document.createElement("img");
      objImage.setAttribute('id','htLightBoxImg');
      objLink.appendChild(objImage);

      // close button
      var objCloseButton = document.createElement("div");
      objCloseButton.setAttribute('id','htLightBoxClose');
      objLink.appendChild(objCloseButton);

      // create details div
      var objLightboxDetails = document.createElement("div");
      objLightboxDetails.setAttribute('id','htLightBoxDetail');
      objLightbox.appendChild(objLightboxDetails);

      // create caption
      var objCaption = document.createElement("div");
      objCaption.setAttribute('id','htLightBoxCaption');
      objCaption.style.display = 'none';
      objLightboxDetails.appendChild(objCaption);

      // create keyboard message
      var objKeyboardMsg = document.createElement("div");
      objKeyboardMsg.setAttribute('id','htLightBoxKeyMsg');
      objKeyboardMsg.innerHTML = 'press <a href="#" onclick="this.parentNode._htLbObj._hide(); return false;"><kbd>x</kbd></a> to close';
      objKeyboardMsg._htLbObj = this;
      objLightboxDetails.appendChild(objKeyboardMsg);

    } // end - _prepare Function
    
  // ----------------------------------------------------------------------
  // _listen(e)
  // This function will listen for the X key to trigger a hide
  // ----------------------------------------------------------------------

    this._listen = function(e){
      if(e == null) k = e.keyCode; // ie
        else k = e.which; // mozilla
      if(k == 0 || k == 120) // esc || x
        this._hide();
    } // end - _listen Function

  // ----------------------------------------------------------------------
  // Initialize Object
  // ----------------------------------------------------------------------

  if( typeof document != 'object' )
    return null;
  if( typeof document._htLbObj === 'undefined' )
    document._htLbObj = this;
  this._addevnt('window.onload','document._htLbObj._prepare();');
  
} // end - htLightBox Object

