var _sendHttp = GetXmlHttpObject();
var _recHttp = GetXmlHttpObject();
var _lastMsg = new Array();
var _mTimer;
var _popped = new Array();
var _lastPop = 1;
var _nrPop = 1;
var _roomPop = new Array();
var _newRoom;
var _thisRoom;
var _popPos = new Array("0", "130", "230", "410", "590", "770");
var _listTip;
var _lm = 0;
var _firstRun = true;

function listChat() {

	var xmlHttp = GetXmlHttpObject();
	var url = "/ajaxchat.php?cmd=listChat";
	xmlHttp.open("GET", url, true);
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			var xmlDoc = xmlHttp.responseXML;
			if (xmlDoc != null) {
				_listTip = "";
				var room_nodes = xmlDoc.getElementsByTagName("Room");
				var n_rooms = room_nodes.length;
				for (i = 0; i < n_rooms; i++) {
					if (room_nodes[i].getElementsByTagName("ID")[0])
						_listTip+= "<a href='javascript:;' onclick='connectTo(\""+room_nodes[i].getElementsByTagName("ID")[0].firstChild.nodeValue+"\", \"1\"); hideDyn(\"listDyn\");'>";
					if (room_nodes[i].getElementsByTagName("Name")[0])
						_listTip+= room_nodes[i].getElementsByTagName("Name")[0].firstChild.nodeValue;
					if (room_nodes[i].getElementsByTagName("ID")[0])
						_listTip+= " #"+room_nodes[i].getElementsByTagName("ID")[0].firstChild.nodeValue;
					if (room_nodes[i].getElementsByTagName("Author")[0])
						_listTip+= " by "+room_nodes[i].getElementsByTagName("Author")[0].firstChild.nodeValue;
					if (room_nodes[i].getElementsByTagName("ID")[0])
						_listTip+= "</a>";

					_listTip+= "<br />";
				}
				switchDyn("listDyn", _listTip);
			}
		}
	}
	xmlHttp.send(null);

}

function listMembers(cid) {

	var xmlHttp = GetXmlHttpObject();
	var url = "/ajaxchat.php?cmd=listMembers&id="+cid;
	xmlHttp.open("GET", url, true);
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			var xmlDoc = xmlHttp.responseXML;
			if (xmlDoc != null) {
				_listmTip = "";
				var name_nodes = xmlDoc.getElementsByTagName("Name");
				var n_names = name_nodes.length;
				for (i = 0; i < n_names; i++) {
					
					if (name_nodes[i].getAttribute('id'))
						_listmTip+= "<a href='/forum/members.php?id="+name_nodes[i].getAttribute('id')+"'>";
						
					_listmTip+= name_nodes[i].firstChild.nodeValue;
					
					if (name_nodes[i].getAttribute('id'))
						_listmTip+= "</a>";

					_listmTip+= "<br />";
				}
				switchDyn("listmDyn", _listmTip);
			}
		}
	}
	xmlHttp.send(null);

}

function showList() {
	listChat();
}

function chatLook() {

	var xmlHttp = GetXmlHttpObject();
	var url = "/ajaxchat.php?cmd=chatLook";
	xmlHttp.open("GET", url, true);
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			var xmlDoc = xmlHttp.responseXML;
			if (xmlDoc != null) {
				var room_nodes = xmlDoc.getElementsByTagName("Room");
				var n_rooms = room_nodes.length;
				for (i = 0; i < n_rooms; i++) {
					var chid = room_nodes[i].firstChild.nodeValue;
					var lid = room_nodes[i].getAttribute('id');
					if (lid == "invite") 
						acceptInvite(chid);
					else if (!document.getElementById("winChat"+chid) && (lid>_lastMsg[chid] || _lastMsg[chid] == null))
						connectTo(chid);
				}
			}
			setTimeout('chatLook();',4000);
			if (_nrPop>1 && !_mTimer) {
				getChatText();
				_mTimer = setInterval('getChatText()', 1000);
			}
			else if (_nrPop<2) {
				clearInterval(_mTimer);
				_mTimer = null;
			}
		}
	}
	xmlHttp.send(null);			

}

function scrollDown(id) {
	document.getElementById(id).scrollTop = document.getElementById(id).scrollHeight;
}

function chatMenu(cid, id, priv) {
	var menu;
	menu = "<a href='javascript:;' onclick='leaveChat(\""+cid+"\", \""+id+"\"); hideDyn(\"Op"+cid+"\");'>Leave chat</a>";
	menu+= "<br /><a href='javascript:;' onclick='listMembers(\""+cid+"\")'>List members</a>";
	menu+= "<br /><a href='javascript:;' onclick='invMemberDyn(\""+cid+"\")'>Invite member</a>";
	menu+= "<br /><a href='javascript:;' onclick='saveChat(\""+cid+"\")'>Save chat log</a>";
	menu+= "<br /><a href='javascript:;' onclick='terminateChat(\""+cid+"\", \""+id+"\"); hideDyn(\"Op"+cid+"\");'>Kill chat</a>";
	switchDyn("Op"+cid, menu);
}

function createRoom(priv, hide) {
	if (hide)
		var v = newPop("1");
	else
		var v = newPop();
	if (!v)
		return false;
	var popDiv = document.getElementById("sidepopped"+_lastPop);
	popDiv.innerHTML = "Chat #"+_newRoom;
	if (priv)
		popDiv.innerHTML+= " (private)";
	else
		popDiv.innerHTML+= " (public)";
	popDiv.innerHTML+= "<br /><div id='winChat"+_newRoom+"' class='winChat'></div>";
	popDiv.innerHTML+= "<form style='margin: 0 0 3px 0;' onsubmit='return blockSubmit(\""+_newRoom+"\");'><input id=\"ChatMessage"+_newRoom+"\" class=\"textbox_g2\" name=\"ChatMessage\" /> <input type=\"button\" value=\"Send\" name=\"ChatSend\" onclick='sendChatText(\""+_newRoom+"\");' />";
	popDiv.innerHTML+= "</form>";
	popDiv.innerHTML+= "<a href='javascript:;' onclick='chatMenu(\""+_newRoom+"\", \""+_lastPop+"\", \""+priv+"\");'>Options</a>";
	_roomPop[_newRoom] = _lastPop;
	document.getElementById("ChatMessage"+_newRoom).focus();
	if (_nrPop>1 && !_mTimer) {
		getChatText();
		_mTimer = setInterval('getChatText()', 1000);
	}
	else if (_nrPop<2) {
		clearInterval(_mTimer);
		_mTimer = null;
	}
}

function createChatRoom(priv) {

	var xmlHttp = GetXmlHttpObject();
	var url = "/ajaxchat.php?cmd=newChat";
	if (priv) {
		if (!document.getElementById("chatWith"))
			return;
		var chatWith = document.getElementById("chatWith").value;
		chatWith = urlCode(chatWith);
		url+= "&cw="+chatWith;
		hideDyn("privDyn");
	}
	xmlHttp.open("GET", url, true);
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			var xmlDoc = xmlHttp.responseXML;
			if (xmlDoc == null)
				return;
			_newRoom = xmlDoc.getElementsByTagName("Room")[0].firstChild.nodeValue;
			_lastMsg[_newRoom] = 0;
			if (priv)
				createRoom(1);
			else
				createRoom();	
		}
	}
	xmlHttp.send(null);
}
	
function getChatText() {
	if (_recHttp.readyState == 4 || _recHttp.readyState == 0) {
		_recHttp.open("GET", '/ajaxchat.php?cmd=getMsgs&lid='+_lm, true);
		_recHttp.onreadystatechange = function() {
			if (_recHttp.readyState == 4) { 
				handleReceiveChat();
			} 
		};
		_recHttp.send(null);
	}
}

function handleReceiveChat() {

	var chat_div = null;
	var cid, mid;
	var i, j;

	var xmlDoc = _recHttp.responseXML;
	if (xmlDoc != null) {
	
		var chat_nodes = xmlDoc.getElementsByTagName("Chat");
		for (i=0; i < chat_nodes.length; i++) {
		
			cid = chat_nodes[i].getAttribute("id");
			
			if (!document.getElementById('winChat'+cid))
				continue;
			
			chat_div = document.getElementById('winChat'+cid);

			var message_nodes = chat_nodes[i].getElementsByTagName("Message");
			for (j = 0; j < message_nodes.length; j++) {
				mid = message_nodes[j].getAttribute('id');
				if (_lastMsg[cid] == mid)
					continue;
				var user_node = message_nodes[j].getElementsByTagName("Author");
				var text_node = message_nodes[j].getElementsByTagName("Text");
				var time_node = message_nodes[j].getElementsByTagName("Time");
				var chatTime = "Message sent: "+time_node[0].firstChild.nodeValue;
				if (user_node[0].firstChild.nodeValue == "0") {
					chat_div.innerHTML += "<span class='chatSystem' onmouseover='showTip(\"chatTime\", \""+chatTime+"\")' onmouseout='hideTip(\"chatTime\")' onmousemove='moveTip(\"chatTime\")'>"+text_node[0].firstChild.nodeValue+"</span>";
					var saveLog = confirm(text_node[0].firstChild.nodeValue+"\nSave Chat log?");
					if (saveLog)
						saveChat(cid);
					closePop(_roomPop[cid]);
					return;
				}
				else {
					chat_div.innerHTML += "<span class='chatSender' onmouseover='showTip(\"chatTime\", \""+chatTime+"\")' onmouseout='hideTip(\"chatTime\")' onmousemove='moveTip(\"chatTime\")'>"+ user_node[0].firstChild.nodeValue +"</span>";
					chat_div.innerHTML += "<span class='chatDelimiter'> &raquo;</span> ";
					chat_div.innerHTML += text_node[0].firstChild.nodeValue + "<br />";
				}
				if (_lastMsg[cid] < mid) {
					_lastMsg[cid] = mid;
					if (!_firstRun && !_popped[_roomPop[cid]]) 
						document.getElementById("sidepopper"+_roomPop[cid]).style.backgroundPosition = "0 bottom";
				}
				if (_lm < mid)
					_lm  = mid;
			}
			if (j)
				document.getElementById("winChat"+cid).scrollTop = document.getElementById("winChat"+cid).scrollHeight;
				
		}
		
		_firstRun = false;
		
	}
	
}

function sendChatText(cid) {
	if (_sendHttp.readyState == 4 || _sendHttp.readyState == 0) {
		_sendHttp.open("POST", '/ajaxchat.php?id='+cid, false);
		_sendHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		var param = 'ChatMessage=' + urlCode(document.getElementById('ChatMessage'+cid).value);
		_sendHttp.send(param);
		document.getElementById('ChatMessage'+cid).value = '';
		document.getElementById('ChatMessage'+cid).focus();
	}
}

function blockSubmit(cid) {
	sendChatText(cid);
	return false;
}

/*

function GetXmlHttpObject()
{
	var xmlHttp=null;
	try  // Firefox, Opera 8.0+, Safari
	{		
		xmlHttp=new XMLHttpRequest();
	}
	catch (e) // Internet Explorer 6.0+
	{  
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		// 5.5+
		catch (e)
		{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	
	return xmlHttp;
}

*/

function sidePop(id, cid) {

	if (!_popped[id]) {
		document.getElementById("sidepopped"+id).style.display = "block";
		document.getElementById("sidepopper"+id).style.backgroundPosition = "0 center";
		_popped[id] = true;
		if (cid) {
			scrollDown("winChat"+cid);
			document.getElementById("ChatMessage"+cid).focus();
		}
	}
	else {
		document.getElementById("sidepopped"+id).style.display = "none";
		document.getElementById("sidepopper"+id).style.backgroundPosition = "0 top";
		_popped[id] = false;
	}

}

function newPop(hide, cid) {

	// Popped
	var nextPop = null;
	for (var i=2; i<6; i++) {
		if (!document.getElementById("sidepopped"+i)) {
			nextPop = i;
			break;
		}
	}
	if (nextPop == null) {
		alert("You can only have 4 chat windows");
		return false;
	}

	var popDiv = document.createElement('div');
	popDiv.setAttribute('id', "sidepopped"+nextPop);

	popDiv.className = "sidepopped";	

	document.body.appendChild(popDiv);

		
	popDiv.style.top = _popPos[nextPop]+"px";
	if (hide)
		popDiv.style.display = "none";
	else
		popDiv.style.display = "block";
	
	// Popper
	
	var popperDiv = document.createElement('div');
	popperDiv.setAttribute('id', "sidepopper"+nextPop);
	popperDiv.setAttribute('onclick', "sidePop(\""+nextPop+"\", \""+_newRoom+"\")");
	
	popperDiv.className = "sidepopper";
	
	document.body.appendChild(popperDiv);
		
	popperDiv.style.top = parseInt(_popPos[nextPop])+"px";
	if (hide)
		popperDiv.style.backgroundPosition = "0 top";
	else
		popperDiv.style.backgroundPosition = "0 center";
	
	// Finish
	
	_nrPop++;
	_lastPop = nextPop;
	if (hide)
		_popped[_lastPop] = false;
	else
		_popped[_lastPop] = true;
	
	return true;
}

function closePop(id) {

	if (!document.getElementById("sidepopped"+id))
		return;
		
	document.body.removeChild(document.getElementById("sidepopper"+id));
	document.body.removeChild(document.getElementById("sidepopped"+id));
	_popped[id] = false;
	_nrPop--;
	
}

function urlCode(text) {
	
	text = text.replace("$", "%24");
	text = text.replace("&", "%26");
	text = text.replace("+", "%2B");
	text = text.replace("?", "%3F");
	text = text.replace("=", "%3D");
	text = text.replace("/", "%2F");
	text = text.replace("@", "%40");
	text = text.replace(";", "%3B");
	text = text.replace(":", "%3A");
	text = text.replace(" ", "%20");

	return text;

}

function invMemberDyn(cid) {

	var invDyn = "<form onsubmit='return blockInv(\""+cid+"\")'>Invite: <input type='text' name='invMember"+cid+"' id='invMember"+cid+"' class='textbox_g2' /> <input type='button' value='Go' onclick='invMember(\""+cid+"\")' /></form>";
	
	switchDyn("invDyn", invDyn);
	document.getElementById("invMember"+cid).focus();

}

function blockInv(cid) {

	invMember(cid);
	return false;

}

function invMember(cid) {

	if (!document.getElementById("invMember"+cid))
		return;
	var chatWith = document.getElementById("invMember"+cid).value;
	chatWith = urlCode(chatWith);
	hideDyn("invDyn");

	var xmlHttp = GetXmlHttpObject();
	var url = "/ajaxchat.php?cmd=invMember&id="+cid+"&cw="+chatWith;
	xmlHttp.open("GET", url, false);
	xmlHttp.send(null);			
}

function acceptInvite(cid) {

	var accept = confirm("You have been invite to chat room #"+cid+", would you like to join?");
	if (accept)		
		var cmd = "acceptInv";
	else
		var cmd = "declineInv";
	
	var xmlHttp = GetXmlHttpObject();
	var url = "/ajaxchat.php?cmd="+cmd+"&id="+cid;
	xmlHttp.open("GET", url, true);
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			var xmlDoc = xmlHttp.responseXML;
			if (xmlDoc != null) {
				var access = xmlDoc.getElementsByTagName("Room")[0].firstChild.nodeValue;
				if (access == "private")
					createRoom(1, 0);
				else
					createRoom(0, 0);
			}
		}
	}
	xmlHttp.send(null);				

}

function saveChat(cid) {

	var xmlHttp = GetXmlHttpObject();
	var url = "/ajaxchat.php?cmd=saveChatLog&id="+cid;
	xmlHttp.open("GET", url, true);
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			alert("Chat log sent to your inbox");
		}
	}
	xmlHttp.send(null);			

}

function terminateChat(cid, id) {

	var sure = confirm("Terminate chat room?");
	
	if (!sure)
		return;

	var xmlHttp = GetXmlHttpObject();
	var url = "/ajaxchat.php?cmd=delChat&id="+cid;
	xmlHttp.open("GET", url, true);
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			closePop(id);
		}
	}
	xmlHttp.send(null);

}

function leaveChat(cid, id) {
	var xmlHttp = GetXmlHttpObject();
	var url = "/ajaxchat.php?cmd=leaveChat&id="+cid;
	xmlHttp.open("GET", url, true);
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			closePop(id);
		}
	}
	xmlHttp.send(null);
	
}

function blockPriv() {

	createChatRoom("1");
	return false;

}

function connectTo(cid, show) {
	
	if (show)
		var h = 0;
	else
		var h = 1;
	
	cid = parseInt(cid);
	
	if (document.getElementById("winChat"+cid)) {
		alert("You are already in that chat room");
		return;
	}
	
	var xmlHttp = GetXmlHttpObject();
	var url = "/ajaxchat.php?cmd=joinChat&id="+cid;
	xmlHttp.open("GET", url, true);
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			var xmlDoc = xmlHttp.responseXML;
			if (xmlDoc == null)
				return;
			_thisRoom = xmlDoc.getElementsByTagName("Room")[0].firstChild.nodeValue;
			if (_thisRoom == "denied") {
				alert("Sorry, that chat room is private.");
				return;
			}
			if (_thisRoom == "empty") {
				alert("That chat room doesn't exist.");
				return;
			}
			
			_newRoom = cid;
			_lastMsg[cid] = 0;
			if (_thisRoom == "private")
				createRoom(1, h);
			else
				createRoom(0, h);
		
			document.getElementById("ChatNr").value = '';
		}
	}
	xmlHttp.send(null);			

}

function connectChat() {

	var ChatID = document.getElementById("ChatNr").value;
	ChatID = parseInt(ChatID);
	
	connectTo(ChatID, 1);

}

function blockConnect() {
	connectChat();
	return false;
}

function createPrivRoom() {	
	createChatRoom("1");
}

function showH() {
	show("hint");
}

function hideS() {
	hideslow("hint");
}

function showHi(ev) {
	showHint(document.getElementById("chatWith").value, "userhint", ev, "chatWith");
}