/*
* Created : 3/17/2011
* Author  : pscott
* Purpose : Add listeners to show panels in header on click event
*/

var actionPanelActivated = false;
var formElementHasFocus = false;

Event.observe(window, 'load', function(evt){
	//collect all the panels only once
	actionPanels = $('actionPanel').immediateDescendants();

	$$('#actions li').each(function(action){
		if(action.id && actionPanels.find(hasActionPanel.curry(action.id))){
			action.observe('click', function(evt){
				//hide all panels before showing the correct one
				actionPanels.each(function(panel){
					panel.hide();
				});
			
				$('actionPanel').show();
				$(this.id.substr(0, this.id.indexOf('Btn')) + 'Panel').show();
				actionPanelActivated = false;
			});
		}
	});
	
	$('actionPanel').observe('mouseover', function(evt){
		actionPanelActivated = true;
	});
	
	$('actionPanel').select('input, select, button').each(function(formElem){
		formElem.observe('focus', function(evt){
			formElementHasFocus = true;
		});
		
		formElem.observe('blur', function(evt){
			formElementHasFocus = false;
		});
	});
	
	//use our own mouseout so we don't close the panel when the mouse out is fired when moving between elements inside the header
	Event.observe(document, 'mousemove', function(evt){
		//don't hide if elements are in use
		if(formElementHasFocus)
			return;
		
		var boundingElement = actionPanelActivated ? $('actionPanel') : $('header');
		var coordinate = {
			x: boundingElement.cumulativeOffset()[0],
			x2: boundingElement.cumulativeOffset()[0] + boundingElement.clientWidth,
			y: boundingElement.cumulativeOffset()[1],
			y2: boundingElement.cumulativeOffset()[1] + boundingElement.clientHeight
		};
		
		if(evt.clientX < coordinate.x || evt.clientY < coordinate.y || evt.clientX > coordinate.x2 || evt.clientY > coordinate.y2)
			$('actionPanel').hide();
	});
});

//helper function to check if a link has an action panel
function hasActionPanel(actionId, actionPanel){
	if(actionId.substr(0, actionId.indexOf('Btn')) + 'Panel' == actionPanel.id) return true;
	else return false;
}
