﻿var ImageRotator = Class.create({
    initialize: function(_id, _images, _timeout, _cookie, _startIndex) {
        this.cookie = _cookie;
        this.imgActive = $(_id + "_img1");
        this.imgPreload = $(_id + "_img2");

        this.timeout = _timeout * 1000;
        if (this.timeout < 2000)
            this.timeout = 2000;

        this.images = _images;
        this.index = _startIndex;

        if (this.images.length > 1) {
            if (++this.index >= this.images.length)
                this.index = 0;

            this.imgPreload.src = this.images[this.index];

            Event.observe(document, "dom:loaded", function() {
                setTimeout(this.showNext.bindAsEventListener(this), this.timeout);
            } .bindAsEventListener(this));
        }
    },

    setCookie: function(name, value, path, expires, domain, secure) {
        var s = name + "=" + escape(value);

        if (expires) {
            var today = new Date();
            today.setTime(today.getTime());
            expires = expires * 1000 * 60;
            var expires_date = new Date(today.getTime() + (expires));
            s = s + "; expires=" + expires_date.toGMTString();
        }

        s = s +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            ((secure) ? "; secure" : "");

        document.cookie = s;
    },

    showNext: function() {
        this.setCookie(this.cookie, this.index);

        //Show transition
        Effect.toggle(this.imgActive, "appear", { duration: 1.0 });
        Effect.toggle(this.imgPreload, "appear", { duration: 1.0 });

        setTimeout(this.prepareNext.bindAsEventListener(this), 1500);
        setTimeout(this.showNext.bindAsEventListener(this), this.timeout);

    },

    prepareNext: function() {
        var img = this.imgActive;
        this.imgActive = this.imgPreload;
        this.imgPreload = img;

        if (++this.index >= this.images.length)
            this.index = 0;
        this.imgPreload.src = this.images[this.index];
    }


});