 /** @fileoverview  JavaScript Slideshow
 *
 * Simple slideshow using prototype and scriptaculous.
 * 
 * Usage:
 * ------
 * <script src="slideshow.js"></script>
 * <style type="text/css">
 *     #slideshow { position: relative; width: 100px; height: 100px; }
 *     #slideshow div { position: absolute; left: 0; top: 0; }
 * </style>
 * <div class="slideshow" id="slideshow">
 *     <div class="slide"><img src="slide1.jpg"></div>
 *     <div class="slide"><img src="slide2.jpg"></div>
 *     <div class="slide"><img src="slide3.jpg"></div>
 * </div>
 * <script type="text/javascript">new Slideshow('slideshow', 3000);</script>
 *
 * See also: http://blog.remvee.net/post/17
 *
 * @package    Slideshow
 * @author     R.W. van 't Veer
 * @author     Murat Purc (murat@purc.de)
 * @copyright  (c) 2006 - R.W. van 't Veer
 *
 * Changes:
 * 2006-06-20 by Murat Purc (murat@purc.de), Added handling of Elements having display none styles.
 * 2008-09-28 by Murat Purc (murat@purc.de), Refactoring of code
*/


/**
 * Class Slideshow
 */
Slideshow = Class.create({

    /**
     * Array of slide elements
     * @type  {array}
     */
    aSlides: [],

    /**
     * Actual position
     * @type  {int}
     */
    current: 0,

    /**
     * Time to wait between fades
     * @type  {int}
     */
    timeout: 4000,


    /**
     * Constructor
     * 
     * @param  {string}  Id of element which contains the images
     * @param  {int}     Time between two slides
     */
    initialize: function (slideshow, timeout) {

        var nl = $(slideshow).getElementsByTagName('div');
        for (var i = 0; i < nl.length; i++) {
            if (Element.hasClassName(nl[i], 'slide')) {
                nl[i].style.zIndex = nl.length - i;
                Element.hide(nl[i]);
                this.aSlides.push(nl[i]);
            }
        }
        this.timeout = timeout;

        Element.show(slideshow);

        Element.setStyle(this.aSlides[this.current], {display: 'inline'});
        setTimeout((function(){this._next();}).bind(this), this.timeout);
    },


    /**
     * Runs fade effect and prepares next fade
     */
    _next: function() {
        for (var i = 0; i < this.aSlides.length; i++) {
            var slide = this.aSlides[(this.current + i) % this.aSlides.length];
            slide.style.zIndex = this.aSlides.length - i;
        }

        Effect.Fade(this.aSlides[this.current], {
            afterFinish: function(effect) {
                effect.element.style.zIndex = 0;
                Element.show(effect.element);
                Element.setOpacity(effect.element, 1);
            }
        });

        this.current = (this.current + 1) % this.aSlides.length;

        // show next element
        Element.setStyle(this.aSlides[this.current], {display: 'inline'});
        setTimeout((function(){this._next();}).bind(this), this.timeout);
    }


});

