jQuery(function() {

	//retrieve comments to display on page  
    jQuery.getJSON("/api/v2/trends/active.json?callback=?", function(data)
	{
	    //loop through all items in the JSON array 
		if(data)
		 {
			var html = '<ul class="buttonlist">';
        
			var trends = data.trends; // second element is the list of trends
	        for (var x = 0; x < trends.length; x++) {  
				html += formatTrendText(trends[x]);
			}
		
			html += "</ul>"
			
			// add trend items to panel
	 		jQuery("#active_trends").append(html);  
			// Format dates
			jQuery('.date').timeago();			
		}
		else
		{
			jQuery("#active_trends").append("No trends available");
		}          
    });
	
	function formatTrendText(trend)
	{
		
		var date = '';
		var description = 'No definition.';
		if(trend.description == null)
		{
			date = trend.last_trended_at;
		}
		else
		{
			description = trend.description.text;
			date = trend.description.created_at;
		}
			
		var html = '<li class=""><a class="buttonlist_square" href="/trend/' + encodeURIComponent(trend.name) + '"><span class="count">' + trend.edit_count +'</span></a>';
		html += '<div class="buttonlist_desc"><a href="/trend/' + encodeURIComponent(trend.name) + '"><b>' + trend.name + '</b></a>';
		html += '<div class="description" style="font-size:90%;display:none">' + description + ' (<a href="/trend/' + encodeURIComponent(trend.name) + '">edit</a>)</div>';
		html += '<div class="date" style="color:#AAAAAA;font-size:90%">Last edited: <abbr class="date"  title="' + date + '">' + date + ' UTC</abbr></div>';
		html += '</div></li>';
		return html;	
	}
	
});
