﻿$(document).ready(function(){

setInterval(updateShoutbox, 10000);

//global vars
	var inputUser = $("#userNick");
	var inputMessage = $("#message");
	var loadingIndicator = $("#loadlamangkuk");
	var messageList = $(".content");
	
	//functions
	function updateShoutbox(){
		//just for the fade effect
		//messageList.fadeOut();
		loadingIndicator.fadeIn();
		var channelUpdate = $("#cenel").val();
		//send the post to shoutbox.php
		$.ajax({
			type: "POST", url: "js/shoutbox.php", data: "action=update&c=" + channelUpdate,
			complete: function(data){
				loadingIndicator.fadeOut();
				messageList.html(data.responseText);
				//messageList.fadeIn(2000);
			}
		});
	}
	//check if all fields are filled
	function checkForm(){
		if(inputMessage.attr("value"))
			return true;
		else
			return false;
	}
	
	//Load for the first time the shoutbox data
	updateShoutbox();
	
	//on submit event
	$("#form").submit(function(){
		if(checkForm()){
			var nick = inputUser.attr("value");
			var message = inputMessage.attr("value");
			var channelID = $("#cenel").val();
			//we deactivate submit button while sending
			$("#send").attr({ disabled:true, value:"Proses..." });
			$("#send").blur();
			//send the post to shoutbox.php
			$.ajax({
				type: "POST", url: "js/shoutbox.php", data: "action=insert&n=" + nick + "&m=" + message + "&c=" + channelID,
				complete: function(data){
					messageList.html(data.responseText);
					updateShoutbox();
					//reactivate the send button
					$("#send").attr({ disabled:false, value:"Hantar" });
				}
			 });
		}
		else alert("Please fill all fields!");
		//we prevent the refresh of the page after submitting the form
		return false;
	});
});

	function padamShout(id) {
		//messageList.hide();
		//loadingIndicator.fadeIn();
		var shoutID = id;
		$.ajax({
			type: "POST", url: "js/shoutbox.php", data: "action=padam&idShout=" + shoutID,
			complete: function(data){
            
                $("#jerit" + shoutID).remove();
		}
	});
}