
// Upon page load, no video has been embedded yet.
var FirstVideoEmbedded = 0;
var runPlaylist = 1;
var PreviousPlaylistIndex = 0;
var PreviousVideoIndex = 0;
var CurrentPlaylist = 0;
var CurrentVideo = 0;
var NextVideo = 0;

// jQuery method to execute code after the DOM has fully loaded.
$(document).ready(function(){

	// If there is a URL hash, load the playlist and video information.
	if (window.location.hash){
		var ListAndVideo = window.location.hash.substr(1).split(",");
		// If playlist value is valid, otherwise it will remain at the default 0.
		if (ListAndVideo[0] < PlayListTitle.length) { CurrentPlaylist = ListAndVideo[0]; }
		// If the video value is valid for the current playlist, otherwise it will remiain at the default 0.
		if (ListAndVideo[1] < PlayList[CurrentPlaylist].length) { CurrentVideo = ListAndVideo[1]; }
	}
	if (ShowPlaylist == 1) {
		PrintPlaylistButtons();
		LoadPlaylist(CurrentPlaylist);
	}
	LoadEmbeddedVideo(CurrentPlaylist,CurrentVideo,'');
	
	// When a mouse click is detected in the playlist, load the requested video.
	$('#BNplaylist a').live('click',function(event){
		// Process only if this anchor element in the BNplaylist DIV has an ID tag.
		if (this.id) {
			// Prevent the link from executing.
			event.preventDefault();

			// The anchor ID in the playlist has a one-character prefix to prevent the browser's
			// hash functionality from scrolling down to an achor with the ID number.
			// Strip off the one-character prefix. (First character is index 0)
			var IDstring = this.id;			
			CurrentVideo = parseInt(IDstring.substr(1));

			// Load an embedded video. Parameter is the Playlist array ID.
			LoadEmbeddedVideo(CurrentPlaylist,CurrentVideo,'autostart');
		}
	});

	// When a mouse click is detected in the list of playlists, load the playlist.
	$('#ListofPlaylists a').live('click',function(event){
		// Process only if this anchor element in the BNplaylist DIV has an ID tag.
		if (this.id) {
			// Prevent the link from executing.
			event.preventDefault();

			// The anchor ID in the playlist has a one-character prefix to prevent the browser's
			// hash functionality from scrolling down to an achor with the ID number.
			// Strip off the one-character prefix. (First character is index 0)
			var IDstring = this.id;			
			CurrentPlaylist = parseInt(IDstring.substr(1));

			// Load the playlist.
			LoadPlaylist(CurrentPlaylist);
			LoadEmbeddedVideo(CurrentPlaylist,0,'');
		}
	});

	$('#mutebutton').live('click',function(event){
		if (YTplayer.isMuted()) {
			YTplayer.unMute();
			updateHTML('mutebutton', 'Turn Sound Off');
		}
		else {
			YTplayer.mute();
			updateHTML('mutebutton', 'Turn Sound On');
		}
	});
	
});


// When the YouTube embedded player is fully loaded, this function is called.
function onYouTubePlayerReady(playerID) {
	// Establish the DOM pointer to the embedded YouTube player.
	YTplayer = document.getElementById("YouTubePlayer");
	// Monitor the player state changes for playlist use, specifically the 0 (video finished) state.
	YTplayer.addEventListener("onStateChange", "OnEmbeddedPlayerStateChange");

	// If we are on the home page.
	if (ShowPlaylist == 0) {
		// Start the first embedded video on mute.
		YTplayer.mute();
		// Update the state of the mute button.
		updateHTML('mutebutton', 'Turn Sound On');
	}
}


// When a state change is registered in the embedded player, execute this function.
function OnEmbeddedPlayerStateChange(newState) {
	// Documented states: (-1) Unstarted (loading), (0) Ended, (1) Playing, (2) Paused, (3) Buffering, (5) Cued (ready to play)
	switch(newState) {
		 case -1: StateDescription = "Loading (-1)";      break;
		  case 0: StateDescription = "Finished (0)";
					// If playlist is running.
 					if (runPlaylist == 1) { LoadEmbeddedVideo(CurrentPlaylist,NextVideo,'autostart'); }
		  			break;
		  case 1: StateDescription = "Playing (1)";			break;
		  case 2: StateDescription = "Paused (2)";			break;
		  case 3: StateDescription = "Buffering (3)";		break;
		  case 5: StateDescription = "Ready to play (5)";	break;
		 default: StateDescription = "Undefined (an error?)";
	}
}


// Update a particular HTML element with a new value
function updateHTML(elementID, string) {
	document.getElementById(elementID).innerHTML = string;
}

// Call this function for JSON-encoded string - it converts '\n' to '<br />'
function updateHTML_json(elementID, string) {
	document.getElementById(elementID).innerHTML = string.replace(/\n/g,"<br />");
}


// Pass the PlayList array indices to load a video.
function LoadEmbeddedVideo(List, PlayThisIndex, varAutoStart) {
	var PreviousVideo;
	
	// Make sure the index is a number.
	ListNumber = parseInt(List);
	CurrentVideo = parseInt(PlayThisIndex);

	// For playlist use, determine the next and previous videos on the list.
	if ( CurrentVideo + 1 >= PlayList[ListNumber].length ) { NextVideo = 0; }
	else { NextVideo = CurrentVideo + 1; }
	if (CurrentVideo == 0) { PreviousVideo = PlayList[ListNumber].length - 1; }
	else { PreviousVideo = CurrentVideo - 1; }
	
	// Extract the video information from the PlayList array
	var VideoName = PlayList[ListNumber][CurrentVideo][1];
	var VideoDescription = PlayList[ListNumber][CurrentVideo][2];
	var videoYouTubeID = PlayList[ListNumber][CurrentVideo][3];

	// Update the Description box.
	// The video on the Library page has player controls, but the home page does not, so make a mute button.
	// The Library and Home pages have different DIV names because the sizes are different.
	var TitleString = '<h3 style="margin:0 0 10px;">' + VideoName + '</h3>';
	if (ShowPlaylist == 1) {
		VideoDescription = TitleString + VideoDescription;
		updateHTML_json('VideoDescription', VideoDescription); 
	}
	else { 
		var MuteButton = '<div id="mutebutton">Turn Sound <span style="visibility:hidden">On</span></div>'; 
		VideoDescription = TitleString + MuteButton + VideoDescription;
		updateHTML_json('VideoDescriptionHome', VideoDescription); 
	}
	// Upon loading the page, embed the first video.
	if (FirstVideoEmbedded == 0) {
		var atts = { id: "YouTubePlayer" };
		// For the Video Library page.
		if (ShowPlaylist == 1) {
			// ?enablejsapi=1 is required to enable the API, &playerapiid=YTplayer, &rel=0 do not show related videos, &fs=1 allow full screen.
			var YTembedURLstring = '?enablejsapi=1&playerapiid=YTplayer&rel=0&fs=1';
			var params = { allowScriptAccess: "always", allowFullScreen: "true", autostart: "false" };
			swfobject.embedSWF("http://www.youtube.com/v/" + videoYouTubeID + YTembedURLstring, "YouTubeEmbedLibrary", "593", "358", "8", null, null, params, atts);
		}
		// For the home page.
		else {
			// For chromeless player, '&version=3' is required! Add '&autoplay=1' to enable auto start.
			var YTembedURLstring = '&enablejsapi=1&version=3&playerapiid=YTplayer&rel=0&autoplay=1';
			var params = { allowScriptAccess: "always", autostart: "true" };
			swfobject.embedSWF("http://www.youtube.com/apiplayer?video_id=" + videoYouTubeID + YTembedURLstring, "YouTubeEmbedHome", "610", "343", "8", null, null, params, atts); 
		}
		FirstVideoEmbedded = 1;
	}
	// The SWF object has already been embedded.
	else {
		// Load new video, start playing if autostart is specified.
		YTplayer.cueVideoById(videoYouTubeID,0);
		if (varAutoStart > '') { YTplayer.playVideo(); }
		// Update the mute button if it is the home page.
		if (ShowPlaylist == 0) {
			if (YTplayer.isMuted()) { updateHTML('mutebutton', 'Turn Sound On'); }
			else { updateHTML('mutebutton', 'Turn Sound Off'); }
		}
	}

	// After loading the video, scroll the playlist to center the chosen thumbnail.
	if (ShowPlaylist == 1) {
		$('#BNplaylist').scrollTo('#t' + CurrentVideo, 1000, {axis:'x',offset:-235} );

		// Update the selected video thumbnail highlight.
		$('#t' + PreviousVideoIndex).removeClass('t_lit').addClass('t_unlit');
		$('#t' + CurrentVideo).removeClass('t_unlit').addClass('t_lit');

		// Update the address bar hash with the array index of the current video.
		window.location.hash = '#' + ListNumber + ',' + CurrentVideo;
	}
	PreviousVideoIndex = CurrentVideo;
}
// End of LoadEmbeddedVideo() function.


// Load a playlist.
function LoadPlaylist(CurrentPlaylist) {
	// Update the Playlist button highlight.
	$('#b' + PreviousPlaylistIndex + ' a').removeClass('b_lit').addClass('b_unlit');
	$('#b' + CurrentPlaylist + ' a').removeClass('b_unlit').addClass('b_lit');
	PreviousPlaylistIndex = CurrentPlaylist;

	// PlaylistWidth is (thumbnail width + (borderwidth * 2) + margin-right) * number of videos in the playlist.
	var PlaylistWidth = 132 * PlayList[CurrentPlaylist].length;
	var PlaylistString = '<div style="width:' + PlaylistWidth + 'px; height:150px; overflow:hidden;">';
	for (var index = 0 ; index < PlayList[CurrentPlaylist].length ; index++) {
		PlaylistString = PlaylistString + 
		'<div class="tnWrapper">' + 
		'<div id="t' + index + '" class="tn t_unlit">' + 
		'<a id="v' + index + '" href="http://www.youtube.com/watch?v=' + PlayList[CurrentPlaylist][index][3] + 
		'" title="' + PlayList[CurrentPlaylist][index][1] + '" target="_blank">' + 
		'<img src="' + PlayList[CurrentPlaylist][index][4] + '" width="120" height="90" border="0" alt="" /></a></div>' +
		'<span style="color:#00708e;">' + PlayList[CurrentPlaylist][index][1] + '</span>' + "</div>";
	}
	PlaylistString = PlaylistString + '</div>';
	updateHTML('PlaylistTitle', '<span style="color:#808080;">Current Playlist:</span> ' + PlayListTitle[CurrentPlaylist]);
	updateHTML('BNplaylist', PlaylistString);
}


// Print out the playlist buttons.
function PrintPlaylistButtons() {
	var PlaylistButtonsString = '';
	for (var index = 0 ; index < PlayListTitle.length ; index++) {
		PlaylistButtonsString = PlaylistButtonsString + '<div id="b' + index + '" class="playlistbutton">' + 
		'<a id="p' + index + '" class="b_unlit" href="">' + PlayListTitle[index] + "</a></div>\n";
	}
	updateHTML('ListofPlaylists', PlaylistButtonsString);
}



