var CometChat = {
  currentUsername:null,
  currentUserLink:null,
  currentUserImage:null,
  currentUserStaff:'0',
  driverFrame:null,
  usersOnlineBoxes:[],
  openRooms:[],
  IMBoxes:[],
  inputEnabled:true,
  liveHelpAvailable:false,
  invisible:1,
  invisibleConfirmed:true,
  fallback:true,
  blinkReady:false,
  staffColor:'#FF0000',
  staffImageType:'.gif',
  liveTime:0,
  initialize:function(cometDomain, domainMask)
  {
    $("body").append("<iframe id=\"cometChatDriverFrame_"+cometDomain+"\" name=\"cometChatDriverFrame_"+cometDomain+"\" style=\"display:none;width:0;height:0;\"></iframe>");
    CometChat.driverFrame = window.frames['cometChatDriverFrame_'+cometDomain];
    CometChat.driverFrame.location.href = "http://"+cometDomain+domainMask+"/chatdriver.php?cache=1";
    
    $(".LiveHelpRequest").click(function()
    {
      CometChat.sendLiveHelpRequest();
    });

    $(".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';
    }

    //Live help
    moduleXML += '<module name="LiveHelp"><available>'+liveHelp+'</available></module>';
    
    //Count down
    moduleXML += '<module name="CountDown"><liveTime>'+CometChat.liveTime+'</liveTime></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
          updateBox.removeOnlineUser(parseInt($(this).text()));
        });

        $("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 ageSexLocation = $this.children('asl').text();
          
          updateBox.addOnlineUser(newUserID, newUsername, newUserImage, newUserLink, staff, ageSexLocation);
        });
      }
    });

    //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 $IMData = $("modules module[name=InstantMessanger]", $responseXML);
    $("window", $IMData).each(function()
    {
      var $this = $(this);

      var userType = $this.attr("userType");
      var userID = $this.attr("userID");

      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);
        }
        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();
            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;
          });
        }



      }

    });

    //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();
      }
    }
    
    //Count down
    var $countDownData = $("modules module[name=CountDown]", $responseXML);
    if($countDownData.length == 1 && $countDownData.children("newLiveTime").length == 1) {
      //Update the countdown time
      var newLiveTime = parseInt($countDownData.children("newLiveTime").text());
      var newTime = parseInt($countDownData.children("newTime").text());
      var lobbyVideo = $countDownData.children("lobbyVideo").text()
      
      CometChat.liveTime = newLiveTime;
      $("#countdown").get(0).resetCountDown(newTime, newLiveTime);
      
      if(newLiveTime > newTime) {
        setTimeout("CometChat.lobbyLoadVideo('alt')", 10);
      } else {
        setTimeout("CometChat.lobbyLoadVideo('live')", 10);
      }
    }


    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)
  {
    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);

      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");
  },
  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);
  },
  lobbyLoadVideo:function(videoType) {    
    
    var ajaxOptions = {
      'url':'/lobby.php',
      'type':'get',
      'data':{
        'video':videoType      
      },
      'dataType':'html',
      'success':function(data) {
        $("#lobbyVideo").html(data);
      },
      'error':function(data) {
        alert('Error:' + data);
      }
    };
    
    $.ajax(ajaxOptions);
  }

};

//############## 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, ageSexLocation)
  {
    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(/{ASL}/g, ageSexLocation).
      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);
    }
  },
  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();
  }
}

//############### 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);

  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()
  {
    room.$messages.children().remove();
  });
}

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)
{
  this.userID = setUserID;
  this.username = setUsername;
  this.userType = setUserType;

  this.minimized = setMinimized;
  this.initialized = setInitialized;
  this.lastUpdate = setLastUpdate;

  this.blinking = false;

  if(setInitialized)
  {
    this.blinkReady = false;
  }
  else
  {
    this.blinkReady = true;
  }

  this.blinking = false;

  var IMBoxHTML = CometChat.templates.IMBox.
    replace(/{USERID}/g, this.userID).
    replace(/{USERNAME}/g, this.username);

  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);

    this.$messages.append("<li "+extraClass+">"+messageHTML+"</li>");

    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}</a>' +
  '    </div>' +
  '    <div style="margin-bottom:3px; cursor:pointer;">' +
  '      {ASL}' +
  '    </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 class="MessageHeadshot CleanBorderSmall">' +
  '  <a href="{USERLINK}" target="_blank"><img src="{USERIMAGE}" style="width:40px;" class="MessageUserImage" /></a>' +
  '</div>-->' +
  '<div style="overflow:hidden; padding-left:10px;">' +
  '  <div class="MessageInfo">' +
  '    <div class="MessageLink">' +
  '      <a href="{USERLINK}" target="_blank" style="font-family: Myriad Pro; font-size:13px; color: {USERCOLOR}; text-decoration: none;">{USERNAME}</a> <span>says:</span>' +
  '    </div>' +
  '    <!--<div class="MessageTimestamp">' +
  '      {TIMESTAMP}' +
  '    </div>-->' +
  '  </div>' +
  '  <div class="Message">' +
  '    <span style="font-family: Myriad Pro;color: #636363; font-size:13px;">{MESSAGE}</span>' +
  '  </div>' +
  '</div>',
  IMBox:'' +
  '<div class="IMWindow" id="IM_{USERID}">' +
  ' <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('');
}
