
dojo.require("dojox.cometd");

var room = {   
    username: null,
    channel: "/chat/demo",
    
    join: function(name){        
        dojox.cometd.init("cometd");
        room.username=name;
        dojo.byId('join').className='hidden';
        dojo.byId('joined').className='';
        dojox.cometd.subscribe(room.channel, room, "chatCallback");
        dojox.cometd.publish(room.channel, {
            user: room.username,
            text: " has joined"
        });
    },
    leave: function(){
        if (room.username==null)
            return;
        dojox.cometd.unsubscribe(room.channel, room, "chatCallback");
        dojox.cometd.publish(room.channel, {
            user: room.username,
            text: " has left"
        });
        dojox.cometd.disconnect();
        // switch the input form
        dojo.byId('join').className='';
        dojo.byId('joined').className='hidden';
        room.username=null;
    },
    chat: function(text){
        dojox.cometd.publish(room.channel, {
            user: room.username,
            text: text
        });
    },
    chatCallback: function(message){  
        if(!message.data){
            alert("bad message format "+message);
            return;
        }  
        var messageLog=dojo.byId('messageLog');       
        var from=message.data.user;
        var text=message.data.text;
        from+=":";
        // display the  chat text
        messageLog.innerHTML += "<br/><span class=\"from\">"+from+" &nbsp;</span><span class=\"text\">"+text+"</span>";
    },
    
    init: function(){
        dojo.connect(dojo.byId("joinB"),"onclick",function(){
            if (!dojo.byId("sendName").value.length) {
                alert("Please enter Name");
                return;
            }
            room.join(dojo.byId('sendName').value);
        });       
        dojo.connect(dojo.byId("sendB"),"onclick",function(){
            if (!dojo.byId("sendText").value.length) {
                alert("Please enter Text");
                return;
            }
            room.chat(dojo.byId("sendText").value);
        });       
        dojo.connect(dojo.byId("leaveB"),"onclick",function(){
            room.leave();
        });        
    }
};

dojo.addOnLoad(room, "init");
dojo.addOnUnload(room,"leave");

