var tag;
var targetId;
var valueRetweetMap;

function setupTagCounts(tag, targetId, valueRetweetMap) {
	this.tag = tag;
	this.targetId = targetId;
	this.valueRetweetMap = valueRetweetMap;
	setOnLoad(reloadTagCounts);
}

function reloadTagCounts() {
	var script = document.getElementById("tagCountScript");
	if (script) {
		document.getElementsByTagName("head")[0].removeChild(script);
	} else {
		script = document.createElement("script");
		script.setAttribute("id", "tagCountScript");
		script.setAttribute("language", "javascript");
		script.setAttribute("src", "http://tweetymail.com/tagcounts?tag=" + escape(tag));
	}
	document.getElementsByTagName("head")[0].appendChild(script);	
}

function handleTagCounts(result) {
	if (result.success) {	
		var tableBody = document.getElementById(targetId);
		while (tableBody.firstChild) {
			tableBody.removeChild(tableBody.firstChild);
		}
		for (var i = 0; i < result.results.length; i++) {
			var value = result.results[i];		
			var row = document.createElement("tr");
			if (i % 2 != 0) {
				row.className = "tagCountAlt";
			}
			var nameCell = document.createElement("td");
			nameCell.className = "tagCountName";
			var nameAnchor = document.createElement("a");
			nameAnchor.href = value.description;
			nameAnchor.innerHTML = value.name;
			nameCell.appendChild(nameAnchor);
			row.appendChild(nameCell);
			var countCell = document.createElement("td");
			countCell.className = "tagCountCount";
			countCell.innerHTML = value.count + (value.count != 1 ? " tweets" : " tweet");
			row.appendChild(countCell);
			var retweetCell = document.createElement("td");
			retweetCell.className = "tagCountRetweet";
			var rtAnchor = document.createElement("a");
			rtAnchor.href = "http://twitter.com/home?status=" + escape(valueRetweetMap[value.name]);
			var rtImg = document.createElement("img");
			rtImg.src = "http://tweetymail.com/images/tweet.png";
			rtAnchor.appendChild(rtImg);
			retweetCell.appendChild(rtAnchor)
			row.appendChild(retweetCell);
			tableBody.appendChild(row);
		}
	}
}

function setOnLoad(func) {
	var existing = window.onload;
	if (existing) {
		window.onload = function() {
			existing();
			func();
		};
	} else {
		window.onload = func;
	}	
}