//This javascript file contains score submission logic and feedform presentation for Facebook Connect enabled games


//================================================================================
//GLOBAL VARIABLES
//================================================================================

//function initGlobalVariables()
//{
	//var gameScore = 0;
	//var previousHighScore = score;
	//var previousLifetimeScore = score_lifetime;
	var scoreSubmissionInterval = 1; 
	//in minutes NOTE: Currently set to only 5 seconds for testing purposes. We will either boost teh loop to 'N' minutes or remove the loop altogether and only update the score upon the conclusion of the game.
	//var gameScore = 0; //numeric game score
	var rawScore = ""; //stores the XML string that game score broadcast spits out
	var baseScoreSubmitURL = "report_score.php?fb_id="; 
	var startGameURL = "http://fb.popcap.com/online-games/zuma/start_game.php";
	//alert("init fired");
	var starMedalScale = [15000,25000,50000,75000,100000,115000,130000]; //Slantz doesn't think we can reach 150 - checking with msft. Vechey wants less than 25
	//alert("intit 2 fired");
	var lifetimeMedalScale = [1000000,5000000,10000000]; //We may add more as time goes on - and the code is set up to handle this!
	var xmlhttp = new XMLHttpRequest();
	var callToActionURL = "http://fb.popcap.com/online-games/zuma/" //to make it easier to swap the call to action link for feed forms(when we switch from test to live)
	//var baseImageURL = "http://golfballsbygrace.com/i/" //to make it easier to swap the images for the feed forms(when we switch from test to live)
	var baseImageURL = "http://fb.popcap.com/online-games/images/" //to make it easier to swap the images for the feed forms(when we switch from test to live)

	var medalFeedID = 114324295714;
	//114324295714 - this is the correct generic template without a typo.
	//112598050714 - this is the generic template bundle on LIVE - THIS ONE HAS THE TYPO - IT'S BAD
	//78374077214 - this is the generic medal feed on TEST
	
	var smackFeedID = 114324295714; 
	//114324295714 - this is the correct generic template without a typo.
	//112598050714 - this is the generic template bundle on LIVE - THIS ONE HAS THE TYPO - IT'S BAD
	//84438717214 - this is the generic smack on TEST - note, it's exactly the same as 84438717214. So until we have specific iCID's in the Call To Action, we will use a single generic design template.
	//78728247214 - this was the custom smack we used to use on TEST
	
	var shareFeedID = 114324295714;
	//114324295714 - this is the correct generic template without a typo.
	//112598050714 - this is the generic template bundle on LIVE - THIS ONE HAS THE TYPO - IT'S BAD
	//78374077214 - this is the generic shareFeed feed on TEST	- it's the same generic design used by medalFeedID
	
	//var userID; //this is now assigned in index.xsl
	//var profilePicURL = "http://golfballsbygrace.com/i/userpic.jpg"
//}

//================================================================================
//SCORE MANIPULATION
//================================================================================

//Strip the score from the game score broadcast XML
function updateAndStripScore(strScore)
{
	gameScore = parseInt(strScore.slice(strScore.indexOf("<score>")+7,strScore.indexOf("</score>")));
	return gameScore;
}

//Submit score via  post
function pushScoreToDB(gameScore)
{
	midGameScorePushURL = baseScoreSubmitURL + fb_id + "&score=" + gameScore;
	$.post(midGameScorePushURL);
	return null
}

//Check to see if it's a high score and submit if it is 
function submitScore (numScore)
{
	if (numScore > previousHighScore) 
	{
		pushScoreToDB(numScore);
		// Reload the leaderboard
		reloadAndReset("myFirstCarousel");
	}
}

//submit final score with game over flag set (no verification of score being higher than previous)
function submitFinalScore (numScore)
{
	endGameScorePushURL = baseScoreSubmitURL + fb_id + "&score=" + gameScore + "&game_end=true";
	$.post(endGameScorePushURL);
	return null;
}

function currentHighestScore()
{
	var highestScore;
	if (gameScore > previousHighScore)
	{
		highestScore = gameScore;
	}
	else
	{
		highestScore = previousHighScore;
	}
	return highestScore;
}

function addCommasToScore(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

//Loop to grab score broadcast every N minutes and submit - for test purposes only - score submission will happen at the end of the game
/*
function scoreCheck()
{
	submitScore(updateAndStripScore(rawScore));
	trophyCaseUpdate(starMedalScale,gameScore, previousHighScore, previousLifetimeScore);
	reloadAndReset("myFirstCarousel");
	timeout = setTimeout("scoreCheck()",(10000*scoreSubmissionInterval));
}

//Ends the submitScore loop - for test purposes only - score submission will happen at the end of the game
function stopScoreCheck()
{
	clearTimeout(timeout);
}
*/

//================================================================================
//EVENTS
//================================================================================

//Do necessary things at start of the game. (called from <game>.js start game event)
function startGame()
{
	if (loggedInState) 
	{
		//userID = parseInt(fb_id); //Moved to document ready event in index.xsl
		//trophyCaseUpdate(starMedalScale,gameScore, previousHighScore, previousLifetimeScore); //make sure Weekly Medals Trophy Case is up to date
		$.post(startGameURL);
		//scoreCheck(); //start temporary looploop
	}
}

//Do the necessary thing at each GameBreak (this function is called in Zuma.js)

function breakGame()
{
	if (loggedInState) 
	{
		//alert("Submit Score");
		submitScore(updateAndStripScore(rawScore));
		//trophyCaseUpdate(starMedalScale,gameScore, previousHighScore, previousLifetimeScore); //make sure Weekly Medals Trophy Case is up to date
		
		//alert("2 second delay, then Update Medals");
		//alert("Reload Carousel");
		reloadAndReset('myFirstCarousel');
		
		$(this).delay(2000,function(){
			trophyCaseUpdate(starMedalScale,gameScore, previousHighScore, previousLifetimeScore); //make sure Weekly Medals Trophy Case is up to date
	  	});
	}
}

//Submit high score and feedform at the end of game if warranted (called from <game>.js gameover event)
function endGame()
{
	if (loggedInState) 
	{
		//stopScoreCheck(); //stop temporary timer
		//alert("Submit Final Score");
		//$(this).delay(6000,function(){
			submitFinalScore(updateAndStripScore(rawScore));
	  	//});
		
		//alert("Launch Form Feeds");
		if (newMedalCheck(lifetimeMedalScale, previousLifetimeScore + gameScore, previousLifetimeScore))
		{
		 	lifetimeStarMedalFeed((newMedalCheck(lifetimeMedalScale, previousLifetimeScore + gameScore, previousLifetimeScore))/1000000);
		} 		
		else if 
		(newMedalCheck(starMedalScale, gameScore, previousHighScore))
		{
			starMedalFeed((newMedalCheck(starMedalScale, gameScore, previousHighScore))/1000);
		}
		//trophyCaseUpdate(starMedalScale,gameScore, previousHighScore, previousLifetimeScore + gameScore);
		refreshLifetimeScore(previousLifetimeScore + gameScore);

		//alert("Update Medals");
		trophyCaseUpdate(starMedalScale,gameScore, previousHighScore, previousLifetimeScore + gameScore); //make sure Weekly Medals Trophy Case is up to date

		//alert("Reload Carousel");
		reloadAndReset('myFirstCarousel');
		
		//superHack second delayed call to carousel to MAKE it refresh
		$(this).delay(2000,function(){
			reloadAndReset('myFirstCarousel'); 
	  	});
	}
}


//================================================================================
//RIDALPHY
//================================================================================

//Did the player earn a medal?
function newMedalCheck(mMedalScale, mScore, mPreviousScore)
{
	if (mScore > mPreviousScore && mScore > mMedalScale[0])
	{
		for (iNew = 1; iNew <= mMedalScale.length; iNew++)
		{
			if (mScore < mMedalScale[iNew] && mScore >= mMedalScale[iNew-1] && mPreviousScore < mMedalScale[iNew-1])
			{
				return mMedalScale[iNew-1];
			}
			else if (mScore >= mMedalScale[mMedalScale.length] && mPreviousScore < mMedalScale[mMedalScale.length])
			{
				return mMedalScale[mMedalScale.length];
			}
		}
		return 0;
	}
	else return 0;
}

//Update the trophy case to the latest and greates - at onload and at game end?
function trophyCaseUpdate(tMedalScale, tScore, tPreviousScore, tLatestLifetimeScore)
{
	var highestScore
	
	//Determine highest score
	if (tScore >= tPreviousScore)
	{
		highestScore = tScore;
	}
	else
	{
		highestScore = tPreviousScore;
	}
	
	//Weekly Medals - work way up the array colorizing medals until the highest medal is 'lit'
	for (iWeek=0; iWeek <= tMedalScale.length; iWeek++)
	{
		if (highestScore >= tMedalScale[iWeek])
		{
			swapMedal(tMedalScale[iWeek]/1000);
		}
		//else return;
	}

	//Lifetime Medals - work way up the array colorizing medals until the highest medal is 'lit'
	for (iLife=0; iLife <= lifetimeMedalScale.length; iLife++)
	{
		if (tLatestLifetimeScore >= lifetimeMedalScale[iLife])
		{
			swapLifetimeMedal(lifetimeMedalScale[iLife]/1000000);
		}
		else return;
	}
}

//================================================================================
//FEEDFORMS
//================================================================================

//Ridalphy feeds
function starMedalFeed(starMedalNumber)
{
	var starTrophyText = starMedalNumber + "K Medal";	
	var starMessageText = "This has earned <fb:pronoun uid='" + userID + "' objective ='true' useyou='false'></fb:pronoun> a " + starTrophyText +". <a href = callToActionURL>Zuma</a> is available on PopCap.com.";
	launchMedalFeedForm(starMedalNumber, starTrophyText, starMessageText);	
}

function lifetimeStarMedalFeed(lifetimeMedalNumber)
{
	var lifetimeTrophyText = lifetimeMedalNumber + " MILLION points lifetime medal";
	var lifetimeMessageText = "This has earned <fb:pronoun uid='" + userID + "' objective ='true' useyou='false'></fb:pronoun> a " + lifetimeTrophyText + ". <a href = callToActionURL>Zuma</a> is available on PopCap.com.";
	launchLifetimeMedalFeedForm(lifetimeMedalNumber, lifetimeTrophyText, lifetimeMessageText);	
}

function launchMedalFeedForm(medalNumber, trophyText, messageText)
{
	scrollTo(0,0); // scroll to top of page
	FB_RequireFeatures(["Connect"], function()
	{
			FB.Facebook.init(facebookAppKey, "xd_receiver.htm");
		
			//Our customization
			var template_data = 
			{
				"1line":"just earned a " + trophyText + "in <a href = " + callToActionURL + ">Zuma</a>.",
				"sstitletext":"received a high score of " + addCommasToScore(currentHighestScore()) + " in <a href = " + callToActionURL + ">Zuma</a>",
				"ssbodytext":messageText,
				"images":
				[
				 {"src":baseImageURL + "BAPLeft-Medal2.gif", "href":callToActionURL},
				 {"src":baseImageURL + "BAP" + medalNumber + "k-Medal.gif", "href":callToActionURL},
				 {"src":baseImageURL + "BAPRight-Medal2.gif", "href":callToActionURL}				 
				 
				 
				 //{"src":baseImageURL + "zuma-medal-" + medalNumber + "-color.png", "href":callToActionURL},
				 //{"src":baseImageURL + "zuma-medal-slot2.gif", "href":callToActionURL},
				 //{"src":baseImageURL + "zuma-medal-slot3.gif", "href":callToActionURL},
				 //{"src":baseImageURL + "zuma-medal-slot4.gif", "href":callToActionURL},
				 //{"src":baseImageURL + "zuma-medal-slot5a.gif", "href":callToActionURL}
				]
			};
			
			var user_message= null; //{value:"earned a " + trophyText + " in Zuma!"};
			
			FB.ensureInit(function() 
			{
				FB.Connect.showFeedDialog(medalFeedID,template_data,null,null,null,FB.RequireConnect.Require,null,"Show off your Zuma skills!",user_message);
			});
	});
}

function launchLifetimeMedalFeedForm(medalNumber, trophyText, messageText)
{
	scrollTo(0,0); // scroll to top of page
	FB_RequireFeatures(["Connect"], function()
	{
		//FB.ensureInit(function() 
		//{
			FB.Facebook.init(facebookAppKey, "xd_receiver.htm");
		
			//Our customization
			var template_data = 
			{
				"1line":"just earned a " + trophyText + "in <a href = callToActionURL>Zuma</a>.",
				"sstitletext":"received a high score of " + addCommasToScore(currentHighestScore()) + " in <a href = callToActionURL>Zuma</a>",
				"ssbodytext":messageText,
				"images":
				[
				 {"src":baseImageURL + "zuma-medal-" + medalNumber + "million-color.png", "href":callToActionURL},
				 {"src":baseImageURL + "zuma-medal-slot2.gif", "href":callToActionURL},
				 {"src":baseImageURL + "zuma-medal-slot3.gif", "href":callToActionURL},
				 {"src":baseImageURL + "zuma-medal-slot4.gif", "href":callToActionURL},
				 {"src":baseImageURL + "pclogo.gif", "href":callToActionURL}
				]
			};
			
			var user_message= null; //{value:"earned a " + trophyText + " in Zuma!"};
			
			FB.ensureInit(function() 
			{
				FB.Connect.showFeedDialog(medalFeedID,template_data,null,null,null,FB.RequireConnect.Require,null,"Show off your Zuma skills!",user_message);
			});
		//});	
	});
}

//Other user submitted feeds
function launchSmackTalkFeedForm (targetID, profilePicURL) //Needs to be a seperate function because FB doesn't allow a variable desitnation URL.
{
	scrollTo(0,0); // scroll to top of page
	FB_RequireFeatures(["Connect"], function()
	{
		FB.Facebook.init(facebookAppKey, "xd_receiver.htm");

		//Our customization
		var formID = smackFeedID;
		var victimID = targetID.toString();		
		var template_data = 
		{
			"1line":"said to <fb:name uid='" + victimID + "' capitalize='true' firstnameonly ='true' />: you have been outdone.",
			"sstitletext":"has clearly superior Zuma skills",
			"ssbodytext":"Let it be known on this day that <fb:name uid='" + userID + "' firstnameonly ='true' useyou='false' /> is a much better Zuma player than you.",
			"images":
			[
				{"src":baseImageURL + "smack-slot1.gif", "href":callToActionURL},
				{"src":baseImageURL + "smack-slot2.gif", "href":callToActionURL},
				{"src":baseImageURL + "smack-slot3.gif", "href":callToActionURL},
				{"src":baseImageURL + "smack-slot4.gif", "href":callToActionURL},
				{"src":baseImageURL + "pclogo.gif", "href":callToActionURL}	
			]
		};
		var body_general = null; //handled in template_data
		var story_size = null; //deprecated. no longer used.
		var require_connect = FB.RequireConnect.Require;
		var callback = null;
		var user_message_prompt = "Tell 'em how much better you are..."; 
		var user_message = null; //{value: "I just leap-frogged you with my awesome score."}; 
		FB.ensureInit(function() 
		{
			FB.Connect.showFeedDialog(formID, template_data, victimID, body_general, story_size, require_connect, callback, user_message_prompt, user_message);
		});
	});
}

function launchShareFeedForm()
{
	scrollTo(0,0);
	//FB.Connect.requireSession();
    //FB.Facebook.get_sessionState().waitUntilReady(function()
	//{													   
		FB_RequireFeatures(["Connect"], function()
		{
			FB.Facebook.init(facebookAppKey, "xd_receiver.htm");
	
			//Our customization
			var formID = shareFeedID;
			var template_data = 
			{
				"1line":"is inviting you to check out Zuma!",
				"sstitletext":" asks, 'Why not take a break-cation?'",
				"ssbodytext":"Take a trip to Zuma on PopCap.com. Survive the ancient temples of Zuma, the critically acclaimed action-puzzler from PopCap! Fire magical balls from your stone frog idol to make matches of three or more and clear the deadly chain before it reaches the golden skull.",
				"images":
				[
					{"src":baseImageURL + "BAPLeft-Share.gif", "href":callToActionURL},
					{"src":baseImageURL + "BAPCenter-Share.gif", "href":callToActionURL},
					{"src":baseImageURL + "BAPRight-Share.gif", "href":callToActionURL}					
					
					
					//{"src":baseImageURL + "share-slot1.jpg", "href":callToActionURL},
					//{"src":baseImageURL + "share-slot2.jpg", "href":callToActionURL},
					//{"src":baseImageURL + "share-slot3.jpg", "href":callToActionURL},
					//{"src":baseImageURL + "share-slot4.jpg", "href":callToActionURL},
					//{"src":baseImageURL + "share-slot5.jpg", "href":callToActionURL}				
				]
			};
			var body_general = null; //handled in template_data
			var victimID = null;
			var story_size = null; //deprecated. no longer used.
			var require_connect = FB.RequireConnect.doNotRequire;
			var callback = null;
			var user_message_prompt = "Invite your friends to play Zuma"; 
			var user_message = null; //{value: "is inviting you to check out Zuma!"}; 
			FB.ensureInit(function() 
			{
				FB.Connect.showFeedDialog(formID, template_data, victimID, body_general, story_size, require_connect, callback, user_message_prompt, user_message);
			});
		});
	//});
}
