//////////////////////////////////////////
//           ajaximrpg 5.00             //
//       AJAX Instant Messenger         //
//  Copyright (c) 2006-2008, 2010-2012  //
//      Do not remove this notice       //
//////////////////////////////////////////

/**
 * Chatroom Class
 **/
var Chatroom = {
   windows: {},             // JavaScript object to store all chatroom windows
   position: 0,             // initial position to track cascading windows
   sendBoxWithFocus: null,  // current IM box that has focus

   /**
    * Create a new public chatroom.
    *
    * @arguments
    *   room - chatroom name
    *
    * @author Joshua Gross
    * @author Daniel Howard
    **/
   createChatroom: function(room) {
      Event.observe(window, 'resize', Chatroom.resizeBrowser);
      
      var winId = randomString(32)+'_chat';
      var winName = room;
      var winTitle = room;
      
      // find a good location for the window
      var winLeft = (2 + (Chatroom.position * 25)) + 'px';
      var winTop  = (2 + (Chatroom.position * 25)) + 'px';
      var winWidth = Browser.width()-300;
      var winHeight = Browser.height()-100;
   
      if (Chatroom.position++ == 2) {
         Chatroom.position = 0;
      }

      // create the actual window
      var win = new ChatWindow({id: winId, className: "dialog", title: winTitle, width: winWidth, height: winHeight, top: winTop, left: winLeft, resizable: true, draggable: true, detachable: false, minWidth: 475, minHeight: 300, showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
      win.setConstraint(true, {left: 0, right: 0, top: 0, bottom: 0});
      win.room = room;

      // create the window contents
      var html = '';
      html += '<div class="chatUserList" id="'+winId+'_userlist"><ul id="'+winId+'_ul" class="sortable box"><li style="display:none"></li></ul></div>\r\n';
      html += '<div class="chatDocList" id="'+winId+'_doclist"></div>\r\n';
      html += '<div class="rcvdMessages" id="'+winId+'_rcvd">'+getHelpMessage(user)+'</div>\r\n';
      html += '<a href="#" class="insertEmoticonLink" id="'+winId+'_insertEmoticon" onclick="Chatroom.windows[\''+winName+'\'].toggleEmoticonList();return false;" onselectstart="return false;"><img src="themes/'+theme+'/emoticons/mini_smile.gif" width="14" height="14" style="border:0;" /></a>\r\n';
      html += '<div style="overflow:auto;"><textarea class="inputText" id="'+winId+'_sendBox" onfocus="blinkerOn(false);" onkeypress="return Chatroom.windows[\''+winName+'\'].keyHandler(event);"></textarea></div>\r\n';
      win.getContent().innerHTML = html;

      // create the document tree contents
      html = '';
      html += '<ul id="'+winId+'_tree" class="tree">';
      html += '  <li>Shared<ul>';
      html += '    <li><a href="journal" title="'+hrefPath+'journal/index.php" target="_blank">Journals and logs</a></li>';
      html += '  </ul></li>';
      html += '  <li>ajaximrpg<ul>';
      html += '    <li><a href="http://www.svexpertise.com/ajaximrpg/server" title="http://www.svexpertise.com/ajaximrpg/server" target="_blank">Play</a></li>';
      html += '    <li><a href="http://ajaximrpg.sourceforge.net/" title="http://ajaximrpg.sourceforge.net/" target="_blank">Code</a></li>';
      html += '    <li><a href="http://www.twitter.com/ajaximrpg" title="http://www.twitter.com/ajaximrpg" target="_blank">Tweet</a></li>';
      html += '    <li><a href="http://groups.google.com/group/ajaximrpg" title="http://groups.google.com/group/ajaximrpg" target="_blank">Discuss</a></li>';
      html += '  </ul></li>';
      html += '</ul>';
      $(winId+"_doclist").innerHTML = html;

      new Tree($(winId+"_tree"));

      win.handleResize('', false);
      
      // show the window
      win.show();
      win.toFront();
      Windows.focusedWindow = win;
      Chatroom.windows[winName] = win;

      var plugins_a = makeArray(plugins);
      for (var p=0; p < plugins_a.length; p++) {
         if ((typeof plugins_a[p].onCreateChatroom) == 'function') {
            plugins_a[p].onCreateChatroom(room);
         }
      }

      setTimeout("$('"+winId+"_sendBox').focus();", 250);
   },
   
   /**
    * Create new private instant messaging window.
    *
    * @arguments
    *   username - the other user to IM with
    *
    * @author Joshua Gross
    * @author Benjamin Hutchins
    * @author Daniel Howard
    **/
   createMessenger: function(username) {
      var room = this.getIMRoomName(username);
      var buddyicon = typeof Roomlist.listObjects[room] == 'undefined'? 'none': Roomlist.listObjects[room].icon;
      var iconsrc = (buddyicon=='none'? defaultIcon: pathToIcons+room+'.'+buddyicon);
   
      var winId = randomString(32) + '_im';
      var winName = room;
      var winTitle = username;

      // find a good location for the window
      var winLeft = Math.round(Math.random()*(Browser.width()-360))+'px';
      var winTop  = Math.round(Math.random()*(Browser.height()-400))+'px';
      var winWidth = 320;
      var winHeight = 335;

      // create the actual window
      var win = new ChatWindow({id: winId, className: "dialog", title: winTitle, width: winWidth, height: winHeight, top: winTop, left: winLeft, resizable: true, draggable: true, detachable: imDetachable, minWidth: 320, minHeight: 150, showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
      win.setConstraint(true, {left: 0, right: 0, top: 0, bottom: 0});
      win.room = room;
    
      // create the window contents
      var html = '';
      html += '<div class="userToolbar" id="'+winId+'_userFuncs">\r\n';
      html += '<img src="themes/'+theme+'/window/addbuddy.png" class="toolbarButton" onclick="Dialogs.newBuddy();$(\'newBuddyUsername\').value=\''+winName+'\'" alt="'+Languages.get('addBuddyButton')+'" title="'+Languages.get('addBuddyButton')+'" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" />\r\n';
      html += '<img src="themes/'+theme+'/window/block.png" class="toolbarButton" onclick="Dialogs.blockBuddy(\''+username+'\');" alt="'+Languages.get('blockBuddy')+'" title="'+Languages.get('blockBuddy')+'" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" />\r\n';
      html += '</div>\r\n';
      html += (useIcons?(defaultIcon==""&&buddyicon=="none"?'':'<img src="'+iconsrc+'" id="buddyIcon_'+username+'" alt="Buddy Icon" class="buddyIcon" onmouseover="IM.buddyIconHover(this);" onmouseout="IM.buddyIconNormal(this);" />'):'')+'\r\n';
      html += '<div class="rcvdMessages" id="'+winId+'_rcvd"></div>\r\n';
      html += '<a href="#" class="insertEmoticonLink" id="'+winId+'_insertEmoticon" onclick="Chatroom.windows[\''+winName+'\'].toggleEmoticonList();return false;" onselectstart="return false;"><img src="themes/'+theme+'/emoticons/mini_smile.gif" width="14" height="14" style="border:0;" /></a>\r\n';
      html += '<div style="overflow:auto;"><textarea class="inputText" id="'+winId+'_sendBox" onfocus="blinkerOn(false);Chatroom.sendBoxWithFocus=this;" onblur="Chatroom.sendBoxWithFocus=null;" onkeypress="return Chatroom.windows[\''+winName+'\'].keyHandler(event);"></textarea></div>\r\n';
      win.getContent().innerHTML = html;
      
      $(winId+'_rcvd').setStyle({left: '5px', height: (win.getSize().height - 135) + 'px', width: (win.getSize().width - 10) + 'px'});
      $(winId+'_insertEmoticon').setStyle({top: (win.getSize().height - 65) + 'px'});
      $(winId+'_sendBox').setStyle({top: (win.getSize().height - 45) + 'px', left: '1px', width: (win.getSize().width - 14) + 'px', fontWeight: '400', fontStyle: 'normal', textDecoration: 'none'});

      win.handleResize = function(eventName, detached) {
         var win = this;
         var winId = win.getId();
         var curIM = $(winId + '_rcvd');
         $(winId + '_rcvd').setStyle({height: (win.getSize()['height'] - 135) + 'px', width:  (win.getSize()['width'] - 10) + 'px'});
         $(winId + '_insertEmoticon').setStyle({top: (win.getSize()['height'] - 65) + 'px'});
         $(winId + '_sendBox').setStyle({top: (win.getSize()['height'] - 45) + 'px', width: (win.getSize()['width'] - 16) + 'px'});
         curIM.scrollTop = curIM.scrollHeight - curIM.clientHeight + 6;
      };

      // show the window
      win.show();
      win.toFront();
      Windows.focusedWindow = win;
      Chatroom.windows[room] = win;

      var plugins_a = makeArray(plugins);
      for (var p=0; p < plugins_a.length; p++) {
         if ((typeof plugins_a[p].onCreateMessenger) == 'function') {
            plugins_a[p].onCreateMessenger(room);
         }
      }

      setTimeout("$('"+winId+"_sendBox').focus();", 250);

      if (vanishingIcons) {
         setTimeout("if ($('buddyIcon_"+room+"')){$('buddyIcon_"+room+"').hide();}", vanishingSpeed);
      }
   },

   /**
    * Process chatroom window resize
    *
    * @arguments
    *   name - chatroom name
    *
    * @author Joshua Gross
    **/
   handleResize: function(eventName, win, detached) {
      var winId = win.getId();
      if (winId == 'bl') {
         Roomlist.sizeRoomList();
      } else if (winId.indexOf('_im') != -1) {
         win.handleResize(eventName, detached);
      } else if (win.getId().indexOf('_chat') != -1) {
         win.handleResize(eventName, detached);
      } else if (win.getId().indexOf('admin-') != -1) {
         AdminWindows.handleResize(win);
      } else {
         var plugins_a = makeArray(plugins);
         for (var p=0; p < plugins_a.length; p++) {
            if ((typeof plugins_a[p].onResize) == 'function') {
               plugins_a[p].onResize(eventName, win, detached);
            }
         }
      }
   },

   /**
    * Reposition roomlist
    *
    * @author Daniel Howard
    **/
   resizeBrowser: function() {
      for (var room in Chatroom.windows) {
         if (typeof(Chatroom.windows[room].getId) != 'undefined' && typeof($(Chatroom.windows[room].getId())) != 'undefined') {
            var win = Chatroom.windows[room];
            if (win.isVisible()) {
               var l = parseInt(win.getLocation().left);
               var t = parseInt(win.getLocation().top);
               var r = l + win.getSize().width;
               var b = t + win.getSize().height;
               if (r > (Browser.width() - 250)) {
                  r = Browser.width() - 250;
               }
               if (b > (Browser.height() - 60)) {
                  b = (Browser.height() - 60);
               }
               var w = r - l;
               var h = b - t;
               win.setSize(w, h);
               Chatroom.handleResize(null, win, null);
            }
         }
      }
   },

   /**
    * @author Joshua Gross
    **/
   handleClose: function(eventName, win) {
      if ((win.getId().indexOf('_im') == -1) && (win.getId().indexOf('_chat') == -1)) {
         var plugins_a = makeArray(plugins);
         for (var p=0; p < plugins_a.length; p++) {
            if ((typeof plugins_a[p].onClose) == 'function') {
               plugins_a[p].onClose(eventName, win);
            }
         }
         return;
      }
      Chatroom.leave(win.room);
   },

   /**
    * Proccess the leaving of a chatroom
    *
    * @arguments
    *   room - room name the user is leaving
    *
    * @author Joshua Gross
    **/
   getIMRoomName: function(username) {
      var users = new Array();
      users[0] = user;
      users[1] = username;
      users.sort();
      return 'im_' + users[0] + '_' + users[1];
   },

   /**
    * Proccess the leaving of a chatroom
    *
    * @arguments
    *   room - room name the user is leaving
    *
    * @author Joshua Gross
    **/
   getIMUser: function(room) {
      var users = room.split('_');
      if (user == users[1]) {
         return users[2];
      }
      return users[1];
   },

   /**
    * Start or receive a new IM session.
    *
    * @argument
    *   u - user who started the IM
    *
    * @author Joshua Gross
    **/
   joinIM: function(u) {
      var username = (u? u: $('sendto').value);
      if (username.replace(/^\s*|\s*$/g,"").length > 0) {
         var password = 'anonymous';
         var room = this.getIMRoomName(username);
         var xhConn = new XHConn();
         xhConn.connect(pingTo, "POST", "call=joinroom&room="+encodeURIComponent(room)+"&password="+hex_md5(password), function(xh) {
            if (xh.outputText.indexOf('"') == -1) {
               alert('Chatroom.joinIM() failed: ' + xh.outputText);
            } else {
               var response = xh.outputText.evalJSON(true);
               if (typeof(Chatroom.windows[room]) == 'undefined') {
                  Chatroom.createMessenger(username);
               } else {
                  if (!Chatroom.windows[room].isVisible()) {
                     var win = Chatroom.windows[room];
                     var rcvdBox = $(win.getId() + '_rcvd');
                     if (imHistory == true) {
                        rcvdBox.innerHTML =
                           '<span class="imHistory">' +
                           rcvdBox.innerHTML.replace(new RegExp('\(' + Languages.get('autoreply') + ':\)/g'), Languages.get('autoreply') + ':').replace(/<(?![Bb][Rr] ?\/?)([^>]+)>/ig, '') +
                           '</span>\n';
                     } else {
                        rcvdBox.innerHTML = '';
                     }
                     Chatroom.windows[room].show();
                  }
               }
               if (!u) {
                  Windows.close('newIM');
               }
               var win = Chatroom.windows[room];
               var rcvdBox = $(win.getId() + '_rcvd');
               rcvdBox.innerHTML += response.html;
               Chatroom.windows[room].toFront();
               setTimeout("$('" + Chatroom.windows[room].getId() + "_sendBox').focus()", 125);
               setTimeout("scrollToBottom('" + Chatroom.windows[room].getId() + "_rcvd')", 125);
            }
         });
      } else {
         if (u) {
            alert('illegal username in Chatroom.joinIM()');
         } else {
            $('newim_error_msg').innerHTML = Languages.get('newIMProper');
         }
      }
   },

   /**
    * @author Joshua Gross
    **/
   toggleEmoticonList: function() {
      var eL = $('emoticonList');
      var eLBtn = $(this.getId() + '_insertEmoticon');
      
      $('fontsList', 'fontSizeList', 'fontColorList').invoke('hide');

      if ($('emoticonList').style.display == 'block') {
         $('emoticonList').setStyle({display: 'none'});
      } else {
         eL.setStyle({left:    Position.cumulativeOffset(eLBtn)[0] + 'px',
                      top:     (Position.cumulativeOffset(eLBtn)[1] + Element.getHeight(eLBtn) - 1) + 'px',
                      zIndex:  Windows.maxZIndex + 20,
                      display: 'block'});

         Chatroom.active = this;
      }
   },

   /**
    * Append status changes to chat window
    *
    * @author Benjamin Hutchins
    **/
   notifyUser: function(username, error) {
      if (typeof(Chatroom.windows[username]) != 'undefined') {
         if (Chatroom.windows[username].isVisible()) {
            Chatroom.windows[username].sendResult('', error);
         }
      }
   },

   /**
    * Send request to server to enter a chatroom
    *
    * @argument
    *   room - room name user is entering
    *
    * @author Joshua Gross
    **/
   join: function(room, password) {
      if ($('newRoom')) {
         if (($('roompassword').value != $('roomconfirm').value)) {
            $('newroom_error_msg').innerHTML = Languages.get('registerPasswordsMatch');
            new Effect.Shake('newRoom');
            return;
         }
      }

      var xhConn = new XHConn();
      xhConn.connect(pingTo, "POST", "call=joinroom&room="+room+"&password="+hex_md5(password), function(xh) {
         if (xh.outputText.indexOf('"') == -1) {
            switch(xh.outputText) {
               case 'already_joined':
                  $('newroom_error_msg').innerHTML = Languages.get('alreadyInRoom').replace('%1', room);
                  break;
               case 'invalid_room':
               case 'not_allowed':
                  $('newroom_error_msg').innerHTML = Languages.get('invalidRoom');
                  break;
               case 'invalid_chars':
                  $('newroom_error_msg').innerHTML = Languages.get('invalidRoomChars');
                  break;
               case 'invalid_password':
                  $('newroom_error_msg').innerHTML = Languages.get('registerPasswordsMatch');
                  break;
            }

            if ($('newRoom')) {
               new Effect.Shake('newRoom');
            } else {
               new Effect.Shake('join');
            }
         } else {
            var response = xh.outputText.evalJSON(true);
            if (!$(room + '_im')) {
               Chatroom.createChatroom(room);
            } else {
               if (!Chatroom.windows[room].isVisible()) {
                  Chatroom.windows[room].show();
                  setTimeout("scrollToBottom('" + room + "_rcvd')", 125);
               }
            }
            var users = response.users;
            var aliases = response.aliases;
            var statuses = response.statuses;
            var shares = response.shares;
            for (var s=0; s < shares.length; ++s) {
               IM.sendMessage(shares[s].sender, room, shares[s].share);
            }
            for (var i=0; i < users.length; i++) {
               if (!$(users[i]+'_'+name+'_chatUser')) {
                  Chatroom.windows[room].addUser(users[i], aliases[i], parseInt(statuses[i]));
               }
            }
            Windows.close('newRoom');
            Windows.close('join');
            Chatroom.windows[room].toFront();
            setTimeout("$('"+Chatroom.windows[room].getId()+"_sendBox').focus()", 125);
         }
      });
   },

   /**
    * Proccess the leaving of a chatroom
    *
    * @arguments
    *   room - room name the user is leaving
    *
    * @author Joshua Gross
    **/
   leave: function(room) {
      var win = Chatroom.windows[room];
      if (win.getId().indexOf('_chat') != -1) {
         win = null;
         Chatroom.windows[room] = null;
      }
      var xhConn = new XHConn();
      xhConn.connect(pingTo, "POST", "call=leaveroom&room="+room, function(xh) {
         var response = xh.outputText.evalJSON(true);
         if (response.error == '') {
            var room = response.room;
            var win = Chatroom.windows[room];
            if (win != null) {
               var rcvdBox = $(win.getId() + '_rcvd');
               var alias = getAlias(user, room);
               rcvdBox.innerHTML = rcvdBox.innerHTML + response.html;
               scrollToBottom(win.getId()+"_rcvd");
            }
         }
      });
   }
};

/**
 * Chatroom Window Class
 **/
var ChatWindow = Class.create();
Object.extend(ChatWindow.prototype, IMWindow.prototype);
Object.extend(ChatWindow.prototype, {
   curSelected: '', // current user selected from the chatroom user list

   /**
    * Add a user to the chatroom user list
    *
    * @arguments
    *   username - user to add
    *   alias - alias of user
    *
    * @author Joshua Gross
    * @author Daniel Howard
    **/
   addUser: function(username, alias, status) {
      var url = Status.getImageUrl(status);
      $(this.getId() + '_ul').innerHTML += '<li id="'+username+'_'+this.room+'_chatUser" class="buddy" onmousedown="Chatroom.windows[\'' + this.room + '\'].clickUser(\''+username+'\');return false;" onselectstart="return false;" onmouseover="Chatroom.windows[\'' + this.room + '\'].selectUser(this, \''+username+'\', true);" onmouseout="Chatroom.windows[\'' + this.room + '\'].selectUser(this, \''+username+'\', false);" ondblclick="Chatroom.windows[\'' + this.room + '\'].onUserDblClick();" style="padding:0px;"><img src="'+url+'" alt="" id="'+username+'_'+this.room+'_chatImg" />&nbsp;<span id="'+username+'_'+this.room+'_chatUserAlias">'+alias+'</span></li>';
      $(username+'_'+this.room+'_chatUser').setStyle({listStyleType: 'none'});
   },
   
   /**
    * Add a user to the chatroom user list
    *
    * @arguments
    *   username - user to add
    *
    * @author Joshua Gross
    **/
   setUserStatus: function(username, status) {
      var src = null;
      var imgObj = $(username+'_'+this.room+'_chatImg');

      if (status == Status.offline) {
         src = 'themes/' + theme + '/offline.png';
      } else if (status == Status.online) {
         src = 'themes/' + theme + '/online.png';
      } else if (status == Status.away) {
         src = 'themes/' + theme + '/away.png';
      } else if (status == Status.disconnected) {
          src = 'themes/' + theme + '/offline.png';
      }
      if ((imgObj != null) && (src != null)) {
         imgObj.src = src;
      }
   },
   
   /**
    * Remove a user from the chatroom user list
    *
    * @arguments
    *   username - user to remove
    *
    * @author Joshua Gross
    **/
   deleteUser: function(username) {
      var toDelete = $(username + '_' + this.room + '_chatUser');
      if (typeof(toDelete) !== 'undefined') {
         toDelete.parentNode.removeChild(toDelete);
      }
   },

   /**
    * Change a user on the chatroom user list
    *
    * @arguments
    *   username - user to change
    *   alias - alias of user
    *
    * @author Daniel Howard
    **/
   changeUser: function(olduser, newuser) {
      var url = $(olduser+'_'+this.room+'_chatImg').src;
      var alias = newuser;
      $(this.getId() + '_ul').innerHTML += '<li id="'+newuser+'_'+this.room+'_chatUser" class="buddy" onmousedown="Chatroom.windows[\'' + this.room + '\'].clickUser(\''+newuser+'\');return false;" onselectstart="return false;" onmouseover="Chatroom.windows[\'' + this.room + '\'].selectUser(this, \''+newuser+'\', true);" onmouseout="Chatroom.windows[\'' + this.room + '\'].selectUser(this, \''+newuser+'\', false);" ondblclick="Chatroom.windows[\'' + this.room + '\'].onUserDblClick();" style="padding:0px;"><img src="'+url+'" alt="" id="'+newuser+'_'+this.room+'_chatImg" />&nbsp;<span id="'+newuser+'_'+this.room+'_chatUserAlias">'+alias+'</span></li>';
      $(newuser+'_'+this.room+'_chatUser').setStyle({listStyleType: 'none'});
      this.deleteUser(olduser);
   },
   
   /**
    * Resize chat room.
    *
    * @arguments
    *   eventName - resize or maximize
    *   detached - detached from main window or not
    *
    * @author Joshua Gross
    * @author Daniel Howard
    **/
   handleResize: function(eventName, detached) {
      var winId = this.getId();
      $(winId+'_userlist').setStyle({height: ((this.getSize().height/2)-11)+'px'});
      $(winId+'_doclist').setStyle({top: ((this.getSize().height/2)+26)+'px', height: ((this.getSize().height/2)-10)+'px'});
      $(winId+'_rcvd').setStyle({marginTop: '5px', left: '163px', width: (this.getSize().width-170)+'px', height: (this.getSize().height-103)+'px'});
      $(winId+'_insertEmoticon').setStyle({left: '163px', top: (this.getSize().height-65)+'px'});
      $(winId+'_sendBox').setStyle({left: '160px', top: (this.getSize().height-45)+'px', width: (this.getSize().width-175)+'px'});
   },

   /**
    * Change a user on the chatroom user list
    *
    * @arguments
    *   username - user to change
    *   alias - alias of user
    *
    * @author Daniel Howard
    **/
   changeAlias: function(username, alias) {
      $(username+'_'+this.room+'_chatUserAlias').innerHTML = alias;
      $(username+'_'+this.room+'_chatUser').setStyle({listStyleType: 'none'});
   },
   
   /**
    * Process mouseover and mousout calls for the user list
    *
    * @arguments
    *   sel - element
    *   username - user's username
    *   selected - is mouse over or did it go out
    *
    * @author Joshua Gross
    **/
   selectUser: function(sel, username, selected) {
      if (selected === false) {
         if (this.curSelected != username) {
            try {
               Element.addClassName(sel, 'listNotSelected');
               Element.removeClassName(sel, 'listSelected');
               Element.removeClassName(sel, 'listHover');
            } catch(e) { }
         } else {
            Element.addClassName(sel, 'listSelected');
            Element.removeClassName(sel, 'listNotSelected');
            Element.removeClassName(sel, 'listHover');
         }
      } else {
         Element.addClassName(sel, 'listHover');
         Element.removeClassName(sel, 'listSelected');
         Element.removeClassName(sel, 'listNotSelected');
      }
   },

   /**
    * Process event when a user is clicked
    *
    * @arguments
    *   username - the username of the user clicked
    *
    * @author Josh Gross
    **/
   clickUser: function(username) {
      if (this.curSelected.length > 0) {
         try {
            var el = $(this.curSelected + '_' + this.room + '_chatUser');
            Element.addClassName(el, 'listNotSelected');
            Element.removeClassName(el, 'listSelected');
            Element.removeClassName(el, 'listHover');
         } catch(e) { }
      }

      this.curSelected = username;

      var oel = $(this.curSelected + '_' + this.room + '_chatUser');
      Element.addClassName(oel, 'listSelected');
      Element.removeClassName(oel, 'listNotSelected');
      Element.removeClassName(oel, 'listHover');
   },

   /**
    * On DoubleClick of a user from the chatroom user
    * list, start a private IM with him/her.
    *
    * @author Joshua Gross
    **/
   onUserDblClick: function() {
      if (this.curSelected.length > 0) {
         if (typeof(Chatroom.windows[this.curSelected]) == 'undefined') {
            Chatroom.joinIM(this.curSelected);
         } else {
            if (!Chatroom.windows[this.curSelected].isVisible()) {
               Chatroom.windows[this.curSelected].show();
               Chatroom.windows[this.curSelected].toFront();
               setTimeout("scrollToBottom('" + Chatroom.windows[this.curSelected].getId() + "_rcvd')", 125);
               setTimeout("$('" + Chatroom.windows[this.curSelected].getId() + "_sendBox').focus();", 250);
            } else {
               Chatroom.windows[this.curSelected].toFront();
               setTimeout("$('" + Chatroom.windows[this.curSelected].getId() + "_sendBox').focus();", 250);
            }
         }
      }
   }
});


/**
 * Class to handle the window of the chat rooms
 **/
var ChatroomList = {
   curSelected: '',  // current selected chat room

   /**
    * Get list of chat rooms that exist
    *
    * @author Joshua Gross
    **/
   get: function(applyTo) {
      var xhConn = new XHConn();
      xhConn.connect(pingTo, "POST", "call=roomlist", function(xh) {
         var rooms = xh.outputText.evalJSON(true);

         applyTo.innerHTML = '<ul id="join_room_ul" class="sortable box" style="padding: 0px; margin: 0px;">';
            
         if ((rooms.length > 0) || (predefRooms.length > 0)) {
            for (var i=0; i < predefRooms.length; i++) {
               var hexmd5 = hex_md5(predefRooms[i]);
               if (!$('chatroom_list_' + hexmd5)) {
                  applyTo.innerHTML += '<li id="chatroom_list_' + hexmd5 + '" class="buddy" style="padding-left:1%;" onmousedown="ChatroomList.clickRoom(\'' + predefRooms[i] + '\');return false;" onmouseover="ChatroomList.selectRoom(this, \'' + predefRooms[i] + '\', true);" onmouseout="ChatroomList.selectRoom(this, \'' + predefRooms[i] + '\', false);" ondblclick="Dialogs.joinRoom(\'' + predefRooms[i] + '\');">&nbsp;&nbsp;&nbsp;&nbsp;<img src="themes/' + theme + '/online.png" alt="" />&nbsp;' + predefRooms[i] + '</li>';
               }
            }
            for (var i=0; i < rooms.length; i++) {
               var hexmd5 = hex_md5(rooms[i]);
               if (!$('chatroom_list_' + hexmd5)) {
                  applyTo.innerHTML += '<li id="chatroom_list_' + hexmd5 + '" class="buddy" style="padding-left:1%;" onmousedown="ChatroomList.clickRoom(\'' + rooms[i] + '\');return false;" onmouseover="ChatroomList.selectRoom(this, \'' + rooms[i] + '\', true);" onmouseout="ChatroomList.selectRoom(this, \'' + rooms[i] + '\', false);" ondblclick="Dialogs.joinRoom(\'' + rooms[i] + '\');">&nbsp;&nbsp;&nbsp;&nbsp;<img src="themes/' + theme + '/online.png" alt="" />&nbsp;' + rooms[i] + '</li>';
               }
            }
         }
         applyTo.innerHTML += '</ul>';
         var groupname = 'Rooms';
         applyTo.innerHTML =
            '<li id="' + groupname.replace(/\s/, '_') + '_groupTop" class="groupTop" onmousedown="return false;" onselectstart="return false;" onclick="Roomlist.toggleGroup(\'' + groupname + '\');"><img id="' + groupname.replace(/\s/, '_') + '_groupArrow" src="themes/' + theme + '/window/arrow.png" />&nbsp;&nbsp;' + groupname + 
            (groupname!='Rooms' ? ' <a href="#" class="delLink" onclick="Dialogs.removeGroup(\'' + groupname + '\');return false;"><img src="themes/' + theme + '/window/smallx.png" style="border:0;" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" /></a>' : '') + '</li>' + "\n" + '<ul id="' + groupname.replace(/\s/, '_') + '_group" class="group">' + applyTo.innerHTML + '</ul>';
      });
   },

   /**
    * Process mouseover and mouseout of list items
    *
    * @arguments
    *   sel - list element
    *   roomname - chatroom name
    *   selected - did mouse go over or out
    *
    * @author Joshua Gross
    **/
   selectRoom: function(sel, roomname, selected) {
      if (selected === false) {
         if (this.curSelected != roomname) {
            try {
               Element.addClassName(sel, 'listNotSelected').removeClassName('listSelected').removeClassName('listHover');
            } catch(e) { }
         } else {
            Element.addClassName(sel, 'listSelected').removeClassName('listNotSelected').removeClassName('listHover');
         }
      } else {
         Element.addClassName(sel, 'listHover').removeClassName('listSelected').removeClassName('listNotSelected');
      }
   },

   /**
    * Process the clicking of a room
    *
    * @arguments
    *   roomname - room that was clicked
    *
    * @author Joshua Gross
    **/
   clickRoom: function(roomname) {
      if (this.curSelected.length > 0) {
         try {
            Element.addClassName($('chatroom_list_' + hex_md5(this.curSelected)), 'listNotSelected').removeClassName('listSelected').removeClassName('listHover');
         } catch(e) { }
      }
      
      this.curSelected = roomname;
      
      var edit = $('roomname');
      
      if ((edit != null) && (typeof(edit) !== 'undefined')) {
         edit.value = roomname;
      }
      
      Element.addClassName($('chatroom_list_' + hex_md5(roomname)), 'listSelected').removeClassName('listNotSelected').removeClassName('listHover');
   }
};

