/*
    Copyright (c) 2005 Joost Diepenmaat, Zeekat Softwareontwikkeling, 
    all rights reserved.

    Permission is hereby granted, free of charge, to any person obtaining 
    a copy of this software and associated documentation files (the 
    "Software"), to deal in the Software without restriction, including 
    without limitation the rights to use, copy, modify, merge, publish, 
    distribute, sublicense, and/or sell copies of the Software, and to 
    permit persons to whom the Software is furnished to do so, subject to 
    the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
    OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE 
    OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


    chatbase.js $Revision: 1.8 $

    A base class for a chatbox using XMLHttpRequest.

    The webpage for this code is at http://zeekat.nl/downloads/chatbox/
*/



(function() {
    var xjs = nl.zeekat.xjs;
    var chat = xjs.namespace("nl.zeekat.chat");

    //
    //  default messagelist constructor.
    //  this makes a nice table layout
    //
    
    chat.MessageList = xjs.constructor(
    {
       
        init: function (chatbox) {
            this.chatbox = chatbox;
            this.div = document.createElement("div");
            this.div.className = "messagelist";
            this.table = document.createElement("table");
            this.div.appendChild(this.table);
            this.rows = 0;
            this.cells = 0;
 
        },
        
        addMessage: function (message) {
            var tr = this.table.insertRow(this.rows++);
            this.cells = 0;
            if (message.emote) {
                tr.className = "emote";
            }
            for (var i =0; i < this.chatbox.actions.length; i++) {
                var th = tr.insertCell(this.cells++);
                th.className = this.chatbox.actions[i];
                th.appendChild(this.chatbox[this.chatbox.actions[i]](message));
            }

            var m = tr.insertCell(this.cells++);
            m.className = "message";
            var html = message.html;
            if (message.emote) {
                html = this.chatbox.htmlEscape(message.author)+" "+html;
            }
            m.innerHTML = html;

        },
        
        element: function () {
            return this.div;
        }
   });

    /*
     constructor for a "compressed" chatbox
     uses a lot less space than the default one
     but doesn't look as nice
    */

    chat.MessageListSmall = xjs.constructor(
    {
       
        init: function (chatbox) {
            this.chatbox = chatbox;
            this.div = document.createElement("div");
            this.div.className = "messagelist";
 
        },
        
        addMessage: function (message) {
            var p = document.createElement("span");
            if (message.emote) {
                p.className = "emote";
            }
            for (var i =0; i < this.chatbox.actions.length; i++) {
                p.appendChild(this.chatbox[this.chatbox.actions[i]](message));
                p.appendChild(document.createTextNode(" "));
            }

            var m = document.createElement("span");
            m.className = "message";
            var html = message.html;
            if (message.emote) {
                html = "<i>" +this.chatbox.htmlEscape(message.author)+" "+html+"</i>";
            }
            m.innerHTML = html;
            p.appendChild(m);
            this.div.appendChild(p);
            this.div.appendChild(document.createElement("br"));
        },
        
        element: function () {
            return this.div;
        }
   });

    chat.ChatBase = xjs.constructor(
    {
        messageTagName: "message",
        
        readyStates: [
            "U","!","L","I","C"
        ],
        
        init: function (baseUrl, elementId, messageListConstructor) {
            if (arguments.length == 0) {
                return;
            }
            if (messageListConstructor) {
                this.messageListConstructor = messageListConstructor;
            }
            else {
                this.messageListConstructor = chat.MessageList;
            }
            this.requestNumber = 0;
            this.baseUrl = baseUrl;
            this.elementId = elementId;
            this.secondsLeft = 0;
            this.readyState = 0;
            var neededMethods = [
                "document.getElementById",
                "document.createTextNode",
                "document.getElementsByTagName",
                "document.getElementById('"+elementId+"').innerHTML",
                "document.createElement",
                ];

            for (var i =0; i < neededMethods.length; i++) {
                try { 
                    eval(neededMethods[i]); 
                } 
                catch(e) {
                    alert("Can't find method or property '"+neededMethods[i]+"' you probably need a different browser");
                    return false;
                }
            }

            // on mozilla, we need special privileges to do an XML request
            // to a remote server. In fact, unless you sign this script it
            // will only work from a local file:// URL or from the server
            // it tries to connect to.
            
            if (document.location.href.indexOf(baseUrl) != 0) {
                try {
                    if (netscape.security.PrivilegeManager.enablePrivilege) {
                        this.getPrivs = function (func) {
                            netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
                            func();
                        }
                    }
                }
                catch (e) {  }
            }
            if (!this.getPrivs) {
                this.getPrivs = function (func) { func () }
            }

            this.blockElement = document.getElementById(this.elementId);
            if (!this.blockElement) {
                alert("element "+elementId+" not found!");
            }

            this.createInterface();
        },

        createInterface: function() {
            this.clearInterface();


            this.statusElement = document.createElement("div");
            this.statusElement.className = "statusbar";
            this.statusElement.appendChild(document.createTextNode("Starting interface"));
            this.blockElement.appendChild(this.statusElement);
            this.messageListElement = (new this.messageListConstructor(this)).element();
            this.blockElement.appendChild(this.messageListElement);
            this.form = document.createElement("form");
            this.form.className = "inputbar";

            this.inputBox = document.createElement("input");
            this.inputBox.type = "text";
            this.inputBox.className = "inputbox";

            var chatbox = this;
            this.form.onsubmit = function() {
                if (chatbox.inputBox.value.match(/\S/)) {
                    chatbox.send(chatbox.inputBox.value);
                }
                return false;
            }
            this.form.appendChild(this.inputBox);
            var submit = document.createElement("input");
            submit.type="submit";
            submit.value = "Send";

            this.form.appendChild(submit);

            this.blockElement.appendChild(this.form);
        },

        clearInterface: function() {
            // remove all content from the block
            while (this.blockElement.firstChild) {
                this.blockElement.removeChild(this.blockElement.firstChild);
            }
        },

        updateStatus: function(text) {
            if (text) {
                this.lastText = text;
            }
            else {
                text = this.lastText;
            }
            this.statusElement.replaceChild(
                document.createTextNode(
                    this.baseUrl +" [ " + 
                    this.readyStates[this.readyState] + " | #" +
                    this.requestNumber + " ] " + text),
                this.statusElement.firstChild
            );
        },

        updateContent: function(dom) {
            var chatbox = this;
            this.getPrivs(
                function() {

                    var messages = dom.getElementsByTagName(chatbox.messageTagName);
                    var list = new chatbox.messageListConstructor(chatbox);
                    for (var i=0; i < messages.length; i++) {
                        list.addMessage(chatbox.parseMessage(messages.item(i)));

                        chatbox.blockElement.replaceChild(list.element(),chatbox.messageListElement);
                        chatbox.messageListElement = list.element();
                    }
                }
            );
            chatbox.updateStatus("Ok");
        },

        refresh: function() {
            this.updateStatus("Refresh...");
            var chatbox = this;
            this.getRequest(this.messagesUrl,
                function(resp) {
                    chatbox.updateContent(resp.responseXML);
                    chatbox.secondsLeft = 30;
                    chatbox.timer = setTimeout( function() { chatbox.countDown() }, 1000 );
                },
                ""
            );
        },


        countDown: function() {
            var chatbox = this;
            if (this.secondsLeft-- == 0) {
                this.refresh();
            }
            else {
                this.timer = setTimeout( function() { chatbox.countDown() }, 1000 );
            }
        },

        getRequest: function(url, callback, data) {
            if (this.timer) {
                clearTimeout(this.timer);
            }
            this.secondsLeft = 0;
            var req = this.request();
            var chatbox = this;
            req.onreadystatechange = function () {
                chatbox.readyState = req.readyState;
                chatbox.updateStatus();
                if (req.readyState == 4) {
                    callback(req);
                }
            }
            this.getPrivs(
                function() {  
                    req.open("GET",url)
                }
            );
            req.send(data);
        },

        start: function() {
            this.refresh();
        },

        // these create links for each message
        // if you subclass this object, you can add more!

        actions: [ "replyLink", "authorLink" ],

        replyLink: function(message) {
           var cb = this;
           var a = document.createElement("a");
           a.onclick= function() {
               cb.inputBox.value = "["+message.author+"]: " + cb.inputBox.value;
               cb.inputBox.focus();
               return false;
           }
           a.title = "Reply to "+message.author;
           a.appendChild(document.createTextNode("R"));
           return a;
       },

       authorLink: function(message) {
           return document.createTextNode(message.emote ? "*" : "<"+message.author+">");
       },


       htmlEscape: function(html) {
            var out = html.replace(/&/g,"&amp;");
            out.replace(/</g,"&gt;");
            out.replace(/>/g,"&lt;");
            return out;
       }
 
    });

    if (window.XMLHttpRequest) {
        chat.ChatBase.prototype.request = function () { 
            this.requestNumber++;
            return new window.XMLHttpRequest() 
        };
    }
    else if (window.ActiveXObject) {
        chat.ChatBase.prototype.request = function () {
            this.requestNumber++;
            return new ActiveXObject("Microsoft.XMLHTTP");
        };
    }
    else {
        alert("Can't use XMLHttpRequest, you probably need a different browser");
    }    
})();



