function OnChatLoad()
{
	setInterval(function() {pm_auto_checker.checkPms()}, 10000);

	show_load_title = false;
	default_document_title = "Чат Норрис Citysakh.ru";
	user = {
		login: "",
		status: "online"
	};
	lastpost = 0;
	refresh_indicator_pos = 0;
	send_mod = "";
	chat_focused = true;
	chat_unread_count = {
		all: 0,
		to_user: 0
	};
	lastsuccess = {
		posts: true,
		posts_time: time(),
		users: true,
		newpost: true,
		newpost_time: time()
	};
	posts_options = {
		filters : {
			only_me: false
		},
		colored_text: 0	};
	newpost_after_send = ""; //to_fix???
	
	pm_mode = {
		mode_on: false,
		to_login: ""
	};
	ignore_list = new Array();
	
	exit_run = false;

	posts_req = new XmlHttp();
	posts_req.Init();
	posts_req.url = "/actions/chat_actions.php";
	posts_req.method = "post";
	posts_req.errorCallbackFunc = function() {
		refresh_indicator.style.color = "red";
	};
	
	
	try {
	chat_posts = document.getElementById("chat_posts");
	chat_users = document.getElementById("chat_users");
	refresh_indicator = document.getElementById("refresh_indicator");
	chat_newpost = document.getElementById("chat_newpost");
	
	} catch (e) {
	}
	
	//chat_posts_height = 400;
	chat_posts_height = chat_posts.offsetHeight;
	chat_posts.scrollTop = chat_posts.scrollHeight;
	
	if (IE)
	{
		active_element = document.activeElement;
		document.onfocusout = function () { 
			if (active_element != document.activeElement) 
				active_element = document.activeElement 
			else 
				OnBlur();
		};
		document.onfocusin = OnFocus;
	} else {
		addHandler(document, "blur", OnBlur);
		addHandler(document, "focus", OnFocus);
	}

	RefreshPostsList();
	//RefreshUsersList();
	setInterval(RefreshPostsList, 1500);
	//setInterval(RefreshUsersList, 5000);
	
	LoadBtns();
	
	chat_posts_text_size = 1;
	if (!chat_posts_text_size || chat_posts_text_size <= 0.5 || chat_posts_text_size > 1.9) chat_posts_text_size = 1;
	document.getElementById("chat_posts").style.fontSize = chat_posts_text_size + "em";
}
function LoadBtns()
{
	document.getElementById("btn_posts_color_all").style.fontWeight = 
		(posts_options.colored_text == 1) ? "bold" : "";
}

function SetChatCookie(name, value)
{
	document.cookie = name +"="+ value +"; path=/; expires=Mon, 01-Jan-2010 00:00:00 GMT";
}
function OnBlur()
{
	chat_focused = false;
}
function OnFocus()
{
	chat_focused = true;
	chat_unread_count.all = 0;
	chat_unread_count.to_user = 0;
	ShowUnread();
}
function AppendChat(html)
{
	//alert(chat_posts.scrollTop + 400 + " " + chat_posts.scrollHeight);
	var do_autoscroll = ((chat_posts.scrollTop + chat_posts_height) >= chat_posts.scrollHeight) ? true : false;
	chat_posts.innerHTML += html;
	//alert(chat_posts.scrollTop +  400 + " " + chat_posts.scrollHeight);
	if (do_autoscroll)
		chat_posts.scrollTop = chat_posts.scrollHeight;
}
function FormatMessage(post)
{
	//TODO: rework
	var html = "";
	var msg_class = "";
	switch (post[3])
	{
		case "1":
			html += "<span class=\"sys_msg\">";
			html += "(" + post[0] + ")</span> ";
			html += post[2];
			html += ": <a class=\"chat_nick\" href=\"javascript:///\" onclick=\"PasteNick(this);\">" + post[1] + "</a> ";
			break;
		case "2":
			html += "<span class=\"adm_msg\"> ---> Чат Норрис: ";
			html += post[2] + "</span>";
			break;
		case "3":
			eval(post[2]);
			break;
		default:
			if (post[4] || post[6] != "" || post[1] == user.login) msg_class = " class=\"user_message\"";
			html += "<span";
			html += (post[4] && post[6] == "") ? " class=\"to_user\"" : "";
			html += (post[6] != "") ? " title=\"Сообщение пользователю "+ post[6] +"\" class=\"pm_msg\"" : "";
			html += ">(" + post[0] + ")</span> ";
			//ник
			html += "<a class=\"chat_nick\" style=\"color: #"+ post[5] +";\" href=\"javascript:///\" onclick=\"";
			html += (post[6] != "" && post[6] == user.login) ? "PastePmNick('"+ post[1] +"', '"+ post[5] +"');" : "PasteNick(this);";
			html += "\">" + post[1] + "</a>: ";
			
			html += (post[6] != "") ? post[6] + ", " : "";
			if (posts_options.colored_text)
				html += "<span style=\"color: #"+post[5]+";\">" + post[2] + "</span>";
			else
				html += post[2];
	}
	if (msg_class == "" && posts_options.filters.only_me) msg_class = " class=\"chat_message_invisible\"";
	return (html != "") ? "<div"+ msg_class +">" + html + "</div>" : ""; 
}
function FilterOnlyMe()
{
	var elements = chat_posts.getElementsByTagName("div");
	posts_options.filters.only_me = (posts_options.filters.only_me) ? false : true;
	if (posts_options.filters.only_me) {
		for (var i=0;i<elements.length;i++) {
			if (elements[i].className == "")
				elements[i].className = "chat_message_invisible";
		}
		document.getElementById("btn_posts_filter_me").style.fontWeight = "bold";
	}
	else {
		for (var i=0;i<elements.length;i++) {
			if (elements[i].className == "chat_message_invisible")
				elements[i].className = "";
		}
		chat_posts.scrollTop = chat_posts.scrollHeight;
		document.getElementById("btn_posts_filter_me").style.fontWeight = "";
	}
}
function ChatPostsColored()
{
	posts_options.colored_text = (posts_options.colored_text == 1) ? 0 : 1;
	document.getElementById("btn_posts_color_all").style.fontWeight = 
		(posts_options.colored_text) ? "bold" : "";
	SetChatCookie("chat_posts_colored", posts_options.colored_text);
}

function time()
{
	return new Date().getTime();
}

function RefreshPostsList()
{
	if (time() - lastsuccess.posts_time > 10000) 
	{
		//AppendChat("<div style=\"color: red; font-weight: bold;\">время ожидания истекло (" + (time() - lastsuccess.posts_time)+")</div>");
		posts_req.requestObj.abort();
		lastsuccess.posts = true;
		lastsuccess.posts_time = time();
		refresh_indicator.style.color = "red";
	}
	if (!lastsuccess.posts || !lastsuccess.newpost || exit_run) return false;
	//if (time() - lastsuccess.newpost_time > 300000 && user.status == "online") ChangeStatus("away");
	var vars = {
		action: "getposts",
		lastpost: lastpost
	};	
	lastsuccess.posts = false;
	RefreshIndicator();
	try {
		posts_req.callBackFunc = function(jsHttp) 
		{
			lastsuccess.posts = true;
			lastsuccess.posts_time = time();
			refresh_indicator.style.color = "black";
			
			if (jsHttp.responseText == "") {
				location.replace("/chat/info?type=timeout2");
			}
			if (jsHttp.responseText == ".") return;
			eval("var json = " + jsHttp.responseText);
			
			if (json.usernotfound && json.usernotfound == true) location.replace("/chat/info?type=timeout");
			if (json.usernotfound2 && json.usernotfound2 == true) location.replace("/chat/info?type=notlogin");
			if (json.hash_error && json.hash_error == true) location.replace("/chat/info?type=hash_error");
			
			if (json.Message.Type == "info") 
			{
				for (var i=0;i<json.Posts.length;i++)
					AppendChat(FormatMessage(json.Posts[i]));
					
				if (lastpost == 0) chat_posts.scrollTop = chat_posts.scrollHeight;
				if (lastpost != 0 && !chat_focused) 
				{
					chat_unread_count.all += parseInt(json.pc);
					chat_unread_count.to_user += parseInt(json.tuc);
				}
				ShowUnread();
				lastpost = json.lp;
				if (json.Users) UpdateUsersList(json.Users);
			} else {
				alert(json.Message.Type + ":\n" + json.Message.Text);
			}
		};
		posts_req.SendRequest(vars);
	} catch (e) {
		
	}
}
function SendPostByEnter(e)
{
	//var key = (e.keyCode == 0) ? e.which : e.keyCode;
	CheckNewPostLimit();
	if (e.keyCode == 13) {
		SendPost();
		return false;
	}
	return true;
}
function CheckNewPostLimit()
{
	var text = chat_newpost.value;
	var prev_count = chat_newpost.rows;
	var rows_count = Math.ceil(text.length / 100);
	rows_count = (rows_count <= 0) ? 2 : rows_count + 1;
	if (prev_count != rows_count) chat_newpost.rows = rows_count;
	if (text.length >= 255)
	{
		text = text.substr(0, 255);
		chat_newpost.value = text;
	}
}
function SendPost()
{
	if (!lastsuccess.newpost) return false;
	var text = document.getElementById("chat_newpost").value;
	var vars = "action=sendpost&text=" + xh_prepare_str(text) + "&mod=" + send_mod + "&tologin=" + pm_mode.to_login;
	try {
		lastsuccess.newpost = false;
		SwitchSendInfo();
		sendXmlHttpRequest("post", "/actions/chat_actions.php?sendpost", vars, function(jsHttp) 
		{
			lastsuccess.newpost = true;
			lastsuccess.newpost_time = time();
			SwitchSendInfo();
			eval("var json = " + jsHttp.responseText);
			if (json.Message.Type == "info") 
			{
				if (json.Result == true)
				{
					//document.getElementById("chat_newpost").value = "";
					deleteTextButNicks();
					document.getElementById("chat_newpost").rows = 2;
					document.getElementById("chat_newpost").focus();
					newpost_after_send = document.getElementById("chat_newpost").value;
					//if (user.status == "away") ChangeStatus("online");
				}	
			} else {
				if (json.Message.Text != "")
					AppendChat("<div style=\"color: red; font-weight: bold;\">"+ json.Message.Type + ": " + json.Message.Text +"</div>");
				//alert(json.Message.Type + ":\n" + json.Message.Text);
			}
		});
	} catch (e) {
		alert(e);
	}
}
function UpdateUsersList(users)
{
	var html = "";
	ignore_list = new Array();
	for (var i=0;i<users.length;i++)
	{
		html += "<div>";
		if (user.login != users[i].Login)
		{
			html += "<a id=\"chat_usermenu_"+ i +"\" href=\"/Profile?user="+ users[i].Login +"\" onclick=\"ShowNickMenu(this, event, '"+ users[i].Login +"', '"+ users[i].Color +"'); return false;\" title=\"Открыть меню пользователя\">";
			//html += "<a href=\"/Profile?user="+ users[i].Login +"\" target=\"_blank\" title=\"Просмотреть Профиль\">";
				html += "<img alt=\"*\"class=\"chat_user_img\" src=\"/img/chat/"+ users[i].UserSex +"2_1.png\"></a> ";
			if (users[i].IgnoreOn)
				html += "<span class=\"chat_user_ignored\" title=\"Пользователь в списке игорируемых\">"+ users[i].Login +"</span>";
			else
				html += "<a class=\"chat_nick\" style=\"color: #"+ users[i].Color +";\" href=\"javascript:///\" onclick=\"PasteNick(this);\">" + users[i].Login + "</a>";
			if (users[i].IgnoreOn)
			{
				//html += " (ignore on)";
				ignore_list[users[i].Login] = "on";
			}
		} else {
			html += "<img class=\"chat_user_img\" src=\"/img/chat/"+ users[i].UserSex +"2_1.png\"> ";
			html += "<span class=\"chat_nick\" style=\"color: #"+ users[i].Color +";\">"+ users[i].Login +"</span>";
		}
		html += "</div>";
	}
	document.getElementById("chat_users_count").innerHTML = users.length;
	chat_users.innerHTML = html;
}

//nick functions
function isNickInField(login)
{
	var chat_newpost = document.getElementById("chat_newpost");
	var reg = new RegExp("\\["+login+"\\]", "i");
	return reg.test(chat_newpost.value);
}
function deleteTextButNicks()
{
	var chat_newpost = document.getElementById("chat_newpost");
	var arr = chat_newpost.value.match(/(\[[a-zа-яА-Яё0-9\-\_]{3,20}\])/ig);
	chat_newpost.value = ""; 
	var text = "";
	if (arr.length > 0) {
		for (var i=0;i<arr.length;i++) {
			text += arr[i] + " ";
		}
	}
	chat_newpost.value = text;
	//chat_newpost.value = chat_newpost.value.replace(/(\[[a-zа-яё0-9\-\_]{3,20}\])*(.)/gi, "$1");
}
function ClearNewpostField()
{
	document.getElementById("chat_newpost").value = "";
	document.getElementById("chat_newpost").focus();
	
}
function PasteNick(sender)
{
	var chat_newpost = document.getElementById("chat_newpost");	
	if (newpost_after_send != "" && newpost_after_send == chat_newpost.value) {
		newpost_after_send = "";
		chat_newpost.value = "";
	}
	if (sender.innerHTML == user.login || isNickInField(sender.innerHTML)) {
		chat_newpost.focus();
		return false;
	}
	chat_newpost.value = "[" + sender.innerHTML + "] " + document.getElementById("chat_newpost").value;
	chat_newpost.focus();
	if (IE && chat_newpost.createTextRange)
	{
		var range = chat_newpost.createTextRange();
		range.collapse(false);
		range.select();
	}
	CheckNewPostLimit();
	CancelPmMode();
}
function deleteNlicksButText()
{
	var text = document.getElementById("chat_newpost").value;
	text = text.replace(/(\[[a-zа-яА-Яё0-9\-\_]{3,20}\])/ig, "").replace(/^\s+/, "");
	document.getElementById("chat_newpost").value = text;
}
function PastePmNick(login, color)
{
	if (ignore_list[login]) return false;
	deleteNlicksButText();
	var html = "Приватное сообщение пользователю: <span style=\"color: #"+ color +";\">" + login + "</span>";
	html += " | <a class=\"small_link\" href=\"javascript:///\" onclick=\"CancelPmMode();\">писать всем</a>";
	document.getElementById("chat_pm_nick").innerHTML = html;
	pm_mode.mode_on = true;
	pm_mode.to_login = login;
	document.getElementById("chat_newpost").focus();
}
function CancelPmMode()
{
	document.getElementById("chat_pm_nick").innerHTML = "";
	pm_mode.mode_on = false;
	pm_mode.to_login = "";
}
function ShowNickMenu(sender, event, login, color)
{
	//var login = sender.innerHTML;
	//document.getElementById("chat_usermenu_pastenick").onclick = function() {PasteNick(sender); DropMenu.HideMenu();};
	document.getElementById("chat_usermenu_startpm").onclick = function() {PastePmNick(login, color); DropMenu.HideMenu();};
	document.getElementById("chat_usermenu_profile").href = "/Profile?user=" + login;
	document.getElementById("chat_usermenu_pm").href = "/PM?to="+ login +"#new";
	if (ignore_list[login]) {
		document.getElementById("chat_usermenu_ignore").onclick = function() {Ignore(login, ""); DropMenu.HideMenu();};
		document.getElementById("chat_ignore_checked").style.display = "inline"; 
	} else {
		document.getElementById("chat_usermenu_ignore").onclick = function() {Ignore(login, "on"); DropMenu.HideMenu();};
		document.getElementById("chat_ignore_checked").style.display = "none";
	}
	
	DropMenu.SwitchDisplay("chat_usermenu", event, sender, 10, -8);
}
//

function SwitchSendInfo()
{
	document.getElementById("ajax_send_info_img").style.display = (document.getElementById("ajax_send_info_img").style.display == "none") ? "inline" : "none";
}
function RefreshIndicator()
{
	var s = new Array("|", "/", "--", "\\", "|", "/", "--", "\\");
	if (refresh_indicator_pos >= 0) refresh_indicator_pos++;
	if (refresh_indicator_pos > 7) refresh_indicator_pos = 0;
	refresh_indicator.innerHTML = s[refresh_indicator_pos];
}
function ShowUnread()
{
	var unreads = "";
	unreads += (chat_unread_count.all != 0) ? chat_unread_count.all : "";
	unreads += (chat_unread_count.to_user != 0) ? ":" + chat_unread_count.to_user : "";
	if (unreads != "") unreads = "["+ unreads +"] ";
	document.title = unreads + default_document_title;
}
function InsertText(open, close)
{
	var msgfield = document.getElementById("chat_newpost");
	msgfield.focus();
	var ss = msgfield.selectionStart, st = msgfield.scrollTop, sh = msgfield.scrollHeight;
	if (!ss && document.selection) 
	{
		msgfield.caretPos = document.selection.createRange().duplicate();		
		var text = open;
		if (close != "")
			text += document.selection.createRange().text;
		text += close;
		msgfield.caretPos.text = text;
	}
	else if (ss || ss == '0') {
		var se = msgfield.selectionEnd;
		var text = msgfield.value.substring(0, ss) + open;
		if (close != '')
			text += msgfield.value.substring(ss, se);
		text += close + msgfield.value.substring(se, msgfield.value.length);
		msgfield.value = text;
		se = close.length ? se : ss;
		msgfield.selectionStart = se + open.length + close.length;
		msgfield.selectionEnd = se + open.length + close.length;
	}
	else
		msgfield.value += open + close;
	msgfield.scrollTop = st + msgfield.scrollHeight - sh;
	msgfield.focus();
}

function Ignore(login, ignore)
{
	var vars = "action=ignore&login="+ login +"&ignore=" + ignore;
	try {
		sendXmlHttpRequest("post", "/actions/chat_actions.php", vars, function(jsHttp) 
		{
			eval("var json = " + jsHttp.responseText);
			if (json.Message.Type == "info") 
			{
				if (json.Result == true)
				{
					AppendChat("<div style=\"font-weight: bold;\">"+ json.IgnoreStatus +"</div>");
					if (json.Users) UpdateUsersList(json.Users);
				}	
			} else {
				AppendChat("<div style=\"color: red; font-weight: bold;\">"+ json.Message.Type + ": " + json.Message.Text +"</div>");
			}
		});
	} catch (e) {
		alert(e);
	}
}

function ChangePostsTextSize(direction)
{
	var font_size = parseFloat(document.getElementById("chat_posts").style.fontSize);
	if (!font_size || font_size == 0.5 || font_size > 1.9) font_size = 1;
	font_size = font_size + (direction*0.1);
	document.getElementById("chat_posts").style.fontSize = font_size + "em";
	SetChatCookie("chat_posts_font", font_size);
	chat_posts.scrollTop = chat_posts.scrollHeight;
}

function ChangeStatus(status)
{
	var vars = "action=changestatus&status="+status;
	exit_run = true;
	try {
		sendXmlHttpRequest("post", "/actions/chat_actions.php?changestatus", vars, function(jsHttp) 
		{
			eval("var json = " + jsHttp.responseText);
			if (json.Message.Type == "info") 
			{
				if (json.Result == true)
				{
					//
				}	
			} else {
				//AppendChat("<div style=\"color: red; font-weight: bold;\">"+ json.Message.Type + ": " + json.Message.Text +"</div>");
			}
		});
	} catch (e) {
		alert(e);
	}
}

function ChatExit()
{
	var vars = "action=exit";
	exit_run = true;
	try {
		sendXmlHttpRequest("post", "/actions/chat_actions.php?exit", vars, function(jsHttp) 
		{
			eval("var json = " + jsHttp.responseText);
			if (json.Message.Type == "info") 
			{
				if (json.Result == true)
				{
					location.replace("/chat/info?type=exit")
				}	
			} else {
				AppendChat("<div style=\"color: red; font-weight: bold;\">"+ json.Message.Type + ": " + json.Message.Text +"</div>");
			}
		});
	} catch (e) {
		alert(e);
	}
}	
