/**
CBeebies Site wide
@requires glow.dom
**/
if ( window.cbb == undefined )
	cbb = { };

(function (){
	cbb.site = {
	
		navMain: null,
		
		init : function()
		{
			cbb.site.keyboardListener.init();
		
			cbb.site.guInfo.init();
			cbb.site.toggleSound.init();
			cbb.site.embed.nav();
			cbb.site.embed.flashBrandArea();
			cbb.site.interstitial.init();
		},
		readCookie: function(name)
		{
			var nameEQ = name+"=";
			var ca = document.cookie.split(';');
			var c;
			for(var i=0;i<ca.length;i++)
			{
				c = ca[i];
				while (c.charAt(0) == ' ') c = c.substring(1, c.length);
				if(c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
			}
			return null;
		},
		writeCookie: function(name, value, days)
		{
			if(days) 
			{
				var date = new Date();
				date.setTime(date.getTime() + (days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			}
			else var expires = "";
			document.cookie = name+"="+value+expires+"; path=/";
		},
		eraseCookie: function(name)
		{
			writeCookie(name, "", -1);
		},
		
		
		disableFlash: function(bool)
		{
			/*
			*	Passes a 'true'/'false' to the flash nav and hppromo, so that
			*	their event listeners can be forced on/off.
			*	Flash event listeners need to be disabled when the lightbox is open
			*/
			var flashDisabled = (bool) ? 'true' : 'false';	
			try{window.document.getElementById("cbb-banner-swf").disableFlash(flashDisabled);}			
			catch(e){}
			
			try{window.document.getElementById("cbb-mainpromo-swf").disableFlash(flashDisabled);}			
			catch(e){}
		},
		
		navmainLoaded: function()
		{
			glow.dom.get('#cbb-banner-swf').css("visibility", "visible");
		},
				
		launchRadioplayer: function(theURL)
		{
			if(theURL == undefined) theURL = "/cbeebies/radioplayer/";			
			var windowParams = "location=0,status=0,scrollbars=0, resizable=0, width=740, height=560";
			
			window.open(theURL, "CBeebiesRadioPlayer", windowParams);
			
			try{window.document.getElementById("cbb-mainpromo-swf").disableFlash('true');}			
			catch(e){}
		}
	};
	cbb.site.keyboardListener =
	{
		shiftPressed: false,
		tabPressed: false,
		tabbableItems: [],
		
		init: function()
		{
			shiftPressed = false,
			tabPressed = false,
			tabbableItems = [],

			document['onkeydown'] = cbb.site.keyboardListener.keyDownHandler;
			document['onkeyup'] = cbb.site.keyboardListener.keyUpHandler;
			
			window.document.getElementById("a-cbeebies-logo").onfocus = cbb.site.keyboardListener.logoGotFocus;
			window.document.getElementById("a-cbeebies-logo").onblur = cbb.site.keyboardListener.logoLostFocus;			
		},
				
		addTabbableItem: function(obj)
		{
			//tabbableItems.push(obj);
						
			////////////////////////////////////////
			// Store the embed id value, indexed by a 'key' name
			// 
			// example:
			//		tabbableItems["navshows"] = 'cbb-shows-swf';
			
			tabbableItems[obj.key] = obj.id;
			
			////////////////////////////////////////
		},
		
		keyDownHandler: function(e)
		{
			var evt = e || window.event;

			if(evt.keyCode == 9) tabPressed = true;
			else if(evt.keyCode == 16) shiftPressed = true;			
		},
		
		keyUpHandler: function(e)
		{
			var evt = e || window.event;

			if(evt.keyCode == 9) tabPressed = false;
			else if(evt.keyCode == 16) shiftPressed = false;
		},
		
		logoGotFocus: function()
		{			
			// logo got focus
		},
		
		logoLostFocus: function()
		{			
			// if shift has been pressed, then we are tab-cycling
			// backwards, so lets not give the tabbableItems focus
			if(!shiftPressed)
			{
				document.getElementById(tabbableItems['navmain']).focus();
			}
		},
		
		navmainLostFocus: function(tabToNextItem)
		{			
			if(!tabToNextItem)
			{
				// Tab to the previous item
				document.getElementById("a-cbeebies-logo").focus();
			}
			else
			{
				// Tab to the homepage promo, if it exists, otherwise
				// remove focus from the 'navshows' and then move to the 
				// next item on the page
				
				var hpPromo = document.getElementById("cbb-mainpromo-swf");
				
				if(hpPromo != null)
				{					
					hpPromo.focus();
				}
				else
				{
					document.getElementById(tabbableItems['navmain']).blur();
				}
			}
		},
		
		hpPromoLostFocus: function(tabToNextItem)
		{
			if(!tabToNextItem)
			{
				// Tab to the previous item
				document.getElementById(tabbableItems['navmain']).focus();
			}			
			
			else
			{
				
				var hpPromo = document.getElementById("cbb-mainpromo-swf");				
				if(hpPromo != null)
				{
					// Remove focus from homepage promo
					hpPromo.blur();
				}
			}
		}
		
	};
	/**
	*	Embeds for nav and flash brand area
	*/
	cbb.site.embed = {
		dateTime: function ()
		{
			var date = new Date();
			var d = date.getDate();
			var dd = (d < 10) ? '0' + d : d;
			var m = date.getMonth() + 1;
			var mm = (m < 10) ? '0'+m : m;
			var y = date.getFullYear()-2000;
			var yy = (y < 10) ? '0' +y : y;
			var h = date.getHours();
			var hh = (h < 10) ? '0'+h : h;
			var min = date.getMinutes();
			var mm = (min < 10) ? '0'+min : min;
			var s = date.getSeconds();
			var ss = (s < 10) ? '0'+s : s;
			var dateTime = dd+'/'+mm+'/'+yy+' '+hh+':'+mm+':'+ss;
			return dateTime;
		},
		nav : function(xmlPath, basePath)
		{		
			if (!xmlPath) xmlPath = '/cbeebies/swf/navbar/';
			if(!basePath) basePath = '/cbeebies/swf/navbar/';
			
			var sectionId;
			for(var i=0;i<cbb.sections.length; i++)
			{
				if(cbb.sections[i].section == cbb.section)
				{
					sectionId =i;
				}
			}
			var opts = {
				
				width: "100%",
				height: "149",
				attributes: {
					id: "cbb-banner-swf",
					name: "cbb-banner-swf"
				},
				params: {
					seamlesstabbing: "false",
					allowscriptaccess: "always",
					scale: "noscale",
					wmode: "window",
					flashVars:{
						d: cbb.site.embed.dateTime(),
						season: cbb.season,
						secid: sectionId,
						xmlpath: xmlPath,
						base: basePath,
						soundenabled: cbb.site.toggleSound.getSound()
					}
				},
				message: function(){return glow.dom.get('#cbb-banner-embed').html();}
			};
			cbb.site.navMain = new glow.embed.Flash("/cbeebies/swf/navbar/preloader_cbeebies_navbar_wide"+cbb.suffixes.swf+".swf", "#cbb-banner-embed", "9", opts).embed();			
			cbb.site.keyboardListener.addTabbableItem({key:"navmain", id:opts.attributes.id});
			
			////////////////////////////////////////
			// Hide the swf.
			// Once the swf has loaded, it calls:	
			//	cbb.site.navmainLoaded()
			// to set itself visible.
			glow.dom.get('#cbb-banner-swf').css("visibility", "hidden");	
			////////////////////////////////////////
		},
		flashBrandArea : function()
		{
			if(glow.dom.get("#cbb-flashsplash").length == 0) return;
			if(!window.flashConfig) return;
			var flashWidth =(flashConfig.width) ? flashConfig.width : "734";
			var flashHeight = (flashConfig.height) ? flashConfig.height : "302";
			var flashParams = (flashConfig.params) ?flashConfig.params :{};
						
			
			var opts = {
				width: flashWidth,
				height: flashHeight,
								
				attributes: {
					id: "cbb-flashsplash-swf",
					name: "cbb-flashsplash-swf",
					bgcolor: "#EAEAEA"
				},
				params: flashParams,
				message: function(){ cbb.site.embed.flashMsg() }
			};
			new glow.embed.Flash(flashConfig.src, "#cbb-flashsplash", flashConfig.version, opts).embed();
			
			//glow.dom.get('#cbb-flashsplash').css("visibility", "hidden");
			glow.dom.get('#cbb-flashsplash').css("visibility", "visible");
			
		},
		flashBrandAreaReady : function()
		{
			// Called from the FBA constructor, sets FBA div be visible
			glow.dom.get('#cbb-flashsplash').css("visibility", "visible");
		},
		flashMsg : function()
		{
			var msgNode = glow.dom.get("#cbb-flashsplash");
			glow.dom.get(msgNode.get(".cbb-text-overlay p")[0]).empty().text("You do not have the correct Flash Player to see this.");
			return msgNode.html();
		}
	};
	/**
	* Interstitial iPlayer message that appears when iPlayer promo is clicked.
	**/
	cbb.site.interstitial = {
		iPlayerPanel: null,
		showThis: true,
		/**
		*	Construct a panel and set event listeners for the iPlayer message
		* 	An example is launched from the iPlayer promo above the footer
		**/
		init: function()
		{
			var cookie = cbb.site.readCookie('cbb-iplayer-msg');
			if (!cookie | cookie == 'true' ) cbb.site.interstitial.showThis = true;
			else cbb.site.interstitial.showThis = false;
			var checkIt = (!cbb.site.interstitial.showThis) ? "checked='checked'" : "";
			var iPlayerLinks = glow.dom.get(".cbb-iplayer-link");
			var iPlayerPanelContent = glow.dom.create("<div id='iPlayerPanel'>" +
				"<h2>You are about to go to CBeebies iPlayer<span><!-- --></span></h2>"+
				"<p>The CBeebies iPlayer is designed to put parents more in control of your family's viewing - allowing you to schedule your favourite shows online when it suits you."+
				"<p><a href='#' id='iplayer_no'> Back to Cbeebies<span><!-- --></span></a>"+
				"<a href='#' id='iplayer_yes'>CBeebies iPlayer<span><!-- --></span></a></p>"+
				"<form><p><input type='checkbox'"+checkIt+" name='show-again' id='show-again' /> Do not show me this again</p></form>" +
				"<p class='grownups-link'><a href='/cbeebies/grownups/about/cbeebies_iplayer.shtml'>Tell me more about the CBeebies iPlayer</a></p>"+
			"</div>");
			
			var customTemplate = '<div class="customTemplate">'+
					'<div class="customTemplate-head">'+
						'<div class="panel-hd"></div>'+
					'</div>'+
					'<div class="customTemplate-body">'+
						'<div class="panel-bd"></div>'+
					'</div>'+
					'<div class="panel-ft"></div>'+
					'<div class="customTemplate-bottom">'+
						'<a href="#" class="panel-close">Close<span><!-- --></span></a>'+
					'</div>'+
				'</div>';
			this.iPlayerPanel = new glow.widgets.Panel(iPlayerPanelContent, {modal: true, className: 'cbb-iplayer-msg', width: 514, template: customTemplate, hideWhileShown: glow.dom.get('.cbb-sound-toggle-btn')});
			this.iPlayerPanel.content.addClass('cbb-iplayer-lb');
			glow.events.addListener(iPlayerLinks, "click", function(e) {
				cbb.site.interstitial.launchInterstitial();
				e.preventDefault();
			});
			glow.events.addListener(glow.dom.get("#iplayer_no"), "click", function(e){
				cbb.site.interstitial.iPlayerPanel.hide();
				e.preventDefault();
			});
			glow.events.addListener(glow.dom.get("#iplayer_yes"), "click", function(e){
				cbb.site.interstitial.launchIPlayer();
				e.preventDefault();
			});
			glow.events.addListener(glow.dom.get("input#show-again"), "click", function(e){
				cbb.site.interstitial.showThis = !e.source.checked;
				var show = (cbb.site.interstitial.showThis) ? 'true' : 'false';
				cbb.site.writeCookie('cbb-iplayer-msg', show);
			});
		},
		launchInterstitial: function()
		{
			if(cbb.site.interstitial.showThis) cbb.site.interstitial.iPlayerPanel.show();
			else cbb.site.interstitial.launchIPlayer();
		},
		launchIPlayer: function()
		{
			window.location = "/iplayer/cbeebies/";
		}
	};
	/**
	*	Sound toggle button and flash interface for muting sound in all flash content
	*/
	cbb.site.toggleSound = {
		isOn : true,
		init : function()
		{
			this.checkCookie();
			this.addSoundToggle();
			this.addListeners();
		},
		addSoundToggle : function()
		{
			//var classes = "cbb-sound-toggle-btn";
			//if (this.isOn) classes += " cbb-sound-on";
			//var soundButton = glow.dom.create('<li id="cbb-sound-onoff" class="'+classes+'"><a href="#"><span id="cbb-sound-graphic"> </span></a></li>');
			//glow.dom.get('ul#cbb-nav-globals').append(soundButton);
		},
		addListeners : function()
		{
			var classes = "cbb-sound-toggle-btn";
			var isOn = cbb.site.toggleSound.checkCookie();
			if (!isOn) classes += " cbb-sound-on";
			glow.dom.get("#cbb-nav-gu").parent().append("<li id='cbb-sound-onoff' class='"+classes+"'><a href='#'><span id='cbb-sound-graphic'></span></a></li>");
			glow.events.addListener(
				'#cbb-nav-globals .cbb-sound-toggle-btn',
				'click',
				this.clickEventHandler,
				this
			)
		},
		clickEventHandler : function(e)
		{
			this.toggleSound();			
			e.preventDefault();
		},
		checkCookie : function()
		{
			var soundOn = cbb.site.readCookie('cbb-nav-sound-enabled');
			
			if(soundOn == 'false') this.isOn = false;
			else this.isOn = true;
			
			return this.isOn;
		},
		setCookie : function()
		{
			var soundOn = (!this.isOn) ? 'false' : 'true';			
			cbb.site.writeCookie('cbb-nav-sound-enabled', soundOn, 1000);
		},
		updateBtn : function()
		{
			var sndBtn = glow.dom.get('.cbb-sound-toggle-btn');
			sndBtn.toggleClass('cbb-sound-on');			

		},
		updateFlash : function()
		{			
			window.document.getElementById("cbb-banner-swf").toggleSound(this.isOn);			
		},
		toggleSound : function()
		{
			this.isOn = !this.isOn;
						
			this.setCookie();
			
			this.updateBtn();
			this.updateFlash();
		},
		getSound : function()
		{
			return this.isOn;
		}
	};
	
	/**
	*	Grown-ups information slide down panel for promos throughout the site
	*/
	cbb.site.guInfo = {
		isAnimated : true,
		wrapperHeights : [],
		preventInteraction: true,
		rollColours: {
			games: '#9a0611',
			songs: '#da3505',
			makes: '#0b7889',
			stories: '#037e03',
			watch: '#b00a65'
		},
		init : function()
		{
			this.wrapInformation(glow.dom.get('div.cbb-grownups'));
			this.addPointer(glow.dom.get('div.cbb-grownups h3'));
			this.hideContainers(glow.dom.get('.cbb-grownups-wrapper'));
			this.addListeners('div.cbb-grownups h3');
		},
		wrapInformation : function(nodeList)
		{
			nodeList.each(function(i)
			{
				var id = cbb.site.guInfo.wrapperHeights.length;
				
				/*var replacementNodeList = glow.dom.create('<div id="gu-wrapper-id-'+id+'" class="cbb-grownups-wrapper"></div>');
				replacementNodeList.css('overflow', 'hidden');
				this == nodeList[i];
				var _node = glow.dom.get(this);
				_node.append(replacementNodeList);
				var pars = _node.get('p');
				var clone = pars.clone(false);
				replacementNodeList.append(clone);
				pars.remove();*/
				this == nodeList[i];
				var _node = glow.dom.get(this).get('.cbb-grownups-wrapper');
				_node.attr('id', 'gu-wrapper-id-'+id);
				_node.css('overflow', 'hidden');
				
				cbb.site.guInfo.wrapperHeights.push( {id: id, height: _node.css('height')} );
			});
		},
		addPointer : function(nodeList)
		{
			nodeList.addClass('cbb-grownups-btn');
		},
		hideContainers : function(nodeList)
		{
			nodeList.each(function(i)
			{
				this == nodeList[i];
				if(cbb.site.guInfo.isAnimated)
				{
					var anim = glow.anim.css(this, 0.25, { "height": {to:0}}).start();
					cbb.site.guInfo.preventInteraction = true;
					var node = glow.dom.get(this);
						var listener = glow.events.addListener(anim, "complete", function() {
						node.hide();
						glow.events.removeListener(this);
						cbb.site.guInfo.preventInteraction = false;
					});
				}
				else 
				{
					glow.dom.get(this).hide();
				}
			});
		},
		showContainers : function(nodeList)
		{
			nodeList.each(function(i)
			{
				this == nodeList[i];
				var height, j = 0;
				var id = parseInt(glow.dom.get(this).attr('id').replace('gu-wrapper-id-', ''));
				for( ; j < cbb.site.guInfo.wrapperHeights.length; ++j)
				{
					if(cbb.site.guInfo.wrapperHeights[j].id == id) height = cbb.site.guInfo.wrapperHeights[j].height;
				}
				if(cbb.site.guInfo.isAnimated)
				{
					glow.dom.get(this).show();
					var anim = glow.anim.css(this, 0.5, { "height": {to:height}}).start();
					cbb.site.guInfo.preventInteraction = true;
					var node = glow.dom.get(this);
					var listener = glow.events.addListener(anim, "complete", function() {
						glow.events.removeListener(this);
						cbb.site.guInfo.preventInteraction = false;
						glow.dom.get('.cbb-promo').css('height', 'auto');
					});
				}
				else
				{
					glow.dom.get(this).show();
				}
			});
		},
		clickEventHandler : function(e)
		{
			if(cbb.site.guInfo.preventInteraction) return;
			var trigger = glow.dom.get(e.attachedTo);
			trigger.toggleClass('cbb-grownups-info-on');
			var wrapper = trigger.parent().get('.cbb-grownups-wrapper');
			if (wrapper.css('height') == "0px") this.showContainers(wrapper);
			else this.hideContainers(wrapper);
			e.preventDefault();
		},
		addListeners : function(selector,val)
		{
			glow.events.addListener(
				selector,
				'click',
				this.clickEventHandler,
				this
			);
			
			var nodeSel = glow.dom.get(selector);
			
			if (!val &&  glow.dom.get('body').hasAttr('class'))
			{
				var bodyClass = glow.dom.get('body').attr('class').split(' ');
				val = bodyClass[0].substring(4);
				
				glow.events.addListener(glow.dom.get(selector),'mouseover',function (e) {
						glow.dom.get(this).toggleClass('btn-mouse-over');
						//glow.dom.get(this).css('color',cbb.site.guInfo.rollColours[val]);
					}
				);
				glow.events.addListener(glow.dom.get(selector),'mouseout',function () {
						glow.dom.get(this).toggleClass('btn-mouse-over');
						//glow.dom.get(this).css('color','#000');
					}
				);
				glow.events.addListener(glow.dom.get('.cbb-promo.cbb-'+val+' .cbb-grownups-btn'),'mouseover',function () {
						glow.dom.get('.cbb-'+val+' .cbb-grownups-btn').css('color',cbb.site.guInfo.rollColours[val]);
					}
				);
				glow.events.addListener(glow.dom.get('.cbb-promo.cbb-'+val+' .cbb-grownups-btn'),'mouseout',function () {
						glow.dom.get('.cbb-'+val+' .cbb-grownups-btn').css('color','#000');
					}
				);
			}
		}
	}
})();
gloader.load(
	["glow", "1", "glow.dom", "glow.anim", "glow.events", "glow.embed", "glow.widgets.Panel"],
	{
		async : false,
		onLoad : function(g)
		{
			glow = g;
			glow.ready(function()
			{
				cbb.site.init();
			});
		}
	}
);

function fullScreenPop(url) {
	var w = 600, h = 400; // default sizes
	if (window.screen) {
		w = window.screen.availWidth - 12;
		h = window.screen.availHeight - 48;
	}
	pop_window = window.open(url,'fullwin','width=' + w + ',height=' + h + ',left=0,screenX=0,top=0,screenY=0,fullscreen=no,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=no,resizable=yes');
	self.name = "main";
}

function openNewWindow(url){
	fullScreenPop(url);
}
