modules.loadActions.prototype.gallery = function(){
  
  gallery = this.gallery;
  
  gallery.gridClassName = 'grid';
  gallery.rotatorClassName = 'rotator';
  gallery.carouselClassName = 'carousel';
  gallery.browseClassName = 'browse';
  gallery.moduleConfig = SiteVars.modules.Gallery;
  gallery.paused = false;
  gallery.pageSize = 25;
  //currentPage // used for grid
  
  
  /* Rotator Functions */
  gallery.currentPage = 1;
  gallery.pages = Math.ceil(gallery.moduleConfig.gallerySize / gallery.pageSize); 
  
  gallery.reset = false;

  //{{{ gallery.rotatorLoad = function()
  
  
  if (gallery.moduleConfig.gallerySize == 1) {
   return; 
  }
  
  
  gallery.gridLoad = function(){
    
    gallery.allRotators = $$('.'+gallery.gridClassName);

    
    
    gallery.allRotators.each(function(rotator){
        //set the properties of the rotator
        
        rotator.strip    = Element.select(rotator, '.imagelist')[0];
        rotator.strip.startNum     = 1;
        rotator.strip.lowVisible   = 1;
        rotator.strip.highVisible  = parseInt(gallery.moduleConfig.panelWindowSize);
        rotator.strip.totalVisible = parseInt(gallery.moduleConfig.panelWindowSize);
        rotator.strip.buffer       = parseInt(gallery.moduleConfig.buffer);
               
        
        //controls
        rotator.rHandler = Element.select(rotator, '.responsehandler')[0];
        rotator.countDown = 10; // was 10
        rotator.endFlag = false;
        
        rotator.slide = false; // or slide
        
        
        // size
        rotator.currentPage = 1; // increment
        


       
        rotator.strip.totalCount   = Math.ceil(parseInt(gallery.moduleConfig.gallerySize) / gallery.pageSize) - 1; // total pages

          

        
        
        //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.currentRotationIndex = 0;
         
        
        
        rotator.strip.xDistance    = 85 * gallery.pageSize - 1;
        rotator.strip.sliding      = false;
        
        
        
        //load up the behaviors
        
        gallery.rotatorPanelBehavior(rotator);
        
        
        //console.dir(rotator);
        
    });
    
  } //}}}
  
  
 
  
  //{{{ gallery.rotatorPanelBehavior = function(rotator)
  gallery.rotatorPanelBehavior = function(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(res){
            rotator.endFlag = (panel == rotator.panels.last() && gallery.moduleConfig.endOnLast == 'true' || rotator.endFlag==true) ? true : false;
            
            var elm = new Element('div');
            elm.innerHTML = res.responseText;
            
            
            
            $$('.gallery-title')[0].innerHTML = Element.select(elm, 'h1')[0].innerHTML; 
            
            if( Element.select(rotator.rHandler, '.fullvideo') ) {
               gallery.rotatorParserVideo(rotator);
            } else {
               gallery.rotatorParser(rotator);
            }
            
            
          }
          panel.removeAttribute('title');
          
          
          Event.observe(panel, 'click', function(e){
              // rotator clicked, change the index
              
              //rotator.currentRotationIndex =
              // get the current selected index
              //alert(panel.parentLi);
              
              //activepanel
              gallery.paused = false;
              gallery.rotatorImageLoad(rotator, panel)
              panel.blur();
              Event.stop(e);
              
              
              // reset to activepanel and set currentRotationIndex
              
              var temp = 0;
              for(x=0; x<=rotator.panels.length; x++){
                
                if (Element.hasClassName(rotator.panels[x].parentLi, 'activepanel')) {
                  rotator.currentRotationIndex = temp;
                  break;
                } else {
                  
                  if (temp >= gallery.pageSize) {
                    temp = 0; 
                  } else {
                    temp++;
                  }
                  
                  
                } // if

              } // for
              
          
              

              
          });
        }
    });
    
    /* Set the initial timer functions */
    if (gallery.reset == false) {
      rotator.generateTimer = gallery.rotatorSetRotation(rotator);
      
    }
    
  } //}}}

  gallery.rotatorSetRotation = function(rotator){
    
    window.setInterval(function(){
        
        if(rotator.endFlag == true || gallery.paused == true){
          //do nothing
        }
        else if(rotator.countDown >= 1 ){
          
          //$('debug').innerHTML = 'M:' + rotator.countDown;
          
          rotator.countDown--;
        }
        else if(rotator.countDown == 0){
          
          //$('debug').innerHTML = rotator.countDown;
          
          rotator.countDown = 'stop';
          gallery.rotatorDoRotation(rotator)
          
        } else {
           //$('debug').innerHTML = 'stopped at ' + rotator.countDown;
        }
        
    }, 1000, [rotator]);
  }
  
  
  
  
  
  
  

  
  
    
  gallery.gotoPage = function(page) {
     
     // make ajax request
     gallery.currentPage = page;
     
      var opts = {
        url: '/' + CoreSiteVars.cmscontext + '/test/grid/ajaxpage?async=true',
        params:'pageNumber=' + gallery.currentPage
      };
     
      
       opts.onComplete = function(res) {
           
           //var elm =  Element.select(res.transport.responseXML, '.imageset')[0];
           //alert(elm.innerHTML);
           //
           var elem = new Element('div');
           elem.innerHTML = res.responseText;
           
           
           $$('.imagelist')[0].innerHTML =  Element.select(elem, '.imageset')[0].innerHTML;
           
           
           // set the active panel
           gallery.reset = true;
           
           gallery.gridLoad();
           
           //rotator.panels      = Element.select(rotator, '.panel');
           var rotator = gallery.allRotators[0];
           rotator.activePanel = Element.select(rotator, '.activepanel')[0];
           gallery.rotatorImageLoad(rotator, rotator.panels[0]);
     
                 
           
          
           
        } 
        
        //  var newImage = Element.select(rotator.rHandler, '.fullimage')[0]
        //alert('updating....' + opts.url);
        modules.sendAsync(opts);      
      
      
      
     
  }
  
  
  
  //{{{ gallery.rotatorDoRotation = function(rotator)
  gallery.rotatorDoRotation = function(rotator){
    
    var skip = false;
    
    for(x=0; x<=rotator.panels.length; x++){

      
      
       if(x==rotator.panels.length-1 && rotator.endFlag == false) {
         
         
         
           if (rotator.strip.totalCount == 0) {
              gallery.currentPage = 1; 
              break; 
           }
         
         
           gallery.currentPage++; // set to next page
             
           
           
           
           if (gallery.currentPage > gallery.pages) {
              gallery.currentPage = 1; 
           }
         
         
            var opts = {
              url:  SiteVars.modules.Gallery.panels.url,
              params:'context=' + SiteVars.islandId + '&pageNumber=' + gallery.currentPage + '&galleryXML=' + SiteVars.modules.Gallery.panels.data 
            };
            
            opts.onComplete = function(res) {
               
               //var elm =  Element.select(res.transport.responseXML, '.imageset')[0];
               //alert(elm.innerHTML);
               //
               var elem = new Element('div');
               elem.innerHTML = res.responseText;
               
               
               $$('.imagelist')[0].innerHTML =  Element.select(elem, '.imageset')[0].innerHTML;
               
               // set the active panel
               gallery.reset = true;
               gallery.gridLoad();
               
               //rotator.panels      = Element.select(rotator, '.panel');
               rotator.activePanel = Element.select(rotator, '.activepanel')[0];
               
               // reset panels
               
               
               
               
              for(x=0; x<=rotator.panels.length; x++){
                if(rotator.panels[x].parentLi == rotator.activePanel && rotator.endFlag == false){
                  
                  gallery.rotatorImageLoad(rotator, rotator.panels[x]);
                  
                  
                  break;
                }
              }
                     
               
              
               
            } 
            
            //  var newImage = Element.select(rotator.rHandler, '.fullimage')[0]
            //alert('updating....' + opts.url);
            modules.sendAsync(opts);
            
            
            return; // escape
            
          
       } else if(rotator.panels[x].parentLi == rotator.activePanel && rotator.endFlag == false){
         
         
         rotator.currentRotationIndex++;
         
         
         break;
       }
    }
    
    

    
    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);
      }
    });
    
    
    
    // set title and stuff
  // $$('.gallery-caption')[0].innerHTML =  Element.select(rotator.rHandler, '.h3')[0].innerHTML;;
    
    
    
  } //}}}
  
  
  
  
  //{{{ 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');
        }
    });
    
    //alert('foobar!: ' + rotator.countDown);
   
    
    
    
    //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
    /* if(topNav.backVersion < 8 && topNav.backVersion != false){
      topNav.rebuild();
    } */
    
    //DD_roundies.addRule('ol.imagelist li', '12px');
    //DD_roundies.addRule('a.button-style', '7px');
    //Cufon.replace('h1');
    //Cufon.now(); 
    
    
  } //}}}
  
  
  gallery.rotatorParserVideo = 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.rHandler.innerHTML='';
    rotator.countDown = 10;
 
    
  } //}}}
  
  

  
  
  
  /* Lightbox extensions (extends base object at lightbox.js)*/
  
  //{{{ gallery.extendLightbox = function()
  gallery.extendLightbox = function(){

    //The following functions are only extending the lightbox object in order to deal with the addition of the hi-res download link, the cms-specific locations of the icons and the translation of text output
    //the following functions have been overriden:
    //  - initialize()
    //  - start()
    //  - updateDetails()
    
    // Also, the final line has been commented out of lightbox.js ( document.observe ... ) and call to the new Lightbox(); is being made here
    
    LightboxOptions.fileLoadingImage = '../template_images/gallery/loading.gif';
    LightboxOptions.fileBottomNavCloseImage = '../template_images/gallery/closelabel.gif';
    LightboxOptions.labelImage = gallery.moduleConfig.phrases.labelImage;
    LightboxOptions.labelOf = gallery.moduleConfig.phrases.labelOf;
    
    //{{{ 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',{id:'outerImageContainer'}, 
                    Builder.node('div',{id:'imageContainer'}, [
                        Builder.node('img',{id:'lightboxImage'}), 
                        Builder.node('div',{id:'hoverNav'}, [
                            Builder.node('a',{id:'prevLink', href: '#' }),
                            Builder.node('a',{id:'nextLink', href: '#' })
                        ]),
                        Builder.node('div',{id:'loading'}, 
                            Builder.node('a',{id:'loadingLink', href: '#' }, 
                                Builder.node('img', {src: LightboxOptions.fileLoadingImage})
                            )
                        )
                    ])
                ),
                Builder.node('div', {id:'imageDataContainer'},
                    Builder.node('div',{id:'imageData'}, [
                        Builder.node('div',{id:'imageDetails'}, [
                            Builder.node('span',{id:'caption'}),
                            Builder.node('span',{id:'numberDisplay'}),
                            Builder.node('a',{id:'hireslink', href: '#', target:'_blank'},gallery.moduleConfig.phrases.downloadText)
                        ]),
                        Builder.node('div',{id:'bottomNav'},
                            Builder.node('a',{id:'bottomNavClose', href: '#' },
                                Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage })
                            )
                        )
                    ])
                )
            ]));
      
      
      Event.observe($('hireslink'), 'click', function(e){
        
        var image = $('lightboxImage');
        var newLocation = image.src.substring(0, image.src.indexOf('?'))
        
        $('hireslink').href = newLocation;
        
        //Event.stop(e);
      });
          
      
      $('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));
  
          var th = this;
          (function(){
              var ids = 
                  'overlay lightbox outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 
                  'imageDataContainer imageData imageDetails caption numberDisplay hireslink bottomNav bottomNavClose';   
              $w(ids).each(function(id){ th[id] = $(id); });
          }).defer();
      } //}}}
      
    //{{{ Lightbox.prototype.start = function(imageLink)
    Lightbox.prototype.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 });

        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.title]);         
        } else {
            // if image is part of a set..
            this.imageArray = 
                $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
                collect(function(anchor){ return [anchor.href, anchor.title, anchor.className]; }).
                uniq();
            
            while (this.imageArray[imageNum][0] != imageLink.href) { 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);
      } //}}}
      
    //{{{ Lightbox.prototype.updateDetails = function()
    Lightbox.prototype.updateDetails = function() {
        //if allowdownload classname is present
        //console.log(this.imageArray[this.activeImage][2]);
        if (this.imageArray[this.activeImage][2].indexOf('allowdownload') != -1){
            $('hireslink').show();
        }
        else{
          $('hireslink').hide();
        }
        
        // if caption is not null
        if (this.imageArray[this.activeImage][1] != ""){
            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)
            } 
        );
      } //}}}

      
      new Lightbox();
  } //}}}
  
  
  
  
  
  if($$('.'+gallery.gridClassName)[0]){
    gallery.gridLoad();
  }  
  
 
  
}



