/*
ABC News common scripts
Created by: Andrew Kesper, October 2006
Modified by: Andrew Kesper, April 2008
*/

news = true; // News livery
if (!getQueryStringVariable('site').match(/^(news)?$/)) news = false; // one-story-many-views


/************* NEW FUNCTIONS ***************/
// Add new string functions
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
String.prototype.toTitleCase = function() { 
	var ls = this.toLowerCase();
	var la = ls.split(' ');
	for (var i=0; i<la.length; i++) la[i] = la[i].charAt(0).toUpperCase()+la[i].slice(1);
	return la.join(' ');
}

// Add encodeURIComponent and decodeURIComponent capability for old browsers (e.g. Win IE 5.0, Mac IE 5.x). Uses escape/unescape and converts '+' to/from '%2B'
if (!window.encodeURIComponent) encodeURIComponent = function (s) { return escape(s).replace(/\+/, '%2B'); };
if (!window.decodeURIComponent) decodeURIComponent = function (s) { return unescape(s.replace(/%2B/, '+')); };

// Native XMLHttpRequest (AJAX) object for IE
if (!window.XMLHttpRequest && window.ActiveXObject) {
	window.XMLHttpRequest = function() {
		try { return new ActiveXObject('Microsoft.XMLHTTP'); } 
		catch (e) { }
		return null;
	};
}

// Andrew's version of getElementsByTagName that supports an XML namespace prefix
// Example usage: getElementsByTagNameScope(document, 'media', 'content')
function getElementsByTagNameScope (xmlelement, scope, localname) {
	// Works in IE and FF3:
	var output = xmlelement.getElementsByTagName(scope+':'+localname);
	if (output.length > 0) return output;
	// If no elements were found, try this alternative method instead...
	// Works in Firefox 2, Safari, Opera:
	output = new Array();
	var temp = xmlelement.getElementsByTagName(localname);
	for (var i=0; i<temp.length; i++) {
		if (temp[i].prefix == scope) output[output.length] = temp[i];
	}
	return output;
}

// Andrew's version of getElementsByClassName that supports older browsers
// Example usage: getElementsByClassNameAK(document, 'section')
function getElementsByClassNameAK (elem, theClass) {
	if (typeof document.getElementsByClassName != 'undefined') return elem.getElementsByClassName(theClass);
	var e = elem.getElementsByTagName('*');
	var e2 = new Array();
	for (var i=0; i<e.length; i++) {
		if (classExists(e[i], theClass)) e2[e2.length] = e[i];
	}
	return e2;
}

function addLoadEvent (func) { // Source: http://simon.incutio.com/archive/2004/05/26/addLoadEvent
	var oldonload = window.onload;
	if (typeof window.onload != 'function') window.onload = func;
	else {
		window.onload = function() {
			if (oldonload) oldonload();
			func();
		}
	}
}

// Run the onload event now instead of when the page has fully finished loading
function runLoadEvent () {
	window.onload();
	window.onload = function () {};
}

// Add a CSS class to the specified element (will not add the class if it already exists)
function classAdd (element, theclass) {
	if (!element) return;
	if (!element.className) element.className = '';
	var reg = new RegExp('(^| )'+theclass+'( |$)', 'g');
	if (element.className.search(reg) == -1) element.className = (element.className + ' ' + theclass).trim();
}

// Remove a CSS class from the specified element
function classRemove (element, theclass) {
	if (!element) return;
	if (!element.className) return;
	var reg = new RegExp('(^| )'+theclass+'( |$)', 'g');
	element.className = element.className.replace(reg, ' ').trim();
}

// Return true if a class name exists in the specified element
function classExists (element, theclass) {
	if (!element) return false;
	if (!element.className) return false;
	var reg = new RegExp('(^| )'+theclass+'( |$)', 'g');
	return reg.test(element.className);
}



// Return query string variable, or an empty string if it doesn't exist
// Example: getQueryStringVariable('latitude', 'lat') returns value of 'latitide', if that doesn't exist, returns value of 'lat', if that doesn't exist, returns an empty string
function getQueryStringVariable () {
	var query = window.location.search.substring(1);
	var vars = query.split('&');
	for (var i=0; i<getQueryStringVariable.arguments.length; i++) {
		for (var j=0; j<vars.length; j++) {
			var pair = vars[j].split('=');
			if (pair[0] == getQueryStringVariable.arguments[i]) return decodeURIComponent(pair[1]);
		}
	}
	return '';
}



// Based on code from http://microformats.org/wiki/rest/ahah
function simpleAjax(url, target, onsuccess) {
	if (typeof target == 'string') target = document.getElementById(target);
	url += (url.indexOf('?') == -1 ? '?' : '&') + Math.floor(new Date().getTime()/(1000*60*2)); // ensures fresh request every 2 minutes
	req = new XMLHttpRequest();
	if (req) {
		classAdd(target, 'ajaxLoading');
		req.onreadystatechange = function() {
			if (req.readyState == 4) { // only if req is "loaded"
				if (req.status == 200 || req.status == 304) { // only if "OK"
					if (req.responseText != '') {
						classAdd(target, 'ajaxRendering');
						target.innerHTML = req.responseText;
						if (typeof onsuccess == 'function') onsuccess();
						else if (typeof onsuccess == 'string') eval(onsuccess);
						classRemove(target, 'ajaxRendering');
					}
				}
				else { // HTTP error
					target.innerHTML = '<!-- Error loading '+url+' -->';
				}
				processLinks();
				processImages();
				classRemove(target, 'ajaxLoading');
			}
		};
		req.open('GET', url, true);
		req.send('');
	}
}

// Load content into target container when tab is clicked
function tabLoad (tabLink, target, url, onsuccess) {
	if (typeof target == 'string') target = document.getElementById(target);
	setClassUnsetSiblings(tabLink.parentNode, 'active');
	simpleAjax(url, target, onsuccess);
	if (tabLink.blur) tabLink.blur(); // removes dotted outline from link in Mozilla browsers
	return false;
}

function stateTabLoad (state) { // for state headlines on news home page
	tabLoad(document.getElementById('t-'+state), 'stateContent', '/news/indexes/idx-'+state+'/top3.inc', copyFitStateHeadlines);
	preferenceSet('state', state);
	return false;
}

function copyFitStateHeadlines () {
	copyfit('topstory', 'topstories', document.getElementById('stateContent').getElementsByTagName('UL')[0], 3);
}

// copyfit: Get heights of 'columnA' and 'columnB' as close as possible by removing items from 'list' (however 'list' will always have at least 'stopAt' number of items)
function copyfit (columnA, columnB, list, stopAt) {
	if (typeof columnA == 'string') columnA = document.getElementById(columnA);
	if (typeof columnB == 'string') columnB = document.getElementById(columnB);
	if (typeof list == 'string') list = document.getElementById(list);
	if (typeof list == 'undefined') var list = columnA.parentNode.getElementsByTagName('UL')[0];
	if (typeof stopAt == 'undefined') var stopAt = 3;
	if (columnA && columnB && list) {
		if (contains(columnA, list)) {
			var listColumn = columnA;
			var otherColumn = columnB;
		}
		else if (contains(columnB, list)) {
			var listColumn = columnB;
			var otherColumn = columnA;
		}
		else return; // list sits outside both columns - abort
		var items = new Array();
		for (var i=0; i<list.childNodes.length; i++) if (list.childNodes[i].nodeType == 1) items[items.length] = list.childNodes[i];
		var numTotal = items.length;
		var numVisible = numTotal+0;
		var done = false;
		while (!done) {
			if (numVisible <= stopAt) done = true;
			else {
				var lastVisibleItemHeight = items[numVisible-1].scrollHeight;
				var differenceNow = listColumn.scrollHeight-otherColumn.scrollHeight;
				var differenceNext = differenceNow-lastVisibleItemHeight;
				if (Math.abs(differenceNext) < Math.abs(differenceNow)) { // if removing another item makes listColumn closer in height to otherColumn
					items[numVisible-1].style.display = 'none';
					numVisible--;
				}
				else done = true;
			}
		}
		for (var i=numVisible; i>0; i--) items[numVisible-1].style.display = 'block';
	}
}

// Finds out if 'a' is an ancestor of 'b'
function contains (a, b) {
	// climb through 'b' parents till we find 'a'
 	while (b && (a != b) && (b != null)) b = b.parentNode;
	return a == b;
}

/************ MISCELLANEOUS FUNCTIONS **************/

// Give focus to the first text/textarea form element in the document
function formFocus () {
	var inputs = document.getElementsByTagName('INPUT');
	for (var i=0; i<inputs.length; i++) {
		if (inputs[i].type == 'text') {
			inputs[i].focus();
			return;
		}
	}
	inputs = document.getElementsByTagName('TEXTAREA');
	if (inputs.length > 0) inputs[0].focus();
}

function thumnbailScrollerGenerate (containerid) {
	var container;
	var colnames = new Array('column5a','column5b','column5c','column5d','column5e');
	if (container = document.getElementById(containerid)) {
		if (!window.highlightScroller) highlightScroller = new Object();
		var controls = document.createElement('DIV');
		controls.id = containerid+'_controls';
		controls.className = 'highlightscrollercontrols';
		var temp = container.childNodes;
		var divs = new Array();
		for (var i=0; i<temp.length; i++) {
			if (classExists(temp[i], 'headline') || classExists(temp[i], 'section')) { // check that class name is 'section' or 'headline'
				divs[divs.length] = temp[i];
			}
		}
		delete temp;
		var aprev = document.createElement('A');
		aprev.id = containerid+'_show_prev';
		aprev.className = 'prev';
		aprev.href = 'javascript:highlightScrollerMoveBy("'+containerid+'", -1);';
		aprev.onclick = function (f) {
			eval(this.href.replace(/^javascript:/, ''));
			return false;
		};
		var aprevimg = document.createElement('IMG');
		aprevimg.src = '/news/img/2007/blank.gif';
		aprevimg.width = 26;
		aprevimg.height = 16;
		aprev.appendChild(aprevimg);
		if (divs.length > 5) controls.appendChild(aprev);
		for (var i=0; i<divs.length; i+=5) {
			var num = (i/5);
			highlightScroller[containerid+'_length'] = num+1;
			var columns = document.createElement('DIV');
			columns.className = 'columns';
			columns.id = containerid+'_'+num;
			for (var j=0; j<5; j++) {
				if (divs[i+j]) {
					var newcolumn = document.createElement('DIV');
					newcolumn.className = colnames[j];
					newcolumn.appendChild(divs[i+j]);
					columns.appendChild(newcolumn);
				}
			}
			container.appendChild(columns);
			var a = document.createElement('A');
			a.id = containerid+'_show_'+num;
			a.href = 'javascript:highlightScrollerMoveTo("'+containerid+'", '+num+');';
			a.onclick = function (f) {
				eval(this.href.replace(/^javascript:/, ''));
				return false;
			};
			var aimg = document.createElement('IMG');
			aimg.src = '/news/img/2007/blank.gif';
			aimg.width = 16;
			aimg.height = 16;
			a.appendChild(aimg);
			if (divs.length > 5) controls.appendChild(a);
		}
		var anext = document.createElement('A');
		anext.id = containerid+'_show_next';
		anext.className = 'next';
		anext.href = 'javascript:highlightScrollerMoveBy("'+containerid+'", 1);';
		anext.onclick = function (f) {
			eval(this.href.replace(/^javascript:/, ''));
			return false;
		};
		var anextimg = document.createElement('IMG');
		anextimg.src = '/news/img/2007/blank.gif';
		anextimg.width = 26;
		anextimg.height = 16;
		anext.appendChild(anextimg);
		if (divs.length > 5) controls.appendChild(anext);
		container.parentNode.insertBefore(controls, container.nextSibling);
		highlightScrollerMoveTo(containerid, 0);
	}
}

// Generate a scrollable feature thingy
function highlightScrollerGenerate (containerid) {
	var container;
	if (container = document.getElementById(containerid)) {
		if (classExists(container, 'thumbnailscroller')) {
			thumnbailScrollerGenerate(containerid);
			return;
		}
		if (!window.highlightScroller) highlightScroller = new Object();
		var controls = document.createElement('DIV');
		controls.id = containerid+'_controls';
		controls.className = 'highlightscrollercontrols';
		var temp = container.childNodes;
		var divs = new Array();
		for (var i=0; i<temp.length; i++) {
			if (temp[i].tagName && temp[i].tagName.toLowerCase() == 'div' && (classExists(temp[i], 'headline') || classExists(temp[i], 'section'))) { // check that class name is 'section' or 'headline'
				divs[divs.length] = temp[i];
			}
		}
		delete temp;
		var aprev = document.createElement('A');
		aprev.id = containerid+'_show_prev';
		aprev.className = 'prev';
		aprev.href = 'javascript:highlightScrollerMoveBy("'+containerid+'", -1);';
		aprev.onclick = function (f) {
			eval(this.href.replace(/^javascript:/, ''));
			return false;
		};
		var aprevimg = document.createElement('IMG');
		aprevimg.src = '/news/img/2007/blank.gif';
		aprevimg.width = 26;
		aprevimg.height = 16;
		aprev.appendChild(aprevimg);
		if (divs.length > 2) controls.appendChild(aprev);
		for (var i=0; i<divs.length; i+=2) {
			var num = (i/2);
			highlightScroller[containerid+'_length'] = num+1;
			var columns = document.createElement('DIV');
			columns.className = 'columns';
			columns.id = containerid+'_'+num;
			var column2a = document.createElement('DIV');
			column2a.className = 'column2a';
			column2a.appendChild(divs[i]);
			columns.appendChild(column2a);
			if (divs[i+1]) {
				var column2b = document.createElement('DIV');
				column2b.className = 'column2b';
				column2b.appendChild(divs[i+1]);
				columns.appendChild(column2b);
			}
			container.appendChild(columns);
			var a = document.createElement('A');
			a.id = containerid+'_show_'+num;
			a.href = 'javascript:highlightScrollerMoveTo("'+containerid+'", '+num+');';
			a.onclick = function (f) {
				eval(this.href.replace(/^javascript:/, ''));
				return false;
			};
			var aimg = document.createElement('IMG');
			aimg.src = '/news/img/2007/blank.gif';
			aimg.width = 16;
			aimg.height = 16;
			a.appendChild(aimg);
			if (divs.length > 2) controls.appendChild(a);
		}
		var anext = document.createElement('A');
		anext.id = containerid+'_show_next';
		anext.className = 'next';
		anext.href = 'javascript:highlightScrollerMoveBy("'+containerid+'", 1);';
		anext.onclick = function (f) {
			eval(this.href.replace(/^javascript:/, ''));
			return false;
		};
		var anextimg = document.createElement('IMG');
		anextimg.src = '/news/img/2007/blank.gif';
		anextimg.width = 26;
		anextimg.height = 16;
		anext.appendChild(anextimg);
		if (divs.length > 2) controls.appendChild(anext);
		container.parentNode.insertBefore(controls, container.nextSibling);
		highlightScrollerMoveTo(containerid, 0);
	}
}

function highlightScrollerMoveTo (containerid, num) {
	highlightScroller[containerid+'_current'] = num;
	displayThisHideSiblings(containerid+'_'+highlightScroller[containerid+'_current']);
	setClassUnsetSiblings(containerid+'_show_'+highlightScroller[containerid+'_current'], 'active');
}

function highlightScrollerMoveBy (containerid, num) {
	highlightScroller[containerid+'_current'] += num;
	if (highlightScroller[containerid+'_current'] >= highlightScroller[containerid+'_length']) highlightScroller[containerid+'_current'] -= highlightScroller[containerid+'_length'];
	else if (highlightScroller[containerid+'_current'] < 0) highlightScroller[containerid+'_current'] += highlightScroller[containerid+'_length'];
	displayThisHideSiblings(containerid+'_'+highlightScroller[containerid+'_current']);
	setClassUnsetSiblings(containerid+'_show_'+highlightScroller[containerid+'_current'], 'active');
}

function displayThisHideSiblings (element) { // 'element' can be a DOM element or a string representing the ID of a DOM element
	if (typeof element == 'undefined') return;
	if (typeof element == 'string') element = document.getElementById(element);
	var x = element.previousSibling;
	while (x != null) {
		if (x.nodeType == 1) x.style.display = 'none';
		x = x.previousSibling;
	}
	x = element.nextSibling;
	while (x != null) {
		if (x.nodeType == 1) x.style.display = 'none';
		x = x.nextSibling;
	}
	element.style.display = 'block';
}

function setClassUnsetSiblings (element, theclass) { // 'element' can be a DOM element or a string representing the ID of a DOM element
	if (element == null) return;
	if (typeof element == 'undefined') return;
	if (typeof element == 'string') {
		if (document.getElementById(element)) element = document.getElementById(element);
		else return;
	}
	var x = element.previousSibling;
	while (x != null) {
		classRemove(x, theclass);
		x = x.previousSibling;
	}
	x = element.nextSibling;
	while (x != null) {
		classRemove(x, theclass);
		x = x.nextSibling;
	}
	classAdd(element, theclass);
}

// Open link in a popup window
function popup (url, width, height, windowname) {
	if (!width) var width = 600;
	if (!height) var height = 400;
	if (!windowname) var windowname = 'abcnewspopup'+new Date().getTime();
	if (url.indexOf('?') != -1) url += '&layout=popup';	else url += '?layout=popup';
	var left = screen.width/2 - width/2;
	var top = screen.height/2 - height/2;
	window.open(url, windowname, 'width='+width+',height='+height+',toolbar=0,resizable=1,scrollbars=1,left='+left+',top='+top);
	return false;
}

/************ NEWSRADIO WIDGET FUNCTIONS **************/
function nrInit () {
	if (nr = document.getElementById('newsradio-widget-nowplaying')) {
		nrText = nr.innerHTML.replace(/<[^>]+>/g, '').trim(); // original text, HTML tags removed
		nr.innerHTML = nrText;
		if (nr.scrollWidth > nr.clientWidth) { // if the text is longer than the space allocated for it
			nrOn = false; // ticker enabled?
			nrRev = false; // reverse direction?
			nrSubstr = 0; // character position to display text from
			nr.onmouseover = function () {
				if (!nrOn) {
					nrOn = true;
					nrGo();
				}
			};
			nr.onmouseout = function () {
				nrStop();
			};
		}
	}
}
function nrGo() {
	var nrChange = false; // change direction?
	if (nrRev) {
		if (nrSubstr == 0) nrChange = true; // if start of text is visible
		else nrSubstr--;
	}
	else {
		if (nr.scrollWidth <= nr.clientWidth) nrChange = true; // if end of text is visible
		else nrSubstr++;
	}
	if (nrChange) {
		nrRev = !nrRev;
		nrTimeout = setTimeout('nrGo();', 2000);
	}
	else {
		//nr.innerHTML = nrText.substr(nrSubstr).replace(/ +/, '&nbsp;');
		nr.style.textIndent = '-'+(nrSubstr)+'px';
		nrTimeout = setTimeout('nrGo();', 30);
	}
}
function nrStop() {
	clearTimeout(nrTimeout);
	//nr.innerHTML = nrText;
	nr.style.textIndent = '0';
	nrOn = false;
	nrRev = false;
	nrSubstr = 0;
}
if (news) addLoadEvent(nrInit);




function setActiveNav () {
	if (document.getElementById('nav_1st') && document.getElementById('nav_2nd')) {
		if (typeof activenav == 'string') setClassUnsetSiblings(document.getElementById('n-'+activenav), 'active');
		else if (getQueryStringVariable('section') != '') {
			setClassUnsetSiblings(document.getElementById('n-'+getQueryStringVariable('section')), 'active');
		}
		else if (window.location.pathname == '/news/' || window.location.pathname == '/news/default.htm') setClassUnsetSiblings(document.getElementById('n-newshome'), 'active');
		else {
			var sections = new Array('justin','australia','world','business','sport','entertainment','weather','opinion','blogs','video','audio','photos','feeds','alerts');
			for (var i=0; i<sections.length; i++) {
				if (window.location.pathname.indexOf('/news/'+sections[i]+'/') == 0) {
					setClassUnsetSiblings(document.getElementById('n-'+sections[i]), 'active');
					return;
				}
			}
		}
	}
}

function loadCSS (url, media) {
	var link = document.createElement('LINK');
	link.rel = 'stylesheet';
	link.type = 'text/css';
	link.href = url;
	if (typeof media != 'undefined') link.media = media;
	document.getElementsByTagName('HEAD')[0].appendChild(link);
}

function loadJS (url) {
	var s = document.createElement('SCRIPT');
	s.type = 'text/javascript';
	s.src = url;
	document.getElementsByTagName('HEAD')[0].appendChild(s);
}

