// active flyout
var flyout;

// matches found
var matches = 0;

// add mouse click listener
document.onmouseup = cleanUp;	

// close flyouts that lose focus
function cleanUp(evt) {	
	//alert("cleanUp called");
	evt = (evt) ? evt : ((window.event) ? event : null);
	if(evt) {
		var elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);					
		//alert("Received click: " + elem);
		if(elem && flyout) {
			if(elem != flyout && childSearch(elem, flyout) == 0) {
				flyout.style.display = "none";
			}
			matches = 0;				
		}			
	}
}

function childSearch(needle, haystack) {
	//alert("childSearch called\nneedle: " + needle + "\nhaystack: " + haystack);	
	if(!haystack) { return matches; }
	
	// extract children
	var children = haystack.childNodes;
	
	// loop through child nodes
	for(var i = 0; i < children.length; i++) {
		// match found
		if(children[i] == needle) {
			//alert("Match found!");
			matches++;
		}
		
		// recursive search
		if(children[i].childNodes.length > 0) {
			childSearch(needle, haystack.childNodes[i]);
		}
	}
	return matches;
}

function toggleDisplay(id) {
	//alert("toggleDisplay called");
	// get object
	var obj = document.getElementById(id);
	
	// check display status
	if(obj.style.display == "inline") {
		// hide object
		obj.style.display = "none";
		flyout = null;
	}
	else {
		// show object
		obj.style.display = "inline";
		flyout = obj;
	}		
}