
function initOnLoad(){
    ytp.nowDisplayUrl = '';
    updateHTML(ytp.VIDEO_PLAYER_DIV, "");
    if (testFlash()) {
        ytp.clearSearchBox();
        ytp.reset();
        parseURL();
    }
};

function loadplaylist(){
	
    if (ytp.critical_error == 1) { return }; 
    if(ytp.error == 1){
        ytp.hideError();
    }
    updateHTML(ytp.VIDEO_LIST_CONTAINER_DIV, 'Loading ...');
    //chngS(10);
    ytp.reset();
    ytp.clearPlayerDescription();
    ytp.hideNavigation();
    ytp.videoPlayerHide();
    updateHTML(ytp.LIST_COUNT_DIV, '');
    updateHTML(ytp.MAIN_TITLE_DIV, '');
    updateHTML(ytp.VIDEO_INFO_DIV, '');
    //updateHTML(ytp.PL_STATS_DIV, "Playing ...");
    var playlistURL = document.getElementById( "pl_url" );
    //ytp.listVideoSearch(ytSearchTerm.value, 1);
    ytp.loadPlaylist(playlistURL.value);

    //ytp.nowDisplayUrl = '';
    //updateHTML(ytp.VIDEO_PLAYER_DIV, "");
    //if (testFlash()) {
    //    ytp.clearSearchBox();
     //   ytp.reset();
     //   parseURL();
    //}
};

/*clears text initially in input field*/
function clearDefaultandCSS(el) {
    if (el.defaultValue==el.value) el.value = "";
    if (el.style) el.style.cssText = "";
};

/*submits on"enter" button*/
function submitenter(myfield,e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	
	if (keycode == 13)
	   {
	   startytsearch();
	   return false;
	   }
	else
	   return true;
};

function moveToList(obj, targetId) {
	
	if (targetId == '#sortable2') {
		$(obj).html("<<");
		$(obj).click(function() {
			moveToList(this, "#sortable1");
		   });
	};
	if (targetId == '#sortable1') {
		$(obj).html(">>");
		$(obj).click(function() {
			moveToList(this, "#sortable2");
		   });
	};
	$(targetId).append(obj.parentNode);
	showHideHelper('sortable2', 'result-helper');	
};

function do_sortable(){
	
	$("#sortable1").sortable({ 
		cancel: '.static',
		connectWith: '#sortable2', 
		placeholder: "place-highlight",
		receive:  function(event, ui) {
            var id;
            showHideHelper('sortable2', 'result-helper');
			
			var obj = $(ui.item).get(0);
			obj = $(obj).children().get(3);
			obj.innerHTML = ">>";
			$(obj).click(function() {
				moveToList(this, "#sortable2");
		   	});
        }
 		});
	
	$("#sortable2").sortable({ 
		cancel: '.static',
		connectWith: '#sortable1',
		placeholder: "place-highlight",
		receive:  function(event, ui) {
            var id;
            showHideHelper('sortable2', 'result-helper');
			var obj = $(ui.item).get(0);
			obj = $(obj).children().get(3);
			obj.innerHTML = "<<";
			$(obj).click(function() {
				moveToList(this, "#sortable1");
		   	});
        }
		});
	$("#sortable1, #sortable2").disableSelection();
		
};

function do_moveable(){
	$(".move1").click(function() {
		moveToList(this, "#sortable2");
	});
};

function showHideHelper(listId, dropzoneId ) {
    var usedLength = $('#'+listId).children().length;
    ytp.result_length = usedLength-1;
	$("#result_count").html(usedLength-1);
    if( usedLength >= 2){
        $('#'+dropzoneId).hide();
    } else {
        $('#'+dropzoneId).show();
    }
};

function getPlaylist(){
	ytp.result_playlist = [];
	
	if (ytp.result_length >= 1) {
		var $res_list = $("#sortable2").children(); //childNodes
		var len = $res_list.length;
		for (var i = 0; i < $res_list.length; i++)
	    {
			//console.log($res_list.get(i));
			obj = $res_list.get(i);
			id = $(obj).attr('id');
			if (id != 'result-helper') {
				ytp.result_playlist.push(id);
			}
	    }
	}
	return ytp.result_playlist;
}

function save_to_yotube() {
	//console.log("do save YT");
	var title = $("#pl_title").attr('value');
	var descr = $("#pl_description").attr('value');
	var playlist_str = getPlaylist().toString();
	$.ajax({
		type: "POST",
		url: "playlist.php",
		dataType: "json",
		data: ({ queryType: "addPlaylist", 'title': title, 'description': descr, 'playlist': playlist_str }),
		success: function(data, textStatus){
			//console.log("otvet: " + textStatus + ' data: '+ data);
	        //try {
	        //    var myObj = eval( '(' + data + ')' );
	        //} catch (e) {}
	        //if(myObj) {
				//myObj = data;
	        	//console.log('obj - '+ myObj);
	            if (data.status == 'error'){
	                //console.log(myObj.message);
	                //console.log(myObj.errorMessage);
	                ytp.showError(data.message + data.errorMessage);
	            } else {
	            	ytp.showError(data.message);
	            }
	        //} else { 
	        //	console.log(data);
	        //	ytp.showError('Loaded data incorect! Please Reload It!');}

	  	},
	  	error: function (XMLHttpRequest, textStatus, errorThrown) {
	  		some_error(XMLHttpRequest, textStatus, errorThrown);
	  	}
	});
	
};

function save_to_xml() {
	playlist = getPlaylist();
	//["L9zc4wgMSNg", "WPzgGs_cHWo", "rn9utR2jdrQ" ]//getPlaylist();
	//ytp.result_playlist = playlist;
	
	$("#search_wrapper").remove();
	$("#playlist_wrapper").remove();
	$("#main_wrapper").remove();
	$("#topbar").remove();
	
	$("#global").empty();
	$("#global").css("background","grey");
	forms = '<form id="edit_playlist" name="playlist" action="playlist.php" method="post">'+
	'<input type="hidden" name="queryType" value="createXml" /><br />'+
	'Title: <input type="text" name="mainTitle" size="80" value="Name of playlist" /><br />'+
	'Description: <input type="text" name="mainDescription" size="100" value="Some Description" /><br /> <br />'+
	'</form>'; 
//	'Title: <input class="xml_title" type="text" name="xtitle['+id+']" size="80" value="'+data.entry.title.$t+'" /><br />';
//	out += 'Author: <input class="xml_aythor" type="text" name="xauthor['+id+']" size="50" value="'+authors_name.join(", ")+'" /><br />';
	$("#global").append( forms );
	out ='';
	for (var i = 0; i < playlist.length; i++) {
		//console.log("{i} - "+playlist[i]);
		$.ajax({
		    dataType: "jsonp",
		    async: "false",
		    url: "http://gdata.youtube.com/feeds/api/videos/"+playlist[i]+"?v=2&alt=json&callback=?",
		    success: function(data){
				var authors_name = [];
				author = data.entry.author;
				for(var i in author) {
					authors_name.push(author[i].name.$t);
				}
				//console.log(data.entry.title.$t+' - '+authors_name.join(", "));
				id = data.entry.media$group.yt$videoid.$t;
				var out = "";
				out += '<div class="xml_items">';
				out += '<img class="xml_img" src="'+data.entry.media$group.media$thumbnail[0].url+'" />';
				out += 'Title: <input class="xml_title" type="text" name="xtitle['+id+']" size="80" value="'+data.entry.title.$t+'" /><br />';
				out += 'Author: <input class="xml_aythor" type="text" name="xauthor['+id+']" size="50" value="'+authors_name.join(", ")+'" /><br />';
				out += 'Description: <textarea class="xml_descr" name="xdescr['+id+']" rows="3" cols="80">'+data.entry.media$group.media$description.$t+'</textarea><br />';
				out += '</div>';
				$("#edit_playlist").append( out );
				}
		  }); 
	
	};
//	$("#global").append( out );
	$("#edit_playlist").append( out );
	button = '<input id="save_playlist" type="submit" value="Generate List" />';
	$("#edit_playlist").append( button );
	//$("#save_playlist").insertBefore(".xml_items");
	//for (var i = 0; i < ytp.result_playlist.length; i++) {
	//	console.log(" ytp-pl - "+ytp.result_playlist[i].title);
	//}
	
	//out += '<input type="submit" value="Submit" />	</form>'; 
	

//	
//	
	//console.log(out);
	//$("#main_wrapper").html();


};

function print_data(){
	 var str = $("form#edit_playlist").serializeArray();
	 //console.log(str);
	 str = $(str).serialize();
	 //console.log(str);
	 //console.log('------------');
	 str = $("form#edit_playlist").serialize();
	 //console.log(str);
	 //$("#butt").html(str);
	 //$("#ser123").html(str);
	 


}

function in_array(needle, haystack){
	//console.log(needle);
	//console.log(haystack);
	for(var key in haystack){ // РџРµСЂРµР±РёСЂР°РµРј РІСЃРµ СЌР»РµРјРµРЅС‚С‹ РјР°СЃСЃРёРІР° 
		if(needle == haystack[key]){ // Р� СЃСЂР°РІРЅРёРІР°РµРј СЃ РёСЃРєРѕРјС‹Рј СЌР»РµРјРµРЅС‚РѕРј 
			return true; // Р’СЃРµ РѕС‡РµРЅСЊ РїСЂРѕСЃС‚Рѕ 
		} 
	} 
	return false; 
} 


function testFlash(){
   if (swfobject.hasFlashPlayerVersion("9.0.0")) {
       return true;
    }
    else {
    var txt = 'You need Flash player 9+ and JavaScript enabled to view this video.<br /> \
<a href="http://get.adobe.com/flashplayer/" target=\"_blank\"> Please update your FlashPlayer  </a>';
    updateHTML('player_text', txt);
    ytp.critical_error = 1;
    return false;
    } 
}

//function testLogin(){
//	$.ajax({
//		type: "POST",
//		url: "playlist.php",
//		dataType: "text",
//		data: ({ queryType: "testLogin", }),
//		success: function(data, textStatus){
//	        updateHTML('login_status', data);
//	  	},
//	  	error: function (XMLHttpRequest, textStatus, errorThrown) {
//	  		some_error(XMLHttpRequest, textStatus, errorThrown);
//	  	}
//	});
//	
//}

function some_error(XMLHttpRequest, textStatus, errorThrown) {
	 try {
		 var myObj = eval( '(' + XMLHttpRequest.responseText + ')' );
	 } catch (e) {}
	 if(myObj) {
	     if (myObj.status == 'error'){
	         //console.log('err-code' + myObj.error_code);
	         ytp.showError(myObj.message + myObj.errorMessage);
	     } 
	 } else { 
		 //console.log(XMLHttpRequest.responseText);
		 ytp.showError('Some error! Please Reload!');
		 }
}
 
function parseURL(){
   if (ytp.critical_error == 1) { return }; 
   var url = window.location.href;
   var SearchTerm = "";
   var playlistURL = "";
   var publ = "";
   var advImg = "images/fload.jpg";
   if ( url.indexOf( '?playlist=' ) >= 0 ){
            advImg = "";
            playlistURL = url.substring( url.indexOf( '?playlist=' )+10, url.length );
            if ( url.indexOf( '#' ) >= 0 ){ 
                playlistURL = playlistURL.substring( 0, playlistURL.indexOf( '#' ) );} 
            if ( url.indexOf( '&' ) >= 0 ){
                publ = playlistURL.substring(playlistURL.indexOf( '&' )+1,playlistURL.length ); 
                playlistURL = playlistURL.substring( 0, playlistURL.indexOf( '&' ) );
            }
            ytp.loadPlaylist(playlistURL);
            if (publ){
                ytp.savePlaylist(playlistURL, publ);
            }
   }
   if ( url.indexOf( '#' ) > 0 ){
      SearchTerm = decodeURIComponent(url.substring( url.indexOf( '#' )+1, url.length ));
      if (SearchTerm.length>0) {
          advImg = "";
          document.getElementById( "yts" ).value = SearchTerm;
          updateHTML(ytp.VIDEO_LIST_CONTAINER_DIV,'Loading ...');
          //chngS(10);
          ytp.listVideoSearch(SearchTerm, 1);
      }
   }
   if(advImg.length >0 ){
      ytp.showPlayerImage(advImg);
   }
}

//do search on YT
function startytsearch() {
    if (ytp.critical_error == 1) { return }; 
    if(ytp.error == 1){
        ytp.hideError();
    }
    updateHTML(ytp.VIDEO_LIST_CONTAINER_DIV, 'Loading ...');
    //chngS(10);
    ytp.reset();
    ytp.clearPlayerDescription();
    ytp.hideNavigation();
    ytp.videoPlayerHide();
    updateHTML(ytp.LIST_COUNT_DIV, '');
    updateHTML(ytp.MAIN_TITLE_DIV, '');
    updateHTML(ytp.VIDEO_INFO_DIV, '');
    //updateHTML(ytp.PL_STATS_DIV, "Playing ...");
    var ytSearchTerm = document.getElementById( "yts" );
    ytp.listVideoSearch(ytSearchTerm.value, 1);
}

// return random (0..max)
function getRandom( max) {
    return Math.floor( Math.random()* max);
}


// function for controlling ytp
function updateHTML(elmId, value) {
  document.getElementById(elmId).innerHTML = value;
}

function updateHTMLadd(elmId, value) {
  document.getElementById(elmId).innerHTML = document.getElementById(elmId).innerHTML+"<br />"+value;
}

function initPlaer(videoID){
    if (ytp.critical_error == 1) { return }; 
    //  Specifies your FlashVars
    var flashvars = {   
        rel: 0, //The player search functionality will be disabled if rel is set to 0.
        showsearch: 0,
        egm: 0,
        border: 0,
        enablejsapi: 1,
        //loop: 1, //setting of 1 will cause the player to play the initial video again and again.
        showinfo: 0
    };
    // The parameters for the embed object
    var params = {     
          allowScriptAccess: "always", 
          bgcolor: "#cccccc",
          menu: "true",
          volume: 20
      };
      // 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
      
      // The attributes for the embed object
      var atts = {      
          id: "myytplayer"
      };
      swfobject.embedSWF("http://www.youtube.com/v/"+videoID+"&playerapiid=ytplayer&autoplay=0&rel=0",
                         "videoPlayer", "450", "285", "8", null, flashvars, params, atts);

  ytp.plaerLoad = 1;                        
     
}

function disablePlaer(){
    if (document.getElementById("myytplayer")) {
	    swfobject.removeSWF("myytplayer");
    }
    updateHTML( 'searchResultsVideoColumn',"<div id=\"videoPlayer\"> </div>");
    //ytp.nowPlaying = 0;
    ytp.plaerLoad = 0;
}


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

// display player error
function onPlayerError(errorCode) {
  ytp.videoPlayerHide();
  ytp.showError('Sorry. This Video cannot be played!');
  disablePlaer();
  //if (ytp.rndState != "off"){
  //    ytp.autoNextVideo(); 
  //}

}

function onytplayerStateChange(newState) {
    //if (newState == 0 && ytp.previousState == 1 && ytp.rndState != "off" ){
    //    ytp.autoNextVideo();
    //}
    //if (newState == 0 && ytp.previousState == 1 && ytp.rndState == "off"){
    //    seekTo(0);
    //    setTimeout ("pause();", 2500);
    //}
    ytp.previousState = newState;
}

// functions for the api calls
function loadNewVideo(id, startSeconds) {
  if (ytplayer) {
    ytplayer.loadVideoById(id, parseInt(startSeconds));
  }
  
}

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

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

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

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

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

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

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

function getEmbedCode() {
  alert(ytplayer.getVideoEmbedCode());
}

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


//***********************************************************************************/
// array sort function
function sRank(a, b) { 
       return a.rank - b.rank;
}

function sRank_down(a, b) { 
    if (a.rank < b.rank)
       return 1;
    else if (a.rank > b.rank)
       return -1;
    else
       return 0;
}

function sTitle(a, b) { 
    if (a.title > b.title)
       return 1;
    else if (a.title < b.title)
       return -1;
    else
       return 0;
}

function sGroup(a, b) { 
    if (a.group > b.group)
       return 1;
    else if (a.group < b.group)
       return -1;
    else
       return 0;
}

/** *********************************************************************
 * provides namespacing for the YouTube Video Browser PHP version (ytp)
 */
var ytp = {};

/**
 * maximum number of results to return for list of videos <=50
 * @type Number
 */
ytp.MAX_RESULTS_LIST = 25;

/**
 * url where ytp located
 * @type String
 */
ytp.YTP_URL = 'http://192.168.255.133/site/ytp/ytplayer.html';

/**
 * navigation button id used to page to the previous page of
 * results in the list of videos
 * @type String
 */
ytp.PREVIOUS_PAGE_BUTTON = 'previousPageButton';

/**
 * navigation button id used to page to the next page of
 * results in the list of videos
 * @type String
 */
ytp.NEXT_PAGE_BUTTON = 'nextPageButton';

/**
 * container div id used to hold list of videos
 * @type String
 */
ytp.VIDEO_LIST_CONTAINER_DIV = 'searchResultsVideoList';

/**
 * container div id used to hold the video player
 * @type String
 */
ytp.VIDEO_PLAYER_DIV = 'videoPlayer';

/**
 * container div id used to hold the Title of player
 * @type String
 */
ytp.MAIN_TITLE_DIV = 'mtitle';

/**
 * container div id used to hold the video Info in Playing tab
 * @type String
 */
ytp.VIDEO_INFO_DIV = 'video_info';

/**
 * container div id used to hold the count of playlist
 * @type String
 */
ytp.LIST_COUNT_DIV = 'searchResultsCount';

/**
 * container div id used to hold the number of currently playing
 * @type String
 */
//ytp.PL_STATS_DIV = 'pl_stats';

/**
 * container div id used to hold the description of playlist or image
 * @type String
 */
ytp.PL_TEXT_DIV = 'player_text';

/**
 * container div id used to hold the error message
 * @type String
 */
ytp.ERROR_DIV = 'error_msg';

/**
 * container div id used to hold the public playlist in More tab
 * @type String
 */
ytp.PUBLIC_PLAYLIST_DIV = 'publicPlaylists';

/**
 * the page number to use for the next page navigation button
 * @type Number
 */
ytp.nextPage = 2;

/**
 * the page number to use for the previous page navigation button
 * @type Number
 */
ytp.previousPage = 0;

/**
 * count of items of playlist
 * @type Number
 */
ytp.itemsCount = 0;

/**
 * mark of player loading
 * @type Number
 */
ytp.plaerLoad = 0;

/**
 * contains currently played playlist
 * @type String
 */
ytp.playList = false;

/**
 * mark of error
 * @type String
 */
ytp.error = 0; 

ytp.critical_error = 0; 


/** 
 * the last search term used to query - allows for the navigation
 * buttons to know what string query to perform when clicked
 * @type String
 */
ytp.previousSearchTerm = '';

/**
 * previous state mark of player
 * @type Number
 */
ytp.previousState = -1;  

/**
 * mark currently state of random / list/ off
 * @type String
 */
ytp.rndState = "off";

/**
 * number of currently playing video
 * @type Number
 */
ytp.nowPlaying = 0;

/**
 * url for detach function
 * @type String
 */
ytp.nowDisplayUrl = '';

/**
 * mark "Back" button
 * @type Number
 */
ytp.beBack = 0;

/**
 * number of result playlist
 * @type Number
 */
ytp.result_length = 0;

/**
 * result playlist
 * @type array
 */
ytp.result_playlist = [];




ytp.reset = function(){
    ytp.initRnd();
    ytp.result_playlist = [];
    if(ytp.plaerLoad == 1) {
        stop();
        clearVideo();
    }
    return true;
}

ytp.initRnd = function(){
    //document.getElementById( "rnd" ).checked = false;
    //document.getElementById( "pll" ).checked = false;
    ytp.rndState = "off";
}


ytp.randomize = function(obj) {
   //if (ytp.rndState == obj.id){
   //    ytp.rndState="off"; obj.checked = false;
   //} else {
   //    ytp.rndState = obj.id;
   //} 
}

ytp.savePlaylist = function(playlistURL, publ){
    
   var params = 'queryType=savePlaylist&playlist=' + playlistURL+'&'+ publ;
   var filePath = 'ytplayer.php';
   ytp.sendRequest(filePath, params, ytp.ERROR_DIV, 'savePlaylist');
    
};

ytp.clearSearchBox = function(){
    document.getElementById('yts').value = 'search youtube';
    
}

ytp.clearPlayerDescription = function(){
    updateHTML(ytp.PL_TEXT_DIV, "");
    document.getElementById(ytp.PL_TEXT_DIV).style.display = 'none';
    return true;
}

ytp.showPlayerDescription = function(msg){
    updateHTML(ytp.PL_TEXT_DIV, msg);
    document.getElementById(ytp.PL_TEXT_DIV).style.display = 'inline';
    return true;
}

ytp.showPlayerImage = function(advImg){
    updateHTML(ytp.PL_TEXT_DIV, "<a href=\"javascript:void(0);\" target=\"_blank\"> <img src=\""+ advImg +"\" width=\"450\" height=\"285\" border=\"0\" /></a>");
    document.getElementById(ytp.PL_TEXT_DIV).style.display = 'inline';
    return true;
}

ytp.videoPlayerHide = function(){
    if(ytp.plaerLoad == 1) { 
        stop();
        clearVideo();
    }
    document.getElementById('searchResultsVideoColumn').style.visibility = 'hidden';
    if(ytp.plaerLoad == 1) {
        if (document.getElementById('myytplayer')){
            document.getElementById('myytplayer').style.visibility = 'hidden';
        }
    }
    return true;
}

ytp.videoPlayerShow = function(){
    document.getElementById('searchResultsVideoColumn').style.visibility = 'visible';
    if(ytp.plaerLoad == 1) {
        if (document.getElementById('myytplayer')){
            document.getElementById('myytplayer').style.visibility = 'visible';
        }
    }
    return true;
}

ytp.showError = function(msg){
    ytp.error = 1;
    updateHTML(ytp.ERROR_DIV, msg);
    document.getElementById(ytp.ERROR_DIV).style.visibility = 'visible';
    return true;
};
ytp.hideError = function(){
    ytp.error = 0;
    updateHTML(ytp.ERROR_DIV, '');
    document.getElementById(ytp.ERROR_DIV).style.visibility = 'hidden';
    return true;
};

ytp.sortPlayList = function(SortBy){
    var tmpList =  ytp.playList.items;
    var nowID = ( ytp.nowPlaying >= 0)?(tmpList[ytp.nowPlaying].videoId):(-1);
    if (SortBy == 'sRank') {tmpList.sort(sRank);}
    if (SortBy == 'sTitle') {tmpList.sort(sTitle);}
    if (SortBy == 'sGroup') {tmpList.sort(sGroup);}

    var text = "<table class=\"videoList\"><tbody width=\"270\">";
    for (var i = 0; i < tmpList.length; i++)
    {
        text+= "<tr width=\"270\">"+
            "<td>" +tmpList[i].rank+ "</td>"+
            "<td width=\"40\"> <img class=\"img_pointer\" src=\"" + tmpList[i].thumbnailUrl +"\" width=\"40\" height=\"30\" onclick=\"ytp.presentVideo('" +tmpList[i].videoId +"','" +(i+1)+"')\"/> </td>"+
            "<td> <a href=\"javascript:void(0);\" onclick=\"ytp.presentVideo('" +tmpList[i].videoId +"','" +(i+1)+"')\">" + tmpList[i].title+", "+ tmpList[i].group +"</a> </td>"+
            "</tr>";
        if (nowID == tmpList[i].videoId){
            ytp.nowPlaying = i;
        }
    }
    text+="</table>";
    updateHTML(ytp.VIDEO_LIST_CONTAINER_DIV, text);
    ytp.playList.items = tmpList;
};

/**
 * Sends an AJAX request to the server to retrieve a list of videos or
 * the video metadata.  Sends the request to the specified filePath
 * on the same host, passing the specified params
 * @param {String} filePath The path to which the request should be sent
 * @param {String} params The URL encoded POST params
 * @param {String} resultDivName The name of the DIV used to hold the results
 * @param {String} action
 */
ytp.sendRequest = function(filePath, params, resultDivName, action) {
    if (ytp.critical_error == 1) { return false; }; 

    //create AJAX object
    xmlhr = null;
    if (window.XMLHttpRequest) {
        try {
            var xmlhr = new XMLHttpRequest();
        } catch (e){}
    } else if (window.ActiveXObject) {
        try {
            var xmlhr = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e){
            try {
                var xmlhr = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e){}
        }
    }

        
  xmlhr.open('POST', filePath, true);
  xmlhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
  xmlhr.onreadystatechange = function() {
    if (xmlhr.readyState == 1) {
        updateHTML(resultDivName, '<b>Loading...</b>');
    } else if (xmlhr.readyState == 4 && xmlhr.status == 200) {
      if (xmlhr.responseText) {
        try {
            var myObj = eval( '(' + xmlhr.responseText + ')' );
        } catch (e) {}
        if(myObj) {
            if (myObj.status == 'error'){
                updateHTML(resultDivName, '');
                ytp.videoPlayerHide();
                ytp.showError(myObj.msg);
            } else {
                ytp.showResults(myObj, action);
            }
        } else { ytp.videoPlayerHide(); ytp.showError('Loaded data incorect! Please Reload It!');}

      }
    } else if (xmlhr.readyState == 4) {
      ytp.videoPlayerHide();
      ytp.showError('Invalid response received - Status: ' + xmlhr.status);
    }
  }
  xmlhr.send(params);
};

/**
 * Uses ytp.showResults to display  info at  video player 
 * @param {String} p The object of recived data
 * @param {String} action, what do.
**/
ytp.showResults = function(p, action) { 
    var text = "";

    //display Playlist Category with count in More tab
//    if (action == 'loadPlaylistCat'){
//        text = '<lu>Featured playlists:';
//        var it = p.items;
//        for(var category in it){
//            text+= "<li class=\"playlistCat\" onclick=\"ytp.loadTitleCat('"+category+"');\"> "+category + " ("+  it[category]+ ")</li>";
//        }
//        text +="</lu>";
//        updateHTML(ytp.PUBLIC_PLAYLIST_DIV, text);
//    }

    //display Title of playlists in selected Category in More tab
//    if (action == 'loadTitleCat'){
//        text = '<lu class="categoryList"> <span class="categoryList" onclick="ytp.loadPlaylistCat();"> Back </span>';
//        for (i = 0; i < p.items.length; i++) {
//            text+= "<li class=\"playlistCat\" onclick=\"ytp.loadPlaylist('"+p.items[i].url+"');\">"+  p.items[i].title+ "</li>";
//        }
//        text +="</lu>";
//        updateHTML(ytp.PUBLIC_PLAYLIST_DIV, text);
//    }
    
    //display playlist of search from YT in playlist tab
    if (action == 'getSearch'){
        if (p.totalResults == 0){
            updateHTML(ytp.MAIN_TITLE_DIV, "Playlist for: "+ ytp.previousSearchTerm);
            updateHTML(ytp.VIDEO_INFO_DIV, ' ');
            ytp.hideNavigation();
            updateHTML(ytp.VIDEO_LIST_CONTAINER_DIV, '');
            ytp.videoPlayerHide();
            ytp.showError('Nothing found');
            //chngS(12);
            return false;
        }
        ytp.itemsCount = p.totalResults;
        ytp.playList = p;
        ytp.nowPlaying = -1;
        updateHTML(ytp.MAIN_TITLE_DIV, "Playlist for: "+ ytp.previousSearchTerm);
        updateHTML(ytp.LIST_COUNT_DIV, "<b>"+p.startIdx+" - "+p.stopIdx+" of "+p.totalResults+"</b>");
        if(p.startIdx == 1 && ytp.doBack == 0){
            //updateHTML(ytp.PL_STATS_DIV, "Playing "+ 0 +" of "+p.totalResults);
            updateHTML(ytp.VIDEO_INFO_DIV, ' ');
        }
        if(p.img.length >0 && ytp.doBack == 0){
            ytp.hideError();
            ytp.showPlayerImage(p.img);
        }
        text = "<ul id=\"sortable1\"  class=\"ui-sortable\"\">";
        getPlaylist();
        for (i = 0; i <  p.items.length; i++) {
        	if (!in_array(p.items[i].videoId, ytp.result_playlist)) {
	            text+= "<li id=\"" +p.items[i].videoId +"\" class=\"ui-state-default\">"+
	            "<span class=\"items_id\">" + p.items[i].itemsID + "</span>" +
	            "<img class=\"img_pointer\"  src=\"" + p.items[i].thumbnailUrl +"\" width=\"40\" height=\"30\" onclick=\"ytp.presentVideo('" +p.items[i].videoId +"','" + p.items[i].itemsID +"')\" />"+
	            "<span class=\"title\">" + p.items[i].title + "</span>" +
	            " <a class=\"move1\" href=\"javascript:void(0);\" > >> </a>" +
	            "</li>";
        	}
        }
        text+="</ul>";
        updateHTML(ytp.VIDEO_LIST_CONTAINER_DIV, text);
        do_sortable();
        do_moveable();
    }

    //display playlist in playlist tab
    if (action == 'loadPlaylist'){
        ytp.itemsCount = p.items.length;
        ytp.playList = p;
        ytp.showPlayerDescription(p.listDescription);
        updateHTML(ytp.MAIN_TITLE_DIV, p.playerTitle);
        updateHTML(ytp.VIDEO_INFO_DIV, " ");
        if(p.img.length >0 ){
            ytp.showPlayerImage(p.img);
        }
        if (ytp.playList.plType == "my") {
            var sorter = ytp.playList.sort.split(',');
            updateHTML(ytp.LIST_COUNT_DIV, "<a href=\"javascript:void(0);\" onclick=\"ytp.sortPlayList('sRank');\">"+sorter[0]+"</a>|"+
                "<a href=\"javascript:void(0);\" onclick=\"ytp.sortPlayList('sTitle');\">"+sorter[1]+"</a>|"+
                "<a href=\"javascript:void(0);\" onclick=\"ytp.sortPlayList('sGroup');\">"+sorter[2]+"</a>");
            //updateHTML(ytp.PL_STATS_DIV, "Playing "+ 0 +" of "+ytp.itemsCount);
        }
        if (ytp.playList.plType == "yt") {
            updateHTML(ytp.LIST_COUNT_DIV, " ");
            if(p.startIdx == 1){
            	//updateHTML(ytp.PL_STATS_DIV, "Playing "+ 0 +" of "+ytp.itemsCount);
            	}
        }
        
//        text = "<table class=\"videoList\"><tbody width=\"270\">";
//        for (i = 0; i < p.items.length; i++) {
//            text+= "<tr width=\"270\">"+
//            "<td>" + p.items[i].itemsID + "</td>"+
//            "<td width=\"40\"> <img class=\"img_pointer\" src=\"" + p.items[i].thumbnailUrl +"\" width=\"40\" height=\"30\" onclick=\"ytp.presentVideo('" +p.items[i].videoId +"','" + p.items[i].itemsID +"')\" /> </td>"+
//            "<td> <a href=\"javascript:void(0);\" onclick=\"ytp.presentVideo('" +p.items[i].videoId +"','" + p.items[i].itemsID +"')\">" + p.items[i].title + (p.plType == 'my' ? ", "+p.items[i].group : "")+"</a> </td>"+
//            "</tr>";       
//        }
//        text+="</table>";
//        updateHTML(ytp.VIDEO_LIST_CONTAINER_DIV, text);
        //--------------------------------------------
        
        text = "<ul id=\"sortable1\"  class=\"ui-sortable\"\">";
        getPlaylist();
        for (i = 0; i <  p.items.length; i++) {
        	if (!in_array(p.items[i].videoId, ytp.result_playlist)) {
	            text+= "<li id=\"" +p.items[i].videoId +"\" class=\"ui-state-default\">"+
	            "<span class=\"items_id\">" + p.items[i].itemsID + "</span>" +
	            "<img class=\"img_pointer\"  src=\"" + p.items[i].thumbnailUrl +"\" width=\"40\" height=\"30\" onclick=\"ytp.presentVideo('" +p.items[i].videoId +"','" + p.items[i].itemsID +"')\" />"+
	            "<span class=\"title\">" + p.items[i].title + "</span>" +
	            " <a class=\"move1\" href=\"javascript:void(0);\" > >> </a>" +
	            "</li>";
        	}
        }
        text+="</ul>";
        updateHTML(ytp.VIDEO_LIST_CONTAINER_DIV, text);
        do_sortable();
        do_moveable();
    }

    //display currently played video information in Playing tab
    if (action == 'presentVideo'){
        var info = "<b>Rank:</b> "+ ytp.playList.items[ytp.nowPlaying].itemsID +" <br />";
        if (ytp.playList.plType == 'my'){
            info += "<b>Title:</b> "+ ytp.playList.items[ytp.nowPlaying].title +" <br />"+
                "<b>Group:</b> "+ ytp.playList.items[ytp.nowPlaying].group +" <br />"+
                "<b>Description:</b> "+ ytp.playList.items[ytp.nowPlaying].description +" <br />";
        } else 
            info += "<b>Title:</b> "+ p.title +" <br />";
        if (ytp.playList.plType == "yt") {
            info += "<b>Description:</b> "+ p.description +" <br />"+
            "<b>Author:</b> "+ p.author +" <br />"+
            "<b>View count:</b> "+ p.viewCount + "<br />"+
            "<b>Rating:</b> "+ p.rating +" <br />"+
            "<b>Category:</b> "+ p.category +" <br />"+
            "<b>Duration Time:</b> "+ p.duration +" sec. <br />";
        }
        updateHTML(ytp.VIDEO_INFO_DIV, info);
    }
    
    //display currently played video information in Playing tab
    if (action == 'savePlaylist'){
        ytp.loadPlaylistCat();
    }
    
}

/**
 * Retrieves Playlist Category with count
**/
//ytp.loadPlaylistCat = function()
//{
//   var params = 'queryType=loadPlaylistCat';
//   var filePath = 'ytplayer.php';
//   ytp.sendRequest(filePath, params, ytp.PUBLIC_PLAYLIST_DIV, 'loadPlaylistCat');
//}

/**
 * Retrieves Title of playlists in selected Category
**/
//ytp.loadTitleCat = function(category){
//    if(ytp.error == 1){
//        ytp.hideError();
//    }
//    var params = 'queryType=loadTitleCat&category='+category;
//    var filePath = 'ytplayer.php';
//    ytp.sendRequest(filePath, params, ytp.PUBLIC_PLAYLIST_DIV, 'loadTitleCat');
//}

/**
 * Retrieves a playlist of videos by URL.
 * @param {String} URL
 */
ytp.loadPlaylist = function(URL)
{
   ytp.reset();
   if(ytp.error == 1){
        ytp.hideError();
    }
   ytp.clearPlayerDescription();
   ytp.hideNavigation();
   ytp.videoPlayerHide();
   updateHTML(ytp.MAIN_TITLE_DIV, '');
   updateHTML(ytp.VIDEO_INFO_DIV, '');
   //updateHTML(ytp.PL_STATS_DIV, "Playing ...");
   updateHTML(ytp.LIST_COUNT_DIV, '');
   //chngS(10);
   ytp.nowDisplayUrl = '?playlist='+URL;
   var params = 'queryType=loadPlaylist&playlist=' + URL;
   var filePath = 'ytplayer.php';
   ytp.sendRequest(filePath, params, ytp.VIDEO_LIST_CONTAINER_DIV, 'loadPlaylist');

};

/**
 * Retrieves a list of videos matching the provided criteria.  The list of
 * videos can be restricted to a particular standard feed or search criteria.
 * @param {String} searchTerm The search term(s) to use for querying as the
 *     'vq' query parameter value
 * @param {Number} page The 1-based page of results to return.
 */
ytp.listVideoSearch = function(searchTerm, page) {
  ytp.doBack = 0;
  ytp.nowDisplayUrl = '#' + searchTerm;
  ytp.previousSearchTerm = searchTerm; 
  var maxResults = ytp.MAX_RESULTS_LIST;
  var startIndex =  (((page - 1) * ytp.MAX_RESULTS_LIST) + 1);
  if (ytp.playList){
      if (startIndex < ytp.playList.startIdx){
            ytp.doBack = 1;
      }
  }
  ytp.presentFeed(maxResults, startIndex, searchTerm);
  ytp.updateNavigation(page);
};


/**
 * Display a YT video for the specified video ID.
 * @param {String} videoId The ID of the YouTube video to show
 * @param {String} itemsId in playlist from 1 to end
 */

ytp.presentVideo = function(videoId, itemsId) {
    if ( ytp.plaerLoad == 1) {
        stop();
        clearVideo();
    }
    if (ytp.clearPlayerDescription()){ }; 
    if(ytp.error == 1){
        ytp.hideError();
    }
    if ( ytp.plaerLoad == 0) {
         initPlaer(videoId);
         if (ytp.rndState != 'off'){
            setTimeout ("play();", 1000);
         }
    } else{
        if (ytp.rndState == 'off'){
            cueNewVideo(videoId, 0);
        } else { loadNewVideo(videoId, 0); }
    }
    ytp.nowPlaying = itemsId-ytp.playList.startIdx;
    //updateHTML(ytp.PL_STATS_DIV, "Playing " +itemsId+" of "+ytp.itemsCount);
    //chngS(11);
    ytp.displayVideoInfo(videoId);
    ytp.videoPlayerShow();
};


/**
 * Retrieves a YT video metadata for the specified video ID.
 * @param {String} videoId The ID of the YouTube video to show
 */
ytp.displayVideoInfo = function(videoId){
    document.getElementById(ytp.VIDEO_INFO_DIV).innerHTML = '<b>Loading...</b>';
    var params = 'queryType=showVideo&videoId=' + videoId;
    var filePath = 'ytplayer.php';
    ytp.sendRequest(filePath, params, ytp.VIDEO_INFO_DIV, 'presentVideo');
}

/**
 * Rewind to next video from playlist)
 */
ytp.autoNextVideo = function(){
    if (ytp.rndState == 'rnd'){
        ytp.nowPlaying = getRandom(ytp.playList.items.length);
    }
    if (ytp.rndState == 'pll'){
        if(ytp.playList.items[(ytp.nowPlaying+1)]){
            ytp.nowPlaying++;
        } else {
            ytp.nowPlaying = 0;
        }
    }
    ytp.autoPresentVideo(ytp.playList.items[ytp.nowPlaying].videoId, ytp.playList.items[ytp.nowPlaying].itemsID);
}

/**
 * Display and play YT video for the specified video ID.
 * @param {String} videoId The ID of the YouTube video to show
 * @param {String} itemsId in playlist
 */
ytp.autoPresentVideo = function(videoId, itemsId) {
    if ( ytp.plaerLoad == 1) {
        stop();
        clearVideo();
    }
    if (ytp.clearPlayerDescription()){ };
    if(ytp.error == 1){
        ytp.hideError();
        ytp.videoPlayerShow();
    }
    if ( ytp.plaerLoad == 0) {
         initPlaer(videoId);
         setTimeout ("play();", 1500);
    } else {
        loadNewVideo(videoId, 0);
    }
    //updateHTML(ytp.PL_STATS_DIV, "Playing " +itemsId+" of "+ytp.itemsCount);
    ytp.displayVideoInfo(videoId);
};

/**
 * Retrieves a list of YT videos.
 * @param {Number} maxResults The maximum number of videos to list
 * @param {Number} startIndex The first video to include in the list
 * @param {String} searchTerm The search terms to pass to the specified feed
 */
ytp.presentFeed = function(maxResults, startIndex, searchTerm){
  var params = 'queryType=getSearch' + //queryType + 
               '&maxResults=' + maxResults +
               '&startIndex=' + startIndex + 
               '&searchTerm=' + searchTerm;
  var filePath = 'ytplayer.php';
  //chngS(10);
  ytp.sendRequest(filePath, params, ytp.VIDEO_LIST_CONTAINER_DIV, 'getSearch');
};

/**
 * Hide Navigation button when they are not needed
 */
ytp.hideNavigation = function() {
    document.getElementById(ytp.NEXT_PAGE_BUTTON).style.display = 'none';
    document.getElementById(ytp.PREVIOUS_PAGE_BUTTON).style.display = 'none';
    updateHTML(ytp.LIST_COUNT_DIV, "");
    }

/**
 * Updates the variables used by the navigation buttons and the 'enabled' 
 * status of the buttons based upon the current page number passed in.
 * @param {Number} page The current page number
 */
ytp.updateNavigation = function(page) {
  ytp.nextPage = page + 1;
  ytp.previousPage = page - 1;
  document.getElementById(ytp.NEXT_PAGE_BUTTON).style.display = 'inline';
  document.getElementById(ytp.PREVIOUS_PAGE_BUTTON).style.display = 'inline';
  if (ytp.previousPage < 1) {
    document.getElementById(ytp.PREVIOUS_PAGE_BUTTON).disabled = true;
  } else {
    document.getElementById(ytp.PREVIOUS_PAGE_BUTTON).disabled = false;
  }
  document.getElementById(ytp.NEXT_PAGE_BUTTON).disabled = false;
};
