
(function() {

    var mchat = document.mchat = {};

    // 2008-09-22
    mchat.init = function mchat_init() {
      dd("MChat initialized");
      this.input = $("#chat_input").get(0);
      this.userlist = $("#chat_userlist").get(0);
      xb.cleanDom(this.userlist);
      this.console = $("#chat_console").get(0);
      this.nick = null;
      this.user = {};

      xb.cleanDom(this.console);
        
      document.mevent.handler.push(this);

      this.autoconnect = setTimeout('document.mchat.beginConnect()', 2000);
      this.input.focus();
    };

    // 2008-09-22
    mchat.cycle = function mchat_cycle() {
        dd("mchat: " + (this.cycleCount++) + "\n");
    };

    // 2008-09-22
    mchat.onChatUserListUpdate = function(rows) {

    };

    // 2008-09-22
    mchat.onChatActivityUpdate = function(r) {

    };

    mchat.keyPressed =
    function mchat_keyPressed(e) {
      var keynum;

      if (window.event)
        keynum = e.keyCode;
      else
        keynum = e.which;

      var keychar = String.fromCharCode(keynum);

      if (keynum == 13) {
        mchat.sendClicked();
        return true;
      }

      return false;
    };

    mchat.sendClicked =
    function mchat_sendClicked() {
      var msg = new String(this.input.value);

      if (msg && msg.length) {
        if (msg.charAt(0) != '/') {
          document.mevent.process(new MEvent({name: 'Command',
                                             command: 'say',
                                             message: msg}));
        } else {
          var a = msg.substring(1).split(" ", 1);
            document.mevent.process(
                new MEvent({name: 'Command',
                            command: a[0],
                            message: msg.substring(a[0].length+1).replace(/^\s+/, "")
                           }));
        }

        this.input.value = "";
      }

    };

    // 2008-10-06
    mchat.beginConnect =
    function mchat_beginConnect(e) {
      if (this.sock) {
        dd("Already connected?");
        return;
      }

      this.report({ notice: 'Initiating connection...'});
      this.sock = new document.MSocket({ port: 81 });
      this.sock.addListener(this);
      this.sock.requestConnect();
    };

    // 2008-10-06
    mchat.report =
    function mchat_report(e) {

        if (!('dom' in e)) {
            e.dom = document.createElement('div');
            e.dom.appendChild(document.createTextNode(e.notice));
        }

        this.console.appendChild(e.dom);
        this.console.scrollTop = this.console.scrollHeight;
    };

    mchat.requestConnection =
    function mchat_requestConnection() {
        this.sock.requestSend('PlsConnect {"version": 1}\n');
    }

    mchat.requestNick =
    function mchat_requestNick(nick) {

        var n = nick || this.pendingNick || this.grantedNick || "Guest";
        this.report({ notice: "Requesting nickname: \"" + n + "\"." });
        this.sock.requestSend('PlsNick {"nick": "' + n + '"}\n');
    };

    // 2008-10-09
    mchat.setNick =
    function mchat_setNick(nick) {
        this.pendingNick = nick;

        if (!this.sock) {
            this.report({ notice: "Nickname set: '" + this.pendingNick + "'."});
            //this.grantNick(this.pendingNick);
            return;
        }

        this.requestNick();
    };

    // 2008-10-09
    mchat.requestSay =
    function mchat_requestSay(message) {
        // XXX TODO ESCAPE QUOTES.
        var escapedMessage = message;
        this.sock.requestSend('PlsSay {"message": "' + escapedMessage + '"}\n');
    }

    // 2008-10-09
    mchat.userJoin =
    function mchat_userJoin(u) {

        var user;

        if (u.id in this.user) {
            user = this.user[u.id];
            user.nick = u.nick;
        } else {
            user = this.user[u.id] = {
                id: u.id,
                nick: u.nick
            }
        }

        if (!('dom' in user)) {

            var x = document.createElement('div');
            user.dom = x;
            this.userlist.appendChild(user.dom);
        } else {

            xb.clearDom(user.dom);
        }

        user.dom.appendChild(document.createTextNode(user.nick + " [" + user.id + "]"));
    }

    // 2008-10-09
    mchat.userPart =
    function mchat_userPart(id) {
        var user;

        if (id in this.user) {
            user = this.user[id];

            if ('dom' in user) {
                user.dom.parentNode.removeChild(user.dom);
            }
        }
    }

})();

document.mready.push({
  callback: function() { document.mchat.init(); },
  runlevel: 10,
  description: 'mchat init'});

// document.mready.push({
//   callback: function() { document.mchat.beginConnect(); },
//   runlevel: 20,
//   description: 'mchat connect'});
