//
// game.js -- FOCAL support code
//
//
// Main page must call FOCAL_Load(name, id) after the page has loaded.
// The two parameters are:
//
// 	 name		- DOM name of the flash game object
//	 id			- game identifier (to pass to GetCookie() for options; see Options.js)
//	 scoreURL	- URL to page that gets name from user for score

pageLoaded = false;

function FOCAL_Load(name, id, scoreURL)
{
	gameName = name;
	gameOpt = id;
	gamePostURL = scoreURL;

	pageLoaded = true;
}

function IsPageLoaded()
{
	return pageLoaded;
}

// Unnecessarily general for scaffolding and largely untested.
// (works in the browsers I use for development which is just fine)
// Should be replaced by jquery or similar.

function getGame()
{
	if (window.document[gameName])
	{
		return window.document[gameName];
	}
	if (navigator.appName.indexOf('Microsoft Internet') == -1)
	{
		if (document.embeds && document.embeds[gameName])
		{
			return document.embeds[gameName];
		}
		else
		{
			return document.getElementById(gameName);
		}
	}
}

function FOCAL_Unload()
{
	getGame().SaveGame();
}

function SetFocusOnGame()
{
	getGame().focus();
}

function ClickEmulatorButton(player, keybit)
{
	getGame().ClickEmulatorButton(player, keybit);
}

function DebugNotifyBuildID(buildID)
{
	buildtag = document.getElementById('build');
	if (buildtag)
	{
		buildtag.innerHTML = buildID;
	}
}

function NotifyLightState(name, state)
{
	var light = document.getElementById('l_' + name);
	if (light)
	{
		if (name.substr(0, 4) == 'land')
		{
			light.src = 'landsel' + name.substr(4, 1) + (state ? 'lit' : '') + '.png';
		}
		else
		{
			light.src = 'state' + state + '.png';
		}
	}
}

function GetOptions()
{
	return GetCookie(gameOpt);
}

function SetGameOptions(opt)
{
	getGame().SetGameOptions(opt);
}

// Call by game when it finds a saved game at startup.
// You can either:
//		return true to load and continue the saved game
//		return false to defer the decision and then call either:
//			UseSavedGame(true) - load and continue saved game
//			UseSavedGame(false) - ignore the saved game
//			But the callback must occur or the game will not continue.

function NotifySavedGame()
{
	setTimeout('AskUseSaveGame()', 100);
	return false;
}

function AskUseSaveGame()
{
	answer = confirm("Continue saved game?  You will lose your saved game if you do not continue it now.");
	getGame().UseSavedGame(answer);
}

// Re-display the high score board

var last_score_mode = '0';
var rank = '';

function RefreshScoreList()
{
	baseurl = config.score_base_url + gameOpt.toUpperCase() + last_score_mode + '/' + rank;
	window.frames.highscores_iframe.location.replace(baseurl);
	filter_reset();
	SetFocusOnGame();
}

// Stores the scores so that the child window can read them and use them in text

var ScoresForDisplay = [ 0, 0 ];
var ScoresPending = [ false, false ];
var PlayerPosting = 0;
var ScoresSent = [ false, false ];

// Opens a child window to get the name for player 1 or 2

function OpenPostPopup(player)
{
	PlayerPosting = player;
	ScoresSent[player - 1] = false;
	window.frames.highscores_iframe.location.replace(gamePostURL + '?' + player);
}

function NotifyNeedScoreName(player, score)
{
	getGame().ExitFullScreen();

	// If there was a previous window open for this player, close it

	if (PlayerPosting == player)
	{
		PlayerClose(player);
	}

	// Is this a timed score?

	if (score < 0 || gameOpt == 'adv') {
		if (score < 0) score = -score;
		newscore = score.toString();
		while (newscore.length < 8) newscore = '0' + newscore;
		l = newscore.length;
		score = newscore.substr(0, l-6) + ':' + newscore.substr(l-6, 2) + ':' + newscore.substr(l-4, 2) + '.' + newscore.substr(l-2, 2);
		if (score.substr(0, 3) == '00:') score = score.substr(3);
//		if (score.charAt(0) == '0' && (score.charAt(2) == ':' || score.charAt(2) == '.')) score = score.substr(1);
	}

	// Note the new score for the new window

	ScoresForDisplay[player - 1] = score;
	ScoresPending[player - 1] = true;

	// If nobody is being asked for score or score is being replaced, pop up this one.

	if (PlayerPosting == 0)
	{
		OpenPostPopup(player);
	}
	else
	{
	}
}

// Player has entered name, pass on to game for posting and process next player

function GiveScoreName(player, name)
{
	PlayerDone(player);
	id = getGame().GiveScoreName(player, name);
	ScoresSent[player - 1] = true;
}

// player has finished or cancelled, clean up

function PlayerClose(player)
{
	ScoresPending[player - 1] = false;
	PlayerPosting = 0;
}

// After player 1 or 2 is dealt with, see if another window needs to be opened.

function PlayerDone(player)
{

	PlayerClose(player);

	if (ScoresPending[0])
	{
		OpenPostPopup(1);
	}
	else if (ScoresPending[1])
	{
		OpenPostPopup(2);
	} 
}

// Player 1 or 2 cancelled, go to next player

function NotGivingScoreName(player)
{
	rank = '';
	PlayerDone(player);
	if (PlayerPosting == 0) RefreshScoreList();
}

// Score posting success/failure callback.  The result can be:
//
//	io			network error -- retry might get through
//	security	security error -- retry unlikely to succeed
//
// Or it may return what the score posting server said.
//
//	rank:id		number pair indicating position on scoreboard and
//				the score ID
//
//	''			Sometimes an empty string can come back.  If so, a
//				repost might work as seed checking may have been
//				unreasonably slow.

// This function simply shows the raw results.

function NotifyScorePostResult(id, player, score, name, result)
{
	// did we get a rank back?
	i = result.indexOf(':');
	if (i == -1) 
	{
		// submit failed, let the user try again
		ScoresSent[player - 1] = false;
		window.frames.highscores_iframe.ScoreRetry();
		rank = '';
		return;
	}

	// redisplay high score board with new rank
	rank = '?highlight=' + result.substr(i+1);
	if (PlayerPosting == 0) 
	{
		RefreshScoreList();
	}
}

// Notification of game mode change, to update score board

function NotifyScoreModeChange(id) 
{
	id = id - 1;
	if (id < 0) id = 0;
	if (id.toString() == last_score_mode) return;
	last_score_mode = id.toString();
	rank = '';
	RefreshScoreList();
}

//
// Notification stubs for marketing measurements.
//

function NotifyGameStart()
{
}

function NotifyGameEnd(duration)
{
}

