function Room(domElem, lib) { var players = {}; var keys = {}; 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: parseInt(domElem.guest.value)}) }); 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); keys[key] = name; players[key] = player; player.position = lib.insert(name, logins); beforePlayer = players[keys[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(); } if(player != undefined) { playersList.removeChild(player.dom); logins.splice(player.position, 1); delete keys[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; } function select(key) { if(key == domElem.guest.value) { unselect(players[key].dom); } else { if(session.selected) { unselect(session.selected); } players[key].dom.className = "selected"; session.selected = players[key].dom; domElem.guest.value = key; domElem.invite.disabled = false; } } function unselect(dom) { dom.className = ""; domElem.guest.value = ""; domElem.invite.disabled = true; } }