jQuery(function() {

	//retrieve comments to display on page  
    jQuery.getJSON("/api/v2/contributors/active.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">Edits</th><th width="70%">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("#active_contributors").append(html);  
			// Format dates
			//jQuery('.date').timeago();			
		}
		else
		{
			jQuery("#active_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><td style="text-align:center"><a href="/users/' + contributor.user_id + '?hours=168">' + contributor.edits +'</a></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;	
	}
	
});
