/*
*/

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 (also works in IE)
// Example usage: getElementsByTagNameScope(document, 'media', 'content')
function getElementsByTagNameScope(xmlelement, scope, localname) {
	// IE version
	if (navigator.userAgent.indexOf('MSIE') != -1) { // can't use "if (document.all)" as it would also apply to Opera
		return xmlelement.getElementsByTagName(scope+':'+localname);
	}
	// Standards-compliant version
	var 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;
}

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 '';
}




/*************** PREFERENCES ****************/

// Set up out default preferences
preferences = new Array(); // An array of preference objects
preferences[preferences.length] = new Preference('connection', new Array('hi', 'lo'), 'hi');
preferences[preferences.length] = new Preference('video', new Array('inpage', 'wm', 'real'), 'inpage');
preferences[preferences.length] = new Preference('audio', new Array('inpage', 'wm', 'real', 'mp3'), 'inpage');
preferences[preferences.length] = new Preference('timestamp', new Array('relative', 'absolute', '24hour'), 'relative');
preferences[preferences.length] = new Preference('layout', new Array('fixed', 'liquid'), 'fixed');
preferences[preferences.length] = new Preference('state', new Array('nsw', 'vic', 'qld', 'wa', 'sa', 'tas', 'act', 'nt'), 'nsw');
preferences[preferences.length] = new Preference('homepagetab', new Array('topstories', 'justin', 'mostpopular'), 'topstories');
preferences[preferences.length] = new Preference('mapapi', new Array('google', 'yahoo', 'microsoft'), 'google');
preferences[preferences.length] = new Preference('glance', new Array('show', 'hide'), 'hide');


// Name of our preferences cookie
var preferencesCookie = 'newsPreferences';

// Definition of a preference object
function Preference (name, possibleValues, defaultValue) {
	this.name = name;
	this.possibleValues = possibleValues;
	this.defaultValue = defaultValue;
	this.value = preferenceGet(name); // The value stored in the cookie, or if there is none, the default value
}

// Get a preference value
function preferenceGet (name) {
	// Look in cookie
	var cookieData = getCookie(preferencesCookie);
	if (cookieData != null && cookieData != 'undefined' && cookieData != '') {
		var p = cookieData.split(';');
		for (var i=0; i<p.length; i++) {
			var x = p[i].split('~');
			if (x[0] == name) return x[1];
		}
	}
	// Can't find preference in cookie - now look in default preferences
	for (var i=0; i<preferences.length; i++) {
		if (preferences[i].name == name) return preferences[i].defaultValue;
	}
	// Looks like a non-existant preference has been requested
	return null;
}

/*************** PREFERENCES PANEL ****************/

function enablePreferences () {
	var n2;
	if (n2 = document.getElementById('nav_2nd')) {
		var pBtn = document.createElement('span');
		pBtn.id = 'preferencesButton';
		pBtn.innerHTML = '<a href="/kabinet/" onclick="return prefOpen();"><img src="/img/design/nav_preferences.gif" alt="Preferences" width="17" height="15" /></a>';
		n2.appendChild(pBtn);
	}
}
if (news) addLoadEvent(enablePreferences);

function prefClose () {
	var pPanel;
	if (pPanel = document.getElementById('preferencesPanel')) {
		pPanel.parentNode.removeChild(pPanel);
	}
}

function prefLoad () {
	for (var e=0; e<document.forms['preferences'].elements.length; e++) {
		var r = document.forms['preferences'].elements[e];
		if (r.type == 'radio') {
			if (preferenceGet(r.name) == r.value) {
				r.checked = true;
			}
			else {
				r.checked = false;
			}
		}
	}
}
function prefSave () {
	for (var e=0; e<document.forms['preferences'].elements.length; e++) {
		var r = document.forms['preferences'].elements[e];
		if (r.type == 'radio') {
			if (r.checked) {
				preferenceSet(r.name, r.value); 
			}
		}
	}
	alert('Your preferences have been saved.');
	setLayout();
	relativeTimestamps();
	prefClose();
}
function prefReset () {
	if (confirm('Are you sure you want to clear your preferences and return to the default settings?')) {
		alert('Your preferences have been reset.');
		preferenceReset();
		prefLoad();
		setLayout();
		relativeTimestamps();
	}
}

/************* MEDIA RSS ***************/

inpageplayer = 'inpageplayer'; // id of in-page player (Flash container)

function showVideo (mediaUrl, insertafter, width, autoplay, guid) {
	if (!mediaUrl) return true;
	if (!insertafter) return true;
	if (!width) var width = '100%';
	if (!autoplay) var autoplay = 'true';
	if (!guid) var guid = null;
	if (insertafter.nextSibling != null && insertafter.nextSibling.id == inpageplayer) { // collapse media player if already open
		if (temp = document.getElementById(inpageplayer)) {
			if (temp.previousSibling != null) classRemove(temp.previousSibling, 'active');
			temp.parentNode.removeChild(temp);
			delete temp;
		}
	}
	else if (mediaUrl.indexOf('.flv') != -1) { // already know the FLV file
		showVideo_play(mediaUrl, insertafter, width, autoplay);
	}
	else if (mediaUrl.indexOf('.xml') != -1 || mediaUrl.indexOf('.rss') != -1) { // need to read Media RSS file to determine FLV file
		var ajaxobj = new XMLHttpRequest();
		ajaxobj.onreadystatechange = function() {showVideo_ajax(ajaxobj, insertafter, width, autoplay, guid);};
		ajaxobj.open('GET', mediaUrl, true);
		ajaxobj.send('');
	}
	else { // assume we are directly linking to another type of media file (e.g. asx, ram)
		location = mediaUrl;
	}
	if (insertafter.blur) insertafter.blur(); // removes dotted outline from link in Mozilla browsers
	return false;
}
function showVideo_ajax (ajaxobj, insertafter, width, autoplay, guid) {
	if (ajaxobj.readyState == 4) { // only if "loaded"
		if (ajaxobj.status == 200 || ajaxobj.status == 304) { // only if "OK"
			var mediarss = ajaxobj.responseXML; // this is a document node
			var items = mediarss.getElementsByTagName('item');
			if (items.length < 1) return true; // No <item> elements; abort
			var itemsIndex;
			if (guid != null) { // guid specified; use <item> with matching <guid>
				for (var i=0; i<items.length; i++) if (items[i].getElementsByTagName('guid')[0].firstChild.nodeValue == guid) itemsIndex = i;
				if (typeof itemsIndex == 'undefined') return true; // guid not found in Media RSS; abort
			}
			else itemsIndex = 0; // guid not specified; assume first <item>
			var url = '';
			var content = getElementsByTagNameScope(items[itemsIndex], 'media', 'content');
			var format = preferenceGet('video');
			var connection = preferenceGet('connection');
			if (connection == 'lo') var bestbitrate = 999999999; else var bestbitrate = 0;
			for (var j=0; j<content.length; j++) {
				if ((content[j].getAttribute('type') == 'video/x-flv' && format == 'inpage') || (content[j].getAttribute('type') == 'video/x-ms-wmv' && format == 'wm') || (content[j].getAttribute('type') == 'application/vnd.rn-realmedia' && format == 'real')) {
					if ((connection == 'lo' && parseInt(content[j].getAttribute('bitrate'), 10) < bestbitrate) || (connection != 'lo' && parseInt(content[j].getAttribute('bitrate'), 10) > bestbitrate)) {
						bestbitrate = content[j].getAttribute('bitrate');
						url = content[j].getAttribute('url');
					}
				}
			}
			var link = items[itemsIndex].getElementsByTagName('link');
			if (link.length > 0) if (typeof insertafter.href != 'undefined') if (insertafter.href.indexOf('.htm') != -1) if (link[0].firstChild.nodeValue != insertafter.href) var transcript = link[0].firstChild.nodeValue;
			if (url != '') {
				if (format == 'inpage') showVideo_play(url, insertafter, width, autoplay, transcript);
				else location = url;
			}
			else { // preferred format not available
				if (typeof insertafter.href != 'undefined') location = insertafter.href;
			}
		}
		else location = insertafter.href; // Media RSS file not available
	}
}

function showAudio (mediaUrl, insertafter, width, autoplay, guid) {
	if (!mediaUrl) return true;
	if (!insertafter) return true;
	if (!width) var width = '100%';
	if (!autoplay) var autoplay = 'true';
	if (!guid) var guid = null;
	if (insertafter.nextSibling != null && insertafter.nextSibling.id == inpageplayer) { // collapse media player if already open
		if (temp = document.getElementById(inpageplayer)) {
			if (temp.previousSibling != null) classRemove(temp.previousSibling, 'active');
			temp.parentNode.removeChild(temp);
			delete temp;
		}
	}
	else if (mediaUrl.indexOf('.mp3') != -1) { // already know the MP3 file
		showAudio_play(mediaUrl, insertafter, width, autoplay);
	}
	else if (mediaUrl.indexOf('.xml') != -1 || mediaUrl.indexOf('.rss') != -1) { // need to read Media RSS file to determine MP3 file
		var ajaxobj = new XMLHttpRequest();
		ajaxobj.onreadystatechange = function() {showAudio_ajax(ajaxobj, insertafter, width, autoplay, guid);};
		ajaxobj.open('GET', mediaUrl, true);
		ajaxobj.send('');
	}
	else { // assume we are directly linking to another type of media file (e.g. asx, ram)
		location = mediaUrl;
	}
	if (insertafter.blur) insertafter.blur(); // removes dotted outline from link in Mozilla browsers
	return false;
}
function showAudio_ajax (ajaxobj, insertafter, width, autoplay, guid) {
	if (ajaxobj.readyState == 4) { // only if "loaded"
		if (ajaxobj.status == 200 || ajaxobj.status == 304) { // only if "OK"
			var mediarss = ajaxobj.responseXML; // this is a document node
			var items = mediarss.getElementsByTagName('item');
			if (items.length < 1) return true; // No <item> elements; abort
			var itemsIndex;
			if (guid != null) { // guid specified; use <item> with matching <guid>
				for (var i=0; i<items.length; i++) if (items[i].getElementsByTagName('guid')[0].firstChild.nodeValue == guid) itemsIndex = i;
				if (typeof itemsIndex == 'undefined') return true; // guid not found in Media RSS; abort
			}
			else itemsIndex = 0; // guid not specified; assume first <item>
			var url = '';
			var content = getElementsByTagNameScope(items[itemsIndex], 'media', 'content');
			var format = preferenceGet('audio');
			for (var j=0; j<content.length; j++) {
				if ((content[j].getAttribute('type') == 'audio/mpeg' && (format == 'inpage' || format == 'mp3')) || (content[j].getAttribute('type') == 'audio/x-ms-wma' && format == 'wm') || (content[j].getAttribute('type') == 'application/vnd.rn-realmedia' && format == 'real')) {
					url = content[j].getAttribute('url');
				}
			}
			var link = items[itemsIndex].getElementsByTagName('link');
			if (link.length > 0) if (typeof insertafter.href != 'undefined') if (insertafter.href.indexOf('.htm') != -1) if (link[0].firstChild.nodeValue != insertafter.href) var transcript = link[0].firstChild.nodeValue;
			if (url != '') {
				if (format == 'inpage') showAudio_play(url, insertafter, width, autoplay, transcript);
				else location = url;
			}
			else { // preferred format not available
				if (typeof insertafter.href != 'undefined') location = insertafter.href;
			}
		}
		else location = insertafter.href; // Media RSS file not available
	}
}


function resize16x9 (element) {
	if (typeof element == 'undefined') return;
	if (typeof element == 'string') {
		if (element = document.getElementById(element));
		else return;
	}
	width = element.clientWidth;
	height = Math.round((width/16)*9);
	element.style.height = height+'px';
}


	
/************* COOKIES ***************/

function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain) {
	if (getCookie(name)) document.cookie = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}


/************* OPACITY ***************/
// (adapted from: http://www.brainerror.net/scripts_js_blendtrans.php)

// Fade from one opacity setting to another
function opacityFade (object, opacStart, opacEnd, millisec, thisFade) {
	if (!thisFade) var thisFade = new Date().getTime();
	currentFade = thisFade;

    //speed for each frame
	var skip = 10;
    var speed = Math.round((millisec / 100) * skip);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
	if (opacStart > opacEnd) {
		for (var i=opacStart; i>=opacEnd; i-=skip) {
			setTimeout("opacitySet('" + object + "', " + i + ", "+thisFade+")",(timer * speed));
			timer++;
		}
	} 
	else if (opacStart < opacEnd) {
		for (var i=opacStart; i<=opacEnd; i+=skip) {
			setTimeout("opacitySet('" + object + "', " + i + ", "+thisFade+")",(timer * speed));
			timer++;
		}
	}
}

// Change the opacity for different browsers
function opacitySet (object, opacity, thisFade) {
	if (thisFade && typeof currentFade != 'undefined') {
		if (thisFade != currentFade) {
			return;
		}
	}
	if (typeof object == 'string') object = document.getElementById(object);
    object = object.style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
	object.filter = (opacity < 100 ? "alpha(opacity=" + opacity + ")" : "none");
}



/************* CLIPPINGS FUNCTIONALITY ***************/

if (news) addLoadEvent(populateClippings);

// Cookie format: url1~title1;url2~title2;url3~title3 etc.

var clippingsCookie = 'newsMyStories';

function clippingAdd (url, title) {
	lbHide_do();
	url = url.replace(/^[a-z]+:\/\/[^\/]+/, ''); // discard the domain name, we only need the path to the web page
	title = title.replace(/(<[^>]+>|Related Story:)/ig, '').trim(); // discard HTML tags and "Related Story:" in title
	if (clippingExists(url)) return false;
	// If we have reached this point, we need to set the cookie
	var exp = new Date().getTime();
	exp += 1000*60*60*12; // expire 12 hours from now
	exp = new Date(exp);
	var cookieData = getCookie(clippingsCookie);
	setCookie(clippingsCookie, (cookieData==null || cookieData.trim()=='' ? '' : cookieData+';')+url+'~'+title, exp, '/', '.abc.net.au');
	if (!clippingExists(url)) {
		var cookieData = getCookie(clippingsCookie);
		if (cookieData == null || cookieData == '') alert('Sorry, this story could not be added.\n\nPlease ensure that cookies are enabled in your web browser.');
		else alert('Sorry, this story could not be added.\n\nYou may have too many items in My Stories.');
	}
	else populateClippings(url);
	storytools();
	return false;
}



function clippingExists (url) {
	var cookieData = getCookie(clippingsCookie);
	if (cookieData == null || cookieData == '') return false;
	var clippings = cookieData.split(';');
	for (var i=0; i<clippings.length; i++) {
		if (url.indexOf(clippings[i].split('~')[0]) != -1) return true;
	}
	return false;
}

function populateClippings (newURL) {
	var c;
	if (c = document.getElementById('clippings')) {
		c.innerHTML = '';
		var cookieData = getCookie(clippingsCookie);
		if (cookieData == null || (typeof cookieData == 'string' && cookieData.trim()=='')) c.innerHTML = 'Bookmark stories, video and audio clips you may want to access later.';
		else {
			var clippings = cookieData.split(';');
			var html = '';
			for (var i=0; i<clippings.length; i++) {
				var x = clippings[i].split('~');
				var highlight = false;
				var fadefrom = new Array(255,255,51); // rgb colour
				if (newURL) if (newURL.indexOf(x[0]) != -1) {
					highlight = true;
					for (var j=1; j<=10; j++) {
						setTimeout('if (cn = document.getElementById("myc'+i+'")) cn.style.backgroundColor="rgb('+Math.round(fadefrom[0]+(j/10)*(255-fadefrom[0]))+','+Math.round(fadefrom[1]+(j/10)*(255-fadefrom[1]))+','+Math.round(fadefrom[2]+(j/10)*(255-fadefrom[2]))+')";', ((j/10)*1000)+500);
					}
				}
				html += '<li><a href="'+x[0]+'" id="myc'+i+'"'+(highlight?' style="background-color:rgb('+fadefrom[0]+','+fadefrom[1]+','+fadefrom[2]+');"':'')+'>'+x[1]+'</a></li>';
			}
			c.innerHTML = '<ul>'+html+'</ul>';
		}
	}
	processLinks();
}

function lbHide () {
	lbTimeout = window.setTimeout('lbHide_do();', 1500);
}

function lbHide_do () {
	var lb;
	if (lb = document.getElementById('linkButton')) lb.parentNode.removeChild(lb);
}

function lbHide_abort () {
	if (window.lbTimeout) window.clearTimeout(lbTimeout);
}

function processLinks () {
	var links = document.getElementsByTagName('A');
	var storyPageRegex = /(news|news_dev)\/(items|newsitems|stories|video|audio|photos)\/[0-9]{4}.*/;
	var tagPageRegex = /(news|news_dev)\/tag\/[-'A-Za-z0-9]+\/?$/;
	for (var i=0; i<links.length; i++) {
		if (storyPageRegex.test(links[i].href) && links[i].innerHTML.replace(/(<[^>]+>)/ig, '').trim() != '' && !classExists(links[i], 'more')) myStoriesLink(links[i]);
		else if (tagPageRegex.test(links[i].href) && links[i].innerHTML.replace(/(<[^>]+>)/ig, '').trim() != '' && !classExists(links[i], 'more')) myTagsLink(links[i]);
	}
}

function myStoriesLink (link) {
	link.onmouseout = function (e) {
		if (typeof lbHide == 'function') lbHide();
	};
	link.onmouseover = function (e) {
		if (typeof lbHide_abort == 'function') lbHide_abort();
		if (typeof lbHide_do == 'function') lbHide_do();
		var side = 'right';
		if (link.parentNode.nodeName.match(/^(li|h[1-6])$/i)) {
			var parentText = link.parentNode.innerHTML.replace(/<[^>]+>/g, '').trim();
			var linkText = link.innerHTML.replace(/<[^>]+>/g, '').trim();
			if (parentText.indexOf(linkText) == 0) side = 'left';
		}
		if (link.parentNode.scrollWidth == link.scrollWidth) {
			side = 'left';
		}
		var lb = document.createElement('A');
		lb.id = 'linkButton';
		lb.appendChild(document.createTextNode(' '));
		lb.onmouseover = function (f) {
			if (typeof lbHide_abort == 'function') lbHide_abort();
		};
		lb.onmouseout = function (f) {
			if (typeof lbHide == 'function') lbHide();
		};
		if (typeof clippingExists == 'function' && clippingExists(this.href)) {
			lb.className = 'lb_'+side+'_remove_blue';
			lb.title = 'Remove from My Stories';
			lb.alt = lb.title;
			lb.href = 'javascript:clippingRemove("'+this.href.replace(/"/g, '\"')+'");';
		}
		else {
			lb.className = 'lb_'+side+'_add_blue';
			lb.title = 'Add to My Stories';
			lb.alt = lb.title;
			lb.href = 'javascript:clippingAdd("'+this.href.replace(/"/g, '\"')+'", "'+this.innerHTML.replace(/(<[^>]+>|Related Story:)/ig, '').trim().replace(/"/g, '\"')+'");';
		}
		lb.onclick = function (f) {
			eval(this.href.replace(/^javascript:/, ''));
			return false;
		};
		this.parentNode.insertBefore(lb, (side=='left' ? this : this.nextSibling));
	}
}

function myTagsLink (link) {
	link.onmouseout = function (e) {
		if (typeof lbHide == 'function') lbHide();
	};
	link.onmouseover = function (e) {
		if (typeof lbHide_abort == 'function') lbHide_abort();
		if (typeof lbHide_do == 'function') lbHide_do();
		var side = 'right';
		if (link.parentNode.nodeName.match(/^(li|h[1-6])$/i)) {
			var parentText = link.parentNode.innerHTML.replace(/<[^>]+>/g, '').trim();
			var linkText = link.innerHTML.replace(/<[^>]+>/g, '').trim();
			if (parentText.indexOf(linkText) == 0) side = 'left';
		}
		if (link.parentNode.scrollWidth == link.scrollWidth) {
			side = 'left';
		}
		var tagname = this.href;
		tagname = tagname.replace(/^.*\/tag\//, '');
		tagname = tagname.replace(/\/.*$/, '');
		var lb = document.createElement('A');
		lb.id = 'linkButton';
		lb.appendChild(document.createTextNode(' '));
		lb.onmouseover = function (f) {
			if (typeof lbHide_abort == 'function') lbHide_abort();
		};
		lb.onmouseout = function (f) {
			if (typeof lbHide == 'function') lbHide();
		};
		if (typeof watchlistExists == 'function' && watchlistExists(tagname)) {
			lb.className = 'lb_'+side+'_remove_green';
			lb.title = "Remove '"+tagname+"' from My Tags";
			lb.alt = lb.title;
			lb.href = 'javascript:watchlistRemove("'+tagname.replace(/"/g, '\"')+'");';
		}
		else {
			lb.className = 'lb_'+side+'_add_green';
			lb.title = "Add '"+tagname+"' to My Tags";
			lb.alt = lb.title;
			lb.href = 'javascript:watchlistAdd("'+tagname.replace(/"/g, '\"')+'");';
		}
		lb.onclick = function (f) {
			eval(this.href.replace(/^javascript:/, ''));
			return false;
		};
		this.parentNode.insertBefore(lb, (side=='left' ? this : this.nextSibling));
	}
}





/************* IMAGE TOOLTIPS ****************/

// For each image, if title attribute is empty, set it to equal the alt attribute
function processImages() {
	var images = document.getElementsByTagName('IMG');
	for (var i=0; i<images.length; i++) if ((typeof images[i].title == 'undefined' || (typeof images[i].title == 'string' && images[i].title == '')) && ((typeof images[i].alt == 'string'))) images[i].title = images[i].alt;
}
if (news) addLoadEvent(processImages);


/************* LIQUID/FIXED LAYOUT ****************/
function setLayout () {
	if (location.search.indexOf('layout=popup') != -1) { // location.search is the query string
		document.getElementsByTagName('HTML')[0].className = 'popup';
	}
	else if (preferenceGet('layout') == 'liquid') {
		document.getElementsByTagName('HTML')[0].className = 'liquid';
	}
	else {
		document.getElementsByTagName('HTML')[0].className = '';
	}
}
setLayout();

function toggleLayout () {
	if (preferenceGet('layout') == 'liquid') {
		preferenceSet('layout', 'fixed');
	}
	else {
		preferenceSet('layout', 'liquid');
	}
	setLayout();
	if (window.onresize) window.onresize(); // trigger the onresize event if one exists
}

// 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 () { // reduce number of state headlines to make its column similar in height to the top story
	//document.title='Copy fit';
	var minVisible = 3;
	if (document.getElementById('topstory') && document.getElementById('topstories') && document.getElementById('stateContent')) {
		var stateHeadlines = document.getElementById('stateContent').getElementsByTagName('LI');
		var numTotal = stateHeadlines.length;
		var numVisible = numTotal+0;
		var done = false;
		while (!done) {
			if (numVisible <= minVisible) done = true;
			else {
				var difference = document.getElementById('topstories').scrollHeight - document.getElementById('topstory').scrollHeight;
				var thisHeight = stateHeadlines[numVisible-1].scrollHeight;
				if (Math.abs(difference-thisHeight) > Math.abs(difference)) done = true; // if removing another headline makes the column closer in height to the other column
				else {
					stateHeadlines[numVisible-1].style.display = 'none';
					numVisible--;
				}
			}
		}
		for (var i=numVisible; i>0; i--) {
			stateHeadlines[numVisible-1].style.display = 'block';
		}
	}
}

/************ 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);



/**
 * SWFObject v1.4.4: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * **SWFObject is the SWF embed script formerly known as FlashObject. The name was changed for
 *   legal reasons.
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}
if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}
if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}
deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){if(!document.getElementById){return;}
this.DETECT_KEY=_b?_b:"detectflash";
this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params=new Object();
this.variables=new Object();
this.attributes=new Array();
if(_1){this.setAttribute("swf",_1);}
if(id){this.setAttribute("id",id);}
if(w){this.setAttribute("width",w);}
if(h){this.setAttribute("height",h);}
if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();
if(c){this.addParam("bgcolor",c);}
var q=_8?_8:"high";
this.addParam("quality",q);
this.setAttribute("useExpressInstall",_7);
this.setAttribute("doExpressInstall",false);
var _d=(_9)?_9:window.location;
this.setAttribute("xiRedirectUrl",_d);
this.setAttribute("redirectUrl","");
if(_a){this.setAttribute("redirectUrl",_a);}};
deconcept.SWFObject.prototype={setAttribute:function(_e,_f){
this.attributes[_e]=_f;
},getAttribute:function(_10){
return this.attributes[_10];
},addParam:function(_11,_12){
this.params[_11]=_12;
},getParams:function(){
return this.params;
},addVariable:function(_13,_14){
this.variables[_13]=_14;
},getVariable:function(_15){
return this.variables[_15];
},getVariables:function(){
return this.variables;
},getVariablePairs:function(){
var _16=new Array();
var key;
var _18=this.getVariables();
for(key in _18){_16.push(key+"="+_18[key]);}
return _16;},getSWFHTML:function(){var _19="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
if(this.getAttribute("doExpressInstall")){
this.addVariable("MMplayerType","PlugIn");}
_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
var _1a=this.getParams();
for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}
var _1c=this.getVariablePairs().join("&");
if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";
}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");}
_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">";
_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
var _1d=this.getParams();
for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}
var _1f=this.getVariablePairs().join("&");
if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}
return _19;
},write:function(_20){
if(this.getAttribute("useExpressInstall")){
var _21=new deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){
this.setAttribute("doExpressInstall",true);
this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));
document.title=document.title.slice(0,47)+" - Flash Player Installation";
this.addVariable("MMdoctitle",document.title);}}
if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){
var n=(typeof _20=="string")?document.getElementById(_20):_20;
n.innerHTML=this.getSWFHTML();return true;
}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}
return false;}};
deconcept.SWFObjectUtil.getPlayerVersion=function(){
var _23=new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}
catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}
catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}
catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}
return _23;};
deconcept.PlayerVersion=function(_27){
this.major=_27[0]!=null?parseInt(_27[0]):0;
this.minor=_27[1]!=null?parseInt(_27[1]):0;
this.rev=_27[2]!=null?parseInt(_27[2]):0;
};
deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
if(this.major<fv.major){return false;}
if(this.major>fv.major){return true;}
if(this.minor<fv.minor){return false;}
if(this.minor>fv.minor){return true;}
if(this.rev<fv.rev){
return false;
}return true;};
deconcept.util={getRequestParameter:function(_29){
var q=document.location.search||document.location.hash;
if(q){var _2b=q.substring(1).split("&");
for(var i=0;i<_2b.length;i++){
if(_2b[i].substring(0,_2b[i].indexOf("="))==_29){
return _2b[i].substring((_2b[i].indexOf("=")+1));}}}
return "";}};
deconcept.SWFObjectUtil.cleanupSWFs=function(){if(window.opera||!document.all){return;}
var _2d=document.getElementsByTagName("OBJECT");
for(var i=0;i<_2d.length;i++){_2d[i].style.display="none";for(var x in _2d[i]){
if(typeof _2d[i][x]=="function"){_2d[i][x]=function(){};}}}};
deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};
__flash_savedUnloadHandler=function(){};
if(typeof window.onunload=="function"){
var _30=window.onunload;
window.onunload=function(){
deconcept.SWFObjectUtil.cleanupSWFs();_30();};
}else{window.onunload=deconcept.SWFObjectUtil.cleanupSWFs;}};
if(typeof window.onbeforeunload=="function"){
var oldBeforeUnload=window.onbeforeunload;
window.onbeforeunload=function(){
deconcept.SWFObjectUtil.prepUnload();
oldBeforeUnload();};
}else{window.onbeforeunload=deconcept.SWFObjectUtil.prepUnload;}
if(Array.prototype.push==null){
Array.prototype.push=function(_31){
this[this.length]=_31;
return this.length;};}
var getQueryParamValue=deconcept.util.getRequestParameter;
var FlashObject=deconcept.SWFObject;
var SWFObject=deconcept.SWFObject;

/************ DATE FUNCTIONS **************/

// Return true if dateObj falls within Australian Eastern Daylight Time (Sydney)
function daylightSavings (dateObj) {
	var aedt = new Array(
	/*'October 29, 1995','March 31, 1996',
	'October 27, 1996','March 30, 1997',
	'October 26, 1997','March 29, 1998',
	'October 25, 1998','March 28, 1999',
	'October 31, 1999','March 26, 2000',
	'August 27, 2000','March 25, 2001',*/
	'October 28, 2001','March 31, 2002',
	'October 27, 2002','March 30, 2003',
	'October 26, 2003','March 28, 2004',
	'October 31, 2004','March 27, 2005',
	'October 30, 2005','April 2, 2006',
	'October 29, 2006','March 25, 2007',
	'October 28, 2007','March 30, 2008',
	'October 26, 2008','March 29, 2009',
	'October 25, 2009','March 28, 2010',
	'October 31, 2010','March 27, 2011',
	'October 30, 2011','March 25, 2012',
	'October 28, 2012','March 31, 2013',
	'October 27, 2013','March 30, 2014',
	'October 26, 2014','March 29, 2015',
	'October 25, 2015','March 27, 2016',
	'October 30, 2016','March 26, 2017');
	var dateInt = dateObj.getTime();
	var ds;
	for (var i=0; i<aedt.length; i++) {
		if (Date.parse(aedt[i]+' 02:00:00') < dateInt) ds = (i%2==0);
		else return ds;
	}
	return false;
}


// Convert absolute timestamps to relative timestamps
function relativeTimestamps () {
	if (!window.servertimestamp) return;
	clientTimeNow = new Date().getTime();
	if (!window.clientTimeLoad) clientTimeLoad = clientTimeNow+0;
	var clientTimePadding = clientTimeNow-clientTimeLoad;
	var relative = true;
	if (preferenceGet('timestamp') != 'relative') {
		relative = false;
	}
	var convertUnder = 60*60*12; // only convert timestamps aged less than x seconds
	var weekdays = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
	var months = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
	var spans = document.getElementsByTagName('SPAN');
	for (var i=0; i<spans.length; i++) {
		if (classExists(spans[i], 'timestamp') && (typeof spans[i].ts != 'undefined' || spans[i].innerHTML.match(/^[a-zA-Z]+ [0-9]+, [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}$/))) {
			var time;
			if (typeof spans[i].ts == 'undefined') spans[i].ts = new Date(spans[i].innerHTML);
			var sec = (servertimestamp.getTime()-spans[i].ts.getTime()+clientTimePadding)/1000;
			if (relative && sec < convertUnder) {
				if (sec < 0) {
					time = '';
				}
				else if (sec <= 60) {
					var seconds = Math.floor(sec);
					time = seconds+' second'+(seconds==1 ? '' : 's');
				}
				else if (sec <= 60*60) {
					var minutes = Math.floor(sec/60);
					time = minutes+' minute'+(minutes==1 ? '' : 's');
				}
				else if (sec <= 60*60*24) {
					var hours = Math.floor(sec/60/60);
					var minutes = Math.floor(sec/60)%60;
					time = hours+' hour'+(hours==1 ? '' : 's')+' '+minutes+' minute'+(minutes==1 ? '' : 's');
				}
				else {
					var days = Math.floor(sec/60/60/24);
					var hours = Math.floor(sec/60/60)%24;
					time = days+' day'+(hours==1 ? '' : 's')+' '+hours+' hour'+(hours==1 ? '' : 's');
				}
				if (time == '') spans[i].innerHTML = '';
				else spans[i].innerHTML = time+' ago';
			}
			else {
				spans[i].innerHTML = weekdays[spans[i].ts.getDay()]+' '+months[spans[i].ts.getMonth()]+' '+spans[i].ts.getDate()+', '+spans[i].ts.getFullYear()+' '+(spans[i].ts.getHours()>12 ? spans[i].ts.getHours()-12 : spans[i].ts.getHours())+':'+(spans[i].ts.getMinutes().toString().length==1 ? '0' : '')+spans[i].ts.getMinutes()+(spans[i].ts.getHours()>11 ? 'pm' : 'am')+' '+(daylightSavings(spans[i].ts) ? 'AEDT' : 'AEST');
			}
		}
	}
	relativeTimestampsTimeout = window.setTimeout('relativeTimestamps()', 1000*60);
}
addLoadEvent(relativeTimestamps);


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;
				}
			}
		}
	}
}
if (news) addLoadEvent(setActiveNav);


function textInputHint (theInput, theText, theClass) {
	if (typeof theInput == 'string') theInput = document.getElementById(theInput);
	theInput.defaultText = theText;
	theInput.defaultClass = theClass;
	// Add hint if text field is empty
	theInput.onblur = function () {
		if (this.value == '' || this.value == this.defaultText) {
			classAdd(this, this.defaultClass);
			this.value = this.defaultText;
		}
	};
	theInput.onblur(); // force onblur event to run now
	// Remove hint if text field is empty
	theInput.onfocus = function () {
		if (this.value == this.defaultText) {
			classRemove(this, this.defaultClass);
			this.value = '';
		}
	};
	// Remove hint when form is submitted
	if (theInput.form) { // if the text field is inside a submittable form
		if (typeof theInput.form.textInputHints == 'undefined') theInput.form.textInputHints = new Array();
		theInput.form.textInputHints[theInput.form.textInputHints.length] = theInput;
		theInput.form.onsubmit = function () {
			for (var i=0; i<this.textInputHints.length; i++) {
				this.textInputHints[i].onfocus();
			}
		}
	}
}
