/***
* ------------------------------------ GLOBALS ---------------------------------------------
***/

var PRECISE_BUILD_VERSION = "2009.07.01";


//alert ( "LOADING GAME LOGIC" );

var WILD_CARD_CATEGORY_ID = 21;

var WILD_CARD_CAPTION = "Wild Card";


/**
* Is "true" if the Flash game control/status bar is loaded.
*/
var m_bottomGameInfoBarLoaded = false;

/**
* Is "true" if the Flash question panel is loaded.
*/
var m_questionPanelLoaded = false;

/**
* True if the currently displaying video is a You Tube video.
*/
var m_isYouTubeVideo = false;

/**
* SLW 601.  True if the currently displaying video is a PopJax video.
*/
var m_isPopJaxVideo = false;

/**
* Is "true" if the current you tube video (the one for the question being displayed) is
* ready and the user can start answering questions.
*/ 
var m_youTubeVideoReady = false;
   
/**
* Is "true" if the current you tube video (the one for the question being displayed) is
* ready and the user can start answering questions and the Flash question panel has
* been "told" that the video is ready.
*/ 
var m_gameKnowsYouTubeVideoLoaded = false;

/**
* Is "true" if the game is over.
*/
var m_gameOver = false;


/**
* This is the "user" object.  It came from the server.
*/
var m_userInfo = null;


/**
* The row and column of the selected game piece.  In our code, we use 1, 1 as the upper left-hand corner
* game piece.  But the back end starts at 0, 0 - so remember this when talking to the back end!!!
*/
var m_selectedGamePieceCol = -1;
var m_selectedGamePieceRow = -1;



/**
* This is only true after the user clicked on a game cell and while we're waiting for the question to be served up to us
* by the back end.
*/
var m_loadingQuestion = false;

/**
* True once the question for the clicked-on game piece has been loaded into the Flash question panel.
*/
var m_questionLoadedIntoQuestionPanel = false;

/**
* The SWF name for the game control/info bar along the bottom of the page.
*/
var bottomGameInfoBarSwf = "/content/game/GameInfoBar.swf?affColor=0x111111";
   
/**
* The "Question" XML (model) object.
*/
var m_currentQuestionResponseXml = null;

var m_currentQuestionResponseObject = null;

/**
* The "Question" JavaScript (model) object.
*/
var m_currentQuestionObject = null;

/**
* "True" if the You Tube video is loaded.
*/
var m_youTubePlayerLoaded = false;

/**
* This contains the "Game" JavaScript (model) object.  It is null until the new game has been returned to us by 
* the back end.
*/
var m_gameData = null;

/**
* This is "true" after a game has been loaded into the gameboard.
*/
var m_gameDataLoadedIntoGameBoard = false;

/**
* This is "true" if we started to download the question panel.
*/
var m_loadedQuestionPanel = false;

/**
* This is "true" if we got a "game already played" message in response to a start game.
*/
var m_gameAlreadyPlayed = false;


var m_debugStr = "";

var m_didEndGame = false;

var m_rulesShowing = false;

var m_gameboardReadyForPlay = false;

var m_averageScoreForThisGame = null;

var m_playerPercentagePosition = null;

//var m_idOfQuestionBeingAnswered = null;



/**
* FAKE GAME DATA!!!
**/
   var game = [
      { row:1, col:1, videoPath:"resources/largeVideos/12_TV_Ads.flv", title:"TV Ads", videoId:"mNazT3GY7z0" },
	  { row:1, col:2, videoPath:"resources/largeVideos/12_TV_Ads.flv", title:"TV Ads", videoId:"mNazT3GY7z0"  },
	  { row:1, col:3, videoPath:"resources/largeVideos/12_TV_Ads.flv", title:"TV Ads", videoId:"mNazT3GY7z0"  },
	  { row:2, col:1, videoPath:"resources/largeVideos/12_TV_Ads.flv", title:"TV Ads", videoId:"mNazT3GY7z0"  },
	  { row:2, col:2, videoPath:"resources/largeVideos/12_TV_Ads.flv", title:"TV Ads", videoId:"mNazT3GY7z0"  },
	  { row:2, col:3, videoPath:"resources/largeVideos/12_TV_Ads.flv", title:"TV Ads", videoId:"mNazT3GY7z0"  },
	  { row:3, col:1, videoPath:"resources/largeVideos/12_TV_Ads.flv", title:"TV Ads", videoId:"mNazT3GY7z0"  },
	  { row:3, col:2, videoPath:"resources/largeVideos/12_TV_Ads.flv", title:"TV Ads", videoId:"mNazT3GY7z0"  },
	  { row:3, col:3, videoPath:"resources/largeVideos/12_TV_Ads.flv", title:"TV Ads", videoId:"mNazT3GY7z0"  }
   ];


/**
* The width of the embedded video.
*/
//var m_videoWidth = "500px";

/**
* Height of the embedded video.
*/
//var m_videoHeight = "400px";

var m_dailyPoints   = null;
var m_weeklyPoints  = null;
var m_monthlyPoints = null;

var m_averageScore  = 0 ;
var m_top10PctScore = 0 ;

var m_showedDailyDrawingAnimation = false;
var m_showedWeeklyDrawingAnimation = false;
var m_showedMonthlyDrawingOneAnimation = false;
var m_showedMonthlyDrawingTwoAnimation = false;

/**
* These can get set to true if the player gets past one of these thresholds yet is playing POP4 and POPSPIN and hasn't yet
* "won" that game.
*/
var m_delayedShowDailyDrawingAnimation = false;
var m_delayedShowWeeklyDrawingAnimation = false;
var m_delayedShowMonthlyDrawingOneAnimation = false;
var m_delayedShowMonthlyDrawingTwoAnimation = false;


var m_gameInfo = null;

var m_selectedGameCell = null; // getGameCellByPosition ( col, row )

var m_lifetimeScore = null;

var m_currentLevel = null;

function ASSERT_THROW ( assertion, throwMessage ) {
	if ( assertion ) {
		var throwMessageWithQuestionId = throwMessage;
		if ( m_currentQuestionObject != null ) {
			throwMessageWithQuestionId = " qid=" + m_currentQuestionObject.id + " " + throwMessage ;
		}
		throw throwMessageWithQuestionId;
	}
}

function suppressDrawingWinnerAnimations () {
	var doSuppress = true;
	
	try {
		/*if ( this["m_suppressDrawingWinnerAnimations"] ) {
			doSuppress = this["m_suppressDrawingWinnerAnimations"];
		}
		*/
		if ( ! m_suppressDrawingWinnerAnimations ) {
			doSuppress = false;
		}
	} catch ( exc ) 
	{
		doSuppress = true;
	}
	
	return doSuppress;
}

/**
* HOTFIX TO HANDLE VIDEOS NOT LOADING... !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/

var SHOW_SKIP_BUTTON_AFTER_THIS_MANY_MS = 10000;

var m_checkIfVideoLoadedYetTimerId = null;

function checkIfVideoLoadedYet () {
	m_checkIfVideoLoadedYetTimerId = null;
	//alert ( "VIDEO LOADED YET? : " + m_toldGameThatVideoIsPlaying );
	if ( m_toldGameThatVideoIsPlaying == false ) {
	   var skipQuestionDiv = document.getElementById ( "skipQuestionDiv" );
	   skipQuestionDiv.style.display = "block";
	   m_videoLoadStatus = "timeout";
		
		/**
		* Hide the "Loading Video" animation.
		*/
		hideLoadingVideoOverlay ();
		
	}
}


function clearCheckForLoadedVideoTimer () {
	if ( m_checkIfVideoLoadedYetTimerId ) {
		clearTimeout(m_checkIfVideoLoadedYetTimerId);
		m_checkIfVideoLoadedYetTimerId = null;
	}
	
}

function skipQuestion () {
	
    // Store the time that the user answered the question
	//m_questionAnsweredTime = new Date ();
	calculateVideoLoadAndQuestionAnswerTimings();
	
	
	clearCheckForLoadedVideoTimer ();
	
	//alert ( "SKIP QUESTION correct_answer: " + m_currentQuestionObject.correct_answer );
	
	dataService_getAnswer ( handleAnswerReturnedAfterUserSkipQuestion, m_selectedGamePieceCol - 1, m_selectedGamePieceRow - 1, 
	   m_currentQuestionObject.correct_answer, 1, m_videoLoadedTime, m_userAnswerQuestionTime, m_videoLoadStatus  );
	m_awaitingResponseToGetAnswerMessage = true;
	
}

function skipQuestionInPreviewMode () {

    // Store the time that the user answered the question
	//m_questionAnsweredTime = new Date ();
	
	//alert ( " skipQuestionInPreviewMode called" );
	
	calculateVideoLoadAndQuestionAnswerTimings();

//alert ( "survived calculateVideoLoadAndQuestionAnswerTimings" );

	clearCheckForLoadedVideoTimer ();

//alert ( "survived clearCheckForLoadedVideoTimer" );

	goBackToGameBoard ();
	
//alert ( "survived goBackToGameBoard " );
	
	//alert ( "SKIP QUESTION correct_answer: " + m_currentQuestionObject.correct_answer );
	
/*	
	alert ( " m_currentQuestionObject.id: " + m_currentQuestionObject.id );
	
	try {
		   dataService_getAnswerPreview ( handleAnswerReturnedAfterUserSkipQuestion, m_currentQuestionObject.id, 
					m_currentQuestionObject.correct_answer, 1  );
	//fromFlash_getAnswerPreview ( m_currentQuestionObject.id, m_currentQuestionObject.correct_answer, 1  );
	} catch ( exc ) {
		alert ( "EXC: " + exc );
	}
*/	
	
}

function handleAnswerReturnedAfterUserSkipQuestion ( data, xml ) {
	
	
	/**
	* Only record this with Google Analytics if this wasn't a "bonus" question (the one that hangs off the main question).
	*/
   if ( m_isAnswerToBonusQuestion == false ) {		
		/**
		* Another question within the game was answered.  Depending
		* on which # question this is, it might trigger a call to Google Analytics to
		* track this event.
		*/
		anotherQuestionWasAnswered ();
   }	
	
//alert ( " foo data back " ); window.doThisNow();

   /**
   * Mister Gorbachev, "tear down that wall" - Reagan.
   * 
   * Oh!  I mean, remove the overlay that prevented the user from clicking on the video!
   */
   hideClearVideoOverlayDiv ();
   
   if ( data.code == AnswerResponse.CODE_ANSWER_CORRECT ||
        data.code == AnswerResponse.CODE_GAME_WON || 
	    ( data.code == AnswerResponse.CODE_BLACKOUT_FINISH && data.isAnswerCorrect == "true" ) ) {
		
	  m_answerWasCorrect = true;
   
   } else {
      m_answerWasCorrect = false;
   }
	
   if ( data.code == AnswerResponse.CODE_GAME_WON || 
		data.code == AnswerResponse.CODE_GAME_LOST ||
		data.code == AnswerResponse.CODE_BLACKOUT_FINISH ) {
	
	   m_gameOverData = data;
	   
	   m_gameOver = true;
   }
   
   if ( data.average ) {
	   m_averageScoreForThisGame = Math.round(data.average);
   }
   if ( data.percentile ) {
	   var playerPercentile = Number(data.percentile) * 100;
	   playerPercentile = Math.round(playerPercentile);
	   var playerPercentage = 100 - playerPercentile;
	   if ( playerPercentage < 1 ) {
		   playerPercentage = 1;
	   }
	   m_playerPercentagePosition = playerPercentage;
   }
   
//alert ( " GAME OVER? " +  m_gameOver );

	if ( m_gameId == null ) {
		if ( data.gameId != null && data.gameId != "null" && data.gameId != "undefined" ) {
			m_gameId = data.gameId;
		}
	}

   /**
   * Increment the "current score of the game" value.
   */
   if ( m_answerWasCorrect ) {
      m_currentGameScore = Number(data.score);
   }
	
   nextQuestion ();	
}

/**
* END OF HOTFIX!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
**/


/***
* ------------------------------------ HANDLE "REGISTER" OR "LOG IN" BEFORE STARTING A GAME ----------------
***/
function registeredAndLoggedInNowStartGame () {
	// alert ( "REG AND LOGGED IN, START GAME" );
	reg_hideRegistrationScreen ();
	
	//restartTheGameWithLoginCredentials ();
	
}

var m_startGameCalled = false;

function restartTheGameWithLoginCredentials () {
//alert ( "RE START GAME AGAIN NOW WITH USER LOGGED IN" );
	m_gameDataLoadedIntoGameBoard = false;
	m_startGameParms.pjuid = m_pjuid;
	m_startGameCalled = false;
	// loadPage ();
	dataService_getUser ( userInfoReady, m_pjuid );
}


/***
* ------------------------------------ "LOADING" CONTENT INTO PAGE ----------------
***/

/**
* This starts loading the page and its data.
*/
function loadPage ( hideUserLookupIfNull ) 
{
   /* IF the 'hide' parameter is omitted, set it to false */
   if ( !hideUserLookupIfNull )
     hideUserLookupIfNull = false ;


   /**
   * Ajax call.  If the user is logged in, get their name, email address, games played, lifetime score, etc.  Only once we've got the
   * user's data to we invoke a "start game" transaction.
   */
   if ( ((m_pjuid == null) || (m_pjuid == "null")) && hideUserLookupIfNull )
   {
     dataService_getUser ( nullUserInfoReady, m_pjuid );
   }
   else
     dataService_getUser ( userInfoReady, m_pjuid );
	  
   /**
   * Load the bottom game control/info panel.  We don't know if the user's data will come back 
   * to us first or this panel will load first, so only once both the data has arrived and the panel is 
   * loaded to we load the panel with data and then start a new game.
   */
   embedFlashContent ( "bottomGameInfoPanel", "bottomGameInfoPanelContainer", bottomGameInfoBarSwf, 
					   "100%", "100%", "#ffffff", "transparent", "exactFit" );

   
   /**
   * Init the dialogs.
   */
  // alert ( "init the dialogs" );
   
   try {
	   
	   if ( m_isFacebookGame == false ) {
         reg_initRegistrationPage ();
         login_initLoginPage ();
         reg_setAfterRegistrationCallback (afterRegistrationCallback);	   
         login_setAfterLoginCallback (afterLoginCallback);

         shareQuestion_initRegistrationPage ();
      //shareGame_initShareQuestionPage ();
         shareGame_initRegistrationPage ();
	   }
   } catch ( exc ) {
	   printTrace ( "EXC: " + exc );
   }
   

}

// alert ( "LOAD PAGE LOADED" );
	
function loadRestOfPage () {

	  
   /**
   * Load the Flash question panel.
   */
   embedFlashContent ( "questionPanel", "questionPanelContainer", questionPanelSwf, 
					   "100%", "100%", "#ffffff", "transparent", "exactFit" );
	  
}


/**
* This is called once the server returns to us the user's data.
*/
function userInfoReady ( data, xml ) {

   m_userInfo = data;

// document.getElementById("userNameLoggedIn").innerHTML = m_pjusername;

   var userNameLoggedIn = document.getElementById ( "userNameLoggedIn" );
	if ( userNameLoggedIn && m_userInfo.name && m_userInfo.name != "" && m_userInfo.name.indexOf ( "anonymous" ) < 0 && m_userInfo.name.indexOf ( "fbUser" ) ) {
		if ( document.getElementById("logOutForm2") ) 
		{
			document.getElementById("logOutForm2").style.display = "block";	
			var logInForm  = document.getElementById ("loginform2");
			if ( logInForm )
			  logInForm.style.display  = "none";
		}
		m_pjusername = userNameLoggedIn.value;
		userNameLoggedIn.innerHTML = m_userInfo.name;
		//alert ( "ASSIGN NAME" );
	}
							
   if ( m_fbname != null ) {
	   m_userInfo.name = m_fbname;
   }
	
	
   
   if ( m_userInfo.dailyScore != null && m_userInfo.dailyScore != "null" ) {
	   m_dailyPoints = Number( m_userInfo.dailyScore );
   }
   
   if ( m_userInfo.weeklyScore != null && m_userInfo.weeklyScore != "null" ) {
	   m_weeklyPoints = Number( m_userInfo.weeklyScore );
   }

   if ( m_userInfo.monthlyScore != null && m_userInfo.monthlyScore != "null" ) {
	   m_monthlyPoints = Number( m_userInfo.monthlyScore );
   }
   

   if ( m_userInfo.lifetimeScore != null && m_userInfo.lifetimeScore != "null" ) {
	   m_lifetimeScore = Number(m_userInfo.lifetimeScore);
	   m_currentLevel = calculateLevel ( m_lifetimeScore );
   }
	
	/**
	* New SLW 9/9/08. This is for those times that the game doesn't know the user's pjuid but the back end does.  And it is an anonymous user.
	*/
	if ( m_userInfo.id ) {
		m_pjuid = m_userInfo.id;
	}
	// m_pjuid 
   

   // m_dailyPoints
   
  // alert ( " m_weeklyPoints: " + m_weeklyPoints );
	 
   /**
   * If the bottom control/info bar is loaded, cause the user info to be loaded into it and the "start game" transaction
   * to be sent to the back end.
   */
   if ( m_bottomGameInfoBarLoaded ) {
      setTimeout ( loadUserInfoIntoBottomInfoPanel, 10 );
   }	  
}

function nullUserInfoReady ( data, xml ) 
{
    m_userInfo = data;
    var userNameLoggedIn = "anonymous" ;

   if ( m_userInfo.dailyScore != null && m_userInfo.dailyScore != "null" ) {
	   m_dailyPoints = Number( m_userInfo.dailyScore );
   }
   
   if ( m_userInfo.weeklyScore != null && m_userInfo.weeklyScore != "null" ) {
	   m_weeklyPoints = Number( m_userInfo.weeklyScore );
   }

   if ( m_userInfo.monthlyScore != null && m_userInfo.monthlyScore != "null" ) {
	   m_monthlyPoints = Number( m_userInfo.monthlyScore );
   }
   

   if ( m_userInfo.lifetimeScore != null && m_userInfo.lifetimeScore != "null" ) {
	   m_lifetimeScore = Number(m_userInfo.lifetimeScore);
	   m_currentLevel = calculateLevel ( m_lifetimeScore );
   }

   /**
   * If the bottom control/info bar is loaded, cause the user info to be loaded into it and the "start game" transaction
   * to be sent to the back end.
   */
   if ( m_bottomGameInfoBarLoaded ) {
      setTimeout ( loadUserInfoIntoBottomInfoPanel, 10 );
   }	  
}



/**
* This function is called once the user's info has been retrieved from the back end.
* This happens at the beginning of a game.
*
* NOTE: This function "kicks off" a "start game" message to the back end.
*/   
function loadUserInfoIntoBottomInfoPanel () {
	  
//alert ( "LOAD USER INFO INTO BOTTOM PANEL" );

   var bottomGameInfoPanel = document.getElementById ( "bottomGameInfoPanel" );
   
   var playerName = m_userInfo.name;
	
	/**
	* Added if ( m_pjuid == null, then blank-out the name ).  This way, anonymous players' names don't appear.
	*/
   if ( playerName == null || playerName == "null" || m_pjuid == null || m_pjuid == "null" ) {
	   playerName = ""; 
   }
	
	if ( playerName.indexOf ( "anonymous" ) >= 0 ) {
		playerName = ""; 
	}
   
   var lifetimeScore = m_userInfo.lifetimeScore;
   if ( lifetimeScore == null || lifetimeScore == "null" ) {
	   lifetimeScore = "";
   } else {
	  // m_lifetimeScore = lifetimeScore;
   }
   
   var dailyScore = m_userInfo.dailyScore;
   if ( dailyScore == null || dailyScore == "null" ) {
	   dailyScore = "";
   } else {
	  // m_lifetimeScore = lifetimeScore;
   }
   
   /*  Trac # 632 - ALSO get Score-to-Beat info now */


   var totalNumberOfGamesPlayed = m_userInfo.totalNumberOfGamesPlayed;
   if ( totalNumberOfGamesPlayed == null || totalNumberOfGamesPlayed == "null" ) {
	   totalNumberOfGamesPlayed = "";
   }
   
 // alert ( " dailyScore: " + dailyScore );

   //bottomGameInfoPanel.setUserInfo ( playerName, "",  dailyScore ); //,  totalNumberOfGamesPlayed );
   
   try
   {
     bottomGameInfoPanel.setUserInfo     ( playerName  );  
     bottomGameInfoPanel.setScore        ( "0" );
     bottomGameInfoPanel.showScores      ( );
   }
   catch ( exc )
   {
   }
   
 //alert ( "ABOUT TO GET GAME AGAIN" );
 
	   
   // var m_startGameParms = new Object ();
   
   if ( m_startGameCalled == false ) {
		
		/**
		* Ensure "reportingOrigin" and "reportingRef" are added to the start game message.
		*/
		addOriginReporting ( m_startGameParms );
      dataService_startGame ( handleGameStarted, m_startGameParms );
	  m_startGameCalled = true;
   }
   
}


function playerHasPlayedGame () {

//alert ( " PLAYER HAS PLAYED GAME" );
//alert ( " m_gameData.gameDetails.playedGame: " + m_gameData.gameDetails.playedGame );

	if ( m_gameData ) {
		// playedGame="false"
		if ( m_gameData.gameDetails && m_gameData.gameDetails.playedGame && m_gameData.gameDetails.playedGame == "true" ) {
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

/**
* This callback is called once the back end has returned to us a "new game" and its
* data.
*/   
function handleGameStarted ( data, xml ) {
	
	/**
	* Reset the counter used in determining whether or not to report a question
	* answer event with Google Analytics.
	*/
	resetQuestionCount ();
	
   
   // Record when the game started.
   m_gameStartTime = new Date();
   
   
   m_gameAlreadyPlayed = false;
   
   m_gameData = data;
   
  // m_gameData = null;
  
   ASSERT_THROW ( m_gameData == undefined || m_gameData == null, "handleGameStarted: game data is missing!" );
   
  // alert ( " playerHasPlayedGame: " + playerHasPlayedGame () );
   
   
/*
   if ( m_gameData.code == "GAME_OK" ) {
	   
	   if ( m_gameData != null && m_gameBoardLoaded && ( m_gameDataLoadedIntoGameBoard == false ) ) {
		  var largeVideoPath = m_gameData.gameDetails.largeVideoPath;
		  var gameName = m_gameData.gameDetails.gameName;
	
		  var gameboardNew = document.getElementById ( "gameboardNew" );
		  gameboardNew.loadHitGameCells ( largeVideoPath, gameName );
		  
		  m_gameDataLoadedIntoGameBoard = true;
	   }
	   
   } else { 
	  
	  m_gameAlreadyPlayed = true;
	  var gameboardNew = document.getElementById ( "gameboardNew" );
	  gameboardNew.showEndOfGameBack ();
	  
   }

*/
   
   if ( m_gameData != null && m_gameBoardLoaded && ( m_gameDataLoadedIntoGameBoard == false ) ) {
	
	//alert ( " handle game started" );
	   loadGameIntoGameboard ();
   }   
   
   
   
}
   
function getGameCellByPosition ( col, row ) {
	
	var colsPerRow = 3;
	
	if ( m_currentGameType == GAME_TYPE_HIT ) {
		colsPerRow = 3;
	} else {
		colsPerRow = 4;
	}
	
	var rowsToSkip = row - 1;
	var cellsToSkip = ( rowsToSkip * colsPerRow );
	cellsToSkip += col - 1;
	
	var gridCell = m_gameData.gridCells.gridCells[cellsToSkip];
	
	return gridCell;
}
								
function loadGameIntoGameboard () {

//alert ( " m_gameData.code: "  + m_gameData.code + " m_gameAlreadyPlayed: " + m_gameAlreadyPlayed );


   if ( m_gameData.code == "GAME_OK" ) 
   {
      m_averageScore  = m_gameData.averageScore ;
      m_top10PctScore = m_gameData.topTenPercentScore ;
	  	  
      if ( m_averageScore == undefined  || m_averageScore == null  )
        m_averageScore = "795" ;
      if ( m_top10PctScore == undefined || m_top10PctScore == null )
        m_top10PctScore = "1393" ;
	 
      var bottomGameInfoPanel = document.getElementById ( "bottomGameInfoPanel" );	
      if (bottomGameInfoPanel) 
	  {
         try
		 {
           bottomGameInfoPanel.setScoresToBeat ( m_averageScore,  m_top10PctScore) ;
		 }
		 catch ( exc )
		 {
		 }
	  }
	   
//alert ( "GOT GAME OK" );
	   
      if ( m_currentGameType == GAME_TYPE_HIT ) {
	      var largeVideoPath = m_gameData.gameDetails.largeVideoPath;
		  var largeImagePath = m_gameData.gameDetails.largeImagePath;
		 		 
         ASSERT_THROW (  largeVideoPath == undefined || largeVideoPath == null , "loadGameIntoGameboard: largeVideoPath value missing!" );
         ASSERT_THROW (  largeImagePath == undefined || largeImagePath == null , "loadGameIntoGameboard: largeImagePath value missing!" );

	     var gameName = m_gameData.gameDetails.gameName;

         ASSERT_THROW (  gameName == undefined || gameName == null , "loadGameIntoGameboard: Game Name Missing" );

         ASSERT_THROW (  ( m_gameData.gridCells.gridCells == undefined || m_gameData.gridCells.gridCells == null || 
						  m_gameData.gridCells.gridCells.length == 0 ) , "loadGameIntoGameboard: Game Cells missing!" );


		 
         for ( var idx = 0; idx < m_gameData.gridCells.gridCells.length; idx++ ) {
			 var gridCell = m_gameData.gridCells.gridCells[idx];
			 gridCell.setVideoPath (largeVideoPath);
			 gridCell.setLargeImagePath (largeImagePath);
			 gridCell.setCaption (gameName);
		 }
		 
//alert ( " cells " + m_gameData.gridCells.toXml () );

/*
	    this.adServerLocation = xml.getAttribute ( "adServerLocation" );
		this.adDisplayDuration = xml.getAttribute ( "adDisplayDuration" );
		this.allowAdSkip = xml.getAttribute ( "allowAdSkip" );

*/
	   
	     var gameboardNew = document.getElementById ( "gameboardNew" );
		  
//alert ( "AD DATA: " + m_gameData.adServer );

        if ( m_gameData.adServer ) {
			  m_adDartId = m_gameData.adServer.adServerLocation;
			  m_minimumMSToShowAd = m_gameData.adServer.adDisplayDuration;
			  m_allowAdSkip = m_gameData.adServer.allowAdSkip;
			  
		  }
		  
		//  alert ( m_gameData.gridCells.toXml () );
		 
        if ( m_adDartId ) {
			  gameboardNew.loadHitGameCells ( m_gameData.gridCells.toXml (), m_adDartId, m_minimumMSToShowAd, m_allowAdSkip ); 
		  } else {
	        gameboardNew.loadHitGameCells ( m_gameData.gridCells.toXml () ); 
		  }
		 

      } else {
		  
/*
var WILD_CARD_CATEGORY_ID = 21;

var WILD_CARD_CAPTION = "Wild Card";

*/
		  
		  var gameCategories = m_gameData.gameCategories;
		  
	//	  alert ( "CATS: " + gameCategories );
		  
		  // 21_Wild_Card.jpg  "Wild Card"
		  
		  var pathToVideos = "";
		  var wildCardCells = new Array ();
		  
          for ( var idx = 0; idx < m_gameData.gridCells.gridCells.length; idx++ ) {
			 var gridCell = m_gameData.gridCells.gridCells[idx];
			 var categoryId = gridCell.categoryId;
			 
			 if ( Number(categoryId) == WILD_CARD_CATEGORY_ID ) {
				 wildCardCells.push(gridCell);
			 } else {
			    var category = gameCategories.getCatgoryById ( categoryId );
				var lastSlashIndex = category.smallVideoPath.lastIndexOf("/");
				 
				if ( lastSlashIndex >= 0 ) {
				   pathToVideos = category.smallVideoPath.substr(0, lastSlashIndex+1);
				}
				
			    gridCell.setVideoPath (category.smallVideoPath);
			    gridCell.setCaption (category.name);
				
			 }
		  }
		  
		  for ( var idx = 0; idx < wildCardCells.length; idx++ ) {
			  var gridCell = wildCardCells[idx];
			  gridCell.setVideoPath ( pathToVideos + "21_Wild_Card.flv" );
			  gridCell.setCaption ( WILD_CARD_CAPTION );
		  }
		  
	      var gameboardNew = document.getElementById ( "gameboardNew" );
		  
		//  alert ( "m_gameData.gridCells.toXml (): " + m_gameData.gridCells.toXml () );
	      
        if ( m_adDartId ) {
			  gameboardNew.loadPop4GameCells ( m_gameData.gridCells.toXml (), m_adDartId, m_minimumMSToShowAd, m_allowAdSkip ); 
		  } else {
	        gameboardNew.loadPop4GameCells ( m_gameData.gridCells.toXml () ); 
		  }
		  
		  //largeVideoPath, gameName );
		  
		  
		 // alert ( " WILD CARDS: " + wildCardCells.length );
		  
		  /*
			 var category = gameCategories.getCatgoryById ( categoryId );
			
			//alert ( "cell: " + idx + " CATEGORY FOR id: " + categoryId " : " + category );
			
		//	alert ( " category.smallVideoPath: " + category.smallVideoPath );
			
			 
			// alert ( "CELL: " + gridCell.toXml() );
		  }
		  */
		  
		  
		//  alert ( "CATS: " + gameCategories );
		  
		  
		 // alert ( "LOAD POP4" );
		  // loadPop4GameCells
	  }
	  
	  m_gameDataLoadedIntoGameBoard = true;
	  
   } else { /* Otherwise, game was already played!!! */
   
 //alert ( "GAME WAS ALREADY PLAYED" );
  
	  m_gameAlreadyPlayed = true;
	  var gameboardNew = document.getElementById ( "gameboardNew" );
	  printTrace ( "pre: gameboardNew.showEndOfGameBack" );
	  gameboardNew.showEndOfGameBack ();
	  printTrace ( "post: gameboardNew.showEndOfGameBack" );
	  
	  m_gameDataLoadedIntoGameBoard = true;
   }

}


/**
* This is called once the landing page's video wall "HIT GAMES" data is retrieved.
*/	
//function handleLandingPageHitGamesListLoaded ( data, xml ) {
//   
//   // alert ( "HIT GAMES STUFF READY data: " + data );
//	 
//	var landingPageHitGames = data; // data.landingPageHitGames.landingPageHitGames;
//}





/***
* ------------------------------------ "ASYNCHRONOUS LOADING OF FLASH/MODULES" INTO PAGE ----------------
***/

/**
* This function can be subclassed by different HTML pages where the game resides.  When it is called, you can do whatever
* you want to do.  One option is to reposition the info bar to its correct position.
*/
function handleInfoBarLoaded () {
}

/**
* Once a Flash component (one of the pieces of the game) loads into the page, it calls this "moduleLoaded" function.
* The "moduleId" allows us to know what module is loaded so we can execute the appropriate code.
*/
function moduleLoaded ( moduleId ) {
	
//alert ( "LOADED: " + moduleId );

   /**
   * The gameboard has been loaded.
   */
   if ( moduleId == "gameboard" ) {
	   m_gameBoardLoaded = true;	   
   }
   
   if ( m_gameData != null && m_gameBoardLoaded && ( m_gameDataLoadedIntoGameBoard == false ) ) {
	   
//alert ( "MODULE LOADED" );

	   loadGameIntoGameboard ();
	   
	   /*
	  var largeVideoPath = m_gameData.gameDetails.largeVideoPath;
	  var gameName = m_gameData.gameDetails.gameName;

	  var gameboardNew = document.getElementById ( "gameboardNew" );
	  gameboardNew.loadHitGameCells ( largeVideoPath, gameName );
	  
	  m_gameDataLoadedIntoGameBoard = true;
	  */
   }
	      
   
   /**
   * The game control panel/info panel along the bottom of the page has loaded.
   */
   if ( "bottomGameInfoPanel" == moduleId ) {	   
      m_bottomGameInfoBarLoaded = true;
		
		/**
		* Here is our chance to reposition the info bar.
		*/
		handleInfoBarLoaded ();
		
	  if ( m_userInfo != null ) {
	     setTimeout ( loadUserInfoIntoBottomInfoPanel, 10 );
	  }
   }
  
   if ( m_gameBoardLoaded && m_bottomGameInfoBarLoaded && ( m_loadedQuestionPanel == false ) ) {
	   
	   m_loadedQuestionPanel = true;
	   
	  /**
	  * Once the gameboard and bottom panel are showing, we can load the "question" panel in the background.
	  */
	  loadRestOfPage ();
   }
  
   /**
   * The Flash question panel has loaded.
   */
   if ( "questionPanel" ==  moduleId ) {
      m_questionPanelLoaded = true;
		
		/**
		var questionPanel = document.getElementById ( "questionPanel" ); 
		*/
		//alert ( "WOULD LOAD SKIN HERE" );
		//if ( m_questionPanelSkin != null ) {
		//	try {
		//		var questionPanelToSkin = document.getElementById ( "questionPanel" );
		//		questionPanelToSkin.applySkin( m_questionPanelSkin );
		//	} catch ( excLoadingSkin ) {
		//		//alert ( "EXC: " + excLoadingSkin );
		//	}
		//}
	 
      if ( m_currentQuestionResponseXml && m_questionPanelLoaded ) {
	     delayedShowQuestion ();
	  }
	
	  if ( m_youTubeVideoReady && m_questionPanelLoaded && ( m_gameKnowsYouTubeVideoLoaded == false ) ) {
	      m_youTubeVideoReady = true;
		  m_gameKnowsYouTubeVideoLoaded = true;
		  unMuteYouTubeVideo ();
	      var questionPanel = document.getElementById ( "questionPanel" ); 
		  printTrace ( "pre: questionPanel.youTubeVideoCueued" );
	    //  alert ( "foo" );
		  questionPanel.youTubeVideoCueued ();
		  printTrace ( "post: questionPanel.youTubeVideoCueued" );
		  
		  /**
		  * This handles the situation where the user answered the question before the you tube API told us the video was ready.
		  */
		  if ( m_answerFromUser ) {
			  m_getAnswerDataServiceToCall ( handleAnswerReturned, m_selectedGamePieceCol - 1, m_selectedGamePieceRow - 1, 
				  m_answerFromUser, m_scaleFromAnswer, m_videoLoadedTime, m_userAnswerQuestionTime, m_videoLoadStatus  );
			  m_answerFromUser = null;
		  }
	  }
   }
}
   
/***
* ------------------------------------ "SKINNING" FUNCTIONALITY ----------------
***/

function fromFlash_applyQuestonPanelSkin ( skin ) {
	//alert ( "APPLY SKIN" );
	m_questionPanelSkin = skin;
}

/***
* ------------------------------------ "GAME INFO BAR" FUNCTIONALITY ----------------
***/


function fromFlash_endGame () {
	//alert ( "CALLED" );
	setTimeout ( delayedEndGame, 100 );
}

function delayedEndGame () {
	//alert ( "END GAME" );
	handleBeforeSendEndGameMessage ();
	dataService_endGame ( handleGameEnded );
}

function handleGameEnded ( data, xml ) {
	//alert ( "GAME ENDED! " + data );
	if ( m_gameId == null ) {
		if ( data.gameId != null && data.gameId != "null" && data.gameId != "undefined" ) {
			m_gameId = data.gameId;
		}
	}
	
	m_didEndGame = true;
	
	try {
	   var gameboardNew = document.getElementById ( "gameboardNew" );
	   printTrace ( "pre: gameboardNew.pauseSound" );
	   gameboardNew.pauseSound ();
	   printTrace ( "post: gameboardNew.pauseSound" );
	} catch ( exc ) {
		// Hide it!
	}
	
	//gameboardNew.showEndOfGameBack ();
	handleGameEndedByUser ( m_gameId );
}

function handleBeforeSendEndGameMessage () {
   defaultHandleBeforeSendEndGameMessage ();
}

function defaultHandleBeforeSendEndGameMessage () {
	// alert ( "default handle before end game" );
   var gameboard = document.getElementById ( "gameboardNewContainer" );
   gameboard.style.left = 2000 + "px"; //"100px"; //display = "block";
   gameboard.style.display = "none";
   
   var singleQuestionPanel = document.getElementById ( "singleQuestionPanel" );
   singleQuestionPanel.style.left = 2000 + "px"; //"100px"; //display = "block";
   singleQuestionPanel.style.display = "none";
   
   
   showEndGameAnimation ();   
}

function defaultHandleGameEndedByUser ( gameId ) {
	// alert ( "DEFAULT GAME ENDED BY USER" );
	
	//alert ( "UNSUBCLASSED GAME ID: " + gameId );
	//var gameboardNew = document.getElementById ( "gameboardNew" );
	
//   var gameboard = document.getElementById ( "gameboardNewContainer" );
//   gameboard.style.left = 2000 + "px"; //"100px"; //display = "block";
//   gameboard.style.display = "none";

//alert ( "SHOULD BE GONE" );

	//gameboardNew.innerHTML = "";
	//gameboardNew.pauseSound ();
	//gameboardNew.showEndOfGameBack ();		
}

function handleOldGameEnded ()
{
}

function handleGameEndedByUser ( gameId ) 
{
	trackFlashAction ("PlayGame_Abandoned") ;
	
    var gameboardContainer  = document.getElementById ( "gameboardNewContainer" );
    var bottomGameInfoCtr   = document.getElementById ( "bottomGameInfoPanelContainer" );
    if ( m_currentGameType == GAME_TYPE_HIT ) 
	{
		// New logic - show SWF for whole end-game experience in a new page.
		//  function in gameScriptsLoadAtTop.js will set up params and link to that page.
		gameboardContainer.style.display = "none" ;
		bottomGameInfoCtr.style.display  = "none" ;
		showVersion2_EndGame ("");			
	} 
	else 
	{ 
	   // Give a shot at some extra logic for "old" games
	   handleOldGameEnded() ;
	   
	   // Keep old logic for Pop4 / PopSpin
	   var gameboardNew = document.getElementById ( "gameboardNew" );
	   gameboardNew.showEndOfGameBack ();
	}


}

function fromFlash_showRules () {
	//alert ( "CALLED" );
	setTimeout ( delayedShowRules, 100 );
}


function fromFlash_soundOn () {
	setTimeout ( delayedSoundOn, 100 );
}

function delayedSoundOn () {
	//alert ( "SOUND ON" );
	var gameboardNew = document.getElementById ( "gameboardNew" );
	gameboardNew.unMuteGameSounds ();  // resumeSound
}

function fromFlash_soundOff () {
	setTimeout ( delayedSoundOff, 100 );
}

function delayedSoundOff () {
	//alert ( "SOUND OFF" );
	var gameboardNew = document.getElementById ( "gameboardNew" );
	try {
	//alert ( "CALLING PAUSE SOUND: "  + gameboardNew );
	   gameboardNew.muteGameSounds() ;   // pauseSound ();
	} catch ( exc ) {
		printTrace ( "EXC: " + exc );
	}
}



/***
* ------------------------------------ "GAME PLAY EVENTS"  ---------------------------------------------
***/

function fromFlash_gamePiecesShowing () {
	
printTrace ( "CALL FROM GAMEBOARD: fromFlash_gamePiecesShowing ()" );

	m_gameboardReadyForPlay = true;
	// alert ( "GAME PIECES SHOWING" );
	
	var rulesWereShownCookie = getCookie ( "rulesWereShownCookie" );
	//alert ( " rulesWereShownCookie: " + rulesWereShownCookie );
	if ( rulesWereShownCookie == null ) {
	    // THIS IS WHERE WE WOULD HAVE POPPED UP RULES AT STARTUP. setTimeout ( delayedShowRules, 100 );
	}
	setSingleSessionCookie ( "rulesWereShownCookie", "true" );
	
}

/**
* The user has clicked the "next question" or "back" button on the Flash question panel.
*/
function goBackToGameBoard () {
	
printTrace ( "CALL FROM QUESTION PANEL: goBackToGameBoard () " );

	/**
	* If we answered the first question right and then declined to answer the bonus question, the current game score is stored
	* in "m_currentGameScoreAfterFirstBonusQuestion".  Now it is time for us to update the running score of the game with this value.
	*/
	if ( m_currentGameScoreAfterFirstBonusQuestion != null ) {
		m_currentGameScore = m_currentGameScoreAfterFirstBonusQuestion;
		m_currentGameScoreAfterFirstBonusQuestion = null;
	}


   // SLW new 7/21/08.
   m_currentQuestionObject = null;
   m_currentQuestionResponseObject = null;
	//m_idOfQuestionBeingAnswered = null;
	m_currentGameScoreAfterFirstBonusQuestion = null;

   nextQuestion (); 
	
	handleGameBoardIsShowing ();
}

function nextQuestion () {
	
	clearCheckForLoadedVideoTimer ();
	
	calculateTotalTimeInVideo ( "clickNext" );
	setTimeout ( sendVideoPlayedMetricsMessage, 100 );

//alert ( "NEXT QUESTION CALLED" );

//alert ( " about to stop video" );
   // Added to hide the movie right away.  This seems to deal with the problem where sometimes if the user clicks "next question" that click will
   // cause "nextQuestion" to be called right away but then "delayedNextQuestion" won't be called until tons of data downloads to the movie 
   // - which ironically we don't want to see any more after the user clicks "next question"!
   hideMoviePlayer ();

   setTimeout ( delayedNextQuestion, 100 );
}


function hideMoviePlayer () {
	   /**
   * This where we free up video player resources.
   */
   try {
	   if ( m_isYouTubeVideo || m_isPopJaxVideo ) {
		  stopYouTubeVideo ();
		  clearVideo ();
	   } else {
		  var nonYouTubeMovie = document.getElementById ( "nonYouTubeMovie" );
		  var nonYouTubeEmbeddedVideo = document.getElementById ("nonYouTubeEmbeddedVideo");
		   
		  /**
		  * Sort of voodo, hail Mary, placeebo, but...
		  */	   
		  fixMemoryLeaksFromFlashMovie ( "nonYouTubeEmbeddedVideo" );
		   
		   // Clear out the container of the non-youtube video
		  if ( nonYouTubeMovie ) {
			 nonYouTubeMovie.innerHTML = "";
			 nonYouTubeMovie.parentNode.removeChild(nonYouTubeMovie);
		  }
	   }
   } catch ( excclosevideo ) {
	   printTrace ( "HIDE MOVIE PLAYER: " + excclosevideo );
   }

}

/**
* This handles showing the gameboard again after the user has clicked the "next question" button.
*/	 
function delayedNextQuestion () {
	
	//calculateTotalTimeInVideo ( "clickNext" );
	
//alert ( "delayed next question called" );

   /**
   * Make sure the "hidden video overlay" is no longer showing.
   */
   hideHiddenVideoDiv ();
	
//alert ( "DELAYED NEXT Q" );
	
   /**
   * Get access the the panel that contains the video and the Flash question panel.  And then shove them off the screen so we can
   * now show the gameboard.
   */	
   var singleQuestionPanel = document.getElementById ( "singleQuestionPanel" );
   singleQuestionPanel.style.left = "2000px"; 
		   


   /**
   * This where we free up video player resources.
   */
/** THIS IS "hideMoviePlayer"  
   try {
	   if ( m_isYouTubeVideo ) {
		  stopYouTubeVideo ();
		  clearVideo ();
	   } else {
		  var nonYouTubeMovie = document.getElementById ( "nonYouTubeMovie" );
		  var nonYouTubeEmbeddedVideo = document.getElementById ("nonYouTubeEmbeddedVideo");
		   
		  fixMemoryLeaksFromFlashMovie ( "nonYouTubeEmbeddedVideo" );
		   
		   // Clear out the container of the non-youtube video
		  if ( nonYouTubeMovie ) {
			 nonYouTubeMovie.innerHTML = "";
			 nonYouTubeMovie.parentNode.removeChild(nonYouTubeMovie);
		  }
	   }
   } catch ( excclosevideo ) {
	   printTrace ( "EXC closing video: " + excclosevideo );
   }
*/		   
		
//alert ( "SHOULD SHOW GAMEBOARD" );

	// NOT USED?	var moviePanel = document.getElementById ( "moviePanel" );

   /**
   * Now we show the gameboard.
   */
   var gameboard = document.getElementById ( "gameboardNewContainer" );
   gameboard.style.left = m_gameboardLeftPos + "px"; //"100px"; //display = "block";
	
   /**
   * Send a message to the Flash gameboard - telling it that it is visible now.
   */	
   printTrace ( "pre: gameboardNew.showGameboard" );
   var gameboardNew = document.getElementById ( "gameboardNew" );
   gameboardNew.showGameboard ( m_gameOver );
   printTrace ( "post: gameboardNew.showGameboard" );
		
   /**
   * Update the "current game score" in the bar along the bottom of the gameboard.
   */
   var bottomGameInfoPanel = document.getElementById ( "bottomGameInfoPanel" );	
   try
   {
     bottomGameInfoPanel.setScore   ( m_currentGameScore );
     bottomGameInfoPanel.showScores ( );
   }
   catch ( exc )
   {
   }
   
   var showingNewGameLevelOverlay = false;
   
   /**
   * If this is a "clear the board" game, then the user will keep any points they score.  If it is not a clear the board game, they 
   * will only keep points if they win the game.
   */
   if ( m_clearTheBoardGame && userIsLoggedIn () && playerHasPlayedGame () == false ) {
	   
	   /*
	   m_currentLevel = calculateLevel ( m_lifetimeScore );
m_clearTheBoardGame = true;
	   */
	   
	   var lifetimeAndCurrentGameScore = m_lifetimeScore + Number(m_currentGameScore);
	   var newLevel = calculateLevel( lifetimeAndCurrentGameScore );
		
	   //alert ( "LEVEL: " + newLevel );
	   
	   // For Trac 1009 - stop showing new game level...
	   /***
	   if ( newLevel != m_currentLevel ) 
	   {
		   m_currentLevel = newLevel;
		   var gameboardNew = document.getElementById ( "gameboardNew" );
		   
		   gameboardNew.showNewGameLevelOverlay ( m_currentLevel );
		   showingNewGameLevelOverlay = true;
	   } 
	   ***/
	   
   }
   
   var doShowDailyDrawingQualificationAnimation = false;
   var doShowMonthlyDrawingOneQualificationAnimation = false;
   var doShowMonthlyDrawingTwoQualificationAnimation = false;
	
//alert ( "WELL???? m_dailyPoints: " + m_dailyPoints + " m_showedDailyDrawingAnimation: " + m_showedDailyDrawingAnimation + " playerHasPlayedGame () " + //playerHasPlayedGame () );

   if ( m_dailyPoints != null && ( m_showedDailyDrawingAnimation == false ) && playerHasPlayedGame () == false ) {
	   var dailyPointsWithCurrentGameScoreAdded = Number ( Number(m_dailyPoints) + Number(m_currentGameScore) );
	   
//alert ( " dailyPointsWithCurrentGameScoreAdded: " + dailyPointsWithCurrentGameScoreAdded );

	   if ( m_dailyPoints < 5000 &&  dailyPointsWithCurrentGameScoreAdded >= 5000 ) {
			if ( m_gameType == "POP4" || m_gameType == "POPSPIN" || suppressDrawingWinnerAnimations() ) {
		// alert ( "DELAYING" );
				//m_delayedShowDailyDrawingAnimation = true;
				// DO NOTHING.  WE'LL HANDLE THIS AT THE END OF THE GAME
			} else {
		      doShowDailyDrawingQualificationAnimation = true;
			}
	   }
   }

//alert ( " doShowDailyDrawingQualificationAnimation: " + doShowDailyDrawingQualificationAnimation );

   if ( m_monthlyPoints != null && ( m_showedMonthlyDrawingOneAnimation == false ) && playerHasPlayedGame () == false ) {
	   var monthlyPointsWithCurrentGameScoreAdded = Number ( Number(m_monthlyPoints) + Number(m_currentGameScore) );
	   
	   if ( m_monthlyPoints < 25000 &&  monthlyPointsWithCurrentGameScoreAdded >= 25000 ) {
			if ( m_gameType == "POP4" || m_gameType == "POPSPIN" || suppressDrawingWinnerAnimations() ) {
				// Do nothing now.
			} else {
		      doShowMonthlyDrawingOneQualificationAnimation = true;
			}
	   }
   }

   if ( m_monthlyPoints != null && ( m_showedMonthlyDrawingTwoAnimation == false ) && playerHasPlayedGame () == false ) {
	   var monthlyPointsWithCurrentGameScoreAdded = Number ( Number(m_monthlyPoints) + Number(m_currentGameScore) );
	   
	   if ( m_monthlyPoints < 50000 &&  monthlyPointsWithCurrentGameScoreAdded >= 50000 ) {
			if ( m_gameType == "POP4" || m_gameType == "POPSPIN" || suppressDrawingWinnerAnimations() ) {
				// Do Nothing.
			} else {
		      doShowMonthlyDrawingTwoQualificationAnimation = true;
			}
	   }
   }

   if ( doShowDailyDrawingQualificationAnimation && 
	     ( doShowMonthlyDrawingOneQualificationAnimation == false ) && ( doShowMonthlyDrawingTwoQualificationAnimation == false )  
	   ) {
	   m_showedDailyDrawingAnimation = true;
	   showQualifyForDailyPrize ();
   }
   
   if ( ( doShowMonthlyDrawingOneQualificationAnimation == true ) && ( doShowMonthlyDrawingTwoQualificationAnimation == false ) ) {
	 //  alert ( "SHOW MONTHLY 1" );
	   m_showedMonthlyDrawingOneAnimation = true;
	   showQualifyForMonthlyPrizeOne ();
   }
   
   if ( doShowMonthlyDrawingTwoQualificationAnimation ) {
	   //alert ( "SHOW MONTHLY 2" );
	   m_showedMonthlyDrawingTwoAnimation = true;
	   showQualifyForMonthlyPrizeTwo ();
   }
   
   
   // m_weeklyPoints
   
   //try {
   
   /**
   * Mark the "just played" game piece on the game board correct or wrong.
   */
   if ( m_answerWasCorrect ) {
      gameboardNew.markPieceAsCorrect ( m_selectedGamePieceCol, m_selectedGamePieceRow );
   } else {
      gameboardNew.markPieceAsWrong ( m_selectedGamePieceCol, m_selectedGamePieceRow );
   }
   
//alert ( "DONE MARKING PIECE" );

   
//	 } catch ( exc ) {
//		 alert ( "EXC: "+ exc );
//	 }

		
		// gameboardVisible
	
   /**
   * Now do what we do to hide or clean up/delete the Flash question panel.
   */	
   var questionPanelContainer = document.getElementById ( "questionPanelContainer" );
		
   if ( !isIE () ) {
	 //  alert ( "IS NOT IE SO DELETE Q PANEL" );
	   questionPanelContainer.innerHTML = "";
	   m_questionPanelLoaded = false;
   }
   
   m_currentQuestionResponseXml = null;
		
//alert ( " GAME OVER: " + m_gameOver );

   /**
   * If the game is over, tell the gameboard to animate up an "end of game" background image.
   */
   if ( m_gameOver ) {
	   
//alert ( " CALLING GAME COMPLETED" );	   
      if ( showingNewGameLevelOverlay ) {
		  setTimeout ( delayedHandleGameCompleted, 4000 );
	  } else {
         handleGameCompleted ( m_gameId );
	  }
   }
   
 //alert ( "End of func" );
}

function delayedHandleGameCompleted () {
	handleGameCompleted ( m_gameId );
}

/**
* On www.videojax.com and affiliates, when the game is over, show a game over screen.
*/
function handleGameCompleted ( gameId ) 
{
   // DO THIS WHEN NOT SHOWING AN ANIMATION...
   fixMemoryLeaksFromFlashMovie ();
	
   var gameboardNew = document.getElementById ( "gameboardNew" );

   var playerPercentage = Number(100);

   if ( m_gameOverData.percentile ) {
	   var playerPercentile = Number(m_gameOverData.percentile) * 100;
	   playerPercentile = Math.round(playerPercentile);
	   playerPercentage = 100 - playerPercentile;
	   if ( playerPercentage < 1 ) {
		   playerPercentage = 1;
	   }
   }

   gameboardNew.playGameOverNormalScoreSound ();
		
    var gameboardContainer  = document.getElementById ( "gameboardNewContainer" );
    var bottomGameInfoCtr   = document.getElementById ( "bottomGameInfoPanelContainer" );
    if ( m_currentGameType == GAME_TYPE_HIT ) 
	{
		// New logic - show SWF for whole end-game experience in a new page.
		//  function in gameScriptsLoadAtTop.js will set up params and link to that page.
		gameboardContainer.style.display = "none" ;
		bottomGameInfoCtr.style.display  = "none" ;
		var lastGameId = "" ;
		if ( m_gameOverData.playedgameId )
		  lastGameId = m_gameOverData.playedgameId ;
		showVersion2_EndGame (lastGameId);			
	} 
	else 
	{ 
	   // Keep old logic for Pop4 / PopSpin
	   gameboardNew.showEndOfGameBack ();
	}
}



function getSuggestedNextGamesToPlay () {
	
	var pjuid = -1;
	
	var gameId = m_gameId;
	if ( m_pjuid != null ) { //userIsLoggedIn () ) {
		pjuid = m_pjuid;
		if ( pjuid == null || pjuid == "null" ) {
			pjuid = -1;
			if ( getCookie ( "pjuid" ) ) {
				pjuid = getCookie ( "pjuid" );
			}
		}
	}
	
	// alert ( " PJUID: " + pjuid + " getCookie ( 'pjuid' ) " + getCookie ( "pjuid" ) );
	
	dataService_getSuggestedNextGames ( handleGetSuggestedNextGamesToPlayCompleted, pjuid, gameId )
}

function getGamePageJsp () {
}

/**
* You can subclass this.
*/
function addExtraElementsToRecommendedGame ( anchorElement, index ) {
}

function getExtraGameParameters () {
	return "";
}

// Function to call when user selects one of the recommended games.
// Inserted as an onClick handler for the <a> tags in the recommendation screen.
function onRecdGameSelected ()
{
   trackUserAction ("EndGame_SelectRecommendedGame") ;	
   return true ;
}


function handleGetSuggestedNextGamesToPlayCompleted ( data, xml ) {
	//alert ( "NEXT GAMES TO PLAY: " + data );
	
	var endGameNotLoggedInSuggestedGamesTitle = document.getElementById( "endGameNotLoggedInSuggestedGamesTitle" );
	if ( endGameNotLoggedInSuggestedGamesTitle ) {
	   endGameNotLoggedInSuggestedGamesTitle.style.display = "block";
	}
	
    var endGameLoggedInSuggestedGamesTitle = document.getElementById( "endGameLoggedInSuggestedGamesTitle" );
	endGameLoggedInSuggestedGamesTitle.style.display = "block";
	
	var pjuid = null;
	var playerName = null;
	if ( userIsLoggedIn () ) {
		pjuid = m_pjuid;
		playerName = m_userInfo.name;
	}
	
	var nextGamesDivId = "suggestedGamesNotLoggedInDiv";
	
	if ( userIsLoggedIn () ) {
		nextGamesDivId = "suggestedGamesLoggedInDiv";
	}
	
	var nextGamesDiv      = document.getElementById( nextGamesDivId );
	var endGameMessageDiv = document.getElementById ( "endGameMessage" );
	if ( ! userIsLoggedIn () ) 
	  endGameMessageDiv = document.getElementById ( "endGameNotLoggedInMessage" );
	  
	// Trac 631 - use data.endGameMessage for a message based on scored achieved...
	if ( endGameMessageDiv != undefined && endGameMessageDiv != null )
	{
	  if ( data.endGameMessage == undefined || data.endGameMessage == null )
	    endGameMessageDiv.innerHTML = "Thanks for playing!" ;
	  else
	    endGameMessageDiv.innerHTML = data.endGameMessage ;
	}
	
	var suggestedNextGames = data.suggestedNextGames;
	
	var numberOfGames = Math.min (m_numberOfSuggestedGamesToShow, suggestedNextGames.length);

    // track action that recs were shown...
	if ( numberOfGames > 0 )
      trackUserAction ("EndGame_ShowRecommendedGames") ;
	
    for ( var idx = 0; idx < numberOfGames; idx++ ) {
		var suggestedGame = suggestedNextGames[idx];
		
		var gameId = suggestedGame.gameId;
		var gameName = suggestedGame.gameName;
		var thumbnailUrl = suggestedGame.thumbnailUrl;
		
	//	alert ( " ID: " + gameId + " NAME: " + gameName + " URL: " + thumbnailUrl );
		
		var gameUrl = m_gamePageJsp = "?game_type=HIT&game_id=" + gameId + "&pjuid=" + pjuid + "&pjusername=" + playerName;
		gameUrl += getExtraGameParameters ();
		
		var a = document.createElement ( "a" );
		a.setAttribute ( "href", gameUrl );
		a.onclick = function () { onRecdGameSelected() };
														
		a.style.display = "block";
	//	a.style.float = "left"; // It seems like "float" is a reserved word in some browsers.  If you use this syntax in Safari/Mac,
	    // then the browser won't even load "gameLogic.js"!!!  Seems like leaving this out allows the game to work ok.
		a.style.textDecoration = "none";
		a.style.textAlign="center"; 
		//a.style.width="100px"; 
		//a.style.height="100px"; 
		//a.style.margin="0px";
		a.className = "floatLeftThumbImage";
		
		var img = document.createElement ( "img" );
		img.src = thumbnailUrl;
		img.setAttribute ( "src", thumbnailUrl );
		//img.style.width="80px"; 
		//img.style.height="60px"; 
		img.style.display="block"; 
		img.style.marginLeft="auto"; 
		img.style.marginRight="auto"; 
		img.style.border="none";
		
        a.appendChild(img);
		
		var span = document.createElement ( "span" );
	//	span.style.color = m_suggestedGameLabelColor; //"#000033";
	//	span.style.fontSize = "12px";
		span.style.fontWeight = "bold";
		span.style.textDecoration = "none";
		span.innerHTML = gameName;
		//span.className = "gameLabelClass";
		a.appendChild(span);
				
		if ( nextGamesDiv ) {
		   nextGamesDiv.appendChild(a);
		}
		
		addExtraElementsToRecommendedGame (a, idx);		
	}
	
}



function dismissLoginFormAtTopIfUserNotLoggedIn () {
	var logInForm = document.getElementById("loginform2");
	if ( logInForm ) {
		logInForm.style.display = "none";
	}
}

/**
* The user has clicked a game piece.
*/
function showQuestion ( col, row ) {
	
	/**
	* If the user starts playing the game and they are still not logged in, remove the ability for them to log in half-way through the game.
	*/
	dismissLoginFormAtTopIfUserNotLoggedIn ();
	
    printTrace ( "CALL FROM GAMEBOARD: showQuestion ()" );
	
	var skipQuestionDiv = document.getElementById ( "skipQuestionDiv" );
	skipQuestionDiv.style.display = "none";
	
	
	m_selectedGameCell = getGameCellByPosition ( col, row );
	
	//alert( " CELL: " + m_selectedGameCell );
	
	// var m_selectedGameCell = null; // getGameCellByPosition ( col, row )
	
   /**
   * Don't let a quick double-click on a question cause a reload of the question!
   * In other word, don't support double-clicking on a game piece.
   */
   if ( m_loadingQuestion ) {
printTrace ( "Loading question so bail" );	   
      return;
   }
   
   m_questionLoadedIntoQuestionPanel = false;
   
   m_loadingQuestion = true;
   
   m_selectedGamePieceCol = col;
   m_selectedGamePieceRow = row;
   
   m_answerFromUser = null;
	
   /**
   * Cause the "get question" Ajax call to happen in a different thread.
   */
   setTimeout ( delayedGetQuestion, 100 );	
}

/**
* The user has clicked a game piece.
*/
function showQuestionById ( questionId  ) {
	
	m_singleQuestionId = questionId;
	
	m_selectedGameCell = null; // getGameCellByPosition ( col, row );
	
	//alert( " CELL: " + m_selectedGameCell );
	
	// var m_selectedGameCell = null; // getGameCellByPosition ( col, row )
	
   /**
   * Don't let a quick double-click on a question cause a reload of the question!
   * In other word, don't support double-clicking on a game piece.
   */
   if ( m_loadingQuestion ) {
      return;
   }
   
   m_questionLoadedIntoQuestionPanel = false;
   
   m_loadingQuestion = true;
   
  // m_selectedGamePieceCol = questionId;
  // m_selectedGamePieceRow = row;
	
	m_answerFromUser = null;
	
   /**
   * Cause the "get question" Ajax call to happen in a different thread.
   */
   setTimeout ( delayedGetQuestionById, 100 );	
}

function delayedGetQuestionById () {
   dataService_getQuestionById ( handleQuestionReady, m_singleQuestionId );
}

//var m_waitingForQuestion = false;

/**
* This will call the data service that returns the question corresponding the game piece the user clicked.
*/
function delayedGetQuestion () {
	
printTrace ( "delayedGetQuestion () called" );

   try {
		//m_waitingForQuestion = true;
      dataService_getQuestion ( handleQuestionReady, m_selectedGamePieceCol - 1, m_selectedGamePieceRow - 1 );
   } catch ( exc ) {
	    printTrace ( "EXC in delayedGetQuestion" + exc );
   }
}
	
function setEmbedVideoSize ( embedOrig ) 
{
	var modifiedEmbed ;
	
	var isHulu = embedOrig.indexOf ( "hulu." ) ;
	if ( (isHulu > 0) && (forceHuluWidth != null) && (forceHuluWidth != '') )
	{
		// Patch up the size of Hulu video DIV
	   modifiedEmbed = embedOrig.replace      ( /"512"/g, forceHuluWidth  );
	   modifiedEmbed = modifiedEmbed.replace  ( /"341"/g, forceHuluHeight );
	   //alert ("FIXED HULU EMBED: " + modifiedEmbed ) ;
	   return modifiedEmbed;
	}
	
	var vidWidth  = m_videoWidth.substr (0,3)  ;  //  "512px";  
    var vidHeight = m_videoHeight.substr(0,3)  ;  //  "380px";    

	modifiedEmbed = embedOrig;
	var indexOfWidthStart       = modifiedEmbed.indexOf ( "width=" );
	if ( indexOfWidthStart < 0 )
	  return modifiedEmbed ;
	  
	var indexOfWidthFirstQuote  = indexOfWidthStart + 6 ;
	var quoteChar               = embedOrig.substr (indexOfWidthFirstQuote, 1) ;
		
	var indexOfWidthSecondQuote = 0;
	
	if ( indexOfWidthStart > 0 ) 
	{
		indexOfWidthSecondQuote = embedOrig.indexOf ( quoteChar, indexOfWidthFirstQuote + 1 );
		if ( indexOfWidthSecondQuote > 0 ) 
		{
			modifiedEmbed = embedOrig.substring ( 0, indexOfWidthFirstQuote + 1 ) + 
			                vidWidth +
			                embedOrig.substring ( indexOfWidthSecondQuote );
		}
	}
	
	indexOfWidthStart       = modifiedEmbed.indexOf ( "height=" );
	indexOfWidthFirstQuote  = indexOfWidthStart + 7 ;
	if ( indexOfWidthStart > 0 ) 
	{
		indexOfWidthSecondQuote = modifiedEmbed.indexOf ( quoteChar, indexOfWidthFirstQuote + 1 );
		if ( indexOfWidthSecondQuote > 0 ) 
		{
			modifiedEmbed = modifiedEmbed.substring ( 0, indexOfWidthFirstQuote + 1 ) + 
			                vidHeight +
			                modifiedEmbed.substring ( indexOfWidthSecondQuote );
		}
	}
	
	return modifiedEmbed;
}


// Examine an URL and indicate if the "house" player should be used to perform it
// Right now, that is anything with 'rtmp:' or 'videojax' in it, or any URL
//  that ends with '.flv'

function useHousePlayer ( theURL )
{
  var lcURL = theURL.toLowerCase() ;
  var uLen  = theURL.length ;
  
  if ( lcURL.indexOf ( "rtmp:" ) >= 0 )
	return true;
	
  if ( (uLen > 4) && (lcURL.lastIndexOf(".flv") == (uLen-4)) )
    return true ;
	 
  if ( lcURL.indexOf ( "videojax" ) >= 0 )
	return true;
	
  return false ;
}

/**
* This is called after the "get question" data service returns.  This is where we start to display
* the video and setup a timer that once it "dings" will cause the currently selected question to be
* placed into the Flash question panel.
*/	
function handleQuestionReady ( data, xml ) {
	
	/**
	* If we get called when "m_waitingForQuestion" is false, that means we've already processed the response to the GET_QUESTION call.  So throw
	* away this "nth" response we've gotten back from the server.
	*/
	//if ( m_waitingForQuestion == false ) {
	//	alert ( "DUP FROM SERVER" );
	//	return;
	//}
	//m_waitingForQuestion = false;
	
	
   initQuestionAndVideoMetrics ();

	// Record when the loading of the question started...
	m_questionStartTime = new Date();
	
	
//alert ( "HANDLQ QUESTION READY CALLED" );

   m_loadingQuestion = false;   
   m_youTubeVideoReady = false;
   m_gameKnowsYouTubeVideoLoaded = false;
	   
   var questionText = data.questions[0].text;
   var url = data.questions[0].url;
   
	/**
	* New stuff to handle showing "loading question" over the video before it is skipped ahead.
	*/
	m_isSkipAheadQuestion = false;
	m_didSeekForSkipAhead = false;
	var startQuestionAtThisPosition = Number(data.questions[0].startVideo);
	if ( startQuestionAtThisPosition > 0 ) {
		m_isSkipAheadQuestion = true;
	}
	// alert ( " m_isSkipAheadQuestion: " + m_isSkipAheadQuestion );
	
	
	
   ASSERT_THROW ( questionText == undefined || questionText == null , "handleQuestionReady: question text field is missing!" );

   ASSERT_THROW (( ( url == undefined || url == null ) && ( data.questions[0].embedTag == undefined || data.questions[0].embedTag == null ) ), "handleQuestionReady: question has no url or embedTag!" );



   /**
   * Set our reference to the Question (model) object.  It is a JavaScript object containing the 
   * question's attributes.
   */	   
   m_currentQuestionObject = data.questions[0];
	//m_idOfQuestionBeingAnswered = m_currentQuestionObject.id;
   
   m_currentQuestionResponseObject = data; // This is the QuestionResponse containing the main question and maybe the bonus question.
   
   /**
   * Put up the overlay now if one is needed.
   *
   * NOTE: This should actually only be shown when the video has been loaded but hasn't yet shown the user frame 1 (yea right, like you could do that!)
   */
   showOverlayIfNecessary ();
	
   /**
   * Set our reference to the XML "string" version of the question.  This will be passed into the Flash
   * question panel (which will parse it using ActionScript into an ActionScript XML object).
   */	   
   m_currentQuestionResponseXml = xml + "";
	
   /**
   * Get or generate the HTML "embed" tag for the selected question's video.
   */
   var embed = null;

   /**
   * First, try to coerce the url into its equivalent form as an "embed" tag.  (NOTE: Only those
   * video sites whose formats we support and know about will yield an embed tag for a url).
   */
   embed = getMovieEmbedFromUrl ( url );
		
   /**
   * If no "embed" tag yet, then we'd better have one as an attribute of the question.
   */
   if ( embed == null ) {
      embed = data.questions[0].embedTag;
	  
      ASSERT_THROW ( embed == undefined || embed == null, "handleQuestionReady: question has no url or embedTag!" );
	  
	  
	  embed = setEmbedVideoSize ( embed );
//alert ( " EMBED: " + embed );
   }


   /**
   * Are we dealing with a YouTube video?
   */   
   m_isYouTubeVideo = false;
   m_isPopJaxVideo  = false; // SLW 601
      
// if ( embed.indexOf ( "rtmp:" ) >= 0 ) 
   if ( useHousePlayer(embed) )
   { 
      m_isPopJaxVideo = true;
   } 
   else if ( embed.indexOf ( "youtube" ) >= 0 ) 
   {
      m_isYouTubeVideo = true;
   } 
	
	   
   /**
   * Now for some UI stuff!!!
   *
   * This is where we show the "div" containing both the video and the Flash question panel.  And at the same time, we
   * hide the gameboard.
   */
   var singleQuestionPanel = document.getElementById ( "singleQuestionPanel" );
   singleQuestionPanel.style.display = "block";
   singleQuestionPanel.style.left = "0px";
   handleVideoAndQuestionShowing ();
	
   // Hide Scores-to-Beat portion of Info Panel...
   var bottomGameInfoPanel = document.getElementById ( "bottomGameInfoPanel" );
   if (bottomGameInfoPanel)
   {
	   try
	   {
           bottomGameInfoPanel.hideScores ( );
	   }
	   catch ( exc )
	   {
		   // This is a somewhat benign error that happens in FF 2.0, only
		   // the FIRST time we try to hide the scores. Rather than try to
		   // figure this out, just let it pass...
		  // alert ("Could NOT hideScores") ;
	   }
   }
   
   /**
   * If in gameboard mode, move the gameboard over.  If in question mode, there is no gameboard to move over.
   */
   var gameboard = document.getElementById ( "gameboardNewContainer" );
   if ( gameboard ) {
      gameboard.style.left="2000px";//display = "none";
   }
   
   var movieUrl = document.getElementById ( "movieUrl" );
   //movieUrl = null;
   if ( movieUrl ) {
       movieUrl.innerHTML = "";
   }
   
   /**
   * These are not used now!!! They are used if we switch to a SWFObject version 2 model for embedding.
   */	
   var swfPath = "http://www.youtube.com/v/" + videoId + "&autoplay=1"; //&enablejsapi=1&playerapiid=ytplayer";	
   var params = { allowScriptAccess: "always", wmode: "transparent",  quality:"high", salign:"tl",  align:"tl", scale:"noScale" };	
   var atts = { id: "theMovie" };

m_debugStr = "video showing... ";

   try {
	   
	   /**
	   * For some reason, when running as a widget, the browser security won't let us do this embed after embedding the movie.
	   * But it will allow us to first embed the question panel and then embed the movie!!!
	   */
		if ( this["m_insidePopjaxWidget"] ) {
		   try {
			   embedFlashContent ( "questionPanel", "questionPanelContainer", "http://www.frisbeefish.com/popjax/game/QuestionPanel.swf", "100%", "100%", "#ffffff", "transparent", "exactFit" );
		   } catch ( exchack ) {
			   printTrace ( "EXC INSIDE OF HACK: " + exchack );
		   }
		}

      if ( m_isPopJaxVideo ) {
			
/*
	     var theMovie = null;
		 // if ( m_youtubeTypeVideoPlayerId != null ) {
		  theMovie = document.getElementById ( m_idOfPopJaxPlayerHolderDiv ); //"popJaxPlayer" ); // m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie" );
		//  }
	 
	     if ( theMovie ) {
	        theMovie.style.position = "absolute";						 
	        theMovie.style.left = "2000px";
         }
			
			theMovie = document.getElementById ( m_idOfYouTubePlayerHolderDiv ); //"youTubePlayer" ); //"popJaxPlayer" ); 
	     if ( theMovie ) {
	        theMovie.style.position = "absolute";						 
	        theMovie.style.left = "2000px";
         }

*/

          /**
			 * Nudge the youtube player out of the screen.
			 */
			 var thePlayerToHide = document.getElementById ( m_idOfYouTubePlayerHolderDiv ); //"youTubePlayer" ); //"popJaxPlayer" ); 
	       if ( thePlayerToHide ) {
	         thePlayerToHide.style.position = "absolute";						 
	         thePlayerToHide.style.left = "2000px";
          }
			 
			// alert ( "done hiding" );

			
//alert ( "IS POPJAX VIDEO!!!" );			
			 
			 m_youtubeTypeVideoPlayerId = "popJaxPlayer";
			 
         /**
         * Grab the YouTube video ID from the embed tag.
         */	   
         var videoId = extractVideoIdFromEmbed ( embed );
			
//alert ( "POPJAX VIDEO ID: " + videoId );			
			
	
	     /** MY GOOGLE/YOUTUBE DEVELOPER ID for "scott@popjax.com" **/
         var yourDevKey = 'AI39si42dRaaY6YNh7kA6NgfNw6MS-qT2Xw6JCWysA4YAGpYDAofcOpUlc4iV39EFZ4mrhQO9Ejm0MWwIQiMuvxZ6PUxOJhJWw';
         // THE GOOGLE "DO NOT USE" ONE 'AI39si6Wdgo0IIMzvKzOhGlFz97x0SjBZqNuiXvhJxXNd4KXrkcQCXsOnJtP4FlBhZbiA7uE3wGkLzH5dIF06TvAzs5IFBrgJg';
	   
	//alert ( " m_popjaxPlayerLoaded: " + m_popjaxPlayerLoaded );
	
	     /**
		 * If the chromeless player isn't yet loaded, we need to load it.  Only once it is loaded can we load the movie into it.
		 */
	     if ( m_popjaxPlayerLoaded == false ) {
	
	        /**
			* Set to "true" so we don't try to load the player when we select the next question.
			* NOTE: It looks like this is not used!!!
			*/
	       // m_youTubePlayerLoaded = true;  
	   
	        m_veryFirstVideoId = videoId; /* Need to remember this for once we've loaded the chromeless you tube video player */
	   
	        var cpSwfPath = m_popjaxVideoPlayerUrl; // "http://gdata.youtube.com/apiplayer?key=" + yourDevKey + "&enablejsapi=1&playerapiid=ytplayer";
			  
//alert ( " POPJAX PLAYER PATH: " + cpSwfPath );

/**
* SLW 601 Start of more stuff.
*/

	     var moviePanel = document.getElementById ( "moviePanel" );
	     var popJaxPlayerHolderDiv = document.createElement ( "div" );
	     popJaxPlayerHolderDiv.style.position = "absolute";
	     popJaxPlayerHolderDiv.style.left = "0px";
	     popJaxPlayerHolderDiv.style.width = m_videoWidth; 
	     popJaxPlayerHolderDiv.style.height = m_videoHeight; 
	     popJaxPlayerHolderDiv.setAttribute ( "id", m_idOfPopJaxPlayerHolderDiv );
	   
	     moviePanel.appendChild ( popJaxPlayerHolderDiv );
/**
* SLW 601 End of more stuff
*/

			  
			 // SLW 601 embedFlashContent ( "theMovie", "moviePanel", cpSwfPath, m_videoWidth, m_videoHeight, "#ffffff", "transparent", "exactFit" );
	       // SLW 601 more embedFlashContent ( m_youtubeTypeVideoPlayerId, "moviePanel", cpSwfPath, m_videoWidth, m_videoHeight, "#ffffff", "transparent", "exactFit" ); 
			  embedFlashContent ( m_youtubeTypeVideoPlayerId, m_idOfPopJaxPlayerHolderDiv, cpSwfPath, m_videoWidth, m_videoHeight, "#ffffff", "transparent", "exactFit", "_enableJSApi=1" ); 

	        /**
			* Put the chromess player in its correct location on the screen and make sure it is set to position "absolute"
			*/
		    var theMovie = document.getElementById ( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie" );
		    theMovie.style.position = "absolute";						 
		    theMovie.style.left = "0px";
		
	
         } else { /* Else the chromess player is already loaded so load a movie into it */

            /**
		    * Put the chromess player in its slot (it might have been shoved beyond view because we were showing some video from
		    * a non youtube site).
		    */	   
			 /** WAS
		    var theMovie = document.getElementById ( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie" );
		    theMovie.style.position = "absolute";						 
		    theMovie.style.left = "0px";
			 ***/
		    var theMovie = document.getElementById ( m_idOfPopJaxPlayerHolderDiv ); //m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie" );
		    theMovie.style.position = "absolute";						 
		    theMovie.style.left = "0px";
			 
	   
//alert ( "CALLING LOAD NEW VIDEO" );
	        /**
		    * Now load the video into the player.
		    */
	        loadNewVideo ( videoId, 0 );
         }

		} else if ( m_isYouTubeVideo ) {
			
			 
          /**
			 * Nudge the PopJax player out of the screen.
			 */
			 var thePlayerToHide = document.getElementById ( m_idOfPopJaxPlayerHolderDiv ); //"youTubePlayer" ); //"popJaxPlayer" ); 
	       if ( thePlayerToHide ) {
	         thePlayerToHide.style.position = "absolute";						 
	         thePlayerToHide.style.left = "2000px";
          }
			 
			 m_youtubeTypeVideoPlayerId = "youTubePlayer";
			 
   
          //var movieUrl = document.getElementById ( "movieUrl" );
		  if ( url != null && url != "null" && url != "undefined" ) {
			  var linkText = "<a href='" + url + "' target='_blank' >" + url + "</a>";
			  if ( movieUrl ) {
                 movieUrl.innerHTML = linkText;
			  }
		  }

         /**
         * Grab the YouTube video ID from the embed tag.
         */	   
         var videoId = extractVideoIdFromEmbed ( embed );
			
	
	     /** MY GOOGLE/YOUTUBE DEVELOPER ID for "scott@popjax.com" **/
         var yourDevKey = 'AI39si42dRaaY6YNh7kA6NgfNw6MS-qT2Xw6JCWysA4YAGpYDAofcOpUlc4iV39EFZ4mrhQO9Ejm0MWwIQiMuvxZ6PUxOJhJWw';
         // THE GOOGLE "DO NOT USE" ONE 'AI39si6Wdgo0IIMzvKzOhGlFz97x0SjBZqNuiXvhJxXNd4KXrkcQCXsOnJtP4FlBhZbiA7uE3wGkLzH5dIF06TvAzs5IFBrgJg';
	   
	     /**
		 * If the chromeless player isn't yet loaded, we need to load it.  Only once it is loaded can we load the movie into it.
		 */
	     if ( m_videoPlayerLoaded == false ) {
	
	        /**
			* Set to "true" so we don't try to load the player when we select the next question.
			* NOTE: It looks like this is not used!!!
			*/
	        m_youTubePlayerLoaded = true;  
	   
	        m_veryFirstVideoId = videoId; /* Need to remember this for once we've loaded the chromeless you tube video player */
			
			// There are a few things we can try to remedy Trac #643:
			//  0. DO NOTHING - as it looks like this is WORKING NOW (05-Jan-2009)
			//  1. remove the key and playerapiid params
			//  2. switch URL to www.youtube.com
			//  3. use the YTProxy player at /content/game/YTProxy1.swf
	   
	        // var cpSwfPath = "http://gdata.youtube.com/apiplayer?key=" + yourDevKey + "&enablejsapi=1&playerapiid=ytplayer";
			
	        // var cpSwfPath = "http://www.youtube.com/apiplayer?enablejsapi=1";   // This is 1 + 2
			
			/*  Interesting note from YT Developer Forum:
			
			    http://groups.google.com/group/youtube-api-gdata/
			      browse_thread/thread/897f00ba5f7a0dd/35f65ae31b0ccff8?hl=en#35f65ae31b0ccff8
				 
				 Jan 15, 2009
				 
				 Please do update your chromeless player urls to the new url (www.youtube.com/apiplayer) as the 
				 gdata url may go away in the distant future. [NB: YTProxy1.swf uses this URL]
				 
				 Note that you no longer need to use the developer key to access the player swf, 
				 so you can remove that as well. 
			
			     see also: http://code.google.com/apis/youtube/chromeless_player_reference.html
			*/
			
			
	        var cpSwfPath = "/content/game/YTProxy1.swf";                          // This is 3
			
			// Here we try to deal with a NEW bug (Trac #762) where IE7 does not skip-ahead in video... 
			/***  ... but no luck...
			if ( isIE() ) 
			{
				cpSwfPath = "http://gdata.youtube.com/apiplayer?key=" + yourDevKey + "&enablejsapi=1&playerapiid=ytplayer";
			}
            ***/
			  
/**
* SLW 601 Start of more stuff.
*/
	     var moviePanel = document.getElementById ( "moviePanel" );
	     var youTubePlayerHolderDiv = document.createElement ( "div" );
	     youTubePlayerHolderDiv.style.position = "absolute";
	     youTubePlayerHolderDiv.style.left = "0px";
	     youTubePlayerHolderDiv.style.width = m_videoWidth; 
	     youTubePlayerHolderDiv.style.height = m_videoHeight; 
	     youTubePlayerHolderDiv.setAttribute ( "id", m_idOfYouTubePlayerHolderDiv );
	   
	     moviePanel.appendChild ( youTubePlayerHolderDiv );
/**
* SLW 601 End of more stuff
*/			  
			 // SLW 601 embedFlashContent ( "theMovie", "moviePanel", cpSwfPath, m_videoWidth, m_videoHeight, "#ffffff", "transparent", "exactFit" );
	       // SLW 601 part 2 embedFlashContent ( m_youtubeTypeVideoPlayerId, "moviePanel", cpSwfPath, m_videoWidth, m_videoHeight, "#ffffff", "transparent", "exactFit" ); 
	        embedFlashContent ( m_youtubeTypeVideoPlayerId, m_idOfYouTubePlayerHolderDiv, cpSwfPath, m_videoWidth, m_videoHeight, "#ffffff", "transparent", "exactFit" ); 

	        /**
			* Put the chromess player in its correct location on the screen and make sure it is set to position "absolute"
			*/
		    var theMovie = document.getElementById ( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie" );
		    theMovie.style.position = "absolute";						 
		    theMovie.style.left = "0px";
		
	
         } else { /* Else the chromess player is already loaded so load a movie into it */

            /**
		    * Put the chromess player in its slot (it might have been shoved beyond view because we were showing some video from
		    * a non youtube site).
		    */	   
		    var theMovie = document.getElementById ( m_idOfYouTubePlayerHolderDiv ); //m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie" );
		    theMovie.style.position = "absolute";						 
		    theMovie.style.left = "0px";
	   
//alert ( "CALLING LOAD NEW VIDEO" );		
	        /**
		    * Now load the video into the player.
		    */
	        loadNewVideo ( videoId, 0 );
         }
   
      } else { /* NOT!!! a youtube video so we do some squirrely stuff here */
     
         /**
	     * Try to grab the YouTube chromess player.  If it has been loaded, shove it off the side of the screen so that
	     * our video will show next to the question rather than the empty YouTube chromeless player.  NOTE: We don't want to
	     * delete the youtube chromeless player each time this happens!!!  We just want to hide it.  (By not flopping the youtube player
	     * in and out of memory, we reduce memory leaks!)
	     */
	     var theMovie = null;
		 // if ( m_youtubeTypeVideoPlayerId != null ) {
		  theMovie = document.getElementById ( m_idOfPopJaxPlayerHolderDiv ); //"popJaxPlayer" ); // m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie" );
		//  }
	 
	     if ( theMovie ) {
	        theMovie.style.position = "absolute";						 
	        theMovie.style.left = "2000px";
         }
			
			theMovie = document.getElementById ( m_idOfYouTubePlayerHolderDiv ); //"youTubePlayer" ); //"popJaxPlayer" ); 
	     if ( theMovie ) {
	        theMovie.style.position = "absolute";						 
	        theMovie.style.left = "2000px";
         }
			
/*
"popJaxPlayer"
"youTubePlayer"
*/

         /**
	     * Here we create a "div" called "nonYouTubeMovie" that is at a peer level with "theMovie" (the one containing the youtube player).
	     * Then we create a child "embed" with the id "nonYouTubeEmbeddedVideo".  This will contain whatever video site's video player that
	     * we need.
	     */	 
	     var moviePanel = document.getElementById ( "moviePanel" );
	     var nonYouTubeMovie = document.createElement ( "div" );
	     nonYouTubeMovie.style.position = "absolute";
	     nonYouTubeMovie.style.left = "0px";
	     nonYouTubeMovie.style.width = m_videoWidth; //"500px"; /* Explicit size rather than "100%" */
	     nonYouTubeMovie.style.height = m_videoHeight; // "400px"; /* Explicit size rather than "100%" */
	     nonYouTubeMovie.setAttribute ( "id", "nonYouTubeMovie" );
	   
	     moviePanel.appendChild ( nonYouTubeMovie );
	  
	     nonYouTubeMovie.innerHTML = embed;

         /**
	     * In some situations, we won't have already assigned an "id" to the embed, so this ensures that we've got one.
	     */	  
	     var embedElement = nonYouTubeMovie.getElementsByTagName ( "embed" )[0];
	     embedElement.setAttribute ( "id", "nonYouTubeEmbeddedVideo" );
      }

   } catch ( excfff ) {
      printTrace ( "handleQuestionReady Exception: " + excfff );
   }

   /**
   * Now overlay the movie so the user can't click while answering the question.
   */
   showClearVideoOverlayDiv ();
   
m_debugStr += "embedding question panel... ";

   /**
   * This is where we either embed or display the Flash question panel.
   */
   if ( isIE () ) {
 //alert ( "IS IE SO JUST MOVING QUESTION" );
      singleQuestionPanel.style.left = "0px";
		handleVideoAndQuestionShowing ();
	  var questionPanel = document.getElementById ( "questionPanel" );
	 // alert ( " questionPanel: " + questionPanel );
	  if ( questionPanel == null ) {
		  embedFlashContent ( "questionPanel", "questionPanelContainer", questionPanelSwf, 
							  "100%", "100%", "#ffffff", "transparent", "exactFit" );
	  }
   } else {
	   
m_debugStr += " about to embed q panel ";

// http://www.frisbeefish.com/popjax/game/QuestionPanel.swf";
      if ( this["m_insidePopjaxWidget"] != true ) {
         try {
            embedFlashContent ( "questionPanel", "questionPanelContainer", questionPanelSwf, 
							    "100%", "100%", "#ffffff", "transparent", "exactFit" );
	     } catch ( embedexc ) {
		     m_debugStr += " EXC: " + embedexc;
		    // HIDE THIS. THIS IS THROWN IN FIRST QUESTION WHEN IN FACEBOOK.  SOME SECURITY ISSUE. alert ( " EXC: " + m_debugStr );
	     }
	  }
m_debugStr +=   " srvived that ";	  
   }

//alert ( " m_currentQuestionResponseXml:  " + m_currentQuestionResponseXml +    " 	m_questionPanelLoaded: " + m_questionPanelLoaded );   

   if ( m_currentQuestionResponseXml && m_questionPanelLoaded ) {	   
      delayedShowQuestion ();
   } else {
      setTimeout ( checkOneLastTimeIfCanShowQuestion, 300 );
   }
}
	
/**
* This is called in the rare event that both the question panel and the question data 
* arrived at exactly the same time (for instance, it seems like in IE there are multiple threads processing 
* stuff.  One loads the "question" panel while the other handles the Ajax call to get the question.  If the panel loads
* and calls the "moduleLoaded" function via one thread and at the same time the ajax data arrives and the 
* "handleQuestionReady" function is called, we can have a race condition where this will never be 
* true: "( m_currentQuestionResponseXml && m_questionPanelLoaded ) ".  So, to handle that rare condition, 
* this "checkOneLastTimeIfCanShowQuestion" is called 100ms after the "handleQuestionReady" function 
* is called.  Once those 100ms are up and this function is called, then if there was the race condition then at 
* this time "( m_currentQuestionResponseXml && m_questionPanelLoaded )" would equal TRUE and we could load the question
* data into the question panel.
**/
function checkOneLastTimeIfCanShowQuestion () {
   if ( m_currentQuestionResponseXml && m_questionPanelLoaded && ( m_questionLoadedIntoQuestionPanel == false ) ) {
	   delayedShowQuestion ();
   }
}

	
function delayedShowQuestion ()  {

// alert ( " FOO " + m_currentQuestionResponseXml );

m_debugStr += "delayed Show question... ";
	if ( !m_questionLoadedIntoQuestionPanel ) {
	   var questionPanel = document.getElementById ( "questionPanel" );
	   var points = "100";
	   if ( m_selectedGameCell != null ) {
		   points = m_selectedGameCell.points;
	   }
	   printTrace ( "pre: questionPanel.showQuestion" );
	  
//alert ( " ABOUT TO SHOW THIS: " + m_currentQuestionResponseXml );	  
	   
	   /**
		* SLW NEW 9/23/08
		*/
		if ( m_questionPanelSkin != null ) {
			try {
				//var questionPanelToSkin = document.getElementById ( "questionPanel" );
				questionPanel.applySkin( m_questionPanelSkin );
			} catch ( excLoadingSkin ) {
				//alert ( "EXC: " + excLoadingSkin );
			}
		}

		
	   questionPanel.showQuestion ( m_currentQuestionResponseXml, points ); // 200 ); //xml );
		
		/**
		* This makes it so that if the question is a text entry one, the user can just start typing right away and hit <Enter> to answer the question.
		*/
		try {
		   questionPanel.focus();
		} catch ( failedToSetFocus ) {
		}
		
	   printTrace ( "post: questionPanel.showQuestion" );
	   m_questionLoadedIntoQuestionPanel = true;
	}
m_debugStr += " survived ... ";	
}
   




/** SLW UP TO HER OK TOO **/


/***
* ------------------------------------ "VIDEO OVERLAY" PROCESSING ---------------------------------------------
***/

/**
* Called by the question panel when the timer is starting to count down.  This is
* our chance to do stuff like initialize the "obscure the movie" overlay
*/
function timerCountdownStarted () {
   setTimeout ( asyncTimerCountdownStarted, 100 );
}
	
/**
* Handles stuff we want to do now that the video is loaded and the user is starting to think about the question.
*/
function asyncTimerCountdownStarted () {

/*
   if ( m_currentQuestionObject.revealStart && m_currentQuestionObject.revealEnd ) {
		
      if ( ( Number(m_currentQuestionObject.revealEnd) > Number(m_currentQuestionObject.revealStart) ) &&
		   ( Number(m_currentQuestionObject.revealStart) > 0 && Number(m_currentQuestionObject.revealEnd) > 0 ) ) {
		
		 var revealStart = Number(m_currentQuestionObject.revealStart) * 1000;
		 var revealEnd = Number(m_currentQuestionObject.revealEnd) * 1000;
		 
		 showHiddenVideoDiv ();
		
	    var revealSwf = "reveal.swf?beginMs=" + revealStart + "&endMs=" + revealEnd;
        embedFlashContent ( "revealswf", "revealDiv", revealSwf, "100%", "100%", 0xffffff, "transparent", "exactFit" );		
      }
   }
 */
}

function showOverlayIfNecessary () {
	
   /**
   * This is where we put up the "overlay" in front of the video if necessary.  Basically, the overlay goes up immediately, then
   * starting at "revealStart" seconds into the question, the first of 3 layers of the overlay is removed (the outermost).  Then
   * the subsequent 2 layers are removed in a step by step fashion.  Each layer takes 1.5 seconds to fade away.  The "revealEnd"
   * variable indicates how many seconds into the question the last of the three layers should be removed.
   */
   if ( m_currentQuestionObject.revealStart && m_currentQuestionObject.revealEnd ) {
		
      if ( ( Number(m_currentQuestionObject.revealEnd) >= Number(m_currentQuestionObject.revealStart) ) &&
		   ( Number(m_currentQuestionObject.revealStart) > 0 && Number(m_currentQuestionObject.revealEnd) > 0 ) ) {
		
		 var revealStart = Number(m_currentQuestionObject.revealStart) * 1000;
		 var revealEnd = Number(m_currentQuestionObject.revealEnd) * 1000;
		 
		 /**
		 * Show the div that the overlay flash animation will live within.
		 */
		 showHiddenVideoDiv ();
		
		 /**
		 * Now embed the flash overlay over the video and show it.
		 */
	    var revealSwf = "/content/game/reveal.swf?beginMs=" + revealStart + "&endMs=" + revealEnd;
		 	
        embedFlashContent ( "revealswf", "revealDiv", revealSwf, "100%", "100%", 0xffffff, "transparent", "exactFit" );		
      }
   }
}

function showClearVideoOverlayDiv () {
	var movieUrl = document.getElementById ( "movieUrl" );
	movieUrl.style.display = "none";
	
	var overTheMovieDiv = document.getElementById ( "overTheMovieDiv" );
	overTheMovieDiv.width = m_videoWidth;
	overTheMovieDiv.height = m_videoHeight;
   var clearVideoOverlay = document.getElementById ( "clearVideoOverlay" );
   if ( clearVideoOverlay ) {
      clearVideoOverlay.style.display = "block";
      clearVideoOverlay.style.width = m_videoWidth; //"500px";  // On IE6 if you set so "100%" it doesn't show the div.
      clearVideoOverlay.style.height = m_videoHeight; //"400px"; // On IE6 if you set so "100%" it doesn't show the div.
   }
}

function hideClearVideoOverlayDiv () {

	var movieUrl = document.getElementById ( "movieUrl" );
	
	if ( movieUrl.innerHTML != "" )
	  movieUrl.style.display = "block";
	else
	  movieUrl.style.display = "none";

    var clearVideoOverlay  = document.getElementById ( "clearVideoOverlay" );
	var overTheMovieDiv    = document.getElementById ( "overTheMovieDiv" );
	overTheMovieDiv.width  = "0px";
	overTheMovieDiv.height = "0px";
   
   if ( clearVideoOverlay ) {
      clearVideoOverlay.style.display = "none";
      clearVideoOverlay.style.width   = "0px"; 
      clearVideoOverlay.style.height  = "0px"; 
   }
}

/**
* Show the "loading video" overlay over the video.
*/
function showLoadingVideoOverlay () {
	
fromFlash_printTrace ( "show loading video called" );

   var revealDiv = document.getElementById ( "revealDiv" );
   revealDiv.style.display = "block";
   revealDiv.style.width = m_videoWidth; //"500px";  // On IE6 if you set so "100%" it doesn't show the div.
   revealDiv.style.height = m_videoHeight; //"400px"; // On IE6 if you set so "100%" it doesn't show the div.
	
   var loadingVideoSwf = "/content/game/loadingVideo.swf";
   embedFlashContent ( "revealswf", "revealDiv", loadingVideoSwf, "100%", "100%", 0xffffff, "transparent", "exactFit" );	
	m_loadingVideoOverlayShowing = true;
}

/**
* Hide the "loading video" overlay that was above the video.
*/
function hideLoadingVideoOverlay () {

fromFlash_printTrace ( "hideLoadingVideoOverlay called, m_loadingVideoOverlayShowing "  + m_loadingVideoOverlayShowing );


//alert ( "HIDE LOADING VIDEO OVERLAY" );

   if ( m_loadingVideoOverlayShowing == true ) {
		var revealDiv = document.getElementById ( "revealDiv" );
		revealDiv.style.display = "none";
		revealDiv.style.width = "0px";
		revealDiv.style.height = "0px";
		revealDiv.innerHTML = "";
		m_loadingVideoOverlayShowing = false;
	}
}


function showHiddenVideoDiv () {
	
//alert ( "SHOW HIDDEN VIDEO DIV CALLED" );

   var revealDiv = document.getElementById ( "revealDiv" );
   revealDiv.style.display = "block";
   revealDiv.style.width = m_videoWidth; //"500px";  // On IE6 if you set so "100%" it doesn't show the div.
   revealDiv.style.height = m_videoHeight; //"400px"; // On IE6 if you set so "100%" it doesn't show the div.
}

function hideHiddenVideoDiv () {
	
   /**
   * First, get access to the Flash overlay.  It might already be gone, but if it isn't, tell it to stop
   * processing (this will tell it to stop animating and to NOT!!! try to call any JavaScript functions.  If
   * we weren't hiding the Flash overlay, it would call "revealIsFinished" when it was done removing the
   * 3 layers of the overlay.
   */
   var revealswf = document.getElementById ( "revealswf" );

   try {
		if ( revealswf ) {
			revealswf.unhideBox ();
           revealswf.stopProcessing ();
		}
   } catch ( exc ) {
		// HIDE. Sometimes we get into a condition where the div is set to display "none."  In those situations, calling
		// any functions on the Flash overlay can cause errors.  
   }
	
   /**
   * Make sure the div containing the "hidden video" overlay is removed from the screen.
   */
   var revealDiv = document.getElementById ( "revealDiv" );
   revealDiv.style.display = "none";
   revealDiv.style.width = "0px";
   revealDiv.style.height = "0px";
}

/**
* The "hidden video" Flash overlay calls this once the video is no longer "hidden"/obscured.
*/
function revealIsFinished () {
	setTimeout ( hideHiddenVideoDiv, 10 ); // Call the "hide the div" function in another thread to prevent crashing the browser.
}


/***
* ------------------------------------ "MISC" FUNCTIONS ---------------------------------------------
***/

/*
   var BASE_SKIN_URL = "http://popjax.s3.amazonaws.com/gameSkins/";
	var HTML_SKIN_DIR = "htmlSkin/"
   function loadHtmlSkin ( elementId, skinName, skinFileName ) {
	
	   var skinUrl = BASE_SKIN_URL + skinName + "/" + HTML_SKIN_DIR + skinFileName;
		
		printTrace ( "URL: " + skinUrl );
		var ajaxCallParms = { 
			method: 'get',
		  
			onComplete: function () {
				printTrace ( "DONE" );
			},
			
			onFailure :function (code) {
			  printTrace ( "FAILURE" );
			}
		}
		
		try {
		   printTrace ( " Ajax.Updater: " + Ajax.Updater );
		   myAjax = new Ajax.Updater ( "skinBehindGameboard", 
			   "/game/resources/AvengeWidgetAttractImageReduced.jpg", ajaxCallParms ); //( elementId, skinUrl, ajaxCallParms );
			printTrace ( "AFTER CALL TO UPDATER" );
		} catch ( exc ) {
		   printTrace ( "EXC: " + exc );
		}
	}
*/



var m_gameStartTime = null;
var m_questionStartTime = null;
var m_videoLoadedTime = null;
var m_exactTimeWhenVideoWasFullyLoaded = null;
var m_questionAnsweredTime = null;
var m_gameOverTime = null;
var m_videoLoadTime = null;
var m_userAnswerQuestionTime = null;
var m_entireTimeWatchingVideo = null;
var m_videoLoadStatus = "unknown";
var m_videoPlayStatus = "unknown";

function initQuestionAndVideoMetrics () {
	m_questionStartTime = null;
	m_exactTimeWhenVideoWasFullyLoaded = null;
	m_videoLoadStatus = "unknown";
	m_entireTimeWatchingVideo = null;
	m_videoPlayStatus = "unknown";
}



function getHoursMinutesSecondsFromTime ( _time ) {

	timediff = _time.getTime();
	
	var retval = new Object;
	
	retval.weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
	timediff -= retval.weeks * (1000 * 60 * 60 * 24 * 7);
	
	retval.days = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
	timediff -= retval.days * (1000 * 60 * 60 * 24);
	
	retval.hours = Math.floor(timediff / (1000 * 60 * 60)); 
	timediff -= retval.hours * (1000 * 60 * 60);
	
	retval.mins = Math.floor(timediff / (1000 * 60)); 
	timediff -= retval.mins * (1000 * 60);
	
	
	retval.secs = Math.floor(timediff / 1000); 
	timediff -= retval.secs * 1000;
	
	return retval;

}

function calculateVideoLoadAndQuestionAnswerTimings () {
	
	try {
		
		// When the user was done answering the question.
		var questionAnsweredTime = new Date ();
		
		// Diff between now and way back when the question's video started to load.
		var questionAnsweredTimeDiff = new Date ();
	    questionAnsweredTimeDiff.setTime(Math.abs(questionAnsweredTime.getTime() - m_questionStartTime.getTime()));
		
		// Convert into an object with hours, minutes, seconds representing the diff.
        questionAnsweredTimeDiff = getHoursMinutesSecondsFromTime (questionAnsweredTimeDiff);
        m_userAnswerQuestionTime =  Number(questionAnsweredTimeDiff.mins) * 60 + Number(questionAnsweredTimeDiff.secs);
		if ( m_userAnswerQuestionTime < 1 ) {
			m_userAnswerQuestionTime = 1;
		}
	   
//alert ( "ANSWER TIME SECS: " + m_userAnswerQuestionTime );	   
		
//alert ( " m_exactTimeWhenVideoWasFullyLoaded: " + m_exactTimeWhenVideoWasFullyLoaded );

        /**
		* If the video never loaded or it wasn't a YouTube video, then "m_exactTimeWhenVideoWasFullyLoaded" has a value
		* of null.  So if this was the case, we process it and see if we are dealing with a "timeout" of a YouTube video or we
		* are dealing with another form of video whose load time we'll never know.
		*/
        if ( m_exactTimeWhenVideoWasFullyLoaded == null ) {
			
			if ( m_videoLoadStatus == "timeout" ) {
				m_exactTimeWhenVideoWasFullyLoaded = new Date(); // Set the video loaded time to when user clicked the "Sorry, video timed out" link.
				var videoLoadedTimeDiffTimeout = new Date();
				videoLoadedTimeDiffTimeout.setTime(Math.abs(m_exactTimeWhenVideoWasFullyLoaded.getTime() - m_questionStartTime.getTime()));
					 
				// Convert into an object with hours, minutes, seconds representing the diff.
				videoLoadedTimeDiffTimeout = getHoursMinutesSecondsFromTime (videoLoadedTimeDiffTimeout);
				m_videoLoadedTime = Number(videoLoadedTimeDiffTimeout.mins) * 60 + Number(videoLoadedTimeDiffTimeout.secs);
				if ( m_videoLoadedTime < 1 ) {
					m_videoLoadedTime = 1;
				}
			} else {
				m_videoLoadedTime = 0; // For non YouTube videos, we assume that it loaded instantly!!!
			}
			
		} else {
			// Diff between when the video was completely loaded and when it started loading.
			var videoLoadedTimeDiff = new Date();
			videoLoadedTimeDiff.setTime(Math.abs(m_exactTimeWhenVideoWasFullyLoaded.getTime() - m_questionStartTime.getTime()));
				 
			// Convert into an object with hours, minutes, seconds representing the diff.
			videoLoadedTimeDiff = getHoursMinutesSecondsFromTime (videoLoadedTimeDiff);
			m_videoLoadedTime = Number(videoLoadedTimeDiff.mins) * 60 + Number(videoLoadedTimeDiff.secs);
			if ( m_videoLoadedTime < 1 ) {
				m_videoLoadedTime = 1;
			}
		}

//alert ( "LOAD TIME SECONDS: " + m_videoLoadedTime );



	} catch ( exc ) {
		// HIDE alert ( "EXC: " + exc );
	}
	
}

function getVideoLoadTimeInSeconds () {
	
	var videoLoadedTimeInSeconds = 0;
	
        if ( m_exactTimeWhenVideoWasFullyLoaded == null ) {
			
			if ( m_videoLoadStatus == "timeout" ) {
				m_exactTimeWhenVideoWasFullyLoaded = new Date(); // Set the video loaded time to when user clicked the "Sorry, video timed out" link.
				var videoLoadedTimeDiffTimeout = new Date();
				videoLoadedTimeDiffTimeout.setTime(Math.abs(m_exactTimeWhenVideoWasFullyLoaded.getTime() - m_questionStartTime.getTime()));
					 
				// Convert into an object with hours, minutes, seconds representing the diff.
				videoLoadedTimeDiffTimeout = getHoursMinutesSecondsFromTime (videoLoadedTimeDiffTimeout);
				videoLoadedTimeInSeconds = Number(videoLoadedTimeDiffTimeout.mins) * 60 + Number(videoLoadedTimeDiffTimeout.secs);
				if ( videoLoadedTimeInSeconds < 1 ) {
					videoLoadedTimeInSeconds = 1;
				}
			} else {
				videoLoadedTimeInSeconds = 0; // For non YouTube videos, we assume that it loaded instantly!!!
			}
			
		} else {
			// Diff between when the video was completely loaded and when it started loading.
			var videoLoadedTimeDiff = new Date();
			videoLoadedTimeDiff.setTime(Math.abs(m_exactTimeWhenVideoWasFullyLoaded.getTime() - m_questionStartTime.getTime()));
				 
			// Convert into an object with hours, minutes, seconds representing the diff.
			videoLoadedTimeDiff = getHoursMinutesSecondsFromTime (videoLoadedTimeDiff);
			videoLoadedTimeInSeconds = Number(videoLoadedTimeDiff.mins) * 60 + Number(videoLoadedTimeDiff.secs);
			if ( videoLoadedTimeInSeconds < 1 ) {
				videoLoadedTimeInSeconds = 1;
			}
		}	
		
	return videoLoadedTimeInSeconds;
}

function calculateTotalTimeInVideo ( _videoPlayStatus ) {
	
//alert ( " CALLED calculateTotalTimeInVideo: " + _videoPlayStatus );

	var timeWatchingVideo = new Date ();
	
	try {
		
		/**
		* If non-null, then this function was already called when the video ended so we don't need to calculate now.
		*/
		if ( m_entireTimeWatchingVideo == null ) {
			
			m_videoPlayStatus = _videoPlayStatus;
			
		   var m_totalTime = new Date();
		   m_totalTime.setTime(Math.abs(timeWatchingVideo.getTime() - m_questionStartTime.getTime()));
		
		   var totalTimeDiff = getHoursMinutesSecondsFromTime (m_totalTime);
	
	//alert ( "TOTAL mins: " + totalTimeDiff.mins + " secs: " + totalTimeDiff.secs );
	
			m_entireTimeWatchingVideo = Number(totalTimeDiff.mins) * 60 + Number(totalTimeDiff.secs);
			
			var videoLoadTimeInSeconds = getVideoLoadTimeInSeconds ();
			//alert ( " videoLoadTimeInSeconds: " + videoLoadTimeInSeconds );
			m_entireTimeWatchingVideo = m_entireTimeWatchingVideo - videoLoadTimeInSeconds; // Remove the video load time from total time in video.
			if ( m_entireTimeWatchingVideo < 1 ) {
				m_entireTimeWatchingVideo = 1;
			}
		
		    
		}


	} catch ( exc ) {
		printTrace ( "EXC: " + exc );
	}
	
}

/**
* This is the function that would send the "VideoPlayed" message to the back end.  This message records how long the user
* was watching the video for the current question.
*/
function sendVideoPlayedMetricsMessage () {
	//alert ( "SEND VIDEO PLAYED METRICS MESSAGE" );
	//alert ( " m_entireTimeWatchingVideo: " + m_entireTimeWatchingVideo + " m_videoPlayStatus: " + m_videoPlayStatus );
	
	/**
	DISABLE FOR NOW. THERE WAS AN ISSUE WHERE GET_QUESTION criss crossed with VideoPlayed and ajax got fucked up.
	dataService_videoPlayed ( handleVideoPlayedResponse,  m_selectedGamePieceCol - 1, m_selectedGamePieceRow - 1, 
			m_entireTimeWatchingVideo, m_videoPlayStatus );
   ***/
	

	//alert ( "after data service" );
	
	/*
		dataService_getAnswer ( handleAnswerReturnedAfterUserSkipQuestion, m_selectedGamePieceCol - 1, m_selectedGamePieceRow - 1, 
	   m_currentQuestionObject.correct_answer, 1, m_videoLoadedTime, m_userAnswerQuestionTime, m_videoLoadStatus  );

	*/
	// m_selectedGamePieceCol - 1, m_selectedGamePieceRow - 1
}

function handleVideoPlayedResponse ( data, xml ) {
	//alert ( "Video played response: " + data );
}


/*
m_entireTimeWatchingVideo
*/


/*
  1.  Copy the coding into the HEAD of your HTML document
  2.  Add the last code into the BODY of your HTML document  -->

<!-- STEP ONE: Paste this code into the HEAD of your HTML document  -->

<HEAD>

<SCRIPT LANGUAGE="JavaScript">
<!-- Original:  Ronnie T. Moore -->
<!-- Web Site:  The JavaScript Source -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin
function isValidDate(dateStr) {
// Date validation function courtesty of 
// Sandeep V. Tamhankar (stamhankar@hotmail.com) -->

// Checks for the following valid date formats:
// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY

var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; // requires 4 digit year

var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
alert(dateStr + " Date is not in a valid format.")
return false;
}
month = matchArray[1]; // parse date into variables
day = matchArray[3];
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
alert("Month must be between 1 and 12.");
return false;
}
if (day < 1 || day > 31) {
alert("Day must be between 1 and 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert("Month "+month+" doesn't have 31 days!")
return false;
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
alert("February " + year + " doesn't have " + day + " days!");
return false;
   }
}
return true;
}

function isValidTime(timeStr) {
// Time validation function courtesty of 
// Sandeep V. Tamhankar (stamhankar@hotmail.com) -->

// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.

var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

var matchArray = timeStr.match(timePat);
if (matchArray == null) {
alert("Time is not in a valid format.");
return false;
}
hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];

if (second=="") { second = null; }
if (ampm=="") { ampm = null }

if (hour < 0  || hour > 23) {
alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
return false;
}
if (hour <= 12 && ampm == null) {
if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
alert("You must specify AM or PM.");
return false;
   }
}
if  (hour > 12 && ampm != null) {
alert("You can't specify AM or PM for military time.");
return false;
}
if (minute < 0 || minute > 59) {
alert ("Minute must be between 0 and 59.");
return false;
}
if (second != null && (second < 0 || second > 59)) {
alert ("Second must be between 0 and 59.");
return false;
}
return true;
}

function dateDiff(dateform) {
date1 = new Date();
date2 = new Date();
diff  = new Date();

if (isValidDate(dateform.firstdate.value) && isValidTime(dateform.firsttime.value)) { // Validates first date 
date1temp = new Date(dateform.firstdate.value + " " + dateform.firsttime.value);
date1.setTime(date1temp.getTime());
}
else return false; // otherwise exits

if (isValidDate(dateform.seconddate.value) && isValidTime(dateform.secondtime.value)) { // Validates second date 
date2temp = new Date(dateform.seconddate.value + " " + dateform.secondtime.value);
date2.setTime(date2temp.getTime());
}
else return false; // otherwise exits

// sets difference date to difference of first date and second date

diff.setTime(Math.abs(date1.getTime() - date2.getTime()));

timediff = diff.getTime();

weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

days = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
timediff -= days * (1000 * 60 * 60 * 24);

hours = Math.floor(timediff / (1000 * 60 * 60)); 
timediff -= hours * (1000 * 60 * 60);

mins = Math.floor(timediff / (1000 * 60)); 
timediff -= mins * (1000 * 60);


secs = Math.floor(timediff / 1000); 
timediff -= secs * 1000;
*/

function sendErrorReportToPopjax () {
	alert ( "Sending Report to VideoJax.com" );
	dataService_userFeedback ( handleErrorReportSentToPopjax, "", "ERROR DUMP (sent to howie@VideoJax.com): " + escape(m_dataServiceTraceString) );
}
								  
										
function handleErrorReportSentToPopjax ( data, xml ) {
	alert ( "Error Reported to VideoJax.com" );
}

function fromFlash_printTrace ( str ) {
	//alert ( "FROM FLASH: " + str );
	printTrace (str);
}

function printTrace ( str ) 
{
	if ( window["m_dataServiceTraceString"] ) 
	{
	   var tslen    = m_dataServiceTraceString.length ;
	   var maxTslen = 12000 ;
	   if ( tslen > maxTslen )
	     m_dataServiceTraceString = m_dataServiceTraceString.substr(tslen-maxTslen,maxTslen) ;
	   m_dataServiceTraceString +=  ("> " + str + "\r") ;
	}
}

function calculateLevel ( lifetimeScore ) {
	
	
	var gameLevel = 1;

	if ( lifetimeScore >= 2500 && lifetimeScore < 3500 ) {
		gameLevel = 2;
	}

	if ( lifetimeScore >= 3500 && lifetimeScore < 5000 ) {
		gameLevel = 3;
	}

/*	
	if ( lifetimeScore >= 500 && lifetimeScore < 1000 ) {
		gameLevel = 2;
	}

	if ( lifetimeScore >= 1000 && lifetimeScore < 5000 ) {
		gameLevel = 3;
	}
*/

	if ( lifetimeScore >= 5000 && lifetimeScore < 10000 ) {
		gameLevel = 4;
	}

	if ( lifetimeScore >= 10000 && lifetimeScore < 15000 ) {
		gameLevel = 5;
	}

	if ( lifetimeScore >= 15000 && lifetimeScore < 20000 ) {
		gameLevel = 6;
	}

	if ( lifetimeScore >= 20000 && lifetimeScore < 30000 ) {
		gameLevel = 7;
	}

	if ( lifetimeScore >= 30000 && lifetimeScore < 40000 ) {
		gameLevel = 8;
	}

	if ( lifetimeScore >= 40000 && lifetimeScore < 50000 ) {
		gameLevel = 9;
	}

	if ( lifetimeScore >= 50000 && lifetimeScore < 75000 ) {
		gameLevel = 10;
	}

	if ( lifetimeScore >= 75000 && lifetimeScore < 100000 ) {
		gameLevel = 11;
	}

	if ( lifetimeScore >= 100000 && lifetimeScore < 150000 ) {
		gameLevel = 12;
	}

	if ( lifetimeScore >= 150000 && lifetimeScore < 200000 ) {
		gameLevel = 13;
	}

	if ( lifetimeScore >= 200000 && lifetimeScore < 250000 ) {
		gameLevel = 14;
	}

	if ( lifetimeScore >= 250000 && lifetimeScore < 300000 ) {
		gameLevel = 15;
	}

	if ( lifetimeScore >= 300000 && lifetimeScore < 350000 ) {
		gameLevel = 16;
	}

	if ( lifetimeScore >= 350000 && lifetimeScore < 400000 ) {
		gameLevel = 17;
	}

	if ( lifetimeScore >= 400000 && lifetimeScore < 450000 ) {
		gameLevel = 18;
	}

	if ( lifetimeScore >= 450000 && lifetimeScore < 500000 ) {
		gameLevel = 19;
	}

	if ( lifetimeScore >= 500000 && lifetimeScore < 600000 ) {
		gameLevel = 20;
	}

	if ( lifetimeScore >= 600000 && lifetimeScore < 700000 ) {
		gameLevel = 21;
	}

	if ( lifetimeScore >= 700000 && lifetimeScore < 800000 ) {
		gameLevel = 22;
	}

	if ( lifetimeScore >= 800000 && lifetimeScore < 900000 ) {
		gameLevel = 23;
	}

	if ( lifetimeScore >= 900000 && lifetimeScore < 1000000 ) {
		gameLevel = 24;
	}

	if ( lifetimeScore >= 1000000 ) {
		gameLevel = 25;
	}

	return gameLevel;
}

function fromFlash_showPreciseVersion () {
	alert ( "Build Version: " + PRECISE_BUILD_VERSION );
}

function answeringBonusQuestion () {
	return m_currentQuestionResponseObject.hasBonusQuestion ();
}

function userIsLoggedIn () {
	
	var userLoggedIn = false;
	
	if ( m_userInfo ) {
		userLoggedIn = ( ( m_userInfo.code != "UNREGISTERED_USER" ) && ( m_userInfo.name.indexOf ( "anonymous" ) < 0 ) );
	}
	
//alert ( "SCOTT: userLoggedIn: " + userLoggedIn );

	return userLoggedIn;
}

function getPlayerEmailAddress () {
	if ( userIsLoggedIn () ) {
		//alert ( " EMAIL IS: "  + m_userInfo.email );
		return m_userInfo.email;
	} else {
		//alert ( "NOT LOGGED IN" );
		return null;
	}
}

function stringIsBlank ( str ) {
	var blankRE=/^[\s]+$/
	if ( str == "" || blankRE.test(str) ) {
		return true;
	} else {
		return false;
	}
}

function getWholeCookie ( offset ) {
	var endstr = document.cookie.indexOf ( ";", offset );
	if ( endstr == -1 ) {
		endstr = document.cookie.length;
	}
	return unescape(document.cookie.substring(offset, endstr));
}

function getCookie ( cookieName ) {
	var arg = cookieName + "=";
	var argLength = arg.length;
	var cookieLength = document.cookie.length;
	var i = 0;
	while ( i < cookieLength ) {
		var j = i + argLength;
		if ( document.cookie.substring(i,j) == arg ) {
			return getWholeCookie(j);
		}
		i = document.cookie.indexOf ( " ", i) + 1;
		if ( i == 0 ) {
			break;
		}
	}
	
	return null;
}

function setCookie ( name, value ) {
	document.cookie = name + "=" + escape(value);
}

function setSingleSessionCookie ( name, value ) {
	document.cookie = name + "=" + escape(value);
}

function tossCookie ( name ) {
	if ( getCookie(name) ) {
		document.cookie = name + "= null; expires=Thu, 01-Jan-2001 00:00:01 GMT";
	}
}


/**
* Test for whether or not we're running within IE.
*/
function isIE () {
	
	var _isIE = false;
	
	    var agt=navigator.userAgent.toLowerCase();
        var myApp = navigator.appName;
		if ( myApp.indexOf ( "Microsoft" ) >= 0 && agt.indexOf ("msie") >= 0  ) {
		   _isIE = true;
		}
		
	return  _isIE;	
}


function dumpTrace ( requiredPassword ) {
	
	//alert ( "DUMP TRACE" );
 	var password = prompt ( "Password?" );
	if ( password == requiredPassword ) {
		showTraceMessagesDialog ();
		//alert ( " MATCH! " );
	}
	//alert ( " requiredPassword: " + requiredPassword + " password: " + password );
}

function fromFlash_showProofSheet ( requiredPassword ) {
	
	//alert ( "DUMP TRACE" );
 	var password = prompt ( "Password?" );
	if ( password == requiredPassword ) {
		showProofSheet();
		//alert ( " MATCH! " );
	}
	//alert ( " requiredPassword: " + requiredPassword + " password: " + password );
}

function showProofSheet () {
	//alert ( "SHOW PROOF SHEET" );
	
	if ( m_gameId ) {
		window.location.href = "/videocube/gameProofSheet.jsp?gameId=" + m_gameId;
	}
	
}

/**
* This can be used by Flash components to put up the "alert" box in the browser.
*/
function alertInBrowser ( msg ) {
	alert  ( msg );
}

/**
* This is called when the user clicks the "Play Another Game" link.
*/
function playAnotherGame () {
	 
	// alert ( "CALLING FIX MEMORY LEAKS" );
	 
   //fixMemoryLeaksFromFlashMovie ();
   
   trackUserAction ("EndGame_ReturnToChooser") ;
	 
   window.location.href = "/videocube/index.htm"; //hitGameNoLeak.html";
}
 
/**
* It is VERY important to call this from IE when we are done playing a game.  It should remove some of the memory leaks that
* sit around after you've dynamically embedded Flash into a web page.
*/
function fixMemoryLeaksFromFlashMovie ( movieDivId ) {
	 var playingFlashMovie = null;
	 
	 if ( movieDivId ) {
		  playingFlashMovie = $( movieDivId ); 
	 } else {
		 playingFlashMovie = $( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie"); 
	 }
	 
	// alert ( " FIX LEAKS ON THIS GUY: " + playingFlashMovie );
	 
	 if ( playingFlashMovie == null ) {
		 return null;
	 }
	 
	for (var i in playingFlashMovie) {
			if (typeof playingFlashMovie[i] == "function") {
				
		//	 alert ( "FOUND A FUNCTION, NULLING IT OUT" );
				
				var bail = false;
				
				  try {
					playingFlashMovie[i] = function() {};
				  } catch ( exc ) {
					// HIDE  alert ( " EXC: " + exc );
					  bail = true;
				  }
			}
			if ( bail ) {
				break;
			}
	}
	
 //	alert ( "REMOVING MOVIE NOW" );
	playingFlashMovie.parentNode.removeChild(playingFlashMovie);
	 
 //	alert ( "DONE" );
}




/***
* ------------------------------------ "VIDEO/EMBED/URL" PROCESSING ---------------------------------------------
***/


/**
* This converts a url into an "embed" tag for the video.
*
* NOTE!!!: This should be extended as we add new video sites that we want to support.  This magic
* function returns the "embed" tags for the various sites in the correctly formatted, formatting of formatation.
*/
function getMovieEmbedFromUrl (url)
{

	if (url.indexOf("youtube.com")!=-1)
	{
		var i = url.indexOf("?v=")+3;
		var c = url.substring(i, i+11);
		//var e = '<embed src="http://www.youtube.com/v/'+c+'&autoplay=1&rel=0" type="application/'+
		//	'x-shockwave-flash" wmode="transparent" width="405" scale="showall" height="353"></embed>';

// 
// With old Youtube client without!!! the API
//

		var e = '<embed src="http://www.youtube.com/v/'+c+'&autoplay=1&rel=0" type="application/'+
			'x-shockwave-flash" wmode="transparent" width="90%" scale="showall" height="90%"></embed>';


//
// With new YouTube client-side API
//
/*
		var e = '<embed id="playingFlashMovie" src="http://www.youtube.com/v/'+c+'&autoplay=1&rel=0&enablejsapi=1&playerapiid=ytplayer" type="application/'+
			'x-shockwave-flash" wmode="transparent" width="90%" scale="showall" height="90%"></embed>';
*/
			
		return e;
	}
	
	/**
	* SLW 601.  Added this.  This assumes that we use a url structure identical to youtube urls except instead of "youtube.com" it is
	* "popjax.com"
	*/
	// if (url.indexOf("rtmp:") != -1 ) 
	if ( useHousePlayer(url) )
	{
		/**
		* In the name of haste, we are just returning the url.  It will then be passed into "extractVideoIdFromEmbed" which will also return
		* the URL.  (All of this nonsense "stays the same" whether processing a youtube url or one with an "rtmp" url.
		*/
		return url;		
	}
	
	
	
	if (url.indexOf("livevideo.com")!=-1)
	{
		var i = url.indexOf("?cid=") ;
		if (i == -1) 
		{
			i = url.lastIndexOf("/") - 32;
		}
		else
		{
			i += 5; // skip past cid
		}
		var c = url.substring(i, i+32);
		//var e = '<embed src="http://www.livevideo.com/flvplayer/embed/'+c+'2&autostart=1" '+
		//	'type="application/x-shockwave-flash" quality="high" WIDTH="425" HEIGHT="369" '+
		//	'wmode="transparent" autoplay="true"></embed>';
		// WAS scale="showall" 
			
		var e = '<embed id="nonYouTubeEmbeddedVideo" src="http://www.livevideo.com/flvplayer/embed/'+c+'2&autostart=1" '+
			'type="application/x-shockwave-flash" quality="high" width="100%" scale="showall" height="100%" '+
			'wmode="transparent" autoplay="true"></embed>';
			
		return e;
	}
	if (url.indexOf("metacafe.com")!=-1)
	{
		var i = url.indexOf("/watch/")+7;
		var c = url.substring(i);
		if (c.substring(c.length-1)=="/")
			c = c.substring(0,c.length-1);
		var e = '<embed id="nonYouTubeEmbeddedVideo"  src="http://www.metacafe.com/fplayer/'+c+'.swf" width="100%" '+
			'height="100%" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" '+
			'type="application/x-shockwave-flash" flashVars="playerVars=showStats=no|autoPlay=yes|videoTitle="> </embed>';
		return e;
	}
	if (url.indexOf("myspace.com")!=-1)
	{

		var i = url.indexOf("videoid=")+8;
		var c = url.substring(i);
		var e = '<embed id="nonYouTubeEmbeddedVideo"  src="http://lads.myspace.com/videos/vplayer.swf" '+
			'flashvars="m='+c+'&a=1" '+
			'type="application/x-shockwave-flash" width="100%" '+
			'height="100%" wmode="transparent"></embed>';
		return e;
	
	}
	
	if (url.indexOf("myspacetv.com")!=-1)
	{

		var i = url.indexOf("videoid=")+8;
		var c = url.substring(i);
		var e = '<embed id="nonYouTubeEmbeddedVideo"  src="http://lads.myspace.com/videos/vplayer.swf" '+
			'flashvars="m='+c+'&a=1" '+
			'type="application/x-shockwave-flash" width="100%" '+
			'height="100%" wmode="transparent"></embed>';
		return e;
	
	}	
}

/**
* This looks for an embed tag for a youtube video and grabs the videoid from that embed tag.
*/
function extractVideoIdFromEmbed ( embed ) {
	
	/**
	* SLW 601.  Assumes that videos streamed thru the popjax player have an embed with "popjax.com" rather than "youtube.com".  But structure
	* of embed is identical to that of youtube.com.
	*/
	var embedPreamble = null;
	if ( embed.indexOf ( "youtube" ) >= 0 ) {
		embedPreamble = "http://www.youtube.com/v/";
	} else {
		//embedPreamble = "http://www.popjax.com/v/";
		return embed; 
	}
	
	var lenOfPreamble = embedPreamble.length; // SLW 601  "http://www.youtube.com/v/".length;
	var idxVideoId = embed.indexOf ( embedPreamble ); // SLW 601  "http://www.youtube.com/v/" );
	idxVideoId += lenOfPreamble;
	var idxAutoplayParm = embed.indexOf ( "&autoplay" );
	
	var videoId = embed.substr ( idxVideoId, ( idxAutoplayParm - idxVideoId ) );
	
	return videoId;
}

/*
var m_isYouTubeVideo = false;

function setIsYouTubeVideo ( b ) { m_isYouTubeVideo = b; };

function getIsYouTubeVideo () { return m_isYouTubeVideo; }

function extractVideoIdFromEmbed ( embed ) {
	var lenOfPreamble = "http://www.youtube.com/v/".length;
	var idxVideoId = embed.indexOf ( "http://www.youtube.com/v/" );
	idxVideoId += lenOfPreamble;
	var idxAutoplayParm = embed.indexOf ( "&autoplay" );
	
	var videoId = embed.substr ( idxVideoId, ( idxAutoplayParm - idxVideoId ) );
	
	return videoId;
}


function extractLinkToVideoFromEmbed ( embed ) {
	var idxStartOfLink = embed.indexOf ( "<a" );
	var idxEndOfLink = embed.indexOf ( "</a>" );
	idxEndOfLink += 4;
	
	var linkText = embed.substr ( idxStartOfLink, ( idxEndOfLink - idxStartOfLink ) );
	
	return linkText;
}
*/


/*

<a href='"+url+"' style='font-size:small' target='_blank'>"+url+"</a>


var e = '<embed id="playingFlashMovie" src="http://www.youtube.com/v/'+c+'&autoplay=1&rel=0&enablejsapi=1&playerapiid=ytplayer" type="application/'+
			'x-shockwave-flash" wmode="transparent" width="90%" scale="showall" height="90%"></embed>';
*/

/*
function embedYouTubeVideo ( flashContentId, parentDivId, swfPath, width, height  ) {
		
//var atts = { id: "myytplayer" };
		
	   var so = new SWFObject( swfPath, flashContentId, width, height, "8" ); //, backColor );
	   so.addParam("quality", "high");
       so.addParam("wmode", "transparent" ); // "transparent" ); //window");
       so.addParam("allowScriptAccess", "always");
       so.addParam("salign", "TL");
	   so.addParam("align", "TL");
	   so.addParam("scale", "exactFit" ); //noScale");
	   
	   so.addVariable("id", "ytplayer");
	   
	   so.useExpressInstall('expressinstall.swf');
	   so.write( parentDivId );	
}
*/

/**
* This is a callback that we register with the youtube flash video player.  It tells us as the state of the currently loaded (or loading)
* video changes.  This is where we decide when to let the Question panel know when the video is loaded and the user can begin answering
* the question.
*/
function onPlayerStateChange(newState) {
  
 // alert("Player's new state: " + newState);
   
  // var currentVideoEvent = document.getElementById ( "currentVideoEvent" );

     fromFlash_printTrace ( "PLAYER STATE: " + newState + " m_isSkipAheadQuestion:  " + m_isSkipAheadQuestion + " m_didSeekForSkipAhead: " + m_didSeekForSkipAhead +
									" m_loadingVideoOverlayShowing: " + m_loadingVideoOverlayShowing ); 

   switch ( newState ) {
		
		
      case -1: /* ??? */
	    break;
		
      case 0: /* VIDEO ENDED */
	   // alert ( "VIDEO ENDED" );
	     calculateTotalTimeInVideo ( "playToEnd" );
	     break;
		 
	   case 1: /* PLAYING */
	     if ( !m_toldGameThatVideoIsPlaying ) {
			 
			 
			 /**
			 * Hide the thingy that lets you bail from the question.
			 */
	         var skipQuestionDiv = document.getElementById ( "skipQuestionDiv" );
	         skipQuestionDiv.style.display = "none";
			 
			 m_toldGameThatVideoIsPlaying = true;
	         tellGameYouTubeVideoReady ();
				
				/**
				* Hide the "Loading Video" overlay.
				*/
				if ( m_isSkipAheadQuestion == false ) {
				   hideLoadingVideoOverlay ();
				}
		 }
		 
/*
function hideLoadingVideoOverlay () {

fromFlash_printTrace ( "hideLoadingVideoOverlay called, m_loadingVideoOverlayShowing "  + m_loadingVideoOverlayShowing );

*/
     fromFlash_printTrace ( "PLAY, m_isSkipAheadQuestion:  " + m_isSkipAheadQuestion + " m_didSeekForSkipAhead: " + m_didSeekForSkipAhead +
									" m_loadingVideoOverlayShowing: " + m_loadingVideoOverlayShowing ); 
									
		 /**
		 * Now we can hide the "Loading video..." overlay in those situations where it was a "seek ahead into the video" type question.
		 */
		 if ( m_isSkipAheadQuestion == true && m_didSeekForSkipAhead == true && m_loadingVideoOverlayShowing ) {
			 if ( m_wentIntoBufferingDuringSkipAhead ) {
				 hideLoadingVideoOverlay ();
			 }		 
		}
		 
		 //alert ( " m_isSkipAheadQuestion: " + m_isSkipAheadQuestion + "  m_didSeekForSkipAhead: " + m_didSeekForSkipAhead );
/*
		if ( m_isSkipAheadQuestion == true ) {
			m_didSeekForSkipAhead = true;
	//		hideLoadingVideoOverlay ();
		}
*/

	     break;
		 
	  case 2: /* PAUSED */
	     break;
		 
	   case 3: /* BUFFERING */
		   /**
			* If we are in "seek ahead" process and we've hit the BUFFERING stage, we can't be certain ho long it will take for the
			* buffered and skipped-ahead video to show up in the player.  So turn off the thread that woudl have torn down the "loading video" overlay (since
		   * we wouldn't want that overlay torn down before the video that is being buffered into the player arrived).
			*/
		   if ( m_didSeekForSkipAhead ) {
			   m_wentIntoBufferingDuringSkipAhead = true;   
			   killTakeDownOverlayThread ();
		   } 		
		
	      break;
		 
	   case 5: /* VIDEO CUEUED - note that if you are using the non "chromeless" video player, this is when we know the 
	              video is loaded and the user can start answering the question. */
		 // WITH THE "CHROMED" VERSION OF PLAYER WE DO THIS tellGameYouTubeVideoReady ();
	    //  currentVideoEvent.innerHTML = ( "Player Event Received By Web Page:  [VIDEO CUED]" );
	      break;
   }
}

function onPlayerError ( code ) {
   //alert ( "YOutube player error: " + code );
	
   if ( m_checkIfVideoLoadedYetTimerId ) {
		clearTimeout(m_checkIfVideoLoadedYetTimerId);
		m_checkIfVideoLoadedYetTimerId = null;
   }

   checkIfVideoLoadedYet ();

   m_videoLoadStatus = "error";	
}

/**
* This is where we communicate with the Flash question panel - telling it that the video is loaded and the user
* can now start answering the question.
*/
function tellGameYouTubeVideoReady () {
	
//alert ( " tellGameYouTubeVideoReady called" );

	
	// Record when the video was loaded...
	m_exactTimeWhenVideoWasFullyLoaded = new Date ();
	
	m_videoLoadStatus = "loaded";
	
   m_youTubeVideoReady = true;
	
   if ( m_youTubeVideoReady && m_questionPanelLoaded && ( m_gameKnowsYouTubeVideoLoaded == false ) ) {
      m_youTubeVideoReady = true;
      m_gameKnowsYouTubeVideoLoaded = true;
	  
	  unMuteYouTubeVideo ();
	  // Talk to the Flash question panel here.
      var questionPanel = document.getElementById ( "questionPanel" ); 
	  printTrace ( "pre: questionPanel.youTubeVideoCueued" );
	  //alert ( "FOO" );
	  questionPanel.youTubeVideoCueued ();
	  printTrace ( "post: questionPanel.youTubeVideoCueued" );
	  
	  /**
	  * This handles the situation where the user answered the question before the you tube API told us the video was ready.
	  */
	  if ( m_answerFromUser ) {
		  

		  // Store the time that the user answered the question
		 // m_questionAnsweredTime = new Date ();
		  calculateVideoLoadAndQuestionAnswerTimings();
		  
		  m_getAnswerDataServiceToCall ( handleAnswerReturned, m_selectedGamePieceCol - 1, m_selectedGamePieceRow - 1, 
			  m_answerFromUser, m_scaleFromAnswer, m_videoLoadedTime, m_userAnswerQuestionTime, m_videoLoadStatus  );
		  m_answerFromUser = null;
	  }
   }
}

/**
* This will stop (not pause) the currently loaded YouTube video.  Only once the video is stopped
* can you "clear" the video (I think!!!).
*/
function stopYouTubeVideo() {
	
   var playingFlashMovie = $( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie"); 
	
   if (playingFlashMovie) {
      playingFlashMovie.stopVideo();
   }
}
		
/**
* "Clear" the video out of the you tube player.  This should (theoretically, close any net stream/connection objects that are lying around
* as well as clean up any memory that was allocated for the video we are "clearing" out of the player.  Don't think this actually does a 
* complete job as of 3/26/08 (there seems to still be memory leaks when using this over and over again in IE).
*/
function clearVideo() {
	 
   var playingFlashMovie = $( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie");
   
   if (playingFlashMovie) {
      playingFlashMovie.clearVideo();
   }
}
		
/**
* This variable remembers whether or not we've told the game that the current video is loaded.
*/
var m_toldGameThatVideoIsPlaying = false;


/**
* This loads a YouTube video into the "chromeless" YouTube video player.
*
* Parms: id - The YouTube Video ID
*        startSeconds - How many seconds into the video to start (in other words, the starting cueue point in terms of seconds).
*/
function loadNewVideo(id, startSeconds) {

   /**
   * At first we are at the point where the game doesn't know whether the video has been loaded and is ready
   * to watch yet.
   */
   m_toldGameThatVideoIsPlaying = false;
	
	if ( m_isSkipAheadQuestion ) {
	   /**
	   * Put the "loading video" overlay up.
	   */
	   showLoadingVideoOverlay ();
	}
	 
   var playingFlashMovie = $( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie"); 

   if (playingFlashMovie) {
	   
     m_checkIfVideoLoadedYetTimerId = setTimeout ( checkIfVideoLoadedYet, SHOW_SKIP_BUTTON_AFTER_THIS_MANY_MS  );
 //alert ( "ID: " + id );

//alert ( " m_isYouTubeVideo: " + m_isYouTubeVideo );

      if ( m_isYouTubeVideo == true ) {
			playingFlashMovie[YOU_TUBE_LOAD_VIDEO_FUNCTION](id, startSeconds);
		} else {
			
			playingFlashMovie[POP_JAX_LOAD_VIDEO_FUNCTION](id, startSeconds);
		}
      // SLW 601 was --> playingFlashMovie.loadVideoById(id, startSeconds);
   }
}
 
 
 
 /*
                         win.attachEvent("onunload", function () {
                                var obj = getElementById(id);
                                if (obj) {
                                        for (var i in obj) {
                                                if (typeof obj[i] == "function") {
                                                        obj[i] = function() {};
                                                }
                                        }
                                        obj.parentNode.removeChild(obj);
                                }
                        });

 */
		
var m_veryFirstVideoId = null;
var m_videoPlayerLoaded = false;
var m_popjaxPlayerLoaded = false;

//function onPopjaxPlayerReady () {
//	alert ( "ON POP JAX PLAYER READY" );
//}

function onYouTubePlayerReady(playerId) {

//alert ( "ON YOU TUBE POP JAX PLAYER READY" );

  // if ( m_isPopJaxVideo ) {
//		
	//	alert ( "doing this for testing only" );
	//	onPopJaxPlayerReady ();
	//	return;
	//}
	
   m_videoPlayerLoaded = true;
  
   var playingFlashMovie = $( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie"); // was "theMovie"
   loadNewVideo ( m_veryFirstVideoId, 0 );
   playingFlashMovie.addEventListener("onStateChange", "onPlayerStateChange");
   playingFlashMovie.addEventListener("onError", "onPlayerError");
}   

function onPopJaxPlayerReady() {

//alert ( "ON POP JAX PLAYER READY" );

   m_popjaxPlayerLoaded = true;
  
   var playingFlashMovie = $( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie"); // was "theMovie"
   loadNewVideo ( m_veryFirstVideoId, 0 );
   playingFlashMovie.addEventListener("onStateChange", "onPlayerStateChange");
   playingFlashMovie.addEventListener("onError", "onPlayerError");
}   


/**
* SLW 11/15/08 - START OF HOTFIX FOR VIDEO OVERLAY NOT GOING AWAY 
*/
//var m_seekToSecondsValue = null;
var m_overlayTakedownThread = null;
var m_wentIntoBufferingDuringSkipAhead = false;
var MS_TO_WAIT_BEFORE_PULLING_DOWN_SKIP_AHEAD_OVERLAY = 1000;

function killTakeDownOverlayThread () {
	if ( m_overlayTakedownThread != null ) {
		clearInterval (m_overlayTakedownThread);
		m_overlayTakedownThread = null;
	}
}

function takeDownOverlay () {
	try {
		//var playingFlashMovie = $("theMovie");
		//var currPlayhead = Number( playingFlashMovie.getCurrentTime() );
		//printTrace ( "CURR PLAYHEAD POSITION: " + currPlayhead );
		//if ( currPlayhead >= m_seekToSecondsValue ) {
			clearInterval (m_overlayTakedownThread);
			m_overlayTakedownThread = null;
			//alert ( "cleared interval currPlayhead:" + currPlayhead );
			hideLoadingVideoOverlay ();
		//}
		//printTrace ( "CURR POS: " + currPlayhead );
	} catch ( exc ) {
	}
}

function startVideoOverlayTakedownThread ( ) {
	m_wentIntoBufferingDuringSkipAhead = false;
	//m_seekToSecondsValue = seekToSecondsValue;
	if ( m_overlayTakedownThread != null ) {
		clearInterval (m_overlayTakedownThread);
		m_overlayTakedownThread = null;
	}
	m_overlayTakedownThread = setInterval ( takeDownOverlay, MS_TO_WAIT_BEFORE_PULLING_DOWN_SKIP_AHEAD_OVERLAY );
}
/**
* SLW 11/15/08 - END OF HOTFIX FOR VIDEO OVERLAY NOT GOING AWAY 
*/


function startYouTubeVideoAtThisCuePoint ( seconds ) {
	
printTrace ( "CALL FROM QUESTION PANEL: startYouTubeVideoAtThisCuePoint () " );
	
//	alert ( "SEEK SECONDS: " + seconds );
	try {
		
/**
* SLW 11/15/08 - START OF HOTFIX FOR VIDEO OVERLAY NOT GOING AWAY 
*/		
		startVideoOverlayTakedownThread ( );
/**
* SLW 11/15/08 - END OF HOTFIX FOR VIDEO OVERLAY NOT GOING AWAY 
*/


		if ( m_isSkipAheadQuestion == true ) {
			m_didSeekForSkipAhead = true;
	//		hideLoadingVideoOverlay ();
		}
		
	   var playingFlashMovie = $( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie");	
	   if ( playingFlashMovie )
	   {
         printTrace ( "VIDEO Player [" + m_youtubeTypeVideoPlayerId + "] seekTo(): " + seconds );
	     playingFlashMovie.seekTo( seconds, true );
	   }
	    else
           printTrace ( "** NO VIDEO Player for seekTo(): " + seconds );
		
				
	} catch ( exc ) {
		printTrace ( "EXC: " + exc );
	}
}

function pauseYouTubeVideo () {

printTrace ( "CALL FROM QUESTION PANEL: pauseYouTubeVideo () " );

	//alert ( "PAUSE" );
	var playingFlashMovie = $( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie");	
	playingFlashMovie.pauseVideo ();
}

function resumeYouTubeVideo () {
	
printTrace ( "CALL FROM QUESTION PANEL: resumeYouTubeVideo () " );

	//alert ( "RESUME" );
	var playingFlashMovie = $( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie");	
	playingFlashMovie.playVideo ();
}

function muteYouTubeVideo () {
	
printTrace ( "CALL FROM QUESTION PANEL: muteYouTubeVideo () " );

	//alert ( "MUTE" );
	var playingFlashMovie = $( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie");	
	playingFlashMovie.mute ();
}

function unMuteYouTubeVideo () {
	
printTrace ( "CALL FROM QUESTION PANEL: unMuteYouTubeVideo () " );

	//alert ( "UNMUTE" );
	try {
	  var playingFlashMovie = $( m_youtubeTypeVideoPlayerId ); // SLW 601 "theMovie");	
	  playingFlashMovie.unMute ();
	  playingFlashMovie.setVolume(100);
	 // alert ( "SHOULD HAVE DONE IT" );
	} catch ( exc ) {
		 printTrace ( " EXC: " + exc );
	}
}


/** SLW UP TO HERE OK TOO **/

/* 
/////////////////////////////////////////////////////////////////////////////////////
//
// End of new YouTube API Stuff
//
////////////////////////////////////////////////////////////////////////////////////////
*/




function getDebugPasswordFromUser() {
   var password = prompt("Password please", "")
   return password;
}




/**********************************************************************
* CALLED BY FLASH
***********************************************************************/

/**
* The user clicked the thumbs up or thumbs down icon for the question.
*/
function fromFlash_rateQuestion ( questionId, rating ) {
	try {
printTrace ( "CALL FROM QUESTION PANEL: fromFlash_rateQuestion () " );		
		dataService_rateQuestion ( handleRateQuestionResponse, questionId, rating );
	} catch ( exc ) {
		printTrace ( "fromFlash_rateQuestion Exception: " + exc );
	}
}

/**
* Invoked once the response to the "rate question" message is returned by the back end.
*/
function handleRateQuestionResponse ( data, xml ) {
	// NO OP!!! alert ( "RATE QUESTION RESPONSE: " + data );
}

/**
* The user clicked the "tag as favorite" icon for the question.
*/
function fromFlash_markQuestionAsFavorite ( questionId ) {
	try {
printTrace ( "CALL FROM QUESTION PANEL: fromFlash_markQuestionAsFavorite () " );			
		if ( userIsLoggedIn () == false ) {
			alert ( "You must be logged in to save a favorite question." );
		} else {
		   dataService_markQuestionAsFavorite ( handleMarkAsFavoriteResponse, questionId );
		}
	} catch ( exc ) {
		printTrace ( "fromFlash_markQuestionAsFavorite Exception: " + exc );
	}
}

/**
* Invoked once the response to the "rate question" message is returned by the back end.
*/
function handleMarkAsFavoriteResponse ( data, xml ) {
	// NO OP!!!  alert ( "MARK QUESTION AS FAVORITE RESPONSE: " + data );
}



/***
* ------------------------------------ "GAME SOUNDS" PROCESSING ---------------------------------------------
***/

function fromFlash_playSound ( soundId ) {
	printTrace ( " PLAY SOUND: " + soundId );
}

function fromFlash_stopSounds () {
	printTrace ( "STOP SOUNDS" );
}



/***
* ------------------------------------ USER NEEDS A DATA ENTRY FORM ---------------------------------------------
***/

/**
* The user clicked the "video not loading" link in the question panel.
*/
function fromFlash_showVideoNotLoadingDialog ( questionId ) {
//	alert ( " SHOW VIDEO NOT LOADING DIALOG " );
	showVideoNotLoadingDialog ( questionId );
}

/**
* The user clicked the "submit a question for this video" link in the question panel.
*/
function fromFlash_showSubmitQuestionDialog ( questionId ) {
	//alert ( "SHOW SUBMIT QUESTION DIALOG" );
	//if ( m_currentQuestionObject.url.indexOf ( "youtube" ) < 0 ) {
	//} else {
		
	if ( userIsLoggedIn () == false ) {
		alert ( "You must be logged in to submit a question." );
	} else {		
        showSubmitQuestionDialog ( questionId );
	}
	//}
}

/**
* The user clicked the "send question to a friend" link in the question panel.
*/
function fromFlash_showSendQuestionToFriendDialog ( questionId ) {
//	printTrace ( "SHOW SEND QUESTION TO FRIEND DIALOG" );
	showSendQuestionToFriendDialog ( questionId );
}




/***
* ------------------------------------ "LOCKOUT" (USER DIDN'T ANSWER QUESTION IN TIME ) ------------------
***/

/**
* Called when the timer has ticked down to zero and the user didn't answer the question.
* Tells the back end to mark the question as if it were answered incorrectly.
*/
function fromFlash_lockoutQuestion ( questionId, callbackName ) {
	
    // Store the time that the user answered the question
	//m_questionAnsweredTime = new Date ();
	calculateVideoLoadAndQuestionAnswerTimings();
	
printTrace ( "CALL FROM QUESTION PANEL: fromFlash_lockoutQuestion () " );

    // Remember the callback (hosted by the Flash question panel) that we'll call once we get the answer back from the back end.
	m_answerReceivedCallbackName = callbackName;
	
	try {
		dataService_lockoutQuestion ( handleAnswerReturned, m_selectedGamePieceCol - 1, m_selectedGamePieceRow - 1, m_videoLoadedTime, m_userAnswerQuestionTime, m_videoLoadStatus );
	} catch ( exc ) {
		printTrace ( "fromFlash_lockoutQuestion Exception: " + exc );
	}
}	

/**
* Called when the timer has ticked down to zero and the user didn't answer the bonus question.
* Tells the back end to mark the question as if it were answered incorrectly.
*/
function fromFlash_lockoutBonusQuestion ( questionId, callbackName ) {
	
    // Store the time that the user answered the question
	//m_questionAnsweredTime = new Date ();
	calculateVideoLoadAndQuestionAnswerTimings();
	
printTrace ( "CALL FROM QUESTION PANEL: fromFlash_lockoutBonusQuestion () " );

    // Remember the callback (hosted by the Flash question panel) that we'll call once we get the answer back from the back end.
	m_answerReceivedCallbackName = callbackName;
	
	try {
		dataService_lockoutBonusQuestion ( handleAnswerReturned, m_selectedGamePieceCol - 1, m_selectedGamePieceRow - 1, m_videoLoadedTime, m_userAnswerQuestionTime, m_videoLoadStatus );
	} catch ( exc ) {
		printTrace ( "fromFlash_lockoutBonusQuestion Exception: " + exc );
	}
}

/**
* Called when the timer has ticked down to zero and the user didn't answer the question while
* looking at in "preview" mode. Tells the back end to mark the question as if it were 
* answered incorrectly.
*/
function fromFlash_lockoutPreviewQuestion ( questionId, callbackName ) {
	
    // Store the time that the user answered the question
	//m_questionAnsweredTime = new Date ();
	calculateVideoLoadAndQuestionAnswerTimings();
	
printTrace ( "CALL FROM QUESTION PANEL: fromFlash_lockoutPreviewQuestion () " );

    // Remember the callback (hosted by the Flash question panel) that we'll call once we get the answer back from the back end.
	m_answerReceivedCallbackName = callbackName;
	
	try {
		dataService_lockoutPreviewQuestion ( handleAnswerReturned, questionId, m_videoLoadedTime, m_userAnswerQuestionTime, m_videoLoadStatus );
	} catch ( exc ) {
		printTrace ( "fromFlash_lockoutPreviewQuestion Exception: " + exc );
	}
}

/**
* This is the callback that is invoked once the back end responds to a "LOCKOUT" message
* the game sends it.
*/
//function handleLockoutQuestionReturned ( data, xml ) {
//	alert ( "LOCKOUT EXECUTED: " + data );
//}






/***
* ------------------------------------ PROCESS "ANSWER" TO QUESTION ---------------------------------------------
***/



/**
* This stores the callback (hosted by the Flash question panel) that we'll call once an answer
* for a question is returned by the back end.
*/
var m_answerReceivedCallbackName = null;

var m_answerFromUser = null;

var m_scaleFromAnswer = null;

var m_getAnswerDataServiceToCall = null;

var m_isAnswerToBonusQuestion = false;


var m_awaitingResponseToGetAnswerMessage = false;

/**
* Called when the user has answered a question during a game.  This was called by the Flash question panel.
*/
function fromFlash_getAnswer ( questionId, userAnswer, scale, callbackName  ) {

	
    m_answerFromUser = userAnswer;
	m_scaleFromAnswer = scale;
   
printTrace ( "CALL FROM QUESTION PANEL: fromFlash_getAnswer () " );	
	
	m_numberOfQuestionsAnswered++;

    // Remember the callback (hosted by the Flash question panel) that we'll call once we get the answer back from the back end.
	m_answerReceivedCallbackName = callbackName;
	
	try {
		  
		if ( ( m_isYouTubeVideo || m_isPopJaxVideo ) && m_gameKnowsYouTubeVideoLoaded == false ) {
			// Don't get answer now.  We'll get it later.
			m_getAnswerDataServiceToCall = dataService_getAnswer;
			m_awaitingResponseToGetAnswerMessage = true;
		} else {
			
			// Store the time that the user answered the question
			//m_questionAnsweredTime = new Date ();
			calculateVideoLoadAndQuestionAnswerTimings();
			
//alert ( " m_userAnswerQuestionTime: " + m_userAnswerQuestionTime );

            m_isAnswerToBonusQuestion = false;
			dataService_getAnswer ( handleAnswerReturned, m_selectedGamePieceCol - 1, m_selectedGamePieceRow - 1, userAnswer, scale, m_videoLoadedTime, m_userAnswerQuestionTime, m_videoLoadStatus  );
			m_awaitingResponseToGetAnswerMessage = true;
		}
	} catch ( exc ) {
		printTrace ( "fromFlash_getAnswer Exception: " + exc );
	}
}


/**
* Called when the user has answered a "bonus" question.  This was called by the Flash question panel.
*/
function fromFlash_getBonusAnswer ( questionId, userAnswer, scale, callbackName  ) {
	
	
	m_answerFromUser = userAnswer;
	m_scaleFromAnswer = scale;
	
printTrace ( "CALL FROM QUESTION PANEL: fromFlash_getBonusAnswer () " );		
	
	m_numberOfQuestionsAnswered++;
	
    // Remember the callback (hosted by the Flash question panel) that we'll call once we get the answer back from the back end.
	m_answerReceivedCallbackName = callbackName;
	
	try {
		if ( ( m_isYouTubeVideo || m_isPopJaxVideo ) && m_gameKnowsYouTubeVideoLoaded == false ) {
			// Don't get answer now.  We'll get it later.
		   m_getAnswerDataServiceToCall = dataService_getBonusAnswer;
		} else {
			
			// Store the time that the user answered the question
			//m_questionAnsweredTime = new Date ();
			calculateVideoLoadAndQuestionAnswerTimings();
			
			m_isAnswerToBonusQuestion = true;
		   dataService_getBonusAnswer ( handleAnswerReturned, m_selectedGamePieceCol - 1, m_selectedGamePieceRow - 1, userAnswer, scale, m_videoLoadedTime, m_userAnswerQuestionTime, m_videoLoadStatus  );
		}
	} catch ( exc ) {
		printTrace ( "fromFlash_getBonusAnswer Exception: " + exc );
	}
}


/**
* Called when the user has answered a question in "preview question" mode.  This was called by the Flash question panel.
*/
function fromFlash_getAnswerPreview ( questionId, userAnswer, scale, callbackName  ) {
	
	
	m_answerFromUser = userAnswer;
	m_scaleFromAnswer = scale;
	
printTrace ( "CALL FROM QUESTION PANEL: fromFlash_getAnswerPreview () " );		
	
    // Remember the callback (hosted by the Flash question panel) that we'll call once we get the answer back from the back end.
	m_answerReceivedCallbackName = callbackName;
	
	try {
		if ( ( m_isYouTubeVideo || m_isPopJaxVideo ) && m_gameKnowsYouTubeVideoLoaded == false ) {
			// Don't get answer now.  We'll get it later.
		   m_getAnswerDataServiceToCall = dataService_getAnswerPreview;
		} else {
			
			// Store the time that the user answered the question
			//m_questionAnsweredTime = new Date ();
			calculateVideoLoadAndQuestionAnswerTimings();
			
		   dataService_getAnswerPreview ( handleAnswerReturned, questionId, userAnswer,  scale, m_videoLoadedTime, m_userAnswerQuestionTime, m_videoLoadStatus  );
		}
	} catch ( exc ) {
		printTrace ( "fromFlash_getAnswerPreview Exception: " + exc );
	}
}



/**
* Called when the user has answered a "bonus" question in "question preview" mode.  This was called by the Flash question panel.
*/
function fromFlash_getBonusAnswerPreview ( questionId, userAnswer, scale, callbackName  ) {
	
	
	m_answerFromUser = userAnswer;
	m_scaleFromAnswer = scale;
	
printTrace ( "CALL FROM QUESTION PANEL: fromFlash_getBonusAnswerPreview () " );		
	
    // Remember the callback (hosted by the Flash question panel) that we'll call once we get the answer back from the back end.
	m_answerReceivedCallbackName = callbackName;
	
	try {
		if ( ( m_isYouTubeVideo || m_isPopJaxVideo ) && m_gameKnowsYouTubeVideoLoaded == false ) {
			// Don't get answer now.  We'll get it later.
		   dataService_getBonusAnswerPreview = dataService_getBonusAnswerPreview; //dataService_getAnswerPreview;
		} else {		
		
		// Store the time that the user answered the question
		//m_questionAnsweredTime = new Date ();
		calculateVideoLoadAndQuestionAnswerTimings();
		
		   dataService_getBonusAnswerPreview ( handleAnswerReturned, questionId, userAnswer,  scale, m_videoLoadedTime, m_userAnswerQuestionTime, m_videoLoadStatus  );
		}
	} catch ( exc ) {
		printTrace ( "fromFlash_getBonusAnswer Exception: " + exc );
	}
}



/**
* This indicates whether the answer that the user entered was correct or incorrect.
*/
var m_answerWasCorrect = false;

/**
* This is a reference to the JavaScript (model) object containing the "game over" message.
*/
var m_gameOverData = null;

var m_currentGameScoreAfterFirstBonusQuestion = null;

/**
* This is called when the correct answer has been returned by the back end.  It tells
* us whether or not the user was correct, what the current score of the game is,
* whether or not the game is over, won/lost, etc.
*/
function handleAnswerReturned ( data, xml ) {
	
	/**
	* Only record this with Google Analytics if this wasn't a "bonus" question (the one that hangs off the main question).
	*/
   if ( m_isAnswerToBonusQuestion == false ) {		
		/**
		* Another question within the game was answered.  Depending
		* on which # question this is, it might trigger a call to Google Analytics to
		* track this event.
		*/
		anotherQuestionWasAnswered ();
   }	
	
//alert ( " foo data back " ); window.doThisNow();

   /**
   * Mister Gorbachev, "tear down that wall" - Reagan.
   * 
   * Oh!  I mean, remove the overlay that prevented the user from clicking on the video!
   */
   hideClearVideoOverlayDiv ();
   
   if ( data.code == AnswerResponse.CODE_ANSWER_CORRECT ||
        data.code == AnswerResponse.CODE_GAME_WON || 
	    ( data.code == AnswerResponse.CODE_BLACKOUT_FINISH && data.isAnswerCorrect == "true" ) ) {
		
	  m_answerWasCorrect = true;
   
   } else {
      m_answerWasCorrect = false;
   }
	
   var updateDailyScoreWithGameScore = false;
   
   if ( data.code == AnswerResponse.CODE_GAME_WON || 
		data.code == AnswerResponse.CODE_GAME_LOST ||
		data.code == AnswerResponse.CODE_BLACKOUT_FINISH ) {
	
	   m_gameOverData = data;
	   
	   m_gameOver = true;
	   
	   if ( userIsLoggedIn () && ( data.code == AnswerResponse.CODE_GAME_WON || 
		    data.code == AnswerResponse.CODE_BLACKOUT_FINISH ) ) {
		   updateDailyScoreWithGameScore = false ;  // true;
	   }
   }
   
   if ( data.average ) {
	   m_averageScoreForThisGame = Math.round(data.average);
   }
   if ( data.percentile ) {
	   var playerPercentile = Number(data.percentile) * 100;
	   playerPercentile = Math.round(playerPercentile);
	   var playerPercentage = 100 - playerPercentile;
	   if ( playerPercentage < 1 ) {
		   playerPercentage = 1;
	   }
	   m_playerPercentagePosition = playerPercentage;
   }
   
//alert ( " GAME OVER? " +  m_gameOver );

	if ( m_gameId == null ) {
		if ( data.gameId != null && data.gameId != "null" && data.gameId != "undefined" ) {
			m_gameId = data.gameId;
		}
	}

   ASSERT_THROW ( data.code == AnswerResponse.CODE_ANSWER_CORRECT && (data.score == undefined || data.score == null), 
     "handleAnswerReturned: Game Score Missing" );
   


   
   /**
   * Increment the "current score of the game" value.
   */
   if ( m_answerWasCorrect ) {
	   
//alert ( " answeringBonusQuestion (): " + answeringBonusQuestion () );

	   if ( answeringBonusQuestion () == true ) {
			
			/**
			* If we have gotten the first part of a question with a bonus question correct, remember the score as of the point in time
			* when the first part was answered correctly.  We'll need to rememember this for those times when the player then decides to 
			* decline to play the bonus question.
			*/
			if ( m_isAnswerToBonusQuestion == false ) {
//alert ( "SCOTT, remembering for later" );				
				m_currentGameScoreAfterFirstBonusQuestion = Number(data.score);
			} else {
            m_currentGameScore = Number(data.score);
				m_currentGameScoreAfterFirstBonusQuestion = null;
			}
	   } else if ( answeringBonusQuestion () == false ) {
		   m_currentGameScore = Number(data.score);
	   }
    } else {
		 
		 /**
		 * If the user got the second/bonus question wrong, then delete the value of "m_currentGameScoreAfterFirstBonusQuestion"
		 */
		 if ( answeringBonusQuestion () == true && m_isAnswerToBonusQuestion == true ) {
//alert ( "SCOTT, clearing the value!" );
          m_currentGameScoreAfterFirstBonusQuestion = null;
		 }
	 }
	
	
//alert ( " answeringBonusQuestion (): " + answeringBonusQuestion () + " m_isAnswerToBonusQuestion: " + m_isAnswerToBonusQuestion );

	
//alert ( "TRACE m_answerWasCorrect: " + m_answerWasCorrect +  " m_currentGameScore: " + m_currentGameScore );

   
   
   if ( updateDailyScoreWithGameScore ) {
	   var bottomGameInfoPanel = document.getElementById ( "bottomGameInfoPanel" );
	   var origDailyPoints = Number ( m_userInfo.dailyScore );
	   var newDailyPoints  = Number(origDailyPoints) + Number(m_currentGameScore);
	   try
	   {
         if (bottomGameInfoPanel) 
	       bottomGameInfoPanel.setDailyPoints ( newDailyPoints );
	   }
	   catch ( exc)
	   {
	   }
	   
   }
   

	
   /**
   * Stringify the returned XML "answer data" message the back end gave us.
   */
   var xmlString = String(xml);  
 
   /**
   * Now call the "callback" within the question panel that is expecting to hear from
   * us once the answer has been received from the back end.
   */
   var questionPanel = document.getElementById ( "questionPanel" ); 
   printTrace ( "pre: questionPanel[" + m_answerReceivedCallbackName + "] ()" );
   questionPanel[m_answerReceivedCallbackName] ( xmlString );	
   printTrace ( "post: questionPanel[" + m_answerReceivedCallbackName + "] ()" );
}


/** SLW UP TO HERE IS OK **/


/***
* ------------------------------------ END OF GAME STUFF ---------------------------------------------
***/


function getGameOverTopMessageText () {
	
   var message = "";
	
   if ( m_currentGameScore < 300 ) {
      message = "You Scored " + m_currentGameScore + " Points"; 
   } else if ( m_currentGameScore >= 300 && m_currentGameScore < 700 ) {
      message = "<span style='color:#FF99FF; font-weight:bold;'>Congratulations.</span> You scored " + m_currentGameScore + " points!";
   } else if ( m_currentGameScore >= 700 && m_currentGameScore < 1000 ) {
      message = "<span style='color:#FF99FF; font-weight:bold;'>Awesome!</span> You scored " + m_currentGameScore + " points!";
   } else if ( m_currentGameScore >= 1000 ) {
      message = "<span style='color:#FF99FF; font-weight:bold;'>Epic!</span> You scored " + m_currentGameScore + " points!";
   }

   return message;
}

function getCongratulationsText () {
	
   var message = "";
	
   if ( m_currentGameScore < 300 ) {
      message = ""; 
   } else if ( m_currentGameScore >= 300 && m_currentGameScore < 700 ) {
      message = "Congratulations.";
   } else if ( m_currentGameScore >= 700 && m_currentGameScore < 1000 ) {
      message = "Awesome!";
   } else if ( m_currentGameScore >= 1000 ) {
      message = "Epic!";
   }

   return message;
}




/**
* This is called by the gameboard.  It lets us know that the background for the
* gameboard is now showing.  Handle it in another thread.
*/
function gameOverBackShowing () {
	
   printTrace ( "CALL FROM GAMEBOARD: gameOverBackShowing ()" );

//alert ( " gameOverBackShowing CALLED m_gameAlreadyPlayed " + m_gameAlreadyPlayed );

   if ( m_gameOverData != null &&  m_gameOverData.code == AnswerResponse.CODE_GAME_LOST ) {
	   setTimeout ( delayedShowGameLostMessage, 100 );
   } else if ( m_didEndGame ) {
	   // alert ( "DID END GAME SO WHAT?" );
   } else {
      if ( m_gameAlreadyPlayed ) {
         setTimeout ( delayedShowGameAlreadyPlayedMessage, 100 );
      } else {
         setTimeout ( delayedGameOverBackShowing, 100 );
      }
   }
   
  // if ( doShowEndGameSurvey () ) {
//	   showEndGameSurvey ();
  // }
}


var MONTH_NAMES = [ "invalid",
   "January", "February", "March", "April", "May", "June", 
   "July", "August", "September", "October", "November", "December"
];

function getFriendlyDateString ( unfriendlyString ) {
	var friendlyDateString = "March 30, 2008";
	
	var parts = unfriendlyString.split("-");
	
	var month = Number(parts[1]);
	var monthName = MONTH_NAMES[month];
	
	var day = Number(parts[2]);
	var year = parts[0];
	
	friendlyDateString = monthName + " " + day + ", " + year;
	
	return friendlyDateString;
}

/**
* This shows the "Game Lost" message.
*/
function delayedShowGameLostMessage () {
   var gameOverMessageDiv = document.getElementById ( "gameOverMessageDiv" );
   gameOverMessageDiv.style.display = "block";
	
//alert ( "called from delayedShowGameLostMessage" );
	handleEndOfGameScreenShowing ();

   var gameOverTopMessage = document.getElementById ( "gameOverTopMessage" );
   gameOverTopMessage.innerHTML = "Sorry, You Lost.";

   setTimeout ( showPlayAgainMessage, 400 );	
   
   setTimeout ( showGameOverLinkToPopjax, 800 );
}


/**
* This shows the "game already played" message.
*/
function delayedShowGameAlreadyPlayedMessage () {
   
   var gameOverMessageDiv = document.getElementById ( "gameOverMessageDiv" );
   gameOverMessageDiv.style.display = "block";
	
//alert ( "	from delayedShowGameAlreadyPlayedMessage " );
	handleEndOfGameScreenShowing ();

   var gameOverTopMessage = document.getElementById ( "gameOverTopMessage" );
   gameOverTopMessage.innerHTML = "Game Already Played!";

   var datePlayedString = getFriendlyDateString ( m_gameData.playedDate );
   var alreadyPlayedScore = m_gameData.score;
   
   var gameOverMessageChallengeFriendsMessage = document.getElementById ( "gameOverMessageChallengeFriendsMessage" );
   gameOverMessageChallengeFriendsMessage.innerHTML = "On " + datePlayedString + " you scored " + alreadyPlayedScore + " points";
   gameOverMessageChallengeFriendsMessage.style.display = "block";
   gameOverMessageChallengeFriendsMessage.style.marginTop = "20px";
   gameOverMessageChallengeFriendsMessage.style.marginBottom = "100px";
   

   setTimeout ( showPlayAgainMessage, 400 );
   
   setTimeout ( showGameOverLinkToPopjax, 800 );
}

function showDailyOrMonthlyWinnerMessage () {
//alert ( " showDailyOrMonthlyWinnerMessage, m_dailyPoints: " + m_dailyPoints + " m_currentGameScore: " + m_currentGameScore );

   try {
		var doShowDailyDrawingQualificationAnimation = false;
		var doShowMonthlyDrawingOneQualificationAnimation = false;
		var doShowMonthlyDrawingTwoQualificationAnimation = false;
		
		var dailyPointsWithCurrentGameScoreAdded = Number ( Number(m_dailyPoints) + Number(m_currentGameScore) );
		if ( m_dailyPoints < 5000 &&  dailyPointsWithCurrentGameScoreAdded >= 5000 ) {
			doShowDailyDrawingQualificationAnimation = true;
		}
	
		var monthlyPointsWithCurrentGameScoreAdded = Number ( Number(m_monthlyPoints) + Number(m_currentGameScore) );	
		if ( m_monthlyPoints < 25000 &&  monthlyPointsWithCurrentGameScoreAdded >= 25000 ) {
			doShowMonthlyDrawingOneQualificationAnimation = true;
		}
	
		var monthlyPointsWithCurrentGameScoreAdded = Number ( Number(m_monthlyPoints) + Number(m_currentGameScore) );
		if ( m_monthlyPoints < 50000 &&  monthlyPointsWithCurrentGameScoreAdded >= 50000 ) {
			doShowMonthlyDrawingTwoQualificationAnimation = true;
		}
	
		if ( doShowDailyDrawingQualificationAnimation && 
			  ( doShowMonthlyDrawingOneQualificationAnimation == false ) && ( doShowMonthlyDrawingTwoQualificationAnimation == false )  
			) {
			m_showedDailyDrawingAnimation = true;
			showQualifyForDailyPrize ();
		}
		
		if ( ( doShowMonthlyDrawingOneQualificationAnimation == true ) && ( doShowMonthlyDrawingTwoQualificationAnimation == false ) ) {
		 //  alert ( "SHOW MONTHLY 1" );
			m_showedMonthlyDrawingOneAnimation = true;
			showQualifyForMonthlyPrizeOne ();
		}
		
		if ( doShowMonthlyDrawingTwoQualificationAnimation ) {
			//alert ( "SHOW MONTHLY 2" );
			m_showedMonthlyDrawingTwoAnimation = true;
			showQualifyForMonthlyPrizeTwo ();
		}
	} catch ( justInCase ) {
	}
	
}

/**
* This does whatever we want done now that the end of game background is showing.
* (We'll put up "game over", "game won/lost", "congratulations", etc. messages.)
*/
function delayedGameOverBackShowing () {
	
//alert ( "HERE IS WHERE WE SHOULD DO IT" );

   /**
	* Now, we determine if the player is playing a POP4 or POPSPIN game and if so, did they pass the threshold
	* for winning a daily or monthly high score prize.
	*/
	if ( m_gameType == "POP4" || m_gameType == "POPSPIN" ) {
	   showDailyOrMonthlyWinnerMessage ();
	}

	var gameOverMessageDiv = document.getElementById ( "gameOverMessageDiv" );
	if ( gameOverMessageDiv != null ) {
	   gameOverMessageDiv.style.display = "block";
	}
	
//alert ( "	delayedGameOverBackShowing " );
	handleEndOfGameScreenShowing ();
	
	var gameOverTopMessageText = getGameOverTopMessageText ();
	
	var gameOverTopMessage = document.getElementById ( "gameOverTopMessage" );
	
	if ( gameOverTopMessage != null ) {
	   gameOverTopMessage.innerHTML = gameOverTopMessageText;
	}
	
/*
	setTimeout ( showChallengeFriendsMessage, 400 );
	setTimeout ( showPlayAgainMessage, 800 );
	setTimeout ( showBottomGameOverMessages, 1000 );
*/

    setTimeout ( showBottomGameOverMessages, 400 );
	setTimeout ( showChallengeFriendsMessage, 800 );
	setTimeout ( showPlayAgainMessage, 1200 );
	

}

function showChallengeFriendsMessage () {
	var gameOverMessageChallengeFriendsMessage = document.getElementById ( "gameOverMessageChallengeFriendsMessage" );
	if ( gameOverMessageChallengeFriendsMessage != null ) {
	   gameOverMessageChallengeFriendsMessage.style.display = "block";
	}
}

function showPlayAgainMessage () {
	var gameOverMessagePlayAgainMessage = document.getElementById ( "gameOverMessagePlayAgainMessage" );
	
   if ( gameOverMessagePlayAgainMessage != null ) {
	   gameOverMessagePlayAgainMessage.style.display = "block";
	}
}

function generateAverageScoreForThisGameMessage ( _averageScore ) {
	return "The average score for this game was " + m_averageScoreForThisGame + " points";
}

function getAverageScoreElementDisplayType () {
	return "block";
}

function showAverageAndPercentileValues () {
	
	try {
		var endOfGameAverageScore = document.getElementById ( "endOfGameAverageScore" );
		var endOfGameScorePercentile = document.getElementById ( "endOfGameScorePercentile" );
		
		endOfGameAverageScore.style.display = getAverageScoreElementDisplayType (); //"block";
		endOfGameAverageScore.innerHTML = generateAverageScoreForThisGameMessage (m_averageScoreForThisGame);
		   //"The average score for this game was " + m_averageScoreForThisGame + " points";
		if ( m_playerPercentagePosition && m_playerPercentagePosition <= 20 ) {
			if ( endOfGameScorePercentile ) {
			   endOfGameScorePercentile.innerHTML = "Congratulations!  You scored within the top " + m_playerPercentagePosition + "%";
			   endOfGameScorePercentile.style.display = "block";
			}
		} else {
			if ( endOfGameScorePercentile ) {
			   endOfGameScorePercentile.style.display = "none";
			}
			//extraGameOverMessage.style.height = "50px";
		}
	} catch ( exc ) {
		printTrace ( "EXC: " + exc );
	}
	
}

function showBottomGameOverMessages () {
	var extraGameOverMessage = document.getElementById ( "extraGameOverMessage" );
	if ( extraGameOverMessage ) {
	   extraGameOverMessage.style.display = "block";
	}
	
	var endOfGameAverageScore = document.getElementById ( "endOfGameAverageScore" );
	var endOfGameScorePercentile = document.getElementById ( "endOfGameScorePercentile" );
	var endOfGameNotLoggedInRegisterNow = document.getElementById ( "endOfGameNotLoggedInRegisterNow" );
	
	// For 5/5 only!
	endOfGameAverageScore.style.display = getAverageScoreElementDisplayType (); // "block";
	endOfGameAverageScore.innerHTML = generateAverageScoreForThisGameMessage (m_averageScoreForThisGame);
	  //"The average score for this game was " + m_averageScoreForThisGame + " points";
	if ( m_playerPercentagePosition && m_playerPercentagePosition <= 20 ) {
		if ( endOfGameScorePercentile != null ) {
	      endOfGameScorePercentile.innerHTML = "Congratulations!  You scored within the top " + m_playerPercentagePosition + "%";
	      endOfGameScorePercentile.style.display = "block";
		}
	} else {
		if ( endOfGameScorePercentile != null ) {
		   endOfGameScorePercentile.style.display = "none";
		}
		if ( extraGameOverMessage != null ) {
		   extraGameOverMessage.style.height = "50px";
		}
	}
	
	if ( userIsLoggedIn () == true ) {
		// This is where we fill in the correct values
		// m_averageScoreForThisGame
        // m_playerPercentagePosition
		//
		//endOfGameAverageScore.innerHTML = "The average score for this game was " + m_averageScoreForThisGame + " points";
		//if ( m_playerPercentagePosition && m_playerPercentagePosition <= 20 ) {
		//   endOfGameScorePercentile.innerHTML = "Congratulations!  You scored within the top " + m_playerPercentagePosition + "%";
		//}
		

      if ( endOfGameNotLoggedInRegisterNow != null ) {
		   endOfGameNotLoggedInRegisterNow.style.display = "none";
		}
	} else {
		
      if ( endOfGameAverageScore != null ) {
		   endOfGameAverageScore.style.display = "none";
		}
		
		if ( endOfGameScorePercentile != null ) {
		   endOfGameScorePercentile.style.display = "none";
		}
		
		if ( extraGameOverMessage != null ) {
		   extraGameOverMessage.style.height = "86px";
		}
	}

    showGameOverLinkToPopjax ();
}

function showGameOverLinkToPopjax () {
	var linkToPopjaxGameOverMessage = document.getElementById ( "linkToPopjaxGameOverMessage" );
	if ( linkToPopjaxGameOverMessage ) {
	   linkToPopjaxGameOverMessage.style.display = "block";	
	}
}


/***
* ------------------------------------ ONCE ALL THE GAME FUNCTIONS ARE LOADED -------------------------------------
***/

// window.onload = loadPage; 



/***
* ------------------------------------ DIALOG HELPER FUNCTIONS ----------------
***/

function isEmailValid ( _email ) {
	
	var isValid = false;
	
	var containsAt = (_email.indexOf ( "@" ) > 0);
	var containsDot = (_email.indexOf ( "." ) > 0);
	var idxEndOfEmailPart = _email.lastIndexOf( "." );
	var idxOfAt = _email.indexOf( "@" );
	
	if ( containsAt && containsDot && ( idxOfAt < (idxEndOfEmailPart - 1) ) && idxEndOfEmailPart < ( _email.length - 1 ) ) {
		isValid = true;
	}
	
	return isValid;
	
	/*if ( _email.indexOf ( "@" ) > 0 && _email.indexOf ( "." ) > _email.indexOf ( "@" ) && _email.indexOf ( "." ) < _email.length - 2 ) {
		return true;
	} else {
		return false; 
	}
	*/
}



function showVideoNotLoadingDialog ( questionId ) {

	var dialogBoxesDiv = document.getElementById ( "dialogBoxesDiv" );
	dialogBoxesDiv.style.display = "block";

	var dialog = document.getElementById ("videoNotLoadingDialog");
	dialog.style.display = "block";
	dialog.style.visibility = "visible";
}

function showTraceMessagesDialog () {

	var dialogBoxesDiv = document.getElementById ( "dialogBoxesDiv" );
	dialogBoxesDiv.style.display = "block";

	var dialog = document.getElementById ("traceMessagesDialog");
	dialog.style.display = "block";
	dialog.style.visibility = "visible";
	
	var traceMessages = document.getElementById ("traceMessages");
	//alert ( " m_dataServiceTraceString: " + m_dataServiceTraceString );
	traceMessages.value = (m_dataServiceTraceString);
	// m_dataServiceTraceString
}

function closeDialog ( dialogId ) {
	
	var dialogBoxesDiv = document.getElementById ( "dialogBoxesDiv" );
	dialogBoxesDiv.style.display = "none";
	
	var dialog = document.getElementById (dialogId);
//alert ( "DIALOG:  " + dialog + " FOR ID: " + dialogId );
	dialog.style.display = "none";
	dialog.style.visibility = "hidden";
	
}

/** SEEMS OK HERE TOO SLW **/

/*

       <div id="dialogBoxesDiv" >
       
       
          <div id="gameHelp" style="position:absolute; top:0px; left:50px; width:500px; height:424px; background-color:#ff0000;">              
          </div>              
*/

// endGameAnimation

/***
* ------------------------------------ "END GAME ANIMATION" ----------------
***/

function showEndGameAnimation () {

//alert ( "SHOW RULES CALLED" );

	var dialogBoxesDiv = document.getElementById ( "dialogBoxesDiv" );
	dialogBoxesDiv.style.display = "block";

	var endGameAnimation = document.getElementById ( "endGameAnimation" );
	endGameAnimation.style.display = "block";
	
//alert ( "FOO" );

//	var gameName = m_gameData.gameDetails.gameName;
	
	var animationSWF = "/content/game/EndGameAnimation.swf"; //?gameName=" + gameName;
	
//	alert ( " animationSWF: " + animationSWF );
	
	embedFlashContent ( "endGameMovie", "endGameAnimation", animationSWF, 
					    "100%", "100%", 0xffffff, "transparent", "exactFit" );
}
		 


/***
* ------------------------------------ "RULES" ----------------
***/

function delayedShowRules () {
//alert ( "SHOW RULES" );
	showRules ();
}

function showRules () {

//alert ( "SHOW RULES CALLED" );

	var dialogBoxesDiv = document.getElementById ( "dialogBoxesDiv" );
	dialogBoxesDiv.style.display = "block";

	var gameHelp = document.getElementById ( "gameHelp" );
	gameHelp.style.display = "block";
	
	try {
		
	//	alert ( " m_gameType: " + m_gameType );
		
		//alert ( "ABOUT TO DO IT" );
   switch ( m_gameType ) {
      case "HIT":
	     if ( m_origin == ORIGIN_SITE ) {
	        embedFlashContent ( "gameRules", "gameHelp", "/content/game/gameHelpAssets.swf?helpToShow=popQuiz3x3", 
							    "100%", "100%", 0xffffff, "transparent", "exactFit" );
		 } else {
			 // alert ( "FACEBOOK HIT" );
			 embedFlashContent ( "gameRules", "gameHelp", "/content/game/gameHelpAssetsFacebook.swf?helpToShow=blackout", 
								 "100%", "100%", 0xffffff, "transparent", "exactFit" );
		 }
	     break;
		 
      case "POP4":
	     embedFlashContent ( "gameRules", "gameHelp", "/content/game/gameHelpAssets.swf?helpToShow=strikeout", 
							  "100%", "100%", 0xffffff, "transparent", "exactFit" );
	     break;
		 
	  case "POPQUIZ":
	     embedFlashContent ( "gameRules", "gameHelp", "/content/game/gameHelpAssets.swf?helpToShow=popQuiz3x3", 
							 "100%", "100%", 0xffffff, "transparent", "exactFit" );
	     break;
		 
      case "POPSPIN":
	     embedFlashContent ( "gameRules", "gameHelp", "/content/game/gameHelpAssets.swf?helpToShow=spinner", 
							 "100%", "100%", 0xffffff, "transparent", "exactFit" );
	     break;
		 
      case "CUSTOM":
	  //alert ( "CUSTOM" );
	     embedFlashContent ( "gameRules", "gameHelp", "/content/game/gameHelpAssetsFacebook.swf?helpToShow=popQuiz4x4",
							 "100%", "100%", 0xffffff, "transparent", "exactFit" );
	     break;
   }
	} catch ( exc ) {
		printTrace ( "EXC: " + exc );
	}
	

}




function unloadRulesWindow () {
	
	var dialogBoxesDiv = document.getElementById ( "dialogBoxesDiv" );
	dialogBoxesDiv.style.display = "none";
	
	 $('gameHelp').innerHTML = "";
	 $('gameHelp').style.display = "none";
			// $('gameHelp').style.display = "none";
		//	$('gameHelp').style.width = "0px";
		//	$('gameHelp').style.height = "0px";	 
	 m_rulesShowing = false;
}

function unloadRules () {
	m_rulesShowing = false;
	setTimeout( unloadRulesWindow, 10 );
}



/***
* ------------------------------------ "FEEDBACK" DIALOG ----------------
***/
function showFeedbackDialog () {

	var dialogBoxesDiv = document.getElementById ( "dialogBoxesDiv" );
	dialogBoxesDiv.style.display = "block";

    var feedback =  document.getElementById ( "feedback" );
	feedback.value = "";
	
	var feedback_contents = document.getElementById ( "feedback_contents" );
	feedback_contents.style.display = "block";

    var feedbackEmail =  document.getElementById ( "feedbackEmail" );
	feedbackEmail.style.backgroundColor = "#ffffff";
	feedbackEmail.style.color = "#000000";
	
    var feedback =  document.getElementById ( "feedback" );
	feedback.style.backgroundColor = "#ffffff";
	feedback.style.color = "#000000";
	feedback.value = "";
	
	var feedbackThanks = document.getElementById ( "feedbackThanks" );
	feedbackThanks.style.display = "none";

	var feedbackPage = document.getElementById ( "feedbackPage" );
	feedbackPage.style.display = "block";
	feedbackPage.style.visibility = "visible";

}

function doFeedback () {
	
	var feedback =  document.getElementById ( "feedback" );
	var feedbackText = feedback.value;

	var feedbackEmail =  document.getElementById ( "feedbackEmail" );
	var feedbackEmailText = feedbackEmail.value;
	
	if ( feedbackEmailText != "" && !isEmailValid ( feedbackEmailText ) ) {
		alert ( "Please enter a valid email address or a blank one." );
		feedbackEmail.style.backgroundColor = "#ff0000";
		feedbackEmail.style.color = "#ffffff";
		return;
	}
	
	if ( feedbackText == "" ) {
		alert ( "Please enter feedback" );
		return;
	}

	var feedback_contents = document.getElementById ( "feedback_contents" );
	feedback_contents.style.display = "none";

	var feedbackThanks = document.getElementById ( "feedbackThanks" );
	feedbackThanks.style.display = "block";
	

	dataService_userFeedback ( handleFeedbackSent, feedbackEmailText, feedbackText );
	
}

function handleFeedbackSent ( data, xml ) {
	// printTrace ( "FEEDBACK SENT!" );
}


/***
* ------------------------------------ "SUBMIT QUESTION" DIALOG ----------------
***/

function showSubmitQuestionDialog ( questionId ) {

    var cbChooseOne1 = document.getElementById ( "cbChooseOne1" );
	cbChooseOne1.checked = false;
	
	var cbChooseOne2 = document.getElementById ( "cbChooseOne2" );
	cbChooseOne2.checked = false;
	
	var cbChooseOne3 = document.getElementById ( "cbChooseOne3" );
	cbChooseOne3.checked = false;
	
	var cbChooseOne4 = document.getElementById ( "cbChooseOne4" );
	cbChooseOne4.checked = false;
	
	
	var cbTrue = document.getElementById ( "cbTrue" );
	cbTrue.checked = false;
	var cbFalse = document.getElementById ( "cbFalse" );
	cbFalse.checked = false;
	
	var submitQuestionFillInTheBlankAnswer = document.getElementById ( "submitQuestionFillInTheBlankAnswer" );
	submitQuestionFillInTheBlankAnswer.value = "";
	submitQuestionFillInTheBlankAnswer.className = "dialogField";
	
	
	var submitQuestionQuestionText = document.getElementById ( "submitQuestionQuestionText" );
	//var submitQuestionFromEmail = document.getElementById ( "submitQuestionFromEmail" );
	var submitQuestionFormError = document.getElementById ( "submitQuestionFormError" );
	
	submitQuestionQuestionText.className = "dialogField";
	//submitQuestionFromEmail.className = "dialogField";
    submitQuestionFormError.innerHTML = "";
	
	var dialogBoxesDiv = document.getElementById ( "dialogBoxesDiv" );
	dialogBoxesDiv.style.display = "block";

	var submitQuestionButton = document.getElementById ( "submitQuestionButton" );
	submitQuestionButton.style.display = "block";
	//submitQuestionButton.style.visibility = "visible";
	
	var cancelSubmitQuestionButton = document.getElementById ( "cancelSubmitQuestionButton" );
	cancelSubmitQuestionButton.style.backgroundImage = "url(images/DialogCancelButton.png)";
	cancelSubmitQuestionButton.parentNode.style.width = "180px";

	var dialog = document.getElementById ("submitQuestionDialog");
	dialog.style.display = "block";
	dialog.style.visibility = "visible";
	
	var submitQuestionForm = document.getElementById ( "submitQuestionForm" );
	submitQuestionForm.style.display = "block";

	var submitQuestionSuccess = document.getElementById ( "submitQuestionSuccess" );
	submitQuestionSuccess.style.display = "none";
	
	
    if ( m_gameInfo == null ) {
		dataService_getGameInfo ( handleGameInfoReady, m_pjuid );
	} else {
		//alert ( "GAME INFO EXISTS" );
		dumpGameInfo ();
	}
	
	
}

function enforceOnlyOneSelected ( idSelectedCb, listOfCheckBoxesToUnSelect ) {
	
	//alert ( " enforceOnlyOneSelected" );
	var selectedCb = document.getElementById ( idSelectedCb );
	//alert ( " selectedCb: " + selectedCb + " sel? " + selectedCb.checked );
	if ( selectedCb.checked ) {
		for ( var idx = 0; idx < listOfCheckBoxesToUnSelect.length; idx++ ) {
			var cb = document.getElementById ( listOfCheckBoxesToUnSelect[idx] );
			cb.checked = false;
		}
	}
}




var QUESTION_TYPE_CHOOSE_ONE = "single choice";
var QUESTION_TYPE_FILL_IN_THE_BLANK = "free text";
var QUESTION_TYPE_TRUE_FALSE = "binary";

function handleSubmitQuestionTypeChanged () {
	var submitQuestionQuestionType = document.getElementById ( "submitQuestionQuestionType" );
	var selectedOption = submitQuestionQuestionType.options[ submitQuestionQuestionType.selectedIndex ];
	//alert ( " selectedOption: " + selectedOption.value );
	
	var submitQuestionFillInTheBlankAnswerDiv = document.getElementById ( "submitQuestionFillInTheBlankAnswerDiv" );
	var submitQuestionChooseOneAnswerDiv = document.getElementById ( "submitQuestionChooseOneAnswerDiv" );
	var submitQuestionTrueFalseAnswerDiv = document.getElementById ( "submitQuestionTrueFalseAnswerDiv" );
	
//	var submitQuestionFillInTheBlankAnswerDiv = document.getElementById ( "submitQuestionFillInTheBlankAnswerDiv" );
	
	switch ( selectedOption.value ) {
		case QUESTION_TYPE_CHOOSE_ONE:
		   submitQuestionFillInTheBlankAnswerDiv.style.display = "none";
		   submitQuestionTrueFalseAnswerDiv.style.display = "none";
		   submitQuestionChooseOneAnswerDiv.style.display = "block";
		   break;
		   
		case QUESTION_TYPE_FILL_IN_THE_BLANK:
		   submitQuestionFillInTheBlankAnswerDiv.style.display = "block";
		   submitQuestionChooseOneAnswerDiv.style.display = "none";		
		   submitQuestionTrueFalseAnswerDiv.style.display = "none";
		   break;
		   
	    case QUESTION_TYPE_TRUE_FALSE:
		   submitQuestionFillInTheBlankAnswerDiv.style.display = "none";
		   submitQuestionChooseOneAnswerDiv.style.display = "none";		
		   submitQuestionTrueFalseAnswerDiv.style.display = "block";
		   break;
	}
}

function validateSubmitQuestion () {
	
	try {
		var submitQuestionQuestionText = document.getElementById ( "submitQuestionQuestionText" );
	//	var submitQuestionFromEmail = document.getElementById ( "submitQuestionFromEmail" );
	//	var submitQuestionMessage = document.getElementById ( "submitQuestionMessage" );
		var submitQuestionFormError = document.getElementById ( "submitQuestionFormError" );
		submitQuestionFormError.innerHTML = "";
		
		submitQuestionQuestionText.className = "dialogField";
	//	submitQuestionFromEmail.className = "dialogField";
		
		var submitQuestionQuestionTextValue = submitQuestionQuestionText.value;
	//	var submitQuestionFromEmailValue = submitQuestionFromEmail.value;
	//	var submitQuestionMessageValue = submitQuestionMessage.value;

		if ( submitQuestionQuestionTextValue == "" ) {
			submitQuestionQuestionText.className = "dialogFieldError";
			submitQuestionFormError.innerHTML = "Please enter a question.";
			return false;
		}
		
	    var submitQuestionQuestionType = document.getElementById ( "submitQuestionQuestionType" );
	    var selectedOption = submitQuestionQuestionType.options[ submitQuestionQuestionType.selectedIndex ];
		
		switch ( selectedOption.value ) {
			case QUESTION_TYPE_CHOOSE_ONE:
			   if ( validateSubmitQuestionChooseOne () == false ) {
				   return false;
			   }
			   break;
			   
			case QUESTION_TYPE_FILL_IN_THE_BLANK:
			   if ( validateSubmitQuestionFillInTheBlank () == false ) {
				   return false;
			   }
			   break;
			   
			case QUESTION_TYPE_TRUE_FALSE:
			   if ( validateSubmitQuestionTrueFalse () == false ) {
				   return false;
			   }
			   break;
		}
		


	} catch ( exc ) {
		printTrace ( "EXC: " + exc );
	}

	return true;
}

function validateSubmitQuestionChooseOne () {
	
	var submitQuestionFormError = document.getElementById ( "submitQuestionFormError" );
	
    var cbChooseOne1 = document.getElementById ( "cbChooseOne1" );
	var cbChooseOne2 = document.getElementById ( "cbChooseOne2" );
	var cbChooseOne3 = document.getElementById ( "cbChooseOne3" );
	var cbChooseOne4 = document.getElementById ( "cbChooseOne4" );

    var chooseOneAnswer1 = document.getElementById ( "chooseOneAnswer1" );
	var chooseOneAnswer2 = document.getElementById ( "chooseOneAnswer2" );
	var chooseOneAnswer3 = document.getElementById ( "chooseOneAnswer3" );
	var chooseOneAnswer4 = document.getElementById ( "chooseOneAnswer4" );
	
	chooseOneAnswer1.className = "answerDialogField";
	chooseOneAnswer2.className = "answerDialogField";
	chooseOneAnswer3.className = "answerDialogField";
	chooseOneAnswer4.className = "answerDialogField";
		
    if ( cbChooseOne1.checked == false && cbChooseOne2.checked == false &&
		 cbChooseOne3.checked == false && cbChooseOne4.checked == false ) {
		submitQuestionFormError.innerHTML = "Please specify a correct answer.";		
		return false;
	}
	
//alert ( " IS THIS BLANK:  [" + chooseOneAnswer1.value + "] stringIsBlank(chooseOneAnswer1.value): " + stringIsBlank(chooseOneAnswer1) );

	if ( cbChooseOne1.checked == true && stringIsBlank(chooseOneAnswer1.value) ) {  //chooseOneAnswer1.value == "" ) {
		cbChooseOne1.checked = false;
		submitQuestionFormError.innerHTML = "Can not select and empty answer.";
		chooseOneAnswer1.className = "answerDialogFieldError";
		return false;
	}

	if ( cbChooseOne2.checked == true && stringIsBlank(chooseOneAnswer2.value) ) { // chooseOneAnswer2.value == "" ) {
		cbChooseOne2.checked = false;
		submitQuestionFormError.innerHTML = "Can not select and empty answer.";
		chooseOneAnswer2.className = "answerDialogFieldError";
		return false;
	}

	if ( cbChooseOne3.checked == true && stringIsBlank(chooseOneAnswer3.value) ) { // chooseOneAnswer3.value == "" ) {
		cbChooseOne3.checked = false;
		submitQuestionFormError.innerHTML = "Can not select and empty answer.";
		chooseOneAnswer3.className = "answerDialogFieldError";
		return false;
	}

	if ( cbChooseOne4.checked == true && stringIsBlank(chooseOneAnswer4.value) ) {  // chooseOneAnswer4.value == "" ) {
		cbChooseOne4.checked = false;
		submitQuestionFormError.innerHTML = "Can not select and empty answer.";
		chooseOneAnswer4.className = "answerDialogFieldError";
		return false;
	}
	
	var numberEmpty = 0;
	
	if ( chooseOneAnswer1.value == "" ) { numberEmpty++; }
	if ( chooseOneAnswer2.value == "" ) { numberEmpty++; }
	if ( chooseOneAnswer3.value == "" ) { numberEmpty++; }
	if ( chooseOneAnswer4.value == "" ) { numberEmpty++; }
	
	if ( numberEmpty >= 3 ) {
		submitQuestionFormError.innerHTML = "Please specify at least 2 choices.";
		chooseOneAnswer1.className = "answerDialogFieldError";
		chooseOneAnswer2.className = "answerDialogFieldError";
		chooseOneAnswer3.className = "answerDialogFieldError";
		chooseOneAnswer4.className = "answerDialogFieldError";
		return false;
	}

	
	// submitQuestionQuestionText.className = "dialogField";
	
	return true;
}

function validateSubmitQuestionFillInTheBlank () {
	
	var submitQuestionFormError = document.getElementById ( "submitQuestionFormError" );
	
	var submitQuestionFillInTheBlankAnswer = document.getElementById ( "submitQuestionFillInTheBlankAnswer" );
	submitQuestionFillInTheBlankAnswer.className = "dialogField";
	
	if ( stringIsBlank (submitQuestionFillInTheBlankAnswer.value) ) { // submitQuestionFillInTheBlankAnswer.value == "" ) {
		submitQuestionFillInTheBlankAnswer.className = "dialogFieldError";
		submitQuestionFormError.innerHTML = "Please specify a correct answer.";
		
		return false;
	}
	
	return true;
}

function validateSubmitQuestionTrueFalse () {
	
	var submitQuestionFormError = document.getElementById ( "submitQuestionFormError" );
	
	var cbTrue = document.getElementById ( "cbTrue" );
	var cbFalse = document.getElementById ( "cbFalse" );

    if ( cbTrue.checked == false && cbFalse.checked == false ) {
		submitQuestionFormError.innerHTML = "Please specify a correct answer.";		
		return false;
	}
	
	return true;
}


function createSubmitQuestionPostData () {
	
	// alert ( " createSubmitQuestionPostData called"  );

   var postData = new Object ();
   
	postData.toString = function () {
		var str = "";
		for ( var p in this ) {
			if ( p != "toString" ) {
			   str += p + " : " + this[p] + " \n";
			}
		}
		//	if ( p != "toString" ) {
		//	   str += " " + p ":\"" + this[p] + "\"";
		//	}
		//}
		return str;
	}
   
	var questionText = document.getElementById ( "submitQuestionQuestionText" ).value;
    postData["new"] = "false";
    postData.selectedCat = "0";
    postData.requestType = "submit";
    postData["questionDto.questionText"] = questionText;
    postData["questionDto.keywords"] = questionText;
    postData["questionDto.url"]=m_currentQuestionObject.url; // "http://www.youtube.com/watch?v=p7GHBQDjgXg";
	
	var categoryGroupId = 2;
	var categoryId = m_selectedGameCell.categoryId;
	if ( categoryId == 0 || categoryId == 21 ) {
		categoryId = 6; // Some category.  I don't know what the category is for a hit game question.
	} else {
		var category = m_gameInfo.categories.getCategoryById ( categoryId );
		//alert ( " CAT:  " + category );
		categoryGroupId = category.parentCategoryGroupIds[0];
	}
	postData["categoryId"]=categoryId;
	postData["categoryGroupId"] = categoryGroupId;

	var submitQuestionQuestionType = document.getElementById ( "submitQuestionQuestionType" );
	var selectedOption = submitQuestionQuestionType.options[ submitQuestionQuestionType.selectedIndex ];
	
	switch ( selectedOption.value ) {
		case QUESTION_TYPE_CHOOSE_ONE:
		
			var cbChooseOne1 = document.getElementById ( "cbChooseOne1" );
			var cbChooseOne2 = document.getElementById ( "cbChooseOne2" );
			var cbChooseOne3 = document.getElementById ( "cbChooseOne3" );
			var cbChooseOne4 = document.getElementById ( "cbChooseOne4" );
		
            var chooseOneAnswer1 = document.getElementById ( "chooseOneAnswer1" );
	        var chooseOneAnswer2 = document.getElementById ( "chooseOneAnswer2" );
	        var chooseOneAnswer3 = document.getElementById ( "chooseOneAnswer3" );
	        var chooseOneAnswer4 = document.getElementById ( "chooseOneAnswer4" );
		
		    postData["questionDto.type"] = "single choice";
		    postData["questionDto.data01"] = chooseOneAnswer1.value;
		    postData["questionDto.data02"] = chooseOneAnswer2.value;
			if ( chooseOneAnswer3.value != "" ) {
		       postData["questionDto.data03"] = chooseOneAnswer3.value; // only if a value
			}
			if ( chooseOneAnswer4.value != "" ) {
		       postData["questionDto.data04"] = chooseOneAnswer4.value; // only if a value
			}
	   
	   
               var correctChoice = "0";
                  	   	       
               if ( cbChooseOne1.checked ) {
               	  correctChoice = "0";
               } else if ( cbChooseOne2.checked ) {
               	  correctChoice = "1";
               } else if ( cbChooseOne3.checked ) {
               	  correctChoice = "2";
               } else {
               	  correctChoice = "3";
               }

   	          postData["singleChoiceAnswer"] = correctChoice;
		   break;
		   
		case QUESTION_TYPE_FILL_IN_THE_BLANK:
		   var submitQuestionFillInTheBlankAnswer = document.getElementById ( "submitQuestionFillInTheBlankAnswer" );
		   postData["questionDto.type"] = "free text";
           postData["freeTextAnswer"] = submitQuestionFillInTheBlankAnswer.value;
		   postData["questionDto.data01"] = submitQuestionFillInTheBlankAnswer.value;  // HACK!!! If I don't do this, the back end blows.
		  // postData["categoryId"]=null;
	      // postData["categoryGroupId"] = "undefined";

		   break;
		   
		case QUESTION_TYPE_TRUE_FALSE:
		
			var cbTrue = document.getElementById ( "cbTrue" );
			var cbFalse = document.getElementById ( "cbFalse" );
			postData["questionDto.type"] = "binary";
			if ( cbTrue.checked ) {
   	   	       postData["binaryAnswer"] = "0";
            } else {
   	   	       postData["binaryAnswer"] = "1";
            }
		   break;
	}


   return postData;
}

/*	
	var postData = new Object ();
	
	postData.toString = function () {
		var str = "";
		for ( p in this ) {
			if ( p != "toString" ) {
			   str += " " + p ":\"" + this[p] + "\"";
			}
		}
		return str;
	}
	
	var questionText = document.getElementById ( "submitQuestionQuestionText" ).value;
    postData.new = "false";
    postData.selectedCat = "0";
    postData.requestType = "submit";
    postData["questionDto.questionText"] = questionText;
    postData["questionDto.keywords"] = questionText;
    postData["questionDto.url"]="http://www.youtube.com/watch?v=p7GHBQDjgXg";
	
	
	printTrace ( "SURVIVED" );
	
	return postData;
}
*/

function doSubmitQuestion () {
	
	if ( !validateSubmitQuestion () ) {
		return;
	}
	
	

	
	
	var httpPostFields = createSubmitQuestionPostData ();
	
//	alert (  " httpPostFields: " + httpPostFields );
	
	//var submitQuestionFromEmailValue = document.getElementById ( "submitQuestionFromEmail" ).value;
//	var submitQuestionMessageValue = document.getElementById ( "submitQuestionMessage" ).value;

    dataService_submitQuestion ( handleQuestionSubmitted, httpPostFields );


 //   dataService_emailQuestion ( handleQuestionSubmitted, m_currentQuestionObject.id, submitQuestionFromEmailValue, 
//	   submitQuestionToEmailValue, submitQuestionMessageValue ); 

	var submitQuestionButton = document.getElementById ( "submitQuestionButton" );
	submitQuestionButton.style.display = "none";
	
	var cancelSubmitQuestionButton = document.getElementById ( "cancelSubmitQuestionButton" );
	cancelSubmitQuestionButton.style.backgroundImage = "url(images/DialogCloseButton.png)";
	cancelSubmitQuestionButton.parentNode.style.width = "82px";
	
	var submitQuestionForm = document.getElementById ( "submitQuestionForm" );
	submitQuestionForm.style.display = "none";

	var submitQuestionSuccess = document.getElementById ( "submitQuestionSuccess" );
	submitQuestionSuccess.style.display = "block";

	//alert ( "parent: " +  cancelSendQuestionToAFriendButton.parentNode );
}

function handleQuestionSubmitted ( data ) { //, xml ) {
	//alert ( "SUBMITTED!" );
}


function handleGameInfoReady ( data, xml ) {
	m_gameInfo = data;
	
	dumpGameInfo ();
}

function dumpGameInfo () {
	//this.categoryGroups
	//alert ( " CATEGORY GROUPS: " + m_gameInfo.categoryGroups );
}




/***
* ------------------------------------ "SEND QUESTION TO FRIEND" DIALOG ----------------
***/

function showSendQuestionToFriendDialog ( questionId ) {

   shareQuestion_showShareQuestionScreen ();
   
/*
	var sendQuestionToEmail = document.getElementById ( "sendQuestionToEmail" );
	var sendQuestionFromEmail = document.getElementById ( "sendQuestionFromEmail" );
	var sendQuestionFormError = document.getElementById ( "sendQuestionFormError" );
	
	sendQuestionToEmail.className = "dialogField";
	sendQuestionFromEmail.className = "dialogField";
    sendQuestionFormError.innerHTML = "";
	
	var dialogBoxesDiv = document.getElementById ( "dialogBoxesDiv" );
	dialogBoxesDiv.style.display = "block";

	var sendQuestionToAFriendButton = document.getElementById ( "sendQuestionToAFriendButton" );
	sendQuestionToAFriendButton.style.display = "block";
	//sendQuestionToAFriendButton.style.visibility = "visible";
	
	var cancelSendQuestionToAFriendButton = document.getElementById ( "cancelSendQuestionToAFriendButton" );
	cancelSendQuestionToAFriendButton.style.backgroundImage = "url(images/DialogCancelButton.png)";
	cancelSendQuestionToAFriendButton.parentNode.style.width = "180px";

    
	var playerEmailAddress = getPlayerEmailAddress ();
	if ( playerEmailAddress ) {
		var sendQuestionFromEmail = document.getElementById ( "sendQuestionFromEmail" );
		sendQuestionFromEmail.value = playerEmailAddress;
	}
	
	var dialog = document.getElementById ("sendQuestionToAFriendDialog");
	dialog.style.display = "block";
	dialog.style.visibility = "visible";
	
	var sendQuestionForm = document.getElementById ( "sendQuestionForm" );
	sendQuestionForm.style.display = "block";

	var sendQuestionSuccess = document.getElementById ( "sendQuestionSuccess" );
	sendQuestionSuccess.style.display = "none";
*/

}

function validateSendQuestionToFriend () {
	
	try {
		var sendQuestionToEmail = document.getElementById ( "sendQuestionToEmail" );
		var sendQuestionFromEmail = document.getElementById ( "sendQuestionFromEmail" );
		var sendQuestionMessage = document.getElementById ( "sendQuestionMessage" );
		var sendQuestionFormError = document.getElementById ( "sendQuestionFormError" );
		
		sendQuestionToEmail.className = "dialogField";
		sendQuestionFromEmail.className = "dialogField";
		
		var sendQuestionToEmailValue = sendQuestionToEmail.value;
		var sendQuestionFromEmailValue = sendQuestionFromEmail.value;
		var sendQuestionMessageValue = sendQuestionMessage.value;

		if ( sendQuestionToEmailValue == "" ) {
			sendQuestionToEmail.className = "dialogFieldError";
			sendQuestionFormError.innerHTML = "Please enter a \"To\" email address.";
			return false;
		}

		if ( sendQuestionFromEmailValue == "" ) {
			sendQuestionFromEmail.className = "dialogFieldError";
			sendQuestionFormError.innerHTML = "Please enter a \"From\" email address.";
			return false;
		}

		if ( !isEmailValid ( sendQuestionToEmailValue ) ) {
			sendQuestionToEmail.className = "dialogFieldError";
			sendQuestionFormError.innerHTML = "To email address is invalid.";
			return false;
		}
	
		if ( !isEmailValid ( sendQuestionFromEmailValue ) ) {
			sendQuestionFromEmail.className = "dialogFieldError";
			sendQuestionFormError.innerHTML = "From email address is invalid.";
			return false;
		}
	} catch ( exc ) {
		printTrace ( "EXC: " + exc );
	}

	return true;
}

function doSendQuestionToFriend () {
	
	if ( !validateSendQuestionToFriend () ) {
		return;
	}

	var sendQuestionToEmailValue = document.getElementById ( "sendQuestionToEmail" ).value;
	var sendQuestionFromEmailValue = document.getElementById ( "sendQuestionFromEmail" ).value;
	var sendQuestionMessageValue = document.getElementById ( "sendQuestionMessage" ).value;

    dataService_emailQuestion ( handleQuestionSentToFriend, m_currentQuestionObject.id, sendQuestionFromEmailValue, 
	   sendQuestionToEmailValue, sendQuestionMessageValue ); 

	var sendQuestionToAFriendButton = document.getElementById ( "sendQuestionToAFriendButton" );
	sendQuestionToAFriendButton.style.display = "none";
	
	var cancelSendQuestionToAFriendButton = document.getElementById ( "cancelSendQuestionToAFriendButton" );
	cancelSendQuestionToAFriendButton.style.backgroundImage = "url(images/DialogCloseButton.png)";
	cancelSendQuestionToAFriendButton.parentNode.style.width = "82px";
	
	var sendQuestionForm = document.getElementById ( "sendQuestionForm" );
	sendQuestionForm.style.display = "none";

	var sendQuestionSuccess = document.getElementById ( "sendQuestionSuccess" );
	sendQuestionSuccess.style.display = "block";

	//alert ( "parent: " +  cancelSendQuestionToAFriendButton.parentNode );
}

function handleQuestionSentToFriend ( data, xml ) {
	//alert ( "SENT!" );
}


/***
* ------------------------------------ "SEND GAME TO FRIEND(s)" DIALOG ----------------
***/

function showSendGameToFriendDialog () {

   shareGame_showShareQuestionScreen ();
   
/*
	var sendGameToEmail = document.getElementById ( "sendGameToEmail" );
	var sendGameFromEmail = document.getElementById ( "sendGameFromEmail" );
	var sendGameFormError = document.getElementById ( "sendGameFormError" );
	
	sendGameToEmail.className = "dialogField";
	sendGameFromEmail.className = "dialogField";
    sendGameFormError.innerHTML = "";

	var playerEmailAddress = getPlayerEmailAddress ();
	if ( playerEmailAddress ) {
		sendGameFromEmail.value = playerEmailAddress;
	}

	var dialogBoxesDiv = document.getElementById ( "dialogBoxesDiv" );
	dialogBoxesDiv.style.display = "block";

	var sendGameToAFriendButton = document.getElementById ( "sendGameToAFriendButton" );
	sendGameToAFriendButton.style.display = "block";
	//sendGameToAFriendButton.style.visibility = "visible";
	
	var cancelSendGameToAFriendButton = document.getElementById ( "cancelSendGameToAFriendButton" );
	cancelSendGameToAFriendButton.style.backgroundImage = "url(images/DialogCloseButton.png)";
	cancelSendGameToAFriendButton.parentNode.style.width = "180px";

	var dialog = document.getElementById ("sendGameToAFriendDialog");
	dialog.style.display = "block";
	dialog.style.visibility = "visible";
	
	var sendGameForm = document.getElementById ( "sendGameForm" );
	sendGameForm.style.display = "block";

	var sendGameSuccess = document.getElementById ( "sendGameSuccess" );
	sendGameSuccess.style.display = "none";
*/

}

function createEmailListArray ( originalEmailFieldValue ) {

  
   
   var addressesArray = null;
		
	if ( originalEmailFieldValue.indexOf ( ";" ) > 0 ) {
		addressesArray = originalEmailFieldValue.split (";");
		// addressesArray = addresses.
	} else if ( originalEmailFieldValue.indexOf ( "," ) > 0 ) {
		addressesArray = originalEmailFieldValue.split (",");
	} else {
		addressesArray = originalEmailFieldValue.split (" ");
	}

	
	
	return addressesArray;
}


function createCommaSeparatedEmailList ( originalEmailFieldValue ) {

   var addresses = null;
   
   var addressesArray = createEmailListArray ( originalEmailFieldValue );
		
	addresses = addressesArray.join ( ", " );
	
	return addresses;
}

function validateSendGameToFriend () {
	
	try {
		var sendGameToEmail = document.getElementById ( "sendGameToEmail" );
		var sendGameFromEmail = document.getElementById ( "sendGameFromEmail" );
		var sendGameMessage = document.getElementById ( "sendGameMessage" );
		var sendGameFormError = document.getElementById ( "sendGameFormError" );
		
		sendGameToEmail.className = "dialogField";
		sendGameFromEmail.className = "dialogField";
		
		var sendGameToEmailValue = sendGameToEmail.value;
		var sendGameFromEmailValue = sendGameFromEmail.value;
		var sendGameMessageValue = sendGameMessage.value;

		if ( sendGameToEmailValue == "" ) {
			sendGameToEmail.className = "dialogFieldError";
			sendGameFormError.innerHTML = "Please enter a \"To\" email address.";
			return false;
		}

		if ( sendGameFromEmailValue == "" ) {
			sendGameFromEmail.className = "dialogFieldError";
			sendGameFormError.innerHTML = "Please enter a \"From\" email address.";
			return false;
		}

        var toEmailAddresses = createEmailListArray ( sendGameToEmailValue );
		
		for ( var idx = 0; idx < toEmailAddresses.length; idx++ ) { 
		   var oneEmailAddress = toEmailAddresses[idx];
		  // alert ( " oneEmailAddress: " + oneEmailAddress );
		   if ( !isEmailValid ( oneEmailAddress ) ) {
			  sendGameToEmail.className = "dialogFieldError";
			  sendGameFormError.innerHTML = "To email address is invalid.";
			  return false;
		   }
		}
	
	//alert ( " sendGameFromEmailValue: " + sendGameFromEmailValue );
	
		if ( !isEmailValid ( sendGameFromEmailValue ) ) {
			sendGameFromEmail.className = "dialogFieldError";
			sendGameFormError.innerHTML = "From email address is invalid.";
			
	//alert ( "THINKS IS INVALID" );
	
			return false;
		}
	} catch ( exc ) {
		printTrace ( "EXC: " + exc );
	}

	return true;
}

function doSendGameToFriend ( gamePageId ) {
	
	if ( !validateSendGameToFriend () ) {
		return;
	}

//alert ( " SHOULD DO SEND" );

	var sendGameToEmailValue = document.getElementById ( "sendGameToEmail" ).value;
	var sendGameFromEmailValue = document.getElementById ( "sendGameFromEmail" ).value;
	var sendGameMessageValue = document.getElementById ( "sendGameMessage" ).value;

    sendGameToEmailValue = createCommaSeparatedEmailList ( sendGameToEmailValue );
	
    var gameType = m_currentGameType;
    if ( gameType != "HIT" ) {
	   gameType = "player";
    }
   
    var origin = "site";
   
//try {   
    dataService_emailGame ( handleGameSentToFriend, m_gameId, m_pjuid, gameType, origin, sendGameFromEmailValue, 
		sendGameToEmailValue, sendGameMessageValue, gamePageId );


  //  dataService_emailQuestion ( handleQuestionSentToFriend, m_currentQuestionObject.id, sendQuestionFromEmailValue, 
//	   sendQuestionToEmailValue, sendQuestionMessageValue ); 

	var sendGameToAFriendButton = document.getElementById ( "sendGameToAFriendButton" );
	sendGameToAFriendButton.style.display = "none";
	
	var cancelSendGameToAFriendButton = document.getElementById ( "cancelSendGameToAFriendButton" );
	cancelSendGameToAFriendButton.style.backgroundImage = "url(images/DialogCloseButton.png)";
	cancelSendGameToAFriendButton.parentNode.style.width = "82px";
	
	var sendGameForm = document.getElementById ( "sendGameForm" );
	sendGameForm.style.display = "none";

	var sendGameSuccess = document.getElementById ( "sendGameSuccess" );
	sendGameSuccess.style.display = "block";

//} catch ( exc ) {
//	alert ( "EXC: " + exc );
//}
	//alert ( "parent: " +  cancelSendQuestionToAFriendButton.parentNode );
}

function handleGameSentToFriend ( data, xml ) {
	// alert ( "SENT GAME!" );
}





/***
* ------------------------------------ "QUALIFY FOR WEEKLY PRIZE" ----------------
***/

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


function showQualifyForDailyPrize ()
{	
	// SKIP THIS WHOLE THING: July 2009
	return ;
	
	var pageSize = getPageSize ();
	


	//alert ( "page size: " + pageSize );
	
	var objBody = document.getElementsByTagName ( "body" )[0];
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','objOverlay');
	objOverlay.style.display = 'block';
	objOverlay.style.position = "absolute";
	objOverlay.style.top = "0px";
	objOverlay.style.left = "0px";
	objOverlay.style.width = pageSize[0] + "px"; 
	objOverlay.style.height = pageSize[1] + "px";
	objOverlay.style.backgroundColor="#000000";
	objOverlay.style.textAlign = "center";
	objOverlay.style.opacity = ".8";
	objOverlay.style.filter = "alpha(opacity=80)";
//	objOverlay.onclick = function () {
		//alert ( "CLICKED this: " + this );
		
//		this.parentNode.removeChild(this);
//			
//	}
	objBody.appendChild(objOverlay);
	
	var objAnimationContainer = document.createElement("div");
	objAnimationContainer.setAttribute('id','objAnimationContainer');
	objAnimationContainer.style.display = 'block';
	objAnimationContainer.style.position = "absolute";
	objAnimationContainer.style.top = "0px";
	objAnimationContainer.style.left = "0px";
	objAnimationContainer.style.width = pageSize[0] + "px"; 
	objAnimationContainer.style.height = pageSize[1] + "px";
	objAnimationContainer.style.textAlign = "center";
	objAnimationContainer.onclick = function () {
		//alert ( "CLICKED this: " + this );
		
		//alert ( " delayedQualifyForDrawingAnimation: " + delayedQualifyForDrawingAnimation );
		delayedQualifyForDrawingAnimation ();
		
		//alert ( " objOverlay: " + objOverlay );
		//objOverlay.parentNode.removeChild(objOverlay);
		//this.parentNode.removeChild(this);
		//alert ( "SURVIVED" );	
	}
	objAnimationContainer.removeOverlay = function () {
		//alert ( " objOverlay: " + objOverlay );
		objOverlay.parentNode.removeChild(objOverlay);
		this.parentNode.removeChild(this);
		//alert ( "SURVIVED" );	
		
	}
	objBody.appendChild(objAnimationContainer);


	var flashQualifyMessageContainer = document.createElement("div");
	flashQualifyMessageContainer.setAttribute('id','flashQualifyMessageContainer');
	flashQualifyMessageContainer.style.marginTop = "0px";
	flashQualifyMessageContainer.style.marginLeft = m_gameAchievementMessageContainerMarginLeft; //"auto";
	flashQualifyMessageContainer.style.marginRight = "auto";
	flashQualifyMessageContainer.style.width = m_gameAchievementMessageContainerWidth + "px"; //"900px";
	flashQualifyMessageContainer.style.height = m_gameAchievementMessageContainerHeight + "px"; //"600px";
	flashQualifyMessageContainer.style.border = "none";
	flashQualifyMessageContainer.style.overflow = "hidden";
	//flashQualifyMessageContainer.style.backgroundColor = "#ff0000";
	objAnimationContainer.appendChild( flashQualifyMessageContainer );
	
	 embedFlashContent ( "flashQualifyMessage", "flashQualifyMessageContainer", 
		"/content/game/DailyDrawingAnimation.swf", "100%", "100%", "#ffffff", "transparent", "exactFit" );
	
}

function showQualifyForMonthlyPrizeOne ()
{
	// SKIP THIS WHOLE THING: July 2009
	return ;
	
	var pageSize = getPageSize ();

	//alert ( "page size: " + pageSize );
	
	var objBody = document.getElementsByTagName ( "body" )[0];
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','objOverlay');
	objOverlay.style.display = 'block';
	objOverlay.style.position = "absolute";
	objOverlay.style.top = "0px";
	objOverlay.style.left = "0px";
	objOverlay.style.width = pageSize[0] + "px"; 
	objOverlay.style.height = pageSize[1] + "px";
	objOverlay.style.backgroundColor="#000000";
	objOverlay.style.textAlign = "center";
	objOverlay.style.opacity = ".8";
	objOverlay.style.filter = "alpha(opacity=80)";
//	objOverlay.onclick = function () {
		//alert ( "CLICKED this: " + this );
		
//		this.parentNode.removeChild(this);
//			
//	}
	objBody.appendChild(objOverlay);
	
	var objAnimationContainer = document.createElement("div");
	objAnimationContainer.setAttribute('id','objAnimationContainer');
	objAnimationContainer.style.display = 'block';
	objAnimationContainer.style.position = "absolute";
	objAnimationContainer.style.top = "0px";
	objAnimationContainer.style.left = "0px";
	objAnimationContainer.style.width = pageSize[0] + "px"; 
	objAnimationContainer.style.height = pageSize[1] + "px";
	objAnimationContainer.style.textAlign = "center";
	objAnimationContainer.onclick = function () {
		//alert ( "CLICKED this: " + this );
		
		//alert ( " delayedQualifyForDrawingAnimation: " + delayedQualifyForDrawingAnimation );
		delayedQualifyForDrawingAnimation ();
		
		//alert ( " objOverlay: " + objOverlay );
		//objOverlay.parentNode.removeChild(objOverlay);
		//this.parentNode.removeChild(this);
		//alert ( "SURVIVED" );	
	}
	objAnimationContainer.removeOverlay = function () {
		//alert ( " objOverlay: " + objOverlay );
		objOverlay.parentNode.removeChild(objOverlay);
		this.parentNode.removeChild(this);
		//alert ( "SURVIVED" );	
		
	}
	objBody.appendChild(objAnimationContainer);


	var flashQualifyMessageContainer = document.createElement("div");
	flashQualifyMessageContainer.setAttribute('id','flashQualifyMessageContainer');
	flashQualifyMessageContainer.style.marginTop = "0px";
	flashQualifyMessageContainer.style.marginLeft = m_gameAchievementMessageContainerMarginLeft; //"auto";
	flashQualifyMessageContainer.style.marginRight = "auto";
	flashQualifyMessageContainer.style.width = m_gameAchievementMessageContainerWidth + "px"; //"900px";
	flashQualifyMessageContainer.style.height = m_gameAchievementMessageContainerHeight + "px"; //"600px";
	flashQualifyMessageContainer.style.border = "none";
	flashQualifyMessageContainer.style.overflow = "hidden";
	//flashQualifyMessageContainer.style.backgroundColor = "#ff0000";
	objAnimationContainer.appendChild( flashQualifyMessageContainer );
	
	 embedFlashContent ( "flashQualifyMessage", "flashQualifyMessageContainer", 
		"/content/game/MonthlyDrawingOneAnimation.swf", "100%", "100%", "#ffffff", "transparent", "exactFit" );
	
}

function showQualifyForMonthlyPrizeTwo () 
{
	// SKIP THIS WHOLE THING: July 2009
	return ;

    var pageSize = getPageSize ();

	//alert ( "page size: " + pageSize );
	
	var objBody = document.getElementsByTagName ( "body" )[0];
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','objOverlay');
	objOverlay.style.display = 'block';
	objOverlay.style.position = "absolute";
	objOverlay.style.top = "0px";
	objOverlay.style.left = "0px";
	objOverlay.style.width = pageSize[0] + "px"; 
	objOverlay.style.height = pageSize[1] + "px";
	objOverlay.style.backgroundColor="#000000";
	objOverlay.style.textAlign = "center";
	objOverlay.style.opacity = ".8";
	objOverlay.style.filter = "alpha(opacity=80)";
//	objOverlay.onclick = function () {
		//alert ( "CLICKED this: " + this );
		
//		this.parentNode.removeChild(this);
//			
//	}
	objBody.appendChild(objOverlay);
	
	var objAnimationContainer = document.createElement("div");
	objAnimationContainer.setAttribute('id','objAnimationContainer');
	objAnimationContainer.style.display = 'block';
	objAnimationContainer.style.position = "absolute";
	objAnimationContainer.style.top = "0px";
	objAnimationContainer.style.left = "0px";
	objAnimationContainer.style.width = pageSize[0] + "px"; 
	objAnimationContainer.style.height = pageSize[1] + "px";
	objAnimationContainer.style.textAlign = "center";
	objAnimationContainer.onclick = function () {
		//alert ( "CLICKED this: " + this );
		
		//alert ( " delayedQualifyForDrawingAnimation: " + delayedQualifyForDrawingAnimation );
		delayedQualifyForDrawingAnimation ();
		
		//alert ( " objOverlay: " + objOverlay );
		//objOverlay.parentNode.removeChild(objOverlay);
		//this.parentNode.removeChild(this);
		//alert ( "SURVIVED" );	
	}
	objAnimationContainer.removeOverlay = function () {
		//alert ( " objOverlay: " + objOverlay );
		objOverlay.parentNode.removeChild(objOverlay);
		this.parentNode.removeChild(this);
		//alert ( "SURVIVED" );	
		
	}
	objBody.appendChild(objAnimationContainer);


	var flashQualifyMessageContainer = document.createElement("div");
	flashQualifyMessageContainer.setAttribute('id','flashQualifyMessageContainer');
	flashQualifyMessageContainer.style.marginTop = "0px";
	flashQualifyMessageContainer.style.marginLeft = m_gameAchievementMessageContainerMarginLeft; //"auto";
	flashQualifyMessageContainer.style.marginRight = "auto";
	flashQualifyMessageContainer.style.width = m_gameAchievementMessageContainerWidth + "px"; //"900px";
	flashQualifyMessageContainer.style.height = m_gameAchievementMessageContainerHeight + "px"; //"600px";
	flashQualifyMessageContainer.style.border = "none";
	flashQualifyMessageContainer.style.overflow = "hidden";
	//flashQualifyMessageContainer.style.backgroundColor = "#ff0000";
	objAnimationContainer.appendChild( flashQualifyMessageContainer );
	
	 embedFlashContent ( "flashQualifyMessage", "flashQualifyMessageContainer", 
		"/content/game/MonthlyDrawingTwoAnimation.swf", "100%", "100%", "#ffffff", "transparent", "exactFit" );
	
}

/*
endGameEmailAddresses" onclick="handleClickInEndGameChallengeAddressList
*/

var m_clickedInEndGameChallengeAddressList = false;

function handleClickInEndGameChallengeAddressList () {
	if ( m_clickedInEndGameChallengeAddressList == false ) {
		m_clickedInEndGameChallengeAddressList = true;
		var endGameEmailAddresses = document.getElementById ( "endGameEmailAddresses" );
		
		//alert ( " endGameEmailAddresses: " + endGameEmailAddresses ):
		//alert ( " VAL: " + endGameEmailAddresses.value );
		endGameEmailAddresses.value = "";
	}
}

function sendChallengeFromEndGameScreen () {
	//alert ( "SEND CHALLENGE FROM END GAME" );
	
	var fromEmailAddress = m_userInfo.email;
	var gameName = m_gameData.gameDetails.gameName;

//alert ( "SCOTT: sendChallengeFromEndGameScreen" );

   try {
	shareGame_sendGameChallengeFromEndGamePage ( fromEmailAddress, gameName );
	} catch ( exc ) {
		printTrace ( "EXC: " + exc );
	}
}


/*
var m_endGameAnimationCheckTimeout = null;


function handleEndGameAnimationCheckTimeout () {
	printTrace  ( "  END GAME ANIMATINO CHECK TIMEOUT: " + m_endGameAnimationCheckTimeout );
	
	if ( m_endGameAnimationCheckTimeout != null ) {
		m_endGameAnimationCheckTimeout = null;
	    setTimeout ( delayedQualifyForDrawingAnimation, 100 );	
	    setTimeout ( afterNewEndGameAnimation, 110 );
	}
	
}

function startTimerToCheckIfEndGameAnimationDone () {
	m_endGameAnimationCheckTimeout = setTimeout ( handleEndGameAnimationCheckTimeout, 14000 );
}
*/

function fromFlash_endGameAnimationDone () {
	
//alert ( " fromFlash_endGameAnimationDone called" );

//return;
	
//	var _endGameAnimationCheckTimeout = m_endGameAnimationCheckTimeout;
	
	// If the timer that was waiting for the end game screen to go away has "dinged", then it already tore down the end of game
	// screen, so we do nothing here.
//	if ( m_endGameAnimationCheckTimeout == null ) {
	//	return;
		
	// Otherwise, we received the "fromFlash_endGameAnimationDone" call from the end game animation before the timer "dinged", so we
	// just proceed as normal - including turning off the timer so it doesn't "ding" while we're ending the game.
	//} else {
	//	m_endGameAnimationCheckTimeout = null;
	//	clearTimeout (_endGameAnimationCheckTimeout);
	//}
	
	
//printTrace ( "END GAME ANIMATION RECEIVED FROM FLASH DONE" );

    
	
	//function dismissQualifyForDrawingAnimation () {
	setTimeout ( delayedQualifyForDrawingAnimation, 100 );
	
	setTimeout ( afterNewEndGameAnimation, 110 );
//}

}

function fromFlash_endGameAnimationLoaded () {
	
	
	var objOverlay = document.getElementById ( "objOverlay" );
	objOverlay.style.display = "block";

	var gameOverMessageDiv = document.getElementById ( "gameOverMessageDiv" );
	gameOverMessageDiv.style.display = "block";
	
//printTrace ( " from fromFlash_endGameAnimationLoaded " );
	handleEndOfGameScreenShowing ();

	// printTrace ( "END GAME ANIMATION LOADED, SHOWING?" );
}

function afterNewEndGameAnimation () {
	
	/**
	* Hide all the old HTML stuff in the "game over" div...
	*/
//	var gameOverTopMessage
	
	
	var gameboardNew = document.getElementById ( "gameboardNew" );
    gameboardNew.hideAllVideoCells ();

	var gameOverMessageDiv = document.getElementById ( "gameOverMessageDiv" );
	gameOverMessageDiv.style.display = "block";
	
//printTrace ( "from afterNewEndGameAnimation" );
	handleEndOfGameScreenShowing ();
	
	
	
  // if ( doShowEndGameSurvey () ) {
	//   showEndGameSurvey ();
  // }


   // var gameboardNew = document.getElementById ( "gameboardNew" );
	
	
/*
	   m_gameOverData = data;
	   
	   m_gameOver = true;
   }
   
   if ( data.average ) {
	   m_averageScoreForThisGame = Math.round(data.average);
   }
   if ( data.percentile ) {
	   var playerPercentile = Number(data.percentile) * 100;
	   playerPercentile = Math.round(playerPercentile);
	   var playerPercentage = 100 - playerPercentile;
	   m_playerPercentagePosition = playerPercentage;
   }

*/

/*
   var playerPercentage = Number(100);

   if ( m_gameOverData.percentile ) {
	   var playerPercentile = Number(m_gameOverData.percentile) * 100;
	   playerPercentile = Math.round(playerPercentile);
	   playerPercentage = 100 - playerPercentile;
   }

   if ( playerPercentage <= 20 ) {
	 gameboardNew.playGameOverHighScoreSound ();
   } else {
	  gameboardNew.playGameOverNormalScoreSound ();
   }
*/	
	

	//printTrace ( "GENERIC afterNewEndGameAnimation " );
	// do nothing here.  For facebook games, this is when we redirect.
}

function showNewVersionOfEndOfGame () {
	
	var endOfGameColorsDiv = document.getElementById ( "endOfGameColorsDiv" );
	var endOfGameLoggedInDiv = document.getElementById ( "endOfGameLoggedInDiv" );
	var endOfGameNotLoggedInDiv = document.getElementById ( "endOfGameNotLoggedInDiv" );
	
	if ( endOfGameColorsDiv ) {
	   endOfGameColorsDiv.style.display = "block";
	}

	var endGameMessageDiv ;
	if ( userIsLoggedIn () ) 
	{
		endOfGameLoggedInDiv.style.display = "block";
		
		var endGamePlayerName = document.getElementById ( "endGamePlayerName" );
		var endGameDailyScore = document.getElementById ( "endGameDailyScore" );
		var endGameMonthlyScore = document.getElementById ( "endGameMonthlyScore" );
		var endGameLifetimeScore = document.getElementById ( "endGameLifetimeScore" );
		var endGameGameName = document.getElementById ( "endGameGameName" );
		var endGameGamePoints  = document.getElementById ( "endGameGamePoints" );
	    endGameMessageDiv = document.getElementById ( "endGameMessage" );
		var endGameNeededToQualifyForDaily = document.getElementById ( "endGameNeededToQualifyForDaily" );
		var endGameNeededToQualifyForMonthly = document.getElementById ( "endGameNeededToQualifyForMonthly" );
		//var endGameNeededToQualifyForBonusMonthly = document.getElementById ( "endGameNeededToQualifyForBonusMonthly" );
		var endGameAvatarImage = document.getElementById ( "endGameAvatarImage" );
		
		var beforeEndGameDailyScore = Number(m_userInfo.dailyScore);
		var afterEndGameDailyScore = Number ( beforeEndGameDailyScore + Number(m_currentGameScore) );
		
		var beforeEndGameMonthlyScore = Number(m_userInfo.monthlyScore);
		var afterEndGameMonthlyScore = Number ( beforeEndGameMonthlyScore + Number(m_currentGameScore) );
		
		var beforeEndGameLifetimeScore = Number(m_userInfo.lifetimeScore);
		var afterEndGameLifetimeScore = Number ( beforeEndGameLifetimeScore + Number(m_currentGameScore) );
		
		if ( endGamePlayerName ) {
		   endGamePlayerName.innerHTML = m_userInfo.name;
		}
		if ( endGameDailyScore ) {
		   endGameDailyScore.innerHTML = afterEndGameDailyScore;
		}
		if ( endGameMonthlyScore ) {
		   endGameMonthlyScore.innerHTML = afterEndGameMonthlyScore;
		}
		if ( endGameLifetimeScore ) {
		   endGameLifetimeScore.innerHTML = afterEndGameLifetimeScore;
		}
		endGameGameName.innerHTML = m_gameData.gameDetails.gameName;
		endGameGamePoints.innerHTML = m_currentGameScore;		

//printTrace ( "SCORE: " + m_currentGameScore );		
		
/*
*       Daily $100: XXX more points to qualify
*       Monthly $1000: xxxxx more points to qualify
*/

		var amountNeededToQualifyForDaily = 0;
		if ( afterEndGameDailyScore < 5000 ) {
			amountNeededToQualifyForDaily = Number ( 5000 - Number (afterEndGameDailyScore) );
		}
		
		if ( false )   // amountNeededToQualifyForDaily == 0
		{
			if ( endGameNeededToQualifyForDaily ) {
			   endGameNeededToQualifyForDaily.innerHTML = "You are qualified for the <b>Daily $100</b> - congrats!";
			}
		} else {
			if ( endGameNeededToQualifyForDaily ) {
			   endGameNeededToQualifyForDaily.innerHTML = "<b>Daily $100</b>: <b>" + amountNeededToQualifyForDaily + "</b> more points to qualify.";
			}
		}
		
		//endGameNeededToQualifyForDaily.innerHTML = amountNeededToQualifyForDaily;
		
		var amountNeededToQualifyForMonthly = 0;
		if ( afterEndGameMonthlyScore < 25000 ) {
			amountNeededToQualifyForMonthly = Number ( 25000 - Number (afterEndGameMonthlyScore) );
		}
		
		if ( false )   // amountNeededToQualifyForMonthly == 0 
		{
			if ( endGameNeededToQualifyForMonthly ) {
			   endGameNeededToQualifyForMonthly.innerHTML = "You are qualified for the <b>Monthly $1000</b> drawing - awesome!";
			}
		} else {
			if ( endGameNeededToQualifyForMonthly ) {
			   endGameNeededToQualifyForMonthly.innerHTML = "<b>Monthly $1000</b>: <b>" + amountNeededToQualifyForMonthly + "</b> more points to qualify.";
			}
		}
		
		//endGameNeededToQualifyForMonthly.innerHTML = amountNeededToQualifyForMonthly;
	
		// m_pjuid
		//m_pjuid = 54;
	
	   if ( endGameAvatarImage ) {
		   endGameAvatarImage.src = "/videocube/imageserver.htm?file=" + m_pjuid + "_avatar.jpg&avatarType=player";
		}
	} 
	else 
	{
		
		if ( endOfGameNotLoggedInDiv ) {
		   endOfGameNotLoggedInDiv.style.display = "block";
		}
		
		var endGameGameName   = document.getElementById ( "endGameNotLoggedInGameName" );
		var endGameGamePoints = document.getElementById ( "endGameNotLoggedInGamePoints" );
	    endGameMessageDiv     = document.getElementById ( "endGameNotLoggedInMessage" );
		
		if ( endGameGameName ) {
		   endGameGameName.innerHTML = m_gameData.gameDetails.gameName;
		}
		if ( endGameGamePoints ) {
		   endGameGamePoints.innerHTML = m_currentGameScore;
		}
		
	}
	
	
	/**
	* Here is where we choose not to show the animation.
	*/
	if ( m_showEndOfGameAnimation == false ) 
	{
		
		// printTrace ( "SHOULD DO SOMETHING" );
		 
		var congratsMessageText = getCongratulationsText ();	 
	    var congratsMessage = document.getElementById ( "congratsMessage" );
	    if ( congratsMessage ) 
		{
		  //	printTrace ( " gameOverTopMessageText: " + congratsMessageText );
	      congratsMessage.innerHTML = congratsMessageText;
		}

        showAverageAndPercentileValues ();		 
		 
		var gameboardNew = document.getElementById ( "gameboardNew" );
		try
		{			
		  gameboardNew.hideAllVideoCells ();	
		  gameboardNew.showEndOfGameBack ();
		}
		catch ( exc ) 
		{
          var gameboardC = document.getElementById ( "gameboardNewContainer" );
          gameboardC.style.display = "none";
        }
  
		var gameOverMessageDiv = document.getElementById ( "gameOverMessageDiv" );
	    gameOverMessageDiv.style.display = "block";			
		handleEndOfGameScreenShowing ();
		
		return;
	}
	

	//alert ( "CALLING SHOW END OF GAME ANIMATION" );
	
//	var gameOverMessageDiv = document.getElementById ( "gameOverMessageDiv" );
//	gameOverMessageDiv.style.display = "block";
	
	var pageSize = getPageSize ();
	


	//printTrace ( "page size: " + pageSize );
	
	var objBody = document.getElementsByTagName ( "body" )[0];
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','objOverlay');
	objOverlay.style.display = 'none'; //block';
	objOverlay.style.position = "absolute";
	objOverlay.style.top = "0px";
	objOverlay.style.left = "0px";
	objOverlay.style.width = pageSize[0] + "px"; 
	objOverlay.style.height = pageSize[1] + "px";
	objOverlay.style.backgroundColor="#000000";
	objOverlay.style.textAlign = "center";
	objOverlay.style.opacity = "0"; // ".8";
	objOverlay.style.filter = "alpha(opacity=0)"; //80)";
//	objOverlay.onclick = function () {
		//printTrace ( "CLICKED this: " + this );
		
//		this.parentNode.removeChild(this);
//			
//	}
	objBody.appendChild(objOverlay);
	
	var objAnimationContainer = document.createElement("div");
	objAnimationContainer.setAttribute('id','objAnimationContainer');
	objAnimationContainer.style.display = 'block';
	objAnimationContainer.style.position = "absolute";
	objAnimationContainer.style.top = "0px";
	objAnimationContainer.style.left = "0px";
	objAnimationContainer.style.width = pageSize[0] + "px"; 
	objAnimationContainer.style.height = pageSize[1] + "px";
	objAnimationContainer.style.textAlign = "center";
	objAnimationContainer.onclick = function () {
		//printTrace ( "CLICKED this: " + this );
		
		//alert ( " delayedQualifyForDrawingAnimation: " + delayedQualifyForDrawingAnimation );
		
		// DO NOT ALLOW as of 6/30/08 delayedQualifyForDrawingAnimation ();
		
		//alert ( " objOverlay: " + objOverlay );
		//objOverlay.parentNode.removeChild(objOverlay);
		//this.parentNode.removeChild(this);
		//alert ( "SURVIVED" );	
	}
	objAnimationContainer.removeOverlay = function () {
		//alert ( " objOverlay: " + objOverlay );
		objOverlay.parentNode.removeChild(objOverlay);
		this.parentNode.removeChild(this);
		//alert ( "SURVIVED" );	
		
	}
	objBody.appendChild(objAnimationContainer);


	var flashQualifyMessageContainer = document.createElement("div");
	flashQualifyMessageContainer.setAttribute('id','flashQualifyMessageContainer');
	flashQualifyMessageContainer.style.marginTop = "0px";
	flashQualifyMessageContainer.style.marginLeft = m_gameAchievementMessageContainerMarginLeft; //"auto";
	flashQualifyMessageContainer.style.marginRight = "auto";
	flashQualifyMessageContainer.style.width = m_gameAchievementMessageContainerWidth + "px"; //"900px";
	flashQualifyMessageContainer.style.height = m_gameAchievementMessageContainerHeight + "px"; //"600px";
	flashQualifyMessageContainer.style.border = "none";
	flashQualifyMessageContainer.style.overflow = "hidden";
	//flashQualifyMessageContainer.style.backgroundColor = "#ff0000";
	objAnimationContainer.appendChild( flashQualifyMessageContainer );
	
	
    var gameName = m_gameData.gameDetails.gameName;
	var averageScore = Math.round(m_gameOverData.average);
	var playerPercentile = Number(m_gameOverData.percentile) * 100;
	playerPercentile = Math.round(playerPercentile);
	var playerPercentage = 100 - playerPercentile;
	if ( playerPercentage < 1 ) {
		playerPercentage = 1;
	}
	
	var messageToPlayer = "";
	
//m_currentGameScore = 300;
	
   if ( m_currentGameScore < 300 ) {
      messageToPlayer = null;
   } else if ( m_currentGameScore >= 300 && m_currentGameScore < 700 ) {
      messageToPlayer = "Congratulations.";
   } else if ( m_currentGameScore >= 700 && m_currentGameScore < 1000 ) {
      messageToPlayer = "Awesome!";
   } else if ( m_currentGameScore >= 1000 ) {
      messageToPlayer = "Epic!";
   }
	
//alert ( " gameName: " + gameName + " escaped: " + escape(gameName) );

    var escapedGameName = gameName.replace  ( /'/g, "%27" );
	escapedGameName = escapedGameName.replace  ( / /g, "%20" );
//	alert ( " escapedGameName: " + escapedGameName );

//alert ( "USING gameName: " + gameName );

	var endOfGameSwf = "/content/game/EndOfGameAnimation.swf?gamePoints=" + m_currentGameScore; //gameName2=" + gameName; //gameName; // escape(gameName);
   // endOfGameSwf += "&gamePoints=" + m_currentGameScore;
	endOfGameSwf += "&averageScore=" + averageScore;
	if ( playerPercentage <= 20 ) {
		endOfGameSwf += "&percentile=" + playerPercentage;
	}
	if ( messageToPlayer ) {
		endOfGameSwf += "&playerMessage=" + messageToPlayer;
	}
	
     /**
	 * NOTE: Had to do my own escape on the game.  For some reason, when using the default JS "escape" it screwed up
	 * non Basic Latin type characters (like an "enyay" from Spanish).
	 * What happened was the default 'escape' would mistakenly escape the special Latin character(s).  Then on the Flash side, the
	 * characters couldn't be made back into what they were supposed to be so they were hidden.
	 *
	 * NOTE 2: You can't pass "gameName" in the "src" URL for the embed/object tag.  If you do, things don't work.  But you CAN!!!
	 * pass the value of "gameName" as a flashvars.  So that's what we are doing here.
	 */
	 embedFlashContent ( "flashQualifyMessage", "flashQualifyMessageContainer", 
		endOfGameSwf, "100%", "100%", "#ffffff", "transparent", "exactFit", "gameName=" + escapedGameName );
	
}

function showNewEndOfGameAnimation () {

//alert ( "SHOW END OF GAME ANIMATION" );

	//alert ( "CALLING SHOW END OF GAME ANIMATION" );
	
//	var gameOverMessageDiv = document.getElementById ( "gameOverMessageDiv" );
//	gameOverMessageDiv.style.display = "block";
	
	var pageSize = getPageSize ();
	
	var gameOverTopMessage = document.getElementById ( "gameOverTopMessage" );
	gameOverTopMessage.style.display = "none";


	//alert ( "page size: " + pageSize );
	
	var objBody = document.getElementsByTagName ( "body" )[0];
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','objOverlay');
	objOverlay.style.display = 'block';
	objOverlay.style.position = "absolute";
	objOverlay.style.top = "0px";
	objOverlay.style.left = "0px";
	objOverlay.style.width = pageSize[0] + "px"; 
	objOverlay.style.height = pageSize[1] + "px";
	objOverlay.style.backgroundColor="#000000";
	objOverlay.style.textAlign = "center";
	objOverlay.style.opacity = "0"; //.8";
	objOverlay.style.filter = "alpha(opacity=0)"; //80)";
//	objOverlay.onclick = function () {
		//alert ( "CLICKED this: " + this );
		
//		this.parentNode.removeChild(this);
//			
//	}
	objBody.appendChild(objOverlay);
	
	var objAnimationContainer = document.createElement("div");
	objAnimationContainer.setAttribute('id','objAnimationContainer');
	objAnimationContainer.style.display = 'block';
	objAnimationContainer.style.position = "absolute";
	objAnimationContainer.style.top = "0px";
	objAnimationContainer.style.left = "0px";
	objAnimationContainer.style.width = pageSize[0] + "px"; 
	objAnimationContainer.style.height = pageSize[1] + "px";
	objAnimationContainer.style.textAlign = "center";
	objAnimationContainer.onclick = function () {
		//alert ( "CLICKED this: " + this );
		
		//alert ( " delayedQualifyForDrawingAnimation: " + delayedQualifyForDrawingAnimation );
		// NO MORE!!! 6/30/08  delayedQualifyForDrawingAnimation ();
		
		//alert ( " objOverlay: " + objOverlay );
		//objOverlay.parentNode.removeChild(objOverlay);
		//this.parentNode.removeChild(this);
		//alert ( "SURVIVED" );	
	}
	objAnimationContainer.removeOverlay = function () {
		//alert ( " objOverlay: " + objOverlay );
		objOverlay.parentNode.removeChild(objOverlay);
		this.parentNode.removeChild(this);
		//alert ( "SURVIVED" );	
		
	}
	objBody.appendChild(objAnimationContainer);


//alert ( "NEWER SIZE" );

	var flashQualifyMessageContainer = document.createElement("div");
	flashQualifyMessageContainer.setAttribute('id','flashQualifyMessageContainer');
	flashQualifyMessageContainer.style.marginTop = "0px";
	flashQualifyMessageContainer.style.marginLeft = m_gameAchievementMessageContainerMarginLeft; //"auto";
	flashQualifyMessageContainer.style.marginRight = "auto";
	flashQualifyMessageContainer.style.width = Number(Number(m_gameAchievementMessageContainerWidth) + 20) + "px"; //"900px";
	flashQualifyMessageContainer.style.height = Number(Number(m_gameAchievementMessageContainerHeight) + 80) + "px"; //"600px";
	flashQualifyMessageContainer.style.border = "none";
	flashQualifyMessageContainer.style.overflow = "hidden";
	
flashQualifyMessageContainer.style.position = "absolute";
flashQualifyMessageContainer.style.left = "-104px";
flashQualifyMessageContainer.style.top = "-70px";
flashQualifyMessageContainer.style.width = "870px";
flashQualifyMessageContainer.style.height = "600px";


	//flashQualifyMessageContainer.style.backgroundColor = "#ff0000";
	objAnimationContainer.appendChild( flashQualifyMessageContainer );
	
	
//alert( " flashQualifyMessageContainer.style.marginLeft: " + flashQualifyMessageContainer.style.marginLeft );
	
	
    var gameName = m_gameData.gameDetails.gameName;
	var averageScore = Math.round(m_gameOverData.average);
	var playerPercentile = Number(m_gameOverData.percentile) * 100;
	playerPercentile = Math.round(playerPercentile);
	var playerPercentage = 100 - playerPercentile;
	if ( playerPercentage < 1 ) {
		playerPercentage = 1;
	}
	
	var messageToPlayer = "";
	
//m_currentGameScore = 300;
	
   if ( m_currentGameScore < 300 ) {
      messageToPlayer = null;
   } else if ( m_currentGameScore >= 300 && m_currentGameScore < 700 ) {
      messageToPlayer = "Congratulations.";
   } else if ( m_currentGameScore >= 700 && m_currentGameScore < 1000 ) {
      messageToPlayer = "Awesome!";
   } else if ( m_currentGameScore >= 1000 ) {
      messageToPlayer = "Epic!";
   }

/* WAS
	var endOfGameSwf = "EndOfGameAnimation.swf?gameName=" + escape(gameName);
    endOfGameSwf += "&gamePoints=" + m_currentGameScore;
	endOfGameSwf += "&averageScore=" + averageScore;
	if ( playerPercentage <= 20 ) {
		endOfGameSwf += "&percentile=" + playerPercentage;
	}
	if ( messageToPlayer ) {
		endOfGameSwf += "&playerMessage=" + messageToPlayer;
	}
	
	
	 embedFlashContent ( "flashQualifyMessage", "flashQualifyMessageContainer", 
		endOfGameSwf, "100%", "100%", "#ffffff", "transparent", "exactFit" );
*/

    var escapedGameName = gameName.replace  ( /'/g, "%27" );
	escapedGameName = escapedGameName.replace  ( / /g, "%20" );

	var endOfGameSwf = "/content/game/EndOfGameAnimation.swf?gamePoints=" + m_currentGameScore; //gameName2=" + gameName; //gameName; // escape(gameName);
   // endOfGameSwf += "&gamePoints=" + m_currentGameScore;
	endOfGameSwf += "&averageScore=" + averageScore;
	if ( playerPercentage <= 20 ) {
		endOfGameSwf += "&percentile=" + playerPercentage;
	}
	if ( messageToPlayer ) {
		endOfGameSwf += "&playerMessage=" + messageToPlayer;
	}
	
     /**
	 * NOTE: Had to do my own escape on the game.  For some reason, when using the default JS "escape" it screwed up
	 * non Basic Latin type characters (like an "enyay" from Spanish).
	 * What happened was the default 'escape' would mistakenly escape the special Latin character(s).  Then on the Flash side, the
	 * characters couldn't be made back into what they were supposed to be so they were hidden.
	 *
	 * NOTE 2: You can't pass "gameName" in the "src" URL for the embed/object tag.  If you do, things don't work.  But you CAN!!!
	 * pass the value of "gameName" as a flashvars.  So that's what we are doing here.
	 */
	 embedFlashContent ( "flashQualifyMessage", "flashQualifyMessageContainer", 
		endOfGameSwf, "100%", "100%", "#ffffff", "transparent", "exactFit", "gameName=" + escapedGameName );


}



function dismissQualifyForDrawingAnimation () {
	setTimeout ( delayedQualifyForDrawingAnimation, 100 );
}

function delayedQualifyForDrawingAnimation () {
//	alert ( "DISMISS" );
	var flashQualifyMessageContainer = document.getElementById ( "flashQualifyMessageContainer" );
	flashQualifyMessageContainer.innerHTML = "";

//alert ( "REMOVING" );

 //   var objBody = document.getElementsByTagName ( "body" )[0];
	
//alert ( " objAnimationContainer.parentNode: " + objAnimationContainer.parentNode );
//alert ( " objAnimationContainer.parentNode.removeChild: " + objAnimationContainer.parentNode.removeChild );

//alert ( " document: " + document );
//alert ( " document.getElementById: " + document.getElementById );
    
	var objNameOtherThanObjAnimationContainer = document.getElementById ( "objAnimationContainer" );
	
//alert ( " OBJ:  " + objNameOtherThanObjAnimationContainer );
	
//alert ( " objAnimationContainer.removeOverlay: " + objAnimationContainer.removeOverlay );
objNameOtherThanObjAnimationContainer.removeOverlay ();
	
	
//	objBody.removeChild(objAnimationContainer);

//alert ( "AFTER" );
	
//	objOverlay = document.getElementById ( "objOverlay" );
//	objBody.removeChild(objOverlay);
	
}

/***
* ------------------------------------ "SURVEY QUIZ" PROCESSING ---------------------------------------------
***/

/*
setCookieWithExpiresInThisManyDays
*/

var GAMES_PLAYED_COOKIE_NAME = "numberOfGamesPlayed";
var WHICH_GAME_TO_SHOW_SURVEY = 3;

/*
function doShowEndGameSurvey () {
	var numberOfGamesPlayed = getCookie(GAMES_PLAYED_COOKIE_NAME);

    if ( numberOfGamesPlayed == null ) {
		numberOfGamesPlayed = Number(0);
	} 
	
	numberOfGamesPlayed = Number(numberOfGamesPlayed) + 1;
	
	setCookieWithExpiresInThisManyDays ( GAMES_PLAYED_COOKIE_NAME, numberOfGamesPlayed, 30 );
	
	if ( Number(numberOfGamesPlayed) == Number(WHICH_GAME_TO_SHOW_SURVEY) ) {
	   return true;
	} else {
	   return false;
	}
}

function showEndGameSurvey () {
	setTimeout ( delayedShowEndGameSurvey, 1000 );
}

function delayedShowEndGameSurvey () {
	// alert ( "SHOW POPUP" );
	
   var dialogBoxesDiv = document.getElementById ( "dialogBoxesDiv" );
   dialogBoxesDiv.style.display = "block";
 //  dialogBoxesDiv.style.backgroundColor = "#ff0000";
   //dialogBoxesDiv.style.overflow = "visible";
   
   var login_loginDialog = document.getElementById ("login_loginDialog");
   if ( login_loginDialog ) {
	  login_loginDialog.style.display = "none";
   }
   
   
   var reg_registrationDialog = document.getElementById ("reg_registrationDialog");
   if ( reg_registrationDialog ) {
	  reg_registrationDialog.style.display = "none";
   }
   
   var error_fatalGameErrorDialog = document.getElementById ("error_fatalGameErrorDialog");
   if ( error_fatalGameErrorDialog ) {
	  error_fatalGameErrorDialog.style.display = "none";
   }
	   
   var survey_surveyDialog = document.getElementById ("survey_surveyDialog");
   if ( survey_surveyDialog ) {
	   survey_surveyDialog.style.display = "block";
   }
	
}

function sendEndGameSurveyData () {
   var dialogBoxesDiv = document.getElementById ( "dialogBoxesDiv" );
   dialogBoxesDiv.style.display = "none";

   var survey_surveyDialog = document.getElementById ("survey_surveyDialog");
   if ( survey_surveyDialog ) {
	   survey_surveyDialog.style.display = "block";
   }

 // endGameSurveyWhatUserLiked, endGameSurveyWhatUserDidNotLike, endGameSurveyCategories
 
   var endGameSurveyWhatUserLiked = document.getElementById ("endGameSurveyWhatUserLiked").value;
   var endGameSurveyWhatUserDidNotLike = document.getElementById ("endGameSurveyWhatUserDidNotLike").value;
   var endGameSurveyCategories = document.getElementById ("endGameSurveyCategories").value;
   
  // alert ( "endGameSurveyWhatUserLiked: " + endGameSurveyWhatUserLiked + "  endGameSurveyWhatUserDidNotLike: " +
//		    endGameSurveyWhatUserDidNotLike + " endGameSurveyCategories: " + endGameSurveyCategories );
   
   storeUserComment ( endGameSurveyWhatUserLiked, "endGameLiked" );
   storeUserComment ( endGameSurveyWhatUserDidNotLike, "endGameDidNotLike" );
   storeUserComment ( endGameSurveyCategories, "endGameCategoriesWouldLike" );
}
*/


function storeUserComment ( userComment, commentType  ) {
  try {
   var iframe = document.createElement ( "iframe" );
   var nowObject = new Date(); // '2007-11-30 10:41:47'
   var creationDateTime = nowObject.getFullYear() + "-" + 
      Number(Number(nowObject.getMonth())+Number(1)) + "-" + 
	  Number(Number(nowObject.getDay())+Number(1)) + " " + 
	  nowObject.getHours() + ":" + nowObject.getMinutes();

    // nowObject.year + "-" + nowObject.month + "-" + nowObject.
   var iframeSource = "/videocube/storeUserContent.jsp?userFeedback=" + userComment + "&creationDateTime=" + creationDateTime +
      "&commentType=" + commentType;
	  
	// alert ( " iframeSource: " + iframeSource );
	  
 //  if ( QA_DB_ACCESS == true ) {
//	  iframeSource += "&isNotProd=true";
 //  }
   
   iframe.src = iframeSource;
   iframe.setAttribute ( "src", iframeSource );
   iframe.style.width = "1px";
   iframe.style.height = "1px";
   document.body.appendChild(iframe);
  } catch ( exc ) {
	  printTrace ( "EXC: " + exc );
  }
	
}


/***
* ------------------------------------ "ERROR DIALOG" PROCESSING ---------------------------------------------
***/

// error_fatalGameErrorDialog

   function showFatalGameErrorDialog ( errorDumpString, exceptionText, responseText ) {
	   
	  // alert ( "SHOW REG CALLED" );
	   
	   if ( exceptionText != undefined && exceptionText != null ) {
		   var exceptionTextDiv = document.getElementById ( "exceptionText" );
		   exceptionTextDiv.innerHTML = exceptionText;
		   
		   var extraDataToLog = null; //exceptionText;
		   if ( responseText != undefined && responseText != null ) {
			   extraDataToLog = responseText;
			  // dataToLog =  escape(dataToLog);
			   extraDataToLog = extraDataToLog.replace  ( /\'/g, "\\'" );
			  // dataToLog = dataToLog.substring ( 0, 120 );
			//   alert ( "AFTER REPLACE" );

			  // alert ( " dataToLog: " + dataToLog );
		   }
		   try {
			   storeUserComment ( exceptionText, "gameError" );
			   if ( extraDataToLog ) {
			      storeUserComment ( extraDataToLog, "gameError" );
			   }
		   } catch ( excHideLogCall ) {
		   }
	   }
	   
	   var dialogBoxesDiv = document.getElementById ( "dialogBoxesDiv" );
	   dialogBoxesDiv.style.display = "block";
	 //  dialogBoxesDiv.style.backgroundColor = "#ff0000";
       //dialogBoxesDiv.style.overflow = "visible";
	   
	   var login_loginDialog = document.getElementById ("login_loginDialog");
	   if ( login_loginDialog ) {
	      login_loginDialog.style.display = "none";
	   }
	   
	   
	   var reg_registrationDialog = document.getElementById ("reg_registrationDialog");
	   if ( reg_registrationDialog ) {
	      reg_registrationDialog.style.display = "none";
	   }
	   
	   var error_fatalGameErrorDialog = document.getElementById ("error_fatalGameErrorDialog");
	   if ( error_fatalGameErrorDialog ) {
	      error_fatalGameErrorDialog.style.display = "block";
	   }
	   
	   var fatalErrorMessageDetails = document.getElementById ("fatalErrorMessageDetails");
	//   alert ( " fatalErrorMessageDetails: " + fatalErrorMessageDetails );
	   var leftChevronsGone = errorDumpString.replace  ( /</g, "&lt;" );
	   var rightChevronsGone = leftChevronsGone.replace  ( />/g, "&gt;" );
	//   alert ( " rightChevronsGone: " + rightChevronsGone );
	   fatalErrorMessageDetails.innerHTML = rightChevronsGone; // urlencode(errorDumpString); //escape(errorDumpString);
	  //alert ( "BAR" );
	  
   }
   
   function hideFatalGameErrorDialog () {
	   var error_fatalGameErrorDialog = document.getElementById ("error_fatalGameErrorDialog");
	   if ( error_fatalGameErrorDialog ) {
	      error_fatalGameErrorDialog.style.display = "none";
	   }	   
   }

   function fatalGameErrorShowDetails () {
	   var fatalErrorMessageDetails = document.getElementById ("fatalErrorMessageDetails");
	   fatalErrorMessageDetails.style.display = "block";
   }
   
   function handleOkPressedFromFatalGameError () {
	   hideFatalGameErrorDialog ();
	   delayedEndGame ();
   }

/**
* ------------ COOKIE PROCESSING ------------
*/
    function getWholeCookie ( offset ) {
		var endstr = document.cookie.indexOf ( ";", offset );
		if ( endstr == -1 ) {
			endstr = document.cookie.length;
		}
		return unescape(document.cookie.substring(offset, endstr));
	}
	
    function getCookie ( cookieName ) {
		var arg = cookieName + "=";
		var argLength = arg.length;
		var cookieLength = document.cookie.length;
		var i = 0;
		while ( i < cookieLength ) {
			var j = i + argLength;
			if ( document.cookie.substring(i,j) == arg ) {
				return getWholeCookie(j);
			}
			i = document.cookie.indexOf ( " ", i) + 1;
			if ( i == 0 ) {
				break;
			}
		}
		
		return null;
	}
	
	function setCookieWithExpiresInThisManyDays (c_name,value,expiredays)
	{
	   var exdate=new Date();
	   exdate.setDate(exdate.getDate()+expiredays);
	   document.cookie=c_name+ "=" +escape(value)+
	   ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
	}

	function setCookie ( name, value ) {
		document.cookie = name + "=" + escape(value);
	}
	
	function tossCookie ( name ) {
		if ( getCookie(name) ) {
			document.cookie = name + "= null; expires=Thu, 01-Jan-2001 00:00:01 GMT";
		}
	}
	
	/***
	* Functions for tracking which # question was answered.
	*/
	function resetQuestionCount () {
		m_numberOfQuestionBeingAnswered = 0;
		m_questionAnsweredToGoogleAnalyticsCode = new Array ();
		m_questionAnsweredToGoogleAnalyticsCode[1] = "PlayGame_Answer1";
		m_questionAnsweredToGoogleAnalyticsCode[5] = "PlayGame_Answer5";
		m_questionAnsweredToGoogleAnalyticsCode[9] = "PlayGame_Answer9";
	}
	
	function anotherQuestionWasAnswered () {
		m_numberOfQuestionBeingAnswered += 1;
		if ( m_questionAnsweredToGoogleAnalyticsCode != null && 
			 m_questionAnsweredToGoogleAnalyticsCode [m_numberOfQuestionBeingAnswered] ) 
		{			
			trackUserAction( m_questionAnsweredToGoogleAnalyticsCode [m_numberOfQuestionBeingAnswered] );
		}
	}


   function trackUserAction ( action ) 
   {
		/**
		* Only call the tracking function if it has been defined in the HTM/JSP page for the game.
		*/
	   var trackingFn = window ["trackFlashAction"] ;
	   if ( trackingFn )
	   {
		   trackingFn ( action ) ;
	   }
   } 
