﻿function Banner(clientId, uniqueId, period) {
    this.id = clientId;
    this.uniqueId = uniqueId;
    this.period = period;
    this.timer = window.setInterval("BannersRotator.Enqueue('" + clientId + "')", period * 1000);
}

function BannersRotator() {
    this.banners = [];
    this.queue = [];
    this.timer = -1;
}

BannersRotator.prototype.Find = function (clientId) {
    var result = null;
    for (var i = 0; i < this.banners.length; i++) {
        if (this.banners[i].id == clientId) {
            result = this.banners[i];
            break;
        }
    }
    return (result);
}

BannersRotator.prototype.Add = function (clientId, uniqueId, period) {
    var found = this.Find(clientId);
    if (null == found) {
        var banner = new Banner(clientId, uniqueId, period);
        this.banners.push(banner);
    }
}

BannersRotator.prototype.IsEnqueued = function (clientId) {
    var result = false;
    for (var i = 0; i < this.queue.length; i++) {
        if (this.queue[i].id == clientId) {
            result = true;
            break;
        }
    }
    return (result);
}

BannersRotator.Enqueue = function (bannerId) {
    var banner = BannersRotator.instance.Find(bannerId);
    if (null != banner && !BannersRotator.instance.IsEnqueued(bannerId)) {
        BannersRotator.instance.queue.push(banner);
        window.setTimeout("BannersRotator.Process('send')", 1);
    }
}

BannersRotator.instance = new BannersRotator();

BannersRotator.Process = function (mode) {
    if (mode == 'send') {
        if ((BannersRotator.instance.queue.length > 0) && (BannersRotator.instance.timer == -1)) {
            BannersRotator.instance.timer = window.setTimeout("BannersRotator.Process('timeout')", 30000);
            BannersRotator.Callbackxx(BannersRotator.instance.queue[0]);
        }
    }
    else if (mode == 'cleanup') {
        BannersRotator.instance.queue.shift();
        if (BannersRotator.instance.timer != -1) {
            window.clearTimeout(BannersRotator.instance.timer);
            BannersRotator.instance.timer = -1;
        }
        window.setTimeout("BannersRotator.Process('send')", 0);
    }
    else if (mode == 'timeout') {
        BannersRotator.Process('cleanup');
    }
}

BannersRotator.Callbackxx = function (banner) {
    if (null != banner) {
        BannersRotator.ExecuteCallback(banner.uniqueId, banner.id, banner.id);
    }
}

BannersRotator.Callback = function (id) {
    var banner = BannersRotator.instance.Find(id);
    if (null != banner) {
        BannersRotator.ExecuteCallback(banner.uniqueId, banner.id, banner.id);
    }
}

BannersRotator.ReceiveServerData = function (value, controlId) {
    document.getElementById(controlId).innerHTML = value;
    window.setTimeout("BannersRotator.Process('cleanup')", 0);
}

