/**
 *  Lightbox Extension for TYPO3 extension "perfectlightbox", protaculous mode
 *
 *  At the moment of writing, the perfectlightbox extension comes with Lightbox version 2.03.3
 *  and thus needs some special handling regarding to method calls (getPageSize which is global
 *  in this version and controls to objects (extended elements) which is not included in this version
 *
 *  On the other hand, functionality like slideshow is already included in the (modified)
 *  Lightbox script
 *
 *  this file extends the lightbox script with
 *    - slideshow functionality
 *    - and navigational elements moved to bottomNav container
 *
 *  @author:  tommy(at)profi(dot)it
 *  @since:   2009-12-09 14:26:22
 *
 */

var Lightbox = Class.create(Lightbox, {
  initialize: function($super) {
    // call super class method
    $super();

    // @todo: document
    Element.setWidth('lbImageDataContainer', 250);

    // controls to objects: move elements to objects in Lightbox. context
    var th = this;
    (function(){
        var ids =
            'overlay lbLightbox lbOuterImageContainer lbImageContainer lightboxImage lbHoverNav prevLink nextLink loading loadingLink ' +
            'lbImageDataContainer lbImageData lbImageDetails lbCaption lbNumber bottomNav bottomNavClose';
        $w(ids).each(function(id){ th[id] = $(id); });
    }).defer();

    // modify controls
    this.modifyControls();
  },

  /**
   * modifies controls of the lightbox skeleton
   *
   */
  modifyControls: function() {
    // remove original prevLink and nextLink elements
    $$('#prevLink, #nextLink').invoke('remove');

    // switch close and slideshow control elements...
    var closeLinkRef = $('closeLink').remove();
    $('bottomNav').insert({ top: closeLinkRef });

    $('bottomNav').insert({ bottom: Builder.node('a', { id: 'nextLink', href: '#' }, LightboxOptions.labelNext) });
    $('bottomNav').insert({ bottom: Builder.node('a', { id: 'prevLink', href: '#' }, LightboxOptions.labelPrevious) });
  },

	//
	//	start()
	//	Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
  //
	//  overridden method to move Lightbox container a little further to the upper viewport limit
	//
	start: function(imageLink) {

		hideSelectBoxes();
		hideFlash();

		// stretch overlay to fill page and fade in
		var arrayPageSize = getPageSize();

		// ###########################################################################################################################
		// BEN: The setting of the width is not necessary as it's set to 100% in css. If user resizes browser during lightshow it breaks.
		//Element.setWidth('overlay', arrayPageSize[0]);
		Element.setHeight('overlay', arrayPageSize[1]);
		// ###########################################################################################################################

		new Effect.Appear('overlay', { duration: overlayDuration, from: 0.0, to: overlayOpacity });

		imageArray = [];
		imageNum = 0;

		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName( imageLink.tagName);

		// if image is NOT part of a set..
		if((imageLink.getAttribute('rel') == 'lightbox')){
			// add single image to imageArray
			imageArray.push(new Array(imageLink.getAttribute('href'), imageLink.getAttribute('title')));

			// ###########################################################################################################################
			//
			// BEN: Make sure the presentation mode and/or slideshow is disabled for single images!
			//
			presentationMode = false;
			slideshowEnabled = false;
			slideshowActive = false;
			$('pauseLink').hide();
			$('playLink').hide();
			// ###########################################################################################################################
		} else {
		// if image is part of a set..

			// loop through anchors, find other images in set, and add them to imageArray
			for (var i=0; i<anchors.length; i++){
				var anchor = anchors[i];
				if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == imageLink.getAttribute('rel'))){
					imageArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title')));
				}
			}

			// ############### BEN: Changed this to the "normal" prototype function that exists for these things!
			// probably this is even not wanted!? Disable completely?
			//imageArray.removeDuplicates();
			//imageArray.uniq();
			while(imageArray[imageNum][0] != imageLink.getAttribute('href')) { imageNum++;}

			// ###########################################################################################################################
			//
			// BEN: Adding a search for 'present' here. If matched activate presentation mode otherwise reset to false
			// Added another search for 'slideshow' to activate slideshow
			//
			if(imageLink.getAttribute('rel').toLowerCase().match('present')){
				presentationMode = true;
			} else {
				presentationMode = false;
			}
			if(imageLink.getAttribute('rel').toLowerCase().match('slideshow')){
				slideshowEnabled = true;
				slideshowActive = enableSlideshowAutoplay;
			} else {
				slideshowEnabled = false;
				slideshowActive = false;
				$('pauseLink').hide();
				$('playLink').hide();
			}
			// ###########################################################################################################################
		}

		// calculate top and left offset for the lightbox
		var arrayPageScroll = getPageScroll();
    // instead to use a 10th we use a 30th to move lightbox a little more to the upper viewport limit
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 30);
		var lightboxLeft = arrayPageScroll[0];
		Element.setTop('lbLightbox', lightboxTop);
		Element.setLeft('lbLightbox', lightboxLeft);

		$('lbLightbox').show();

		this.changeImage(imageNum);
	},

	//
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	changeImage: function(imageNum) {

		activeImage = imageNum;	// update global var

		// hide elements during transition
		if(animate){ $('lbLoading').show();}
		$('lightboxImage').hide();
		$('lbHoverNav').hide();
		$('prevLink').hide();
		$('nextLink').hide();
		//$('lbImageDataContainer').hide();
		$('lbNumber').hide();

		imgPreloader = new Image();

		// once image is preloaded, resize image container
		imgPreloader.onload=function(){
			Element.setSrc('lightboxImage', imageArray[activeImage][0]);
			myLightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height);
			// ###########################################################################################################################
			//
			// BEN: Adding link to image if saving is allowed
			//
			if (allowSave) {
				document.getElementById('saveLink').setAttribute('href',imageArray[activeImage][0]);
			}
			// ###########################################################################################################################
			imgPreloader.onload=function(){};	//	clear onLoad, IE behaves irratically with animated gifs otherwise
		}
		imgPreloader.src = imageArray[activeImage][0];
	},


  /**
   * overridden resizeImageContainer method
   *
   */
  resizeImageContainer: function($super, imgWidth, imgHeight) {
    $super(imgWidth, imgHeight);

    // set height to 0 (according to image replacement technique)
		Element.setHeight('prevLink', 0);
		Element.setHeight('nextLink', 0);

    if(!( wDiff == 0)){
		  Element.setWidth('lbImageDataContainer', this.widthCurrent);

      new Effect.Scale('lbImageDataContainer', this.xScale, {scaleY: false, delay: resizeDuration, duration: resizeDuration});
      //new Effect.Morph('lbImageDataContainer', { style: 'width: '+ widthNew +'px;', duration: resizeDuration });
    }
  },

	//
	//	updateDetails()
	//	Display caption, image number, and bottom nav.
	//
	updateDetails: function() {

		// if caption is not null
		if(imageArray[activeImage][1]){
			$('lbCaption').show();
			Element.setInnerHTML( 'lbCaption', imageArray[activeImage][1]);
		} else {
			$('lbCaption').hide();
		}

		// if image is part of set display 'Image x of x'
		if(imageArray.length > 1){
			$('lbNumber').show();
			Element.setInnerHTML( 'lbNumber', " " + lllImage + " " + eval(activeImage + 1) + " " + lllOf + " " + imageArray.length);
		}

		// ###########################################################################################################################
		//
		// BEN: Adding presentation mode
		// Added slideshow controls
		//
		if(presentationMode){
			// Hide numberDisplay again
			$('lbNumber').hide();
			myLightbox.updatePresentationNav();
		} else {
			$('lbPresent').hide();
		}

		if(slideshowEnabled) {
			if(slideshowActive) {
				$('playLink').hide();
				$('pauseLink').show();
			} else {
				$('pauseLink').hide();
				$('playLink').show();
			}
		}
		// ###########################################################################################################################

		// update overlay size and update nav
		var arrayPageSize = getPageSize();
		Element.setHeight('overlay', arrayPageSize[1]);
		myLightbox.updateNav();
    /*
		new Effect.Parallel(
			[ new Effect.SlideDown( 'lbImageDataContainer', { sync: true, duration: resizeDuration, from: 0.0, to: 1.0 }),
			  new Effect.Appear('lbImageDataContainer', { sync: true, duration: resizeDuration }) ],
			{ duration: resizeDuration, afterFinish: function() {
				// update overlay size and update nav
				var arrayPageSize = getPageSize();
				Element.setHeight('overlay', arrayPageSize[1]);
				myLightbox.updateNav();
				}
			}
		);
		*/
	}
});
