var menuBar = document.getElementById('sbc-menu');
var menuLevel = new Array();
var closeTimer = null;
var timeout = 2000;

function addEvent(obj, evType, fn){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, true);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		if (evType == 'mouseover') {
			obj.onmouseover = fn;
		} else if (evType == 'mousemove') {
			obj.onmousemove = fn;
		} else if (evType == 'mouseout') {
			obj.onmouseout = fn;
		} else if (evType == 'click') {
			obj.onclick = fn;
		} else if (evType == 'load') {
			obj.onload = fn;
		} else {
			return false;
		}
	}
}

function getEventTarget(e) {
	var t;
	if (e.target) {
		t = e.target;
	} else if (e.srcElement) {
		t = e.srcElement;
	}
	if (t.nodeType == 3) // defeat Safari bug
		t = t.parentNode;
	return t;
}

function initMenu() {
	l = menuBar.getElementsByTagName('A');
	for (i = 0; i < l.length; i++) {
		addEvent(l[i], 'mouseover', menuOver);
	}
}

function getLevel(m) {
	l = 0;
	
	while (m != menuBar) {
		m = m.parentNode;
		if (m.tagName == 'LI') {
			l++;
		}
	}
	
	return l;
}

function getLink(m) {
	l = m.getElementsByTagName('A');
	if (l.length) {
		return l[0];
	} else {
		return null;
	}
}

function menuOver(e) {
	if (!e) var e = window.event;
	var t = getEventTarget(e);
	
	if (t.tagName == 'A') {
		menuParent = t.parentNode.parentNode;
	} else {
		menuParent = t.parentNode.parentNode.parentNode;
	}
	
	level = getLevel(menuParent);
	for (j = menuLevel.length - 1; j >= level; j--) {
		if (menuLevel[j] && menuLevel[j] != menuParent) {
			closeMenu(menuLevel[j]);
			menuLevel[j] = null;
		}
	}
	menuLevel[level] = menuParent;
	
	u = menuParent.getElementsByTagName('UL');
	if (u.length) {
		thePopup = u[0];
		if (thePopup.parentNode.parentNode == menuParent) {
			thePopup.style.display = 'block';
		}
		
		a = getLink(menuParent);
		if (a) {
			a.className = 'active';
		}
	}
	
	resetTimer();
}

function closeMenu(mp) {
	v = mp.getElementsByTagName('UL');
	if (v.length) {
		p = v[0];
		if (p.parentNode.parentNode == mp) {
			p.style.display = 'none';
		}
	}
	a = getLink(mp);
	if (a && a.className == 'active') {
		a.className = '';
	}
}

function resetTimer() {
	if (closeTimer) {
		clearInterval(closeTimer);
		closeTimer = null;
	}
	
	closeTimer = setTimeout('autoClose()', timeout);
}

function autoClose() {
	if (closeTimer) {
		clearTimeout(closeTimer);
		closeTimer = null;
	}

	for (j = menuLevel.length - 1; j >= 0; j--) {
		if (menuLevel[j]) {
			closeMenu(menuLevel[j]);
			menuLevel[j] = null;
		}
	}
}

initMenu();
