var timeDiff;

function evalTimeDiff(gmtTime,scheduleOffset,transition)
{
var tempOffset = new Date();
var serverOffset = -tempOffset.getTimezoneOffset()*60*1000;
var timeOffset = serverOffset - scheduleOffset;
timeDiff = gmtTime - timeOffset;
loadStreamPromotions(timeDiff,transition);
}

function loadStreamPromotions(timeDiff,transition)
{
var flashvars = {configXmlUrl: "/flash/streamPromotions/APNC_LiveStreamPromo_Config.xml", serverTime: timeDiff, transitionIn: transition}
var params = {scale: "noscale", wmode: "transparent", menu: "false"}
swfobject.embedSWF("/flash/streamPromotions/ABC_09_APNC_LiveStreamPromo.swf", "streamPromotionsFlash", "300", "70", "9.0.115", false, flashvars, params);
}

function openLiveStreamListen(arg)
{
if (document.all){
var xMax = screen.width, yMax = screen.height;
var xOffset = (xMax - 480)/2, yOffset = (yMax - 440)/2;
}
popupWin = window.open('/listenLIVE.htm', arg, 'width=480,height=440,top='+yOffset+',left='+xOffset+',menubar=no,scrollbars=no,status=no,toolbar=no')
popupWin.focus()
}

function openLiveStreamWatch(arg)
{
if (document.all){
var xMax = screen.width, yMax = screen.height;
var xOffset = (xMax - 480)/2, yOffset = (yMax - 440)/2;
}
popupWin = window.open('/watchLIVE.htm', arg, 'width=480,height=440,top='+yOffset+',left='+xOffset+',menubar=no,scrollbars=no,status=no,toolbar=no')
popupWin.focus()
}

function copyDate() {
	var copyright_year = "";
	if (typeof serverGMTDateTime != 'undefined') {
		var myGMTDateTime = new Date(serverGMTDateTime);
		copyright_year = myGMTDateTime.getFullYear();
	};
	var date_year = '<p><a href="http://www.abc.net.au/common/copyrigh.htm" target="_blank">&copy;' + copyright_year + ' ABC</a> <a href="/privacy.htm">Privacy Policy</a></p>';
	document.getElementById("footerCopyright").innerHTML=date_year;	
}

/**
 * Compare the difference in time between two dates. If less than 36 hours, return the
 * time difference in words. If not, don't return anything.
 * 
 * @param date dtBase Base date to compare against
 * @param date dtComp Date to compare with
 */
function getTimeDiffInWords(dtBase, dtComp) {
	itemTimeStampDif = dtBase.getTime() - dtComp.getTime();
	itemTimeStampHours = Math.floor(itemTimeStampDif/(1000*60*60));
	itemTimeStampMins = Math.floor(itemTimeStampDif/(1000*60)%60);
	itemTimeStampSecs = Math.floor(itemTimeStampDif/(1000)%60);
	if (itemTimeStampHours < 24) {
  	if (itemTimeStampHours == 1) {
  		var writeHours = itemTimeStampHours + ' hour ';
  	}
  	else if (itemTimeStampHours == 0) {
  		var writeHours = '';
  	} else {
  		var writeHours = itemTimeStampHours + ' hours ';
  	}
  	if (itemTimeStampMins == 1) {
  		var writeMinutes = itemTimeStampMins + ' minute ';
  	}
  	else if (itemTimeStampMins == 0) {
  		var writeMinutes = itemTimeStampSecs + ' seconds ';
  	} else {
  		var writeMinutes = itemTimeStampMins + ' minutes ';
  	}
  	return writeHours + writeMinutes + 'ago'; 
	} // end if < 36 hrs ago
}

function fixDates() {
	if (typeof serverGMTDateTime != 'undefined') {
		var astTime = new Date(serverGMTDateTime);

		var spans = document.getElementsByTagName('span');
		for (var i=0; i<spans.length; i++) {
			if (spans[i].innerHTML.match("/")) {
				
				var dateTemp = spans[i].innerHTML;
				dateTemp.toString();
				dateTempYear = dateTemp.substring(6,10);
				dateTempMonth = dateTemp.substring(3,5);
				dateTempDay = dateTemp.substring(0,2);
				var newDateTemp = dateTempMonth + '/' + dateTempDay + '/' + dateTempYear;
				var fixCreatedDate = new Date();
				fixCreatedDate.setTime(Date.parse(newDateTemp));
				var mycrap = fixCreatedDate.toString();
				mycrap1 = mycrap.substring(0,3);
				mycrap2 = mycrap.substring(7,10);
				mycrap3 = mycrap.substring(3,7);
				mycrap4 = mycrap.substring(10,33);
				spans[i].innerHTML = mycrap1+","+mycrap2+mycrap3+mycrap4;
				
			} else {
				
				if (classExists(spans[i], 'timestamp')) {
					myoffset = spans[i].innerHTML.indexOf("+") + 1;
					myoffset = spans[i].innerHTML.substring(myoffset, myoffset + 2);
					itemTimeStamp = new Date(spans[i].innerHTML);
					itemTimeStamp.setHours(itemTimeStamp.getHours() - myoffset);
					var sDiff = getTimeDiffInWords(astTime, itemTimeStamp);
					if (sDiff) { spans[i].innerHTML = sDiff; } // only update it if we got a value back
				} // end if classExists
				
			} // end innerHTML.match
		} // end for
	}	// end if typeof
}	// end function

function mediaExpires() {
	if (typeof serverGMTDateTime != 'undefined') {
	if (typeof publishedDate != 'undefined') {
		var expiresDate = new Date(publishedDate);
		var todayDate = new Date(serverGMTDateTime);
		expiresDate.setMonth(18);
		if (todayDate > expiresDate){
			document.getElementById('relatedVideo').style.display = 'none';
			document.getElementById('relatedAudio').style.display = 'none';
		};
		var myhtml = String(document.getElementById('headlinesRelated').innerHTML);
		var switcheroo = myhtml.replace(/&amp;apos;/gi, "'");
		document.getElementById('headlinesRelated').innerHTML = switcheroo;
	};
	};
}

function classExists (element, theclass) {
	if (!element) return false;
	if (!element.className) return false;
	var reg = new RegExp('(^| )'+theclass+'( |$)', 'g');
	return reg.test(element.className);
}

function openLiveStream(xx,yy) {
if (document.all){
var xMax = screen.width, yMax = screen.height;
var xOffset = (xMax - 480)/2, yOffset = (yMax - 440)/2;
}
popupWin = window.open(xx, yy, 'width=480,height=440,top='+yOffset+',left='+xOffset+',menubar=no,scrollbars=no,status=no,toolbar=no')
popupWin.focus()
}

function headlinesShare()
{
var sp;
var thisURL;
var thisTitle;
if (sp = document.getElementById('headlinesShare'))
{
thisURL = window.location.href;
thisEditURL = thisURL.substring(0,63);
thisTitle = document.title;
sp.innerHTML = '<p><a href="javascript:window.print()">Print</a> | <a href="http://www.abc.net.au/cgi-bin/common/mailto/mailto-nojs_query.pl?'+ thisEditURL +'">Email</a>&nbsp;&nbsp; SHARE: <a href="http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+thisEditURL+';title='+thisTitle+'" target="_blank" onclick="window.open(\'http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+thisEditURL+';title='+thisTitle+'\', \'Delicious\',\'toolbar=no,width=700,height=600,resizable=yes\'); return false;">del.icio.us</a> | <a href="http://digg.com/submit?url='+thisEditURL+'" target="_blank" onclick="window.open(\'http://digg.com/submit?url='+thisEditURL+'\', \'Digg\',\'toolbar=no,width=800,height=600,resizable=yes,scrollbars=yes\'); return false;">Digg</a> | <a href="http://www.stumbleupon.com/submit?url='+thisEditURL+'" target="_blank" onclick="window.open(\'http://www.stumbleupon.com/submit?url='+thisEditURL+'&title='+thisTitle+'\', \'StumbleUpon\',\'toolbar=no,width=800,height=600,resizable=yes,scrollbars=yes\'); return false;">StumbleUpon</a> | <a href="http://www.facebook.com/sharer.php?u=='+thisEditURL+'&amp;t='+thisTitle+'" target="_blank" onclick="window.open(\'http://www.facebook.com/sharer.php?u='+thisEditURL+'&amp;t='+thisTitle+'\', \'Facebook\',\'toolbar=no,width=800,height=600,resizable=yes,scrollbars=yes\'); return false;">Facebook</a> | <a href="http://www.google.com/bookmarks/mark?op=add&amp;hl=en&amp;bkmk='+thisEditURL+'&amp;annotation=&amp;labels=&amp;title='+thisTitle+'" target="_blank" onclick="window.open(\'http://www.google.com/bookmarks/mark?op=add&amp;hl=en&amp;bkmk='+thisEditURL+'&amp;annotation=&amp;labels=&amp;title='+thisTitle+'\', \'Google\',\'toolbar=no,width=800,height=600,resizable=yes,scrollbars=yes\'); return false;">Google</a></p>';
}	
}

function mainMediaPlayer(streamURL,type)
{
var mmp;
if (mmp = document.getElementById('mainMedia'))
{
mmp.innerHTML = '<div id="mainMediaPlayer"><embed src="'+streamURL+'?WT.svl=embedded&WT.cg_n=liveStream" width="425" height="319" autostart="1" id="media_item" type="application/x-mplayer2" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/" showcontrols="1" showstatusbar="0" name="media_item"></embed></div>';
}
}

var tickerPos=1;
var t;

function timedCount()
{
document.getElementById("weatherBar").innerHTML=ticker_array[tickerPos];
if(tickerPos == ticker_array.length-1){tickerPos = 1;} else{tickerPos = tickerPos + 1;}
t=setTimeout("timedCount()",10000);
}

function ajaxRequest(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])
   }
   catch(e){
    //suppress error
   }
  }
 }
 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  return new XMLHttpRequest()
 else
  return false
}

//---------------------  old tags_fix_AJAX() remove after a week of publishing

function tags_AJAX() {
	var tags_request=new ajaxRequest()
	tags_request.onreadystatechange = function(){
		if (tags_request.readyState==4){
			if (tags_request.status==200 || window.location.href.indexOf("http")==-1){
				var xmldata = tags_request.responseXML; //retrieve result as an XML object
				var xml_map = xmldata.getElementsByTagName("mp");
				var xml_map_length = xml_map.length;
		
				var tagList = document.getElementsByTagName("li");
				for (var h = 0; h < tagList.length; h++)
				{

					if (tagList[h].className == "tag_item")
					{
						var wallace_map = tagList[h].getElementsByTagName("a");
						var wallace_subject = wallace_map[0].innerHTML;

						for (var i=0; i<xml_map_length; i++)
						{
							var xml_subject = xml_map[i].getAttributeNode('sb').nodeValue;
							if (xml_subject == wallace_subject)
							{
								if (xml_map[i].getAttributeNode('ed_as')) {var screen_name = xml_map[i].getAttributeNode('ed_as').nodeValue;}
								else {var screen_name = xml_map[i].getAttributeNode('as').nodeValue;}
								var file_name = xml_map[i].getAttributeNode('fn').nodeValue;
								tagList[h].innerHTML = '<a href="/tags.htm?tag=' + screen_name +'">' + screen_name + '</a>';
							}
						}
						
					}
				}
			} else {alert("An error has occured requesting tags.xml")}
		}
 	}
 tags_request.open("GET", "/xml/tags.xml", true);
 tags_request.send(null);
}

function tags_fix_AJAX() {
	var tags_request=new ajaxRequest()
	tags_request.onreadystatechange = function(){
		if (tags_request.readyState==4){
			if (tags_request.status==200 || window.location.href.indexOf("http")==-1){
				var xmldata = tags_request.responseXML; //retrieve result as an XML object
				var xml_map = xmldata.getElementsByTagName("mp");
				var xml_map_length = xml_map.length;
				if(tagList[1]!=''){
				var tagResults = '<li class="first"><strong>Tags:</strong></li>';

				for (var h = 1; h < tagList.length; h++)
				{
					if(tagList[h]!='')
					{
						for (var i=0; i<xml_map_length; i++)
						{
							
							var xml_subject = xml_map[i].getAttributeNode('sb').nodeValue.toLowerCase();	
							if (xml_subject == tagList[h].toLowerCase())
							{
								if (xml_map[i].getAttributeNode('ed_as')) {var screen_name = xml_map[i].getAttributeNode('ed_as').nodeValue;}
								else {var screen_name = xml_map[i].getAttributeNode('as').nodeValue;}
								var file_name = xml_map[i].getAttributeNode('fn').nodeValue;
										
								tagResults += '<li class="tag_item"><a href="/tags.htm?tag=' + screen_name +'">' + screen_name + '</a></li>';
							}
						}
					}
				}
				document.getElementById("ulTags").innerHTML=tagResults;}

				
			} else {alert("An error has occured requesting tags.xml")}
		}
 	}
 tags_request.open("GET", "/xml/tags.xml", true);
 tags_request.send(null);
}

//---------------------  Media functions required by all pages with media

// parameter "insertafter"- required for inpage players usually the object "this"

function paramcheck (pass_mediaurl, pass_insertafter, pass_mywidth, pass_myheight, pass_autoplay, pass_guid, pass_caption, pass_mediatitle, pass_medialink) {
	if (!pass_mediaurl) {return true} else {mediaurl = pass_mediaurl};
	if (!pass_insertafter) {return true} else {insertafter = pass_insertafter};
	if (!pass_mywidth) {mywidth = '100%'} else {	mywidth = pass_mywidth};
	if (!pass_myheight) {myheight = mywidth} else {myheight = pass_myheight	};
	if (!pass_autoplay) {autoplay = 'true'} else {autoplay = pass_autoplay};
	if (!pass_caption) {caption = ""} else {caption = pass_caption};
	if (!pass_mediatitle) {mediatitle = ""} else {mediatitle = pass_mediatitle};
	if (!pass_medialink) {medialink = ""} else {medialink = pass_medialink};

	playerstyle = 'inpage';
}

function showVideo (mediaurl, insertafter, mywidth, autoplay, guid, caption, mediatitle, medialink) {
	paramcheck(mediaurl, insertafter, mywidth, "", autoplay, guid, caption, mediatitle, medialink);
	media_type = "video";
	play_media();
		return false;
}

function showAudio (mediaurl, insertafter, mywidth, autoplay, guid, caption, mediatitle, medialink) {
	paramcheck(mediaurl, insertafter, mywidth, "", autoplay, guid, caption, mediatitle, medialink);
	media_type = "audio";
	play_media();
		return false;
}

function showPhotos () {
	slideshow = new Array();
	slideshowIndex = 0;
	gallery_items = (gallery_array.length - 1) /2;
	j = 1;
	// Load items into slideshow
	for (var i=0; i<gallery_items; i++) {
		slideshow[i] = new StoryPhoto(gallery_array[j], "285", gallery_array[j+1]);
		j = j + 2;
	}
	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('sspPhoto')) {
			var div = document.createElement('div');
			div.id = 'sspPhotoNav';
			div.innerHTML = '<a href="javascript:slideshowPrev();"><img style="float:left;" src="/img/common/space.gif" width="20" height="20" /></a><a href="javascript:slideshowNext();"><img style="float:right;" src="/img/common/space.gif" width="20" height="20" /></a>';
			sp.insertBefore(div, 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, navtext;
	if (img = document.getElementById('sspPhotoImg')) {
		if (img.src != slideshow[slideshowIndex].src) {
			img.src = slideshow[slideshowIndex].src;
			img.width = slideshow[slideshowIndex].width;
			img.title = slideshow[slideshowIndex].caption;
			img.alt = img.title;
		}
	}
	if (caption = document.getElementById('sspPhotoCaption')) {
		caption.innerHTML = slideshow[slideshowIndex].caption;
	}
	if (navtext = document.getElementById('sspPhotoNo')) {
		if(gallery_items > 1)
		{navtext.innerHTML = 'PHOTO ' + (slideshowIndex+1) + ' of ' + slideshow.length;}
		else {navtext.innerHTML = 'PHOTO ';}
	}
}

function StoryPhoto (src, width, caption) {
	this.src = src;
	this.width = width;
	this.caption = caption;
}

function play_media () {
	if (playerstyle == "external" || playerstyle == "") {
		open(mediaurl, "mediaplayer");
	} else {
	player_width = 285; //default size
	player_height = 160; //default size
	media_item = "";
	
		if (mediaurl.indexOf('.flv') != -1) {
			//newsplayer currently forces autoplay
			media_item = '<object class="player_flv" type="application/x-shockwave-flash" data="http://www.radioaustralianews.net.au/flash/flvplayer.swf" width="' + player_width + '" height="' + player_height + '">';
			media_item += '<param name="movie" value="http://www.radioaustralianews.net.au/flash/flvplayer.swf" />';
			media_item += '<param name="allowFullScreen" value="true" />';
			media_item += '<param name="wmode" value="transparent" />';
			media_item += '<param name="flashvars" value="mediaURL=' + mediaurl + '&autoPlay=' + autoplay + '" />';
			media_item += '<\/object>';
		}
		
		if (mediaurl.indexOf('.mp3') != -1) {
			//newsplayer currently forces autoplay
			player_height = Math.round(player_width / 7); 
			media_item = '<object class="player_mp3" type="application/x-shockwave-flash" data="http://www.abc.net.au/australianetwork/flash/player_mp3.swf" width="' + player_width + '" height="' + player_height + '">';
			media_item += '<param name="movie" value="http://www.abc.net.au/australianetwork/flash/player_mp3.swf" />';
			media_item += '<param name="wmode" value="transparent" />';
			media_item += '<param name="flashvars" value="mediaURL=' + mediaurl + '&autoPlay=' + autoplay + '&glassyplayer=false&playershadow=false&playerbgcolor=#2E2E2E&pausecolor=#FFFFFF&scrubcolor=#FFFFFF&scrubbgcolor=#1A1A1A&itemtimecolor=#FFFFFF&volumeiconcolor=#FFFFFF&timetextcolor=#FFFFFF&loadingbarcolor=#777777&loadingbgcolor=#FFFFFF" />';
			media_item += '<\/object>';
		}
		
		if ((mediaurl.indexOf('.jp') != -1) || (mediaurl.indexOf('.gif') != -1)) {
			media_item += '<img src="' + mediaurl + '" alt="" title="" border="0" width="' + player_width + '" />';
		}
		
		if (mediaurl.indexOf('google_map.htm') != -1) {
			media_item += '<iframe src="' + mediaurl + '" width="' + player_width  + '" height="' + player_height + '" frameborder="0" scrolling="no"></iframe>';
		}
		
		startInpage(media_item);
	}
}


function showMap (insertafter, mywidth, latitude, longitude, caption) {
	if (!latitude) return true;
	if (!longitude) return true;
	mediaurl = 'http://www.abc.net.au/local/maps/google_map.htm?latitude=' + encodeURIComponent(latitude) + '&amp;longitude=' + encodeURIComponent(longitude) + '&amp;caption=' + encodeURIComponent(caption);
	paramcheck (mediaurl, insertafter, mywidth, '', '', '', '', caption, '', '');
	media_type = "map";
	play_media();

	return false;
}



function startInpage (media_item) {
	if (temp = document.getElementById("inpageplayer")) {
		if (temp.parentNode == insertafter.parentNode) {  // i have the player
			removeInpage();
			return false;
		} else {   // my brother has the player
			removeInpage();
			var div = document.createElement("DIV");
			div.id = "inpageplayer";
			insertafter.parentNode.insertBefore(div, insertafter.nextSibling);
			div.innerHTML = media_item;
		}
	} else {   // nobody has the player
		var div = document.createElement('DIV');
		div.id = "inpageplayer";
		insertafter.parentNode.insertBefore(div, insertafter.nextSibling);
		div.innerHTML = media_item;
	}
}

function removeInpage() {
	if (temp = document.getElementById("inpageplayer")) {
		temp.innerHTML = "";
		temp.parentNode.removeChild(temp);
		delete temp;
	}
}


function addUnloadEvent(func)
{
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function'){
    	window.onunload = func;
	} else {
		window.onunload = function(){ oldonunload(); func(); };
	}
}


addUnloadEvent(removeInpage);
