if (!document.Devnet) Devnet = {};

Devnet.BannerRotator = new Class({

    options: {
        delay: 20000, // 20 seconds
        duration: 1000, // 1 second
        initialBanner: 0 // Index of initial banner to display
    },

    initialize: function(el, banners, options) {
        this.element = $(el);
        options = options || [];
        this.setOptions(options);

        this.current = this.options.initialBanner;
		this.element.innerHTML = "Loading...";
		this.banners = new Asset.images(banners, { onComplete: this.banners_onComplete.bind(this) });
    },

    setupIndex: function() {
        var idx = Cookie.read(this.element.id);
        if (idx) this.current = parseInt(idx);
        if (this.current >= this.banners.length) this.current = 0;
        Cookie.write(this.element.id, (this.current+1));
    },

    updateIndex: function() {
        this.current ++;
        if (this.current >= this.banners.length) this.current = 0;
        Cookie.write(this.element.id, (this.current+1));
    },

    banners_onComplete: function() {
        this.setupIndex();
        this.element.innerHTML = "";
        this.banners.each(function(banner) {
            banner.setStyle('opacity', 0);
            banner.setStyle('position', 'absolute');
            banner.injectInside(this.element);
        }, this);
        this.banners[this.current].setStyle('opacity', '0');
        new Fx.Morph(this.banners[this.current], {duration:this.options.duration}).start({
            opacity: [0, 1]
        });
        this.swap_banner.periodical(this.options.delay, this);
    },

    swap_banner: function() {
        new Fx.Morph(this.banners[this.current], {duration:this.options.duration}).start({
            opacity: [1, 0]
        });
        this.updateIndex();
        if (this.current >= this.banners.length) this.current = 0;
        this.banners[this.current].setStyle('opacity', '0');
        new Fx.Morph(this.banners[this.current], {duration:this.options.duration}).start({
            opacity: [0, 1]
        });
    }

});
Devnet.BannerRotator.implement(new Options);
