window.onerror = CatchError;
var lastTrack, stillLoading, player, loading;
var funcRef = function () {
	player = document.getElementById("player");
	player.Play();
	loading.style.display = "none";
	stillLoading = 0;
};

// This is some really nasty code.  We get an unspecified error if we
// try to start the player before the .mp3 is downloaded, so the
// workaround is to trap it and try again in 1 second.
function CatchError() {
	setTimeout(funcRef,1000);
	return true;
}

function PlayTrack(el,name) {
	if (stillLoading) return;
	var div = document.getElementById("player_holder");
	player = document.getElementById("player");
	var image = el.src;
	if (image.match(/pause\.png$/)) {
		el.src = "play.png";
		player.Stop();
		lastTrack = null;
	} else {
		if (lastTrack) {
			lastTrack.src = "play.png";
			player.Stop();
		}
		stillLoading = 1;
		el.src = "pause.png";
		div.innerHTML = '<embed src="' + name + '" id="player" autostart="false" height="0" width="0" enablejavascript="true" />';
		loading = document.getElementById("loading");
		var pos = GetAbsoluteViewportPosition(el);
		loading.style.display = "";
		loading.style.left = (pos["x"] + 30) + "px";
		loading.style.top = (pos["y"] - 10 - loading.offsetHeight) + "px";
		setTimeout(funcRef,1000);
		lastTrack = el;
	}
	return;
}

function GetAbsoluteViewportPosition(item) {
	var rv = new Array();
	rv["x"] = 0;
	rv["y"] = 0;
	var elem = item;
	while (elem != null) {
		rv["x"] += elem.offsetLeft - elem.scrollLeft;
		rv["y"] += elem.offsetTop - elem.scrollTop;
		elem = elem.offsetParent;
	}
	return rv;
}
