/* 
   code for including on all portal pages.
   deal with carousel + main flash embedding, flash background etc.
*/
if ( window.cbbc == undefined )
	cbbc = {};
if ( !cbbc.glowVersion )
	cbbc.glowVersion = "0.3.1";


glow.module("cbbc.portal", cbbc.glowVersion,
{
	require: 
	[
		"glow.dom",
		"cbbc.sifr"
	],
	implementation: function()
	{
		var doc = document,
			nav = navigator,
			u = navigator.userAgent.toLowerCase(),
			p = navigator.platform.toLowerCase(),
			win = (p) ? /win/.test(p) : /win/.test(u),
			$ = glow.dom.get,
			lang = glow.lang,
			listId = "cbbc-carousel-brands",
			swfId = "cbbc-carousel-swf"
			tabsDivId = "cbb-main-tab-flash",
			showsDivId = "cbbc-shows",
			iPlayerDivId = "cbbc-childrens-iplayer",
			allShowsXml = "/cbbc/include/data/carousel/allshowsxml.sssi",
			flashPlayerVersion = "8.0.0";
		
		var embedCarousel = function()
		{
			if ( !glow.isReady )
			{
				P.setVisibility(listId, false);
				glow.ready(embedCarousel);
				return;
			}
			
			var flashvars = {
				swfid: swfId,
				xml_path: allShowsXml,
				random: cbbc.random,
				bgY: cbbc.section
			};
			
			// get urls + images for brands from dom. saves another xml request
			var list = $("#"+listId);
			var links = list.get("a");
			
			var urls = [];
			var imgs = [];
			
			var len = links.length;
			for ( var i=0; i<len; i++ )
			{
				flashvars["url"+i] = links.attr("href");
				flashvars["img"+i] = links.get("img").attr("src");
				links = links.slice(1, len-i);
			}
			
			var attributes = {
				id: swfId,
				name: swfId
			};
			
			var params = {
				bgcolor: P.BGCOLORS[cbbc.section]
			}
			
			swfobject.embedSWF("/cbbc/swf/carousel.swf", listId, "550", "74", flashPlayerVersion, null, flashvars, params, attributes);
		}
		
		
		var embedTabs = function()
		{
			if ( !glow.isReady )
			{
				P.setVisibility(tabsDivId, false);
				glow.ready(embedTabs);
				return;
			}
			
			if ( !$("#"+tabsDivId).length )
				return;
			
			var query = ( cbbc.isPreview ) ? "%26cbbc_preview=1+%26day="+cbbc.day+"%26month="+cbbc.month+"%26year="+cbbc.year : "";
			var flashvars = {
					section: cbbc.section,
					location: cbbc.tab || 1,
					childlocation: cbbc.childtab || null,
					xmlPath: ( cbbc.section == "watch") ? "/cbbc/include/data/tabs/xml_watch.sssi?cbbc_section=" + cbbc.section + query : "/cbbc/include/data/tabs/xml.sssi?cbbc_section=" + cbbc.section + query
				};
				
			var params = {
					bgcolor: P.BGCOLORS[cbbc.section]
				};
			
			var attributes = {
					id: "flContent",
					name: "flContent"
				};

			swfobject.embedSWF("/cbbc/swf/tabs.swf", tabsDivId, "160", Math.max($("#"+tabsDivId).height()+6, 438), flashPlayerVersion, "", flashvars, params, attributes);
		}
		
		var embedIPlayer = function()
		{
			if ( !glow.isReady )
			{
				P.setVisibility(iPlayerDivId, false);
				glow.ready(embedIPlayer);
				return;			
			}
			
			var flashvars = {
				bgY: cbbc.section			
			};
			
			var params = {
				bgcolor: P.BGCOLORS[cbbc.section]
			};
			
			var attributes = {
				id: "cbbc-childrens-iplayer-swf",
				name: "cbbc-childrens-iplayer-swf"
			};
			
			swfobject.embedSWF("/cbbc/swf/iplayercarousel.swf", iPlayerDivId, "226", "73", flashPlayerVersion, "", flashvars, params, attributes);
		}
		
		var embedShowButtons = function()
		{
			if ( !glow.isReady )
			{
				P.setVisibility(showsDivId, false);
				glow.ready(embedShowButtons);
				return;			
			}
			
			var flashvars = {
				bgY: cbbc.section
			};
			
			var params = {
				bgcolor: P.BGCOLORS[cbbc.section],
				allowScriptAccess: "always"
			};
			
			var attributes = {
				id: "cbbc-shows-swf",
				name: "cbbc-shows-swf"
			};
			swfobject.embedSWF("/cbbc/swf/showbuttons.swf", showsDivId, "174", "104", flashPlayerVersion, "", flashvars, params, attributes);
		}
		
		/*var initSifr = function()
		{
			var mink = "/cbbc/swf/mink.swf";
			cbbc.sifr.replaceElement(
				cbbc.named(
				{
					sSelector:"#cbbc-player-core h2.cbbc-player-header span, h3.cbbc-player-subheader span, .cbbc-player-header h2 span, #cbbc-help-promos h2.cbbc-player-header span",
					sFlashSrc:mink,
					sColor:"#ffffff",
					sBgColor:"#000000",
					sTextAlign:"center"
				})
			);
			cbbc.sifr.replaceElement(
				cbbc.named(
				{
					sSelector:"#cbbc-promos span.label",
					sFlashSrc:"/cbbc/swf/mink.swf",
					sColor:"#ffffff",
					sLinkColor:"#ffffff",
					sBgColor:"#000000",
					sHoverColor:"#5c8503",
					sHoverBgColor:"#dbebb6",
					sTextAlign:"center",
					bInLink:true
				})
			);*/
			/*cbbc.sifr.replaceElement(
				cbbc.named(
				{
					sSelector:"#cbbc-vertical-carousel span.label",
					sFlashSrc:mink,
					sColor:"#ffffff",
					sLinkColor:"#ffffff",
					sBgColor:"#000000",
					sHoverColor:"#5c8503",
					sHoverBgColor:"#dbebb6",
					sTextAlign:"center",
					bInLink:true
				})
			);*/
		//}
		
		var P = function() {};
		
		P.getSwf = function(movieName)
		{
			if (navigator.appName.indexOf("Microsoft") != -1) {
				return window[movieName];
			}
			else {
				return document[movieName];
			}
		}
		
		P.createCSS = function(sel, decl)
		{
			var h = doc.getElementsByTagName("head")[0];
			
			var s = doc.createElement("style");
			s.setAttribute("type", "text/css");
			s.setAttribute("media", "screen");
			if (!(glow.env.ie && win) && typeof doc.createTextNode != "undefined") {
				s.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
			}
			h.appendChild(s);
			if (glow.env.ie && win && typeof doc.styleSheets != "undefined" && doc.styleSheets.length > 0) {
				var ls = doc.styleSheets[doc.styleSheets.length - 1];
				if (typeof ls.addRule == "object") {
					ls.addRule(sel, decl);
				}
			}
		}
		
		P.setVisibility = function(id, isVisible)
		{
			var v = isVisible ? "visible" : "hidden";
			if ( glow.isReady ) {
				$("#"+id).css("visibility", v);
			}
			else {
				P.createCSS("#" + id, "visibility:" + v);
			}
		}
		
		P.BGCOLORS = {
			home: "#83cbd3",
			watch: "#32001c",
			games: "#dbeed2",
			create: "#000000",
			grab: "#14535b",
			find: "#32160c"
		};
		
		//if ( !cbbc.noFlash && glow.isSupported && swfobject.hasFlashPlayerVersion(flashPlayerVersion) )
		if(!cbbc.noFlash && swfobject.hasFlashPlayerVersion(flashPlayerVersion))
		{
			//initSifr();
			//embedCarousel();
			//embedTabs();
			//embedIPlayer();
			//embedShowButtons();
		}
		
		return P;
	}
});



glow.module("cbbc.bg", cbbc.glowVersion,
{
	require: 
	[
		"glow.dom",
		"glow.events",
		"cbbc.portal"
	],
	implementation: function()
	{
		var DIV_ID_L = "bgl",
			DIV_ID_R = "bgr",
			SWF_ID_L = "bgleft",
			SWF_ID_R = "bgright",
			SWF_URL = "/cbbc/swf/bg/{section}_{position}.swf",
			dom = glow.dom,
			$ = glow.dom.get,
			events = glow.events,
			lang = glow.lang,
			portal = cbbc.portal,
			contentW,
			divL,
			divR,
			swfL,
			swfR,
			freezeLink,
			initCount = 0,
			flashPlayerVersion = "8.0.0",
			getsFlash = ( swfobject.hasFlashPlayerVersion(flashPlayerVersion) && !cbbc.noFlash );
		
		var Bg = function(){};
		
		var getViewSize = function()
		{
			var offsetX, offsetY;
			if ( typeof(self.pageYOffset) == "number" ) {
				offsetX = window.pageXOffset;
				offsetY = window.pageYOffset;
			} else if ( document.documentElement && document.documentElement.scrollTop ) {
				offsetX = document.documentElement.scrollLeft;
				offsetY = document.documentElement.scrollTop;
			} else if ( document.body ) {
				offsetX = document.body.scrollLeft;
				offsetY = document.body.scrollTop;
			}
			
			var windowWidth, windowHeight;
			if ( document.documentElement && document.documentElement.clientHeight ) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if ( document.body ) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}
			if ( self.innerHeight ) {	// all except Explorer
				windowHeight = self.innerHeight;
			}
			
			return {x:offsetX, y:offsetY, w:windowWidth, h:windowHeight};
		}
		
		/*
		return object with x, y positions for an element
		*/
		var getObjCoords = function(o)
		{
			var oX = 0;
			var oY = 0;
			if (o.offsetParent) {
				while (1) {
					oX += o.offsetLeft;
					oY += o.offsetTop;
						if (!o.offsetParent) {
							break;
						}
					o=o.offsetParent;
				}
			} else if (o.x) {
				oX += o.x;
				oY += o.y;
			}
			
			return {x:oX, y:oY};
		}
	
		/*
			only for use on barlesque pages
			returns an object with w, h of page or viewport, whichever is larger.
		*/
		var getPageSize = function()
		{
			var view = getViewSize();
		
			var w = view.w;
			var h = view.h;
			
			// try to get barlesque footer. should be last element on the page
			var bot = $("#blq-foot");
			if ( !bot.length )
			{
				return {w:w, h:h};
			}
			
			var p = getObjCoords(bot[0]);
			
			// using glow NodeList.height() method caused flickering in IE.
			var botH = bot[0].offsetHeight;
			var botX = p.y + botH;
			
			// if page height is greater than viewport height return page height
			if ( botX > h )
				h = botX;
			// otherwise if gecko type, return the width of viewport without vertical scrollbar
			else if ( self.innerWidth )
			{
				h = self.innerHeight-1;
				w = self.innerWidth;
			}
			
			h = ( botX > h ) ? botX : h;
			
			return {w:w, h:h};
		};
		
		var embed = function()
		{
			if ( !getsFlash )
				return;
			
			contentW = $("#blq-main").width();
			
			var attrs = {
				bgcolor: cbbc.portal.BGCOLORS[cbbc.section],
				quality:"high",
				scale:"noScale",
				allowScriptAccess: "sameDomain",
				swLiveConnect: true
			}
			
			var flashvars = {
				random: cbbc.random
			};
			
			attrs.id = SWF_ID_L;
			attrs.name = SWF_ID_L;
			attrs.align = "TR";
			
			var container = $("#blq-container");
			
			// fix for missing span in aps pages not allowing backgrounds to be inserted in ie
			try
			{
				container.after("<div id='" + DIV_ID_R + "'><div id='" + SWF_ID_R + "'></div></div>");
				container.after("<div id='" + DIV_ID_L + "'><div id='" + SWF_ID_L + "'></div></div>");
			}
			catch(e) { return; }
			
			divL = $("#" + DIV_ID_L);
			divR = $("#" + DIV_ID_R);
			
			swfobject.embedSWF("/cbbc/swf/bg/" + cbbc.section + "_left.swf", SWF_ID_L, "100%", "100%", flashPlayerVersion, null, flashvars, attrs);
			
			attrs.id = SWF_ID_R;
			attrs.name = SWF_ID_R;
			attrs.align = "TL";
			
			swfobject.embedSWF("/cbbc/swf/bg/" + cbbc.section + "_right.swf", SWF_ID_R, "100%", "100%", flashPlayerVersion, null, flashvars, attrs);
			
			// add sound control
			$("#blq-local-nav").prepend("<div id='cbbc-sound-switch'><div id='cbbc-sound-state'><div id='cbbc-sound-holder'></div></div></div>");
			
			var params = {
				bgcolor: "#87C600"
			}
			
			var flashvars = {
				swfid: "cbbc-sound-switch",
				random: cbbc.random
			}
			
			swfobject.embedSWF("/cbbc/swf/soundswitch.swf", "cbbc-sound-holder", 68, 78, flashPlayerVersion, null, flashvars, params, {id:"cbbcsoundswf"});
			
			
			Bg.positionBg();
			events.addListener( window, "resize", Bg.positionBg, Bg );
		};
		
		events.addListener( window, "load", embed, this );
		
		
		// PUBLIC
		
		// each bg.swf calls this function when it's initialised
		Bg.hasInitialised = function()
		{
			if ( ++initCount == 2 )
			{
				//positionBg();
				//events.addListener( window, "resize", positionBg, this );
			}
		}
		
		Bg.positionBg = function()
		{
			var page = getPageSize(),
				flashW = (page.w - contentW)/2,
				flashH = page.h;
			
			// hack for apparent difference in rounding logic for the position of centered elements
			// between ie + other browsers. should be possible to get rid of this when i work out
			// exactly what's going on.
			// in ie, when calculated flash width is xx.5, the offset is removed.
			var offset = /*@cc_on ( flashW != Math.floor(flashW) ) ? 0 : @*/ 1;
			
			divR.css("left", (Math.floor(flashW) + contentW - offset)+"px");
			// if viewport is narrower than content, hide the flash by shrinking container divs
			if ( getViewSize().w <= contentW )
			{
				divL.css("height", "1px");
				divL.css("width", "1px");
				divR.css("height", "1px");
				divR.css("width", "1px");
			}
			// otherwise resize container divs
			else
			{
				var leftW = Math.floor(flashW) + 1 + offset * -1;
				var rightW = flashW + offset;
				divL.css("height", flashH+"px");
				divL.css("width", leftW+"px");
				divR.css("height", flashH+"px");
				divR.css("width", rightW+"px");
			}
		};
		
		Bg.toggleSound = function(isOn)
		{
			var state = $("#cbbc-sound-state");
			
			if ( typeof isOn == "string" )
				isOn = ( isOn == "true" ) ? true : false;
			
			if ( isOn )
				state.addClass("on");
			else
				state.removeClass("on");
			
			return true;
		}
		
		return Bg;
	}
});


