

var timer = null;
var menu = {parent: null, el: null};
var subOffset = {x: 0, y: -1};

function menuEnter() {
	window.clearTimeout(timer);
    timer = null;
}

function menuLeave() {
    if( timer == null ) {
        timer = window.setTimeout( hideMenu, 500 );
    }
}

function hideMenu( parent ) {
    while( menu && menu.el && menu.el !== parent ) {
        menu.el.style.visibility = "hidden";
        menu = menu.parent;
    }
}

function getPosition( element ){
    var el = element, left = 0, top = 0;
    do {
        left += el.offsetLeft || 0;
        top  += el.offsetTop || 0;
        el = el.offsetParent;
    } while (el);
    return {'x': Math.round(left), 'y': Math.round(top)};
}

function showMenu( event, id, element, parent, changeLeftPermanent, changeTopPermanent, useJqueryPosition, fixed) {
    
    if( !document.getElementById(id) ) {
        return;
    }
   
   	parent = $(parent) || null;
   	if (parent) {	
    	hideMenu( parent );
    }
    
    if (element) {

			if ( ! useJqueryPosition) {
    		var position = getPosition(element);
    	}
    	else {
    		var _position = $(element).position();
    		var position = {
    			'x': Math.round(_position.left),
    			'y': Math.round(_position.top)
    		};
    	}
    	
			$('#'+id).css('z-index', 9999);
			if (fixed) {
	    	$('#'+id).css('position', 'fixed');
	    } else {
    		$('#'+id).css('position', 'absolute');
    	}
    	
    	if ( ! $('#'+id).css('left') || $('#'+id).css('left') == '0px' || $('#'+id).css('left') == 0 || changeLeftPermanent) {
    		$('#'+id).css('left', position.x+'px');
    	}
    	
    	if ( ! $('#'+id).css('top') || $('#'+id).css('top') == '0px' || $('#'+id).css('top') == 0 || changeTopPermanent) {
    		$('#'+id).css('top', position.y+'px');
    	}
    }
    menu = {parent: menu, el: document.getElementById(id)};
    menu.el.style.visibility = "visible";

    menuEnter();
}
