/* Copyright IBM Corp. 2001, 2008  All Rights Reserved.               */

/*this file replaces Menu.js for use with the dojo menu*/
dojo.declare("lconn.MenuUtility", null, {
	// contains the dom node that was last clicked/keypressed to open the menu
	openedBy: null,
 
	openMenu: function (evt, menuId){	
		// summary: open a dijit pointed by menuId (typically a dijit.Menu) in a popup placed around the node in evt.target
		//	typically called on a onclick event in the page (onclick="menuUtility.openMenu(event, 'id of your menu')"
		//	you can also use dojo.connect to bind it programmatically in a dom node
		var menu = dijit.byId(menuId);		
		
		// standardize the event (fix cross-browser differences)
		evt = dojo.fixEvent(evt);
		
		// store the DOM of the action link that opened the menu
		this.openedBy = evt.target;

		// open the menu, place it relative to the target position of the node
		dijit.popup.open({
			popup: menu,
			around: evt.target,
			orient: {'BL':'TL', 'BR':'TR', 'TL':'BL', 'TR':'BR'},
			onExecute: function(){ 
			},
			onCancel: function(){ 				
				dijit.popup.close(menu); 
			}, 
			onClose: function(){
	    		try{
		        	evt.target.focus();
		        }
		        catch(exception)
		        {
					//Will try again to add focus. IE doesn't like it when an element is invisible and focus is set on the element.
					setTimeout(function () {
				        try{
				        	evt.target.focus();
				        }
				        catch(exception2)
				        {
							//do nothing at this point
				        }
			        }, 1000);
		        }    			
			}}); 

		menu.focus();

		// close the menu when the user click outside the menu 
		dojo.connect(menu, "_onBlur", function(){dijit.popup.close(menu)}); 			
		
		dojo.stopEvent(evt);
	},

	openMenuA11y: function (evt, menuId){
		// for keyboard a11y
		if (evt.keyCode == dojo.keys.ENTER){
			this.openMenu(evt, menuId);
		} 
	}});
 
 // one instance per page
 menuUtility = new lconn.MenuUtility();
