var ytvbp = {};

ytvbp.LOCATION = '';

/**
 * maximum number of results to return for list of videos
 * @type Number
 */
ytvbp.MAX_RESULTS_LIST = 5;

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

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

/** 
 * container div id used to hold the details of the hovered over item
 * @type String
 */
ytvbp.DETAILS_CONTAINER_DIV = 'utubeDetails';

ytvbp.YOUTUBECONTAINER = 'utubeContainer';

/**
 * 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} queryType The type of query to be done - either 'all'
 *     for querying all videos, or the name of a standard feed.
 * @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.
 */
ytvbp.listVideos = function(queryType, searchTerm, page) {
    
  //ytvbp.previousSearchTerm = searchTerm; 
  ytvbp.previousQueryType = queryType; 
  var maxResults = ytvbp.MAX_RESULTS_LIST;
  var startIndex =  (((page - 1) * ytvbp.MAX_RESULTS_LIST) + 1);
  ytvbp.presentFeed(queryType, maxResults, startIndex, searchTerm);
  
  //ytvbp.updateNavigation(page);
};

/**
 * Sends an AJAX request to the server to retrieve a list of videos or
 * the video player/metadata.  Sends the request to the specified filePath
 * on the same host, passing the specified params, and filling the specified
 * resultDivName with the resutls upon success.
 * @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
 */
ytvbp.sendRequest = function(filePath, params, resultDivName) {
    
  if (window.XMLHttpRequest) {
    var xmlhr = new XMLHttpRequest();
  } else {
    var xmlhr = new ActiveXObject('MSXML2.XMLHTTP.3.0');
  }
        
  xmlhr.open('POST', filePath, true);
  xmlhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 

  xmlhr.onreadystatechange = function() {
    var resultDiv = document.getElementById(resultDivName);
    if (xmlhr.readyState == 1) {
      resultDiv.innerHTML = '<b>&nbsp;&nbsp;<img src="'+ytvbp.HOST+'images/loadercircles.gif" style="border:0px;">&nbsp;&nbsp;Loading...</b>'; 
    } else if (xmlhr.readyState == 4 /*&& xmlhr.status == 200*/) {
      if (xmlhr.responseText) {
        var rstring = xmlhr.responseText;
        
        if(rstring=="<h3>No videos found.</h3>")
        {
            document.getElementById(ytvbp.YOUTUBECONTAINER).style.display = 'none';
        }
        
        resultDiv.innerHTML = rstring;     
        
      }
    } else if (xmlhr.readyState == 4) {
      //alert('Invalid response received - Status: ' + xmlhr.status);
      document.getElementById(ytvbp.YOUTUBECONTAINER).style.display = 'none';
    }
  } 
  xmlhr.send(params);
}

/**
 * Uses ytvbp.sendRequest to display a YT video player and metadata for the
 * specified video ID.
 * @param {String} videoId The ID of the YouTube video to show
 */
ytvbp.presentVideo = function(videoId) {
  var params = 'queryType=show_video&videoId=' + videoId;
  var filePath = ytvbp.LOCATION;
  ytvbp.sendRequest(filePath, params, ytvbp.VIDEO_PLAYER_DIV);

}

/**
 * Uses ytvbp.sendRequest to display a list of of YT videos.
 * @param {String} queryType The name of a standard video feed or 'all'
 * @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
 */
ytvbp.presentFeed = function(queryType, maxResults, startIndex, searchTerm){
  var params = 'queryType=' + queryType + 
               '&maxResults=' + maxResults +
               '&startIndex=' + startIndex + 
               '&searchTerm=' + searchTerm

  var filePath = ytvbp.LOCATION;
  //var filePath = '../../../../includes/utubebrowser/index.php';
  ytvbp.sendRequest(filePath, params, ytvbp.VIDEO_LIST_CONTAINER_DIV);
  
}

ytvbp.showInfo = function(tip)
{
    tt = document.getElementById(ytvbp.DETAILS_CONTAINER_DIV);
    tt.innerHTML = base64_decode(tip);


}

ytvbp.exit = function() {
    tt = document.getElementById(ytvbp.DETAILS_CONTAINER_DIV);
    tt.innerHTML = '';
 
}


function base64_decode( data ) {
    // Decodes data encoded with MIME base64
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_base64_decode/
    // +       version: 805.821
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Thunder.m
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)    
    // -    depends on: utf8_decode
    // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
    // *     returns 1: 'Kevin van Zonneveld'
    
    // mozilla has this native 
    // - but breaks in 2.0.0.12!
    //if (typeof window['btoa'] == 'function') {
    //    return btoa(data);
    //}
    
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = ac = 0, dec = "", tmp_arr = [];

    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1<<18 | h2<<12 | h3<<6 | h4;

        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);
    
    dec = tmp_arr.join('');
    //dec = utf8_decode(dec);
    
    return dec;
}

