var itemindex = 0;
var currentSelection;
var currentVideoID;
var currentTitle;
var currentLink;
var currentRating;
var currentDBParent;
var playerInterval;
var autoplay = false;
var currentPlayerState;
var editingVideoID;
var initialVolume;
var volumeTimeout;
var videosWatched = 0;
var adPlaying = false;
var ytplayerDefined = false;
var playlistStartY;
var playlistEndY;
var currentDirectVideo;


var initLink = 'gqsMTZQ-pmE';

var params = { allowScriptAccess: "always", bgcolor: "#222222", allowFullScreen: "true", wmode: "opaque" };
// this sets the id of the object or embed tag to 'myytplayer'.
// You then use this id to access the swf and make calls to the player's API
var atts = { id: "myytplayer" };



function setFBPlayerHeight() {
	if (navigator.appVersion.match('MSIE')) playerHeight = 283;
	else playerHeight = 285;
	playerWidth = 375;
	embedPlayer(playerWidth, playerHeight);
}	

function embedPlayer(playerWidth, playerHeight) {
	
	$('#playerContainer').html('<div id="ytapiplayer"></div>');
	
	if (mainCategory == 'Music' || mainCategory == 'Video') {
		swfobject.embedSWF("http://www.youtube.com/v/"+initLink+"&amp;border=0&amp;enablejsapi=1&amp;playerapiid=ytplayer&amp;fs=1&amp;rel=0&amp;dgm=0&amp;color2=0x66a2cc&amp;color1=0xbcd8eb",
	            "ytapiplayer", playerWidth, playerHeight, "8", null, null, params, atts);
	}
	
}

function removeVideo(i) {
	toBeRemoved = $('#item_'+i);
	if ($(toBeRemoved).attr('class') == 'playListItem' || $(toBeRemoved).attr('class') == 'playListItemSelected') {
		$(toBeRemoved).remove();
	}
	else {
		removeAllPageChildren(toBeRemoved);
		$(toBeRemoved).remove();
	}
}

function displayCurrentlyPlaying(){

	if (currentDBParent != null) {
		$('#playListHeaderTitle').html('<div id = "playListHeaderTitleText">Now Playing: '+currentTitle+'</div>' +
				'<div class = "playListVideoButtons" style = "width:60px;">' +
					'<a id = "playListFBShare" title = "Share video on Facebook" href = "javascript:shareVideoOnFacebook(\''+currentTitle+'\', \''+currentLink+'\', \''+currentDBParent+'\');"></a>' +
					'<a id = "like_current" class = "smallLikeButton" title = "Like this video" style = "margin-top:4px;" href = "javascript:giveThumbsUp(\''+currentVideoID+'\', \'like\', \''+currentTitle+'\', \''+currentLink+'\', '+currentRating+', \''+currentDBParent+'\');"></a>' +
					'<a id = "dislike_current" class = "smallDislikeButton" title = "Dislike this video" style = "margin-top:4px;" href = "javascript:giveThumbsUp(\''+currentVideoID+'\', \'dislike\', \''+currentTitle+'\', \''+currentLink+'\', '+currentRating+', \''+currentDBParent+'\');"></a>' +
				'</div>');
	}
	else {
		$('#playListHeaderTitle').html('<div id = "playListHeaderTitleText">Now Playing: '+currentTitle+'</div>' +
				'<div class = "playListVideoButtons" style = "width:60px;">' +
					'<a id = "playListFBShare" title = "Share video on Facebook" href = "javascript:shareVideoOnFacebook(\''+currentTitle+'\', \''+currentLink+'\', \''+currentDBParent+'\');"></a>' +
				'</div>');
	}
}	

function stopEditingPage() {
	editingVideoID = null;
	$('#playListHeader').html('<div id = "playListHeaderTitle"></div>' +
			'<div id = "playListFormButtonContainer"><a id = "saveCollectionButton" href = "javascript:makeChooseMainCategory();"></a></div>');
	displayCurrentlyPlaying();
}

function editPage(pageID) {

	playListClearAll();
	var lastElement = null;
	editingVideoID = pageID;
	
	url = getBaseURL('/ajax/getPageInfoToShare.php');
	$.get(url, {contentID: pageID},  function(pageInfo) {
		encodedPageInfo = eval('('+pageInfo+')');
		pageTitle = encodedPageInfo.title;	
		$('#playListHeader').html('<div id = "playListHeaderTitle"><div id = "playListHeaderTitleText">Editing Collection: <b>'+pageTitle+'</b></div></div>' +
				'<div id = "playListFormButtonContainer"><a id = "cancelEditButton" href="javascript:stopEditingPage();"></a>'+
				'<a id = "updateCollectionButton" href = "javascript:savePlaylist();"></a></div>');
	});
	
	url = getBaseURL('/ajax/playlist.php');
	$.ajax({
		url: url+'&dbid='+pageID,
		dataType: 'json',
		success: function(jsonEncode) {
			$(jsonEncode).each(function() {
				if ($(this)[0].type=='video') {
					var linkid = $(this)[0].linkid.replace('youtube:', "");
					itemhtml = createHTML($(this)[0].contentTitle, linkid, $(this)[0].rating, 0, pageID, $(this)[0].likes);
					
					if (lastElement == null) {
						$('#leftNavPlayListContainer').append(itemhtml);
					}
					else {
						$(lastElement).after(innerhtml);
						lastElement = $(lastElement).next();
					}
					itemindex++;
				}
				else {
					itemhtml = createClosedPageHTML($(this)[0].contentTitle, $(this)[0].linkid.replace('flotate:',""), 0);
					if (lastElement == null) {
						$('#leftNavPlayListContainer').append(itemhtml);
					}
					else {
						$(lastElement).after(innerhtml);
						lastElement = $(lastElement).next();
					}
					itemindex++;
				}
				$('#universalWindow').html('<img src = "images/smallWindowBG.png">'+
						'<a class = "closeButton" style = "right:30px; top:20px;" href = "javascript:closeWindow();">X</a>' +
						'<div class = "mediumText" "style = "position:absolute; top:0px; margin:30px 40px 30px 20px;">' +
						'The content of the collection you are editing is shown on the playlist. You can now add, ' +
						'delete, or rearrange things and then click Update when you are done.</div>');
				displayWindow(620);
			});
		}
	});
}

function playListClearAll() {
	$('#leftNavPlayListContainer').children().each(function() {
		$(this).remove();
	});
	itemindex = 0;
}

function repeatAll() {
	
	if ($('#playListRepeat').attr('class') == "playListRepeat") {
		$('#playListRepeat').attr('class', 'playListRepeatSelected');
	}
	else if ($('#playListRepeat').attr('class') == "playListRepeatSelected") {
		$('#playListRepeat').attr('class', 'playListRepeat');
	}
}

function playListRandom() {
	
	if ($('#playListRandom').attr('class') == "playListRandom") {
		$('#playListRandom').attr('class', 'playListRandomSelected');
	}
	else if($('#playListRandom').attr('class') == "playListRandomSelected") {
		$('#playListRandom').attr('class', 'playListRandom');
	}
}

function nextVideo() {
	if (adPlaying == false) {
		if (currentDirectVideo != null) {
			if ($('#'+currentDirectVideo).attr('type') == 'searchVideo') $('#'+currentDirectVideo).css('background', '#eeffff');
			else $('#'+currentDirectVideo).css('background', '#ffffff');
			if ($('#'+currentDirectVideo).next().length > 0 && $('#'+currentDirectVideo).next().attr('rank') == 'video') loadPageListItem($('#'+currentDirectVideo).next());
			else currentDirectVideo = null;
		}
		else if ($('#playListRandom').attr('class') == "playListRandomSelected") {
			$('#'+currentSelection).attr('class', 'playListItem');
			playListItems = $('#leftNavPlayListContainer').children('.playListItem');
			randomSelection = Math.floor(Math.random()*playListItems.size());
			loadPageListItem(playListItems[randomSelection]);
		}
		else if ($('#'+currentSelection).attr('class') == 'playListItemSelected') {
			var currentSelectionDiv = $('#'+currentSelection);
			$(currentSelectionDiv).attr('class', 'playListItem');
			var videoFound = playNextSequential(currentSelectionDiv);
			if (videoFound == false && $('#playListRepeat').attr('class') == "playListRepeatSelected") {
				playFirstVideo();
			}
		}
		else {
			playFirstVideo();
		}
	}
}

function playFirstVideo() {
	if ($($('#leftNavPlayListContainer').children()[0]).attr('class') == 'playListItem') {
		loadPageListItem($('#leftNavPlayListContainer').children()[0]);
	}
	else {
		playNextSequential($('#leftNavPlayListContainer').children()[0]);
	}
}

function playNextSequential(currentSelectionDiv) {
	while($(currentSelectionDiv).next().length>0) {
		currentSelectionDiv = $(currentSelectionDiv).next();
		if ($(currentSelectionDiv).attr('class') == 'playListItem') {
			loadPageListItem(currentSelectionDiv);
			return true;
		}	
	}
	return false;
}

function previousVideo() {
	if (adPlaying == false) {
		var currentSelectionDiv = $('#'+currentSelection);
		$(currentSelectionDiv).attr('class', 'playListItem');
		var videoFound = playPreviousSequential(currentSelectionDiv);
	}
}

function playPreviousSequential(currentSelectionDiv) {
	while($(currentSelectionDiv).prev().length>0) {
		currentSelectionDiv = $(currentSelectionDiv).prev();
		if ($(currentSelectionDiv).attr('class') == 'playListItem') {
			loadPageListItem(currentSelectionDiv);
			return true;
		}	
	}
	return false;
}

function loadPageListItem(pageItemDiv) {
	if (currentDirectVideo != null) {
		currentDirectVideo = $(pageItemDiv).attr('id');
		var video = $('#'+currentDirectVideo);
		$(video).css('background', '#ccddee');
		currentLink = $(video).attr('videolink');
	}
	else {
		if (currentSelection != null) $('#'+currentSelection).css('border', 'none');
		$(pageItemDiv).attr('class', 'playListItemSelected'); 
		currentSelection = $(pageItemDiv).attr('id');
		var video = $('#'+currentSelection);
		currentLink = $(video).attr('name');
	}	
	
	currentVideoID = $(video).attr('id').split('_')[1];
	currentTitle = $(video).attr('title');
	currentRating = $(video).attr('rating');
	currentDBParent = $(video).attr('dbparent');
	
	displayCurrentlyPlaying();
	
	//loadNewVideo($(pageItemDiv).attr('name'), 0);
	loadNewVideo(currentLink, 0);
	
	/*if ($('#remoteControlBox').attr('class') == 'remotePLControlBox' || $('#remoteControlBox').attr('class') == 'remotePLMenuBox' ) {
		position = $('#'+currentSelection).position();
		
		if(position.top < 50) {
			delta = 50-position.top;
			$('#playListContainer').attr('scrollTop', $('#playListContainer').attr('scrollTop') - delta);
		}
		else if ($('#playListContainer').attr('offsetHeight')-position.top < 50) {
			delta = 50 - ($('#playListContainer').attr('offsetHeight')-position.top);
			$('#playListContainer').attr('scrollTop', $('#playListContainer').attr('scrollTop') + delta);
		}
		$('.playListItemSelected').css('border', '2px solid #1288ff');
	}*/
}

function playSelectedVideo(i) {
	if (currentDirectVideo != null) {
		$('#'+currentDirectVideo).css('background', '#ffffff');
		currentDirectVideo = null;
	}
	if (playlistStartY == playlistEndY) {
		$('#'+currentSelection).attr('class', 'playListItem');
		loadPageListItem($('#item_'+i));
	}	
}

function mainCategoryChoice(categoryChoice) {
	if (categoryChoice != mainCategory) changeMainCategory(categoryChoice);
	savePlaylist();
}

function makeChooseMainCategory() {
	url = getBaseURL('/ajax/chooseMainCategory.php');
	$('#universalWindow').load(url, function() {
		$('#savePageItemContainer').sortable();
		var alertLeft = $(document).width()/2-310;
		if ($('#fbcss').length > 0) alertLeft = 70;
		$('#universalWindow').css('left', alertLeft);
		$('#universalWindow').show();
	});	
}

function savePlaylist() {
	
	createPageIndex = 0;
	if (editingVideoID== null) {
		
		url = getBaseURL('/ajax/createflopage.php');
		$('#universalWindow').load(url, function() {
			initiateCreatePage();	
			$('#leftNavPlayListContainer').children().each(function() {
				if($(this).attr('pagelevel') == '0') {
					if ($(this).attr('class') == 'playListItem' || $(this).attr('class') == 'playListItemSelected') {
						addPageItem($(this).attr('title'), "youtube:"+$(this).attr('name'), $(this).attr('rating'), $(this).attr('likes'));
					}
					else {
						addPageItem($(this).attr('title'), "flotate:"+$(this).attr('name'));
					}
				}
			});
			nextPhoto();
		});
	}
	else {
		
		url = getBaseURL('/ajax/createflopage.php');
		$('#universalWindow').load(url+'&pageID='+editingVideoID, function() {
			initiateCreatePage();	
			$('#savePageItemContainer').sortable();
			$('#leftNavPlayListContainer').children().each(function() {
				if($(this).attr('pagelevel') == '0') {
					if ($(this).attr('class') == 'playListItem' || $(this).attr('class') == 'playListItemSelected') {
						addPageItem($(this).attr('title'), "youtube:"+$(this).attr('name'), $(this).attr('rating'), $(this).attr('likes'));
					}
					else {
						addPageItem($(this).attr('title'), "flotate:"+$(this).attr('name'));
					}
				}
			});
			nextPhoto();
		});
	}
}


//youtube functions many can be replaced

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

/*function playPlaylist() {
	if ($('#'+currentSelection).attr('class') == 'playListItem' && currentPlayerState != 1) checkForStateToPlay();
}*/

function addToPlayList(id, addToRecent) {
	var page = $('#'+id);
	currentVideoID = id.split('_')[0];
	currentTitle = $(page).attr('realtitle');
	currentLink = $(page).attr('videolink');
	currentRating = $(page).attr('rating');
	currentDBParent = $(page).attr('dbparent');

	$('#universalAlert').html('<div id = "mediumAlertBox"><div class = "alertText">Video Added</div></div>');
	displayAlert(240);
	var playListBoxTimeout = setTimeout("closeAlert();", 500);
	
	if (addToRecent==null) addToRecent = false;
	var autoplay;
	if ($('#'+currentSelection).attr('class') != 'playListItemSelected' && currentPlayerState != 1) autoplay = true;
	else autoplay = false;
	itemhtml = createHTML(currentTitle, currentLink, currentRating, 0, currentDBParent);
	$('#leftNavPlayListContainer').append(itemhtml);
	if (autoplay == true) loadPageListItem($('#item_' + itemindex));
	itemindex++;
	if (addToRecent != false) {
		url = getBaseURL('/ajax/recent.php');
		$.get(url, { contentID: currentLink, contentTitle:currentTitle, contentRating:currentRating });
	}
}

function addPageInsidePlayList(title, link, parent, edit) {
	var itemhtml;
	var lastChildElement;
	
	$('#universalAlert').html('<div id = "mediumAlertBox"><div class = "alertText">Collection Added</div></div>');
	displayAlert(240);
	var playListBoxTimeout = setTimeout("closeAlert();", 500);
	
	var thisItemIndex;
	if (parent == null) {
		var parent = $('#leftNavPlayListContainer');
		var pagelevel = 0;
		itemhtml = createPageHTML(title, link, pagelevel, edit);
		$('#leftNavPlayListContainer').append(itemhtml);
		parent = $('#item_'+itemindex);
		thisItemIndex = itemindex;
		itemindex++;
		if (sharerID==null) {
			url = getBaseURL('/ajax/recent.php');
			$.get(url, {contentID: link});
		}
		else {
			url = getBaseURL('/ajax/recent.php');
			$.get(url, { contentID: link, sharerID:sharerID});
			sharerID = null;
		}
	}
	else {
		var pagelevel = parseInt($(parent).attr('pagelevel'));
		var parent = parent;
	}
	
	var lastElement = parent;
	
	url = getBaseURL('/ajax/playlist.php');
	$.ajax({
		url: url+'&dbid='+link,
		dataType: 'json',
		success: function(jsonEncode) {
			$(jsonEncode).each(function() {
				if ($(this)[0].type == 'video') {
					var linkid = $(this)[0].linkid.replace('youtube:', "");
					innerhtml = createInnerVideoHTML($(this)[0].contentTitle, linkid, $(this)[0].rating, pagelevel+1, link, $(this)[0].likes);
					$(lastElement).after(innerhtml);
					lastElement = $(lastElement).next();
					if (initialVideo != null && initialVideo == $(lastElement).attr('name')) {
							loadPageListItem(lastElement);
							initialVideo = null;
					}
					else if ($('#'+currentSelection).attr('class') != 'playListItemSelected' && currentPlayerState != 1 && initialVideo == null) {
						loadPageListItem(lastElement);
					}
					itemindex++;
				}
				else {
					
					if (pagelevel < 1) {
						itemhtml = createInnerPageHTML($(this)[0].contentTitle, $(this)[0].linkid.replace('flotate:',""), pagelevel+1);
						$(lastElement).after(itemhtml);
						lastElement = $(lastElement).next();
						itemindex++;
						addPageInsidePlayList($(this)[0].contentTitle, $(this)[0].linkid.replace('flotate:',""), lastElement, 'false');
					}
					else {
						itemhtml = createInnerClosedPageHTML($(this)[0].contentTitle, $(this)[0].linkid.replace('flotate:',""), pagelevel+1);
						$(lastElement).after(itemhtml);
						lastElement = $(lastElement).next();
						itemindex++;
					}
				}
			});
		}
	});
	
}

function addSinglePageToPlayList(dbid) {
	
	url = getBaseURL('/ajax/getPageInfoToShare.php');
	$.get(url, {contentID: dbid},  function(pageInfo) {
			encodedPageInfo = eval('('+pageInfo+')');
			pageTitle = encodedPageInfo.title;
			addPageInsidePlayList(pageTitle, dbid, null, 'false');	
	});
	
}

function getLastChildElement(parentElement) {
	
	var parentElementPageLevel = $(parentElement).attr('pagelevel');
	while ($(parentElement).next().length>0  && $(parentElement).next().attr('pagelevel')>parentElementPageLevel) {
		parentElement = $(parentElement).next();
	}
	return parentElement;
	
}

function removeAllPageChildren(parentElement) {
	
	var parentElementPageLevel = $(parentElement).attr('pagelevel');
	var elementToBeRemoved;
	if($(parentElement).next().length>0  && $(parentElement).next().attr('pagelevel')>parentElementPageLevel) {
		elementToBeRemoved = $(parentElement).next();
		while(true) {
			if($(elementToBeRemoved).next().length>0  && $(elementToBeRemoved).next().attr('pagelevel')>parentElementPageLevel) {
				var tempElement = elementToBeRemoved.next();
				elementToBeRemoved.remove();
				elementToBeRemoved = tempElement;
			}
			else {
				elementToBeRemoved.remove();
				break;
			}
		}
	}
	
}

function toggleOpenClosed(index) {
	if (playlistStartY == playlistEndY) {
		pageItemDiv = $('#item_'+index);
		pageItemTitleDiv = $('#pageTitle_'+index);
		pageContainer = $('#pageContainer_'+index);
		
		
		if ($(pageItemDiv).attr('open')=='true') {
			$(pageItemDiv).attr('open', 'false');
			$(pageItemTitleDiv).html("<small>&#9658;</small>&nbsp;&nbsp;"+$(pageItemDiv).attr('title'));
			removeAllPageChildren(pageItemDiv);
			
		}
		else {
			$(pageItemDiv).attr('open', 'true');
			$(pageItemTitleDiv).html("<small>&#9660;</small>&nbsp;&nbsp;"+$(pageItemDiv).attr('title'));
			
			
			var thisItemIndex = index;
			var pagelevel = parseInt($(pageItemDiv).attr('pagelevel'));
			var lastElement = pageItemDiv;
			
			
			url = getBaseURL('/ajax/playlist.php');
			$.ajax({
				url: url+'&dbid='+$(pageItemDiv).attr('name'),
				dataType: 'json',
				success: function(jsonEncode) {
					$(jsonEncode).each(function() {
						if ($(this)[0].type=='video') {
							var linkid = $(this)[0].linkid.replace('youtube:', "");
							innerhtml = createInnerVideoHTML($(this)[0].contentTitle, linkid, $(this)[0].rating, pagelevel+1, $(pageItemDiv).attr('name'));
							$(lastElement).after(innerhtml);
							lastElement = $(lastElement).next();
							itemindex++;
						}
						else {
							itemhtml = createInnerClosedPageHTML($(this)[0].contentTitle, $(this)[0].linkid.replace('flotate:',""), pagelevel+1);
							$(lastElement).after(itemhtml);
							lastElement = $(lastElement).next();
							itemindex++;
							
						}
					});
				}
			});
		}
	}	
}

function createInnerVideoHTML(title, link, rating, pagelevel, dbParentID, likes) {
	if (likes==null) likes = 0;
	if (itemindex % 2 == 0) background = "#001626";
	else background = "#002540";
	var titleLeft = (pagelevel*15) + 20;
	var itemhtml = "<div style = 'background:"+background+";' class = 'playListItem' pagelevel = '"+pagelevel+"' id = 'item_"+itemindex+"' title = '"+title+"' name = '"+link+"' rating ='"+rating+"' likes ='"+likes+"' dbparent = '"+dbParentID+"'>" +
						"<div class = 'playListItemTitle' style = 'left:"+titleLeft+"px;' onclick = 'playSelectedVideo("+itemindex+");'>"+title+"</div>" +
						"<div class = 'playListVideoButtons'>" +
							"<a id = 'like_"+itemindex+"' class = 'smallLikeButton' title = 'Like this video' href = 'javascript:giveThumbsUp(\""+itemindex+"\", \"like\", \""+title+"\", \""+link+"\", "+rating+", \""+dbParentID+"\");'></a>" +
							"<a id = 'dislike_"+itemindex+"' class = 'smallDislikeButton' title = 'Dislike this video' href = 'javascript:giveThumbsUp(\""+itemindex+"\", \"dislike\", \""+title+"\", \""+link+"\", "+rating+", \""+dbParentID+"\");'></a>" +	
						"</div>" +
					"</div>";
	return itemhtml;
	
}

function createPageHTML(title, link, pagelevel, edit) {
	background = "#002138";
	if (edit == 'true' || edit == 1) {
		var itemhtml = "<div class = 'playListPageItem' pagelevel = '"+pagelevel+"' id = 'item_"+itemindex+"' style = 'background:"+background+";' open = 'true' itemindex = '"+itemindex+"' title = '"+title+"' name = '"+link+"' >" +
							"<div class = 'playListItemClose' onclick = 'removeVideo("+itemindex+");'>X</div>" +
							"<div id = 'pageTitle_"+itemindex+"' class = 'playListItemTitle' onclick = 'toggleOpenClosed("+itemindex+");'><small>&#9660;</small>&nbsp;&nbsp;"+title+"</div>" +
							"<div class = 'playListVideoButtons'><a class = 'smallEditButton' title = 'Edit Collection: "+title+"' href = 'javascript:editPage("+link+");'></a></div>" +
						"</div>";
	}
	else {
		var itemhtml = "<div class = 'playListPageItem' pagelevel = '"+pagelevel+"' id = 'item_"+itemindex+"' style = 'background:"+background+";' open = 'true' itemindex = '"+itemindex+"' title = '"+title+"' name = '"+link+"' >" +
							"<div class = 'playListItemClose' onclick = 'removeVideo("+itemindex+");'>X</div>" +
							"<div id = 'pageTitle_"+itemindex+"' class = 'playListItemTitle' onclick = 'toggleOpenClosed("+itemindex+");'><small>&#9660;</small>&nbsp;&nbsp;"+title+"</div>" +
						"</div>";
		
	}
	return itemhtml;
}

function createClosedPageHTML(title, link, pagelevel) {
	background = "#002138";
	var itemhtml = "<div class = 'playListPageItem' pagelevel = '"+pagelevel+"' id = 'item_"+itemindex+"' open = 'false' itemindex = '"+itemindex+"' title = '"+title+"' style = 'background:"+background+";' name = '"+link+"' >" +
						"<div class = 'playListItemClose' onclick = 'removeVideo("+itemindex+");'>X</div>" +
						"<div id = 'pageTitle_"+itemindex +"' class = 'playListItemTitle' onclick = 'toggleOpenClosed("+itemindex+");'><small>&#9658;</small>&nbsp;&nbsp;"+title+"</div>" +
					"</div>";
	return itemhtml;
}

function createInnerPageHTML(title, link, pagelevel) {
	if (itemindex % 2 == 0) background = "#003961";
	else background = "#003052";
	var titleLeft = (pagelevel * 15) + 20;
	var itemhtml = "<div class = 'playListPageItem' pagelevel = '"+pagelevel+"' id = 'item_"+itemindex+"' style = 'background:"+background+";' open = 'true' itemindex = '"+itemindex+"' title = '"+title+"' name = '"+link+"' >" +
						"<div id = 'pageTitle_"+itemindex +"' class = 'playListItemTitle' style = 'left:"+titleLeft+"px;' onclick = 'toggleOpenClosed("+itemindex+");'><small>&#9660;</small>&nbsp;&nbsp;"+title+"</div>" +
					"</div>";
	return itemhtml;
}

function createInnerClosedPageHTML(title, link, pagelevel) {
	if (itemindex % 2 == 0) background = "#003961";
	else background = "#003052";
	var titleLeft = (pagelevel * 15) + 20;
	var itemhtml = "<div class = 'playListPageItem' pagelevel = '"+pagelevel+"' id = 'item_"+itemindex+"' style = 'background:"+background+";' open = 'false' itemindex = '"+itemindex+"' title = '"+title+"' name = '"+link+"' >" +
						"<div id = 'pageTitle_"+itemindex +"' class = 'playListItemTitle' style = 'left:"+titleLeft+"px;' onclick = 'toggleOpenClosed("+itemindex+");'><small>&#9658;</small>&nbsp;&nbsp;"+title+"</div>" +
					"</div>";
	return itemhtml;	
}


function createHTML(title, link, rating, pagelevel, dbParentID, likes) {
	if (likes==null) likes =0;
	if (itemindex % 2 == 0) background = "#001626";
	else background = "#002540";
	var itemhtml = "<div class = 'playListItem' pagelevel = '"+pagelevel+"' id = 'item_"+itemindex+"' title = '"+title+"' style = 'background:"+background+";' name = '"+link+"' rating ='"+rating+"' likes ='"+likes+"' dbparent = '"+dbParentID+"'>" +
						"<div class = 'playListItemClose' onclick = 'removeVideo("+itemindex+");'>X</div>" +
						"<div class = 'playListItemTitle' onclick = 'playSelectedVideo("+itemindex+");'>"+title+"</div>" +
						"<div class = 'playListVideoButtons'>" +
							"<a id = 'like_"+itemindex+"' class = 'smallLikeButton' title = 'Like this video' href = 'javascript:giveThumbsUp(\""+itemindex+"\", \"like\", \""+title+"\", \""+link+"\", "+rating+", \""+dbParentID+"\");'></a>" +
							"<a id = 'dislike_"+itemindex+"' class = 'smallDislikeButton' title = 'Dislike this video' href = 'javascript:giveThumbsUp(\""+itemindex+"\", \"dislike\", \""+title+"\", \""+link+"\", "+rating+", \""+dbParentID+"\");'></a>" +
						"</div>" +
					"</div>";
	return itemhtml;
}

function determinePlayOrMove(event){
	playlistStartY = event.clientY;
	$('#playListContainer').unbind('mouseup', playlistMouseUp);
	$('#playListContainer').bind('mouseup', playlistMouseUp);
}

function playlistMouseUp(event){
	playlistEndY = event.clientY;
}

function autoChangeVolume() {
	
	/*link = getVideoUrl();
	link = link.split('v=')[1];
	link = link.split('&')[0];
	url = getBaseURL('/ajax/getVolumeRatio.php');
	$.get(url, { contentID: link}, function(volumeInfo){
		if (sessionUserID != '4') {
			encodedVolumeInfo = eval('('+volumeInfo+')');
			setVolume(encodedVolumeInfo.volumeRatio);
			initialVolume = getVolume();
			clearTimeout(volumeTimeout);
			volumeTimeout = setTimeout('checkVolumeChange();', 30000);
		}
	});	*/
}

function checkVolumeChange() {
	
	/*endVolume = getVolume();
	if(endVolume > 3 && endVolume != initialVolume){
		link = getVideoUrl();
		link = link.split('v=')[1];
		link = link.split('&')[0];
		url = getBaseURL('/ajax/adjustVolume.php');
		$.get(url, { contentID: link, volumeChangeRatio:endVolume});

	}*/
}



function onPlayerError(errorCode) {
	
	if (errorCode == 100 || errorCode == 150 || errorCode == 101)	{
		
		url = getBaseURL('/ajax/videoCheck.php');
		link = getVideoUrl();
		link = link.split('v=')[1];
		link = link.split('&')[0];
		
		url = url + '&videoID='+ link;
		$.ajax({
			url: url,
			success: function(html){
				$("body").append("<div id='videoInfoBox'>"+html+"</div>");
				setTimeout('removeVideoInfoBox()', 4000);
			}
		});
	}
	
	setTimeout('checkForStateToPlay();', 2000);
		//setTimeout('play()', 2000);
}

function removeVideoInfoBox() {
	$('#videoInfoBox').remove('#videoInfoBox');	
}

function onytplayerStateChange(newState) {
	
	if (adPlaying == false) {
		currentPlayerState = newState;
		//add a timeout to this, should allow us to check that the state isn't changing...
		if (newState == 0) {
			videosWatched++;
			setTimeout('checkForStateToPlay();', 500);
		}
	}
}

function checkForStateToPlay() {

	if (currentPlayerState != 1 || currentPlayerState != 2 || currentPlayerState != 3)  {
		nextVideo();
	}
	else setTimeout('checkForStateToPlayFinal();', 1500);
}

function checkForStateToPlayFinal() {
	if (currentPlayerState != 1 || currentPlayerState != 2 || currentPlayerState != 3)  {
		nextVideo();
	}
}

function directPlayVideo(id, addToRecent) {
	if (currentDirectVideo != null) {
		if ($('#'+currentDirectVideo).attr('type') == 'searchVideo') $('#'+currentDirectVideo).css('background', '#eeffff');
		else $('#'+currentDirectVideo).css('background', '#ffffff');
	}	
	currentDirectVideo = id;
	var video = $('#'+id);
	$(video).css('background', '#ccddee');
	currentVideoID = id.split('_')[0];
	currentLink = $(video).attr('videolink');
	currentTitle = $(video).attr('realtitle');
	currentRating = $(video).attr('rating');
	currentDBParent = $(video).attr('dbparent');
	
	if (addToRecent == null) addToRecent = false;
	if (addToRecent != false) {
		url = getBaseURL('/ajax/recent.php');
		$.get(url, { contentID: currentLink, contentTitle:currentTitle, contentRating:currentRating });
	}
	
	displayCurrentlyPlaying();
	loadNewVideo(currentLink, '0');
}


function endAd(id) {
	videosWatched++;
	adPlaying = false;
	loadNewVideo(id, '0');
}
  
// functions for the api calls
function loadNewVideo(id, startSeconds) {
  
	if (adPlaying == false) {
		if (ytplayerDefined == true) {
			if (videosWatched % 10 == 3 && sessionUserID != '4') {
				ytplayer.loadVideoById('egntqcKLJZo', 0);
				adPlaying = true;
				setTimeout("endAd('"+id+"');", 13000);
			}
			else {
				ytplayer.loadVideoById(id, parseInt(startSeconds));
				autoChangeVolume();
			}
		}
		else setTimeout("loadNewVideo('"+id+"','"+startSeconds+"');", 500);
	}
}


function cueNewVideo(id, startSeconds) {
  if (ytplayer) {
    ytplayer.cueVideoById(id, startSeconds);
    autoChangeVolume();
    
  }
}

function play() {
  if (ytplayer) {
    ytplayer.playVideo();
  }
}

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

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

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

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 getEmbedCode() {
  alert(ytplayer.getVideoEmbedCode());
}

function getVideoUrl() {
  return ytplayer.getVideoUrl();
}

function setVolume(newVolume) {
  if (ytplayer) {
    ytplayer.setVolume(newVolume);
  }
}

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