/***** 
Q: How to embed a single vodcast into the page?
-----------------------------------------------
1. include this SSI into the page
<!--#include virtual="/global/common/inc/global_media.html" -->

2. add this code to the body (remember to change the FLV url)
  <script><!--
  var mediaType="vodcast";
  embedMediaFlash("/xxx.flv", "true", "targetDivId");
  //-->
  </script>

Q: Possible parameters for controlling vodcast/podcast?
-------------------------------------------------------
one or more of the following (note, do NOT incl file extension):
1. playlistPath=xxx
2. startIndex=2 (buffers 2nd playlist item)
3. flvPath=xxx
4. mp3Path=xxx

*****/

var xmlUrl, xmlDoc;
var mediaType;
var startIndex;
var errorMsg = false;
var domainName = window.location.host;
var redirectDomain = (domainName.indexOf("omy")==-1) ? "http://www.omy.sg" : ""; //if called from other domain (eg. mypaper.sg) then use SWF files from omy server - else this is blank

//called just before loading the top banner ad
function loadxml(media){
	mediaType = media; //eg. "vodcast", "podcast", "gallery"
	var playlistPath = getQryValue("playlistPath");
	if (playlistPath) {
		xmlUrl = playlistPath;
		if (playlistPath.slice(-4)!=".xml") xmlUrl = playlistPath+".xml"; //using slice since substr negative doesnt work in IE
		if (xmlUrl.indexOf(domainName)==-1 && xmlUrl.charAt(0)!="/") //xmlfeed is from another domain
			sendXMLRequest(xmlUrl,setXMLFromXMLRequest,false); //send to proxy script to populate xmlDoc
		else importXML();
	}
	else if (!getQryValue("flvPath") && !getQryValue("mp3Path"))
		errorMsg = "No media specified"; //no valid qrystr found (set now to display later in generateHTML() when divs are loaded)
}


/***** HANDLE XML FILES *****/
//used for remote XML
function setXMLFromXMLRequest(req) {
	xmlDoc = req.responseXML; //response from proxy script
	if (xmlDoc.getElementsByTagName('omy').length>0) setBodyId(); //response is a proper XML file (not HTML) and can find <omy> node
	else errorMsg = "Media listing unavailable"; //XML response could not be found
}

//used for local XML
function importXML() {
	if (document.implementation && document.implementation.createDocument){
		xmlDoc = document.implementation.createDocument('', '', null);
		xmlDoc.load(xmlUrl);
		//omyNode = xmlDoc.firstChild;
		xmlDoc.onload = setBodyId;
	}
	else if (window.ActiveXObject){
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false; //dont load XML before the URL has loaded
		xmlDoc.load(xmlUrl);
		//omyNode = xmlDoc.firstChild.nextSibling;
		setBodyId();
		/*xmlDoc.onreadystatechange = function () {
			if (xmlDoc.readyState == 4) generateHTML();
		};*/
 	}
	else{
		document.getElementById("mediaHolder").innerHTML = "Your browser is unable to load XML files";
		return;
	}
}

var xmlDocStr = ""; //global to be used by gallery
//retrieves the section name from the xml and swaps into body id
//in order to set correct ad/netrating tags
function setBodyId() {
	if (xmlDoc.getElementsByTagName("omy").length==0) {
		errorMsg = "Media listing unavailable"; //XML file could not be found
		return;
	}
	var sectionName = xmlDoc.getElementsByTagName("omy")[0].getAttribute('section');
	if (sectionName) document.body.id = sectionName; //overwrite body id with the section pulled from the xml playlist
	
	//XML is alr loaded by now, populate the custom-escaped XML str into "xmlDocStr"
	if (mediaType=="gallery") xmlDocStr = customEscape(XMLtoString(xmlDoc));
}


/***** HANDLE PLAYER *****/
//called from HTML page, after "mediaHolder" div has alr been loaded
var mediaTimer;
function chkXML() {
	mediaTimer = setInterval(loadPlayer, 300);	
}
function loadPlayer() {
	if (errorMsg) {
		displayError(errorMsg);
		return; //dont continue to load XML or flash
	}
	
	//possible media params
	if (getQryValue("flvPath")) {//no playlist, only single FLV file
		clearInterval(mediaTimer);
		embedMediaFlash(getQryValue("flvPath")+".flv"); //directly embed player, passing it a flashvar to the FLV file
	}
	else if (getQryValue("mp3Path")) {
		clearInterval(mediaTimer);
		embedMediaFlash(getQryValue("mp3Path")+".mp3");
	}
	else if (getQryValue("playlistPath")) {
		if (xmlDoc.getElementsByTagName("omy")[0].getAttribute('articleUrl').length==0) { //no url provided (efusion's xml)
			document.getElementById("btn_readArticle").style.visibility = "hidden"; //hide the "Read this Article" button
		}
		
		//make sure that xml has loaded and is readable before flash is loaded
		if (mediaType=="gallery") {
			if (xmlDocStr!="") { //xmlDocStr is ready
				clearInterval(mediaTimer);
				embedMediaFlash(xmlDocStr);
			}
		}
		else { //vodcast or podcast
			if (xmlDoc.getElementsByTagName("omy").length>0) { //xmlDoc is ready
				clearInterval(mediaTimer);
				if (getQryValue("startIndex")) {
					startIndex = parseInt(getQryValue("startIndex"))-1;
				}
				if (getQryValue("playlistPath")) generateFromPlaylist();
			}
		}
	}
}

//process the xml playlist
//loads the playlist items and the first vodcast/podcast
function generateFromPlaylist() {
	document.getElementById("mediaArticleHeadline").innerHTML = unescape(xmlDoc.getElementsByTagName("omy")[0].getAttribute('headline'));
	
	//populate playlist items
	if (xmlDoc.getElementsByTagName(mediaType).length==0) { //eg. the <vodcast> or <podcast> node
		displayError("No "+mediaType+"s found in this media listing"); //eg. "no vodcasts found in this media listing"
		return;
	}
	
	var aryMediaNode = xmlDoc.getElementsByTagName(mediaType)[0].getElementsByTagName("media"); //the <media> nodes in eg. <vodcast>
	for (var i=0; i<aryMediaNode.length; i++) { //for this <media> node (if any)
		//set default fields
		var media_img =redirectDomain+"/global/common/media/imgs/tn_"+mediaType+".gif"; //the default thumbnail
		var media_title = mediaType.substr(0, 1).toUpperCase() + mediaType.substr(1) + " " + (i+1); //eg. "Vodcast 2"
		var media_duration = "";
		for (var j=0; j<aryMediaNode[i].childNodes.length; j++) { //for the child nodes of this <media> node
			var aryMediaChild = aryMediaNode[i].childNodes[j]; //ary of <src>, <img>, <title>, <duration> nodes
			if (aryMediaChild.nodeType==1) { //#text
				if (aryMediaChild.nodeName=="src") var media_src = aryMediaChild.childNodes[0].nodeValue;
				else if (aryMediaChild.nodeName=="img" && aryMediaChild.hasChildNodes()) media_img = aryMediaChild.childNodes[0].nodeValue;
				else if (aryMediaChild.nodeName=="title" && aryMediaChild.hasChildNodes()) media_title = aryMediaChild.childNodes[0].nodeValue;
				else if (aryMediaChild.nodeName=="duration" && aryMediaChild.hasChildNodes()) media_duration = aryMediaChild.childNodes[0].nodeValue;
			}
		}
		
		var str='';
		var media_title_rpl = media_title.replace(/'/g, "\\'"); //replace all single quotes so that it will pass thru loadFlv() fine
		str+='<dt><a href="javascript:loadFlv(\''+media_src+'\', \''+media_title_rpl+'\')"><img src="'+media_img+'" width="100" height="75" \/><\/a><\/dt>';
		str+='<dd><a href="javascript:loadFlv(\''+media_src+'\', \''+media_title_rpl+'\')">'+getTitleLink(media_title)+'<\/a><div class="timedate">'+unescape(media_duration);
		str+='<\/div><\/dd>';
		
		//append the playlist item to the DOM
		document.getElementById("mediaPlaylist").innerHTML += str;
		
		//startIndex=0 then startIndex==-1 and !startIndex==false
		//no startIndex then startIndex==null and !startIndex==true
		if (startIndex && startIndex==-1 && i==0) {
			embedMediaFlash(media_src); //pass first flv url as param
			document.getElementById("mediaItemTitle").innerHTML = unescape(media_title);
		}
		else if (	(startIndex && startIndex==i) || //if startIndex specified and this is the requested playlist item,
					(startIndex && startIndex>=aryMediaNode.length) || //OR if specified and out of bounds (no such index)
				  	(!startIndex && i==0)) { //OR if not specified and this is the first playlist item
			embedMediaFlash(media_src); //pass first flv url as param
			document.getElementById("mediaItemTitle").innerHTML = unescape(media_title);
		}
	}
}

//uses SWFObject to embed flash vodcast/podcast/gallery into the element with id=trgId, or "mediaHolder" as default trgId
function embedMediaFlash(media_src, media_autoplay, trgId) {
	//vodcast/podcast alr does this checking in generateHTML() this is primarily for gallery which does not run generateHTML()
	if (errorMsg) {
		displayError(errorMsg);
		return; //dont continue to load XML or flash
	}
	
	if (mediaType=="vodcast" || mediaType=="podcast") {
		var width = "320";
		var height = "306";
	}
	else if (mediaType=="gallery") {
		var width = "615";
		var height = "430";
	}
	else if (mediaType=="vodcast_180x190") {
		var width = "180";
		var height = "190";
	}
	else if (mediaType=="vodcast_240x215") {
		var width = "240";
		var height = "215";
	}
	
	var media_autoplay = (typeof(media_autoplay)=="undefined") ?  true : media_autoplay; //default is to autoplay
	var divId = (trgId) ? trgId : "mediaHolder"; //default is to embed into <div id="mediaHolder">
	
	var so = new SWFObject(redirectDomain+"/global/common/media/swf/"+mediaType+".swf", "mediaObj", width, height, "8", ""); //redirectDomain is blank if called frm omy server, else is omy server
	so.addParam("wmode", "transparent");
	if (mediaType=="gallery") so.addVariable("xmlresponse", unescape(media_src)); //pull a global var
	else {
		if (media_src.substr(0,7)!="http://") media_src = "http://"+domainName+media_src;
		so.addVariable("firstMediaSrc", media_src);
		so.addVariable("autoPlayMedia", media_autoplay);
	}
	so.useExpressInstall(redirectDomain+"/global/common/swf/expressinstall.swf");
	
	so.write(divId);
}

//the function that calls the AS function "sendFlvToAS()"
function loadFlv(src, title) {
	document.getElementById("mediaObj").sendFlvToAS(src);
	if (document.getElementById("mediaItemTitle")) document.getElementById("mediaItemTitle").innerHTML = unescape(title);
	
	//urchinTracker(); //call google analytics
	if (typeof(pageTracker)!='undefined') pageTracker._trackPageview();
}

function getTitleLink(media_title) {
	var maxChineseChars = 5;
	var chineseCharsLength = 6; //eg. "%u5730" - must handle 6 chars at once in case there are chinese chars
	var maxChars = maxChineseChars*chineseCharsLength;
	
	var str = unescape(media_title);
	if (str.length>maxChars) return unescape(str.substr(0,maxChars))+'...';
	else return str;
}

function displayError(msg) {
	document.getElementById("mediaHolder").innerHTML = "<div class='errorMsg'><h4>"+msg+"</h4></div>";
	document.title += " - "+msg; //change title as well to track hits in google analytics
}

/***** MISC FUNCTIONS *****/
//used only by gallery, to custom-escape an XML string
//used because an unescaped string is passed to Flash (since AS cannot unescape a JS escape())
function customEscape(str) {
	str = str.replace(/"/g, "'" ); //cannot have double quotes else will break the text when sending to flash
	str = str.replace(/%u201C/g, "{quot}"); //cannot have open qoutes, replace with single quote
	str = str.replace(/%u201D/g, "{quot}"); //cannot have close quotes
	str = str.replace(/%22/g, "{quot}"); //cannot have double quotes
	str = str.replace(/%27/g, "{quot}"); //cannot have single quotes	
	str = str.replace(/%26/g, "{amp}"); //cannot have & characters
	str = str.replace(/&amp;/g, "{amp}"); //cannot have & characters	
	str = str.replace(/&lt;/g, "{lt}"); //cannot have < characters
	str = str.replace(/&gt;/g, "{gt}"); //cannot have > characters
	return str;
}

//called from media popups, to launch article page: "launchPage()" OR launch homepage "launchPage('homepage')"
//if the parent opener is present, loads in that window, else loads in new window
function launchPage() {
	if (arguments.length==0) url = unescape(xmlDoc.getElementsByTagName("omy")[0].getAttribute('articleUrl'));
	else if (arguments.length==1 && arguments[0]=="homepage") url = "http://"+window.location.host;
	
	if (url=='') return;
	
	if (!window.opener || window.opener.closed) {
		var articlePopup = window.open(url);
		articlePopup.focus();
	}
	else { //window.opener && window.opener.open && !window.opener.closed
		window.opener.location.href = url;
		window.opener.focus();
	}
	self.close();
}


/***** embed an mp3 player (identical to t2s cept doesnt redirect path) *****/
function embedMp3Flash(media_src, trgId, saveAsFilename, media_autoplay) {
	var so = new SWFObject(redirectDomain+"/global/common/media/swf/t2s.swf", "mp3Obj"+trgId, "227", "43", "8", "");
	so.addParam("wmode", "transparent");
	so.addVariable("mp3player", true);
	so.addVariable("t2sFilename", media_src);
	so.addVariable("saveAsFilename", saveAsFilename);
	so.addVariable("autoPlayMedia", media_autoplay);
	so.useExpressInstall('/global/common/swf/expressinstall.swf');
	so.write(trgId);
}
