/**
 *  Plugin which renders the YouTube channel videos list to the page
 *  @author:  H. Yankov (hristo.yankov at gmail dot com)
 *  @version: 1.0.0 (Nov/27/2009)
 *	http://yankov.us
 */

 var __mainDiv;
 var __preLoaderHTML;
 var __opts;
 
 (function($){

	$.fn.shuffle = function() {
		return this.each(function(){
			var items = $(this).children().clone(true);
			return (items.length) ? $(this).html($.shuffle(items)) : this;
		});
	}
	
	$.shuffle = function(arr) {
		for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
		return arr;
	}
	
})(jQuery);
 
 
 
 function __jQueryYouTubeChannelReceiveData(data) {
	$.each(data.feed.entry, function(i,e) {
		__mainDiv.append(e.content.$t);
	});
	
	// Mark the first div in the list
	$(__mainDiv).find("div:first").addClass("firstVideo");
	
	// Now hide objects depending on the settings and fix the img style
	$(__mainDiv).find("div").each(function () {
	
		var img = jQuery(this).find("table > tbody > tr:first > td:eq(0) > div ").html();
		var title= jQuery(this).find("table > tbody > tr:first > td:eq(1) > div > a").html();

		
		tmp = jQuery(this).find("table > tbody > tr:first > td:eq(1) > div > a").text();
		title2 = tmp.substring(tmp.indexOf(' - ')+3,tmp.length);

	
		$(this).html(img);
		$(this).find("a").append("<br/>"+title2);
		$(this).hide();
		$(this).width("260px");
		$(this).addClass("video");
				
		//$(this).find("a").attr("rel","prettyPhoto");
		$(this).find("a").prettyPhoto()
		$(this).find("a").attr("title",title);
	
	});
	
	
	 $(__mainDiv).shuffle();
	
	
	$(__mainDiv).find("div").slice(0,3).show();
	
	// Remove the preloader and show the content
	$(__preLoaderHTML).remove();
	__mainDiv.show();
}





				
(function($) {
$.fn.youTubeChannel = function(options) {
	var videoDiv = $(this);

	$.fn.youTubeChannel.defaults = {
		userName: null,
		loadingText: "Loading...",
		linksInNewWindow: true,
		hideVideoLength: false,
		hideFrom: true,
		hideViews: false,
		hideRating: false,
		hideNumberOfRatings: true,
		removeBordersFromImage: true
	}
			
    __opts = $.extend({}, $.fn.youTubeChannel.defaults, options);
	
	return this.each(function() {
		if (__opts.userName != null) {			
			videoDiv.append("<div id=\"channel_div\"></div>");
			__mainDiv = $("#channel_div");
			__mainDiv.hide();
			
			__preLoaderHTML = $("<p class=\"loader\">" + __opts.loadingText + "</p>");
			videoDiv.append(__preLoaderHTML);
			
			// TODO: Error handling!
			//$.getScript("http://gdata.youtube.com/feeds/base/users/" + __opts.userName + "/uploads?alt=json-in-script&callback=__jQueryYouTubeChannelReceiveData");
			$.getScript("http://gdata.youtube.com/feeds/base/playlists/4534E1BF3453472A?alt=json-in-script&callback=__jQueryYouTubeChannelReceiveData");
		}
	});
};
})(jQuery);
