/*
 * @required prototype.js
 * @author chalermpong.chaiyawan@gmail.com
 */

var BgImageRotator = Class.create({
    initialize: function(config) {
        this.config = config || { images: $A([]), interval: 3, target: $(document.body), anchorDescription: false, anchorLinkButton: false };
        this.config.target = $(this.config.target || document.body);
        if (Object.isArray(this.config.images)) {
            this.config.images = $A(this.config.images);
        }
        else {
            this.config.images = $A([]);
        }
        if (0 > this.config.interval) {
            this.config.interval = 3;
        }
    },

    nextImage: function() {
        this.currentImageIndex = this.currentImageIndex || 0;

        if (this.currentImageIndex >= this.config.images.length) {
            this.currentImageIndex = 0;
        }

        return this.config.images[this.currentImageIndex++];
    },

    rotateNext: function() {
        var image_object = this.nextImage();
        var config = this.config;
        var anchor_description = config.anchorDescription;
        var anchor_link_button = config.anchorLinkButton;
        $(config.target).setStyle({ backgroundImage: 'url(' + image_object.image + ')' });
        if (anchor_description) {
            anchor_description.href = image_object.url || '#';
            anchor_description.target = image_object.target || '';
            anchor_description.update(image_object.description || '');
        }
        if (anchor_link_button) {
            anchor_link_button.href = image_object.url || '#';
            anchor_link_button.target = image_object.target || '';
        }
    },

    start: function() {
        if (!this.periodicalExecuter) {
            this.rotateNext();
            this.periodicalExecuter = new PeriodicalExecuter(function(pe) {
                if (!this.owner.periodicalExecuter) {
                    pe.stop();
                }
                else {
                    $(this.owner).rotateNext();
                }
            }, this.config.interval || 3);
            this.periodicalExecuter.owner = this;
        }
    },

    stop: function() {
        this.periodicalExecuter = null;
    }
});

