/**

    chat-isg.js
        Author : Hamilton Chua (ham@solutiongrove.com)
        Date Created : 3/29/2008

    Chat for iSolutiongrove

**/

isgChat = function(config) {
    
   // put config in an object property
   this.config = config;
   
   // the url to subsribe to
   this.chaturl = null;
   
   // who is logged in 
   this.userid = null;
   
   // reference to the layout for the chat
   this.layout = null;
   
   // the room id the user is currently in
   this.room_id = null;

   this.users_in_room = [];

   this.chaturl = '/isg/chat';

   this.tb_status = null;

   this.poller = null ;

   if (this.config.s) {
        this.session = this.config.s;
    } else {
        this.session = null;
    }
   
   this.createLayout();
}


// *** methods ***

isgChat.prototype = {

    rooms_ds : new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'xmlhttp/chat-listrooms'
        }), reader: new Ext.data.JsonReader(
            {totalProperty: 'total', root: 'results', id: 'room_id'}, [
            {name: 'pretty_name'},
            {name: 'description'},
            {name: 'active_p'},
            {name: 'archive_p'},
            {name: 'user_p'}]
        ), remoteSort:true, sortInfo:{field:"pretty_name",direction:"ASC"}
    }),
    
    createLayout : function() {
    
        /*  Load the UI in document.body if a layoutdiv is not provided */

        var layoutitems = [this.createMessagePanel(),this.createPostForm(),this.createUsersPanel()]

        this.layout = new Ext.Panel({
            id:"chat-ui",
            layout:'border',
            items: layoutitems
        })
        
        this.layout.findById('messagefield').focus();
        
    },
    
    createToolbar : function() {
        var tb = [];
        tb.push(this.createRoomsCombo());
        tb.push('<span id="tb_status"></span>');
        return tb;
    },
    
    createRoomsCombo : function() {
        var combo = new Ext.form.ComboBox( {
            autoCreate:true,
            allowBlank:false,
            id:'roomlist',
            editable:false,
            store:this.rooms_ds,
            displayField:'pretty_name',
            mode:"remote",
            queryDelay:0,
            minChars:2,
            forceSelection:true,
            minChars:1,
            emptyText:'Choose a chat room to enter',
            triggerAction:'all' } );

        combo.on("select",this.login_to_room,this);

        return combo;
    },
    
    createPostForm : function() {

        var panel = new Ext.form.FormPanel({
            id:'post-panel',
            region:'south',
            titlebar:false,
            split:false,
            height:150,
            resizable:false,
            buttonAlign:'right',
            frame:true,
            hidden:true,
            items: [
                {   xtype:'textarea',
                    id:'messagefield',
                    name:'chatmsg',
                    hideLabel:true,
                    width:'99%',
                    height:'100px',
                    enterIsSpecial : true}
            ], buttons: [
                {text: 'Send Message',id:'sendbtn',handler:this.sendMsg, scope:this}
            ]
        });

        panel.findById('messagefield').on('specialkey',function(field,e) {
            if(e.getKey() == 13) {
                this.sendMsg();
            }
        },this);

        return  panel;
    },
    
    createUsersPanel : function() {
        var panel = new Ext.Panel ({
            id:'user-panel',
            region:'east',
            titlebar:true,
            title:'Users',
            layout:'fit',
            split:true,
            width:250,
            autoScroll:true,
            hidden:true,
            bodyStyle:'padding:10px;'
        });
        return  panel;
    },
    
    createMessagePanel : function() {
        var panel = new Ext.Panel ({
            id:'message-panel',
            region:'center',
            titlebar:false,
            layout:'fit',
            split:true,
            autoScroll:true,
            tbar:this.createToolbar(),
            bodyStyle:'padding:10px;'
        });
        return  panel;
    },

    login_to_room : function(combo,record,i) {

       Ext.get('tb_status').update('<img src="/resources/ajaxhelper/ext2/resources/images/default/grid/wait.gif" />');

        if(this.room_id != null) {
            Ext.Ajax.request({
                url:this.chaturl,
                params:{m:'logout',id:this.room_id,s:this.session},
                success:function(o) {
                    // exited current room

                },failure:function() {
                    // Ext.Msg.alert('Chat Error','Sorry, we got an error entering the chat room.');
                },scope:this
            });


        }

        Ext.Ajax.request({
            url:this.chaturl,
            params:{m:'login',id:record.id,s:this.session},
            success:function(o) {
                Ext.get('tb_status').update('');
                this.layout.findById('message-panel').body.update("");
                this.layout.findById('user-panel').body.update("");
                this.layout.findById('user-panel').show();
                this.layout.findById('post-panel').show();
                this.layout.doLayout();
                this.users_in_room = [];
                this.room_id = record.id;
                this.addMsg(Ext.decode(o.responseText));
                this.get_room_users();
                this.initPolling();
            },failure:function() {
                Ext.get('tb_status').update('');
                // Ext.Msg.alert('Chat Error','Sorry, we got an error entering the chat room.');
            },scope:this
        });

        return true;

    },

    initPolling : function() {

        var task = {
            run: function(){
                Ext.Ajax.request({
                    url:this.chaturl,
                    params:{m:'get_updates',id:this.room_id,s:this.session},
                    success:function(o) {
                        eval(o.responseText);
                    },failure:function() {
                        // Ext.Msg.alert('Chat Error','Sorry, we got an error getting a message.');
                    },scope:this
                })}, 
            scope:this,
            interval: 1000 //1 second
        }

        if(this.poller == null) {

            this.poller = new Ext.util.TaskRunner();

        } else {

            this.poller.stopAll();

        }

        this.poller.start(task);


    },

    stopPolling : function() {

        this.poller.stopAll();

    },

    getUsercolor : function(user_id) {

        var usercolor = '#000000';

        for(var x=0; x<this.users_in_room.length; x++) {
            if(this.users_in_room[x].user_id == user_id) {
                usercolor = this.users_in_room[x].color;
                break;
            }
        }

        return usercolor;


    },

    userInroom : function(user_id) {

        var isinroom = false;

        for(var x=0; x<this.users_in_room.length; x++) {
            if(this.users_in_room[x].user_id == user_id) {
                isinroom = true;
                break;
            }
        }

        return isinroom;

    },

    buildUserlist : function(user_obj_arr) {

        var userlistbody = this.layout.findById('user-panel').body;
        for(var x=0; x<user_obj_arr.length; x++) {
            if(!this.userInroom(user_obj_arr[x].user_id)) {
                this.users_in_room.push(user_obj_arr[x]);
                userlistbody.insertHtml('beforeEnd','<div id="user-'+user_obj_arr[x].user_id+'" class="onechatuser" style="color:'+user_obj_arr[x].color+'">'+user_obj_arr[x].user+'</div>');
            }
        }

    },

    get_room_users : function() {
        Ext.Ajax.request({
            url:this.chaturl,
            params:{m:'get_users',id:this.room_id,s:this.session},
            success:function(o) {
                var arr = eval(o.responseText);
                this.buildUserlist(arr);
            },failure:function() {
                // Ext.Msg.alert('Chat Error','Sorry, we got an error retreiving users.');
            },scope:this
        });

    },
    
    sendMsg : function() {
        if(this.room_id != null) {
            var msg = this.layout.findById('messagefield').getValue();
            this.layout.findById('messagefield').reset();
            Ext.Ajax.request({
                url:this.chaturl,
                params:{m:'add_msg',id:this.room_id,s:this.session,msg:msg},
                success:function(o) {
                    this.addMsg(Ext.decode(o.responseText));
                },failure:function() {
                    // Ext.Msg.alert('Chat Error','Sorry, we got an error sending your message.');
                },scope:this
            });
        }
    },

    formatMsg : function(msg_obj) {
        var html;
        var color = this.getUsercolor(msg_obj.user_id);
        html = msg_obj.timestamp + " <b style='color:"+color+"'>" + msg_obj.user + "</b> : " + msg_obj.msg;
        return html;
    },
    
    addMsg : function(msg_obj) {
    
        var chatbody = this.layout.findById('message-panel').body;
        var msg = this.formatMsg(msg_obj);
        chatbody.insertHtml('beforeEnd','<div class="onechatmsg">'+msg+'</div>');

    }

}