var LightboxColorWhite = '#fff';
var LightboxColorDark = '#000';

//
//  Configuration of js gallery
//
LightboxOptions = Object.extend(
  window.LightboxOptions,
  {
    fileLoadingImage:        sImageDir + 'lightbox/loading.gif',
//    fileBottomNavCloseImage: sImageDir + 'lightbox/closelabel.gif',
    fileBottomNavCloseImage: 'fileadmin/templates/images/diashw_close.gif',

    overlayOpacity: 0.8,   // controls transparency of shadow overlay

    animate: true,         // toggles resizing animations
    resizeSpeed: 8,        // controls the speed of the image resizing animations (1=slowest and 10=fastest)

    borderSize: 20,         //if you adjust the padding in the CSS, you will need to update this variable

	// When grouping images this is used to write: Image # of #.
	// Change it for non-english localization
  labelImage: oLocalLang.sGetLang('lightbox_labelImage', " Bild "),
  labelOf: oLocalLang.sGetLang('lightbox_labelOf', " von "),

  labelBackground: " ",
  labelSlideShowStart: " ",
  labelSlideShowStop: " ",
  SlideShowClassRunning: "ss_running",
  SlideShowClassPaused: "ss_paused",
  
  bSlideShow: false,
  iSlideShowTimer: 8,
  bSlideShowLoop: false,
  iOneSideNeighbours: 2,
  bPageVisibleStyleDisplay : 'inline',
  sPagerDots : ' ... '
});


Lightbox.prototype = Object.extend(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.bSlideShow = LightboxOptions.bSlideShow;
      this.bDisplayed = false;
      var labelSlideShow = this.bSlideShow ? LightboxOptions.labelSlideShowStop : LightboxOptions.labelSlideShowStart;
      var classSlideShow = this.bSlideShow ? LightboxOptions.SlideShowClassRunning : LightboxOptions.SlideShowClassPaused;
      this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0;
      this.overlayDuration = LightboxOptions.animate ? 0.2 : 0;  // shadow fade in/out duration

        // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
        // If animations are turned off, it will be hidden as to prevent a flicker of a
        // white 250 by 250 box.
        var size = (LightboxOptions.animate ? 250 : 1) + 'px';

        var objBody = $$('body')[0];

        objBody.appendChild(Builder.node('div',{id:'overlay'}));

        objBody.appendChild(Builder.node('div',{id:'lightbox'},
          Builder.node('div', {id:'externalContainer'}, [

            
            Builder.node('div',{id:'outerImageContainer'}, [
              Builder.node('div',{id:'imageDetails'}
              ),
              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:'imageNavigationData'},[

                Builder.node('span',{id:'changeBg'},[
                  /*Builder.node('div', {id:'labelBg'}, LightboxOptions.labelBackground + ''),*/
                  Builder.node('span',{id:'makeWhiteBg', style:'background:' + LightboxColorWhite + ';'}),
                  Builder.node('span',{id:'makeDarkBg', style:'background:' + LightboxColorDark + ';'})
                ]),               
              
                Builder.node('div',{id:'bottomNav'},
                  Builder.node('a',{id:'bottomNavClose', href: '#' },
                    Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage })
                  )
                ),            

                Builder.node('div',{id:'slideShowManage'},[
                  Builder.node('a',{id:'prevLink1', href: '#'}),
                  Builder.node('a',{id:'nextLink1', href: '#'}),
                  Builder.node('div',{id:'slideShowRun', 'class':classSlideShow}, labelSlideShow)
                ]),
                
              ]),
              
              Builder.node('div',{id:'imageNavigationDataRow2'},[

                Builder.node('span',{id:'imageNumber'},
                  Builder.node('span',{id:'numberDisplay'})
                ),
              
              ]),
              
              Builder.node('div',{id:'lb_pager'}, 'pager'),
            
              Builder.node('div',{id:'imageData'},[
                Builder.node('span',{id:'caption'}),
                Builder.node('div', {id:'imageDescription'}, 'the description'),                
              ])
            ])
          ])
        ));

    $('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.stopSlideShow(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this));
    $('prevLink1').observe('click', (function(event) { event.stop(); this.stopSlideShow(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this));
    $('nextLink').observe('click', (function(event) { event.stop(); this.stopSlideShow(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this));
    $('nextLink1').observe('click', (function(event) { event.stop(); this.stopSlideShow(); 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));

    $('makeDarkBg').observe('click', (function(event) { event.stop(); this.colorizeContainers(LightboxColorDark); }).bindAsEventListener(this));
    $('makeWhiteBg').observe('click', (function(event) {event.stop(); this.colorizeContainers(LightboxColorWhite);}).bindAsEventListener(this));
    document.observe('showroom:lb_pager', (function(event) { 
      event.stop();
      this.stopSlideShow(); 
      if(event.memo.imageNumber != this.activeImage) {
        this.changeImage(event.memo.imageNumber);
      }
    }).bindAsEventListener(this));
    $('slideShowRun').observe('click', (function(event) { 
      event.stop(); 
      this.bSlideShow = !this.bSlideShow;
      
      if (this.bSlideShow) {
        $('slideShowRun').update(LightboxOptions.labelSlideShowStop);
        $('slideShowRun').writeAttribute("class", "ss_running");
      } else {
        $('slideShowRun').update(LightboxOptions.labelSlideShowStart);
        $('slideShowRun').writeAttribute("class", "ss_paused");
      }
    }).bindAsEventListener(this));

        var th = this;
        (function(){
            var ids =
                'overlay lightbox outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink prevLink1 nextLink1 loading loadingLink ' +
                'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose';
            $w(ids).each(function(id){ th[id] = $(id); });
        }).defer();
    this.oSlideShowEngine(this);
  },
  pager_initialized: false,
  initPager: function(oObj) {
	if (oObj.pager_initialized) {
		return;
	}
	sPagerContent = "";
	iPagesNum = oObj.imageArray.length
    $('lb_pager').update( iPagesNum + ', ' + oObj.activeImage);
    if (iPagesNum < 2) {
    	$('lb_pager').update('&nbsp;');
    	this.pager_initialized = true;
    	return;
    }
   
    for (i = 1;i<=iPagesNum;i++) {
      sOnClick = "document.fire('showroom:lb_pager', {imageNumber: " + (i - 1) + "});";
      sPagerContent += '<a id="lb_page'+ i +'" onclick="' + sOnClick + '"><span>' + i + '</span></a>';
      if (i == 1) {
        sPagerContent += '<span id="lb_page_dots_first">' + window.LightboxOptions.sPagerDots + '</span>';
      } 
      if (i == iPagesNum - 1) {
        sPagerContent += '<span id="lb_page_dots_last">' + window.LightboxOptions.sPagerDots + '</span>';
      }
      
    }
    $('lb_pager').update(sPagerContent);
    
    
    this.pager_initialized = true;
  },
  
  pagerChange: function(iTotal, iCurrent, iNeigbours) {
    if (iTotal == 0) {
    	return
    }
    iCurrentPage = iCurrent+1;
    
    if ($('lb_page_dots_last') !== null ) {
      if (iCurrentPage + iNeigbours < iTotal - 1) {
        $('lb_page_dots_last').style.display = window.LightboxOptions.bPageVisibleStyleDisplay;
      } else {
        $('lb_page_dots_last').style.display = 'none';
      }
    }
    
    if ($('lb_page_dots_first') !== null ) {
      if (iCurrentPage - iNeigbours > 2) {
        $('lb_page_dots_first').style.display = window.LightboxOptions.bPageVisibleStyleDisplay;
      } else {
        $('lb_page_dots_first').style.display = 'none';
      }
    }

    for (i = 1; i <= iTotal; i++) {
      bHide = false;
      if (i < (iCurrentPage - iNeigbours)) {
        bHide = true;
      }
      if (i > (iCurrentPage + iNeigbours)) {
        bHide = true;
      }
      if (i == 1 || i == iTotal) {
        bHide = false;
      }
      sPagerElementId = 'lb_page' + i;
      if ($(sPagerElementId) != null) {
        if (bHide) {
        	$(sPagerElementId).style.display = 'none';
        }else {
        	$(sPagerElementId).style.display = window.LightboxOptions.bPageVisibleStyleDisplay;
        }
        if (iCurrentPage == i) {
          $(sPagerElementId).writeAttribute('class', 'lb_current_page');
        } else {
          $(sPagerElementId).writeAttribute('class', '');
        }
      }
      
    }
    
  },
  
  colorizeContainers: function(newColor) {
    $('outerImageContainer').setStyle({backgroundColor: newColor});
    //$('imageDataContainer').setStyle({backgroundColor: newColor});
  },
  oSlideShowEngine: function (oObj) {
    this.timer = new PeriodicalExecuter(function(pe) {oObj.MakeNextSlide();}, LightboxOptions.iSlideShowTimer);
  },
  MakeNextSlide: function() {
    if (this.bSlideShow && this.bDisplayed) {
      var iNextImg;
      if (this.imageArray.length > this.activeImage + 1) {
        iNextImg = this.activeImage + 1;
        this.changeImage(iNextImg);
      } else {
        if (LightboxOptions.bSlideShowLoop) {
          iNextImg = 0;
          this.changeImage(iNextImg);
        } else {
          this.stopSlideShow();
        }
      }
    }
  },
  preloadNeighborImages: function(){
        var preloadNextImage, preloadPrevImage;
        if (this.imageArray.length > this.activeImage + 1){
            preloadNextImage = new Image();
            preloadNextImage.src = this.imageArray[this.activeImage + 1][0];
        } else {
          if (LightboxOptions.bSlideShowLoop) {
            preloadNextImage = new Image();
            preloadNextImage.src = this.imageArray[0][0];
          }
        }

        if (this.activeImage > 0){
            preloadPrevImage = new Image();
            preloadPrevImage.src = this.imageArray[this.activeImage - 1][0];
        } else {
          if (LightboxOptions.bSlideShowLoop) {
            preloadPrevImage = new Image();
            preloadPrevImage.src = this.imageArray[this.imageArray.length - 1][0];
          }
        }
  },
  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]; }).
                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);
        this.bDisplayed = true;
        this.initPager(this);
  },
  end: function() {
        this.bDisplayed = false;
        this.stopSlideShow();
        this.disableKeyboardNav();
        this.lightbox.hide();
        new Effect.Fade(this.overlay, { duration: this.overlayDuration });
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
  },
  stopSlideShow: function() {
      this.bSlideShow = false;
      $('slideShowRun').update(LightboxOptions.labelSlideShowStart);
      $('slideShowRun').writeAttribute("class", "ss_paused");
  },
  
  changeImage: function(imageNum) {

      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();
      this.prevLink1.hide();
      this.nextLink1.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(){
          this.lightboxImage.src = this.imageArray[this.activeImage][0];
          this.resizeImageContainer(imgPreloader.width, imgPreloader.height);
          this.pagerChange(this.imageArray.length, imageNum, window.LightboxOptions.iOneSideNeighbours);
      }).bind(this);
      imgPreloader.src = this.imageArray[this.activeImage][0];
  },  
  
    resizeImageContainer: function(imgWidth, imgHeight) {

        // get current width and height
        var widthCurrent  = this.outerImageContainer.getWidth();
        var heightCurrent = this.outerImageContainer.getHeight();

        // get new width and height
        var widthNew  = (imgWidth  + LightboxOptions.borderSize * 2);
        var heightNew = (imgHeight + LightboxOptions.borderSize * 2);

        // scalars based on change from old to new
        var xScale = (widthNew  / widthCurrent)  * 100;
        var yScale = (heightNew / heightCurrent) * 100;

        // calculate size difference between new and old image, and resize if necessary
        var wDiff = widthCurrent - widthNew;
        var hDiff = heightCurrent - heightNew;

        if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {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.prevLink1.setStyle({ height: '15' + 'px' });
            this.nextLink1.setStyle({ height: '15' + 'px' });
            this.prevLink1.setStyle({ width: '20' + 'px' });
            this.nextLink1.setStyle({ width: '20' + 'px' });
            
            this.imageDataContainer.setStyle({ width: widthNew + 'px' });

            this.showImage();
        }).bind(this).delay(timeout / 1000);
    },  
    
    //
    //  updateNav()
    //  Display appropriate previous and next hover navigation.
    //
    updateNav: function() {

        this.hoverNav.show();

        // if not first image in set, display prev image button
        if (this.activeImage > 0) {
          this.prevLink.show();
          this.prevLink1.show();
        }  

        // if not last image in set, display next image button
        if (this.activeImage < (this.imageArray.length - 1)) {
          this.nextLink.show();
          this.nextLink1.show();
        }  

        this.enableKeyboardNav();
    },    
  
  updateDetails: function() {

        // if caption is not null
        if (this.imageArray[this.activeImage][1] != ""){
            var sCaption = this.imageArray[this.activeImage][1];
            var aDetails = [];
            sCaption.scan(/[^\|]+/, function(match){ aDetails.push(match[0])});
            this.caption.update(aDetails[0]).show();
            $('imageDescription').update(aDetails[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)
            }
        );
  }
});

/**
 overloaded method for load light box: was done becasue of issue linked with checking of loading DOM elements
 by prototype function observe which works not correct. 
*/

document.observe('page:fully_loaded', function () { new Lightbox(); });
