var socket = io();

var output = function (message, className) {
    var html = '';

    if (className) {
        html = '<div ' + 'class="' + (className || '') + '">' + message + '</div>'
    } else {
        html = '<div>' + message + '</div>'
    }

    $('#output').append(html);
};

socket.on('broadcast-login', function (data) {
    output(data.message, 'broadcast');
});

socket.on('broadcast-say', function (data) {
    output(data.message, 'broadcast');
});

socket.on(user + '-response', function (data) {
    output(data.message, 'private');
});

socket.on(user + '-error', function (data) {
     output(data.message, 'error');
});

$('#output').on('click', '.clickable', function () {
    $('#command').val($('#command').val() + $(this).text());
});

$('#command').focus();

var KEYS = Object.freeze({
    ENTER: 13,
    UP_ARROW: 38,
    DOWN_ARROW: 40
});

var commandHistory;
var index;
var upOnce = false;
var upCount = 0;

$('#command').keyup(function (e) {
    commandHistory = commandHistory || [];
    index = typeof index === 'undefined' ? commandHistory.length - 1 : index;

    if (e.keyCode === KEYS.ENTER) {
        var command = $('#command').val();

        commandHistory.push(command);

        index = commandHistory.length - 1;

        $('#command').val('');

        $.post('http://localhost:3000/execute', {
            command: command
        }, function (data) {
            $('#output').scrollTop($('#output')[0].scrollHeight);
        });
    } else if (e.keyCode === KEYS.UP_ARROW) {
        $('#command').val(commandHistory[index]);


        if (index > 0) {
            index--;
        } else {
            index = 0;
        }
    } else if (e.keyCode === KEYS.DOWN_ARROW) {
        if (index < commandHistory.length - 1) {
            index++;
            $('#command').val(commandHistory[index]);
        } else if (index == commandHistory.length - 1){
            $('#command').val('');
        }
    }
});

@@ -276,16 +276,75 @@
 d(html);
+%0A%0A    $('#output').scrollTop($('#output')%5B0%5D.scrollHeight);
 %0A%7D;%0A%0Asoc
@@ -1456,73 +1456,8 @@
 ) %7B%0A
-            $('#output').scrollTop($('#output')%5B0%5D.scrollHeight);
 %0A   
@@ -1562,17 +1562,16 @@
 dex%5D);%0A%0A
-%0A
         

Make auto-scrolling work with multiple lines