﻿function rotator(myvarname, datasource, elem1id, elem2id, initfunc, delay, crossfadedelay) {
    if (crossfadedelay === undefined) {
        crossfadedelay = 20;
    }
    if (delay === undefined) {
        delay = 5000;
    }
    this.datasource = datasource;
    this.initfunc = initfunc;
    this.cfdelay = crossfadedelay;
    this.fadepos = -1;
    this.idx = 0;
    this.cfframes = 30;
    this.delay = delay;

    this.elem1 = document.getElementById(elem1id);
    this.elem2 = document.getElementById(elem2id);

    this.rotate = function() {
        if (this.fadepos == -1) {
            //setup
            this.fadepos = 0;
            var newidx = this.idx;
            while (newidx == this.idx) {
                newidx = Math.floor(Math.random() * this.datasource.length);
                if (newidx == this.datasource.length) {
                    newidx = 0;
                }
            }

            this.idx = newidx;

            this.initfunc(this.elem2, datasource[this.idx]);

            setTimeout(myvarname + '.rotate()', this.cfdelay);

        }
        else {
            if (this.fadepos >= 100) {
                //finish
                this.fadepos = -1;
                this.elem2.style.opacity = 0;
                this.elem2.style.filter = 'alpha(opacity=0)';

                this.elem1.style.opacity = 1;
                this.elem1.style.filter = 'alpha(opacity=100)';

                this.elem1.innerHTML = this.elem2.innerHTML;

                setTimeout(myvarname + '.rotate()', this.delay);
            }
            else {
                this.fadepos += (100 / this.cfframes);

                this.elem2.style.opacity = this.fadepos / 100;
                this.elem2.style.filter = 'alpha(opacity=' + this.fadepos + ')';

                this.elem1.style.opacity = (100 - this.fadepos) / 100;
                this.elem1.style.filter = 'alpha(opacity=' + (100 - this.fadepos) + ')';
                setTimeout(myvarname + '.rotate()', this.cfdelay);

            }
        }

    }
    setTimeout(myvarname + '.rotate()', this.delay);
}
        
