var box_height = '400';

function typing_timeout(uid){
	var u = top.find_user(uid);
	if (!u||!u.box)return;
	u.box.stop_typing();
}

function chat_box(user){
	var time = 0;

	if (!top.multi_window || user.uid==-1)
	{
		var m = id2node("messages",top.document);
		var d = m.contentDocument;
		if (!d)d = m.contentWindow.document;

		this.doc = d;
		var c = id2node("chat",this.doc);
		this.messages = c.cloneNode(true);
		c.parentNode.insertBefore(this.messages,c);
		this.messages.setAttribute('id','');
	}
	else {
		var tpl = id2node("multi_win_template",top.document);
		var wnd = open("", '', 'status=no,toolbar=no,location=no,directories=no,menubar=no,scrollbar=no,scrollbars=no,resizable=no,copyhistory=no,width='+top.multi_win_template_width+',height='+multi_win_template_height);
		var d = wnd.document;
		d.open();
		d.write(tpl.innerHTML);
		d.close();
		wnd.focus();
		this.mwnd = wnd;
		this.mwnd.self_box = this;
		this.wnd_cache = d.documentElement.outerHTML;

		this.doc = d;
		this.messages = id2node("chat",d);
	}

	this.user = user;
	this.sid = 0;
	this.new_messages = 0;
	this.typing = false;			// another user typing
	this.self_typing = false;		// we are typing
	this.to_typing = 0;

	this.clear = function(){
		var n = this.messages.firstChild;
		while(n.firstChild){
			n.removeNode(n.firstChild);
		}
	}

	this.start_typing = function(){
		if (this.sid==0)
		{
			this.stop_typing();
			return;
		}
		if (!this.self_typing)
		{
			top.chat_send('/typing '+this.sid+' 1');
			this.self_typing = true;
		}
		if (this.to_typing!=0)
			window.clearTimeout(this.to_typing);
		this.to_typing = window.setTimeout('top.typing_timeout('+this.user.uid+')',10000);
	}

	this.stop_typing = function(){
		if (this.self_typing)
		{
			top.chat_send('/typing '+this.sid+' 0');
			this.self_typing = false;
		}
		if (this.to_typing!=0)
		{
			window.clearTimeout(this.to_typing);
			this.to_typing = 0;
		}
	}

	this.set_typing = function(is_typing){
		this.typing = is_typing;
		if (top.active_box==this)
			top.update_typing();
		this.user.update_status();
	}
	
	this.ensure_created = function(){
		if (this.user.uid==-1)return;
		if (!this.mwnd)return;
		if (top.multi_window&&this.mwnd.closed)
		{
			var wnd = open("", '', 'status=no,toolbar=no,location=no,directories=no,menubar=no,scrollbar=no,scrollbars=no,resizable=no,copyhistory=no,width='+top.multi_win_template_width+',height='+multi_win_template_height);
			var d = wnd.document;
			d.open();
			d.write(this.wnd_cache);
			d.close();
			wnd.focus();
			this.mwnd = wnd;
			this.mwnd.self_box = this;

			this.doc = d;
			this.messages = id2node("chat",d);
		}

	}

	this.show = function(){
		this.ensure_created();

		if (top.active_box)
			top.active_box.hide();

		this.doc.body.background_orig = this.doc.body.background;
		this.doc.body.background = '';

		var n = null;
		if (!this.is_admin_chat)
		{
			if (top.multi_window)
				n = id2node("timer_box",this.doc);
			else
				n = id2node("timer_box");
			if (n)n.style.display='';
			if (top.multi_window)
				n = id2node("actions_box",this.doc);
			else
				n = id2node("actions_box");
			if (!top.is_admin)
			{
				if (this.sid!=0)
				{
					if (n)n.style.display='';
				}
			}
			else
				if (n)n.style.display='';
		}

		if (this.is_admin_chat && top.users)
		{
			for (var i=0; i<top.users.length ; i++ )
			{
				if (top.users[i].level==1 && top.users[i].new_messages)
				{
					top.users[i].new_messages = 0;
					top.users[i].update_status();
				}
			}
		}

		top.active_box = this;
		this.messages.style.display = '';
		this.new_messages = 0;
		this.user.update_status();
		this.scroll();
		top.update_clock(this.time);
		top.update_typing();

		if (top.multi_window&&this.user.uid!=-1)
			this.mwnd.focus();
	}
	
	this.hide = function(){
		if (top.multi_window)
		{
		}
		else {
			if (top.active_box==this){
				top.active_box = null;
				id2node("timer_box").style.display='none';
				id2node("actions_box").style.display='none';
				if (this.doc.body.background_orig)this.doc.body.background = this.doc.body.background_orig;
			}
			this.messages.style.display = 'none';
			this.user.update_status();
			top.update_typing();
		}
	}

	this.message_count = function(){
		var cnt = 0;
		var n = this.messages.firstChild;
		while (n&&n.nodeName.toLowerCase()!='tr')
		{
			n = n.firstChild;
		}
		while (n)
		{
			if (n.style.display!='none')
				cnt++;
			n = n.nextSibling;
		}
		return cnt;
	}

// message processing
	this.replace = function(uid,tm,msg,node){
		if (node.nodeName=='#text')
		{
			if (node.nodeValue.indexOf('#time#')!=-1){
				var level = get_user_level();
				switch (level){
				case 0:
					level = "user";
					break;
				case 1:
					level = "op";
					break;
				default:
				case -1:
					level = "system";
					break;
				}
				node.parentNode.setAttribute("class","chat_time_"+level);
				node.parentNode.className = "chat_time_"+level;
				node.nodeValue = node.nodeValue.replace('#time#',tm);
			}
			if (node.nodeValue.indexOf('#author#')!=-1){
				var level = get_user_level(uid);
				switch (level){
				case 0:
					level = "user";
					break;
				case 1:
					level = "op";
					break;
				default:
				case -1:
					level = "system";
					break;
				}
				node.parentNode.setAttribute("class","chat_author_"+level);
				node.parentNode.className = "chat_author_"+level;
				node.nodeValue = node.nodeValue.replace('#author#',get_user_name(uid).replace(/ /g,"\xa0"));
			}
			if (node.nodeValue.indexOf('#message#')!=-1)
			{
				var level = get_user_level(uid);
				switch (level){
				case 0:
					level = "user";
					break;
				case 1:
					level = "op";
					break;
				default:
				case -1:
					level = "system";
					break;
				}
				node.parentNode.setAttribute("class","chat_message_"+level);
				node.parentNode.className = "chat_message_"+level;
				node.parentNode.insertBefore(msg,node);
				node.nodeValue = node.nodeValue.replace('#message#','');
			}
		}
		else
		{
			var n = node.firstChild;
			while (n)
			{
				this.replace(uid,tm,msg,n);
				n = n.nextSibling;
			}
		}
	}

	this.append_text = function(parent,s){
		var tn = this.doc.createTextNode(s);
		tn.nodeValue = s;
		parent.appendChild(tn);
	}

	this.append_link = function(parent,url,s,target){
		if (target!='_top')
			target='_blank';
		var ln = this.doc.createElement("a");
		var tmp = url.toLowerCase();
		if (target!='_top')
		{
			if (tmp.substr(0,5)!='http:' && tmp.substr(0,6)!='https:' && tmp.substr(0,4)!='ftp:' && tmp.substr(0,7)!='mailto:')
				url = 'http://'+url;
		}
		ln.setAttribute("href",url);
		ln.setAttribute("target",target);
		var tn = this.doc.createTextNode(s);
		tn.nodeValue = s;
		ln.appendChild(tn);
		parent.appendChild(ln);
	}

	this.append_format = function(parent,fmt,s){
		var ln = this.doc.createElement(fmt);
		var tn = this.doc.createTextNode(s);
		tn.nodeValue = s;
		ln.appendChild(tn);
		parent.appendChild(ln);
	}

	this.append_tag = function(parent,tag){
		var ln = this.doc.createElement(tag);
		parent.appendChild(ln);
	}

	this.append_action = function(parent,act,s){
		var ln = this.doc.createElement("a");
		ln.setAttribute("href",'#');
		ln.custom_action = act;
		ln.onclick = function(){eval(this.custom_action);return false;}
		var tn = this.doc.createTextNode(s);
		tn.nodeValue = s;
		ln.appendChild(tn);
		parent.appendChild(ln);
	}

	this.scroll = function(){
		if (top.multi_window&&this.user.uid!=-1)
		{
			if (top.multi_window)
				this.ensure_created();
			this.messages.parentNode.scrollTop = 99999;
		}
		else{
			if (!this.wnd)
			{
				var frm = id2node("messages",document);
				if (top.frames&&top.frames["messages"])
					this.wnd = top.frames["messages"];
				else if (frm.contentWindow)
					this.wnd = frm.contentWindow;
				else
					this.wnd = frm.document.defaultView;
			}
			if (this.wnd)
			{
				this.wnd.scroll(0,999999);
				top.tmp_scroll = this;
				window.setTimeout("if (top.tmp_scroll)top.tmp_scroll.scroll2();",100);
			}
		}
	}
	
	this.scroll2 = function(){
		if (this.wnd)
		{
			this.wnd.scroll(0,999999);
		}
	}

	this.process_message = function(message){
		var df = this.doc.createDocumentFragment();
		var msg = message;
		var start = 0;
		msg = msg.replace(/\[\\?url\]/g,"");

		// detect urls
		var res = msg.match(/(^|[\x00-\x20,\.\(\)\[\]])([^\x00-\x20]+@|https?:|ftp:|www\.|ftp\.)[^\x00-\x20]+/gi);
		var pos = 0;
		if (res)
		{
			for (var i=0;i<res.length;i++){
				var token = res[i];
				pos = msg.indexOf(token,pos);

				var len = token.length;
				var url = "";
				if (token.match(/^[\x00-\x20,\.\(\)\[\]]/i)){
					token = token.substr(1);
					pos++;
					len--;
				};
				if (token.match(/[,\.]$/i)){
					token = token.substr(0,token.length-1);
					len--;
				};
				if (token.match(/^(https?:|ftp:)/i)){
					url = token;
				}
				else if (token.indexOf("@")!=-1){
					url = "mailto:"+token;
				}
				else
					url = "http://"+token;
				
				msg = msg.substr(0,pos)+"[url"+url+"]"+token+"[/url]"+msg.substr(pos+len);
			}
		}

		// parse message
		start = 0;
		while (msg.length>0)
		{
			var pos = msg.indexOf("[",start);
			if (pos!=-1)
			{
				var pos1 = msg.indexOf("]",pos);
				if (pos1!=-1)
				{
					var tag = msg.substr(pos+1,pos1-pos-1).toLowerCase();

					if (tag.substr(0,3)=='url')
					{
						var pos2 = msg.toLowerCase().indexOf("[/url]",pos1);
						if (pos2!=-1)
						{
							var url = msg.substr(pos1+1,pos2-pos1-1);
							if (pos>0)
							{
								this.append_text(df,msg.substr(0,pos));
								start = 0;
							}
							this.append_link(df,tag.substr(3),url);
							msg = msg.substr(pos2+6);
							start = 0;
							continue;
						}
					}

					if (tag=='b')
					{
						var pos2 = msg.toLowerCase().indexOf("[/b]",pos1);
						if (pos2!=-1)
						{
							var ttt = msg.substr(pos1+1,pos2-pos1-1);
							if (pos>0)
							{
								this.append_text(df,msg.substr(0,pos));
								start = 0;
							}
							this.append_format(df,"b",ttt);
							msg = msg.substr(pos2+4);
							start = 0;
							continue;
						}
					}

					if (tag=='close')
					{
						var pos2 = msg.toLowerCase().indexOf("[/close]",pos1);
						if (pos2!=-1)
						{
							var url = msg.substr(pos1+1,pos2-pos1-1);
							if (pos>0)
							{
								this.append_text(df,msg.substr(0,pos));
								start = 0;
							}
							this.append_action(df,'top.send_offline();',url);
							msg = msg.substr(pos2+8);
							start = 0;
							continue;
						}
					}

					if (tag=='send')
					{
						var pos2 = msg.toLowerCase().indexOf("[/send]",pos1);
						if (pos2!=-1)
						{
							var url = msg.substr(pos1+1,pos2-pos1-1);
							if (pos>0)
							{
								this.append_text(df,msg.substr(0,pos));
								start = 0;
							}
							this.append_action(df,'top.send_confirm(this);',url);
							msg = msg.substr(pos2+8);
							start = 0;
							continue;
						}
					}

					if (tag=='accept' && top.is_admin)
					{
						if (pos>0)
						{
							this.append_text(df,msg.substr(0,pos));
							start = 0;
						}
						this.append_action(df,'top.accept('+this.user.uid+');','Accept');
						msg = msg.substr(pos+8);
						start = 0;
						continue;
					}

					if (tag=='cancel' && top.is_admin)
					{
						if (pos>0)
						{
							this.append_text(df,msg.substr(0,pos));
							start = 0;
						}
						this.append_action(df,'top.cancel('+this.user.uid+');','Cancel');
						msg = msg.substr(pos+8);
						start = 0;
						continue;
					}

					if (tag=='br')
					{
						if (pos>0)
						{
							this.append_text(df,msg.substr(0,pos));
							start = 0;
						}
						this.append_tag(df,'br');
						msg = msg.substr(pos+4);
						start = 0;
						continue;
					}

					start = pos+1;
					continue;
				}
			}
			break;
		}
		if (msg.length>0)
		{
			this.append_text(df,msg);
		}
		return df;
	}

	this.on_operator_connect = null;
	this.on_cancel_request = null;
	this.add_message = function(uid,tm,msg){
		if (top.multi_window)
			this.ensure_created();

		if (uid!=top.userid&&uid!=0&&!this.is_admin_chat&&(top.active_box==this||top.multi_window))
		{
			top.play_sound('new_message');
		}

		var tmp;
		try
		{
			var message = this.process_message(unescape(msg));
			if (tm==0)
				tm = new Date();
			else
				tm = new Date(tm*1000);
			tm = top.formatDate(tm);
			
			if (uid==0)
				tmp = id2node("chat_row_system",this.doc).cloneNode(true);
			else
				tmp = id2node("chat_row",this.doc).cloneNode(true);
			tmp.style.display = '';
			tmp.setAttribute("id","");
			this.replace(uid,tm,message,tmp);
			this.messages.firstChild.appendChild(tmp);
			if (this.on_operator_connect)
				this.on_operator_connect[this.on_operator_connect.length] = tmp;
			if (this.on_cancel_request && uid==0)
				this.on_cancel_request[this.on_cancel_request.length] = tmp;
		}
		catch (e)
		{
		}

		if (top.active_box==this || top.multi_window)
		{
			this.scroll();
			if (this.mwnd){
				this.mwnd.focus();
				this.wnd_cache = d.documentElement.outerHTML;
			}
		}
		else {
			this.new_messages++;
			if (this.is_admin_chat && uid!=0){
				var u = find_user(uid);
				if (u)
				{
					u.new_messages++;
					u.update_status();
				}
			}
			this.user.update_status();
		}
		return tmp;
	}
}

function add_message_to_session(sid,uid,tm,msg){
	if (top.users==null)return;
	
	for (var i=0;i<top.users.length;i++){
		if (top.users[i].box && top.users[i].box.sid == sid){
			top.users[i].box.add_message(uid,tm,msg);
			return;
		}
	}
}

function add_message_to_user(targ_uid,uid,tm,msg){
	if (top.users==null)return;
	
	for (var i=0;i<top.users.length;i++){
		if (top.users[i].uid==targ_uid){
			var cb = top.users[i].get_chat_box();
			cb.add_message(uid,tm,msg);
			return;
		}
	}
}

function set_session_id(uid,sid){
	if (top.users==null)return;
	
	if (!top.is_admin)
	{
		var n;
		n = id2node("actions_box");
		if (sid==0){
			if (n)n.style.display='none';
		}
		else {
			if (n)n.style.display='';
		}
	}

	for (var i=0;i<top.users.length;i++){
		if (top.users[i].uid==uid){
			var cb = top.users[i].get_chat_box();
			cb.sid = sid;
			if (sid>0)
				cb.time = 0;
			else
				cb.stop_typing();
			if (top.active_box==cb)
			{
				top.update_clock(0);
			}
			top.users[i].update_status();
			return;
		}
	}
}

function logout_popup(){
  open('close_monitor.php', 'MonitorUnload', 'status=no,toolbar=no,location=no,directories=no,menubar=no,scrollbar=no,scrollbars=no,resizable=no,copyhistory=no,width=5,height=5,left=0,top=0,screenX=0,screenY=0');
}

function notifyChildClose(w){
	if (top.users==null)return;
	
	for (var i=0;i<top.users.length;i++){
		var cb = top.users[i].box;
		if (cb&&typeof cb.mwnd!="undefined" && cb.mwnd==w)
		{
			if (cb.sid!=0)
			{
				top.active_box=cb;
				top.leave_chat();
			}
			top.users[i].clear_request();
			set_session_id(top.users[i].uid,0);
		}
	}	
}
