/*
Foreign Correspondent common scripts
Created by: Andrew Kesper, 6 July 2008
Modified by: Andrew Kesper, 6 July 2008
*/

/************* 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 '';
}


/************* 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 (typeof insertafter == 'string') insertafter = document.getElementById(insertafter);
	if (!width) var width = '100%';
	if (!autoplay) var autoplay = 'true';
	if (!guid) var guid = null;
	if (temp = document.getElementById(inpageplayer)) {
		if (temp.previousSibling != null) classRemove(temp.previousSibling, 'active');
		temp.parentNode.removeChild(temp);
		delete temp;
	}
	if (typeof nowPlaying != 'undefined' && nowPlaying == mediaUrl+'?'+guid) {
		// was already playing this item - don't want to play it again
		delete nowPlaying;
	}
	else {
		nowPlaying = mediaUrl+'?'+guid;
		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
			mediaUrl += (mediaUrl.indexOf('?') == -1 ? '?' : '&') + Math.floor(new Date().getTime()/(1000*60*2));
			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)
			delete nowPlaying;
			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 showVideo_play (url, insertafter, width, autoplay, transcript) {
	classAdd(insertafter, 'active');
	if (width.indexOf('%') != -1) var height = Math.round((parseInt(width, 10)/100)*insertafter.parentNode.scrollWidth/16*9); // width is a percentage
	else var height = Math.round(parseInt(width, 10)/16*9); // assume width is in pixels
	var div = document.createElement('DIV');
	div.id = inpageplayer;
	div.className = 'videoplayer';
	insertafter.parentNode.insertBefore(div, insertafter.nextSibling);
	window.onresize = function () {
		resize16x9(inpageplayer+'Object');
	};
	swfurl = 'http://www.abc.net.au/news/swf/flvplayer.swf';
	var so = new SWFObject(swfurl, inpageplayer+'Object', width, height, '8', '#000000', true);
	so.addParam('allowFullScreen', 'true');
	so.addVariable('mediaURL', url);
	so.addVariable('autoPlay', autoplay);
	so.write(inpageplayer);
	resize16x9(inpageplayer+'Object');
	if (transcript) {
		if (!transcript.match(/news(_dev)?\/(audio|video)\//)) {
			var p = document.createElement('P');
			p.innerHTML = '<small><a href="'+transcript+'" onclick="return popup(this.href, 950, 500);">View Transcript</a></small>';
			div.insertBefore(p, null);
		}
	}
}

function showAudio (mediaUrl, insertafter, width, autoplay, guid) {
	if (!mediaUrl) return true;
	if (!insertafter) return true;
	if (typeof insertafter == 'string') insertafter = document.getElementById(insertafter);
	if (!width) var width = '100%';
	if (!autoplay) var autoplay = 'true';
	if (!guid) var guid = null;
	if (temp = document.getElementById(inpageplayer)) {
		if (temp.previousSibling != null) classRemove(temp.previousSibling, 'active');
		temp.parentNode.removeChild(temp);
		delete temp;
	}
	if (typeof nowPlaying != 'undefined' && nowPlaying == mediaUrl+'?'+guid) {
		// was already playing this item - don't want to play it again
		delete nowPlaying;
	}
	else {
		nowPlaying = mediaUrl+'?'+guid;
		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
			mediaUrl += (mediaUrl.indexOf('?') == -1 ? '?' : '&') + Math.floor(new Date().getTime()/(1000*60*2));
			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)
			delete nowPlaying;
			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 showAudio_play (url, insertafter, width, autoplay, transcript) {
	classAdd(insertafter, 'active');
	if (width.indexOf('%') != -1) width = Math.round((parseInt(width, 10)/100)*insertafter.parentNode.scrollWidth);
	// Standard size of audio player is 285x40 pixels. Should be no bigger than this
	if (width > 285) width = 285;
	var height = Math.round(width/285*40);
	var div = document.createElement('DIV');
	div.id = inpageplayer;
	div.className = 'audioplayer';
	insertafter.parentNode.insertBefore(div, insertafter.nextSibling);
	window.onresize = function () {};
	var swfurl = 'http://www.abc.net.au/news/swf/mp3player.swf';
	var so = new SWFObject(swfurl, inpageplayer+'Object', width, height, '8', '#FFFFFF', true);
	so.addParam('allowFullScreen', 'true');
	so.addVariable('mediaURL', url);
	so.addVariable('autoPlay', autoplay);
	so.write(inpageplayer);
	if (transcript) {
		if (!transcript.match(/news(_dev)?\/(audio|video)\//)) {
			var p = document.createElement('P');
			p.innerHTML = '<small><a href="'+transcript+'" onclick="return popup(this.href, 950, 500);">View Transcript</a></small>';
			div.insertBefore(p, null);
		}
	}
}

function showPhotos (mediaRSS) {
/*
	if (typeof slideshow != 'undefined') { // slideshow objeect already defined - initialise the slideshow immediately
		slideshowInit();
		return false;
	}
*/
	if (!mediaUrl) return true;
	if (mediaUrl.indexOf('.xml') != -1 || mediaUrl.indexOf('.rss') != -1) { // assume mediaUrl is a Media RSS file
		var ajaxobj = new XMLHttpRequest();
		ajaxobj.onreadystatechange = function() {showPhotos_ajax(ajaxobj);};
		ajaxobj.open('GET', mediaUrl, true);
		ajaxobj.send('');
	}
	else { // can't do anything with mediaUrl
		return true;
	}
	return false;
}

function showPhotos_ajax (ajaxobj) {
	if (ajaxobj.readyState == 4) { // only if "loaded"
		if (ajaxobj.status == 200 || ajaxobj.status == 304) { // only if "OK"
			slideshow = new Array();
			slideshowIndex = 0;
			// Load existing image into slideshow
			var img;
			if (img = document.getElementById('storyPhotosImg')) {
				slideshow[slideshow.length] = new StoryPhoto(img.src, img.width, img.height, (document.getElementById('storyPhotosCaption') ? document.getElementById('storyPhotosCaption').innerHTML : img.alt));
			}
			delete img;
			// Load rest of items into slideshow
			var mediarss = ajaxobj.responseXML; // this is a document node
			var items = mediarss.getElementsByTagName('item');
			for (var i=0; i<items.length; i++) {
				var source = getElementsByTagNameScope(items[i], 'media', 'copyright')
				var content = getElementsByTagNameScope(items[i], 'media', 'content');
				// add to slideshow if not already present
				// otherwise just set the other versions of the photo
				var addToSlideshow = true;
				for (var j=0; j<content.length; j++) {
					if (content[j].getAttribute('width') == '285' && (content[j].getAttribute('url').match(/\.jpe?g$/i) || content[j].getAttribute('type').match(/^image\/jpe?g$/))) {
						var versions = new Array();
						var tallest = j; // tallest 285-pixel-wide version of this photo
						for (var m=0; m<content.length; m++) {
							if (content[m].getAttribute('width') == '285' && parseInt(content[m].getAttribute('height'), 10) > parseInt(content[tallest].getAttribute('height'), 10)) tallest = m;
							versions[versions.length] = new StoryPhotoVersion(content[m].getAttribute('url'), parseInt(content[m].getAttribute('width'), 10), parseInt(content[m].getAttribute('height'), 10));
						}
						for (var k=0; k<slideshow.length; k++) {
							if (slideshow[k].src == content[j].getAttribute('url') || slideshow[k].src == content[tallest].getAttribute('url')) {
								addToSlideshow = false;
								slideshow[k] = new StoryPhoto(slideshow[k].src, slideshow[k].width, slideshow[k].height, slideshow[k].caption, versions);
							}
						}
						if (addToSlideshow) {
							slideshow[slideshow.length] = new StoryPhoto(content[tallest].getAttribute('url'), parseInt(content[tallest].getAttribute('width'), 10), parseInt(content[tallest].getAttribute('height'), 10), items[i].getElementsByTagName('title')[0].firstChild.nodeValue+(source.length > 0 ? ' ('+source[0].firstChild.nodeValue+')' : ''), versions);
							addToSlideshow = false;
						}
					}
				}
			}
			slideshowInit();
		}
	}
}

function slideshowInit () {
	if (typeof slideshow == 'undefined') return;
	if (slideshow.length < 1) return;
	if (typeof slideshowIndex == 'undefined') slideshowIndex = 0;
	if (slideshow.length > 1) {
		var sp;
		if (sp = document.getElementById('storyPhotos')) {
			var p = document.createElement('P');
			p.id = 'storyPhotosNav';
			p.innerHTML = '<span id="storyPhotosNavPrev"><a href="javascript:slideshowPrev();"><img src="/news/img/2007/btn_editorspick_prev_26x16.png" width="26" height="16" /></a></span> <span id="storyPhotosNavNext"><a href="javascript:slideshowNext();"><img src="/news/img/2007/btn_editorspick_next_26x16.png" width="26" height="16" /></a></span> <span id="storyPhotosNavText"></span>';
			sp.insertBefore(p, sp.firstChild);
		}
	}
	slideshowUpdate();
}

function slideshowNext () {
	if (typeof slideshow == 'undefined') return;
	if (slideshow.length <= 1) return;
	if (typeof slideshowIndex == 'undefined') slideshowIndex = 0;
	if (slideshowIndex < slideshow.length-1) slideshowIndex++;
	else slideshowIndex = 0;
	if (slideshowIndex < slideshow.length-2) {
		var preload = new Image();
		preload.src = slideshow[slideshowIndex+1].src;
	}
	slideshowUpdate();
}

function slideshowPrev () {
	if (typeof slideshow == 'undefined') return;
	if (slideshow.length <= 1) return;
	if (typeof slideshowIndex == 'undefined') slideshowIndex = 0;
	if (slideshowIndex > 0) slideshowIndex--;
	else slideshowIndex = slideshow.length-1;
	slideshowUpdate();
}

function slideshowUpdate () {
	if (typeof slideshow == 'undefined') return;
	if (slideshow.length < 1) return;
	if (typeof slideshowIndex == 'undefined') slideshowIndex = 0;
	var img, caption, link, navtext;
	if (img = document.getElementById('storyPhotosImg')) {
		if (img.src != slideshow[slideshowIndex].src) {
			currentFade = new Date().getTime();
			opacitySet(img, 0, currentFade);
			img.style.visibility = 'hidden';
			doFade = function () {
				img.src = slideshow[slideshowIndex].src;
				img.width = slideshow[slideshowIndex].width;
				img.height = slideshow[slideshowIndex].height;
				img.title = slideshow[slideshowIndex].caption;
				img.alt = img.title;
				img.onload = function () {
					img.style.visibility = 'visible';
					setTimeout("opacityFade('storyPhotosImg', 0, 100, 150, "+currentFade+")", 100);
				};
			}
			setTimeout("doFade()", 100);
		}
	}
	if (caption = document.getElementById('storyPhotosCaption')) {
		caption.innerHTML = slideshow[slideshowIndex].caption;
	}
	if (link = document.getElementById('storyPhotosLink')) {
		link.href = slideshow[slideshowIndex].versions[slideshow[slideshowIndex].biggest].src;
		link.onclick = function () {
			var img = slideshow[slideshowIndex].versions[slideshow[slideshowIndex].best];
			imgWindow(img.src, null, img.width, img.height, slideshow[slideshowIndex].caption);
			return false;
		};
	}
	if (navtext = document.getElementById('storyPhotosNavText')) {
		navtext.innerHTML = 'Slideshow: Photo '+(slideshowIndex+1)+' of '+slideshow.length;
	}
}

// StoryPhoto object
function StoryPhoto (src, width, height, caption, versions) {
	this.src = src;
	this.width = width;
	this.height = height;
	this.caption = caption;
	if (versions) {
		this.versions = versions; // array of StoryPhotoVersion objects
		this.biggest = 0; // index of biggest version, compared by width*height
		this.best = 0; // index of version most suitable for this screen resolution
		for (var i=0; i<versions.length; i++) {
			if (versions[this.biggest].width*versions[this.biggest].height < versions[i].width*versions[i].height) this.biggest = i;
			if (versions[this.best].width*versions[this.best].height < versions[i].width*versions[i].height && versions[i].width < screen.width-170) this.best = i;
		}
	}
}

// StoryPhotoVersion object
function StoryPhotoVersion (src, width, height) {
	this.src = src;
	this.width = width;
	this.height = height;
}

// Open a popup window containing an image, title and caption
function imgWindow (imgurl, windowname, width, height, title, caption) {
	if (!windowname) var windowname = 'abcnewspopup'+new Date().getTime();
	if (!caption) var caption = title;
	var horz = width+120;
	var vert = Math.min(height+160, screen.height-120); // avoid popup displaying taller than the screen resolution
	var left = screen.width/2 - horz/2;
	var top = screen.height/2 - vert/2;
	var w = window.open('', windowname, 'width=' + horz + ',height=' + vert +',toolbar=0,resizable=1,scrollbars=1,left='+left+',top='+top);
	w.document.writeln('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
	w.document.writeln('<html><head><title>' + title + '</title></head><body>');
	w.document.writeln('<style type="text/css">* {font-family:Verdana,Arial,Helvetica,sans-serif;font-size:100%;color:white;line-height:133%;} html, body {height:100%;margin:0;padding:0;background-color:#222;border:none;} body {font-size:75%;text-align:center;} div.image {max-width:100%;padding:40px 0 30px 0;x-border-bottom:2px solid white;} div.image img {border:3px solid white;} p {margin:0 25px;padding-bottom:8px;} div.caption {padding-top:8px;} a {color:#ccc;}</style>');
	w.document.writeln('<div class="image"><img src="'+imgurl+'" width="'+width+'" height="'+height+'" alt="'+title+'" title="'+title+'" /></div>');
	w.document.writeln('<div class="caption">');
	w.document.writeln('<p>'+caption+'</p>');
	w.document.writeln('<p style="font-size:smaller;"><a href="javascript:window.parent.close();">Close Image</a></p></div>');
	w.document.writeln('</body></html>');
	w.document.close();
	if (window.focus) w.focus();
	return false;
}

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';
}

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
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){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"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(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},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[_16.length]=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");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_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");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_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{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}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(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[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(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;



/************ LIGHTBOX EFFECT **************/

function lightboxCreate (w, h, title) {
	if (typeof w == 'undefined') var w = 400;
	if (typeof h == 'undefined') var h = 224;
	if (typeof title == 'undefined') var title = '';
	var lb, html = '', pad = 5;
	lightboxClose();
	html += '<div id="lb-dimmer" onclick="lightboxClose();" style="background-color: #222; zoom: 1; opacity: 0.5; -moz-opacity: 0.5; -khtml-opacity: 0.5; filter: alpha(opacity=50); position: absolute; z-index: 9999998; left: 0; top: 0; width: '+document.body.scrollWidth+'px; height: '+document.body.scrollHeight+'px;"></div><div id="lb-dialog" style="background-color: #000; position: absolute; z-index: 9999999; left: 100px; top: 100px; width: '+w+'px; padding: '+pad+'px;"><p style="padding: 0 5px; margin: 0 0 5px 0; font-size: 8pt; color: #FFF;"><a href="javascript:void(lightboxClose());" style="float: right; color: #FFF; margin-left: 1em;"><b>Close</b></a>'+title+'&nbsp;</p><div id="lb-content"></div></div>';
	lb = document.createElement('DIV');
	lb.id = 'lightbox';
	lb.innerHTML = html;
	document.body.appendChild(lb);
	lightboxPos(w, h, pad);
	onscroll = function () { eval('lightboxPos('+w+', '+h+', '+pad+');') };
	return document.getElementById('lb-content');
}

function lightboxPos (w, h, pad) {
	var lbd, d;
	d = (typeof document.documentElement != 'undefined' ? document.documentElement : document.body);
	if (lbd = document.getElementById('lb-dialog')) {
		var x, y;
		x = (typeof d.scrollLeft != 'undefined' ? d.scrollLeft : window.pageXOffset) + (typeof d.clientWidth != 'undefined' ? d.clientWidth : window.innerWidth)/2 - w/2 - pad;
		y = (typeof d.scrollTop != 'undefined' ? d.scrollTop : window.pageYOffset) + (typeof d.clientHeight != 'undefined' ? d.clientHeight : window.innerHeight)/2 - h/2 - pad;
		lbd.style.left = x+'px';
		lbd.style.top = y+'px';
	}
}

function lightboxClose () {
	var lb;
	if (lb = document.getElementById('lightbox')) lb.parentNode.removeChild(lb);
	onscroll = function () {};
	if (typeof nowPlaying != 'undefined') delete nowPlaying;
}


/*************** 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'), 'inpage');

// Name of our preferences cookie
var preferencesCookie = 'foreignPreferences';

// 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
}

// Set a preference, and store it in the cookie for later retrieval
function preferenceSet (name, value) {
	for (var i=0; i<preferences.length; i++) {
		if (preferences[i].name == name) {
			for (var j=0; j<preferences[i].possibleValues.length; j++) {
				if (preferences[i].possibleValues[j] == value) {
					// If we've got to this point, the value specified is valid
					var cookieData = getCookie(preferencesCookie);
					var p = new Array();
					if (cookieData != null && cookieData != 'undefined' && cookieData != '') {
						p = cookieData.split(';');
						for (var k=0; k<p.length; k++) {
							var x = p[k].split('~');
							if (x[0] == name) p.splice(k, 1); // remove existing value
						}
					}
					p[p.length] = name+'~'+value; // add new value
					cookieData = p.join(';');
					var exp = new Date().getTime();
					exp += 1000*60*60*24*31; // expire 1 month from now
					exp = new Date(exp);
					setCookie(preferencesCookie, cookieData, exp, '/foreign/', '.abc.net.au');
				}
			}
		}
	}
}

// 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;
}

function preferenceReset() {
	deleteCookie(preferencesCookie, '/foreign/', '.abc.net.au');
}


/************* 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");
}


/*********** VIDEO LINKS ************/
function initVideoLinks () {
	var v = getElementsByClassNameAK(document, 'videolink');
	var pVideo = preferenceGet('video');
	var pConnection = preferenceGet('connection');
	for (var i=0; i<v.length; i++) {
		if (classExists(v[i], pVideo) && classExists(v[i], pConnection)) classRemove(v[i], 'hide');
		else classAdd(v[i], 'hide');
		var f = getElementsByClassNameAK(document, 'format');
		for (var j=0; j<f.length; j++) classAdd(f[j], 'hide');
	}
}
addLoadEvent(initVideoLinks);