// Show an ad to a user every fixed number of plays
var globalAdFrequency = 4;
var showAd = false;
var adPlayPosition;

var playDiv;

/**
 * Checks the ad-play frequency, then plays an ad if appropriate (followed by the game) or just loads the game
 * This can be called on page load but can also be accessed by calling this function directly from the Flash game or an AJAX call to this method
 */
function playAdOrGame() {

	// First write out the div holder for the ad or the game
	document.write('<div id="play1"></div>');
	playDiv = document.getElementById("play1");

	// Check the ad frequency on page load
	if (typeof whenToShowAd != "undefined" && whenToShowAd == "always" ) {
		  showAd = true;
		} else {
		  checkAdFrequency(); 
	}
	
	//alert("should we show an ad?: " + showAd);
	if (showAd) {
		// can add additional logic here to load different types of ads

		// Load a video preplay ad (then the game)
		playVideoAd();
	} else {
		// Just load the game
		embedFlashGame();
	}
}

/**
 * Sets whether or not a pre-play ad should run based on play frequency.
 */
function checkAdFrequency() {

	// See if an ad frequency cookie is already set
	if ( $.cookie("adPlayPosition") ) {
		adPlayPosition = $.cookie("adPlayPosition");
		//alert('we have a cookie: ' + $.cookie("adPlayPosition") );

	// Otherwise set one
	} else {

		// Randomly select a user's starting point so ALL users don't have to play [globalAdFrequency] times before seeing the 1st ad
		// start at position [globalAdFrequency-1] or [globalAdFrequency] so the user has 0 or 1 gameplay before seeing 1st ad
		var adPlayPositionStart = Math.floor(Math.random()*(globalAdFrequency - (globalAdFrequency-2) )) + (globalAdFrequency-1);
		$.cookie("adPlayPosition", adPlayPositionStart);
		adPlayPosition = adPlayPositionStart;
		//alert("just set cookie position to: " + adPlayPositionStart);
	}

	// Make sure we're dealing with a number (not a string) for the addition just below
	adPlayPosition = parseInt(adPlayPosition);

	// If it's time to play an ad, set that up and restart the position counter
	if ( adPlayPosition == globalAdFrequency ) {
		showAd = true;
		adPlayPosition = 1;

	// Otherwise just increment the position
	} else {
		adPlayPosition += 1;
	}

	// Update the adPlayCount cookie
	$.cookie("adPlayPosition", adPlayPosition);
}

//holds a reference to the video player.
var player;
var timeoutID;

/**
 * Function to set up and call the video ad - timeout or ad complete will trigger the game to load
 *
 * This function requires these varibles set at embedding:
 * 	dartCategory (the section/channel keyword)
 * 	gameId (the game keyword)
 * 	gameDisplayName (self explanatory)
 */
function playVideoAd(){

	// Blank out the playDiv to hold the video ad
	playDiv.innerHTML = '<div id="flashVideo"></div>';

	// Global variables for the video ad player
	var yumeUrl = "/jsource/plugins/yumesdk3";
	var dartSite = "ag.nol";
	var mode = "mode.live"; // - possible values are "mode.dev" or "mode.live"
	var adComplete = "embedFlashGame"; // - name of a javascript function to call when the ad is done playing.

	// Page local variables for the video ad player
	//var rugrat // - demo identifier, will trigger "under13" for ad calls

	var flashVars = {
		yumeUrl: yumeUrl,
		dartSite: dartSite,
		mode: mode,
		gameName: gameKeyword, //gameDisplayName,
		gameType: dartCategory,
		gameId: gameKeyword,
		rugrat: "false",
		adComplete: adComplete
	};
	var flashParams = {
		allowScriptAccess: "always",
		bgcolor: "#000000",
		quality: "high"
	};
	swfobject.embedSWF("/jsource/GamePlayer.swf", "flashVideo", "480", "340", "9", "", flashVars, flashParams);

	player = window.document.flashVideo;

	// Set a default timeout to ensure the game is shown if ad call fails
	timeoutID = setTimeout( embedFlashGame, 36 * 1000 );
}

/**
 * Function to clear any ad on the page and load the game
 *
 * This function requires these varibles set at embedding:
 * 	gameName (reference to the Flash game to be played).
 * 	gameWidth (self explanatory)
 * 	gameHeight (self explanatory)
 */
function embedFlashGame(){

	// Clear the timeout just in case
	if(timeoutID) {clearTimeout(timeoutID);}
	
	// High Scores games use displayCustomEmbed
	if (typeof customEmbed != "undefined" && customEmbed != "") {
		
		// Blank out the playDiv and set up the game container
		playDiv.innerHTML = customEmbed;
		
	} else {
		
		// Blank out the playDiv and set up the game container
		playDiv.innerHTML = "<div id='FlashContent'></div>";
		
		// Load the game
		var flashVars = {};
		var flashParams = {
			AllowScriptAccess: "never",
			quality: "high"
		};
		
		gameName+=getURL();
		swfobject.embedSWF(gameName, "FlashContent", gameWidth, gameHeight, "9", "", flashVars, flashParams);
	}
}

/**
 * Reskin the backround of the site
 * @param bgImageUrl, the url to the image to apply to the background
 * @param bgColor, the color to apply to the backround behind the image
 */
$(document).ready(function() {
     
     reskinSetBackgroundImgAndColor = function(bgImageUrl,bgColor) {
         //alert('within reskinBackgroun');
 		$("body").css("background-image","url("+bgImageUrl+")");
 		$("body").css("background-color",bgColor);
 		$("body").css("background-repeat","no-repeat");
 		//$("#banner").css("background-image","url(null)");
 	}
     
     
    reskinBackground = function( bgImageUrl, bgColor  ) {
	    $("body").css("background-image","url("+bgImageUrl+")");
	    $("body").css("background-color",bgColor);
	    $("body").css("background-repeat","no-repeat");
 		$("#banner").css("background-image","url(null)");
	    var reskinIsActive = true;
    }

            reskinSetBackgroundLinks = function(bgClickthroughUrl, bgClickableHeight) {
                    // gets width of content, will likely not change                var contentWidth = $("#wrapper").width();

                    // inserts links in the gutters
                    $("body").prepend('<a href="'+bgClickthroughUrl+'" class="gutLinks clearLink" id="gutLinkLft">&nbsp;<\/a><a href="'+bgClickthroughUrl+'" target="_blank" class="gutLinks clearLink" id="gutLinkRit">&nbsp;<\/a>');

                    // checks browser width and calculates width of gutter links
                    resizeGutterLinks =  function(contentWidth) {
                            var browserWidth =  $(window).width();
                            var gutterWidth = (browserWidth - contentWidth) / 2;
                            $(".gutLinks").width(gutterWidth);
                            $(".gutLinks").css("padding-top",bgClickableHeight);
                    }
                    // if user resizes window call the function again
                    $(window).resize(function(){
                            resizeGutterLinks(contentWidth);
                    });

                    // start checking content width
                    resizeGutterLinks(contentWidth);
            }
    
    reskinBackground_ready = function( bgImageUrl, bgColor  ) {
            reskinSetBackgroundImgAndColor( bgImageUrl, bgColor );
    }

    reskinBackgroundClickable_ready = function( bgImageUrl, bgColor, bgClickthroughUrl, bgClickableHeight ) {
             reskinSetBackgroundImgAndColor(bgImageUrl, bgColor);
             reskinSetBackgroundLinks(bgClickthroughUrl, bgClickableHeight);
     }

    reskinBackgroundSelectable_ready = function(bgImageUrls, bgColors, selectableImageMapUrl, clickthroughUrls, clickTrackingUrls ) {
            // get the number of skins
            var numOfSkins = bgImageUrls.length;

            // removes the banner ad frame
            //$("#inBodyAd .adWrap > iframe").remove();

            // fix ie6 background image flicker
            if(typeof document.body.style.maxHeight === "undefined"){
                    try {
                            document.execCommand("BackgroundImageCache",false,true);
                    }
                    catch(e) {
                            //alert(e.message)
                    }
            }

            // helper function for onClick event
            selectableSkinLinkOnClick = function (skinNum){
                    reskinBackground_ready( bgImageUrls[skinNum], bgColors[skinNum] );
                    reskinSelectSprite( "#selectableSkinLink-"+skinNum );
                    reskinDynamicTracking( clickthroughUrls[skinNum], clickTrackingUrls[skinNum] );
            }

            // change selected sprite background position
            reskinSelectSprite = function(linkId) {
                    $("#reskinContent li a.selected").removeClass("selected");
                    $(linkId).addClass("selected");
            }

            // sets the wrapping reskin div that contains a class to style the template, based on the numOfSkins
            var StringBuffer = function () {
                    this.__strings__ = new Array;
            }
            StringBuffer.prototype.append = function (str) {
                    this.__strings__.push(str);
            };
            StringBuffer.prototype.toString = function () {
                    return this.__strings__.join("");
            };
            var buffer = new StringBuffer();

            buffer.append("<div id='reskinContent' class='reskinContent-"+numOfSkins+"'>")
            buffer.append("<a href='"+clickthroughUrls[0]+"' id='reskinSponsorLink' target='_blank' class='clearLink'>&nbsp;</a>");
            buffer.append("<ul>");
            for(i=0; i<numOfSkins; i++) {
                    // have to draw the onclick here, can't attach dynamically because -- suprise -- IE sucks
                    buffer.append("<li><a href=\"#\" onclick=\"selectableSkinLinkOnClick("+i+"); return false;\" id=\"selectableSkinLink-"+i+"\" class=\"clearLink\">select skin "+i+"</a></li>");
            }
            buffer.append("</ul>");
            $("#banner").append(buffer.toString());

            $("#reskinContent ul li a").css("background-image","url("+selectableImageMapUrl+")");

            //call the default (first) skin and set set default sprite to selected position
            reskinBackground_ready(bgImageUrls[0],bgColors[0]);
            reskinSelectSprite("#selectableSkinLink-0");
    }

    reskinDynamicTracking = function( clickthroughUrl, clickTrackingUrl ) {
            $("#reskinSponsorLink").attr("href", clickthroughUrl);

            // load tracking pixel
            try {
                    if ( typeof $("#selectableTracker").attr("src") == "undefined" ){
                            $("#reskinContent").append('<img id="selectableTracker" src="' + clickTrackingUrl + '" style="display:none;" />');
                    }
                    else {
                            $("#selectableTracker").attr("src", clickTrackingUrl);
                    }
            }
            catch(e) {
                    //alert(e.message);
            }
    }


	// ------------------------------------
	// Show an upgrade message to IE 6 users
	// ------------------------------------

	// if the user has not previously closed the upgrade message and a reskin is not active and reskinIsActive is not true and the browser is IE6 or less, show it
	if ( ( $.cookie("swHideIE6Upgrade") != "true") && ( typeof reskinIsActive == "undefined" ) && (typeof document.body.style.maxHeight === "undefined") && $(".brand-mamabar").length ) {
		$("body").css({backgroundPosition: "center 80px"});
		$(".brand-mamabar").after("<div id='ie6Upgrade'><div><h3>You are using an outdated browser<\/h3><p>For a better experience using this site please upgrade to a modern web browser. It's quick, it's easy, and it's safe!<\/div><\/div>")
		$("#ie6Upgrade div").append("<ul><li><a href='http://firefox.com/' target='_new' onclick='sendLinkEvent( \"ie6-upgrade-to-firefox\" );' class='clearLink b-ff'><\/a><\/li><li><a href='http://www.microsoft.com/windows/internet-explorer/default.aspx' target='_new' onclick='sendLinkEvent( \"ie6-upgrade-to-ie8\" );' class='clearLink b-ie'><\/a><\/li><li><a href='http://www.apple.com/safari/' target='_new' onclick='sendLinkEvent( \"ie6-upgrade-to-safari\" );' class='clearLink b-sf'><\/a><\/li><\/ul>")
		$("#ie6Upgrade div").append("<a href='#' onclick='sendLinkEvent( \"ie6-upgrade-dismissed\" );' class='icon16Lft icon16Close clearLink'><\/a>")
	}

	//close the ie6upgrade bar
	$("#ie6Upgrade .icon16Close").live("click", function(){
		$("#ie6Upgrade").hide();
		$("body").css({backgroundPosition: "center 18px"});
		//user has clicked the close button, don't show again for 30 days
		var cookieOptions = { path: '/', domain: '.shockwave.com', expires: 30 };
		$.cookie("swHideIE6Upgrade", "true", cookieOptions);
		return false;
	})		

});


// because we have to wait for the document to be fully rendered
// these helper functions delay the firing until functions above are available

reskinBackground = function( bgImageUrl, bgColor ) {
        reskinIsActive = true;
        $(document).ready(function () { reskinBackground_ready( bgImageUrl, bgColor ); });
}
reskinBackgroundClickable = function( bgImageUrl, bgColor, bgClickthroughUrl, bgClickableHeight ) {
        reskinIsActive = true;
        $(document).ready(function () { reskinBackgroundClickable_ready( bgImageUrl, bgColor, bgClickthroughUrl, bgClickableHeight ); });
}

reskinBackgroundSelectable = function( bgImageUrls, bgColors, selectableImageMapUrl, clickthroughUrls, clickTrackingUrls ) {
        reskinIsActive = true;
        $(document).ready(function () { reskinBackgroundSelectable_ready( bgImageUrls, bgColors, selectableImageMapUrl, clickthroughUrls, clickTrackingUrls ); });
}

