// JavaScript Document


function isIE()
{
  return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}



if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
  throw new Error( "This browser does not support XMLHttpRequest." )
};

var msg=0;
var input=0;
var user=0;
var last_id=0;
var chat=0;
var tmpString="";

function replaceHtml(el, html) {
	var oldEl = typeof el === "string" ? document.getElementById(el) : el;
	
	var newEl = document.createElement("div");
	newEl.id = oldEl.id;
	newEl.innerHTML = html;
	oldEl.parentNode.addChild(newEl);
	oldEl.parentNode.removeChild(oldEl);

	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;
};


function check()
{
	ajax = new XMLHttpRequest;
	ajax.onreadystatechange=function(){
		if(ajax.readyState==4 && String(ajax.responseText).length > 3){
			var msgs = String(ajax.responseText).split('</div>\n');
			var m=''
			tmpString = "";//String(document.getElementById(msg).innerHTML);
			var a = "";
			for(i=0;i<msgs.length;i++){
				m = String(msgs[i]).split(';');
				if(parseInt(m[0])>last_id){
					a = tmpString;
					tmpString = String(m[1]) + "</div>" + String(a);
					last_id=m[0];
				}
			}
			try
			{
				document.getElementById(msg).insertAdjacentHTML ('afterBegin',tmpString);
			}
			catch(err)
			{
				document.getElementById(msg).innerHTML = tmpString + document.getElementById(msg).innerHTML;
			}
			//alert("--"+document.getElementById(msg).innerHTML+"--");
			//msg.scrollY += 1000;
		}
	}
	ajax.open("POST",'chat.php',true);
	ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	ajax.send('action=check&user_id='+user+'&chat_id='+chat+'&last_id='+last_id);
	
}
function send()
{
	ajax = new XMLHttpRequest;
	ajax.open("POST",'chat.php',true);
	ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	ajax.send('action=send&user_id='+user+'&chat_id='+chat+'&msg='+escape(document.getElementById(input).value));
	document.getElementById(input).value = '';	
	
}

function makeChat(msg_id,input_id,button_id,user_id,chat_id)
{
		msg = (msg_id);
		input = (input_id);
		user= user_id;
		chat = chat_id;
		setInterval("check()",2000);
}

