// Temporary token sponosor.  Comment out when not neededvar tokenSponsor = "RMHC";// Trophy object for displayfunction Trophy() {	this.name = "";	this.criteria = "";	this.tokens = 0;	this.code = "";}$(document).ready(function() {	// Layout config for the game overlay options	var overlayLayout = {		legacy :		   "overlaySmlNoBkg",		error :		       "overlaySmlNoBkg",		noToken :		   "overlaySml",		trophy :	   		"overlayLrg",		trophyMulti :	   "overlayLrg",		sipTrophy :		   "overlayLrg",		sipTrophyMulti :   "overlayLrg",		sipToken : 		   "overlayLrg",		sis :			   "overlayLrg",		nsi :			   "overlayLrg",		challengeConfirm : "overlayLrg",		challenge:		   ""	};	// HTML templates for overlay table and overlay error	//var overlayTableHTML = '<table id="gameOverlay" class="centerVH shadowBox"><tr><td class="shtl"></td><td class="shtm"></td><td class="shtr"></td></tr><tr><td class="shml"></td><td class="shmm"><div id="overlayTop"><div class="swLogoSmall"></div><a href="#" class="iconHelp clearLink">help</a></div></td><td class="shmr"></td></tr><tr><td class="shbl"></td><td class="shbm"></td><td class="shbr"></td></tr></table>';	var overlayTableHTML = '<table id="gameOverlay" class="centerVH shadowBox"><tr><td class="shtl"></td><td class="shtm"></td><td class="shtr"></td></tr><tr><td class="shml"></td><td class="shmm"><div id="overlayTop"><div class="swLogoSmall"></div></div></td><td class="shmr"></td></tr><tr><td class="shbl"></td><td class="shbm"></td><td class="shbr"></td></tr></table>';	var errorOverlay = '<div class="content"><p class="alignC mb15 errorMessage"></p><p class="alignC"><a href="#" onclick="closeGameOverlay(true); return false;" class="btnBig btnOnlineFull">Play Again</a></p></div><div id="overlayBot"></div>';	var challengeButton = '<a href="#" onclick="showChallenge(); return false;" class="btnBig btnMyShockwaveFull ml10">Challenge a Friend</a>';	var challengeData = null;	/**	 *	 * @param eventManagerJSON	 * @param highScoresJSON	 */	loadGameOverlay = function( eventManagerJSON, highScoresJSON ) {		if ( typeof overlayDebug != "undefined" ) {			alert("loading game overlay with:\n\neventManagerJSON:\n" + eventManagerJSON + "\n\nhighScoresJSON:\n" + highScoresJSON);		}		var tokensAwarded = 0;		var trophies = [];		// Check the user's logged in status		var loggedInStandard = ( signedInState == "SignedInStandard" );		var loggedInPremium = ( signedInState == "SignedInPremium" || signedInState == "SignedInClub" || signedInState == "SignedInFreeClub" );		// Convert the JSON strings into a JS objects		try {			var awardData = eval('(' + eventManagerJSON + ')');			var userScoreData = eval('(' + highScoresJSON + ')');		} catch ( error ) {			//alert ("there was a problem evaluating the JSON, it was too long or malformed:\n\n" + error.description );			overlayError( "Due to an unexpected error, you are unable to submit scores at this time.<br/>We apologize for the inconvenience" );			return;		}		// Extract the user score data		if ( userScoreData ) {			var gameId = userScoreData.gameId;			var keyword = userScoreData.keyword;			var gameModeTitle = userScoreData.gameTitle;			var currentScore = userScoreData.score;			var bestScore = userScoreData.bestScore;			var isBestScore = userScoreData.isBestScore == "true";			var showTrophies = userScoreData.showTrophies == "true";			var showTokens = userScoreData.showTokens == "true";			var showHighScores = userScoreData.showHighScores == "true";			var dailyRank = userScoreData.dailyRank;			var totalDailyPlays = userScoreData.dailyListSize;		}		// Only iterate and pull out the trophies and tokens if we have data and should show it		if ( awardData && (showTrophies || showTokens) ) {			// Check the Status of the response and that the Body exists and is OK as well			if ( awardData.Head.Status == "OK" && awardData.Body && awardData.Body.EventStatus.Status == "OK" ) {				// Iterate through the AwardsProcessed				for ( award in awardData.Body.AwardsProcessed ) {					// Iterate through AwardsPackage					for ( awardPackage in awardData.Body.AwardsProcessed[award].AwardsPackage ) {						var outcome = awardData.Body.AwardsProcessed[award].Outcome;						var awardType = awardData.Body.AwardsProcessed[award].AwardsPackage[awardPackage].Type;						var additionalTokens = awardData.Body.AwardsProcessed[award].AwardsPackage['Tokens'].Value;						// If AwardsPackage.Tokens and outcome was PRESENTED or ATTEMPTED_BUT_ANONYMOUS add tokens to total						if ( awardType == "Token" && ( outcome == "PRESENTED" || outcome == "ATTEMPTED_BUT_ANONYMOUS") ){							tokensAwarded += additionalTokens;						}						// If AwardsPackage[element].Type is Trophy and outcome was PRESENTED, add to trophy array						if ( awardType == "Trophy" && outcome == "PRESENTED" ) {							var trophy = new Trophy();							trophy.code = awardPackage;							trophy.name = awardData.Body.AwardsProcessed[award].AwardsPackage[awardPackage].Name;							trophy.criteria = awardData.Body.AwardsProcessed[award].Message;							trophy.tokens = additionalTokens;							trophies[trophies.length] = trophy;						}					}				}				// treat negative token amounts as zero				if ( tokensAwarded < 0 ) {					tokensAwarded = 0;				}			} else {				alert ( "status not OK" );  // Some error condition need to figure out what TODO			}		}		// Choose which overlay type to show based on the states gathered above		var overlayType = "legacy"; // default to only showing a link to the HighScoresPod		// If we have USER SCORE DATA but NO TOKENS and NO TROPHIES are won - points only - should be rare		if ( userScoreData && showHighScores && (tokensAwarded == 0) && (trophies.length == 0) ) {			overlayType = "noToken";		}		// If the user is LOGGED IN PREMIUM		else if ( awardData && loggedInPremium ) {			// and multiple TROPHIES are won in a CLUB GAME or multiple TROPHIES are won without any score			if ( (!showHighScores && !showTokens && showTrophies) && (trophies.length > 1) ) {				overlayType = "trophyMulti";			}			// and only 1 TROPHY is won in a CLUB GAME or 1 TROPHY is won without any score			else if ( (!showHighScores && !showTokens && showTrophies) && (trophies.length == 1) ) {				overlayType = "trophy";			}			// and TOKENS and multiple TROPHIES are won			else if ( (showTokens && showTrophies) && (tokensAwarded > 0) && (trophies.length > 1) ) {				overlayType = "sipTrophyMulti";			}			// and TOKENS and 1 TROPHY are won			else if ( (showTokens && showTrophies) && (tokensAwarded > 0) && (trophies.length == 1) ) {				overlayType = "sipTrophy";			}			// and TOKENS are won with NO TROPHIES			else if ( showTokens && (tokensAwarded > 0) && (trophies.length == 0) ) {				overlayType = "sipToken";			}		}		// If user IS LOGGED IN STANDARD and TOKENS and trophies are won (for promotional/sponsored trophies)		else if ( loggedInStandard && showTokens && (tokensAwarded > 0) && (trophies.length > 0) ) {			overlayType = "sipTrophy";		}		// If user IS LOGGED IN STANDARD and TOKENS only are won		else if ( loggedInStandard && showTokens && (tokensAwarded > 0) ) {			overlayType = "sis";		}		// If the user is NOT LOGGED IN but has qualified to win TOKENS		else if ( showTokens && tokensAwarded > 0 ) {			overlayType = "nsi";		}		// Clear any existing game overlay screens		$("#gameOverlay").remove();		// Turn off visibility of game first		hideGame();		// Set up the new overlay		$("#gameCanvas").after( overlayTableHTML );		$("#gameOverlay").addClass( overlayLayout[overlayType] );		// call HTML files with the overlayType requested		$.ajax({			url:"/html/gameOverlay/" + overlayType + ".html",			cache: false,			success: function( html ){				// inject the html				$("#gameOverlay #overlayTop").after( html );				// fill in the variables				$("#gameOverlay #gameTitle").html( gameModeTitle );				if ( showTokens ) {					$("#gameOverlay #totalTokensAwarded").html( formatNumber(tokensAwarded) );				}				// if high scores should be shown fill in appropriate fields				if ( showHighScores ) {					$("#gameOverlay #gamePointsAwarded").html( currentScore );					// if at this point there is no event data but the game may have tokens, show an error message instead of the high score ranking					if ( showTokens && (awardData == null || typeof awardData == "undefined") ) {						$("#gameOverlay #dailyRank").html("We could not award you tokens for this game. Sorry about that. If this continues to happen, please <a target='_blank' href='/help/contact_us.jsp'>contact customer service</a>.");					// otherwise if the user didn't place in the daily rankings, show a message instead of the ranking					} else if ( dailyRank == "0" ) {						$("#gameOverlay #dailyRank").html("You did not place in today's high scores. Give it another try!");					// otherwise, show the ranking in the daily high scores					} else {						$("#gameOverlay #userScoreRank").html( dailyRank );						$("#gameOverlay #usersTotal").html( totalDailyPlays );					}					// if the user is logged in					if ( loggedInStandard || loggedInPremium ) {						// add the "challenge" button						challengeData = userScoreData;						$("#overlayButtons").append( challengeButton );						// if the current score is the best score, offer a challenge						if ( isBestScore ) {							$("#gameOverlay #badgeYourBestScore").css( "display", "block" );							//$("#gameOverlay #bestScore").html( "Your Best Score Ever! <a href='#'>Challenge a Friend to beat it!</a>" );							$("#gameOverlay #bestScore").html( "<b>Your Best Score Ever!</b>" );						} else {							$("#gameOverlay #userBestScoreEver").html( bestScore );						}					}				} else {					// if we're not showing score make sure to blank out the fields					$("#gameOverlay #gamePointsAwarded").empty();					$("#gameOverlay #bestScore").empty();					$("#gameOverlay #dailyRank").html("&nbsp;");				}				// If trophies were won, fill in the Trohpy info				if ( showTrophies && (trophies.length > 0) ) {					$("#gameOverlay #numTrophies").html( trophies.length );					// Create an LI element for each trophy, populate it and add it to the DOM					for ( var i = 0; i < trophies.length; i++ ) {						var trophyElement = $("#gameOverlay .carousel-element:first").clone(true);						$(trophyElement).find(".trophyTitle").html( trophies[i].name );						$(trophyElement).find(".criteria").html( trophies[i].criteria );						$(trophyElement).find(".trophyTokens").html( trophies[i].tokens );						// create a string template for each flash trophy object						var trophyFlashString = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="230" height="310" title="trophy"><param name="movie" value="/swf/trophies/overlay_tokenandtrophy_shell.swf"><param name="quality" value="high"><param name="wmode" value="transparent"><param name="FlashVars" VALUE="tokensWon=0&trophyPath="><param name="SCALE" value="exactfit"><embed src="/swf/trophies/overlay_tokenandtrophy_shell.swf" width="230" height="310" flashvars="tokensWon=0&trophyPath=" wmode="transparent" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" scale="exactfit"></embed></object>';						// update the string representation with the tokens and path to the trophy						trophyFlashString = trophyFlashString.replace( /tokensWon=0/g, "tokensWon=" + tokensAwarded );						trophyFlashString = trophyFlashString.replace( /trophyPath=/g, "trophyPath=/swf/trophies/" + gameKeyword + "/" + trophies[i].code + ".swf" );						// insert the flash string back into the dom as an object						$(trophyElement).find(".awardContainer").append( trophyFlashString );						// for all trophies other than the first, make sure they're hidden until needed						if ( i != 0 ) {							$(trophyElement).removeClass("active").css("display","none");						}						$("#gameOverlay #trophyCarousel").append( trophyElement );					}					// Now remove the template LI; this is done so that the trophy SWF will load properly - it won't just by updating an existing OBJECT or EMBED					$("#gameOverlay .carousel-element:first").remove();				// otherwise if tokens were still won, configure the token animation with the correct number				} else if ( showTokens && tokensAwarded > 0 ) {					// create a string template for the flash object					var tokenFlashString = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="236" height="193" title="tokens"><param name="movie" value="/swf/tokens/tokendisplay_tokenonly_shell.swf"><param name="quality" value="high"><param name="FlashVars" VALUE="tokensWon=0"><param name="SCALE" value="exactfit"><param name="wmode" value="transparent"><embed src="/swf/tokens/tokendisplay_tokenonly_shell.swf" wmode="transparent" width="236" height="193" flashvars="tokensWon=0" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" scale="exactfit"></embed></object>';					// update the string representation with the correct tokens					tokenFlashString = tokenFlashString.replace( /tokensWon=0/g, "tokensWon=" + tokensAwarded );					// insert the new formatted flash string back into the dom					$("#gameOverlay .tokenContainer").append( tokenFlashString );				}				// If there is a sponsor, modify the overlay accordingly				applySponsor( keyword, overlayType, tokensAwarded );				// If there is no sponsor and the game has trophies and the user is not signed in, change the upsell message to feature trophies				if ( (typeof tokenSponsor == 'undefined') && (overlayType == "nsi") && showTrophies ) {					$("#upsellGameOverlay").removeClass("upsellGameOverlayTokens").addClass("upsellGameOverlayTrophies").html("Want to earn more?");				}				// attach carousel handlers to new ajax content				attachCarousel();				// center the gameOverlay				centerVH();			}		});	}	showChallengeConfirm = function( recipientEmailAddresses ) {		// Clear any existing game overlay screens		$("#gameOverlay").remove();		// Set up the new overlay		$("#gameCanvas").after( overlayTableHTML );		$("#gameOverlay").addClass( overlayLayout['challengeConfirm'] );		// call HTML files with the overlayType requested		$.ajax({			url:"/html/gameOverlay/challengeConfirm.html",			cache: false,			success: function( html ){				// inject the html				$("#gameOverlay #overlayTop").after( html );				$("#gameOverlay #recipientEmail").html( recipientEmailAddresses );				// center the gameOverlay				centerVH();			}		});	}	// Show the challenge screen	showChallenge = function () {		if ( challengeData != null ) {			// Clear any existing game overlay screens			$("#gameOverlay").remove();			// Set up the new overlay			$("#gameCanvas").after( overlayTableHTML );			$("#gameOverlay").addClass( overlayLayout['challenge'] );			// call HTML files with the overlayType requested			$.ajax({				url:"/html/gameOverlay/challenge.html",				cache: false,				success: function( html ){					// inject the html					$("#gameOverlay #overlayTop").after( html );					// fill in the variables					var bestScore = challengeData.bestScore;					$("#gameOverlay #userBestScoreEver").html( bestScore );					$("#gameOverlay #bestScore").val( bestScore );					$("#gameOverlay #gameKeyword").val( challengeData.keyword );					// center the gameOverlay					centerVH();				}			});		}	}	// Call this method to dismiss the overlay	// Flash may externally call this function without the 'userInitiated' parameter	closeGameOverlay = function ( userInitiated ) {		//restore visibility to the game first so that IE can get a handle to it's exposed methods		showGame();		// Get a handle to the Object containing the SDK		var gameHandle = $("#gameCanvas object").attr("id");		// Call the method to allow the game in the object to continue		// For IE		if ( ! jQuery.support.opacity ) {			var movie = document.getElementById(gameHandle);			try {				// continue command for Director				if ( typeof isDirectorGame != 'undefined' ) {					dirProxy.call('continueDispatch', 1);				// continue command for Flash				} else {					movie.continueDispatch();				}			} catch (err) {				overlayError( "We're really sorry, there was a problem continuing the game!<br /><br />Please try again below or <a href='javascript:document.location.reload();'>reload the page and start over</a>.<br /><br />(" + err.description + ")" );				return false;			}		// For other browsers		} else {			try {				var movie = eval("document." + gameHandle);				// continue command for Director				if ( typeof isDirectorGame != 'undefined' ) {					dirProxy.call('continueDispatch', 1);				// continue command for Flash				} else {					movie.continueDispatch();				}			} catch (err) {				overlayError( "We're really sorry, there was a problem continuing the game!<br /><br />Please try again below or <a href='javascript:document.location.reload();'>reload the page and start over</a>.<br /><br />(" + err.description + ")" );				return false;			}		}		// userInitiated is a flag to distinguish if the close was initiated by Flash or the user		if ( userInitiated ) {			// place to do stuff if user initiated the close		} else {			// place to do stuff if flash initiated the close		}		// remove the overlay		$("#gameOverlay").remove();	};	overlaySignIn = function ( trigger ) {		signIn( trigger, function( results ) {			var gameHandle = $("#gameCanvas object").attr("id");			try {				signedInState = results.login_state_code;				// For IE				if ( ! jQuery.support.opacity ) {					var movie = document.getElementById(gameHandle);					if ( typeof overlayDebug != "undefined" ) {						alert( "about to call userSignIn on the SDK: '" + results.member_id + "','" + results.login_state_code + "','" + results.screenname + "','" + results.member_email + "'");					}					// signin command for Director					if ( typeof isDirectorGame != 'undefined' ) {						dirProxy.call('userSignIn', results.member_id, results.login_state_code, results.screenname, results.member_email);					// signin command for Flash					} else {						movie.userSignIn( results.member_id, results.login_state_code, results.screenname, results.member_email );					}				// For other browsers				} else {					if ( typeof overlayDebug != "undefined" ) {						alert( "about to call into the SDK: document." + gameHandle + ".userSignIn( '" + results.member_id + "','" + results.login_state_code + "','" + results.screenname + "','" + results.member_email + "');");					}					// signin command for Director					if ( typeof isDirectorGame != 'undefined' ) {						dirProxy.call('userSignIn', results.member_id, results.login_state_code, results.screenname, results.member_email);					// signin command for Flash					} else {						eval("document." + gameHandle + ".userSignIn( '" + results.member_id + "','" + results.login_state_code + "','" + results.screenname + "','" + results.member_email + "');");					}				}			} catch (err) {				overlayError( "We're really sorry, you have been signed in but there was a problem awarding you the tokens for your game play.<br /><br />Please <a href='javascript:document.location.reload();'>reload the page to continue</a>.<br /><br />(" + err.description + ")" );				return false;			}		});	}	sdkPostLoginSubmitSuccess = function () {		// if we're in a daughter window and viewing a jigsaw game and the user is signed in premium, make sure to force fullscreen player		if ( typeof inDaughterWindow != 'undefined' &&			 (signedInState == 'SIP' || signedInState == 'SIC' || signedInState == 'SIFC' ) &&				(gameKeyword == 'jigsawpuzzles') ) {			document.location.href = document.location.href + "&fullScreen=1";			// and if the parent window is still open, reload that so that the user is signed in correctly			if (window.opener != null) {     			window.opener.location.reload();    		}		} else {			document.location.reload();		}	}	sdkPostLoginSubmitFail = function () {		alert("we have a failure in event submission from the SDK - but, the user is already logged in on shockwave!  what now?");	}	overlayError = function ( errorMessage ) {		// Clear any existing game overlay screens		$("#gameOverlay").remove();		// Turn off visibility of game first		hideGame();		// Set up the new overlay		$("#gameCanvas").after( overlayTableHTML );		$("#gameOverlay").addClass( overlayLayout["error"] );		// inject the error html		$("#gameOverlay #overlayTop").after( errorOverlay );		// update the error message		$("#gameOverlay p.errorMessage").html( errorMessage );		// center the gameOverlay		centerVH();	}	hideGame = function( ) {		// For IE we CAN'T toggle the visibility of the game and still access it		if ( ! jQuery.support.opacity ) {			$("#gameCanvas object").css("position","absolute");			$("#gameCanvas object").css("top","0");			$("#gameCanvas object").css("left","-9999px");		// For other browsers we can just toggle the visibility		} else {			$("#gameCanvas object").css("visibility","hidden");		}	}	showGame = function () {		// For IE we CAN'T toggle the visibility of the game and still access it		if ( ! jQuery.support.opacity ) {			$("#gameCanvas object").css("position","static");		// For other browsers we can just toggle the visibility		} else {			$("#gameCanvas object").css("visibility","visible");		}	}	logScratcher = function ( scratcherType ) {		// call out to Omniture's linkEvent tracker		sendLinkEvent( "scratcher_" + gameKeyword + "_" + scratcherType );		// post an AJAX request to our server as a backup on the server logs		$.post( "/logScratcher.jsp?keyword=" + gameKeyword + "&type=" + scratcherType );	}	donateTokens = function ( tokenAmount ) {		if ( typeof tokenSponsor != 'undefined' ) {			// call out to Omniture's linkEvent tracker			sendLinkEvent( "donate_" + tokenSponsor + "_" + tokenAmount );			// Clear any existing game overlay screens			$("#gameOverlay").remove();			// Set up the new overlay			$("#gameCanvas").after( overlayTableHTML );			$("#gameOverlay").addClass( overlayLayout['challengeConfirm'] ).addClass( "tokenDonation_" + tokenSponsor );			// call HTML files with the overlayType requested			$.ajax({				url:"/html/gameOverlay/challengeConfirm.html",				cache: false,				success: function( html ){					// inject the HTML and update the content					$("#gameOverlay #overlayTop").after( html );					// THE FOLLOWING LINE IS HARDCODED FOR RMHC SPONSOR RIGHT NOW, NEED TO EXTRACT THIS AND GET IT PASSED IN					$("#confirmContent").html("<a href='/sponsors/mcdonalds/index.jsp' onclick='overlayLink(\"http://ad.doubleclick.net/clk;219492304;15177704;f?http://www.shockwave.com/sponsors/mcdonalds/index.jsp\");return false;'><img src='/sponsorsStatic/" + tokenSponsor + "/i/donateThanks.png' class='donateThanksImg' alt='Thank you' /></a>");					// center the gameOverlay					centerVH();				}			});		}	}	applySponsor = function ( keyword, overlayType, tokensAwarded ) {		// HACK - HACK - HACK = remove me soon pls.		//     this makes sure the donation sponsor does not show for this game		if ( keyword == 'kfckitchen' ) {			return;		}		// END HACK - HACK - HACK = remove me soon pls.		if (typeof tokenSponsor == 'undefined' ) {			return;		}		// update the different versions of the overlay to initiate token donation		if ( overlayType == "nsi" ) {			$("#upsellGameOverlay").removeClass("upsellGameOverlayTokens").addClass("tokenDonation_" + tokenSponsor).html("Donate Your Tokens");			$("#upsellGameOverlay").attr("href", "#");			$("#upsellGameOverlay").unbind("click");			$("#upsellGameOverlay").click(function(e){donateTokens( tokensAwarded );return false;});			$("#upsellGameOverlay").attr("onclick", "donateTokens( " + tokensAwarded + " );return false;");		} else if ( overlayType == "sis" ) {			$("#overlayUpsell").remove();			$("#overlayButtons").addClass("mb15");			$("#overlayBot").append("<a href='#' onclick='donateTokens( " + tokensAwarded + " );return false;'><img class='itemCentered' src='/sponsorsStatic/" + tokenSponsor + "/i/overlayDonateSignedIn.png' alt='donate your tokens' /></a>");		} else if ( overlayType == "sipToken" ) {			$("#overlayButtons").addClass("mb15");			$("#overlayBot").append("<a href='#' onclick='donateTokens( " + tokensAwarded + " );return false;'><img class='itemCentered' src='/sponsorsStatic/" + tokenSponsor + "/i/overlayDonateSignedIn.png' alt='donate your tokens' /></a>");		} else if ( overlayType == "sipTrophy" || overlayType == "sipTrophyMulti" ) {			$("#overlayButtons").addClass("mb10");			$("#overlayBot").append("<a href='#' onclick='donateTokens( " + tokensAwarded + " );return false;'><img src='/sponsorsStatic/" + tokenSponsor + "/i/overlayDonateTrophy.png' alt='donate your tokens' /></a>");		}	}	overlayLink = function ( url ) {		if ( typeof inDaughterWindow != 'undefined' ) {			gotoInParent( url, true );		} else {			document.location.href = url;		}	}});