var idlist=[];
var count_lastid = 10;
function addidlist(id)
{
	idlist.push(id);
	if(idlist.length > count_lastid)idlist.shift();
}

function isidlist(id)
{
	var ch = false;
	for(var i in idlist)
	if(idlist[i] == id)
	ch=true;
	return ch;
}

var canLoad = true;
var unlockLoad = null;
function Loading() {
	if(canLoad)
	{
		clearTimeout(unlockLoad);
		unlockLoad = setTimeout('canLoad=true;',5000);
		canLoad = false;

		JsHttpRequest.query(
		(chattype == 'public') ? 'chat.php?type=load' : 'privat.php?type=load' ,
		{
		'lid': lid,
		'det': det
		},
		function(result, errors) {
			canLoad = true;
			if (result) {
				if(result['out']) {
					window.location.href = result['out'];
				} else {
					var isnew = false;
					for(var i in result['msgs']) if(!isidlist(result['msgs'][i]['id']))
					{
						msg = result['msgs'][i]['m'];
						color = (/^#[0-9a-f]{6}/i).exec(msg);
						msg = (color == null) ? msg : '<font color="'+color+'">' + msg.substring(7) + '</font>';

						html = htmlmsg(
						result['msgs'][i]['ty'],
						result['msgs'][i]['ti'],
						result['msgs'][i]['n'],
						(result['msgs'][i]['hn'] == '' ? result['msgs'][i]['n'] : result['msgs'][i]['hn']),
						msg );

						if(html !== false)
						{
							if(backSlide)
							{
								$("#chat").append("<div>" + html + "</div>");
								ScrollChat();
							}
							else
							{
								$("#chat").prepend("<div>" + html + "</div>");
							}
							isnew = true;
						}

						addidlist(result['msgs'][i]['id']);
						lid = result['msgs'][i]['id'];

					}

					if(isnew)
					{
						if(result['uol'])
						{
							UpdateOnlineList();
							Sound('online');
						}
						else
						{
							Sound('msg');
						}
					}
				}
			}
		},
		true
		);
	}
}

function ScrollChat() {
	$("#chat").scrollTop($("#chat").get(0).scrollHeight);
}


var canUpdateOnline = (chattype == 'public') ? true : false;
var unlockUpdateOnline = null;
function UpdateOnlineList() {
	if(canUpdateOnline)
	{
		clearTimeout(unlockUpdateOnline);
		unlockUpdateOnline = setTimeout('canUpdateOnline=true;',5000);
		canUpdateOnline = false;

		Status(st_onlining);
		JsHttpRequest.query(
		'chat.php?type=online',
		{
		},
		function(result, errors) {
			if (result)
			{
				canUpdateOnline = true;
				Status(st_onlined);

				var html = "";
				for(var i in result['ols'])
				{
					html += htmlonline(i,
					result['ols'][i]['d'],
					result['ols'][i]['n'],
					(result['ols'][i]['hn'] == '' ? result['ols'][i]['n'] : result['ols'][i]['hn']),
					result['ols'][i]['st'] );
				}

				$('#online').html(html);

				html = '';
				for(var j in result['ar'])
				{
					html += htmlroom(j,
					result['ar'][j]['id'],
					result['ar'][j]['n'],
					result['ar'][j]['c'],
					result['ar'][j]['p'] );
				}

				$('#rooms').html(html);

				Resize();
			}
		},
		true
		);
	}
}

var usercolor = '';
var canSend = true;
var unlockSend = null;
function Send(msg) {
	if(canSend && msg.length > 0)
	{
		if(msg.charAt(0) == '@') {
			if(msg.substring(1) == 'me') {
				SetModerator();
				document.getElementById('text').value = '';
			}
		}
		else if(msg.charAt(0) == '%') {
			SetStatus(msg.substring(1));
		}
		else
		{
			clearTimeout(unlockSend);
			unlockSend = setTimeout('canSend=true',5000);
			canSend = false;

			Status(st_sending);
			JsHttpRequest.query(
			(chattype == 'public') ? 'chat.php?type=send' : 'privat.php?type=send' ,
			{
			'msg': usercolor+msg,
			'det': det
			},
			function(result, errors) {
				if (result) {
					canSend = true;
					Status(st_sended);
					document.getElementById('text').value = '';
					Loading();
				} else {alert(errors);}
			},
			true
			);
		}
	}
}

function SetColor(from) {
	if(from != null) {
		usercolor = from + ' ';
		document.getElementById('text').style.color = from;
	} else {
		usercolor = '';
		document.getElementById('text').style.color = '';
	}
	$('#colorbox').hide();
	$('#text').focus();
}

function ClickOk() {
	var text = document.getElementById('text');
	Send(text.value);
	document.getElementById('text').focus();
}


$.fn.insertAtCaret = function (myValue) {
	return this.each(function(){
		//IE support
		if (document.selection) {
			this.focus();
			sel = document.selection.createRange();
			sel.text = myValue;
			this.focus();
		}
		//MOZILLA/NETSCAPE support
		else if (this.selectionStart || this.selectionStart == '0') {
			var startPos = this.selectionStart;
			var endPos = this.selectionEnd;
			var scrollTop = this.scrollTop;
			this.value = this.value.substring(0, startPos)
			+ myValue
			+ this.value.substring(endPos,
			this.value.length);
			this.focus();
			this.selectionStart = startPos + myValue.length;
			this.selectionEnd = startPos + myValue.length;
			this.scrollTop = scrollTop;
		} else {
			this.value += myValue;
			this.focus();
		}
	});

};


function Insert(the) {
	$('#text').insertAtCaret(' ' + the + ' ');
	MenusHide();
}

function absPosition(obj) {
	var x = y = 0;
	while(obj) {
		x += obj.offsetLeft;
		y += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return {x:x, y:y};
}

var currentmenu = null;
function Menu(menu,link) {
	if(currentmenu != null && currentmenu != menu)
	{
		$(currentmenu).hide();
	}
	if($(menu).is(':hidden'))
	{
		pos = absPosition($(link).get(0));
		$(menu).show();
		$(menu).css({
			top: (pos.y - $(menu).height()),
			left: pos.x
		});
		currentmenu = menu;
	}
	else
	{
		$(menu).hide();
	}
}

function MenusHide() {
	if(currentmenu != null)	$(currentmenu).hide();
}


var canSound = true;
function Sound(type) {
	if(canSound && soundManager.play) {
		soundManager.play(type);
	}
}
function OnOffSound() {
	if(canSound){
		canSound = false;
	}else{
		canSound = true;
	}
}


var sleepMode = false;
function OnOffSleepMode() {
	if(sleepMode){
		sleepMode = false;
		SetStatus('');
		SetNewLoadingIntval( loadtime );
	}else{
		sleepMode = true;
		SetStatus(st_sleep);
		SetNewLoadingIntval( sleeptime );
		Loading();
	}
}


function Status(txt) {
	$('#status').html(txt);
}


var openedwindows = {};
function OpenPrivatChat(ID,name) {
	openedwindows["privat"+ID] = window.open("privat.php?ID="+ID+"&name="+encodeURIComponent(name), "privat"+ID, "width=600,height=400,toolbar=no,status=no,scrollbars=no,menubar=no,resizable=yes");
}
function IsWindowOpen(ID) {
	if(openedwindows["privat"+ID])	{
		return !openedwindows["privat"+ID].closed;
	} else {
		return false;
	}
}


function SetRoom(room, passworded) {
	var password = '';
	if(passworded)
	{
		password = window.prompt("Для входа в эту комнату нужно ввести пароль.", "")
	}
	JsHttpRequest.query(
	'change.php',
	{
	'setroom': room,
	'password': password
	},
	function(result, errors) {
		if (result) {
			if(result['success'])
			{
				ClearChat();
				lid = 0;
				$('#roomtitle').text(result['name']);
			}
			else
			{
				window.alert(result['msg']);
			}
		}
	},
	true
	);
}

function SetStatus(status) {
	JsHttpRequest.query(
	'change.php',
	{
	'setstatus': status
	},
	function(result, errors) {
		document.getElementById('text').value = '';
	},
	true
	);
}

function ClearChat() {
	$("#chat").html("&nbsp;");
}

function SetNewLoadingIntval(intval) {
	if(loader) {
		clearInterval(loader);
		loader = setInterval('Loading();', intval);
	}
}

//-----------------
// READY          -
//-----------------
var loader = null;
$(document).ready(function(){

	Resize();
	soundManagerInit();

	$('#colorbutton').click(function (){
		Menu('#colorbox', '#colorbutton');
	});

	$('#smilebutton').click(function (){
		Menu('#smilebox', '#smilebutton');
	});

	$('#text').focus(function () {
		MenusHide();
	});

	$('#text').keydown(function(evt){
		var text = document.getElementById('text');
		evt = (evt) ? evt : ((window.event) ? event : null )
		if(evt) {

			if(evt.keyCode == 13 && canSend && !evt.shiftKey) {
				Send(text.value);
				return clearEv(evt);
			}

		}
	});

	Loading();
	UpdateOnlineList();
	loader = setInterval('Loading();', loadtime);
});
function clearEv(e){
	if (e.preventDefault) e.preventDefault()
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
	return (e.returnValue = false);
}

function Resize()
{
	docHeight = window.innerHeight;
	if(!docHeight){
		docHeight = $(document).height();
	}
	docHeight = parseInt(docHeight);

	calculatedHeight = docHeight - chatSafeSize;
	$('#chat').height(calculatedHeight);

	if(chattype == "public")
	{
		calculatedHeight = $("#online").height() + $("#rooms").height() + onlineSafeSize;		if(calculatedHeight >= docHeight)
		{			$("#onlinescroll").css("overflow", "auto");
			$("#onlinescroll").height(docHeight - $("#rooms").height() - onlineSafeSize);
		}
		else
		{			$("#onlinescroll").css("overflow", "visible");
			$("#onlinescroll").height("auto");		}	}
}

$(window).resize(Resize);

/* Moderators Functions */

function KeepModerator() {
	$(".mod").removeClass("mod");
}

function SetModerator() {
	var password = "";
	password = window.prompt("Введите ваш пароль.", "")
	if(password != "")
	{
		JsHttpRequest.query(
		'change.php',
		{
		'setmoderator': true,
		'password': password
		},
		function(result, errors) {
			if (result) {
				if(result['success'])
				{
					$(".mod").removeClass("mod");
					setInterval('KeepModerator()',800);
					window.alert(result['msg']);
				}
				else
				{
					window.alert(result['msg']);
				}
			}
		},
		true
		);
	}
}


function ModBox(url) {
	$('#modbox').show();
	$('#modbody').load(url);
}

function ModMsg(message) {
	$.post('moderator.php', {tab: 'msg', msg: message});
	$('#msg').val('');
}

function ModBan(det) {
	$('#modbox').show();
	$('#modbody').load("moderator.php?tab=ban&det="+det);
}

function ModSendBan() {
	$.post('moderator.php', {
		tab: 'ban',
		banName: $('#banName').val(),
		checkDet: $('#checkDet').is(':checked'),
		checkIP: $('#checkIP').is(':checked'),
		banDet: $('#banDet').val(),
		banIP: $('#banIP').val(),
		fortime: $('#fortime').val(),
		why: $('#why').val()
	}, function (html) {
		$('#modbody').html(html);
	});
}

function ModDetBan(id) {
	$('#modbody').load("moderator.php?tab=ban&deleteBan="+id);
}

function ModDel(userdet, name) {
	if(window.confirm("Удалить из чата " + name + "?"))	{
		$.post('moderator.php', {tab: 'del', det: userdet});
	}
}


