// Handles settings and event handling.

// Editable game settings.
var popcap_upsellURL		= "http://www.popcap.com";	//DigitalBros-specific default Upsell url
var popcap_enableUpsell		= false;		// Set to true if you want the upsell button to open the specified link.
var popcap_internal_ads		= false;		// Set to true if you want to display an ad solely devoted to promoting the download version of the game. True by default for Java games with external ads enabled; ad breaks will not occur reliably otherwise.
var popcap_external_ads		= false;		// Set to true to enable ad breaks.
var popcap_integrated_ads	= false;	// Set to true to enable fully ad-integrated breaks. Do NOT set to true unless ads actually are integrated.
var popcap_runPreroll		= false;	// Set to true to run a preroll ad.
var popcap_ad_length		= 15;		// The amount of time (in seconds) an ad is displayed.
var popcap_ad_threshold		= 0;		// The minimum amount of time (in seconds) that must elapse between ad displays.
var popcap_score_broadcast	= 1000;		// The frequency (in seconds) of score broadcasts.
var popcap_score_report		= false;	// Toggles show/hide of a score display.
var popcap_enableZone		= true;		// Set to true to utilize the Zone API. False enables the PopCap API.
var popcap_debug			= false;	// Toggles show/hide of a text area that displays game events/API calls.

// *** Do NOT modify settings below this line! **********************************************************************************
var popcap_cheats			= false;
var popcap_isIE				= document.all != null; 
var popcap_isFlash			= false;
var popcap_isAX				= false;
var popcap_isPCAPIonly		= false;
var popcap_isZoneAPIonly	= false;
var popcap_params			= new Array();
var popcap_paramvals		= new Array();
var popcap_isGameOver		= false;
var popcap_flashvars		= '';
var popcap_gamename			= '';
var popcap_breakcount		= 0;
var popcap_intAdFrequency	= 0;

// Need to make sure external ads are turned on for fully ad-integrated games.
if (popcap_integrated_ads) popcap_external_ads = true;
	
// Utility
function thisObject(name)
{
	return document.getElementById(name);
}

function ControlAdDisplay()
{
	popcap_breakcount++;
	
	if (popcap_internal_ads && (popcap_gamename == 'peggle' || popcap_gamename == 'BookwormAdventures') && popcap_breakcount % popcap_intAdFrequency == 0)
		thisObject('GameObject').PopcapNotify('GameUpsell','');
	else if (popcap_external_ads) 
		PopcapAdGameBreak();	
	else if (popcap_isFlash) 
		thisObject('GameObject').TCallLabel('/','GameContinue');
	else 
		thisObject('GameObject').PopcapNotify('GameContinue','');
}

// Message conversion: PopCap to Zone
function ApplyZoneTags(method,param)
{
	var details = new Array();
	var tags = new Array();
	var zonemsg = '';
	
	if (!param) param = '';	
	details = param.split(/\s|,|Next/);
	
	return param;
	
	// Dot not Apply Zone Conversation, it doesn't work
	
	/* *** Evaluate Method ***
	if (method == 'pc_launchinstaller') {
		zonemsg = 'CustomEvent <gamedata>DeluxeDownload</gamedata>';
		
		
	} else if (method == 'pc_gameloaded') {
		zonemsg = 'SessionReady <data></data>';
		
		
	} else if (method == 'pc_gamestart') {
		zonemsg = 'GameReady <data>';
		tags = gameready.split(/\s|,/);
		
		if (gameready != '' && tags.length == details.length)
			for (var i=0; i < tags.length; i++)
				zonemsg += '<'+tags[i]+'>'+details[i]+'</'+tags[i]+'>';
		
		zonemsg += '</data>';
		
		
	} else if (method == 'pc_gamebreak') {
		if (param.search(/GameOver/) != -1)
		{
			details = param.split(/\s|,|GameOver/);
			zonemsg = 'GameEnd <gamedata>';
			tags = gamebreak.split(/\s|,/);
			
			if (gamebreak != '' && tags.length == details.length)
				for (var i=0; i < tags.length; i++)
					zonemsg += '<'+tags[i]+'>'+details[i]+'</'+tags[i]+'>';
			
			zonemsg += '</gamedata>';
		}
		else
		{
			zonemsg = 'GameBreak <data>';
			tags = gamebreak.split(/\s|,/);
			
			if (gamebreak != '' && tags.length == details.length)
				for (var i=0; i < tags.length; i++)
					zonemsg += '<'+tags[i]+'>'+details[i]+'</'+tags[i]+'>';
			
			zonemsg += '</data>';
		}
		
		
	} else if (method == 'pc_scorebroadcast') {
		zonemsg = 'ScoreBroadcast <game>';
		tags = scorebroadcast.split(/\s|,/);
		
		if (scorebroadcast != '' && tags.length == details.length)
			for (var i=0; i < tags.length; i++)
				zonemsg += '<'+tags[i]+'>'+details[i]+'</'+tags[i]+'>';
		
		zonemsg += '</game>';
		
		
	} else if (method == 'pc_gameover') {
		zonemsg = 'ScoreSubmit <game>';
		tags = scoresubmit.split(/\s|,/);
		
		if (scoresubmit != '' && tags.length == details.length)
			for (var i=0; i < tags.length; i++)
				zonemsg += '<'+tags[i]+'>'+details[i]+'</'+tags[i]+'>';
		
		zonemsg += '</game>';
		
		
	} else {
		return param;
	} 
	
	return zonemsg;
	*/
}

// Message conversion: Zone to PopCap
function StripZoneTags(param)
{
	var tags = /(\<(\/?[^\>]+)\>)/g;
	
	return param.replace(tags,' ');
}

// Output to debug display
function PopcapDebug(str)
{
	if (thisObject('PopcapDebugBox'))
		thisObject('PopcapDebugBox').value += str + '\n';
}

// Event Handling
function PopCapEventHandler(method,param)
{	
	//alert("PopCapEventHandler(_"+method+"_,"+param+")");
	if (!popcap_enableZone) PopcapDebug(method+' '+param);
		
	if (popcap_enableZone && popcap_isPCAPIonly)
		PopcapDebug(ApplyZoneTags(method,param));

	if (popcap_score_report && !popcap_enableZone)
		Popcap_DisplayScore(method,param);
	
	
	// *** Evaluate Method ***
	
	if (method == 'pc_launchinstaller') {
		if (popcap_enableUpsell) window.open(popcap_upsellURL);
		
		
	} else if (method == 'pc_gamestart') {
		//FUEPS LOGIC (begin)
		if (levelBannerOnGameStart) {
    	levelBanner();
  	}
		//FUEPS LOGIC (end)
		
		
	} else if (method == 'pc_gameloaded') {
		if (popcap_isAX && (popcap_external_ads || popcap_score_report))
			thisObject('GameObject').PopcapNotify('pc_sendgamebreaks','1');
		
		
	} else if (method == 'pc_gamebreak') {
		if (popcap_score_report)
		{
			if (!popcap_enableZone) 
				Popcap_DisplayScore(method,param);
			else if (popcap_enableZone && popcap_isPCAPIonly) 
				Zone_DisplayScore(ApplyZoneTags(method,param));
		}
		
		// Set flag to run postroll
		//if (param.search(/GameOver/i) != -1) popcap_isGameOver = true;
		//if (popcap_external_ads) PopcapAdGameBreak(method);
		
		// FUEPS LOGIC (begin)
		if (levelBannerOnGameBreak) {        	
    	levelBanner();
  	}
		// FUEPS LOGIC (end)
		
		
	} else if (method == 'pc_scorebroadcast') {
		if (popcap_score_report)
		{
			if (!popcap_enableZone) 
				Popcap_DisplayScore(method,param);
			else if (popcap_enableZone && popcap_isPCAPIonly) 
				Zone_DisplayScore(ApplyZoneTags(method,param));
		}
		
		
	} else if (method == 'pc_gameover') {
		if (popcap_score_report)
		{
			if (!popcap_enableZone)
				Popcap_DisplayScore(method,param);
			else if (popcap_enableZone && popcap_isPCAPIonly) 
				Zone_DisplayScore(ApplyZoneTags(method,param));
		}
		
		// FUEPS LOGIC (begin)
		if (freePlaying) {
  		aggiornaInfoDiv(param);
  	} else {
  		//Allora utente registrato e salvo il risultato se e solo se ratio > 0
  		//alert("invio registrazione punti al server");
  		if (jsTokenRatio>0) {
  		  document['FuepsAPI'].setInfo('score',""+param);
  		}
  	}
		// FUEPS LOGIC (end)
		
		
	} 
}

function ZoneEventHandler(method,param) {
	
	//alert("ZoneEventHandler("+method+","+param+")");
	if (popcap_enableZone) PopcapDebug(method+' '+param);
	
	// *** Evaluate Method ***
	if (method == 'CustomEvent') {
		if (popcap_enableUpsell) window.open(popcap_upsellURL);
		
		if (!popcap_enableZone && popcap_isZoneAPIonly)
			PopcapDebug('pc_launchinstaller '+popcap_upsellURL);
			
		if (popcap_isFlash)
		{
			thisObject('GameObject').SetVariable('CustomData',param);
			thisObject('GameObject').TCallLabel('/','CustomReturn');
		}
		else thisObject('GameObject').PopcapNotify('CustomReturn',param);
		
		
	} else if (method == 'SessionReady') {
		//FUEPS LOGIC (begin)
		/*if (levelBannerOnGameBreak) {        	
    	levelBanner();
  	}*/
		//FUEPS LOGIC (end)
	
		if (popcap_isFlash) thisObject('GameObject').TCallLabel('/','SessionStart');
		else thisObject('GameObject').PopcapNotify('SessionStart','');
		
		
	} else if (method == 'GameReady') {
		if (!popcap_enableZone && popcap_isZoneAPIonly)
			PopcapDebug('pc_gamestart' + StripZoneTags(param));
		
		// FUEPS LOGIC (begin)
		/*if (levelBannerOnGameStart) {
    	levelBanner();
  	}*/
		// FUEPS LOGIC (end)
		
		if (popcap_isFlash) thisObject('GameObject').TCallLabel('/','GameStart');
		else thisObject('GameObject').PopcapNotify('GameStart','');
		
		
	} else if (method == 'GameBreak') {
		ControlAdDisplay();
		if (!popcap_enableZone && popcap_isZoneAPIonly)
			PopcapDebug('pc_gamebreak' + StripZoneTags(param));
		
		// FUEPS LOGIC (begin)
		if (levelBannerOnGameBreak) {        	
    	levelBanner();
  	}
		// FUEPS LOGIC (end)
		
		
	} else if (method == 'ScoreBroadcast') {
		// Logic for score display
		if (!popcap_enableZone && popcap_isZoneAPIonly)
		{
			if (popcap_score_report) Popcap_DisplayScore('pc_scorebroadcast',StripZoneTags(param));
			
			PopcapDebug('pc_scorebroadcast' + StripZoneTags(param));
		}
		else if (popcap_score_report) Zone_DisplayScore(param);	
		
		
	} else if (method == 'ScoreSubmit') {
		// Logic for score display
		if (!popcap_enableZone && popcap_isZoneAPIonly)
			PopcapDebug('pc_gameover' + StripZoneTags(param));
		else if (popcap_score_report)
			Zone_DisplayScore('ScoreSubmit'+param);
		
		// FUEPS LOGIC (begin)
		var scoreSubmitted = catchScore(param);
		//alert("score submitted = " + scoreSubmitted);
		if (freePlaying) {
      		aggiornaInfoDiv(scoreSubmitted);
      	} else {
      		//Allora utente registrato e salvo il risultato se e solo se ratio > 0
      		//alert("invio registrazione punti al server");
      		if (jsTokenRatio>0) {
      		  document['FuepsAPI'].setInfo('score',""+scoreSubmitted);
      		}
      	}
		// FUEPS LOGIC (end)
		
		
	} else if (method == 'GameEnd') {
		popcap_isGameOver = true; // Set flag to run postroll
		
		if (popcap_external_ads) PopcapAdGameBreak();
		else if (popcap_isFlash) thisObject('GameObject').TCallLabel('/','GameMenu');
		else if (popcap_gamename == 'astropop') thisObject('GameObject').PopcapNotify('GameStart','');
		else thisObject('GameObject').PopcapNotify('GameMenu','');
		
		// FUEPS LOGIC (begin)
		if (levelBannerOnScore) {
    	endBanner();
  	}
		// FUEPS LOGIC (end)
		
		
	} 
}

// Called by game. The appropriate event handler is chosen according to the API enabled.
// EDIT: ReceiveNotification are implemented on commonGame.js, this is the PopCap way 
function ReceiveNotificationPopCap(method,param) 
{
	//alert("ReceiveNotificationPopCap("+method+","+param+")");
	if (popcap_enableZone)
	{
		if (method.search(/^pc/) != -1 && popcap_isPCAPIonly)
			PopCapEventHandler(method,param);
		else if (method.search(/^pc/) == -1)
			ZoneEventHandler(method,param);
	}
	else
	{
		if (method.search(/^pc/) == -1 && popcap_isZoneAPIonly)
			ZoneEventHandler(method,param);
		else if (method.search(/^pc/) != -1)
			PopCapEventHandler(method,param);
	}
}

// EDIT FUEPS

//unpause the game
function PopCap_unpauseGame() {
	if (popcap_enableZone)			
	{
		if (popcap_isFlash && popcap_isGameOver)
		{
			if (popcap_isPCAPIonly) 
				thisObject('GameObject').TCallLabel('/','PauseOff');
			else
				thisObject('GameObject').TCallLabel('/','GameMenu');
		}
		else if (popcap_isFlash)
		{				
			if (popcap_isPCAPIonly) 
				thisObject('GameObject').TCallLabel('/','PauseOff');
			else
				thisObject('GameObject').TCallLabel('/','GameContinue');
		}
		else if (popcap_isPCAPIonly)
		{
			thisObject('GameObject').PopcapNotify('pc_pause','0');
		}
		else if (popcap_isGameOver)
		{
			if (popcap_gamename == 'astropop') 
				thisObject('GameObject').PopcapNotify('GameStart','');
			else 
				thisObject('GameObject').PopcapNotify('GameMenu','');
		}
		else
			thisObject('GameObject').PopcapNotify('GameContinue','');
	}
	else
	{
		if (popcap_isFlash)
		{
			if (popcap_isZoneAPIonly)
				thisObject('GameObject').TCallLabel('/','GameContinue');
			else
				thisObject('GameObject').TCallLabel('/','PauseOff');
		}
		else if (popcap_isZoneAPIonly)
		{
			if (popcap_isGameOver)
				thisObject('GameObject').PopcapNotify('GameMenu','');
			else
				thisObject('GameObject').PopcapNotify('GameContinue','');
		}
		else
			thisObject('GameObject').PopcapNotify('pc_pause','0');
	}
	
	popcap_isGameOver = false;
}


function PopCap_pauseGame() {
	if (!(popcap_enableZone || popcap_isZoneAPIonly) || popcap_isPCAPIonly)	{		
		if (popcap_isFlash) thisObject('GameObject').TCallLabel('/','PauseOn');
		else thisObject('GameObject').PopcapNotify('pc_pause','1');
	}
}


// This method can overrided (Insaniquarium)
function catchScore(param) {
	return valueTag(param,"score");
}

function valueTag(str,tag) {
	 var pStart = str.indexOf("<"+tag+">");
	 if (pStart == -1)
	  return "";
	 else
	  pStart = pStart + ("<"+tag+">").length;

	 var pEnd = str.indexOf("</"+tag+">",pStart);
	 if (pEnd == -1)
	  return "";

	 return str.substring(pStart,pEnd);
}
