// These functions create the ad layer.

var popcap_in_focus          = true;
var popcap_time_last_ad      = (new Date()).getTime(); 
var popcap_timer             = null;
var popcap_ad_countdown      = 0;
var popcap_ad_countdown_view = false; //CUSTOM: allows ad iframe onload event to set 'true' to view countown display via WriteAdText()
var popcap_active_element    = null; //CUSTOM: allows focus handling of window and ad iframe for firefox

//CUSTOM: Provide default integrated ads
if (!popcap_integrated_preroll) var popcap_integrated_preroll = '/webgames/preroll.html';
if (!popcap_integrated_midroll) var popcap_integrated_midroll = '/webgames/mid.html';
if (!popcap_integrated_postroll) var popcap_integrated_postroll = '/webgames/postroll.html';


// Utility
function PopcapSetFocusEvents()
{
	//optional child iframe name argument (ad iframe id/name is 'spot')
	var child = (arguments.length > 0) ? arguments[0] : false;

	//set active element to the main window.top document
	//needed by firefox to compare against current document.activeElement
	popcap_active_element = document.activeElement;

	if (popcap_isIE) {
		if (child) {
			window.frames[child].document.onfocusout = function() { PopcapOnBlur(); }
			window.frames[child].document.onfocusin = function() { PopcapOnFocus(); }
		}
		else {
			document.onfocusout = function() { PopcapOnBlur(); }
			document.onfocusin = function() { PopcapOnFocus(); }
		}
	}
	else {
		if (child) {
			window.frames[child].onblur = function() { PopcapOnBlur(); }
			window.frames[child].onfocus = function() { PopcapOnFocus(); }
		}
		else {
			window.onblur = function() { PopcapOnBlur(); }
			window.onfocus = function() { PopcapOnFocus(); }
		}
	}
}

function PopcapOnFocus()
{
	popcap_in_focus = true;
	//DEBUG: $("#content").css("border", "solid 3px green");
}

function PopcapOnBlur()
{
	if (popcap_active_element != document.activeElement) {
		popcap_active_element = document.activeElement;
		//DEBUG: $("#content").css("border-top", "solid 3px black");
		return;
	}
	popcap_in_focus = false;
	//DEBUG: $("#content").css("border", "solid 3px red");
	
	if (popcap_breakcount != 0) {
		try {
			popcap_countdown_message.style.visibility = 'hidden';
		}
		catch (e) {}
	}
}

// Writes placeholder text into the ad container if ads are not integrated.
function WriteAdText(forceCountdownDisplay)
{
	//CUSTOM: adapt WriteAdText for popcap_integrated_ad pre-roll countdown display
	//NOTE: ad iframe requires onload="parent.popcap_countdown_viewable=true;" to activate
	//try/catch assists safari with early iframe error
	try 
	{
		popcap_countdown_message = window.frames['spot'].document.getElementById('countdown_message');
		popcap_countdown_number = window.frames['spot'].document.getElementById('countdown_number');
		popcap_countdown_game = window.frames['spot'].document.getElementById('countdown_game');
	}
	catch (e) {}
	if ((popcap_ad_countdown_view || popcap_runPreroll) && popcap_ad_countdown > 0 && (popcap_in_focus || forceCountdownDisplay))
	{
		//countdown_message.style.display = 'block';
		try
		{
			popcap_countdown_game.innerHTML = popcap_display_name;
			popcap_countdown_message.style.visibility = 'visible';
			if (popcap_ad_countdown > 1) popcap_countdown_number.innerHTML = popcap_ad_countdown;
			if (popcap_ad_countdown < 1) popcap_countdown_message.style.visibility = 'hidden';
		}
		catch (e) {}
	}

	/*ORIGINAL
	var ad = document.getElementById('adcontainer');
	
	ad.innerHTML = '';
	ad.innerHTML = 'This is an in-game ad.<br>\n';
	
	if (popcap_ad_countdown>0 && (popcap_in_focus || forceCountdownDisplay))
		ad.innerHTML += 'It will automatically end in ' + popcap_ad_countdown + ' seconds.<br>\n';
  
	ad.innerHTML +='<br>\n';
	ad.innerHTML += '<a href="javascript:void(0)" onclick="javascript:window.open(\'http://www.popcap.com\');">Click here to see ad details.</a><br><br>\n';
	
	if (!popcap_runPreroll) // Prevent user from forcing resume on a preroll
		ad.innerHTML += '<a href="javascript:void(0)" onclick="javascript:PopcapEndad(true);">Click here to resume game.</a>\n';
  
	if (popcap_ad_countdown>0 && (popcap_in_focus || forceCountdownDisplay))
		ad.innerHTML += 'It will automatically end in ' + popcap_ad_countdown + ' seconds.<br>\n';
	*/
}

// Sets up the ad container.
function MakeAd()
{
	if (popcap_external_ads)
	{
		var ad_tag = '';
		var game_top = '10px';
		var game_left = '10px';

		ad_tag += '<style type="text/css">\n';

		ad_tag += '#adcontainer {\n';
		ad_tag += 'position: absolute;\n';
		ad_tag += 'top: ' + game_top + ';\n';
		ad_tag += 'left: ' + game_left + ';\n';
		ad_tag += 'z-index: 1;\n';	
		ad_tag += 'visibility: hidden;\n';		
		ad_tag += 'display: none;\n';
		ad_tag += 'width: ' + popcap_app_width + ';\n';
		ad_tag += 'height: ' + popcap_app_height + ';\n';
		ad_tag += 'border-collapse: collapse;\n';
		ad_tag += 'border: none;\n';
		ad_tag += 'margin: none;\n';
		ad_tag += 'padding: none;\n';
		ad_tag += 'color: #ffffff;\n';
		ad_tag += 'background: none transparent;\n';
		ad_tag += '}\n';

		ad_tag += '</style>\n\n';
		
		//CUSTOM: div replaces table
		ad_tag += '<div id="adcontainer">\n';
		
		if (popcap_integrated_ads)
		{
			ad_tag += '<iframe id="spot" name="spot" onload="parent.popcap_ad_countdown_view=true;" width="' + popcap_app_width + '" height="' + popcap_app_height + '" src="';
			
			//CUSTOM: allowtransparency for ie iframe, fix iframe syntax
			ad_tag += '" scrolling="no" frameborder="0" border="0" marginheight="0" marginwidth="0" oncontextmenu="return false" allowtransparency="true"></iframe>';			
		}
		
		ad_tag += '</div>';

		document.write(ad_tag);
			
		//CUSTOM: variables for preroll URIs, location.replace() to avoid browser history
		if (popcap_runPreroll)
			frames['spot'].location.replace(popcap_integrated_preroll);
		else
			frames['spot'].location.replace(popcap_integrated_midroll);

	}
}

// Hides the ad and resumes the game. Called when the ad display timer has expired, or when the user clicks to continue.
function PopcapEndad(force)
{
	//if window is not in focus don't end ad... user must manually click to restart game
	if (popcap_in_focus || force || popcap_breakcount == 0)
	{
		if (!popcap_runPreroll)
		{
			//unpause the game
			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; // Always set to false in case a post-roll was ended			
		}
		
		//CUSTOM: 
		//firefox writes tags after preroll runs to avoid activex/javascript communication issues
		if (popcap_runPreroll 
				&& (!popcap_isIE 
					|| (popcap_isJava 
						&& popcap_isIE 
						&& navigator.userAgent.indexOf('MSIE 7') != -1))) {
			thisObject('gamediv').innerHTML += popcap_tag;
		}
		
		//show the game
		thisObject('gamediv').style.visibility = 'visible';
			
		//hide the ad
		thisObject('adcontainer').style.visibility = 'hidden';
		
		//location.replace() to avoid browser history
		if (popcap_integrated_ads) frames['spot'].location.replace('about:blank');
		
		thisObject('adcontainer').style.display = 'none';
		
		clearTimeout(popcap_timer);
		
		// make sure focus is on the game now
		thisObject('GameObject').focus();
		//NOTE: should this be conditional?
		//if (popcap_isIE) thisObject('GameObject').focus();
		
		//CUSTOM:
		//ie needs a little help with the PopcapSetFocusEvents()
		if (popcap_isIE && popcap_isAX) {
			PopcapOnFocus();
		}
	}
}

// Timer for ad display.
function PopcapAdTimer(forceCountdownDisplay)
{
	if (popcap_ad_countdown > 0) popcap_ad_countdown--;
	
	//CUSTOM: exceptions to avoid ad auto timeout due to certain browser focus tracking issues
	//FOR: ie7 win java, ff2 win java, ff3 win ax/flash/java, ff2 mac flash/java
	if (popcap_isJava 
			|| ($.platform.win 
				&& $.browser.mozilla 
				&& $.browser.version >= 1.9) //ff3
			|| ($.platform.mac
				&& $.browser.mozilla)) {
		popcap_ad_countdown_view = false;
	}
	
	//CUSTOM: adapt WriteAdText for popcap_integrated_ad countdown display
	if (popcap_integrated_ads) WriteAdText(forceCountdownDisplay);
	//ORIGINAL: 
	//if (!popcap_integrated_ads) WriteAdText(forceCountdownDisplay);
	
	if (popcap_ad_countdown == 0)
	{
		if ((popcap_ad_countdown_view || popcap_runPreroll) 
				&& (popcap_in_focus || popcap_breakcount == 0)) 
		{
			PopcapEndad(false);
		}
		if (popcap_runPreroll) 
		{
			popcap_runPreroll = false;
			//used to record the end of the preroll in Omniture here - see PLC-2954
		}
		//used to record webgame session readiness in Omniture here - see PLC-2954
	}
	else popcap_timer = setTimeout('PopcapAdTimer(false)',1000); 
}

// Pauses and hides the game, displays an ad.
function PopcapAdGameBreak()
{
	var current_date = new Date(); 
	var current_time = current_date.getTime(); 
	var ad_interval = current_time - popcap_time_last_ad;
	
	if (ad_interval > popcap_ad_threshold*1000) 
	{
		get_omniture_interstitial();
		
		if (popcap_integrated_ads) 
		{
			//CUSTOM: variables for preroll URIs, location.replace() to avoid browser history
			if (popcap_isGameOver)
				frames['spot'].location.replace(popcap_integrated_postroll);
			else
				frames['spot'].location.replace(popcap_integrated_midroll);
		}
		
		// Zone automatically pauses the game upon a GameBreak; game only needs to be paused manually if using the PopCap API.
		if (!(popcap_enableZone || popcap_isZoneAPIonly) || popcap_isPCAPIonly)
		{		
			if (popcap_isFlash) 
				thisObject('GameObject').TCallLabel('/','PauseOn');
			else 
				thisObject('GameObject').PopcapNotify('pc_pause','1');
		}

		thisObject('gamediv').style.visibility = 'hidden';
	
		//show the ad
		thisObject('adcontainer').style.visibility = 'visible';
		thisObject('adcontainer').style.display = 'block';
		
		//use setTimeout to end ad (maybe also be overriden by ad itself)
		if (popcap_ad_length > 0)
		{
			popcap_ad_countdown = popcap_ad_length+1;
			PopcapAdTimer(true);
		}
		
	
		//store the time this ad was displayed to test against the next threshold
		popcap_time_last_ad = current_time;
	}
	else
	{
		//kickstart Zone API pause
		if ((popcap_enableZone || popcap_isZoneAPIonly) || !popcap_isPCAPIonly)
		{	
			if (popcap_isGameOver) {
				if (popcap_isFlash) 
					thisObject('GameObject').TCallLabel('/','GameMenu');
				else 
					thisObject('GameObject').PopcapNotify('GameMenu','');
				
				//PopcapEndad() will not be run so reset game over state
				popcap_isGameOver = false;
			}
			else {
				if (popcap_isFlash) 
					thisObject('GameObject').TCallLabel('/','GameContinue');
				else 
					thisObject('GameObject').PopcapNotify('GameContinue','');
			}
		}
		
	}
}

// Runs a preroll ad
function PopcapPreroll()
{
	var current_date = new Date(); 
	var current_time = current_date.getTime();
	
	if (popcap_isJava) {
		get_omniture_tech('Java',true);
	}
	else if (popcap_isAX) {
		get_omniture_tech('ActiveX',true);
	}
	else if (popcap_isFlash) {
		get_omniture_tech('Flash',true);
	}
	
	 
	//show the ad
	thisObject('adcontainer').style.visibility = 'visible';
	thisObject('adcontainer').style.display = 'block';

	//use setTimeout to end ad (maybe also be overriden by ad itself)
	if (popcap_ad_length > 0)
	{
	    //used to record the start of the preroll in Omniture here - see PLC-2954
		popcap_ad_countdown = popcap_ad_length+1;
		PopcapAdTimer(true);
	}

	//store the time this ad was displayed to test against the next threshold
	popcap_time_last_ad = current_time;
}

// Checks if a preroll can be run on Firefox or IE; don't run it if the plugin's not installed!
function CanRunPreroll()
{
	if (popcap_runPreroll)
	{
		if (!popcap_isIE && popcap_isAX)
		{
			try
			{
				var pluginType = 'application/x-popcaploader;version=1.0.0.1';
				mimetype = navigator.mimeTypes[pluginType];
				
				if (!(mimetype && mimetype.enabledPlugin && mimetype.type==pluginType)) 
				{
					return false;
				}
				else 
				{
					return true;
				}
			}
			catch (e)
			{
				return false;
			}
		}
		else if (popcap_isIE && popcap_isAX)
		{
			try
			{
				var controlType = new ActiveXObject("PopCapLoader.PopCapLoaderCtrl2"); 
				if (!controlType)
				{
					return false;
				}
				else 
				{
					//CUSTOM: ie control is installed, hide ie install dialog
					$("#plugin_dialog_ie").hide(); 
					scroll(0,0);
					return true;
				}
			}
			catch (e)
			{
				return false;
			}
		}
		else if (!popcap_isIE && popcap_isFlash)
		{
			if ($.plugdetect('flash'))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else if (popcap_isIE && popcap_isFlash)
		{
			try
			{
				var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.9');
				//CUSTOM: ie control is installed, hide ie install dialog
				$("#plugin_dialog_ie").hide(); 
				scroll(0,0);
				return true;
			}
			catch (e)
			{
				return false;
			}
		}
		else if (!popcap_isIE && popcap_isJava)
		{
			if ($.plugdetect('java') 
					|| $.browser.safari 
					|| ($.browser.opera && navigator.javaEnabled())) {
				return true;
			}
			else return false;
		}
		else if (popcap_isIE && popcap_isJava)
		{
			try 
			{
				//var axo = new ActiveXObject('JavaWebStart.isInstalled');
				if (PluginDetect.isMinVersion('Java', '1.2') != -1)
				{
					$("#plugin_dialog_java").hide();
					scroll(0,0);
					return true;
				}
				else
				{
					//no java detection for win98/ME users, assume they have java
					if (navigator.userAgent.indexOf('Windows 98') != -1) return true;
					else return false;
				}
			}
			catch (e)
			{
				//no java detection for win98/ME users, assume they have java
				if (navigator.userAgent.indexOf('Windows 98') != -1) return true;
				else return false;
			}
		}
		else return true;
		//NOTE: should this return false by default?
		//else return false;
	}
	else return false;
}

MakeAd();

if (CanRunPreroll()) PopcapPreroll();
else 
{
	if (popcap_isJava) {
		get_omniture_tech('Java',false);
	}
	else if (popcap_isAX) {
		get_omniture_tech('ActiveX',false);
	}
	else if (popcap_isFlash) {
		get_omniture_tech('Flash',false);
	}
	//CUSTOM: preroll fails due to control/plugin so show game
	if (popcap_runPreroll && !popcap_isIE && popcap_isFlash) {
		//write tags after preroll fails to trigger install prompts
		thisObject('gamediv').innerHTML += popcap_tag;
	}
	else if (popcap_runPreroll && popcap_isJava) {
		//write tags and show the game, java may be installed despite detection failure
		if (!popcap_isIE || (popcap_isIE && navigator.userAgent.indexOf('MSIE 7') == -1)) thisObject('gamediv').innerHTML += popcap_tag;
		thisObject('gamediv').style.visibility = "visible";
	}
}

