﻿Ext.BLANK_IMAGE_URL = _modulePath+'images/s.gif';
Ext.NO_AVATAR_URL = _modulePath+'images/no_avatar.jpg';
var bln_changing_rooms=false;


String.prototype.trim = function() {
    a = this.replace(/^\s+/, '');
    return a.replace(/\s+$/, '');
};


//JS Localization
function localize(key){
    if(jsLocale[key]!='undefined' && jsLocale[key]!=null){
        return jsLocale[key].toString();
    }else{
        return '#LOCALE KEY: "'+key+'" UNDEFINED#';
    }
}

function localize_svr_msg(txt){
    // Accepts a string with an localizable string encoded in {} brackets,
    //  And returns the txt with the string localized from function "localize"
    try{
        var re=/{.*}/g
        var mtch=txt.match(re);
        if (mtch!='undefined' && mtch!=null){
            mtch=mtch.toString()
            return txt.replace(mtch,localize(mtch.substring(1,mtch.length-1)));        
        }else{
            return txt;
        }
     }catch(e){
        return txt;
     }
    
}

//alert(Ext.BLANK_IMAGE_URL);
var _smilies = [
    [":-o","001"], 
    [":-s","002"], 
    [":)","003"], 
    [":drool:","004"], 
    [":lol:","005"], 
    [":sweat:","006"], 
    [":hammer:","007"],
    [":X","010"], 
    [":D","011"], 
    [":'(","012"], 
    [":$","013"], 
    [":@","014"], 
    [":P","015"], 
    [":(","016"], 
    ["B)","017"],
    [":O","018"], 
    [":E","019"], 
    ["+o(","020"], 
    ["}-)","021"], 
    ["8-)","022"], 
    [":^)","023"], 
    [":~","024"], 
    ["|-)","025"],
    ["8-|","026"], 
    [":yes:","027"], 
    [":-Q~","028"], 
    ["8|","029"], 
    ["#-)","030"], 
    ["}:o","031"], 
    ["?:/","032"], 
    [":-*","033"],
    ["@:|","034"], 
    ["~==","035"], 
    [":bomb:","036"], 
    [":skull:","037"], 
    [":wave:","038"], 
    ["zzz","039"], 
    [":pig:","040"], 
    ["{~o","041"],
    ["(L)","043"], 
    ["(U)","044"], 
    ["(Y)","045"], 
    ["(N)","046"], 
    [":agree:","047"], 
    [":peace:","048"]
]
SmiliePicker = function(config){
    SmiliePicker.superclass.constructor.call(this, config);
    this.addEvents({
        select: true
    });

    if(this.handler){
        this.on("select", this.handler, this.scope, true);
    }
};
Ext.extend(SmiliePicker, Ext.Component, {
    itemCls : "x-color-palette",
    value : null,
    // private
    ctype: "SmiliePicker",    
    smilies : _smilies,
    // private
    onRender : function(container, position){
        var t = new Ext.MasterTemplate(
            '<tpl><a href="#" hidefocus="on"><em><img width="20" height="20" id="emot-{1}" alt="{0}" src="'+_modulePath+'images/emoticons/{1}.gif"></em></a></tpl>'
        );
        var c = this.smilies;
        for(var i = 0, len = c.length; i < len; i++){
            //t.add([c[i][0],c[i][1]]);
            t.add(c[i]);
        }
        var el = document.createElement("div");
        el.className = this.itemCls;
        t.overwrite(el);
        container.dom.insertBefore(el, position);
        this.el = Ext.get(el);
        this.el.on("click", this.handleClick,  this, {delegate: "img"});
    },

    // private
    afterRender : function(){
        SmiliePicker.superclass.afterRender.call(this);
        if(this.value){
            var s = this.value;
            this.value = null;
            this.select(s);
        }
    },

    // private
    handleClick : function(e, t){
        e.preventDefault();
        if(!this.disabled){
            var c = t.alt;
            this.select(c);
        }
    },

    /**
     * Selects the specified color in the palette (fires the select event)
     * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
     */
    select : function(smilie){
        this.fireEvent("select",this,smilie);
    }
});



/**
 * @class SmilieItem
 * @extends Ext.menu.Adapter
 * A menu item that wraps the {@link Ext.ColorPalette} component.
 * @constructor
 * Creates a new Smilie(Emoticon Menu)
 * @param {Object} config Configuration options
 */
SmilieItem = function(config){
    SmilieItem.superclass.constructor.call(this, new SmiliePicker(config), config);
    /** The Ext.ColorPalette object @type Ext.ColorPalette */
    this.emoticons = this.component;
    this.relayEvents(this.emoticons, ["select"]);
    if(this.selectHandler){
        this.on('select', this.selectHandler, this.scope);
    }
};
Ext.extend(SmilieItem, Ext.menu.Adapter);


/**
 * @class SmilieMenu
 * @extends Ext.menu.Menu
 * A menu containing a {@link Ext.menu.ColorItem} component (which provides a basic color picker).
 * @constructor
 * Creates a new ColorMenu
 * @param {Object} config Configuration options
 */
SmilieMenu = function(config){
    SmilieMenu.superclass.constructor.call(this, config);
    this.plain = true;
    var ci = new SmilieItem(config);
    this.add(ci);
    /**
     * The {@link Ext.ColorPalette} instance for this ColorMenu
     * @type ColorPalette
     */
    this.emoticons = ci.emoticons;
    /**
     * @event select
     * @param {ColorPalette} palette
     * @param {String} color
     */
    this.relayEvents(ci, ["select"]);
};
Ext.extend(SmilieMenu, Ext.menu.Menu);









AvatarPicker = function(config){
    AvatarPicker.superclass.constructor.call(this, config);
    this.addEvents({
        select: true
    });

    if(this.handler){
        this.on("select", this.handler, this.scope, true);
    }
};
Ext.extend(AvatarPicker, Ext.Component, {
    itemCls : "x-color-palette",
    value : null,
    ctype: "AvatarPicker",    
    avatars : oAvatars,
    onRender : function(container, position){
        //TODO:  new template for avatars
        var t = new Ext.MasterTemplate(
            '<tpl><a href="#" hidefocus="on"><em><img width="28" height="28" id="avatar-{0}" alt="{0}" src="{0}"></em></a></tpl>'
        );
        var c = this.avatars;
        for(var i = 0, len = c.length; i < len; i++){
            //t.add([c[i][0],c[i][1]]);
            t.add(c[i]);
        }
        var el = document.createElement("div");
        el.className = this.itemCls;
        t.overwrite(el);
        container.dom.insertBefore(el, position);
        this.el = Ext.get(el);
        this.el.on("click", this.handleClick,  this, {delegate: "img"});
    },
    afterRender : function(){
        SmiliePicker.superclass.afterRender.call(this);
        if(this.value){
            var s = this.value;
            this.value = null;
            this.select(s);
        }
    },
    handleClick : function(e, t){
        e.preventDefault();
        if(!this.disabled){
            //TODO: something new here for selection
            var c = t.alt;
            this.select(c);
        }
    },
    select : function(avatar){
        this.fireEvent("select",this,avatar);
    }
});

AvatarItem = function(config){
    AvatarItem.superclass.constructor.call(this, new AvatarPicker(config), config);
    this.avatars = this.component;
    this.relayEvents(this.avatars, ["select"]);
    if(this.selectHandler){
        this.on('select', this.selectHandler, this.scope);
    }
};
Ext.extend(AvatarItem, Ext.menu.Adapter);

AvatarMenu = function(config){
    AvatarMenu.superclass.constructor.call(this, config);
    this.plain = true;
    var ci = new AvatarItem(config);
    this.add(ci);
    this.avatars = ci.avatars;
    this.relayEvents(ci, ["select"]);
};
Ext.extend(AvatarMenu, Ext.menu.Menu);

var avatarMenu = new AvatarMenu({
    selectHandler : function(cm, avatar){
        SWIRL.DNN.Modules.SWIRLChat.AJAX.UpdateUserAvatar(room_id,chat_userid,avatar,security_token,function(res){});
        my_avatar_url=avatar;
    } 
});
















var myMsgID = 0;


soundManager.onload = function() {
    //TODO:  load sounds so they are ready...
    soundManager.createSound({id:'tick-setting',url:soundManager.soundPath+'button-1.mp3',volume:40,autoLoad:false,stream:false});
    soundManager.createSound('DoorCreak',soundManager.soundPath+'DoorCreak.mp3');
    soundManager.createSound('Space',soundManager.soundPath+'Space.mp3');
    soundManager.createSound({id:'Notify',url:soundManager.soundPath+'notify.mp3',volume:10,autoLoad:false,stream:false});
}

function convertURL(txt) {
    var re=/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/g
    var repl="<a href='$&' target='_blank' class='url-highlight'>$&</a>";
    return txt.replace(re,repl);
}
var myDiv;
function escapeHTML(txt) {
    if(!myDiv){myDiv=document.createElement('div')};
    var text=document.createTextNode(txt);
    myDiv.innerHTML='';
    myDiv.appendChild(text);
    return myDiv.innerHTML;
}
function convertEmoticon(txt) {
    for(var x=0;x<_smilies.length;x++){
        //return txt.replace(':)','<img src="'+_modulePath+'images/emoticons/001.gif"/>');
        txt=txt.replace(_smilies[x][0],'<img src="'+_modulePath+'images/emoticons/'+_smilies[x][1]+'.gif"/>');
    }
    return txt
}

Ext.example = function(){
    var msgCt;

    function createBox(t, s){
        return ['<div class="msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
    }
    return {
        msg : function(title, format){
            if(!msgCt){
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
            }
            msgCt.alignTo(document, 't-t');
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
            m.slideIn('t').pause(1).ghost("t", {remove:true});
        },

        init : function(){
            var s = Ext.get('extlib'), t = Ext.get('exttheme');
            if(!s || !t){ // run locally?
                return;
            }
            var lib = Cookies.get('extlib') || 'yahoo', 
                theme = Cookies.get('exttheme') || 'aero';
            if(lib){
                s.dom.value = lib;
            }
            if(theme){
                t.dom.value = theme;
                Ext.get(document.body).addClass('x-'+theme);
            }
            s.on('change', function(){
                Cookies.set('extlib', s.getValue());
                setTimeout(function(){
                    window.location.reload();
                }, 250);
            });

            t.on('change', function(){
                Cookies.set('exttheme', t.getValue());
                setTimeout(function(){
                    window.location.reload();
                }, 250);
            });
        }
    };
}();

Ext.onReady(Ext.example.init, Ext.example);


// old school cookie functions grabbed off the web
var Cookies = {};
Cookies.set = function(name, value){
     var argv = arguments;
     var argc = arguments.length;
     var expires = (argc > 2) ? argv[2] : null;
     var path = (argc > 3) ? argv[3] : '/';
     var domain = (argc > 4) ? argv[4] : null;
     var secure = (argc > 5) ? argv[5] : false;
     document.cookie = name + "=" + escape (value) +
       ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
       ((path == null) ? "" : ("; path=" + path)) +
       ((domain == null) ? "" : ("; domain=" + domain)) +
       ((secure == true) ? "; secure" : "");
};

Cookies.get = function(name){
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	var j = 0;
	while(i < clen){
		j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return Cookies.getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if(i == 0)
			break;
	}
	return null;
};

Cookies.clear = function(name) {
  if(Cookies.get(name)){
    document.cookie = name + "=" +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
};

Cookies.getCookieVal = function(offset){
   var endstr = document.cookie.indexOf(";", offset);
   if(endstr == -1){
       endstr = document.cookie.length;
   }
   return unescape(document.cookie.substring(offset, endstr));
};











/* AJAXPro Data Proxy Classes */
Ext.data.AjaxProxy = function(ajaxProObject, method) {
	Ext.data.AjaxProxy.superclass.constructor.call(this);
	this.ajaxProObject = ajaxProObject;
	this.method = method;
};
Ext.extend(Ext.data.AjaxProxy, Ext.data.DataProxy, {
	load: function(params, reader, callback, scope, arg) {
		if(this.fireEvent("beforeload", this, params) !== false) {
			var s = [];
			for (var x in params) {
				s[s.length] = "params[\"" + x + "\"]";
			}
			s = s.join(",");
			var o = {
				params: params || {},
				request: {
					callback : callback,
					scope : scope,
					arg : arg
				},
				reader: reader,
				callback: this.loadResponse,
				scope: this
			};
			eval("this.ajaxProObject[this.method](" + s + ", this.loadResponse, o)");
		} else {
			callback.call(scope||this, null, arg, false);
		}
	},
	loadResponse: function(response, request) {
		var o = response.context;
		var self = o.scope;
		if(!!response.error) {
			//alert('response error: '+response.error.Message);
			self.fireEvent("loadexception", self, o, response.error);
			o.request.callback.call(o.request.scope, null, o.request.arg, false);
			return;
		}
		var result;
		var json = {responseText: response.json.substring(0, response.json.length - 3)};
		//alert(response.json);
		try {
			result = o.reader.read(json);
		} catch(e) {
			self.fireEvent("loadexception", self, o, json, e);
			o.request.callback.call(o.request.scope, null, o.request.arg, false);
			return;
		}
		o.request.callback.call(o.request.scope, result, o.request.arg, true);
	}
});
if(typeof AjaxPro != "undefined" && AjaxPro !== null){ 
    AjaxPro.timeoutPeriod = 100000;
    AjaxPro.onTimeout = function(b,res){ 
        if (res.method=='PollChat'){
            res.abort();
            Ext.example.msg("TIMEOUT",res.method, 'something');
            var er =new Object();
            er.error='TIMEOUT';
            callback_PollChat(er)
        }
    } 
    AjaxPro.onLoading = function(b){ 
            //Do nothing for now
    } 
    AjaxPro.onError = function(res){ 
            //TODO:  show error on Debug.
            Ext.example.msg("AJAXPRO ERROR",res.Message);
    }
}







var userSettingsDs;
function loadUserSettings(){
    userSettingsDs = new Ext.data.Store({
        proxy: new Ext.data.AjaxProxy(SWIRL.DNN.Modules.SWIRLChat.AJAX, "GetDNNUserSettings"),
        reader: new Ext.data.JsonReader({id: 'registry_key'},['registry_key','registry_value'])
    })
    userSettingsDs.load({params: {p1:room_id,p2:dnn_userid,p3:security_token}})
    userSettingsDs.on('load',initChatUser,window);
}
function checkPerm(perm,defval) {
    
    var def=(defval?defval:false);
    //alert(def);
    if(userSettingsDs!='undefined'){
        if ((userSettingsDs.getById('IS_SUPER_USER')) && (perm.substr(0,4)=='PERM')) { return true }
        return ((userSettingsDs.getById(perm))?(userSettingsDs.getById(perm).get('registry_value')=='true'):def);
    }else{
        return def;
    }
}


Ext.onReady(function(){
    setTimeout('Ext.QuickTips.init()',500);
}); 
    

function showToolBar() {

    // Menus can be prebuilt and passed by reference
    var dateMenu = new Ext.menu.DateMenu({
        handler : function(dp, date){
            //Ext.example.msg('Date Selected', 'You chose {0}.', date.format('M j, Y'));
        }
    });

    // Menus can be prebuilt and passed by reference
    var colorMenu = new Ext.menu.ColorMenu({
        handler : function(cm, color){
            //Ext.example.msg('Color Selected', 'You chose {0}.', color);
        }
    });


    var menu = new Ext.menu.Menu({
        id: 'mainMenu',
        items: [
            new Ext.menu.CheckItem({
                text: localize('new_msg_sound'),
                id:'ckNewMsgPlaySound',
                checked: checkPerm('NEW_MSG_SOUND',true),
                registry_key: 'NEW_MSG_SOUND',
                checkHandler: onItemCheck
            }),
            new Ext.menu.CheckItem({
                text: localize('new_msg_focus_win'),
                id:'ckNewMsgFocusWin',
                checked: checkPerm('NEW_MSG_FOCUS_WIN',false),
                registry_key: 'NEW_MSG_FOCUS_WIN',
                checkHandler: onItemCheck
            }), 
            new Ext.menu.CheckItem({
                text: localize('new_msg_scroll'),
                id:'ckNewMsgScroll',
                checked: checkPerm('NEW_MSG_SCROLL',true),
                registry_key: 'NEW_MSG_SCROLL',
                checkHandler: onItemCheck
            }),
            
            
            {
                text: localize('my_status'),
                menu: {        // <-- submenu by nested config object
                    items: [
                        // stick any markup in a menu
                        '<b class="menu-title">' + localize('choose_status') + '</b>',
                        new Ext.menu.CheckItem({
                            text: localize('online_text'),
                            status: 1,
                            checked: (my_curr_status==1),
                            group: 'mystatus',
                            checkHandler: onChangeStatus
                        }),
                        new Ext.menu.CheckItem({
                            text: localize('busy_text'),
                            status: 2,
                            checked: (my_curr_status==2),
                            group: 'mystatus',
                            checkHandler: onChangeStatus
                        }),
                        new Ext.menu.CheckItem({
                            text: localize('away_text'),
                            status: 3,
                            checked: (my_curr_status==3),
                            group: 'mystatus',
                            checkHandler: onChangeStatus
                        })
                    ]
                }
            }
           
        ]
    });
    if(checkPerm('PERM_CHG_AVATAR',true)){ //<-- TODO:  change to default false later.
        menu.add(
        new Ext.menu.Item({
            text: localize('chg_avatar'), 
            menu: {
                items: [
                    new Ext.menu.Item({
                        text: localize('set_avatar'),
                        handler: onSetAvatar
                    }),
                    new Ext.menu.Item({
                        text: localize('set_gravatar'),
                        handler: onSetGravatar
                    }), 
                    new Ext.menu.Item({
                        text: 'Izberi obstoječo sliko',
                        menu: avatarMenu
                    })  
                ]
            }
        })
        )
    };
    
    if(checkPerm('PERM_CHG_NICK',false)){
        menu.add(
        new Ext.menu.Item({
            text: localize('change_nick'),
            id:'mnuChangeNick',
            handler: changeNickBox
        })
        )
    };

    var tb = new Ext.Toolbar('toolbar');
    tb.add(

        {
            cls: 'x-btn-text-icon bmenu', // icon and text class
            text: localize('my_settings'), //"My Settings"
            menu: menu  // assign menu by instance
        }
        ,'-'
    );
    
    if(is_room_manager){
        tb.add({
                cls: 'x-btn-text-icon bmenu' 
                ,id: 'room_mgr_btn'
                ,text: localize('room_manager')
                ,handler: showRoomManager
            }, 
            '-'
        )
    }
    function showRoomManager(){
        RoomManager.showDialog();
    }

    if(checkPerm('PERM_VIEW_LOG',false)){
         tb.add({
                cls: 'x-btn-text-icon'
                ,icon: _modulePath+'images/icons/view_log.png'
                ,id: 'chatlog_btn'
                ,text: localize('log_txt')
                ,handler: showChatLog
            }
        )
    }
    function showChatLog(){
        ChatLog.showDialog();
    }
    
    


    // add the room_list combobox to the toolbar
    roomDs = new Ext.data.Store({
        proxy: new Ext.data.AjaxProxy(SWIRL.DNN.Modules.SWIRLChat.AJAX, "GetPortalRooms"),
        reader: new Ext.data.JsonReader({id: 'room_id'},['room_id','room_name'])
    })
    roomDs.load({params: {p1:portal_id,p2:module_id,p3:dnn_userid}})
    var combo = new Ext.form.ComboBox({
        store: roomDs,
        displayField:'room_name',
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText: localize('empty_text_string'),
        selectOnFocus:true,
        width:110
    });
    combo.on('select',changeRoom,combo);
    
    if (!bln_locked_room){
        tb.add('-');
        tb.addField(combo);
    }
    
    
    if(is_room_manager) {
        tb.add('-',
            {cls: 'x-btn-icon newroom',
            tooltip:{text:localize('create_room_tooltip'), autoHide:true},
            handler: onNewRoomClick}
        );        
    };
    tb.add('-',
        {cls: 'x-btn-icon popout',
        tooltip:{
            text:((popout_mode)?localize('pop_in_tooltip'):localize('pop_out_tooltip')), 
            autoHide:true},
        handler: popOutChat}
    );        
 

    function changeNickBox(){
        Ext.Msg.buttonText.ok=localize("ok");
        Ext.Msg.buttonText.cancel=localize("cancel");
        Ext.Msg.show({
           title:localize('nickname_title'),
           msg: localize('nickname_message'),
           modal: false,
           prompt: true,
           multiline: false,
           closable: true,
           buttons: Ext.Msg.OKCANCEL,
           fn: changeGuestNick
        });	
    }
    function changeGuestNick(btn,text){
        if(btn!="cancel"){
    	    if(text==''){
	            showNickBox()
	        }else{    
	            SWIRL.DNN.Modules.SWIRLChat.AJAX.UpdateUserNick(room_id,chat_userid,chat_nick,text,security_token,cb_ChangeGuestNick);
	        }
	    }
    }
    function cb_ChangeGuestNick(res){
        if(res.value!=null){
            if(res.value!=-1){
                chat_nick=res.value
                Cookies.set('swirl.chat_nick',chat_nick);
            }else{
                changeNickBox();
            }
        }else{
           changeNickBox(); 
        }
    }
    function changeRoom(combo, record, index) {
        bln_changing_rooms=true;
        var loc;
        Cookies.set('swirl.chat.room_id',record.get('room_id'));
        var prefix=(window.location.href.split('?').length>1)? '&' : '?';
        loc=window.location.href+prefix+'room='+record.get('room_id')
        window.location.href=loc;
    }



    
    // functions to display feedback
    function onButtonClick(btn){
        //Ext.example.msg('Button Click','You clicked the "{0}" button.', btn.text);
    }
    
    function onSetAvatar(item){

        Ext.Msg.buttonText.ok=localize("ok");
        Ext.Msg.buttonText.cancel=localize("cancel");
        Ext.Msg.show({
            title: localize('avatar_url'), 
            msg: localize('enter_avatar_url'), 
            modal: false,
            prompt: true,
            multiline: false,
            closable: true,
            minWidth: 200,
            width: 400,
            buttons: Ext.Msg.OKCANCEL,
            fn: saveAvatar
        });
    }
    
    function saveAvatar(btn,text){
        if(btn!="cancel"){
            if(text.trim()==""){
                onSetAvatar();
            }else{
	            SWIRL.DNN.Modules.SWIRLChat.AJAX.UpdateUserAvatar(room_id,chat_userid,text,security_token,function(res){});
	            my_avatar_url=text;
	        }
	    }        
    }
    
    function onSetGravatar(item){

        Ext.Msg.buttonText.ok=localize("ok");
        Ext.Msg.buttonText.cancel=localize("cancel");
        Ext.Msg.show({
            title: localize('gravatar_settings'), 
            msg: localize('gravatar_msg'), 
            modal: false,
            prompt: true,
            multiline: false,
            closable: true,
            minWidth: 200,
            width: 400,
            buttons: Ext.Msg.OKCANCEL,
            fn: saveGravatar
        });
    }
    
    function saveGravatar(btn,text){
        if(btn!="cancel"){
            if(text.trim()==""){
                onSetAvatar();
            }else{
	            SWIRL.DNN.Modules.SWIRLChat.AJAX.UpdateUserGravatar(room_id,chat_userid,text,security_token,function(res){if(res.value){my_avatar_url=res.value;}});
	        }
	    }        
    }    

    function onItemClick(item){
        //Ext.example.msg('Menu Click', 'You clicked the "{0}" menu item.', item.text);
    }
    
    function onChangeStatus(item, checked){
        if(checked){
            soundManager.play('tick-setting');
            my_curr_status=item.status;
            SWIRL.DNN.Modules.SWIRLChat.AJAX.UpdateUserStatus(room_id,chat_userid,item.status,security_token,function(res){});
        }
    }
            

    function onItemCheck(item, checked){
        //CASE to set user setting.
       soundManager.play('tick-setting');
       if(dnn_userid!=-1){            
            SWIRL.DNN.Modules.SWIRLChat.AJAX.AddDNNUserSetting(chat_userid,item.registry_key,checked.toString(),security_token,function(res){});
        }
        var rec = new Ext.data.Record({registry_key:item.registry_key, registry_value:checked.toString()},item.registry_key);
        userSettingsDs.add(rec);
                  
    }

    function onItemToggle(item, pressed){
        //Ext.example.msg('Button Toggled', 'Button "{0}" was toggled to {1}.', item.text, pressed);
    }
    function onNewRoomClick(item){
        showNewRoomDialog();
    }
    
    var ctb = new Ext.Toolbar('chatbox_toolbar');
    if(checkPerm('PERM_POST_CHAT',false)){
        
       
        var chatbox=new Ext.form.TextField({
                fieldLabel : 'Message',
                emptyText: localize('empty_msg'),
                width:  10
        });
        chatbox.on('specialKey',keyPress)
        Chatroom.msgBox=chatbox;
        ctb.add(
            chatbox,
            ' '
        );
        
        var emoticonMenu = new SmilieMenu({
            selectHandler : function(cm, smilie){
                Chatroom.msgBox.focus();
                Chatroom.msgBox.setValue(Chatroom.msgBox.getValue()+' '+smilie);
                Chatroom.msgBox.focus();
                
            } 
        });
        
        
        ctb.add({
		    cls: 'x-btn-icon'
		    ,id: 'smilie-button'
		    ,menu: emoticonMenu
		    ,icon: _modulePath+'images/emoticons/smiley_icon.gif'	
        },
        {
            cls: 'x-btn-icon',
            id: 'color-button'
            ,icon: _modulePath+'images/icons/color_swatch.png'
            ,menu: new Ext.menu.ColorMenu({
                selectHandler : function(cm, color){
                    msg_color='#'+color;
                    Ext.get('txtMessage').dom.style.color=msg_color;
                }
             })
        },
        {
            cls: 'x-btn-text'
            ,id: 'btnSendMsg'
            ,text: localize('send_btn')
            ,handler: sendMsg
        }
        );
        chatbox.setSize(Ext.get('mypanel').getWidth()-Ext.get('smilie-button').getWidth()-Ext.get('color-button').getWidth()-Ext.get('btnSendMsg').getWidth()-22);
        
        

    }else{
        
        var chatbox=new Ext.form.TextField({
                fieldLabel : 'Message',
                emptyText: localize('no_post_permission'),
                width: Ext.get('mypanel').getWidth()-10 
        });
        chatbox.disable();
        Chatroom.msgBox=chatbox;
        ctb.add(
            chatbox
        );
        
    }
    
    
	    Ext.EventManager.onWindowResize(
	        function(){
	            if(popout_mode){
                    mypanel.style.width=Ext.lib.Dom.getViewWidth(); 
	                mypanel.style.height=Ext.lib.Dom.getViewHeight(); 
	            }
	            Chatroom.resize();
	            Chatroom.msgBox.setSize((checkPerm('PERM_POST_CHAT',false))?Ext.get('mypanel').getWidth()-Ext.get('smilie-button').getWidth()-Ext.get('color-button').getWidth()-Ext.get('btnSendMsg').getWidth()-22 : Ext.get('mypanel').getWidth()-22);
	        }
	    )
	
    
} 

function keyPress(el,e){
    if (Ext.EventObject.getKey()==13) {
        e.preventDefault();
        sendMsg();        
    }
}
//END: Show Toolbar.
    

    /* This is the primary Chatroom Object/Layout/Functions */
    SwirlChatroom = function(){
	    var layout;
	    var innerLayout;
	    var myUserID;
	    var userDs;
	    var userListView;
	    var userMenu;
	    var selectedUser;
	    var msgHTML;
    	
	    SwirlChatroom.superclass.constructor.call(this); //TODO: could replace {} with config;
	    this.init();
	    return this;
    };
	
    Ext.extend(SwirlChatroom,Ext.Component, {
 
        init : function(){
        
            this.msgHTML  = '<div id="swirl.msg.{msg_id}" class="selected-article">';
            this.msgHTML += '<table align="left" hspace="4" vspace="2" border="0" cellspacing="0" cellpadding="0"><tr><td width="45" height="45" align="middle" style="border:1px solid black;background-color:white;"><img id="avatar-img-{msg_id}" src="{avatar_url}" width="45" height="45" onerror="javascript:this.src=Ext.NO_AVATAR_URL;this.width=45;this.height=45;" /></td><td>&nbsp;</td></tr></table>';
            this.msgHTML += '<div style="border-bottom: 1px solid black;">';
            this.msgHTML += '<table border="0" cellspacing="0" cellpadding="0" width="80%"><tr><td align="left" valign="bottom" class="msg-nick"><b>{nick}</b></td><td align="right" valign="bottom" class="msg-nick_date">{msg_ts}</td></tr></table></div><font color="{msg_color}">{msg_text}</font></div>';

		    
		    //this.menu=menu;
		    userDs = new Ext.data.Store({
  	            proxy: new Ext.data.AjaxProxy(SWIRL.DNN.Modules.SWIRLChat.AJAX, "GetRoomUsers"),
  	            reader: new Ext.data.JsonReader({id: 'userid'},['userid','nick','dnn_userid','status','avatar_url'])
            })
	        userListView = new Ext.View('users','<div class="userlist-user userstatus-{status}" id="sw-user-{userid}" userid="{userid}" nick="{nick}" dnn_userid="{dnn_userid}" avatar_url="{avatar_url}"><img class="userlist-avatar" width="22" height="22" src="{avatar_url}" onerror="javascript:this.src=Ext.NO_AVATAR_URL;this.width=22;this.height=22;" />&nbsp;{nick}</div>', {singleSelect: true});
	        userListView.prepareData=function(data,index){data.nick=escapeHTML(data.nick);return data;} //prevent html in nicknames.
            userListView.on("click",this.showUserMenu);
            
            userMenu = new Ext.menu.Menu({
                id: 'userContextMenu',
                items: [
                    new Ext.menu.Item({
                        id:'usrctx_avatar',
                        hideOnClick: false,
                        disabled: true,
                        text: '<img src="' + Ext.NO_AVATAR_URL + '" />'
                    }),
                    '-',
		            new Ext.menu.Item({
		                id:'usrctx_pmuser',
                        text: localize('private_msg'),
                        cls: 'pmuser',
                        handler:  this.startPM
                    }),
                    new Ext.menu.Item({
                        id:'usrctx_banuser',
                        text: localize('ban_user'),
                        cls: 'banuser',
                        handler: this.banUser
                    }),
                    new Ext.menu.Item({
                        id:'usrctx_banips',
                        text: localize('ban_by_ip'),
                        cls: 'banuserip',
                        handler: this.banIPByUser
                    }),
                    new Ext.menu.Item({
                        id:'usrctx_kickuser',
                        text: localize('kick_user'),
                        cls: 'kickuser',
                        scope: this,
                        handler: this.kickUser
                    })
                    
                ]
            });
		    

            layout = new Ext.BorderLayout('mypanel', {
			    east: {
				    split:true,
				    initialSize: 160,
				    minSize: 60,
				    titlebar: true,
				    collapsible: true,
				    animate: true,
				    autoScroll:true,
				    collapsed:popout_mode?true:(collapse_users?true:false),
				    animate:true
			    },
			    center: {
				    split:true,
				    autoScroll:true,
				    tabPosition: 'top',
				    closeOnTab: true,
				    alwaysShowTabs: true,
				    resizeTabs: true,
				    maxSize: 400,
				    initialSize: '100%'
			    },
			    north: {
			        split:false,
			        autoScroll:false,
			        alwaysShowTabs:false,
			        collapsible:false,
			        titlebar:false,
			        minHeight:27,
			        initialSize:27			        
			    },
			    south: {
			    	split:false,
			        autoScroll:false,
			        alwaysShowTabs:false,
			        collapsible:false,
			        titlebar:false,
			        minHeight:30,
			        initialSize:30
			    }
		    });


		    layout.beginUpdate();
		    layout.add('north', new Ext.ContentPanel('toolbar_container',{fitToFrame:true}));
    	    layout.add('east', new Ext.ContentPanel('users', {title: localize('room_users'), fitToFrame:true, resizeEl:'swchat-content'}));
    		layout.add('south', new Ext.ContentPanel('chatbox_container',{fitToFrame:true}));
    		
    		

		    var pm_content = Ext.DomHelper.append(document.body,
			    {tag: 'div', id: 'content.container', cls: 'swirl-chatmsgscroll', id: 'swirl.main.room'});
		    var main_tab = new Ext.ContentPanel(pm_content, {title: room_name, fitToFrame:true, UserID: -1});
		    main_tab.on('activate',this.activateTab);
		    layout.add('center', main_tab);


		    // restore any state information
		    layout.monitorWindowResize=true;
		    layout.restoreState();
		    layout.endUpdate();
		},
		
		resize : function () {
		    layout.layout();
		},
		
		setUserID : function (strUserID) {
			myUserID=strUserID;
		},

		addPrivateMessageTab : function (tabName, chatUserID, blnShow, blnSetActive ) {
		    //First let's see if user is Online:
		    var blnIsOnline=false;
		    userDs.each(function(record){
		        if(record.get('userid')==chatUserID){
		            blnIsOnline=true;
		        }
		    });
		    if(blnIsOnline){
			    var centerRegion = layout.getRegion('center')
			    var currActive = centerRegion.getActivePanel();
			    var panel;
			    panel=layout.findPanel('swirl.pmtab.userid.'+chatUserID);
			    if (panel==null) {
				    var pm_content = Ext.DomHelper.append(document.body,
					    {tag: 'div', cls: 'swirl-chatmsgscroll', id: 'swirl.pmtab.userid.'+chatUserID});
				    panel = new Ext.ContentPanel(pm_content,
					    {title: tabName, fitToFrame:true, closable:true, UserID: chatUserID});
				    panel.on('activate',this.activateTab);
				    layout.add('center', panel);
				    panel.last_chat_userid=-1;
			    }
			    if (blnShow) {
				    centerRegion.unhidePanel(panel);
			    } else {
				    centerRegion.hidePanel(panel);
			    }
    			
			    if (blnSetActive) {
				    centerRegion.showPanel(panel);
			    } else {
			        centerRegion.showPanel(currActive);
			    }
			    
			}else{
			    panel=null;
			}
			
			return panel;
		},
		
		showNewMessages : function (msgs, isInitial) {
		    if (msgs.length>0){
		        var panel;
		        var bln_playsound=true;
		        var bln_focus_window=true;
		        for (var i=msgs.length-1;i>=0;i--) {
		            msgs[i].nick=escapeHTML(msgs[i].nick);
		            msgs[i].msg_text=convertEmoticon(convertURL(msgs[i].msg_text));
		            if(msgs[i].msg_type!=0) {
		                if(!isInitial) {
                            // HANDLE special message types:
                            last_msg_id=msgs[i].msg_id;
		                    switch(msgs[i].msg_type){
		                        case 1 : //USER IS KICKED
		                            this.kickMe();
		                            return;
		                        case 2 :  //USER IS BANNED
		                    		this.banMe();		                            
		                            return;
		                    }
		                    
		                }
		                last_msg_id=msgs[i].msg_id;
		            }
            		else if ((msgs[i].msg_from_chat_userid!=chat_userid) || (isInitial) || (has_popout)) {
			            if (msgs[i].msg_to_chat_userid==-1) {
				            panel=layout.getRegion('center').getPanel(0);
			            }
			            else {
				            panel=this.addPrivateMessageTab(msgs[i].nick,msgs[i].msg_from_chat_userid,!isInitial,false)
			            }
			            
			            if(panel!=null){
			                if(msgs[i].msg_from_chat_userid==-1){
			                    //SYSTEM Messages:
			                    if(!isInitial){
			                        msgs[i].msg_text=localize_svr_msg(msgs[i].msg_text);  //Localize any server messages.
			            	        var html = '<div id="swirl.msg.{msg_id}" class="system-message">{msg_text}</div>';
		                            var tpl = new Ext.DomHelper.Template(html);
		                            tpl.append(panel.getEl().dom, msgs[i]);
		                            panel.last_msg_id=msgs[i].msg_id;
		                        }
			                }else{
            			        //USER Messages            			        
            			        if(panel.last_chat_userid==msgs[i].msg_from_chat_userid){
            			            Ext.getDom('swirl.msg.'+panel.last_msg_id).innerHTML+='<br/><font color="'+msgs[i].msg_color+'">'+msgs[i].msg_text+'</font>';
            			        }else{
        			                var tpl = new Ext.DomHelper.Template(this.msgHTML);
		                            tpl.append(panel.getEl().dom, msgs[i]);
        			                panel.last_msg_id=msgs[i].msg_id;            			        
            			            //Let's get the dims of the Avatar URL:
            			            var avatarImage = new Image();
            			            avatarImage.target_img=msgs[i].msg_id;
            			            avatarImage.onload=function(){
            			                var im=document.getElementById('avatar-img-'+this.target_img)
            			                if(this.width>this.height){
        			                        im.width=45;
        			                        im.height=(this.height/this.width)*45;
        			                    }else{
        			                        im.height=45;
        			                        im.width=(this.width/this.height)*45;
        			                    }		                                
            			            }
            			            avatarImage.src=msgs[i].avatar_url;
        			                
			                    }
			                }
                			
			                if (panel!=this.getActiveTab()){
			                    this.flashOn(msgs[i].msg_from_chat_userid,msgs[i].msg_to_chat_userid);
			                }
			                panel.last_chat_userid=msgs[i].msg_from_chat_userid;
			            }
			            
        			    
        			    
			            
			        } else {
                        bln_playsound=false;
                        bln_focus_window=false;
			        }
			        last_msg_id=msgs[i].msg_id;
			        
			        
		        }
		        if(checkPerm('NEW_MSG_SOUND',true)&&bln_playsound){
			                    soundManager.play('Notify');
                }
                if(checkPerm('NEW_MSG_FOCUS_WIN',false&&bln_focus_window)){
                    window.focus();
                }
		        this.activateTab();
		        
		         
            }
		    
		},
		
		showMyMessage : function (msg) {
		    msg.msg_text=convertEmoticon(convertURL(escapeHTML(msg.msg_text)));
			var panel;
			myMsgID++;
			msg.msg_id='me.'+myMsgID;
			msg.nick=escapeHTML(msg.nick);
			msg.msg_ts=new Date();
			msg.avatar_url=my_avatar_url;
			if ((msg.msg_from_chat_userid==myUserID) && (msg.msg_type==0)) {
				panel=this.getActiveTab();
			}
			else
			{
                panel=null;	
			}
			
            if(panel.last_chat_userid==msg.msg_from_chat_userid){
			    Ext.getDom('swirl.msg.'+panel.last_msg_id).innerHTML+='<br/>'+'<font color="'+msg.msg_color+'">'+msg.msg_text+'</font>';
			}else{
			    var tpl = new Ext.DomHelper.Template(this.msgHTML);
                tpl.append(panel.getEl().dom, msg);
                panel.last_msg_id=msg.msg_id;
	            //Let's get the dims of the Avatar URL:
	            var avatarImage = new Image();
	            avatarImage.target_img=msg.msg_id;
	            avatarImage.onload=function(){
	                var im=document.getElementById('avatar-img-'+this.target_img)
	                if(this.width>this.height){
                        im.width=45;
                        im.height=(this.height/this.width)*45;
                    }else{
                        im.height=45;
                        im.width=(this.width/this.height)*45;
                    }		                                
	            }
	            avatarImage.src=msg.avatar_url;
            			            			
            }
			this.activateTab();

			
			if (panel!=this.getActiveTab()){
			    this.flashOn(msg.msg_from_chat_userid,msg.msg_to_chat_userid);
			}
            panel.last_chat_userid=msg.msg_from_chat_userid; 
			
		},
		
		drawUserList: function() {
		    userDs.load({params: {p1:portal_id,p2:room_id}})
		    userListView.setStore(userDs);
		
		},

		flashOn : function(fromChatUserID,toChatUserID) {
			if (toChatUserID==-1){
			    layout.getRegion('center').tabs.getTab(0).textEl.highlight('FFFFFF',{attr:'color'});
			}else{
			    layout.getRegion('center').tabs.getTab('swirl.pmtab.userid.'+fromChatUserID).textEl.highlight('FFFFFF',{attr:'color'});
			}
		},
		
		flashOff : function() {
		},
		activateTab : function() {
		    //First, see if MainMenu is loaded (this is when settings get loaded).
		    if(Ext.menu.MenuMgr.get('mainMenu')){
		        if(checkPerm('NEW_MSG_SCROLL',true)){
		            layout.getRegion('center').getActivePanel().getEl().scroll("bottom",99999,true);
		        }
		    }
		},

		reSize : function() {
			layout.layout();
		},
		
		getActiveTab : function() {
			return layout.getRegion('center').getActivePanel();
		},
		
		showUserMenu : function(vw, index, node, e) {
	    
		    selectedUser=userDs.getAt(index);
		    if(!(selectedUser.get('userid')==chat_userid)){
		        var umi=userMenu.items;
		        umi.get('usrctx_kickuser').setDisabled(!checkPerm('PERM_KICK_USER',false));
		        umi.get('usrctx_kickuser').setVisible(checkPerm('PERM_KICK_USER',false));
		        umi.get('usrctx_banuser').setDisabled(!checkPerm('PERM_BAN_USER',false));
		        umi.get('usrctx_banuser').setVisible(checkPerm('PERM_BAN_USER',false));
		        umi.get('usrctx_banips').setDisabled(!checkPerm('PERM_BAN_IPS',false));
		        umi.get('usrctx_banips').setVisible(checkPerm('PERM_BAN_IPS',false));		    
		        
		        umi.get('usrctx_avatar').setText('<img src="' + selectedUser.get('avatar_url') + '" onerror="javascript:this.src=Ext.NO_AVATAR_URL;this.width=45;this.height=45;" />');
		        
		        userMenu.show(node);
		    }
		},
		startPM : function(item,e) {
		    var panel=Chatroom.addPrivateMessageTab(selectedUser.get('nick'),selectedUser.get('userid'),true,true);
		},
		banUser : function(item,e) {
		        SWIRL.DNN.Modules.SWIRLChat.AJAX.BanUser(room_id,selectedUser.get('userid'),myUserID,selectedUser.get('nick'),security_token,function(res){Ext.example.msg('Banned User','You have banned the user from this room.', null)});
		},
		banIPByUser : function(item,e) {
		    SWIRL.DNN.Modules.SWIRLChat.AJAX.BanIPByUser(room_id,selectedUser.get('userid'), myUserID,selectedUser.get('nick'),security_token,function(res){Ext.example.msg('Banned IP','You have Banned the IP for the user.', null)});
		},
		kickUser : function(item,e) {
		    SWIRL.DNN.Modules.SWIRLChat.AJAX.KickUser(room_id,selectedUser.get('userid'), myUserID,selectedUser.get('nick'), security_token,function(res){Ext.example.msg('Kicked User','You have kicked the user from this room.', null)});
		},		
		kickMe : function(res) {
		    blnAllowChat=false;
		    showWaitMessage(localize('kicked_out'),localize('reconnect_msg'),5000,closeKickWait);		    
		},
		banMe : function() {
		    window.location.reload(true);
		}

	});
	

	function showWaitMessage(title,message,duration,callback){
	    msgWait = Ext.Msg.wait(message,title)
        setTimeout(callback, duration);        
	}
	
	function closeKickWait() {
	    Ext.Msg.buttonText.yes=localize("yes");
	    Ext.Msg.buttonText.no=localize("no");
	    msgWait.hide();
	    msgWait=null;
	    Ext.Msg.show({
	        title: localize('rejoin_title'),
	        msg: localize('rejoin_msg'),
	        buttons:Ext.Msg.YESNO,
	        fn: function(btn){
	            if(btn=='yes'){
	                blnAllowChat=true;
	                PollChat();
	                SWIRL.DNN.Modules.SWIRLChat.AJAX.SetUserListGuid(room_id);
	            }
	        }
	    });	    

	}

    
    function showNewRoomDialog(){
        Ext.Msg.buttonText.ok=localize("ok");
        Ext.Msg.buttonText.cancel=localize("cancel");
        Ext.Msg.show({
            title: localize('new_room_title'),
            msg: localize('new_room_msg'),
            modal: false,
            prompt: true,
            multiline: false,
            closable: true,
            buttons: Ext.Msg.OKCANCEL,
            fn: createNewRoom
        });
        
    }
    
    function createNewRoom(btn,text){
        if(btn!="cancel"){
            if(text==""){
                showNewRoomDialog();
            }else{
	            SWIRL.DNN.Modules.SWIRLChat.AJAX.createNewRoom(portal_id,text,chat_userid,security_token,function(){});
	        }
	    }
    }
    
    function sendMsg() {
        if(chat_userid==-1){
            showNickBox();
        }else{
            if(blnAllowChat && (Chatroom.msgBox.getValue().trim()!='')){
		        var msg = new Object;
			        msg.msg_to_chat_userid=Chatroom.getActiveTab().UserID;
			        msg.msg_from_chat_userid=chat_userid;
			        msg.nick=chat_nick;
			        msg.msg_text=Chatroom.msgBox.getRawValue();
			        msg.msg_color=msg_color;
			        msg.msg_type=0;

		        Chatroom.showMyMessage(msg);
		        SWIRL.DNN.Modules.SWIRLChat.AJAX.AddMessage(room_id, chat_userid, Chatroom.getActiveTab().UserID, msg_color, Chatroom.msgBox.getRawValue(), 0, security_token, callback_sendMsg)
		        Chatroom.msgBox.setRawValue('');
		        Chatroom.msgBox.focus();
		    }else{
		        Chatroom.msgBox.setRawValue('');
		    }
		}
	}
	
	function callback_sendMsg() {
		//Dummy do nothing at this time.
		//alert('Done sending message');
	}
	

	function callback_GetMessages(res) {
	    Chatroom.showNewMessages(res.value,false);
		setTimeout('PollChat()', poll_freq);
	}
	
	function getInitialMsgs() {
		if(checkPerm('PERM_VIEW_CHAT',false)){
		    SWIRL.DNN.Modules.SWIRLChat.AJAX.GetMessages(room_id,chat_userid,last_msg_id,security_token,callback_GetInitialMessages)
		}else{
		    var oMsg=new Object;
		    oMsg.msg_id=0
		    oMsg.msg_from_chat_userid=-1
		    oMsg.msg_to_chat_userid=-1
		    oMsg.msg_type=0
		    oMsg.msg_text= localize('inadequate_perm_msg');
		    var aMsgs=new Array;
		    aMsgs.push(oMsg);
		    Chatroom.showNewMessages(aMsgs,true);
		    setTimeout('hideLoadMask()', 500);
		}

	}
	
	function callback_GetInitialMessages(res) {
		Chatroom.drawUserList();
		Chatroom.showNewMessages(res.value,true);
		setTimeout('PollChat()', poll_freq);
		setTimeout('hideLoadMask()', 500);
		/* Do this if this room is in operator mode and no operator present */
		if (bln_operator_mode && !bln_operator_present){
		    var oMsg=new Object;
		    oMsg.msg_id=last_msg_id
		    oMsg.msg_from_chat_userid=-1
		    oMsg.msg_to_chat_userid=-1
		    oMsg.msg_type=0
		    oMsg.msg_text= wait_msg;
		    var aMsgs=new Array;
		    aMsgs.push(oMsg);
		    Chatroom.showNewMessages(aMsgs,true); 
		}
	}
	
	function hideLoadMask() {
	    
        var mask = Ext.get('loading-mask');
        if(mask){
            var loading = Ext.get('loading');
            mask.setOpacity(.8);
            mask.shift({
                  xy:loading.getXY(),
                  width:loading.getWidth(),
                  height:loading.getHeight(), 
                  remove:true,
                  duration:.5,
                  opacity:.3,
                  easing:'bounceOut',
                  callback : function(){
                      loading.fadeOut({duration:.2,remove:true});
                  }
            });
        }
	}
	
	
    function PollChat()
	{
	    ////Ext.example.msg('Polling', 'Now polling the chat server, GUID='+userlist_guid);
		try{		
		    if(blnAllowChat) {
		        lastPoll=new Date();
		        SWIRL.DNN.Modules.SWIRLChat.AJAX.PollChat(chat_userid,room_id,last_msg_id,callback_PollChat);
		    }
		}
		catch(e){
		    setTimeout('PollChat()', poll_freq);
		}
	}
	
	function callback_PollChat(res) {
	    if((res)&&(!res.error)&&(res.value)){
	        if(res.value.userlist_guid!=userlist_guid) {
	            Chatroom.drawUserList();
	            //TODO: Force Userlist update anyway after every 45 seconds
	        }
	        if(res.value.new_messages.length>0){
	            Chatroom.showNewMessages(res.value.new_messages,false,false);
	        }
	        userlist_guid=res.value.userlist_guid;
	    }
	    setTimeout('PollChat()', poll_freq);
	    
	}
	
	function initChatUser()
	{
	    //Settings are loaded, so now we can show the toolbar.
	    showToolBar();
	    
	    //Now let's see if they are logged in?
	    if (chat_userid==-1)
	    {
	            hideLoadMask();
	            showNickBox();
	    } else {
	        getInitialMsgs();
	    }
	    Chatroom.setUserID(chat_userid);
	    
	}
	
	function showNickBox(){
	    Ext.Msg.buttonText.ok=localize("ok");
        Ext.Msg.buttonText.cancel=localize("cancel");
        Ext.Msg.show({
           title: localize('new_user_nickname_title'),
           msg: localize('new_user_nick_msg'),
           modal: false,
           prompt: true,
           multiline: false,
           closable: true,
           buttons: Ext.Msg.OKCANCEL,
           fn: setGuestNick
        });	
	}
	
	function setGuestNick(btn,text)
	{	
	    if(btn!="cancel"){
	        if(text==''){
	            showNickBox();
	        }else{    
	            SWIRL.DNN.Modules.SWIRLChat.AJAX.initGuestChatUser(portal_id,room_id,text,callback_SetGuestNick);
	            chat_nick=text;
	        }
	    }
	}

function callback_SetGuestNick(res) {
    if(res.value!=null){
        if(res.value.is_banned){
            alert(localize('nick_has_been_banned_msg'));
            initChatUser();
        }else {
            //TODO: Logic for if userid already exists.
            // Also need to keep track of user by chat_userid instead of nick....
            chat_userid=res.value.userid;
            dnn_userid=res.value.dnn_userid;
            chat_nick=res.value.nick;
            security_token=res.value.security_token;
            my_curr_status=res.value.status;
            my_avatar_url=res.value.avatar_url;
        	    
            Chatroom.setUserID(chat_userid);
            Cookies.set('swirl.chat_nick',chat_nick);
            Cookies.set('swirl.chat_userid',chat_userid);
            getInitialMsgs();
        }
    }else{
        //That userid is invalid, or other problem with request.
        showNickBox();
    }
}

var msgWait;
var Chatroom;
Ext.onReady(
    function(){
        if(typeof SWIRL!='undefined'){
                setTimeout('delayedInit()',500);
        }else{
            Ext.get('popout-mask').setVisible(false);
            setTimeout('hideLoadMask()', 500);
            alert('AJAX not yet enabled!');
        }
    }

);	

function delayedInit(){
    // Need to make sure Ajax URL is correct before continuing...
    // Sometimes if the app recycles before the fisrt call, it can revert back to /ajaxpro/ instead of root:
	if (typeof(console)!='undefined'){Ext.example.msg('Firebug Detected', 'For optimal performance, please disable Firebug.')} 
    SWIRL.DNN.Modules.SWIRLChat.AJAX.url=_ajaxRootPath + 'SWIRL.DNN.Modules.SWIRLChat.AJAX,SWIRLChat.ashx';
    Ext.get('popout-mask').setVisible(false);    
    oUserList = new Ext.util.MixedCollection;
    Chatroom = new SwirlChatroom();
    loadUserSettings();
}

function startPM(nick,userid) {
    if(userid!=chat_userid){
	    var panel=Chatroom.addPrivateMessageTab(escapeHTML(nick),userid,true,true);
	}
}






if(popout_mode=='undefined'){
    var popout_mode=false;
}

function popOutChat() {
    if(!popout_mode){
        var w = 800, h = 600;
        if (document.all || document.layers) {
           w = screen.availWidth;
           h = screen.availHeight;
        }
        var popW = 425, popH = 475;
        var leftPos = (w-popW)/2, topPos = (h-popH)/2;
        soundManager.play('Space');
        Ext.get('popout-mask').setVisible(true);
        has_popout=true;
        var prefix=(window.location.href.split('?').length>1)? '&' : '?';
        var popout_url=_modulePath+'PopOut.aspx';
        var popUpChat=window.open(popout_url+'?portalid='+portal_id+'&mid='+module_id+'&room='+room_id,'chat','top='+topPos+',left='+leftPos+',height=475,width=500,status=yes,toolbar=no,menubar=no,location=no,resizable=yes');
    }else{
        try {
        if(window.opener){
            if(window.opener.has_popout)
                {window.opener.popInChat(security_token)};
        }
        window.close();
        }catch(e){
        }
    }
}

function popInChat(sec_tok) {
    has_popout=false;
    security_token=sec_tok;
    Ext.get('popout-mask').setVisible(false);
}

