Array.prototype.random = function(){
   this.sort(function(){return (Math.random()*10) > 5});
}

var Widget = {};
Widget.Fader = Class.create({
    init: function(imgId, imageList, options) {
        this.imgTag = $(imgId);
        this.imgParent = this.imgTag.ancestors()[0];
        this.options = Object.extend({
            timer: 5,
            fadetime: 2,
            looping: true,
            order: "none",
            autoStart: true,
            startImage: null
            
        }, options || {});
        this.imageList = imageList;
        if (this.options.order == "random") {
            // sort list by random
            this.imageList.random();
        }
        if (this.options.startImage != null) {
           this.imageList[this.imageList.length] = this.options.startImage;
        }
        
        // create img tags
        this.imageTags = [];
        for (var i = 0; i < this.imageList.length; i++) {
           this.imageTags[i] = new Element("img");
           this.imageTags[i].src = this.imageList[i];
           Element.setOpacity(this.imageTags[i], 0);
        }
        if(this.options.autoStart) {
            setTimeout(this.fade1.bind(this), this.options.timer * 1000);
        }
        this.counter = 0;
    },
    
    fade1: function() {
        // create new img tag position absolute over the other
        // fade out
        this.imgParent.setStyle({backgroundImage: "url('" + this.imageList[this.counter] + "')"});
        new Effect.Opacity(this.imgTag, { from: 1.0, to: 0, duration: this.options.fadetime });
        this.updateCounter();
        //timeout
        setTimeout(this.fade2.bind(this), this.options.timer * 1000);
    },
    
    fade2: function() {
        // create new img tag position absolute over the other
        // fade out
        Element.setOpacity(this.imageTags[this.counter], 0);
        this.imgParent.replaceChild(this.imageTags[this.counter], this.imgTag);
        new Effect.Opacity(this.imageTags[this.counter], { from: 0, to: 1.0, duration: this.options.fadetime });
        this.imgTag = this.imageTags[this.counter];
        this.updateCounter();
        //timeout 
        setTimeout(this.fade1.bind(this), this.options.timer * 1000);
    },

    updateCounter: function() {
        if (this.counter + 1 >= this.imageList.length) {
            this.counter = 0;
        } else {
            this.counter++;
        }
    }
    
});
