LightboxOptions = Object.extend({
 fileLoadingImage:  '/assets/images/icons/ic_loading_sm.gif',
 fileBottomNavCloseImage: '/assets/images/icons/ic_close_30.png',
 overlayOpacity: 0.8,   // controls transparency of shadow overlay

 animate: true,   // toggles resizing animations
 resizeSpeed: 9,  // controls the speed of the image resizing animations (1=slowest and 10=fastest)

 borderSize: 10,   //if you adjust the padding in the CSS, you will need to update this variable

 // When grouping images this is used to write: Image # of #.
 // Change it for non-english localization
 labelImage: "Image",
 labelOf: "of"
}, window.LightboxOptions || {});

// -----------------------------------------------------------------------------------

var Lightbox = Class.create();

Lightbox.prototype = {
 activeImage: undefined,
 
 // initialize()
 // Constructor runs on completion of the DOM loading. Calls updateImageList and then
 // the function inserts html at the bottom of the page which is used to display the shadow 
 // overlay and the image container.
 //
 initialize: function() {
  this.updateImageList();
  if (LightboxOptions.resizeSpeed > 10) LightboxOptions.resizeSpeed = 10;
  if (LightboxOptions.resizeSpeed < 1)  LightboxOptions.resizeSpeed = 1;

  this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0;
  this.overlayDuration = LightboxOptions.animate ? 0.2 : 0;  // shadow fade in/out duration

  // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
  // If animations are turned off, it will be hidden as to prevent a flicker of a
  // white 250 by 250 box.
  var size = (LightboxOptions.animate ? 250 : 1) + 'px';
  var objBody = $$('body')[0];
  var aDescription = $$('.ArticleDescription')[0].innerHTML;
  objBody.appendChild(Builder.node('div',{id:'overlay'}));
  objBody.appendChild(Builder.node('div',{id:'lightbox'}, [
   Builder.node('div', {id:'outerImageContainer'}, [
    Builder.node('div',{id:'ArticleDescriptionID',className:'ArticleDescription'}),
    Builder.node('div', {className:'imageContainerWrap'}, [
     Builder.node('div', {className:'imageContentWrap'}, [
      Builder.node('div', {id:'imageContainer'}, [
       Builder.node('img',{id:'lightboxImage'}), 
       Builder.node('div',{id:'loading',className:'contentLoading'},
        Builder.node('p',{id:'loadingLink'})
       )
      ])
     ]),
     Builder.node('div',{id:'ArticleImagePreviewID',className:'ArticleImagePreview'},
      Builder.node('ul',{id:'ArticleImagePreviewUL'})
     )
    ]),
    Builder.node('div',{id:'buttonClose'},
     Builder.node('a',{id:'bottomNavClose', href: '#' },
       Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage })
     )
    )
   ])
  ]));

  $('ArticleDescriptionID').update(aDescription.replace('openPage(','openPageNew('));  
  $('ArticleImagePreviewID').hide();
  $('overlay').hide().observe('click', (function() { this.end(); }).bind(this));
  $('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this));
  $('outerImageContainer').setStyle({ width: size, height: size });
  $('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
  $('buttonClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
  var th = this;
  (function(){
   var ids = 'overlay lightbox outerImageContainer ArticleDescriptionID imageContainer lightboxImage loading loadingLink ' + 
    'ArticleImagePreviewID ArticleImagePreviewUL buttonClose bottomNavClose';
   $w(ids).each(function(id){ th[id] = $(id); });
  }).defer();
 },

 //
 // updateImageList()
 // Loops through anchor tags looking for 'lightbox' references and applies onclick
 // events to appropriate links. You can rerun after dynamically adding images w/ajax.
 //
 updateImageList: function() {   
  this.updateImageList = Prototype.emptyFunction;
  document.observe('click', (function(event){
   var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]');
   if (target) {
    event.stop();
    var ul = $('ArticleImagePreviewUL').update($('ArticleImageUL').innerHTML);
    $$('ul[id=ArticleImagePreviewUL] a').each(function(elem){
     elem.observe('click', (function(event) { event.stop(); this.selectImage(event); }).bind(this));
    }.bind(this));
    if (target.href.indexOf('#')==-1) this.start(target);
   }
  }).bind(this));
 },
 
 //
 //  start()
 //  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
 //
 start: function(imageLink) { 
  $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
  // stretch overlay to fill page and fade in
  var arrayPageSize = this.getPageSize();
  $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
  new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity });  

  // calculate top and left offset for the lightbox 
  var arrayPageScroll = document.viewport.getScrollOffsets();
  var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
  var lightboxLeft = arrayPageScroll[0];
  this.lightbox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show();
  var a = $$('ul[id=ArticleImagePreviewUL] a.active')[0];
  if (a) this.changeImage(a.href.parseQuery().pic);
 },

 //
 //  changeImage()
 //  Hide most elements and preload image in preparation for resizing image container.
 //
 changeImage: function(imageNum) {
  this.activeImage = imageNum; // update global var
  // hide elements during transition
  if (LightboxOptions.animate) this.loading.show();
  this.lightboxImage.hide();
  // HACK: Opera9 does not currently support scriptaculous opacity and appear fx
  this.ArticleDescriptionID.setStyle({opacity: .0001});
  $('ArticleImagePreviewUL').setStyle({opacity: .0001});
  var imgPreloader = new Image();
  // once image is preloaded, resize image container
  imgPreloader.onload = (function(){
   this.lightboxImage.src = img_src[this.activeImage]['zoom'];
   this.resizeImageContainer(imgPreloader.width, imgPreloader.height);
  }).bind(this);
  imgPreloader.src = img_src[this.activeImage]['zoom'];
 },

 //
 //  resizeImageContainer()
 //
 resizeImageContainer: function(imgWidth, imgHeight) {
  // get current width and height
  var widthCurrent  = this.outerImageContainer.getWidth();
  var heightCurrent = this.outerImageContainer.getHeight();

  // get new width and height
  var widthNew  = (imgWidth  + LightboxOptions.borderSize * 2);
  var heightNew = (imgHeight + LightboxOptions.borderSize * 2);

  // scalars based on change from old to new
  var xScale = (widthNew  / widthCurrent)  * 100;
  var yScale = (heightNew / heightCurrent) * 100;

  // calculate size difference between new and old image, and resize if necessary
  var wDiff = widthCurrent - widthNew;
  var hDiff = heightCurrent - heightNew;

  if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleContent: false,scaleX: false, duration: this.resizeDuration, queue: 'front',}); 
  if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleContent: false,scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); 

  // if new and old image are same size and no scaling transition is necessary, 
  // do a quick pause to prevent image flicker.
  var timeout = 0;
  if ((hDiff == 0) && (wDiff == 0)){
   timeout = 100;
   if (Prototype.Browser.IE) timeout = 250;   
  }

  (function(){
   this.ArticleDescriptionID.setStyle({ width: widthNew + 'px' });
   this.showImage();
  }).bind(this).delay(timeout / 1000);

 },
 
 //
 //  showImage()
 //  Display image and begin preloading neighbors.
 //
 showImage: function(){
  this.loading.hide();
  new Effect.Appear(this.lightboxImage, { 
   duration: this.resizeDuration, 
   queue: 'end', 
   afterFinish: (function(){ this.updateDetails(); }).bind(this) 
  });
  this.preloadNeighborImages();
 },

 //
 //  updateDetails()
 //  Display caption, image number, and bottom nav.
 //
 updateDetails: function() {
  new Effect.Parallel(
   [ 
    new Effect.SlideDown(this.ArticleDescriptionID, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), 
    new Effect.SlideDown(this.ArticleImagePreviewID, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }),
    new Effect.Appear(this.ArticleImagePreviewID, { sync: true, duration: this.resizeDuration }),    
    new Effect.Appear(this.buttonClose, { sync: true, duration: this.resizeDuration }),    
    new Effect.Appear(this.ArticleDescriptionID, { sync: true, duration: this.resizeDuration })
   ], 
   { 
    duration: this.resizeDuration, 
    afterFinish: (function() {
     // update overlay size and update nav
     var arrayPageSize = this.getPageSize();
     this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
    }).bind(this)
   } 
  );
 },

 //
 //  preloadNeighborImages()
 //  Preload previous and next images.
 //
 preloadNeighborImages: function(){
  var preloadImage, im;
  for (im in img_src)
  {
   if (im!=this.activeImage)
   var src=img_src[im]['zoom'];
   if (src!='#')
   {
    preloadImage = new Image();
    preloadImage.src = src;
   }
  }
 },

 //
 //  end()
 //
 end: function() {
  this.lightbox.hide();
  new Effect.Fade(this.overlay, { duration: this.overlayDuration });
  $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
 },

 selectImage: function(event) {
  var current = event.element();
  var a = current.up('a');
  if (a.className=='active') return;
  $('ArticleImagePreviewUL').select('a.active').each(function(el){el.className=''});
  a.className='active';
  this.changeImage(a.href.parseQuery().pic);
 },
 //
 //  getPageSize()
 //
 getPageSize: function() {
   
   var xScroll, yScroll;
  
  if (window.innerHeight && window.scrollMaxY) { 
   xScroll = window.innerWidth + window.scrollMaxX;
   yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
   xScroll = document.body.scrollWidth;
   yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
   xScroll = document.body.offsetWidth;
   yScroll = document.body.offsetHeight;
  }
  
  var windowWidth, windowHeight;
  
  if (self.innerHeight) { // all except Explorer
   if(document.documentElement.clientWidth){
    windowWidth = document.documentElement.clientWidth; 
   } else {
    windowWidth = self.innerWidth;
   }
   windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
   windowWidth = document.documentElement.clientWidth;
   windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
   windowWidth = document.body.clientWidth;
   windowHeight = document.body.clientHeight;
  } 
  
  // for small pages with total height less then height of the viewport
  if(yScroll < windowHeight){
   pageHeight = windowHeight;
  } else { 
   pageHeight = yScroll;
  }
 
  // for small pages with total width less then width of the viewport
  if(xScroll < windowWidth){ 
   pageWidth = xScroll;  
  } else {
   pageWidth = windowWidth;
  }

  return [pageWidth,pageHeight];
 }
}
var LightboxBlock;

document.observe('dom:loaded', function () { LightboxBlock = new Lightbox(); });

function openPageNew(page,id)
{
 LightboxBlock.end();
 return openPage(page,id);
}
