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

ytvb.MAX_RESULTS_LIST = 50; //maximum number of results to return for list of videos

ytvb.VIDEO_LIST_TABLE = 'searchResultsVideoListTable'; //table id used to display list of videos

ytvb.VIDEO_LIST_TABLE_CONTAINER_DIV = 'searchResultsVideoList'; //container div id used to hold table for list of videos

ytvb.VIDEO_PLAYER_DIV = 'videoPlayer'; //container div id used to hold the video player

ytvb.FLASH_MIME_TYPE = 'application/x-shockwave-flash'; //the MIME type used for flash videos, needed to find the appropriate media:content link to use

ytvb.jsonFeed_ = null; //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.jsonFeedRelated_ = null; //the JSON feed for the list of related video 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.jsonFeedUser_ = null; //the JSON feed for the list of videos by the author of the currently playing video - 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}

/**
 * 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) {
  var script = document.createElement('script');
  script.setAttribute('src', 
      scriptSrc + scriptCallback);
  script.setAttribute('id', scriptId);
  script.setAttribute('type', 'text/javascript');
  document.getElementsByTagName('head')[0].appendChild(script);
};


/**
 * 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.
 */
ytvb.listVideos = function(queryType, searchTerm, page) {
  var queryUrl = 'http://gdata.youtube.com/feeds/videos?max-results=' + ytvb.MAX_RESULTS_LIST + '&start-index=1&author=' + searchTerm;

  ytvb.appendScriptTag(queryUrl, 'searchResultsVideoListScript',  '&alt=json-in-script&callback=ytvb.listVideosCallback');

};

/**
 * 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 resultsTableContainer = document.getElementById(
      ytvb.VIDEO_LIST_TABLE_CONTAINER_DIV);

  // Deletes and re-adds the results table from container
  // NOTE: Any other elements added to the container will also be cleared
  while (resultsTableContainer.childNodes.length >= 1) {
    resultsTableContainer.removeChild(resultsTableContainer.firstChild);
  }

  var resultsTable = document.createElement('form');
  var tr= document.createElement('div');

  resultsTableContainer.appendChild(resultsTable);

  // 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 (lceValues.inArray(entry.id.$t)){
		if (! entry.yt$noembed) {
		  ytvb.appendVideoDataToTable(tr, entry, i);
		}
	
	}
  
  }

  resultsTable.appendChild(tr);
  tb_init('a#ythumb');
};


/**
 * 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;
};
 
 
/**
 * Returns a function that can be added as an event handler for playing
 * a video upon the firing of the event.
 * @param {String} videoUrl The URL of the video to play
 * @param {Number} entryIndex The index of the entry in the referring feed
 * @return {Function} The video playing function
 */
ytvb.generatePlayVideoLinkOnclick = function(videoUrl, entryIndex) {
  return function() {
    ytvb.playVideo(entryIndex);
    return false;
  };
};


/** function to check in array */
Array.prototype.inArray = function (value) {
  var i;
  for (i=0; i < this.length; i++) {
    if (this[i] === value) {
    return true;
    }
  }
  return false;
};


/**
 * Adds the HTML representation of the passed video entry to the 
 * table (tbody) element bassed.
 * @param {Node} tbody The table tbody node.  tbody is needed due to IE, as IE
 *     doesn't allow direct adding of rows to a table.
 * @param {Object} entry The JSON-encoded video entry to display in the table
 * @param {Number} entryIndex The index of the video in the JSON feed's
 *     entries.  This is needed to pass to the code which generates a video
 *     player when an onclick event is fired.
 */

  ytvb.appendVideoDataToTable = function(tr, entry, entryIndex) {
  var td = document.createElement('span');

  var a = document.createElement('a');
  a.setAttribute('href', '#TB_inline?height=350&width=400&inlineId=videoPlayer');
  a.setAttribute('id', 'ythumb');
  a.className= 'thickbox';
  
  var img = document.createElement('img');

  img.className= 'thumbVIDEO';

  img.setAttribute('src', 
      entry.media$group.media$thumbnail[0].url);

  img.onclick = ytvb.generatePlayVideoLinkOnclick(entry.id.$t, entryIndex);
 	 
	 
  a.appendChild(img);
  td.appendChild(a);
  tr.appendChild(td);
  
};


//**************************************************************************************************************
/**
 * Adds the object and embed tags to play the specified video
 * @param {Number} entryIndex The index of the video in the referring feed
*/
ytvb.playVideo = function(entryIndex) {
  var entry;
  try {
      entry = ytvb.jsonFeed_.entry[entryIndex];
  
    var videoHref = ytvb.findMediaContentHref(entry, ytvb.FLASH_MIME_TYPE);
    var videoPlayerDiv = document.getElementById(ytvb.VIDEO_PLAYER_DIV);
    var html = [];
    html.push('<b>');
	html.push(entry.media$group.media$title.$t);
    html.push('</b><br />');
    html.push('<object width="400" height="325"><param name="movie" value="');
    html.push(videoHref);

    html.push('&autoplay=1"></param><param name="wmode" value="transparent">');
    html.push('</param><embed src="');
    html.push(videoHref);
    html.push('&autoplay=1" type="application/x-shockwave-flash" ');
    html.push('wmode="transparent" width="400" height="325"></embed></object>');
//	html.push('<h2>'+videoHref+'</h2>');
//	html.push('<h2>'+entry.media$group.media$title.$t+'</h2>');
    videoPlayerDiv.innerHTML = html.join('');
  } catch (err) {
    alert(err);
  }
};

var my_id = "outer_most_containing_div_for_the_page";


