function initJavaScript() {
	document.forms['chatForm'].elements['chatbarText'].setAttribute('autocomplete','off');
	checkStatus('');
	receiveChatText();
	MyContextMenu = document.getElementById('contextMenu');
	MyChatMenu = document.getElementById('chatMenu');
	document.onclick = onClickDocument;
	correctPNG();
}

function onClickDocument() {
	if(disableClickDocument == 0) {
		closeContextMenu();
		closeChatMenu();
	}
	else {
		disableClickDocument = 0;
	}
}

function eventKey() {
	if(document.all) {
		if(event.keyCode == 13) {
			sendComment();
		}
	}
}

function checkStatus(focusState) {
	currentChatText = document.forms['chatForm'].elements['chatbarText'];
	oSubmit = document.forms['chatForm'].elements['submit'];
	if (currentChatText.value != '' || focusState == 'active') {
		oSubmit.disabled = false;
	} else {
		oSubmit.disabled = true;
	}
}

function checkOnline(new_md5) {
	if(new_md5 != users_md5) {
		users_md5 = new_md5;
		receiveChatUsers();
	}
}

function checkRooms(new_md5) {
	if(new_md5 != rooms_md5) {
		rooms_md5 = new_md5;
		receiveChatRooms();
	}
}

function openContextMenu(e) {
	disableClickDocument = 1;
	if(!IE && e.which == 1) {
		selectedUser = this.text;
		selectedUserId = this.id;
		setWhisper();
	}
	MyContextMenu.style.display = "block";
	if(IE) {
		x = window.event.clientX;
		y = window.event.clientY;
		
		if(x+MyContextMenu.offsetWidth+15 > document.body.offsetWidth) {
			x = document.body.offsetWidth - 120;
		}
		selectedUser = this.innerText;
		selectedUserId = this.id;
	}
	else {
		x = e.pageX;
		y = e.pageY;
		if(x+MyContextMenu.offsetWidth+15 > window.innerWidth) {
			x = window.innerWidth - 120;
		}
		
		selectedUser = this.text;
		selectedUserId = this.id;
	}
	MyContextMenu.style.top = y + 5 + "px";
	MyContextMenu.style.left = x+15 + "px";
	return false;
}

function closeContextMenu() {
	if(MyContextMenu.style.display != "none") {
		MyContextMenu.style.display = "none";
		selectedUser = null;
		selectedUserId = null;
	}
}

function openChatMenu(e) {
	disableClickDocument = 1;
	MyChatMenu.style.display = "block";

	if(IE) {
		x = window.event.clientX;
		y = window.event.clientY;
		
		if(x+MyChatMenu.offsetWidth+15 > document.body.offsetWidth) {
			x = document.body.offsetWidth - 120;
		}
	}
	else {
/*		x = e.pageX;
		y = e.pageY;
		if(x+MyChatMenu.offsetWidth+15 > window.innerWidth) {
			x = window.innerWidth - 120;
		}*/
	}
	y=0;
	x=0;
	MyChatMenu.style.top = y + 5 + "px";
	MyChatMenu.style.left = x+15 + "px";
	return false;
}

function closeChatMenu() {
	if(MyChatMenu.style.display != "none") {
		MyChatMenu.style.display = "none";
	}
}

function setWhisper() {
	currentChatText = document.forms['chatForm'].elements['chatbarText'];
	if(selectedUser == null) {
		userName = IE ? this.innerText : this.text;
		currentChatText.value = "/to " + userName + " ";
	}
	else {
		currentChatText.value = "/to " + selectedUser + " ";
	}
	currentChatText.focus();
	closeContextMenu();
}

function insertSmile(obj) {
	var input = document.getElementById('chatbarText');
	input.focus();

	if(typeof document.selection != 'undefined') {
		var range = document.selection.createRange();
		
		var insText = range.text;
		range.text = obj.id + insText;
		
		range = document.selection.createRange();
		if (insText.length == 0) {
			range.move('character', -eTag.length);
		} else {
			range.moveStart('character', aTag.length + insText.length + eTag.length);      
		}

		range.select();
	}
	else
	{
		var start = input.selectionStart;
		var end = input.selectionEnd;
		var insText = input.value.substring(start, end);
		input.value = input.value.substr(0, start) + obj.id + insText + input.value.substr(end);
		
		var pos;
		if (insText.length == 0) {
			pos = start + obj.id.length;
		} else {
			pos = start + obj.id.length + insText.length;
		}
		
		input.selectionStart = pos;
		input.selectionEnd = pos;
	}
}

function viewProfil() {
	window.open("viewProfil.php?userid=" + selectedUserId, "UserProfil", "toolbar=0,statusbar=0,scrollbars=yes,width=450,height=300");
}

function viewMyProfil() {
	window.open("viewProfil.php?userid=" + myUserId, "UserProfil", "toolbar=0,statusbar=0,scrollbars=yes,width=450,height=300");
}

function viewColor(obj) {
	document.getElementById('colorViewer').style.backgroundColor = obj.id;
}

function setOrigColor() {
	document.getElementById('colorViewer').style.backgroundColor = color;
}

function setColor(obj) {
	color = obj.id;
}

function changeRoom() {
	password="";
	if(this.className == "prooms") {
		password = prompt("Bitte Passwort eingeben","");
	}
	if(password == null) {
		return false;
	}
	sendChangeRoom(this.innerHTML, password);
}

function ChangeRoomReady() {
	receiveChatText();
	window.setTimeout("receiveChatRooms()", 200);
}

function createRoom() {
	RNDIV = document.getElementById('createRoomName');
	RNDIV.style.top = ((document.body.offsetHeight - RNDIV.offsetHeight) / 2) + "px";
	RNDIV.style.left = ((document.body.offsetWidth - RNDIV.offsetWidth) / 2) + "px";
}

function createRoomNameAccept() {
	createRoomName = document.getElementById('createRoomNameField').value;
	createRoomNameAbort();
	openRoomPasswort();
}

function openRoomPasswort() {
	RNDIV = document.getElementById('createRoomPasswort');
	RNDIV.style.top = ((document.body.offsetHeight - RNDIV.offsetHeight) / 2) + "px";
	RNDIV.style.left = ((document.body.offsetWidth - RNDIV.offsetWidth) / 2) + "px";
}	

function createRoomPasswortAccept() {
	createRoomPasswort = document.getElementById('createRoomPasswortField').value;
	sendCreateRoom(createRoomName, createRoomPasswort);
	createRoomPasswortAbort();
	createRoomClearAll();
}

function createRoomNameAbort() {
	RNDIV = document.getElementById('createRoomName');
	RNDIV.style.top = "-1000px";
	RNDIV.style.left = "-1000px";
}
	
function createRoomPasswortAbort() {
	RNDIV = document.getElementById('createRoomPasswort');
	RNDIV.style.top = "-1000px";
	RNDIV.style.left = "-1000px";
	createRoomClearAll();
}

function createRoomClearAll() {
	document.getElementById('createRoomNameField').value = "";
	document.getElementById('createRoomPasswortField').value = "";
	createRoomName = "";
	createRoomPasswort = "";
}	

function CreateRoomReady() {
	receiveChatText();
	receiveChatRooms();
	receiveChatUsers();
}

function receiveChatText() {
	if (httpReceiveChat.readyState == 4 || httpReceiveChat.readyState == 0) {
  	httpReceiveChat.open("GET",GetChaturl + '?lastID=' + lastID + '&rand='+Math.floor(Math.random() * 1000000), true);
    httpReceiveChat.onreadystatechange = handleHttpReceiveChat; 
  	httpReceiveChat.send(null);
	}
}

function receiveChatUsers() {
	if (httpReceiveChatUsers.readyState == 4 || httpReceiveChatUsers.readyState == 0) {
  	httpReceiveChatUsers.open("GET",GetChatUsers + '?rand='+Math.floor(Math.random() * 1000000), true);
    httpReceiveChatUsers.onreadystatechange = handleHttpReceiveChatUsers; 
  	httpReceiveChatUsers.send(null);
	}
}
	
function receiveChatRooms() {
	if (httpReceiveChatRooms.readyState == 4 || httpReceiveChatRooms.readyState == 0) {
  	httpReceiveChatRooms.open("GET",GetChatRooms + '?rand='+Math.floor(Math.random() * 1000000), true);
    httpReceiveChatRooms.onreadystatechange = handleHttpReceiveChatRooms; 
  	httpReceiveChatRooms.send(null);
	}
}
	
function sendComment() {
	currentChatText = document.forms['chatForm'].elements['chatbarText'].value.replace(/&/g, "|und|").replace(/\+/g, "|plus|");
	if (currentChatText != '' & (httpSendChat.readyState == 4 || httpSendChat.readyState == 0)) {
		param = 'text='+ currentChatText + '&color=' + color;
		httpSendChat.open("POST", SendChaturl, true);
		httpSendChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  		httpSendChat.onreadystatechange = handleHttpSendChat;
  		httpSendChat.send(param);
  		document.forms['chatForm'].elements['chatbarText'].value = '';
	} else {
		setTimeout('sendComment();',1000);
	}
}

function sendChangeRoom(room, password) {
	if (httpSendChangeRoom.readyState == 4 || httpSendChangeRoom.readyState == 0) {
		param = 'room=' + room.replace(/&gt;&gt;/, "");
		if(password != null) {
			param += '&password='+ password;
		}
		httpSendChangeRoom.open("POST", SendChangeRoom, true);
		httpSendChangeRoom.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  		httpSendChangeRoom.onreadystatechange = ChangeRoomReady;
  		httpSendChangeRoom.send(param);
	} else {
		setTimeout('sendChangeRoom("' + room + ',' + password + '");',1000);
	}
}
	
function sendCreateRoom(roomName, roomPassword) {
	if (httpSendCreateRoom.readyState == 4 || httpSendCreateRoom.readyState == 0) {
		param = 'roomName=' + roomName;
		if(roomPassword != "") {
			param += '&roomPassword='+ roomPassword;
		}
		httpSendCreateRoom.open("POST", SendCreateRoom, true);
		httpSendCreateRoom.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  		httpSendCreateRoom.onreadystatechange = CreateRoomReady;
  		httpSendCreateRoom.send(param);
	} else {
		setTimeout('sendCreateRoom("' + roomName + '", "' + roomPassword + '");',1000);
	}
}
	

function handleHttpReceiveChat() {
  if (httpReceiveChat.readyState == 4) {
    results = httpReceiveChat.responseText.split('\n');
    
    for(i=0; i<(results.length-1);i++) {
	    message = results[i].split('\t');
	    
	    if(message[0] == "message" || message[0] == "pmessage") {
	    	insertNewContent(message[2], message[3], message[0], message[4]);
	    	lastID = message[1];
    	}
    	
    	if(message[0] == "system") {
	    	if(message[1] == "online") {
		    	checkOnline(message[2]);
	    	}

	    	if(message[1] == "rooms") {
		    	checkRooms(message[2]);
	    	}
    	}
    }
	    
    setTimeout('receiveChatText();',3000);
  }
}

function handleHttpReceiveChatUsers() {
  if (httpReceiveChatUsers.readyState == 4) {
    results = httpReceiveChatUsers.responseText.split('\n');
    
    updateUsers(results);
  }
}

function handleHttpReceiveChatRooms() {
  if (httpReceiveChatRooms.readyState == 4) {
    results = httpReceiveChatRooms.responseText.split('\n');
    
    updateRooms(results);
  }
}

function handleHttpSendChat() {
  if (httpSendChat.readyState == 4) {
  	receiveChatText();
  }
}

function insertNewContent(liName, liText, typ, color) {
	insertO = document.getElementById("outputList");
	oLi = document.createElement('li');
	oTable = document.createElement('table');
	
	oRow = oTable.insertRow(0);
	
	oTd = oRow.insertCell(0);
	if(typ == "pmessage") {
		oTd.setAttribute('className','pname');
		oTd.setAttribute('class','pname');
	}
	else {
		oTd.setAttribute('className','name');
		oTd.setAttribute('class','name');
	}
	
	oTd.vAlign = "top";
	oTd.noWrap = true;
	oText = document.createTextNode(liName+': ');
	oTd.appendChild(oText);
	
	oTd = oRow.insertCell(1);
	oTd.innerHTML = liText;
	if(typ == "pmessage") {
		oTd.setAttribute('className','pname');
		oTd.setAttribute('class','pname');
	}
	
	oTd.style.color = color;
	
	oLi.appendChild(oTable);
	insertO.appendChild(oLi);
	correctPNG();
	document.getElementById('scrollOutputDiv').scrollTop = parseInt(document.getElementById('chatOutput').offsetHeight);

}

function updateUsers(results) {
	insertO = document.getElementById("UserOutputList");
    for(i=insertO.childNodes.length;i>=1;i--) {
	    insertO.removeChild(insertO.childNodes[i-1]);
    }
    for(i=0; i<(results.length-1);i++) {
	    user = results[i].split('\t');
	    oLi = document.createElement('li');
	    oA = document.createElement('a');
	    if(IE) {
	    	oA.onclick = setWhisper;
    	}
    	else {
	    	oA.onclick = openContextMenu;
    	}
	    oA.oncontextmenu = openContextMenu;
	    oA.href="#";
   		
	    oA.setAttribute('className','name');
		oA.setAttribute('class','name');
		oA.setAttribute('id', user[1]);
		
		oText = document.createTextNode(user[2]);
	    
		if(user[1] != 0) {
			oLi.appendChild(oA);
			oA.appendChild(oText);
		}
		else {
			oLi.appendChild(oText);
		}
	
		insertO.appendChild(oLi);
    }
}

function updateRooms(results) {
	insertO = document.getElementById("roomOutputList");
    for(i=insertO.childNodes.length;i>=1;i--) {
	    insertO.removeChild(insertO.childNodes[i-1]);
    }
    for(i=0; i<(results.length-1);i++) {
	    rooms = results[i].split('\t');
		
	    oLi = document.createElement('li');
	    oA = document.createElement('a');
	    oA.onclick = changeRoom;
	    oA.href="#";
		oText = document.createTextNode(rooms[2]);
		
		if(rooms[0] == "prooms") {
			oA.setAttribute('className','prooms');
			oA.setAttribute('class','prooms');
		}
		else {
			oA.setAttribute('className','rooms');
			oA.setAttribute('class','rooms');
    	}
    	
		oLi.appendChild(oA);
		oA.appendChild(oText);
		
		insertO.appendChild(oLi);
    }
}

function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 or higher.
{
	if(IE) {
		for(var i=0; i<document.images.length; i++)
		{
			var img = document.images[i]
			var imgName = img.src.toUpperCase()
			if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
			{
				var imgID = (img.id) ? "id='" + img.id + "' " : ""
				var imgClass = (img.className) ? "class='" + img.className + "' " : ""
				var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
				var imgStyle = "display:inline-block;" + img.style.cssText
				var imgAttribs = img.attributes;
				for (var j=0; j<imgAttribs.length; j++)
				{
					var imgAttrib = imgAttribs[j];
					if (imgAttrib.nodeName == "align")
					{
						if (imgAttrib.nodeValue == "left") imgStyle = "float:left;" + imgStyle
						if (imgAttrib.nodeValue == "right") imgStyle = "float:right;" + imgStyle
						break
					}
				}
				var strNewHTML = "<span " + imgID + imgClass + imgTitle
				strNewHTML += " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
				strNewHTML += "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
				strNewHTML += "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
				img.outerHTML = strNewHTML
				i = i-1
			}
		}
	}
}

var GetChaturl = "getChatData.php";
var GetChatUsers = "getChatUsers.php";
var GetChatRooms = "getChatRooms.php";
var SendChaturl = "sendChatData.php";
var SendChangeRoom = "sendChangeRoom.php";
var SendCreateRoom = "sendCreateRoom.php";

var lastID = -1;
var users_md5 = "";
var rooms_md5 = "";
var color = "#000000";

var timeoutCloseMenu = null;
var selectedUser = null;
var selectedUserId = null;

var createRoomName = null;
var createRoomPasswort = null;

var httpReceiveChat = getHTTPObject();
var httpReceiveChatUsers = getHTTPObject();
var httpReceiveChatRooms = getHTTPObject();

var httpSendChat = getHTTPObject();
var httpSendChangeRoom = getHTTPObject();
var httpSendCreateRoom = getHTTPObject();

var MyContextMenu = null;
var MyChatMenu = null;
var disableClickDocument = 0;

var IE = document.all ? true : false;

window.onload = initJavaScript;
