(function($) {
	var $options = null;
	var $this = null;
	$.fn.youtube = function(options){
		$this = $(this);
		// extend our default options with those provided
		$options = $.extend({}, $.fn.youtube.defaults, options);
		
		return this.each(function(){  
			var url = $.youtube.getURL();
			$.youtube.request(url);
		})
	};
	
	// default option
	$.fn.youtube.defaults = {
		callback			: null,
		api_key				: null,
		url					: null,
		
		type				: null,		// allowed values: 'playlist', 'search','user'
		keyword				: null,		// A search query term. Searches for the specified string in all video metadata, such as titles, tags, and descriptions.
		users				: null,		// videos uploaded by a specific user
		alt					: null,		// The format of feed to return, such as atom (the default), rss, or json.
		orderby				: null,		// The order in which to list entries, such as relevance (the default for the videos feed) or viewCount.
		start_index			: null,		// The 1-based index of the first result to be retrieved (for paging). 
		max_results			: 10,		// The maximum number of entries to return at one time
		categories			: null,		// The categories and/or tags to use in filtering the feed results. 
										// For example, feedURL/-/fritz/laurie returns all entries 
										// that are tagged with both of the user-defined tags fritz and laurie.
				
		most_viewed			: null,
		top_rated			: null,
		recently_featured	: null,
		top_favorites		: null,
		most_discussed		: null,
		most_linked			: null,
		most_responded		: null,
		recently_featured	: null,
		playlist_id			: null,		// playlists feed contains a list of public playlists defined by a user.
		
		cleanReturn			: 1,		// do you want a full youtube return, or just an image list
		inlineVideo			: 1			// do you want to redirect to youtube, or play inlinevideo
	};
	
	$.youtube = {
		$options: null,
		getURL : function(){
			var query = "";
			
			if ($options.url) return $options.url;
			if (!$options.alt) $options.alt = 'json-in-script';
        	if (!$options.callback) $options.callback = 'jQuery.youtube.response';
		
			query = 'http://gdata.youtube.com/feeds/api/';
			
			switch ($options.type){
				case 'users' : query += 'users/' + $options.users + '/uploads?v=2&alt=' + $options.alt + '&callback=' + $options.callback; break;
				case 'search' : query  += 'videos?v=2&alt=' + $options.alt + '&callback=' + $options.callback; break;
				case 'playlist' : query += 'playlists/'; break;
				default : query = 'http://gdata.youtube.com/feeds/api/videos';
			};
			
			if ($options.keyword) query += '&q=' + encodeURIComponent($options.keyword);
			if ($options.start_index) query += '&start-index=' + $options.start_index;
			if ($options.max_results) query += '&max-results='+ $options.max_results;
			
			return query;
		},
		request: function(url){
			var script = document.createElement('script');
			script.type = 'text/javascript';
			script.src = url;
			$('head',document).append(script);
		},
		response: function(json){		
			if(json.feed.entry){
				var aVideos = [];
				$.each(json.feed.entry, function(i, item){
					//alert(item.media$group);
					var title = '<b>'+item.media$group.media$title.$t+'</b>';
					var meta = '<cite class="bkgd">&nbsp;</cite><cite class="text">'+$.youtube.formatTime(item.media$group.yt$duration.seconds)+'</cite>';
					var img = '<img src="images/blank.gif" width="122" height="74" border="0" alt="" style="background:url('+item.media$group.media$thumbnail[2].url+') center center" />';
					//var id = item.media$group.yt$videoid.$t +':'+item.media$group.media$thumbnail[4].width+'x'+item.media$group.media$thumbnail[4].height;
					var id = item.media$group.yt$videoid.$t +':'+640+'x'+356;
					var videoURL;
					if (typeof(item.media$group.media$content) != 'undefined'){
						videoURL = item.media$group.media$content[0].url;
					}
					if (videoURL){
						aVideos[aVideos.length] = '<li><a href="#YouTubeEmbed" class="#YouTubeEmbed" rel="'+videoURL+'" id="'+id+'">'+img+meta+'</a>'+title+'</li>';
					} else {
						aVideos[aVideos.length] = '<!-- <li><a href="#YouTubeEmbed" class="#YouTubeEmbed" id="'+id+'">'+img+meta+'</a>'+title+'</li> -->';
					}
				});
				$options.container.html('<ul>'+aVideos.toString().split(",").join('')+'</ul>');
				$.youtube.enableFancyZoom();
				$this.show();
				$this.carousel();
			} else {
				$this.remove();
			};
		},
		enableFancyZoom: function(){
			$options.container.find('a').click(function(e){
				var size = $(this).attr('id').split(':')[1].split('x');
				var src = $(this).attr('rel');
				$('#YouTubeEmbed').css({'width':size[0]+'px','height':size[1]+'px'}).html($.youtube.injectEmbedCode(size[0],size[1],src));
				return false;
			}).fancyZoom({directory:'images/fancyzoom'});
		},
		injectEmbedCode: function(width,height,src){
			var oeYouTube = '<object type="application/x-shockwave-flash" id="youTubeVideo" width="' + width + '" height="' + height + '" data="' + src + '">' +
				'<param name="movie" value="' + src + '" />' + 
				'<param name="quality" value="high" />' +
				'<param name="bgcolor" value="#000000" />' +
				'<param name="wmode" value="transparent" />' +
				'<param name="allowScriptAccess" value="sameDomain" /></object>';
			return oeYouTube;
		},
		formatTime: function(secs){
			var totalSecs = secs;
			var tSeconds = Math.floor(totalSecs % 60);
			var tMinutes = Math.floor(totalSecs / 60);
			return (!isNaN(totalSecs))? tMinutes +":"+ $.youtube.pad(tSeconds,2) : "0:00";
		},
		pad: function(num,pad){
			 while(num.toString().length < pad) num = '0' + num;
			 return num;
		}
	};
})(jQuery);

jQuery(function($){
	$('#YouTubeFeed').youtube({
		type: 'users',
		users: 'lpgavideo',
		max_results: 9,
		keyword: $('span.player-name',this).text().toLowerCase()+' '+ytgup( 'id' ),
		container: $('div.carousel-thumbs',this)
	});
});

function ytgup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
