/* Copyright (c) 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Provides functions for browsing and searching YouTube 
 * data API feeds, as a sample for how to interact with the JSON output
 * from the API. 
 * @author api.rboyd@google.com (Ryan Boyd)
 * @author edited by tlogan@gmail.com (Thomas Logan)
 */


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

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

ytvb.SONG_LIST = 'listTracks';


ytvb.FLASH_MIME_TYPE = 'application/x-shockwave-flash';


/** 
 * the URL to use for the standard YouTube video feed
 * @type String
 */
//ytvb.VIDEO_FEED_URL = 
//    'http://gdata.youtube.com/feeds/videos';
ytvb.VIDEO_FEED_URL = 
    'http://gdata.youtube.com/feeds/api/videos';

/**
 * map of URLs used for the different types of feeds to query
 * @type Object
 */
ytvb.QUERY_URL_MAP = {
  'top_rated' : ytvb.STANDARD_FEED_URL_TOP_RATED,
  'most_viewed' : ytvb.STANDARD_FEED_URL_MOST_VIEWED,
  'recently_featured' : ytvb.STANDARD_FEED_URL_RECENTLY_FEATURED,
  'all' : ytvb.VIDEO_FEED_URL
};



/**
 * the internal string used to represent the type of the feed
 * for which an index is a reference to - this is for references
 * to videos in the main list of videos displayed in the app
 * @type String
 */
ytvb.REFERRING_FEED_TYPE_MAIN = 'main';



/**
 * the JSON feed for the list of search results - stored for debugging 
 * purposes and to access data in the future based upon the index value
 * of the entry in the feed
 * @type {Object|Null}
 */
ytvb.jsonFeed_ = null;



/**
 * Creates a script tag for retrieving a Google data JSON feed and and
 * adds it into the html head. 
 * @param {String} scriptSrc The URL for the script, assumed to already have at
 *     least one query parameter, so the '?' is not added to the URL
 * @param {String} scriptId The id to use for the script tag added to the head
 * @param {String} scriptCallback  The callback function to be used after the 
 *     JSON is retrieved.  The JSON is passed as the first argument to the 
 *     callback function.
 */
ytvb.appendScriptTag = function(scriptSrc, scriptId, scriptCallback) {
  // Remove any old existance of a script tag by the same name
  var oldScriptTag = document.getElementById(scriptId);
  if (oldScriptTag) {
    oldScriptTag.parentNode.removeChild(oldScriptTag);
  }
  // Create new script tag
  var script = document.createElement('script');
  script.setAttribute('src', 
      scriptSrc + '&alt=json-in-script&callback=' + scriptCallback);
  script.setAttribute('id', scriptId);
  script.setAttribute('type', 'text/javascript');
  // Append the script tag to the head to retrieve a JSON feed of videos
  // NOTE: This requires that a head tag already exists in the DOM at the
  // time this function is executed.
  document.getElementsByTagName('head')[0].appendChild(script);
};


/**
 * Given the JSON representing an entry, finds the media:content element with
 * a 'type' attribute of the specified value.
 * @param {Object} entry The evaluated JSON data representing an entry/video
 * @param {String} type The MIME type to find amongst the 
 *     media:content elements
 * @return {String|Null} The URL (href) value int he found atom:link or null
 */
ytvb.findMediaContentHref = function(entry, type) {
  for (var i = 0, content; content = entry.media$group.media$content[i]; i++) {
    if (content.type == type) {
      return content.url;
    }
  }
  // a media:content element with the specified MIME type was not found
  return null;
};

/**
 * Retrieves a list of videos matching the provided criteria.  The list of
 * videos can be restricted to a particular standard feed or search criteria.
 *
 * Please see the following URL for more info on the different standard feeds
 * in the <a href="http://code.google.com/apis/youtube/reference.html#Feeds">
 * Reference Guide</a>
 * @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.
 */

//TLO CHANGE
//ytvb.listVideos = function(queryType, searchTerm, page) {
ytvb.listVideos = function(queryType, searchTerm) {
  var queryUrl = ytvb.QUERY_URL_MAP[queryType];
  if (queryUrl) {
    if (searchTerm != '') {
      queryUrl += '?q=' + searchTerm;

	  queryUrl += '&max-results=' + ytvb.MAX_RESULTS_LIST;
	  queryUrl += '&orderby=relevance';
	  queryUrl += '&v=1';

    }
	
// Deletes and re-adds the results table from container
  // NOTE: Any other elements added to the container will also be cleared
	  if (tracks.GetItemCount() > 0) 
	  {
		tracks.RemoveAllItems();
  	}
  
    ytvb.appendScriptTag(queryUrl, 
                         'searchResultsVideoListScript', 
                         'ytvb.listVideosCallback');

  } else {
    alert('Unknown feed type specified');
  }
};

/**
 * Callback function used for processing the results of ytvb.listVideos.
 * This function calls appendVideoData to list each of the videos in the UI
 * @param {Object} data The object obtained by evaluating the JSON text 
 *     returned by the YouTube data API
 */
ytvb.listVideosCallback = function(data) 
{
  // Stores the json data returned for later lookup by entry index value

  ytvb.jsonFeed_ = data.feed;
//  var songList = document.getElementById(
//      ytvb.SONG_LIST);


  

  // Loops through entries in the feed and calls appendVideoData for each
  for (var i = 0, entry; entry = data.feed.entry[i]; i++) 
  {
    // The entry.yt$noembed property will exist if this YouTube video does
    // not support viewing in an embedded player on a third-party site.  
    // Exclude these videos from listing here.  A feature request has been
    // submitted for an additional query parameter to exclude these results
    // from the initial results feed.

  if (! entry.yt$noembed) 
  {
     ytvb.appendVideoData(entry, i);
  }
  
  }
  
  //TODO examine
  if(UseKeyboard)
  {
appCommands.FocusTrack();
  }
};


ytvb.appendVideoData = function(entry, entryIndex) 
{
    appCommands.AddTrack(entry.title.$t,entry.id.$t);
};

/*
POST /feeds/api/users/default/playlists HTTP/1.1
Host: gdata.youtube.com
Content-Type: application/atom+xml
Content-Length: CONTENT_LENGTH
Authorization: AuthSub token="AUTHORIZATION_TOKEN"
GData-Version: 2
X-GData-Client: CLIENT_ID
X-GData-Key: key=DEVELOPER_KEY

<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
    xmlns:yt="http://gdata.youtube.com/schemas/2007">
  <title type="text">Sports Highlights Playlist</title>
  <summary>A selection of sports highlights</summary>
</entry>



POST /feeds/api/playlists/PLAYLIST_ID HTTP/1.1
Host: gdata.youtube.com
Content-Type: application/atom+xml
Content-Length: CONTENT_LENGTH
Authorization: AuthSub token="AUTHORIZATION_TOKEN"
GData-Version: 2
X-GData-Client: CLIENT_ID
X-GData-Key: key=DEVELOPER_KEY

<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
    xmlns:yt="http://gdata.youtube.com/schemas/2007">
  <id>VIDEO_ID</id>
  <title type="text">Optional custom video title</title>
  <summary>Optional custom video description</summary>
</entry>
*/
