var last_index = -1;
var submenu_anim = 0;
var submenu_timer = 5;
var submenu_normfactor = 20;
var menu_min_speed = 0.5;
var menu_timer = 20;

function toggleItem(index) {
	if (submenu_anim > 0) return;
	if (last_index != -1 && last_index != index)
		slideMenu(last_index);
	slideMenu(index);
	if (last_index == index)
		last_index = -1;
	else
		last_index = index;
}

function slideMenu(menuindex) {
	var submenu = document.getElementsByName("subItem").item(menuindex);
	var nextitem = document.getElementsByName("mainItem").item(menuindex + 1);
	if (!submenu && !nextitem) {
		submenu = subItem[menuindex];
		nextitem = mainItem[menuindex + 1];
	}
	if (submenu.childNodes) {
		if (submenu.childNodes.length == 0) return;
	}
	else {
		if (submenu.children.length == 0) return;
	}
	submenu_anim++;
	var next_menuindex = menuindex + 1;
	if (isHidden(submenu)) {	// submenu is invisible
		show(submenu);
		start = submenu.offsetTop;
		height = submenu.offsetHeight;
		end = height + start;
		nextitem.style.top = start;
		setTimeout("animateSubmenu(" + next_menuindex + ",-1," + start + "," + start + "," + end + ")", submenu_timer);
	}
	else { 																	// submenu is visible
		start = submenu.offsetTop;
		height = submenu.offsetHeight;
		end = height + start;
		setTimeout("animateSubmenu(" + next_menuindex + "," + menuindex + "," + end + "," + end + "," + start + ")", submenu_timer);
	}
}

function animateSubmenu (mindex, sindex, startpos, curpos, endpos) {
	var mainitem = document.getElementsByName("mainItem").item(mindex);
	if (!mainitem)
		mainitem = mainItem[mindex];
	mainitem.style.top = Math.round(curpos);
	if (Math.round(curpos) != endpos) {
		x = curpos - startpos;					// Using y = (x-a)^2 + c parabola formula for animation
		a = (endpos - startpos) / 2;
		c = a * a;
		y = c - (x - a) * (x - a);
		speed = menu_min_speed + y * submenu_normfactor / (Math.abs(a) * 100);	// Normalize parabola
		if (startpos > endpos) {
			curpos = curpos - speed;
			if (curpos < endpos)
				curpos = endpos;
		}
		else {
			curpos = curpos + speed;
			if (curpos > endpos)
				curpos = endpos;
		}
		setTimeout("animateSubmenu(" + mindex + "," + sindex + "," + startpos + "," + curpos + "," + endpos + ")", menu_timer);
	}
	else {
		if (sindex != -1) {
			var submenu = document.getElementsByName("subItem").item(sindex);
			if (!submenu)
				submenu = subItem[sindex];
			hide(submenu);
		}
		mainitem.style.top = endpos;
		submenu_anim--;
	}
}

function show (obj) {
	obj.style.display = "";
}

function hide (obj) {
	obj.style.display = "none";
}

function isShown (obj) {
	return obj.style.display == "";
}

function isHidden (obj) {
	return obj.style.display == "none";
}
