var chatURL = "includes/mugs_chat/chat_ajax.php";
var xmlHttpGetMessages = createXmlHttpRequestObject();
var updateInterval = 1000;
var refreshcounter = 5;
var refreshturns = 5;
var debugMode = true;
var cache = new Array();
var lastMessageID = -1; 

/* creates an XMLHttpRequest instance */
function createXmlHttpRequestObject() 
{
  var xmlHttp;
  try
  {
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
      { 
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

/* this function initiates the chat; it executes when the chat page loads */
function init() 
{
  var oMessageBox = document.getElementById("messageBox");
  oMessageBox.setAttribute("autocomplete", "off");  
  requestNewMessages();
}
 
/* function called when the Send button is pressed */
function sendMessage()
{	
  var oCurrentMessage = document.getElementById("messageBox");
  var currentUser = document.getElementById("userName").value;
  var currentChat = document.getElementById("chatId").value;
  if (trim(oCurrentMessage.value) != "" && trim(currentUser) != "" && trim(currentChat) != "")
  {
    params =  "action=SendAndRetrieveNew" +
              "&id=" + encodeURIComponent(lastMessageID) + 
              "&name=" + encodeURIComponent(currentUser) + 
              "&message=" + encodeURIComponent(oCurrentMessage.value) +
              "&chatid=" + encodeURIComponent(currentChat);
    
    cache.push(params);
    oCurrentMessage.value = "";
  }
}

/* makes asynchronous request to retrieve new messages, post new messages */
function requestNewMessages()
{ 
  var currentUser = document.getElementById("userName").value;
  var currentChat = document.getElementById("chatId").value;
  var currentUserID = document.getElementById("userId").value;

  if(xmlHttpGetMessages)
  {
    try
    {
      // don't start another server operation if such an operation 
      //   is already in progress 
      if (xmlHttpGetMessages.readyState == 4 || xmlHttpGetMessages.readyState == 0) 
      {
    	// we will store the parameters used to make the server request
        var params = "";
        refreshcounter++;
        // Empfangen, Benutzerupdate und Kontrolle der anderen Benutzer
        if(refreshcounter > refreshturns){
        	refreshcounter = 0;
        	params = "action=UpdateAndRetrieveNew" +
        			 "&id=" +lastMessageID +
        			 "&chatid=" + encodeURIComponent(currentChat) +
                     "&name=" + encodeURIComponent(currentUser) +
                     "&userid=" + encodeURIComponent(currentUserID);
        }
        // if there are requests stored in queue, take the oldest one
        else if (cache.length>0){
        	params = cache.shift();
        }
        // if the cache is empty, just retrieve new messages        
        else
          params = "action=RetrieveNew" +
                   "&id=" +lastMessageID +
                   "&chatid=" + encodeURIComponent(currentChat) +
                   "&name=" + encodeURIComponent(currentUser);        
        // call the server page to execute the server-side operation
        xmlHttpGetMessages.open("GET", chatURL + '?' + params, true);
        xmlHttpGetMessages.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttpGetMessages.onreadystatechange = handleReceivingMessages;
        
        //alert(chatURL + '?' + params);
        
        xmlHttpGetMessages.send(null);
      }
      else
      {
        // we will check again for new messages 
        setTimeout("requestNewMessages();", updateInterval);
      }
    }
    catch(e)
    {
      displayError(e.toString());
    }
  }
}

/* function that handles the http response when updating messages */
function handleReceivingMessages() 
{
  // continue if the process is completed
  if (xmlHttpGetMessages.readyState == 4) 
  {
    // continue only if HTTP status is "OK"
    if (xmlHttpGetMessages.status == 200) 
    {
      try
      {
        // process the server's response
        readMessages();
      }
      catch(e)
      {
        // display the error message
        displayError(e.toString());
      }
    } 
    else
    {
      // display the error message
      displayError(xmlHttpGetMessages.statusText);
    }
  }
}

/* function that processes the server's response when updating messages */
function readMessages()
{  
  // retrieve the server's response 
  var response = xmlHttpGetMessages.responseText;
  // server error?
  if (response.indexOf("ERRNO") >= 0 || response.indexOf("error:") >= 0 || response.length == 0)
    throw(response.length == 0 ? "Void server response." : response);
  // retrieve the document element
  response = xmlHttpGetMessages.responseXML.documentElement;
  // retrieve the arrays from the server's response     
  idArray = response.getElementsByTagName("id");
  nameArray = response.getElementsByTagName("username");
  timeArray = response.getElementsByTagName("time");
  messageArray = response.getElementsByTagName("message");
  userArray = response.getElementsByTagName("chatuser");
  userIdArray = response.getElementsByTagName("chatuserid");
  chatIdArray = response.getElementsByTagName("chatid");
  chatNameArray = response.getElementsByTagName("chatname");
  chatPwArray = response.getElementsByTagName("chatpw");
  chatMembersArray = response.getElementsByTagName("chatmembers");
  // add the new messages to the chat window
  displayMessages(idArray, nameArray, timeArray, messageArray);
  // updates the "who`s online" window
  displayUsers(userArray, userIdArray);
  // updates the chatroom window
  displayChatrooms(chatIdArray, chatNameArray, chatPwArray, chatMembersArray);
  // the ID of the last received message is stored locally
  if(idArray.length>0) lastMessageID = idArray.item(idArray.length - 1).firstChild.data;
  // restart sequence
  setTimeout("requestNewMessages();", updateInterval);
}

/* function that appends the new messages to the chat list  */
function displayMessages(idArray, nameArray, timeArray, messageArray)
{
  // each loop adds a new message
  for(var i=0; i<idArray.length; i++)
  {
    // get the message details
    var time = timeArray.item(i).firstChild.data.toString();
    var name = nameArray.item(i).firstChild.data.toString();
    var message = messageArray.item(i).firstChild.data.toString();
    // compose the HTML code that displays the message
    var htmlMessage = "";
    htmlMessage += "<div style=\"margin-bottom: 6px;\">"; 
    htmlMessage += "<span style='color: #740000; font-style:italic;'>" + name + "</span> <span style='font-size: 10px; font-weight: bold;'>[" + time + "]</span>: <br/>";
    htmlMessage += message.toString() + "<br />";
    htmlMessage += "</div>";
    // display the message
    displayMessage(htmlMessage);
  }
}

// displays a message
function displayMessage(message)
{
  // get the scroll object
  var oScroll = document.getElementById("chat_scroll");
  // check if the scroll is down
  var scrollDown = (oScroll.scrollHeight - oScroll.scrollTop <= oScroll.offsetHeight );
  // display the message
  oScroll.innerHTML += message;
  // scroll down the scrollbar
  oScroll.scrollTop = scrollDown ? oScroll.scrollHeight : oScroll.scrollTop;
}

// displays the user-window
function displayUsers(userArray, userIdArray){
	
	var html = "";
	
	for(var i=0; i<userArray.length; i++){
		var user = userArray.item(i).firstChild.data.toString();
		var id = userIdArray.item(i).firstChild.data.toString();
		html += "<div style=\"margin-bottom: 2px; margin-left: 5px; font-weight: bold;\">";
		html += "<a href=\"profile_view.php?id=" + id + "\" target=\"_blank\" onclick=\"popup('profile_view.php?id=" + id + "'); return false\">" + user + "</a>";
		html += "</div>";
	}
	
	var oScroll = document.getElementById("chatuser_scroll");
	oScroll.innerHTML = html;
}

// displays the chatroom-window 
function displayChatrooms(chatIdArray, chatNameArray, chatPwArray, chatMembersArray){
	
	var html = "";
	
	for(var i=0; i<chatIdArray.length; i++){
		var chatName = chatNameArray.item(i).firstChild.data.toString();
		var chatId = chatIdArray.item(i).firstChild.data.toString();
		var chatMembers = chatMembersArray.item(i).firstChild.data.toString();
		var chatPw = chatPwArray.item(i).firstChild.data.toString();
		var locked = "";
		if(chatPw == "1") locked = "&nbsp; <img src=\"img/locked.jpg\" height=\"10\" width=\"10\">"; 
		
		html += "<div style=\"margin-bottom: 2px; margin-left: 5px; font-weight: bold;\">";
		html += "<a href=\"index.php?section=chat&switch=" + chatId + "\">" + chatName + "</a> &nbsp; (" + chatMembers + " online) " + locked + "";
		html += "</div>";
	}
	
	var oScroll = document.getElementById("chatrooms_scroll");
	oScroll.innerHTML = html;
	
}

// function that displays an error message
function displayError(message)
{
  // display error message, with more technical details if debugMode is true
  displayMessage("Error accessing the server! "+ (debugMode ? "<br/>" + message : ""));
}

/* handles keydown to detect when enter is pressed */
 
function handleKey(e) 
{
  // get the event
  e = (!e) ? window.event : e;
  // get the code of the character that has been pressed        
  code = (e.charCode) ? e.charCode :
         ((e.keyCode) ? e.keyCode :
         ((e.which) ? e.which : 0));
  // handle the keydown event       
  if (e.type == "keydown") 
  {
    // if enter (code 13) is pressed
    if(code == 13)
    {
      // send the current message  
      sendMessage();
    }
  }
}

/* removes leading and trailing spaces from the string */
function trim(s)
{
    return s.replace(/(^\s+)|(\s+$)/g, "")
}
