// -----------------------------------------------------------------------------------
//
//	Martijn Smeets Fotografie Slideshow v0.96
//  by Martijn Smeets - http://www.martijnsmeetsfotografie.nl
//	Last Modification: February 25, 2010
//
//	Based on the original Lightbox by: Lokesh Dhakar - http://www.lokeshdhakar.com
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//  	- Free for use in both personal and commercial projects
//		- Attribution requires leaving author name, author link, and the license info intact.
//
// -----------------------------------------------------------------------------------
/*

    Table of Contents
    -----------------
    Configuration

    Lightbox Class Declaration
    - initialize()
    - updateImageList()
    - start()
    - changeImage()
    - resizeWindow()
    - showImage()
    - updateDetails()
    - updateNav()
    - enableKeyboardNav()
    - disableKeyboardNav()
    - keyboardAction()
    - preloadNeighborImages()
    - toggleAutoSlideshowMode()
    - startAutoSlideshowMode()
    - stopAutoSlideshowMode()
    - advanceSlideshow()
    - next()
    - previous()
    - end()
    - originalState()
    
    Function Calls
    - document.observe()
   
*/
// -----------------------------------------------------------------------------------

//
//  Configuration
//
slideshowOptions = Object.extend({
    fileLoadingImage:        'http://www.martijnsmeetsfotografie.nl/images/loading-bar-black.gif',     
    fileSlideshowCloseImage: 'http://www.martijnsmeetsfotografie.nl/images/slideshowClose.png',

    captionOpacity: 1.0,	// controls transparency of caption
    arrowOpacity: 0.2,		// controls transparency of the left and right arrows
    
    animate: true,			// toggles resizing animations
    resizeSpeed: 7,			// controls the speed of the image resizing animations (1=slowest and 10=fastest)
    slideshowDelay : 5,		// the delay between switching photos in the slideshowMode (in seconds)
    
	initialHeight: 527,    //the initial height of the slideshow div (same as CSS value)
	initialWidth: 790,     //the initial width of the slideshow div (same as CSS value)

	// When grouping images this is used to write: Image # of #.
	// Change it for non-english localization
	labelImage: "Image",
	labelOf: "of"
}, window.slideshowOptions || {});

// -----------------------------------------------------------------------------------

var Slideshow = Class.create();

Slideshow.prototype = {
    imageArray: [],
    animating: false,
    activeImage: undefined,
    autoSlideshowMode: false,
    activeSlideshow: false,
    
    // initialize()
    // Constructor runs on completion of the DOM loading. Calls updateImageList and then
    // the function inserts html at the bottom of the page which is used to display the shadow 
    // overlay and the image container.
    //
    initialize: function() {    
        
        this.updateImageList();
        
        this.keyboardAction = this.keyboardAction.bindAsEventListener(this);

        if (slideshowOptions.resizeSpeed > 10) slideshowOptions.resizeSpeed = 10;
        if (slideshowOptions.resizeSpeed < 1)  slideshowOptions.resizeSpeed = 1;

	    this.resizeDuration = slideshowOptions.animate ? ((11 - slideshowOptions.resizeSpeed) * 0.15) : 0;
	    this.overlayDuration = slideshowOptions.animate ? 0.5 : 0;  // shadow fade in/out duration

        // Code inserts html in the 'contentContainer DIV that looks similar to this:
        //
		//	<div id="slideshow">
		//		<div id="slideshowImageContainer">
		//			<img id="slideshowImage">
		//		</div>
		//		<div id="navigationControls">
		//			<div id="navigationLeft">
		//				<a href="#" ></a>
		//			</div>
		//		<div id="navigationRight">
		//			<a href="#" ></a>
		//		</div>    
		//		<div id="slideshowPlayContainer">
		//			<div id="slideshowPlay">
		//				<a href="#" ></a>
		//			</div>
		//		</div>  
		//           
		//		<div id="slideshowDataContainer">
		//			<div id="slideshowData">
		//				<div id="imageDetails">
		//					<span id="imageCaption"></span>
		//					<div id="imageNumberContainer">
		//						<span id="imageNumber"></span>
		//					</div>
		//				</div>
		//				<div id="slideshowCloseContainer">
		//					<a href="#" id="slideshowClose">
		//						<img src="http: www.martijnsmeetsfotografie.nl/images/slideshowClose.png">
		//					</a>
		//				</div>
		//			</div>
		//		</div>		
		//	</div>


		// The element in which the slideshow HTML structure should be appended
        var objSlideshow = $('contentContainer');

        objSlideshow.appendChild(Builder.node('div',{id:'slideshow'}, [
                Builder.node('div',{id:'slideshowImageContainer'}, [
                    Builder.node('img',{id:'slideshowImage'}) 
                ]),
                Builder.node('div',{id:'navigationControls'}, [
                    Builder.node('div',{id:'navigationLeft'}, [
                    	Builder.node('a',{id: 'navigationLeftLink', href: '#', title: 'Click or use arrow keys' }) 
                    ]),
                    Builder.node('div',{id:'navigationRight'}, [
                    	Builder.node('a',{id: 'navigationRightLink', href: '#', title: 'Click or use arrow keys' }) 
                    ]),
                    Builder.node('div',{id:'slideshowPlayContainer'}, [
                    	Builder.node('div',{id:'slideshowPlay'}, [
                    		Builder.node('a',{id:'slideshowPlayLink', href: '#', title: 'Click or press S to start the slideshow' }) 
                    	])	
                    ])
                ]),
        		Builder.node('div', {id:'slideshowDataContainer'}, [
                	Builder.node('div',{id:'slideshowData'}, [
                		Builder.node('div',{id:'imageDetails'}, [
                        	Builder.node('span',{id:'imageCaption'}),
                        	Builder.node('div',{id:'imageNumberContainer'}, [
                        		Builder.node('span',{id:'imageNumber'})
                        	]),
                    	]),
                    	Builder.node('div',{id:'slideshowCloseContainer'},
                        	Builder.node('a',{id:'slideshowClose', href: '#', title: 'Click or press ESC to close the image viewer' }, 'Close X')
                    	)
                	])
                ])
        ]));   

		// EVENTS
		$('slideshow').hide().observe('click', (function(event) { if (event.element().id == 'slideshow') this.end(); }).bind(this)); 
		$('navigationLeftLink').observe('click', (function(event) { event.stop(); this.previous(); }).bindAsEventListener(this));
		$('navigationRightLink').observe('click', (function(event) { event.stop(); this.next(); }).bindAsEventListener(this));	
		$('slideshowPlayLink').observe('click', (function(event) { event.stop(); this.toggleAutoSlideshowMode(); }).bindAsEventListener(this));
		$('slideshowClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));

		// Make HTML elements accessible by the 'this' call
        var th = this;
        (function(){
            var ids = 'footer contentContainer mainMenuContainer scrollbarContent scrollbarTrack ' +
            		  'slideshow slideshowImageContainer slideshowImage navigationControls navigationLeft navigationLeftLink navigationRight navigationRightLink ' + 
            		  'slideshowPlayContainer slideshowPlay slideshowPlayLink slideshowDataContainer slideshowData imageDetails imageCaption imageNumberContainer ' +
            		  'imageNumber slideshowCloseContainer slideshowClose';   
            $w(ids).each(function(id){ th[id] = $(id); });
        }).defer();
    },



    //
    // updateImageList()
    // Loops through anchor tags looking for 'lightbox' references and applies onclick
    // events to appropriate links. You can rerun after dynamically adding images w/ajax.
    //
    updateImageList: function() {   
        this.updateImageList = Prototype.emptyFunction;
        document.observe('click', (function(event){
            var target = event.findElement('a[rel^=slideshow]') || event.findElement('area[rel^=slideshow]');
            if (target) {
                event.stop();
                this.start(target);
            }
        }).bind(this));
    },


    
    //
    //  start()
    //  Hide the window below and start the slideshow mode. If image is part of a set, add siblings to imageArray.
    //
    start: function(imageLink) {    

		// Temporarily hide the scrollbar and other background elements
        //$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
		this.scrollbarTrack.style.visibility = 'hidden';
  	    new Effect.Parallel(
        [ 
        	new Effect.Appear(this.mainMenuContainer, { duration: this.overlayDuration, from: 1.0, to: 0.0 }),
        	new Effect.Appear(this.scrollbarContent, { duration: this.overlayDuration, from: 1.0, to: 0.0 }),
        	new Effect.Appear(this.footer, { duration: this.overlayDuration, from: 1.0, to: 0.0 })
	    ], 
            { 
    	        duration: this.overlayDuration,
    	        afterFinish: (function() {
	                	this.scrollbarContent.style.visibility = 'hidden';
                }).bind(this)   
    	     }
    	 );
    	 
    	 

		// Create an array with all the slideshow images of the page
        this.imageArray = [];
        var imageNum = 0;       
        if ((imageLink.rel == 'slideshow')){
            // 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++; }
        }

        // show the slideshow and go to the first image 
        this.slideshow.show();
        this.changeImage(imageNum);
    },




    //
    //  changeImage()
    //  Hide most elements and preload image in preparation for resizing image container.
    //
    changeImage: function(imageNum) {   
        
        this.activeImage = imageNum; 		// update global var

        // hide elements during transition
        this.slideshowImage.hide();
        this.navigationControls.hide();
        this.navigationLeftLink.hide();
        this.navigationRightLink.hide(); 
        
		// HACK: Opera9 does not currently support scriptaculous opacity and appear fx
        this.slideshowDataContainer.setStyle({opacity: .0001});     
        
        var imgPreloader = new Image();
        
        // once image is preloaded, resize image container
        imgPreloader.onload = (function(){
            this.slideshowImage.src = this.imageArray[this.activeImage][0];
            this.resizeWindow(imgPreloader.width, imgPreloader.height);
        }).bind(this);
        imgPreloader.src = this.imageArray[this.activeImage][0];
    },
    
    
    

    //
    //  resizeWindow()
    //	resize the image window to accommodate the new image
    //
    resizeWindow: function(imgWidth, imgHeight) {

        // get width and height of the current image and the new image
        var widthCurrent  = this.slideshow.getWidth();
        var heightCurrent = this.slideshow.getHeight();
        var widthNew  = imgWidth;
        var heightNew = imgHeight;

        // scalars based on change from old to new slideshow window
        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.contentContainer, yScale, {scaleX: false, scaleContent: false, scaleFromCenter: true, duration: this.resizeDuration, queue: 'end'}); 
        if (wDiff != 0) new Effect.Scale(this.contentContainer, xScale, {scaleY: false, scaleContent: false, scaleFromCenter: true, duration: this.resizeDuration, queue: 'end'});

        // 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.showImage(); }).bind(this).delay(timeout / 1000);
    },
    
    
    
    
    //
    //  showImage()
    //  Display image and begin preloading neighbors
    //
    showImage: function(){
        new Effect.Appear(this.slideshowImage, { 
            duration: this.resizeDuration, 
            queue: 'end', 
            afterFinish: (function(){ this.updateDetails(); }).bind(this) 
        });
        this.preloadNeighborImages();

		// if autoSlideshowMode is active, queue the next slide
        if(this.autoSlideshowMode)
	        (function(){
    	        	this.advanceSlideshow();
        	}).bind(this).delay(slideshowOptions.slideshowDelay);     
    },





    //
    //  updateDetails()
    //  Reload caption section (caption, image number, controls, close)
    //
    updateDetails: function() {
        // if imageCaption is not null
        if (this.imageArray[this.activeImage][1] != "") {
            this.imageCaption.update(this.imageArray[this.activeImage][1]).show();
        }
        
        // if image is part of set display 'Image x of x' and controls
        if (this.imageArray.length > 1){
            this.imageNumber.update( slideshowOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + slideshowOptions.labelOf + '  ' + this.imageArray.length);
        }
        
        // Fade in the slideshowDataContainer
  	    new Effect.Appear(this.slideshowDataContainer, { duration: this.resizeDuration, from: 0.0, to: 1.0, afterFinish: (function() { this.updateNav(); }).bind(this) });   
    },
       
    
    
    

    //
    //  updateNav()
    //  Display appropriate previous and next hover navigation.
    //
    updateNav: function() {
              
        if (this.activeImage > 0) this.navigationLeftLink.show();									// Not first image
        if (this.activeImage < (this.imageArray.length - 1)) this.navigationRightLink.show();			// Not last image
        this.enableKeyboardNav();
        
        // Fade in the navigationControls
  	    new Effect.Appear(this.navigationControls, { duration: this.resizeDuration, from: 0.0, to: 1.0 });          
    },



    //
    //  enableKeyboardNav()
    //
    enableKeyboardNav: function() {
        document.observe('keydown', this.keyboardAction); 
    },

    //
    //  disableKeyboardNav()
    //
    disableKeyboardNav: function() {
        document.stopObserving('keydown', this.keyboardAction); 
    },



    //
    //  keyboardAction()
    //
    keyboardAction: function(event) {
        var keycode = event.keyCode;

        var escapeKey;
        if (event.DOM_VK_ESCAPE) {  // mozilla
            escapeKey = event.DOM_VK_ESCAPE;
        } else { // ie
            escapeKey = 27;
        }

        var key = String.fromCharCode(keycode).toLowerCase();
        
        if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close slideshow
            this.end();
        } else if ((key == 'p') || (keycode == 37)){ // display previous image
            this.previous();
        } else if ((key == 'n') || (keycode == 39)){ // display next image
            this.next();
        } else if ((key == 's') ){ // start or stop the autoSlideshowMode
            this.toggleAutoSlideshowMode();
        }
    },



    //
    //  preloadNeighborImages()
    //  Preload previous and next images.
    //
    preloadNeighborImages: function(){
        var preloadNextImage, preloadPrevImage;
        if (this.imageArray.length > this.activeImage + 1){
            preloadNextImage = new Image();
            preloadNextImage.src = this.imageArray[this.activeImage + 1][0];
        }
        if (this.activeImage > 0){
            preloadPrevImage = new Image();
            preloadPrevImage.src = this.imageArray[this.activeImage - 1][0];
        }
    },



    
    //
    //  toggleAutoSlideshowMode()
    //  Start/Stop the slideshowMode.
    //
    toggleAutoSlideshowMode: function(){
    	if(this.autoSlideshowMode) this.stopAutoSlideshowMode();
    	else this.startAutoSlideshowMode();
    },
    
    //
    //  startAutoSlideshowMode()
    //
    startAutoSlideshowMode: function(){
		this.autoSlideshowMode = true;
   		this.slideshowPlayLink.style.background = 'url(http://www.martijnsmeetsfotografie.nl/images/slideshowPause.png) no-repeat';
   		this.slideshowPlayLink.setAttribute('title', 'Click or press S to pause the slideshow');
   		// Check whether or not a slideshow is already active
   		if(!this.activeSlideshow) {
   			this.activeSlideshow = true; 
       		(function(){
   	    	    this.advanceSlideshow();
       		}).bind(this).delay(slideshowOptions.slideshowDelay); 
       	}
    },    

    //
    //  stopAutoSlideshowMode()
    //
    stopAutoSlideshowMode: function(){
       	this.autoSlideshowMode = false;
       	this.slideshowPlayLink.style.background = 'url(http://www.martijnsmeetsfotografie.nl/images/slideshowPlay.png) no-repeat';
       	this.slideshowPlayLink.setAttribute('title', 'Click or press S to start the slideshow');
    },

    //
    //  advanceSlideshow()
    //  automatically display the next (or first) image
    //
    advanceSlideshow: function(){
        if (this.autoSlideshowMode) { 								// Continue this slideshow
        	this.disableKeyboardNav();
        	if(this.activeImage < (this.imageArray.length - 1)) 
	        	this.changeImage(this.activeImage + 1);   
	    	else 
	    		this.changeImage(0);
	    } else  													// End this slideshow
	    	this.activeSlideshow = false;
    },
    
    
    
    //
    //  next()
    //  'manually' display the next image
    //
    next: function(){
        if(this.activeImage < (this.imageArray.length - 1)) {  
            this.stopAutoSlideshowMode();
			this.disableKeyboardNav();
	        this.changeImage(this.activeImage + 1);   
	    }
    },    
    
    //
    //  previous()
    //  'manually' display the previous image
    //
    previous: function(){
        if(this.activeImage != 0) {        	
            this.stopAutoSlideshowMode();
			this.disableKeyboardNav();
	        this.changeImage(this.activeImage - 1);   
	    }
    },        





    //
    //  end()
    //  End the slideshow view mode
    //
    end: function() {
    	// disable the slideshow and its controls
    	if(this.autoSlideshowMode) 
    		this.stopAutoSlideshowMode();
        this.disableKeyboardNav();
        this.slideshow.hide();
        
        // get width and height of current image
        var widthCurrent  = this.slideshow.getWidth();
        var heightCurrent = this.slideshow.getHeight();

        // get new width and height
        var widthNew  = slideshowOptions.initialWidth;
        var heightNew = slideshowOptions.initialHeight;
        
        // scalars based on change from old to new slideshow window
        var xScale = (widthNew  / widthCurrent)  * 100;
        var yScale = (heightNew / heightCurrent) * 100;

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

		// If a vertical resize is needed
        if (hDiff != 0)
        	new Effect.Scale(this.contentContainer, yScale, {
        		scaleX: false, 
        		scaleContent: false, 
        		scaleFromCenter: true, 
        		duration: this.resizeDuration, 
        		queue: 'front'
  	    	}); 
  	    
  	    // if a horizontal resize is needed
        if (wDiff != 0) 
  	    	new Effect.Scale(this.contentContainer, xScale, {
  	    		scaleY: false, 
  	    		scaleContent: false, 
  	    		scaleFromCenter: true, 
  	    		duration: this.resizeDuration, 
  	    		queue: 'end',
  	    		afterFinish: (function() { this.originalState(); }).bind(this)
  	    	});
  	    	
  	    else 
			this.originalState(); 
    	 
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
    },
  
  
    
    //
    //  originalState()
    //  Brings back the background elements and the scrollbar (if needed)
    //
    originalState: function() {   
    	this.scrollbarContent.style.visibility = 'visible';
        new Effect.Parallel(
        	[ 
        		new Effect.Appear(this.mainMenuContainer, { duration: this.overlayDuration, from: 0.0, to: 1.0 }),
        		new Effect.Appear(this.scrollbarContent, { duration: this.overlayDuration, from: 0.0, to: 1.0 }),
        		new Effect.Appear(this.footer, { duration: this.overlayDuration, from: 0.0, to: 1.0 })
	    	], 
            {
    	        duration: this.overlayDuration,
    	        afterFinish: (function() { 	this.scrollbarTrack.style.visibility = 'visible'; }).bind(this)
    	     }
    	);

	}
}

document.observe('dom:loaded', function () { new Slideshow(); });