// ********************************************************************************************
// XBrowser DOM event routines © Ben Johnson, 2004
// 	- REQUIRES: [core]
// ********************************************************************************************
SetModStatus("dom.events", "ready");


// ROUTINES ***********************************************************************************

// returns true if param is a W3C DOM Event object
function IsDomEvent(vObj) { return (String(vObj) == "[object Event]");	}

// setup IE-style event object if Mozilla; call via:  "FixEventObj()"
// 	domEvent is optional; if wish, can explicitly pass Mozilla event object in (otherwise will be found automatically)
// TO DO: switch to ieEmu approach, where event object emulated automatically in Mozilla
function FixEventObj(domEvent) {
	// if Mozilla, adapt DOM-style event model to emulate IE-style event model
	if(!D.all) { 
		if(!IsDomEvent(domEvent)) {
			var fncCaller = FixEventObj.caller;
			// if event object not explicitly passed, assume is first argument of caller func
			domEvent = fncCaller.arguments[0];
			// if first argument of caller func isn't an event object, try grandparent func (e.g., inline handler)
			if(!IsDomEvent(domEvent)) domEvent = fncCaller.caller.arguments[0];
			if(!IsDomEvent(domEvent)) WarnMsg("FixEventObj() Error: no Event object passed to FixEventObj() or its parent/grandparent functions", 2);
		}
		window.event = domEvent;
		window.event.srcElement = domEvent.target;
		window.event.keyCode = domEvent.which;				// TO DO: check that this is correct
	}
}

// Register specified event handler/listener for specified event (DOM style naming, e.g., "mouseover") on specified element
// 	- returns true if successful, false if not
// 	- Fixes IE so that "this" references in handler func refer to the event source element instead of Global object
//  - e.g., AttachEvent(window, "load", OnWinLoad);
function AttachEvent(oElem, sEventName, fncHandler) {
	if(is.Obj(oElem)) {
		if(oElem.addEventListener) {
			oElem.addEventListener(sEventName, fncHandler, false);																		// W3C DOM-style handler
			return true;		// TO DO: check addEventListener was successful before return true
		}
		else if(oElem.attachEvent)
			// event handler called in context of event source element to fix "this" references
			return oElem.attachEvent("on" + sEventName, function() { fncHandler.call(oElem) } );			// IE-style handler
		else {
			WarnMsg("can't find way to attach events for this browser");
			return false;
		}
	}
	else throw CustomErr("Specified element doesn't exist (type="+ (typeof oElem) +")");
}

function FireEvent(oElem, sEventName, e) {
	if(oElem.fireEvent)
		// IE-style
		oElem.fireEvent("on" + sEventName, event);
	else if(oElem.dispatchEvent)
		// W3C DOM-style
		oElem.dispatchEvent(e);
	else
		WarnMsg("can't find way to fire events for this browser", 1);
}
