/** 
*	YT Fetch 0.1
*	By CosmicSpork
*
*	Requires JQuery and Facebox
**/

var YTFetch = {
	StartIndex: 1,
	PageSize: 10,
	TotalRecords: 0,
	AccName: null,
	Type: null,
	Data: null,	
	ItemsPerRow: 5,
	OrderBy: "published",
	YTBBCode: "[YouTube]{0}[/YouTube]",
	SearchTerm: null,
	
	GetVideos: function(accName, type, startIndex, searchTerm) {	
		this.StartIndex = startIndex;
		
		if(this.StartIndex == null)
			this.StartIndex = 1;
		
		if(searchTerm != null)
			this.SearchTerm = searchTerm;
		
		this.AccName = accName;
		this.Type = type;
			
		var url = "http://gdata.youtube.com/feeds/api/users/" + this.AccName + "/" + this.Type;
		
		var parameters = '?orderby=' + this.OrderBy + '&max-results=' + this.PageSize + '&start-index=' + this.StartIndex;
		if(this.SearchTerm) {
			parameters += "&q=" + this.SearchTerm;
		}
		parameters += '&alt=json-in-script&callback=YTFetch.OnDataReceived&=?'
		
		if($("#YTFetch:visible").length == 0) {
			jQuery.facebox('<div id="YTFetch"><div class="Info"></div><div class="Search">Search: <input type="text" class="Input" /><a href="#" class="SearchBtn">Go</a><a href="#" class="ClearBtn">X</a></div><div class="Tabs"><span class="Tab Uploads">Uploads</span><span class="Tab Favorites">Favorites</span></div><div class="Content" style="display:none"><div class="Inner"></div></div><div class="Loader"></div><div class="Pager"></div></div>');
			$("#YTFetch .Tabs .Uploads").click(function() {
				YTFetch.GetVideos(YTFetch.AccName, "uploads", 1, '');
			});
			$("#YTFetch .Tabs .Favorites").click(function() {
				YTFetch.GetVideos(YTFetch.AccName, "favorites", 1, '');
			});
			$("#YTFetch .Search .SearchBtn").click(function() {
				var term = $("#YTFetch .Search .Input").val();
				YTFetch.GetVideos(YTFetch.AccName, YTFetch.Type, YTFetch.StartIndex, term);
				return false;	
			});
			$("#YTFetch .Search .ClearBtn").click(function() {
				YTFetch.GetVideos(YTFetch.AccName, YTFetch.Type, 1, '');
				return false;	
			});
		}
		
		$("#YTFetch .Tabs .Tab").removeClass("Tab-Selected");
		$("#YTFetch .Search .Input").val(this.SearchTerm);
		
		switch(type) {
			case "uploads":
				$("#YTFetch .Tabs .Uploads").addClass("Tab-Selected");
			break;
			
			case "favorites":
				$("#YTFetch .Tabs .Favorites").addClass("Tab-Selected");
				$("#YTFetch .Search").hide();
			break;
		}
		
		$("#YTFetch .Info").text("---");
		$("#YTFetch .Pager").text("-----");
		$("#YTFetch .Loader").show();
		$("#YTFetch .Content").hide();
		$("#YTFetch .Search .ClearBtn").hide();

		jQuery.getJSON(url + parameters);
	},
	
	OnDataReceived: function(data) {
		if(!data) {
			this.OnDataError();
		} else {		
		YTFetch.TotalRecords = parseInt(data.feed.openSearch$totalResults.$t);
		YTFetch.Data = data;
		
		$("#YTFetch .Search").hide();
		
		if(this.Type == "uploads" && this.TotalRecords > this.PageSize || this.SearchTerm)
			$("#YTFetch .Search").show();
			
		if(this.SearchTerm)
			$("#YTFetch .Search .ClearBtn").show();
		
		var recordsLength = data.feed.entry != undefined ? data.feed.entry.length : 0;

		$("#YTFetch .Loader").hide();
		$("#YTFetch .Content").show();
		$("#YTFetch .Info").html("Total Videos: " + YTFetch.TotalRecords);
		
		if(YTFetch.TotalRecords > 0) {
			var prevBtn = document.createElement("span");
			var nextBtn = document.createElement("span");
			$(prevBtn).html("Prev").addClass("Prev").addClass("Disabled");
			$(nextBtn).html("Next").addClass("Next").addClass("Disabled");
			
			$("#YTFetch .Pager").html("<span class=\"Detail\">Videos " + this.StartIndex + " to " + Math.abs(this.StartIndex + recordsLength - 1) + "</span>");
				
			if((this.StartIndex - this.PageSize) >= 1) {
				$(prevBtn).removeClass("Disabled").click(function() {
					YTFetch.GetVideos(YTFetch.AccName, YTFetch.Type, YTFetch.StartIndex - YTFetch.PageSize);
				});	
			}
				
			if((this.StartIndex + this.PageSize) <= this.TotalRecords) {
				$(nextBtn).removeClass("Disabled").click(function() {
					YTFetch.GetVideos(YTFetch.AccName, YTFetch.Type, YTFetch.StartIndex + YTFetch.PageSize);
				});	
			}
			
			$("#YTFetch .Pager").prepend(nextBtn).prepend(prevBtn);
		} else
			$("#YTFetch .Pager").html("-----");
		}
		
		this.GenerateContent();
	},
	
	OnDataError: function() {
		$("#YTFetch .Loader").hide();
		$("#YTFetch .Content").show();
		$("#YTFetch .Content .Inner").html("An Error Has Occurred. The user you specified might not exist.");
	},
	
	GenerateContent: function() {
		if(this.TotalRecords > 0) {
			var table = document.createElement("table");
			table.cellPadding = 0;
			table.cellSpacing = 0;
			$(table).addClass("VideoTable");
			var entries = this.Data.feed.entry;
			var numRows = entries.length / this.ItemsPerRow;
			var curEntryIndex = 0;
			for(var r = 0; r < numRows; r++) {
				var row = document.createElement("tr");
				$(row).addClass("VideoRow");
				for(var c = 0; c < this.ItemsPerRow; c++) {
					if(entries[curEntryIndex] == undefined)
						break;
					
					var entry = entries[curEntryIndex];
					var entryBox = this.GenerateVideoBox(entry);
					var cell = document.createElement("td");
					$(cell).addClass("VideoCell").hover(function() {
						$(this).addClass("VideoCell-Hover");
					},
					function() {
						$(this).removeClass("VideoCell-Hover");
					}).append(entryBox);					
					curEntryIndex++;
					$(row).append(cell);
				}
				$(table).append(row);
			}
			$("#YTFetch .Content .Inner").html("").append(table);
		} else {
			$("#YTFetch .Content .Inner").html("No Videos Found");
		}
	},
	
	GenerateVideoBox: function(entry) {
		var authorName = entry.author[0].name.$t
		var byText = ' by ' + authorName;
		var titleText = entry.title.$t;
		
		var title = '<div class="Title">' + this.LimitString(titleText, 28) + '</div>';
		var author = '<div class="Author">' + this.LimitString(authorName,18) + '</div>';
		
		if(YTFetch.Type == "uploads") {
			author = "";
			byText = "";
		}
		var ytIdLastSlashPos = entry.id.$t.lastIndexOf("/");
		var ytId = entry.id.$t.substring(ytIdLastSlashPos + 1, entry.id.$t.length);
		var ytBB = YTFetch.YTBBCode.replace("{0}",ytId);
		var onClick = ' onclick="insert_text(\'' + ytBB + '\', true);YTFetch.Close();return false;"';
		
		var imageUrl = entry.media$group.media$thumbnail[0].url;
		var image = '<div class="Image" title="' + titleText + byText + '">'
		image += '<img src="' + imageUrl + '" alt="' + titleText + '" width="120" height="90" />';
		image += '</div>';

		return '<div class="Box"' + onClick + '>' + image + title + author + '</div>';
	},
	
	LimitString: function(string, maxLength) {
		var result = string;
		if((string.length) > maxLength) {
			var newString = string.substring(0, maxLength - 3) + "...";
			result = "<span title=\""+ string +"\">" + newString + "</span>";
		}
		
		return result;
	},
	
	Close: function() {
		jQuery(document).trigger('close.facebox');
	}
}