if (!document.trace) {
	this.trace = function(output) {
	//	if (console.log && output) console.log(output);
	}
}


//// GLOBAL

/** The frequency by which to show ads (milliseconds) */
var AD_FREQUENCY = (60 * 1000) * 2; //<< every 2 minutes...
	
/** The JS wrapper */
var wrapperJS;

/** The FLASH wrapper */
var wrapperFlash;

/** The FLASH wrapper container */
var wrapperFlashContainer;

/*window.addEvent('domready', function() {
	wrapperJS = new GameWrapper();
});*/


//// Callback re-wires. @todo rewire flash to call these directly via 'wrapperJS.______'

function onWrapperReady() { if (wrapperJS) wrapperJS.onWrapperReady(); }
function onWrapperInitComplete() { if (wrapperJS) wrapperJS.onWrapperInitComplete(); }
function onGameLoadStatus(amountLoaded) { if (wrapperJS) wrapperJS.onGameLoadStatus(amountLoaded); }
function onGameStart() { if (wrapperJS) wrapperJS.onGameStart(); }
function onGameComplete(score) { if (wrapperJS) wrapperJS.onGameComplete(score); }
function onRoundStart() { if (wrapperJS) wrapperJS.onRoundStart(); }
function onRoundComplete() { if (wrapperJS) wrapperJS.onRoundComplete(); }
function onShowInterstitialState() { if (wrapperJS) wrapperJS.onShowInterstitialState(); } 
function onHideInterstitialState() { if (wrapperJS) wrapperJS.onHideInterstitialState(); }
function onGetChallengeMenu() { if (wrapperJS) wrapperJS.onGetChallengeMenu(); }
function onAcceptChallenge() { if (wrapperJS) wrapperJS.onAcceptChallenge(); }
function onStartChallenge(playerId) { if (wrapperJS) wrapperJS.onStartChallenge(playerId); }
function onNextGameResultsScene() { if (wrapperJS) wrapperJS.onNextGameResultsScene(); }
function onSubmitComment(comment) { if (wrapperJS) wrapperJS.onSubmitComment(comment); }
function onAdComplete() { if (wrapperJS) wrapperJS.onAdComplete(); }


//// Game Wrapper JS Class

var GameWrapper = new Class({
	
	/**
	 * Called automatically when instance is created.
	 */
	initialize : function() {
		
		this.flashReady = false;
		this.gameLoaded = false;
		this.amountLoaded = -1;
		this.gameStartTime = -1;
		this.gamePlayTime = -1;
		this.roundStartTime = -1;
		this.roundPlayTime = -1;
		this.interstitialStartTime = -1;
		this.interstitialPlayTime = -1;
		this.interstitialCompleteTime = this.getTimestamp() - AD_FREQUENCY;
		this.inGameAdCompleteTime = this.getTimestamp() - inGameAdRefreshPeriod * 1000;
		this.outGameAdCompleteTime = this.getTimestamp() - outGameAdRefreshPeriod * 1000;
		this.interstitialTemplate = "";
		
		this.runningPlayTime = -1;
		
		this.gameTitle = "";
		this.gameTitleScreenAsset = "";
		this.gamePlayAsset = "";
		this.gameMode = "";
		this.scoreA = "";
		this.scoreB = "";
		
		this.assetPath = $('assetPath').getText();
		
		this.loop = 0;
		this.finalMenu = false;
		
		this.uid = 0;
		
		this.gameInProgress = false;
		this.challengeInProgress = false;
		this.challengeMode = false;
		this.lastResultsScreen = '';
		
		this.gameResultsWait = 0;
		
		this.embedFlash();
		
		this.baseOmnitureTitle = '';
		this.omnitureCalls = 0;
	},
	
	/**
	 * Inject the Flash Wrapper element into the document.
	 */
	embedFlash : function() {
		
		trace('GameWrapper.embedFlash()');
		
		var flashvars = {
			assetPath: this.assetPath
		};
	
		var params = {
			menu: "false", 
			allowScriptAccess: "always"
		};
	
		var attributes = {};

		 var dateNow = new Date().getTime();
		swfobject.embedSWF(sn_swf_base_url + "usa_gl_wrapper.swf?rnd="+dateNow , "game_wrapper", "924", "480", "9.0.0", sn_swf_base_url + "expressInstall.swf", flashvars, params, attributes);
		
		wrapperFlashContainer = $('game_wrapper_container');
	},
	
	/**
	 * Called back from Flash Wrapper when the wrapper has loaded 
	 * and initialized its external interface.
	 */
	onWrapperReady : function() {
		
		trace('GameWrapper.onWrapperReady()');
		
		this.flashReady = true;
		this.applyContentInit();
	},
	
	/**
	 * Parse the document content that initially defines the game params that 
	 * are to be applied to the Flash Wrapper.
	 */
	applyContentInit : function() {
		
		trace('GameWrapper.applyContentInit()');
		
		// parse the document content...
		
		var gameTitle = $('gameTitle').getText();
		var gameTitleScreenAsset = $('gameTitleScreenAsset').getText();
		var gamePlayAsset = $('gamePlayAsset').getText();
		var gameMode = $('gameMode').getText();
		var scoreA = $('scoreA').getText();
		var scoreB = $('scoreB').getText();
		
		// init the wrapper, from the document content...
		
		this.initWrapper(gameTitle, gameTitleScreenAsset, gamePlayAsset, gameMode, scoreA, scoreB);
	},
	
	/**
	 * Init/re-init the Flash Wrapper.
	 * 
	 * @param 	gameTitle The game title text to display.
	 * @param 	gameTitleScreenAsset Full URL of the game title screen SWF.
	 * @param 	gamePlayAsset Full URL of the game play SWF.
	 * @param 	gameMode The game mode id ('normal', 'challenge').
	 * @param 	scoreA The number to display in the scoreA field.
	 * @param 	scoreB The number to display in the scoreB field.
	 */
	initWrapper : function(gameTitle, gameTitleScreenAsset, gamePlayAsset, gameMode, scoreA, scoreB) {
		
		trace('GameWrapper.initWrapper(' + gameTitle + ', ' + gameTitleScreenAsset + ', ' + gamePlayAsset + ', ' + gameMode + ', ' + scoreA + ', ' + scoreB + ')');
		
		// get a reference to the flash element itself...
		
		if (window.ie) { 
			wrapperFlash = window["game_wrapper"]; 
		} else { 
			wrapperFlash = document["game_wrapper"]; 
		}
		
		// keep instance vars of args...
		
		this.gameTitle = gameTitle;
		this.gameTitleScreenAsset = gameTitleScreenAsset;
		this.gamePlayAsset = gamePlayAsset;
		this.gameMode = gameMode;
		this.scoreA = scoreA;
		this.scoreB = scoreB;
		
		// reset loading state...
		
		this.gameLoaded = false;
		
		// init the Flash wrapper...
		
		trace('-- GameWrapper -> FlashWrapper.init(' + gameTitle + ', ' + gameTitleScreenAsset + ', ' + gamePlayAsset + ', ' + gameMode + ', ' + scoreA + ', ' + scoreB + ')');
		
		wrapperFlash.init(this.gameTitle, this.gameTitleScreenAsset, this.gamePlayAsset, this.gameMode, this.scoreA, this.scoreB);
	},
	
	/**
	 * Called back by Flash Wrapper once the wrapper has been 
	 * initialized and is ready to proceed.
	 */
	onWrapperInitComplete : function() {
		
		trace('GameWrapper.onInitComplete()');
	},
	
	/**
	 * Called back by Flash Wrapper periodically during main game content 
	 * loading. Signifies the load status of the game.
	 * 
	 * @param 	amountLoaded The current amount loaded (-1, 0.0 to 1.0);
	 */
	onGameLoadStatus : function(amountLoaded) {
		
		trace('GameWrapper.onGameLoadStatus(' + amountLoaded + ')');
		
		this.amountLoaded = amountLoaded;
		
		if (amountLoaded < 0) {
			// loading still pending (no bytes received)...
		} else if (amountLoaded >= 0 && amountLoaded < 1) {
			// loading in progress...
		} else if (amountLoaded >= 1) {
			this.gameLoaded = true;
		}
	},
	
	/**
	 * Called back by Flash Wrapper when a game is started.
	 */
	onGameStart : function() {
		
		trace('GameWrapper.onGameStart()');
		if (!this.gameInProgress) {
			this.gameInProgress = true;
			this.gameStartTime = this.getTimestamp();
			this.gamePlayTime = 0;
			this.roundPlayTime = 0;
			this.interstitialPlayTime = 0;
			this.interstitialCompleteTime = 0;
			this.inGameAdCompleteTime = 0;
			this.outGameAdCompleteTime = 0;
			this.lastResultsScreen = '';
			this.gameResultCount = 0; //<< TEMP, FOR TESTING
			
			this.queryAdDelivery('onGameStart');
			
			if (!this.challengeInProgress)
			{
				this.challengeMode = false;
				// call ajax function to start match, only if u r logged in
				if (sn_currentUserData)
				{
					sn_games_startGame(sn_currentUserData.a, sn_currentGameUUID);
				}
			}
		}
	},
		
	/**
	 * Called back by Flash Wrapper when a game completes.
	 */
	onGameComplete : function(score) {
		//if(document.getElementById("endGameContainer")) { //  Show End Game Screen
		//	sn_games_showHideEndGameScreen();
		//}
		//trace('GameWrapper.onGameComplete(' + score + ')');
		if (this.gameInProgress || this.challengeInProgress) {
			// call ajax function to start match, only if u r logged in
			if (sn_currentUserData)
			{
				sn_games_endGame(sn_currentMatchUUID, sn_currentUserData.a, score, 1, this.gameStartTime, this.getTimestamp(), '', this.challengeInProgress);
				//sn_games_endGame(matchUUID, personUUID, score, numberOfTries, startTime, stopTime, playerMessage)
			}
			else
			{
				// if not logged in show a thanks for playing message to continue
				this.loadGameResults(wrapperJS);
			}
			
			// get the total seconds the game has been played for...
			this.gamePlayTime = (this.getTimestamp() - this.gameStartTime) / 1000;
			
			// subtract the total seconds of ad delivery time from the play time...
			
			this.gamePlayTime -= this.interstitialPlayTime;
			this.gameInProgress = false;
			this.queryAdDelivery('onGameComplete');
		}
	},
	
	/**
	 * Called back by Flash Wrapper when a round is started.
	 */
	onRoundStart : function() {
	
		trace('GameWrapper.onRoundStart()');
	
		this.roundStartTime = this.getTimestamp();
		this.roundPlayTime = 0;
		this.sendOmniture('ROUND');
	},
	
	/**
	 * Called back by Flash Wrapper when a round completes.
	 */
	onRoundComplete : function() {
	
		trace('GameWrapper.onRoundComplete()');
		
		this.roundPlayTime = (this.getTimestamp() - this.roundStartTime) / 1000;
		this.runningPlayTime += this.roundPlayTime;
		this.queryAdDelivery('onRoundComplete');
	},
	
	/**
	 * Query to determine whether an ad should be displayed when 
	 * a game state is reached.
	 */
	queryAdDelivery : function(state) {
		
		trace('GameWrapper.queryAdDelivery(' + state + ')');
		
		var scope = this;
		
		// enclosure - handle when query fails...
		// in this case the wrapper is allowed to advance (show no ad)
		
		var queryAdDeliveryFailure = function() {
		
			trace('-- GameWrapper -> FlashWrapper.advance()');
			
			if (!adInterrupt) wrapperFlash.advance();
		}
		
		// enclosure - handle when query returns...
		// in this case the return value is either false or empty (no ad),
		// or is the URL of an iframe to display containing the ad delivery template...
		
		var queryAdDeliverySuccess = function(result) {
			
			if (!result) {
			
				// returned false or empty - do not show an ad
				
				trace('-- GameWrapper -> FlashWrapper.advance()');
				
				if (!adInterrupt) wrapperFlash.advance();
			
			} else {
			
				scope.interstitialTemplate = result;
				
				trace('-- GameWrapper -> FlashWrapper.showInterstitialState()');
				trace('-- Template: ' + scope.interstitialTemplate);
				
				wrapperFlash.showInterstitialState();
			}
		}
		
		switch (state) {
		
			case 'onGameStart' :
				
				// query to see if an ad should display at start
				// hard coded logic here for testing:
				// always show an ad when a game starts...
				
				this.sendOmniture();
				queryAdDeliverySuccess('/games/ad/serve?type=gamestart' + (enableVideoAds ? 'video' : ''));
				if (typeof inGameAdForcePeriod != 'undefined' && inGameAdForcePeriod) setNextAd();
				sn_refreshAd728x90('ad728x90');
				setNext728();
				this.outGameAdCompleteTime = this.getTimestamp();
				
				break;
				
			case 'onGameComplete' :
				
				// -- query to see if an ad should display at game completion
				// hard coded logic here for testing:
				// do not show an ad...
				
				this.showGameResults();
				
				break;
				
			case 'onNextGameResultsScene' :
				
				// -- query to see if an ad should display at game end menu
				// hard coded logic here for testing:
				// do not show an ad...
				
				trace('-- GameWrapper -> FlashWrapper.advance()');
				
				this.showGameResults();
				
				break;
				
			case 'onRoundComplete' :
			default :
				
				// query to see if an ad should display between game rounds
				// hard coded logic here for testing:
				// show an ad between rounds when a span of time has elapsed since
				// the previous ad delivery...
				
				var timeSinceLastAd = this.getTimestamp() - this.interstitialCompleteTime;
				var timeSinceLastInGameAd = this.getTimestamp() - this.inGameAdCompleteTime;
				var timeSinceLastOutGameAd = this.getTimestamp() - this.outGameAdCompleteTime;
				
				if (adInterrupt || timeSinceLastInGameAd >= inGameAdRefreshPeriod * 1000) {
					if (!adInterrupt && typeof inGameAdForcePeriod != 'undefined' && inGameAdForcePeriod && timerAd)
						window.clearInterval(timerAd);
					/*if (adInterrupt) {
						var d = new Date();
						trace('Forced 300x250: ' + d.getHours()+':'+d.getMinutes()+':'+d.getSeconds()+'.'+(d.getTime() % 1000));
					} else {
						var d = new Date();
						trace('Round 300x250: ' + d.getHours()+':'+d.getMinutes()+':'+d.getSeconds()+'.'+(d.getTime() % 1000));
					}*/
					this.sendOmniture();
					queryAdDeliverySuccess('/games/ad/serve?type=duringgame' + (enableVideoAds ? 'video' : ''));
					sn_refreshAd728x90('ad728x90');
					setNext728();
					this.outGameAdCompleteTime = this.getTimestamp();
				} else if (timeSinceLastOutGameAd >= outGameAdRefreshPeriod * 1000) {
					this.sendOmniture();
					sn_refreshAd728x90('ad728x90');
					setNext728();
					this.outGameAdCompleteTime = this.getTimestamp();
					wrapperFlash.advance();
				} else {
					wrapperFlash.advance();
				}
				
				break;
		}
		
	},

	/**
	 * Called back by Flash Wrapper when the interstitial state 
	 * has been transitioned to completely.
	 */
	onShowInterstitialState : function() {
	
		trace('GameWrapper.onShowInterstitialState()');
		
		this.interstitialStartTime = this.getTimestamp();
		this.interstitialPlayTime = 0;
		
		this.showInterstitial();
		if (adInterrupt) wrapperFlash.pause(); //window.setTimeout("wrapperFlash.pause();", 500);
	},
	
	/**
	 */
	showInterstitial : function() {
		
		trace('GameWrapper.showInterstitial()');
		trace('-- Template: ' + this.interstitialTemplate);
		
		// occlude the flash game wrapper from view...
		
		this.hideFlashContainer();
		
		// create the ad iframe's div parent container...
		
		var adElement = new Element('div', { 'id' : 'interstitial_wrapper' });
		adElement.setStyles('display: block; position: absolute; left: 13px; top: 2px; width: 924px; height: 480px;');
		adElement.injectInside($$('#game .content')[0]);
		
		// create the ad template iframe...
		
		this.uid = Math.round(Math.random() * 1000000);
		
		var adFrame = new Element('iframe', {id: 'ad_container' + this.uid, name: 'ad_container' + this.uid, src: this.interstitialTemplate, frameborder : '0', scrolling : 'no'});
		adFrame.setStyles('width: 924px; height: 480px; padding: 0; margin: 0');
		adFrame.injectInside(adElement);
		
		// watch + push load state to the ad wrapper...
		
		this.loop = this.watchLoadProgress.periodical(800, this);
	},
	
	/**
	 */
	watchLoadProgress : function() {
		
		trace('GameWrapper.watchLoadProgress()');
		trace('-- GameWrapper.gameLoaded = ' + this.gameLoaded);
		
		if (this.gameLoaded) {
		
			this.loop = $clear(this.loop);
			
			//var adFrame = window.frames['ad_container'];
			var adFrame = $('ad_container' + this.uid).contentWindow;
			
			if (adFrame.onLoadComplete) { 
				trace('-- GameWrapper -> AdTemplate.onLoadComplete()');
				adFrame.onLoadComplete();
			} else {
				this.loop = this.deferAdFrameCallToLoadComplete.periodical(800, this);
			}
		}
	},
	
	/**
	 */
	deferAdFrameCallToLoadComplete : function() {
	
		trace('GameWrapper.deferAdFrameCallToLoadComplete()');
		
		var adFrame = $('ad_container' + this.uid).contentWindow;
		
		if (adFrame.onLoadComplete) {
			trace('-- GameWrapper -> AdTemplate.onLoadComplete()');
			adFrame.onLoadComplete();
			this.loop = $clear(this.loop);
		}
	},
	
	/**
	 * Called back by Ad template when ad completes.
	 */
	onAdComplete : function() {
		
		trace('GameWrapper.onAdComplete()');
		
		// remove the ad iframe's div parent container...
		
		var adElement = $('interstitial_wrapper');
		adElement.setStyle('display', 'none');
		adElement.remove();
		
		// bring the flash game wrapper back into view...
wrapperFlash.resume();
		
		this.showFlashContainer();
		
		trace('-- GameWrapper -> FlashWrapper.hideInterstitialState()');
		
		wrapperFlash.hideInterstitialState();	
	},
	
	/**
	 * Called back by Flash Wrapper when the insterstitial state 
	 * has been resumed from completely.
	 */
	onHideInterstitialState : function() {
	
		trace('GameWrapper.onHideInterstitialState()');
		
		this.interstitialPlayTime = (this.getTimestamp() - this.interstitialStartTime) / 1000;
		this.interstitialCompleteTime = this.getTimestamp();
		this.inGameAdCompleteTime = this.getTimestamp();
		
		//trace('testing FlashWrapper.advance() reference: ' + wrapperFlash.advance);
		
		trace('-- GameWrapper -> FlashWrapper.advance()');
		
		if (typeof inGameAdForcePeriod != 'undefined' && inGameAdForcePeriod) setNextAd();
		if (!adInterrupt) { 
			setTimeout("wrapperFlash.advance()", 50);
		}
		adInterrupt = false;
	},
	
	/**
	 * Called back from Flash Wrapper to request challenge menu
	 * content for the current game/session.
	 */
	onGetChallengeMenu : function() {
	
		trace('GameWrapper.onGetChallengeMenu()');
		
		// enclosure, handle success result of request...
		
		var xmlContentRequestSuccess = function(response) {
			wrapperFlash.populateChallengeMenu(response);
		}
		
		// enclosure, handle failure result of request...
		
		var xmlContentRequestFailure = function() {
			trace('-- GameWrapper: ERROR GETTING CHALLENGE MENU XML');
		}
		
		// static example, replace with real request as needed...
		// see mootools Ajax documentation for more info...
		
		var provider = '/games/act/getVsList?gameUUID=' + sn_currentGameUUID;
		
		var xmlContentRequest = new Ajax(provider, {
			method: 'get',
			onStateChange: function() { try { if ((this.transport.readyState != 4) || (this.transport.status == 200)) return; } catch(e) { xmlContentRequestFailure(); }},
			onComplete: xmlContentRequestSuccess
		});
		
		xmlContentRequest.request();

	},
	
	/**
	 * Called back from Flash Wrapper when a challenge is accepted. 
	 * This occurs when the game is in challenge mode (the player 
	 * arrives at the game by clicking a pending challenge link), 
	 * and the player starts the challenge (vs. starting a practice
	 * round). 
	 * 
	 * It is assumed that the server will manage the challenge session 
	 * and interpret subsequent events (game complete, etc.) as part 
	 * of that challenge session.
	 */
	onAcceptChallenge : function() {
		this.challengeMode = true;
		this.challengeInProgress = true;
		trace('GameWrapper.onAcceptChallenge()');
		trace('-- PHP: send challenge start (current challenge accepted) to server');
	},
	
	/**
	 * Called back from Flash Wrapper when a challenge is initiated. 
	 * This occurs when the game is in normal mode (the player arrives 
	 * at the game through normal means), and the player chooses the 
	 * VS mode option and selects an opponent to challenge (vs. starting 
	 * a normal game).
	 * 
	 * It is assumed that the server will manage the challenge session 
	 * and interpret subsequent events (game complete, etc.) as part 
	 * of that challenge session.
	 */
	onStartChallenge : function(playerId) {
		// call ajax function to start match, only if u r logged in
		if (sn_currentUserData)
		{
			this.challengeMode = true;
			this.challengeInProgress = true;
			sn_games_startChallenge(sn_currentUserData.a, playerId)
		}
		trace('GameWrapper.onStartChallenge(' + playerId + ')');
		
	},
	
	/**
	 * Query the server to return the results of gameplay for this 
	 * session to the summary menus. This is hard-coded as an example 
	 * of the flow and expected return values.
	 */
	showGameResults : function() {
		/*trace('GameWrapper.showGameResults()');
		
		// enclosure - handle when query returns results...
		var queryGameResultsSuccess = function(response) {
			if (response != 'error')
			{
				trace('-- GameWrapper -> FlashWrapper.showGameResultsScene(' + response + ')');
				wrapperFlash.showGameResultsScene(response);
			}
			else
			{
				wrapperFlash.advance();
			}
		}
		
		// enclosure - handle when query fails...
		// advance without showing any more results...
		
		var queryGameResultsFailure = function() {
		
			trace('-- GameWrapper: ERROR GETTING GAME RESULTS XML');
			trace('-- GameWrapper -> FlashWrapper.advance()');
			wrapperFlash.advance();
		}
		
		var provider;
		var resultsContentRequest;
		
		var randomRefresh = Math.round(Math.random()*1000000000000);
		
		if (this.challengeMode)
		{
			provider = '/games/act/getGameEndResults?type=challenge&playerUUID=' + sn_currentUserData.a + '&matchUUID=' + sn_currentMatchUUID + '&random=' + randomRefresh;
		}
		else
		{
			provider = '/games/act/getGameEndResults?type=score&playerUUID=' + sn_currentUserData.a + '&matchUUID=' + sn_currentMatchUUID + '&random=' + randomRefresh;
		}
		*/
		/*switch (this.gameResultCount) {
			
			case 0 :
				provider = '/games/act/getGameEndResults?type=challenge&playerUUID=' + sn_currentUserData.a + '&matchUUID=' + sn_currentMatchUUID;
				break;
				
			case 1 :
				provider = '/games/act/getGameEndResults?type=score&playerUUID=' + sn_currentUserData.a + '&matchUUID=' + sn_currentMatchUUID;
				break;
				
			default :
				break;
		}*/
		/*
		if (provider && sn_currentUserData) {
			resultsContentRequest = new Ajax(provider, {
				method: 'get',
				onStateChange: function() { try { if ((this.transport.readyState != 4) || (this.transport.status == 200)) return; } catch(e) { queryGameResultsFailure(); }},
				onComplete: queryGameResultsSuccess
			});
			resultsContentRequest.request();
		}
		
		this.gameResultCount++;*/
	},

	
	loadGameResults : function(objRef) {
		trace('Challenge Mode: ' + objRef.challengeMode);
		trace('Game In Progress: ' + objRef.gameInProgress);
		trace('Challenge In Progress: ' + objRef.challengeInProgress);
		trace('GameWrapper.loadGameResults()');
		
		// enclosure - handle when query returns results...
		
		var queryGameResultsSuccess = function(response) {
			if (response != 'error')
			{
				//trace('-- GameWrapper -> FlashWrapper.showGameResultsScene(' + response + ')');
				//wrapperFlash.showGameResultsScene(response);
				////// Show End Game Screen /////////
				if(document.getElementById("endGameContainer")) {
					//document.getElementById("endGameAdIframe").src = "/gbl/adEndGame";
					//document.getElementById("endGameAdContainer").style.display = "block";
					sn_games_getGameEndResults(null, null, "notloggedin");
				}
				////////////////////////////////////

			}
			else
			{
				wrapperFlash.advance();
			}
			wrapperJS.gameInProgress = false;
			wrapperJS.challengeInProgress = false;
		}
		
		// enclosure - handle when query fails...
		// advance without showing any more results...
		
		var queryGameResultsFailure = function() {
		
			trace('-- GameWrapper: ERROR GETTING GAME RESULTS XML');
			trace('-- GameWrapper -> FlashWrapper.advance()');
			wrapperJS.gameInProgress = false;
			wrapperJS.challengeInProgress = false;
			wrapperFlash.advance();
		}
		
		var provider;
		var resultsContentRequest;
		
		var randomRefresh = Math.round(Math.random()*1000000000000);
		
		if (!sn_currentUserData)
		{
			// not logged in
			provider = '/games/act/getGameEndResults?type=notloggedin&random=' + randomRefresh;
			resultsContentRequest = new Ajax(provider, {
				method: 'get',
				onStateChange: function() { try { if ((this.transport.readyState != 4) || (this.transport.status == 200)) return; } catch(e) { queryGameResultsFailure(); }},
				onComplete: queryGameResultsSuccess
			});
			resultsContentRequest.request();
		}
		
		
		if (objRef.challengeMode)
		{
			// first time this is being called
			if (objRef.lastResultsScreen == '')
			{
				provider = '/games/act/getGameEndResults?type=challenge&playerUUID=' + sn_currentUserData.a + '&matchUUID=' + sn_currentMatchUUID + '&random=' + randomRefresh;
				objRef.lastResultsScreen = 'vsGameResults';
			}
			// if the last call was for the game results or the comment, then show comment screen again
			else if (objRef.lastResultsScreen == 'vsGameResults' || objRef.lastResultsScreen == 'vsGameResultsComment')
			{
				provider = '/games/act/getGameEndResults?type=challengeComment&playerUUID=' + sn_currentUserData.a + '&matchUUID=' + sn_currentMatchUUID + '&random=' + randomRefresh;
				objRef.lastResultsScreen = 'vsGameResultsComment';
			}
		}
		else
		{
			provider = '/games/act/getGameEndResults?type=score&playerUUID=' + sn_currentUserData.a + '&matchUUID=' + sn_currentMatchUUID + '&random=' + randomRefresh;
			objRef.lastResultsScreen = 'singlePlayerResults';
		}
		
		/*switch (this.gameResultCount) {
			
			case 0 :
				provider = '/games/act/getGameEndResults?type=challenge&playerUUID=' + sn_currentUserData.a + '&matchUUID=' + sn_currentMatchUUID;
				break;
				
			case 1 :
				provider = '/games/act/getGameEndResults?type=score&playerUUID=' + sn_currentUserData.a + '&matchUUID=' + sn_currentMatchUUID;
				break;
				
			default :
				break;
		}*/
		
		if (provider && sn_currentUserData) {
			resultsContentRequest = new Ajax(provider, {
				method: 'get',
				onStateChange: function() { try { if ((this.transport.readyState != 4) || (this.transport.status == 200)) return; } catch(e) { queryGameResultsFailure(); }},
				onComplete: queryGameResultsSuccess
			});
			resultsContentRequest.request();
		}
		
		objRef.gameResultCount++;
	},
	
	/**
	 * Called back from Flash Wrapper when a user pages through the 
	 * ending summary scenes following a game play. 
	 */
	onNextGameResultsScene : function() {
	
		trace('GameWrapper.onNextGameResultsScene()');
		
		this.queryAdDelivery('onNextGameResultsScene');
	},
	
	/**
	 * Called back from Flash Wrapper when a user submits a comment, 
	 * typically associated with certain game results scenes where a 
	 * user is able to enter commentary. 
	 * 
	 * @param 	comment The user's comment text.
	 */
	onSubmitComment : function(comment) {
		trace('GameWrapper.onSubmitComment()');
		trace('-- PHP: send comment to server: "' + comment + '"');
		
		// enclosure - handle when query returns results...
		var querySubmitCommentSuccess = function(response) {
			if (response != 'error')
			{
				trace('-- GameWrapper -> FlashWrapper.showGameResultsScene(' + response + ')');
				wrapperFlash.showGameResultsScene(response);
			}
			else
			{
				wrapperFlash.advance();
			}
			wrapperJS.gameInProgress = false;
			wrapperJS.challengeInProgress = false;
		}
		
		// enclosure - handle when query fails...
		// advance without showing any more results...
		
		var querySubmitCommentFailure = function() {
		
			trace('-- GameWrapper: ERROR GETTING SUBMIT COMMENT XML');
			trace('-- GameWrapper -> FlashWrapper.advance()');
			wrapperJS.gameInProgress = false;
			wrapperJS.challengeInProgress = false;
			wrapperFlash.advance();
		}
		
		var provider;
		var resultsContentRequest;
		var randomRefresh = Math.round(Math.random()*1000000000000);
		provider = '/games/act/addchallengecomment';
			
		if (provider && sn_currentUserData) {
			trace('Provider: ' + provider);
			
			submitCommentRequest = new Ajax(provider, {
				method: 'post',
				postBody: 'matchUUID=' + sn_currentMatchUUID + '&playerUUID=' + sn_currentUserData.a + '&message=' + comment + '&random=' + randomRefresh,
				onStateChange: function() { try { if ((this.transport.readyState != 4) || (this.transport.status == 200)) return; } catch(e) { querySubmitCommentFailure(); }},
				onComplete: querySubmitCommentSuccess
			});
			submitCommentRequest.request();
		}
		
		//sn_games_addChallengeComment(sn_currentMatchUUID, sn_currentUserData.a, comment);
	},
	

	hideFlashContainer : function() {
		wrapperFlashContainer.setStyle('left', '-2000px');
	},
	
	
	showFlashContainer : function() {
		wrapperFlashContainer.setStyles('');
	},
	
	
	/** 
	 * @return 	A timestamp of the current UTF time in milliseconds.
	 */
	getTimestamp : function() {
		return new Date().getTime();
	},
	
	toString : function() {
		return "[GameWrapper]";
	},
	
	sendOmniture : function(eventType) {
		trace('GameWrapper.sendOmniture()');
		trace('Omniture Calls: ' + this.omnitureCalls);
		
		var s=s_gi('nbcuglobal,nbcuusanetworkd,nbcuusanetbu'); 
		
		// set the basename if it's blank
		if (this.baseOmnitureTitle == '')
		{
			this.baseOmnitureTitle = s.pageName;
		}
		// dont call omniture again if it's just been called (on page load)
		if (this.omnitureCalls == 0)
		{
			this.omnitureCalls++;
		}
		else
		{
			trace('Making Omniture Call: ' + eventType);
			var additionalOmnitureData = '';
			if (eventType == 'ROUND')
			{
				additionalOmnitureData = ' - new round';
			}
			 
			s.pageName= this.baseOmnitureTitle + additionalOmnitureData;
			void (s.t());
			
			this.omnitureCalls++;
		}
	}
});

