// JavaScript Document


var lastMsg = 0;
var mTimer;
var msgSmileys = new Array();
var msgSmiley = new Array();
var chatStart = false;
$(document).ready(function(){
	if(chatStart == true) {
		getChatText();
		document.getElementById("chMsg").focus();
		$("form#chForm").submit(function(){
			   var userName = document.getElementById("chUserName").value;
			   sendMsg(userName);
			   return false;
		});
	}
});
function clearMsg(){
	document.getElementById("chMsg").value = "";
	msgSmileys = new Array();
	msgSmiley = new Array(2);
}
function sendMsg(userName){
	
	$("#actionStatus").ajaxStart(function(){
			$(this).html("<img src=\"http://www.msjb.org/_images/loaders/ajax-loader(4).gif\" >");
	}).ajaxComplete(function(){
			$(this).html("Poruka poslata.").show();
	});
	
	document.getElementById("chMsg").focus();
	var msg = document.getElementById("chMsg").value;
	
	$.post("_server/server.chat.php", {
		action: "send",
		msg: msg,
		user: userName//,
		//smileys: getSmileys()
		}, function(xml){
			if($('error',xml).text() == 0){
				$('#chStatus').text("Poruka poslata.");
				clearInterval(mTimer);
				getChatText();
				document.getElementById("chMsg").value = "";
			} else {
				$('#chStatus').text("Došlo je do greške.");	
			}
			msgSmileys = new Array();
			msgSmiley = new Array();
	});
}

function getChatText(){
	$("#actionStatus").ajaxStart(function(){
			$(this).html("<img src=\"http://www.msjb.org/_images/loaders/ajax-loader(4).gif\" >");
	}).ajaxComplete(function(){
			$(this).html("Poruke dobavljene.").show();
	});
	
	$.post("_server/server.chat.php", {
		action: "getChatText",
		chat: 1,
		last: lastMsg
		}, function(xml){
			if($('error',xml).text() == 0){
				handleChatText(xml);
			}
	});	
}

function handleChatText(xml){
	$("msg", xml).each(function(id){
		var msg = $("msg", xml).get(id);
		var userName = $("userName", msg).text();
		var msgText = $("msgText", msg).text();
		msgText = msgText.replace(/\[/g,"<");
		msgText = msgText.replace(/\]/g,">");
		//alert(msgText);
		var postTime = $("postTime", msg).text();
		var msgId = $("msgId", msg).text();
		lastMsg = msgId;
		$('#chMessages').prepend("<div class=\"chMsg\"><b>"+userName+"</b> ["+postTime+"] : <br/><br/>"+msgText+"</div>");
	});
	mTimer = setTimeout('getChatText();',5000);
}
function addSmiley(smiley){
	
	var pos = document.getElementById("chMsg").value.length;
	document.getElementById("chMsg").value += " ["+smiley+"] ";
	msgSmiley = new Array();
	msgSmiley[0] = pos;
	msgSmiley[1] = smiley;
	msgSmileys[msgSmileys.length] = msgSmiley;
	document.getElementById("chMsg").focus();
}
function getSmileys(){
	var msgSmileysString = "";
	for(var i=0; i<msgSmileys.length; i++){
		msgSmileysString += msgSmileys[i][0] + "-" + msgSmileys[i][1] + "|";	
	}
	return msgSmileysString;
}

