
/* Based on John Resig's implementation in env.js. */
Object.extend(window, {
  _timers: [],
  
  setTimeout: function(fn, time) {
    var num;
    return num = setInterval(function() {
      fn();
      clearInterval(num);
    }, time);
  },
  
  setInterval: function(fn, time) {
    var num = this._timers.length;
    (this._timers[num] = new java.lang.Thread(new java.lang.Runnable({
      run: function() {
        while (true) {
          java.lang.Thread.currentThread().sleep(time);
          fn();
        }
      }
    }))).start();
    return num;
  },
  
  clearInterval: function(num) {
    if (this._timers[num]) {
      this._timers[num].stop();
      delete this._timers[num];
    }
  }
});

window.clearTimeout = window.clearInterval;

$w('encode decode').each(function(op) {
  window[op + 'URIComponent'] = function(s) {
    return String(java.net['URL' + op.capitalize() + 'r'][op](s, 'UTF-8'));
  };
});

Object.extend(String.prototype, {
  escapeHTML: function() {
    var result = '';
    var wasBlankChar = false;

    for (var i = 0; i < this.length; i++) {
      var c = this.charAt(i);
      if (c == ' ') {
        result += wasBlankChar ? '&nbsp;' : ' ';
        wasBlankChar = !wasBlankChar;
      }
      else {
        wasBlankChar = false;
        if ($w('& " < >').include(c)) {
          result += {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}[c];
        }
        else {
          var ci = 0xFFFF & c.charCodeAt(0);
          result += (ci < 160) ? c : '&#' + ci + ';';
        }
      }
    }
    return result;
  },
  
  unescapeHTML: function() {
    throw new Error('Not yet implemented.');
  }
});

