
/*
  Copyright (C) 2005-2006 by Domenico De Felice

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

  Authors: Domenico De Felice, <dfdcod [at] gmail [dot] com>
*/

Tratto.bindings = {
    help: {}
};

Tratto.bindings.init = function() {
    document.addEventListener('keypress', function(event) {

                                  if (!Tratto.bindings._shouldDispatch(event)) return;

                                  var key = Tratto.bindings._pressedKey(event);
                                  var binding = Tratto.bindings[key];

                                  if (binding) binding(event);

                              }, false);
};

Tratto.bindings._shouldDispatch = function(event) {
    var tag = event.target.tagName;
    var writeable = _g(event.target, "readonly") != "true";
    var typetext = _g(event.target, "type") == "text";

    if (tag == 'textarea' && writeable) return false;
    if (tag == 'input' && typetext && writeable) return false;
    if (tag == 'textbox' && writeable) return false;

    return true;
};

Tratto.bindings._pressedKey = function(event) {
    var keycodes = {
        8: "del",
        9: "tab",
        13: "enter",
        19: "pause",
        27: "esc",
        33: "pageup",
        34: "pagedown",
        35: "end",
        36: "home",
        45: "ins",
        46: "canc",
        112: "f1",
        113: "f2",
        114: "f3",
        115: "f4",
        116: "f5",
        117: "f6",
        118: "f7",
        119: "f8",
        120: "f9",
        121: "f10",
        122: "f11",
        123: "f12"
    };

    var key;
    if (event.charCode) {
        key = String.toLowerCase(String.fromCharCode(event.charCode));
    } else {
        var code = event.keyCode;
        key = keycodes[code] || "key" + code;
    }

    if (event.metaKey) key = "Meta+" + key;
    if (event.shiftKey) key = "Shift+" + key;
    if (event.altKey) key = "Alt+" + key;
    if (event.ctrlKey) key = "Ctrl+" + key;

    return key;
};
