var dateToday = new Date();

function formatPublished() {
	var tagDiv = document.getElementsByTagName("span");
	for (var i = 0; i < tagDiv.length; i++) {
		  if (tagDiv[i].className == "timestamp") {
			var objDateString = new Object();
			objDateString["dateTime"] = tagDiv[i].innerHTML;
			DateString = tagDiv[i].innerHTML.substring(0,16);
			var itemDate = new Date(objDateString["dateTime"] );
			var total_minutes = (dateToday - itemDate) / 60000;
			if (total_minutes < 60) {
				tagDiv[i].innerHTML = Math.floor(total_minutes) + " minutes ago"; 
			} else if (total_minutes < 119) {
				total_minutes = Math.floor(total_minutes - 60);
				tagDiv[i].innerHTML = "1 hour and " + total_minutes + " minutes ago";
			} else if (total_minutes < 720) {
				var total_hours = Math.floor(total_minutes / 60);
				total_minutes = Math.floor(total_minutes - (total_hours * 60));
				tagDiv[i].innerHTML = total_hours + " hours and " + total_minutes + " minutes ago";
			};
		};
	};
}

function editlinks () {
	var a = document.getElementsByTagName('A');
	var storyPageRegex = /news\/(items|newsitems|stories|video|audio|photos)\/[0-9]{4}.*/;
	for (var i=0; i<a.length; i++) if (storyPageRegex.test(a[i].href)) a[i].href += (a[i].href.indexOf('?') != -1 ? '&' : '?') + 'site=australianetwork';
}

//---------------------  Media functions required by all pages with media


// 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;
}

// 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_insertafter == "masterplayer" ) { if (!document.getElementById("masterplayer")) {return true}; };
	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_guid) {guid = null} else {guid = pass_guid};
	if (!pass_caption) {caption = ""} else {caption = pass_caption};
	if (!pass_mediatitle) {mediatitle = ""} else {mediatitle = pass_mediatitle};
	if (!pass_medialink) {medialink = ""} else {medialink = pass_medialink};

	connection = 'hi';
	playerstyle = 'popup';
	videoformat = 'inpage';
	audioformat = 'mp3';
}

function showVideo (mediaurl, insertafter, mywidth, autoplay, guid, caption, mediatitle, medialink) {
	paramcheck(mediaurl, insertafter, mywidth, "", autoplay, guid, caption, mediatitle, medialink);
	media_type = "video";
	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() { ajax_call(ajaxobj); };
		ajaxobj.open('GET', mediaurl, true);
		ajaxobj.send('');
	} else {
		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";
	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() { ajax_call(ajaxobj); };
		ajaxobj.open('GET', mediaurl, true);
		ajaxobj.send('');
	} else {
		play_media();
	}
	return false;
}

function showPhotos (mediaurl, insertafter, mywidth, myheight, caption, mediatitle, medialink) {
	paramcheck(mediaurl, insertafter, mywidth, myheight, "", "", caption, mediatitle, medialink);
	media_type = "photo";
	
	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() { ajax_photo(ajaxobj); };
		ajaxobj.open('GET', mediaurl, true);
		ajaxobj.send('');
	} else {
		play_media();
	}
	
	return false;
}

function ajax_video() {
	var bestbitrate = 0;
	for (var j=0; j < content.length; j++) {
		if (
			(content[j].getAttribute('type') == 'video/x-flv' && videoformat == 'inpage')
		) {
			if (
				(connection != 'lo' && parseInt(content[j].getAttribute('bitrate'), 10) > bestbitrate)
			) {
				bestbitrate = content[j].getAttribute('bitrate');
				mediaurl = content[j].getAttribute('url');
			};
		};
	};
}

function ajax_audio() {
	for (var j=0; j < content.length; j++) {
		if (
			(content[j].getAttribute('type') == 'audio/mpeg' && (audioformat == 'inpage' || audioformat == 'mp3'))
		) {
			mediaurl = content[j].getAttribute('url');	
		};
	};

}

function ajax_photo(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="http://australianetwork.com/sportslounge/img/button_previous.png" width="26" height="16" /></a></span><span id="storyPhotosNavText"></span><span id="storyPhotosNavNext"><a href="javascript:slideshowNext();"><img src="http://australianetwork.com/sportslounge/img/button_next.png" width="26" height="16" /></a></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) {
			img.src = slideshow[slideshowIndex].src;
			img.width = slideshow[slideshowIndex].width;
			img.height = slideshow[slideshowIndex].height;
			img.title = slideshow[slideshowIndex].caption;
			img.alt = img.title;
		}
	}
	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;
	}
}

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;
		}
	}
}

function StoryPhotoVersion (src, width, height) {
	this.src = src;
	this.width = width;
	this.height = height;
}

function ajax_call (ajaxobj) {	
	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 RSSitems = mediarss.getElementsByTagName('item');
			if (RSSitems.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 < RSSitems.length; i++) {
					if (RSSitems[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>
			}

			content = getElementsByTagNameScope(RSSitems[itemsIndex], 'media', 'content');
			
			if (media_type == "video") {ajax_video();};
			if (media_type == "audio") {ajax_audio();};
			if (media_type == "photo") {ajax_photo();};
			
			caption = RSSitems[itemsIndex].getElementsByTagName('description');
			caption = caption[0].firstChild.nodeValue;
			mediatitle = RSSitems[itemsIndex].getElementsByTagName('title');
			mediatitle = mediatitle[0].firstChild.nodeValue;
			medialink = RSSitems[itemsIndex].getElementsByTagName('link');
			medialink = medialink[0].firstChild.nodeValue;

			if (mediaurl != '') { play_media(); } else { alert('no url supplied'); return true; } // preferred format not available 	
			
		} else { alert('RSS unavailable'); return true; } // Media RSS file not available
	}
}

function play_media () {
	if (playerstyle == "external" || playerstyle == "") {
		open(mediaurl, "mediaplayer");
	} else {
	player_width = 400; //default size
	player_height = 224; //default size
	media_item = "";

		if (mywidth != "100%") {		
			player_width = Math.round(parseInt(mywidth, 10));
			player_height = Math.round(parseInt(myheight, 10));
		} else {
				// default size for: flv, mp3, asx, wma, rm
				if (media_type == "photo") { player_width = 532; }
				if (media_type == "map") { player_width = 532; player_height = 340; }
		}
	
		if (mediaurl.indexOf('.flv') != -1) {
			//newsplayer currently forces autoplay
			media_item = '<object class="player_flv" type="application/x-shockwave-flash" data="http://www.abc.net.au/news/swf/flvplayer.swf" width="' + player_width + '" height="' + player_height + '">';
			media_item += '<param name="movie" value="http://www.abc.net.au/news/swf/flvplayer.swf" />';
			media_item += '<param name="allowFullScreen" value="true" />';
			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>';
		}
		
		startLightbox(media_item);
	}
}

function imgWindow (mediaurl, windowname, mywidth, myheight, caption, mediatitle) {
	showPhotos(mediaurl, "force_popup", mywidth, myheight, caption, mediatitle);
}

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;
}

// 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/, '+')); };


//---------------------  Lightbox Functions required by all pages with media


// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();
	
	if(key == 'x'){ hideLightbox(); }
}


// listenKey()
function listenKey () {	document.onkeypress = getKey; }
	

// showLightbox()
// Preloads images. Pleaces new image in lightbox then centers and displays.
function startLightbox(media_item)
{
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) { selects[i].style.visibility = "hidden"; };
		
	var objOverlay = document.getElementById('lightboxOverlay');
	var objCenter = document.getElementById('lightboxCenter');
	var objLightbox = document.getElementById('lightbox');
	var objTitle = document.getElementById('lightboxTitle');
	var objImage = document.getElementById('lightboxImage');
	var objCaption = document.getElementById('lightboxCaption');

	objOverlay.style.display = 'block';
	objCenter.style.display = 'block';
	objLightbox.style.display = 'block';

	objTitle.innerHTML = '<a href="#" onclick="hideLightbox(); return false;"><img class="lightbox_close" src="http://australianetwork.com/sportslounge/img/button_hide.gif" width="51" height="14" border="0" alt="close" title="close"/></a>' + mediatitle + "&nbsp;";
	objImage.innerHTML = media_item;
	objCaption.innerHTML = caption;
	objOverlay.style.height = document.body.scrollHeight;
	objLightbox.style.width = (player_width + 22) + 'px';
			
	// Check for 'x' keypress
	listenKey();
}


// hideLightbox()
function hideLightbox()
{
	// get objects
	objOverlay = document.getElementById('lightboxOverlay');
	objCenter = document.getElementById('lightboxCenter');
	objLightbox = document.getElementById('lightbox');
	objImage = document.getElementById('lightboxImage');

	// hide lightbox and overlay
	if (objOverlay) {
		objOverlay.style.display = 'none';
		objCenter.style.display = 'none';
		objLightbox.style.display = 'none';
		objImage.innerHTML = '';
		
		selects = document.getElementsByTagName("select");
		for (i = 0; i != selects.length; i++) { selects[i].style.visibility = "visible"; }
	}
	
	// disable keypress listener
	document.onkeypress = '';
}


// initLightbox()
// The function inserts html markup at the top of the page just after "utilities" div.
// These divs are used contain the overlay pattern and the inline image.

function initLightbox()
{
	// the rest of this code inserts html at the top of the page that looks like this:
	// <div id="lightboxOverlay">	onclick="hideLightbox(); </div>
	// <div id="lightboxCenter">
	//	 	<div id="lightbox">
	//			<div id="lightboxTitle" />
	//			<div id="lightboxImage" />
	//			<div id="lightboxCaption"></div>
	//			<div id="lightboxKeyboardMsg"></div>
	// 		</div>
	// </div>
	var objBody = document.getElementById('logo_bar');
	var objBodyParent = objBody.parentNode;
	
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','lightboxOverlay');
	objOverlay.onclick = function () {hideLightbox(); return false;}
	objOverlay.style.display = 'none';
	objBodyParent.insertBefore(objOverlay, objBody);

	var objLightboxCenter = document.createElement("div");
	objLightboxCenter.setAttribute('id','lightboxCenter');
	objLightboxCenter.style.display = 'none';
	objBodyParent.insertBefore(objLightboxCenter, objOverlay.nextSibling);
	
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','lightbox');
	objLightbox.style.display = 'none';
	objLightboxCenter.appendChild(objLightbox);
	
	var objTitle = document.createElement("div");
	objTitle.setAttribute('id','lightboxTitle');
	objLightbox.appendChild(objTitle);
	
	var objImage = document.createElement("div");
	objImage.setAttribute('id','lightboxImage');
	objLightbox.appendChild(objImage);

	var objCaption = document.createElement("div");
	objCaption.setAttribute('id','lightboxCaption');
	objLightbox.appendChild(objCaption);

	var objKeyboardMsg = document.createElement("div");
	objKeyboardMsg.setAttribute('id','lightboxKeyboardMsg');
	objKeyboardMsg.innerHTML = 'PRESS <a href="#" onclick="hideLightbox(); return false;">X</a> TO CLOSE';
	objLightbox.appendChild(objKeyboardMsg);
}


function addUnloadEvent(func)
{
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function'){
    	window.onunload = func;
	} else {
		window.onunload = function(){ oldonunload(); func(); };
	}
}

addUnloadEvent(hideLightbox);
