var chanTopics = new Array();
var blurred = false;

document.getElementsByClassName =
function (cname) {
	var returnArr = new Array();
	var elems = document.getElementsByTagName("*");
	for (var i = elems.length - 1; i >= 0; i--) {
		if (elems[i].className == cname)
			returnArr.push (elems[i]);
	}
	if (returnArr.length == 0)
		return false;
	return returnArr;
}
var previous;
function strCode (str) {
	code = "";
	str = str.toLowerCase();
	var len = str.length;
	for (var i = 0; i < len; i++) {
		code += str.charCodeAt(i) + "";
	}
	//We can't just have the code as an int, cause ABC and CBA would then have the same code.
	return (parseInt (code));
}
function sortF (elem1, elem2) { 
	var children1 = elem1.getElementsByTagName("*");
	var children2 = elem2.getElementsByTagName("*");
	var val = document.sortBy;
	var num = document.n;
	if (!children1[val].innerText) { //FIREFOX
		children1[val].innerText = children1[val].textContent;
	}
	if (!children2[val].innerText) {
		children2[val].innerText = children2[val].textContent;
	}
	if (!document.order) {
		if (!num) { //blame IE for this abomination, > and < just wouldn't work
			return (strCode(children1[val].innerText) - strCode(children2[val].innerText));
		}
		else {
			return (parseInt(children1[val].innerText) - parseInt (children2[val].innerText));
		}
	}
	else {
		if (!num) {
			return (strCode(children2[val].innerText) - strCode(children1[val].innerText));
		}
		else {
			return (parseInt(children2[val].innerText) - parseInt (children1[val].innerText));
		}
	}
}
function sortby (elemclass,val,num) {
	var elems = document.getElementsByClassName (elemclass);
	document.sortBy = val;
	document.n = num;
	if (previous == elemclass + " " + val)
		document.order = !document.order;
	else
		previous = elemclass + " " + val;
	elems.sort (sortF);
	for (var i = elems.length - 1; i >= 0; i--) {
		var pn = elems[i].parentNode;
		pn.removeChild (elems[i]);
		pn.appendChild (elems[i]);
	}
}


function setcookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1) { 
				c_start=c_start + c_name.length+1; 
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1)
					c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
			} 
		}
	return "";
}	
htIRCFrame.prototype.setTopic = function (msg,chan) {
	var topicElem=document.getElementById("topicElem");
		if(old = topicElem.firstChild) {
			topicElem.removeChild(old);
		}
	topicElem.appendChild(IRCtoDOM(msg));
}
window.onblur = function() {
	blurred = true;
}
window.onfocus = function() {
	blurred = false;
	parent.setT ("Surrealchat.net");
}
function disp_prompt() {
	var nameZ = prompt("Please enter new nickname","");
		if (nameZ!=null && nameZ!="") {
			serverSendText("NICK " + nameZ);
 		}
}
function createTimeStamp() {
	var ts = document.createElement('span');
	var c = new Date();
	var hours = c.getHours();
	if(hours < 10) hours = " " + hours;
	var minutes = c.getMinutes();
	if(minutes < 10) minutes = "0" + minutes;
	ts.appendChild(document.createTextNode('[' + hours + ':' + minutes + '] '));
	ts.className = 'chattimestamp';

	return ts;
}

//FIXME - color support is messy

var MSIE = (document.all ? 1 : 0);

var colorcodes = [
	"#ffffff", //0
	"#000000", //1
	"#00007f", //2
	"#009300", //3
	"#ff0000", //4
	"#7f0000", //5
	"#9c009c", //6
	"#fc7f00", //7
	"#ffff00", //8
	"#00fc00", //9
	"#009393", //10
	"#00ffff", //11
	"#0000fc", //12
	"#ff00ff", //13
	"#7f7f7f", //14
	"#d2d2d2", //15
];


function IRCtoDOM(text, m) {
	var container = document.createElement('p');
	container.appendChild(createTimeStamp());
	var cfg, cbg, cbold, citalic, cunderline;
	if (text.replace(/[0-9](?:[0-9])/g,'').match(this.nick.get()) && m ) {
		var text3 = text.replace(/[0-9](?:[0-9])/g,'');
		var thing = text3.split(">")[0] + '>';
		var thing2 = text3.split('>')[1];
		var d = document.createElement('span');
		d.style['color'] = 'red';
		thing2 = thing.replace('>','&gt;');
		thing2 = thing.replace('<','&lt;');
		d.innerHTML = thing2;
		e = document.createElement('span');
		e.appendChild(d);
		container.appendChild(e);
		var text2 = text.replace(thing,'');
		text = text2;
	}
	var ctext = text.split(/(\x03(?:\d{1,2})?(?:,\d{1,2})?|\x02|\x0f|\x16|\x1f|(?:http:\/\/)?(?:[-a-z0-9]+\.)+[a-z]+(?:\/[-.a-z0-9%._~:\/?#[\]@!$&'()*+,;=]+)?)/i); // you are not expected to understand this.
	for(var i = 0; i < ctext.length; i++) {
		var currentpart = ctext[i];
		var firstchar = currentpart.substring(0, 1);

		if(firstchar === "\x03") {
			if(currentpart.length === 1) {
				cfg = undefined;
				cbg = undefined;
			} else {
				var ccodes = currentpart.substring(1).split(',');
				if(ccodes[0] && ccodes[0].length > 0) {
					cfg = colorcodes[parseInt(ccodes[0])];
				}
				if(ccodes[1] && ccodes[1].length > 0) {
					cbg = colorcodes[parseInt(ccodes[1])];
				}
			}
		}
		else if(firstchar === "\x02") {
			cbold = (cbold ? 0 : 1);
		}
		else if(firstchar === "\x0f") {
			cfg = cbg = cbold = citalic = cunderline = undefined;
		}
		else if(firstchar === "\x16") {
			citalic = (citalic ? 0 : 1);
		}
		else if(firstchar === "\x1f") {
			cunderline = (cunderline ? 0 : 1);
		} else {
			var e;

			if(currentpart.match(/^(?:http:\/\/)?(?:[-a-z0-9]+\.)+[a-z]+(?:\/[-.a-z0-9%._~:\/?#[\]@!$&'()*+,;=]+)?$/i)) {
				e = document.createElement('a');
				e.className = 'irctextlink';
				e.href = (currentpart.match(/^http:\/\//i) ? currentpart : "http://" + currentpart);
				e.target = "_blank";
			} else {
				e = document.createElement('span');
			}

			if(cfg) e.style['color'] = cfg;
			if(cbg) e.style['backgroundColor'] = cbg;
			if(cbold)  { e.style['fontWeight'] = 'bold'; }
			if(cunderline) e.style['textDecoration'] = 'underline';
			//var cur = (MSIE ? currentpart : currentpart.replace(/\s/g, "\u00a0\u200b"));
			e.appendChild(document.createTextNode(currentpart));
			
			container.appendChild(e);
		}
	}
	return container;
}

function htIRCMixins(x) {
	x.createP = function (text) {
		var p = document.createElement('p');
		p.appendChild(document.createTextNode(text));
		return p;
	}
	
	x.setP = function (name, text) {
		var p;
		if(p = document.getElementById(name)) {
			p.firstChild.nodeValue = text;
		} else {
			var p = document.createElement('p');
			p.appendChild(document.createTextNode(text));
			p.id = name;
			p.style.display = 'none';
			document.getElementsByTagName('body')[0].appendChild(p);
		}
	}

	x.getP = function (name) {
		return document.getElementById(name).firstChild.nodeValue;
	}
}

//--

function htIRCMyNick() {
	htIRCMixins(this);

	this.set = function (nick) {
		this.setP('chatnick', nick);
	}

	this.get = function () {
		return this.getP('chatnick');
	}

	this.randomize = function () {
		var n = this.get();
		n = n.substring(0, 25) + Math.floor(Math.random()*99999).toString();
		//TODO: Cleanup
		this.set(n);
		serverSendText('NICK ' + n);
	}

	if(window.htirc.initialNick) {
		this.set(window.htirc.initialNick);
	} else {
		this.set('Guest' + Math.floor(Math.random()*99999).toString());
	}
}

//--


function htIRCNamesList() {
	this.elem = document.getElementById('chatnames').cloneNode(true);
	this.elem.style.display = 'none';
	this.elem.style.className = 'nameslist';
	this.elem.id = '';
	document.getElementById('chatboxc').appendChild(this.elem);
	document.getElementById('chatnamesd').appendChild(this.elem);
	this.hash = new Object;
}



htIRCNamesList.prototype.foreach = function (call) {
	var el = this.elem.firstChild;
	while(el) {
		var ret = call(el);
		if(ret) { return ret; }
		el = el.nextSibling;
	}
}

htIRCNamesList.prototype.getAlph = function (name) {
	var lname = name.toLowerCase();
	return this.foreach(function (el) {
		if(el.firstChild.value.toLowerCase() > lname) {
			return el;
		}
	});
}

document.onmousemove = function (e) {
	e = (e ? e : window.event);
	document.x = e.clientX;
	document.y = e.clientY;
}

function button0IE1(e) {
	return (e.button == 0 || (navigator.userAgent.match("IE") && e.button == 1));
}

document.onmousedown = function (e) {
	e = (e ? e : window.event);
	var target = (e.target ? e.target : e.srcElement);
	if (button0IE1(e))  {
		
		if (target.className != 'rightmenu' && target.className != "menuli") {
			closeMenus();
		}
	}
	else if (e.button == 2) {
		if (document.getElementsByClassName('activetab')[0].value != '-server-' && !document.getElementsByClassName('activetab')[0].value.match ("#")) {
			document.nc = document.getElementsByClassName('activetab')[0].value;
			var div = document.getElementsByClassName ('rightmenu 2')[0];
			div.style.position="absolute";
			div.style.left = document.x + 'px';
			div.style.top = document.y + 'px';
			div.style.display = "";
		}
		else if (document.getElementsByClassName('activetab')[0].value == '-server-') {
			var div = document.getElementsByClassName ('rightmenu 4')[0];
			div.style.position="absolute";
			div.style.left = document.x + 'px';
			div.style.top = document.y + 'px';
			div.style.display = "";
		}
		else if (document.getElementsByClassName('activetab')[0].value.match ("#")) {
			if (target.className == "nameslistitem")
				return;
			document.nc = document.getElementsByClassName('activetab')[0].value;
			var div = document.getElementsByClassName ('rightmenu 3')[0];
			div.style.position="absolute";
			div.style.left = document.x + 'px';
			div.style.top = document.y + 'px';
			div.style.display = "";
		}
	}
}

document.oncontextmenu = function() { return false; }

function banlist (channel) {
	clearBList();
	serverSendText ("MODE " + channel + " b");
}
function chanlist (channel) {
	clearChList();
	serverSendText ("LIST");
}
function elist (channel) {
	clearBList();
	serverSendText ("MODE " + channel + " e");
}
function unban (host, chan) {
	serverSendText ("MODE " + chan + " -b " + host);
	setTimeout (function() { banlist (chan); }, 300);
}
function unexempt (host, chan) {
	serverSendText ("MODE " + chan + " -e " + host);
	setTimeout (function() { elist (chan); }, 300);
}
function clearBList () {
	document.getElementById ("banlist").innerHTML = '<div id="window-title"><span id=\'window-close\' onclick="clearBList();closeBList()">&#215;</span>&nbsp;&nbsp;&nbsp;&nbsp;Banlist</div><br/><span style="width:985px;position:fixed"><input type="button" style="width:33.3%" onclick="sortby(\'banz\',0);"  value="Mask" /><input style="width:33.3%" type="button" value="User" onclick="sortby(\'banz\',1);" /><input style="width:33.3%" type="button" value="Date" onclick="sortby(\'banz\',2);"/></span><br/><br/>';
}
function clearChList () {
	document.getElementById ("chanlist").innerHTML = '<div id="window-title"><span id=\'window-close\' onclick="clearChList();closeChList()">&#215;</span>&nbsp;&nbsp;&nbsp;&nbsp;Channel List</div><br/><span style="width:985px;position:fixed"><input style="width:33.3%" onclick="sortby(\'channels\',0);" type="button" value="Name" /><input style="width:10%" onclick="sortby(\'channels\',1,true);" type="button" value="Users" /><input style="width:56.7%" type="button" value="Topic" onclick="sortby(\'channels\',2);"/></span><br/><br/><br/>';
}
function closeBList () {
	document.getElementById ("banlist").style.display = "none";
}
function closeChList () {
	document.getElementById ("chanlist").style.display = "none";
}

htIRCNamesList.prototype.add = function (name) {
	var n = document.createElement('li');
	var b = document.createElement('input');
	b.type = 'button';
	b.value = name;
	b.className = 'nameslistitem';
	b.onmousedown = function (e) {
		e = (e ? e : window.event);
		if (button0IE1(e)) {
			openQuery(this.value);
			//document.getElementsByClassName ('rightmenu')[0].style.display = 'none';
		}
		else if (e.button == 2) {
			document.nc = b.value;
			var div = document.getElementsByClassName ('rightmenu')[0];
			div.style.position="absolute";
			div.style.left = document.x + 'px';
			div.style.top = document.y + 'px';
			div.style.display = "";
		}
	}
	n.appendChild(b);
	var aln = this.getAlph(name);
	if(aln) {
		this.elem.insertBefore(n, aln);
	} else {
		this.elem.appendChild(n);
	}
	this.hash[name.toLowerCase()] = n;
}

htIRCNamesList.prototype.exists = function (name) {
	return this.hash[name.toLowerCase()];
}

htIRCNamesList.prototype.del = function (name) {
	var e;

	if(e = this.hash[name.toLowerCase()]) {
		this.elem.removeChild(e);
		this.hash[name.toLowerCase()] = false;
		return true;
	}
	else {
		return false;
	}
}

htIRCNamesList.prototype.change = function(oldn, newn) {
	var e;

	if(e = this.hash[oldn.toLowerCase()]) {
		this.elem.removeChild(e);
		this.add(newn);
		this.hash[oldn.toLowerCase()] = false;
		return true;
	}
	else {
		return false;
	}
}

htIRCNamesList.prototype.addList = function (nameslist) {
	var names = nameslist.split(' ');

	for(var x in names) {
		if(names[x]) {
			var actualname;
			if(names[x].match(/^[~&@%+]/)) {

				actualname = names[x].substring(1);
			}
			else {
				actualname = names[x];

			}

			if(!this.hash[actualname.toLowerCase()]) {
				this.add(actualname);

			}
		}
	}
}

htIRCNamesList.prototype.clear = function () {
	var el;
	while(el = this.elem.firstChild) {
		this.elem.removeChild(el);
	}

	this.hash = new Object;
}

//--

function htIRCUI() {
	var sframe = new htIRCFrame('-server-');
	sframe.activate();

	document.forms.chatform.onsubmit = userTypedSomething;
	document.getElementById('chatinput').onkeydown = function (e) {
		if((e && e.keyCode == 9) || (window.event && window.event.keyCode == 9)) {
			window.htirc.frames.current.autoComplete(this);
			return false;
		}
		if((e && e.keyCode == 13) || (window.event && window.event.keyCode == 13)) {
			userTypedSomething();
			return false;
		}
	}
	
	document.getElementById('chatclose').onclick = function () {
		window.htirc.frames.current.destroy();
	}
}

function part() {
	window.htirc.frames.current.destroy();
}
//--

function htIRCFrameContainer() {
	this.current = undefined;
	this.list = new Object();
}

htIRCFrameContainer.prototype.get = function (name) {
	var id = name.toLowerCase();

	var ret;
	if(ret = this.list[id]) {
		return ret;
	}
	else {
		return new htIRCFrame(name);
	}
}

htIRCFrameContainer.prototype.exists = function (name) {
	var id = name.toLowerCase();

	var ret;
	if(ret = this.list[id]) {
		return true;
	}
	else {
		return false;
	}
}

htIRCFrameContainer.prototype.foreach = function (f) {
	var ret;
	for(id in this.list) {
		ret = f(this.list[id]);
		if(ret) return ret;
	}
}

htIRCFrameContainer.prototype.appendAll = function (text) {
	for(id in this.list) {
		this.list[id].append(text);
	}
}

htIRCFrameContainer.prototype.updateTabs = function () {
	var tablist = document.getElementById('chatframelist');
	while(tablist.firstChild) {
		tablist.removeChild(tablist.firstChild);
	}
	
	for(id in this.list) {
		var frame = this.list[id];
		var e = document.createElement('input');
		e.type = 'button';
		e.frameTarget = frame;
		e.value = frame.name;
		e.onclick = function () { this.frameTarget.activate(); };
		e.activate = 
			function () { 
				this.className = 'activetab'; 
					
			}
		e.deactivate = function () {
			if(!this.className.match(/inactivetab/)) {
				this.className = 'inactivetab';
			}
		};

		e.deactivate();
		tablist.appendChild(e);
		frame.tab = e;
	}
}

htIRCFrameContainer.prototype.exists = function (name) {
	return this.list[name.toLowerCase()];
}

//--

function htIRCFrame(name) {
	htIRCMixins(this);

	this.name = name;
	this.id = name.toLowerCase();
	
	this.elem = document.getElementById('chatbox').cloneNode(true);
	//this.elem.style.overflow = 'auto';
	this.elem.style.display = 'none';
	this.elem.className = 'chatbox';
	this.elem.id = '';
	document.getElementById('chatboxc').appendChild(this.elem);

	this.nl = new htIRCNamesList;

	window.htirc.frames.list[this.id] = this;
	window.htirc.frames.updateTabs();
	this.activate();
}

htIRCFrame.prototype.destroy = function () {
	var prev;
	
	//FIXME
	if(this.id.match(/^#/)) {
		serverSendText('PART ' + this.id);
	}

	for(x in window.htirc.frames.list) {
		if(!prev) { prev = x; }

		if(x == this.id) {
			break;
		}

		prev = x;
	}
	
	this.elem.style.display="none";	
	//FIXME?
	this.nl.elem.style.display="none";

	delete(window.htirc.frames.list[id]);
	window.htirc.frames.updateTabs();
	window.htirc.frames.list[prev].activate();

	//FIXME
	this.nl.elem.parentNode.removeChild(this.nl.elem);
	this.nl = undefined;

	this.elem.parentNode.removeChild(this.elem);
}

htIRCFrame.prototype.doScroll = function () {
	this.elem.parentNode.scrollTop = this.elem.parentNode.scrollHeight;
}

htIRCFrame.prototype.append = function (text, m) {
	//var p = this.createP(text);
	m = (m === null?false:m);
	var p = IRCtoDOM(text, m);
	p.className = 'chatline';
	this.elem.appendChild(p);
	this.doScroll();
}

htIRCFrame.prototype.highlight = function (t,s) {
	if(this.tab.className == 'inactivetab') {
		if (t) {
			this.tab.className += ' otherhighlight';
		}
		else if (s)
			this.tab.className += ' servhighlight';
		else if (!t && !s)
			this.tab.className += ' highlighttab';
	}
	else if (this.tab.className == "inactivetab highlighttab" && t) {
		this.tab.className ="inactivetab otherhighlight";
	}
	else if (this.tab.className == "inactivetab highlighttab" && s) {
		this.tab.className ="inactivetab servhighlight";
	}
	
}
function joinCh (chan) {
	serverSendText ("CS :JOIN " + chan);
}
htIRCFrame.prototype.activate = function () {
	for(id in window.htirc.frames.list) {
		var frame = window.htirc.frames.list[id];

		frame.elem.style.display="none";
		if(frame.nl)
			frame.nl.elem.style.display="none";
		frame.tab.deactivate();
	}

	this.elem.style.display="block";
	if(this.nl)
		this.nl.elem.style.display="block";
	
	window.htirc.frames.current = this;
	
	this.tab.activate();
	this.doScroll();

	//FIXME ?
		if (chanTopics[this.name]) {
			window.htirc.frames.get(this.name).setTopic(chanTopics[this.name],this.name);
		}
		else {
			var topicElem = document.getElementById("topicElem");
			if(old = topicElem.firstChild) {
				topicElem.removeChild(old);
			}
		}
	document.getElementById('chatnamesc').style.visibility = (this.id == '-server-' ? 'hidden' : 'inherit');
	document.getElementById('chatclose').style.visibility = (this.id == '-server-' ? 'hidden' : 'inherit');
	document.forms.chatform.chatinput.focus();
}

htIRCFrame.prototype.autoComplete = function (textbox) {
	var n = /(.*(?:^| ))(.+)(\W*)$/.exec(textbox.value);
	var c = this.nl.getAlph(n[2]);
	if(c) {
		c = c.firstChild.value;
	}
	else {
		c = this.nl.elem.firstChild.firstChild.value;
	}

	if(!n[1]) c += ', ';

	textbox.value = n[1] + c;
}

//--

//htIRCDispatch

//--

function htIRC() {
	htIRCMixins(this);

	this.begin = function () {

		// TODO: Move this junk somewhere else
		if(!window.htirc.initialNick) {
			window.htirc.initialNick = document.getElementById('chatnickinput').value;
			window.htirc.initialNSPass = document.getElementById('chatpassinput').value;
		}
		window.htirc.initialNick = window.htirc.initialNick.replace(
			/^[^\][a-zA-Z`\\\|{}_]|[^\][a-zA-Z0-9`\\\|{}_-]/g, "_"
		);
		document.getElementById('chatlogindlg').style.display='none';
		document.getElementById('chatc').style.display='block';

		this.nick = new htIRCMyNick;
		this.frames = new htIRCFrameContainer;
		this.ui = new htIRCUI;
		
		createIFrame();
		hello();

		
	}
}

htIRC.prototype.dispatch = function (line) {
	var msgParts = /^:?(.*?)(?: :(.*))?$/.exec(line);
	if(!msgParts) return;
	msgParts.shift();
	var params = msgParts[0].split(' ');
	var msg = msgParts[1];

	if (params[1] == 'MODE' ) {
		var msg = "";
		var nick = maskGetNick(params[0]);
		var f;
			for (var i = 4; i < params.length; i++) {
				msg += params[i] + " ";
			}
			if (params[2] != this.nick.get()) {
				var f = this.frames.get(params[2]);
			}
			else
				var f = this.frames.get('-server-');
		if (params[3]) //apparently when connecting it sets mode +undefined to itself?
			f.append (nick + " set mode " + params[3] + " " + msg)
	}

	else if(params[1] == 'PRIVMSG') {
		var nick = maskGetNick(params[0]);
		var dst;
		if(insEqual(params[2], this.nick.get())) {
			dst = nick;
		} else {
			dst = params[2];
		}
		var ctcp = /^\001(.*?)(?: (.*?))?\001?$/.exec(msg);
		if(ctcp) {
			if(ctcp[1] == 'ACTION') {
				this.frames.get(dst).append('* ' + nick + ' ' + ctcp[2]);
				this.frames.get(dst).highlight();
				if (blurred)
					window.parent.setT("Someone said something!");
			} else {
				this.frames.get('-server-').append('--- Received CTCP ' + ctcp[1] + ' from ' + nick);
				this.frames.get('-server-').highlight(0,1);
				if(ctcp[1] == 'VERSION') {
					serverSendText('NOTICE ' + nick + ' :\001VERSION htIRC experimental prerelease -- ' + navigator.userAgent + '\001');
				}
				if (ctcp[1] == "PING")
					serverSendText ("NOTICE " + nick + " :\001PING " + ctcp[2] + "\001");
				if (ctcp[1] == "TIME")
					serverSendText ("NOTICE "+ nick + " :\001TIME " + new Date() + "\001");
			}
		} else {
			this.frames.get(dst).append('<' + nick + '> ' + msg, true);
			if (blurred)
				window.parent.setT("Someone said something!");
			if (msg.replace(/[0-9](?:[0-9])/g,'').match(this.nick.get()))
				var t = true;
			else
				var t = false;
			this.frames.get(dst).highlight(t);
		}
	}
	else if(params[0] == 'PING') {
		serverSendText('PONG :' + msg);
	}
	else if(params[1] == '376') { // end of motd
		if (window.htirc.initialNSPass)
			serverSendText('NS SID '  + window.htirc.initialNick + ' ' +
				window.htirc.initialNSPass);
		if (window.htirc.initialChans)
			serverSendText('CS :JOIN ' + window.htirc.initialChans);
		//serverSendText("PRIVMSG erry,tab|away :detected a 376. If i'm not joined, i'm screwed - chanlist:" + window.htirc.initialChans);
		if (getCookie ('notify')) {
			var nl = getCookie ('notify').split (',');
			for (var i = 0; i < nl.length; i++) {
				serverSendText ('WATCH +' + nl[i]);
			}
		}
	}
	else if (params[1] == 322) { //channel list
		var chanlist = document.getElementById ("chanlist");
		var div = document.createElement ("div");
		div.className = "channels";
		//console.log (params);
		div.ondblclick = function() { joinCh (params[3]); }
		var div2 = document.createElement ("div");
		div2.className = "chan name";
		div2.style.float="left";
		div2.style.width = "33.3%";
		div2.innerHTML = params[3];
		div.appendChild (div2);
		var div3= document.createElement ("div");
		div3.innerHTML = parseInt(params[4]);
		div3.className = "chan users";
		div3.style.float="left";
		div3.style.width = "10%";
		if (navigator.userAgent.match ("MSIE 7") || navigator.userAgent.match ("MSIE 6"))
			div3.style.width = "8%";
		div.appendChild (div3);
		var div4 = IRCtoDOM (msg);
		div4.style.float = "left";
		div4.className = "chan topic";
		div4.style.width = "56.7%";
		div.appendChild (div4);
		div.appendChild (document.createElement("br"));
		chanlist.appendChild (div);
	}
	else if (params[1] == 367 || params[1] == 348) { //ban/exceitpion list
		/*<div class='banz' ondblclick="unban('zzzzzzz','#erry')"><input type='radio' id='b1' style="display:none;float:left" /><label for="b1"><div class="bans" style="float:left">zzzzzzz</div></label><label for="b1"><div class="bans" style="float:left">erry</div></label><label for="b1"><div class="bans" style="float:left">22 Dec 2012</div></label></div>*/
		var chanlist = document.getElementById ("banlist");
		var div = document.createElement ("div");
		div.className = "banz";
		if (params[1] == 367)
			div.ondblclick = function() { unban (params[4], params[3]); }
		else
			div.ondblclick = function() { unexempt (params[4], params[3]); }
		var div2 = document.createElement ("div");
		div2.className = "bans";
		div2.style.float="left";
		div2.innerHTML = params[4];
		div.appendChild (div2);
		var div3= document.createElement ("div");
		div3.innerHTML = params[5];
		div3.className = "bans";
		div3.style.float="left";
		if (navigator.userAgent.match ("MSIE 7") || navigator.userAgent.match ("MSIE 6"))
			div3.style.width = "31%";
		div.appendChild (div3);
		var div4 = document.createElement ("div");
		
		div4.innerHTML = new Date (new Date().getTime() - params[6]);
		div4.className = "bans";
		div4.style.float = "left";
		div.appendChild (div4);
		
		div.appendChild (document.createElement("br"));
		chanlist.appendChild (div);
	}
	else if (params[1] == 368 || params[1] == 349) { //end of ban/excempt list
		document.getElementById ('banlist').style.display = "";
	}
	else if (params[1] == 323) { //end of channel list
		var chanlist = document.getElementById ('chanlist');
		chanlist.style.display = "";
		var oldh = chanlist.innerHTML; //IE weirdness
		chanlist.innerHTML = "";
		chanlist.innerHTML = oldh;
	}
		
	else if(params[1]==301) { 
		//is away
		if(this.frames.exists(params[3])) {
			this.frames.get(params[3]).append('---' + params[3] + ' is away: ' + msg + '---');
			this.frames.get(params[3]).highlight();
		} else {
			this.frames.get('-server-').append('---' + params[3] + ' is away: ' + msg + '---');
			this.frames.get('-server-').highlight(0,1);
		}
	}
	else if (params[1]==421) { 
		//unknown command
		this.frames.get('-server-').append('---' + params[3] + " is an unknown command.");
		this.frames.get('-server-').highlight(0,1);
	}
	else if(params[1]==473) { 
		//channel is +i
		this.frames.get('-server-').append('---Cannot join ' + params[3] + ' (You need to be invited)');
		this.frames.get('-server-').highlight(0,1);
	}
	else if (params[1]==474) {
		//you are banned
		this.frames.get('-server-').append('---Cannot join ' + params[3] + ' (You are banned! Well done!)');
		this.frames.get('-server-').highlight(0,1);
	}
	else if (params[1]==401) {
		//no such nick/channel
		this.frames.get('-server-').append('---' + params[3] + ' no such nick/channel');
		this.frames.get('-server-').highlight(0,1);
	}
	else if (params[1] == 311) {
		this.frames.get('-server-').append('---' + params[3] + ' is ' + params[4] + '@' + params[5] + ' * ' + msg);
		this.frames.get('-server-').highlight(0,1);
	}
	else if (params[1] == 312) {
		this.frames.get('-server-').append('---' + params[3] + ' is using the ' + params[4] + ' server on ' + msg);
		this.frames.get('-server-').highlight(0,1);
	}
	else if (params[1] == 317) {
		var myDate = new Date( params[5] *1000);

		this.frames.get('-server-').append('---' + params[3] + ' has been idle ' + params[4] + ' seconds, signed on ' + myDate.toGMTString());
		this.frames.get('-server-').highlight(0,1);
	}
	else if (params[1] == 313 || params[1] == 310 || params[1] == 320 || params[1] == 378 || params[1] == 379) {
		//nick is an ircop, nick is "available for help", or swhois
		//nick is connecting from host IP
		//nick is using modes +whatever
		this.frames.get('-server-').append('---' + params[3] + ' ' + msg);
		this.frames.get('-server-').highlight(0,1);
	}
	else if (params[1] == 319) {
		//nick is on some channels
		this.frames.get('-server-').append('---' + params[3] + ' has joined: ' + msg);
		this.frames.get('-server-').highlight(0,1);
	}
	else if (params[1] == 318) {
		this.frames.get('-server-').append('---' + params[3] + ' end of /whois');
		this.frames.get('-server-').highlight(0,1);
	}
	else if (params[1]==604) {
		//notify: nick is online
		window.htirc.frames.appendAll("\03"+ 4 + "\x1f" +  "--NOTIFY-- " + params[3] +' is online');
	}
	else if (params[1]==600) {
		//notify: nick just logged on
		window.htirc.frames.appendAll("\03"+ 4 + "\x1f" +  "--NOTIFY-- " + params[3] + ' is now online');
	}
	else if (params[1]==601) {
		//notify: nick is now offlie
		window.htirc.frames.appendAll("\03"+ 4 + "\x1f" +  "--NOTIFY-- " + params[3] + ' has quit IRC or changed nickname');
	}
	else if (params[1]==605) {
		//notify: nick is not online
		window.htirc.frames.appendAll("\03"+ 4 + "\x1f" +  "--NOTIFY-- " + params[3] + ' is not online');
	} else if (params[1] == 607) {
		this.frames.get('-server-').append (params[2] + ': end of watch list.'); 
		this.frames.get('-server-').highlight(0,1);
	}
	else if (params[1] == 404) {
		//no external MSG/you are banned/+m?
		this.frames.get(params[3]).append('---' + params[3] + ' ' +  msg);
	}
	else if (params[1]==475) {
		//channel is +k
		this.frames.get('-server-').append('---Cannot join ' + params[3] + ' (Need the correct channel key. If you have it type /join ' + params[3] + '(key))');
		this.frames.get('-server-').highlight(0,1);
	}
	else if (params[1]=='NOTICE') {
		nickz = params[0].split("!");
		nickz = nickz[0];
		this.frames.get('-server-').append('---Notice by ' + nickz + ': ' + msg);
		this.frames.get('-server-').highlight(0,1);
	}
	else if(params[1] == '432' || params[1] == '433') { 
		// nickname in use / erroneous
		nick2 = prompt("The nick you chose is " + (params[1] == '432'?"not allowed":"in use already") + ", please choose another!");
		if (nick2)
		{		
			serverSendText('NICK ' + nick2);
			this.nick.set(nick2);
		}
	}
	else if(params[1] == '332') { // topic
		this.frames.get(params[3]).append('--- Topic for ' +
				params[3] + ' is: ' + msg);
		chanTopics[params[3]] = msg;
		this.frames.get(params[3]).setTopic(msg,params[3]);
	}	
	else if(params[1] == '353') { // names response
		this.frames.get(params[4]).nl.addList(msg);
	}
	else if(params[1] == 'JOIN') {
		userJoined(maskGetNick(params[0]), msg);
	}
	else if(params[1] == 'PART') {
		userLeft(maskGetNick(params[0]), params[2], undefined, msg);
	}
	else if(params[1] == 'KICK') {
		userLeft(params[3], params[2], maskGetNick(params[0]), msg);
	}
	else if(params[1] == 'NICK') {
		var outmsg;
		if(insEqual(maskGetNick(params[0]), this.nick.get())) {
			outmsg = '--- You are now known as ' + msg;
			this.nick.set(msg);
		}
		else {
			outmsg = '--- ' + maskGetNick(params[0]) + ' is now known as ' + msg;
		}

		this.frames.foreach(function (e) {
			if(e.nl.change(maskGetNick(params[0]), msg)) {
				e.append(outmsg);
			}
		});
	}
	else if(params[1] == 'TOPIC') {
		appendChatLine('--- ' + maskGetNick(params[0]) + ' has changed the topic to: ' + msg, params[2]);
		this.frames.get(params[2]).setTopic(msg,params[2]);
	}
	else if(params[1] == 'QUIT') {
		var outmsg = '<-- ' + maskGetNick(params[0]) + ' has quit (' + msg + ')';
		this.frames.foreach(function (frame) {
			if(frame.nl.del(maskGetNick(params[0]))) {
				frame.append(outmsg);
			}
		});
	} else {
	
		appendChatLine(line, '-server-');
		this.frames.get('-server-').highlight(0,1);
	}
}

htIRC.prototype.gotDisconnected = function () {
	//FIXME
	window.htirc.frames.appendAll("Connection lost. To reconnect, reload this page.");
}


	
function boldText() {
	document.getElementById("chatinput").value+="";
}
	
function underlineText() {
	document.getElementById("chatinput").value+="";
}

window.htirc = new htIRC;

window.htirc.oldonload = window.onload;
window.onload = function () {
	if(window.htirc.initialNick) {
		window.htirc.begin();
	}
	if(window.htirc.oldonload) window.htirc.oldonload();
};

/* functions for the rightclick menu so that the code isn't full of big text in onclick and looks kinda better. Sorta.*/
function closeMenus() { 
	document.getElementsByClassName ("rightmenu")[0].style.display = "none";
	document.getElementsByClassName ("rightmenu 2")[0].style.display = "none";
	document.getElementsByClassName ("rightmenu 3")[0].style.display = "none";
	document.getElementsByClassName ("rightmenu 4")[0].style.display = "none";
}

function silence (nick) {
	serverSendText ("NS SILENCE ADD " + nick);
	closeMenus();
}

function whois (nick) {
	serverSendText ("WHOIS " + nick);
	closeMenus();
}

function kick (nick) {
	var reason = prompt ("Enter kick reason", "POW!");
	if (!reason)
		reason = "POW!";
	serverSendText ("CS KICK " + window.htirc.frames.current.name + " " + nick + " " + reason);
	closeMenus();
}

function ban (nick) {
	serverSendText ("CS BAN " + window.htirc.frames.current.name + " " + nick);
	closeMenus();
}

function kickban (nick) {
	var reason = prompt ("Enter kickban reason", "POW!");
	if (!reason)
		reason = "POW!";
	serverSendText ("CS KICKBAN " + window.htirc.frames.current.name + " " + nick + " " + reason);
	closeMenus();
}

