var empOverlay;
var gameOverlay;
var useMerlinDevXML;

glow.ready(function() {
	
	var flashVersion = deconcept.SWFObjectUtil.getPlayerVersion();
	
	if(typeof merlinNoFlash=="undefined") merlinNoFlash=false;
	if(typeof merlinJSDebug=="undefined") merlinJSDebug=false;
	if(typeof merlinJSUseBLQMast=="undefined") merlinJSUseBLQMast=false;
	
	var isMerlinIEBrowser=glow.env.ie < 99 ? true : false;
	var isMerlinGeckoBrowser=glow.env.gecko > 0  ? true : false;
	
	if(!merlinNoFlash && flashVersion['major'] >= 9) {
	
		var path=typeof SWFAddress=="undefined" ? null : SWFAddress.getPath();
		
		if(path == "/images/") window.location="/merlin/pictures/#/pictures/";
		if(typeof useMerlinSWFAddressInitPage=="undefined") useMerlinSWFAddressInitPage=false;
		if(typeof merlin_swfaddress_initpage=="undefined") merlin_swfaddress_initpage=null;
		
		if(useMerlinSWFAddressInitPage && merlin_swfaddress_initpage){
			if(isMerlinGeckoBrowser){
				SWFAddress.setValue(merlin_swfaddress_initpage);		
			}else{
				var newLocation  = merlin_swfaddress_initpage == "games" ? "/merlin/#/" +merlin_swfaddress_initpage +"/" : window.location +"#/" +merlin_swfaddress_initpage +"/";
				if(window.location != newLocation) window.location = newLocation;
			}
		}
		glow.dom.get("body").addClass("flash_9");		
		writeSite();
		
	}else{
	
		glow.dom.get("body").removeClass("merlin_js");
	}
	

	
	var exploreOpenListener;
	var exploreCloseListener;

	
	
	//var exploreFixSelector=merlinJSUseBLQMast ? "#blq-mast" : "#blq-nav-btn a";
	var exploreFixSelector="#blq-nav-btn a , #blq-nav-btn";
		
	if (isMerlinIEBrowser) {
	  	//use interval to check #blq-nav-links display property
	  	setInterval(checkBlqNavLinkIE,500);
	}else{
		//use event listener to detect when explore links are displayed
		addOpenListener();
	}
	



	//check for focus in/out of bbc accesibility links	
	glow.events.addListener('.blq-hide a','focus',function () {		
		glow.dom.get('#main-container-swf').css('margin-top','20px');
	});
	glow.events.addListener('#blq-acc-help a , #blq-mast a','focus',function () {		
		glow.dom.get('#main-container-swf').css('margin-top','0px');
	});
	

	glow.events.addListener('#launchCamelotDefenceGame','click',function () {		
		launchCamelotDefenceGame();
	});	
	
	
	
	
	var gameOverlayInner='<div id="gameOverlay-inner">';
	gameOverlayInner+='<div class="game-header">';
	gameOverlayInner+='<div class="merlin-logo"><a href="/merlin/"><span>Merlin</span></a></div>';
	gameOverlayInner+='<div class="close"><a href="/merlin/"><span>close</span></a></div>';
	gameOverlayInner+='</div>';
	gameOverlayInner+='<div id="gameOverlay-swf"></div>';
	gameOverlayInner+='</div>';
	
	glow.dom.get("#gameOverlay").html(gameOverlayInner);
	
	gameOverlay = new glow.widgets.Overlay("#gameOverlay", {
	  modal: true, closeOnMaskClick: false,focusOnShow: true
	});	
	
	
	
	
	
	
	
	
	
	

	
	//check if the "explore the bbc" links are visible, adjust margin above swf content accordingly	
	function checkBlqNavLinkIE(){
		var display=glow.dom.get('#blq-nav-links').css('display');
		var marginTop=glow.dom.get('#main-container-swf').css('margin-top');		
		if(display=='block' && (marginTop=="0px" || marginTop=="auto") ){
			glow.dom.get('#main-container-swf').css('margin-top','46px');
		}else if(display!='block' && marginTop=="46px"){
			glow.dom.get('#main-container-swf').css('margin-top','0px');	
		}
	}
	
	//add open listener to "explore" button
	function addOpenListener(){
		glow.events.removeListener(exploreOpenListener);
		exploreOpenListener = glow.events.addListener(
				exploreFixSelector,
				'click',
				function (event) {	
					glow.dom.get('#main-container-swf').css('margin-top','46px');
					addCloseListener();										
				}
		);
	}
	//add close listener to "explore" button
	function addCloseListener(){
		glow.events.removeListener(exploreOpenListener);
		exploreCloseListener = glow.events.addListener(
				exploreFixSelector,
				'click',
				function (event) {	
					glow.dom.get('#main-container-swf').css('margin-top','0px');
					if (glow.env.ie > 6) scrollTo(0,0);
					addOpenListener();
				}
		);	
	}
	
	
	
	if(flashVersion['major'] >= 9) {
	
		glow.dom.get('#launch-merlinsmagic , #launch-camelotdefence , #launch-questforthemorteus').addClass('jslink');
		

		glow.events.addListener(
			'#launch-merlinsmagic',
			'click',
			function (event) {	
				document.location='/merlin/#/games/magiceye/';									
			}
		);
		glow.events.addListener(
			'#launch-camelotdefence',
			'click',
			function (event) {	
				launchCamelotDefenceGame();									
				return false;
			}
		);
		glow.events.addListener(
			'#launch-questforthemorteus',
			'click',
			function (event) {	
				launchMortaeusGame();									
				return false;
			}
		);

	}
	

	
	
	
	
});

function swfDebug(value){
	
}

//handle keyboard focus change in swf, scroll browser to ensure focus target is visible
function swfFocusChangeHandler(minY,maxY){	
	//y+=65;	
	//y-=150;
	var h=getHeight();	
	var scrollY=getScrollY();
	var minVisibleY=scrollY;
	var maxVisibleY=h+scrollY;
	
	var halfY = minY + ((maxY-minY)/2)
	var visibleY = maxVisibleY - minVisibleY;
	var targetY = halfY - (visibleY/2);
	
	scrollTo(0,targetY);
	return;
	
	if(y<minVisibleY){
		scrollTo(0,y-150);
		glow.dom.get('#scroll-debug').html("Y1: " +minVisibleY +" , " +y +" , " +maxVisibleY);
	}else if(y>maxVisibleY){
		scrollTo(0,y-50);
		glow.dom.get('#scroll-debug').html("Y2: " +minVisibleY +" , " +y +" , " +maxVisibleY);		
	}else{
		glow.dom.get('#scroll-debug').html("N: " +minVisibleY +" , " +y +" , " +maxVisibleY);	
	}
}


function writeEMP(){
	scrollTo(0,0);
	//display overlay
	empOverlay.show();

	//$('#main-container-swf').css('display','none');
	//$("body").append("<div id=\"emp-overlay\"></div>");

	var emp = new bbc.Emp();
	emp.setDomId("emp-overlay-inner");
	emp.setWidth("512");
	emp.setHeight("323");
	emp.setPlaylist("http://www.bbc.co.uk/doctorwho/playlists/s4_01/video/s4_01_trl_02.xml");
	emp.write();
}

function writeSite(){	

	var swfContainer = glow.dom.get("#main-container-swf");
	
	if(swfContainer.length == 0) return;
	
	if(typeof useMerlinDevXML=="undefined") useMerlinDevXML=false;
	
	
	glow.dom.get("#main-container-jpg").css("display","none");
	
	var currentTime = new Date();
	var rand="?no_cache=" + currentTime.getTime();
	
	var so = new SWFObject('/merlin/swf/merlin.swf' +rand, 'merlin', '974', '926', '9', '#000000');
	so.useExpressInstall('/merlin/swf/expressinstall.swf');
	if(useMerlinDevXML) so.addVariable('merlin_config_path', '/merlin/config_dev.xml');
	else so.addVariable('merlin_config_path', '/merlin/config.xml' + rand);
	
	
	so.addParam('allowScriptAccess', 'always');
	so.addParam('allowFullScreen', 'true');	
	so.addParam('menu', 'true');					
	
	
	so.write('main-container-swf');
	
	
	glow.dom.get("#swf-footer").addClass("flash");
}

function launchMortaeusGame(){

	
	var gameMode="lightbox";
	var url;
		
	switch(gameMode){
		case "lightbox":			
		
			url="http://downloads.bbc.co.uk/merlin/games/questforthemortaeus/main.swf"
			var gameHtml='';
			
			var so = new SWFObject(url, 'merlin-game', '640', '480', '9', '#000000');
			so.useExpressInstall('/merlin/swf/expressinstall.swf');	
			so.addParam('allowScriptAccess', 'always');
			so.addParam('allowFullScreen', 'false');	
			so.addParam('menu', 'true');					
			so.addVariable('base_url','http://downloads.bbc.co.uk/merlin/games/questforthemortaeus/');					
			so.write('gameOverlay-swf');				
			
			glow.dom.get("#gameOverlay-inner").removeClass('camelotdefence');
						
			gameOverlay.show();	
			
			
			
			glow.events.addListener('#gameOverlay .close , #gameOverlay  .merlin-logo','click',function () { 
				glow.dom.get("#gameOverlay-swf").html("");
				gameOverlay.hide(); 				
				return false;
			});

	
			break;
		case "lightbox_iframe":
			url="/merlin/games/questforthemortaeus/";
			glow.dom.get("#gameOverlay").addClass('active').html('<IFRAME SRC="' +url +'" TITLE="Merlin Game" width="640px" height="480px" frameborder="0" scrolling="no"></IFRAME>');
			gameOverlay.show();		
			break;	
		case "popup":
			url="/merlin/games/questforthemortaeus/main.swf"
			gameWindow = this.open(url, title, "toolbar=no, menubar=no ,location=no, scrollbars=no, resizable=no, width=" + width + ", height=" + height + ", top=" + (screen.height/2 - height/2) + ", left=" + (screen.width/2 - width/2) + "\""); 		
			break;				
	}

	
}

function launchCamelotDefenceGame(){
	
	var gameMode="lightbox";
	var url;
		
	switch(gameMode){
		case "lightbox":			
		
			url="http://downloads.bbc.co.uk/merlin/games/camelotdefence/merlin.swf?v=041208"
			var gameHtml='';
			
			var so = new SWFObject(url, 'merlin-game', '768', '500', '9', '#000000');
			so.useExpressInstall('/merlin/swf/expressinstall.swf');	
			so.addParam('allowScriptAccess', 'always');
			so.addParam('allowFullScreen', 'false');	
			so.addParam('menu', 'true');					
			so.addParam('base','http://downloads.bbc.co.uk/merlin/games/camelotdefence/');					
			so.write('gameOverlay-swf');				
						
					
					
			glow.dom.get("#gameOverlay-inner").addClass('camelotdefence');						
			gameOverlay.show();	
			
			
			
			glow.events.addListener('#gameOverlay .close , #gameOverlay  .merlin-logo','click',function () { 
				glow.dom.get("#gameOverlay-swf").html("");
				gameOverlay.hide(); 				
				return false;
			});

	
			break;
		case "lightbox_iframe":
			url="/merlin/games/camelotdefence/";
			glow.dom.get("#gameOverlay").addClass('active').html('<IFRAME SRC="' +url +'" TITLE="Merlin Game" width="640px" height="480px" frameborder="0" scrolling="no"></IFRAME>');
			gameOverlay.show();		
			break;	
		case "popup":
			url="/merlin/games/camelotdefence/m.swf"
			gameWindow = this.open(url, title, "toolbar=no, menubar=no ,location=no, scrollbars=no, resizable=no, width=" + width + ", height=" + height + ", top=" + (screen.height/2 - height/2) + ", left=" + (screen.width/2 - width/2) + "\""); 		
			break;				
	}

	
}

function getHeight() {
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    myHeight = document.body.clientHeight;
  }
  return myHeight;
}

function getScrollY() {
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    scrOfY = window.pageYOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    scrOfY = document.body.scrollTop;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
}