// Home Page Carousel
CarouselOptions = Object.extend({
    changeInterval: 6000
}, window.CarouselOptions || {});

var Carousel = Class.create();

Carousel.prototype = {
    // Vars
    imageList : [],
    currentIndex : null,
    timer : null,
    isInTransition : false,
    effects : [],
    preloadImage : null,
    // Entry point
    initialize : function(images){
        this.imageList = images;
        this.isInTransition = false;
        this.currentIndex = 1;
        
        var that = this;
        setTimeout(function(){that.load();}, CarouselOptions.changeInterval || 1000 );
        //this.load();
    },
    
    load : function()
    {
        this.preloadImage = new Image();
        this.preloadImage.src = this.imageList[this.currentIndex].image;
        this.preloadImage.onload = (function()
        {
            this.update();
            this.setTimer();
        }).bind(this);
    },
    
    updateIndex : function()
    {
        if(this.currentIndex < this.imageList.length-1){
            this.currentIndex++;
        } else {
            this.currentIndex = 0;
        }
    },
    
    update : function()
    {
        if( this.isInTransition )
        {
            this.clearAllEffects();
        }
        
        $('main-image').style.opacity = 0.0;
        $('main-image').src = this.preloadImage.src;
        this.isInTransition = true;
        
        this.effects[this.effects.length] = new Effect.Appear( 'main-image', {
            from : 0.0, 
            to : 1.0, 
            duration : 1.75, 
            delay : 0.1,
            afterFinish : (function(){
                this.isInTransition = false;
            }).bind(this)
        });
    },
    
    stopTimer : function() {
        clearInterval( this.timer );
    },

    setTimer : function() {
        if( this.timer ) this.stopTimer();
        var that = this;
        this.timer = setInterval(function(){ that.updateIndex(); that.load(); }, CarouselOptions.changeInterval || 1000 );
    },
    
    clearAllEffects : function() {
        for( var i = 0; i < this.effects.length; ++i)
        {
            this.effects[i].element.writeAttribute( "style", "" );
            this.effects[i].cancel();
        }
        this.effects = [];
        this.isInTransition = false;
    }
}
