var shoutboxInputEnabled = true;
function shoutSent(id_channel) {
    //zapobiega klikukrotnym dodaniom
    if (!shoutboxInputEnabled || $("#shoutbox_message").attr("disabled")) {
        return;
    }
    id_channel = parseInt(id_channel);
    
    var message = $("#shoutbox_message").val();

    if (message.length > 0 && id_channel > 0) {
        $.post("ajax/request/shoutbox_message.php", {message : message, id_channel : id_channel},
            function (data, status){
                if (status !== "success" || data !== '') {
                    //alert(lang['error_shoutbox_add_message'])
                }
                else {
                    refreshShoutbox(id_channel);
                    $("#shoutbox_message").val('');
                }
                shoutboxInputEnabled = true;
            }
        );
    }
}

var date_of_last_message = null;
var scrollIt = false;

function refreshShoutbox(id_channel) {
    $("#loader").ajaxStart(function() {
        $(this).show();
    });
    $("#loader").ajaxStop(function() {
        $(this).hide();
    });
    
    scrollIt = scrollItDown();

    if (!date_of_last_message) {
        var last_date = document.getElementById("date_of_last_message");
        if (last_date) {
            date_of_last_message = last_date.innerHTML;
            last_date.parentNode.removeChild(last_date);
        }
    }

    $.post("./ajax/request/shoutboxGetMessages.php", {date_of_last_message : date_of_last_message, id_channel : id_channel},
        function(data) {
            $("#shout_body_data").append(data);
            var last_date = document.getElementById("date_of_last_message");

            if (last_date) {
                date_of_last_message = last_date.innerHTML;
                last_date.parentNode.removeChild(last_date);
            }
            if (scrollIt) {
                scrollShoutbox();
            }
            
    }, "html");

}

function scrollItDown() {
    var shoutbox = document.getElementById("shout_body_data");
    var scrollTop = shoutbox.scrollTop;
    var scrollHeight = shoutbox.scrollHeight;
    var offsetHeight = shoutbox.offsetHeight;
    
    return scrollTop + offsetHeight == scrollHeight ? true : false;
}

function scrollShoutbox() {
    var shoutbox = document.getElementById("shout_body_data");
    var scrollTop = shoutbox.scrollTop;
    var scrollHeight = shoutbox.scrollHeight;
    var offsetHeight = shoutbox.offsetHeight;
    
    //alert(scrollTop+" "+offsetHeight+" "+scrollHeight+" "+(scrollTop+offsetHeight))
    
    $("#shout_body_data").attr("scrollTop", scrollHeight - offsetHeight);
}


