var AdRoller = {
    
    _instance : undefined,
    
    _activePanelIndex : undefined,
    _panelCount : undefined,
    _intervalId : undefined,
    
    instance : function() {
        if (!AdRoller._instance) {
            AdRoller.init();
        }
        return AdRoller._instance;
    },
    
    init : function() {
        // set the instance for use in the timeout
        AdRoller._instance = this;
    
        // dynamically construct the nav based on the number of panels defined
        $('#ad-panel-canvas #ad-panels').children().each(function(index) {
            $('<li class="ad-bullet inactive" id="ad-bullet' + index + '"></li>').appendTo('#ad-panel-canvas #ad-nav ul')
        });
        $('#ad-panel-canvas #ad-nav ul li').click(function() {
            var navIndex = $('#ad-panel-canvas #ad-nav ul li').index(document.getElementById($(this).attr('id')));
            AdRoller.activatePanel(navIndex, true);
        });
        
        // randomly select the initial panel and activate it
        this._panelCount = $('#ad-panel-canvas #ad-panels').children().size();        
        this.activatePanel(Math.floor(Math.random() * this._panelCount));
        
        // activate the ad roller
        this._intervalId = setInterval("AdRoller.instance().activateNextPanel()", 8000);
        
        return;
    },
    
    activatePanel : function(index, stopAdRoller) {
        // set the new active panel
        this._activePanelIndex = index;
        // deactivate the ad roller if need be
        if (stopAdRoller) {
            clearInterval(this._intervalId);
        }
        // show the ad block
        $('#ad-panel-canvas #ad-panels .panel:eq(' + index + ')').css('display', 'block');
        $('#ad-panel-canvas #ad-panels .panel:eq(' + index + ')').siblings().css('display', 'none');
        // activate the associated nav element
        $('#ad-panel-canvas #ad-nav ul li:eq(' + index + ')').addClass('active');
        $('#ad-panel-canvas #ad-nav ul li:eq(' + index + ')').removeClass('inactive');
        $('#ad-panel-canvas #ad-nav ul li:eq(' + index + ')').siblings().addClass('inactive');
        $('#ad-panel-canvas #ad-nav ul li:eq(' + index + ')').siblings().removeClass('active');       
        return;
    },
    
    activateNextPanel : function() {
        if (this._panelCount > this._activePanelIndex+1) {
            this.activatePanel(this._activePanelIndex+1, false);
        } else {
            this.activatePanel(0, false);        
        }
        return;
    },

};