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


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 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 = 'videoInfo';

/**
 * 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;




ytp.reset = function(){
    ytp.initRnd();
    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\" onclick=\"ytp.presentVideo('" +tmpList[i].videoId +"','" +(i+1)+"')\">"+
            "<td>" +tmpList[i].rank+ "</td>"+
            "<td width=\"40\"> <img src=\"" + tmpList[i].thumbnailUrl +"\" width=\"40\" height=\"30\" /> </td>"+
            "<td> <a href=\"javascript:void(0);\">" + 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 }; 

    //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 = "<table class=\"videoList\"><tbody width=\"270\">";
        for (i = 0; i <  p.items.length; i++) {
            text+= "<tr width=\"270\" onclick=\"ytp.presentVideo('" +p.items[i].videoId +"','" + p.items[i].itemsID +"')\">"+
            "<td>" + p.items[i].itemsID + "</td>"+
            "<td width=\"40\"> <img src=\"" + p.items[i].thumbnailUrl +"\" width=\"40\" height=\"30\" /> </td>"+
            "<td> <a href=\"javascript:void(0);\">" + p.items[i].title + "</a> </td>"+
            "</tr>";
        }
        text+="</table>";
        updateHTML(ytp.VIDEO_LIST_CONTAINER_DIV, text);
    }

    //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\" onclick=\"ytp.presentVideo('" +p.items[i].videoId +"','" + p.items[i].itemsID +"')\">"+
            "<td>" + p.items[i].itemsID + "</td>"+
            "<td width=\"40\"> <img src=\"" + p.items[i].thumbnailUrl +"\" width=\"40\" height=\"30\" /> </td>"+
            "<td> <a href=\"javascript:void(0);\">" + p.items[i].title + (p.plType == 'my' ? ", "+p.items[i].group : "")+"</a> </td>"+
            "</tr>";       
        }
        text+="</table>";
        updateHTML(ytp.VIDEO_LIST_CONTAINER_DIV, text);
    }

    //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;
};

