function Room(domElem, lib) { var players = {}; var keysByName = {}; var logins = []; var session = { key: null, loggedIn: false, selected: null }; var playersList = domElem.getElementsByClassName('players')[0]; domElem.addEventListener('submit', function(e) { e.preventDefault(); lib.send({tag: "Invitation", to: session.selected}) }); return { populate: populate, enter: enter, leave: leave, name: name }; function Player(key, name) { var player = { name: name, dom: document.createElement('li'), position: null }; player.dom.textContent = name; if(key != session.key) { player.dom.addEventListener('click', function(e) { e.preventDefault(); if(session.loggedIn) { select(key); } }); } else { on(); player.dom.title = "Hey ! That's you !"; } return player; } function populate(playersHash, sessionKey) { session.key = sessionKey; lib.clearElement(playersList); for(var key in playersHash) { enter(key, playersHash[key] || "anon"); } } function enter(key, name) { var player = Player(key, name); keysByName[name] = key; players[key] = player; player.position = lib.insert(name, logins); beforePlayer = players[keysByName[logins[player.position]]]; playersList.insertBefore(player.dom, beforePlayer && beforePlayer.dom); logins.splice(player.position, 0, name); } function leave(key) { var player = players[key]; if(key == session.key) { off(); } else if(key == session.selected) { reset(); } if(player != undefined) { playersList.removeChild(player.dom); logins.splice(player.position, 1); delete keysByName[player.name] delete players[key]; } } function name(key) { player = players[key]; return player && player.name; } function on() { domElem.className = ""; session.loggedIn = true; } function off() { domElem.className = "off"; session.loggedIn = false; reset(); } function select(key) { if(key === session.selected) { unselect(key); } else { reset(); players[key].dom.className = "selected"; session.selected = key; domElem.invite.disabled = false; } } function reset() { if(session.selected) { unselect(session.selected); } } function unselect(key) { players[key].dom.className = ""; session.selected = null; domElem.invite.disabled = true; } }