/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var onSlideShowEnd = null;
var onShow = function(index) {
    
}

function startSlideshow() {
    var showDuration = 1500;
    var currentIndex = 0;   
    var container = $('slideshow-images');
    var images = container.getElements('img');
    var captionElement = $('slideshow-captions');
    var captions = null;
    if(captionElement) {
        captions = captionElement.getElements('img');
    }
    var firstLoad = false;

    var interval;
    
    images.each(function(img, i) {
        if(i > 0) {
            img.fade('hide');
            if(captions) {
                captions[i].fade('hide');
            }
        }
    });
    
    var show = function() {
        if(firstLoad == false) {
            window.clearInterval(interval);
            interval = show.periodical(4500);

        }
        firstLoad = true;
        onShow(currentIndex);

        if(onSlideShowEnd && (currentIndex == images.length - 1)) {
            onSlideShowEnd();
        }
        var nextIndex = currentIndex < images.length - 1 ? currentIndex + 1 : 0;

        images[currentIndex].set('tween', {duration:2000});
        images[currentIndex].tween('opacity', 0);
        images[nextIndex].set('tween', {duration:2000});
        images[nextIndex].tween('opacity', 1);

        if(captions) {
            captions[currentIndex].set('tween', {duration:2000});
            captions[currentIndex].tween('opacity', 0);
            captions[nextIndex].set('tween', {duration:2000});
            captions[nextIndex].tween('opacity', 1);
        }
        currentIndex = nextIndex;
    };
    
    window.addEvent('load', function() {
        interval = show.periodical(showDuration);
    });
}
