(function() {

    var mchat = document.mchat;

    // 2008-10-05
    mchat.onCommand =
    function mchat_onCommand(e) {

        dd("mchat_onCommand called, command: " + e.command);

        switch (e.command) {
        case 'connect':
            this.beginConnect();
            break;
        case 'eval':
            var ex;
            var result;
            try {
                result = eval(e.message);
            } catch (ex) {

            }
            if (ex)
                this.report({ notice: "EXCEPTION " + ex.message });
            else
                this.report({ notice: "RESULT: " + result });
            break;
        case 'nick':
            this.setNick(e.message);
            break;
        case 'say':
            this.requestSay(e.message);
            break;
        case 'die':
            this.sock.requestSend('PlsDie\n');
            break;
        }
    };


    // 2008-10-06
    mchat.onConnect =
    function mchat_onConnect(e) {
        this.report({ notice: 'Connection established.'});
        this.requestConnection();
    };

    // 2008-10-06
    mchat.onClose =
    function mchat_onClose(e) {
        this.report({ notice: 'Socket connection closed.'});
        delete this.sock;
        xb.clearDom(this.userlist);
        this.user = {};
        this.autoconnect = setTimeout('document.mchat.beginConnect()', 2000);
    };

    // 2008-10-06
    mchat.onDataReceived = document.msock.default_onDataRecieved;

    mchat.onPing =
    function mchat_onPing(e) {
        //this.report({ notice: 'PING received' });
        this.sock.requestSend("PONG { \"id\": " + e.id + ", \"time\": " + e.time + "}\n");
    };

    // 2008-10-09
    mchat.onConnection =
    function mchat_onConnection(e) {
        this.connection_id = e.id;
        this.report({ notice: "Connection recognized (" + e.id + ")." });
        this.requestNick();
    };

    // 2008-10-09
    mchat.onSetNick =
    function mchat_onSetNick(e) {
        if (e.id == this.connection_id) {
            this.report({ notice: "Nick granted: \"" + e.nick + "\"."});
        }
        this.userJoin(e);
    };

    // 2008-10-09
    mchat.onWho =
    function mchat_onWho(e) {
        for (var i = 0 ; i < e.who.length ; i++) {
            this.userJoin(e.who[i]);
        }
    };

    // 2008-10-09
    mchat.onPart =
    function mchat_onPart(e) {
        this.report({ notice: 'Got part: ' + e.id });
        this.userPart(e.id);
    };

    mchat.onSay =
    function mchat_onSay(e) {
        this.report({ notice: this.user[e.id].nick + ": " + e.message });
    }

 })();
