

/************ START gallery ********************/

var Gallery = function(){
    var config, slides, thumbs, currentIdx, autoPlayTimer;
    var firstRun = true;
    
    function showImage(idx){
        
        if (!firstRun) {
            var objFadeOut = new Fx.Tween(slides[currentIdx], {duration: 'long'});
            objFadeOut.start('opacity', 1, 0);
        } else {
            firstRun = false;
        }
                
        var objFadeIn = new Fx.Tween(slides[idx], {duration: 'long'});
        objFadeIn.start('opacity', 0, 1);
        
        currentIdx = idx;

        if (config.autoPlay === true){
            var newIdx = ((idx + 1) >= slides.length) ? 0 : (idx + 1);
            autoPlayTimer = showImage.delay(config.speed, this, newIdx);
        } else if (autoPlayTimer) {
            $clear(autoPlayTimer);
        }
    }
    
    return {
        init: function(cfg){
            config = cfg;
            
            slides = $$('div.gallery-slide');
            thumbs = $$('div.gallery ul li a');
            currentIdx = Math.floor(Math.random() * (slides.length));
                        
            slides.each(function(el, idx){
                el.setStyles({
                    position: 'absolute',
                    visibility: 'hidden',
                    opacity: 0
                });
            });
            
            $('slide-wrapper').setStyle('height', 340);
            
            showImage(currentIdx);
            
            $('gallery-thumbs').setStyle('display', 'block');
            
            thumbs.each(function(el, idx){
                el.addEvent('click', function(e){
                    e.stop();
                    var idx = parseInt(el.rel.replace('slide-', ''), 10) - 1;
                    config.autoPlay = false;
                    showImage(idx);                    
                })
            });
        }
    }
}();
