var svgNS = "http://www.w3.org/2000/svg";
var height = 500;
var width = 800;
var maxSize = 30;

function addBand(sim, band) {
	var svg = document.getElementById("svg-container");

	var rect = document.createElementNS(svgNS, "rect");
	svg.appendChild(rect);

	var text = document.createElementNS(svgNS, "text");
	var fontSize = (sim / 100.0) * maxSize;
	text.setAttribute("font-size", fontSize + "px");
	text.appendChild(document.createTextNode(band));
	svg.appendChild(text);
	var len = text.getComputedTextLength();
	var x = (width - len) * Math.random();
	var y = fontSize + (width - fontSize) * Math.random();
	text.setAttribute("x", x + "px");
	text.setAttribute("y", y + "px");
	text.setAttribute("fill-opacity", sim / 200.0);
	text.setAttribute("band", band);
	text.addEventListener("click", changeArtist, false);

	rect.setAttribute("x", x + "px");
	rect.setAttribute("y", (y - fontSize) + "px");
	rect.setAttribute("width", (len * 1.05) + "px");
	rect.setAttribute("height", (fontSize * 1.5) + "px");
	rect.setAttribute("fill-opacity", sim / 400.0);
	rect.setAttribute("band", band);
	rect.addEventListener("click", changeArtist, false);
}

function changeArtist(e) {
	remoteAS.getNewArtist(e.target.getAttribute("band"));
}

function handleNewArtist(result) {
	emptySVG();
	var svg = document.getElementById("svg-container");

	for (var i = result[1].length - 1; i >= 0; --i) {
		addBand(result[1][i][0], result[1][i][1]);
	}

	var text = document.createElementNS(svgNS, "text");
	text.appendChild(document.createTextNode(result[0]));
	text.setAttribute("font-size", maxSize + "px");
	text.setAttribute("font-weight", "bold");
	text.setAttribute("y", ((height - maxSize) / 2) + "px");
	svg.appendChild(text);
	var len = text.getComputedTextLength();
	text.setAttribute("x", ((width - len) / 2) + "px");
}

function emptySVG() {
	var svg = document.getElementById("svg-container");
	while (svg.hasChildNodes()) {
		svg.removeChild(svg.firstChild);
	}
}

var asCallback = {
getNewArtist: handleNewArtist,
};

var remoteAS = new Audioscrobbler_Server(asCallback);

