﻿$(document).ready(function(){
	//global vars
	var inputUser = $("#nick");
	var inputImg = $("#img");
	var inputMessage = $("#message");
	var loading = $("#loading");
	var messageList = $(".content");
	
	//functions
	
	//Update shoutbox
	function updateShoutbox(){
		//just for the fade effect
		messageList.hide();
		loading.fadeIn();
		//send the post to shoutbox.php
		$.ajax({
			type: "POST", url: "shoutbox.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") && inputImg.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");
			var img = inputImg.attr("value");
			//we deactivate submit button while sending
			$("#send").attr({ disabled:true, value:"En cours" });
			$("#send").blur();
			//send the post to shoutbox.php
			$.ajax({
				type: "POST", url: "shoutbox.php", data: "action=insert&nick=" + nick + "&img=" + img + "&message=" + message,
				complete: function(data){
					messageList.html(data.responseText);
					updateShoutbox();
					//reactivate the send button
					$("#send").attr({ disabled:false, value:"Envoi" });
				}
			 });
		}
		else alert("Merci de renseigner tous les champs !");
		//we prevent the refresh of the page after submitting the form
		return false;
	});
	
	//CHECK AUTA UPDATE
	function checkReload(){
		var checkbox_status = $('#autoreload').attr("checked");
		var checkbox_obj = $('#autoreload');
		if (checkbox_status) {
			$('#onoff').stop(true, true).fadeIn(0).text("Autoreload is on").delay(0).fadeOut(0);
			autoupdateShoutbox();
			intervalID = setInterval(autoupdateShoutbox, 5000);
		} else {
			$('#onoff').stop(true, true).fadeIn(0).text("Autoreload is off").delay(0).fadeOut(0);
			clearInterval(intervalID);
			autoupdateShoutbox();
		} }

		$('#autoreload').click(function() {
		checkReload();
	});

	checkReload();
	
	//Auto Update shoutbox
	function autoupdateShoutbox(){
		//send the post to shoutbox.php
		$.ajax({
			type: "POST", url: "shoutbox.php", data: "action=update",
			complete: function(data){
				messageList.html(data.responseText);
			}
			
		});
	}
});


