// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
var showErrors = true;
var direction = '';

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject()
{
  var xmlHttp;
  // this should work for all browsers except IE6 and older
  try
  {
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    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
      {
         xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      }
      catch (e) {} // ignore potential error
    }
  }
  // return the created object or display an error message
  if (!xmlHttp){
	 // alert("Error creating the XMLHttpRequest object.");
  }
  else
    return xmlHttp;
}


function displayError($message)
{
  if (showErrors)
  {
    showErrors = false;
    //alert("Error encountered: \n" + $message);
  }
}





//******************************************************************************//
//**			SEND MESSAGE TO CHAT AND UPDATE THE CHAT WINDOW		   		  **//
//******************************************************************************//
function sendMessageToDB(messagetext,sendmessage)
{

  if (xmlHttp)
  {
	// try to connect to the server
    try
    {
      if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
      {

        // Display "Loading..." message while loading feed
        //document.getElementById("loading").style.display = "block";

        document.getElementById('sendmessage').messagetext.value = '';

       // Call the server page to execute the server-side operation
        params = "location=1&messagetext=" + messagetext + "&sendmessage=" + sendmessage;
        xmlHttp.open("POST", "add_msg_chat_ajax.php", true);
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttp.onreadystatechange = handleHttp_sendMessageToDB;
        xmlHttp.send(params);
      }
      else
      {
        // if connection was busy, try again after 1 second
        setTimeout("sendMessageToDB('" + messagetext + "' , " + sendmessage + " );", 1000);
      }
    }
    // display the error in case of failure
    catch (e)
    {
      //displayError(e.toString());
    }
  }
}


// function that retrieves the HTTP response
function handleHttp_sendMessageToDB()
{
  // continue if the process is completed
  if (xmlHttp.readyState == 4)
  {
   // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200)
    {
      try
      {
        displayINFO();
      }
      catch(e)
      {
        // display error message
        //displayError(e.toString());
      }
    }
    else
    {
      //displayError(xmlHttp.statusText);
    }
  }
}

function displayINFO()
{
  // read server response as text, to check for errors
  var response = xmlHttp.responseText;
  if (response.indexOf("ERRNO") >= 0 || response.indexOf("error:") >= 0 || response.length == 0)
    throw(response.length == 0 ? "Void server response." : response);

  // hide the "Loading..." message upon feed retrieval
  //document.getElementById("loading").style.display = "none";

  // append XSLed XML content to existing DOM structure

  var ChatContainer = document.getElementById("chat_window");
  ChatContainer.innerHTML = response;

}
//******************************************************************************//
//**			END SEND MESSAGE TO CHAT AND UPDATE THE CHAT WINDOW		   	  **//
//******************************************************************************//







//******************************************************************************//
//**					UPDATE THE CHAT WINDOW		  				 		  **//
//******************************************************************************//
function updateChatWindow()
{
  if (xmlHttp)
  {
	// try to connect to the server
    try
    {
      if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
      {

        // Display "Loading..." message while loading feed
        //document.getElementById("loading").style.display = "block";

        // Call the server page to execute the server-side operation
        params = "";
        xmlHttp.open("POST", "update_msg_chat_ajax.php", true);
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttp.onreadystatechange = handleHttp_updateChatWindow;
        xmlHttp.send(params);
      }
      else
      {
        // if connection was busy, try again after 1 second
        setTimeout("updateChatWindow();", 1000);
      }
    }
    // display the error in case of failure
    catch (e)
    {
      //displayError(e.toString());
    }
  }
}


// function that retrieves the HTTP response
function handleHttp_updateChatWindow()
{
  // continue if the process is completed
  if (xmlHttp.readyState == 4)
  {
   // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200)
    {
      try
      {
        displayINFO_CHAT();
      }
      catch(e)
      {
        // display error message
        //displayError(e.toString());
      }
    }
    /*else
    {
      displayError(xmlHttp.statusText);
    }  */
  }
}

function displayINFO_CHAT()
{
  // read server response as text, to check for errors
  var response = xmlHttp.responseText;
  if (response.indexOf("ERRNO") >= 0 || response.indexOf("error:") >= 0 || response.length == 0)
    throw(response.length == 0 ? "Raspunsul de la server." : response);

  // hide the "Loading..." message upon feed retrieval
  //document.getElementById("loading").style.display = "none";

  // append XSLed XML content to existing DOM structure

  var ChatContainer = document.getElementById("chat_window");

  var newData = response;
  //var clearCurrentText = ChatContainer.innerHTML.toUpperCase().replace(/ /gi,'').replace(/\t/gi,'').replace(/\n/gi,'').replace(/\r/gi,'').replace(/"/gi,'').replace(/&QUOT;/gi,'');
  //var clearFutureText  = response.toUpperCase().replace(/ /gi,'').replace(/\t/gi,'').replace(/\n/gi,'').replace(/\r/gi,'').replace(/"/g,'').replace(/&QUOT;/gi,'');
  //alert(clearCurrentText);
  //alert(clearFutureText);

  // if(clearCurrentText != clearFutureText){
  	 //playSound(0);
  	 ChatContainer.innerHTML = newData;
  //}

  setTimeout("updateChatWindow()", 2000);

}
//******************************************************************************//
//**					END UPDATE THE CHAT WINDOW		 				  	  **//
//******************************************************************************//






//******************************************************************************//
//**					Controleaza cenzura in chat  				 		  **//
//******************************************************************************//
function check_cenzura(messagetext)
{
  if (xmlHttp)
  {
	// try to connect to the server
    try
    {
      if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
      {
      	//alert("textul = " + messagetext);
        params = "messagetext=" + messagetext;
        xmlHttp.open("POST", "check_cenzura_ajax.php", true);
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttp.onreadystatechange = handleHttp_cenzuraChat;
        xmlHttp.send(params);
      }
    }
    catch (e)
    {}
  }
}


function handleHttp_cenzuraChat()
{
  if (xmlHttp.readyState == 4)
  {
    if (xmlHttp.status == 200)
    {
      try
      {
        display_mat();
      }
      catch(e)
      {}
    }
  }
}

function display_mat()
{
  // read server response as text, to check for errors
  var response = xmlHttp.responseText;
  if (response.indexOf("ERRNO") >= 0 || response.indexOf("error:") >= 0 || response.length == 0)
    throw(response.length == 0 ? "Raspunsul de la server." : response);

  //alert(response);

  var ChatTextArea = document.getElementById('messagetext');

  if(response == '1'){

  	 ChatTextArea.style.color = "#FF0000";
  	 }
  else{
  	 ChatTextArea.style.color = "#000000";

  	 }

}
//******************************************************************************//
//**					END Controleaza cenzura in chat 				  	  **//
//******************************************************************************//

