function another_login_message(){
	alert('The session has terminated because you signed on with this screen name at another location.');
}

function play_sound(name){
	if (top.soundCtl&&top.soundCtl.gotoAndPlay)
	{
		top.soundCtl.gotoAndPlay('/'+name, 'start');
	}
}

function another_login(msg){
	top.stop_refresh();
	if (msg)
		top.another_login_message();
	var o = top.opener;
	if (o&&!o.closed)
		o.location=o.location;
	window.close();
	top.do_close();
}

function focus_chat(){
	top.focus();
}

function formatDate(d){
        var h = d.getHours();
        var m = d.getMinutes();
        var s = d.getSeconds();
	if (m<10)m = '0'+m;
	if (s<10)s = '0'+s;
        if (h>=12){
                h-= 12;
                var a = "PM";
        }
        else {
                var a = "AM";
        }
        if (h==0)h=12;
        return h+':'+m+':'+s+"\xa0"+a;
}

function find_node(id,p){
	if (p==null)p=document;

	if (p.getAttribute&&p.getAttribute("id")==id)return p;
	var n = p.firstChild;
	while (n)
	{
		var r = find_node(id,n);
		if (r)return r;
		n = n.nextSibling;
	}
	return null;
}

function uniqid(){
	var d = new Date();
	return d.getTime();
}

function id2node(id,d){
	try
	{
		if (!d)d=document;
		if (d.getElementById)
			return d.getElementById(id);
		else if (d.all)
			return d.all[id];
		else
			return null;
	}
	catch (e)
	{
	}
	return null;
}

function chat_msg(f){
	if (top.active_box==null || (top.active_box.sid==0 && !top.active_box.is_admin_chat)){
		f['message'].focus();
		return false;
	}
	
	var msg = f["message"].value;
	f["message"].value = "";
/*
	if (msg.substr(0,6)=='/help ' && top.is_admin  && !top.active_box.is_admin_chat)
	{
		chat_send('/help '+top.active_box.user.uid+' '+msg.substr(6));
		top.active_box.add_message(0,0,'Please wait, Requesting assistance...');
	}
	else */if (msg=='/clear')
	{
		top.active_box.clear();
		f['message'].focus();
		f['message'].focus();
		return false;
	}
	else if (msg.length>0){
		chat_send('/msg '+top.active_box.sid+' '+msg);
	}
	top.active_box.stop_typing();
	f['message'].focus();
	f['message'].focus();
	return false;
}

function request_help(){
	if (!top.is_admin || !top.active_box || top.active_box.sid==0)return;

/*
	var f = document.forms[0];
	f["message"].value = "/help ";
	f["message"].focus();
	top.active_box.add_message(0,0,'You are about to request an assistance from another operator. Please enter your question bellow and press Send button.');
*/
	top.chat_send("/help "+top.active_box.user.uid+" 1");
	top.active_box.on_cancel_request2 = top.active_box.add_message(0,0,"Please wait. Transfering chat... [CANCEL]");
}

function send_offline(){
	top.stop_refresh();
	top.location='offline.php';
}

function leave_chat(){
	if (top.active_box&&top.active_box.sid!=0)
	{
		top.chat_send('/leave '+top.active_box.sid);
	}
}

function init_send_queue(){
	top.to_send = 0;
	top.send_queue = new Array();
	top.last_send_event = 0;
}

function send_queue_add(cmd){
	top.last_send_event ++;
	top.send_queue[top.send_queue.length] = [top.last_send_event,cmd];
	top.load();
}

function send_queue_accept(id){
	while (top.send_queue.length>0 && top.send_queue[0][0]<=id){
		top.send_queue = top.send_queue.slice(1);
	}

	if (top.send_queue.length>0)
	{
		top.load();
	}
}

function chat_send(cmd){
	send_queue_add(cmd);
}

function accept(uid){
	chat_send('/accept '+uid);
}

function cancel(uid){
	chat_send('/cancel '+uid);
}

function email_chat(){
//	top.active_box.add_message(0,0,"If you'd like a transcript of this chat sent to you by email, please [SEND]click here[/SEND]");
}

function send_confirm(n){
	chat_send('/email');
	if (n&&n.parentNode)
	{
		n.parentNode.style.display = 'none';
	}
}

function proc_user(cmd){
	var pos = cmd.indexOf(" ");
	if (pos==-1)return;
	var uid = parseInt(cmd.substr(0,pos));
	if (isNaN(uid))return;
	cmd = cmd.substr(pos+1);
	
	pos = cmd.indexOf(" ");
	if (pos==-1)return;
	var level = parseInt(cmd.substr(0,pos));
	if (isNaN(level) || level<0 || level>1)return;
	cmd = cmd.substr(pos+1);
	
	pos = cmd.indexOf(" ");
	if (pos==-1)return;
	var st = parseInt(cmd.substr(0,pos));
	if (isNaN(st) || st<0 || st>1)return;
	var nm = cmd.substr(pos+1);
	top.process_user(uid,level,st,nm);
	if (top.is_admin)
		top.focus_chat();
}

function proc_request(cmd){
	var pos = cmd.indexOf(" ");
	if (pos==-1)return;
	var uid = parseInt(cmd.substr(0,pos));
	if (isNaN(uid))return;
	cmd = cmd.substr(pos+1);
	
	pos = cmd.indexOf(" ");
	if (pos==-1)return;
	var operator = parseInt(cmd.substr(0,pos));
	if (isNaN(operator))return;
	var msg = cmd.substr(pos+1);
	
	top.set_user_request(uid,operator,msg);
	if (top.is_admin&&!top.multi_window)
		top.focus_chat();
}

function proc_endrequest(cmd){
	var uid = parseInt(cmd);
	if (isNaN(uid))return;
	top.clear_user_request(uid);
}

function proc_session(cmd){
	var pos = cmd.indexOf(" ");
	if (pos==-1)return;
	var sid = parseInt(cmd.substr(0,pos));
	if (isNaN(sid))return;
	cmd = cmd.substr(pos+1);
	
	pos = cmd.indexOf(" ");
	if (pos==-1)return;
	var uid = parseInt(cmd.substr(0,pos));
	if (isNaN(uid))return;
	cmd = cmd.substr(pos+1);
	var st = parseInt(cmd);
	if (isNaN(st))return;
	if (st==0){
		set_session_id(uid,0);
		if (!top.is_admin)
		{
			top.email_chat();
		}
	}
	else {
		set_session_id(uid,sid);
		if (!top.is_admin && top.to_no_operator!=0){
			if (top.active_box.on_operator_connect)
			{
				for (var i=0; i<top.active_box.on_operator_connect.length; i++ )
				{
					top.active_box.on_operator_connect[i].style.display = 'none';
				}
				top.active_box.on_operator_connect = null;
			}
			window.clearTimeout(top.to_no_operator);
		}
		if (top.is_admin)
		{
			select_user(uid);
		}
	}
	if (top.is_admin&&!top.multi_window)
		top.focus_chat();
}

function proc_typing(cmd){
	var pos = cmd.indexOf(" ");
	if (pos==-1)return;
	var sid = parseInt(cmd.substr(0,pos));
	if (isNaN(sid))return;
	cmd = cmd.substr(pos+1);
	var flag = parseInt(cmd);

	if (top.users==null)return;

	if (flag==0)
		flag = false;
	else
		flag = true;
	
	for (var i=0;i<top.users.length;i++){
		if (top.users[i].box && top.users[i].box.sid == sid){
			top.users[i].box.set_typing(flag);
			return;
		}
	}
}

function proc_msg(cmd){
	var pos = cmd.indexOf(" ");
	if (pos==-1)return;
	var sid = parseInt(cmd.substr(0,pos));
	if (isNaN(sid))return;
	cmd = cmd.substr(pos+1);
	
	pos = cmd.indexOf(" ");
	if (pos==-1)return;
	var uid = parseInt(cmd.substr(0,pos));
	if (isNaN(uid))return;
	cmd = cmd.substr(pos+1);
	
	pos = cmd.indexOf(" ");
	if (pos==-1)return;
	var tm = parseInt(cmd.substr(0,pos));
	if (isNaN(tm))return;
	
	var message = cmd.substr(pos+1);
	
	if (!top.is_admin && sid==0)
		top.active_box.add_message(uid,tm,message);
	else
		top.add_message_to_session(sid,uid,tm,message);
	if (top.is_admin&&!top.multi_window)
		top.focus_chat();
}

function proc(id,cmd){
	if (top.last_event&&top.last_event>=id)return;
	top.last_event = id;
	
	if (cmd.substr(0,1)!="/")return;

	var pos = cmd.indexOf(" ");
	var code = "";
	if (pos==-1){
		code = cmd.substr(1);
		cmd = "";
	}	
	else {
		code = cmd.substr(1,pos-1);
		cmd = cmd.substr(pos+1);
	}
	switch (code){
	case "user":
		top.proc_user(cmd);
		break;
	case "request":
		top.proc_request(cmd);
		break;
	case "end_request":
		top.proc_endrequest(cmd);
		break;
	case "session":
		top.proc_session(cmd);
		break;
	case "msg":
		top.proc_msg(cmd);
		break;
	case "typing":
		top.proc_typing(cmd);
		break;
	}
}

function load2(){
	top.sending = false;
	top.load();
}

function stop_refresh(){
	top.disable_refresh = true;
}

function do_close(){
	top.close_window = true;
}

function load(){
	if (top.disable_refresh)return;
	if (top.sending)return;
	if (top.to_load!=0)
	{
		window.clearTimeout(top.to_load);
		top.to_load = 0;
	}
	var xmlchat = initxmlhttp() ;
	var url = 'sync.php?rnd='+top.uniqid();
	if (top.last_event)
		url += "&e="+top.last_event;
	if (top.send_queue.length>0)
	{
		top.sending = true;
		var id = top.send_queue[0][0];
		var cmd = top.send_queue[0][1];
		cmd = cmd.replace(/(\r\n)/gi,"[br]");
		cmd = cmd.replace(/\n/gi,"[br]"); // firefox double check 
		cmd = cmd.replace(/\+/g,'%2B');
		url += "&id="+id+"&cmd="+escape(cmd);
	}
	else
		top.sending = false;
	try
	{
		xmlchat.open( "GET", url, true ) ;
		xmlchat.onreadystatechange=function()
		{
			if (xmlchat.readyState==4)
			{
				if (xmlchat.status==200)
				{
					top.sending = false;
					eval( xmlchat.responseText ) ;
				}
			}
		}
		xmlchat.send(null);
		top.to_load = window.setTimeout("top.load2()",2000);
	}
	catch (e)
	{
		top.to_load = window.setTimeout("top.load2()",100);
	}
}

function init_user(){
	process_user(top.userid,0,1,top.username);
	select_user(top.userid);
	add_message_to_user(top.userid,0,0,'Please wait. Connecting to operator...');
	top.to_no_operator = window.setTimeout("no_operator()",60000);
	top.active_box.on_operator_connect = new Array();
}

function init_admin(){
	process_user(-1,0,0,'');
	var u = find_user(-1);
	var cb = u.get_chat_box();
	cb.is_admin_chat = true;
	cb.add_message(0,0,"This is Admin Chat. Here you can communicate with other operators online.");
}

function update_clock(tm,doc){
	if (!doc)doc = document;
	var timer = id2node("timer",doc);
	if (!timer)return;
	if (typeof tm=="undefined")tm = 0;
	var sec = tm%60;
	var min = (tm-sec)/60;

	if (sec<10)
	{
		sec = '0'+sec;
	}
	if (min<10)
	{
		min = '0'+min;
	}
	timer.firstChild.nodeValue = min+':'+sec;
}

function clock_timer(){

	if (top.close_window)
	{
		window.close();
	}
	setTimeout("top.clock_timer()",1000);
	var curtm = 0;
	if (top.users)
	{
		for (var i = 0; i<top.users.length ; i++ )
		{
			var u = top.users[i];
			if (u.box && u.box.sid!=0)
			{
				u.box.time++;
			}
			if (u.box && top.active_box==u.box)
			{
				curtm = u.box.time;
			}
			if (u.box && top.multi_window){
				try
				{
					top.update_clock(curtm,u.box.doc);
				}
				catch (e)
				{
				}
			}
			if (u.request!=null)
			{
				u.request_time++;
				if (u.request_time==60)
				{
					u.update_status();
				}
			}
		}
	}
	top.update_clock(curtm);
	top.update_typing();
}

function no_operator(){
	add_message_to_user(top.userid,0,0,'Sorry, there are no operators currently available.');
	add_message_to_user(top.userid,0,0,'Please [CLOSE]click here[/CLOSE] to leave a message or wait a bit more. Thank you!');
	top.to_no_operator = window.setTimeout('top.no_operator()',60000);
}

function do_init(){
	top.disable_refresh = false;
	top.sending = false;
	top.last_event = 0;
	top.to_send_value = 3000;
	top.to_load = 0;
	setTimeout("top.clock_timer()",1000);
	top.to_load = window.setTimeout("top.load2()",2000);

	init_send_queue();
	top.active_box = null;
	
	load();
	if (top.is_admin)
		init_admin();
	else
		init_user();
}

function chat_init(){
//	if (navigator.userAgent.indexOf("MSIE")==-1)
//	{
//		top.multi_window = false;
//	};
top.multi_window = false;
	if (top.is_admin){
		if (top.loaded_m && top.loaded_u)
		{
			top.do_init();
			return;
		}
	}
	else { 
		if (top.loaded_m){
			top.do_init();
			return;
		}
	}
	window.setTimeout("top.chat_init()",500);
}

function show_admin_chat(){
	if (!top.is_admin)return;
	var u = find_user(-1);
	var cb = u.get_chat_box();
	cb.show();
}

function keypress(evt,f)
{
	var keyCode = evt.which?evt.which:evt.keyCode;
	if (keyCode == 13)
	{
		f.onsubmit();
		evt.cancelBubble = true;
		return false;
	}
	else
	{
		if (top.active_box)top.active_box.start_typing();
	}
	return true;
}

function update_typing(){
	var vis = false;
	if (top.active_box&&top.active_box.sid!=0&&top.active_box.typing)
	{
		vis = true;
	}

	var n = id2node("typing");
	if (n)
	{
		n.style.display = vis?'':'none';
	}
}

function print_chat(){
	if(!top.active_box)return;
	if(!top.active_box.wnd)return;
	top.active_box.wnd.print();
}
