function updateHTML(elmId, value) {
  document.getElementById(elmId).innerHTML = value;
}

function setytplayerState(newState) {
  updateHTML("playerstate", newState);
}

function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("myytplayer");
  setInterval(updateytplayerInfo, 100);
  updateytplayerInfo();
  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
  ytplayer.addEventListener("onError", "onPlayerError");
}

function onytplayerStateChange(newState) {
  setytplayerState(newState);
}

function onPlayerError(errorCode) {
  alert("An error occurred: "+ errorCode);
}

function updateytplayerInfo() {
//  updateHTML("bytesloaded", getBytesLoaded());
//  updateHTML("bytestotal", getBytesTotal());
//  updateHTML("runTime_seconds", getDuration());
  updateHTML("runTime_seconds", getCurrentTime());
//  updateHTML("startbytes", getStartBytes());
}

// functions for the api calls
function play() {
  if (ytplayer) {
    ytplayer.playVideo();
  }
}

function pause() {
  if (ytplayer) {
    ytplayer.pauseVideo();
  }
}

function stop() {
  if (ytplayer) {
    ytplayer.stopVideo();
  }
}

function getPlayerState() {
  if (ytplayer) {
    return ytplayer.getPlayerState();
  }
}

function seekTo(seconds) {
  if (ytplayer) {
    ytplayer.seekTo(seconds, true);
  }
}

function getBytesLoaded() {
  if (ytplayer) {
    return ytplayer.getVideoBytesLoaded();
  }
}

function getBytesTotal() {
  if (ytplayer) {
    return ytplayer.getVideoBytesTotal();
  }
}

function getCurrentTime() {
  if (ytplayer) {
    return ytplayer.getCurrentTime();
  }
}

function getDuration() {
  if (ytplayer) {
    return ytplayer.getDuration();
  }
}

function getStartBytes() {
  if (ytplayer) {
    return ytplayer.getVideoStartBytes();
  }
}

function mute() {
  if (ytplayer) {
    ytplayer.mute();
  }
}

function unMute() {
  if (ytplayer) {
    ytplayer.unMute();
  }
}

function startFromBeginning() {
  if (ytplayer) {
    ytplayer.seekTo(0, true);
  }
}


function replaceAll(text, strA, strB) {
    while ( text.indexOf(strA) != -1) {
        text = text.replace(strA,strB);
    }
    return text;
}

var strYouTubeURL = "";
var displayCurrentRunTime = "";
var currentCaptionNumber = 0;
var videoStarted = false;

$(document).ready(function(){
	var yt = "e.g. http://youtube.com/watch?v=X_eVEW_Y02o";
	$("#youTubeURL").val(yt);
	$("#youTubeURL").focus(function(){$(this).select();});
	$("#txtTimeCodeGenerated").click(function(){$(this).select();});
	$("#step2Contents").hide();
	$("#step3Contents").hide();
	$("#step4Contents").hide();
	$("#btnStep1").click(function(){$("#step1Contents").slideUp('fast');$("#step2Contents").slideDown('fast');strYouTubeURL = $("#youTubeURL").val().split("=")[1];return false;});
	$("#btnStep2").click(function(){
		$("#step2Contents").slideUp('fast');
		$("#step3Contents").slideDown('fast');
		//embed YouTubeContent
		strYouTubeURL = "http://www.youtube.com/v/" + strYouTubeURL + "&amp;border=0&amp;enablejsapi=1&amp;playerapiid=ytplayer";
		var params = { allowScriptAccess: "always" };
		var atts = { id: "myytplayer" };
		swfobject.embedSWF(strYouTubeURL, "youTubeContent", "425", "344", "8", null, null, params, atts);
		$("#btnPlay").click(function(){videoStarted=true;play();});
		$("#btnPause").click(function(){pause();});
		$("#btnRestart").click(function(){videoStarted=true;resetCaptionsCaptured();startFromBeginning();});
		$("#generatedRows").empty();
//		$("#txtTimeCodeGenerated").val("{QTtext}{timescale:100}{font:Trebuchet MS}{size:14}\n{backColor:0,0,0} {textColor:65535,65535,65535}{width:320}{justify:center}");
		$("#txtTimeCodeGenerated").val("");
		var strCaptionText = document.getElementById("rawCaptionText").value;
		strCaptionText = replaceAll(strCaptionText,"\n\n","\n");
		var arrCaptionText = strCaptionText.split("\n");
		var loopLength = arrCaptionText.length;
		for (i=0; i<loopLength; i++)
		{
			var thisLine = arrCaptionText[i];
			thisLine = replaceAll(thisLine,"\"","&quot;");
			if (thisLine!="") {
				$("#generatedRows").append("<div><span id=\"indicator_captionLine" + (i+1) + "\">pending ...</span> <input type=\"text\" id=\"captionLine" + (i+1) + "\" value=\"" + thisLine + "\"></div>");
			}
		}
		var promptText = "<strong>Press '<strong>a</strong>' key to <strong>a</strong>dd &rarr;</strong>";
		currentCaptionNumber = 0;
		$(document).keypress(function(e){
			if (((e.which==65)||(e.which==97)) && (currentCaptionNumber<arrCaptionText.length))
			{
				if(videoStarted) {
					displayCurrentRunTime = $("#runTime_seconds").text();

//TODO: fix time delay option
//					if ($("#addDelay[checked]")) {
//						decimals -= 300;
//						if (decimals<0) {
//							decimals = decimals +1000;
//							seconds = parseInt(seconds) - 1;
//						}
//						decimals=decimals.toString();
//						seconds=seconds.toString();
//					}

					var s = displayCurrentRunTime; 
					var m;
					var h;
					var s_rem;
					var m_rem;
					var h_rem;
					var dec = s.split(".")[1].substring(0,2);
					s = Math.floor(s);              // The balance of seconds
					m = Math.floor(s/60);  // The minutes
					h = Math.floor(s/60/60);  // The hours
					s_rem = (s % 60).toString();
					m_rem = (m % 60).toString();
					h_rem = (h % 60).toString();
					if (s_rem.length==1) {s_rem="0" + s_rem;}
					if (m_rem.length==1) {m_rem="0" + m_rem;}
					if (h_rem.length==1) {h_rem="0" + h_rem;}
					if (dec.length==1) {dec=dec+"0"}
					var displayedTime = h_rem + ":" + m_rem + ":" + s_rem + "." + dec;

					var currentCaptionText = $("#generatedRows input:eq(" + currentCaptionNumber + ")").val();
	//				$("#txtTimeCodeGenerated").val($("#txtTimeCodeGenerated").val() + "[" + displayCurrentRunTime + "]\n" + currentCaptionText + "\n\n");
					$("#txtTimeCodeGenerated").val($("#txtTimeCodeGenerated").val() + displayedTime + "\n" + currentCaptionText + "\n\n");
					$("#currentCaptionPreview").show().fadeTo('fast',0.8);
					$("#currentCaptionPreview span").text(currentCaptionText);
					if (currentCaptionNumber>0)
					{
						$("#generatedRows span:eq(" + (currentCaptionNumber-1) + ")").html("<img src=\"/_images/tiny-tick.png\" alt=\"\"> Already added");
						$("#generatedRows span:eq(" + (currentCaptionNumber-1) + ")").parent().removeClass("activeCaptionRow");
						$("#generatedRows span:eq(" + (currentCaptionNumber-1) + ")").next().fadeTo('medium',0.4);
					}
					$("#generatedRows span:eq(" + currentCaptionNumber + ")").html("<strong>Adding this line &rarr;</strong>");
					$("#generatedRows span:eq(" + currentCaptionNumber + ")").parent().addClass("activeCaptionRow");
					currentCaptionNumber++;
					$("#generatedRows input:eq(" + currentCaptionNumber + ")").focus().blur();
					if (currentCaptionNumber == arrCaptionText.length)
					{
						doLastStep();
					}
				}
				else {
					alert("Cannot add captions just yet.\n\nyou need to press the Play button first :) ");
				}
			}
		});
	return false;
	});

	function resetCaptionsCaptured() {
		$("#generatedRows div span").text("pending ...");
		$("#generatedRows div").removeClass("activeCaptionRow");
		$("#generatedRows input").fadeTo(1,1);
		currentCaptionNumber=0;
		$("#txtTimeCodeGenerated").val("");
	}
	function doLastStep() {$("#step3Contents").slideUp('fast');$("#step4Contents").slideDown('fast');$("#txtTimeCodeGenerated").attr("readonly","readonly").select();}
	$("#btnStep4").click(function(){location.href="default.php";});
	$("#IamDoneHere").click(function(){doLastStep();});
	$("#youTubeOverlay").click(function(){alert("Please use the play/pause/start controls on the right to control this movie's playback");});
//	$("#btnStep1").click();
//	$("#btnStep2").click();
	

});	