// set lightbox options
LightboxOptions.animate = false;
// this is being used to load AJAX on different gallery types.
// currently used by carousel and the scrollable galleries.
modules.loadActions.prototype.gallery = function() {
    gallery = this.gallery;
    gallery.lbox = null;
    gallery.carouselPage = 0; // current page in popup
    gallery.lbox = new Lightbox();
}



modules.loadActions.prototype.gallery.extendLightbox = function(){
   
    
 
    /* adds image via ajax to box */
    Lightbox.prototype.selImage = null;
    
    Lightbox.prototype.addImages = function(elem,setting) {
      var self = this;
      
      
      
      gallery.carouselPage = 0;
      
      var pfx = SiteVars.path_to_top;
      if ((typeof CoreSiteVars != null && typeof CoreSiteVars != 'undefined')) {
        if ( CoreSiteVars.cmscontext == 'staging' ) {
          pfx = '/' + CoreSiteVars.cmscontext;
        }
      }

      
      var ajaxurl = pfx + '/gallery/ajax-scrollable-loader';
      var ajaxparams = 'islandId=' + SiteVars.islandId  + '&galleryXML=' + gallery.galleryXML + '&galleryType=carousel-popup&contentType=' + setting.type; 
      
      if (setting.type == 'Media') {
        ajaxurl = pfx + '/gallery/ajax-media-loader'
        ajaxparams = 'galleryXML=' + gallery.galleryXML + '&galleryType=carousel-popup&contentType=' + setting.type + '&searchTerm=' + setting.searchTerm;
      }
      
      
      var opts = {
        sendMethod:'get',
        url: ajaxurl,
        params: ajaxparams
      };
      opts.onComplete = function(res) {
        var elem = new Element('div');
        elem.innerHTML = res.responseText;
        //alert(Element.select(elem, '.imageset')[0].innerHTML );
        //Element.insert($('innerImageNavigation'), { bottom: Element.select(elem, '.carousel-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(setting);
      }
      
      
      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.sendMethod = 'get';
      
      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');
      
      
      
        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
          //var elem = new Element('div');
          //elem.innerHTML = r.responseText;
          //var panel = Element.select(elem, '#panel-summary')[0]; // from AJAX
          
          // if summary is collapsed, then we need to add clear it out, hide, insert, and expand
          
          summary.hide();
          summary.innerHTML = r.responseText;
          summary.show();
         
          
          try {
            $$('.omniture-package')[0].innerHTML.evalScripts();
          } catch(e) {
            
          }
          
        }

        modules.sendAsync(opts);
      
    }
    
    
    //  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(setting) {
      //carousel-up
      //carousel-down
      //gallery.carouselPage
      
      this.bindImage();  
      
      
      //console.log('binding navigation');
            
      Event.stopObserving($('carousel-up'), 'click');
      Event.stopObserving($('carousel-down'), 'click');
      
      var pages = 0;
      
      if (setting.type == 'Video') {
        pages =  Math.ceil($$('.popup-Video li').length / 4)  - 1;
      } else if (setting.type == 'Media') { 
        pages =  Math.ceil($$('.imageset li').length / 5)  - 1;
      } else {
        pages =  Math.ceil($$('.popup-Image li').length / 4) - 1;
      }

      
      //console.log('pages: ' + pages);
      
      
 
      
      Event.observe($('carousel-up'), 'click', function(e) {
          //alert('going up ' + gallery.carouselPage + ' and ' + SiteVars.modules.Gallery.carousel.totalSize);
          //console.log('xx: this: ' + gallery.carouselPage);
          	
           
          
          if (gallery.carouselPage <= 0) {
            gallery.carouselPage = 0;
            return;
          } else {
            gallery.carouselPage--;  
            
            
            new Effect.Move($$('.carousel-items')[0], { 
                  duration:.5,
                  fps:100,
                  x:0, 
                  y:312
            });            
            
          }
          Event.stop(e);
          //} else {
            
          //}
          
      });
      
     
      
      // next
      Event.observe($('carousel-down'), 'click', function(e) {
          
          //alert(gallery.carouselPage + ' and ' + pages);
          
           
          //console.log(gallery.carouselPage + ' vs ' + (pages - 1));
          //console.log('xx: this: ' + gallery.carouselPage);
           
           
          if (gallery.carouselPage >= pages) {
            
            return;
          } else {
            
            gallery.carouselPage++;  
            
            //console.log($$('.carousel-items')[0]);
           //.carousel-container
            new Effect.Move($$('.carousel-items')[0], { 
                  duration:.5,
                  fps:100,
                  x:0, 
                  y:-312
            });
           
            
          }

          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 = imageLink.json.evalJSON();
          
          var setting = GallerySettings.GetSetting(json.lightboxid);
          
          
          $('javascroll').innerHTML = '';
          // now repopulate 
          
          this.addImages($('javascroll'), setting);
          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'}));
        
        /*MVN-999*/
        if(SiteVars.currentLocale.indexOf('en')==-1){
        	//console.log('if '+currentLocale);
        	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'})
								
							]),
							Builder.node('div', {className:'bottom'}, [
								 Builder.node('span',{id:'closewin'},[ 
									 Builder.node('a',{href: '#', id:'bottomNavClose'}, SiteVars.modules.LBox.phrases.close),
										 ' X'
								 ])
							])
		
					]));
        //console.log('if '+currentLocale);
        }	else{ // almost same as if - only diff is that  the else includes a link to the /guidebook/gallery
        	//console.log('else '+currentLocale);
							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'})
									
								]),
								Builder.node('div', {className:'bottom'}, [
									 Builder.node('span',{id:'gallerynav'},[
										 Builder.node('a',{id:'gotogal', href: SiteVars.path_to_top +  '/' + SiteVars.islandId + '/guidebook/gallery' }, SiteVars.modules.LBox.phrases.goToGallery)
									 ]),
									 Builder.node('span',{id:'closewin'},[ 
										 Builder.node('a',{href: '#', id:'bottomNavClose'}, SiteVars.modules.LBox.phrases.close),
											 ' X'
									 ])
								])
							
						]));
						//	console.log('else '+currentLocale);
        
        }
        
      
      
      
      
      
      
      Event.observe($('hireslink'), 'click', function(e){
        
        var image = $('lightboxImage');
        var newLocation = image.src.substring(0, image.src.indexOf('?'))
        
        $('hireslink').href = newLocation;
        
        //Event.stop(e);
      });
      
      //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 });
      $('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
      
      /*
      $('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.showImage = function(){
      
      
      
      
        this.loading.hide();
        
  
        
        
        
        new Effect.Appear(this.lightboxImage, { 
            duration: this.resizeDuration, 
            queue: 'end', 
            afterFinish: (function(){
              
              this.updateDetails();
              
            }).bind(this) 
        });
        this.preloadNeighborImages();
        
    },
    
    
    
    //
    //  changeImage()
    //  Hide most elements and preload image in preparation for resizing image container.
    //
    Lightbox.prototype.changeImage =  function(imageNum) {   
        this.loadImageStrip();
        
        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();      
        if (json.type == 'Video') {
          
          this.showVideo(json);
        } 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'});
      
        }
        
        this.updateDetails();
    },
        
    
    
    
    
    
     
    // 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 != null && typeof CoreSiteVars != 'undefined')) {
        if ( CoreSiteVars.cmscontext == 'staging' ) {
          pfx = '/' + CoreSiteVars.cmscontext;
        }
      }else if(SiteVars.currentLocale!='' && SiteVars.currentLocale!='undefined'){
        	pfx = '/' + SiteVars.mappedLocale;
      }	

            
      var opts = {
        sendMethod:'get',
        url: pfx + '/internal/gallery/load-video',
        params:'docid=' + json.docid
      };      
      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});
        
                
        //IE7 fix
        
         // var ie7 = (document.all && !window.opera && window.XMLHttpRequest);
          
          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');
              alert(r.responseText);
              
              scripts.each(function(item) {
                 eval(item.innerHTML); 
              });
              
            }
              
        
        /*
        var scripts = Element.select($('outerImageContainer'), 'script');
        scripts.each(function(item) {
           eval(item.innerHTML); 
        });
        */
        
        
        // test for now, remove later
       // $$('.carousel-container')[0].setStyle( {width:'271px',height:'224px'} );
        
      }
      
      modules.sendAsync(opts);
    }
  

}

modules.loadActions.prototype.gallery.extendLightbox();


