var Bekent = Bekent || {};

Bekent.Rotater = new Class({

    Implements: [Options, Events],

    options: {
        slideInterval: 5000,
        transitionDuration: 500,
        startIndex: 0,
        autoplay: true
    },
    running: false,

    initialize: function(slides,options){
        this.setOptions(options);
        this.slides = $$(slides);
        this.createFx();
        this.showSlide(this.options.startIndex);
        if(this.slides.length < 2) this.options.autoplay = false;
        if(this.options.autoplay) this.autoplay();
        return this;
    },

    createFx: function(){
        if (!this.slideFx) this.slideFx = new Fx.Elements(this.slides, {duration: this.options.transitionDuration, onStart: function(){ this.running = true; }.bind(this), onComplete: function(){ this.running = false; }.bind(this)});
        this.slides.each(function(slide){
            slide.setStyle('opacity',0);
        });
    },

    showSlide: function(slideIndex){
        var action = {};
        this.slides.each(function(slide, index){
            if(index == slideIndex && index != this.currentSlide){ //show
                action[index.toString()] = {
                    opacity: 1
                };
            } else {
                action[index.toString()] = {
                    opacity:0
                };
            }
        }, this);
        this.currentSlide = slideIndex;
        this.slideFx.start(action);
        return this;
    },

    autoplay: function(){
        this.slideshowInt = this.rotate.periodical(this.options.slideInterval, this);
        return this;
    },

    rotate: function(){
        var current = this.currentSlide;
        var next = (current+1 >= this.slides.length) ? 0 : current+1;
        this.showSlide(next);
        return this;
    },

    stop: function(){
        $clear(this.slideshowInt);
        return this;
    }

});
