function youtubeLoader(needle) {
	if(typeof(KEYWORD) == "object") {
		KEYWORD.setNeedle(needle);		
	} else {
		KEYWORD = new keywordFilter(needle);
	}
	this.needle = needle;
	videoQuery = "";
	var that = this;
	
}

youtubeLoader.prototype.loadVideos = function(startIndex) {  //Loads the JSON object from Youtube and performs callback
	if (startIndex) {
		this.startIndex = startIndex;	
	} else {
		this.startIndex = 1;
	}
	
	$.ajax({
		type:"GET",
		dataType:"jsonp",
		that:this,
		url: "http://gdata.youtube.com/feeds/api/videos?alt=json-in-script&category="+escape(this.needle)+"&max-results=6&start-index="+this.startIndex+"&format=5&safeSearch=strict&orderby=published&lr=en&v=2",
		error: function(XMLHttpRequest, textStatus, errorThrown){
			$('<p></p>')
			.html("There was an error with your request")
			.appendTo('#errorPane');
			returnVal = false;
		},
		success: function(html) {
			videoQuery = eval(html);
		},
		complete:function () {
			this.that.listVideos();
			tb_init("a.thickbox");
		}
	});
	
}

youtubeLoader.prototype.listVideos = function() {  //Takes data from JSON and prints it to screen
	$("#videoGrid").html("");
	if (videoQuery.feed.entry) {  //Check for a value of zero
		var videos = videoQuery.feed.entry;
		for (var i=0; i < videos.length; i++) {
			var videoTitle = videos[i].title.$t;
			var videoAuthor = videos[i].author[0].name.$t;
			//var videoViews = videos[i].yt$statistics.viewCount;
			var videoDate = new Date();
			videoDate.setISO8601(videos[i].published.$t);
			var relativeDate = relative_time(videoDate);
			var videoThumb = videos[i].media$group.media$thumbnail[0].url;
			var videoSWF = videos[i].media$group.media$content[0].url;
			var videoType = videos[i].media$group.media$content[0].type;
			var dots = "";
			if (videoTitle.length > 35) {
				var dots = "...";
			}
			
			$("#videoGrid").append('<div class="videoContainer"><a href="#TB_inline?height=450&width=520&inlineId=videoHolder" class="thickbox" title="'+videoTitle+'" onclick="replaceVideo(\''+videoSWF+'\',\''+videoType+'\');"><img border="0" class="youtubeThumb" src="'+videoThumb+'" title="'+videoTitle+'" /></a><div class="videoInfo"><div class="videoTitle">'+videoTitle.substring(0,35)+dots+'</div><div class="videoUser">'+videoAuthor+'</div><div class="uploadTimer">'+relativeDate+'</div></div>');
		}
		//creates next button if neccesary
		
		$("#videoContent .controlButtons").html("");
		if ((parseInt(videoQuery.feed.openSearch$startIndex.$t)+parseInt(videoQuery.feed.openSearch$itemsPerPage.$t)) < parseInt(videoQuery.feed.openSearch$totalResults.$t)) {
			$("#videoContent .controlButtons").append("<div class='moreButton'><a id='vidnext' class='navlink' href='javascript:void(0);'>Next</a></div>");
				
			$("#vidnext").attr("href", 'javascript:new youtubeLoader("'+this.needle+'").loadVideos('+eval(parseInt(videoQuery.feed.openSearch$startIndex.$t)+parseInt(videoQuery.feed.openSearch$itemsPerPage.$t))+');');
		}
		
		
		//Create Previous Button If Necessary
		if ((parseInt(videoQuery.feed.openSearch$startIndex.$t)-parseInt(videoQuery.feed.openSearch$itemsPerPage.$t)) > 0) {
			$("#videoContent .controlButtons").append("<div class='moreButton'><a id='vidprevious' class='navlink' href='javascript:void(0);'>Previous</a></div>");
			
			
			$("#vidprevious").attr("href", 'javascript:new youtubeLoader("'+this.needle+'").loadVideos('+eval(parseInt(videoQuery.feed.openSearch$startIndex.$t)-parseInt(videoQuery.feed.openSearch$itemsPerPage.$t))+');');
		}
			
		
	} else {  // If no videos return, reset needle and load video's again
		this.needle = "discovery"
		this.loadVideos();
	}
}

function replaceVideo (videoSWF, videoType) {  // Creates inline code of video flash object onthe fly for displaying in thickbox.
	$("#videoHolder").html('<div style="text-align:center; padding:30px;"><object width="425" height="350"><param name="movie" value="'+videoSWF+'"></param><embed src="'+videoSWF+'" type="'+videoType+'" width="425" height="350"></embed></object></div>');	
}


function relative_time(C){	
	var A=Date.parse(C);
	var D=new Date();
	var E=parseInt((D.getTime()-A)/1000);
	E=E+(D.getTimezoneOffset());
	if(E<60)
		{ return "less than a minute ago" }
	else
		{ if (E<120) 
			{ return "about a minute ago" }
		else
			{
				if (E<(60*60)) {
					return (parseInt(E/60)).toString()+" minutes ago"}
				else {
					if(E<(120*60)) {
						return "about an hour ago"
					}
					else {
						if(E<(24*60*60)) {
							return "about "+(parseInt(E/3600)).toString()+" hours ago"
						}
						else {
							if(E<(48*60*60))
								{return"1 day ago"}
							else{return(parseInt(E/86400)).toString()+" days ago"}
						}
					}
				}
			}
		}
}


Date.prototype.setISO8601 = function (string) {
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
        "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = string.match(new RegExp(regexp));

    var offset = 0;
    var date = new Date(d[1], 0, 1);

    if (d[3]) { date.setMonth(d[3] - 1); }
    if (d[5]) { date.setDate(d[5]); }
    if (d[7]) { date.setHours(d[7]); }
    if (d[8]) { date.setMinutes(d[8]); }
    if (d[10]) { date.setSeconds(d[10]); }
    if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14]) {
        offset = (Number(d[16]) * 60) + Number(d[17]);
        offset *= ((d[15] == '-') ? 1 : -1);
    }

    offset -= date.getTimezoneOffset();
    var time = (Number(date) + (offset * 60 * 1000));
    this.setTime(Number(time));
}
