/**
CBeebies Lighbox
@requires glow.net, glow.embed, glow.anim
**/
if ( window.cbb == undefined )
	cbb = { };

(function (){
	cbb.lb = {
		lightboxOpen: false,
		windowTitle: null,
		pageData : null,
		panel : null,
		flashMov: null,
		mask: null,
		panelTemplate: null,
		recentHash: "",
		lastURL: null,
		pollInt: null,
		flashVars: "",
		launchLB: function(url)
		{
			cbb.lb.getLB(cbb.lb.parseURL(url));
		},
		embedFlash : function()
		{
			// A non-flash message that appears if the flash version is too low
			var additionalMsg = (glow.dom.get('#cbb-swf-altmsg').length > 0) ? glow.dom.get('#cbb-swf-altmsg').html() : "<p>Or <a href='/cbeebies/makes/theme/character/'>try these colouring in activities</a> instead.</p>";
			var msg = "<div><div id='cbb-non-flash'>";
				msg += "<h2>Oops!<span><!-- --></span></h2>";
				msg += "<p class='cbb-errordetail'>You do not have the correct Flash Player to see this.</p>";
				msg += "<p><a href='/cbeebies/grownups/contact/technicalhelp/index.shtml'>Visit Grownups Technical Help</a> to see how to install it.</p>";
				msg += ""+additionalMsg+"";
				msg += "</div></div>";
			var nonFlash = glow.dom.create(msg);
			var embed = glow.dom.get("#cbb-lb-game-embed");
			var swfMetadata = embed.get('span#swf-url').html().split(',');
			var swfURL = swfMetadata[0];
			var swfVersion = (swfMetadata[1] && swfMetadata[1] != "(none)") ? swfMetadata[1] : "7";
			var swfBase = swfMetadata[0].substring(0, swfMetadata[0].lastIndexOf("/")+1);
			var swfVars = "?cache="+Math.random()*999999+"&base="+swfBase;
			swfVars += (cbb.lb.flashVars != "") ? "&"+cbb.lb.flashVars : "";
			swfVars += (swfMetadata[2] && swfMetadata[2] != "(none)") ? "&"+swfMetadata[2] : "";
			swfURL += swfVars;
			var quality = (swfMetadata[3] && swfMetadata[3] != "(none)" && swfMetadata[3] != "false") ? swfMetadata[3] :"high";
			var scale = (swfMetadata[4] && swfMetadata[4] != "(none)" && swfMetadata[4] != "false") ? swfMetadata[4] : "showall";
			cbb.lb.flashMov = new glow.embed.Flash(swfURL, "#cbb-lb-game-embed", swfVersion,
				{
					height: "454px",
					width: "746px",
					id: "cbb-lb-flash",
					params: {
						allowscriptaccess: "always",
						seamlesstabbing: "true",
						scale: scale,
						quality: quality,
						wmode: "window",
						base: swfBase
					},
					message: function(){return nonFlash.html();}
				}
			)

			cbb.lb.flashMov.embed();
		},
		addLBToDom : function(response)
		{
			if(cbb.lb.panel != null){
				glow.dom.get("#cbb-lb-outer").replaceWith(response);
				cbb.lb.panel.show();
				if(cbb.lb.lightboxOpen)
				{
					cbb.lb.embedFlash();
				}
				return;
			}
			
			var navEmbed = glow.dom.get('#cbb-banner-embed');
			var showEmbed = glow.dom.get('#cbb-shows-embed');
			var promoEmbed = glow.dom.get('#cbb-mainpromo');
			
			cbb.lb.panel = new glow.widgets.Panel(glow.dom.create(response), {
				 mask: cbb.lb.mask,
				 closeOnMaskClick:false,
				 autoPosition: false,
				 anim: "fade",
				 width: "100%",
				 template: cbb.lb.customTemplate,
				 id: "cbb-lb"
			});
			glow.events.addListener(
				cbb.lb.panel,
				"afterShow",
				function(event){
					window.scrollTo(0, glow.dom.get(".cbb-panel-head").offset().top);
					cbb.lb.embedFlash();
					cbb.lb.lightboxOpen = true;
					if(navEmbed.length > 0) navEmbed.css('display', 'none');
					if(showEmbed.length > 0) showEmbed.css('display', 'none');
					if(promoEmbed.length > 0) promoEmbed.css('display', 'none');
				}
			)
			glow.events.addListener(
				cbb.lb.panel,
				"afterHide",
				function(event){
					glow.dom.get('body').removeClass('cbb-lb');
					window.location.hash = "#";
					cbb.lb.recentHash = '#';
					cbb.lb.lightboxOpen = false;
					if(navEmbed.length > 0) navEmbed.css('display', 'block');
					if(showEmbed.length > 0) showEmbed.css('display', 'block');
					if(promoEmbed.length > 0) promoEmbed.css('display', 'block');
				}
			)
			cbb.lb.panel.show();
		},
		getLB : function(url)
		{	
			var queryString = '?brand='+url.brand+'&url='+url.path+"&cache="+Math.random()*999999;
			window.location.hash = "/lb/"+url.brand+"/"+url.path;
			cbb.lb.recentHash = window.location.hash;
			brand = '';
			var request = glow.net.get('/cbeebies/include/lb/lb.sssi'+queryString, {
				onLoad: function(response) {
								
					cbb.lb.lastURL = queryString;
					var regEx = new RegExp("IS_IMMERSIVE");
					cbb.lb.removeLBStyles();
					if(regEx.test(response.text())) cbb.lb.getLBStyles(url.brand);
					
					cbb.lb.addLBToDom(response.text());
					
					// Set the lightbox window title to be the brand name
					cbb.lb.setWindowTitle("BBC - CBeebies - " + url.brand);
				},
				onError: function(response) {
					alert("There has been a problem while loading a file");
				}
			});
		},
		removeLBStyles: function()
		{
			var head = glow.dom.get("head");
			if(head.get(".lightboxStyleSheet").length > 0) head.get(".lightboxStyleSheet").destroy();
		},
		getLBStyles : function(brand)
		{
			var head = glow.dom.get("head");
			var filename = "/cbeebies/"+brand+"/style/"+brand+"_lb.css";
			var css = glow.dom.create("<link href='"+filename+"' rel='stylesheet' type='text/css' class='lightboxStyleSheet' />");
			head.append(css);
		},
		// Derives the lightbox url from the last element of the link's href
		parseURL : function(url)
		{
			if(url.match("/cbeebies/")) var splitURL = url.split("/cbeebies/")[1].split(/\//);
			else var splitURL = url.split(/\//);
			// Need to remove empty elements from the array for consistency
			var removeEmptiesSplitURL = new Array();
			var i = 0;
			for(;i<splitURL.length;++i)
			{
				if(splitURL[i] && splitURL[i] != "games") removeEmptiesSplitURL.push(splitURL[i]);
			}
			if(removeEmptiesSplitURL[removeEmptiesSplitURL.length-1].split("?")[1]) cbb.lb.flashVars += removeEmptiesSplitURL[removeEmptiesSplitURL.length-1].split("?")[1];
			return {path: ""+removeEmptiesSplitURL[removeEmptiesSplitURL.length-1].split("?")[0]+"", brand: ""+removeEmptiesSplitURL[removeEmptiesSplitURL.length-2]+""};
		},
		checkHash : function()
		{
			if(window.location.hash == cbb.lb.recentHash) return false;
			cbb.lb.recentHash = window.location.hash;
			var hash = window.location.hash;
			if(hash.match(/\/lb\//))
			{
				cbb.lb.getLB(cbb.lb.parseURL(hash));
			} else {
					if(cbb.lb.panel) cbb.lb.panel.hide();
					
					// Reset the window title
					cbb.lb.setWindowTitle(cbb.lb.windowTitle);
			}
		},
		setWindowTitle : function(str)
		{
			document.title = str;
		},
		init : function()
		{
			// Defines the opaque mask that the lightbox uses
			cbb.lb.mask = new glow.widgets.Mask({
				color:"#d8f1ff", 
				opacity: 1,
				onClick: function(){return false;}
			})
			// Defines custom template for the lightbox panel
			cbb.lb.customTemplate = '<div class="customTemplate">'+
			'	<div class="customTemplate-head">'+
			'		<div class="cbb-panel-head">'+
			'			<div id="cbb-panel-logo"><a href="/cbeebies"><img src="/cbeebies/img/cbeebies_logo_blocks.png" alt="CBeebies" width="106" height="46" /></a></div>'+
			'			<div id="cbb-panel-back-btn"><a class="panel-close" title="back" href="#">Back<span> </span></a></div>'+
			'		</div>'+
			'	</div>'+
			'	<div class="customTemplate-body"><div class="panel-bd"></div></div>'+
			'	<div class="panel-ft"><!-- --></div>'+
			'	<div class="customTemplate-bottom"></div>'+
			'</div>';
			
			if(cbb.lb.pollInt == undefined) cbb.lb.pollInt = setInterval( cbb.lb.checkHash, 1000 );
			
			var lb = glow.dom.get('.lightbox');
			glow.events.addListener(
				lb,
				'click',
				function(event){
					cbb.lb.getLB(cbb.lb.parseURL(event.attachedTo.href));
					event.preventDefault();
				}
			);
			
			// Store the original window title
			cbb.lb.windowTitle = document.title;
		}
	}
})();

gloader.load(
	["glow", "1", "glow.net", "glow.embed", "glow.anim", "glow.widgets.Panel"],
	{
		async : false,
		onLoad : function(g)
		{
			glow = g;
			glow.ready(function()
			{
				cbb.lb.init();
			});
		}
	}
);

function openExternalURL(type){
	if(type=="recipe"){
		url="recipe.html"
	}else if(type=="certificate"){
		url="certificate.html"
	}
	var windowprops = "menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=no,width=640,height=600";
	winName="barnabyPopup"
	popup = window.open(url,winName,windowprops);
	popup.focus()
}