// events.js

// Assign event handler object
var eventHandler = new eventHandlerArray( null );

// Decide what browser is running
var fNetscape = navigator.appName.indexOf( "Microsoft" ) 
             != -1 ? false : true;

// Create cross-browser compatible event structure
var xEvent = new xEventObject();

function xEventObject()
{
    this.event = null;
    this.element = null;
    return this;
}

function eventHandlerArray()
{
    return new Array( eventHandlerItem( null ) );
}

function eventHandlerItem( handlerID )
{
    this.funcList = new Array()
    this.hID = handlerID
    return this
}
function hookEvent()
{
    var theEvent = hookEvent.arguments[0]
    var theHook = hookEvent.arguments[1]
    
    // Add event capturing at document level
    if ( fNetscape == true )
    {
        if ( document.captureEvents )
        {
            eval( "document.captureEvents( Event." + 
                                           theEvent.toUpperCase() + " );" );
            eval( "document.on" + theEvent + " = runEvent;" );
        }
        else return;
    }
    else
    {
        // Field event to document if it hasn't already been fielded
        if ( !eval( "document.on" + theEvent ) )
            eval( "document.on" + theEvent + " = runEvent;" );
    }
    // Locate the event in the event handlers list
    for ( i = 0; eventHandler[ i ]; i ++ )
    {
        if ( eventHandler[ i ].hID == theEvent )
        {
            // Located the event; find a free slot for this handler
            for ( j = 0; eventHandler[ i ].funcList[ j ] != null; j ++ ) {}
            eventHandler[ i ].funcList[ j ] = theHook;
            return;
        }
    }    
    // Event has not yet been assigned a handler, so extend event structure
    eventHandler[ i ] = new eventHandlerItem( null );
    eventHandler[ i ].hID = theEvent
    eventHandler[ i ].funcList[0] = theHook
}

function runEvent( event )
{
    if ( fNetscape == false )
    {
        xEvent.event = window.event;
        xEvent.element = window.event.srcElement;
    }
    else
    {
        xEvent.event = event;
        xEvent.element = event.target;
    }    
    // Run the event handler list
    for ( i = 0; eventHandler[ i ]; i ++ )
    {
        if ( eventHandler[ i ].hID == xEvent.event.type )
        {
            // Found an array of handlers for this event; run each in turn
            for ( j = 0; eventHandler[ i ].funcList[ j ]; j ++ )
            {
                retCode = eval( eventHandler[ i ].funcList[ j ] 
                                + "( xEvent )" )
                if ( retCode == false )
                {
                    // Stop handling event, and cancel default handling too
                    event.cancelBubble = true;
                    return false;
                }
            }
            // Allow default handling, after we have run our events
            return true;
        }
    }

    // Won't get here
    return false
}