// variables
var socketio = require('socket.io');
var io;
var guestNumber = 1;
var nickNames = {};
var namesUsed = [];
var currentRoom = {};

exports.listen = function (server) {
  io = socketio.listen(server);
  io.set('log level', 1);

  io.sockets.on('connection', function (socket) {
    guestNumber = assignGuestName(socket, guestNumber, nickNames,
      namesUsed);
    joinRoom(socket, 'Lobby');
    handleMessageBroadcasting(socket, nickNames);
    handleNameChangeAttempts(socket, nickNames, namesUsed);
    handleRoomJoining(socket);

    socket.on('rooms', function () {
      socket.emit('rooms', io.sockets.manager.rooms);
    });

    handleClientDisconnection(socket, nickNames, namesUsed);

  });

}

/**
 * Przypisanie nazwy gośca
 * @param  {[type]} socket      [description]
 * @param  {[type]} guestNumber [description]
 * @param  {[type]} nickNames   [description]
 * @param  {[type]} namesUsed   [description]
 * @return {[type]}             [description]
 */
function assignGuestName(socket, guestNumber, nickNames, namesUsed) {
  var name = 'Gość' + guestNumber;
  nickNames[socket.id] = name;
  socket.emit('nameResult', {
    success: true,
    name: name
  })
  namesUsed.push(name);
  return guestNumber + 1;

}

@@ -1229,12 +1229,924 @@
 ber + 1;%0A%0A%7D%0A
+%0A/**%0A * Do%C5%82%C4%85czanie do pokoju%0A * @param  %7B%5Btype%5D%7D socket %5Bdescription%5D%0A * @param  %7B%5Btype%5D%7D room   %5Bdescription%5D%0A * @return %7B%5Btype%5D%7D        %5Bdescription%5D%0A */%0Afunction joinRoom(socket, room) %7B%0A  socket.join(room);%0A  currentRoom%5Bsocket.id%5D = room;%0A  socket.emit('joinResult', %7Broom: room%7D);%0A  socket.broadcast.to(room).emit('message', %7Btext: nickNames%5Bsocket.id%5D + ' do%C5%82%C4%85czy%C5%82 do pokoju ' + room + '.'%7D);%0A  var usersInRoom = io.sockets.clients(room);%0A  if (usersInRoom.length %3E 1) %7B%0A    var usersInRoomSummary = 'Lista u%C5%BCytkownik%C3%B3w w pokoju ' + room + ': ';%0A    for (var index in usersInRoom) %7B%0A      var userSocketId = usersInRoom%5Bindex%5D.id;%0A      if (userSocketId != socket.id) %7B%0A        if (index %3E 0) %7B%0A          usersInRoomSummary += '. ';%0A        %7D%0A        usersInRoomSummary += nickNames%5BuserSocketId%5D;%0A      %7D%0A    %7D%0A    usersInRoomSummary += '.';%0A    socket.emit('message', %7Btext: usersInRoomSummary%7D);%0A  %7D%0A%7D%0A

add joinRoom function