var menu_timer = {};
var menu_hide_delay = 300;

get_position = function(elt) {
	var curleft = curtop = 0;
	if(elt.offsetParent) {
		do {
			curleft += elt.offsetLeft;
			curtop += elt.offsetTop;
		} while (elt = elt.offsetParent);
	}
	return [curleft, curtop];
}

menu_over = function(source, above, left) {
	var parent = source.parentNode;
	var pos = get_position(source);
	var x = pos[0], y = pos[1];
	if(! above) y += source.offsetHeight;
	if(left) x += source.offsetWidth;
	menu_show(parent.id.replace('-source', ''), x, y, above, left);
}
menu_out = function(source) {
	var parent = source.parentNode;
	menu_set_timer(parent.id.replace('-source', ''));
}
menu_click = function(source) {
	return false;
}

menu_set_timer = function(id) {
	menu_clear_timer(id);
	menu_timer[id] = window.setTimeout('menu_hide("'+id+'")', menu_hide_delay);
}
menu_clear_timer = function(id) {
	if(menu_timer[id]) {
		clearTimeout(menu_timer[id]);
		delete menu_timer[id];
	}
}
menu_clear_all = function(id) {
	if(id)
		menu_clear_timer(id);
	for(var mid in menu_timer)
		if(mid != id)
			menu_hide(mid);
}
menu_show = function(id, x, y, above, left) {

	// clear the timer info
	menu_clear_all(id);

	// get ref of the passed id, which is the id of the parent minus the -source part
	var menu = document.getElementById(id);

	//alert("Start of menu_show\n\n original x: " + x + "    original y: " + y + "\nstarting left: " + menu.style.left + "    starting top: " + menu.style.top);

	// safety check to make sure what we want exists
	if(! menu) return;


	//if(above || left) {
		menu.style.visibility = 'hidden';

		// in the case of the bottom menu, this sets the top to 0
		menu.style.top = '';//0+'px';
		menu.style.left = '';//0+'px';
	//}

	//alert("After reset?\n\n original x: " + x + "    original y: " + y + "\nstarting left: " + menu.style.left + "    starting top: " + menu.style.top);


	// setting the menu to block (in the css it is hidden) allows the offsetWidth etc to work,
	// as they only work on block elements
	menu.style.display = 'block';
	if(left) {
		x -= menu.offsetWidth;
	}
	if(above)
		{
		// in the case of the bottom menu, we are setting top to be the value of the parent
		// element minus the height of that parent element
		//alert("subtracting " + menu.offsetHeight);
		y -= menu.offsetHeight;
		//alert("after: " + y);
	}
	menu.style.left = ''+x+'px';
	menu.style.top = ''+y+'px';
	//alert("original x: " + x + "    adjusted y: " + y + "\noffsetWidth: " + menu.offsetWidth + "    offsetHeight: " + menu.offsetHeight + "\nfinal left: " + menu.style.left + "    final top: " + menu.style.top);
	menu.style.visibility = 'visible';



	menu.onmouseover = function() {
		menu_clear_timer(id);
	}
	menu.onmouseout = function() {
		menu_set_timer(id);
	}
}
menu_hide = function(id) {
	menu_clear_timer(id);
	var menu = document.getElementById(id);
	if(! menu) return;
	menu.style.display = 'none';
}
