<repo_name>agilebluefox/chatroom<file_sep>/public/main.js
'use strict';
'use strict()';

$(document).ready(function () {
    // Initialize variables
    var $window = $(window);
    var $usernameInput = $('.usernameInput'); // Input for username
    var $usernames = $('.usernames'); //List of active users
    var $error = $('.error'); // Username error
    var $messages = $('.messages'); // Messages area
    var $inputMessage = $('.inputMessage'); // Input message input box

    var $loginPage = $('.login.page'); // The login page
    var $chatPage = $('.chat.page'); // The chatroom page
    var $currentInput = $usernameInput.focus();

    var username = null;
    var socket = io();

    $window.on('keydown', function (event) {
        if (!(event.ctrlKey || event.metaKey || event.altKey)) {
            $currentInput.focus();
        }

        if (event.which === 13) {
            if (username) {
                sendMessage();
            } else {
                setUsername();
            }
        }
    });

    // Get the username val from the input
    // Check that it's unique
    function setUsername() {
        username = $usernameInput.val().trim();
        socket.emit('add user', username, function (data) {
            if (data.isValid) {
                $loginPage.fadeOut();
                $chatPage.show();
                $loginPage.off('click');
                $currentInput = $inputMessage.focus();
            } else {
                username = null;
                $usernameInput.val('');
                $error.html('Username already taken. Try again.');
                $currentInput = $usernameInput.focus();
            }
            return;
        });
    }

    function logUsers(data) {
        $usernames.empty();
        for (var i = 0; i < data.length; i++) {
            $usernames.append('<li><input type="checkbox" name="user" value="' + data[i] + '" /><label>' + data[i] + '</li>');
        }
    }

    function sendMessage() {
        var message = $inputMessage.val().trim();
        var secretFriend = checkForSelectedUsers();
        if (secretFriend) {
            $messages.append('<li class="secret"> ' + username + ' -> ' + secretFriend + ': ' + message + ' </li>');
            // send a private message
            socket.emit('private', {
                to: secretFriend,
                message: message
            });
        } else {
            $messages.append('<li> ' + username + ': ' + message + ' </li>');
            socket.emit('message', message);
        }
        console.log(message);
        $inputMessage.val('');
    }

    // Handle displaying the logged in users
    // let logUsers = function (loggedInUsers) {
    //     users.empty();
    //     for (let i = 0; i < loggedInUsers.length; i++) {
    //         users.append(`<li><input type="checkbox" name="user" value="${loggedInUsers[i]}" /><label>${loggedInUsers[i]}</label></li>`);
    //         console.log(`The user id is ${loggedInUsers[i]}.`);
    //     }
    //     numUsers.text(loggedInUsers.length);
    // };

    var checkForSelectedUsers = function checkForSelectedUsers() {
        if ($("input[name=user]:checked").length > 0) {
            console.log('something is checked');
            var user = $("input[name=user]:checked").val();
            return user;
        } else {
            return false;
        }
    };

    socket.on('message', function (data) {
        $messages.append('<li> ' + data.username + ': ' + data.message + ' </li>');
    });

    socket.on('private', function (data) {
        $messages.append('<li class="secret"> ' + data.sender + ' -> ' + data.recipient + ': ' + data.message + ' </li>');
    });

    socket.on('new user', function (data) {
        logUsers(data);
    });

    socket.on('remove user', function (data) {
        logUsers(data);
    });
});
<file_sep>/server.js
'use strict';
"use strict()";

// Get the required modules

var socket_io = require('socket.io');
var http = require('http');
var express = require('express');

// Setup an express app
var app = express();
app.use(express.static(__dirname + '/public'));

/**
 * This app needs to support bidirectional communication so a Client
 * can maintain a connection with the server. When new data is 
 * available it will be pushed to the client.
 */
// Wrap the app in an http server
var server = http.Server(app);
// Then wrap the server in socket io
var io = socket_io(server);

// Counter to track client connections
var connections = 0;
var users = {};

// When a connection event occurs...
io.on('connection', function (socket) {
    console.log('Client connected...');

    socket.on('add user', function (username, callback) {
        if (username in users) {
            callback({ isValid: false });
        } else {
            callback({ isValid: true });
            ++connections;
            logNumberClients(connections);
            socket.username = username;
            users[socket.username] = socket;
            console.log(Object.keys(users));
            console.log(username + ' joined the conversation');
            io.emit('new user', Object.keys(users));
        }
    });

    socket.on('message', function (data) {
        socket.broadcast.emit('message', {
            username: socket.username,
            message: data
        });
    });

    socket.on('private', function (data) {
        var sender = socket.username;
        var recipient = data.to;
        var message = data.message;
        users[recipient].emit('private', {
            sender: sender,
            recipient: recipient,
            message: message
        });
    });

    socket.on('disconnect', function () {
        if (!socket.username) return;
        --connections;
        logNumberClients(connections);
        console.log(socket.username + ' has left the room');
        delete users[socket.username];
        io.emit('remove user', Object.keys(users));
    });
});

// Log the number of current users to the console
function logNumberClients(connections) {

    if (connections === 1) {
        console.log('There is ' + connections + ' client connected.');
    } else if (connections > 1) {
        console.log('There are ' + connections + ' clients connected.');
    } else {
        console.log('No users are logged in.');
    }
}

// Start listening on this port
server.listen(8888, function () {
    console.log('The server is running...');
});
