/**
 * Javascript that syncs the player and the text.
 * @author phagon 
 * This is designed to work with JW Player 4.0.46
 */


function addLoadListener(fn)
{
	if (typeof window.addEventListener != 'undefined')
	{
		window.addEventListener('load', fn, false);
	}
	else if (typeof document.addEventListener != 'undefined')
	{
		document.addEventListener('load', fn, false);
	}
	else if (typeof window.attachEvent != 'undefined')
	{
		window.attachEvent('onload', fn);
	}
	else
	{
		return false;
	}
	
	return true;
};




function attachEventListener(target, eventType, functionRef, capture)
{
	if (typeof target.addEventListener != "undefined")
	{
		target.addEventListener(eventType, functionRef, capture);
	}
	else if (typeof target.attachEvent != "undefined")
	{
		var functionString = eventType + functionRef;
		target["e" + functionString] = functionRef;
        
		target[functionString] = function(event)
		{
			if(typeof event == "undefined")
			{
				event = window.event
			};

			target["e" + functionString](event);
        };
        
		target.attachEvent("on" + eventType, target[functionString]);
	}
	else
	{
		eventType = "on" + eventType;

		if (typeof target[eventType] == "function")
		{
			var oldListener = target[eventType];

			target[eventType] = function()
			{
				oldListener();

				return functionRef();
			}
		}
		else
		{
			target[eventType] = functionRef;
		}
	}

	return true;
};





var player;
var elapsedTime;


addLoadListener(insertTimecodes);
addLoadListener(insertSilent);
addLoadListener(playerReady);
//addLoadListener(ie7Fix);

seek='false';

// Set a global variable so we can detect if a user clicks
// on a speaker icon before they have clicked on the play button
notPlaying='true';


//addEventListener(scrub);


// This adds a stop link to the start of the document
// CSS hides it off the screen, but it is available for users 
// with screen readers so they can easily stop the audio playing
// otherwise the audio plays and the transcript is read out - very confusing
function insertSilent() {
	//insert a link before the header
	// innerHTML is ugly but quick
		
	var container=document.getElementsByTagName("body");
	var insertBefore=document.getElementById("header");
	var para=document.createElement("p");
	para.setAttribute("id","silent");
	para.innerHTML='<a href="#" onclick="startAudio(); return false;">Play audio</a> <a href="#" onclick="stopAudio(); notPlaying=true; return false;">Stop audio</a>';
	//container[0].insertBefore(para,insertBefore);
}




function getPlayer(gid) {
	if(navigator.appName.indexOf("Microsoft") != -1) {
		return window[gid];
	} else {
		return document[gid];
	}
};


function playerReady(obj) {
	var id = obj['id'];
	// Filthy hack!!  For some reason id isn't coming through on windows or linux.
if (id == null) {
	id = 'jstest';
}
	var version = obj['version'];
	var client = obj['client'];
//	try {
		player = getPlayer(id);
		//alert('the videoplayer '+id+' has been instantiated');
		//player = document.getElementById(id);
		
//		if (player.addControllerListener==null) {
//			setTimeout("playerReady",1000);
//			return;
//		}
		
		player.addControllerListener("MUTE","muteTracker");
		player.addControllerListener('ITEM','currentItem');
		player.addControllerListener('PLAY','currentState');
		player.addModelListener('STATE', 'stateMonitor');
		player.addModelListener('TIME','currentTime');
		player.addModelListener('BUFFER', 'bufferMonitor');
//	} catch (e) {
//		console.log(player.addControllerListener==null);
//		console.log(e);
//		return false;
//	}
//	if (Browser.Engine.trident) {
//		$("mp3").setStyle("position","absolute");
//		$("mp3").setStyle("top","80px");
//	}
};


function muteTracker(obj) { 
	muteState=obj.state;
	//Write to screen to debug
	//document.getElementById('mute-state').innerHTML = muteState;
	};


function stateMonitor(obj) {
	var newState=obj.newstate;
	var oldState=obj.oldstate;
	//Write to screen to debug
	//document.getElementById('playback-state').innerHTML = newState;
	//document.getElementById('old-state').innerHTML = oldState;
	//document.getElementById('seek').innerHTML = seek;
	
	
	/*
	if(newState == 'PLAYING') {


	}
	*/
	
	
	if(obj.newstate == 'BUFFERING') {
		
	}

	
};

function startAudio() {
	player.sendEvent('PLAY',true);
	}

function stopAudio() {
	player.sendEvent('PLAY',false);
	}

function bufferMonitor(obj) {
	buffered=obj.percentage;
	//Write to screen to debug
	//document.getElementById('buffered').innerHTML = buffered;
}

function currentState(obj) {
	state=obj.state;
	//Write to screen to debug
	//document.getElementById('playback-state').innerHTML = state;
}

function currentItem(obj) {
	playlistItem=obj.index;
	//Write to screen to debug
	//document.getElementById('playbackItem-display').innerHTML = playlistItem;
}

function currentTime(obj) {
	elapsedTime=parseInt(obj.position);	
	//Write to screen to debug
	//document.getElementById('playback-display').innerHTML = elapsedTime;

	// Update transcript with highlighting

	// Find all the table rows in the transcript
		var rowTimeCode=new Array();
		var tableRow=new Array();
		
		// Loop through the tbody objects within in the transcript
		var objTranscript=document.getElementById("transcript");
		var tableBody=objTranscript.getElementsByTagName("tbody");	
		for(k=0;k<tableBody.length;k++) {
			
			// Loop through the table rows for each tbody object
			var rowTimeCode=tableBody[k].getElementsByTagName("tr");
		
			for(i=0;i<rowTimeCode.length;i++) { 
				
				tableRow[i]=rowTimeCode[i].getAttribute('id');


				// Strip the "file" and the "t" out of the row ID
				// This gives us both the playlist number the starting timecode for the table row
				var pattern=/file([0-9]+)-t([0-9]+)/;
				var string=tableRow[i];
				var playlistTable=string.replace(pattern,"$1");
				var tableRowTime=string.replace(pattern,"$2");
	
				// If the current tablerow is less than the current playing time 
				// highlight the row, as long as it's in the currently playing transcript
				// otherwise remove the highlight from the row
				if ((tableRowTime<elapsedTime && playlistItem==k) || (playlistItem>k)) {
					//alert(string);
					addClass(tableRow[i],"current");
				} else {
					deleteClass(tableRow[i]);
				}
			}
		} 

	if(seek=='true') {
		// Check if we are at the right playlist
		if(playlistItem==currentPlaylist && (elapsedTime>0 && elapsedTime!=timeCodePos)) {
			
				player.sendEvent('SEEK', timeCodePos);
				seek='false';

		}
	}


}






// This loops through the summary and adds an icon and a link
// allowing the user to jump to a particular section of the audio file
function insertTimecodes() {
	var tables=new Array();
	var trs=new Array();
	var trs=new Array();
	var trID=new Array();
	
	var tables = document.getElementsByTagName("table");
	for (var i=0;i<tables.length;i++) {
		var tbody = tables[i].getElementsByTagName("tbody")[0];
		var trs = tbody.getElementsByTagName("tr");
		for (var j=0;j<trs.length;j++)	{
			
			var alertMsg=trs[j].getAttribute("id");
			var pattern=/file([0-9]+)-t([0-9]+)/;
			var string=alertMsg;
			var playlistTable=string.replace(pattern,"$1");
			var tableRowTime=string.replace(pattern,"$2");
			
			var tds=trs[j].cells;
			var tdsContent=tds[0].innerHTML;
			//tds[0].innerHTML=tdsContent +' <img src="../../images/sound.png" alt="play" onclick="scrubPlay('+ playlistTable +','+ tableRowTime +');" class="speaker" />';
			
			//Lets do an IE6 check here
			if (typeof document.body.style.maxHeight != "undefined") {
  			// IE 7, mozilla, safari, opera 9
				tds[0].innerHTML=tdsContent +' <img src="../images/sound.png" alt="play" onclick="scrubPlay('+ playlistTable +','+ tableRowTime +');" class="speaker" />';
			} else {
  		// IE6, older browsers
				tds[0].innerHTML=tdsContent +' <img src="../images/sound.gif" alt="play" onclick="scrubPlay('+ playlistTable +','+ tableRowTime +');" class="speaker" />';
			}
			
		}
	}
	return true;
}







// This responds to a click event on the speaker icon
// and moves the playhead to the relevant location
function scrubPlay(file,timeCode) {
	
	// If the audio hasn't been started
	// start playing the file and jump to the correct
	// playlist and timecode
	if(notPlaying=='true') {
		//Start playing
		player.sendEvent('PLAY', true);
		// Jump to the correct playlist
		for(i=0;i<file+1;i++) {
			player.sendEvent('NEXT');
		}	
		// Jump to the correct timecode
		player.sendEvent('SEEK', timeCode);
		// once it's playing set the global variable to false
		if(player.getConfig().state=='BUFFERING' || player.getConfig().state=='PLAYING') {
			notPlaying='false';
		}
	}
	
	//check to see if the current playlist item is the same as the requested item
	var currentPlaylistItem=player.getConfig().item;
	//alert("File: "+file+", currentPlaylistItem: "+playlistItem);
	
	if(file==playlistItem) {
		// We are in the same playlist item and we just need to jump to the location
		player.sendEvent('SEEK', timeCode);
	} else {
		// We are jumping to a different playlist item
		if(file<playlistItem) {
			//go back
			var stepBack=playlistItem-file;
			for(i=0;i<stepBack;i++) {
				player.sendEvent('PREV');
			}
		} else {
			//go forward
			var stepForward=file-playlistItem;
			for(i=0;i<stepForward;i++) {
				player.sendEvent('NEXT');
			}
		}
		// OK we are now at the right file & we need to do a little hack to get it to
		// get it working at the correct timecode in the new playlist item.
		// This is due to the load and buffering of the new file
		
		// Set a bunch of global variables
		seek='true';
		currentPlaylist=file;
		timeCodePos=timeCode;	
	}
}



function addClass(objElement,strClass) {
	var tableRow=document.getElementById(objElement);
	if(!tableRow.className) {
		tableRow.className = strClass;
	} 
}


function deleteClass(objElement) {
	var tableRow=document.getElementById(objElement);
	if(tableRow.className) {
		tableRow.setAttribute("class","");
		tableRow.className = "";
	}
}

function ie7Fix() {
	if (Browser.Engine.trident) {
		$("mp3").setStyle("position","absolute");
		$("mp3").setStyle("top","80px");
	}
}

