// 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 if (typeof whenToShowAd != "undefined" && whenToShowAd == "never" ) {
        showAd=false;
	} 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>';
    $(".pageHeader").append("<div id='game_div' style='display:none;'></div>");  // element needed for the mtvn_game_ad_loader not to fail
	var matureAdFlag = ( typeof isMatureGame != "undefined" && isMatureGame ) ? "!category=mature;gametype=mature;" : "";
	var adUrl = "http://ad.doubleclick.net/pfadx/ag.nol/c/gv/" + dartCategory + "/" + dartCategory + "/" + gameKeyword + ";" +
				//"partner=;" +
				//"franchise=;" +
				"mode=clip;" +
				"mtype=gamevideo;" +
				//"genre=" + dartCategory + ";" +
				"game_type=" + dartCategory + ";" +
				"game_id=" + gameKeyword + ";" +
				"game_name=" + gameKeyword + ";" +
				"demo={demo};" +
				"!category=clip;" +
				"!category=gamevideo;" +
				matureAdFlag +
				"sz=640x480;" +
				"tile=1;" +
				"dcmt=text/xml;" +
				"ord=" + Math.round(Math.random()*10000000000000000) + "?";

	var gamePlayer = new GamePlayer();
	gamePlayer.gameURL = "";
	gamePlayer.gameWidth = -1;
	gamePlayer.gameHeight = -1;
	gamePlayer.gamePerAd = -1;
	gamePlayer.adURL = adUrl;
    gamePlayer.adWidth = 640;
    gamePlayer.adHeight = 480;
	gamePlayer.params = {quantCastID : "p-94wNw88f65Rhk"};

    // Enable Doubleclick or FreeWheel ads here
    gamePlayer.doubleClick.doubleClickEnabled = false;
    gamePlayer.freeWheel.freeWheelEnabled = true;
    gamePlayer.freeWheel.siteSection = "addictinggames__games";
    gamePlayer.freeWheel.assetId = gameKeyword;

    // Disable countdown timer
    gamePlayer.timeDisplayEnabled = false;

    // Provide Game metadata for QuantCast reporting call
    gamePlayer.gameMetaData.gameTitle = gameKeyword;
    gamePlayer.gameMetaData.gameId = gameKeyword;
    gamePlayer.gameMetaData.gameType = dartCategory;
    gamePlayer.gameMetaData.type = "Network";

    gamePlayer.init(document.getElementById("flashVideo"));

    player = window.document.flashVideo;
}
// methods that need to be overridden for the mtvn_game_ad_loader not to fail
function embed_game() {
    // do nothing
}
function launchGame(s) {
    $("#adLoader_div").hide();
    embedFlashGame();
}

/**
 * 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" style="position: absolute; z-index: -1;"></div>';
		
		// Load the game
		var flashVars = {};
		var flashParams = {
			AllowScriptAccess: "always",
			allowNetworking: "all",
			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");
 		$("body").css("background-position", "center 20px");
 		//$("#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");
	    $("body").css("background-position", "center 20px");
 		$("#banner").css("background-image","url(null)");
	    var reskinIsActive = true;
    }

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

                    // inserts links in the gutters
                    $("body").prepend('<a href="'+bgClickthroughUrl+'" target="_blank" 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 ) {
            $('#banner').css('height',186);
            
            // 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>AddictingGames no longer supports your browser. <\/h3><p>You may still be able to play games, but some new features may not work.<br \/>For the best experience, we recommend that you upgrade now.<\/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;
	})

	/**
	 * Workaround for a documented issue with firefox  (https://bugzilla.mozilla.org/show_bug.cgi?id=388714) in which
	 * iframe contents are loaded in the wrong iframe when a page is reloaded. The fix works by adding a hash
	 * character to the end of the url which shouldn't reload the page, instead it just forces FF to check that the
	 * iframe contents match the specified src url. Found the work-around here:
	 * http://forums.mozillazine.org/viewtopic.php?f=25&t=1622325
	 * TESTING NOTES:
	 * - Doesn't seem be causing an increase in ad frame reloads.
	 * - This method in conjunction with a meta refresh on the ad loader pages was causing extra history items to be
	 *   added which resulted in extra back button clicks being necessary to navigate to the previous page after the
	 *   ad iframe page reloaded. Using javascript setTimeout() and location.reload() to reload the ad page seems to
	 *   have fixed that problem.
	 */
	firefoxIframeFix = function () {
		if( $.browser.mozilla ){
			var f=document.getElementsByTagName("iframe");
			for(var i=0;i<f.length;i++){
				if(f[i].src.substr(f[i].src.length-1)!="#"){
					// this case shouldn't cause a reload
					try { // catches error on recent reviews & more popular tips page
						f[i].src=f[i].src + "#";
					} catch (e){}
				}
			}
		}
	}
	firefoxIframeFix();
});

// 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 ); });
}

// Omniture functions
function sendLinkEvent(lnkname){
	sendAnalyticsEvent(null,lnkname);
}
function sendAnalyticsEvent(str,lnkname){
	try {
		if(mtvn.btg.util.String.isDefined(lnkname)){
					obj = {};	
					
					if(mtvn.btg.util.String.isDefined(str)){ 
						obj.name=str;
						omniSetOverrides(obj, "append");
					}else{ 
						obj.name=mtvn.btg.config.ReportSettings.Omniture["account"];
						omniSetOverrides(obj, null);
					}					
					delete obj;
					mtvn.btg.Controller.sendLinkEvent({linkType:"o",lnk:true,linkName:lnkname});
				}else{
					if(mtvn.btg.util.String.isDefined(str))
						omniSetOverrides({name:str}, "append");
					else
						omniSetOverrides({name:mtvn.btg.config.ReportSettings.Omniture["account"]}, null);
					mtvn.btg.Controller.sendPageCall();
				}
			}
catch(e){}	
}

function omniSetOverrides(or,acctNameAction){
	try{
		clearDispatcher();
		var ro = {};
		for(i in or){
			var tmpi=i.replace(/s_/,"");
			tmpi=(tmpi=="account")? "name" : tmpi;
			ro[tmpi]=or[i];
			
			if(tmpi=="name"){
				if(acctNameAction){
					if(acctNameAction=="append"){
						var pattern = new RegExp("^"+ro[tmpi]+"$|^"+ro[tmpi]+",|,"+ro[tmpi]+"$|,"+ro[tmpi]+",");
						if(!pattern.test(mtvn.btg.config.ReportSettings.Omniture["account"]))
							mtvn.btg.config.ReportSettings.Omniture["account"] += ',' + ro[tmpi]; 
					}else if(acctNameAction=="overwrite")
						mtvn.btg.config.ReportSettings.Omniture["account"] = ro[tmpi]; 
				}
				ro[tmpi]= mtvn.btg.config.ReportSettings.Omniture["account"];
			}
		}
		ro.dynamicAccountSelection = true;
		ro.dynamicAccountList = 'viaaddictinggamesdev=dev.addictinggames.com,local,sandbox,localhost,stage,spicy,shiva,adam,grognard,cmillsga';
		ro.linkInternalFilters = 'javascript:,addictinggames.com,facebook.com,digg.com';
		ro.trackExternalLinks = true;
		ro.trackDownloadLinks = false;
		if(mtvn.btg.util.String.isDefined(mtvn.btg.config.ReportSettings.Omniture)) mtvn.btg.config.ReportSettings.Omniture.setAccountVars(ro);
	}catch(e){}
}
function clearDispatcher(){
	try {
		if(mtvn.btg.util.String.isDefined(mtvn.btg.config.ReportSettings.Omniture)){
			mtvn.btg.config.ReportSettings.Omniture={
				enabled: true,
       			        account: 'viaaddictinggames',
		                charSet: 'ISO-8859-1',
		                dynamicAccountSelection: 'true',
		                dynamicAccountList:  'viaaddictinggamesdev=dev.addictinggames.com,local,sandbox,stage,localhost,spicy,shiva,adam,grognard,cmillsga',
		                linkInternalFilters: 'javascript:,addictinggames.com',
		                videoViewEventDisable: false,
		                enableTimeParting: true,
		                trackInlineStats: false

			};			
			mtvn.btg.config.ReportSettings.Omniture["pageName"] = "";
			mtvn.btg.config.ReportSettings.Omniture["channel"] = "";
			mtvn.btg.config.ReportSettings.Omniture["hier1"] = "";
			for(var i=1; i<41; i++){
				mtvn.btg.config.ReportSettings.Omniture["prop"+i] = "";	
			}	
		}
	} catch(e){}
}

// Call an MTVN Reporting function to track a "link event".  We use this for arbitrary tracking of text strings.
// This function is dependent on mtvi_ads_reporting.js.
function trackGamePlayEvent()
{
    var eventText = gameKeyword + " - GamePlayEvent";
    sendLinkEvent( eventText );
}

