chatInit = function() {
        chatTimeout = null;


        ifaceMsg = function(i,t,c,a,h)
        {
            smClass = '';
            if (3 == h)
            {
                smClass = ' class="highlightRed"';
            }
            else if (2 == h)
            {
                smClass = ' class="highlightGreen"';
            }

            if (0 == i % 2)
            {
                $('#ChatMainIn').append('<div class="msg even"><small>' + t + ' <span class="separator">/</span><span' + smClass + '> ' + a + '</span></small> ' + c + '</div>');
            }
            else
            {
                $('#ChatMainIn').append('<div class="msg odd"><small>' + t + ' <span class="separator">/</span><span' + smClass + '> ' + a + '</span></small> ' + c + '</div>');
            }
        }

        ifaceError = function(c)
        {
            $('#ChatMainIn').append('<div class="msg error">' + c + '</div>');
        }

        ifaceScroll = function(force)
        {
            mainHeight = $('#ChatMain').height();
            mainScroll = $('#ChatMain').scrollTop();
            inHeight = $('#ChatMainIn').outerHeight();
            if (Math.abs(inHeight - mainHeight - mainScroll) < 100 || true == force)
            {
                $('#ChatMain').scrollTop($('#ChatMain')[0].scrollHeight);
            }
        }

        $('#createRoom').click( function()
        {
            $.ajax({
                url: '/api/chat.php',
                type: 'POST',
                data: {
                    f: 'createRoom'
                },
                dataType: 'html',
                timeout: 40000,
                error: function(data)
                {
                    window.location.reload();
                    return false;
                },
                success: function(data)
                {
                    alert('Chat został utworzony.');
                    window.location.reload();
                    return false;
                }
            });
        });

        $('#createCoalitionRoom').click( function()
        {
            $.ajax({
                url: '/api/chat.php',
                type: 'POST',
                data: {
                    f: 'createRoom',
                    c: 'true'
                },
                dataType: 'json',
                timeout: 40000,
                error: function()
                {
                    window.location.reload();
                    return false;
                },
                success: function(data)
                {
                    alert('Chat został utworzony.');
                    window.location.reload();
                    return false;
                }
            });
        });

        ban = function(characterId, time, author)
        {
            if (confirm('Czy na pewno zbanować: \n' + author + '?'))
            {
                $.ajax({
                    url: '/api/chat.php',
                    type: 'POST',
                    data: {
                        f: 'ban',
                        roomId: chatId,
                        charId: characterId,
                        banTime: time
                    },
                    dataType: 'json',
                    timeout: 40000,
                    error: function()
                    {
                        alert('Wystąpił błąd. Proszę spróbować ponownie.');
                    },
                    success: function(data)
                    {
                        if ('nieadmin' === data)
                        {
                            isAdmin = false;
                        }
                    }
                });
            }
            return false;
        }

        toRefresh = function(chatCounter, chatTimestamp)
        {
           params = '&id=' + chatId;

           if (0 != chatCounter)
           {
               params = params + '&t=' + chatTimestamp;
           }

            $.ajax({
                url: '/api/chat.php?f=readMessages' + params,
                type: 'GET',
                dataType: 'json',
                timeout: 40000,
                error: function()
                {
                    /*
                    clearTimeout(chatTimeout);
                    ifaceError('Połączenie z serwerem zostało zerwane. <a href="#" class="refresh">Ponów próbę</a>.');
                    $('#ChatMain a.refresh').click(
                        function() {
                            window.location.reload();
                            return false;
                        }
                    );
                    ifaceScroll(false);
                    */
                    clearTimeout(chatTimeout);
                    chatTimeout = setTimeout("toRefresh(" + chatCounter + ", " + chatTimestamp + ")", 2000);
                },
                success: function(data)
                {
                    if ('uprawnienia' === data)
                    {
                        $('#ChatMain').html('Nie posiadasz uprawnień do przebywania na tym chacie.');
                        window.location.reload();
                        return false;
                    }
                    mainHeight = $('#ChatMain').height();
                    mainScroll = $('#ChatMain').scrollTop();
                    inHeight = $('#ChatMainIn').outerHeight();

                    scr = (Math.abs(inHeight - mainHeight - mainScroll) < 100) || (chatCounter == 0);

                    if (null == data.characterId)
                    {
                        $('#ChatInput').html('<a href="#">Zaloguj się</a> lub <a href="/rejestracja/">załóż konto</a>, jeśli chcesz wziąć udział w dyskusji.');
                    }
                    else if ($('#ChatInput').html() == '<a href="#">Zaloguj się</a> lub <a href="/rejestracja/">załóż konto</a>, jeśli chcesz wziąć udział w dyskusji.' || $('#ChatInput').html() == '')
                    {
                        $('#ChatInput').html('<form method="post" action="" id="ChatInputForm"><textarea></textarea><input type="submit" value="»" /><div class="clear"></div></form>');
                        $('#ChatInputForm textarea').keypress(function(e)
                        {
                            if (13 == e.keyCode)
                            {
                                $('#ChatInputForm').trigger('submit');
                                return false;
                            }
                        });

                        $('#ChatInputForm').submit(function()
                        {
                            if (true == /^\s*$/.test($('#ChatInputForm textarea').val()))
                            {
                                alert('Proszę wpisać treść wiadomości.');
                                return false;
                            }

                            if ($('#ChatInputForm textarea').val().length > 1024)
                            {
                                alert('Wiadomość nie może być dłuższa niż 1024 znaki');
                                return false;
                            }

                            $.ajax({
                               url: '/api/chat.php',
                               type: 'POST',
                               data: {
                                    f: 'addMessage',
                                    c: $('#ChatInputForm textarea').val(),
                                    id: chatId
                               },
                               dataType: 'json',
                               timeout: 40000,
                               error: function()
                               {
                               },
                               success: function(data)
                               {
                                    if ('login' === data)
                                    {
                                        alert('Zaloguj się lub załóż konto, jeśli chcesz wziąć udział w dyskusji........');
                                        return;
                                    }

                                    if ('length' === data)
                                    {
                                        alert('Wiadomość nie może być dłuższa niż 1024 znaki.');
                                        return;
                                    }

                                    if ('uprawnienia' === data)
                                    {
                                        alert('Nie posiadasz uprawnień do wypowiadania się na tym chacie.');
                                        return;
                                    }

                                    if (true == /^do.*$/.test(data))
                                    {
                                        alert('Niestety z powodu zbanowania nie możesz pisać wiadomości ' + data);
                                        return;
                                    }

                                    $('#ChatInputForm textarea').val('');
                                    ifaceScroll(true);
                               }
                            });
                            return false;
                        });

                    }

                    $.each(data.data, function(i, item)
                    {
                        d = new Date(parseInt(item.created * 1000));

                        if (d.getMinutes() < 10)
                        {
                            minutes = '0' + d.getMinutes();
                        }
                        else
                        {
                            minutes =  d.getMinutes();
                        }
                        ifaceMsg(chatCounter, d.getHours() + ':' + minutes, item.content, item.author, item.highlight);
                        chatTimestamp = item.created;
                        chatCounter++;
                    });

                    if (scr)
                    {
                        ifaceScroll(true);
                    }


                    clearTimeout(chatTimeout);
                    chatTimeout = setTimeout("toRefresh(" + chatCounter + ", " + chatTimestamp + ")", 2000);
                }
            });
        }

        uRefresh = function () {
            params = '&id=' + chatId;
            setTimeout( function () {
                $.ajax({
                    url: '/api/chat.php?f=readUsers' + params,
                    type: 'GET',
                    dataType: 'json',
                    timeout: 40000,
                    error: function()
                    {
                    },
                    success: function(data) {
                        table = $('#ChatUsersIn table');
                        table.empty();
                        $.each(data.data, function(i, item)
                        {
                            if (1 == item.ban)
                            {
                                banPanel = '(zbanowany)';
                            }
                            else if (false == isAdmin)
                            {
                                banPanel = '';
                            }
                            else
                            {
                                banPanel = '<a href="#" class="banLight" id="ban_10_' + item.character_id + '">banuj 10 minut</a><a href="#" class="banMedium" id="ban_60_' + item.character_id + '">banuj 1 godzina</a><a href="#" class="banHeavy" id="ban_1440_' + item.character_id + '">banuj 1 tura</a>';
                            }

                            table.append('<tr><td><a href="/postac/?bohaterId=' + item.character_id + '" target="_blank">' + item.author + '</a></td><td>' + banPanel + '</td></tr>');

                            if (1 != item.ban)
                            {
                                $('#ban_10_' + item.character_id).click(function() { return ban(item.character_id, 10, item.author); });
                                $('#ban_60_' + item.character_id).click(function() { return ban(item.character_id, 60, item.author); });
                                $('#ban_1440_' + item.character_id).click(function() { return ban(item.character_id, 1440, item.author); });
                            }
                        });
                    }
                });
                uRefresh();
            }, 5000 );
        }
}

chatReload = function()
{
    setTimeout( function() {window.location.reload()}, 30000);
}
