function bindArabic(widget) {
  if (widget.arabicBound) return;
  var ARABIC_MAP = {
    ',': '\u060C',
    ';': '\u061B',
    '?': '\u061F',
    //''': '\u0621', // hamza
    a:  '\u0627', // alef
    e:  '\u0627',
    b:  '\u0628',
    '@': '\u0629', // teh marbuta
    t:  '\u062A',
    th: '\u062B',
    j:  '\u062C',
    H:  '\u062D',
    kh: '\u062E',
    d:  '\u062F',
    dh: '\u0630',
    r:  '\u0631',
    z:  '\u0632',
    s:  '\u0633',
    sh: '\u0634',
    S:  '\u0635',
    D:  '\u0636',
    T:  '\u0637',
    Z:  '\u0638',
    "'": '\u0639', // ain
    '`': '\u0639', // ain
    gh: '\u063A',
    '_': '\u0640', // tatweel
    f:  '\u0641',
    q:  '\u0642',
    k:  '\u0643',
    l:  '\u0644',
    m:  '\u0645',
    n:  '\u0646',
    h:  '\u0647',
    w:  '\u0648',
    u:  '\u0648',
    o:  '\u0648',
    y:  '\u064A',
    i:  '\u064A',
    '0': '\u0660',
    '1': '\u0661',
    '2': '\u0662',
    '3': '\u0663',
    '4': '\u0664',
    '5': '\u0665',
    '6': '\u0666',
    '7': '\u0667',
    '8': '\u0668',
    '9': '\u0669',
    p:  '\u067E'
  };

  function isToggleEvent(event) {
    return event.ctrlKey && String.fromCharCode(event.charCode) == "'";
  };
  function enable() {
    widget.style.background = '#eef';
    widget.onkeypress = keypressEnabled;
  };
  function disable() {
    widget.style.background = 'white';
    widget.onkeypress = keypressDisabled;
  };
  function keypressEnabled(event) {
    if (isToggleEvent(event)) {
      disable();
      return;
    }
    var char = String.fromCharCode(event.charCode);
    var pos = widget.selectionStart;
    
    if (widget.arabicDigraph) {
      var arabic = ARABIC_MAP[widget.arabicDigraph + char];
      // no matter what, we're leaving digraph mode on this keypress.
      widget.arabicDigraph = null;
      if (arabic) {
        widget.value = widget.value.substr(0, widget.selectionStart-1) +
                       arabic +
                       widget.value.substr(widget.selectionEnd);
        widget.setSelectionRange(pos+1, pos+1);
        return false;
      } else if (char == ' ') {
        // digraph char followed by space => eat the space.
        return false;
      }
    }

    if (ARABIC_MAP[char + 'h']) { // potential digraph!
      widget.arabicDigraph = char;
    }

    var arabic = ARABIC_MAP[char];
    if (arabic) {
      widget.value = widget.value.substr(0, widget.selectionStart) +
                     arabic +
                     widget.value.substr(widget.selectionEnd);
      widget.setSelectionRange(pos+1, pos+1);
      return false;
    }
    return true;
  };
  function keypressDisabled(event) {
    if (isToggleEvent(event)) {
      enable();
      return false;
    }
    return true;
  };

  widget.style.fontSize = '150%';
  widget.arabicBound = true;
  disable();
};

// vim: set ts=2 sw=2 et enc=utf-8 :
