var chatURL = "/gather/chat/chat.php";
var updateInterval = 2000; // how many miliseconds to wait to get new message
var debugMode = false;
var lastMessageID = -1; 
var cache = new Array();
var entry = 0;





Event.observe(window,'load', function () {
	
	
	var list_grp_id = $('this_grp_id').value;
	
	var xhr_temp		= new Ajax.PeriodicalUpdater(
		'listUsers', 
		'/gather/grp_xhr_chat_list_links.php', 
		{
			method: 'get', 
			parameters: { grp_id : list_grp_id  },
			frequency: 3, 
			decay: 2
		}
	);

});




Event.observe(window, 'load', function () {
	if ( $('messageBox') ) {
	
		init();
	
		$('messageBox').observe('focus', function () {
			var updateInterval = 0;
		}).observe('blur', function () {
			var updateInterval = 20;
		});
		
	}
	
	
	
});










var XMLHttpRequestObject = getXMLHttp();

if (window.XMLHttpRequest) {
	XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
	XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}



function getXMLHttp() {
  var XMLHttp = null;
  if (window.XMLHttpRequest) {
    try {
      XMLHttp = new XMLHttpRequest();
    } catch (e) { }
  } else if (window.ActiveXObject) {
    try {
      XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) { }
    }
  }
  return XMLHttp;
}



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");
		// try every prog id until one works
		for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
		{
			try 
			{ 
				// try to create XMLHttpRequest object
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			} 
			catch (e) {}
		}
	}
	// return the created object or display an error message
	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 oRoomLoc 		= $("this_grp_id");
  var oMessageBox = $("messageBox");
  		



	sendMessage();
  requestNewMessages();
  
	
  
}

function sendMessage()
{
	if ( $('messageBox') )
	{
		var groupLoc 				= $('this_grp_id').value;
		var msgBoxValue 		= $('messageBox');
		var user_id  				= $('user_id').value;  
		var currentUser 		= $('userName').value;
		var currentColor 		= $('color').value;

		var params =  "mode=SendAndRetrieveNew";
				params += "&id=" + encodeURIComponent(lastMessageID);
				params += "&user_id=" + encodeURIComponent(user_id);
				params += "&name=" + encodeURIComponent(currentUser);
				params += "&grouploc=" + encodeURIComponent(groupLoc);
				params += "&message=" + encodeURIComponent(msgBoxValue.value);
				params += "&color=" + encodeURIComponent(currentColor);

		cache.push(params);

		msgBoxValue.value = "";

		requestNewMessages();
	}
}


function deleteMessages()
{
  // set the flag that specifies we're deleting the messages
  params = "mode=DeleteAndRetrieveNew";  
  // add the message to the queue
  cache.push(params);
}

/* makes asynchronous request to retrieve new messages, post new messages, delete messages */


function requestNewMessages()
{  

	//alert(params);
  // retrieve the roomlocation, username and color from the page
  var rGroupLoc 			= $("this_grp_id").value;
  var user_id  				= $('user_id').value;  
  var currentUser 		= $('userName').value;
  var currentColor 		= $('color').value;

	//alert(rGroupLoc);

  // only continue if XMLHttpRequestObject isn't void
  if(XMLHttpRequestObject)
  {
  
  	
    try
    {
      // don't start another server operation if such an operation 
      //   is already in progress 
      if (XMLHttpRequestObject.readyState == 4 || 
          XMLHttpRequestObject.readyState == 0) 
      {
        // we will store the parameters used to make the server request
        var params = "";
        // if there are requests stored in queue, take the oldest one
        if (cache.length>0)
          params = cache.shift();
        // if the cache is empty, just retrieve new messages        
        else
          params = "mode=RetrieveNew" +
              "&id=" + encodeURIComponent(lastMessageID) + 
              "&user_id=" + encodeURIComponent(user_id) + 
              "&name=" + encodeURIComponent(currentUser) + 
              "&grouploc=" + encodeURIComponent(rGroupLoc) + 
              "&color=" + encodeURIComponent(currentColor);
					
				//alert(params);
        //alert("rec message: " + params);
        // call the server page to execute the server-side operation
        XMLHttpRequestObject.open("POST", chatURL, true);
        XMLHttpRequestObject.setRequestHeader("Content-Type", 
                                   "application/x-www-form-urlencoded");
        XMLHttpRequestObject.onreadystatechange = handleReceivingMessages;
 
        XMLHttpRequestObject.send(params);
      }
      else
      {
        // we will check again for new messages 
        
        //console.log(updateInterval);
        
        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 (XMLHttpRequestObject.readyState == 4) 
  {
    // continue only if HTTP status is "OK"
    if (XMLHttpRequestObject.status == 200) 
    {
      try
      {
        // process the server's response
        readMessages();
      }
      catch(e)
      {
        // display the error message
        displayError(e.toString());
      }
    } 
    else
    {
      
      displayError(XMLHttpRequestObject.statusText);
    }
  }
}

/* function that processes the server's response when updating messages */
function readMessages()
{  
  // retrieve the server's response 
  //var response = XMLHttpRequestObject.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 = XMLHttpRequestObject.responseXML.documentElement;
  // retrieve the flag that says if the chat window has been cleared or not 
  clearChat = false;
           //response.getElementsByTagName("clear").item(0).firstChild.data;
  
  var scroll_str	= $('scroll').innerHTML;
  scroll_str			= scroll_str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  
  
  if ( scroll_str  == 'Loading...' )  $('scroll').innerHTML = '';
  
  
  if(clearChat == "true")
  {
    // clear chat window and reset the id
    $("scroll").innerHTML = '';
    //lastMessageID = -1;
    lastMessageID = 0;
 	}
  
  idArray 			= response.getElementsByTagName("id");
  colorArray 		= response.getElementsByTagName("color");
  nameArray 		= response.getElementsByTagName("name");
  messageArray 	= response.getElementsByTagName("message");
  
  
  displayMessages(idArray, colorArray, nameArray, messageArray);
  
  
  // 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, colorArray, nameArray, messageArray)
{
  
  for(var i=0; i<idArray.length; i++)
  {
    var colorHex 		= colorArray.item(i).firstChild.data.toString();
    var nameStr 		= nameArray.item(i).firstChild.data.toString();
    var msgStr 			= messageArray.item(i).firstChild.data.toString();
    
    
    
    var htmlMessage = "";
    htmlMessage += "<div onclick=\"$('messageBox').value='@ "+nameStr+" > ';$('messageBox').focus();return false;\" class=\"item cursor\" style=\"color: " + colorHex + "\">"; 
    htmlMessage += "<b>" +nameStr + "</b>: ";
    htmlMessage += msgStr.toString();
    htmlMessage += "</div>";
    
    
    

		//document.title = nameStr + ' is talking';
    
    // display the message
    displayMessage (htmlMessage);
  }
}


function displayMessage(message)
{
  var oScroll 		= $("scroll");
  var scrollDown 	= (oScroll.scrollHeight - oScroll.scrollTop <= oScroll.offsetHeight );

  oScroll.innerHTML += message;
	oScroll.scrollTop = scrollDown ? oScroll.scrollHeight : oScroll.scrollTop;
}

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





function switchSwatch(newColor) 
{
	$('color').value									= newColor.toUpperCase();
  $('swatch').style.background     	= newColor;
	$('messageBox').style.color			 	= newColor;
  $('messageBox').focus();
  
  Effect.Fade('colorPicker', {duration: 0.25});
  
  /*
 	var saveDiv = document.createElement('div');
 	var saveStr = document.createTextNode('Some content.');
	saveDiv.appendChild(saveStr);
	
	$('colorPickerId').appendChild(saveDiv);
  */
}


function trim(s)
{
    return s.replace(/(^\s+)|(\s+$)/g, "")
}

function displayError(message)
{
  displayMessage("Error accessing the server! "+ message);
}



function msgTo(userName_userId)
{
	var userArr	= userName_userId.split('~');
	
	
	$('messageBox').value= '@ '+ userArr[0] + ' > ';
	
	
	panelXHR(userArr[1]);
	
}



function getPanelProfile(userName_userId)
{
	var userArr	= userName_userId.split('~');

	panelXHR(userArr[1]);
}


function panelXHR(user_id)
{
	
	
	
	var xhrUrl		= '/gather/grp_xhr_chat_profile.php';
	var xhrTar		= 'userPanel';
	var xhrPar		= '&user_id='+user_id;
	var xhrCall 	= new Ajax.Updater(xhrTar, xhrUrl, {	method: 'get',	parameters: xhrPar});

}

