﻿$(document).ready(function(){
	//global vars
	var inputMessage = $("#message");
	var loading = $("#loading");
	var messageList = $("#messageList");
	var refreshEvery = 115000; //co ile milisekund shoutbox ma automatycznie pobierać najnowsze wiadomości


	

	//functions
	function updateShoutbox(firstTimeLoad){
	  if(firstTimeLoad == true){
      messageList.hide();
      loading.fadeIn();
		}
		
		$.ajax({
			type: "POST", url: "/extension/ezshoutbox/modules/shoutbox/shoutbox.php", data: "action=update",
			complete: function(data){
        if(firstTimeLoad == true)
          loading.fadeOut();
				messageList.html(data.responseText);
				if(firstTimeLoad == true)
          messageList.fadeIn(2000);
			}
		});
	}
	//check if all fields are filled
	function checkForm(){
		if(inputMessage.attr("value"))
			return true;
		else
			return false;
	}
	updateShoutbox(true);
  $(document).everyTime(refreshEvery, function() {
    updateShoutbox(false);}, 0);
    
	//on submit event
	$("#form").submit(function(){
		if(checkForm()){
			var message = inputMessage.attr("value");
			//Deaktywowanie buttona Wyslij w czasie
			$("#send").attr({ disabled:true, value:"Wysyłanie..." });
			$("#send").blur();
			$.ajax({
				type: "POST", url: "/shoutbox/message/", data: "action=insert&msg=" + message,
				complete: function(data){
          //pobranie najnowszego stanu shoutboxa
					updateShoutbox();
					//czyszczenie pola tekstowego wiadomości.
					inputMessage.attr({ value:"" });
					$("#send").attr({ disabled:false, value:"Wyślij!" });
				}
			 });
		}
		else alert("Proszę wprowadzić wiadomość!");
		//to sprawia, że strona się nie odświerza po submicie.
		return false;
	});
});
