jQuery(function() {

		//retrieve comments to display on page  
	    jQuery.getJSON("/api/v2/trends/countries/top.json?callback=?", function(data)
		{
		    //loop through all items in the JSON array 
			if(data)
			 {
				var html = '';
	        
				var trends = data.trends;
		        for (var x = 0; x < trends.length; x++) {  
					html += formatTrendText(trends[x]);
				}
			
				// add trend items to panel
		 		jQuery("#top_places_trends_list").append(html);  
			}
			else
			{
				jQuery("#top_places_trends_list").append("No trends available");
			}          
	    });
		
		function formatTrendText(trend)
		{
			var date = '';
			var description = 'No definition.';
			var slug = encodeURIComponent(encodeURIComponent(trend.name));
			
			if(trend.description == null)
			{
				date = trend.last_trended_at;
			}
			else
			{
				description = trend.description.text;
				date = trend.description.created_at;
			}
			
			var html = '<span><a href="/?woeid=' + trend.woeid + '"><img src="' + countryToFlag(trend.place_name) + '" alt="' + trend.place_name + '" title="' + trend.place_name + '"></a> ';
			html += '<span style="padding-right:10px"><a href="/trend/' + slug + '"><b>' + trend.name + '</b></a>';
			html += '<span class="description" style="font-size:90%;display:none"> ' + description + ' (<a href="/trend/' + slug + '">edit</a>)</span>';
			html += '</span> ';
			return html;	
		}
		
	});
