glow.onDomReady(function() {

	// FF 1.08 CSS fix
	if (glow.env.gecko < 1.8)
	{
		glow.dom.get(".le-promo-navigation .navigation-promo h3").css("width", "110px");
		glow.dom.get(".le-promo-navigation .navigation-promo p").css("width", "110px");
	}



	// *********************************************************
	// Initialise all EMP players on the page (now redundant???)
	// *********************************************************

	for (emp in window.empTable)
	{
		if (empTable[emp].value != "")
		{
			(function() {
				var player = new embeddedMedia.Player();
				//alert(3);
				//console.trace()				
				player.setWidth(choose_dimensions(empTable[emp].id, "width"));
				player.setHeight(choose_dimensions(empTable[emp].id, "height"));
				player.setDomId(empTable[emp].id);
				player.setPlaylist(empTable[emp].value);
				player.write();
			})();
		}
	}



	// *******************
	// Accordian behaviour
	// *******************

	var arrH3Accordian = glow.dom.get("h3.le-accordian");

	arrH3Accordian.each(function(i) {
		glow.events.addListener(arrH3Accordian[i], 'click', function(){

			glow.dom.get(this).parent().parent().css("height", "auto");

			// Change the arrow in the head
			if ( glow.dom.get(this).hasClass("show") )
			{
				// Close the accordian
				glow.dom.get(this).removeClass("show");
				var myAnim = glow.anim.css(
					glow.dom.get(this).next(), 
					0.75,
					{
						"height" : {to: 0}
					},
					{tween:glow.tweens.bounceOut()}
				);
				// Fix for Safari 2: Make the accordian div disappear once it has closed
				var obj = glow.dom.get(this).next().get("ul");
				glow.events.addListener(myAnim, "complete", function(){
					obj.css("display", "none");
				});
				myAnim.start();
			}
			else
			{
				// Open the accordian
				glow.dom.get(this).addClass("show");
				// Fix for Safari 2: Make the accordian div reappear before it opens
				glow.dom.get(this).next().get("ul").css("display", "block");
				var accordian_height = (glow.dom.get(this).next().children().height()+20);
				var myAnim = glow.anim.css(
					glow.dom.get(this).next(), 
					0.75,
					{
						"height" : {to: accordian_height }
					},
					{tween:glow.tweens.bounceOut()}
				).start();
			}

		});
	});

	var arrH2Emphasized = glow.dom.get("h2.emphasised");
	arrH2Emphasized.each(function(i) {

		// Add a <span/> tag to the H2 - this is needed to add an additional background image
		glow.dom.get(arrH2Emphasized[i]).html("<span></span>" + glow.dom.get(arrH2Emphasized[i]).html());

		// Add an event to capture mouse clicks - this will check for the existance of the class 'show' and act accordingly
		glow.events.addListener(glow.dom.get(arrH2Emphasized[i]), 'click', function(){

			if ( glow.dom.get(this).hasClass("show") )
			{
				// Close the accordian
					// Update the class
					glow.dom.get(this).removeClass("show");
					// Hide any flash video inside the accordian
					glow.dom.get(this).parent().parent().get('div.le-emp').css('display', 'none');
					// Set the height of the promo using an animation
					glow.anim.css(
						glow.dom.get(this).parent().parent(), 
						0.75,
						{
							"height" : {to: 37}
						},
						{tween:glow.tweens.bounceOut()}
					).start();
			}
			else
			{
				// Open the accordian
					// Update the class
					glow.dom.get(this).addClass("show");
					// Prepare to set the height of the promo using an animation
					var accordian_height = (glow.dom.get(this).parent().parent().children().height());
					var myAnim = glow.anim.css(
						glow.dom.get(this).parent().parent(), 
						0.75,
						{
							"height" : {to: accordian_height }
						},
						{tween:glow.tweens.bounceOut()}
					);
					// When the animation has ran tidy up the height of the promo by setting it to 'auto'
					var obj = glow.dom.get(this).parent().parent();
					glow.events.addListener(myAnim, "complete", function(){
						// Show any flash video inside the accordian
						glow.dom.get(this).css('display', 'block');
						obj.css("height", "auto");

					}, glow.dom.get(this).parent().parent().get('div.le-emp'));
					// State the animation
					myAnim.start();
			}

		});

		// Finally, add the 'show' class to the promo to give it a default position ('open')
		glow.dom.get(arrH2Emphasized[i]).addClass("show");


	});
	
	
	/* TODO:
		add script to create reflection effect on image lists
	*/
	
	
	// ****
	// Tabs
	// ****
	
	//reference to all theme links in page
	var themes = glow.dom.get("div.theme ul li a");
	
	//add onclick events to all theme links in page
	var changeTheme = glow.events.addListener(
		themes,
		'click',
		function () { 	  	
			var moduleId = glow.dom.get(this).parent().parent().parent().parent().parent().parent().attr('id');
			var currentContainer = glow.dom.get('#' + moduleId).get('.showcontainer');
			var currentTheme = glow.dom.get(currentContainer).attr('id');
			var currentLi = glow.dom.get('#' + moduleId).get('.currenttheme');
			var newTheme = glow.dom.get(this).attr('href').substring(glow.dom.get(this).attr('href').indexOf('=')+1);
			var newContainer = glow.dom.get('#' + moduleId).get('#' + newTheme);
			var newLi = glow.dom.get(this).parent();
			//remove class from current container and add it to new container
			glow.dom.get(currentContainer).removeClass("showcontainer");
			glow.dom.get(newContainer).addClass("showcontainer");
			//remove class from current theme link and add it to new theme link
			glow.dom.get(currentLi).removeClass("currenttheme");
			glow.dom.get(newLi).addClass("currenttheme");
			//select first tab in new container
			var newContainerContent = glow.dom.get(newContainer).children();
			newContainerContent.removeClass('currenttab');
			glow.dom.get(newContainer.get("div.tabcontent")[0]).addClass("currenttab");		

			// update preferences for current module
			tabPrefs.setPrefs(moduleId,newTheme,1);
			
			return false;
		}
    );
	
	// initilise module preferences (retrieved from cookie)
	tabPrefs.init();
	
	var modules = glow.dom.get("div.theme");
	for (var i=0; i<modules.length; i++) {
		var moduleId = glow.dom.get(modules[i]).parent().parent().parent().attr('id');		
		var selectTheme = tabPrefs.getTheme(moduleId);
		var newContainer = glow.dom.get('#' + moduleId).get('#' + selectTheme);

		// if a theme was stored for this module switch to it
		if (selectTheme && (newContainer.attr('id') == selectTheme)) { // as the same cookie might have been used on a page higher up in the path we check if the stored theme actually exists in this module
			var currentContainer = glow.dom.get('#' + moduleId).get('.showcontainer');
			var currentLi = glow.dom.get('#' + moduleId).get('.currenttheme');

			var newLi;
			var moduleLinks = glow.dom.get(modules[i]).get('ul li a');
			for (var h=0; h<moduleLinks.length; h++) {
				var moduleLink = glow.dom.get(moduleLinks[h]);
				if (moduleLink.attr('href').match(selectTheme)) {
					newLi = moduleLink.parent();
				}
			}
			//remove class from current container and add it to new container
			glow.dom.get(currentContainer).removeClass("showcontainer");
			glow.dom.get(newContainer).addClass("showcontainer");
			//remove class from current theme link and add it to new theme link
			glow.dom.get(currentLi).removeClass("currenttheme");
			glow.dom.get(newLi).addClass("currenttheme");
		}
	}
	
	//reference all tabcontent headings and tab containers in page and initialize stacking
	var allTabHeadings = glow.dom.get("div.tabcontent div h3");
	var allTabsContainers = glow.dom.get("div.tabscontainer");
	stack_tabs(allTabHeadings,allTabsContainers);

});



/* Stack the tabs, run on page load and after each theme change */
function stack_tabs(tabHeadings,tabsContainers)
{
	//initialise identified tab headings by swapping text with shorter title
	for (var i=0; i<tabHeadings.length; i++){
		var heading = glow.dom.get(tabHeadings[i]);
		var h2Text = heading.text();
		var h2Title = heading.attr("title");
		heading.html("<span>" + h2Title + "</span>");
		heading.attr("title", h2Text);
	}
	//initialised identified tab sets by adding suitable classes where needed to indicate which tab is current (adapt for cookie)
	for (var i=0; i<tabsContainers.length; i++){	
		var tc = glow.dom.get(tabsContainers[i]);
		
		// get tab number stored for current module
		var moduleId = tc.parent().parent().parent().attr('id');
		var theme = tc.attr('id');
		var selectTab = tabPrefs.getTab(moduleId,theme);

		tc.addClass("show-tab"+ selectTab);
		glow.dom.get(tc.get("div.tabcontent")[selectTab - 1]).addClass("currenttab");		
	}
	//add onclick events to identified tab headings, to move currenttab class and change show-tab? class on container
	var showTab = glow.events.addListener(
		tabHeadings,
		'click',
		function () {
			var tabsContainer = glow.dom.get(this).parent().parent().parent();
			var tabContent = glow.dom.get(this).parent().parent();
			var allContent = glow.dom.get(tabsContainer).children();
			allContent.removeClass('currenttab');
			tabContent.addClass('currenttab');
			var tabNumber = tabContent.attr('class').match('[0-9]');
			var oldTabClass = '' + tabsContainer.attr('class').match('show-tab[0-9]'); //array converted to string
			var newTabClass = 'show-tab' + tabNumber; //array converted to string
			tabsContainer.removeClass(oldTabClass).addClass(newTabClass);
			
			// store tab number for current theme and module
			var moduleId = tabsContainer.parent().parent().parent().attr('id');
			var theme = tabsContainer.attr('id');
			tabPrefs.setPrefs(moduleId,theme,tabNumber);
			
			return false;
		}
    );
}

// mk
var tabPrefs = {
	prefs: {},
	cookieName: 'lePtTabs',
	cookieExpiryDays: 365,  // number of days cookie will be stored
	// retrieves cookie and stores in prefs object
	init: function() {
		var cookieData = this.readCookie(this.cookieName);
		if (cookieData) this.prefs = cookieData;
	},
	// modifies prefs object and stores values in cookie
	setPrefs: function(moduleId, theme, tab) {
		this.prefs[moduleId+'_th'] = theme;
		this.prefs[moduleId+'_ta'] = tab;
		this.storeCookie('lePtTabs', this.prefs);
	},
	// get stored theme for supplied module
	getTheme: function(moduleId) {
		if (this.prefs[moduleId+'_th']) {
			return this.prefs[moduleId+'_th'];
		} else {
			return false;
		}
	},
	// get stored tab for supplied theme and module
	getTab: function(moduleId, theme) {
		if ((this.prefs[moduleId+'_th'] == theme) && this.prefs[moduleId+'_ta']) {
			return this.prefs[moduleId+'_ta'];
		} else {
			return 1;
		}
	},
	// store the cookie string from object supplied
	storeCookie: function(name,prefs) {
		// generate date when cookie will expire
		var date = new Date();
		date.setTime(date.getTime()+(this.cookieExpiryDays*24*60*60*1000));

		// get the url of the page and extract the path
		var pathname = window.location.pathname;
    	path = pathname.substring (0, pathname.lastIndexOf ('/')+1)

		// get cookie string from data object
		var cookieValue = escape(glow.data.encodeUrl(prefs));
		
		// store the cookie
		document.cookie = this.cookieName+"="+cookieValue+"; expires="+date.toGMTString()+"; domain=bbc.co.uk; path="+path;
	},
	// read the cookie and return object
	readCookie: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return glow.data.decodeUrl(unescape(c.substring(nameEQ.length,c.length)));
		}
		return null;
	}
}

/* Opens a popup window for 'additional link' objects in the promo */
function popup(url, height, width)
{
	newwindow = window.open(url, '_new','height='+height+',width='+width+',resizable=yes,scrollbars=yes');
	if (window.focus) newwindow.focus();
	return false;
}

/* Swaps shared EMP player between videos */
function reload(playlist_url, text, title)
{
	if (document.getElementById("clip-promo-emp-player"))
	{
		var emp = new bbc.Emp();
		emp.setWidth("256");
		emp.setHeight("179");
		emp.setDomId("clip-promo-emp-player");
		emp.set("config_settings_autoPlay", "true"); 
		emp.setPlaylist(playlist_url);
		emp.write();
		glow.dom.get('div#clip-promo-emp h4').html(title);
		glow.dom.get('div#clip-promo-emp p').html(text);
		return false;
	}
}

/* Works out what dimensions an EMP should be based on what the id is. */
function choose_dimensions(id, dimension)
{
	if (dimension == "width") { if (id == "main-promo-emp-player") { return 448; } else { return 256; } }
	if (dimension == "height") { if (id == "main-promo-emp-player") { return 287; } else { return 179; } }
}