function wait(msecs)
{
	var start = new Date().getTime();
	var cur = start
	while(cur - start < msecs)
	{
		cur = new Date().getTime();
	}
} 

function Click(e) {
	if (e.type != 'click')
		return

	// only handle links (e.target.tagName is either "A" or "HTML")
	if (e.target.tagName != "A")
		return;

	// prevent page from transitioning to give
	// interpretation thread time to issue request
	wait(250);
}

function MouseDown(e) {
	// this: the window
	// e: the event that is detecting the event
	// e.target: the link that was clicked
	// document.body.innerHTML: current window's html

	if (e.type != 'mousedown')
		return

	// only handle links (e.target.tagName is either "A" or "HTML")
	if (e.target.tagName != "A")
		return;

	// only handle left mouse click
	if (WhichMouseButton(e) != 'LEFT')
		return;

	// the url and text of the link that was clicked
	to_url = e.target;
	to_name = e.target.innerHTML; // e.target.textContent;
	// the page we are currently on
	from_url = this.document.location.href;

	head = document.getElementsByTagName('head')[0];
	el = document.createElement('script');
	el.type = "text/javascript";
	el.src = BuildNotifyURL(to_url, to_name, from_url);
	head.appendChild(el);
	el.onload=function() { el.parentNode.removeChild(el);}
	el.onabort=function() { el.parentNode.removeChild(el);}
}

function WhichMouseButton(e) {
	if (e.which == null) // IE case
		button = (e.button < 2) ? "LEFT" : ((e.button == 4) ? "MIDDLE" : "RIGHT");
	else // All others
		button = (e.which < 2) ? "LEFT" : ((e.which == 2) ? "MIDDLE" : "RIGHT");

	return button;
}

function BuildNotifyURL(to_url, to_name, from_url) {
	return "http://tags.stanford.edu/tags_notify.py?" + "to_url=" + encodeURIComponent(to_url) + "&to_name=" + encodeURIComponent(to_name) + "&from_url=" + encodeURIComponent(from_url) + "&t=" + (new Date()).getTime();
}

window.addEventListener('mousedown', MouseDown, true);
window.addEventListener('click', Click, true);


