var CometChat = {
  currentUsername:null,
  currentUserLink:null,
  currentUserImage:null,
  currentUserStaff:'0',
  currentUserIMSound:'Always',
  driverFrame:null,
  usersOnlineBoxes:[],
  openRooms:[],
  IMBoxes:[],
  inputEnabled:true,
  liveHelpAvailable:false,
  livePrayerAvailable:false,
  invisible:1,
  invisibleConfirmed:true,
  fallback:true,
  blinkReady:false,
  staffColor:'#FF0000',
  staffImageType:'.gif',
  
  lobbySongs:[],
  lobbyNowPlaying:false,
  
  // An object / associative array of name => lastModifiedAt of DynamicRichText
  dynamicRichText: [],
  
  // An array of maps associated with chat rooms
  maps: [],
  
  initialize:function(cometDomain, domainMask)
  {
    // Append the chat driver iframe
    $("body").append("<iframe id=\"cometChatDriverFrame_"+cometDomain+"\" name=\"cometChatDriverFrame_"+cometDomain+"\" style=\"width:0px; height:0px;display:none;\"></iframe>");
    CometChat.driverFrame = frames['cometChatDriverFrame_'+cometDomain];
    CometChat.driverFrame.location.href = "http://"+cometDomain+domainMask+"/chatdriver.php?cache=1";
        
    $(".LiveHelpRequest").click(function() {
      CometChat.sendLiveHelpRequest();
    });
    
    $(".LivePrayerRequest").click(function() {
      CometChat.sendLivePrayerRequest();
    });

    $(".ChatInvisibilityToggle").click(CometChat.toggleInvisibility);

    setTimeout("CometChat.fallbackPoll()", 5000);

    CometChat.blink();

  },
  fallbackPoll:function()
  {
    if(CometChat.fallback) {
      CometChat.sendLongPoll(true);
    }
  },
  getFullXML:function(moduleXML)
  {
    return '<?xml version="1.0" encoding="utf-8"?><request><session>'+CometChat.session+'</session><modules>'+moduleXML+'</modules></request>';
  },
  sendLongPoll:function(fallback)
  {
    var moduleXML = '';

    moduleXML += '<module name="UsersOnline"><invisible>'+CometChat.invisible+'</invisible>';
    //Users online
    if(CometChat.usersOnlineBoxes.length > 0)
    {
      moduleXML += '<boxes>';

      $.each(CometChat.usersOnlineBoxes, function()
      {
        moduleXML += '<box><chatRoomID>'+this.chatRoomID+'</chatRoomID><originalUsersOnline>'+this.usersOnline.join(',')+'</originalUsersOnline></box>';
      });

      moduleXML += '</boxes>';
    }
    moduleXML += '</module>';

    //Chat rooms
    if(CometChat.openRooms.length > 0)
    {
      moduleXML += '<module name="ChatRooms"><chatRooms>';

      $.each(CometChat.openRooms, function()
      {
        moduleXML += '<chatRoom><id>'+this.chatRoomID+'</id><lastTimestamp>'+this.lastTimestamp+'</lastTimestamp></chatRoom>';
      });

      moduleXML += '</chatRooms></module>';
    }

    //IM Boxes
    moduleXML += '<module name="InstantMessanger">';
    if(CometChat.IMBoxes.length > 0)
    {
      moduleXML += '<IMBoxes>';

      $.each(CometChat.IMBoxes, function()
      {
        if(this.initialized != null)
        {
          moduleXML += "<IMBox><userID>"+this.userID+"</userID><userType>"+this.userType+"</userType><minimized>"+this.minimized+"</minimized><lastTimestamp>"+this.lastUpdate+"</lastTimestamp></IMBox>";
        }
      });

      moduleXML += '</IMBoxes>';
    }
    moduleXML += '</module>';


    // Live help
    if(CometChat.liveHelpAvailable) {
      var liveHelp = 'true';
    } else {
      var liveHelp = 'false';
    }
    moduleXML += '<module name="LiveHelp"><available>'+liveHelp+'</available></module>';
    
    // Prayer Request
    if(CometChat.livePrayerAvailable) {
      var livePrayer = 'true';
    } else {
      var livePrayer = 'false';
    }
    moduleXML += '<module name="LivePrayer"><available>'+livePrayer+'</available></module>';
    
    // Lobby music
    if($("#musicPlayer").length > 0) {
      if(CometChat.lobbyNowPlaying) {
        var nowPlaying = "true";
      } else {
        var nowPlaying = "false";
      }
      moduleXML += '<module name="LobbyMusic"><nowPlaying>'+nowPlaying+'</nowPlaying></module>';
    }
    
    // DynamicRichText
    if (CometChat.dynamicRichText.length > 0) {
        moduleXML += '<module name="DynamicRichText">';
        $.each(CometChat.dynamicRichText, function()
        {
            moduleXML += '<dynamicRichText name="' + this.name + '">' + this.lastModifiedAt + '</dynamicRichText>';
        });
        moduleXML += '</module>';
    }
    
    // Chat instructions
    moduleXML += '<module name="ChatInstructions"><maxChatInstructionId>' + CometChat.maxChatInstructionId + '</maxChatInstructionId></module>';
    
    
    var fullXML = CometChat.getFullXML(moduleXML);

    if(!fallback) {
      CometChat.driverFrame.sendXML(fullXML);
    } else {
      CometChat.sendXMLFallback(fullXML);
    }
  },
  sendXMLFallback:function(requestXML)
  {
    if(!CometChat.fallback) {
      return;
    }

    if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
      var ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
      if (ffversion>=2 && ffversion < 3) {
        var dataType="string";
      } else {
        var dataType = "xml";
      }
    } else {
      var dataType = "xml";
    }

    var params = {
      XML:requestXML
    };

    var options = {
      "url":"/cometchat/",
      "type":"POST",
      "cache":false,
      "data":params,
      "dataType":dataType,
      "timeout":40000,
      "error":function(XMLHttpRequest, textStatus, errorThrown)
      {
        $("body").append("<div>AJAX Error:"+XMLHttpRequest+ " -- "+textStatus+" -- "+errorThrown+"</div>");

        setTimeout("CometChat.sendLongPoll(true);", 5000);
      },
      "success":function(xml)
      {
        if(dataType == "string") {
          xml = (new DOMParser()).parseFromString(xml, "text/xml");
        }

        window.parent.CometChat.processLongPoll($(xml));

        setTimeout("CometChat.sendLongPoll(true);", 100);
      }
    };

    $.ajax(options);
  },
  processLongPoll:function($responseXML, fallback)
  {
    //Handle the users online updates
    var $usersOnlineData = $("modules module[name=UsersOnline]", $responseXML);

    var $setInvisibility = $("setInvisibility", $usersOnlineData);
    if($setInvisibility.length == 1)
    {
      CometChat.invisible = parseInt($setInvisibility.text());
      CometChat.invisibleConfirmed = true;

      if(CometChat.invisible) {
        $(".ChatInvisibilityToggle").attr("checked", true);
      } else {
        $(".ChatInvisibilityToggle").removeAttr("checked");
      }

      $(".ChatInvisibilityToggleContainer").removeClass("ChatInvisibilityToggleContainerBusy");
    }

    $("updateBox", $usersOnlineData).each(function()
    { //Loop through each box that has updating to be done
      var $updateBox = $(this);
      var updateBoxChatRoomID = parseInt($updateBox.attr("chatRoomID"));
      var updateBox = CometChat.getUsersOnlineBoxByChatRoomID(updateBoxChatRoomID);

      if(updateBox)
      { //Make sure the box exists

        $("removeUsers removeUser", $updateBox).each(function()
        { //Loop through each user that needs to be removed
        
          var removeUserID = parseInt($(this).text());
          updateBox.removeOnlineUser(removeUserID);
          
          /*
          if (CometChat.maps[updateBoxChatRoomID] != null) {
            CometChat.maps[updateBoxChatRoomID].removeUser(removeUserID);
          }
*/
        });

        $("newUsers newUser", $updateBox).each(function()
        { //Loop through each new user to be added to the box
          var $this = $(this);

          var newUserID = $this.children("userID").text();
          var newUsername = $this.children("username").text();
          var newUserImage = $this.children("userImage").text();
          var newUserLink = $this.children("userLink").text();
          var staff = $this.children("staff").text();
          
          var country = $this.children("country").text();
          var state = $this.children("state").text();
          var city = $this.children("city").text();
          
          // Add the user to the online box
          updateBox.addOnlineUser(newUserID, newUsername, newUserImage, newUserLink, staff);
          
          // If we have a map object for this we should add them to it          
          if (CometChat.maps[updateBoxChatRoomID] != null) {
            CometChat.maps[updateBoxChatRoomID].addUser(newUserID, newUsername, country, state, city);
          }
        });
      }
    });

    //Handle any chat room updates
    var $chatRoomsData = $("modules module[name=ChatRooms]", $responseXML);
    $("chatRoom", $chatRoomsData).each(function()
    { //Loop through each box that has updating to be done
      var $chatRoom = $(this);
      var chatRoomID = parseInt($chatRoom.children("id").text());
      var chatRoom = CometChat.getChatRoomByID(chatRoomID);

      if(chatRoom)
      { //Make sure the box exists
        chatRoom.$messages.find(".Temp").remove();

        $("newMessages newMessage", $chatRoom).each(function()
        { //Loop through each new user to be added to the box
          var $this = $(this);

          var msgUserID = $this.children("userID").text();
          var msgUsername = $this.children("username").text();
          var msgUserImage = $this.children("userImage").text();
          var msgUserLink = $this.children("userLink").text();
          var msgText = $this.children("message").text();
          var msgTimestamp = $this.children("prettyTimestamp").text();
          var staff = $this.children("staff").text();
          
          chatRoom.addMessage(msgUserID, msgUsername, msgUserImage, msgUserLink, msgText, msgTimestamp, false, staff);

          chatRoom.lastTimestamp = $this.children("timestamp").text();
        });
      }
    });

    //IM Updates
    var playSound = false;
    var $IMData = $("modules module[name=InstantMessanger]", $responseXML);
    $("window", $IMData).each(function()
    {
      var $this = $(this);

      var userType = $this.attr("userType");
      var userID = $this.attr("userID");
      var staff = $this.attr("staff");
      
      var $closeWindow = $this.children("closeWindow");
      if($closeWindow.length > 0)
      { //Check for close directive
        var IMBox = CometChat.getIMBox(userType, userID);
        if(IMBox != null)
        {
          IMBox.closeWindow();
        }
      }
      else
      {
        var username = $this.attr("username");
        var minimized = parseInt($this.children("minimized").text());
        var initialized = $this.children("initialized").text();
        
        var IMBox = CometChat.getIMBox(userType, userID);

        if(IMBox == null)
        {          
          IMBox = CometChat.openIM(userID, username, userType, minimized, true, initialized, staff);
        }
        else
        {
          if(IMBox.initialized == null)
          {
            IMBox.initialized = IMBox.lastUpdate = initialized;
          }

          if($this.children("minimized").length > 0 && parseInt(IMBox.minimized) != minimized)
          {
            if(minimized)
            {
              IMBox.minimize();
            }
            else
            {
              IMBox.maximize();
            }
          }
        }

        var $newMessages = $("newMessage", $this);

        if($newMessages.length > 0)
        {                    
          if(CometChat.blinkReady) {
            IMBox.blinking = true;
          }

          IMBox.$messages.find(".Temp").remove();

          $("newMessage", $this).each(function()
          {
            $this = $(this);

            var username = $this.children("username").text();
            
            if(username != CometChat.currentUsername) {
              playSound = true;
            }
            
            var userLink = $this.children("userLink").text();
            var message = $this.children("message").text();
            var prettyTimestamp = $this.children("prettyTimestamp").text();
            var timestamp = $this.children("timestamp").text();

            IMBox.addMessage(username, userLink, message, prettyTimestamp, false)

            IMBox.lastUpdate = timestamp;
          });
        }



      }

    });
    
    if(playSound && CometChat.currentUserIMSound == 'Always' && CometChat.blinkReady) {
      CometChat.playIMSound();
    }
    
    //Live help
    var $liveHelpAvailable = $("modules module[name=LiveHelp] available", $responseXML);
    if($liveHelpAvailable.length > 0)
    {
      var available = $liveHelpAvailable.text();
      if(available == 'true')
      {
        CometChat.liveHelpAvailable = true;

        $(".LiveHelpAvailable").show();
        $(".LiveHelpUnavailable").hide();
      }
      else
      {
        CometChat.liveHelpAvailable = false;

        $(".LiveHelpAvailable").hide();
        $(".LiveHelpUnavailable").show();
      }
    }
    
    //Live prayer
    var $livePrayerAvailable = $("modules module[name=LivePrayer] available", $responseXML);
    if($livePrayerAvailable.length > 0) {
      var available = $livePrayerAvailable.text();
      if(available == 'true') {
        CometChat.livePrayerAvailable = true;

        $(".LivePrayerAvailable").show();
        $(".LivePrayerUnavailable").hide();
      } else {
        CometChat.livePrayerAvailable = false;

        $(".LivePrayerAvailable").hide();
        $(".LivePrayerUnavailable").show();
      }
    }
    
    //Lobby music
    var $lobbyMusic = $("modules module[name=LobbyMusic] playMusic", $responseXML);
    if($lobbyMusic.length > 0) {
      CometChat.playLobbyMusic();
    }
    
    // DynamicRichText    
    var $dynamicRichText = $("modules module[name=DynamicRichText] dynamicRichText", $responseXML);
        
    if ($dynamicRichText.length > 0) {
            
      // We have some DynamicRichText elements that need updating
      $.each($dynamicRichText, function()
      {
        // Grab the info about this DynamicRichText
        var name = $(this).attr('name');
        var lastModifiedAt = $(this).find('lastModifiedAt').text();
        var content = $(this).find('content').text();
        
        // Try and find the object in our list and update it
        $.each(CometChat.dynamicRichText, function()
        {        
          if (this.name == name) {            
            this.update(content, lastModifiedAt);
            
            // We're done searching for this one
            return false;
          }
        });
      });
    }
    
    // ChatInstructions
    var $newInstructions = $("modules module[name=ChatInstructions] newInstruction", $responseXML);
    $.each($newInstructions, function()
    {
      var id = $(this).attr('id');
      var type = $(this).text();
      
      // Theres only one type now, so screw it, loop through all the chats and clear the messages
      $.each(CometChat.openRooms, function()
      {
        // Remove the messages
        this.$messages.find('li').remove();
      });
      
      // Set the new max id
      CometChat.maxChatInstructionId = id;
    });
    
    CometChat.enableInputs();
    CometChat.blinkReady = true;
  },
  addUsersOnlineBox:function(chatRoomID)
  {
    CometChat.usersOnlineBoxes.push(new CometChat.UsersOnlineBox(chatRoomID));
  },
  addChatRoom:function(chatRoomID, lastTimestamp)
  {
    CometChat.openRooms.push(new CometChat.Room(chatRoomID, lastTimestamp));
  },
  openIM:function(userID, username, userType, minimized, alreadyOpened, initialized, staff)
  {
    var addBox = true;
    
    if(CometChat.currentUsername == null || CometChat.currentUsername == "") {
      alert("You must be logged in to chat with users.");
      return;
    }
        
    if(userType == null)
    {
      userType = 'Member';
    }

    //Check for existing IM box
    $.each(CometChat.IMBoxes, function()
    {
      if(this.userID == userID)
      {
        addBox = false;
        return false;
      }
    });

    if(addBox)
    {
      var newBox = new CometChat.IMBox(userID, username, userType, minimized, initialized, null, staff);

      CometChat.IMBoxes.push(newBox);
      //Chat.bindIMWindowEvents();

      if(!alreadyOpened)
      {
        var fullXML = CometChat.getFullXML('<module name="InstantMessanger"><openWindow>'+userID+'</openWindow></module>');

        $.post("/cometchat/", {"XML":fullXML});
      }
      else
      {
        newBox.lastUpdate = newBox.initialized = initialized;
      }
    }

    return newBox;
  },
  getUsersOnlineBoxByChatRoomID:function(chatRoomID)
  {
    var returnBox = null;

    $.each(CometChat.usersOnlineBoxes, function()
    {
      if(chatRoomID == this.chatRoomID)
      {
        returnBox = this;
        return false;
      }
    });

    return returnBox;
  },
  getChatRoomByID:function(chatRoomID)
  {
    var returnRoom = null;

    $.each(CometChat.openRooms, function()
    {
      if(chatRoomID == this.chatRoomID)
      {
        returnRoom = this;
        return false;
      }
    });

    return returnRoom;
  },
  getIMBox:function(userType, userID)
  {
    var returnBox = null;

    $.each(CometChat.IMBoxes, function()
    {
      if(this.userType == userType && this.userID == userID)
      {
        returnBox = this;
        return false;
      }
    });

    return returnBox;
  },
  disableInputs:function()
  {
    $.each(CometChat.openRooms, function()
    {
      this.$submit.addClass("hover");
    });

    $.each(CometChat.IMBoxes, function()
    {
      this.$sendButton.addClass("hover");
    });

    CometChat.inputEnabled = false;
  },
  enableInputs:function()
  {
    $.each(CometChat.openRooms, function()
    {
      this.$submit.removeClass("hover");
    });

    $.each(CometChat.IMBoxes, function()
    {
      this.$sendButton.removeClass("hover");
    });

    CometChat.inputEnabled = true;
  },
  sendLiveHelpRequest:function(publicName, publicEmail)
  {
    if(!publicName)
    {
      publicName = '';
      publicEmail = '';
    }

    var fullXML = CometChat.getFullXML('<module name="LiveHelp"><liveHelpRequest><publicName>'+htmlentities(publicName)+'</publicName><publicEmail>'+htmlentities(publicEmail)+'</publicEmail></liveHelpRequest></module>');

    $.post("/cometchat/", {"XML":fullXML}, function(data)
    {
      var publicUserForm = $("modules module[name=LiveHelp] publicUserForm", data);
      if(publicUserForm.length > 0)
      {
        var publicUserFormHTML = publicUserForm.text();

        $.facebox(publicUserFormHTML);
      }
      else
      {
        var $currentUsername = $("currentUsername", data);
        var $currentUserImage = $("currentUserImage", data);
        var $currentUserLink = $("currentUserLink", data);

        if($currentUsername.length > 0)
        {
          CometChat.currentUsername = $currentUsername.text();
          CometChat.currentUserImage = $currentUserImage.text();
          CometChat.currentUserLink = $currentUserLink.text();
        }

        var agentUserID = parseInt($("agentUserID", data).text());
      }
    }, "xml");
  },
  sendLivePrayerRequest:function()
  {
    // Make sure that the user is logged in before initing a chat request
    if(CometChat.currentUsername == '') {
      alert('You must be a logged in member to chat with a live prayer desk user. Please log in or create an account.');
      return;
    }

    var fullXML = CometChat.getFullXML('<module name="LivePrayer"><livePrayerRequest></livePrayerRequest></module>');

    $.post("/cometchat/", {"XML":fullXML}, function(data)
    {
      var agentUserID = parseInt($("agentUserID", data).text());
    }, "xml");
  },
  toggleInvisibility:function(e)
  {
    var $this = $(this);

    if(CometChat.invisibleConfirmed)
    {
      if($this.attr("checked"))
      {
        var setInvisible = 1;
      }
      else
      {
        var setInvisible = 0;
      }

      var fullXML = CometChat.getFullXML('<module name="UsersOnline"><changeInvisibility>'+setInvisible+'</changeInvisibility></module>');

      $.post("/cometchat/", {"XML":fullXML});

      $this.parent().addClass("ChatInvisibilityToggleContainerBusy");
    }
    else
    {
      e.preventDefault();
    }
  },
  blink:function()
  {
    $.each(CometChat.IMBoxes, function()
    {
      if(this.blinking && this.$window.hasClass("Minimized"))
      {
        this.$title.addClass("Blink");
      }
    });

    setTimeout("CometChat.unblink();", 500);
  },
  unblink:function()
  {
    $.each(CometChat.IMBoxes, function()
    {
      this.$title.removeClass("Blink");
    });

    setTimeout("CometChat.blink();", 1500);
  },
  playIMSound:function() {
    $("#IMSound").remove();
    $("body").append("<embed src=\"/sounds/im.wav\" autostart=true width=0 height=0 id=\"IMSound\" loop=false>");
  },
  playLobbyMusic:function() {
    if($("#musicPlayer").length > 0 && $("#musicPlayer #musicObj").length == 0) {
      $("#musicPlayer").html('<div id="musicObj"></div>');
      
      var flashVars = {};
      $.each(CometChat.lobbySongs, function(index) {
        flashVars["file"+(index+1)] = this;
      });
      
      
      CometChat.lobbyNowPlaying = true;
      swfobject.embedSWF("/flash/music_v2.swf", "musicObj", "100", "20", "9.0.0", null, flashVars, {wmode: 'transparent'});
    }
  }
};

//############## USERS ONLINE BOX #################
CometChat.UsersOnlineBox = function(setChatRoomID)
{
  this.chatRoomID = setChatRoomID;
  this.$users = $("#ChatUsersOnline_"+setChatRoomID);
  this.usersOnline = [];
}

CometChat.UsersOnlineBox.prototype = {
  addOnlineUser:function(userID, username, userImage, userLink, staff)
  {
    this.usersOnline.push(userID);
    
    if(staff == '1') {
      var userColor = CometChat.staffColor;
      var staffImage = ' <img src="/defaultimages/staff'+CometChat.staffImageType+'" title="Staff User" />';
    } else {
      var userColor = '#1a609e';
      var staffImage = '';
    }
    
    var userOnlineHTML = CometChat.templates.userOnline.
      replace(/{USERID}/g, userID).
      replace(/{USERNAME}/g, username).
      replace(/{USERIMAGE}/g, userImage).
      replace(/{USERLINK}/g, userLink).
      replace(/{USERCOLOR}/g, userColor).
      replace(/{STAFFIMAGE}/g, staffImage);
    
    var $boxUsers = this.$users;
    var $onlineUsers = $("div.OnlineUser", $boxUsers);

    var insertedBefore = false;

    $onlineUsers.each(function()
    {
      var $this = $(this);

      if(username.toLowerCase() < $this.data("username").toLowerCase())
      {
        $this.before(userOnlineHTML).prev().data("username", username);
        insertedBefore = true;

        return false;
      }
    });

    if(!insertedBefore)
    {
      $boxUsers.append(userOnlineHTML).find(".OnlineUser:last").data("username", username);
    }
    
    this.showHideOnlineUsersBox();
  },
  removeOnlineUser:function(userID)
  {
    for(var i = 0; i < this.usersOnline.length; i++)
    {
      if(this.usersOnline[i] == userID)
      {
        this.usersOnline.splice(i, 1);
        break;
      }
    }

    this.$users.find(".OnlineUser[rel="+userID+"]").remove();
    this.showHideOnlineUsersBox();
  },
  showHideOnlineUsersBox: function() {
      if ($("#usersInLobby .OnlineUser").length == 0) {
        $("#usersInLobby").css("display","none");
      } else {
        $("#usersInLobby").css("display","inline");
      }
  }
}

//############### CHAT ROOM ######################

CometChat.Room = function(setChatRoomID, setLastTimestamp)
{
  this.chatRoomID = setChatRoomID;
  this.lastTimestamp = setLastTimestamp;
  this.$container = $("#ChatRoomContainer_"+setChatRoomID);
  this.$messages = $(".ChatRoomMessages", this.$container);
  this.$form = $(".ChatRoomForm", this.$container);
  this.$input = $(".ChatRoomInput", this.$container);
  this.$submit = $(".ChatRoomSubmit", this.$container);
  this.$clear = $(".ChatRoomClear", this.$container);
  this.$smallToggle = $(".ChatRoomSmallToggle", this.$container);

  var room = this;

  this.$submit.click(function()
  {
    room.$form.submit();
  });

  this.$form.bind('submit', function()
  {
    if(CometChat.inputEnabled)
    {
      var message = htmlentities(room.$input.val());

      room.addMessage(0, CometChat.currentUsername, CometChat.currentUserImage, CometChat.currentUserLink, message, '', true, CometChat.currentUserStaff);

      var moduleXML = '<module name="ChatRooms"><sendMessage><chatRoomID>'+room.chatRoomID+'</chatRoomID><message>'+message+'</message></sendMessage></module>';
      var fullXML = CometChat.getFullXML(moduleXML);

      room.$input.val("");

      $.post("/cometchat/", {"XML":fullXML});

      CometChat.disableInputs();
    }

    return false;
  });

  this.$clear.click(function()
  {
    // A staff member has clicked on the clear button
    var moduleXML = '<module name="ChatInstructions"><newInstruction>ClearAllChats</newInstruction></module>';
    var fullXML = CometChat.getFullXML(moduleXML);

    $.post("/cometchat/", {"XML":fullXML});
  });
  
  this.$smallToggle.click(function() {
    if(room.$messages.hasClass("ChatRoomSmall")) {
      room.$messages.removeClass("ChatRoomSmall");
      var saveVal = "0";
    } else {
      room.$messages.addClass("ChatRoomSmall");
      var saveVal = "1";
    }
    
    var moduleXML = '<module name="ChatRooms"><saveChatRoomSmall>'+saveVal+'</saveChatRoomSmall></module>';
    var fullXML = CometChat.getFullXML(moduleXML);
    $.post("/cometchat/", {"XML":fullXML});
    
  });
}

CometChat.Room.prototype = {
  addMessage:function(userID, username, userImage, userLink, message, timestamp, temp, staff)
  {
    var room = this;

    if(temp)
    {
      var extraClass = ' class="Temp"';
    }
    else
    {
      var extraClass = '';
    }
    
    if(staff == '1') {
      var userColor = CometChat.staffColor;
      var staffImage = ' <img src="/defaultimages/staff'+CometChat.staffImageType+'" title="Staff User" />';
    } else {
      var userColor = '#636363';
      var staffImage = '';
    }
    
    var messageHTML = CometChat.templates.chatMessage.
      replace(/{USERID}/g, userID).
      replace(/{USERNAME}/g, username).
      replace(/{USERIMAGE}/g, userImage).
      replace(/{USERLINK}/g, userLink).
      replace(/{MESSAGE}/g, message).
      replace(/{TIMESTAMP}/g, timestamp).
      replace(/{USERCOLOR}/g, userColor).
      replace(/{STAFFIMAGE}/g, staffImage);
    
    atBottom = false;
    if ((this.$messages.scrollTop()+205) >= (this.$messages.find("ul").height() - 20) || this.$messages.find("ul").height()  < 205)
        atBottom = true;
        
    this.$messages.find("ul").append("<li "+extraClass+">"+messageHTML+"</li>");
    
    if (CometChat.currentUsername == username || atBottom) {
        this.$messages.scrollTop(1000000);
    }
    
    this.$messages.find("li:last .MessageUserImage").bind('load', function() {
      if (CometChat.currentUsername == username || atBottom) {
        room.$messages.scrollTop(1000000);
      }
    });

  }
}

//############### IM BOX #########################

CometChat.IMBox = function(setUserID, setUsername, setUserType, setMinimized, setInitialized, setLastUpdate, staff)
{
  this.userID = setUserID;
  this.username = setUsername;
  this.userType = setUserType;

  this.minimized = setMinimized;
  this.initialized = setInitialized;
  this.lastUpdate = setLastUpdate;
  
  if(staff) {
    this.userlink = 'javascript:;';
    this.userImage = '/autoimages/20.jpg';
  } else {
    this.userLink = '/users/'+this.username+'/profile.php';
    this.userImage = '/users/'+this.username.substr(0,1)+'/'+this.username.substr(1,1)+'/'+this.username.substr(2)+'/spec/headshot.jpg';
  }
  
  this.blinking = false;
  
  if(setInitialized)
  {
    this.blinkReady = false;
  }
  else
  {
    this.blinkReady = true;
  }
  
  if(CometChat.blinkReady && setInitialized && CometChat.currentUserIMSound == 'First Time') {
    CometChat.playIMSound();
  }

  this.blinking = false;
  
  var IMBoxHTML = CometChat.templates.IMBox.
    replace(/{USERID}/g, this.userID).
    replace(/{USERNAME}/g, this.username).
    replace(/{USERLINK}/g, this.userLink).
    replace(/{USERIMAGE}/g, this.userImage);

  if(setMinimized)
  {
    $("#chatBar #taskBar").append(IMBoxHTML);
  }
  else
  {
    $("#windowBar #IMWindows").append(IMBoxHTML);
  }

  this.$window = $("#IM_"+setUserID);
  this.$title = this.$window.find(".Title");
  this.$minButton = this.$window.find(".MinButton");
  this.$maxButton = this.$window.find(".MaxButton");
  this.$closeButton = this.$window.find(".CloseButton");
  this.$IMForm = this.$window.find(".IMForm");
  this.$messages = this.$window.find(".Messages");
  this.$newMessage = this.$window.find(".NewMessage");
  this.$sendButton = this.$window.find(".SendMessage");

  if(setMinimized)
  {
    this.$minButton.hide();
    this.$window.addClass("Minimized");

    $("#windowBar").css("bottom", "35px");
  }
  else
  {
    this.$maxButton.hide();
  }

  var IMBox = this;

  //Bind events
  IMBox.$minButton.unbind().click(function()
  {
    IMBox.minimize();

    var fullXML = CometChat.getFullXML('<module name="InstantMessanger"><minimizeWindow><userType>'+IMBox.userType+'</userType><userID>'+IMBox.userID+'</userID></minimizeWindow></module>');
    $.post("/cometchat/", {"XML":fullXML});
  });

  IMBox.$maxButton.unbind().click(function()
  {
    IMBox.maximize();

    var fullXML = CometChat.getFullXML('<module name="InstantMessanger"><maximizeWindow><userType>'+IMBox.userType+'</userType><userID>'+IMBox.userID+'</userID></maximizeWindow></module>');
    $.post("/cometchat/", {"XML":fullXML});
  });

  IMBox.$closeButton.unbind().click(function()
  {
    IMBox.closeWindow();

    var fullXML = CometChat.getFullXML('<module name="InstantMessanger"><closeWindow><userType>'+IMBox.userType+'</userType><userID>'+IMBox.userID+'</userID></closeWindow></module>');
    $.post("/cometchat/", {"XML":fullXML});
  });

  IMBox.$sendButton.unbind().click(function()
  {
    IMBox.$IMForm.submit();
  });

  IMBox.$IMForm.unbind().bind('submit', function()
  {
    if(CometChat.inputEnabled)
    {
      var message = htmlentities(IMBox.$newMessage.val());

      IMBox.addMessage(CometChat.currentUsername, CometChat.currentUserLink, message, '', true);

      var moduleXML = '<module name="InstantMessanger"><sendMessage><userType>'+IMBox.userType+'</userType><userID>'+IMBox.userID+'</userID><message>'+message+'</message></sendMessage></module>';
      var fullXML = CometChat.getFullXML(moduleXML);

      IMBox.$newMessage.val("");

      $.post("/cometchat/", {"XML":fullXML});

      CometChat.disableInputs();
    }

    return false;
  });
}

CometChat.IMBox.prototype = {
  minimize:function()
  {
    this.blinking = false;

    this.minimized = 1;

    this.$maxButton.show();
    this.$minButton.hide();
    this.$window.addClass("Minimized");

    this.$window.appendTo("#chatBar #taskBar");

    $("#windowBar").css("bottom", "35px");
  },
  maximize:function()
  {
    this.minimized = 0;

    this.$maxButton.hide();
    this.$minButton.show();
    this.$window.removeClass("Minimized");

    this.blinking = false;

    this.$window.appendTo("#windowBar #IMWindows");
    this.$messages.scrollTop(100000);

    if($("#chatBar #taskBar div").length == 0)
    {
      $("#windowBar").css("bottom", "0px");
    }
  },
  closeWindow:function()
  {
    var IMBox = this;

    IMBox.$window.remove();

    $.each(CometChat.IMBoxes, function(i)
    {
      if(IMBox == this)
      {
        CometChat.IMBoxes.splice(i, 1);
        return false;
      }
    });


    if($("#chatBar #taskBar div").length == 0)
    {
      $("#windowBar").css("bottom", "0px");
    }
  },
  addMessage:function(username, userLink, message, timestamp, temp)
  {
    if(temp)
    {
      var extraClass = ' class="Temp"';
    }
    else
    {
      var extraClass = '';
    }

    var messageHTML = CometChat.templates.IMMessage.
      replace(/{USERNAME}/g, username).
      replace(/{USERLINK}/g, userLink).
      replace(/{MESSAGE}/g, message).
      replace(/{TIMESTAMP}/g, timestamp);
      
    var atBottom = false;
    
    var currentScroll = this.$messages.scrollTop()+150;
    var messagesHeight = 0;
    $.each(this.$messages.find("li"), function() {
      var $this = $(this);
      messagesHeight += $this.height() + 
        parseInt($this.css("padding-top")) + 
        parseInt($this.css("padding-bottom")) + 
        parseInt($this.css("margin-top")) +
        parseInt($this.css("margin-bottom")) + 
        parseInt($this.css("border-top-width")) + 
        parseInt($this.css("border-bottom-width"));
    });
    
    if (currentScroll >= (messagesHeight - 20) || messagesHeight  < 150) {
      var atBottom = true;
    } else {
      var atBottom = false;
    }
        
    this.$messages.append("<li "+extraClass+">"+messageHTML+"</li>");
    
    if (CometChat.currentUsername == username || atBottom) {
      this.$messages.scrollTop(1000000);
    }
  }
};

//############### TEMPLATES ######################
CometChat.templates = {
  userOnline:'' +
  '<div style="overflow:hidden; clear:both; margin-bottom:5px;" class="OnlineUser" rel="{USERID}">' +
  '  <div style="float:left" class="CleanBorderSmall">' +
  '    <a onclick="CometChat.openIM({USERID}, \'{USERNAME}\');" style="cursor:pointer;"><img src="{USERIMAGE}" style="width:40px" /></a>' +
  '  </div>' +
  '  <div style="overflow:hidden; padding-left:3px;">' +
  '    <div style="margin-bottom:3px; cursor:pointer;">' +
  '      <a onclick="CometChat.openIM({USERID}, \'{USERNAME}\');" style="font-family: arial; font-size: 11px; color: {USERCOLOR};">{USERNAME}{STAFFIMAGE}</a>' +
  '    </div>' +
  '    <div style="overflow:hidden;">' +
  '      <div class="COCButton" style="float:left;" onclick="CometChat.openIM({USERID}, \'{USERNAME}\');">' +
  '        <a>Chat</a>' +
  '      </div>' +
  '      <div class="COCButton" style="float:left;">' +
  '        <a href="{USERLINK}" target="_blank">Profile</a>' +
  '      </div>' +
  '    </div>' +
  '  </div>' +
  '</div>',
  chatMessage:'' +
  '<div style="overflow:hidden;">' +
  '  <div class="MessageInfo">' +
  '    <div class="MessageTimestamp">' +
  '      {TIMESTAMP}' +
  '    </div>' +
  '    <div class="MessageLink" style="color: #6c6c6c;">' +
  '      <a href="{USERLINK}" target="_blank" style="color: {USERCOLOR}; text-decoration: none;">{USERNAME}{STAFFIMAGE}</a>:' +
  '      {MESSAGE}' +
  '    </div>' +
  '  </div>' +
  '</div>',
  IMBox:'' +
  '<div class="IMWindow" id="IM_{USERID}">' +
  ' <div class="IMHeadshot CleanBorderSmall">' +
  '   <a href="{USERLINK}" target="_blank"><img src="{USERIMAGE}" style="width:40px;" class="MessageUserImage" /></a>' +
  ' </div>' +
  ' <form class="IMForm">' +
  '   <div class="Title">' +
  '     <div class="Text">{USERNAME}</div>' +
  '     <div class="Buttons"><img src="/images/icons/chat_max.gif" class="MaxButton" /><img src="/images/icons/chat_min.gif" class="MinButton" /><img src="/images/icons/chat_close.gif" class="CloseButton" /></div>' +
  '   </div>' +
  '   <div class="Area">' +
  '     <ul class="Messages"></ul>' +
  '     <div style="overflow:hidden;">' +
  '       <input type="text" name="NewMessage" class="NewMessage" />' +
  '       <div class="COCButton SendMessage" style="font-family: arial; font-size: 10px; color: #2d6fab;"><a>SEND</a></div>' +
  '     </div>' +
  '   </div>' +
  ' </form>' +
  '</div>',
  IMMessage:'' +
  '<div style="overflow:hidden;">' +
  ' <div style="float:right; color:#777777; padding-left:5px;">{TIMESTAMP}</div>' +
  ' <a href="{USERLINK}" target="_blank" style="font-weight:bold;">{USERNAME}</a>: {MESSAGE}' +
  '</div>'
};

//############### HELPER FUNCTIONS #####################
function htmlentities( string ){
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: table from http://www.the-art-of-web.com/html/character-codes/
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'

    var histogram = {}, code = 0, tmp_arr = [];

    histogram['34'] = 'quot';
    histogram['38'] = 'amp';
    histogram['60'] = 'lt';
    histogram['62'] = 'gt';
    histogram['160'] = 'nbsp';
    histogram['161'] = 'iexcl';
    histogram['162'] = 'cent';
    histogram['163'] = 'pound';
    histogram['164'] = 'curren';
    histogram['165'] = 'yen';
    histogram['166'] = 'brvbar';
    histogram['167'] = 'sect';
    histogram['168'] = 'uml';
    histogram['169'] = 'copy';
    histogram['170'] = 'ordf';
    histogram['171'] = 'laquo';
    histogram['172'] = 'not';
    histogram['173'] = 'shy';
    histogram['174'] = 'reg';
    histogram['175'] = 'macr';
    histogram['176'] = 'deg';
    histogram['177'] = 'plusmn';
    histogram['178'] = 'sup2';
    histogram['179'] = 'sup3';
    histogram['180'] = 'acute';
    histogram['181'] = 'micro';
    histogram['182'] = 'para';
    histogram['183'] = 'middot';
    histogram['184'] = 'cedil';
    histogram['185'] = 'sup1';
    histogram['186'] = 'ordm';
    histogram['187'] = 'raquo';
    histogram['188'] = 'frac14';
    histogram['189'] = 'frac12';
    histogram['190'] = 'frac34';
    histogram['191'] = 'iquest';
    histogram['192'] = 'Agrave';
    histogram['193'] = 'Aacute';
    histogram['194'] = 'Acirc';
    histogram['195'] = 'Atilde';
    histogram['196'] = 'Auml';
    histogram['197'] = 'Aring';
    histogram['198'] = 'AElig';
    histogram['199'] = 'Ccedil';
    histogram['200'] = 'Egrave';
    histogram['201'] = 'Eacute';
    histogram['202'] = 'Ecirc';
    histogram['203'] = 'Euml';
    histogram['204'] = 'Igrave';
    histogram['205'] = 'Iacute';
    histogram['206'] = 'Icirc';
    histogram['207'] = 'Iuml';
    histogram['208'] = 'ETH';
    histogram['209'] = 'Ntilde';
    histogram['210'] = 'Ograve';
    histogram['211'] = 'Oacute';
    histogram['212'] = 'Ocirc';
    histogram['213'] = 'Otilde';
    histogram['214'] = 'Ouml';
    histogram['215'] = 'times';
    histogram['216'] = 'Oslash';
    histogram['217'] = 'Ugrave';
    histogram['218'] = 'Uacute';
    histogram['219'] = 'Ucirc';
    histogram['220'] = 'Uuml';
    histogram['221'] = 'Yacute';
    histogram['222'] = 'THORN';
    histogram['223'] = 'szlig';
    histogram['224'] = 'agrave';
    histogram['225'] = 'aacute';
    histogram['226'] = 'acirc';
    histogram['227'] = 'atilde';
    histogram['228'] = 'auml';
    histogram['229'] = 'aring';
    histogram['230'] = 'aelig';
    histogram['231'] = 'ccedil';
    histogram['232'] = 'egrave';
    histogram['233'] = 'eacute';
    histogram['234'] = 'ecirc';
    histogram['235'] = 'euml';
    histogram['236'] = 'igrave';
    histogram['237'] = 'iacute';
    histogram['238'] = 'icirc';
    histogram['239'] = 'iuml';
    histogram['240'] = 'eth';
    histogram['241'] = 'ntilde';
    histogram['242'] = 'ograve';
    histogram['243'] = 'oacute';
    histogram['244'] = 'ocirc';
    histogram['245'] = 'otilde';
    histogram['246'] = 'ouml';
    histogram['247'] = 'divide';
    histogram['248'] = 'oslash';
    histogram['249'] = 'ugrave';
    histogram['250'] = 'uacute';
    histogram['251'] = 'ucirc';
    histogram['252'] = 'uuml';
    histogram['253'] = 'yacute';
    histogram['254'] = 'thorn';
    histogram['255'] = 'yuml';

    for (i = 0; i < string.length; ++i) {
        code = string.charCodeAt(i);
        if (code in histogram) {
            tmp_arr[i] = '&'+histogram[code]+';';
        } else {
            tmp_arr[i] = string.charAt(i);
        }
    }

    return tmp_arr.join('');
}
