/*
 * jQuery based youtubetv plugin
 * http://thinkingbig.net/
 *
 * Copyright (c) 2009 Thinking Big Information Technology Inc.
 * Written by: Ron Myers
 * This code is for use on its intended target site outlined by creators.
 * If you are interested in usage of this plug-in please contact: info@thinkingbig.net
 *
 * Date: 2009-06-17 
 * Revision: 27
 */
(function($)
{  
  $.fn.youtubetv = function(playerIDP, listIDP, optionsP) 
  {  
	var default_options = { 
	  search_type: 'users',
	  search_value: '', 
	  max_results: 100,
	  thumb_width: 70,
	  thumb_height: 52,
	  videoplayer_width: 290,
	  videoplayer_height: 290,
	  num_title_chars_to_show: 20,
	  autoplay: true,
	  video_title_class: 'titlec',
	  list_hover_class: 'video-list-hover',
	  list_selected_class: 'video-list-selected'
	};
	
	var options = $.extend(default_options, optionsP);
	var playerID = playerIDP;
	var listID = listIDP;
	
	var youtube_url = "http://gdata.youtube.com/feeds/"+options.search_type+"/"+options.search_value+"/uploads/?alt=json-in-script&max-results="+options.max_results;
    
	$.get(youtube_url, null,
      function (result) {
		
    	var feed = result.feed;
    	var entries = feed.entry || [];
    	var html = ['<ul class="videos">'];
    	for(var i = 0; i < entries.length; i++)
    	{
    	  var entry = entries[i];
    	  var title = entry.title.$t.substr(0,options.num_title_chars_to_show);
    	  var thumb_url = entry.media$group.media$thumbnail[0].url;
    	  var video_url = entry.media$group.media$content[0].url;
    	  html.push(
    	    '<li id="',video_url,'">',
            '<img src="',thumb_url, '" width="',options.thumb_width,'" height="',options.thumb_height,'" align="left"/><span class="',options.video_title_class,'">', title, '...</span>', '</li>');
    	}
    	
    	html.push('</ul>');
    	$('#'+listID).append(html.join(''));
    	
    	if (entries.length == 0)
    	  $('#'+listID).append('<p>No videos available</p>');
    	    	
    	// video click
    	$('ul.videos li').click(function(e){
    	  $('ul.videos li').removeClass(options.list_selected_class);
    	  $(this).addClass(options.list_selected_class);
    	  
    	  var url = $(this).attr('id') + '&rel=1&border=0&fs=1&autoplay=1';
		  $('#'+playerID).flash({
		    // test.swf is the flash document
  		    swf: url,
		    height: options.videoplayer_height,
			width: options.videoplayer_width
	      });
    	});
    	    	
    	// add hover if assigned
    	if (options.list_hover_class != '')
    	{
    	  $('ul.videos li').hover(
    	    function(){ $(this).addClass(options.list_hover_class); }, 
    	    function(){ $(this).removeClass(options.list_hover_class); }
    	  );
    	}

    	// load the first one if we got one.
    	$('ul.videos li:first').click()
    	
    	
      }, 'jsonp');
  };  
})(jQuery);
