chat = {
	init: function() {
		window.addEvent('keydown', function(event) {
			if (event.key == "enter") {
				event.stop();
				chat.postChat();
			}
		});
		
		chat.getChats.periodical(3000);
	},
	
	getChats: function() {
		var myReq = new Request({
			url: '/getChats',
			onComplete: function(data) {
				var chats = JSON.decode(data);
				var tmpHTML = "";
				
				for (var x in chats) {
					if (chats[x].userID) {
						tmpHTML += '<div class="chat">';
						tmpHTML += '<span class="chatura">'+chats[x].datumSI+'</span>';
            tmpHTML += '<span class="chatuser">: <a href="/petarde/'+ chats[x].username +'">'+chats[x].username+'</a></span>';
            tmpHTML += '<span class="chattext"> : '+ chats[x].text +'</span>';
            tmpHTML += '</div>';
					}
				}
				$('chats').set('html', tmpHTML);
			}	
		}).send(); 
	},
	
	postChat: function() {
		
		var myReq = new Request({
			url: '/postChat',
			onComplete: function(data) {
				$('chetposlji').value = '';
				chat.getChats();
			}
		}).send($('postChat'));
	}
}

window.addEvent('domready', function() { chat.init(); });