/*
    Disclaimer

    While we make every effort to ensure that this code is fit for its intended
    purpose, we make no guarantees as to its functionality. CoreTrek AS will
    accept no responsibility for the loss of data or any other damage or
    financial loss caused by use of this code.


    Copyright

    This programming code is copyright of CoreTrek AS. Permission to run this
    code is given to approved users of CoreTrek's publishing system CorePublish.

    This source code may not be copied, modified or otherwise repurposed for use
    by a third party without the written permission of CoreTrek AS.

    Contact webmaster@coretrek.com for information.

    ============================================================================
    IMPORTANT! This javascript is dependent on Prototype. If Scriptaculous is
               available the tooltip will use some nice effects.
    ============================================================================

    SiteComponents slideshow.js

    Adds navigation to the slideshow tile.
*/

/*
document.observe('dom:loaded', function(event) {
    $$('div.slideshow').each(function(element) {
        new Slideshow(element);
    });
});
*/

var Slideshow = Class.create({

    initialize: function(element) {
        this.element = element;
        this.tileId = element.id.substring(5);
        
        this.current = 0;
        this.images = element.getElementsBySelector('div.slideshow-image');
                     
        this.thumbnailContainer = this.element.down().next(2);      
        this.thumbnails = this.thumbnailContainer.childElements();
        this.setActiveThumb(this.images[this.current]);
        
        this.addListeners();
    },
    
    addListeners: function() {
        // If there is any navigation divs we add listeners to the navigation
        // buttons. If there are none, the tile is set do automatically
        // toggle images at a given interval.
        /*
        this.images.each(function(element) {
            element.down().observe('click', this.nextListener.bindAsEventListener(this));
        }.bind(this));
		*/        
        this.thumbnailContainer.show();
        this.thumbnailContainer.getElementsBySelector('a').each(function(element) {
			element.observe('click', this.thumbnailListener.bindAsEventListener(this));
        }.bind(this));
        
        this.interval = this.element.getElementsBySelector('div.slideshow-interval').first().innerHTML;
        this.pe = new PeriodicalExecuter(this.periodicalExecutor.bind(this), this.interval);
        
    },
    
    /**
     * Navigate to the next image
     */
    previous: function() {
        previous = this.current;
        
        this.current--;
        if(this.current < 0) {
           this.current = this.images.size() - 1;
        }
        
        this.fadeFromTo(this.images[previous], this.images[this.current]);
    },
    
    /**
     * Navigate to the previous image
     */ 
	next: function() {
	    previous = this.current;
	    
	    this.current++;
	    if(this.current >= this.images.size()) {
	       this.current = 0;
	    }
	    
	    this.fadeFromTo(this.images[previous], this.images[this.current]);
    },
    
    /**
     * Navigate to a given element id. The element must be an image container
     * element
     */
    showElementId: function(elementId) {
        var i = 0;
        this.images.each(function(image) {
            if(image.id == elementId) {
                throw $break;
            }
            i++;
        });
        
        var previous = this.current;
        this.current = i;
        
        try {
            this.fadeFromTo(this.images[previous], this.images[this.current]);
        } catch (err) {
            // An error will occur if the loop above did not find any matches..
            // Should not happen, but with IE6 you cannot be sure 
        }
    },
    
    setActiveThumb: function(to) {
        // return if there are no thumbnails (updating on interval)
        if(typeof this.thumbnails == "undefined") {
            return;
        }
        
        var idKey = to.id.substring(to.id.lastIndexOf('-') + 1);
        
        this.thumbnails.each(function(thumb) {
            var href = thumb.down().readAttribute('href');
            var thumbIdKey = href.substring(href.lastIndexOf("#show_image_") + 12);
            
            if(thumb.hasClassName('active')) {
                thumb.removeClassName('active');
            } else if(idKey == thumbIdKey) {
                thumb.addClassName('active');
            }
        }.bind(this));
    },
    
    /**
     * Fade from a given image container to a new one. This method should only
     * be used inside this class. Use either next(), previous() or
     * showElementId() to toggle images.
     */
    fadeFromTo: function(from, to) {
        this.setActiveThumb(to);
        
        try {
        
            Effect.Appear(to, {
                duration: 0.5,
                afterUpdate: function(effect) {
	                // If this is the first frame, we hide the current
	                // image. We do this here to avoid flicker that
	                // occurs when removing image before effect fades in
	                if(effect.currentFrame == 0) {
	                    from.hide();
	                }
	            },
            
                afterFinish: function(effect) {
                    from.removeClassName('active');
                    
	                // Lets check if the image has a star rating object attached,
	                // if it does we need to reinitialize the rating elements
	                try {
	                    var ratings = to.getElementsBySelector("div.rating-container");
	                    if(ratings.size() > 0) {
	                        ratings.each(function(element) {
	                            if(typeof element.rating == 'object') {
	                                element.rating.reinitializeElements();
	                            }
	                        });
	                    }
	                } catch (err) {
	                    // Something went wrong trying to handle the starratings,
	                    // this is probably caused by the fact that there are no
	                    // starrating for this element, this is safe to ignore
	                }
	            }
	        });
	        
	    } catch (e) {
	        // No scriptaculous - hide/show without effect
	        from.hide();
	        to.show();
	        
	    }
	},
	
	// ========================================================================
    // Event listeners
	
    nextListener: function(event) {
        event.stop();
        this.pe.stop();

        this.next();
	}, 
	
    previousListener: function(event) {
        event.stop();
        
        this.previous();
	},
	    
    thumbnailListener: function(event) {

        var i = 0;
   		this.images.each(function(image) {
    	player = image.down();
			if (image.style.display == '' && player.id == 'embeddedObj' + i) {
				player.sendEvent("STOP");
			}
    	i++;
        }.bind(this));

        var href = event.findElement('a').readAttribute('href');
        var imageId = href.substring(href.lastIndexOf("#show_image") + 12);
        var imageContainerId = 'image-' + this.tileId + '-' + imageId;
        
        if (imageId > 0) {
    		event.stop();
        	this.pe.stop();
        	this.showElementId(imageContainerId);
        }
    },
    
    periodicalExecutor: function(pe) {
        this.next();
    }

});
