//
// javascript functions and classes to support pretty package refactor
//

var thePopCapGame = null;
var theAdSpot = null;

//
//     development tools
//

var prettyLog =
{
    isConsole: 0,
    init: function () { if (typeof (console) !== "undefined") { this.isConsole = 1; } },
    log: function (message, debugLevel) { if (debugLevel === null) {  debugLevel = 1; } if ((packageSettings.isDebug >= debugLevel) && this.isConsole) { console.log("[" + this.time() + "](DEBUG_LEVEL_" + debugLevel + ") " + message);  }},
    trace: function (message) {if (this.isConsole) { console.log(message); console.trace(); }},
    time: function () { var Stamp=new Date(); var year=Stamp.getYear(); if(year<2000){year=1900+year;}var ts=(Stamp.getMonth()+1)+"/"+Stamp.getDate()+"/"+year;var Hours=Stamp.getHours();var Mins=Stamp.getMinutes();var Time;if(Hours>=12){Time=" PM";}else{Time=" AM";}if(Hours>12){Hours-=12;}if(Hours===0){Hours=12;}if(Mins<10){Mins="0"+Mins;}ts+=" "+Hours+":"+Mins+Time;return ts;}
};

//
// TRACKING CLASS
//

var trackingGame = 
{   
    sessionStart     : 0,
    sessionPlays     : 0,
    userId           : 0,
    adImpressions    : { preRoll: 0, midRoll: 0, postRoll: 0 },
    secondsPlayed    : 0,
    secondsAds       : 0,
    highestScore     : 0,
    highestLevel     : 0,
    playState        : "idle",
    stateTime        : 0,
    
    initTracking: function ()
    {
        var currentDate = new Date();
        var currentTime = currentDate.getTime();

        this.stateTime = currentTime; 
        this.sessionStart = currentTime;
        this.userId = $.cookie("user_id");
    
        popCapAdSpots.getWebGamesCookie(packageSettings.cookieDomain, packageSettings.cookieName);
    
        if ((packageSettings.isDebug > 0) && (packageSettings.isTracking === true))
        {
           this.initDebugFrame();
        }
    
        setInterval("trackingGame.updateStateSeconds()", 100);
    },
    
    initDebugFrame: function ()
    {
        $(packageSettings.debugLayer).css("visibility", 'visible');
        $(packageSettings.debugLayer).css("display", 'block');

        setInterval("trackingGame.writeTrackingFrame()", 1000); 
    },
    
    updateStateSeconds: function()
    {
        var currentDate = new Date();
        var currentTime = currentDate.getTime();
    
        if (this.playState == "play")
        {
           this.addPlaySeconds(currentTime - this.stateTime);
        }
        else if (this.playState == "ad")
        {
           this.addAdSeconds(currentTime - this.stateTime);
        }
        
        this.stateTime = currentTime;
    },
    
    updateState: function (state)
    {
        this.playState = state;
        prettyLog.log("trackingGame.updateState: updated state to " + state, 3);    
    },
        
    addPlay: function(numPlays) 
    {
        this.sessionPlays += numPlays; 
    },
    
    logIn: function(userId) 
    {
        this.userId = userId;
    },
    
    addAdImpression: function(type, numPlays) 
    {
        if (type == "postroll")
        {
            this.adImpressions.postRoll += numPlays;
        }
        else if (type == "midroll")
        {
            this.adImpressions.midRoll += numPlays;
        }
        else
        {
            this.adImpressions.preRoll += numPlays;
        }   
    },
    
    addPlaySeconds: function(numSeconds) 
    {
        this.secondsPlayed += numSeconds;
    },
    
    addAdSeconds: function(numSeconds) 
    {
        this.secondsAds += numSeconds;      
    },
    
    updateLevel: function(level)
    {
        if (parseInt(level, 10) > parseInt(this.highestLevel, 10))
        {
            this.highestLevel = parseInt(level, 10);
        }
    },
    
    updateScore: function(score)
    {
        if (parseInt(score, 10) > parseInt(this.highestScore, 10))
        {       
            this.highestScore = parseInt(score, 10);
        }       
    },
    
    getSecondsPlayed: function()
    {
        var result = (this.secondsPlayed / 1000);
        return (Math.round (result*100) / 100);
    },
    
    getSecondsIdle: function()
    {
        var result = (this.getSecondsLoaded() - this.getSecondsAds() - this.getSecondsPlayed());
        return (Math.round (result*100) / 100);
    },
    
    getSecondsAds: function()
    {
        var result = (this.secondsAds / 1000);
        return (Math.round (result*100) / 100);
    },
    
    getSecondsLoaded: function()
    {
        var currentDate = new Date();
        
        if (this.sessionStart === 0)
        {
           return 0;
        }
        var result = ((currentDate.getTime() - this.sessionStart) / 1000);  
        return (Math.round (result*100) / 100);
    },

    reportOmniture: function() 
    {
	    if ((this.getSecondsPlayed() > 21600) || (this.getSecondsPlayed() < 0) || (this.sessionPlays > 20) || (this.sessionPlays < 0))
	    {
		   return;
		}
	
        s.channel = "Game Play";
        s.pageName = s.channel + " > " + packageSettings.gameName;
        s.prop2 = packageSettings.gameLCCode;
        s.prop6 = packageSettings.gameLCLang + " > " + s.pageName;
        s.eVar18 = this.userId; 
        s.eVar17 = s.channel;
        s.eVar28 = packageSettings.gameLCLang;
 
        s.eVar21 = packageSettings.gameName + " : " + this.highestScore;
        s.eVar45 = packageSettings.gameName + " : " + this.highestLevel;

        s.events="event36,event45,event46,event47,event44,event39";
        s.products = ";" + packageSettings.gameCode + ";;;event36=" + this.sessionPlays + "|" +
                   "event45=" + this.adImpressions.preRoll + "|" +
                   "event46=" + this.adImpressions.midRoll + "|" +
                   "event47=" + this.adImpressions.postRoll + "|" +
                   "event44=" + this.getSecondsPlayed() + "|" +
                   "event39=" + this.getSecondsAds();

        // needed
        s.prop10 = s.visitorID;

        ///----
        s.server = location.host;
        
        // call omniture
        s.t();
    },
    
    writeTrackingFrame: function() 
    {
        var html = "";  
        if (packageSettings.isDebug <= 0)
        {
             return;
        }

        html += "<pre>&nbsp;<p><b>TRACKING:</b><p>";
        html += '  gameinfo  : ' + packageSettings.gameName + 
                                " (lccode: " + packageSettings.gameLCCode +
                                ", lctext: " + packageSettings.gameLCText + 
                                ", territory: " + packageSettings.gameTerritory + 
                                ", platform: " + packageSettings.gamePlatform + 
                                ", gamecode: " + packageSettings.gameCode + 
                                ") <br>";
        html += '  omniture  : ' + packageSettings.isOmniture + "<br>";
        html += '  partner   : ' + packageSettings.partnerName + "<br>";
        html += '  start     : ' + this.sessionStart + "<br>";
        html += '  pagetime  : ' + this.getSecondsLoaded() + "<br>";
        html += '  idletime  : ' + this.getSecondsIdle() + "<br>";
        html += '  adtime    : ' + this.getSecondsAds() + "<br>";
        html += '  playtime  : ' + this.getSecondsPlayed() + "<br>";
        html += '  plays     : ' + this.sessionPlays + "<br>";
        html += '  popid     : ' + this.userId + "<br>";
        html += '  ads       : ' + this.adImpressions.preRoll + " (preroll), " + this.adImpressions.midRoll + " (midroll), " + this.adImpressions.postRoll + " (postroll) <br>";
        html += '  score     : ' + this.highestScore + "<br>";
        html += '  highlevel : ' + this.highestLevel + "<br>";

        $(packageSettings.debugLayer).html(html);
    }
};

//
// POPCAP GAME BASE CLASS
//

function popCapGame(gameName, id, gameWidth, gameHeight, gameLayer)
{
    popCapGame.prototype.displayName = gameName;
    popCapGame.prototype.embedObject = id;
    popCapGame.prototype.gameWidth = gameWidth;
    popCapGame.prototype.gameHeight = gameHeight;
    
    popCapGame.prototype.paramNames = [];
    popCapGame.prototype.params = [];  
    popCapGame.prototype.hosts = [];
    popCapGame.prototype.signatures = [];
    
    popCapGame.prototype.partnerName = '';
    popCapGame.prototype.basePath = '';
    popCapGame.prototype.upsellUrl = '';
    popCapGame.prototype.enableUpsell = false;
    popCapGame.prototype.gameLayer = gameLayer;
    
    popCapGame.prototype.LoadBroadcast = 'LoadBroadcast';
    popCapGame.prototype.SessionReady = 'SessionReady';
    popCapGame.prototype.GameReady = 'GameReady';
    popCapGame.prototype.ScoreBroadcast = 'ScoreBroadcast';
    popCapGame.prototype.GameBreak = 'GameBreak';
    popCapGame.prototype.ScoreSubmit = 'ScoreSubmit';
    popCapGame.prototype.GameEnd = 'GameEnd';
    popCapGame.prototype.CustomEvent = 'CustomEvent';
    
    popCapGame.prototype.levelCount = 0;
}

popCapGame.prototype.pathConcat = function(first,last)
{
    if (first == '')
    { 
        return last;
    }
    if (first.search(/\/$/) == -1) { return first + '/' + last; }
    return first + last;
};

popCapGame.prototype.applyBasePath = function()
{
};

popCapGame.prototype.write = function()
{
};

popCapGame.prototype.getParams = function()
{
};

popCapGame.prototype.sendNotification = function(method,params)
{
};

popCapGame.prototype.receiveNotification = function(method,params)
{
    prettyLog.log("popCapGame.receiveNotification: received " + method, 3);
    if (method == this.LoadBroadcast) { LoadBroadcast(params); }
    else if (method == this.SessionReady) { SessionReady(params); }
    else if (method == this.GameReady) { GameReady(params); }
    else if (method == this.ScoreBroadcast) { ScoreBroadcast(params); }
    else if (method == this.GameBreak) { GameBreak(params); }
    else if (method == this.ScoreSubmit) { ScoreSubmit(params); }
    else if (method == this.GameEnd) { GameEnd(params); }
    else if (method == this.CustomEvent) { CustomEvent(params); }
    else {} 
};

popCapGame.prototype.SessionStart = function()
{
    prettyLog.log("popCapGame.SessionStart: received", 3);
    this.sendNotification('SessionStart','');
    trackingGame.updateState("idle");   
};

popCapGame.prototype.GameStart = function()
{
    prettyLog.log("popCapGame.GameStart: received", 3);
    this.sendNotification('GameStart','');
    trackingGame.addPlay(1);
    trackingGame.updateState("play");   
};

popCapGame.prototype.GameMenu = function()
{
    prettyLog.log("popCapGame.GameMenu: received", 3);
    this.sendNotification('GameMenu','');
    trackingGame.updateState("idle");   
};

popCapGame.prototype.GameContinue = function()
{
    prettyLog.log("popCapGame.GameContinue: received", 3);
    this.sendNotification('GameContinue','');
    trackingGame.updateState("play");       
};

popCapGame.prototype.CustomReturn = function(params)
{
    prettyLog.log("popCapGame.CustomReturn: received", 3);
    this.sendNotification('CustomReturn',params);
};

popCapGame.prototype.Mute = function(isMute)
{
    prettyLog.log("popCapGame.Mute: received " + isMute, 3);
    this.sendNotification(isMute ? 'MuteOn' : 'MuteOff','');
};

popCapGame.prototype.Pause = function(isPause)
{
    prettyLog.log("popCapGame.Pause: received " + isPause, 3);
    this.sendNotification(isPause ? 'PauseOn' : 'PauseOff','');
    trackingGame.updateState("idle");       
};

popCapGame.prototype.OnLoadBroadcast = function(params)
{
    var loaded = $(params).find("percentcomplete").text();
    prettyLog.log("popCapGame.OnLoadBroadcast: received " + loaded + params, 3);
    
};

popCapGame.prototype.OnSessionReady = function(params)
{
    prettyLog.log("popCapGame.OnSessionReady: received", 3);
    theAdSpot.isOwnerLoaded = true;
    this.SessionStart();
};

popCapGame.prototype.OnGameReady = function(params)
{
    prettyLog.log("popCapGame.OnGameReady: received", 3);
    trackingGame.addPlay(1);        
    trackingGame.updateState("play");   
    this.GameStart();
};

popCapGame.prototype.OnScoreBroadcast = function(params)
{    
    var score = $(params).find("score").text();
    trackingGame.updateScore(score);
    prettyLog.log("popCapGame.OnScoreBroadcast: received " + score + params, 3);
};

popCapGame.prototype.OnGameBreak = function(params)
{
    var level = $(params).find("breakpoint").text();
    trackingGame.updateLevel(level);
    trackingGame.updateState("ad"); 

    prettyLog.log("popCapGame.OnGameBreak: received", 3);
    if (params == 'adCompleted')
    {
        this.GameContinue();
        trackingGame.updateState("play");   
    }
    else
    {
        theAdSpot.display('GameBreak');
    }
};

popCapGame.prototype.OnScoreSubmit = function(params)
{
    prettyLog.log("popCapGame.OnScoreSubmit: received", 3);
};

popCapGame.prototype.OnGameEnd = function(params)
{
    prettyLog.log("popCapGame.OnGameEnd: received " + params, 3);

    if (params == 'adCompleted')
    {
        this.GameMenu();
    }
    else
    {
        theAdSpot.display('GameEnd');
    }
};

popCapGame.prototype.OnCustomEvent = function(params)
{
    prettyLog.log("popCapGame.OnCustomEvent: received " + params, 3);
    
    if (this.enableUpsell) { parent.window.location.replace(this.upsellUrl); }
    this.CustomReturn(params);
};

//
//     MSN API FUNCTIONS (Registered in ActionScript 3 Games)
//

LoadBroadcast = function(params)
{
    prettyLog.log("MSN API: LoadBroadcast", 1);
    thePopCapGame.OnLoadBroadcast(params);
};

SessionReady = function(params)
{
    prettyLog.log("MSN API: SessionReady", 1);
    thePopCapGame.OnSessionReady(params);
};

GameReady = function(params)
{
    prettyLog.log("MSN API: GameReady", 1);
    thePopCapGame.OnGameReady(params);
};

ScoreBroadcast = function(params)
{
    prettyLog.log("MSN API: ScoreBroadcast", 1);
    thePopCapGame.OnScoreBroadcast(params);
};

GameBreak = function(params)
{
    prettyLog.log("MSN API: GameBreak", 1);
    thePopCapGame.OnGameBreak(params);
};

ScoreSubmit = function(params)
{
    prettyLog.log("MSN API: ScoreSubmit", 1);
    thePopCapGame.OnScoreSubmit(params);
};

GameEnd = function(params)
{
    prettyLog.log("MSN API: Gameend", 1);
    thePopCapGame.OnGameEnd(params);
};

CustomEvent = function(params)
{
    prettyLog.log("MSN API: CustomEvent", 1);
    thePopCapGame.OnCustomEvent(params);
};

isProxyReady = function()
{
    prettyLog.log("MSN API: isProxyReady(), tell that we are proxy ready", 1);
    return true;
};

setSWFIsReady = function()
{
    prettyLog.log("MSN API: setSWFIsReady(), tell that we are SWF ready", 1);
    return true;
};

//
//     AD SUPPORT
//

$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return results[1] || 0;}


function adSpot(id, theGame)
{
    adSpot.prototype.adLayer = id;
	adSpot.prototype.splashLayer = "";
    adSpot.prototype.owner = theGame;
    
    adSpot.prototype.adWidth = 0;
    adSpot.prototype.adHeight = 0;
    adSpot.prototype.adlayerWidth = 0;
    adSpot.prototype.adlayerHeight = 0;
    adSpot.prototype.gameWidth = 0;
    adSpot.prototype.gameHeight = 0;

	adSpot.prototype.isVariableAd = false;
    adSpot.prototype.countdown = 0;
    adSpot.prototype.lastShown = 0;
    adSpot.prototype.duration = 5;
    adSpot.prototype.adObject = null;
    adSpot.prototype.globalTimer = null;
    adSpot.prototype.ownerBgcolor = 'white';
    adSpot.prototype.showPreroll = false;
    adSpot.prototype.showMidroll = false;
    adSpot.prototype.showPostroll = false;
    adSpot.prototype.countdown_display = null;
    adSpot.prototype.breakEvent = '';
    adSpot.prototype.isOwnerLoaded = false;
    adSpot.prototype.wait = 60;



    adSpot.prototype.prerollSrc = '';   
    adSpot.prototype.midrollSrc = '';
    adSpot.prototype.postrollSrc = '';

    prettyLog.log("adSpot_constructor: called with layer id of '" + id + "'", 3);
}

adSpot.prototype.write = function()
{   
    var html = "";
    this.setDimensions();

	html += '<div id="adlayer" style="margin: 0; padding: 0; border: 0; outline: 0; font-weight: inherit; font-style: inherit; font-size: 100%; font-family: arial; width: 540px;height: 405px;background: url(/images/web_game/game_window_bkgd.png) no-repeat; margin: 0;padding: 0;">' +
			'<div id="ad_timer" style = "background-color: #000; width: 540px; height: 30px;">' +
			'<div style="color: #fff; font-size: 14px; font-weight: normal; line-height: 30px; padding: 0; margin: 0 0 0 15px;"><span id="countdown_game">Advertisement: Your game</span> will <span id="ad_action">play</span> in&nbsp;<span id="countdown_number">a few</span>&nbsp;seconds</p>' +
			'</div></div>';
	html += '<div id="mid_roll_ad_holder">' +
			'   <div id="mid_roll_ad">' +
			'	<IFRAME id="spot" name="spot" allowtransparency="true" FRAMEBORDER=0 MARGINWIDTH=0 MARGINHEIGHT=0 SCROLLING=NO WIDTH="' + this.adWidth + '" HEIGHT="' +this.adHeight + '"></IFRAME>' +
			'   </div>' +
			'</div>';
	html += '<div id="download_upsell_bottom">' +
			'	<IFRAME id="upsell_bar" name="upsell_bar" allowtransparency="true" FRAMEBORDER=0 MARGINWIDTH=0 MARGINHEIGHT=0 SCROLLING=NO WIDTH="440" HEIGHT="75"></IFRAME>' +
			'</div>';
    html += '</div><div id="splashlayer" style="margin: 0; padding: 0; border: 0; outline: 0; font-weight: inherit; font-style: inherit; font-size: 100%; font-family: arial; width:  540px;height: 405px;background: url(/images/web_game/game_window_bkgd.png) no-repeat; margin: 0;padding: 0;">' +
			'</div>';
  //  alert(html);

/*   
    // OLD "NEW" WEB GAME HTML/DIV
    html += '<div id="adlayer" style="adlayer">';
    html += ' <table style="width:' + this.adlayerWidth + '; height:' + this.adlayerHeight + ';">';
    html += '  <tr>';
    html += '    <td style="text-align:center; vertical-align:middle;">';
    html += '      <div id="countdown_message" style= "margin: 0 0 10px 0; text-align: center; color: #cccccc; font-family: arial, sans-serif; font-size: 12px;" oncontextmenu="return false">';
    html += '        <span id="countdown_game">Your game</span> will <span id="ad_action">play</span> in&nbsp;<span id="countdown_number">a few</span>&nbsp;seconds';
    html += '      </div>';
    html += '      <table style="margin-left:auto; margin-right:auto; width: 315px; height: 250px;">';
    html += '        <tr>';
    html += '          <td oncontextmenu="return false">';
    html += '            <img width="15" height="91" style="margin-top:150px;" src="http://images.popcap.com/www/images/web/advertisement.jpg" alt="Advertisement" title="Advertisement">';
    html += '          </td>';
    html += '          <td oncontextmenu="return false">';
    html += '           <IFRAME id="spot" name="spot" allowtransparency="true" FRAMEBORDER=0 MARGINWIDTH=0 MARGINHEIGHT=0 SCROLLING=NO WIDTH="' + this.adWidth + '" HEIGHT="' +this.adHeight + '"</IFRAME>';
    html += '          </td>';
    html += '        </tr>';
    html += '      </table>';
    html += '    </td>';
    html += '   </tr>';
    html += ' </table>';
    html += '</div>';   
*/    
    document.write(html);
 
	$(this.adLayer).css("margin", "0px 0 0 0px");
    $(this.adLayer).css("z-index", "1");
    $(this.adLayer).css("visibility", "visible");
    $(this.adLayer).css("display", "block");
    $(this.adLayer).css("width", this.adlayerWidth);
    $(this.adLayer).css("height", this.adlayerHeight);


    prettyLog.log("adSpot.write: wrote out ad spot source with jquery", 3);
};

adSpot.prototype.getUpsellBarURL = function()
{
    var adTarget = "";
    var adURL = "";

    if (packageSettings.isOpenAds === true)
    {
        adTarget = popCapAdSpots.getAdTarget(packageSettings.cookieDomain, packageSettings.cookieName, packageSettings.gameCode);
    }

    adURL = this.upsellBarSrc;
    
    prettyLog.log("adSpot.getUpsellBarURL: URL " + adURL + adTarget, 3);
    return adURL + adTarget;
	
};

adSpot.prototype.getAdURL = function(type)
{
    var adTarget = "";
    var adURL = "";
    
    if (packageSettings.isOpenAds === true)
    {
        adTarget = popCapAdSpots.getAdTarget(packageSettings.cookieDomain, packageSettings.cookieName, packageSettings.gameCode);
    }
    switch (type)
    {
        case "preroll":
            adURL = this.prerollSrc;
            break;
        case "midroll":
            adURL = this.midrollSrc;
            break;
        case "postroll":
            adURL = this.postrollSrc;
            break;
        default:    
            adURL = this.prerollSrc;
            break;
    } 
    
    prettyLog.log("adSpot.getAdURL: URL " + adURL + adTarget + " on " + type, 3);
    return adURL + adTarget;
};

adSpot.prototype.setDimensions = function()
{   
    var isTaller = (this.gameHeight !== null && this.height > this.owner.gameHeight);
    var isWider = (this.gameWidth !== null && this.width > this.owner.gameWidth);
        
    if (!isTaller){ this.gameHeight = this.owner.gameHeight; }
    if (!isWider){ this.gameWidth = this.owner.gameWidth; }
    
    if (!isTaller && !isWider)
    {
        prettyLog.log("adSpot.setDimenstions: we didn't need to setDimensions because they look good", 3);
        return;
    }
    
    if ($(this.adLayer))
    {
        var padWidth = this.width/2 - this.owner.gameWidth/2;
        var padHeight = this.height/2 - this.owner.gameHeight/2;        
        if (!$.browser.msie)
        {
            $(this.adLayer).css("width", this.gameWidth);
            $(this.adLayer).css("height", this.gameHeight);
        }
        else
        {
            $(this.adLayer).css("width", this.gameWidth - padWidth);
            $(this.adLayer).css("height", this.gameHeight - padWidth);
        }
        $(this.adLayer).css("backgroundColor", this.ownerBgcolor);
        $(this.adLayer).css("paddingLeft", padWidth);
        $(this.adLayer).css("paddingTop", padHeight);
    }

    prettyLog.log("adSpot.setDimenstions: set height to " + $(this.adLayer).height() + " and width " +  $(this.adLayer).width(), 3);
};

adSpot.prototype.timer = function()
{

	if (this.countdown_display === null)
    {
        this.countdown_display = $("#countdown_number");
    }
	
    if ((this.countdown > 0) && (this.duration > ( this.countdown + 5) ))
    {
        this.countdown_display.html(this.countdown);
    }
    else
    {
	    this.countdown_display.html("a few");
	}

    this.countdown--;

    if (((this.countdown <= 0) && (this.isVariableAd == false)) || (this.countdown <= -5))
    {
	   this.countdown_display.html("a few");
       this.endDisplay();
       prettyLog.log("adSpot.timer: done with the timer, calling adSpot.endDisplay", 5);
    }
    else 
    {
       this.globalTimer = setTimeout('theAdSpot.timer()',1000);
       prettyLog.log("adSpot.timer: still counting, time is currently " + this.countdown, 5);
    }
};

adSpot.prototype.resumeGame = function()
{
    trackingGame.updateState("play");
    if (this.breakEvent == 'GameBreak')
    {
        this.owner.OnGameBreak('adCompleted');
        prettyLog.log("adSpot.resumeGame: call OnGameBreak in thePopCapGame('adCompleted')", 1);
    }
    else
    {
        this.owner.OnGameEnd('adCompleted');
        prettyLog.log("adSpot.resumeGame: call OnGameEnd in thePopCapGame('adCompleted')", 1);
    }
};

adSpot.prototype.display = function(event)
{
    this.breakEvent = event;
    
    if ((this.breakEvent == 'GameBreak' && this.showMidroll) ||
        (this.breakEvent == 'GameEnd' && this.showPostroll))
    {
       var currentDate = new Date();
        var currentTime = currentDate.getTime();
        var interval = currentTime - this.lastShown;
       
        trackingGame.updateState("ad");

        if (this.breakEvent == 'GameBreak') 
        {
	       $("#ad_action").html("resume");
           prettyLog.log("adSpot.display: we have a GameBreak event - MIDROLL", 1);
        }
        else if (this.breakEvent == 'GameEnd')
        {
	       $("#ad_action").html("resume");
           prettyLog.log("adSpot.display: we have a GameEnd event - POSTROLL", 1);
        }
        
        if (interval > this.wait*1000)
        {
            if (this.breakEvent == 'GameEnd')
            {
                trackingGame.addAdImpression("postroll", 1);
                this.setDuration(packageSettings.adDuration, false, false);

                $('#spot').attr('src', this.getAdURL("postroll"));
                $('#upsell_bar').attr('src', this.getUpsellBarURL());
            }
            else
            {
                trackingGame.addAdImpression("midroll", 1);
                this.setDuration(packageSettings.adDuration, false, false);
                $('#spot').attr('src', this.getAdURL("midroll"));
                if (packageSettings.cheerios !== undefined && packageSettings.cheerios != false)
       			{
	                 parent.advanceCheerios();
				}
                $('#upsell_bar').attr('src', this.getUpsellBarURL());
            }
            this.whichLayer("ad");
            prettyLog.log("adSpot.display: set the adObject to visible|block", 3);
            
            if (this.duration > 0)
            {
                this.countdown = this.duration+1;
                this.timer();
                prettyLog.log("adSpot.display: starting countdown in the adlayer " + this.countdown, 5);
            }
            this.lastShown = currentTime;
            return;
        }
        else
        {
           prettyLog.log("adSpot.display: don't display since we don't want to spam users with ads more than every " + this.wait + " seconds, last shown was " + interval + " seconds ago", 1);
        }  
    }
    
    this.resumeGame();
    prettyLog.log("adSpot.display: resuming game", 1);
};

adSpot.prototype.whichLayer = function(chooseLayer)
{
    if (chooseLayer == "ad")
    {
		$(this.splashLayer).css("visibility", 'hidden');
		$(this.splashLayer).css("display", 'none');        
		$(this.adLayer).css("visibility", 'visible');
        $(this.adLayer).css("display", 'block');
        $(this.owner.gameLayer).css("margin-left", '9000px');       
        $(this.owner.gameLayer).css("height", '0px');
        $(this.owner.gameLayer).css("width", '0px');
        prettyLog.log("adSpot.whichLayer: setting ad to be visible, hiding game", 3);       
    }
    else if (chooseLayer == "splash")
	{
	    $(this.splashLayer).css("visibility", 'visible');
		$(this.splashLayer).css("display", 'block');
        $(this.adLayer).css("visibility", 'hidden');
        $(this.adLayer).css("display", 'none');
        $(this.owner.gameLayer).css("margin-left", '9000px');       
        $(this.owner.gameLayer).css("height", '0px');
        $(this.owner.gameLayer).css("width", '0px');
        prettyLog.log("adSpot.whichLayer: showing splash, hiding ad, hiding game", 3);       
	}
    else if (chooseLayer == "game")
    {
		$(this.splashLayer).css("visibility", 'hidden');
		$(this.splashLayer).css("display", 'none');
        $(this.adLayer).css("visibility", 'hidden');
        $(this.adLayer).css("display", 'none');
        $(this.owner.gameLayer).css("margin", '0 0 0 0');      
        $(this.owner.gameLayer).css("height", this.gameHeight + 'px');
        $(this.owner.gameLayer).css("width", this.gameWidth + 'px');
        prettyLog.log("adSpot.whichLayer: setting ad to be hidden, showing game", 3);
    }
    else
    {
        $(this.adLayer).css("visibility", 'hidden');
        $(this.adLayer).css("display", 'none');
        $(this.owner.gameLayer).css("visibility", 'visible');       
        $(this.owner.gameLayer).css("display", 'none');
        prettyLog.log("adSpot.whichLayer: setting ad to be hidden, hiding game also", 3);   
    }
};

adSpot.prototype.endDisplay = function()
{
    var currentDate = new Date();
   
    this.countdown = -1;

    this.whichLayer("game");
    $("#spot").attr('src','about:blank');
    trackingGame.updateState("idle");   

    prettyLog.log("adSpot.endDisplay: hiding the ad layer now, making game visible", 3);

    if (this.showPreroll)
    {
        this.showPreroll = false;
        
        if (this.isOwnerLoaded)
        {
            setTimeout('theAdSpot.owner.OnSessionReady("adCompleted")', 100);
        }

        prettyLog.log("adSpot.endDisplay: preRoll has finished, we are ready to start the game session", 3);
    }
    else
    {
        prettyLog.log("adSpot.endDisplay: mid or post roll ad has finished, lets resume the game", 3);
        this.resumeGame();
    }

    clearTimeout(this.globalTimer);
    this.countdown_display.html("a few");
};

adSpot.prototype.canRunAsPreroll = function()
{
    return this.showPreroll;
};

adSpot.prototype.runAsPreroll = function()
{
    var currentDate = new Date();
    var currentTime = currentDate.getTime();

    this.whichLayer("ad");
    this.setDuration(packageSettings.adDuration, false, false);
    $('#spot').attr('src', this.getAdURL("preroll"));
    $('#upsell_bar').attr('src', this.getUpsellBarURL());
    trackingGame.updateState("ad");
    this.whichLayer("ad");
    prettyLog.log("adSpot.runAsPreroll: preRoll adlayer is now visible", 1);
    trackingGame.addAdImpression("preroll", 1);

    if (this.duration > 0)
    {
        this.countdown = this.duration+1;
        this.timer();
        prettyLog.log("adSpot.runAsPreRoll: starting countdown in adlayer for " + this.countdown + " seconds", 3); 
    }
    this.lastShown = currentTime;
};

adSpot.prototype.skipPreroll = function()
{
    trackingGame.updateState("game");
    this.whichLayer("game");
    prettyLog.log("adSpot.runAsPreroll: not running preRoll", 1);   
};

adSpot.prototype.setDuration = function(duration, setTimer, isVariableAd)
{
	if (setTimer == true)
	{
		clearTimeout(this.globalTimer);
	}
	
	this.isVariableAd = isVariableAd;
	this.duration = duration + 1;
	this.countdown = this.duration;

	if (setTimer == true)
	{
		setTimeout('theAdSpot.timer()',3000);
	}
}

adSpot.prototype.adCompleted = function()
{
	 this.endDisplay();
}

function popcapCallBackDuration(duration)
{
	theAdSpot.setDuration(duration, true, true);
}

function popcapCallBackCompleted(hello)
{
	theAdSpot.adCompleted();
}




