﻿var _mess_id = 1;

function postMsg() {
	$('btnpost').disable();
	new Ajax.Request( 'index.php',	{
		method: 'get',
		parameters: { pstMsg: $('msgpost').value },
		onSuccess: function(transport) {
			$('msgpost').value = '';
			$('btnpost').enable();
			refreshMsg();
		}
	});
	$('msgpost').focus();
}

function cleanMsg() {
	$('btnclean').disable();
	new Ajax.Request( 'index.php',	{
		method: 'get',
		parameters: { dropMsg: 'dropChat' },
		onSuccess: function(transport) {
			$('msgpost').value = '';
			$('btnpost').enable();
			refreshMsg();
		}
	});
	$('msgpost').focus();
}

function refreshMsg() {
	new Ajax.Request( 'index.php',	{
		method: 'get',
		parameters: { refMsg: _mess_id, rnd: Math.floor(Math.random() * 10000) },
		onSuccess: function(transport) {
			var obj = transport.responseText.evalJSON();

			var doc = $( 'frmess' ).contentWindow.document;
			doc.body.innerHTML = obj.msg + doc.body.innerHTML;
			_mess_id = obj.mess_id;
			doc.reply = reply;
		}
	});
}

function chkEnt( event ) {
	if ( event.keyCode == 13 )	{
		postMsg();
		Event.stop(event);
	}
}
function clrPost() {
	$('msgpost').value = '';
	$('msgpost').focus();
}

function reply( nik ){
	$('msgpost').value = nik + ': ' + $('msgpost').value;
	$('msgpost').focus();
	moveCaretToEnd( $('msgpost') );
}

function moveCaretToEnd(inputObject) {
	if (inputObject.createTextRange) {
		var r = inputObject.createTextRange();
		r.collapse(false);
		r.select();
	}
}

document.observe('dom:loaded', function() {
	setInterval( refreshMsg, 10000 );
	refreshMsg();

	Event.observe( $( "smiles" ), 'click', function(event) {
		var element = Event.element(event);
		if ( 'IMG' != element.tagName ) return;
		$('msgpost').value = $('msgpost').value + element.alt + ' ';
		$('msgpost').focus();
	});
});
