
var sDomain = document.domain; //"chat.visual-utopia.com";

var strSessionName = "vuid"
var strSession = queryStr(strSessionName);
var currentLanguage = "en";
var defaultChan = 'Chat Deamon';
var lastUpdate = new Date();
var sChanList = ''
var aChatHistory = new Array('');
var iHistoryIndex = 0
var sPmList = '';
var sIgnoreList = '';
var sFirstChan = '';
var iTxtHeight = 0;
var bFlashing = false;
var refreshRate = 1;
var aAlias = new Array();
var Xcursor = 0;
var Ycursor = 0;
var bFlashType = true;
var bGotFocus = true;
var sUserName = "";
var sChanName = "";
var iHideMenuX1 = 0
var iHideMenuX2 = 0
var iHideMenuY1 = 0
var iHideMenuY2 = 0
var bTranslate = false;
var showthemenu = new Object();
var getNewData;
var bMenuVisible = false;
var idInfo = '';
var runchmd = '' // Command to run at startup
var lastFocus = new Date();
var lastBlur = new Date();
var lastAction = new Date();
var updateInterval = 1;
var defaultUpdateInterval = 1
var bPlayingSound = false;
var bPlaySound = false;
var lastKey = 0;
var bQuitCommand = false;
var sentHello = false;
var debugmode = false;
var delay = -1;

var IE = false;
var FF = false;
var OPERA = (navigator.userAgent.indexOf('Opera') != -1);
var CHROME = (navigator.userAgent.indexOf('Chrome') != -1);
var SAFARI = (navigator.userAgent.indexOf('Safari') != -1);
var FIREFOX = (navigator.userAgent.indexOf('Firefox') != -1);
var MSIE = (navigator.userAgent.indexOf('MSIE') != -1);



// Delete cookies
document.cookie = '';



var googleLanguageLoaded = false;

try {
	google.load("language", "1");
	googleLanguageLoaded = true;
}
catch(e) {googleLanguageLoaded = false;}



var helptxt = "<br>";
helptxt += "  ************************************************************<br>";
helptxt += "  *                     VU CHAT BETA 4.2.1                   *<br>";
helptxt += "  ************************************************************<br>";
helptxt += "  /help = show this message<br>";
helptxt += "  /clear = Clear the textarea<br>";
helptxt += "  /me = Send an action (ex: /me love admin)<br>";
helptxt += "  /join = Join a channel (ex: /join my_room)<br>";
helptxt += "  /topic = Change the topic (ex: /topic What should be done about the dwarves?)<br>";
helptxt += "  /op = Give someone in your channel operator powers<br>";
helptxt += "  /deop = Remove operator powers from someone in your channel<br>";
helptxt += "  /kick = Kick someone out of your channel<br>";
helptxt += "  /invite = Invites someone to your channel (ex: /invite Mr. Admin)<br>";
helptxt += "  /private = No one can join your channel unless invited<br>";
helptxt += "  /reserve = Reserves the channel (ex: /reserve Reserved for Admins bar<br>";
helptxt += "  /abandon = Delete the channel from the database<br>";
helptxt += "  /pm = Sends a private message to another user (ex: /pm Mr. Admin, hello there)  <br>";
helptxt += "  /dice = Throws a dice (ex: /dice 20)  <br>";
helptxt += "  /alias = Change your name (ex: /alias The Dragon)  <br>";
helptxt += "  /showalias = Show the alias list<br>";
helptxt += "  /fullscreen = Reloads the chat in full screen <br>";
helptxt += "  /ignore = Adds someone to the ignore list <br>";
helptxt += "  /list = Shows an list of active channels <br>";
helptxt += "  /lang = Set your language <br>";
helptxt += "  /translate = Turns translation on/off <br>";
helptxt += "  /whois = Gives info about a ruler (ex: /whois Admin)<br>";
helptxt += "  /reload = Reloads the chat <br>";
helptxt += "  /sound = Disables or enables sound <br>";
helptxt += "  /quit = Leaves all channels and exit the chat<br>";
helptxt += "  ************************************************************<br>";
helptxt += "  <br>";
helptxt += "  &#091;orange&#093;this text is red&#091;/orange&#093; will show the text in [orange]orange[/]<br>";
helptxt += "  <br>";
helptxt += "  A list of colors can be found here:<br>";
helptxt += "  http://' + sDomain +'colors.htm<br>";
helptxt += "  <br>";
helptxt += "  To write someones name, write any of the letters and hit tab";
helptxt += "  <br>";
helptxt += "  Use the arrows to toggle your message history";
helptxt += "  <br>";
helptxt += "  <br>";

var translatedHelpText = helptxt;





if(strSession) {
	// Send session-id in every request
	idInfo = strSessionName + '=' + strSession + '&';
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }


if( document.all ) {
  if(navigator.userAgent.indexOf('MSIE') >= 0) IE=true;
}
else
{
  FF=true;
}


if ((document.location.href.indexOf('translate.google.com')!=-1)) {
	// Only Firefox support JSON, do not use google translate proxy
	document.location = 'http://' + sDomain + '/?' + strSessionName + '=' + strSession + '&lang=' + queryStr('tl');
}

function leaveChat() {

	//showText(null, null, 'Body unload');
	// Do not quit during refresh (F5) and do not run on /quit command
	if(lastKey != 116 && !bQuitCommand) sendCommand('/quit');
	
	return true;
}


function test(data) {

	alert('testing...');

	var objSCript = new JSONscriptRequest('http://' + sDomain + '/test.asp?test=' + data);

	objSCript.buildScriptTag();
	objSCript.addScriptTag();
	//objSCript.removeScriptTag();
}

function playSound() {

	if(bPlaySound) {
		document.getElementById('sound').src='wood.mid';
		document.getElementById('sound').style.display='block';

		setTimeout('bPlayingSound=true', 2500);
	}
}

function stopSound() {
	if(debugmode) showText(null, null, 'music stopped!', document.chat.curchan.value);

	document.getElementById('sound').src='stopsound.htm';
	document.getElementById('sound').style.display='none';
	
	bPlayingSound = false;
}



function flash(sTxt) {

	if(bGotFocus) {
		try {
			top.document.title = 'VU Chat';
		}
		catch(e) {}
		bFlashing = false;
	}
	else {

		var re = new RegExp('&#039;', 'i');
		sTxt = sTxt.replace(re, '´');

		if(sTxt.indexOf('   ') == -1) sTxt += '   ';

		sTxt = sTxt.substring(1, sTxt.length) + sTxt.substring(0, 1);

		//alert(sTxt);
		try {
			top.document.title = sTxt;
		}
		catch(e) {}

		bFlashing = true;
		
		setTimeout('flash(\'' + sTxt + '\');', 256);
	}
}


function reading() {
	if(bPlayingSound) stopSound();

	if(!bGotFocus) {
		
		bGotFocus=true;
		
		lastFocus = new Date();
		
		if(debugmode) showText(null, null, 'got focus', document.chat.curchan.value);

		if(getNewData && updateInterval > defaultUpdateInterval) {
			updateInterval = defaultUpdateInterval;
			
			sendCommand('/idle X', defaultChan);
			
			clearInterval(getNewData);
			getNewData = setInterval("refresh()", updateInterval * 1000);
			
			if(debugmode) showText(null, null, ' Changing update interval do default', document.chat.curchan.value);
		
		}

	}
}

function idling() {

	if(bGotFocus) {

		bGotFocus=false;

		lastBlur = new Date();

		if(debugmode) showText(null, null, 'lost focus', document.chat.curchan.value);
	}
}

function bodyLoad() {


	if( document.layers ) {
		document.captureEvents( Event.KEYDOWN || Event.MOUSEDOWN || Event.CLICK || Event.ONFOCUS || Event.ONFOCUSOUT)
	}

	// Active or idling?
	window.onfocus = function() {reading();}
	document.onfocusout = function() {idling();}
	if(!IE) window.onblur = function() {idling();};


	document.onmousemove = handleMousemove;
	document.onkeydown = handleKey;

	document.onmouseup = doSomething;
	document.oncontextmenu=doSomething;
	
	document.onmouseover=doSomething;
	
	//document.onclick = doSomething;
	//document.onmousedown = doSomething;

	//document.oncontextmenu=new Function("return false");


	var lang = queryStr('lang');

	//setTimeout("alert('testing')", 300);

	if(!currentLanguage && lang) {
		//alert('Hello ' + lang + ' user');
		currentLanguage = lang;
		bTranslate = true;
		translateAll('en');
	}


	getNewData = setInterval("refresh()", 1000);

	//clearInterval(getNewData);


	setTimeout('sendHello()', 0);

}

function sendHello() {
	makeRequest();
	sendRequest('http://'+ sDomain +'/talk.asp', idInfo + 'txt=' + encodeURIComponent('HELO'));
	
	sentHello = true;
}


function doSomething(e) {

	reading();
	
	lastAction = new Date();

	if (!e) e = window.event;

	var targ;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;

	var rightclick;
	if (e.which) rightclick = (e.which == 3);
	else if (e.button) rightclick = (e.button == 2);

	var etype = new String(e.type);

	//showText(null, null, e.type + ' (' + noClammers(targ.id) + ')', defaultChan);

	if(bMenuVisible && e.type=='contextmenu') return false;

	if(bMenuVisible && e.type=='mouseup') hideMenu();


	if(rightclick) {
		if(targ.id == 'talk') {
			showMenu('talkmenu');
		}

		else if(targ.value && !(targ.id == 'writer')) {
			sUserName = targ.value;
			showMenu('usermenu');
		}

		else if(targ.id.substring(0, 5) == 'chan_') {
			sChanName = targ.id.substring(5, targ.id.length);
			showMenu('chanmenu');
			switchChan(sChanName);
		}
	}
/*
	else if(navigator.userAgent.indexOf('Opera') >= 0) {

		if(e.type == 'mouseover') {

			if(targ.id == 'talk') {
				showthemenu = setTimeout("showMenu('talkmenu')", 600);
			}

			else if(targ.value) {
				sUserName = targ.value;
				showthemenu = setTimeout("showMenu('usermenu', sUserName)", 600);
			}

			else if(targ.id.substring(0, 5) == 'chan_') {
				sChanName = targ.id.substring(5, targ.id.length);
				showthemenu = setTimeout("showMenu('chanmenu', sChanName); switchChan('"+ sChanName +"');", 1500);
			}

			else {
				clearTimeout(showthemenu);
				//if(bMenuVisible) hideMenu();
			}

		}

		else {
				clearTimeout(showthemenu);
		}
	}
*/


	return true;

}


function showMenu(id, args) {

	hideMenu();

	document.getElementById(id).style.display='block';

	// Move themenu to the mouse position...


	//showText(null, null, 'offsetWidth=' + document.getElementById(id).offsetWidth + ' offsetHeight=' + document.getElementById(id).offsetHeight);

	var minX = 0;
	var maxX = document.body.clientWidth - document.getElementById(id).offsetWidth;

	var minY = 0;
	var maxY = document.body.clientHeight - document.getElementById(id).offsetHeight;

	var posX = Xcursor - 30;
	var posY = Ycursor - 15;

	if(posX > maxX) posX = maxX;
	if(posX < minX) posX = minX;
	if(posY > maxY) posY = maxY;
	if(posY < minY) posY = minY;


	iHideMenuX1 = posX;
	iHideMenuX2 = posX - -document.getElementById(id).offsetWidth;
	iHideMenuY1 = posY;
	iHideMenuY2 = posY - -document.getElementById(id).offsetHeight;

	//window.status = "X=" + Xcursor + " Y=" + Ycursor + " X1=" + iHideMenuX1 + " X2=" + iHideMenuX2 + " Y1=" + iHideMenuY1 + " Y2=" + iHideMenuY2;


	document.getElementById(id).style.top = posY + 'px';
	document.getElementById(id).style.left = posX + 'px';

	// Place the iframe under the menu

	document.getElementById('ifrm').style.display = 'block';

	document.getElementById('ifrm').style.top = posY + 'px';
	document.getElementById('ifrm').style.left = posX + 'px';

	document.getElementById('ifrm').height = document.getElementById(id).offsetHeight;
	document.getElementById('ifrm').width = document.getElementById(id).offsetWidth;

	if(args) document.getElementById(id + 'h').innerHTML = args; 

	bMenuVisible = true;

}

function hideMenu(menu) {

	if(!menu) {

		document.getElementById('talkmenu').style.display = 'none';
		document.getElementById('chanmenu').style.display = 'none';
		document.getElementById('usermenu').style.display = 'none';

		document.getElementById('ifrm').style.display = 'none';

	}

	bMenuVisible = false;

}



function noClammers(s) {

	var temp = new String(s);

	temp = temp.replace(/\]/, "")
	temp = temp.replace(/\[/, "")

	return temp;
}


function privMsg(selectbox, i) {

	var sRuler = selectbox.options[i].value;

	if(sPmList.indexOf(sRuler + ':') == -1) sPmList += sRuler + ':';

	openChan(sRuler);

	makeRequest();
	sendRequest('http://' + sDomain + '/talk.asp', idInfo + 'chan=' + sFirstChan + '&txt=' + encodeURIComponent('/pm ' + sRuler + ', I want to talk with you...'));
}


function removeAllOptions(selectbox) {
	var i;

	for(i=selectbox.options.length-1;i>=0;i--) {
		selectbox.remove(i);
	}
}

function addOption(selectbox,text,value) {
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;
	if(value.substring(0,1) == '%') {
		optn.setAttribute('style', 'color: #A0CB8D;');
		optn.title = 'New Player';
	}
	selectbox.options.add(optn);
}


function handleMousemove(e) {

	

	if (!e) e = window.event;

	if(FF) document.chat.txt.blur() // ??

	reading();
	lastAction = new Date();


	if(FF)
	{
		Xcursor = e.pageX;
		Ycursor = e.pageY;
	}
	else
	{
		Xcursor = (document.layers) ? e.pageX : e.clientX;
		Ycursor = (document.layers) ? e.pageY : e.clientY;

		//Xcursor = Xcursor - -document.body.scrollLeft;
		//Ycursor = Ycursor - -document.body.scrollTop;

	}


	//window.status = Xcursor + ', ' + Ycursor;
	
	//showText(null, null, 'screen=' + e.screenX + ',' + e.screenY + ' client=' + e.clientX + ',' + e.clientY + ' hmm=' + e.x + ',' + e.y, document.chat.curchan.value);

	if(bMenuVisible) {
		if(Xcursor > iHideMenuX2 || Xcursor < iHideMenuX1 || Ycursor > iHideMenuY2 || Ycursor < iHideMenuY1) hideMenu();

	}



}


function removeOption(selectbox, value) {
	for(i=selectbox.options.length-1;i>=0;i--) {
		if(selectbox.options[i].value==value) selectbox.remove(i);
	}
}

function handleKey(e) {

	reading();
	
	lastAction = new Date();

	var key
	
	var evt = (e) ? e : window.event; 
	
	if(FF) key=e.which
	else key=evt.keyCode

	lastKey = key;

	document.chat.txt.focus();
	
	//showText(null, null, key,  document.chat.curchan.value);

	if(key==38) {
		iHistoryIndex--;
		if(iHistoryIndex<0) iHistoryIndex = 0

		document.chat.txt.value = aChatHistory[iHistoryIndex];
	}
	else if(key==40) {
		iHistoryIndex++;
		if(iHistoryIndex >= aChatHistory.length) {
			iHistoryIndex = aChatHistory.length - 1;
			document.chat.txt.value = '';
		}
		else {
			document.chat.txt.value = aChatHistory[iHistoryIndex];
		}
	}
	else if(key==9) {

		var sText = document.chat.txt.value;

		var aText = sText.split(' ');

		sText = aText[aText.length-1].toLowerCase()

		var selectbox = document.chat['users_' + document.chat.curchan.value];

		for(var i=selectbox.options.length-1;i>=0;i--) {
			if(selectbox.options[i].value.toLowerCase().indexOf(sText)>0) {

				document.chat.txt.value = '';

				for(var j=0;j<aText.length-1;j++) {
					document.chat.txt.value += aText[j] + ' ';
				}

				document.chat.txt.value += selectbox.options[i].value;

			}
		}
		return false;
	}
	else if(key==13) {
		sendandclear();
		return false;
	}

}

function update() {

		lastUpdate = new Date();

		makeRequest();
		sendRequest('http://' + sDomain + '/listen.asp', idInfo + 'd=' + Math.floor(lastUpdate.getTime()/256));

		//showText(null, null, 'update...', document.chat.curchan.value);

}


function showResult(sTxt) {

	lastResult = new Date();

	if(sTxt != 'NuLL' && sTxt != '') {

		var aTemp = new Array();

		//alert('showResult: ' + sTxt);

		if(sTxt == '!REFRESH!') {
			//showText(null, null, 'Server wants us to refresh!', null)
			alert('REFRESH');
			clearInterval(getNewData);
			//document.location=document.location.href;
		}


		//if(sTxt!='') alert(sTxt);

		var dDatum = new Date();

		var vMinutes = dDatum.getMinutes();
		var vHours = dDatum.getHours();
		var sChan = '';
		var iTemp = 0

		if(vHours<10) vHours = '0' + vHours;
		if(vMinutes<10) vMinutes = '0' + vMinutes;

		var aTxt = sTxt.split('\r\n');


		for(var i=0;i<aTxt.length-1;i++) {

			iTemp = aTxt[i].indexOf(':')

			sChan = aTxt[i].substring(0,iTemp);

			aTxt[i] = aTxt[i].substring(iTemp+1,aTxt[i].length);

			var sUser = aTxt[i].substring(0,aTxt[i].indexOf(':'));


			if(sUser=='') sUser = '#';

			if(aTxt[i].substring(0,7)=='!USERS!') {


				aTxt[i] = aTxt[i].substring(7,aTxt[i].length)

				removeAllOptions(document.getElementById('users_' + sChan));

				var aUsers = aTxt[i].split(',');
				for(var u=0;u<aUsers.length-1;u++) {

					if(aUsers[u].indexOf('(new)') > -1) {

						var re = new RegExp('(new)', 'i');
						aUsers[u] = aUsers[u].replace(re, '');


					}
					addOption(document.getElementById('users_' + sChan),aUsers[u],aUsers[u]);
				}

			}

			else if(aTxt[i].substring(0,7)=='!ALIAS!') {


				aTxt[i] = aTxt[i].substring(7,aTxt[i].length)

				if(aTxt[i].indexOf(',') == -1) aTxt[i] += ',';

				//alert('Alias...' + aTxt[i]);

				var aUsers = aTxt[i].split(',');
				for(var u=0;u<aUsers.length-1;u++) {
					//alert(aUsers[u]);

					aTemp = aUsers[u].split('=');

					aAlias[sChan + '_' + aTemp[0]] = aTemp[1];
				}


			}

			else if(aTxt[i].substring(0,9)=='!NEWUSER!') {
				aTxt[i] = aTxt[i].substring(9,aTxt[i].length)

				addOption(document.getElementById('users_' + sChan),aTxt[i],aTxt[i]);

				//showText(vHours, vMinutes, '<i class="join">* ' + aTxt[i] + ' has joined ' + sChan + '</i>', sChan, true);

			}


			else if(aTxt[i].substring(0,10)=='!USERLEFT!') {
				aTxt[i] = aTxt[i].substring(10,aTxt[i].length)

				removeOption(document.getElementById('users_' + sChan),aTxt[i]);

				//showText(vHours, vMinutes, '<i class="left">* ' + aTxt[i] + ' has left ' + sChan + '</i>', sChan, true);
			}

			else if(aTxt[i].substring(0,7)=='!LEAVE!') {

				aTxt[i] = aTxt[i].substring(7,aTxt[i].length);
				closeChan(aTxt[i]);

			}

			else if(sChan.substring(0,4)=='!PM!') {

				sChan = sChan.substring(4,sChan.length);

				if(sPmList.indexOf(sChan + ':') == -1) sPmList += sChan + ':';

				showText(vHours, vMinutes, aTxt[i], sChan);

				if(!bFlashing) flash(aTxt[i]);
			}

			else {



				if(sIgnoreList.toLowerCase().indexOf(sUser.toLowerCase()) == -1) {


					var re = new RegExp(sUser + ':', 'i');

					aTxt[i] = aTxt[i].replace(re, '');


					if(aAlias[sChan + '_' + sUser]) sUser = aAlias[sChan + '_' + sUser];


					var aTxt2 = aTxt[i].split('<br>');

					for(var j=0;j<aTxt2.length;j++) {

						aTxt2[j] = '<i class="user">' + sUser + '</i>: ' + aTxt2[j]

						//alert('*' + aTxt2[j].substring(sUser.length+22,sUser.length+30) + '*');

						if(aTxt2[j].substring(sUser.length+22,sUser.length+30)=='!ACTION!') {

							showText(vHours, vMinutes, '* ' + sUser + aTxt2[j].substring(sUser.length+30,aTxt2[j].length), sChan);
						}
						else {

							showText(vHours, vMinutes, aTxt2[j], sChan);

							if(!bFlashing) flash(aTxt2[j].substring(aTxt2[j].indexOf('</i>')+5, aTxt2[j].length));
							
							if(!bGotFocus && (new Date().getTime() - lastAction.getTime()) > 25000) playSound();


						}
					}

				}

			}
		}


	}
}

function refresh() {

	//showText(null, null, 'refresh...', document.chat.curchan.value);

	var curTime = new Date();
	

	if(curTime.getTime() - lastAction.getTime() > 200000) idling();

	

	
	
	if(!bGotFocus) {
		var idle = (curTime.getTime() - lastBlur.getTime()) / 1000;
			
		if(idle > Math.sqrt(updateInterval * 10000) * 2 && idle < 3600 && idle > 200) {
			updateInterval = Math.round(idle*idle / 10000);

			if(getNewData) {
				clearInterval(getNewData);
				getNewData = setInterval("refresh()", updateInterval * 1000);
			}

			sendCommand('/idle ' + updateInterval * 3, defaultChan);

			if(debugmode) showText(null, null, 'lastUpdate:' + (curTime.getTime() - lastUpdate.getTime()) + ' updateInterval:' + updateInterval + ' delay=' + delay + ' AFK');

			lastUpdate = new Date();

		}
	}

	
	if(delay==-1) {
		updateInterval = 5;
		sentHello = false;
	}
	else {
		if(!sentHello) sendHello();
	}

	if(delay > 333 || delay > defaultUpdateInterval * 333) {

		// Slow network
		if(defaultUpdateInterval <= 1 && delay > defaultUpdateInterval * 333) {

			updateInterval = Math.round(delay * 3 / 100 + 5) / 10;

			defaultUpdateInterval = updateInterval;

			clearInterval(getNewData);
			getNewData = setInterval("refresh()", updateInterval * 1000);

			if(debugmode) showText(null, null, 'lastUpdate:' + (curTime.getTime() - lastUpdate.getTime()) + ' updateInterval:' + updateInterval + ' delay=' + delay + ' slow network');
		}

	}
	else {
		// Fast network
		if(defaultUpdateInterval > 1 && bGotFocus) {
			defaultUpdateInterval = 1
			updateInterval = 1;

			clearInterval(getNewData);
			getNewData = setInterval("refresh()", updateInterval * 1000);

			if(debugmode) showText(null, null, 'lastUpdate:' + (curTime.getTime() - lastUpdate.getTime()) + ' updateInterval:' + updateInterval + ' delay=' + delay + ' fast network');
		}
	}
	



	if(curTime.getTime() - lastUpdate.getTime() >= (updateInterval * 1000 - 50)) {
		if(debugmode) showText(null, null, 'lastUpdate:' + (curTime.getTime() - lastUpdate.getTime()) + ' updateInterval:' + updateInterval + ' delay=' + delay + ' UPDATING!');

		update(); // Min 1s intervals
		
	}
	else {
		if(debugmode) showText(null, null, 'lastUpdate:' + (curTime.getTime() - lastUpdate.getTime()) + ' updateInterval:' + updateInterval + ' Not updating! delay=' + delay);

	}


}


function ignore(sUser) {
	if(sIgnoreList.indexOf(sUser) == -1) sIgnoreList += sUser + ','
	else {
		var re = new RegExp(sUser + ',', 'i');
		sIgnoreList =sIgnoreList.replace(re, '');
	};

	showText(null, null, 'Ignore-list: ' + sIgnoreList.substring(0, sIgnoreList.length-1), document.chat.curchan.value);
}

function sendCommand(cmd, chan) {
	document.chat.txt.value = cmd;
	sendandclear(true, chan);
}


function sendandclear(nopush, chan) {

	//eval('document.chat.texta_' + document.chat.curchan.value).focus()

	lastUpdate = new Date();
	txt = document.chat.txt.value.trim();

	// Opera fix
	if(txt.substring(0,2) == "\r\n") txt = txt.substring(2,txt.length);
	//showText(null, null, noClammers("*" + txt + "* = " + txt.length), document.chat.curchan.value);

	if(txt.length > 0) {

		//document.chat.txt.value = '';

		if(txt=='/clear') { fillUp(document.getElementById('texta_' + document.chat.curchan.value));}
		else if(txt.substring(0,5)=='/size') {document.getElementById('texta_' + document.chat.curchan.value).style.fontSize = txt.substring(6,txt.length);}
		else if(txt=='/help') {showHelp(document.chat.curchan.value);}
		else if(txt=='/fullscreen') {top.location=document.location.href;}
		else if(txt=='/reload') {document.location=document.location.href;}
		else if(txt.substring(0,7)=='/ignore') {

			var sUser = txt.substring(8,txt.length);

			ignore(sUser);

		}
		else if(txt.substring(0,5)=='/test') {

			//test(txt.substring(8,txt.length));
			
			alert(new Date().getTime() - lastAction.getTime());
		}
		
		else if(txt.substring(0,6)=='/hello') {

			sendHello();
		}
		
		else if(txt.substring(0,9)=='/interval') {

			defaultUpdateInterval = txt.substring(10,txt.length);
			updateInterval = defaultUpdateInterval;

			clearInterval(getNewData);
			getNewData = setInterval("refresh()", updateInterval * 1000);


			showText(null, null, 'updateInterval changed to ' + updateInterval, document.chat.curchan.value);

		}
		
		else if(txt.substring(0,6)=='/debug') {

			debugmode = debugmode ? false : true;
			
			showText(null, null, (debugmode ? 'Showing debug data!' : 'Debugging OFF'), document.chat.curchan.value);

		}
		
		else if(txt.substring(0,6)=='/sound') {
			bPlaySound = bPlaySound ? false : true;
			
			showText(null, null, (bPlaySound ? 'Sound is now ON' : 'Sound is now OFF'), document.chat.curchan.value);
		}
		
		else if(txt.substring(0,10)=='/translate') {

			bTranslate = bTranslate ? false : true;

			if(bTranslate && !googleLanguageLoaded) {
				google.load("language", "1");
				googleLanguageLoaded = true;
			}

			if(!currentLanguage) {

				bTranslate = false;

				showText(null, null, 'You have to choose a language (/lang [language]) before the chat can be translated', document.chat.curchan.value);

			}

			showText(null, null, (bTranslate ? 'Translation is now ON: Everything you write will be translated to English and what others write will be translated to your language (' + currentLanguage + ')' : 'Translation is now Off'), document.chat.curchan.value);

		}
		else if(txt.substring(0,5)=='/lang') {

			var lang = txt.substring(6,txt.length);

			lang = lang.toUpperCase();

			if(!google.language.Languages[lang]) {

				var d = new String('<span class="no-translate">');

				for (p in google.language.Languages) {
					d += p + ', ';
				}

				d += '</span>';

				showText(null, null, 'Can not translate ' + lang + '. Please chose one of the following languages: ' + d, document.chat.curchan.value);

			}
			else {
			
				var oldLanguage = currentLanguage;
			
				currentLanguage = google.language.Languages[lang];
				showText(null, null, 'Your language is now set to ' + lang, document.chat.curchan.value);

				translateAll(oldLanguage);

			}


		}
		else {

			var sChan = new String();
			
			if(chan) sChan = chan
			else sChan = document.chat.curchan.value;



			//alert('*' + txt + '*')

			if(bTranslate && google.language && txt.substring(0,1) != '/') {

				google.language.translate(txt, currentLanguage, "en", function(result) {
					if (!result.error) {

						txt = unescape(result.translation);

						if(sPmList.indexOf(sChan + ':') > -1) {
							txt = '/pm ' + sChan + ', '+ txt;
							//sChan = sFirstChan;
						}

						makeRequest();
						sendRequest('http://' + sDomain + '/talk.asp', idInfo + 'chan=' + sChan + '&txt=' + encodeURIComponent(txt));

					}
					else showText(null, null, 'Error: Your message could not be translated! (type /translate to turn off translation)', document.chat.curchan.value);
				});

			}

			else {

				if(sPmList.indexOf(sChan + ':') > -1) {
					txt = '/pm ' + sChan + ', '+ txt;
					//sChan = sFirstChan;
				}

				makeRequest();
				sendRequest('http://' + sDomain + '/talk.asp', idInfo + 'chan=' + sChan + '&txt=' + encodeURIComponent(txt));
			}

			if(!nopush) {
				aChatHistory.push(txt);
				iHistoryIndex = aChatHistory.length;
			}

			if(txt.substring(0,6)=='/leave') {
				// Close the chan
				closeChan(sChan);
			}

		}

		if(txt=='/quit') {
			bQuitCommand = true;
			//alert('Live long and prosper');
			document.location='loggedout.htm';
		}

	}

	document.chat.txt.value = '';
	return false;
}

function showHelp(chan) {

	showText(null, null, translatedHelpText, chan);

}

function translateAll(oldl) {

	var obj = new Object();

	//Translate links
	obj = document.getElementsByTagName("a");
	for (var i = 0; i < obj.length ; i++) {
		translate(obj[i], 'innerHTML', oldl);
	}

	//Translate buttons
	obj = document.getElementsByTagName("button");
	for (var i = 0; i < obj.length ; i++) {
		translate(obj[i], 'innerHTML', oldl);
	}

	//Translate headings
	obj = document.getElementsByTagName("h4");
	for (var i = 0; i < obj.length ; i++) {
		translate(obj[i], 'innerHTML', oldl);
	}

}

function translate(obj, property, oldl) {

	//alert('text=' + obj[property] + ' \n\ncurrentLanguage=' + currentLanguage);

	if(google.language && currentLanguage) {

		google.language.translate(obj[property], oldl, currentLanguage, function(result) {
			if (!result.error) {
				obj[property] = result.translation;;
			}
			else obj[property] = obj[property] + '\n(No translation available)'
		});
	}
}	



function showText(iHour, iMinute, txt, chan, notbold) {

	//alert(iHour + ':' + iMinute + ' Showing text in ' + chan +  '...' + txt);

	if(!chan) chan = defaultChan;
	
	if(chan == defaultChan && sChanList.indexOf(document.chat.curchan.value) > -1) chan = document.chat.curchan.value;
	
	var bScroll = false;

	if(sChanList.toLowerCase().indexOf(chan.toLowerCase() + ':')==-1) openChan(chan);

	if(document.chat.curchan.value!=chan && !notbold) document.getElementById('chan_' + chan).style.fontWeight='bold';

	var obj = document.getElementById('texta_' + chan);

	if(obj) {
		if(obj.scrollTop >= (obj.scrollHeight - iTxtHeight) || iTxtHeight <= 15) bScroll = true;
	}

	//if(IE) bScroll = true;

	//showText(null, null, 'bScroll=' + bScroll+ ' iTxtHeight=' + iTxtHeight + ' scrollHeight=' +obj.scrollHeight + ' scrollTop=' + obj.scrollTop, document.chat.curchan.value);
	
	//alert('iTxtHeight=' + iTxtHeight + ' scrollHeight=' +obj.scrollHeight + ' scrollTop=' + obj.scrollTop);

	txt = addColors(txt);

	if(iHour) txt = '<i class="time">[' + iHour + ':' + iMinute + ']</i> ' + txt


	if(txt.indexOf('://') > -1) txt = autolink(txt) ;

	txt += '<br>';

	if(bTranslate && google.language) {

		google.language.detect(txt, function(result) {
			if (!result.error && result.language) {
				google.language.translate(txt, result.language, currentLanguage, function(result) {
					var translated = document.getElementById("translation");
					if (result.translation) {
						document.getElementById('texta_' + chan).innerHTML += result.translation;
						if(bScroll) scrollDown(obj);
					}
					else {
						document.getElementById('texta_' + chan).innerHTML += txt + '(could not translate)';
						if(bScroll) scrollDown(obj);
					}
				});
			}
			else document.getElementById('texta_' + chan).innerHTML += txt + '(unknown language)';
		});

	}
	
	
	else document.getElementById('texta_' + chan).innerHTML += txt;

	if(bScroll) scrollDown(obj);

}


function scrollDown(obj) {

	//document.getElementById('texta_Lobby').innerHTML += 'scrolling down...';
	
	//alert('wanna scroll?');


	if(obj) {
		obj.scrollTop = obj.scrollHeight;

		iTxtHeight = obj.scrollHeight - obj.scrollTop;

		//alert('iTxtHeight=' + iTxtHeight + ' height=' + obj.height + ' scrollTop=' + obj.scrollTop + ' scrollHeight=' + obj.scrollHeight);
		
		
		obj.scrollTop = obj.scrollHeight;
		
		
		obj.scrollTop = obj.scrollHeight;
	}

}


function switchChan(chan) {
	openChan(chan);
}


function openChan(sChanName) {

	//alert('opening ' + sChanName);

	var sChanTable = '<table id="chantable" cellspacing="0" cellpadding="0" width="100%"><tr>';
	var bNewChan = false;

	if(sChanName) {

		var i = 0;


		if(sChanList.toLowerCase().indexOf(sChanName.toLowerCase() + ':')==-1) {

			if(sChanList=='') sFirstChan = sChanName;

			sChanList += sChanName + ':';
			bNewChan = true;

			for(i=0;i<15;i++) {

				if(document.getElementById('texta_' + i)) {
					document.getElementById('texta_' + i).id = 'texta_' + sChanName;
					document.getElementById('users_' + i).id = 'users_' + sChanName;
					break;
				}
			}

		}

		var aChanList = sChanList.split(':');


		for(i=0;i<=(aChanList.length-2);i++) {
			//alert('Hiding ' + i + '... ' + sChanList);
			document.getElementById('texta_' + aChanList[i]).style.display='none';
			document.getElementById('users_' + aChanList[i]).style.display='none';
		}

		for(i=0;i<=(aChanList.length-2);i++) {

			sChanTable += '<td width="' + (100 / (aChanList.length-1)) + '%" style="position: relative;">';

			sChanTable += '<div onMouseOver="this.style.opacity=1" onMouseOut="this.style.opacity=.8" class="channel"><div id="chan_' + aChanList[i] + '" onClick="switchChan(this.innerHTML)" class="inner';
			

			if(aChanList[i]==sChanName) {


				//alert('Showing ' + i + '... ' + sChanList);

				sChanTable += ' active';

				document.chat.curchan.value = aChanList[i];

				document.getElementById('texta_' + aChanList[i]).style.display='block';
				

				if(sPmList.indexOf(aChanList[i] + ':') == -1 && sChanName!=defaultChan) {
					document.getElementById('users_' + aChanList[i]).style.display='block';
					document.getElementById('txtholder').width = '80%';
					document.getElementById('userholder').width = '20%';
				}
				else {
					document.getElementById('users_' + aChanList[i]).style.display='block';
					document.getElementById('txtholder').width = '90%';
					document.getElementById('userholder').width = '1%';
				}
				
				scrollDown(document.getElementById('texta_' + aChanList[i]));

			}

			sChanTable += '">' + aChanList[i] + '</div></div>';

			if(sPmList.indexOf(aChanList[i] + ':') == -1) sChanTable += '<a id="close" href="JavaScript:;" onClick="sendCommand(\'/leave ' + aChanList[i] + '\');" title="Close ' + aChanList[i] + '">X</a>'
			else sChanTable += '<div id="close" href="JavaScript:;" onClick="closeChan(\'' + aChanList[i] + '\');" title="Close">X</div>';

			sChanTable += '</td>'
		}
	}

	sChanTable += '</tr></table>'

	document.getElementById('chans').innerHTML = sChanTable;

	if(bNewChan) fillUp(document.getElementById('texta_' + aChanList[i-1]));

	//document.chat.txt.focus();

}

function closeChan(chan) {

	//alert('closing ' + chan + ' (' + sChanList + ')');


	var aChanList = sChanList.split(':');

	for(i=0;i<=(aChanList.length-2);i++) {
		//alert('i = ' + i + '=' + aChanList[i]);
		document.getElementById('texta_' + aChanList[i]).style.display='none';
		document.getElementById('users_' + aChanList[i]).style.display='none';
	}

 	document.getElementById('texta_' + chan).value = '';

 	removeAllOptions(document.getElementById('users_' + chan));

	document.getElementById('texta_' + chan).display='none';
	document.getElementById('users_' + chan).style.display='none';

	for(i=0;i<15;i++) {
		if(!document.getElementById('texta_' + i)) {
			document.getElementById('texta_' + chan).id = 'texta_' + i;
			document.getElementById('users_' + chan).id = 'users_' + i;
			break;
		}
	}

	var re = new RegExp(chan + ':', 'i');
	sChanList = sChanList.replace(re, '');

	var aChanList = sChanList.split(':');


	// Show another chan
	var sCurChan = document.chat.curchan.value;
	
	if(sCurChan==chan && sChanList.indexOf(sFirstChan) > -1) sCurChan = sFirstChan;
	

	for(i=0; sCurChan==chan && i<=(aChanList.length-2); i++) {
		if(aChanList[i]!=chan) sCurChan = aChanList[i];
	}

	//alert('sChanList=' + sChanList + '. Lets open ' + sCurChan);

	

	if(sChanList.indexOf(sCurChan) == -1) {
		//alert('erm... ' + sCurChan + ' not in list?');
		openChan(null);
		//document.chat.curchan.value = '';
 	}
	else {
		//document.chat.curchan.value = '';
		//alert('We shall open ' + sCurChan + '\n sChanList=' + sChanList);
		openChan(sCurChan);
	}
}

function fillUp(obj) {

	var breaks = '';

	for(var i=16; i<obj.clientHeight; i+=16) breaks += '<br>';
	
	
	obj.innerHTML = breaks;
	scrollDown(obj);
}

function autolink(s)
{
	if(s.indexOf('http') > -1) {

		var re = new RegExp("&amp;", 'i');
		s = s.replace(re, '&');


		var hlink = /\s(ht|f)tp:\/\/([^ \,\;\:\!\)\(\"\'\<\>\f\n\r\t\v])+/g;
		return (s.replace (hlink, function ($0,$1,$2) { s = $0.substring(1,$0.length);
													   // remove trailing dots, if any
													   while (s.length>0 && s.charAt(s.length-1)=='.')
														  s=s.substring(0,s.length-1);
													   // add hlink
													   return " " + '<a href="' + s + '" target="_blank" title="Click to open this link in a new window">' + s + '</a>';
													 }
						 )
			   );
	}
	else {
		return s;
	}
}



function addColors(s) {

	//alert('Adding colors to:' + s);

	s = s.toString();

	s = s.replace(/\[\/(.*)\]/g, '</font>');

	s = s.replace(/(\[.[^(:\]\[.)]+\])/g, function ($0) { return '<font color="' + $0.substring(1, $0.length-1) + '">'; }  );

	return s;
}

function resizeBox() {

	//alert('document.body.clientHeight=' + document.body.clientHeight + '\ndocument.body.clientWidth=' + document.body.clientWidth + '\nFIREFOX=' + FIREFOX + '\ncurchan=' + document.chat.curchan.value);

	if(document.body.clientHeight) {

		document.getElementById('txtholder').height = (document.body.clientHeight - 57) + 'px';
		document.getElementById('userholder').height = (document.body.clientHeight - 57) + 'px';

	}

	if(document.chat.curchan.value!='') scrollDown(document.getElementById('texta_' + document.chat.curchan.value));
}


function queryStr(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[1];
		}
	}
}
