//var feedURL = "getReleaseList.json";
var chapterStartTimes = [];
var currentChapter = 1;
var totalChapters = 0;
var currentChapterEndTime = 0;
	
/*

	Pulls in chapterization data from thePlatform JSON feed using a jQuery AJAX call

*/
function timecodeToMilliseconds(timecode) {
	if ( timecode.length == 8 ) {
		var hours = Number(timecode.substr(0,2));
	} else {
		var hours = 0;
	}
	var minutes = Number(timecode.substr(3,2));
	var seconds = Number(timecode.substr(6,2));
	
	return ((hours*3600000) + (minutes*60000) + (seconds*1000));
}
function millisecondsToTimecode(seconds)
{
   var input = seconds / 1000;
   var time = (input > 3600 ? Math.floor(input / 3600) + ":" : "") + (input % 3600 < 600 ? "0" : "") + Math.floor(input%3600/60) + ":" + (input%60 < 10 ? "0":"") + input % 60;
time = time.substr(0,5);
	if ( time.substr(0,1) == "0" ) {
		return time.substr(1);
	} else {
	 return time;
 }
}

function checkForChapterJump(e) {
	if ( $(document).getUrlParam("chapter") != null ) {
		if ( $(document).getUrlParam("chapter") == Number($(document).getUrlParam("chapter")) ) {
			currentChapter = Number($(document).getUrlParam("chapter"));
			currentChapterEndTime = chapterStartTimes[currentChapter+1];
			tpController.seekToPosition(chapterStartTimes[currentChapter]);
			updateChapterDisplay();
		}
	} else {
		$('#chapterRow1').addClass('chapterSelected');
	}
}
function mediaPlaying(e) {
	
	var currentTime = e.data.currentTime; // in milliseconds
	//$('#time').html(currentTime + " / " + currentChapterEndTime + " / " + currentChapter + " / " + totalChapters);
	if ( currentChapter > totalChapters || currentChapterEndTime == 0 || currentChapter == 0 || totalChapters == 0 ) return;
	if ( currentTime > currentChapterEndTime ) {
		currentChapter++;
		if ( currentChapter > totalChapters ) return;
		currentChapterEndTime = chapterStartTimes[currentChapter+1];
		updateChapterDisplay();
	}
	
}
function mediaSeek(e) {
	//alert("seek");
}
function updateChapterDisplay() {
	$('#chapters li').removeClass('chapterSelected');
	$('#chapterRow'+currentChapter).addClass('chapterSelected');
}
function chapterJSONReceived(d) {
	buildChapters(d);
}

function buildChapters(data) {
	var htmlLine = "";
	var chapterArray = [];
	$.each(data.items,
		function(i,item){
			// grab the data we need from the JSON feed
			var addThisItem = false;
				
			// instead of relying on a set order of the customfields, explicitly search for the fields we need
			// (a little more brute force but safer)
			for (k in  item.contentCustomData) {
				if ( item.contentCustomData[k]["title"] == "ChapterCount" && item.contentCustomData[k]["value"] == "" ) {
					addThisItem = true;
				}
				if ( item.contentCustomData[k]["title"] == "ChapterNumber" ) {
					var chapterNumber = Number(item.contentCustomData[k]["value"]);
				}
				if ( item.contentCustomData[k]["title"] == "ChapterStartTime" ) {
					var chapterStartTime = item.contentCustomData[k]["value"];
				}
				if ( item.contentCustomData[k]["title"] == "ChapterEndTime" ) {
					var chapterEndTime = item.contentCustomData[k]["value"];
				}
			}
			
			if ( addThisItem ) {
				
				var chapterLength = millisecondsToTimecode( timecodeToMilliseconds(chapterEndTime) - timecodeToMilliseconds(chapterStartTime) );
				var chapterStartTimeInMilliseconds = timecodeToMilliseconds(chapterStartTime);
				var chapterThumbnailURL = item.URL;
				var chapterTitle = item.title;
				var chapterDescription = item.description;
				
				// create an unordered list item for each chapter
				htmlLine = "<img src=\"" + chapterThumbnailURL + "\">";
				htmlLine = htmlLine + "<div class=\"rowText\"><span class=\"chapterTitle\">Chapter " + chapterNumber + ": " + chapterTitle + "<\/span><br />";
				htmlLine = htmlLine + "<span class=\"chapterDescription\">" + chapterDescription + "<\/span><span class=\"chapterLength\"> (" + chapterLength + ")<\/span><\/div><div class=\"clear\"></div>";
				chapterArray[chapterNumber] = htmlLine;
				// keep an array of chapter start times in milliseconds.  when the user clicks on a <li> we use this data to send to the Flash player to seek
				chapterStartTimes[chapterNumber] = chapterStartTimeInMilliseconds;
			}
			
		}
	);
	
	currentChapterEndTime = chapterStartTimes[2];
	totalChapters = chapterStartTimes.length - 1;
	
	// since we can't rely on the order of the chapter releases being sequential, we do this
	for (var j=1;j<chapterArray.length;j++) {
		chapterArray[j] = "<li id=\"chapterRow" + j + "\">" + chapterArray[j] + "<\/li>";
	}
	chapterArray.unshift('<ul id=\"chapterTable\" class=\"chaptersDisplay\">');
	chapterArray.push('<\/ul>');
	$('#chapters').html(chapterArray.join(''));
	
	$('#chapters li').hover(
		function(event) {
			$(this).addClass('overRow');
		},
		function(event) {
			$(this).removeClass('overRow');
		}
	);
	$('#chapters li').click ( function(event) {
		$('#chapters li').removeClass('chapterSelected');
		$(this).addClass('chapterSelected');
		// the id of each row looks like "rowXX" where XX is the chapter number, so we use that number
		// to lookup the corresponding time to seek to
		//var seekTimecode = chapterStartTimes[Number(event.currentTarget.id.substr(3))];
		currentChapter = Number(this.id.substr(10));
		var seekTimecode = chapterStartTimes[currentChapter];
		// talk to the Flash player
		tpController.seekToPosition(seekTimecode);
		currentChapterEndTime = chapterStartTimes[currentChapter+1];
		updateChapterDisplay();
	})
}
		
$(function() {
	// set up listener for skipping right to a chapter when the video first loads
	tpController.addEventListener("OnMediaStart", "checkForChapterJump");
	// set up listener for tracking video position and updating current chapter
	tpController.addEventListener("OnMediaPlaying", "mediaPlaying");
	// set up listener for tracking video position and updating current chapter when scrubber is used
	tpController.addEventListener("OnMediaSeek", "mediaSeek");

	$.getJSON(feedURL, {}, function() {  } );
});
