// User level

var pid = 0;
var online = 0;
var id = 0;

$(document).ready(function(){
	$('body').append('<div id="chatwindow"><div id="chatclosediv"><img style="margin:0 0 5px 0;" src="/chat/img/photo.jpg"><img id="chatclose" src="/chat/img/close.gif" alt="Закрыть окно" style="margin:0px;float:right;"></div><div style="clear:both;"></div><div id="history"></div><center><input type="text" id="send" onkeyup="if (event.keyCode == 13) sendMessage();"><img id="post" src="/chat/img/go.gif" onclick="sendMessage();"></center></div>');
	$('body').append('<div id="chatinform">ONLINE менеджер<br><img id="admin-status" src="/chat/img/off.gif"></div>');

	$("#chatinform").draggable();
	$("#chatwindow").draggable();
	
	$("#chatclose").click(function(){
		document.getElementById("chatwindow").style.display="none";
		document.getElementById("chatinform").style.display="block";
	});
	
	$('#admin-status').click(function(){
		var src = $(this).attr("src");
	  	if (src && src.match('off.gif'))
	  		alert("В данный момент менеджер отсутствует");
	  	else
	  	checkMessage(1);
	});
	
	setInterval('checkMessage(0)',5000);
});



function goToEnd(id)
{
	var o = document.getElementById(id);
	o.scrollTop = o.scrollHeight;
}
// Проверяет со стороны клиента, не пришло ли сообщение от админа и открывает окно с этим сообщением
function checkMessage(geth)
{
	JsHttpRequest.query('/chat/ajax/index.php', // backend
	{
		'title': document.title,
		'url': document.location.href,
		'gethistory': geth,
		'pid': pid
	},
	// Function is called when an answer arrives.
	function(result, errors) {
		// Write the answer.
		if (result["newmes"])
		{
			document.getElementById("chatwindow").style.display = "block";
			document.getElementById("chatinform").style.display = "none";
			document.getElementById("history").innerHTML = result["res"];
			goToEnd('history');
		}
		if (!geth && id % 2 == 1)
		{
			if (result['online'] == 1)
			$('#admin-status').attr({'src':'/chat/img/on.gif'});
			else
			$('#admin-status').attr({'src':'/chat/img/off.gif'});
		}

		pid = result["pid"];
	},
	true  // do not disable caching
	);
	id ++;
};
// Отправляет со стороны клиента сообщение
function sendMessage()
{
	JsHttpRequest.query('/chat/ajax/chat.php', // backend
	{
	'mes': document.getElementById("send").value,
	'pid': pid
	},
	// Function is called when an answer arrives.
	function(result, errors) {
		// Write the answer.
		if (result["res"])
		{
			document.getElementById("history").innerHTML = result["res"];
			goToEnd('history');
		}
	},
	true  // do not disable caching
	);
	document.getElementById("send").value = "";
};


