var Trequest = null;
$(document).ready(function() {
    $('#chatDiv').show();
    $('#chatDiv').css("left", $(window).width()/2 - 450);
    $("#showChatLink").click(function(){
        $("#chatContent").show();
        $('#chatDiv').css("left", $(window).width()/2 - 450);
        $('#chatDiv').css("bottom", 0);
        $("#hideChatLink").show();
        $("#showChatLink").hide();
        $("#sendChatField").focus();
        $.ajax({
            url: $("base").attr("href")+'index/chat/texts',
            type: "GET",
            success: function(response) {
                $("#chatTexts").html(response);
                Trequest = null;
            }
        });

        return false;
    });
    
    $("#hideChatLink").click(function(){
        Trequest = null;
        $("#chatContent").hide();
        $("#hideChatLink").hide();
        $("#showChatLink").show();
        return false;
    });

    setInterval(function(){
        $("#personsList:visible ul").load($("base").attr("href")+'index/chat/persons');
    }, 10000);
    
    setInterval(function(){
        if(Trequest == null){
            if($("#chatContent").css('display')=='block'){
                Trequest = 1;
                $.ajax({
                  url: $("base").attr("href")+'index/chat/texts',
                  type: "GET",
                  success: function(response) {
                    $("#chatTexts").html(response);
                    Trequest = null;
                  }
                });
            }
        }
    }, 1500);
    

    $("form#chatForm").submit(function(){
        if($("#sendChatField").val()!=''){
            $("#sendChatField").attr("readonly", true);
            $("#chatForm input[type=submit]").attr("disabled", true);
            $("#chatForm input[type=submit]").val("Wysyłanie ...");
        
            $.ajax({
              url: $(this).attr("action"),
              type: "POST",
              data: $(this).serialize(),
              success: function(response) {
                $("#sendChatField").attr("readonly", false);
                $("#chatForm input[type=submit]").val("Wyślij wiadomość");
                $("#chatForm input[type=submit]").attr("disabled", false);
                $("#sendChatField").val("");
                $("#sendChatField").focus();
                $("#chatTexts").html(response);
              }
            });
        }
        return false;
    });
});
