﻿$(document).ready(function(){
	//global vars
	var inputUser = $("#nimimerkki");
	var inputMessage = $("#huuto");
	var inputAdmin = $("#admin");
	var loading = $("#loading");
	var messageList = $(".huudot > ul");
	
	//functions
	function updateShoutbox(){
		//just for the fade effect
		messageList.hide();
		loading.fadeIn();
		//send the post to shoutbox.php
		$.ajax({
			type: "POST", url: "huuto.php", data: "action=update",
			complete: function(data){
				loading.fadeOut();
				messageList.html(data.responseText);
				messageList.fadeIn(2000);
			}
		});
	}
	//check if all fields are filled
	function checkForm(){
		if(inputUser.attr("value") && 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");
			if(inputAdmin.attr("value"))
				var admin = inputAdmin.attr("value");
			else
				var admin = 0;
			//we deactivate submit button while sending
			$("#send").attr({ disabled:true, value:"Päivitetään..." });
			$("#send").blur();
			//send the post to shoutbox.php
			$.ajax({

				type: "POST", url: "huuto.php", data: "action=insert&nimimerkki=" + nick + "&huuto=" + message + "&admin=" + admin,

				complete: function(data){
					messageList.html(data.responseText);
					updateShoutbox();
					//reactivate the send button
					$("#send").attr({ disabled:false, value:"Huutele!" });
				}
			 });
		}
		else alert("Täytä kaikki kentät!");
		//we prevent the refresh of the page after submitting the form
		return false;
	});
});
