menudata = null;
menudelay = null;
active = null;

$('#topbar').ready(function() {
	$.ajax({
		type: 'POST',
		contentType: 'application/json; charset=urf-8',
		url: '/shared/menuxml.php',
		dataType: 'xml',
		success: function(xml) {
			active = $('#topbar li.active').attr("id");
			menudata = xml;
			$('#topbar li').each(function() {
				var li = this;
				$(li).mouseleave(function() {
					clearTimeout(menudelay);
					menudelay = setTimeout("hidemenu();", 250);
				});
				$(li).mouseenter(function() {
					clearTimeout(menudelay);
					showmenu($(li).attr('id'));
				});
			});
		}
	});
});

function hidemenu() {
	$('#menu').empty();
	$('#topbar li.selected').removeClass('selected');
}

function showmenu(i) {
	var id = i;
	hidemenu();
	$('#menu').append('<div id="dropdown"></div>');
	var menu = $(menudata).find('menu[id="' + id + '"]');
	if ($(menu).attr('subs') == '1') {
		$(menu).children('item').each(function() {
			var opt = this;
			$('#dropdown').append('<a></a>');
			$('#dropdown > a:last').attr('href', $(opt).attr('link'));
			$('#dropdown > a:last').text($(opt).attr('title'));
		});
		$('#' + id).addClass('selected');
		$('#dropdown').css('left', $('#' + id).offset().left + 1);
		$('#dropdown').mouseleave(function() {
			clearTimeout(menudelay);
			menudelay = setTimeout("hidemenu();", 250);
		});
		$('#dropdown').mouseenter(function() {
			clearTimeout(menudelay);
		});
	} else {
		hidemenu();
	}
}
