jQuery(function() {

	//retrieve comments to display on page  
    jQuery.getJSON("/api/v2/contributors/fastest.json?hours=168&callback=?", function(data)
	{
	    //loop through all items in the JSON array 
		if(data)
		 {
			var html = '<table class="boxlist"><thead><tr><th width="10%" style="text-align:center">Rank</th><th width="10%" style="text-align:center">Seconds</th><th width="20%">Trend</th><th width="50%">User/Location</th><th style="text-align:center" width="10%">Country</th></tr></thead>';
        
			var contributors = data.contributors; // second element is the list of trends
	        for (var x = 0; x < contributors.length; x++) {  
				html += formatContributorText(contributors[x], x);
			}
		
			html += "</table>"
			
			// add trend items to panel
	 		jQuery("#fastest_contributors").append(html);  
			// Format dates
			//jQuery('.date').timeago();			
		}
		else
		{
			jQuery("#fastest_contributors").append("No contributors available");
		}          
    });
	
	function formatContributorText(contributor, index)
	{
		var location = '';
		if(contributor.city != null && contributor.city != "")
		{
            location = contributor.city + ', ' + contributor.region;
 		}
		else
		{
			location = "Not specified";
		}

		var user_location = '';
		if(contributor.user_screen_name != null && contributor.user_screen_name != "" && contributor.user_screen_name != "undefined")
		{
			user_location = '<a href="/users/' + contributor.user_id + '">@' + contributor.user_screen_name + '</a>';
 		}
		else {
			user_location = location;
		}
					
		var html = '<tr><td style="font-size:140%;font-weight:bold;text-align:center">#' + (index + 1) +'</td>';
		html += '<td style="text-align:center">' + contributor.time_to_definition + '</td>';
		html += '<td style=""><a href="/trend/' + contributor.slug + '">' + contributor.trend + "</a>";
		html += '<div class="description" style="font-size:80%;display:none">' + contributor.blurb + '</div></td>'
		html += '<td style="">' + user_location + '</td>';
		html += '<td style="text-align:center"><img src="' + countryToFlag(contributor.country) + '" alt="' + contributor.country + '" title="' + contributor.country + '"></td>';
		html += '</tr>';
			
		return html;	
	}
	
});
