function Room(domElem, lib) { var players = {}; var sortedKeys = []; 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}) }); var compareKeysByLogin = lib.funMap(function(key) {return players[key].name;}, lib.defaultCompare); 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(parseInt(key), playersHash[key] || "anon"); } } function enter(key, name) { var player = Player(key, name); players[key] = player; player.position = lib.insert(key, sortedKeys, compareKeysByLogin); beforePlayer = players[sortedKeys[player.position]]; playersList.insertBefore(player.dom, beforePlayer && beforePlayer.dom); sortedKeys.splice(player.position, 0, key); } 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); sortedKeys.splice(player.position, 1); 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; } }