// 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." )
};

function makeChat(msg_id,input_id,button_id,user_id,chat_id)
{
		this.msg = (msg_id);
		this.input = (input_id);
		this.user= user_id;
		this.chat = chat_id;
		this.last_id=0;
}

function replaceHtml(el, html) {
	//with (this) {
	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()
{
	with (this) {
		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",'includes/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()
{
	with (this){
	ajax = new XMLHttpRequest;
	ajax.open("POST",'includes/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 = '';	
	}
	
}

makeChat.prototype.send=send;
makeChat.prototype.check=check;

