var last_message = 0;
var mTimer;

function shoutbox_init() {
	$("form#shoutbox_send").submit(function() {
		sendChatText();
		return false;
	});
	
	$('#sb_poruka').keypress(function(e){
		if (e.which == 13) {
			sendChatText();
			return false; 
		}
	});
	
	getChatText();
}

//Gets the current messages from the server
function getChatText() {
	var timestamp = new Date().getTime();
	
	$.getJSON(
		sajt_url + "/ajax/shoutbox.php?p=" + last_message + "&t=" + timestamp,
		function(result) {
			handleReceiveChat(result)
		});
}

//Add a message to the chat server.
function sendChatText() {
	var trim_msg = $.trim($('#sb_poruka').val());
	
	if (trim_msg == '') {
		alert("Нисте унели поруку!");
		return;
	}
	
	if ($('#sb_dozvola').val() !== '1') {
		$('#div_chat').append('<div style="margin: 4px;">' +
				'<div style="border: dotted 1px; padding: 2px 4px 2px 4px;" class="windowbg2">' +
				'<b>Грешка</b>' + 
				'</div>' + 
				'<div style="padding: 4px;">Немате дозволу да шаљете поруке!</div>' +
				'</div>');
		$('#div_chat').scrollTop($('#div_chat')[0].scrollHeight);
		$('#sb_poruka').val('');
		return;
	}
	
	clearInterval(mTimer);
	
	$.post(
		sajt_url + "/ajax/shoutbox.php?p=" + last_message, 
		{
			message: $('#sb_poruka').val()
		},
		function(result) {	
			handleReceiveChat(eval('(' + result + ')'));
		});
	$('#sb_poruka').val('');
}

//Function for handling the return of chat text
function handleReceiveChat(data) {
	var loop = true;
	
	if (data.msgs === undefined)
		loop = false;
	
	if (loop == true) {
		$.each(data.msgs, function(i, msg){
			if (msg.secret == 1) {
				alert(msg.text);
			} else {
				$('#div_chat').append(
					'<div style="margin: 4px;">' +
					'<div style="border: dotted 1px; padding: 2px 4px 2px 4px;" class="windowbg2">' +
					'<b>' + msg.user + '</b>' + 
					'</div>' + 
					'<div style="padding: 2px;">' + msg.time + '</div>' +
					'<div style="padding: 4px;">' + msg.text + '</div>' +
					'</div>'
				);
			}
			
			last_message = msg.id;
			$('#div_chat').scrollTop($('#div_chat')[0].scrollHeight);
		});
	}
	
	if (data.pms > 0) {
		$('#pp_status').html('<div style="border: solid 2px #899BB7; font-weight: bold; color: green; width: 80%; text-align: center;">' +
			'Имате непрочитане <a href="'+smf_scripturl+'?action=pm">приватне поруке</a>.' + 
			'</div>');
		$('#pp_status').show('normal');
	} else {
		$('#pp_status').hide();
	}

	mTimer = setTimeout('getChatText();',5000);
}