$(document).ready(function() 
{
	show_mess();
	var otv = 0;

	/* ADD MESSAGE */
	function add_mess(){	
		var mess = $('.text').val();
		$.ajax({
			type: "POST",
			url: "addMessage.php",
			dataType: "html",
			data: {user: $('.userId').text(),ans: otv,text: mess},
			success: function(data) {
				$('.text').val('');
				show_mess();
				$('.text').blur();	
				}
		
		});
	}

	/* SHOW MESSAGES */
	function show_mess(){
		$.ajax({
			type: 'POST',
			url: "message.php",
			cache: false,  
			success: function(data){  
				$(".userMessage").html(data);

				$('.answer').on('click',function(){
	           		otv = $(this).children('span').text();
	            	var name = $(this).children('small').text() + ', ';
	            	$('.text').val(name);
	            	$('.text').focus();
    			});
    			$('.deletePost1').on('click',function(){
    				$.post('delMessage.php',{ del:$(this).children('span').text() },function(answer){
    					show_mess();
    				});
    			});

			}  
		});
	}

	/* OTHER FUNCTIONS */
	$('.submit').click(function(){
			add_mess();
	}); 
	$('.submit').keyup(function(event){
			if (event.ctrlKey && event.which == 13){
				add_mess();
			}
	});

	/* SHOW MESSAGE EVER 3s */
	setInterval(show_mess, 3000);
	
});
	