/* quirksmode cookie funcs */
function createCookie(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+"; domain=.bbc.co.uk; path=/radio/";
}

function readCookie(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 c.substring(nameEQ.length,c.length);
	}
	return null;
}

if (glow.isSupported == true) {
	// add a generic "hook" to html tag for enabled page:
	if (typeof document.documentElement.className == "string") {
		document.documentElement.className += " glow-enabled";
	} else {
		document.documentElement.className = "glow-enabled";
	}
}

// keypress event catcher (aimed specifically at a TAB key)
function handleKeyPress(e) {
	if (!e) e = window.event;
	if (e && e.keyCode == 9) {
		return true;
	} else {
		return false;	
	}
}

// listen live popup window function
window.name="main";
function aodpopup(URL) {
	var x = 512;
	var y = 270;
	window.open(URL,'aod','width=' + x + ',height=' + y + ',toolbar=no,personalbar=no,location=no,directories=no,statusbar=no,menubar=no,status=no,resizable=yes,left=60,screenX=60,top=100,screenY=100');
}
if (location.search.substring(1) == "focuswin") {
	window.focus();
}

/* preload tabs image as it's big... */
var tabLoad = new Image();
tabLoad.src = "/radio/images/home/r-home-tabs-sprite.gif";

glow.ready(function() {
	
	// initial selection of radio station (if no cookie then create random panel)	
	var cook = readCookie('BBCRadioHome');
	if (cook) {
		var el = glow.dom.get("#" + cook);
		var tabEl = glow.dom.get("#t-" + cook);
	} else {
		var listEl = glow.dom.get("#stations-list li a");
		var rand = Math.floor(Math.random() * listEl.length);
		var el = glow.dom.get("#radio-home-stations div.blq-clearfix")[rand];
		var tabEl = glow.dom.get(listEl)[rand];
	}
	// now set appropriate "selected" classes:
	glow.dom.get(el).addClass("selected");
	glow.dom.get(tabEl).addClass("selected");
	
	function switchMainPanel(obj) {
		// loop through and attach selected class to appropriate tab:
		glow.dom.get("#stations-list li a").each(function () {
			if (glow.dom.get(this).attr("id") == "t-" + obj) {
				glow.dom.get(this).addClass("selected");	
			} else {
				glow.dom.get(this).removeClass("selected");
			}
		});
		// remove "selected" class from all panel elements
		glow.dom.get("#radio-home-stations div.blq-clearfix").removeClass("selected");
		// attch it to the panel with the obj id ref:
		glow.dom.get("#" + obj).addClass("selected");
	}
	
	// Panels - click and keyboard handling:
	
	// Add a "shift" key listener to check for backwards tabbing
	var shiftOn = false;
	glow.events.addKeyListener("SHIFT", "down", function () {
		shiftOn = true;
	});
	glow.events.addKeyListener("SHIFT", "up", function () {
		shiftOn = false;
	});
	
	// adding click and key controls to each tab
	glow.dom.get("#stations-list li a").each(function () {
		var myId = glow.dom.get(this).attr('id');
		var ident = myId.substring(2, myId.length);
		glow.events.addListener(this, 'click', function () {
			// make sure focus is set upon a click event
			this.focus();
			switchMainPanel(ident);
			return false;	
		});
		// the key event for a tab checks to see if the tab is "selected", if it is, then tab focus is set to the panel's logo
		if (myId != "t-r-ws") {
			glow.events.addListener(this, 'keydown', function (event) {
				if (handleKeyPress(event) == true) {
					if (glow.dom.get(this).hasClass("selected") && shiftOn == false) {
						// set focus to panel
						glow.dom.get("#" + ident + " .identity h2 a")[0].focus();	
						return false;	
					}
				}
			});
		} else {
			// last-link in tabs is World Service - if it's not selected a tab should send the user to the Podcasts panel
			glow.events.addListener(this, 'keydown', function (event) {
				if (handleKeyPress(event) == true) {
					if (glow.dom.get(this).hasClass("selected") && shiftOn == false) {
						// set focus to panel
						glow.dom.get("#" + ident + " .identity h2 a")[0].focus();
						return false;
					} else if (shiftOn == false) {
						if (glow.dom.get("#latest-podcasts h2 a")[0]){
							glow.dom.get("#latest-podcasts h2 a")[0].focus();
							return false;
						} else {
							glow.dom.get("#radio-home-help li.firstChild a")[0].focus();
							return false;
						}
					}
				}
			});
		}
	});
	
	// focus control on panels:
	glow.dom.get("#radio-home-stations div.blq-clearfix").each(function () {
		// get the id of the panel
		var myId = glow.dom.get(this).attr("id");
		// get the <a> tags:
		var els = glow.dom.get(this).get("a");
		// get the firstChild <a> tag
		var firstChild = els[0];
		// handle *backwards* keydown events on the first child link
		glow.events.addListener(firstChild, 'keydown', function (event) {
			if (handleKeyPress(event) == true && shiftOn == true) {
				// set focus to the parent tab
				glow.dom.get("#stations-list li a.selected")[0].focus();
				return false;
			}
		});
		// last-link in tab handling - should send the tabber to the tabs menu once more. Does NOT apply to a tab out of World Service (the last panel in source order)
		if (myId != "r-ws") {
			// get the last <a> tag
			var lastChild = els[els.length-1];
			glow.events.addListener(lastChild, 'keydown', function (event) {
				if (handleKeyPress(event) == true && shiftOn == false) {
					// set focus to the next tab <a> along from the selected tab
					glow.dom.get("#stations-list li a.selected").parent().next().children()[0].focus();
					return false;
				}
			});
		}
	});
	
	// special *backwards* handling for the Podcasts title link - sends focus to World Service tab if it's NOT selected (if it is selected, tab order is normal)
	if (glow.dom.get("#latest-podcasts h2 a")[0]){
		glow.events.addListener(glow.dom.get("#latest-podcasts h2 a")[0], 'keydown', function (event) {
			if (handleKeyPress(event) == true && shiftOn == true && !glow.dom.get("#t-r-ws").hasClass("selected")) {
				glow.dom.get("#t-r-ws")[0].focus();
				return false;
			}
		});
	} else {
		glow.events.addListener(glow.dom.get("#radio-home-help li.firstChild a")[0], 'keydown', function (event) {
			if (handleKeyPress(event) == true && shiftOn == true && !glow.dom.get("#t-r-ws").hasClass("selected")) {
				glow.dom.get("#t-r-ws")[0].focus();
				return false;
			}
		});
	};
	// speech dropdown
	var speechPanel = new glow.widgets.InfoPanel("#speech-menu", {
		context: "#speech",
		pointerPosition: "t",
		offsetInContext: {x: "50%", y: "80%"}
	});
	glow.events.addListener(
		'#speech',
		'click',
		function () {
			speechPanel.show();
			musicPanel.hide();
			azPanel.hide();
			return false;
		}
	);
	// music dropdown
	var musicPanel = new glow.widgets.InfoPanel("#music-menu", {
		context: "#music",
		pointerPosition: "t",
		offsetInContext: {x: "50%", y: "80%"}
	});
	glow.events.addListener(
		'#music',
		'click',
		function () {
			speechPanel.hide();
			musicPanel.show();
			azPanel.hide();
			return false;
		}
	);
	// a-z dropdown
	var azPanel = new glow.widgets.InfoPanel("#az-menu", {
		context: "#az",
		pointerPosition: "t",
		offsetInContext: {x: "50%", y: "80%"}
	});
	glow.events.addListener(
		'#az',
		'click',
		function () {
			speechPanel.hide();
			musicPanel.hide();
			azPanel.show();
			return false;
		}
	);
	
	// handle popup player links (these are the "listen now" links)
	glow.dom.get("#radio-home-stations div ol.schedule li.now a.cta").each(function() {
		glow.events.addListener(this, 'click', function () {
			var targ = glow.dom.get(this).attr("href");
			aodpopup(targ);
			return false;	
		});
	});
	
	// set unload event to drop cookie of selected panel:
	window.onunload = function() {
		var panelId = glow.dom.get("#radio-home-stations div.selected").attr("id");
		createCookie('BBCRadioHome',panelId,31);	// "rP" == radio panel id, set to 1 month currently
	}
});