
// created by: Geoff Pack, Feb 2008
// modified May 2010 - replaced suckerfish drop-downs with js (to add a delay)
// modified June 2010 - added code for new radio tab

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

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 expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

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;
}

function setLocation(location) {
	createCookie("local", location, 14);
}

// need to do this before onload event!
var abcLocal = readCookie("local");

function popIt(width, height) {
	if (width && height) {
		popup = window.open('', 'popup', 'width=' + width + ',height=' + height + ',,top=20,left=20,resizable=yes,status=no');
	 }
	else {
		popup = window.open('', 'popup', 'width=420,height=280,,top=20,left=20,resizable=yes,status=no');
	}
	popup.focus();
}



// ------------------------------------------------------------------
// Nav functions. Replaces suckerfish drop-downs 

var lastNav = null;	
var navTimer = null;

function addNavEvents() {
	// adds mouseover/mouseout triggers for (previous version of) navs
	var topNavs = (document.getElementById('mainNav')) ? document.getElementById('mainNav').childNodes : false;
	
	if (topNavs){
		for (nodeN in topNavs) {
			if (topNavs[nodeN].nodeType == 1) {
				topNavs[nodeN].onmouseover = function() {
					showSubMenu(this);
				}
				topNavs[nodeN].onmouseout = function() {
					hideSubMenu(this);
				}
			}
		}
	}
}


function showSubMenu(obj) {
	// show submenu if it exists
	if (obj && obj.firstChild && obj.firstChild.nextSibling) {
		//document.getElementById('testMsg').innerHTML = "obj.firstChild: " + obj.firstChild
		//+ "<br>obj.firstChild.nextSibling: " + obj.firstChild.nextSibling.id + ""
		//+ "<br>obj.firstChild.nextSibling.nextSibling: " + obj.firstChild.nextSibling.nextSibling.id + "";
		
		if (obj.firstChild.nextSibling.nodeType == 1) {
			obj.firstChild.nextSibling.style.display = 'block'; // IE
		} else if (obj.firstChild.nextSibling.nextSibling) {
			obj.firstChild.nextSibling.nextSibling.style.display = 'block'; // DOM
		}
	}
	// clear timeout
	clearTimeout(navTimer);

	// hide last Nav immediately (if not same as current nav)
	if (lastNav != obj) {
		hideNav();
	}
}

function hideSubMenu(obj) {
	lastNav = obj;
	navTimer = setTimeout('hideNav()',600);
}

function hideNav() {
	var obj = lastNav;

	// hide last submenu if it exists
	if (obj && obj.firstChild && obj.firstChild.nextSibling) {
		if (obj.firstChild.nextSibling.nodeType == 1) {
			obj.firstChild.nextSibling.style.display = 'none'; // IE
		} else if (obj.firstChild.nextSibling.nextSibling) {
			obj.firstChild.nextSibling.nextSibling.style.display = 'none'; // DOM
		}
	}		
}

// ------------------------------------------------------------------

// Show/Hide functions clean up later...
function show(id) {
	document.getElementById(id).style.display = 'block';
}
function hide(id) {
	document.getElementById(id).style.display = 'none';
}

// Scroller

function scroll(N, id, deltaX, backButton, nextButton) {
	var n = 1;
	var x1 = 0;
	this.N = N;
	var obj = document.getElementById(id);

	this.back = function() {
		n--;
		if (n < 1) n = 1;
		x2 = (1-n) * deltaX;
		//document.getElementById(id).style.marginLeft = x2 + 'px';
		moveIt(id,x1,x2);
		x1 = x2;
		
		// modify buttons
		if (backButton && nextButton) {
			classRemove(document.getElementById(backButton),'off');
			classRemove(document.getElementById(nextButton),'off');
			if (n == 1) {classAdd(document.getElementById(backButton),'off')};
		}
		
		return false;	
	}
	this.next = function() {
		n++;
		if (n > N) n = N;
		x2 = (1-n) * deltaX;
		//document.getElementById(id).style.marginLeft = x2 + 'px';
		moveIt(id,x1,x2);
		x1 = x2;
		
		// modify buttons
		if (backButton && nextButton) {
			classRemove(document.getElementById(backButton),'off');
			classRemove(document.getElementById(nextButton),'off');
			if (n == N) {classAdd(document.getElementById(nextButton),'off')};
		}
		
		return false;	
	}
	this.pos = function(X) {
		x2 = (1-X) * deltaX;		
		moveIt(id,x1,x2);
		x1 = x2;
		n=X;
	
		return false;		
	}
}

//var weather = new scroll(4,'weatherScroller',210,'weatherBack','weatherNext');
var weather = new scroll(4,'weatherScroller',220,null,null);
var bestof = new scroll(3,'bestOfScroller',330,'bestOfBack','bestOfNext');

var scrollTimer=new Array(); // timeouts for each object using these fns

function moveIt(id,x1,x2) {
    // clear other scrolls for this object
    if (scrollTimer[id]) clearTimeout(scrollTimer[id]);

	vx = 40; // pixels
	if (x2<x1) vx=-Math.abs(vx);
    x1+=vx;
 
    // test to see if reached destination
    if (vx<0) {if (x1<=x2) {x1=x2; vx=0;}}
    else {if (x1>=x2) {x1=x2; vx=0;}}	

	document.getElementById(id).style.marginLeft = x1 + 'px';	
	if (vx!=0) scrollTimer[id] = setTimeout("moveIt('"+id+"',"+x1+","+x2+")",20);
}


function createWeatherNav () {
	var scroller = document.getElementById("weatherScroller");
	var nav = document.getElementById("weatherNav");
	
	if (nav) {
		// nav is null if location not set...	
		nav.innerHTML = "";
		var dayName;
		
		// get all the days in the Weather scroller
		var N = scroller.childNodes.length;
		var j=0;
		
		for (var i=0; i<N; i++) {	
			// more childnodes than just the days, so ignore others
			if (scroller.childNodes[i].id) {
				j++;
	
				// find day names
				dayName = scroller.childNodes[i].childNodes[1].childNodes[0].nodeValue.substring(0,3);
				
				// write into weatherNav	
				nav.innerHTML += '<a href="#" onclick="return weather.pos('+j+')">' + dayName + '</a> ';
			}
		}
	}
}

function findiViewLinks() {
	// converts furtherInfo links to iView into buttons next to the header
	var links = document.getElementsByTagName('A');

	for (var i=0, j=links.length; i<j; i++) {
		var link = links[i];
		
		if (link.href.indexOf('/iview/#/') !=-1) {
			var li = link.parentNode;
			var ul = li.parentNode;
			var div = ul.parentNode;
			
			// write link before heading			
			var newNode = link.cloneNode(true);
			div.insertBefore(newNode,div.firstChild);

			// change text to image
			newNode.innerHTML = '<img class="iView_button" src="/homepage/2008/styles/iview_button.gif" alt="watch this on iView" height="21" width="75">';			
			
			// remove li from list
			ul.removeChild(li);
		}
	}
}

function findElectionLinks() {
	// removes 'Best of Election' links - if they are the child of a list item - and adds link and overlay to story image
	var links = document.getElementById('bestOfABC').getElementsByTagName('A'); // only links in BestofABC

	for (var i=0, j=links.length; i<j; i++) {
		var link = links[i];
		
		if (link && (link.href.indexOf('/bestof/election/') !=-1) && (link.parentNode.nodeName == 'LI')) {
			var li = link.parentNode;
			var ul = li.parentNode;
			ul.removeChild(li);

			 // n.b. main image is [0] only *before* iView button is written - so must find election links before looking for iView links
			var featureImg = ul.parentNode.getElementsByTagName('IMG')[0];
			featureImg.style.backgroundImage = 'url('+featureImg.src+')'; // make the feature image its own background	
			featureImg.style.backgroundPosition = 'center center';			
			featureImg.style.backgroundRepeat = 'no-repeat';			
			featureImg.src = '/bestof/styles/election_overlay.png'; // change image to election image
			
			if (/MSIE 6/i.test(navigator.userAgent)) {
				// IE6 requires image sizes to be re-specified
				//alert('IE6 !')
				featureImg.style.width = '125px';
				featureImg.style.height = '70px';
			}
			
			if (featureImg.parentNode.nodeName == 'A') {
				featureImg.parentNode.href = "/bestof/election/"; // add link to election page
			}
		}
	}
}

function showRadioTab(id) {
	if (id=='listen') {
		document.getElementById('listenTab').style.zIndex = '4'
		document.getElementById('listen').style.zIndex = '3';
		document.getElementById('podcastsTab').style.zIndex = '2'
		document.getElementById('podcasts').style.zIndex = '1';

		classAdd(document.getElementById('listenTab'),'front');
		classRemove(document.getElementById('podcastsTab'),'front');
	} else {
		document.getElementById('podcastsTab').style.zIndex = '4'
		document.getElementById('podcasts').style.zIndex = '3';
		document.getElementById('listenTab').style.zIndex = '2'
		document.getElementById('listen').style.zIndex = '1';

		classAdd(document.getElementById('podcastsTab'),'front');
		classRemove(document.getElementById('listenTab'),'front');
	}
	return false;
}

function showTempGauge() {
	// Add class to current temp to add thermometer image
	if (document.getElementById('currentTemp')) {
		var ctemp = parseInt((document.getElementById('currentTemp').innerHTML));
		//alert(ctemp);
		var thermo = document.getElementById('thermometerImg');
	
		if (ctemp < 1) {
			thermo.className = 'temp1';
		} else if (ctemp < 11 && ctemp > 0) {
			thermo.className = 'temp2';
		} else if (ctemp < 18 && ctemp > 10) {
			thermo.className = 'temp3';
		} else if (ctemp < 24 && ctemp > 17) {
			thermo.className = 'temp4';
		} else if (ctemp < 30 && ctemp > 23) {
			thermo.className = 'temp5';
		} else if (ctemp < 35 && ctemp > 29) {
			thermo.className = 'temp6';
		} else if (ctemp < 40 && ctemp > 34) {
			thermo.className = 'temp7';
		} else if (ctemp < 50 && ctemp > 39) {
			thermo.className = 'temp8';
		} else if (ctemp > 49) {
			thermo.className = 'temp9';
		}
	}
}

//addLoadEvent(createWeatherNav);
addLoadEvent(findElectionLinks);
addLoadEvent(findiViewLinks);
addLoadEvent(addNavEvents);
addLoadEvent(showTempGauge);
