var iExplorer = document.all&&document.getElementById
var mFirefox = document.getElementById&&!document.all
var menuobj = null
var blockMenu = false;

function SW_RBM_showMenu(e){

	leftPosition = 0;
	topPosition = 0;

	if(menuobj != null){
		object = menuobj;
		while (object.offsetParent.nodeName != "BODY"){
			leftPosition += object.offsetParent.offsetLeft;
			topPosition += object.offsetParent.offsetTop;
			object = object.offsetParent;
		}
		
		//Find out how close the mouse is to the corner of the window
		var rightedge=iExplorer? document.body.clientWidth-event.clientX : window.innerWidth-e.clientX
		var bottomedge=iExplorer? document.body.clientHeight-event.clientY : window.innerHeight-e.clientY
		
		//if the horizontal distance isn't enough to accomodate the width of the context menu
		if (rightedge<menuobj.offsetWidth){
			//move the horizontal position of the menu to the left by it's width
			var styleLeft = iExplorer? document.body.scrollLeft+event.clientX-leftPosition-menuobj.offsetWidth : window.pageXOffset+e.clientX-leftPosition-menuobj.offsetWidth
			menuobj.style.left = styleLeft + "px";
		}else{
			//position the horizontal position of the menu where the mouse was clicked
			var styleLeft = iExplorer? document.body.scrollLeft+event.clientX-leftPosition : window.pageXOffset+e.clientX-leftPosition
			menuobj.style.left = styleLeft + "px";
		}
		
		//same concept with the vertical position
		if (bottomedge<menuobj.offsetHeight){
			var styleTop = iExplorer? document.body.scrollTop+event.clientY-topPosition-menuobj.offsetHeight : window.pageYOffset+e.clientY-topPosition-menuobj.offsetHeight
			menuobj.style.top = styleTop + "px";
		} else {
			var styleTop = iExplorer? document.body.scrollTop+event.clientY-topPosition : window.pageYOffset+e.clientY-topPosition
			menuobj.style.top = styleTop + "px";
		}
		
		menuobj.style.display="block";
		SW_RBM_resetMenu();
		return false
	}
}

function SW_RBM_hideMenu(){
	if(menuobj != null){
		menuobj.style.display="none";
	}
}

function nomostrarMenu(){
	if(menuobj != null){
		menuobj.style.display="none";
	}
}

function SW_RBM_SW_RBM_hideMenuAnterior(menuant){
	if(menuant != null && menuobj != null){
		if (menuant.id != menuobj.id){
			menuant.style.display="none";
		}
	}
}
	
function SW_RBM_openRightButtonMenu(seleccion){
	menuant = menuobj;
	menuobj = document.getElementById(seleccion);
	SW_RBM_SW_RBM_hideMenuAnterior(menuant);
	document.oncontextmenu = SW_RBM_showMenu
	
}

function SW_RBM_resetMenu(){
	document.oncontextmenu = function(){return true}
}

if (iExplorer||mFirefox){
	document.onclick=SW_RBM_hideMenu
}
