///////////////////////////////////
//         ajax im 3.22          //
//    AJAX Instant Messenger     //
//   Copyright (c) 2006-2008     //
// unwieldy studios/Joshua Gross //
//  http://unwieldy.net/ajaxim/  //
//   Do not remove this notice   //
///////////////////////////////////

// See config.js for configuration options //

var user='';
var pass='';
var curSelected='';
var loggedIn=false;
var titlebarBlinker=false;
var defaultTitle=document.title;
var blinkerTimer;
var pingTimer;
var newWin, newWinRcvd;
var windowButtons;
var smilies = [];

// System Class
var System = {
   login: function(u, p) {
      var username = (u ? u : $('username').value);
      var password = (p ? p : $('password').value);
      
      var signonButton = $('signon_button');
      Event.stopObserving(signonButton, 'click', System.login);
      
      var xhConn = new XHConn();
      xhConn.connect(pingTo, "POST", "call=login&username="+username+"&password="+hex_md5(password),
         function(xh) {
            if(xh.responseText == 'invalid' || xh.responseText == 'banned') {
               $('login_error_msg').innerHTML = (xh.responseText == 'invalid' ? lang['incorrectInfo'] : lang['userBanned']);
               $('login_error_msg').show();
               
               new Effect.Shake('modal');
               
               Event.observe(signonButton, 'click', function() { login(); return false; });
            } else {
               user = username;
               pass = hex_md5(password);
               defaultTitle = document.title = document.title + ': ' + user;
               
               if(typeof(Buddylist) != 'undefined') {
                  Buddylist.create();

                  if(trim(xh.responseText).length == 0) System.logout();
      
                  var response = xh.responseText.parseJSON();

                  pingTimer = setInterval('System.ping()', pingFrequency);
                  $('modal').hide();
                  
                  if(response.blocked && response.blocked.length > 0) {
                     var blockList = response.blocked.parseJSON();
                     Buddylist.blocked = blockList;
                  } else {
                     Blocklist.blocked = {};
                  }

                  var buddy;
                  if(response.buddy && response.buddy.length > 0) {
                     var budList = response.buddy.parseJSON();
                     for(var group in budList) {
                        if(!$(group.replace(/\s/, '_')+'_group') && group != 'toJSONString') Buddylist.addGroup(group);
                        if(!Buddylist.list[group]) Buddylist.list[group] = {};
                        for(i=0; i<budList[group].length; i++) {
                              buddy = budList[group][i];
                              Buddylist.list[group][buddy.username] = {'username': buddy.username, 'blocked': (Buddylist.blocked.inArray(buddy.username) ? true : false), 'status': buddy.is_online}

                              if(typeof(Buddylist.listObjects[buddy.username]) == 'undefined') Buddylist.addBuddy(buddy.username, group);
                              $(Buddylist.listObjects[buddy.username].obj).setStyle({display: 'block'});
                              if(buddy.is_online == 0 || buddy.is_online == 50) {
                                 Buddylist.moveBuddy(buddy.username, lang['offline']);
                                 $(Buddylist.listObjects[buddy.username].img).src = 'themes/' + theme + '/offline.png';
                              } else if(buddy.is_online == 2) {
                                 Buddylist.moveBuddy(buddy.username, group);
                                 $(Buddylist.listObjects[buddy.username].img).src = 'themes/' + theme + '/away.png';            
                              } else {
                                 Buddylist.moveBuddy(buddy.username, group);
                                 $(Buddylist.listObjects[buddy.username].img).src = 'themes/' + theme + '/online.png';
                              }
                              if(Buddylist.list[group][buddy.username].blocked == true) $(Buddylist.listObjects[buddy.username].img).src = 'themes/' + theme + '/blocked.png';
                        }
                     }
                  }
               }
               
               if(response.admin == 1) {
                  var s = document.createElement('script');
                  s.src = 'js/admin.js?' + (new Date()).getTime();
                  s.type = 'text/javascript';
                  
                  document.getElementsByTagName('head').item(0).appendChild(s);
                  
                  $('blBottomToolbar').innerHTML += '<a id="admin-button" href="#" onclick="AdminWindows.userSearch();return false;" title="Admin"><img src="themes/' + theme + '/window/admin.png" alt="Admin" style="border:0;" /></a>';
                  $('admin-button').setStyle({'position':'absolute', 'left': '0', 'top': '0'});
               }
               
               Event.observe(document, 'focus', function() { blinkerOn(false); });
               Event.observe(window,   'focus', function() { blinkerOn(false); });

               Event.observe(document, 'blur', function() { blinkerOn(false); });
               Event.observe(window,   'blur', function() { blinkerOn(false); });
               
               Event.observe(document, 'keypress', function(e) {
                                                      var evt = e || window.event;
                                                      if(Windows.focusedWindow.getId().indexOf('_im') != -1 && IM.sendBoxWithFocus == null) {
                                                         var sB = $(Windows.focusedWindow.getId() + '_sendBox');
                                                         sB.focus(); sB.value += String.fromCharCode(evt.charCode);
                                                      }
                                                   });
               
               Event.stopObserving(window, 'resize', recenterModal);
               
               System.ping();
            }
         });
   },

   loginHandler: function(e) {
      var asc = document.all ? event.keyCode : e.which;
      if(asc == 13) System.login();
      return asc != 13;
   },

   logout: function() {
      if(user == '' || pass == '') return;
         
      var xmlhttp=false;
      /*@cc_on @*/
      /*@if (@_jscript_version >= 5)
       try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
       } catch (e) {
        try {
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
         xmlhttp = false;
        }
       }
      @end @*/
      if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
        xmlhttp = new XMLHttpRequest();
      }
      
      xmlhttp.open('POST', pingTo, false);
      xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xmlhttp.send('call=logout');
      
      clearTimeout(pingTimer);
   
      defaultTitle = document.title = document.title.replace(': ' + user, '');
      user = '';
      pass = '';
      
      if(typeof(Status) != 'undefined') {
         Status.state = 0;
         Status.awayMessage = '';
      }
      Element.stopObserving(window, 'resize', recenterModal);
      
      if(typeof(Buddylist) != 'undefined') Buddylist.destroy();
      
      for(var name in IM.windows) {
         if(typeof(IM.windows[name].getId) != 'undefined' && typeof($(IM.windows[name].getId())) != 'undefined') {
            try {
               if(IM.windows[name].detached)
                  IM.windows[name].popup.close();
               else
                  IM.windows[name].destroy();
            } catch(e) { }
         }
      }
      
      for(var name in Chatroom.windows) {
         if(typeof(Chatroom.windows[name].getId) != 'undefined' && typeof($(Chatroom.windows[name].getId())) != 'undefined') {
            try {
               Chatroom.windows[name].destroy();
            } catch(e) { }
         }
      }
      
      if($('admin-userSearch'))
         Windows.getWindow('admin-userSearch').destroy();
      
      Dialog.alert('<span class="dialog_long_label">' + lang['signedOff'] + '</span>',
                   { windowParameters: {className:'alert', width:alertWidth, height: 85}, 
                     okLabel: lang['reconnect'],
                     ok:function(win) {
                        try {
                           window.location.reload();
                        } catch(e) { }
                     }
                   }
      );
   },

   register: function() {
      var error = '';
      
      var registerButton = $('register_button');
      Event.stopObserving(registerButton, 'click', System.register);
      
      if(($('newpassword').value == $('newpassword2').value)) {
         if(checkEmailAddr($('newemail').value)) {
            if($('newpassword').value.length >= 6 && $('newpassword').value.length <= 20) {
               if($('newusername').value.isAlphaNumeric() && $('newusername').value.length >= 3 && $('newusername').value.length <= 16) {
                  var xhConn = new XHConn();
                  
                  var username = $('newusername').value.toLowerCase();
                  var password = $('newpassword').value;
                  var email    = $('newemail').value;
                  xhConn.connect(pingTo, "POST", "call=register&username="+username+"&password="+password+"&email="+email,
                     function(xh) {
                        switch(xh.responseText) {
                           case 'user_registered':
                              Dialog.alert('<span class="dialog_long_label">' + lang['registerSuccess'] + '</span><div style="clear:both"></div>',
                                           {windowParameters: {className:'alert', width:alertWidth},
                                            ok:function(win) { clearInputs(); Dialog.closeInfo(); Dialogs.login(); }});
                              Event.observe(registerButton, 'click', System.register);
                              return;
                           case 'username_taken':
                              error = lang['registerUsernameTaken'];
                              break;
                           case 'username_bad':
                              error = lang['registerUsernameBad'];
                              break;
                           case 'password_bad_length':
                              error = lang['registerPasswordShort'];
                              break;
                           case 'invalid_email':
                              error = lang['registerInvalidEmail'];
                              break;
                           case 'email_already_used':
                              error = lang['registerEmailTaken'];
                              break;
                           default:
                              error = lang['registerFailed'];
                        }
                        
                        $('register_error_msg').innerHTML = error;
                        $('register_error_msg').setStyle({display: 'block'});
                        
                        new Effect.Shake('modal');
                        
                        Event.observe(registerButton, 'click', System.register);
                     });
                     return;
               } else {
                  error = lang['registerUsernameBad'];
               }
            } else {
               error = lang['registerPasswordShort'];
            }
         } else {
            error = lang['registerInvalidEmail'];
         }
      } else {
         error = lang['registerPasswordsMatch'];
      }
      
      $('register_error_msg').innerHTML = error;
      $('register_error_msg').setStyle({display: 'block'});
      
      new Effect.Shake('modal');
      
      Event.observe(registerButton, 'click', System.register);
   },

   ping: function(initial) {
      var xhConn = new XHConn();

      xhConn.connect(pingTo, "POST", "call=ping&away="+(typeof(Status) != 'undefined' ? Status.state : 0)+(initial == true ? '&initial=true' : ''),
         function(xh) {
            var i;

            if(xh.responseText == 'not_logged_in') {
               System.logout();
               return;
            }     
                   
            if(trim(xh.responseText).length == 0) return;

            var response = xh.responseText.parseJSON();

            var from, data, chatroom;
            var messageCount = (typeof(response.messages) !== 'undefined' ? response.messages.length : 0);
            for(i=0; i<messageCount; i++) {
               chatroom = response.messages[i].chatroom;
               if(!chatroom) {
                  from = response.messages[i].sender;
                  who = from;
               } else {
                  var fromx = response.messages[i].sender.split('\.');
                  from = fromx[1];
                  who  = fromx[0];
               }
               data = response.messages[i].message;
               
               var winId = null;
               try { winId = window[chatroom ? 'Chatroom' : 'IM'].windows[who].getId(); } catch(e) { };
            
               if(!$(winId)) {
                  window[chatroom ? 'Chatroom' : 'IM'].create(who, who);
               } else {
                  if(!window[chatroom ? 'Chatroom' : 'IM'].windows[who].detached && !window[chatroom ? 'Chatroom' : 'IM'].windows[who].isVisible()) {
                     window[chatroom ? 'Chatroom' : 'IM'].windows[who].show();
                     setTimeout("scrollToBottom('" + window[chatroom ? 'Chatroom' : 'IM'].windows[who].getId() + "_rcvd')", 125);
                  }
               }
               
               Stamp = new Date(); var h = String(Stamp.getHours()); var m = String(Stamp.getMinutes()); var s = String(Stamp.getSeconds());
               h = (h.length > 1) ? h : "0"+h; m = (m.length > 1) ? m : "0"+m;
               var time = '[' + h + ':' + m + ']';
               
               var curIM = (!window[chatroom ? 'Chatroom' : 'IM'].windows[who].detached ? $(window[chatroom ? 'Chatroom' : 'IM'].windows[who].getId()+"_rcvd") : window[chatroom ? 'Chatroom' : 'IM'].windows[who].popup.$(window[chatroom ? 'Chatroom' : 'IM'].windows[who].getId()+"_rcvd"));
               
               data = data.replace(/(\s|\n|>|^)(\w+:\/\/[^<\s\n]+)/, '$1<a href="$2" target="_blank">$2</a>');
               data = IM.emoteReplace(data, smilies);
               
               if(data.replace(/<([^>]+)>/ig, '').indexOf('/me') == 0)
                  curIM.innerHTML += "<b class=\"user" + (from == user && chatroom ? 'A' : 'B') + "\">" + time + " <i>" + from + ' ' + data.replace(/<([^>]+)>/ig, '').replace(/\/me/, '') + "</i></b><br>\n";
               else
                  curIM.innerHTML += "<b class=\"user" + (from == user && chatroom ? 'A' : 'B') + "\">" + time + " " + from + ":</b> " + data + "<br>\n";
               curIM.scrollTop = curIM.scrollHeight - curIM.clientHeight + 6;
               
               if(!initial) {
                  if(curIM.innerHTML.toLowerCase().replace(/<\S[^>]*>/g, '').indexOf(user.toLowerCase()+': (' + lang['autoreply'].toLowerCase() + ')') == -1 && typeof(Status) != 'undefined' && Status.state == 1 && who == from) {
                     var fontName    = $(winId + '_setFont').innerHTML;
                     var fontSize    = $(winId + '_setFontSize').innerHTML;
                     var fontColor   = $(winId + '_setFontColorColor').style.backgroundColor;
                     window[chatroom ? 'Chatroom' : 'IM'].sendMessage(from, '(' + lang['autoreply'] + ') ' + Status.awayMessage, false, false, false, fontName, fontSize, fontColor);
                  }
                  
                  if(Windows.getFocusedWindow().getId() != window[chatroom ? 'Chatroom' : 'IM'].windows[who].getId() && pulsateTitles == true) {
                     new Effect.Pulsate(window[chatroom ? 'Chatroom' : 'IM'].windows[who].getId() + '_top');
                  }
            
                  if(titlebarBlinker == true && useBlinker == true) {
                     clearTimeout(blinkerTimer);
                     blinkerTimer = setTimeout("titlebarBlink('"+who+"', \""+data.replace(/\"/, '\"').replace(/<([^>]+)>/ig, '')+"\", 0, "+chatroom+")", blinkSpeed);
                  }
               }
               
               curIM = null;
            }
            
            if(response.messageCount > 0 && audioNotify == true) soundManager.play('msg_in', 1, true);
                   
            from = null; data = null;
            var group = '', buddy = '', event = '';
            var eventCount = (typeof(response.events) !== 'undefined' ? response.events.length : 0);
            
            for(i=0; i<eventCount; i++) {
               from = response.events[i].sender;
               data = response.events[i].event;
               who  = (response.events[i].recipient == user ? from : response.events[i].recipient);
               event = data.split(',');

               switch(event[0]) {
                  case 'status':
                     if(typeof(Buddylist) != 'undefined') {
                        group = response.events[i].group;
                        if(group && !$(group.replace(/\s/, '_')+'_group') && group != 'toJSONString') Buddylist.addGroup(group);
                        
                        if(typeof(Buddylist.listObjects[from]) == 'undefined') {
                           Buddylist.addBuddy(from, group);
                           Buddylist.list[group][from] = {'username': from, 'blocked': false, 'status': event[1]};
                           $(Buddylist.listObjects[from].obj).setStyle({display: 'block'});
                        }
                        
                        Buddylist.list[group][from].status = event[1];
                        
                        if(event[1] == 0 || event[1] == 50) {
                           Buddylist.moveBuddy(from, lang['offline']);
                           $(Buddylist.listObjects[from].img).src = (typeof(Buddylist.list[group][from]) !== 'undefined' && Buddylist.list[group][from].blocked ? 'themes/' + theme + '/blocked.png' : 'themes/' + theme + '/offline.png');
                        } else if(event[1] == 2) {
                           Buddylist.moveBuddy(from, group);
                           $(Buddylist.listObjects[from].img).src = (typeof(Buddylist.list[group][from]) !== 'undefined' && Buddylist.list[group][from].blocked ? 'themes/' + theme + '/blocked.png' : 'themes/' + theme + '/away.png');            
                        } else {
                           Buddylist.moveBuddy(from, group);
                           $(Buddylist.listObjects[from].img).src = (typeof(Buddylist.list[group][from]) !== 'undefined' && Buddylist.list[group][from].blocked ? 'themes/' + theme + '/blocked.png' : 'themes/' + theme + '/online.png');
                        }
                     }
                     break;
                  case 'chat':
                     var rcvdBox = $(Chatroom.windows[event[2]].getId()+"_rcvd");
                     Stamp = new Date(); var h = String(Stamp.getHours()); var m = String(Stamp.getMinutes()); var s = String(Stamp.getSeconds());
                     h = (h.length > 1) ? h : "0"+h; m = (m.length > 1) ? m : "0"+m;
                     
                     if(event[1] == 'join') {
                        if(!$(from+'_'+event[2]+'_chatUser') && typeof(Chatroom.windows[event[2]]) != 'undefined') Chatroom.windows[event[2]].addUser(from);
                        rcvdBox.innerHTML = rcvdBox.innerHTML + "<b class=\"userB\">[" + h + ":" + m + "] <i>"+from+" " + lang['hasJoined'] + "</i></b><br>";
                        scrollToBottom(Chatroom.windows[event[2]].getId()+"_rcvd");
                     } else if(event[1] == 'left') {
                        if(typeof(Chatroom.windows[event[2]]) != 'undefined') Chatroom.windows[event[2]].deleteUser(from);
                        rcvdBox.innerHTML = rcvdBox.innerHTML + "<b class=\"userB\">[" + h + ":" + m + "] <i>"+from+" " + lang['hasLeft'] + "</i></b><br>";
                        scrollToBottom(Chatroom.windows[event[2]].getId()+"_rcvd");
                     }
                     break;
               }

               event = null;
            }
            
            from = null; data = null; who = null;            
         }
      );
      
      xhConn = null;
   },

   changePass: function() {
      var currentPw = $('currentpw').value, newPw = $('newpw').value, error = '';

      if(hex_md5(currentPw) == pass) {
         if(newPw == $('confirmpw').value) {
            var xhConn = new XHConn();
            
            xhConn.connect(pingTo, "POST", "call=pwdchange&username="+user+"&password="+hex_md5(currentPw)+"&newpwd="+newPw,
               function(xh) {
                  if(xh.responseText == 'pw_changed') {
                     Dialog.closeInfo();
                     Dialog.alert('<span class="dialog_long_label">' + lang['changeSuccess'] + '</span><div style="clear:both"></div>',
                                  {windowParameters: {className:'alert', width:alertWidth, height:85},
                                   ok: function(win) { Dialog.closeInfo(); Windows.close('changePass'); setTimeout('System.logout();', 250); } });
                  } else if(xh.responseText == 'invalid_pw') {
                     error = lang['currentPassInvalid'];
                     $('currentpw').value = '';
                  } else if(xh.responseText == 'password_bad_length') {
                     error = lang['changePasswordShort'];
                     $('newpw').value = '';
                     $('confirmpw').value = '';
                  } else {
                     error = lang['changeFailed'];
                  }
               }
            );
         } else {
            error = lang['changeNoMatch'];
         }
      } else {
         error = lang['currentPassInvalid'];
      }
      if(error.length > 0) {
         $('changepass_error_msg').innerHTML = error;
      }
   },
   
   resetPass: function() {
      var xhConn = new XHConn();
      var error = '';
      
      xhConn.connect(pingTo, "POST", "call=reset&email="+encodeURIComponent($('resetto').value),
         function(xh) {
            if(xh.responseText == 'pw_reset') {
               Dialog.alert('<span class="dialog_long_label">' + lang['newPasswordEmailed'].replace('%1', $('resetto').value) + '</span><div style="clear:both"></div>',
                            {windowParameters: {className:'alert', width:alertWidth},
                             ok:function(win) { clearInputs(); Dialog.closeInfo(); Dialogs.login(); }});
            } else if(xh.responseText == 'no_email_on_record') {
               error = lang['noEmailOnRecord'];
            } else {
               error = lang['problemResetting'];
            }
            
            $('forgotpass_error_msg').innerHTML = error;
            $('forgotpass_error_msg').setStyle({display: 'block'});
            
            new Effect.Shake('modal');
         }
      );
   }
};

// Dialogs Class
var Dialogs = {
   login: function() {
      clearInputs();
      this.mainDialogShow('login');
      this.currentMainDialog = 'login';
      setTimeout("try { $('username').focus(); } catch(e) { }", 1125);
   },
   
   register: function() {
      clearInputs();
      Dialogs.mainDialogShow('register');
      this.currentMainDialog = 'register';
      setTimeout("try { $('newusername').focus(); } catch(e) { }", 505);
   },
   
   forgotPass: function() {
      clearInputs();
      Dialogs.mainDialogShow('forgotPass');
      this.currentMainDialog = 'forgotPass';
      setTimeout("try { $('resetto').focus(); } catch(e) { }", 505);
   },
   
   mainDialogShow: function(dialog) {
      if(this.currentMainDialog) Element.setStyle(this.currentMainDialog + 'Dialog', {'display': 'none'});
      Element.setStyle(dialog + 'Dialog', {'display': 'block'});
   },
   
   newIM: function() {
      var newIMWin;
       if($('newIM')) {
         Windows.getWindow('newIM').toFront();
         return;
      }  
    
      newIMWin = new Window({id: 'newIM', className: "dialog", width: 240, height: 120, resizable: false,
                             title: lang['newIM'], draggable: true, closable: true, maximizable: false, minimizable: false, detachable: false,
                             minWidth: 240, minHeight: 120, showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
      
      newIMWin.setConstraint(true, {left: 0, right: 0, top: 0, bottom: 0});
      
      newIMWin.getContent().innerHTML = '<div class="dialog_info" style="padding:3px;">' + lang['newIMPlease'] + '</div> \
                                         <span id="newim_error_msg" class="errorMsg">&nbsp;</span> \
                                         <div id="newim_box" style="padding-left:30px;width:100%;"> \
                                         <div style="display:block;float:left;margin-right:5px;padding-top:4px;">' + lang['username'] + ':</div><input type="text" style="width:120px;" id="sendto" name="sendto" onkeypress="handleInput(event, function() { IM.newIMWindow(); })" /> \
                                         </div> \
                                         <div id="newim_buttons">' +
                                         ButtonCtl.create(lang['openIM'], 'IM.newIMWindow();') +
                                         ButtonCtl.create(lang['cancel'], 'Windows.close(\'newIM\');') +
                                         '</div>';

      $('newim_buttons').setStyle({position: 'absolute',
                                   top:      '110px',
                                   left:     '25px'});

      newIMWin.setDestroyOnClose();
      newIMWin.showCenter();
      setTimeout("$('sendto').focus();", 125);
   },

   newRoom: function() {
      var newRoomWin;
      if($('newRoom')) {
         Windows.getWindow('newRoom').toFront();
         return;
      }
      
      newRoomWin = new Window({id: 'newRoom', className: "dialog", width: 240, height: 300, resizable: false,
                               title: lang['newRoom'], draggable: true, closable: true, maximizable: false, minimizable: false, detachable: false,
                               minWidth: 240, minHeight: 120, showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
      
      newRoomWin.setConstraint(true, {left: 0, right: 0, top: 0, bottom: 0});
      
      newRoomWin.getContent().innerHTML = '<div class="dialog_info" style="padding:3px;">' + lang['newRoomPlease'] + '</div> \
                                           <span id="newroom_error_msg" class="errorMsg">&nbsp;</span> \
                                           <div id="newroom_box" style="padding-left:25px;width:100%;"> \
                                           <div style="display:block;margin-right:5px;padding-top:4px;">' + lang['roomname'] + ':</div><input type="text" style="width:187px;margin-left:0px;" id="roomname" name="roomname" onkeypress="handleInput(event, function() { Chatroom.join($(\'roomname\').value); })" /> \
                                           <div id="newroom_room_list"></div> \
                                           </div> \
                                           <div id="newroom_buttons">' +
                                           ButtonCtl.create(lang['joinRoom'], 'Chatroom.join($(\'roomname\').value);') +
                                           ButtonCtl.create(lang['cancel'], 'Windows.close(\'newRoom\');') +
                                           '</div>';
      
      $('newroom_buttons').setStyle({position: 'absolute',
                                     top:      '290px',
                                     left:     '25px'});

      ChatroomList.get($('newroom_room_list'));

      newRoomWin.setDestroyOnClose();
      newRoomWin.showCenter();
      setTimeout("$('roomname').focus();", 125);
   },

   newBuddy: function() {
      var newBuddyWin;
      if($('newBuddy')) {
         Windows.getWindow('newBuddy').toFront();
         return;
      }
      
      newBuddyWin = new Window({id: 'newBuddy', className: "dialog", width: 240, height: 160, resizable: false,
                                title: lang['newBuddy'], draggable: true, closable: true, maximizable: false, minimizable: false, detachable: false,
                                minWidth: 240, minHeight: 120, showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});

      newBuddyWin.setConstraint(true, {left: 0, right: 0, top: 0, bottom: 0});

      newBuddyWin.getContent().innerHTML = '<div class="dialog_info" style="padding:3px;">' + lang['newBuddyPlease'] + '</div> \
                                            <span id="newbuddy_error_msg" class="errorMsg">&nbsp;</span> \
                                            <div id="newbuddy_box" style="padding-left:22px;width:100%;"> \
                                            <div style="display:block;float:left;margin-right:24px;padding-top:4px;">' + lang['username'] + ':</div><input type="text" style="width:110px;" id="newBuddyUsername" name="newBuddyUsername" onkeypress="handleInput(event, function() { Buddylist.addNewBuddy($(\'newBuddyUsername\').value, $(\'newBuddyGroup\').value); })" /><br /> \
                                            <div style="display:block;float:left;margin-right:5px;padding-top:4px;">' + lang['addtogroup'] + ':</div><input type="text" style="width:110px;" id="newBuddyGroup" name="newBuddyGroup" value="Friends" onfocus="this.select();" onkeypress="handleInput(event, function() { Buddylist.addNewBuddy($(\'newBuddyUsername\').value, $(\'newBuddyGroup\').value); })" /> \
                                            </div> \
                                            <div id="newbuddy_buttons">' +
                                            ButtonCtl.create(lang['add'], 'Buddylist.addNewBuddy($(\'newBuddyUsername\').value, $(\'newBuddyGroup\').value);') +
                                            ButtonCtl.create(lang['cancel'], 'Windows.close(\'newBuddy\');') +
                                            '</div>';

      $('newbuddy_buttons').setStyle({position: 'absolute',
                                      top:      '150px',
                                      left:     '25px'});

      newBuddyWin.setDestroyOnClose();
      newBuddyWin.showCenter();
      setTimeout("$('newBuddyUsername').focus();", 125);
   },

   removeBuddy: function() {
      var delBuddyWin;
      if(curSelected == '' || curSelected.length == 0)
         return;
      
      if($('delBuddy')) {
         Windows.getWindow('delBuddy').toFront();
         return;
      }
      
      delBuddyWin = new Window({id: 'delBuddy', className: "dialog", width: 240, height: 70, resizable: false,
                               title: lang['removeBuddy'], draggable: true, closable: true, maximizable: false, minimizable: false, detachable: false,
                               minWidth: 240, minHeight:70, showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
      
      delBuddyWin.setConstraint(true, {left: 0, right: 0, top: 0, bottom: 0});
      
      delBuddyWin.getContent().innerHTML = '<div class="dialog_info" style="padding:3px;">' + lang['removeBuddyAreYouSure'].replace('%1', curSelected) + '</div> \
                                            <div id="delbuddy_buttons">' +
                                            ButtonCtl.create(lang['ok'], 'Buddylist.deleteBuddy(curSelected);Windows.close(\'delBuddy\');') +
                                            ButtonCtl.create(lang['cancel'], 'Windows.close(\'delBuddy\');') +
                                            '</div>';
                                            
      $('delbuddy_buttons').setStyle({position: 'absolute',
                                      top:      '60px',
                                      left:     '25px'});
                                      
      delBuddyWin.setDestroyOnClose();
      delBuddyWin.showCenter();
   },

   blockBuddy: function(buddy) {
      var blockBuddyWin;
      
      if($('blockBuddy')) {
         Windows.getWindow('blockBuddy').toFront();
         return;
      }
      
      blockBuddyWin = new Window({id: 'blockBuddy', className: "dialog", width: 240, height: 70, resizable: false,
                               title: lang['blockBuddy'], draggable: true, closable: true, maximizable: false, minimizable: false, detachable: false,
                               minWidth: 240, minHeight:70, showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
      
      blockBuddyWin.setConstraint(true, {left: 0, right: 0, top: 0, bottom: 0});
      
      blockBuddyWin.getContent().innerHTML = '<div class="dialog_info" style="padding:3px;">' + (Buddylist.blocked.inArray(buddy) ? lang['unblockBuddyAreYouSure'].replace('%1', curSelected) : lang['blockBuddyAreYouSure'].replace('%1', curSelected)) + '</div> \
                                            <div id="blockbuddy_buttons">' +
                                            ButtonCtl.create(lang['ok'], 'Buddylist.blockBuddy(\'' + buddy + '\');Windows.close(\'blockBuddy\');') +
                                            ButtonCtl.create(lang['cancel'], 'Windows.close(\'blockBuddy\');') + 
                                            '</div>';
 
      $('blockbuddy_buttons').setStyle({position: 'absolute',
                                        top:      '60px',
                                        left:     '25px'});

      blockBuddyWin.setDestroyOnClose();
      blockBuddyWin.showCenter();
   },

   removeGroup: function(group) {
      var delGroupWin;  
      if($('delGroup')) {
         Windows.getWindow('delGroup').toFront();
         return;
      }
      
      delGroupWin = new Window({id: 'delGroup', className: "dialog", width: 240, height: 70, resizable: false,
                               title: lang['removeGroup'], draggable: true, closable: true, maximizable: false, minimizable: false, detachable: false,
                               minWidth: 240, minHeight:70, showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
      
      delGroupWin.setConstraint(true, {left: 0, right: 0, top: 0, bottom: 0});
      
      delGroupWin.getContent().innerHTML = '<div class="dialog_info" style="padding:3px;">' + lang['removeGroupAreYouSure'].replace('%1', group) + '</div> \
                                            <div id="delgroup_buttons">' +
                                            ButtonCtl.create(lang['ok'], 'Buddylist.deleteGroup(\'' + group + '\');Windows.close(\'delGroup\');') +
                                            ButtonCtl.create(lang['cancel'], 'Windows.close(\'delGroup\');') +
                                            '</div>';
                                            
      $('delgroup_buttons').setStyle({position: 'absolute',
                                      top:      '60px',
                                      left:     '25px'});

      delGroupWin.setDestroyOnClose();
      delGroupWin.showCenter();
   },

   changePass: function() {
      var changePassWin;
      if($('changePass')) {
         Windows.getWindow('changePass').toFront();
         return;
      }
      
      changePassWin = new Window({id: 'changePass', className: "dialog", width: 300, height: 160, resizable: false,
                                title: lang['changePassword'], draggable: true, closable: true, maximizable: false, minimizable: false, detachable: false,
                                minWidth: 240, minHeight: 120, showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
      
      changePassWin.setConstraint(true, {left: 0, right: 0, top: 0, bottom: 0});
      
      changePassWin.getContent().innerHTML = '<div class="dialog_info" style="padding:3px;">' + lang['changePasswordInstructions'] + '</div> \
                                            <span id="changepass_error_msg" class="errorMsg">&nbsp;</span> \
                                            <div id="changepass_box" style="padding-left:12px;width:100%;"> \
                                            <div style="display:block;float:left;margin-right:5px;padding-top:4px;">' + lang['currentPassword'] + ':</div><input type="password" style="width:110px;" id="currentpw" name="currentpw" onkeypress="handleInput(event, function() { System.changePass(); })" /><br /> \
                                            <div style="display:block;float:left;margin-right:20px;padding-top:4px;">' + lang['newPassword'] + ':</div><input type="password" style="width:110px;" id="newpw" name="newpw" onkeypress="handleInput(event, function() { changePass(); })" /> \
                                            <div style="display:block;float:left;margin-right:4px;padding-top:4px;">' + lang['confirmPassword'] + ':</div><input type="password" style="width:110px;" id="confirmpw" name="confirmpw" onkeypress="handleInput(event, function() { System.changePass(); })" /> \
                                            </div> \
                                            <div id="changepass_buttons">' +
                                            ButtonCtl.create(lang['change'], 'System.changePass();') +
                                            ButtonCtl.create(lang['cancel'], 'Windows.close(\'changePass\');') +
                                            '</div>';

      $('changepass_buttons').setStyle({position: 'absolute',
                                        top:      '150px',
                                        left:     '55px'});

      changePassWin.setDestroyOnClose();
      changePassWin.showCenter();
      setTimeout("$('currentpw').focus();", 125);
   }
};

// Buddylist Class
var Buddylist = {  
   buddyListWin: null,

   create: function() {
      Event.observe(window, 'resize', Buddylist.fixBuddyList);
      
      if(!$('bl')) {
         this.buddyListWin = new Window({id: 'bl', className: "dialog", width: 210, height: (Browser.height() - 60), zIndex: 100, resizable: true, 
                                          title: lang['buddyList'], draggable: true, closable: false, maximizable: false, detachable: false, minWidth: 205, minHeight: 150,
                                          showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
         
         this.buddyListWin.setConstraint(true, {left: 0, right: 0, top: 0, bottom: 0});
      }
      
      this.buddyListWin.getContent().innerHTML = '<div id="blTopToolbar"><span class="toolbarButton">' +
                                                  '<img id="addbuddy" src="themes/'+theme+'/window/addbuddy.png" class="toolbarButton" onclick="Dialogs.newBuddy();" alt="' + lang['addBuddyButton'] + '" title="' + lang['addBuddyButton'] + '" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" /></span>' +
                                                  '<span class="toolbarButton toolbarSpacer"><img id="removebuddy" src="themes/'+theme+'/window/removebuddy.png" class="toolbarButton" onclick="Dialogs.removeBuddy();" alt="' + lang['removeBuddyButton'] + '" title="' + lang['removeBuddyButton'] + '" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" /></span>' +
                                                  '<span class="toolbarButton"><img id="imanyone" src="themes/'+theme+'/window/imanyone.png" class="toolbarButton" onclick="Dialogs.newIM();" alt="' + lang['IMAnyoneButton'] + '" title="' + lang['IMAnyoneButton'] + '" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" /></span>' +
                                                  '<span class="toolbarButton toolbarSpacer"><img id="joinroom" src="themes/'+theme+'/window/joinroom.png" class="toolbarButton" onclick="Dialogs.newRoom();" alt="' + lang['joinChatroomButton'] + '" title="' + lang['joinChatroomButton'] + '" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);"/></span>' +
                                                  '<span class="toolbarButton"><img id="changepassword" src="themes/'+theme+'/window/changepassword.png" class="toolbarButton" onclick="Dialogs.changePass();" alt="' + lang['changePasswordButton'] + '" title="' + lang['changePasswordButton'] + '" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" /></span>' +
                                                  '<span class="toolbarButton"><img id="toggleaudio" src="themes/'+theme+'/window/audio_'+(audioNotify ? 'on' : 'off')+'.png" onclick="toggleAudio();" alt="' + lang['toggleSoundButton'] + '" title="' + lang['toggleSoundButton'] + '" /></span>' +
                                                  (typeof(Status) != 'undefined' ? '<div id="statusSettings"><input type="text" id="customStatus" onkeypress="Status.processCustomAway(event);" style="display:none" onblur="if($(\'customStatus\').style.display != \'none\') { $(\'customStatus\').style.display = \'none\'; $(\'curStatus\').style.display = \'block\'; }" /><a href="#" id="curStatus" onclick="Status.toggleStatusList();return false;">' + lang['available'] + '</a></div>' : '') +
                                                  '</div><div id="blContainer"><ul id="buddylist" class="sortable box"><li style="display:none"></li></ul></div><div id="blBottomToolbar"><a href="#" style="-moz-outline-style: none;" onclick="System.logout();return false;"><img src="themes/'+theme+'/window/signoff.png" style="border:0;" alt="' + lang['signOff'] + '" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" /></a></div>';
      Event.observe(this.buddyListWin.getContent(), 'contextmenu', function() { return false; });
      
      $('bl_minimize').setStyle({left: (this.buddyListWin.getSize()['width'] - 21) + 'px'});
      
      this.sizeBuddyList();
      
      this.buddyListWin.showCenter(false, (((Browser.height()-40) / 2) - (this.buddyListWin.getSize()['height'] / 2)), (buddyListLoc == 0 ? 10 : (Browser.width() - this.buddyListWin.getSize()['width'] - 10)));
      this.buddyListWin.toFront();
      
      this.list = {};
      this.listObjects = {};
      this.blocked = {};
   },
   
   destroy: function() {
      this.buddyListWin.destroy();
   },
   
   fixBuddyList: function() {
      if(Buddylist.buddyListWin.isVisible()) {
         Buddylist.buddyListWin.setSize(210, (Browser.height() - 60));
         Buddylist.buddyListWin.setLocation((((Browser.height()-40) / 2) - (Buddylist.buddyListWin.getSize()['height'] / 2)), (buddyListLoc == 0 ? 10 : (Browser.width() - Buddylist.buddyListWin.getSize()['width'] - 10)));
         Buddylist.sizeBuddyList();
      }
   },

   sizeBuddyList: function() {
      $('blContainer').setStyle({width:  (this.buddyListWin.getSize()['width'] - 8) + 'px',
                                 height: (this.buddyListWin.getSize()['height'] - 95) + 'px'});
                                 
      $('blBottomToolbar').setStyle({width:  (this.buddyListWin.getSize()['width'] - 8) + 'px',
                                     top:    (this.buddyListWin.getSize()['height'] - 7) + 'px'});

      $('bl_minimize').setStyle({left: (this.buddyListWin.getSize()['width'] - 21) + 'px'});                                     
   },

   addNewBuddy: function(username, groupname) {
      if(!inArray(Buddylist.list, username) && (!Buddylist.listObjects[username] || !$(Buddylist.listObjects[username].obj))) {      
         var xhConn = new XHConn();
         
         xhConn.connect(pingTo, "POST", "call=isuser&username="+username, function(xh) {
            if(xh.responseText == 'not_exists') {
               $('newbuddy_error_msg').innerHTML = lang['noSuchUser'];
            } else {
               if(!$(groupname.replace(/\s/, '_') + '_group')) {
                  Buddylist.addGroup(groupname);
                  Buddylist.list[groupname] = [];
               }
               
               Buddylist.addBuddy(username, 'Offline');
               
               if(parseInt(xh.responseText) == 0) {
                  Buddylist.moveBuddy(username, 'Offline');
                  $(Buddylist.listObjects[username].img).src = 'themes/' + theme + '/offline.png';
               } else if(parseInt(xh.responseText) == 2) {
                  Buddylist.moveBuddy(username, groupname);
                  $(Buddylist.listObjects[username].img).src = 'themes/' + theme + '/away.png';            
               } else {
                  Buddylist.moveBuddy(username, groupname);
                  $(Buddylist.listObjects[username].img).src = 'themes/' + theme + '/online.png';
               }
               
               Buddylist.list[groupname][username] = {'username': username, 'blocked': false, 'status': parseInt(xh.responseText)};
         
               var xhConn = new XHConn();
               xhConn.connect(pingTo, "POST", "call=addbuddy&username="+username+'&group='+groupname, null);
               
               Windows.close('newBuddy');
            }
         });
      } else {
         $('newbuddy_error_msg').innerHTML = lang['alreadyOnBuddylist'];
      }
   },

   addBuddy: function(username, groupname) {  
      if(!$(groupname.replace(/\s/, '_') + '_group')) this.addGroup(groupname);
      var groupList = $(groupname.replace(/\s/, '_') + '_group');
   
      var randId = Math.floor(Math.random()*1000000000);
      while($(randId + '_blItem'))
         randId = Math.floor(Math.random()*1000000000);
   
      groupList.innerHTML += '<li id="'+randId+'_blItem" class="buddy" onmousedown="Buddylist.clickBuddy(\''+username+'\');return false;" onselectstart="return false;" onmouseover="Buddylist.selectBuddy(this, \''+username+'\', true);" onmouseout="Buddylist.selectBuddy(this, \''+username+'\', false);" ondblclick="Buddylist.onBuddyDblClick();">&nbsp;&nbsp;&nbsp;&nbsp;<img src="themes/' + theme + '/online.png" alt="" id="'+randId+'_blImg" />&nbsp;'+username+'</li>';
      
      Buddylist.listObjects[username] = {};
      Buddylist.listObjects[username].obj = randId + '_blItem';
      Buddylist.listObjects[username].img = randId + '_blImg';
      
      $(Buddylist.listObjects[username].obj).setStyle({listStyleType: 'none'});
   },

   moveBuddy: function(username, groupname) {
      if(groupname == null) return;
      if($(Buddylist.listObjects[username].obj).parentNode == $(groupname.replace(/\s/, '_') + '_group')) return;
      if(!$(groupname.replace(/\s/, '_') + '_group')) this.addGroup(groupname);
      
      var group = $(groupname.replace(/\s/, '_') + '_group')
      
      group.insertBefore($(Buddylist.listObjects[username].obj), null);
   },

   addGroup: function(groupname) {
      var bList = $('buddylist');
      bList.innerHTML = (groupname=='Offline' ? bList.innerHTML : '') + '<li id="' + groupname.replace(/\s/, '_') + '_groupTop" class="groupTop" onmousedown="return false;" onselectstart="return false;" onclick="Buddylist.toggleGroup(\'' + groupname + '\');"><img id="' + groupname.replace(/\s/, '_') + '_groupArrow" src="themes/' + theme + '/window/arrow.png" />&nbsp;&nbsp;' + groupname + 
                        (groupname!='Offline' ? ' <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"></ul>' + (groupname!='Offline' ? bList.innerHTML : '');
   },
   
   deleteBuddy: function(username) {
      if(username.indexOf('_group') != -1) {
         this.deleteGroup(username.substring(0, username.length - 6));
         return;
      }
   
      var usernam = username;
   
      var ingroup = null;
      for (var group in this.list) {
         if(typeof(this.list[group][username]) !== 'undefined' && this.list[group][username].username == username) {
            ingroup = group;
            break;
         }
      }
   
      var buddyToRmv = $(Buddylist.listObjects[username].obj);

      if(typeof(buddyToRmv) !== 'undefined') {
         buddyToRmv.parentNode.removeChild(buddyToRmv);
         if(this.list[ingroup]) {
            this.list[ingroup][username] = null;

            var xhConn = new XHConn();
            xhConn.connect(pingTo, "POST", "call=removebuddy&username="+username, null);

         }
         Dialog.closeInfo();
      }
   },
   
   blockBuddy: function(username) {     
      var isBlocked = this.blocked.inArray(username);
      if(isBlocked) {
         for(var i=0; i<this.blocked.length; i++) {
            if(this.blocked[i] == username) this.blocked.splice(i, 1);
            break;
         }
      } else {
         this.blocked[this.blocked.length] = username;
      }

      var xhConn = new XHConn();      
      xhConn.connect(pingTo, "POST", "call=blockbuddy&username="+username+(isBlocked ? '&status=' + (Status.state + 1) : ''), null);

      for (var group in this.list) {
         if(typeof(this.list[group][username]) !== 'undefined' && this.list[group][username].username == username) {
            this.list[group][username].blocked = (isBlocked ? false : true);
            $(Buddylist.listObjects[username].img).src = (!isBlocked ? 'images/blocked.png' : (Buddylist.list[group][username].status == 1 ? 'themes/' + theme + '/online.png' : (Buddylist.list[group][username].status >= 2 ? 'themes/' + theme + '/away.png' : 'themes/' + theme + '/offline.png')));
            break;
         }
      }
   },

   deleteGroup: function(groupname) {
      var groupNoSpaces = groupname.replace(/\s/, '_');
      var groupToRmv = $(groupNoSpaces+"_group");
      var groupTop   = $(groupNoSpaces+"_groupTop");
         
      if(typeof(groupToRmv) !== 'undefined') {
         groupToRmv.parentNode.removeChild(groupToRmv);
         groupTop.parentNode.removeChild(groupTop);
         
         for(var i=0;i<this.list[groupname].length;i++) {
            var buddyItem = $(Buddylist.listObjects[this.list[groupname][i].username].obj);
            if(typeof(buddyItem) !== 'undefined') buddyItem.parentNode.removeChild(buddyItem);
         }
         
         delete this.list[groupname];
         
         var xhConn = new XHConn();
         xhConn.connect(pingTo, "POST", "call=removegroup&group="+groupname, null);
         
         Dialog.closeInfo();
      } else {
         $('deletebuddy_error_msg').innerHTML = lang['noSuchGroup'];
         $('deletebuddy_error_msg').show();
         Dialog.win.updateHeight();
      }
   },

   toggleGroup: function(groupname) {
      var groupList = $(groupname.replace(/\s/, '_') + '_group');
      var groupArrow = $(groupname.replace(/\s/, '_') + '_groupArrow');
      
      if(groupList.style.display != 'none') {
         groupList.hide();
         groupArrow.src = 'themes/' + theme + '/window/arrow_up.png';
      } else {
         groupList.show();
         groupArrow.src = 'themes/' + theme + '/window/arrow.png';
      }
   },

   selectBuddy: function(sel, username, selected) {
      if(selected === false) {
         if(curSelected != username) {
            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');
      }
   },

   clickBuddy: function(username) {
      if(curSelected.length > 0) {
         try {
            var el = $(Buddylist.listObjects[curSelected].obj);
            Element.addClassName(el, 'listNotSelected').removeClassName('listSelected').removeClassName('listHover');
         } catch(e) { }
      }
      
      curSelected = username;
      
      var oel = $(Buddylist.listObjects[curSelected].obj);
      Element.addClassName(oel, 'listSelected').removeClassName('listNotSelected').removeClassName('listHover');
   },

   onBuddyDblClick: function() {
      if(curSelected.length > 0) {
         if(typeof(IM.windows[curSelected]) == 'undefined') {
            IM.create(curSelected, curSelected);
         } else {
            if(IM.windows[curSelected].detached) {
               if(IM.windows[curSelected].popup.closed) {
                  IM.windows[curSelected] = IM.windows[curSelected].old;
                  IM.windows[curSelected].show();
               } else {
                  IM.windows[curSelected].popup.focus();
               }
            } else if(!IM.windows[curSelected].isVisible()) {
               IM.windows[curSelected].show();
               IM.windows[curSelected].toFront();
               setTimeout("scrollToBottom('" + IM.windows[curSelected].getId() + "_rcvd')", 125);
               setTimeout("$('" + IM.windows[curSelected].getId() + "_sendBox').focus();", 250);
            } else {
               IM.windows[curSelected].toFront();
               setTimeout("$('" + IM.windows[curSelected].getId() + "_sendBox').focus();", 250);
            }
         }
      }
   }
};

// Status Class
var Status = {
   state: 0,
   awayMessage: '',
   
   set: function(status, away_msg) {
      if(status == 1) { // away
         this.state = 1;
         this.awayMessage = away_msg;
         $('curStatus').innerHTML = this.awayMessage.substring(0, 30) + (this.awayMessage.length > 30 ? '...' : '');
      } else { // back
         this.state = status; // 0 for avail, 99 for "friends only", 49 for "invisible"
         this.awayMessage = '';
         $('curStatus').innerHTML = away_msg;
      }
      
      $('statusList').hide();
   },

   customAway: function() {
      $('curStatus').hide();
      $('customStatus').show().focus();
   },

   processCustomAway: function(e) {
      var asc = document.all ? event.keyCode : e.which;
      
      if(asc == 13) {
         state = 1;
         awayMessage = $('customStatus').value;
         $('curStatus').innerHTML = awayMessage.substring(0, 30) + (awayMessage.length > 30 ? '...' : '');
         $('curStatus').show();
         $('customStatus').hide();
         
         Status.set(1, awayMessage);
      }
      return asc != 13;
   },

   toggleStatusList: function() {
      var sL = $('statusList');
      
      if(sL.style.display == 'block') {
         sL.hide();
         if(sL.style.zIndex > Windows.maxZIndex) Windows.maxZIndex = sL.style.zIndex;
      } else {
         Element.setStyle(sL, {left:    parseInt(Buddylist.buddyListWin.getLocation()['left']) + $('statusSettings').offsetLeft + $('blTopToolbar').offsetLeft + 'px',
                               top:     parseInt(Buddylist.buddyListWin.getLocation()['top']) + $('statusSettings').offsetTop + $('blTopToolbar').offsetTop + $('statusSettings').offsetHeight + 'px',
                               zIndex:  Windows.maxZIndex + 20,
                               display: 'block'});
      }
   }
};

// IM Class
var IM = {
   windows: {},
   sendBoxWithFocus: null,

   create: function(name, imTitle) {
      var imLeft = Math.round(Math.random()*(Browser.width()-360))+'px';
      var imTop  = Math.round(Math.random()*(Browser.height()-400))+'px';
   
      var winId = randomString(32) + '_im';
   
      this.windows[name] = new IMWindow({id: winId, className: "dialog", width: 320, height: 335, top: imTop, left: imLeft,
                                                                   resizable: true, title: imTitle, draggable: true, detachable: imDetachable, minWidth: 320, minHeight: 150,
                                                                   showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
      
      this.windows[name].setConstraint(true, {left: 0, right: 0, top: 0, bottom: 0});
      
      this.windows[name].getContent().innerHTML = '<div class="userToolbar" id="' + winId + '_userFuncs">' +
                                                  '<img src="themes/'+theme+'/window/addbuddy.png" class="toolbarButton" onclick="Dialogs.newBuddy();$(\'newBuddyUsername\').value=\'' + name + '\'" alt="' + lang['addBuddyButton'] + '" title="' + lang['addBuddyButton'] + '" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" /> ' +
                                                  '<img src="themes/'+theme+'/window/block.png" class="toolbarButton" onclick="Dialogs.blockBuddy(\'' + name + '\');" alt="" title="" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" />' +
                                                  '</div>' +
                                                  '<div class="rcvdMessages" id="' + winId + '_rcvd"></div>' + "\n" +
                                                  '<div class="imToolbar" id="' + winId + '_toolbar" onmousemove="return false;" onselectstart="return false;"><img src="themes/'+theme+'/window/bold_off.png" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onclick="IM.windows[\'' + name + '\'].toggleBold();" onmousedown="return false;" alt="' + lang['bold'] + '" id="' + winId + '_bold" /> ' +
                                                  '<img src="themes/'+theme+'/window/italic_off.png" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onclick="IM.windows[\'' + name + '\'].toggleItalic();" onmousedown="return false;" alt="' + lang['italic'] + '" id="' + winId + '_italic" /> '+
                                                  '<img src="themes/'+theme+'/window/underline_off.png" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onclick="IM.windows[\'' + name + '\'].toggleUnderline();" onmousedown="return false;" alt="' + lang['underline'] + '" id="' + winId + '_underline" /></div>' +
                                                  ' <a href="#" class="setFontLink" id="' + winId + '_setFont" onclick="IM.windows[\'' + name + '\'].toggleFontList();return false;" onselectstart="return false;">Tahoma</a>' +
                                                  ' <a href="#" class="setFontSizeLink" id="' + winId + '_setFontSize" onclick="IM.windows[\'' + name + '\'].toggleFontSizeList();return false;" onselectstart="return false;">12</a>' +
                                                  ' <a href="#" class="setFontColorLink" id="' + winId + '_setFontColor" onclick="IM.windows[\'' + name + '\'].toggleFontColorList();return false;" onselectstart="return false;"><div id="' + winId + '_setFontColorColor" style="width:14px;height:14px;display:block;"></div></a>' +
                                                  ' <a href="#" class="insertEmoticonLink" id="' + winId + '_insertEmoticon" onclick="IM.windows[\'' + name + '\'].toggleEmoticonList();return false;" onselectstart="return false;"><img src="themes/' + theme + '/emoticons/mini_smile.gif" width="14" height="14" style="border:0;" /></a>' +
                                                  "\n" + '<div style="overflow:auto;"><textarea class="inputText" id="' + winId + '_sendBox" onfocus="blinkerOn(false);IM.sendBoxWithFocus=this;" onblur="IM.sendBoxWithFocus=null;" onkeypress="return IM.windows[\'' + name + '\'].keyHandler(event);"></textarea></div>';
      
      this.windows[name].setUsername(name);
      
      $(winId + '_rcvd').setStyle({height: (this.windows[name].getSize().height - 135) + 'px',
                                   width: (this.windows[name].getSize().width - 10) + 'px'});
   
      $(winId + '_toolbar').setStyle({top: (this.windows[name].getSize().height - 73) + 'px',
                                      width: (this.windows[name].getSize().width - 10) + 'px'});
      
      $(winId + '_setFont').setStyle({top: (this.windows[name].getSize().height - 65) + 'px'});
      
      $(winId + '_setFontSize').setStyle({top: (this.windows[name].getSize().height - 65) + 'px'});
      
      $(winId + '_setFontColor').setStyle({top: (this.windows[name].getSize().height - 65) + 'px'});
      
      $(winId + '_setFontColorColor').setStyle({backgroundColor: '#000'});
      
      $(winId + '_insertEmoticon').setStyle({top: (this.windows[name].getSize().height - 65) + 'px'});
   
      $(winId + '_sendBox').setStyle({top: (this.windows[name].getSize().height - 45) + 'px',
                                      left: '2px',
                                      width: (this.windows[name].getSize().width - 16) + 'px',
                                      fontWeight: '400',
                                      fontStyle: 'normal',
                                      textDecoration: 'none'});
   
      this.windows[name].show();
      this.windows[name].toFront();
      Windows.focusedWindow = this.windows[name];
      setTimeout("$('"+winId+"_sendBox').focus();", 250);
   },

   sendMessage: function(username, message, chatroom, isBold, isItalic, isUnderline, fontName, fontSize, fontColor) {
      var xhConn = new XHConn();

      xhConn.connect(pingTo, "POST", "call=send&recipient="+username+"&chatroom="+chatroom+"&bold="+isBold+"&italic="+isItalic+"&underline="+isUnderline+"&font="+fontName+"&fontsize="+fontSize+"&fontcolor="+fontColor+"&message="+encodeURIComponent(message),
         function(xh) {
            var error = null;
         
            switch(xh.responseText) {
               case 'sent':
                  error = null;
               break;
               
               case 'sent_offline':
                  error = lang['notifySentButOffline'];
               break;
               
               case 'not_online':
                  error = lang['errorNotLoggedIn'];
               break;
               
               case 'too_long':
                  error = lang['errorMsgTooLong'];
               break;
               
               case 'not_logged_in':
                  System.logout();
               break;
               
               default:
                  error = lang['errorUnknown'];
               break;
            }

            if(chatroom == 'true')
               Chatroom.windows[username].sendResult(message, isBold, isItalic, isUnderline, fontName, fontSize, fontColor, error);
            else
               IM.windows[username].sendResult(message, isBold, isItalic, isUnderline, fontName, fontSize, fontColor, error);
         }
      );

      if(audioNotify == true) soundManager.play('msg_out', 1, true);
   },

   emoteReplace: function(str, itemsList) {
      var r;
      for(var s in itemsList) {
         if(str.indexOf(s) > -1)
            str = str.replace(new RegExp(regExpEscape(s), 'g'), '<img src="themes/' + theme + '/emoticons/' + itemsList[s] + '" alt="' + itemsList[s] + '" title="' + s + '" />');
      }
      return str;
   },

   newIMWindow: function() {
      if($('sendto').value.replace(/^\s*|\s*$/g,"").length > 0) {
         var toWhom = $('sendto').value;
   
         if(typeof(this.windows[toWhom]) == 'undefined') {
            this.create(toWhom, toWhom);
         } else {
            if(!this.windows[toWhom].isVisible()) {
               this.windows[toWhom].show();
               setTimeout("scrollToBottom('" + this.windows[toWhom].getId() + "_rcvd')", 125);
            }
         }
         
         Windows.close('newIM');
         this.windows[toWhom].toFront();
         setTimeout("$('" + this.windows[toWhom].getId() + "_sendBox').focus()", 125);
      } else {
         $('newim_error_msg').innerHTML = lang['newIMProper'];
      }
   },

   handleResize: function(eventName, win) {
      if(win.getId() == 'bl') {
         Buddylist.sizeBuddyList();
      } else if(win.getId().indexOf('_im') != -1) {
         var name = win.getId();
         var curIM = $(name + '_rcvd');
         
         curIM.setStyle({height: (win.getSize()['height'] - 135) + 'px',
                         width:  (win.getSize()['width'] - 10) + 'px'});
         
         $(name + '_toolbar').setStyle({top: (win.getSize()['height'] - 73) + 'px',
                                        width: (win.getSize()['width'] - 10) + 'px'});
         
         $(name + '_setFont').setStyle({top: (win.getSize()['height'] - 65) + 'px'});         
         
         $(name + '_setFontSize').setStyle({top: (win.getSize()['height'] - 65) + 'px'});
         
         $(name + '_setFontColor').setStyle({top: (win.getSize()['height'] - 65) + 'px'});
      
         $(name + '_insertEmoticon').setStyle({top: (win.getSize()['height'] - 65) + 'px'});
         
         $(name + '_sendBox').setStyle({top: (win.getSize()['height'] - 45) + 'px',
                                        width: (win.getSize()['width'] - 16) + 'px'});
         
         curIM.scrollTop = curIM.scrollHeight - curIM.clientHeight + 6;
      } else if(win.getId().indexOf('_chat') != -1) {
         Chatroom.handleResize(win.room);
      } else if(win.getId().indexOf('admin-') != -1) {
         AdminWindows.handleResize(win);
      }
   },
   
   handleClose: function(eventName, win) {
      if(win.getId().indexOf('_im') == -1 && win.getId().indexOf('_chat') == -1) return;
   
      if(typeof(win.room) !== 'undefined') Chatroom.leave(win.room);
           
      var rcvdBox = $(win.getId() + '_rcvd');
      if(imHistory == true) {
         rcvdBox.innerHTML = '<span class="imHistory">' +
                             rcvdBox.innerHTML.replace(new RegExp('\(' + lang['autoreply'] + ':\)/g'), lang['autoreply'] + ':').replace(/<(?![Bb][Rr] ?\/?)([^>]+)>/ig, '') +
                             "</span>\n";
      } else {
         rcvdBox.innerHTML = '';
      }
   },

   handleMinimize: function(eventName, win) {
      if(win.getId().indexOf('_im') == -1) return;
      
      var curIM = $(win.getId() + '_rcvd');
      curIM.scrollTop = curIM.scrollHeight - curIM.clientHeight + 6;
   }
}

var IMWindow = Class.create();
Object.extend(IMWindow.prototype, Window.prototype);

Object.extend(IMWindow.prototype, {
   setUsername: function(username) {
      this.username = username;
   },

   send: function() {
      var winId = this.getId();
      var sendBox = $(winId + '_sendBox');
   
      var isBold      = (sendBox.style.fontWeight == '400' ? 'false' : 'true');
      var isItalic    = (sendBox.style.fontStyle == 'normal' ? 'false' : 'true');
      var isUnderline = (sendBox.style.textDecoration == 'none' ? 'false' : 'true');
      var fontName    = $(winId + '_setFont').innerHTML;
      var fontSize    = $(winId + '_setFontSize').innerHTML;
      var fontColor   = $(winId + '_setFontColorColor').style.backgroundColor;
      var chatroom    = (typeof(this.room) !== 'undefined' ? 'true' : 'false');

      if(trim(sendBox.value).length > 0) {
         var message = sendBox.value;
         sendBox.value = '';
         IM.sendMessage((chatroom == 'true' ? this.room : this.username), message.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&/g, "<amp>"), chatroom, isBold, isItalic, isUnderline, fontName, fontSize, fontColor);
      }
      
      scrollToBottom(winId + '_rcvd');
      sendBox.focus();
   },

   sendResult: function(message, isBold, isItalic, isUnderline, fontName, fontSize, fontColor, result) {
      var winId = this.getId();
      var sendBox = $(winId + '_sendBox');
      
      if(result != null) {
         var rcvdBox = $(winId + '_rcvd');
         rcvdBox.innerHTML = rcvdBox.innerHTML + '<span class="imError">' + result + '</span><br>';
      }
      
      message = message.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/<([^>]+)>/ig, '').replace(/(\s|\n|>|^)(\w+:\/\/[^<\s\n]+)/, '$1<a href="$2" target="_blank">$2</a>');
      message = IM.emoteReplace(message, smilies);
      var rcvdBox = $(winId + '_rcvd');
      Stamp = new Date(); var h = String(Stamp.getHours()); var m = String(Stamp.getMinutes()); var s = String(Stamp.getSeconds());
      h = (h.length > 1) ? h : "0"+h; m = (m.length > 1) ? m : "0"+m;
      if(message.replace(/<([^>]+)>/ig, '').indexOf('/me') == 0)
         rcvdBox.innerHTML = rcvdBox.innerHTML + "<b class=\"userA\">[" + h + ":" + m + "] <i>" + user + ' ' + message.replace(/<([^>]+)>/ig, '').replace(/\/me/, '') + "</i></b><br>\n";
      else
         rcvdBox.innerHTML = rcvdBox.innerHTML + "<b class=\"userA\">[" + h + ":" + m + "] " + user + ":</b> <span style=\"font-family:" + fontName + ",sans-serif;font-size:" + fontSize + "px;color:" + fontColor + ";\">" + (isBold == 'true' ? "<b>" : "") + (isItalic == 'true' ? "<i>" : "") + (isUnderline == 'true' ? "<u>" : "") + message + (isBold == 'true' ? "</b>" : "") + (isItalic == 'true' ? "</i>" : "") + (isUnderline == 'true' ? "</u>" : "") + "</span><br>\n";
   
      scrollToBottom(winId + '_rcvd');
   },
   
   toggleBold: function() {
      var winId = this.getId();
      var sendBox = $(winId + '_sendBox');
         
      sendBox.hide(); // horrah weird Opera 9 input refresh!
      if(sendBox.style.fontWeight == '400') {
         $(winId + '_bold').src = 'themes/' + theme + '/window/bold_on.png';
         sendBox.setStyle({fontWeight: '700'});
      } else {
         sendBox.setStyle({fontWeight: '400'});
         $(winId + '_bold').src = 'themes/' + theme + '/window/bold_off.png';
      }
      sendBox.show(); // horrah weird Opera 9 input refresh!
      setTimeout("$('" + winId + "_sendBox').focus();", 125);
   },
      
   toggleItalic: function() {
      var winId = this.getId();
      var sendBox = $(winId + '_sendBox');
      
      sendBox.hide(); // horrah weird Opera 9 input refresh!
      if(sendBox.style.fontStyle == 'normal') {
         sendBox.setStyle({fontStyle: 'italic'});
         $(winId + '_italic').src = 'themes/' + theme + '/window/italic_on.png';
      } else {
         sendBox.setStyle({fontStyle: 'normal'});
         $(winId + '_italic').src = 'themes/' + theme + '/window/italic_off.png';
      }
      sendBox.show(); // horrah weird Opera 9 input refresh!
      setTimeout("$('" + winId + "_sendBox').focus();", 125);
   },
   
   toggleUnderline: function() {
      var winId = this.getId();
      var sendBox = $(winId + '_sendBox');
      
      sendBox.hide(); // horrah weird Opera 9 input refresh!
      if(sendBox.style.textDecoration == 'none') {
         sendBox.setStyle({textDecoration: 'underline'});
         $(winId + '_underline').src = 'themes/' + theme + '/window/underline_on.png';
      } else {
         sendBox.setStyle({textDecoration: 'none'});
         $(winId + '_underline').src = 'themes/' + theme + '/window/underline_off.png';
      }
      sendBox.show(); // horrah weird Opera 9 input refresh!
      setTimeout("$('" + winId + "_sendBox').focus();", 125);
   },

   toggleFontList: function() {
      var fL = $('fontsList');
      var fLBtn = $(this.getId() + '_setFont');
      
      $('emoticonList', 'fontColorList', 'fontSizeList').invoke('hide');

      if($('fontsList').style.display == 'block') {
         fL.hide();
      } else {
         fL.setStyle({left:    Position.cumulativeOffset(fLBtn)[0] + 'px',
                      top:     (Position.cumulativeOffset(fLBtn)[1] + Element.getHeight(fLBtn) - 1) + 'px',
                      zIndex:  Windows.maxZIndex + 20,
                      display: 'block'});
                      
         IM.active = this;
      }
   },
   
   toggleFontSizeList: function() {
      var fsL = $('fontSizeList');
      var fsLBtn = $(this.getId() + '_setFontSize');
      
      $('emoticonList', 'fontsList', 'fontColorList').invoke('hide');

      if($('fontSizeList').style.display == 'block') {
         $('fontSizeList').setStyle({display: 'none'});
      } else {
         fsL.setStyle({left:    Position.cumulativeOffset(fsLBtn)[0] + 'px',
                       top:     (Position.cumulativeOffset(fsLBtn)[1] + Element.getHeight(fsLBtn) - 1) + 'px',
                       zIndex:  Windows.maxZIndex + 20,
                       display: 'block'});

       IM.active = this;
      }
   },
   
   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'});

         IM.active = this;
      }
   },
   
   toggleFontColorList: function() {
      var fcL = $('fontColorList');
      var fcLBtn = $(this.getId() + '_setFontColor');
      
      $('fontsList', 'fontSizeList', 'emoticonList').invoke('hide');

      if($('fontColorList').style.display == 'block') {
         $('fontColorList').setStyle({display: 'none'});
      } else {
         fcL.setStyle({left:    Position.cumulativeOffset(fcLBtn)[0] + 'px',
                       top:     (Position.cumulativeOffset(fcLBtn)[1] + Element.getHeight(fcLBtn) - 1) + 'px',
                       zIndex:  Windows.maxZIndex + 20,
                       display: 'block'});

         IM.active = this;
      }
   },

   setFont: function(fontname) {
      var winId = this.getId();
      var sendBox = $(winId + '_sendBox');

      sendBox.hide();
      sendBox.setStyle({fontFamily: fontname + ', sans-serif'});
      sendBox.show();
      
      $(winId + '_setFont').innerHTML = fontname;
      setTimeout("$('" + winId + "_sendBox').focus();", 125);
      this.toggleFontList('');
   },
   
   setFontSize: function(size) {
      var winId = this.getId();
      var sendBox = $(winId + '_sendBox');
      
      sendBox.hide();
      sendBox.setStyle({fontSize: size + 'px'});
      sendBox.show();
      
      $(winId + '_setFontSize').innerHTML = size;
      setTimeout("$('" + winId + "_sendBox').focus();", 125);
      this.toggleFontSizeList('');
   },
   
   setFontColor: function(color) {
      var winId = this.getId();
      var sendBox = $(winId + '_sendBox');
      
      sendBox.setStyle({color: color});
      
      $(winId + '_setFontColorColor').setStyle({backgroundColor: color});
      setTimeout("$('" + winId + "_sendBox').focus();", 125);
      this.toggleFontColorList('');
   },
   
   insertText: function(tti) {
      var winId = this.getId();
      var sendBox = $(winId + '_sendBox');
      
      sendBox.value += tti;
      setTimeout("$('" + winId + "_sendBox').focus();", 125);
      this.toggleEmoticonList();
      return false;
   },

   keyHandler: function(e) {
      var asc = document.all ? event.keyCode : e.which;
      
      if(asc == 13) {
         this.send();
         return false;
      }
      
      return true;
   },
   
   detach: function() {
      var winId = this.getId();
      newWin = this.username;
      newWinRcvd = $(winId + '_rcvd').innerHTML;
      this.hide();
      var popupWin = window.open('./popup.php', name + '_im', 'left='+this.getLocation()['left']+',top='+this.getLocation()['top']+',width=320,height=335,toolbar=0,location=1,status=0,menubar=0,resizable=1,scrollbars=0');

      this.popup = popupWin;
      this.detached = true;
   }
});

// Chatroom Class
var Chatroom = {
   windows: {},

   create: function(name, imTitle) {
      var imLeft = Math.round(Math.random()*(Browser.width()-360))+'px';
      var imTop  = Math.round(Math.random()*(Browser.height()-400))+'px';
   
      var winId = randomString(32) + '_chat';
   
      this.windows[name] = new ChatWindow({id: winId, className: "dialog", width: 475, height: 340, top: imTop, left: imLeft,
                                                                   resizable: true, title: imTitle, draggable: true, detachable: false, minWidth: 475, minHeight: 150,
                                                                   showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
      
      this.windows[name].setConstraint(true, {left: 0, right: 0, top: 0, bottom: 0});
      
      this.windows[name].getContent().innerHTML = '<div class="rcvdMessages" id="' + winId + '_rcvd"></div>' + "\n" +
                                                   '<div class="chatUserList" id="' + winId + '_userlist"><ul id="' + winId + '_ul" class="sortable box"><li style="display:none"></li></ul></div>' + "\n" +
                                                   '<div class="imToolbar" id="' + winId + '_toolbar" onmousemove="return false;" onselectstart="return false;"><img src="themes/'+theme+'/window/bold_off.png" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onclick="Chatroom.windows[\'' + name + '\'].toggleBold();" onmousedown="return false;" alt="' + lang['bold'] + '" id="' + winId + '_bold" /> ' +
                                                   '<img src="themes/'+theme+'/window/italic_off.png" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onclick="Chatroom.windows[\'' + name + '\'].toggleItalic();" onmousedown="return false;" alt="' + lang['italic'] + '" id="' + winId + '_italic" /> '+
                                                   '<img src="themes/'+theme+'/window/underline_off.png" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onclick="Chatroom.windows[\'' + name + '\'].toggleUnderline();" onmousedown="return false;" alt="' + lang['underline'] + '" id="' + winId + '_underline" /></div>' +
                                                   ' <a href="#" class="setFontLink" id="' + winId + '_setFont" onclick="Chatroom.windows[\'' + name + '\'].toggleFontList();return false;" onselectstart="return false;">Tahoma</a>' +
                                                   ' <a href="#" class="setFontSizeLink" id="' + winId + '_setFontSize" onclick="Chatroom.windows[\'' + name + '\'].toggleFontSizeList();return false;" onselectstart="return false;">12</a>' +
                                                   ' <a href="#" class="setFontColorLink" id="' + winId + '_setFontColor" onclick="Chatroom.windows[\'' + name + '\'].toggleFontColorList();return false;" onselectstart="return false;"><div id="' + winId + '_setFontColorColor" style="width:14px;height:14px;display:block;"></div></a>' +
                                                   ' <a href="#" class="insertEmoticonLink" id="' + winId + '_insertEmoticon" onclick="Chatroom.windows[\'' + name + '\'].toggleEmoticonList();return false;" onselectstart="return false;"><img src="themes/' + theme + '/emoticons/mini_smile.gif" width="14" height="14" style="border:0;" /></a>' +
                                                   "\n" + '<div style="overflow:auto;"><textarea class="inputText" id="' + winId + '_sendBox" onfocus="blinkerOn(false);" onkeypress="return Chatroom.windows[\'' + name + '\'].keyHandler(event);"></textarea></div>';
      
      this.windows[name].setRoom(name);
      
      $(winId + '_userlist').setStyle({left:   (this.windows[name].getSize().width - 155) + 'px',
                                       height: (this.windows[name].getSize().height - 12) + 'px'});
      
      $(winId + '_rcvd').setStyle({marginTop: '5px',
                                   height:    (this.windows[name].getSize().height - 103) + 'px',
                                   width:     (this.windows[name].getSize().width - 170) + 'px'});
   
      $(winId + '_toolbar').setStyle({top:   (this.windows[name].getSize().height - 73) + 'px',
                                      width: (this.windows[name].getSize().width - 170) + 'px'});
      
      $(winId + '_setFont').setStyle({top: (this.windows[name].getSize().height - 65) + 'px'});
      
      $(winId + '_setFontSize').setStyle({top: (this.windows[name].getSize().height - 65) + 'px'});
      
      $(winId + '_setFontColor').setStyle({top: (this.windows[name].getSize().height - 65) + 'px'});
      
      $(winId + '_setFontColorColor').setStyle({backgroundColor: '#000'});
      
      $(winId + '_insertEmoticon').setStyle({top: (this.windows[name].getSize().height - 65) + 'px'});
   
      var sendBox = $(winId + '_sendBox');
      sendBox.setStyle({top:            (this.windows[name].getSize().height - 45) + 'px',
                        left:           '2px',
                        width:          (this.windows[name].getSize().width - 175) + 'px',
                        fontWeight:     '400',
                        fontStyle:      'normal',
                        textDecoration: 'none'});
   
      this.windows[name].show();
      this.windows[name].toFront();
      Windows.focusedWindow = this.windows[name];
      setTimeout("$('"+winId+"_sendBox').focus();", 250);
   },
   
   handleResize: function(name) {
      var winId = this.windows[name].getId();

      $(winId + '_userlist').setStyle({left:   (this.windows[name].getSize().width - 155) + 'px',
                                       height: (this.windows[name].getSize().height - 12) + 'px'});
      
      $(winId + '_rcvd').setStyle({height: (this.windows[name].getSize().height - 103) + 'px',
                                   width:  (this.windows[name].getSize().width - 170) + 'px'});
   
      $(winId + '_toolbar').setStyle({top:   (this.windows[name].getSize().height - 73) + 'px',
                                      width: (this.windows[name].getSize().width - 170) + 'px'});
      
      $(winId + '_setFont').setStyle({top: (this.windows[name].getSize().height - 65) + 'px'});
      
      $(winId + '_setFontSize').setStyle({top: (this.windows[name].getSize().height - 65) + 'px'});
      
      $(winId + '_setFontColor').setStyle({top: (this.windows[name].getSize().height - 65) + 'px'});
      
      $(winId + '_setFontColorColor').setStyle({backgroundColor: '#000'});
      
      $(winId + '_insertEmoticon').setStyle({top: (this.windows[name].getSize().height - 65) + 'px'});
   
      $(winId + '_sendBox').setStyle({top:   (this.windows[name].getSize().height - 45) + 'px',
                                      left:  '2px',
                                      width: (this.windows[name].getSize().width - 175) + 'px'});
   },

   join: function(room) {
      var xhConn = new XHConn();
      xhConn.connect(pingTo, "POST", "call=joinroom&room="+room,
         function(xh) {
            if(xh.responseText.indexOf('"') == -1) {
               switch(xh.responseText) {
                  case 'already_joined':
                     $('newroom_error_msg').innerHTML = lang['alreadyInRoom'].replace('%1', room);
                     break;
                  case 'room_is_user':
                     $('newroom_error_msg').innerHTML = lang['invalidRoom'];
                     break;
                  case 'invalid_chars':
                     $('newroom_error_msg').innerHTML = lang['invalidRoomChars'];
                     break;
               }
            } else {
               if(!$(room + '_im')) {
                  Chatroom.create(room.toLowerCase(), room.toLowerCase());
               } else {
                  if(!Chatroom.windows[room].isVisible()) {
                     Chatroom.windows[room].show();
                     setTimeout("scrollToBottom('" + room + "_rcvd')", 125);
                  }
               }
               var users = xh.responseText.parseJSON().users;
               for(var i=0; i<users.length; i++)
                  if(!$(users[i]+'_'+name+'_chatUser')) Chatroom.windows[room].addUser(users[i]);
               Windows.close('newRoom');
               Chatroom.windows[room].toFront();
               setTimeout("$('"+Chatroom.windows[room].getId()+"_sendBox').focus()", 125);
            }
           });
   },

   leave: function(room) {
      var xhConn = new XHConn();
      xhConn.connect(pingTo, "POST", "call=leaveroom&room="+room, null);
   }
};

// Chatroom Window Class
var ChatWindow = Class.create();
Object.extend(ChatWindow.prototype, IMWindow.prototype);

Object.extend(ChatWindow.prototype, {
   curSelected: '',

   setRoom: function(name) {
      this.room = name;
   },
   
   addUser: function(username) {
      $(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="themes/' + theme + '/online.png" alt="" id="'+username+'_'+this.room+'_chatImg" />&nbsp;'+username+'</li>';
      $(username+'_'+this.room+'_chatUser').setStyle({listStyleType: 'none'});
   },
   
   deleteUser: function(username) {
      var toDelete = $(username + '_' + this.room + '_chatUser');
      if(typeof(toDelete) !== 'undefined')
         toDelete.parentNode.removeChild(toDelete);
   },
   
   selectUser: function(sel, username, selected) {
      if(selected === false) {
         if(this.curSelected != username) {
            try {
               sel.setStyle({background: listStyles.notSelected.background, color: listStyles.notSelected.text});
            } catch(e) { }
         } else {
            sel.setStyle({background: listStyles.selected.background, color: listStyles.selected.text});
         }
      } else {
         sel.setStyle({background: listStyles.hover.background, color: listStyles.hover.text});
      }
   },

   clickUser: function(username) {
      if(this.curSelected.length > 0) {
         try {
            var sel = $(this.curSelected + '_' + this.room + '_chatUser');
            sel.setStyle({background: listStyles.notSelected.background, color: listStyles.notSelected.text});
         } catch(e) { }
      }
      
      this.curSelected = username;
      
      sel = $(this.curSelected + '_' + this.room + '_chatUser');
      sel.setStyle({background: listStyles.selected.background, color: listStyles.selected.text});
   },

   onUserDblClick: function() {
      if(this.curSelected.length > 0) {
         if(typeof(IM.windows[this.curSelected]) == 'undefined') {
            IM.create(this.curSelected, this.curSelected);
         } else {
            if(!IM.windows[this.curSelected].isVisible()) {
               IM.windows[this.curSelected].show();
               IM.windows[this.curSelected].toFront();
               setTimeout("scrollToBottom('" + IM.windows[this.curSelected].getId() + "_rcvd')", 125);
               setTimeout("$('" + IM.windows[this.curSelected].getId() + "_sendBox').focus();", 250);
            } else {
               IM.windows[this.curSelected].toFront();
               setTimeout("$('" + IM.windows[this.curSelected].getId() + "_sendBox').focus();", 250);
            }
         }
      }
   }
});

// Room List Class
var ChatroomList = {
   curSelected: '',
   
   get: function(applyTo) {
         var xhConn = new XHConn();

         xhConn.connect(pingTo, "POST", "call=roomlist", function(xh) {
            var rooms = xh.responseText.parseJSON();

            applyTo.innerHTML = '<ul id="join_room_ul" class="sortable box"><li style="display:none"></li>';

            if(rooms.length > 0) {
               for(var i=0; i<rooms.length; i++)
                  applyTo.innerHTML += '<li id="chatroom_list_' + hex_md5(rooms[i]) + '" 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);">' + rooms[i] + '</li>';
            } else {
               applyTo.innerHTML += '<li class="buddy" style="padding-left:1%;">No existing chatrooms!</li>';
            }
            applyTo.innerHTML += '</ul>';
         });
   },

   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');
      }
   },

   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;
      $('roomname').value = roomname;
      
      Element.addClassName($('chatroom_list_' + hex_md5(roomname)), 'listSelected').removeClassName('listNotSelected').removeClassName('listHover');
   }
};

// Button control class
var ButtonCtl = {
   create: function(text, action, id) {
      return '<a href="#" ' + (id!=null ? 'id="' + id + '" ' : '') + 'class="stdButton" onclick="' + action + 'return false;" onmouseover="ButtonCtl.hover(this);" onmousedown="ButtonCtl.down(this);" onmouseup="ButtonCtl.normal(this);" onmouseout="ButtonCtl.normal(this);">' + text + '</a>';
   },
   
   hover: function(el) {
      el.className = 'stdButton btnHover';
   },
   
   down: function(el) {
      el.className = 'stdButton btnDown';
   },
   
   normal: function(el) {
      el.className = 'stdButton';
   }
};

window.onbeforeunload = function(event) {
   if(isIE || !event) event = window.event;
   if(event && user.length > 0) {
      var text = lang['onunload'];
      if(isIE) event.returnValue = text;
      window.onbeforeunload = function() { };
      return text;
   }
}

window.onload = function() {
   Windows.addObserver({ onResize: IM.handleResize });
   Windows.addObserver({ onClose: IM.handleClose });
   Windows.addObserver({ onMaximize: IM.handleResize });
   Windows.addObserver({ onMinimize: IM.handleMinimize });

   var getEmoteHTML = new XHConn();
   getEmoteHTML.connect('themes/' + theme +'/emoticons/emoticons.html', 'GET', '', function(xh) {
      document.body.innerHTML += xh.responseText;

      var getEmoteJS = new XHConn();
      getEmoteJS.connect('themes/' + theme +'/emoticons/emoticons.js', 'GET', '', function(xh) {
         window.smilies = xh.responseText.parseJSON();
      });
   });

   setTimeout(function() { recenterModal(null); }, 1000);
   
   Event.observe(window, 'resize', recenterModal);
   Event.observe(window, 'unload', function() { if(user.length > 0) System.logout(); });

   clearInputs();

   $('statusList').getElementsBySelector('img').each(function(el) {
      el.src = el.src.replace(/images/g, 'themes/' + theme);
   });

   Dialogs.login();
};

function clearInputs() {
   var formInputs = document.getElementsByTagName('input');
   for (var i=0; i<formInputs.length; i++)
        if(formInputs[i].type == 'text' || formInputs[i].type == 'password') formInputs[i].value = '';
}

function recenterModal(event) {

   var windowScroll = WindowUtilities.getWindowScroll();    
   var pageSize = WindowUtilities.getPageSize();    

   var top = (pageSize.windowHeight - $('modal').getHeight())/2;
   top += windowScroll.top;
    
   var left = (pageSize.windowWidth - $('modal').getWidth())/2;
   left += windowScroll.left;

   $('modal').setStyle({top:     top + 'px',
                        left:    left + 'px',
                        display: 'block'});
}

function showHide(evt) {
     if (!evt) { evt = window.event; }
     if (document.all) { trgObj = evt.srcElement; }
     else { trgObj = evt.target; }
     if (!trgObj) { return; }
     if (user.length > 0 && trgObj.id != 'statusList' && trgObj.id != 'fontsList' && trgObj.id != 'statusSettings'
          && trgObj.id != 'curStatus' && trgObj.parentNode.id != 'statusList' &&
          trgObj.parentNode.id != 'fontsList' && trgObj.id != 'customMessage' &&
          trgObj.parentNode.id != 'customMessage' && trgObj.id != 'emoticonList' &&
          trgObj.className != 'emotIcon' && trgObj.id != 'fontSizeList' &&
          trgObj.parentNode.id != 'fontSizeList' && trgObj.id != 'fontColorList' &&
          trgObj.className != 'colorItem' &&
          trgObj.className != 'tTable') {
        Element.setStyle($('statusList'), {'display': 'none'});
        Element.setStyle($('emoticonList'), {'display': 'none'});
        Element.setStyle($('fontsList'), {'display': 'none'});
        Element.setStyle($('fontSizeList'), {'display': 'none'});
        Element.setStyle($('fontColorList'), {'display': 'none'});
        return;
     }
}

function handleInput(e, func) {
   var asc = document.all ? event.keyCode : e.which;
   
   if(asc == 13) {
      func();
      return false;
   }
   
   return true;
}

function regExpEscape(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

function scrollToBottom(id) {
   $(id).scrollTop = $(id).scrollHeight - $(id).clientHeight;
}

function trim(text) {
   if(text == null) return null;
   return text.replace(/^[ \t]+|[ \t]+$/g, "");
}

function toggleAudio() {
   if(audioNotify == true) {
      audioNotify = false;
      $('toggleaudio').src = 'themes/'+theme+'/window/audio_off.png';
   } else {
      audioNotify = true;
      $('toggleaudio').src = 'themes/'+theme+'/window/audio_on.png';
   }
}

function titlebarBlink(name, message, alter, chatroom) {
   if(titlebarBlinker == false) {
      document.title = defaultTitle;
      return;
   }
   
   if(chatroom == 0 && IM.windows[name].detached) {
      IM.windows[name].popup.titlebarBlink(name, message, alter);
      return;
   }
   
   if(alter == 0) {
      document.title = name + '!';
      blinkerTimer = setTimeout("titlebarBlink('"+name+"', '"+message+"', 1, "+chatroom+")", 1000);
   } else if(alter == 1) {
      document.title = '"' + message.substring(0, 10) + (message.length > 10 ? '...' : '') + '"';
      blinkerTimer = setTimeout("titlebarBlink('"+name+"', '"+message+"', 2, "+chatroom+")", 1000);
   } else if(alter == 2) {
      document.title = defaultTitle;
      blinkerTimer = setTimeout("titlebarBlink('"+name+"', '"+message+"', 0, "+chatroom+")", 1000);
   }
}

function blinkerOn(onoff) {
   if(onoff == true)
      titlebarBlinker = true;
   else
      titlebarBlinker = false;
}

function buttonHover(el) {
   var newsrc = el.src;
   newsrc = newsrc.replace(/_hover/, '');
   el.src = newsrc.replace(/\.png/, '_hover.png');
}

function buttonDown(el) {
   el.src = el.src.replace(/_hover\.png/, '_down.png');
}

function buttonNormal(el) {
   el.src = el.src.replace(/\_hover.png/, '.png').replace(/\_down.png/, '.png');
}

var Browser = {
   width: function() {
      if (self.innerWidth) {
         return self.innerWidth;
      } else if (document.documentElement && document.documentElement.clientWidth) {
         return document.documentElement.clientWidth;
      } else if (document.body) {
         return document.body.clientWidth;
      }
      return 630;
   },

   height: function() {
      if (self.innerWidth) {
         return self.innerHeight;
      } else if (document.documentElement && document.documentElement.clientWidth) {
         return document.documentElement.clientHeight;
      } else if (document.body) {
         return document.body.clientHeight;
      }
      return 470;
   }
};

function checkEmailAddr(email) {
   var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
   if (filter.test(email)) return true;
   else return false;
}

function randomString(length) {
   var chars = "abcdefghijklmnopqrstuvwxyz1234567890";
   var pass = "";
   var charLength = chars.length;

   for(x=0;x<length;x++) {
      i = Math.floor(Math.random() * charLength);
      pass += chars.charAt(i);
   }

   return pass;
}

function inArray(arr, value)
// Returns true if the passed value is found in the
// array.  Returns false if it is not.
{
   var i;
   for (var group in arr) {
     // Matches identical (===), not just similar (==).
      for(i=0; i<arr[group].length; i++) {
         if(arr[group][i] === value)
            return true;
      }
   }
   return false;
};

Array.prototype.inArray = function(search_term) {
  var i = this.length;
  if (i > 0) {
	 do {
		if (this[i] === search_term) {
		   return true;
		}
	 } while (i--);
  }
  return false;
}

String.prototype.isAlphaNumeric = function() {return /^[A-Za-z0-9_\d]+$/.test (this)};


var loadCSS = document.createElement("link");
loadCSS.setAttribute("rel", "stylesheet")
loadCSS.setAttribute("type", "text/css")
loadCSS.setAttribute("href", 'themes/' + theme + '/style.css')
if (typeof loadCSS != "undefined")
  document.getElementsByTagName("head")[0].appendChild(loadCSS);