function pageselectCallback(page_id, jq){
	location.href='videosearchresult.htm?'+ urlString + '&pagenumber=' + (page_id + 1);
	return false;
}

//------------------------------------------------------------------------------------------------------------------
var ytplayer = null;
var currentVideoId = null;
var isDirty = false; //is set to true when video is loaded using manual intervention
var skipCount = 0;
var moveToNext = true;
//var playlistContainer = 'freatured_container';
//------------------------------------------------------------------------------------------------------------------
function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("myytplayer");
	ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
	ytplayer.addEventListener("onError", "onPlayerError");
}


$(document).ready(function(){ //This will be done globally	
	//FB.init("0c4e5a57e1f1ab1a3d7362bd7b663f5d", "http://plm.najanaja.com/xd_receiver.html");	
	//FB.init("cc83490ba28b59332cd8a82a10adabc3", "http://hohalla.com/xd_receiver.html");
})

//------------------------------------------------------------------------------------------------------------------
function onytplayerStateChange(newState) {
    if(newState == 0 && !isDirty && moveToNext){ //Make sure that you move to next in the playlist only if video is not stopped due to manual intervention			
		playNextOrPrevVideo(true);
	} else if(newState == 1){
		skipCount = 0;
	}
	isDirty = false;
}
//------------------------------------------------------------------------------------------------------------------
function onPlayerError(errorCode) {
	//alert('Here we catch stuff');
	//Move to next in the playlist
	skipCount = skipCount + 1;
	if(skipCount < 5){
		setTimeout('next()', 4000);	//Need to set a flag so that this happens only 5 times in a row.
	}
}
//------------------------------------------------------------------------------------------------------------------

		function prev() {
			if (ytplayer) {
				playNextOrPrevVideo(false);
			}
			return false;
		}
		
 		function next() {
			if (ytplayer) {
				playNextOrPrevVideo(true);
			}
			return false;
		}		
			
		function play() {
			if (ytplayer) {
				ytplayer.playVideo();
			}
			return false;
		}
 
 		function pauseVideo() {
			if (ytplayer) {
				ytplayer.pauseVideo();
			}
			return false;
		}
		
 		function mute() {
			if (ytplayer) {
				ytplayer.mute();
			}
			return false;
		}
		
 		function unMute() {
			if (ytplayer) {
				ytplayer.unMute();
			}
			return false;
		}
		
		//------------------------------------------------------------------------------------------------------------//	
		function mover(obj) {
			var container = getParentContainer(obj);
			if(currentVideoId == obj.id && container == playlistContainer){
				obj.className = 'playinghi';
			} else if(container == playlistContainer){
				obj.className = 'playlisthi';
			}
		}
		//------------------------------------------------------------------------------------------------------------//
		function mout(obj) {
			var container = getParentContainer(obj);	
			if(currentVideoId == obj.id && container == playlistContainer){
				obj.className = 'playinglo';
			} else if(container == playlistContainer){
				obj.className = 'playlistlo';
			}		
		}		
		
//------------------------------------------------------------------------------------------------------------------
//This function gets the position of video that will be played		
//------------------------------------------------------------------------------------------------------------//
function getPositionTobePlayed(currentPosition, flag){ //Flag determines wheather to move forward or backward. true = forward
	
	//var query = "#" + playlistContainer + " div[position]";
	var array = $("#" + playlistContainer + " div[position]");
	if(array.length == 0){ //If the playlist is not loaded
		return -1;
	}
	
	var positions = []; //Read in an array
	for (var i = 0; i < array.length; i++) {
		var data = $(array[i]).attr('position');
		positions.push(data);		
	}

	//positions.sort();		

	if (currentPosition == -1){ //-1 is passed only during init
		return positions[0];
	}

	var index = findIndexInSingleArray(positions, currentPosition);

	if(flag){
		index++; //flag means get next video.
	} else {
		index--; //-1 happens if 0 is playing and user clicks prev
	}
	
	var position = positions[0]; //Default is always zero

	if(index > -1 && index < positions.length){
		position = positions[index];
	}
	return position;
}

//------------------------------------------------------------------------------------------------------------//
function initVideo(){
	var position = getPositionTobePlayed(-1, true);
	if(position != -1){
		
		var obj = $("#" + playlistContainer + " div[position='" + position + "']");
		//var obj = $("div[position='" + position + "']");	
		
		$(obj).attr('className', 'playinglo');
		currentVideoId = obj.attr("id");		
  		//var params = { allowScriptAccess: "always",  allowFullScreen: "true", wmode: "transparent" };
  		var params = { allowScriptAccess: "always",  allowFullScreen: "true"};
    	var atts   = { id: "myytplayer" };
    	var url = "http://www.youtube.com/v/" + currentVideoId + "&hl=en&fs=1&autoplay=" + autoplay + "&enablejsapi=1&rel=0&playerapiid=ytplayer&enablehref=false&readonly=1&fs=1&sourceid=y&playnext=0";
    	swfobject.embedSWF(url, "ytapiplayer", width, height, "8", null, null, params, atts);
		updateLink(currentVideoId);
		getVideoComments(currentVideoId);
		getTitleAndDescription(currentVideoId);
    	if(autoplay == 1){
			writeCategoryInfo(currentVideoId, 'true', 'recently'); //Must write to the recently played log
		}	
	}
}

//------------------------------------------------------------------------------------------------------------//
function loadVideo(obj, flag) {	

	var container = getParentContainer(obj);
	if(container != null){
		playlistContainer = container;
	}

	if (ytplayer) {
		moveToNext = true;
		var videoId = $(obj).attr("id");
		playVideo(videoId, flag);
	}
}
//------------------------------------------------------------------------------------------------------------//
function getParentContainer(obj){
	var parents = $(obj).parents();
	for (var i = 0; i < parents.length; i++) {
		var idx = $(parents[i]).attr('idx');
		if(idx != null){
			return idx;
		}		
	}
	return null;
}

//------------------------------------------------------------------------------------------------------------//
function playVideo(videoId, flag) {
	if (ytplayer) {
		isDirty = flag;			
		setPlayingStyle(videoId);
		currentVideoId = videoId;
		ytplayer.clearVideo();
		ytplayer.loadVideoById(videoId, parseInt("0"));
		updateLink(currentVideoId);
		getVideoComments(currentVideoId);
		getTitleAndDescription(currentVideoId);
		writeCategoryInfo(currentVideoId, 'true', 'recently'); //Must write to the recently played log		
	}
}
//------------------------------------------------------------------------------------------------------------//	
function setPlayingStyle(videoId) {
	//$('#' + currentVideoId).attr('className', 'playlistlo');
	//$('#' + videoId).attr('className', 'playinglo');	
	//$('#' + playlistContainer + ' #' + currentVideoId).attr('className', 'playlistlo');
	
	$("div[position]").attr('className', 'playlistlo');
	$('#' + playlistContainer + ' #' + videoId).attr('className', 'playinglo');
	
	var obj = $('#' + playlistContainer + ' #' + videoId);
	if(obj.length > 0){
		var obj = $('#' + playlistContainer);		
		$('#' + playlistContainer + ' > div').scrollTo($('#' + playlistContainer + ' #' + videoId), 800);
	}
}
//Gets next or prev video entry
//------------------------------------------------------------------------------------------------------------//
function playNextOrPrevVideo(nextorprev){
		var currentPosition = $('#' + currentVideoId).attr('position');	
		currentPosition = getPositionTobePlayed(parseInt(currentPosition), nextorprev);	
		var obj = $("#" + playlistContainer + " div[position=" + currentPosition + "]");
		//var obj = $("div[position=" + currentPosition + "]");
		
		var videoId = obj.attr("id");
		if(videoId == null){
			var obj = $("#" + playlistContainer + " div[position='1']");	
		}
		loadVideo(obj, true);
}
//------------------------------------------------------------------------------------------------------------//
function promoteVideo(vidid, playlist, currentplaylist, obj){
	 writeCategoryInfo(vidid, 'true', playlist)
	$(obj).hide();
	return false;
}
//------------------------------------------------------------------------------------------------------------//
function writeCategoryInfo(vidid, value, playlist){
	if(typeof(value) != "string"){
		value = $(value).attr('checked');
		//values = $(values).val();
	}	
	//console.log("Selected values: " + selected);
	request = requestStart + '<methodname>' + 'writeCategoryInfo' + '</methodname><arg><![CDATA[' + vidid + ']]></arg><arg><![CDATA[' + value + ']]></arg><arg><![CDATA[' + playlist + ']]></arg>' + requestEnd;
	AjaxDwrMethodsHandler.handleRequest(request, function(data){});
}
//------------------------------------------------------------------------------------------------------------//
function getVideoComments(vidid){
	$('#commentboxmessage').attr('innerHTML', '');
	$('#comments').attr('innerHTML', '');
	$('#commentform')[0].reset();
	$('#commentbox').show();	
	
	$('#commentwrapper').css('display', 'none');	
	$("#comments").load("/ajaxvideocomments.htm?vidid=" + vidid);
	$('#commentwrapper').css('display', 'block');

	addedname = false;
	addedcomments = false;
	/*
	request = requestStart + '<methodname>' + 'getVideoComments' + '</methodname><arg><![CDATA[' + vidid + ']]></arg>' + requestEnd;
	AjaxDwrMethodsHandler.handleRequest(request, function(data){	
		if(jQuery.trim(data).length > 0){			
			$('#comments').attr('innerHTML', jQuery.trim(data));
			$('#commentwrapper').css('display', 'block');
		}
	});
	*/
}
//------------------------------------------------------------------------------------------------------------//
function saveComment(){	
	var name = $('#commentname').val();
	var text = $('#commenttext').val();
	if(addedname && addedcomments && jQuery.trim(name) != '' && jQuery.trim(text) != ''){
		request = requestStart + '<methodname>' + 'writeVideoComment' + '</methodname><arg><![CDATA[' + currentVideoId + ']]></arg><arg><![CDATA[' + name + ']]></arg><arg><![CDATA[' + text + ']]></arg>' + requestEnd;
		AjaxDwrMethodsHandler.handleRequest(request, function(data){
			//$('#commentbox').attr('innerHTML', "<h3>Thank you for your comment</h3>");
			$('#commentbox').hide();
			$('#commentboxmessage').attr('innerHTML', "<h2>Thank you for your comment</h2>");			
		});
	}
}
//------------------------------------------------------------------------------------------------------------//
function getTitleAndDescription(vidid){
	request = requestStart + '<methodname>' + 'getVideoInfo' + '</methodname><arg><![CDATA[' + vidid + ']]></arg>' + requestEnd;
	AjaxDwrMethodsHandler.handleRequest(request, function(data){	
		var delimiter = "$$$###";
		var index = data.indexOf(delimiter);
		var title = data.substring(0, index);	
		var description = data.substring(index + delimiter.length, data.length);	
		var sPath = window.location.pathname;
		var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);		
		if(sPage.indexOf('index') == -1 && sPage != ''){
			document.title = title;
			document.description = description;
		}
		title=title.replace(/\'/g,"\\'");		
	});
}
//------------------------------------------------------------------------------------------------------------//	
function updatePlayList(videoId){		
	$('#playlistarea').fadeOut('3000');
	var request = requestStart + '<methodname>' + 'getPlayListVideos' + '</methodname><arg><![CDATA[' + videoId + ']]></arg><arg><![CDATA[' + 'false' + ']]></arg>' + requestEnd;
	AjaxDwrMethodsHandler.handleRequest(request, function(data){
		$('#playlistarea').attr('innerHTML', data);
		$('#currenttitle').attr('innerHTML', "Streaming selected video and its related videos");
		$('#playlistarea').fadeIn('3000');
		playVideo(videoId, true);
	});
}
//------------------------------------------------------------------------------------------------------------//	
function updateLink(videoId){		
	var link = $('#pagelink').val() + videoId;
	$('#vidurl').val(link);
}