

// we set this to false to prevent jumpy animated skin.
LightboxOptions.animate = false;
LighboxLoaded = false;


modules.loadActions.prototype.gallery = function(){



  gallery = this.gallery;
  gallery.rotatorClassName = 'rotator';
  gallery.currentGalleryID = '';
  
  gallery.carouselClassName = 'gallery-rotator';
  
  gallery.browseClassName = 'browse';
  gallery.moduleConfig = SiteVars.modules.Gallery;
  
  gallery.pageSize = 6;
  
  gallery.loaded = false; // have we loaded up all of the pages in AJAX
  gallery.currentPage = 1;
  gallery.pages = Math.ceil(gallery.moduleConfig.gallerySize / 5);
  gallery.galleryXML = SiteVars.modules.Gallery.galleryXML;
  gallery.reset = false;
  gallery.loadedPages = new Array();
  
  gallery.carouselPage = 0; // current page in popup
  gallery.lbox = null;
  
  gallery.summaryState = false; // when false, load summary via AJAX
                                // when true, just show/hide
  /* Rotator Functions */
  
  //{{{ gallery.rotatorLoad = function()
  gallery.rotatorLoad = function(){
    
    
    
    gallery.allRotators = $$('.'+gallery.rotatorClassName);
    gallery.allRotators.each(function(rotator){
        
        //set the properties of the rotator
        //controls
        rotator.rHandler = Element.select(rotator, '.responsehandler')[0];
        rotator.countDown = 10;
        rotator.endFlag = false;
        
        //full view
        rotator.imageArea    = Element.select(rotator, '.imagearea')[0];
        rotator.fullImage    = Element.select(rotator, '.fullimage')[0];
        rotator.imgContainer = Element.select(rotator, '.container')[0];
        rotator.imageTitle   = Element.select(rotator, 'h1')[0];
        rotator.credit       = Element.select(rotator, '.credit')[0];
        rotator.description  = Element.select(rotator, '.description')[0];
        rotator.btnWrap      = Element.select(rotator, '.button-wrapper')[0];
        rotator.btn          = Element.select(rotator.btnWrap, 'a.button-style')[0];
        
        //panels
        rotator.panels      = Element.select(rotator, '.panel');
        rotator.activePanel = Element.select(rotator, '.activepanel')[0];
        
        //rotator strip properties
        rotator.strip    = Element.select(rotator, '.imagelist')[0];

        //load up the behaviors
        gallery.rotatorPanelBehavior(rotator);
        
        rotator.panels.each(function(item) {
            item.json = item.title;
            item.removeAttribute('title');
        });
        
        
        
        //console.dir(rotator);
        
    });
    
  } //}}}
  
  //{{{ gallery.rotatorPanelBehavior = function(rotator)
  gallery.rotatorPanelBehavior = function(rotator){
    
    console.log('loading rotator');
    
    rotator.panels.each(function(panel){
        
        panel.parentLi = Element.ancestors(panel)[0];
        
        if(panel.title){
          
          panel.getAjaxDirective = modules.sanitizeResponse(panel.title, {});
          panel.getAjaxDirective.updateElem = rotator.rHandler;
          panel.getAjaxDirective.onLoad = function(){
            //do nothing
          }
          panel.getAjaxDirective.onSuccess = function(){
            //do nothing
          }
          panel.getAjaxDirective.onComplete = function(){
            rotator.endFlag = (panel == rotator.panels.last() && gallery.moduleConfig.endOnLast == 'true' || rotator.endFlag==true) ? true : false;
            gallery.rotatorParser(rotator);
          }
          panel.removeAttribute('title');
          
          
          
          Event.observe(panel, 'click', function(e){
              gallery.rotatorImageLoad(rotator, panel)
              panel.blur();
              Event.stop(e);
          });
        }
    });
    
    
    
  } //}}}

  //{{{ gallery.rotatorDoRotation = function(rotator)
  gallery.rotatorDoRotation = function(rotator){
        
    for(x=0; x<=rotator.panels.length; x++){
      if(x==rotator.panels.length-1 && rotator.endFlag == false){
        gallery.rotatorImageLoad(rotator, rotator.panels[0]);
        break;
      }
      else if(rotator.panels[x].parentLi == rotator.activePanel && rotator.endFlag == false){
        gallery.rotatorImageLoad(rotator, rotator.panels[x+1]);
        break;
      }
    }
    
  } //}}}
  
  //{{{ gallery.rotatorPanelLoad = function(rotator)
  gallery.rotatorImageLoad = function(rotator, panel){
    
    Element.removeClassName(rotator.activePanel, 'activepanel');
    
    Element.setStyle(rotator.activePanel, {
        backgroundColor:'rgb(178,35,43)',
        color:'rgb(212,112,118)'
    });
    
    Element.addClassName(panel.parentLi, 'activepanel');
    
    Element.setStyle(panel.parentLi, {
        backgroundColor:'rgb(147,28,35)',
        color:'#fff'
    });
    
    
    Element.addClassName(rotator.imageArea, 'loading');
    rotator.activePanel = panel.parentLi;

    Effect.Fade(rotator.fullImage, {
      duration:.5,
      fps:100,
      from:1.0,
      to:0.01,
      afterFinish:function(){
        modules.sendAsync(panel.getAjaxDirective);
      }
    });
  } //}}}
  
  //{{{ gallery.rotatorParser = function(rotator)
  gallery.rotatorParser = function(rotator){
    
    var newImage = Element.select(rotator.rHandler, '.fullimage')[0]
    var imgSrc = Element.select(newImage, 'img')[0];
    
    var preLoad = new Image();
    preLoad.src = imgSrc.src;
    
    rotator.fullImage.innerHTML = newImage.innerHTML;
    rotator.fullImage.className = newImage.className;
    
    Effect.Appear(rotator.fullImage, {
        duration:.5,
        fps:100,
        from:0.01,
        to:1.0,
        afterFinish:function(){
          Element.removeClassName(rotator.imageArea, 'loading');
        }
    });
    
    rotator.imageTitle.innerHTML   = Element.select(rotator.rHandler, 'h1')[0].innerHTML;
    rotator.description.innerHTML  = Element.select(rotator.rHandler, '.description')[0].innerHTML;
    
    rotator.newBtn = Element.select(rotator.rHandler, '.button-style')[0];
    rotator.btn.href = rotator.newBtn.href;
    rotator.btn.innerHTML = rotator.newBtn.innerHTML;
    
    rotator.rHandler.innerHTML='';
    
    rotator.countDown = 10;
    
    //Fix for IE6 nav issues
    
    
  } //}}}
  
  

  
  
  //{{{ gallery.carouselLoad = function()
  gallery.carouselLoad = function(){
    
    
    
    
    gallery.allCarousels = $$('.'+gallery.carouselClassName);
    
    
    
    gallery.allCarousels.each(function(carousel){
        
        
        
        var elem = $(carousel).up(1);
        var json = '';
        
        if (carousel.title != '') {
          carousel.json = carousel.title;
          json = carousel.json.evalJSON();
        }
          
        
        
        
        //var setting = gallery.GetSetting(elem.id);
        carousel.setting = GallerySettings.GetSetting(elem.id);
        //carousel.setting.hits = json.hits;
        
        carousel.loaded = false;
        carousel.currentPage = 1;

        //console.log('this' + carousel.setting.hits);

        
        // rotator or?
        if (typeof carousel.setting.mediaSize != 'undefined' && SiteVars.siteId=='media') {
          carousel.pages = Math.ceil(carousel.setting.hits /  carousel.setting.mediaSize);
        } else if (carousel.setting.orientation == 'horizontal') {
          carousel.pages = Math.ceil(carousel.setting.hits / 4);
        } else {
          carousel.pages = Math.ceil(carousel.setting.hits / 6);
        }
        
        //console.log('pages: ' + carousel.pages);
        
        carousel.reset = false;
        carousel.loadedPages = new Array();
        carousel.loading = false;
        
        //set the properties of the carousel
        //controls
        carousel.bPrev    = Element.select(carousel, '.carouselprev')[0];
        carousel.bNext    = Element.select(carousel, '.carouselnext')[0];
        //alert(Element.select(carousel, '.gallerywrapper-N23CD')[0]);
        
        
        
        carousel.rHandler = Element.select(carousel, '.responsehandler')[0];
        
        //full view
        carousel.imageArea    = Element.select(carousel, '.imagearea')[0];
        carousel.fullImage    = Element.select(carousel, '.fullimage')[0];
        carousel.imgContainer = Element.select(carousel, '.container')[0];
        carousel.imageTitle   = Element.select(carousel, 'h3')[0];
        carousel.credit       = Element.select(carousel, '.credit')[0];
        carousel.description  = Element.select(carousel, '.description')[0];
        
        //panels
        carousel.panels      = Element.select($(elem.id), '.panel');
        
        

        
        
        carousel.activePanel = Element.select(carousel, '.activepanel')[0];
        
        //carousel strip properties
        carousel.strip    = Element.select(carousel, '.imagelist')[0];

        //load up the behaviors
        //gallery.carouselPanelBehavior(carousel);
        
        
        gallery.carouselStripBehavior(carousel);
        
        //console.dir(carousel);
        
        carousel.removeAttribute('title');
    });
    
    
  } //}}}
  
  //{{{ gallery.carouselPanelBehavior = function(carousel)
  gallery.carouselPanelBehavior = function(carousel){
    console.log('loading panelbehaviour');
    

    
    carousel.panels.each(function(panel){
        
        panel.parentLi = Element.ancestors(panel)[0];
        
        
        
          
        
        if(panel.title){
          
          panel.getAjaxDirective = modules.sanitizeResponse(panel.title, {});
          panel.getAjaxDirective.updateElem = carousel.rHandler;
          panel.getAjaxDirective.onLoad = function(){
            //do nothing
          }
          panel.getAjaxDirective.onSuccess = function(){
            //do nothing
          }
          panel.getAjaxDirective.onComplete = function(){
            gallery.carouselParser(carousel);
          }
          panel.removeAttribute('title');
          
          
          Event.observe(panel, 'click', function(e){
              
              Element.removeClassName(carousel.activePanel, 'activepanel');
              Element.addClassName(panel.parentLi, 'activepanel');
              Element.addClassName(carousel.imageArea, 'loading');
              carousel.activePanel = panel.parentLi;
  
              Effect.Fade(carousel.fullImage, {
                duration:.5,
                fps:100,
                from:1.0,
                to:0.01,
                afterFinish:function(){
                  modules.sendAsync(panel.getAjaxDirective);
                }
              });
              
              Event.stop(e);
          });
          
          
        }
    });
  } //}}}
  
  //{{{ gallery.carouselStripBehavior = function(carousel)
  gallery.carouselStripBehavior = function(carousel){
    
    if (typeof carousel.setting.mediaSize != 'undefined' && carousel.setting.mediaSize != 'default') {
      carousel.strip.xDistance    = 89;
    } else if (carousel.setting.orientation == 'vertical') {
       carousel.strip.xDistance    = 197;
    }else if (carousel.setting.orientation == 'horizontal') {
       carousel.strip.xDistance    = 120;
    } else {
      carousel.strip.xDistance    = 96;
    }

    
    Element.setOpacity(carousel.bPrev, 0.4);
    Element.removeClassName(carousel.bPrev, 'active');
    Element.addClassName(carousel.bPrev, 'inactive');    
    
    
    
    Event.observe(carousel.bNext, 'click', function(e){
        //loadedPages
        
        if (carousel.loading == true) {
          return; 
        }
        
        if ((carousel.currentPage + 1) > carousel.pages) {
          return; 
        }
        
        
        carousel.currentPage++; 
        
        // carousel.setting.id
        
        if (carousel.loadedPages.indexOf(carousel.currentPage) <= -1) { 
          
          // load ajax stuff in
          var pfx = SiteVars.path_to_top;
          if (typeof CoreSiteVars != 'undefined' && CoreSiteVars.cmscontext == 'staging') {
            pfx = '/' + CoreSiteVars.cmscontext; 
          }
          
          var strUrl = pfx + '/gallery/ajaxpage?async=true';
          var strTags = ""; 
          
          
          if (carousel.setting.tags != '') {
            strTags = "&tags=" + carousel.setting.tags + "&defaultSearch=" + carousel.setting.defaultSearch;
            strUrl =  pfx + '/gallery/tagsearch-page?async=true';
          }
          if (typeof carousel.setting.mediaSize != 'undefined' && carousel.setting.mediaSize != 'default') {
            strUrl += '&pageSize=' + carousel.setting.mediaSize; 
          }
          if(location.hostname.indexOf('media')!=-1){
            strTags += '&siteIdOverride=' + SiteVars.siteId + '&siteId=' + SiteVars.siteId; 
          }
          
          if(carousel.setting.defaultSearch==true){
            var opts = {
              url: SiteVars.path_to_top + '/' + SiteVars.islandId + '/gallery/carousel-search/' + carousel.setting.id + '/' + carousel.currentPage,
              sendMethod:'get'
            };
          }
          else{
          var opts = {
            url: strUrl,
            sendMethod:'get',
            params:'pageNumber=' +  carousel.currentPage + '&galleryXML=' + carousel.setting.path + '&galleryType=carousel' + '&lightboxid=' + carousel.setting.id + strTags
          };
          }
          opts.onComplete = function(res) {

             var elem = new Element('div');
             elem.innerHTML = res.responseText;
             
             Element.removeClassName( Element.select(carousel, '.activepanel')[0], 'activepanel');
             Element.insert($$('.gallerywrapper-' + carousel.setting.id + ' .imagelist')[0], { bottom: Element.select(elem, '.imageset')[0].innerHTML  });
             
           
             GallerySettings.lbox.updateImageList();
             // clear panels
             carousel.panels = Element.select(carousel.strip, '.panel');
             carousel.panels.each(function(item) {
               if (typeof item.json == 'undefined') {
                 item.json = item.title;
                 item.removeAttribute('title');
               }
             });
             
             // reset
             carousel.reset = true;
             gallery.rotatorLoad();
             gallery.rotatorSlideNext(carousel);
             
             
          }
          
        } else {
          carousel.loading = true;
          gallery.rotatorSlideNext(carousel);
          
        }
        
        
        
        
        if (carousel.loadedPages.indexOf(carousel.currentPage) <= -1) {
          carousel.loading = true;
          modules.sendAsync(opts);
          carousel.loadedPages.push(carousel.currentPage);
        } 
        
        
        
        if ((carousel.currentPage + 1) > carousel.pages ) {
           
          Element.setOpacity(carousel.bNext, 0.4);
          Element.removeClassName(carousel.bNext, 'active');
          Element.addClassName(carousel.bNext, 'inactive');
          
          
          Element.setOpacity(carousel.bPrev, 1);
          Element.removeClassName(carousel.bPrev, 'inactive');
          Element.addClassName(carousel.bPrev, 'active');
          
          carousel.loaded = true;
        } else {
          Element.setOpacity(carousel.bPrev, 1);
          Element.removeClassName(carousel.bPrev, 'inactive');
          Element.addClassName(carousel.bPrev, 'active');
        }
                

        

    });
    
    Event.observe(carousel.bPrev, 'click', function(e){
        
        if (carousel.loading == true) {
          return; 
        }
        
        
        if (carousel.currentPage <= 1) {
          return; 
        }
        
        carousel.currentPage--;
        carousel.loading = true;
        
        
        //console.log('PREV PAGE: ' + carousel.currentPage);
        
        gallery.rotatorSlidePrev(carousel);
        
        if (carousel.currentPage <= 1) {
          
          Element.removeClassName(carousel.bPrev, 'active');
          Element.addClassName(carousel.bPrev, 'inactive');
          Element.setOpacity(carousel.bPrev, 0.4);
          

        } 
        
        
        Element.setOpacity(carousel.bNext, 1);
        Element.removeClassName(carousel.bNext, 'inactive');
        Element.addClassName(carousel.bNext, 'active');
          
       
  
    });
    
    
        
    carousel.panels.each(function(panel) {
        //var link = Element.select(panel, 'a');
        //console.log('========> ' + panel.title);
        //panel.onmouseout = function(e) {
        //  Event.stop(e); 
        //}
        //panel.removeAttribute('title');
    }); 

    
  } //}}}
  
  
  
  gallery.rotatorSlidePrev = function(rotator) {
      nextDistance = rotator.strip.xDistance * 1;
      rotator.strip.sliding = true;
      
      var hx = 0;
      var hy = nextDistance;
      
      // this is used if the gallery is left or right or up or down.
      if (rotator.setting.orientation == 'horizontal') {
        hx = (nextDistance * 4) + 8;
        hy = 0;
      } 
      
      
      new Effect.Move(rotator.strip, { 
            duration:.5,
            fps:100,
            x:hx, 
            y:hy,
            beforeStart:function(){
              rotator.strip.highVisible++;
              rotator.strip.lowVisible++;
            },
            afterFinish:function(){
              gallery.carouselPanelLoad(rotator);
              rotator.strip.sliding = false;
              rotator.loading = false;
            }
          });
  }  
      
  
  
  gallery.rotatorSlideNext = function(rotator) {
      nextDistance = rotator.strip.xDistance * -1;
      rotator.strip.sliding = true;
      
      var hx = 0;
      var hy = nextDistance;
      
      
      //alert(rotator.strip.xDistance);
      
      // this is used if the gallery is left or right or up or down.
      if (rotator.setting.orientation == 'horizontal') {
        
        hx = (nextDistance * 4) - 8;
        hy = 0;
        
      }
      
      
      
      
      new Effect.Move(rotator.strip, { 
            duration:.5,
            fps:100,
            x:hx, 
            y:hy,
            beforeStart:function(){
              rotator.strip.highVisible++;
              rotator.strip.lowVisible++;
              /*
              if(Element.hasClassName(rotator.bPrev, 'inactive')){
                Element.removeClassName(rotator.bPrev, 'inactive');
                Element.setOpacity(rotator.bPrev, 1);
              }
              if(rotator.strip.highVisible == rotator.strip.totalCount){
                Element.addClassName(rotator.bNext, 'inactive');
                Element.setOpacity(rotator.bNext, 0.4);
              }
              */
            },
            afterFinish:function(){
              gallery.carouselPanelLoad(rotator);
              rotator.strip.sliding = false;
              rotator.loading = false;
            }
          });
  }  
    
  
  
  //{{{ gallery.carouselPanelLoad = function(carousel)
  gallery.carouselPanelLoad = function(carousel){
    //console.log(carousel.strip.highVisible + carousel.strip.buffer);
    //not ready for optimized page yet
    
    
  } //}}}
  
  //{{{ gallery.carouselParser = function(carousel)
  gallery.carouselParser = function(carousel){
    
    var newImage = Element.select(carousel.rHandler, '.fullimage')[0]
    var imgSrc = Element.select(newImage, 'img')[0];
    
    carousel.fullImage.innerHTML = newImage.innerHTML;
    carousel.fullImage.className = newImage.className;
    
    Effect.Appear(carousel.fullImage, {
        duration:.5,
        fps:100,
        from:0.01,
        to:1.0,
        afterFinish:function(){
          Element.removeClassName(carousel.imageArea, 'loading');
        }
    });
    
    carousel.imageTitle.innerHTML   = Element.select(carousel.rHandler, 'h3')[0].innerHTML;
    carousel.credit.innerHTML       = Element.select(carousel.rHandler, '.credit')[0].innerHTML;
    carousel.description.innerHTML  = Element.select(carousel.rHandler, '.description')[0].innerHTML;
    
    carousel.rHandler.innerHTML='';
    
  } //}}}
  
  
  /* Lightbox extensions (extends base object at lightbox.js)*/
  
  //{{{ gallery.extendLightbox = function()
  gallery.extendLightbox = function(){
 
    /* adds image via ajax to box */
    Lightbox.prototype.addImages = function(elem, galleryXML, tags) {
      var self = this;
      gallery.carouselPage = 0;
      
      // which gallery am I?????
      
      //console.log('===================== adding images =======================');
      
      var pfx = SiteVars.path_to_top;
      if ((typeof(CoreSiteVars)!='undefined') && (CoreSiteVars.cmscontext == 'staging')) {
        pfx = '/' + CoreSiteVars.cmscontext; 
      }
      
      var tagStr = "";
      var urlStr = pfx + '/gallery/ajax-carousel-loader';
      if (tags) { 
        tagStr = "&tags=" + tags;
        urlStr = pfx + '/gallery/ajax-tagsearch-loader' 
      }
      
      if(!gallery.allCarousels[1] && gallery.allCarousels[0].setting.defaultSearch==true){
        var opts = {
          url: SiteVars.path_to_top + '/' + SiteVars.islandId + '/ajax-standard-loader',
          sendMethod:'get'
        };
      }
      else{
        var opts = {
          url: urlStr,
          params:'galleryXML=' + galleryXML + '&galleryType=carousel-popup' + tagStr
        };
      }
      
      
      opts.onComplete = function(res) {
        var elem = new Element('div');
        elem.innerHTML = res.responseText;
        //alert(Element.select(elem, '.imageset')[0].innerHTML );
        Element.insert($('javascroll'), { bottom: Element.select(elem, '.carousel-imageset')[0].innerHTML  });
        var temp_panels = Element.select('javascroll', '.panel');
        temp_panels.each(function(item) {
            item.json = item.title;
            item.removeAttribute('title');
        });
        
        self.bindNavigation();
      }
      
      
      modules.sendAsync(opts);

    }
    
    // changes the image via AJAX since the image may not be loaded at all
    
    
    Lightbox.prototype.switchImage = function(panel) {
      // get panel number
      var link = panel.firstDescendant();
      
      panel.getAjaxDirective = modules.sanitizeResponse(link.json, {});
      

      
      
      var self = this;
      
      
      
      panel.getAjaxDirective.onComplete = function(res) {
        
        var elem = new Element('div');
        elem.innerHTML = res.responseText;
        var img = Element.select(elem, '.fullimage')[0];
        
        var image = Element.select(img, 'img')[0];
        image.setAttribute('id', 'lightboxImage');
        
        $('innerImageContainer').innerHTML = img.innerHTML;
        Element.setOpacity( $('innerImageContainer'), 1);
          
        self.updateImageList();
        
      }    
      
      // now let's make some effects
      Effect.Fade($('innerImageContainer'), {
          duration:.5,
          fps:100,
          from:1.0,
          to:0.01,
          afterFinish:function(){
            modules.sendAsync(panel.getAjaxDirective);
          }
        });
        

      
      modules.sendAsync(panel.getAjaxDirective);
       //this.changeImage(imageNum);
    }
    
    Lightbox.prototype.bindImage = function() {
      var self = this;
      var pnls = $$('.carousel-panel');
      
      this.updateImageList();
 
    }
    
    //
    // runs an ajax call to get a full summary of the image panel
    //
    Lightbox.prototype.expandSummary = function(docid) {
      var summary = $('imageDetails');
      
      
      if (gallery.summaryState == false) {
        summary.innerHTML = '';
        summary.appendChild(Builder.node('img', {src:'/template_images/loading.gif'}));
        var pfx = SiteVars.path_to_top;
        if (typeof CoreSiteVars != 'undefined' && CoreSiteVars.cmscontext == 'staging') {
          pfx = '/' + CoreSiteVars.cmscontext; 
        }else if(SiteVars.currentLocale!='' && SiteVars.currentLocale!='undefined'){
        	pfx = '/' + SiteVars.mappedLocale;
        }	
        var opts = {
          url: pfx + '/internal/image/summary',
          params:'docid=' + docid  + '&async=true'
        };
        
        opts.onComplete = function(r) {
          
          gallery.summaryState = true; // set in updateDetails to false
      
          summary.hide();
          summary.innerHTML = r.responseText;
          summary.show();
         
          
          // run omniture stuff.
          try {
            $$('.omniture-package')[0].innerHTML.evalScripts();
          } catch(e) {
            
          }
          
        }

        modules.sendAsync(opts);
      } else { // gallery.summaryState
        //
        // Here we can just show/hide the gallery summary because it's already loaded
        //
        if (summary.hasClassName('collapsed')) {
          // show 
          $$('.collasped')[0].innerHTML = '-';
          summary.show();
          summary.removeClassName('collapsed');
          summary.addClassName('uncollapsed');
        } else {
          // hide
          $$('.collasped')[0].innerHTML = '+';
          summary.hide();
          summary.removeClassName('uncollapsed');
          summary.addClassName('collapsed');
        }
        
      } // else
    }
    
    //
    //  updateDetails()
    //  Display caption, image number, and bottom nav.
    // FIXME
    Lightbox.prototype.updateDetails = function() {
    
      
      
       gallery.summaryState = false;
      //alert(this.activeImage);
        // if caption is not null
        if (this.imageArray[this.activeImage][1] != ""){
          
          //alert(this.activeImage); 
          
            var json = this.imageArray[this.activeImage][1].evalJSON();
            
            /*
            $('imageDetails').innerHTML = '';
            $('imageDetails').appendChild(Builder.node('div',{id:'expand-box'}, [
                Builder.node('a', {className:'collasped', href:'#', onclick:"Lightbox.prototype.expandSummary('" + json.docid + "')"}, '+'),
                Builder.node('h1', json.title),
                Builder.node('div', {className:'summary'}, 'lorem ipsum sit dolor amet scribere'),
                Builder.node('div', {className:'summary collapsed', id:'summary'}, '')
              ]
             ));
            */
       //     console.log('================= UPDATING SUMMARY ===================');
            Lightbox.prototype.expandSummary(json.docid);
            
            //json.summary
            
            //this.caption.update(this.imageArray[this.activeImage][1]).show();
            
            
        }
        
        // if image is part of set display 'Image x of x' 
        if (this.imageArray.length > 1){
            this.numberDisplay.update( LightboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + LightboxOptions.labelOf + '  ' + this.imageArray.length).show();
        }

        new Effect.Parallel(
            [ 
                new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), 
                new Effect.Appear(this.imageDataContainer, { 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' });
	                //this.updateNav();
                }).bind(this)
            } 
        );
        
        
    }

    

    
    Lightbox.prototype.bindNavigation = function() {
      //carousel-up
      //carousel-down
      //gallery.carouselPage
      
      this.bindImage();
      
      Event.stopObserving($('carousel-up'), 'click');
      Event.stopObserving($('carousel-down'), 'click');
      
      
      var pages =  Math.ceil($$('.carousel-panel').length / 4); 
      //console.log('pages: ' + pages);
         
         
      Event.observe($('carousel-up'), 'click', function(e) {
          //alert('going up ' + gallery.carouselPage + ' and ' + SiteVars.modules.Gallery.carousel.totalSize);
          
         
          if (gallery.carouselPage <= 0) {
            return;
          } else {
            gallery.carouselPage--;  
            
            
            new Effect.Move($$('.carousel-items')[0], { 
                  duration:.5,
                  fps:100,
                  x:0, 
                  y:310
            });            
            
          }
          
          //} else {
            
          //}
          //console.log(gallery.carouselPage);
           Event.stop(e);

      });
      
      // next
      Event.observe($('carousel-down'), 'click', function(e) {
          
          
          
          if (gallery.carouselPage >= (pages - 1)) {
            return;
          } else {
            gallery.carouselPage++;  
            
            new Effect.Move($$('.carousel-items')[0], { 
                  duration:.5,
                  fps:100,
                  x:0, 
                  y:-310
            });               
            
          }

         // console.log(gallery.carouselPage);
         Event.stop(e);
      });
     

    }
    
    
    Lightbox.prototype.start = function(imageLink) {    
      //alert(imageLink);
        // clear innerImageNavigation
        
        // if the overlay is already appeared, then we just need update the nav
        
        
        var self = this;
      
        if ($('lightbox').getStyle('display') == 'none') {
          
          
         
          //var json = this.imageArray[this.activeImage][1].evalJSON();
          
          var json = imageLink.json.evalJSON();
          
          var setting = GallerySettings.GetSetting(json.lightboxid);
          
          
          $('javascroll').innerHTML = '';
          // now repopulate 
          
          this.addImages($('javascroll'), setting.path, setting.tags);
          self.updateImageList();
          
          
          
        }
        
        
        $$('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 });

        this.imageArray = [];
        var imageNum = 0;       

        if ((imageLink.rel == 'lightbox')){
            // if image is NOT part of a set, add single image to imageArray
            this.imageArray.push([imageLink.href, imageLink.json]);         
        } else {
            // if image is part of a set..
            
            this.imageArray = 
                $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
                collect(function(anchor){ return [anchor.href, anchor.json]; }).
                uniq();
            
            while (this.imageArray[imageNum][0] != imageLink.href) {
              imageNum++; 
              
            }
            
            this.activeImage = imageNum;
            
        }
        
        
        
        // 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();
        
        
      
        this.changeImage(imageNum);
    } 
    
    
    //
    //  resizeImageContainer()
    //
    Lightbox.prototype.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) + 250;
        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, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); 
        if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {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.prevLink.setStyle({ height: imgHeight + 'px' });
            //this.nextLink.setStyle({ height: imgHeight + 'px' });
            this.imageDataContainer.setStyle({ width: widthNew + 'px' });

            this.showImage();
        }).bind(this).delay(timeout / 1000);
    },
      
  
   //{{{ Lightbox.prototype.initialize = function()
    Lightbox.prototype.initialize = function() {    
        
      
      
      
      this.updateImageList(); 
      
      
      
      
      this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
  
      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

      var size = (LightboxOptions.animate ? 250 : 1) + 'px';
      
     
      var objBody = $$('body')[0];
      objBody.appendChild(Builder.node('div',{id:'overlay'}));
      objBody.appendChild(Builder.node('div',{id:'lightbox'}, [
      
          Builder.node('div', {className:'overlay'},[
            
            Builder.node('div', {id:'outerImageContainer'},
              Builder.node('img', {id:'lightboxImage', className: 'mainGalImg'})
            ),
            
            Builder.node('div', {id:'loading'},
              Builder.node('a',{id:'loadingLink', href: '#' }/*, 
                  Builder.node('img', {src: LightboxOptions.fileLoadingImage})*/
              )
            ),
            
            Builder.node('div', {className:'scroller'}, [
              Builder.node('a',{id:'carousel-up', href: '', onclick:'return false' }, 
                Builder.node('img', {src: '/template_images/gallery/gohawaii/overlay/arrow-up.gif'})
              ),
              Builder.node('div', {id:'javascroll'}),
              Builder.node('a',{id:'carousel-down', href: '', onclick: 'return false;' }, 
                Builder.node('img', {src: '/template_images/gallery/gohawaii/overlay/arrow-down.gif'})  
              )
            ]),
            
            /* Builder.node('div', {className:'clear'}), */
            
            Builder.node('div', {id:'imageDataContainer'}, [
              
                Builder.node('div',{id:'imageDetails'}, [
                    Builder.node('span',{id:'numberDisplay'}),
                    Builder.node('a',{id:'hireslink', href: '#', target:'_blank'},'[todo: description, title etc]') 
                ])
                
            ]),
            
            Builder.node('div', {className:'clear'})
            
          ]),
          // FIXME: add phrasepack
          Builder.node('div', {className:'bottom'}, [ 
             /*Builder.node('a',{id:'gotogal', href: SiteVars.path_to_top +  '/' + SiteVars.islandId + '/guidebook/gallery' }, 'GO TO THE GALLERY'),*/
             Builder.node('span',{id:'gallerynav'}),
             Builder.node('span',{id:'closewin'},[ 
               Builder.node('a',{href: '#', id:'bottomNavClose'}, SiteVars.modules.LBox.phrases.close),
                 ' X'
             ])
          ])
        
        
      ]));
      
     if ((SiteVars.siteId != 'media')&&(SiteVars.currentLocale.indexOf('en')!=-1)) { 
       $('gallerynav').appendChild(Builder.node('a',{id:'gotogal', href: SiteVars.path_to_top +  '/' + SiteVars.islandId + '/guidebook/gallery' }, SiteVars.modules.LBox.phrases.goToGallery));
     }  
      
            
            /*
            objBody.appendChild(Builder.node('div',{id:'lightbox'}, [
              
              
               Builder.node('div',{id:'outerImageContainer', className:'overlay'}, 
                    Builder.node('div',{id:'imageContainer'}, [
                        Builder.node('div',{id:'innerImageContainer'}, [
                          Builder.node('img',{id:'lightboxImage'})
                        ]),
                        
                        
                        Builder.node('div',{id:'innerImageNavigation'}),
                        
                        
                        Builder.node('div',{id:'hoverNav'}, [
                            Builder.node('a',{id:'prevLink', href: '#' }),
                            Builder.node('a',{id:'nextLink', href: '#' })
                        ]),
                        
                        
                        Builder.node('div',{id:'carousel-controls'}, [
                          Builder.node('a',{id:'carousel-up', href: '#' }, 'up'),
                          Builder.node('a',{id:'carousel-down', href: '#' }, 'down')
                        ]),
                        
                        
                        Builder.node('div',{id:'imageDetails'}, [
                            Builder.node('span',{id:'numberDisplay'}),
                            Builder.node('a',{id:'hireslink', href: '#', target:'_blank'},'[todo: description, title etc]') 
                        ]),
                        
                        
                        Builder.node('div',{id:'loading'}, 
                            Builder.node('a',{id:'loadingLink', href: '#' }, 
                                Builder.node('img', {src: LightboxOptions.fileLoadingImage})
                            )
                        )
                        
                        
                      ])
                   
                    // GOES HERE
                    
                      
                ),
               
     
                
                Builder.node('div', {id:'imageDataContainer'},
                    Builder.node('div',{id:'imageData'}, [
      
                        
                    ])
                ),
                
                Builder.node('div',{className:'bottom'}, 'GO TO THE GALLERY'),
                

            ]));
            */
                            /*
                        Builder.node('div',{id:'imageDetails'}, [
                            Builder.node('span',{id:'numberDisplay'}),
                            Builder.node('a',{id:'hireslink', href: '#', target:'_blank'},'[todo: description, title etc]') 
                        ])
                        */
            
      
     
      /*
      Event.observe($('hireslink'), 'click', function(e){
        
        var image = $('lightboxImage');
        var newLocation = image.src.substring(0, image.src.indexOf('?'))
        
        $('hireslink').href = newLocation;
        
       
      });
          */
       //this.addImages($('innerImageNavigation'));
    
      
      $('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 });
      
      
      /*
      $('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this));
      $('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this));
      $('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
      */
      $('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
      
      
      $('closewin').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
      
      var th = this;
      (function(){
          var ids = 
              'overlay lightbox innerImageContainer outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 
              'galleryCopy imageDataContainer imageData imageDetails caption numberDisplay hireslink bottomNav bottomNavClose';   
          $w(ids).each(function(id){ th[id] = $(id); });
      }).defer();
          
           //console.log('=========================== FOUND ==========================');
          
    }, //}}}
    
    ///////// DEBUG STARTS HERE
   
    Lightbox.prototype.showImage = function(){
       this.loading.hide();
       
       
        
       var imageNum = 0;
       var imageLink = $('lightboxImage').getAttribute('src'); 
       
       
       //alert(this.imageArray[imageNum][0]);
       for(var i = 0; i < this.imageArray.length; i++) {
          
          if (this.imageArray[i][0] == imageLink) {
            //console.log(this.imageArray[i][0] + ' vs ' + imageLink);
            imageNum++;
            break;
          }
       }
       
       
       this.activeImage = imageNum;
       

           
       
        var json = this.imageArray[this.activeImage][1].evalJSON();
        
        
        if (json.type == 'Video') {
         
            this.showVideo(json);
          
        }
               
   
        
        
        new Effect.Appear(this.lightboxImage, { 
            duration: this.resizeDuration, 
            queue: 'end', 
            afterFinish: (function(){
                
               // need to update activeImage because it's lost for some reason
               
              
              this.updateDetails();
              
            }).bind(this) 
        });
        this.preloadNeighborImages();
        
    }    
    
    
    
    //
    //  changeImage()
    //  Hide most elements and preload image in preparation for resizing image container.
    //
    Lightbox.prototype.changeImage =  function(imageNum) {   
      
        var json = this.imageArray[imageNum][1].evalJSON();
        var self = this;
      
        
        
        this.activeImage = imageNum; // update global var
        

        // hide elements during transition
        if (LightboxOptions.animate) this.loading.show();
        this.lightboxImage.hide();
        //this.hoverNav.hide();
        
        //this.prevLink.hide();
        //this.nextLink.hide();
        
        
		// HACK: Opera9 does not currently support scriptaculous opacity and appear fx
        this.imageDataContainer.setStyle({opacity: .0001});
       
        
        //this.numberDisplay.hide();      
        
       //var imgPreloader = new Image();
        
        // once image is preloaded, resize image container
        
        
        //imgPreloader.onload = (function(){
            
            
            
           if (json.type == 'Video') {
             
             this.showVideo(json);
             //imgPreloader.width = json.width;
             //imgPreloader.height = parseFloat(json.height) + 20;
           } else {
          
               $('outerImageContainer').innerHTML = '';
               $('outerImageContainer').appendChild(
                 
                 //Builder.node('img',{id:'lightboxImage', src:this.imageArray[this.activeImage][0]}));
                 Builder.node('img',{id:'lightboxImage', src:'/template_images/gallery/gohawaii/overlay/main-frame.gif', width:'545', height:'262'})
               );
               
               $('outerImageContainer').setStyle({'background':'url("' + this.imageArray[this.activeImage][0] + '") no-repeat scroll 15px 13px'});
               //alert(imageNum);
               //this.activeImage = 0; // FIXME
               
           }
           
          
          this.updateDetails();
           
          // we no longer use this anymore 
          //$('outerImageContainer').setStyle({'background':'url("' + this.imageArray[this.activeImage][0] + '") no-repeat'});
          //this.lightboxImage.src = this.imageArray[this.activeImage][0];
          
          
          
          
          
          //this.resizeImageContainer(imgPreloader.width, imgPreloader.height);
        //}).bind(this);
        
        
       // imgPreloader.src = this.imageArray[this.activeImage][0];
        
        
    },

    
    // replaces image with video.  needs to load up via AJAX since we don't pass in all of the parameters.
    Lightbox.prototype.showVideo = function(json) {
      
      
      $('outerImageContainer').innerHTML = '';
      $('outerImageContainer').setStyle({'background':'none'});
      var pfx = SiteVars.path_to_top;
      
      if (typeof CoreSiteVars !='undefined' && CoreSiteVars.cmscontext == 'staging') {
        pfx = '/' + CoreSiteVars.cmscontext; 
      }else if(SiteVars.currentLocale!='' && SiteVars.currentLocale!='undefined'){
        	pfx = '/' + SiteVars.mappedLocale;
      }	
            
      var opts = {
        url: pfx + '/internal/gallery/load-video',
        params:'docid=' + json.docid + '&async=true',
        evalScripts:true
      };      
      opts.onComplete = function(r) {
        var elem = new Element('div');
        elem.innerHTML = r.responseText;
        
        var content = Element.select(elem, '.fullvideo')[0];
        Element.insert($('outerImageContainer'), {bottom:content});
        
        //$('outerImageContainer').innerHTML = r.responseText; 
        
        
        //IE7 fix
        //var scripts = Element.select(elem, 'script');
        
        //alert(pfx + '/internal/gallery/load-video?' + 'docid=' + json.docid + '&async=true');
        // IE fix
       
        
        
         // var ie7 = (document.all && !window.opera && window.XMLHttpRequest);
          
         // if (!ie7) {
            try {
              var reg = /<script[^>]*>((?:.|\n)*)<\/script>/;
              
              var arrScripts = reg.exec(r.responseText);
              
              
              
              
              if (window.execScript) {
                window.execScript(arrScripts[1]); 
              } else {  
                eval(arrScripts[1]);
              }
            } catch(e) {
            
              
              // last attempt
              var scripts = Element.select(outerImageContainer, 'script');
              
              scripts.each(function(item) {
                 eval(item.innerHTML); 
              });
              
            }
            /*
          } else {
            alert('whaaaaat');
             var scripts = Element.select(outerImageContainer, 'script');
              
              scripts.each(function(item) {
                 eval(item.innerHTML); 
              });
           
          }
        */
          
        
        /*
        scripts.each(function(item) {
            
           eval(item.innerHTML); 
        });
        */
        
        
        // test for now, remove later
       // $$('.carousel-container')[0].setStyle( {width:'271px',height:'224px'} );
        
      }
      
      modules.sendAsync(opts);
    }
  

    
    
    
    
  } //}}}
  

  
  
  
  if($$('.'+gallery.carouselClassName)[0]){
    //console.log('LOADING FROM carouselLoad()');
    /* AT:commenting out for debugging */
    
    gallery.carouselLoad();
  }
  
  
  if($$('.'+gallery.carouselClassName)[0]){
    /* AT:commenting out for debugging */
    
    gallery.extendLightbox();
  }
  
  
  
}



 // settings for all of the galleries on a single page.  We iterate through them to load up the AJAX


