/**
 * Javascript library to handle a set of keybindings.
 *
 * The user should include this script, and then call setKeybinding(key,
 * callback) for each keybinding that is desired. This script will take care
 * of listening for keypresses and mapping them to the callback functions, or
 * doing nothing if no callback is set.
 *
 * $Horde: horde/templates/javascript/keybindings.js,v 1.5.4.4 2005/10/18 11:34:07 jan Exp $
 *
 * See the enclosed file COPYING for license information (LGPL). If you did
 * not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @package Horde
 */

/**
 * A hash of keybindings.
 *
 * @var _keyMap
 */
var _keyMap = new Array();

/**
 * Set up the keypress listener.
 */
if (typeof document.captureEvents != 'undefined') {
    document.captureEvents(Event.KEYPRESS);
    document.onkeypress = keyHandler;
} else {
    document.onkeydown = keyHandler;
}

/**
 * Sets up a callback for a keycode.
 *
 * @param key       The keycode to trigger on.
 * @param callback  The function to call when "key" is pressed. Should be a
 *                  function. It gets the event and the keycode as parameters,
 *                  so that you can use one function to handle multiple keys if
 *                  you like.
 */
function setKeybinding(key, callback)
{
    if (typeof _keyMap[key] == 'undefined') {
        _keyMap[key] = new Array();
    }

    _keyMap[key][_keyMap[key].length] = callback;
}

/**
 * Invoked by the JavaScript event model when a key is pressed. Gets the
 * keycode (attempts to handle all browsers) and looks to see if we have a
 * keybinding defined for that key. If so, eval() it.
 *
 * @param e  The event to handle. Should be a keypress.
 */
function keyHandler(e)
{
    var e = e || window.event;

    if (e.keyCode) {
        key = e.keyCode;
	} else if (e.which) {
        key = e.which;
    }

    /* If there's a keybinding defined for the key that was pressed, eval()
     * it, passing in the keycode and the event. */
    if (_keyMap[key]) {
        for (var i = 0; i < _keyMap[key].length; i++) {
            if (eval(_keyMap[key][i] + '(e, ' + key + ');')) {
                e.returnValue = false;
<?php if ($GLOBALS['browser']->isBrowser('mozilla')): ?>
                e.preventDefault();
<?php endif; ?>
                break;
            }
        }
    }
}
