﻿var bannerChangeTimeout = 6000;

// Text banner rotation service
var BannerService = function (elementId, timeout, serviceUrl, bannerIds) {
    this.element = $(elementId);
    this.timeout = timeout;
    this.serviceUrl = serviceUrl;
    this.bannerIds = bannerIds;
    this.contentCache = [];
    this.currentId = 0;


    // Start banner rotation
    this.start = function () {
        var self = this;
        function rotate() {
            self.getCurrentBanner(function (content) {
                $(self.element).html(content);
                self.nextBanner();
            });
            setTimeout(rotate, self.timeout);
        }
        if (self.bannerIds.length > 0)
            rotate();
    };


    // Get current banner content from cache or via service
    this.getCurrentBanner = function (callback) {
        var self = this;
        var cachedContent = this.contentCache[this.currentId];
        if (cachedContent) {
            callback(cachedContent);
            return;
        }

        $.ajax({
            type: 'GET',
            url: self.serviceUrl + "?id=" + self.bannerIds[self.currentId],
            success: function (data) {
                if (data) {
                    self.contentCache[self.currentId] = data;
                    if (callback)
                        callback(data);
                }
            }
        });
    };

    // Switch internal state to next banner
    this.nextBanner = function () {
        if (this.bannerIds.length > 0)
            this.currentId = (this.currentId + 1) % this.bannerIds.length;
    };
};


$(document).ready(function () {
    var bs = new BannerService('#banner-div', bannerChangeTimeout, "/Banner.ashx", bottomBannerIds);
    bs.start();
});

