//Parses the delicious feed for ratings tags, sorts them, and generates html from the results.

function ratingSort(a, b) {	//sorts DESCENDING ratings
	if (a.rating>b.rating) return -1;
	if (a.rating<b.rating) return 1;
	return 0;	
}

//1: pull out ratings from each post
var pattern = /(\d)star/;
for (var i=0; i< Delicious.posts.length; i++) {
	var post= Delicious.posts[i];
	post.rating = 0;
	for (tag in post.t) {
		var m = post.t[tag].match(pattern);
		if (m) post.rating = parseInt(m[0]);
	}
}

//2: sort posts by rating
var sortedPosts = Delicious.posts.sort(ratingSort);


//3: generate the HTML - this needs to be called at the appropriate juncture
function displayLinks(title) {
	var html = "";
	for (i in sortedPosts) {
		var post= sortedPosts[i];

		if (i == 0){
			if (title) {
				html = "<p style=\"clear:both\"><strong>"+title+"</strong></p>\r";				
			} else {
				html = "<p style=\"clear:both\"><strong>Explore this topic on the web:</strong></p>\r";
			}
		}
	
		html += '<p><img src="../img/' + post.rating + 'star.gif" height="12" width="70">';
		html += '<a href="' + post.u + '">' + post.d + '</a><br>';
		if (post.n){
			html += post.n;
		}
		html += '</p>';
	}
	document.write(html);
}

//Transitional measure: do it anyway. This should be in the calling html
displayLinks("Related Links:");