catlab-remote-client 5.0.1 → 5.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var io;define("CatLab/Webremote/Tools/Net",[],function(){return{loadJSON:function(e,t,n){var i=new XMLHttpRequest;i.onreadystatechange=function(){i.readyState===XMLHttpRequest.DONE&&200===i.status&&t&&t(JSON.parse(i.responseText))},i.onerror=function(e){e&&n(i,e)},i.open("GET",e,!0),i.send()}}}),define("CatLab/Webremote/Tools/Deferred",[],function(){function c(e){return"[object Array]"===Object.prototype.toString.call(e)}function h(e,t){if(c(e))for(var n=0;n<e.length;n++)t(e[n]);else t(e)}function u(e){var i="pending",o=[],r=[],s=[],a=null,n={done:function(){for(var e=0;e<arguments.length;e++)if(arguments[e])if(c(arguments[e]))for(var t=arguments[e],n=0;n<t.length;n++)"resolved"===i&&t[n].apply(this,a),o.push(t[n]);else"resolved"===i&&arguments[e].apply(this,a),o.push(arguments[e]);return this},fail:function(){for(var e=0;e<arguments.length;e++)if(arguments[e])if(c(arguments[e]))for(var t=arguments[e],n=0;n<t.length;n++)"rejected"===i&&t[n].apply(this,a),r.push(t[n]);else"rejected"===i&&arguments[e].apply(this,a),r.push(arguments[e]);return this},always:function(){return this.done.apply(this,arguments).fail.apply(this,arguments)},progress:function(){for(var e=0;e<arguments.length;e++)if(arguments[e])if(c(arguments[e]))for(var t=arguments[e],n=0;n<t.length;n++)"pending"===i&&s.push(t[n]);else"pending"===i&&s.push(arguments[e]);return this},then:function(){return 1<arguments.length&&arguments[1]&&this.fail(arguments[1]),0<arguments.length&&arguments[0]&&this.done(arguments[0]),2<arguments.length&&arguments[2]&&this.progress(arguments[2]),this},promise:function(e){if(null==e)return n;for(var t in n)e[t]=n[t];return e},state:function(){return i},debug:function(){console.log("[debug]",o,r,i)},isRejected:function(){return"rejected"===i},isResolved:function(){return"resolved"===i},pipe:function(e,t,n){return u(function(n){h(e,function(t){"function"==typeof t?l.done(function(){var e=t.apply(this,arguments);e&&"function"==typeof e?e.promise().then(n.resolve,n.reject,n.notify):n.resolve(e)}):l.done(n.resolve)}),h(t,function(t){"function"==typeof t?l.fail(function(){var e=t.apply(this,arguments);e&&"function"==typeof e?e.promise().then(n.resolve,n.reject,n.notify):n.reject(e)}):l.fail(n.reject)})}).promise()}},l={resolveWith:function(e){if("pending"===i){i="resolved";for(var t=a=1<arguments.length?arguments[1]:[],n=0;n<o.length;n++)o[n].apply(e,t)}return this},rejectWith:function(e){if("pending"===i){i="rejected";for(var t=a=1<arguments.length?arguments[1]:[],n=0;n<r.length;n++)r[n].apply(e,t)}return this},notifyWith:function(e){if("pending"===i)for(var t=a=1<arguments.length?arguments[1]:[],n=0;n<s.length;n++)s[n].apply(e,t);return this},resolve:function(){return this.resolveWith(this,arguments)},reject:function(){return this.rejectWith(this,arguments)},notify:function(){return this.notifyWith(this,arguments)}},t=n.promise(l);return e&&e.apply(t,[t]),t}return u.when=function(){var e,t;if(arguments.length<2)return((e=arguments.length?arguments[0]:void 0)&&"function"==typeof e.isResolved&&"function"==typeof e.isRejected?e:e&&"function"==typeof e.done&&"function"==typeof e.fail?(t=u(),e.done(function(){t.resolve.apply(t,arguments)}),e.fail(function(){t.reject.apply(t,arguments)}),t):u().resolve(e)).promise();for(var n=arguments,i=u(),o=n.length,r=0,s=new Array(o),a=0;a<n.length;a++)(e=>{var t;n[e]&&n[e].done?n[e].done(function(){s[e]=arguments.length<2?arguments[0]:arguments,++r==o&&i.resolve.apply(i,s)}).fail(function(){i.reject(arguments)}):(t=n[e],n[e]=u(),n[e].done(function(){s[e]=arguments.length<2?arguments[0]:arguments,++r==o&&i.resolve.apply(i,s)}).fail(function(){i.reject(arguments)}).resolve(t))})(a);return i.promise()},u}),define("CatLab/Webremote/Collections/ServerList",["CatLab/Webremote/Tools/Deferred"],function(o){function e(e,t){this.defaultId=e.default,this.servers=e.servers,this.connectUrl=e.connectUrl,this.selectedServerId=null,this.preferredServer=t,this.assetsUrl=e.assetsUrl}var t=e.prototype;return t.getFromToken=function(e){if(e.length<8)return{host:this.getDefault().host,token:e};var t=e.substr(0,2);if(t){t=this.getFromId(t);if(t)return{host:t.host,token:e.substr(2)}}throw new Error("Code does not correspondent to any servers.")},t.getSelectedServer=function(){var t=new o;return this.selectedServerId?this.getFromId(this.selectedServerId)?t.resolve(this.getFromId(this.selectedServerId).host):t.reject("Selected remote server not found in server list. Please make sure you are connected to the right network."):this.selectBestServer().then(function(e){this.selectedServerId||(this.selectServer(e.id),t.resolve(e.host))}.bind(this)),t.promise()},t.selectBestServer=function(){var n=new o;if(this.preferredServer)for(var e=0;e<this.servers.length;e++)if(this.servers[e].id==this.preferredServer)return n.resolve(this.servers[e]),n.promise();var i=!1;return this.servers.forEach(function(t){t.discoverable&&this.measureRequestSpeed("https://"+t.host+"/info").then(function(e){console.log("[ServerList] "+t.host+" took "+e+"ms"),i||(i=!0,n.resolve(t))}.bind(this))}.bind(this)),n.promise()},t.selectServer=function(e){this.selectedServerId=e},t.measureRequestSpeed=function(e){var t=new Date,n=new o,i=new XMLHttpRequest;return i.onreadystatechange=function(){var e;4==this.readyState&&200==this.status&&(e=(new Date).getTime()-t.getTime(),n.resolve(e))},i.open("GET",e),i.send(),n.promise()},t.getConnectURL=function(){if(this.selectedServerId){var e=this.getFromId(this.selectedServerId);if(e.connectUrl)return e.connectUrl}return this.connectUrl},t.getAssetURL=function(){var e;return this.assetsUrl||((e=this.getConnectURL())?("http"!==e.substring(0,4)&&(e="https://"+e),this.assetsUrl=e+"/assets/",this.assetsUrl):void 0)},t.getConnectToken=function(e){return null==e?null:this.getFromId(this.selectedServerId).connectUrl?e:this.selectedServerId+e},t.getFromId=function(e){for(var t=0;t<this.servers.length;t++)if(this.servers[t].id==e)return this.servers[t];return null},t.getDefault=function(){return this.getFromId(this.defaultId)},t.serialize=function(){return{server:this.selectedServerId}},t.unserialize=function(e){this.selectServer(e.server)},e}),define("CatLab/Webremote/Config",["CatLab/Webremote/Tools/Net","CatLab/Webremote/Collections/ServerList"],function(i,e){var t="http";return{_options:{host:"www.catlab.tv",serverlist:null,preferredServer:null,protocol:t="undefined"!=typeof window&&void 0!==window.location&&void 0!==window.location.protocol?window.location.protocol.substr(0,window.location.protocol.length-1):t,debug:!1,proxy:"",imageproxy:"",smileys:!0,assetsUrl:null,vendorPath:"/vendor/",audioSync:!1,allowAuthentication:!0,canFullscreen:!0,oauth:{redirectUrl:null}},_initialized:!1,_serverlistSource:null,audioSyncConfig:{alphabet:"qwertyuiop",length:5,freqMin:524,freqMax:1593,freqError:25,debug:!1},set:function(e){void 0!==e&&(e.host,this._options.host=e.host,void 0!==e.protocol&&(this._options.protocol=e.protocol),void 0!==e.debug&&(this._options.debug=e.debug),void 0!==e.imageproxy&&(this._options.imageproxy=e.imageproxy),void 0!==e.proxy&&(this._options.proxy=e.proxy),void 0!==e.smileys&&(this._options.smileys=e.smileys),void 0!==e.assetsUrl&&(this._options.assetsUrl=e.assetsUrl),void 0!==e.vendorPath&&(this._options.vendorPath=e.vendorPath),void 0!==e.audioSync&&(this._options.audioSync=e.audioSync),void 0!==e.serverlist&&e.serverlist!==this._serverlistSource&&(this._options.serverlist=e.serverlist,this._serverlistSource=null,this.serverCollection=null),void 0!==e.preferredServer&&(this._options.preferredServer=e.preferredServer),void 0!==e.allowAuthentication&&(this._options.allowAuthentication=e.allowAuthentication),void 0!==e.audioSyncConfig&&(this.audioSyncConfig=e.audioSyncConfig),void 0!==e.canFullscreen&&(this._options.canFullscreen=e.canFullscreen),void 0!==e.oauth&&void 0!==e.oauth.redirectUrl&&(this._options.oauth.redirectUrl=e.oauth.redirectUrl),void 0!==e.APP_ID&&(this.APP_ID=e.APP_ID),void 0!==e.APP_SECRET)&&(this.APP_SECRET=e.APP_SECRET)},getAll:function(){return this._options},initialize:function(t){var e,n=this._options.serverlist;null===n||"string"!=typeof n||"http"!==n.substring(0,4)?(this._initialized=!0,t()):"json"===n.substring(n.length-4)?i.loadJSON(n,function(e){this._initialized=!0,this._serverlistSource=n,this._options.serverlist=e,t()}.bind(this),function(e,t){alert("Failed to connect to "+n+". Game cannot start."),console.log(t)}.bind(this)):((e=document.createElement("script")).onload=function(){this._initialized=!0,this._serverlistSource=n,this._options.serverlist=getCatLabRemoteServers(),t()}.bind(this),e.onerror=function(){alert("Failed to connect to "+n+". Game cannot start.")}.bind(this),e.src=n,document.head.appendChild(e))},getProtocol:function(e){var t=this._options.protocol;switch(t=void 0!==e&&e&&""===t?"http":t){case"http":case"https":break;default:t="https"}return t},getSocketURL:function(e){return this._options.host?((e=this.getProtocol(e))&&(e+=":"),e+"//"+this._options.host):"undefined"!=typeof window&&void 0!==window.location?window.location.protocol+"//"+window.location.hostname:""},getAssetsURL:function(e){var t;return this._options.assetsUrl||((t=this.getServerList())?t.getAssetURL():this.getSocketURL(e)+"/assets/")},debug:function(){return this._options.debug},getProxiedImage:function(e){return this._options.imageproxy?this._options.imageproxy+encodeURIComponent(e):e},getProxy:function(){return this._options.proxy},useSmileys:function(){return this._options.smileys},useAudioSync:function(){return this._options.audioSync},all:function(){return this._options},getAudioSyncConfig:function(){return this.audioSyncConfig},getProviderConfig:function(){var e={smileys:this.useSmileys(),audioSync:this.useAudioSync()};return this.useAudioSync()&&(e.audioSyncConfig=this.audioSyncConfig),this.APP_ID&&(e.app={id:this.APP_ID,secret:this.APP_SECRET||null}),e},getServerList:function(){return this._options.serverlist?(this.serverCollection||(this.serverCollection=new e(this._options.serverlist,this._options.preferredServer)),this.serverCollection):null},getVendorPath:function(){return this._options.vendorPath},supportsAuthentication:function(){return this._options.allowAuthentication},canFullscreen:function(){return this._options.canFullscreen}}}),define("CatLab/Webremote/Polyfills",[],function(){"function"!=typeof Object.assign&&(Object.assign=function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var n=Object(e),i=1;i<arguments.length;i++){var o=arguments[i];if(null!=o)for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(n[r]=o[r])}return n})}),define("CatLab/Webremote/Tools/Tracker",[],function(){var o=function(e,t,n,i){},t=function(e){o("Page",e,"-",0)};return{setTracker:function(e){o=e},setPageMethod:function(e){t=e},track:function(e,t,n,i){o(e,t,n,i)},page:function(e){t(e)}}}),define("CatLab/Webremote/Tools/Tools",[],function(){var o,r;return{popup:function(e,t){var n=this,i=(t=t||!1,document.createElement("iframe"));i.style.margin=0,i.style.padding=0,i.style.border=0,i.style.position="absolute",i.style.width="100%",i.style.height="100%",i.style.left=0,i.style.top=0,i.src=e,(r=document.createElement("div")).style.margin=0,r.style.padding=0,r.style.border=0,r.style.position="absolute",r.style.width="100%",r.style.height="100%",r.style.left=0,r.style.top=0,r.style.zIndex=9999,r.onclick=function(){n.closePopup()},(o=document.createElement("div")).appendChild(i),o.style.margin=0,o.style.padding=0,o.style.border=0,o.style.position="absolute",o.style.zIndex=1e4,o.style.overflow="auto",o.style.background="white",o.style.boxSizing="border-box",t?(o.style.border="0 none black",o.style.left="0",o.style.top="0",o.style.width="100%",o.style.height="100%"):(o.style.border="5px solid black",o.style.left="10%",o.style.top="10%",o.style.width="80%",o.style.height="80%"),document.body.appendChild(r),document.body.appendChild(o)},oauth2PopupMethod:function(e,t){return window.open(e,"oauth:catlab-remote")},oauth2Popup:function(e,t){return this._popupBridge?this._popupBridge(e,t):"undefined"==typeof window||"function"!=typeof window.open?(console.warn("[OAuth2] Cannot open popup — no bridge configured"),null):this.oauth2PopupMethod(e,t)},setPopupBridge:function(e){return this._popupBridge=e,this},closePopup:function(){o&&o.parentNode.removeChild(o),r&&r.parentNode.removeChild(r)},setOauth2Popup:function(e){return this.oauth2PopupMethod=e,this},sanitize:function(e){var t;return null==e?null:(t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"},String(e).replace(/[&<>"']/g,function(e){return t[e]}))},nl2br:function(e,t){return null==e?"":(e+"").replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,"$1"+(t||void 0===t?"<br />":"<br>")+"$2")},shuffle:function(e){for(var t,n,i=e.length-1;0<i;i--)t=Math.floor(Math.random()*(i+1)),n=e[i],e[i]=e[t],e[t]=n},getUuid:function(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)},findIndex:function(e,t){for(var n=0;n<e.length;n++)if(t(e[n]))return n;return-1},getConnectTokenForDisplay:function(e){return null===e?null:e.length%4==0?this.injectFillerInString(e,4," "):(e.length,this.injectFillerInString(e,3," "))},injectFillerInString:function(e,t,n){return e.match(new RegExp(".{1,"+t+"}","g")).join(n)}}}),define("CatLab/Webremote/Tools/Cookies",[],function(){var r=null,t={setCookieBridge:function(e){r=e},setCookie:function(e,t,n){return this.setItem(e,t,n)},getCookie:function(e){return this.getItem(e)},eraseCookie:function(e){return this.removeItem(e)},getItem:function(e){return r?r.get(e):"undefined"!=typeof document&&void 0!==document.cookie&&e&&this.hasOwnProperty(e)?unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"),"$1")):null},key:function(e){return r?r.key?r.key(e):null:"undefined"==typeof document||void 0===document.cookie?null:unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/,"").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[e])},setItem:function(e,t,n){if(e){if(r)return r.set(e,t,n);var i,o;"undefined"!=typeof document&&void 0!==document.cookie&&(i="",n&&((o=new Date).setTime(o.getTime()+Math.round(24*n*60*60*1e3)),i="; expires="+o.toUTCString()),document.cookie=escape(e)+"="+escape(t)+"; expires="+i+"; path=/; SameSite=Strict;",this.updateLength())}},length:0,removeItem:function(e){if(r)return r.erase(e);e&&this.hasOwnProperty(e)&&"undefined"!=typeof document&&void 0!==document.cookie&&(document.cookie=escape(e)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Strict;",this.length--)},hasOwnProperty:function(e){return r?null!=r.get(e):"undefined"!=typeof document&&void 0!==document.cookie&&new RegExp("(?:^|;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(document.cookie)},updateLength:function(){var e;!r&&"undefined"!=typeof document&&document.cookie&&(e=document.cookie.match(/\=/g),t.length=e?e.length:0)}};return t.updateLength(),t}),define("CatLab/Webremote/Tools/Images",["CatLab/Webremote/Config"],function(o){function e(e){this.images={},this.availableSizes=e=void 0===e?[512,256,128]:e}var t=e.prototype;return t.getImage=function(e,t){var n;return void 0!==t&&-1!==this.availableSizes.indexOf(t)||(t=this.availableSizes[0]),void 0===this.images[e+"_"+t]&&((n=new Image).crossOrigin="anonymous",n.src=this.getUrl(e,t),this.images[e+"_"+t]=n),this.images[e+"_"+t]},t.getUrl=function(e,t){if(this.isExternal(e))return e;void 0!==t&&-1!==this.availableSizes.indexOf(t)||(t=this.availableSizes[0]);for(var n=e.split("/"),i=0;i<n.length;i++)"$SIZE"===n[i]&&(n[i]=t);return e=n.join("/"),o.getAssetsURL()+e},t.isExternal=function(e){return 0===e.indexOf("http")},e}),define("CatLab/Webremote/Tools/Smileys",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Tools/Images"],function(n,i,t){function e(e){this.provider=e,this.smileyKeys=["1f98d","1f61c","1f3b7","1f32e","1f621","1f61b","1f98f","1f34c","1f596","1f34d","2660","1f61a","2602","2665","1f0cf","1f427","1f918","1f98b","1f9df","1f344","1f983","1f338","2618","1f36a","1f383","270c","1f913","1f40d","1f910","1f57a","1f641","1f36c","1f579","1f333","1f40b","1f617","1f42b","1f60d","1f42c","1f339","1f414","1f42d","1f349","1f92e","1f437","1f367","1f62c","1f428","1f994","1f911","1f369","1f9d0","1f378","1f9dd-2640","1f34e","2666","1f47d","1f60a","1f60f","1f43b","1f47b","1f425","1f919","1f346","1f4a8","1f43f","1f37a","1f40c","1f334","1f4a3","1f42e","1f379","1f42f","1f417","1f9c0","1f601","1f41a","1f61d","1f997","26c4","1f34b","1f430","1f47a","1f37c","1f3b1","1f95d","1f433","1f41b","1f37f","1f36d","1f60e","1f354","1f63b","1f680","1f996","1f924","1f341","1f43a","1f922","1f436","1f43c","1f332","1f31a","1f335","1f336","2623","1f31e","1f63d","1f421","1f438","1f63a","1f32d","1f986","1f388","1f41e","1f98c","1f91e","1f64a","1f638","1f3b5","1f43d","1f363","1f373","1f435","1f628","1f635","1f377","1f47e","1f984","1f3a9","1f439","1f925","1f929","1f951","1f4a9","1f921","1f92a","1f96a","1f41f","1f419","1f420","2663","1f40a","1f989","1f91f","1f63c","1f3f3-1f308","1f98a","1f431","1f920","1f41d","1f608","1f612","1f987","1f3ba","1f355","270b","1f98e","1f41c","1f917"],this.taken={},this.takenAmount=0,this.playerKnowsAboutNonUniqueSmileys={},this.images=new t,this.randomSmileys=this.smileyKeys.slice(0),i.shuffle(this.randomSmileys)}var o=e.prototype;return o.shouldHaveUniqueSmileys=function(){return this.takenAmount<this.smileyKeys.length/3},o.setTakenSmileys=function(e){this.taken=e},o.getTakenSmileys=function(e){if(!this.shouldHaveUniqueSmileys())return{};e=this.identifierToText(e);var t,n={};for(t in this.taken)this.taken.hasOwnProperty(t)&&this.taken[t]!==e&&(n[t]=this.taken[t]);return n},o.getRandom=function(e){for(var t=null;null===t&&this.randomSmileys;)if(t=this.randomSmileys.shift(),this.reserve(t,e)||(t=null),0===this.randomSmileys.length)return this.randomSmileys=this.smileyKeys.slice(0),i.shuffle(this.randomSmileys),this.randomSmileys.shift();return t},o.reserve=function(e,t){return this.isExternalSmiley(e)?(this.unreserve(t),!0):(t=this.identifierToText(t),void 0!==this.taken[e]&&this.taken[e]===t?(this.taken[e]=t,!0):!!this.isAvailable(e)&&(this.unreserve(t),this.taken[e]=t,this.takenAmount++,!0))},o.unreserve=function(e){for(var t in e=this.identifierToText(e),this.taken)this.taken.hasOwnProperty(t)&&this.taken[t]===e&&(this.taken[t]=null,delete this.taken[t],this.takenAmount--)},o.isAvailable=function(e){return!this.shouldHaveUniqueSmileys()||!!this.isExternalSmiley(e)||null==this.taken[e]},o.identifierToText=function(e){return JSON.stringify(e)},o.isExternalSmiley=function(e){return"http"===e.substring(0,4).toLowerCase()},o.getUrl=function(e){var t=this.getImageUrl(e);return t?this.isExternalSmiley(e)?e:n.getAssetsURL()+t:null},o.getImageUrl=function(e){return null===e?null:this.isExternalSmiley(e)?e:"smileys/"+e+".png"},o.getHtml=function(e){return null===e?null:'<span class="smiley" style="width: 64px; height: 64px; display: inline-block; background-image: url(\''+this.getUrl(e)+"');\"></span>"},o.getElement=function(e){var t;return null===e?null:((t=document.createElement("div")).innerHTML=this.getHtml(e),t.firstChild)},o.getImage=function(e){return null===e?null:this.images.getImage(this.getImageUrl(e))},o.refreshTakenSmileys=function(e){if(!this.shouldHaveUniqueSmileys())return void 0!==this.playerKnowsAboutNonUniqueSmileys[this.getStringIdentifier(e)]?void 0:(this.playerKnowsAboutNonUniqueSmileys[this.getStringIdentifier(e)]=!0,void e.emit("smileys:taken",{smileys:[]}));e.emit("smileys:taken",{smileys:this.getTakenSmileys(e.getIdentifier())})},o.getStringIdentifier=function(e){return e.type+":"+e.id},e}),define("CatLab/Webremote/Tools/Preloader",["../Config","CatLab/Webremote/Tools/Deferred"],function(t,r){function n(e){this.provider=e,this.provider.on("file:preload",function(e){e&&e.url&&this.preloadClientFile(e.url)}.bind(this)),this.urlMap={}}var e=n.prototype;return e.preload=function(t){if(Array.isArray(t)){for(var e=new r,n=[],i=0;i<t.length;i++)n.push(this.preload(t[i]));return r.when.apply(r,n).then(function(){e.resolve(Array.prototype.slice.call(arguments))}),e.promise()}var o=new r;return this.urlMap[t]=t,this.provider.proxyFile(t).then(function(e){this.urlMap[t]=e.url,this.provider.emit("file:preload",{url:e.url}),o.resolve(e)}.bind(this)),o.promise()},e.sendPreloadFileCommandToPlayer=function(e){for(var t in this.urlMap)this.urlMap.hasOwnProperty(t)&&e.emit("file:preload",{url:this.urlMap[t]})},e.getPreloadedUrl=function(e){return this.urlMap[e]},e.preloadClientFile=function(e){void 0===this.urlMap[e]&&(e.toLowerCase().indexOf("http")<0&&(e=t.getProtocol()+":"+e),this.urlMap[e]=document.createElement("img"),this.urlMap[e].src=e)},e.serialize=function(){return{urlMap:this.urlMap}},n.unserialize=function(e,t){e=new n(e);return void 0!==t&&void 0!==t.urlMap&&(e.urlMap=t.urlMap),e},n}),define("CatLab/Webremote/Tools/Eventable",["CatLab/Webremote/Tools/Tools"],function(i){function e(){}var o=0,t=e.prototype;return t.initializeEventable=function(){this._eventableEvents=[]},t.trigger=function(e){this.eventableTrigger.apply(this,arguments)},t.eventableTrigger=function(e){if("string"!=typeof e)throw new Error("eventableTrigger must be a string");if(void 0!==this._eventableEvents){var t,n=Array.prototype.slice.call(arguments);for(t in n.push(n.shift()),this._eventableEvents)this._eventableEvents.hasOwnProperty(t)&&this.eventMatches(e,t)&&this._eventableEvents[t].slice().forEach(function(e){try{e.method.apply(e.scope,n)}catch(e){console.error(e)}}.bind(this))}},t.eventMatches=function(e,t){return"*"===t||e===t},t.on=function(e,t,n){void 0===this._eventableEvents&&(this._eventableEvents={}),void 0===this._eventableEvents[e]&&(this._eventableEvents[e]=[]),o++,this._eventableEvents[e].push({id:o,method:t,scope:void 0!==n?n:this});var i=[e,o];return{id:i,name:e,method:t,unbind:function(){this.off(null,{id:i,name:e})}.bind(this)}},t.once=function(e,t,n){var i=this.on(e,function(){i.unbind(),t.apply(n,arguments)});return i},t.off=function(e,t){if(void 0!==e||void 0!==t)if(void 0===e||void 0!==t){if(e=t.name,t=t.id,void 0===this._eventableEvents[e])return null;var n=i.findIndex(this._eventableEvents[e],function(e){return e.id===t[1]});0<=n&&this._eventableEvents[e].splice(n,1)}else this._eventableEvents[e]=[];else this._eventableEvents=[]},t.clearEvents=function(){this.clearEventableEvents()},t.clearEventableEvents=function(){this._eventableEvents={}},e}),define("CatLab/Webremote/Models/User",["CatLab/Webremote/Config"],function(t){return function(e){this.accessToken=e,this.name=null,this.avatar=null,this.id=null,this.image=null,this.imageCallbacks=[],this.imageLoaded=!1,this.getAccessToken=function(){return this.accessToken},this.setId=function(e){this.id=e},this.getId=function(){return this.id},this.setName=function(e){this.name=e},this.getName=function(){return this.name},this.setAvatar=function(e){this.avatar=e,this.imageLoaded=!1,this.imageCallbacks=[],this.image=null},this.loadAvatar=function(){this.image||(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=function(){this.afterImageLoad()}.bind(this),this.image.src=t.getProxiedImage(this.avatar))},this.getAvatar=function(){return this.avatar},this.getAvatarSmiley=function(e){var t=this.getAvatar();return t?(t=t.split("?")[0],t+="?shape=circle&size=64&borderWidth=4",e&&(t+="&borderColor="+e.substr(1)),t):null},this.afterImageLoad=function(){this.imageLoaded=!0;for(var e=0;e<this.imageCallbacks.length;e++)this.imageCallbacks[e](this.image);this.imageCallbacks=[]},this.getImage=function(e){this.loadAvatar(),this.imageLoaded?e(this.image):this.imageCallbacks.push(e)}}}),define("CatLab/Webremote/Tools/Storage",["CatLab/Webremote/Tools/Cookies"],function(e){var t={_syncKeys:["users","currentuser"],_syncSink:null,setSyncSink:function(e){this._syncSink="function"==typeof e?e:null},syncToBridge:function(e){-1!==this._syncKeys.indexOf(e)&&this._syncSink&&"undefined"!=typeof window&&void 0!==window.localStorage&&this._syncSink({name:e,rawValue:window.localStorage.getItem(e)})},clean:function(){if(this.isSupported())for(var e=Object.keys(window.localStorage),t=0;t<e.length;t++)this.get(e)},get:function(e,t){if(void 0===t&&(t=function(){}),this.isSupported())try{var n,i=window.localStorage.getItem(e);i?void 0!==(i=JSON.parse(i)).expires?(n=Date.now(),i.expires<n?(this.delete(e),t(null)):t(i.content)):t(i):t(null)}catch(e){t(null),console.log(e)}else t(null)},add:function(t,n,i,o){var r=this;i=i||function(){},this.isSupported()?this.get(t,function(e){(e=null!=e&&""!==e?e:[]).push(n),r.set(t,e,i,o)}):i(null)},set:function(e,t,n,i){if(void 0===n&&(n=function(){}),this.isSupported()){void 0===i&&(i=31536e6);try{var o=Date.now();o+=i,window.localStorage.setItem(e,JSON.stringify({expires:o,content:t}))}catch(e){console.log(e)}this.syncToBridge(e),n()}else n(null)},delete:function(e){this.isSupported()&&(window.localStorage.removeItem(e),this.syncToBridge(e))},remove:function(i,o){var r;this.isSupported()&&(r=this).get(i,function(e){null!=e&&""!=e||(e=[]);for(var t=JSON.stringify(o),n=0;n<e.length;n++)if(t===JSON.stringify(e[n]))return e.splice(n,1),void r.set(i,e)})},upsert:function(i,o,r,s){var a=this;s=s||function(){},this.isSupported()?this.get(i,function(e){null!=e&&""!==e||(e=[]);for(var t=!1,n=0;n<e.length;n++)if(e[n]&&e[n][o]===r[o]){e[n]=r,t=!0;break}t||e.push(r),a.set(i,e,s)}):s(null)},removeBy:function(i,o,r,s){var a=this;s=s||function(){},this.isSupported()?this.get(i,function(e){if(null!=e&&""!==e){for(var t=[],n=0;n<e.length;n++)e[n]&&e[n][o]===r||t.push(e[n]);a.set(i,t,s)}else s()}):s(null)},isSupported:function(){if("undefined"==typeof window)return!1;try{if(void 0===window.localStorage)return!1}catch(e){return console.log(e),!1}return!0}};try{t.clean()}catch(e){console.error(e)}return t}),define("CatLab/Webremote/Collections/AuthenticatedUsers",["CatLab/Webremote/Models/User","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Eventable"],function(n,o,e){var a,l,c=[];function h(e){return 401===e||403===e}function u(e){for(var t=0;t<c.length;t++)if(c[t].getId()==e)return t;return-1}function d(e,t){e=new n(e);return e.setId(t.id),e.setName(t.username),e.setAvatar(t.avatar),e}function t(){this.initializeEventable()}e=t.prototype=new e;return e.initialize=function(e,t){a=t,l=e;var s=this;o.get("users",function(r){r&&o.get("currentuser",function(i){for(var e=!1,t=0;t<r.length;t++){var n,o=r[t];o&&o.access_token&&void 0!==o.username&&-1===u(o.id)&&(n=d(o.access_token,{id:o.id,username:o.username,avatar:o.avatar}),c.push(n),e=!0,i)&&o.access_token===i&&void 0!==l.setUser&&l.setUser(n)}e&&s.trigger("update"),r.forEach(function(e){var n;e&&e.access_token&&(n=e.access_token,a.profile(n,function(e,t){e&&e.user?(e=s.add(n,e.user),i&&n===i&&void 0!==l.setUser&&l.setUser(e)):h(t)&&s.removeByToken(n)}))})})})},e.addFromAccessToken=function(n,i){i=i||function(){};var o=this;a.profile(n,function(e,t){e&&e.user?i(o.add(n,e.user)):(h(t)&&o.removeByToken(n),i(null))})},e.add=function(e,t){var n,i=u(t.id);return-1===i?(n=d(e,t),c.push(n)):((n=c[i]).accessToken=e,n.setName(t.username),n.setAvatar(t.avatar)),o.upsert("users","access_token",{access_token:e,id:t.id,username:t.username,avatar:t.avatar,updated_at:Date.now()}),this.trigger("update"),n},e.removeByToken=function(e){for(var t=0;t<c.length;t++)if(c[t].getAccessToken()===e){c.splice(t,1);break}o.removeBy("users","access_token",e),this.trigger("update")},e.remove=function(e){this.removeByToken(e.getAccessToken())},e.getFromId=function(e){e=u(e);return-1===e?null:c[e]},e.getAll=function(){return c},new t}),define("CatLab/Webremote/Controllers/OAuth2",["CatLab/Webremote/Tools/Tools","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Config"],function(r,s,e,o,t,i){var a,l,c,h,u,d=[],n=[],f=[],p=null;function g(){this.initializeEventable()}e=g.prototype=new e;return e.initialize=function(e){a=(e=e||{}).authorization,l=e.client_id||"none",c=e.authorization||"default",h=e.profile||"",u=e.profile+"/avatar",void 0===e.redirect_uri||i._options.oauth.redirectUrl||(i._options.oauth.redirectUrl=e.redirect_uri);var t=this;if("undefined"!=typeof window){var n,e=function(e){t.onMessage(e)};if(window.addEventListener){for(;n=f.pop();)removeEventListener("message",n);addEventListener("message",e,!1)}else{for(;n=f.pop();)detachEvent("onmessage",n);attachEvent("onmessage",e)}f.push(e)}},e.setRedirectUrl=function(e,t){this.redirectHost=e,this.redirectUrl=e+t},e.getAuthorizeURL=function(){var e="",e=(i.all().oauth&&i.all().oauth.redirectUrl&&(e=i.all().oauth.redirectUrl),a+"?client_id="+encodeURIComponent(l)+"&authorization="+encodeURIComponent(c)+"&response_type=token&redirect_uri="+encodeURIComponent(e)+"&reset=1&state=login");return void 0!==this.redirectUrl?this.redirectUrl+"?url="+encodeURIComponent(e):e},e.onMessage=function(e){if("I must've called a thousand times"!==e.data){var t;if("string"==typeof e.data&&e.data.match(/^oauth::/))try{t=JSON.parse(e.data.substring(7))}catch(e){return}else if("string"==typeof e.data)try{t=JSON.parse(e.data)}catch(e){return}else t=e.data;void 0!==t.access_token&&this.addAccessToken(t.access_token)}},e.addAccessToken=function(i){var e=function(e){if(e&&e.user){var t,n=o.add(i,e.user);for(r.closePopup();t=d.shift();)t(n);this.trigger("update")}}.bind(this);this.call(h,i,e)},e.call=function(e,t,n){var i,e=e+"?access_token="+t;"undefined"!=typeof window&&((i=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP")).onreadystatechange=function(){if(4==i.readyState&&200!=i.status&&n(null,i.status),4==i.readyState&&200==i.status){var e;try{e=JSON.parse(i.responseText)}catch(e){return void n(null,i.status)}n(e)}},i.open("GET",e,!0),i.send())},e.profile=function(e,t){this.call(h,e,t)},e.changeAvatar=function(t,e){var n,i,o;if(t.getAccessToken())return n=new s,(i=new FormData).append("avatar",e.files[0]),(o=new XMLHttpRequest).open("POST",u,!0),o.setRequestHeader("Authorization","Bearer "+t.getAccessToken()),o.onreadystatechange=function(){if(4===o.readyState)if(200<=o.status&&o.status<300)try{var e=JSON.parse(o.responseText);t.setAvatar(e.url),n.resolve(e)}catch(e){n.reject(e)}else n.reject(o.status)},o.send(i),n.promise()},e.link=function(t){var n=new s,e={},e=("object"==typeof(t=void 0===t?{}:t)&&(t=(e=t).callback||function(){}),e.fullscreen||!1),i=(p&&clearInterval(p),this.getAuthorizeURL()),o=r.oauth2Popup(i,e);return o&&(p=setInterval(function(){o&&"function"==typeof o.postMessage?o.postMessage("Hello from the other side","*"):clearInterval(p)}.bind(this),1e3)),d.push(function(e){t(e),n.resolve(e)}),n.promise()},e.onInit=function(e){n.push(e)},e.onAdds=function(){for(var e=0;e<n.length;e++)n[e]()},e.getParamsFromHash=function(e){if("undefined"!=typeof window)return e=(e=e||window.location.hash).slice(1),(e=decodeURIComponent(e)).split("&").reduce(function(e,t){return e[(t=t.split("="))[0]]=t[1],e},{})},e.finish=function(){var e='oauth::{"catlabremote":1,"event":"user:authenticated","access_token":"'+this.getParamsFromHash().access_token+'"}';setTimeout(function(){window.opener&&"function"==typeof window.opener.postMessage&&window.opener.postMessage(e,"*"),window.parent&&"function"==typeof window.parent.postMessage&&window.parent.postMessage(e,"*"),void 0!==window.dialogArguments&&window.dialogArguments.opener&&"function"==typeof window.dialogArguments.opener.postMessage&&window.dialogArguments.opener.postMessage(e,"*"),setTimeout(function(){p&&clearInterval(p),window.close()},1)},1)},new g}),define("CatLab/Webremote/Views/Popups/BasePopup",[],function(){function e(){this.scrollable=!1}var t=e.prototype;return t.render=function(e){this.popupContainer=document.createElement("div"),this.popupContainer.className="catlab-popup-container";var t=document.createElement("div"),t=(t.className="overlay",t.addEventListener("click",function(){this.close()}.bind(this)),this.popupContainer.appendChild(t),this.container=document.createElement("div"),this.container.className="popup",this.popupContainer.appendChild(this.container),this.container.addEventListener("click",function(e){e.stopPropagation()}),this.content=document.createElement("div"),this.container.appendChild(this.content),document.createElement("p")),n=(t.className="close",document.createElement("a"));n.href="javascript:void(0)",n.innerHTML="<span>Close</span>",n.onclick=function(){this.close()}.bind(this),t.appendChild(n),this.container.appendChild(t),e.appendChild(this.popupContainer),this.scrollable&&this.content.classList.add("scrollable"),this.renderContent(this.content)},t.renderContent=function(){},t.close=function(){this.popupContainer.parentNode.removeChild(this.popupContainer)},e}),define("CatLab/Webremote/Views/User",["CatLab/Webremote/Controllers/OAuth2"],function(i){return function(d){this.render=function(e,t,n){t=t||[];var i,o=d.getName(),r=document.createElement("div"),s=(r.className="catlab-user",document.createElement("div")),s=((this.avatardiv=s).className="catlab-avatar",r.appendChild(s),this.renderAvatar(),void 0!==n&&(s.onclick=n),document.createElement("div")),a=(s.className="catlab-info",r.appendChild(s),document.createElement("p"));void 0!==n?((i=document.createElement("a")).innerHTML=o,i.onclick=n,a.appendChild(i)):(a.innerHTML=o,s.appendChild(a)),s.appendChild(a);var l,c,h=document.createElement("ul");h.className="catlab-actions";for(var u=0;u<t.length;u++)(l=document.createElement("li")).className=t[u].token,h.appendChild(l),(c=document.createElement("a")).onclick=t[u].click,c.innerHTML=t[u].text,c.href="javascript:void(0)",l.appendChild(c);s.appendChild(h),e.innerHTML="",e.appendChild(r);n=document.createElement("div");n.className="clearer",r.appendChild(n)},this.renderAvatar=function(){var e=d.getAvatar(),t=document.createElement("img");t.src=e,t.alt="User avatar",this.avatardiv.innerHTML="",this.avatardiv.appendChild(t)},this.enableAvatarUpload=function(t){var n=document.createElement("input");n.type="file",n.accept="image/*",(this.avatarFileInput=n).addEventListener("change",function(){this.avatardiv.classList.add("loading");var e=i.changeAvatar(d,n);e&&e.then&&e.then(function(){this.avatardiv.classList.remove("loading"),this.renderAvatar(),t.setUser(d)}.bind(this))}.bind(this)),this.avatardiv.addEventListener("click",function(){n.click()})},this.uploadAvatar=function(){this.avatarFileInput&&this.avatarFileInput.click()}}}),define("CatLab/Webremote/Views/Popups/AuthenticationPopup",["CatLab/Webremote/Views/Popups/BasePopup","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Views/User","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Tracker"],function(e,l,c,h,t,u){return function(t){function e(){l.link(function(e){o.updateUsers(),o.selectUser(e)})}l.on("update",function(){this.updateUsers()}.bind(this));var o=this,n=document.createElement("div"),i=(n.className="catlab-popup-container",document.createElement("div")),i=(i.className="overlay",n.appendChild(i),document.createElement("div")),r=(i.className="popup",n.appendChild(i),i.innerHTML="<h2>Select account</h2>",document.createElement("ul")),s=(r.className="userlist",i.appendChild(r),document.createElement("div")),s=(s.className="clearer",i.appendChild(s),document.createElement("p")),a=(s.className="connect",document.createElement("a")),s=(a.href="javascript:void(0)",a.innerHTML='<span class="new-user">Connect new user</span>',a.onclick=function(){e()},s.appendChild(a),i.appendChild(a),document.createElement("p")),a=(s.className="close",document.createElement("a"));a.href="javascript:void(0)",a.innerHTML="<span>Close</span>",a.onclick=function(){o.close()},s.appendChild(a),i.appendChild(s),this.selectUser=function(e){t.setUser(e),o.close(),u.track("Click","Select user","AuthenticationPopup")},this.updateUsers=function(){r.innerHTML="";for(var e=c.getAll(),t=0;t<e.length;t++)((e,t)=>{var n=document.createElement("li"),i=[{token:"select",text:"select",click:function(){o.selectUser(t)}},{token:"logout",text:"logout",click:function(){c.remove(t),o.updateUsers(),u.track("Click","Logout","AuthenticationPopup")}}];new h(t).render(n,i,function(){o.selectUser(t)}),e.appendChild(n)})(r,e[t])},this.close=function(){n.parentNode.removeChild(n),u.track("Click","Close popup","AuthenticationPopup")},this.connect=function(){u.track("Click","Connect new","AuthenticationPopup"),e()},this.render=function(e){e.appendChild(n),this.updateUsers()},this.setLoginUrl=function(e){}}}),define("CatLab/Webremote/Views/Popups/SelectSmileyPopup",["CatLab/Webremote/Views/Popups/BasePopup"],function(e){function t(e,t,n){this.Webremote=e,this.callback=t,this.scrollable=!0,this.disableTaken=n}e=t.prototype=new e;return e.renderContent=function(e){e.classList.add("smileys-popup");var t=document.createElement("ul"),n=(t.className="smileys",e.appendChild(t),this.Webremote.smileys.smileyKeys.slice());this.Webremote.getUser()&&this.Webremote.getUser().getAvatar()&&(o=this.Webremote.getUser().getAvatarSmiley(this.Webremote.color))&&n.unshift(o);for(var i=0;i<n.length;i++)this.renderSmiley(t,n[i]);var o=document.createElement("div");o.className="clearer",e.appendChild(o)},e.renderSmiley=function(n,i){var o=document.createElement("li"),r=(o.appendChild(this.Webremote.smileys.getElement(i)),!this.disableTaken||this.Webremote.smileys.isAvailable(i));r||o.classList.add("unavailable"),this.Webremote.getSmiley()===i&&o.classList.add("selected"),o.addEventListener("click",function(){if(r){this.selectSmiley(i);for(var e=n.querySelectorAll(".selected"),t=0;t<e.length;t++)e[t].classList.remove("selected");o.classList.add("selected"),this.close()}}.bind(this)),n.appendChild(o)},e.selectSmiley=function(e){this.callback(e)},t}),define("CatLab/Webremote/Views/Blocks/CurrentUser",["CatLab/Webremote/Views/User","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Tracker"],function(r,s,e,a){return function(o){this.render=function(e){var t,n,i;e.innerHTML="",o.canAuthenticate()&&(i=o.getUser(),(t=document.createElement("div")).className="overlay player-color-background",e.appendChild(t),(t=document.createElement("div")).className="content",t.className+=" player-color-border",e.appendChild(t),i?(e=[{token:"switch",text:"Switch account",click:function(){o.showAuthenticationPopup(),a.track("Click","Switch account","CurrentUser")}},{token:"upload",text:"Upload photo",click:function(){n.uploadAvatar()}},{token:"logout",text:"Logout",click:function(){var e=o.getUser();s.remove(e),o.setUser(null),a.track("Click","Logout","CurrentUser")}}],(n=new r(i)).render(t,e),n.enableAvatarUpload(o)):((i=document.createElement("p")).className="catlab-not-loggedin",(e=document.createElement("a")).href="javascript:void(0);",e.innerHTML="Login",e.onclick=function(){o.showAuthenticationPopup(0===s.getAll().length),a.track("Click","Login","CurrentUser")},i.appendChild(e),t.appendChild(i)))}}}),(()=>{var p={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function g(e){for(var t,n,i,o,r,s,a,l=(e=>{if(m[e])return m[e];for(var t,n=e,i=[],o=0;n;){if(null!==(t=p.text.exec(n)))i.push(t[0]);else if(null!==(t=p.modulo.exec(n)))i.push("%");else{if(null===(t=p.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){o|=1;var r=[],s=t[2],a=[];if(null===(a=p.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(r.push(a[1]);""!==(s=s.substring(a[0].length));){if(null===(a=p.key_access.exec(s))&&null===(a=p.index_access.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");r.push(a[1])}t[2]=r}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");i.push({placeholder:t[0],param_no:t[1],keys:t[2],sign:t[3],pad_char:t[4],align:t[5],width:t[6],precision:t[7],type:t[8]})}n=n.substring(t[0].length)}return m[e]=i})(e),c=arguments,h=1,u=l.length,d="",f=0;f<u;f++)if("string"==typeof l[f])d+=l[f];else if("object"==typeof l[f]){if((i=l[f]).keys)for(t=c[h],n=0;n<i.keys.length;n++){if(null==t)throw new Error(g('[sprintf] Cannot access property "%s" of undefined value "%s"',i.keys[n],i.keys[n-1]));t=t[i.keys[n]]}else t=i.param_no?c[i.param_no]:c[h++];if(p.not_type.test(i.type)&&p.not_primitive.test(i.type)&&t instanceof Function&&(t=t()),p.numeric_arg.test(i.type)&&"number"!=typeof t&&isNaN(t))throw new TypeError(g("[sprintf] expecting number but found %T",t));switch(p.number.test(i.type)&&(s=0<=t),i.type){case"b":t=parseInt(t,10).toString(2);break;case"c":t=String.fromCharCode(parseInt(t,10));break;case"d":case"i":t=parseInt(t,10);break;case"j":t=JSON.stringify(t,null,i.width?parseInt(i.width):0);break;case"e":t=i.precision?parseFloat(t).toExponential(i.precision):parseFloat(t).toExponential();break;case"f":t=i.precision?parseFloat(t).toFixed(i.precision):parseFloat(t);break;case"g":t=i.precision?String(Number(t.toPrecision(i.precision))):parseFloat(t);break;case"o":t=(parseInt(t,10)>>>0).toString(8);break;case"s":t=String(t),t=i.precision?t.substring(0,i.precision):t;break;case"t":t=String(!!t),t=i.precision?t.substring(0,i.precision):t;break;case"T":t=Object.prototype.toString.call(t).slice(8,-1).toLowerCase(),t=i.precision?t.substring(0,i.precision):t;break;case"u":t=parseInt(t,10)>>>0;break;case"v":t=t.valueOf(),t=i.precision?t.substring(0,i.precision):t;break;case"x":t=(parseInt(t,10)>>>0).toString(16);break;case"X":t=(parseInt(t,10)>>>0).toString(16).toUpperCase()}p.json.test(i.type)?d+=t:(!p.number.test(i.type)||s&&!i.sign?a="":(a=s?"+":"-",t=t.toString().replace(p.sign,"")),o=i.pad_char?"0"===i.pad_char?"0":i.pad_char.charAt(1):" ",r=i.width-(a+t).length,r=i.width&&0<r?o.repeat(r):"",d+=i.align?a+t+r:"0"===o?a+r+t:r+a+t)}return d}function e(e,t){return g.apply(null,[e].concat(t||[]))}var m=Object.create(null);"undefined"!=typeof exports&&(exports.sprintf=g,exports.vsprintf=e),"undefined"!=typeof window&&(window.sprintf=g,window.vsprintf=e,"function"==typeof define)&&define.amd&&define("sprintf",[],function(){return{sprintf:g,vsprintf:e}})})(),define("CatLab/Webremote/Tools/Translator",["sprintf"],function(t){function e(){this.translator=null}var n,i,o=e.prototype;return o.setTranslator=function(e){this.translatorScope=this,"function"==typeof e?this.translator=e:("function"==typeof e.t?this.translator=e.t:(e._,this.translator=e._),this.translatorScope=e)},o.t=function(e){if(""===e)return"";if(Array.isArray(e))return this.t.apply(this,e);if(this.translator)return this.translator.apply(this.translatorScope,arguments);for(n=[],i=1;i<arguments.length;i++)n.push(arguments[i]);return t.vsprintf(e,n)},new e}),define("CatLab/Webremote/Views/Blocks/CurrentSmiley",["CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Deferred"],function(n,e){function i(e,t,n,i){this.Webremote=e,this.canSwitch=void 0!==t&&!!t,this.canDrag=void 0!==n&&!!n,this.isProfileSmiley=void 0===i||!!i,this.dragDisabled=!1,this.switchVerb="Switch"}i.initialize=function(){return i.isInitialized||(i.isInitialized=new e).resolve(),i.isInitialized.promise()}.bind(this),i.activeSmileys=["1f601","1f60d","1f60e"];var t=i.prototype;return t._makeDraggable=function(i,o){var r=this,s=null,a=null,l=!1,c=!1,h=0,u=0,d=0,f=0,p=0,g=0;function e(e){var t,n;r.dragDisabled||(l=!0,i.style.cursor="grabbing",n=(void 0!==e.clientX?e:e.touches[0]).clientX,t=(void 0!==e.clientY?e:e.touches[0]).clientY,h=n,u=t,s={left:d=p,top:f=g},n=i.getBoundingClientRect(),a={left:n.left+window.pageXOffset,top:n.top+window.pageYOffset},r.disableDrag(),i.classList.add("flinging"),e.preventDefault())}function t(e){var t,n;l&&(t=(void 0!==e.clientX?e:e.touches[0]).clientX,n=(void 0!==e.clientY?e:e.touches[0]).clientY,p=d+(t-h),g=f+(n-u),i.style.left=p+"px",i.style.top=g+"px",e.preventDefault())}function n(e){var t,n;l&&(l=!1,n={left:p,top:g},10<(t=r.getDistance(s,n))?(c=!0,n=r.getAngle(s,n),r.slingshot(a,n,t,i,o,function(){g=p=0,i.style.cursor="grab"})):(i.style.left="0px",i.style.top="0px",g=p=0,i.style.cursor="grab",r.enableDrag(),i.classList.remove("flinging")),e.preventDefault())}i.style.zIndex="10",i.style.position="relative",i.style.touchAction="none",i.style.cursor="grab",i.addEventListener("mousedown",e),i.addEventListener("touchstart",e,{passive:!1}),document.addEventListener("mousemove",t),document.addEventListener("touchmove",t,{passive:!1}),document.addEventListener("mouseup",n),document.addEventListener("touchend",n),document.addEventListener("touchcancel",function(){l&&(l=!1,i.style.left="0px",i.style.top="0px",g=p=0,i.style.cursor="grab",r.enableDrag(),i.classList.remove("flinging"))}),i.addEventListener("click",function(e){c&&(c=!1,e.stopPropagation(),e.preventDefault())},!0)},t._animateElement=function(s,a,l,c){for(var h={},u=Object.keys(a),e=0;e<u.length;e++){var t=u[e];h[t]=parseFloat(s.style[t])||0}var d=null;requestAnimationFrame(function e(t){d=d||t;for(var t=Math.min((t-d)/l,1),n=.5-Math.cos(t*Math.PI)/2,i=0;i<u.length;i++){var o=u[i],r=h[o]+(a[o]-h[o])*n;s.style[o]=r+("opacity"===o?"":"px")}t<1?requestAnimationFrame(e):c&&c()})},t.setSmiley=function(t){Array.isArray(t)||(t=[t]),this.smileys=t,i.initialize().then(function(){var e;this.selector&&(this.selector.innerHTML="",t.forEach(function(e){var t=this.Webremote.smileys.getElement(e);if(this.selector.appendChild(t),this.canDrag)try{this._makeDraggable(t,e)}catch(e){console.log(e)}}.bind(this)),this.canSwitch)&&((e=document.createElement("p")).className="switch",e.innerHTML='<a href="javascript:void(0)">'+n.t(this.switchVerb)+"</a>",this.selector.appendChild(e))}.bind(this))},t.disableDrag=function(){this.dragDisabled=!0,this.selector&&this.selector.classList.add("drag-disabled")},t.enableDrag=function(){this.dragDisabled=!1,this.selector&&this.selector.classList.remove("drag-disabled")},t.getMaxDistance=function(){var e;return this.selector?(e=this.selector.getBoundingClientRect(),window.innerHeight-e.top):200},t.getDistance=function(e,t){var n=e.left-t.left,e=e.top-t.top;return Math.sqrt(n*n+e*e)},t.getAngle=function(e,t){return Math.atan2(t.top-e.top,t.left-e.top)},t.slingshot=function(e,t,n,i,o,r){var s=Math.min(1,n/this.getMaxDistance());0<Math.sin(t-Math.PI)?this._animateElement(i,{left:0,top:0},1e3,function(){r&&r(),this.enableDrag(),i.classList.remove("flinging")}.bind(this)):(n=1.5*Math.max(e.left,e.top),this._animateElement(i,{left:Math.cos(t-Math.PI)*n,top:Math.sin(t-Math.PI)*n},1e3,function(){setTimeout(function(){i.style.left=-1*parseFloat(i.style.left)+"px",this._animateElement(i,{left:0,top:0},1e3,function(){r&&r(),this.enableDrag(),i.classList.remove("flinging")}.bind(this))}.bind(this),3e3*s)}.bind(this)),setTimeout(function(){this.Webremote.emit("smileys:slingshot",{angle:t,speed:s,smiley:o})}.bind(this),800))},t.render=function(e){i.initialize().then(function(){this.container=e,this.canSwitch||this.canDrag?(this.selector=document.createElement("div"),this.selector.className="smiley-selector"):(this.selector=document.createElement("div"),this.selector.className="smiley-view"),this.selector.innerHTML='<div class="placeholder"></div>',this.container.innerHTML="",this.container.appendChild(this.selector),this.canSwitch&&(this.container.addEventListener("click",function(){this._suppressClick?this._suppressClick=!1:this.isProfileSmiley?this.Webremote.showSmileyPopup():this.Webremote.showSmileyPopup(function(e){if(-1===i.activeSmileys.indexOf(e)){for(;2<i.activeSmileys.length;)i.activeSmileys.shift();i.activeSmileys.push(e),this.setSmiley(i.activeSmileys)}}.bind(this),!1)}.bind(this)),this.isProfileSmiley||this.setSmiley(i.activeSmileys))}.bind(this))},i}),define("CatLab/Webremote/Tools/HashParser",[],function(){return{getParameters:function(){for(var e,t={},n=/\+/g,i=/([^&;=]+)=?([^&;]*)/g,o=function(e){return decodeURIComponent(e.replace(n," "))},r=window.location.hash.substring(1);e=i.exec(r);)t[o(e[1])]=o(e[2]);return t},getParameter:function(e){var t=this.getParameters();return void 0!==t[e]?t[e]:null},clear:function(){history.pushState("",document.title,window.location.pathname+window.location.search)}}}),define("CatLab/Webremote/Tools/Screenfull",[],function(){var s="undefined"!=typeof window&&void 0!==window.document?window.document:{},a=(()=>{for(var e,t=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]],n=0,i=t.length,o={};n<i;n++)if((e=t[n])&&e[1]in s){for(n=0;n<e.length;n++)o[t[0][n]]=e[n];return o}return!1})(),n={change:a.fullscreenchange,error:a.fullscreenerror},e={request:function(o,r){return new Promise(function(e,t){var n=function(){this.off("change",n),e()}.bind(this),i=(this.on("change",n),(o=o||s.documentElement)[a.requestFullscreen](r));i instanceof Promise&&i.then(n).catch(t)}.bind(this))},exit:function(){return new Promise(function(e,t){var n,i;this.isFullscreen?(n=function(){this.off("change",n),e()}.bind(this),this.on("change",n),(i=s[a.exitFullscreen]())instanceof Promise&&i.then(n).catch(t)):e()}.bind(this))},toggle:function(e,t){return this.isFullscreen?this.exit():this.request(e,t)},onchange:function(e){this.on("change",e)},onerror:function(e){this.on("error",e)},on:function(e,t){e=n[e];e&&s.addEventListener(e,t,!1)},off:function(e,t){e=n[e];e&&s.removeEventListener(e,t,!1)},raw:a};return Object.defineProperties(e,{isFullscreen:{get:function(){return Boolean(s[a.fullscreenElement])}},element:{enumerable:!0,get:function(){return s[a.fullscreenElement]}},isEnabled:{enumerable:!0,get:function(){return Boolean(s[a.fullscreenEnabled])}}}),e}),define("CatLab/Webremote/Views/Alert",[],function(){return function(e,t){t=t||function(){},alert(e),t()}}),define("CatLab/Webremote/Views/Welcome",["CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Views/User","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Tracker"],function(e,t,n,r){return function(e){var t=this,n=document.createElement("div"),i=(n.className="catlab-popup-container",document.createElement("div")),i=(i.className="overlay",n.appendChild(i),document.createElement("div")),e=(i.className="popup thanks",n.appendChild(i),i.innerHTML=e,document.createElement("a")),o=(e.innerHTML="Start playing",e.onclick=function(){t.close()},e.href="javascript:void(0)",document.createElement("p"));o.appendChild(e),o.className="playnow",i.appendChild(o),this.close=function(){n.parentNode.removeChild(n),r.track("Click","Close popup","WelcomePopup")},this.render=function(e){e.appendChild(n)}}}),define("CatLab/Webremote/Views/ConnectionTrouble",["CatLab/Webremote/Tools/Translator"],function(e){function t(){this.visible=!1,this.div=null,this.timeoutTillShow=3e3,this.showTimeout=null,this.message=null}var n=t.prototype;return n.show=function(){this.visible||(this.visible=!0,this.div)||(this.showTimeout&&(clearTimeout(this.showTimeout),this.showTimeout=null),setTimeout(function(){this.div||this.visible&&(this.showTimeout=null,this.div=document.createElement("div"),document.body.appendChild(this.div),this.div.style.position="absolute",this.div.style.right="10px",this.div.style.top="10px",this.div.style.width="350px",this.div.style.padding="10px",this.div.style.border="1px solid red",this.div.style.background="black",this.div.style.zIndex="100000",this.div.style.textAlign="center",this.div.style.color="white",this.div.style.font="Sans-serif",this.div.style.fontSize="15px",this.message?this.text(this.message):this.text(e.t("Connection lost")))}.bind(this),this.timeoutTillShow))},n.text=function(e){this.message=e,this.div&&(this.div.innerHTML="<p>"+e+"</p>")},n.hide=function(){this.visible=!1,this.div&&this.div.parentNode&&this.div.parentNode.removeChild(this.div),this.showTimeout&&clearTimeout(this.showTimeout),this.message=null,this.div=null,this.showTimeout=null},t}),define("CatLab/Webremote/Views/GamePaused",["CatLab/Webremote/Tools/Translator"],function(e){function t(){this.visible=!1,this.div=null,this.timeoutTillShow=1,this.showTimeout=null,this.message=null}var n=t.prototype;return n.show=function(){this.visible||(this.visible=!0,this.div)||(this.showTimeout&&(clearTimeout(this.showTimeout),this.showTimeout=null),setTimeout(function(){this.div||this.visible&&(this.showTimeout=null,this.div=document.createElement("div"),document.body.appendChild(this.div),this.div.style.position="fixed",this.div.style.right="0",this.div.style.top="0",this.div.style.width="100%",this.div.style.height="100%",this.div.style.padding="0",this.div.style.background="black",this.div.style.zIndex="100000",this.div.style.textAlign="center",this.div.style.color="white",this.div.style.font="Sans-serif",this.div.style.fontSize="2em",this.div.style.opacity=.9,this.message?this.text(this.message):this.text(e.t("Please wait, the game is paused.")))}.bind(this),this.timeoutTillShow))},n.text=function(e){this.message=e,this.div&&(this.div.innerHTML='<p style="height: 100%; padding: 20% 0">'+e+"</p>")},n.hide=function(){this.visible=!1,this.div&&this.div.parentNode.removeChild(this.div),this.showTimeout&&clearTimeout(this.showTimeout),this.message=null,this.div=null,this.showTimeout=null},t}),define("CatLab/Webremote/Synchronization/ClientRemoteView",[],function(){function e(e,t,n,i,o,r){this.controller=e,this.html="<p>Loading</p>",this.context={},this.viewId=t,this.name=n,this.groupId=void 0!==i?i:null,this.synchronizedData=o,this.createdAt=new Date,this.iframe=r,this.currentValues=[],this.buttons=[]}var o={},t=e.prototype;return t.render=function(e){var t;this.iframe?((t=document.createElement("iframe")).style.width="100%",t.style.height="100%",t.style.border="none",t.style.margin="0",t.style.padding="0",t.style.position="absolute",t.style.left="0",t.style.top="0",e.innerHTML="",e.appendChild(t),this.element=t.contentDocument.body):this.element=e,this.el=e,this.$el=e,this.element.innerHTML=this.html,this.update(),this.controller.components.attach(this,document.body),this.updateEvents(),setTimeout(function(){this.updateEvents(),window.scrollTo(0,1)}.bind(this),10),setTimeout(function(){this.updateEvents()}.bind(this),100),setTimeout(function(){this.updateEvents()}.bind(this),1e3)},t.updateEvents=function(){var h=this;function e(i,t,o){var r,s,a,l,c;h.shouldSetEvents(i,"touch")&&(l=!1,c=null,i.addEventListener("touchstart",function(e){return r=new Date,s={x:e.touches[0].pageX,y:e.touches[0].pageY},a={x:e.touches[0].pageX,y:e.touches[0].pageY},l=!0,c&&clearTimeout(c),t.apply(h,[i])}),i.addEventListener("touchmove",function(e){a={x:e.touches[0].pageX,y:e.touches[0].pageY}}),i.addEventListener("touchend",function(e){var t,n;if(s)return n=Math.abs(a.x-s.x),t=Math.abs(a.y-s.y),s=null,n=(new Date).getTime()-r.getTime()<300&&n<20&&t<20,c=setTimeout(function(){l=!1},1e3),o.apply(h,[i,n])}),i.addEventListener("mousedown",function(e){if(e.preventDefault(),!l)return t.apply(h,[i])}),i.addEventListener("mouseup",function(e){if(e.preventDefault(),!l)return o.apply(h,[i,!0])}))}for(var t=this.element.querySelectorAll("[data-button-id]"),n=0;n<t.length;n++)e(t[n],h.buttonDown,h.buttonUp),this.buttons.push(t[n]);for(t=this.element.querySelectorAll("[data-authentication-button]"),n=0;n<t.length;n++)e(t[n],function(){},h.authenticate);for(t=this.element.querySelectorAll("[data-value-id]"),n=0;n<t.length;n++)(t=>{var n,e;h.shouldSetEvents(t,"change")&&(n=t.getAttribute("data-value-id"),h.currentValues[n]=h.getDataValue(t),t.addEventListener("change",function(e){o[n]=new Date,h.syncValue(t)}),e=null,t.addEventListener("keyup",function(){e&&clearTimeout(e),e=setTimeout(function(){o[n]=new Date,h.syncValue(t)},1e3)}))})(t[n])},t.getDataValue=function(e){return"checkbox"===e.type?e.checked?1:0:e.value},t.syncValues=function(){for(var e=this.element.querySelectorAll("[data-value-id]"),t=0;t<e.length;t++)this.syncValue(e[t])},t.syncValue=function(e){var t=this.getDataValue(e),n=e.getAttribute("data-value-id");void 0!==this.currentValues[n]&&this.currentValues[n]===t||(this.currentValues[n]=t,this.controller.syncValue(n,this.getDataValue(e),this.viewId))},t.update=function(){for(var e=this.element.querySelectorAll("[data-button-decorator]"),t=0;t<e.length;t++)void 0===e[t].dataset.initialClasses&&(e[t].dataset.initialClasses=e[t].className);this.updateBigTextSizes()},t.updateBigTextSizes=function(){for(var e=this.element,t=e.querySelectorAll(".bigtext"),n={},i=0;i<t.length;i++){var o,r=t[i],s=r.getAttribute("data-bigtext-group");if(s){if(void 0===n[s]){n[s]=0;for(var a=e.querySelectorAll('.bigtext[data-bigtext-group="'+s+'"]'),l=0;l<a.length;l++)n[s]=Math.max(n[s],a[l].textContent.length)}o=n[s]}else o=r.textContent.length;r.setAttribute("data-bigtext-length",o)}},t.shouldSetEvents=function(e,t){return void 0===e["hasCatlabEventsAlready"+t]&&(e["hasCatlabEventsAlready"+t]=!0)},t.buttonDown=function(e){try{this.syncValues()}catch(e){console.error(e)}return this.controller.buttonDown(e.getAttribute("data-button-id"),this.viewId),!1},t.buttonUp=function(e,t){return this.controller.buttonUp(e.getAttribute("data-button-id"),this.viewId,t),!1},t.setLabel=function(e,t){for(var n=this.element.querySelectorAll("[data-button-label="+e+"]"),i=0;i<n.length;i++)n[i].innerHTML=t;this.update()},t.setClass=function(e,t){for(var n=this.element.querySelectorAll("[data-button-decorator="+e+"]"),i=0;i<n.length;i++){var o=n[i];o.className=o.dataset.initialClasses+" "+t}this.update()},t.domAppend=function(e,t){var n=document.getElementById(e);if(n){for(var i=this.stringToDom(t),o=[];i.firstChild;)o.push(n.appendChild(i.firstChild));try{for(var r=0;r<o.length;r++)this.controller.components.attach(this._currentView,o[r],!1)}catch(e){console.log(e)}5e3<(new Date).getTime()-this.createdAt.getTime()&&0<o.length&&void 0!==o[0].scrollIntoView&&o[0].scrollIntoView(),this.update(),this.updateEvents()}},t.domReplace=function(e,t){e=document.getElementById(e);e&&(e.innerHTML=t,this.controller.components.attach(this._currentView,e,!1),this.update(),this.updateEvents())},t.domAttribute=function(e,t,n){for(var i=document.querySelectorAll(e),o=0;o<i.length;o++)i[o].setAttribute(t,n)},t.changeValue=function(e){if(void 0!==o[e.id]){if((t=Math.abs(o[e.id].getTime()-(new Date).getTime()))<5)return}else var t=9999999999999;for(var n=this.element.querySelectorAll("[data-value-id="+e.id+"]"),i=0;i<n.length;i++)document.activeElement==n[i]&&t<5e3||(this.currentValues[e.id]=e.value,n[i].value=e.value)},t.vibrate=function(e){void 0!==window.navigator.vibrate&&void 0!==e.pattern&&Array.isArray(e.pattern)&&window.navigator.vibrate(e.pattern)},t.stringToDom=function(e){var t;return(t=0<=e.toLowerCase().indexOf("<tr")?document.createElement("tbody"):document.createElement("div")).innerHTML=e,t},t.stringInterpolateDataElements=function(e,o){return e.replace(/{{(.+?)}}/g,function(e,t,n,i){t=this.controller.resolveDataAttribute(t.trim());return t=o?o(t):t}.bind(this))},t.destroy=function(){this.syncValues(),void 0!==this.synchronizedData&&this.synchronizedData.destroy()},e}),define("CatLab/Webremote/Synchronization/DataItem",[],function(){function n(e,t,n){this.key=e,this.shared=t,this.side=n}var e=n.prototype;return e.setValue=function(e){this.value=e},e.canWrite=function(e){return!!this.shared||this.side===e},e.serialize=function(){return{key:this.key,shared:this.shared,side:this.side,value:this.value}},n.unserialize=function(e){var t=new n(e.key,e.shared,e.side);return t.setValue(e.value),t},n}),define("CatLab/Webremote/Synchronization/SynchronizedData",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Synchronization/DataItem"],function(e,o){function t(e,t,n){this.initializeEventable(),this.id=e,this.synchronizer=t,this.side=n,this.data={}}e=t.prototype=new e;return e.set=function(e,t,n){if(void 0===this.data[e])this.data[e]=new o(e,n,this.side);else if(!this.data[e].canWrite(this.side))throw"Trying to overwrite a non shared data attribute: "+e;this.data[e].setValue(t),this.emit(this.data[e])},e.processMessage=function(e){var t=e.key,n=e.side,i=e.value;if(void 0===this.data[t])this.data[t]=new o(t,e.shared,n);else if(!this.data[t].canWrite(n))throw"Trying to overwrite a non shared data attribute: "+t;this.data[t].setValue(i)},e.get=function(e){return void 0===this.data[e]?null:this.data[e].value},e.emit=function(e,t){void 0===t&&(t=this.synchronizer.emit);e=e.serialize();e.namespace=this.synchronizer.namespace,e.container=this.id,t("data:set",e)},e.refreshTarget=function(e){for(var t in this.data)this.data.hasOwnProperty(t)&&this.emit(this.data[t],e)},e.destroy=function(){this.synchronizer.destroy(this)},e.serialize=function(){var e,t={};for(e in this.data)this.data.hasOwnProperty(e)&&(t[e]=this.data[e].serialize());return t},e.unserialize=function(e){for(var t in this.data={},e)e.hasOwnProperty(t)&&(this.data[t]=o.unserialize(e[t]))},t}),define("CatLab/Webremote/Synchronization/DataSynchronizer",["CatLab/Webremote/Synchronization/SynchronizedData"],function(t){function e(e,t,n){this.namespace=e,this.emit=t,this.dataModels={},this.side=n}e.eventsToListenFor=["data:set"];var n=e.prototype;return n.checkNamespace=function(e){return void 0!==e.namespace&&e.namespace===this.namespace},n.processMessage=function(e,t){void 0!==t.container&&this.getFromIdentifier(t.container).processMessage(t)},n.getFromIdentifier=function(e){return void 0===this.dataModels[e]&&(this.dataModels[e]=new t(e,this,this.side)),this.dataModels[e]},n.destroy=function(e){e=e.id;void 0===this.dataModels[e]&&delete this.dataModels[e]},n.refreshTarget=function(e){for(var t in this.dataModels)this.dataModels.hasOwnProperty(t)&&this.dataModels[t].refreshTarget(e)},n.serialize=function(){var e,t={};for(e in this.dataModels)this.dataModels.hasOwnProperty(e)&&(t[e]=this.dataModels[e].serialize());return{dataModels:t}},n.unserialize=function(e){for(var t in e.dataModels)e.dataModels.hasOwnProperty(t)&&this.getFromIdentifier(t).unserialize(e.dataModels[t])},e}),define("CatLab/Webremote/Synchronization/EventHandler",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e,t){this.initializeEventable(),this.namespace=e,this.emit=t}t.eventsToListenFor=["event:trigger"];e=t.prototype=new e;return e.checkNamespace=function(e){return void 0!==e.namespace&&e.namespace===this.namespace},e.processMessage=function(e,t){if("event:trigger"===e)return this.processTriggerEvent(t)},e.processTriggerEvent=function(e){void 0!==e.event&&this.eventableTrigger(e.event,void 0===e.parameters?{}:e.parameters)},e.trigger=function(e,t){this.emit("event:trigger",{namespace:this.namespace,event:e,parameters:t})},e.refreshTarget=function(e){},e.serialize=function(){return{}},e.unserialize=function(e){},t}),define("CatLab/Webremote/Synchronization/CombinedEventHandler",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e,t){this.initializeEventable(),this.handlers=[]}return(t.prototype=new e).addHandler=function(e){this.handlers.push(e),e.on("*",function(e,t){this.trigger(t,e)}.bind(this))},t}),define("CatLab/Webremote/Synchronization/MessageQueue",[],function(){function e(){this.queue=[]}var t=e.prototype;return t.add=function(e,t,n){this.queue.push({action:e,data:t,ack:n})},t.flush=function(){var e=this.queue;return this.queue=[],e},t.compactFlush=function(){var i,o,r,s,a=[],e=this.flush();return 0===e.length?e:(o={user:{},group:{}},r=0,s={},e.forEach(function(e){if(r++,this.canCompact(e)){var t=null;void 0!==e.data.user?t="user":void 0!==e.data.group&&(t="group"),void 0===o[t][e.action]&&(o[t][e.action]=[]);for(var n=0;n<o[t][e.action].length;n++)if(i=o[t][e.action][n],this.isSimilarMessage(i.event,e)&&(void 0===s[e.data[t]]||s[e.data[t]]<i.index))return s[e.data[t]]=i.index,i.event.data[t].push(e.data[t]),void i.event.data._d.push(this.getDifference(i.event,e));Array.isArray(e.data[t])||(e.data[t]=[e.data[t]]),e.data._d=[{}],s[e.data[t]]=r,o[t][e.action].push({event:e,index:r})}a.push(e)}.bind(this)),a)},t.moveToEnd=function(e,t){e.push(e.splice(e.indexOf(t),1)[0])},t.isSimilarMessage=function(e,t){return e.action===t.action&&this.getCompareDataString(e)===this.getCompareDataString(t)},t.getDifference=function(e,t){var n,i={};for(n in t.data)if(t.data.hasOwnProperty(n)){switch(n){case"user":case"group":case"_d":case"_i":continue}void 0!==e.data[n]&&e.data[n]===t.data[n]||(i[n]=t.data[n])}return i},t.getCompareDataString=function(e){e=Object.assign({},e.data);return delete e.user,delete e.group,delete e.viewId,delete e._d,delete e._i,JSON.stringify(e)},t.canCompact=function(e){return null==e.ack&&void 0!==e.data&&(void 0!==e.data.user||void 0!==e.data.group)},e.unpack=function(e,t){if(void 0===e[t])return[e];var n=Array.isArray(e[t])?e[t]:[e[t]],i=[];void 0!==e._d&&(i=Array.isArray(e._d)?e._d:[e._d]);for(var o=[],r=0;r<n.length;r++){(s={})[t]=n[r];var s=Object.assign({},e,s,void 0!==i[r]?i[r]:{});delete s._d,o.push(s)}return o},Object.defineProperty(t,"length",{get:function(){return this.queue.length}}),e}),define("CatLab/Webremote/Tools/Proxy",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred"],function(n,i){function e(){}function o(e,t,n){var i=(()=>{for(var e=!1,t=0;t<r.length;t++){try{e=r[t]()}catch(e){continue}break}return e})();i&&(i.open(n?"POST":"GET",e,!0),n&&i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=function(){4==i.readyState&&(200==i.status||304==i.status?t(i):console.error("CatLab Remote HTTP error "+i.status))},4!=i.readyState)&&i.send(n)}var r=[function(){return new XMLHttpRequest},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml3.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")}];return e.prototype.get=function(e){n.getProxy()&&(e=n.getProxy()+encodeURIComponent(e));var t=new i;return o(e,function(e){t.resolve(e.responseText)}),t.promise()},new e}),define("CatLab/Webremote/Providers/Provider",["CatLab/Webremote/Synchronization/MessageQueue","CatLab/Webremote/Tools/Proxy","CatLab/Webremote/Tools/Deferred"],function(e,o,r){function t(){this.initializeProvider()}var n=t.prototype;return n.initializeProvider=function(){this.queue=new e,this.postInitializeQueue=[],this.scheduled=!1,this.initialized=!1,this.sendBurstDelay=10,this.maxQueueSize=2500,this.messageCounter=null,this.events={},this.viewNameIdentifierMap={}},n.getProviderSettings=function(){var e=new r;return e.resolve({}),e.promise()},n.setMessageCounter=function(e){this.messageCounter=e},n.initMaster=function(e){this.master=e},n.initPlayer=function(e){this.master=e},n.connect=function(){var e=new r;return e.resolve(),e.promise()},n.disconnect=function(){this.off()},n.setOAuthSettings=function(e){this.emit("oauth:set",e)},n.canProviderLoadExternalXml=function(){return!1},n.canProxyFiles=function(){return!1},n.loadViews=function(t,e,n){var i=new r;return void 0===e&&(e=!1),void 0===n&&(n=this),this.canProviderLoadExternalXml()&&!e?n.emit("view:load",{url:t},function(){i.resolve()}):o.get(t).then(function(e){this.parseViews(e,t,n).then(function(){i.resolve()})}.bind(this)),i.promise()},n.parseViews=function(e,t,n){var i=new r,o=void 0!==t;return void 0===n&&(n=this),o&&void 0!==this.viewNameIdentifierMap[t]?n.emit("view:load",{identifier:this.viewNameIdentifierMap[t]},function(){i.resolve()}):(n.emit("view:load",{xml:e},function(e){o&&e&&e.identifier&&(this.viewNameIdentifierMap[t]=e.identifier),i.resolve()}.bind(this)),this.onParseViews(e)),i.promise()},n.onParseViews=function(e){},n.registerComponent=function(e,t,n){t="string"==typeof t?t:t&&void 0!==t.innerHTML?t.innerHTML:String(t),e='<views><component id="'+e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")+'" xmlns="http://www.w3.org/1999/xhtml">'+t+"</component></views>";return this.parseViews(e,void 0,n)},n.toMaster=function(e,t,n){this.emit(e,t,n)},n.toPlayers=function(e,t,n){this.emit(e,t,n)},n.toPlayer=function(e,t,n,i){n.user=e.getId(),this.emit(t,n,i)},n.toGroup=function(e,t,n,i){n.group=e.getId(),this.emit(t,n,i)},n.emit=function(e,t,n){this.initialized?this.queue?(this.queue.add(e,t,n),this.queue.length>this.maxQueueSize?(clearTimeout(this.scheduled),this.scheduled=null,this.executeQueue()):this.scheduled||(this.scheduled=setTimeout(function(){this.scheduled=null,this.executeQueue()}.bind(this),this.sendBurstDelay))):this.emitOne(e,t,n):this.postInitializeQueue.push({action:e,data:t,ack:n})},n.createGroup=function(e,t,n,i){this.emit("group:create",{externalId:e,globalViews:t,shareColor:n,tags:i=void 0===i?[]:i})},n.executeQueue=function(){this.initialized&&this.emitAll()},n.setInitialized=function(){var e;for(this.initialized=!0;e=this.postInitializeQueue.shift();)this.emit(e.action,e.data,e.ack)},n.setup=function(e){this.emit("master:setup",e)},n.reset=function(e){this.emit("master:reset",null,function(){e()})},n.getStaticUrl=function(e){return e},n.reconnect=function(e,t,n,i){var o=new r;return this.emit("master:reconnect",{token:e,accessToken:t,gameConfig:n},function(){i(),o.resolve()}.bind(this)),o.promise()},n.off=function(){this.events={}},n.on=function(e,t){this._addEvent(e,t,!1),this._touchEvent(e)},n.once=function(e,t){this._addEvent(e,t,!0),this._touchEvent(e)},n._addEvent=function(e,t,n){void 0===this.events[e]&&(this.events[e]=[]),this.events[e].push({callback:t,once:n})},n._touchEvents=function(){for(var e in this.events)this.events.hasOwnProperty(e)&&this._touchEvent(e)},n._touchEvent=function(e){},n._trigger=function(e,n){var i;void 0!==this.events[e]&&(i=[],this.events[e].forEach(function(e){var t=e.callback;e.once&&i.push(e);try{t.apply(this,[n])}catch(e){console.error(e)}}),0<i.length)&&(i.unshift(this.events),function(e){for(var t,n,i=arguments,o=i.length;1<o&&e.length;)for(t=i[--o];-1!==(n=e.indexOf(t));)e.splice(n,1);return e}.apply(this,i))},n.getConnectURL=function(e){return null},n.getConnectToken=function(e){return null},n.tokenConnect=function(e){var t=new r;return t.resolve(),t.promise()},n.noTokenConnect=function(){var e=new r;return e.resolve(),e.promise()},n.restoreProviderSettings=function(e){},n.serializeProviderSettings=function(){return{}},n.proxyFile=function(e){var t=new r;return this.emit("file:proxy",{url:e},function(e){t.resolve({url:e.url})}.bind(this)),t.promise()},t}),define("CatLab/Webremote/Providers/SocketIO",["CatLab/Webremote/Providers/Provider","CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Tools"],function(e,s,a,t){function n(){this.initializeProvider(),this.userId=null,this.randomToken=t.getUuid(),this.loadBalancerSessionToken="connid",this.socket=null,this._registeredEvents={},this._host=null}var l=null,e=n.prototype=new e;return e.getProviderSettings=function(){var t=new a;return s.getServerList()?s.getServerList().getSelectedServer().done(function(e){t.resolve({host:e})}.bind(this)).fail(function(e){alert(e),t.reject(e)}.bind(this)):t.resolve({}),t.promise()},e.canProviderLoadExternalXml=function(){return!0},e.canProxyFiles=function(){return!0},e.connect=function(i,o){var t,r=new a;return this.log("Loading socket.io"),t=function(){this.log("Connecting to socket.io");var e,t=s.getSocketURL(),n=(this._host?t=this._host:void 0!==o.host&&o.host&&(t=(e=s.getProtocol())?e+"://"+o.host:"//"+o.host,this._host=t),this.socket=l(t+"/"+i+"?"+this.loadBalancerSessionToken+"="+this.randomToken,{withCredentials:!1,reconnection:!0}),!1);this.socket.on("connect_error",function(e){n?this._trigger("disconnect"):(this.socket.off(),this.socket.disconnect(),this.socket=null,r.reject())}.bind(this)),this.socket.once("connect",function(){n||(n=!0,this.setInitialized(),this.socket.io.on("reconnect",function(e){this._trigger("reconnect")}.bind(this)),this._touchEvents(),r.resolve())}.bind(this))}.bind(this),require(["socket.io-client"],function(e){l=e,t()}),r.promise()},e.disconnect=function(e){void 0===e&&(e=!0),this.initialized=!1,this.socket&&((e?this:(this._registeredEvents={},this.socket)).off(),this.socket.disconnect(),this.socket=null)},e.off=function(){this._registeredEvents={},this.events={},this.socket.off()},e.setUserId=function(e){return this.userId=e,this},e.emitAll=function(){var e,t=this.queue.compactFlush();if(t.length)for(;e=t.shift();)this.emitOne(e.action,e.data,e.ack)},e.emitOne=function(e,t,n){this.socket.emit(e,t,n),this.messageCounter&&this.messageCounter.outgoing()},e.log=function(){this.master.log.apply(arguments)},e.getStaticUrl=function(e){return e.indexOf("?")<0?e+="?":e+="&",e+(this.loadBalancerSessionToken+"="+this.randomToken)},e._detachEvents=function(e){this.socket&&this.socket.off(e)},e._touchEvent=function(t){this.socket&&void 0===this._registeredEvents[t]&&(this.socket.on(t,function(e){this._trigger(t,e)}.bind(this)),this._registeredEvents[t]=!0)},e._handleSocketIoEvent=function(e,t){switch(e){case"connect":case"disconnect":break;default:return this._trigger(e,t)}},e.getConnectURL=function(e){return s.getServerList()?s.getServerList().getConnectURL():e},e.getConnectToken=function(e){return s.getServerList()?s.getServerList().getConnectToken(e):e},e.tokenConnect=function(e){var t=new a,n={};if(s.getServerList())try{var i=s.getServerList().getFromToken(e);n.host=i.host,e=i.token}catch(e){return t.reject(),t.promise()}return this.connect("remote",n).fail(function(){t.reject()}).then(function(){t.resolve(e)}),t.promise()},e.restoreProviderSettings=function(e){void 0!==e.serverlist&&s.getServerList()&&s.getServerList().unserialize(e.serverlist),void 0!==e.host&&(this._host=e.host)},e.serializeProviderSettings=function(){var e={host:this._host};return s.getServerList()&&(e.serverlist=s.getServerList().serialize()),e},n}),define("CatLab/Webremote/SonicSync/Library/ring-buffer",[],function(){function t(e){this.array=[],this.maxLength=e}return t.prototype.get=function(e){return e>=this.array.length?null:this.array[e]},t.prototype.last=function(){return 0==this.array.length?null:this.array[this.array.length-1]},t.prototype.add=function(e){this.array.push(e),this.array.length>=this.maxLength&&this.array.splice(0,1)},t.prototype.length=function(){return this.array.length},t.prototype.clear=function(){this.array=[]},t.prototype.copy=function(){var e=new t(this.maxLength);return e.array=this.array.slice(0),e},t.prototype.remove=function(e,t){this.array.splice(e,t)},t}),define("CatLab/Webremote/SonicSync/Library/sonic-coder",[],function(){function e(e){this.freqMin=(e=e||{}).freqMin||18500,this.freqMax=e.freqMax||19500,this.freqError=e.freqError||50,this.alphabetString=e.alphabet||"\n abcdefghijklmnopqrstuvwxyz0123456789,.!?@*",this.startChar=e.startChar||"^",this.endChar=e.endChar||"$",this.alphabet=this.startChar+this.alphabetString+this.endChar}return e.prototype.charToFreq=function(e){var t=this.alphabet.indexOf(e),e=(-1==t&&(console.error(e,"is an invalid character."),t=this.alphabet.length-1),this.freqMax-this.freqMin),t=t/this.alphabet.length,e=Math.round(e*t);return this.freqMin+e},e.prototype.freqToChar=function(e){if(!(this.freqMin<e&&e<this.freqMax))if(this.freqMin-e<this.freqError)e=this.freqMin;else{if(!(e-this.freqMax<this.freqError))return console.error(e,"is out of range."),null;e=this.freqMax}var t=this.freqMax-this.freqMin,e=(e-this.freqMin)/t,t=Math.round(this.alphabet.length*e);return this.alphabet[t]},e}),define("CatLab/Webremote/SonicSync/Library/sonic-server",["./ring-buffer","./sonic-coder"],function(t,n){function e(e){this.peakThreshold=(e=e||{}).peakThreshold||-65,this.minRunLength=e.minRunLength||2,this.coder=e.coder||new n(e),this.timeout=e.timeout||300,this.debug=!!e.debug,this.peakHistory=new t(16),this.peakTimes=new t(16),this.callbacks={},this.buffer="",this.state=i,this.isRunning=!1,this.iteration=0}var i=1,o=2;return e.prototype.start=function(){try{navigator.mediaDevices||console.log("No mediadevices found"),navigator.mediaDevices.getUserMedia({audio:{optional:[{echoCancellation:!1}]}}).then(this.onStream_.bind(this)).catch(this.onStreamError_.bind(this))}catch(e){console.log(e)}},e.prototype.stop=function(){this.isRunning=!1,this.track.stop()},e.prototype.on=function(e,t){"message"==e&&(this.callbacks.message=t),"character"==e&&(this.callbacks.character=t)},e.prototype.setDebug=function(e){this.debug=e;e=document.querySelector("canvas");e&&e.parentElement.removeChild(e)},e.prototype.fire_=function(e,t){"function"==typeof e&&e(t)},e.prototype.onStream_=function(e){var t;void 0!==e.getTracks()[0]?(this.track=e.getTracks()[0],t=new AudioContext,e=(this.audioContext=t).createMediaStreamSource(e),t=t.createAnalyser(),e.connect(t),this.freqs=new Float32Array(t.frequencyBinCount),this.analyser=t,this.isRunning=!0,this.raf_(this.loop.bind(this))):console.log("No microphone found.")},e.prototype.onStreamError_=function(e){console.error("Audio input error:",e)},e.prototype.getPeakFrequency=function(){for(var e=-1/0,t=-1,n=this.freqToIndex(this.coder.freqMin);n<this.freqs.length;n++)this.freqs[n]>e&&(e=this.freqs[n],t=n);return e>this.peakThreshold?this.indexToFreq(t):null},e.prototype.loop=function(){this.analyser.getFloatFrequencyData(this.freqs),(this.iteration+1)%300==0&&this.restartServerIfSanityCheckFails();var e=this.getPeakFrequency();e?(e=this.coder.freqToChar(e),this.debug&&console.log("Transcribed char: "+e),this.peakHistory.add(e),this.peakTimes.add(new Date)):(e=this.peakTimes.last())&&new Date-e>this.timeout&&(this.state=i,this.debug&&console.log("Token",this.buffer,"timed out"),this.peakTimes.clear()),this.analysePeaks(),this.debug&&this.debugDraw_(),this.isRunning&&this.raf_(this.loop.bind(this)),this.iteration+=1},e.prototype.indexToFreq=function(e){return this.audioContext.sampleRate/2/this.freqs.length*e},e.prototype.freqToIndex=function(e){var t=this.audioContext.sampleRate/2;return Math.round(e/t*this.freqs.length)},e.prototype.analysePeaks=function(){var e=this.getLastRun();e&&(this.state==i?e==this.coder.startChar&&(this.buffer="",this.state=o):this.state==o&&(e!=this.lastChar&&e!=this.coder.startChar&&e!=this.coder.endChar&&(this.buffer+=e,this.lastChar=e,this.fire_(this.callbacks.character,e)),e==this.coder.endChar)&&(this.state=i,this.fire_(this.callbacks.message,this.buffer),this.buffer=""))},e.prototype.getLastRun=function(){for(var e=this.peakHistory.last(),t=0,n=this.peakHistory.length()-2;0<=n&&this.peakHistory.get(n)==e;n--)t+=1;return t>this.minRunLength?(this.peakHistory.remove(n+1,t+1),e):null},e.prototype.debugDraw_=function(){var e=document.querySelector("canvas");e||(e=document.createElement("canvas"),document.body.appendChild(e)),e.width=document.body.offsetWidth,e.height=480,drawContext=e.getContext("2d");for(var t=0;t<this.freqs.length;t++){var n=this.freqs[t]+400,n=e.height-n-1,i=e.width/this.freqs.length;drawContext.fillStyle="black",drawContext.fillRect(t*i,n,1,1)}},e.prototype.raf_=function(e){"undefined"==typeof window||window.chrome&&chrome.extension?setTimeout(e,1e3/60):requestAnimationFrame(e)},e.prototype.restartServerIfSanityCheckFails=function(){if(this.freqs[0]<-300)console.error("freqs[0] < -300. Restarting."),this.restart();else{for(var e=!0,t=0;t<10;t++)-100==this.freqs[t]&&(e=!1);e||(console.error("freqs[0:10] == -100. Restarting."),this.restart())}},e.prototype.restart=function(){},e}),define("CatLab/Webremote/SonicSync/Library/sonic-socket",["./sonic-coder"],function(t){var n=!1;function e(e){this.coder=(e=e||{}).coder||new t,this.charDuration=e.charDuration||.5,this.coder=e.coder||new t(e),this.rampDuration=e.rampDuration||.001,this.audioContext=new n}return"undefined"!=typeof window&&(n=window.AudioContext||window.webkitAudioContext||!1),e.prototype.send=function(e,t){e=this.coder.startChar+e+this.coder.endChar;for(var n,i=0;i<e.length;i++){var o=e[i],o=this.coder.charToFreq(o),r=this.audioContext.currentTime+this.charDuration*i;this.scheduleToneAt(o,r,this.charDuration)}t&&(n=this.charDuration*e.length,setTimeout(t,1e3*n))},e.prototype.scheduleToneAt=function(e,t,n){var i=this.audioContext.createGain(),n=(i.gain.value=0,i.gain.setValueAtTime(0,t),i.gain.linearRampToValueAtTime(1,t+this.rampDuration),i.gain.setValueAtTime(1,t+n-this.rampDuration),i.gain.linearRampToValueAtTime(0,t+n),i.connect(this.audioContext.destination),this.audioContext.createOscillator());n.frequency.value=e,n.connect(i),n.start(t)},e}),define("CatLab/Webremote/SonicSync/Client",["CatLab/Webremote/Config","CatLab/Webremote/SonicSync/Library/ring-buffer","CatLab/Webremote/SonicSync/Library/sonic-coder","CatLab/Webremote/SonicSync/Library/sonic-server","CatLab/Webremote/SonicSync/Library/sonic-socket","CatLab/Webremote/Tools/Deferred"],function(t,e,n,i,o,r){function s(e){this.options=t.getAudioSyncConfig(),this.alphabet=this.options.alphabet.split(""),this.controller=e}var a=s.prototype;return a.startListener=function(){this.stop();var e=new i(this.options);e.start(),e.on("message",this.onIncomingMessage.bind(this)),this.sonicServer=e},a.startSender=function(){this.sonicSocket=new o(this.options)},a.stop=function(){this.sonicServer&&this.sonicServer.stop()},a.sync=function(){var e=new r,t=this.generateRandomSequence(this.options.length);return this.sonicSocket.send(t+this.getParityLetter(t),function(){this.controller.trigger("sync:audio",{secret:t})}.bind(this)),e.promise()},a.generateRandomSequence=function(e){for(var t,n="",i="",o=0;o<e;o++){for(;t=Math.floor(Math.random()*this.alphabet.length),(i=this.alphabet[t])===n.substr(n.length-1,1););n+=i}return n},a.getParityLetter=function(e){for(var t=0,n=e.split(""),i=0;i<n.length;i++)t+=this.alphabet.indexOf(n[i]);e=t%this.alphabet.length;return n[n.length-1]===this.alphabet[e]&&(e=(e+1)%this.alphabet.length),this.alphabet[e]},a.onIncomingMessage=function(e){var t=e.substr(0,e.length-1),n=this.getParityLetter(t);n===e[e.length-1]?this.onMessage(t):console.log("Parity check failed, expected "+n+", ignoring message")},a.onMessage=function(e){this.controller.emit("sync:audio",{secret:e})},a.generateAlphabet=function(e){for(var t="",n=0;n<Math.min(e.length,9);n++)t+=n.toString();return t},s}),define("CatLab/Webremote/Tools/ClientSniffer",[],function(){function e(){this._canPlayWebM=null}var t=e.prototype;return t.isMobileBrowser=function(){var e,t;return!(!this.isCordova()&&(e=!1,t=navigator.userAgent||navigator.vendor||window.opera,!/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t))&&!/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4)))||e},t.isCordova=function(){return"undefined"!=typeof cordova},t.isInternetExplorer=function(){var e=window.navigator.userAgent,t=e.indexOf("MSIE ");return 0<t?parseInt(e.substring(t+5,e.indexOf(".",t)),10):0<e.indexOf("Trident/")?(t=e.indexOf("rv:"),parseInt(e.substring(t+3,e.indexOf(".",t)),10)):0<(t=e.indexOf("Edge/"))&&parseInt(e.substring(t+5,e.indexOf(".",t)),10)},t.supportsLocalStorage=function(){try{if(window.localStorage)return!0}catch(e){return!1}},t.canPlayWebM=function(){if(null===this._canPlayWebM){this._canPlayWebM=!1;try{var e=document.createElement("video");e.canPlayType&&(this._canPlayWebM=e.canPlayType('video/webm; codecs="vp8, vorbis"'))}catch(e){console.error(e)}}return this._canPlayWebM},new e}),define("CatLab/Webremote/Components/ImagePositionInputComponent",["CatLab/Webremote/Tools/ClientSniffer"],function(o){function e(e,t){this.element=t,this.remotePlayerView=e,this.positions=[],this.canvas=null,this.isLoaded=!1,this.isRotated=!1,this.buttons=null,this.pointCountContainer=null,this.draw()}var t=e.prototype;return t.draw=function(){this.element.innerHTML="",this.rotatedImageElement=null,this.buttons=null,this.circleRadius=this.element.getAttribute("circleRadius")||2,this.circleStroke=this.element.getAttribute("circleStroke")||Math.max(.5,this.circleRadius/5),this.circleStrokeColor=this.element.getAttribute("circleStrokeColor")||"red",this.circleFillColor=this.element.getAttribute("circleFillColor")||"rgb(255,255,0,0.3)",this.image=this.element.getAttribute("src"),this.image&&(this.element.innerHTML='<div class="image"><img /></div>',this.imageElement=this.element.querySelector("img"),this.imageElement.addEventListener("load",function(){this.isLoaded=!0,this.resizeImage(),setTimeout(function(){this.resizeImage()}.bind(this),100)}.bind(this)),this.imageElement.setAttribute("src",this.image),this.resizeImage(),this.imageElement.addEventListener("dragstart",function(e){e.preventDefault()}),this.svgContainer=document.createElement("div"),this.svgContainer.className="pointer-container",this.element.querySelector(".image").appendChild(this.svgContainer),this.resizeSvgContainer(),this.svgContainer.addEventListener("click",function(e){this.svgClick(e)}.bind(this)))},t.resizeSvgContainer=function(){var e=this.imageElement;this.isRotated&&this.rotatedImageElement&&(e=this.rotatedImageElement),this.svgContainer.style.position="absolute",this.svgContainer.style.zIndex="1",this.svgContainer.style.width=e.offsetWidth+"px",this.svgContainer.style.height=e.offsetHeight+"px",this.svgContainer.style.left=e.offsetLeft+"px",this.svgContainer.style.top=e.offsetTop+"px"},t.resizeImage=function(){var e,t,n,i;this.isLoaded&&(e=this.element.clientWidth,t=this.element.clientHeight,n=this.imageElement.naturalWidth,i=this.imageElement.naturalHeight,o.isMobileBrowser()&&"1"==this.element.getAttribute("rotate")?this.isRotated=e/t<1!=n/i<1:this.isRotated=!1,this.isRotated?this.element.classList.add("rotated"):this.element.classList.remove("rotated"),this.isRotated?(this.generateCanvas(),this.rotatedImageElement.style.display="",this.resizeSvgContainer(),this.imageElement.style.display="none"):this.rotatedImageElement&&(this.rotatedImageElement.style.display="none",this.imageElement.style.display=""),this.imageElement.style.maxWidth=e+"px",this.imageElement.style.maxHeight=t+"px",this.rotatedImageElement&&(this.rotatedImageElement.style.maxWidth=e+"px",this.rotatedImageElement.style.maxHeight=t+"px"),this.resizeSvgContainer())},t.generateCanvas=function(){var e,t,n,i,o,r,s,a;this.rotatedImageElement||(o=this.imageElement,e=this.imageElement.naturalWidth,t=this.imageElement.naturalHeight,(n=document.createElement("canvas")).width=t,n.height=e,i=n.getContext("2d"),o=o,r=n.width/2,s=n.height/2,a=0-Math.PI/2,i.setTransform(1,0,0,1,r,s),i.rotate(a),i.drawImage(o,-e/2,-t/2),this.rotatedImageElement=n,this.element.querySelector("div.image").appendChild(this.rotatedImageElement))},t.imageClick=function(e){var t=e.offsetX/this.imageElement.offsetWidth,e=e.offsetY/this.imageElement.offsetHeight;this.selectPosition(t,e)},t.svgClick=function(e){var t=e.offsetX/this.svgContainer.offsetWidth,e=e.offsetY/this.svgContainer.offsetHeight;this.isRotated?this.selectPosition(1-e,t):this.selectPosition(t,e)},t.canvasClick=function(e){var t=e.offsetX/this.rotatedImageElement.offsetWidth,e=e.offsetY/this.rotatedImageElement.offsetHeight;this.selectPosition(1-e,t)},t.selectPosition=function(e,t){0<this.getMaxPoints()&&this.positions.length>=this.getMaxPoints()||(this.positions.push({x:e,y:t}),this.drawCircles(),this.shouldConfirmPosition()?(this.syncPositionData(!1),this.showSubmitButton()):this.submit())},t.shouldConfirmPosition=function(){return"1"==this.element.getAttribute("confirm-position")},t.getMinPoints=function(){return this.element.getAttribute("min-points")&&0<parseInt(this.element.getAttribute("min-points"))?parseInt(this.element.getAttribute("min-points")):1},t.getMaxPoints=function(){return this.element.getAttribute("max-points")&&0<parseInt(this.element.getAttribute("max-points"))?parseInt(this.element.getAttribute("max-points")):1},t.showSubmitButton=function(){var e;this.buttons?this.positionSubmitButton():((e=document.createElement("div")).className="imagemap-buttons",e.innerHTML='<button data-action="submit" class="imagemap-button pulsating">'+(2<this.getMaxPoints()?'<span class="point-counter"></span>':"")+'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 22"><path d="M20.285 2l-11.285 11.567-5.286-5.011-3.714 3.716 9 8.728 15-15.285z"/></svg></button><button data-action="reset" class="imagemap-button"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 22"><path d="M24 20.188l-8.315-8.209 8.2-8.282-3.697-3.697-8.212 8.318-8.31-8.203-3.666 3.666 8.321 8.24-8.206 8.313 3.666 3.666 8.237-8.318 8.285 8.203z" /></button>',this.buttons=e,this.element.appendChild(this.buttons),this.positionSubmitButton(),this.buttons.querySelector("button[data-action=submit]").addEventListener("click",function(){this.submit()}.bind(this)),this.buttons.querySelector("button[data-action=reset]").addEventListener("click",function(){this.reset(),this.hideSubmitButton()}.bind(this)),this.pointCountContainer=this.buttons.querySelector(".point-counter"),this.updatePointCount())},t.updatePointCount=function(){var e;this.pointCountContainer&&(this.pointCountContainer.innerHTML=this.positions.length,this.positions.length<this.getMinPoints()?this.pointCountContainer.classList.add("insufficient"):this.pointCountContainer.classList.remove("insufficient"),e=this.buttons.querySelector("button[data-action=submit]"),this.positions.length>=this.getMinPoints()?(e.classList.add("pulsating"),e.classList.remove("disabled")):(e.classList.remove("pulsating"),e.classList.add("disabled")))},t.hideSubmitButton=function(){this.buttons.style.display="none"},t.positionSubmitButton=function(){this.buttons.style.display="",.5<this.positions[0].x?(this.buttons.classList.add("left"),this.buttons.classList.remove("right")):(this.buttons.classList.add("right"),this.buttons.classList.remove("left"))},t.submit=function(){this.syncPositionData(!0)},t.syncPositionData=function(e){this.positions.length<this.getMinPoints()||this.remotePlayerView.controller.syncValue("position",{x:0<this.positions.length?this.positions[0].x:null,y:0<this.positions.length?this.positions[0].y:null,p:this.positions,c:e},this.remotePlayerView.viewId)},t.drawCircles=function(){this.updatePointCount(),this.svgContainer.innerHTML="",0!==this.positions.length&&this.positions.forEach(function(t){var e=this.imageElement,n=t.x,i=t.y,o=e.offsetWidth,e=e.offsetHeight,r=(this.isRotated&&this.rotatedImageElement&&(n=t.y,i=1-t.x,o=this.rotatedImageElement.offsetWidth,e=this.rotatedImageElement.offsetHeight),o/100*this.circleRadius),s=Math.max(1,o/100*this.circleStroke),a="http://www.w3.org/2000/svg",l=document.createElementNS(a,"svg"),a=document.createElementNS(a,"circle");l.appendChild(a),l.addEventListener("click",function(e){e.preventDefault(),e.stopPropagation(),this.removePoint(t),0===this.positions.length&&this.hideSubmitButton()}.bind(this)),this.svgContainer.appendChild(l),a.setAttribute("cx",r+s),a.setAttribute("cy",r+s),a.setAttribute("r",r),a.setAttribute("stroke-width",s),a.setAttribute("stroke",this.circleStrokeColor),a.setAttribute("fill",this.circleFillColor),l.setAttribute("width",2*(r+s)),l.setAttribute("height",2*(r+s)),l.style.position="absolute",l.style.left=o*n-r-s+"px",l.style.top=e*i-r-s+"px"}.bind(this))},t.removePoint=function(e){e=this.positions.indexOf(e);-1<e&&this.positions.splice(e,1),this.drawCircles()},t.resize=function(){this.resizeImage(),this.drawCircles()},t.update=function(){this.draw()},t.destroy=function(){},t.reset=function(){this.positions=[],this.drawCircles()},e.css=" \t\t\t\timage-position-input {\t\t\t\t\tdisplay: flex; \t\t\t\t\tjustify-content: center;\t\t\t\t\talign-content: center;\t\t\t\t\talign-items: center;\t\t\t\t\twidth: 100%;\t\t\t\t\theight: 100%;\t\t\t\t\tposition: relative;\t\t\t\t\toverflow: hidden;\t\t\t\t} \t\t\t\t \t\t\t\timage-position-input .image { \t\t\t\t\ttext-align: center;\t\t\t\t\ttransform-origin: 0 0; \t\t\t\t} \t\t\t\timage-position-input .image img, \t\t\t\timage-position-input .image canvas { \t\t\t\t\tdisplay: block;\t\t\t\t\tmax-width: 100%;\t\t\t\t\tmax-height: 100%;\t\t\t\t\theight: auto;\t\t\t\t\twidth: auto; \t\t\t\t} \t\t\t\timage-position-input button.imagemap-button svg { \t\t\t\t\theight: 48px; \t\t\t\t\twidth: 48px; \t\t\t\t} \t\t\t\timage-position-input button.imagemap-button { \t\t\t\t\tmargin-left: 10px; \t\t\t\t\tposition: relative; \t\t\t\t} \t\t\t\timage-position-input button.imagemap-button.disabled svg {\t\t\t\t\tfill: gray;\t\t\t\t}\t\t\t\timage-position-input .imagemap-buttons { \t\t\t\t\tposition: absolute; \t\t\t\t\tright: 10px; \t\t\t\t\tbottom: 10px; \t\t\t\t\tz-index: 10; \t\t\t\t} \t\t\t\t\t\t\t\timage-position-input .imagemap-buttons.left {\t\t\t\t\tleft: 10px;\t\t\t\t\tright: auto;\t\t\t\t}\t\t\t\t\t\t\t\timage-position-input.rotated .imagemap-buttons {\t\t\t\t\ttransform: rotate(-90deg);\t\t\t\t\ttransform-origin: 100% 0;\t\t\t\t\ttop: 10px;\t\t\t\t\tright: 80px;\t\t\t\t\tbottom: auto;\t\t\t\t\tleft: auto;\t\t\t\t}\t\t\t\timage-position-input.rotated .imagemap-buttons.left {\t\t\t\t\tbottom: 80px;\t\t\t\t\ttop: auto;\t\t\t\t\tright: 80px; \t\t\t\t\tleft: auto;\t\t\t\t\ttransform-origin: 100% 0;\t\t\t\t}\t\t\t\timage-position-input button.pulsating .point-counter {\t\t\t\t}\t\t\t\timage-position-input .point-counter {\t\t\t\t\tfont-size: 1em;\t\t\t\t\tvertical-align: middle;\t\t\t\t\tposition: absolute;\t\t\t\t\ttop: -1em;\t\t\t\t\tleft: -1em;\t\t\t\t\tborder: 1px solid black;\t\t\t\t\tborder-radius: 100%;\t\t\t\t\tpadding: 0.5em;\t\t\t\t\tbackground: white;\t\t\t\t\tmin-width: 1em;\t\t\t\t}\t\t\t\timage-position-input .point-counter.insufficient {\t\t\t\t\tborder-color: red;\t\t\t\t\tcolor: red;\t\t\t\t}\t\t",e.selector="image-position-input",e}),define("CatLab/Webremote/Components/FullscreenButtonComponent",["CatLab/Webremote/Tools/Screenfull","CatLab/Webremote/Config"],function(e,t){function n(e,t,n){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=n,this.draw()}var i=n.prototype;return i.draw=function(){t.canFullscreen()&&e&&e.isEnabled&&!e.isFullscreen?(this.element.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" style="display: block" width="100%" height="100%" viewBox="0 0 24 24"><path d="M6.426 10.668l-3.547-3.547-2.879 2.879v-10h10l-2.879 2.879 3.547 3.547-4.242 4.242zm11.148 2.664l3.547 3.547 2.879-2.879v10h-10l2.879-2.879-3.547-3.547 4.242-4.242zm-6.906 4.242l-3.547 3.547 2.879 2.879h-10v-10l2.879 2.879 3.547-3.547 4.242 4.242zm2.664-11.148l3.547-3.547-2.879-2.879h10v10l-2.879-2.879-3.547 3.547-4.242-4.242z"/></svg>',this.element.addEventListener("click",function(){e.request(null,{navigationUI:"hide"})}.bind(this))):this.element.innerHTML=""},i.resize=function(){this.draw()},i.update=function(){this.draw()},i.destroy=function(){},n.css=" ",n.selector="fullscreen-button",n}),define("CatLab/Webremote/Components/ViewDefinedComponent",[],function(){function e(e,t){this.element=t,this.remotePlayerView=e,this.position=null,this.draw()}var t=e.prototype;return t.draw=function(){if(this.element){this.element.innerHTML="";for(var e=0;e<this.content.childNodes.length;e++)this.element.appendChild(this.content.childNodes[e].cloneNode(!0));this.componentContainer.attachComponents(this.remotePlayerView,this.element)}},t.update=function(){this.draw()},t.resize=function(){this.draw()},t.destroy=function(){},e.css=" ",e.selector="view-defined-component",e.content="",e}),define("CatLab/Webremote/Views/Popups/IframePopup",["CatLab/Webremote/Views/Popups/BasePopup"],function(e){function t(e){this.url=e}return(t.prototype=new e).renderContent=function(e){this.container.className+=" iframe";var t=document.createElement("iframe");t.src=this.url,t.style.height="99%",t.style.width="100%",t.style.borderWidth="0",e.appendChild(t),e.style.position="relative",e.style.height="100%",e.style.width="100%",e.style.boxSizing="border-box",e.style.overflow="auto",e.style.webkitOverflowScrolling="touch"},t}),define("CatLab/Webremote/Components/ModalIframeLink",["CatLab/Webremote/Views/Popups/IframePopup"],function(t){function e(e,t,n){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=n,this.draw()}var n=e.prototype;return n.draw=function(){this._clickHandler&&this.element.removeEventListener("click",this._clickHandler),this._clickHandler=function(){var e=this.element.getAttribute("href"),e=this.remotePlayerView.stringInterpolateDataElements(e,encodeURIComponent);new t(e).render(document.body)}.bind(this),this.element.addEventListener("click",this._clickHandler)},n.resize=function(){this.draw()},n.update=function(){this.draw()},n.destroy=function(){},e.css=" ",e.selector="modal-iframe-link",e}),define("CatLab/Webremote/Views/Popups/TextPopup",["CatLab/Webremote/Views/Popups/BasePopup"],function(e){function t(e){this.message=e}return(t.prototype=new e).renderContent=function(e){var t=(t=this.message).replace(/(?:\r\n|\r|\n)/g,"<br>");e.innerHTML=t},t}),define("CatLab/Webremote/Components/TooltipComponent",["CatLab/Webremote/Views/Popups/TextPopup"],function(e){function t(e,t,n){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=n,this.draw()}var n=t.prototype;return n.draw=function(){this._clickHandler&&this.element.removeEventListener("click",this._clickHandler),this._clickHandler=function(){new e(this.element.getAttribute("data-tooltip")).render(document.body)}.bind(this),this.element.addEventListener("click",this._clickHandler)},n.resize=function(){},n.update=function(){},n.destroy=function(){},t.css=" ",t.selector="[data-tooltip]",t}),define("CatLab/Webremote/Components/VirtualKeyboardComponent",["SimpleKeyboard","CatLab/Webremote/Config"],function(i,o){var r,s=!1,a=null,e=0;function l(){for(var e=document.querySelectorAll(".simple-keyboard"),t=0;t<e.length;t++)e[t].classList.add("hidden");a=null}function t(e,t,n){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=n,this.inputType=t.getAttribute("type")?t.getAttribute("type").toLowerCase():"text",this.draw()}var n=t.prototype;return n.draw=function(){(function(){if(!s){var e=document.createElement("link"),e=(e.type="text/css",e.rel="stylesheet",e.href=o.getVendorPath()+"simple-keyboard/build/css/index.css",document.head.appendChild(e),document.createElement("div"));e.className="simple-keyboard",document.body.appendChild(e),r=new i.default({onChange:function(e){a&&a.onKeyboardChange(e)}.bind(this),onKeyPress:function(e){switch(e){case"{shift}":case"{lock}":t="default"===r.options.layoutName?"shift":"default",r.setOptions({layoutName:t});break;case"{numbers}":case"{abc}":t="numbers"!==r.options.layoutName?"numbers":"default",r.setOptions({layoutName:t});break;case"{ent}":l();break;case"{arrowup}":a.increaseValue(1);break;case"{arrowdown}":a.increaseValue(-1)}var t}.bind(this),layoutName:"default",layout:{default:["q w e r t y u i o p","a s d f g h j k l","{shift} z x c v b n m {backspace}","{numbers} {space} {ent}"],shift:["Q W E R T Y U I O P","A S D F G H J K L","{shift} Z X C V B N M {backspace}","{numbers} {space} {ent}"],numbers:["1 2 3","4 5 6","7 8 9","{abc} 0 {backspace}"]},physicalKeyboardHighlight:!0,disableCaretPositioning:!1,mergeDisplay:!0,display:{"{numbers}":"123","{ent}":"⇩","{escape}":"esc ⎋","{tab}":"tab ⇥","{backspace}":"⌫","{capslock}":"caps lock ⇪","{shift}":"⇧","{controlleft}":"ctrl ⌃","{controlright}":"ctrl ⌃","{altleft}":"alt ⌥","{altright}":"alt ⌥","{metaleft}":"cmd ⌘","{metaright}":"cmd ⌘","{abc}":"ABC"}});for(var t=document.querySelectorAll(".simple-keyboard"),n=0;n<t.length;n++)t[n].classList.add("hidden");s=!0}})(),this.element.id||(this.element.id="input_"+ ++e),this.element.type="text",/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)&&(this.element.readOnly=!0),this.element.addEventListener("input",this.onInputChange.bind(this)),this.element.addEventListener("focus",this.onInputFocus.bind(this)),this.element.classList.contains("visible")&&this.onInputFocus()},n.hideKeyboard=function(){l()},n.showKeyboard=function(){var e=this,t=this.inputType,n=e.element;"number"===t?r.setOptions({inputName:n.id,layoutName:"numbers",layout:{default:["q w e r t y u i o p","a s d f g h j k l","{shift} z x c v b n m {backspace}","{numbers} {space} {ent}"],numbers:["1 2 3 {arrowup}","4 5 6 {arrowdown}","7 8 9 "+1.1.toLocaleString().substring(1,2),"{backspace} 0 {ent}"]}}):r.setOptions({inputName:n.id,layoutName:"default",layout:{default:["q w e r t y u i o p","a s d f g h j k l","{shift} z x c v b n m {backspace}","{numbers} {space} {ent}"],shift:["Q W E R T Y U I O P","A S D F G H J K L","{shift} Z X C V B N M {backspace}","{numbers} {space} {ent}"],numbers:["1 2 3","4 5 6","7 8 9","{abc} 0 {backspace}"]}});for(var i=document.querySelectorAll(".simple-keyboard"),o=0;o<i.length;o++)i[o].classList.remove("hidden");a=e,r.setInput(n.value,n.id)},n.onKeyboardChange=function(e){this.element.value=e;var t=new Event("change",{bubbles:!0});this.element.dispatchEvent(t),this.element.getAttribute("data-value-realtime")&&(t=this.element.getAttribute("data-value-id"))&&this.remotePlayerView.controller.syncValue(t,e,this.remotePlayerView.viewId)},n.onInputChange=function(){r.setInput(this.element.value,this.element.id)},n.onInputFocus=function(){this.showKeyboard()},n.setInputCaretPosition=function(e){this.element.setSelectionRange&&(this.element.focus(),this.element.setSelectionRange(e,e))},n.increaseValue=function(e){var t;"number"===this.inputType&&(t=(t=parseFloat(this.element.value))||0,this.element.value=t+e)},n.submit=function(){this.hideKeyboard()},n.resize=function(){this.draw()},n.update=function(){this.draw()},n.destroy=function(){this.hideKeyboard()},t.css=" .simple-keyboard { position: fixed; bottom: 0; display: block; } .simple-keyboard.hidden { display: none; } ",t.selector="input.virtual",t}),define("CatLab/Webremote/Components/TimerComponent",[],function(){function e(e,t){this.element=t,this.remotePlayerView=e,this.draw(),this.countdownInterval=setInterval(function(){this.tick()}.bind(this),100),this.startDate=Date.now(),this.targetDate=null,this.counterHtml=null,this.progessBar=null}var t=e.prototype;return t.draw=function(){var e,t=this.element;t.innerHTML="",this.targetDate=this.element.getAttribute("to"),this.targetDate&&((e=this.element.getAttribute("start"))&&(this.startDate=e),(e=document.createElement("div")).className="timer-container",this.counterHtml=document.createElement("div"),this.counterHtml.className="countdown",e.appendChild(this.counterHtml),this.progessBar=document.createElement("div"),this.progessBar.className="progress-bar",this.progessBar.innerHTML="&nbsp;",e.appendChild(this.progessBar),t.appendChild(e))},t.tick=function(){var e,t;this.targetDate&&this.counterHtml&&this.progessBar&&((e=this.targetDate-Date.now())<0?this.counterHtml.innerHTML="0":(t=(Date.now()-this.startDate)/(this.targetDate-this.startDate)*100,this.counterHtml.innerHTML=Math.ceil(e/1e3),this.progessBar.style.width=t+"%"))},t.resize=function(){},t.update=function(){this.draw()},t.clearInterval=function(){this.countdownInterval&&(clearInterval(this.countdownInterval),this.countdownInterval=null)},t.destroy=function(){this.clearInterval()},e.css=" timer-countdown { position: fixed; bottom: 0px; left: 0px; width: 100%; color: white; z-index: 1000; } timer-countdown .progress-bar { position:absolute; height: 3px; bottom: 0; background: #eca93b; } timer-countdown .countdown { display: none; } ",e.selector="timer-countdown",e}),define("CatLab/Webremote/Components/SmileyFlingerComponent",["CatLab/Webremote/Views/Blocks/CurrentSmiley"],function(i){function e(e,t,n){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=n,this.smileySlinger=new i(n.Webremote,!0,!0,!1),this.draw()}var t=e.prototype;return t.draw=function(){this.smileySlinger.render(this.element)},t.resize=function(){this.draw()},t.update=function(){this.draw()},t.destroy=function(){},e.css=" ",e.selector="smiley-flinger",e}),define("CatLab/Webremote/Components/CheatDetectionComponent",[],function(){function e(e,t,n){this.element=t,this.remotePlayerView=e,this.componentContainer=n,this._cheatCheckTimer=null,this._hiddenAt=null,e=t.getAttribute("mode"),this._mode="prepare"===e?"prepare":"detect",n=t.getAttribute("report"),this._report=!("false"===n),this._onVisibilityChange=this._handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this._onVisibilityChange),"detect"===this._mode&&this._consumePrepareState()}var t=null,n=e.prototype;return n._consumePrepareState=function(){var e;t&&(e=t,t=null,Date.now()-e.hiddenAt<6e4)&&this._triggerCheatDetected()},n._handleVisibilityChange=function(){document.hidden?(this._hiddenAt=Date.now(),"detect"===this._mode&&(null!==this._cheatCheckTimer&&clearTimeout(this._cheatCheckTimer),this._cheatCheckTimer=setTimeout(function(){this._cheatCheckTimer=null,Date.now()-this._hiddenAt<5e3&&this._triggerCheatDetected()}.bind(this),1500))):(this._hiddenAt=null,"detect"===this._mode&&null!==this._cheatCheckTimer&&(clearTimeout(this._cheatCheckTimer),this._cheatCheckTimer=null))},n._triggerCheatDetected=function(){this._report&&this.componentContainer&&this.componentContainer.Webremote&&this.componentContainer.Webremote.userEvents&&(this.componentContainer.Webremote.userEvents.trigger("cheat:detected",{}),this.componentContainer.Webremote.groupEvents.trigger("cheat:detected",{}))},n.draw=function(){},n.update=function(){},n.destroy=function(){document.removeEventListener("visibilitychange",this._onVisibilityChange),null!==this._cheatCheckTimer&&(clearTimeout(this._cheatCheckTimer),this._cheatCheckTimer=null),"prepare"===this._mode&&null!==this._hiddenAt&&document.hidden&&(t={hiddenAt:this._hiddenAt})},n.resize=function(){},e.selector="cheat-detection",e}),define("CatLab/Webremote/Components/Components",["./ImagePositionInputComponent","./FullscreenButtonComponent","./ViewDefinedComponent","./ModalIframeLink","./TooltipComponent","./VirtualKeyboardComponent","./TimerComponent","./SmileyFlingerComponent","./CheatDetectionComponent"],function(t,n,o,i,r,s,a,l,c){function e(e){this.components=[t,n,i,r,s,a,l,c],this.Webremote=e,this.viewDefinedComponents=[],this.existingComponents=[]}var h=e.prototype;return h.initialize=function(){for(var e=0;e<this.components.length;e++)this.initializeComponent(this.components[e])},h.initializeComponent=function(e){e.css;var t=document.createElement("style");t.attributes.type="text/css",t.innerHTML=e.css,document.head.appendChild(t)},h.resetViewDefinedComponents=function(){for(var e=0;e<this.viewDefinedComponents.length;e++)this.removeComponent(this.viewDefinedComponents[e])},h.destroyExistingComponentsBySelector=function(e){for(var t=this.existingComponents.length-1;0<=t;t--)this.existingComponents[t].constructor&&this.existingComponents[t].constructor.selector===e&&(this.existingComponents[t].destroy(),this.existingComponents.splice(t,1))},h.removeComponent=function(e){this.destroyExistingComponentsBySelector(e);for(var t=0;t<this.components.length;t++)if(this.components[t].selector===e)return void this.components.splice(t,1)},h.addComponent=function(e){0<=this.components.indexOf(e)||(this.components.push(e),this.initializeComponent(e))},h.addViewDefinedComponent=function(e,i){for(var t=0;t<this.components.length;t++)if(this.components[t].selector===e){this.destroyExistingComponentsBySelector(e),this.components.splice(t,1);break}function n(e,t,n){this.element=t,this.remotePlayerView=e,this.position=null,this.content=i,this.componentContainer=n,this.draw()}this.viewDefinedComponents.push(e),((n.prototype=new o).constructor=n).selector=e,n.content=i,this.components.push(n),this.Webremote._currentView&&this.attachComponent(this.Webremote._currentView,document.body,n)},h.attach=function(e,t,n){(n=void 0===n?!0:n)&&(this.existingComponents.forEach(function(e){e.destroy()}.bind(this)),this.existingComponents=[]),this.attachComponents(e,t)},h.resize=function(){this.existingComponents.forEach(function(e){e.resize()}.bind(this))},h.update=function(){this.existingComponents.forEach(function(e){e.update()}.bind(this))},h.attachComponents=function(e,t){for(var n=0;n<this.components.length;n++)try{this.attachComponent(e,t,this.components[n])}catch(e){console.log(e)}},h.attachComponent=function(e,t,n){for(var i=(t instanceof HTMLElement?t:t[0]).querySelectorAll(n.selector),o=0;o<i.length;o++){var r=new n(e,i[o],this);this.existingComponents.push(r)}},e}),!function(){var e,t;e=this,t=function(){var a,l,c,n,e,i=!1,t=window.navigator.userAgent,h=/([+-]?[0-9.]+)(vh|vw|vmin|vmax)/g,o=/(https?:)?\/\//,u=[].forEach,d=/MSIE [0-9]\./i.test(t),f=/MSIE [0-8]\./i.test(t),p=-1<t.indexOf("Opera Mini"),g=/(iPhone|iPod|iPad).+AppleWebKit/i.test(t)&&(e=t.match(/OS (\d)/))&&1<e.length&&parseInt(e[1])<10,m=-1<t.indexOf(" Android ")&&-1<t.indexOf("Version/")&&parseFloat((t.match("Android ([0-9.]+)")||[])[1])<=4.4,d=d||!!navigator.userAgent.match(/MSIE 10\.|Trident.*rv[ :]*1[01]\.| Edge\/1\d\./);try{new v("test")}catch(a){var v=function(e,t){var n;return t=t||{bubbles:!1,cancelable:!1,detail:void 0},(n=document.createEvent("CustomEvent")).initCustomEvent(e,t.bubbles,t.cancelable,t.detail),n};v.prototype=window.Event.prototype,window.CustomEvent=v}function b(){i&&(r(),setTimeout(function(){n.textContent=y(),n.parentNode.appendChild(n),window.dispatchEvent(new v("viewport-units-buggyfill-style"))},1))}function r(){return c=[],u.call(document.styleSheets,function(e){var t=(e=>{try{if(!e.cssRules)return}catch(e){if("SecurityError"!==e.name)throw e;return}for(var t=[],n=0;n<e.cssRules.length;n++){var i=e.cssRules[n];t.push(i)}return t})(e);!t||"patched-viewport"===e.ownerNode.id||"ignore"===e.ownerNode.getAttribute("data-viewport-units-buggyfill")||e.media&&e.media.mediaText&&window.matchMedia&&!window.matchMedia(e.media.mediaText).matches||u.call(t,s)}),c}function s(n){if(7===n.type){var e;try{e=n.cssText}catch(e){return}h.lastIndex=0,h.test(e)&&!o.test(e)&&(c.push([n,null,e]),a.hacks)&&a.hacks.findDeclarations(c,n,null,e)}else n.style?u.call(n.style,function(e){var t=n.style.getPropertyValue(e);n.style.getPropertyPriority(e)&&(t+=" !important"),h.lastIndex=0,h.test(t)&&(c.push([n,e,t]),a.hacks)&&a.hacks.findDeclarations(c,n,e,t)}):n.cssRules&&u.call(n.cssRules,function(e){s(e)})}function y(){var e=window.innerHeight,t=window.innerWidth;l={vh:e,vw:t,vmax:Math.max(t,e),vmin:Math.min(t,e)};var i,o,r=[],s=[];return c.forEach(function(e){var e=function(e,t,n){var i=[];n=n.replace(h,w),a.hacks&&(n=a.hacks.overwriteDeclaration(e,t,n)),t&&(i.push(e.selectorText),n=t+": "+n+";");for(var o=e.parentRule;o;)o.media?i.unshift("@media "+o.media.mediaText):o.conditionText&&i.unshift("@supports "+o.conditionText),o=o.parentRule;return{selector:i,content:n}}.apply(null,e),t=e.selector.length?e.selector.join(" {\n")+" {\n":"",n=new Array(e.selector.length+1).join("\n}");t&&t===i?(t&&!i&&(i=t,o=n),s.push(e.content)):(s.length&&(r.push(i+s.join("\n")+o),s.length=0),t?(i=t,o=n,s.push(e.content)):(r.push(e.content),o=i=null))}),s.length&&r.push(i+s.join("\n")+o),p&&r.push("* { content: normal !important; }"),r.join("\n\n")}function w(e,t,n){n=l[n];return parseFloat(t)/100*n+"px"}function _(e){return e.slice(0,e.indexOf("/",e.indexOf("://")+3))}return{version:"0.6.1",findProperties:r,getCss:y,init:function(e){if(!i){if((a=(e=!0===e?{force:!0}:e)||{}).isMobileSafari=g,a.isBadStockAndroid=m,!a.ignoreVmax||a.force||f||(d=!1),f||!a.force&&!g&&!d&&!m&&!p&&(!a.hacks||!a.hacks.required(a)))return window.console&&f&&console.info("viewport-units-buggyfill requires a proper CSSOM and basic viewport unit support, which are not available in IE8 and below"),{init:function(){}};var t,r,s;window.dispatchEvent(new v("viewport-units-buggyfill-init")),a.hacks&&a.hacks.initialize(a),i=!0,(n=document.createElement("style")).id="patched-viewport",document[a.appendToBody?"body":"head"].appendChild(n),t=function(){function e(){var e=this,t=arguments;clearTimeout(o),o=setTimeout(function(){n.apply(e,t)},i)}var n,i,o;n=b,i=a.refreshDebounceWait||100;window.addEventListener("orientationchange",e,!0),window.addEventListener("pageshow",e,!0),(a.force||d||(()=>{try{return window.self!==window.top}catch(e){return 1}})())&&(window.addEventListener("resize",e,!0),a._listeningToResize=!0),a.hacks&&a.hacks.initializeEvents(a,b,e),b()},r=0,s=function(){--r||t()},u.call(document.styleSheets,function(e){if(e.href&&_(e.href)!==_(location.href)&&"ignore"!==e.ownerNode.getAttribute("data-viewport-units-buggyfill")){r++;var t=e.ownerNode,n=s,e=t.href,i=n,o=new XMLHttpRequest;if("withCredentials"in o)o.open("GET",e,!0);else{if("undefined"==typeof XDomainRequest)throw new Error("cross-domain XHR not supported");(o=new XDomainRequest).open("GET",e)}o.onload=function(){var e=document.createElement("style");e.media=t.media,e.setAttribute("data-href",t.href),e.textContent=this.responseText,t.parentNode.replaceChild(e,t),n()},o.onerror=i,o.send()}}),r||t()}},refresh:b}},"function"==typeof define&&define.amd?define("viewport-units-buggyfill",[],t):"object"==typeof exports?module.exports=t():e.viewportUnitsBuggyfill=t()}(),!function(){var e,t;e=this,t=function(){var s=/calc\(/g,a=/["']/g,e=window.navigator.userAgent,i=(i=/MSIE [0-9]\./i.test(e))||!!navigator.userAgent.match(/MSIE 10\.|Trident.*rv[ :]*1[01]\.| Edge\/1\d\./);return{required:function(e){return e.isMobileSafari||i},initialize:function(){},initializeEvents:function(e,t,n){e.force||i&&!e._listeningToResize&&(window.addEventListener("resize",n,!0),e._listeningToResize=!0)},findDeclarations:function(e,t,n,i){var o,r;null!==n&&(o=e,r=t,e=i,"content"===n)&&-1<e.indexOf("viewport-units-buggyfill")&&e.replace(a,"").split(";").forEach(function(e){var t,e=e.split(":");2===e.length&&"viewport-units-buggyfill"!==(t=e[0].trim())&&(e=e[1].trim(),o.push([r,t,e]),s.test(e))&&(e=e.replace(s,"-webkit-calc("),o.push([r,t,e]))})},overwriteDeclaration:function(e,t,n){return n=i&&"filter"===t?n.replace(/px/g,""):n}}},"function"==typeof define&&define.amd?define("viewport-units-buggyfill.hacks",[],t):"object"==typeof exports?module.exports=t():e.viewportUnitsBuggyfillHacks=t()}(),define("CatLab/Webremote/Controllers/Webremote",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Tracker","CatLab/Webremote/Tools/Cookies","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Preloader","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Views/Popups/AuthenticationPopup","CatLab/Webremote/Views/Popups/SelectSmileyPopup","CatLab/Webremote/Views/Blocks/CurrentUser","CatLab/Webremote/Views/Blocks/CurrentSmiley","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/HashParser","CatLab/Webremote/Tools/Screenfull","CatLab/Webremote/Views/Alert","CatLab/Webremote/Views/Welcome","CatLab/Webremote/Views/ConnectionTrouble","CatLab/Webremote/Views/GamePaused","CatLab/Webremote/Synchronization/ClientRemoteView","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler","CatLab/Webremote/Synchronization/CombinedEventHandler","CatLab/Webremote/Providers/SocketIO","CatLab/Webremote/SonicSync/Client","CatLab/Webremote/Components/Components","viewport-units-buggyfill","viewport-units-buggyfill.hacks"],function(Config,Tracker,Cookies,Tools,Deferred,Smileys,Preloader,OAuth2,AuthenticationPopup,SelectSmileyPopup,CurrentUser,CurrentSmiley,UsersCollection,Storage,i18n,HashParser,screenfull,AlertPopup,WelcomePopup,ConnectionTroubleView,GamePausedView,ClientRemoteView,DataSynchronizer,EventHandler,CombinedEventHandler,SocketIOProvider,SonicSyncClient,Components,ViewportUnitsBuggyFill,ViewportUnitsBuggyFillHacks){var domelement=null,user,dynamicStylesheet,triggers=[];function addEvent(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent?e.attachEvent("on"+t,n):e["on"+t]=n}var Webremote=function(){};function getParameterByName(e,t){t=t||window.location.href,e=e.replace(/[\[\]]/g,"\\$&");e=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)").exec(t);return e?e[2]?decodeURIComponent(e[2].replace(/\+/g," ")):"":null}return Webremote.prototype={provider:null,element:null,gamedata:null,stylesheets:[],links:[],scripts:[],views:{},userData:null,userEvents:null,groupData:null,groupEvents:null,smiley:null,isOauth2Set:!1,color:null,_currentSmileyViews:[],_currentViewId:null,_currentViewViewId:null,_currentViewGroupId:null,_currentView:null,_connectingDfd:null,_connectedToken:null,_headless:!1,_allowAuthentication:!0,token:null,tokenAction:null,confirmTokenConnect:!1,disableConnectConfirmation:!1,initialize:function(e,t){void 0!==(t=void 0===t?{}:t).disableConnectConfirmation&&(this.disableConnectConfirmation=!!t.disableConnectConfirmation),void 0!==t.token?this.token=t.token:(this.token=getParameterByName("token"),this.token||(this.token=getParameterByName("t")),this.token&&!this.disableConnectConfirmation&&(this.confirmTokenConnect=!0),this.tokenAction=getParameterByName("a")),this.setContainer(e),this.showLoading(),this.sonicSync=null,this.components=new Components(this),this.components.initialize(),this._initialize(t).then(function(){setTimeout(function(){void 0===this.provider.showTokenForm||this.provider.showTokenForm?this.confirmTokenConnect?this.showConfirmTokenConnect().then(function(){this.trigger("remote:initialized"),this.handleTokenInput(this.token)}.bind(this)):(this.showTokenForm(),this.trigger("remote:initialized")):this.provider.noTokenConnect()}.bind(this),2),ViewportUnitsBuggyFill.init({hacks:ViewportUnitsBuggyFillHacks})}.bind(this)),this.setPlayerColor("#000000"),this.setOrientation(),addEvent(window,"resize",this.setOrientation.bind(this))},headless:function(e){return(e=void 0===e?{}:e).headless=!0,this._initialize(e)},_initialize:function(t){var n=new Deferred;return Config.set(t),Config.initialize(function(){Tracker.track("App","Initialize"),void 0===t.provider&&(t.provider=new SocketIOProvider),void 0!==t.headless&&(this._headless=!!t.headless),this.provider=t.provider,this.smileys=new Smileys(this.provider),this.provider.initPlayer(this),this.provider.on("disconnect",function(e){var t=this.getConnectionIssuesView();console.log("Connection lost... reconnecting"),t.show(),t.text(i18n.t("Connection lost... reconnecting"))}.bind(this)),this.provider.on("reconnect",function(e){this.provider.emit("user:reconnect",{id:this.gamedata.id,accessToken:this.gamedata.accessToken}),this._resendCurrentUserLogin(),this.getConnectionIssuesView().hide()}.bind(this)),this.provider.on("user:error",function(e){var t;this._connectingDfd&&(t=this._connectingDfd,this._connectingDfd=null,t.reject(e.message))}.bind(this)),this.provider.on("user:initialize",function(e){this.gamedata=e,this.provider.setUserId(e.id),this._storeGameData(e),this._connectingDfd&&(e=this._connectingDfd,this._connectingDfd=null,e.resolve())}.bind(this)),this.provider.on("view:load",function(e){this.loadViewsXML(e.xml)}.bind(this)),this.provider.on("view:reset",function(e){this.resetViews()}.bind(this)),this.provider.on("config:set",function(e){if(Config.set(e),this.sonicSync&&this.sonicSync.stop(),Config.useAudioSync())try{this.sonicSync=new SonicSyncClient(this),this.sonicSync.startListener()}catch(e){console.error(e)}}.bind(this)),this.provider.on("view:set",function(e){this.showView(e.id,e.viewId,e.group),this.handleCombinedMessages(e)}.bind(this)),this.provider.on("button:label",function(e){this.setLabel(e)}.bind(this)),this.provider.on("button:decorate",function(e){this.setClass(e)}.bind(this)),this.provider.on("oauth:set",function(e){Config.supportsAuthentication()&&(OAuth2.initialize(e),this.isOauth2Set=!0,UsersCollection.initialize(this,OAuth2),this.updateUser(),HashParser.getParameter("access_token"))&&(e=HashParser.getParameter("access_token"),UsersCollection.addFromAccessToken(e,function(e){e&&this.setUser(e)}.bind(this)),HashParser.clear())}.bind(this)),this.provider.on("color:set",function(e){this.setPlayerColor(e.color)}.bind(this)),this.provider.on("user:smiley",function(e){this.setSmiley(e.smiley)}.bind(this)),this.provider.on("smileys:taken",function(e){this.smileys.setTakenSmileys(e.smileys)}.bind(this)),this.provider.on("game:disconnect",function(e){AlertPopup(i18n.t("You have been disconnected from the game."),function(){window.location.reload()})}.bind(this)),this.provider.on("dom:append",function(e){this.domAppend(e)}.bind(this)),this.provider.on("dom:replace",function(e){this.domReplace(e)}.bind(this)),this.provider.on("dom:attribute",function(e){this.domAttribute(e)}.bind(this)),this.provider.on("dom:alert",function(e){AlertPopup(e.message)}),this.provider.on("dom:open",function(e){void 0!==e.url&&window.open(e.url)}),this.provider.on("value:change",function(e){this.changeValue(e)}.bind(this)),this.provider.on("device:vibrate",function(e){this.vibrate(e)}.bind(this)),this.provider.on("game:pause",function(e){this.pause(e)}.bind(this)),this.provider.on("game:unpause",function(e){this.unpause(e)}.bind(this)),this.preloader=new Preloader(this.provider),this.userData=new DataSynchronizer("user",this.emit.bind(this),"client"),this.groupData=new DataSynchronizer("group",this.emit.bind(this),"client"),this.userEvents=new EventHandler("user",this.emit.bind(this)),this.groupEvents=new EventHandler("group",this.emit.bind(this));var e=[this.userData,this.groupData],i=[this.userEvents,this.groupEvents];DataSynchronizer.eventsToListenFor.forEach(function(n){this.provider.on(n,function(t){e.forEach(function(e){e.checkNamespace(t)&&e.processMessage(n,t)})}.bind(this))}.bind(this)),EventHandler.eventsToListenFor.forEach(function(n){this.provider.on(n,function(t){i.forEach(function(e){e.checkNamespace(t)&&e.processMessage(n,t)})}.bind(this))}.bind(this)),this.events=new CombinedEventHandler,this.events.addHandler(this.userEvents),this.events.addHandler(this.groupEvents),n.resolve()}.bind(this)),n.promise()},reconnect:function(e){this.gamedata?(this.provider.emit("user:reconnect",{id:this.gamedata.id,accessToken:this.gamedata.accessToken}),this.provider.once("user:reconnect",function(){e()})):e()},connectProvider:function(e){return this.provider.tokenConnect(e)},_storeGameData:function(){var e=new Deferred,t=this._connectedToken;return Storage.set("gamestate_"+t,this.gamedata,function(){e.resolve()},864e5),e.promise()},_restoreGameData:function(){var t=new Deferred,e=this._connectedToken;return Storage.get("gamestate_"+e,function(e){e?(this.gamedata=e,t.resolve(!0)):t.resolve(!1)}.bind(this)),t.promise()},handleCombinedMessages:function(e){for(var t=[{name:"button:label",method:this.setLabel.bind(this)},{name:"button:decorate",method:this.setClass.bind(this)}],n=0;n<t.length;n++){var i=t[n].name,o=t[n].method;if(void 0!==e[i])for(var r=0;r<e[i].length;r++)o(e[i][r])}},emit:function(e,t){this.provider.toMaster(e,t)},getConnectionIssuesView:function(){return void 0===this.connectionTrouble&&(this.connectionTrouble=new ConnectionTroubleView),this.connectionTrouble},setGamePausedView:function(e){this.gamePaused=e},getGamePausedView:function(){return void 0===this.gamePaused?new GamePausedView:this.gamePaused},setContainer:function(e){domelement=e,this.element=e,dynamicStylesheet=document.createElement("style"),document.body.appendChild(dynamicStylesheet),document.body.className="catlab-remote"},on:function(e,t){void 0===triggers[e]&&(triggers[e]=[]),triggers[e].push(t)},trigger:function(e){var t=[].slice.apply(arguments);if(t.shift(),void 0!==triggers[e])for(var n=0;n<triggers[e].length;n++)triggers[e][n].apply(this,t)},loadViews:function(e,t){var n;t=t||function(){},this._headless?t():((n=new XMLHttpRequest).open("GET",Config.getProxy()+e,!0),n.onreadystatechange=function(){4==n.readyState&&200==n.status&&(this.loadViewsXML(n.responseText),t())}.bind(this),n.send())},resetViews:function(){this.showViewLoadingOverlay(),this.views={},this.components.resetViewDefinedComponents();for(var e=0;e<this.stylesheets.length;e++)try{var t=this.stylesheets[e];t.parentNode&&t.parentNode.removeChild(t)}catch(e){console.error(e)}for(e=0;e<this.links.length;e++)try{var n=this.links[e];n.parentNode&&n.parentNode.removeChild(n)}catch(e){console.error(e)}this.stylesheets=[]},injectXmlns:function(e){return e.replace(/<views(\s[^>]*)?>/,function(e){return/\bxmlns\s*=/.test(e)?e:e.replace("<views",'<views xmlns="http://www.w3.org/1999/xhtml"')})},loadViewsXML:function(e,t){if(t=t||function(){},!this._headless){var n;if(Tracker.track("App","Load Views"),e=this.injectXmlns(e),window.DOMParser?n=(new DOMParser).parseFromString(e,"text/xml"):((n=new ActiveXObject("Microsoft.XMLDOM")).async=!1,n.loadXML(e)),0===n.getElementsByTagName("views").length)return!1;for(var i=n.getElementsByTagName("views").item(0).getElementsByTagName("component"),o=0;o<i.length;o++)this.loadComponent(i.item(o));for(var r=n.getElementsByTagName("views").item(0).getElementsByTagName("view"),o=0;o<r.length;o++)this.loadView(r.item(o));var s=n.getElementsByTagName("views").item(0).getElementsByTagName("stylesheet");for(o=0;o<s.length;o++){var a=s.item(o),l=document.createElement("style");this.stylesheets.push(l),l.innerHTML=a.textContent,document.body.appendChild(l)}var c=n.getElementsByTagName("views").item(0).getElementsByTagName("link");for(o=0;o<c.length;o++){var h=c.item(o).getAttribute("href"),u=document.createElement("link");u.rel="stylesheet",u.type="text/css",u.media="all",u.href=h,this.links.push(u),document.getElementsByTagName("head")[0].appendChild(u)}for(s=n.getElementsByTagName("views").item(0).getElementsByTagName("style"),o=0;o<s.length;o++)this.stylesheets.push(s.item(o)),document.body.appendChild(s.item(o));var d=n.getElementsByTagName("views").item(0).getElementsByTagName("script");for(o=0;o<d.length;o++)this.scripts.push(d.item(o)),this.evalScript(d.item(o));return ViewportUnitsBuggyFill.refresh(),t(),!0}t()},evalScript:function(xml){var aWebremote=Webremote;!function(){try{var Webremote=aWebremote;eval(xml.textContent)}catch(e){console.error(e)}}.bind(window)()},loadView:function(e){var t=e.getAttribute("id"),n=document.createElement("div"),i=!1;e.getAttribute("iframe")&&"false"!==e.getAttribute("iframe").toLowerCase()&&(i=!0);for(var o=0;o<e.childNodes.length;o++)n.appendChild(e.childNodes[o].cloneNode(!0));n.id=t,n.className="view "+e.className,this.views[t]={iframe:i,html:(new XMLSerializer).serializeToString(n)},this._currentViewId===t&&this.showView(this._currentViewId,this._currentViewViewId,this._currentViewGroupId)},loadComponent:function(e){for(var t=e.getAttribute("id"),n=document.createElement("div"),i=0;i<e.childNodes.length;i++)n.appendChild(e.childNodes[i].cloneNode(!0));this.components.addViewDefinedComponent(t,n)},showView:function(e,t,n){var i,o;this._headless||(this._currentView&&this._currentView.destroy(),"remote:authenticate"!==e?(this._currentViewId=e,this._currentViewViewId=t,this._currentViewGroupId=n,void 0!==this.views[e]?(i=(n?this.groupData:this.userData).getFromIdentifier("view:"+t),o=this.views[e],this._currentView=new ClientRemoteView(this,t,e,n,i,o.iframe),this._currentView.html=o.html,this._currentView.render(this.element),this.hideViewLoadingOverlay(),this.updateUser(),Tracker.track("App","Show View",e),this.trigger("remote:view:show",{id:e,view:this._currentView}),this.trigger("view:set",this._currentView)):this.element.innerHTML='<div class="loading"><p>Please wait, loading...</p><p>(Loading view: '+e+")</div></p>"):this.showAuthenticationView())},updateUser:function(){Tracker.track("App","Set user");var e=document.getElementById("authentication");e&&new CurrentUser(this).render(e),this._currentSmileyViews=[],Config.useSmileys()?(this.setSmileySelectViews(),this.setSmileyViews()):this.removeSmileyViews()},setSmileySelectViews:function(){for(var e=document.getElementsByTagName("smiley-select"),t=0;t<e.length;t++){var n=!e[t].hasAttribute("flingable")||"false"!==e[t].getAttribute("flingable"),n=new CurrentSmiley(this,!0,n);n.render(e[t]),this.smiley&&n.setSmiley(this.smiley),this._currentSmileyViews.push(n)}},setSmileyViews:function(){for(var e=document.getElementsByTagName("smiley"),t=0;t<e.length;t++){var n=e[t].hasAttribute("changeable")&&"false"!==e[t].getAttribute("changeable"),i=e[t].hasAttribute("flingable")&&"false"!==e[t].getAttribute("flingable"),n=new CurrentSmiley(this,n,i);n.render(e[t]),this.smiley&&n.setSmiley(this.smiley),this._currentSmileyViews.push(n)}},removeSmileyViews:function(){for(var e=document.getElementsByTagName("smiley-select"),t=0;t<e.length;t++)e[t].parentNode.removeChild(e[t]);for(e=document.getElementsByTagName("smiley"),t=0;t<e.length;t++)e[t].parentNode.removeChild(e[t]);for(var n=document.getElementsByClassName("if-config-smileys"),t=0;t<n.length;t++)n[t].parentNode.removeChild(n[t])},popup:function(e){new WelcomePopup(e).render(domelement)},showAuthenticationPopup:function(e){e=e||!1;var t=new AuthenticationPopup(this);t.render(domelement),e&&t.connect()},showSmileyPopup:function(e,t){void 0===e&&(e=function(e){this.selectSmiley(e)}.bind(this)),void 0===t&&(t=!0);for(var n=domelement.querySelectorAll(".catlab-popup-container"),i=0;i<n.length;i++)n[i].parentNode.removeChild(n[i]);new SelectSmileyPopup(this,e,t).render(domelement)},showAuthenticationView:function(){Cookies.removeItem("last_token"),this.element&&(this.element.innerHTML='<p id="catlab-message">'+i18n.t("Please login.")+"</p>",OAuth2.link({fullscreen:!0}).then(function(e){e?(this.setUser(e),this.element.innerHTML='<p id="catlab-message">'+i18n.t("Welcome! You may now close this screen.")+"</p>",this.provider.disconnect(!1),window.close()):this.showAuthenticationView()}.bind(this)))},buttonDown:function(e,t){this.provider.toMaster("button:down",{id:e})},buttonUp:function(e,t,n){this.provider.toMaster("button:up",{id:e,click:n=void 0!==n&&n}),this.trigger("user:interaction")},syncValue:function(e,t,n){return this.provider.toMaster("value:change",{id:e,value:t,viewId:n}),!1},showLoading:function(){this.element&&(this.element.innerHTML='<p id="catlab-loading">Connecting...</p>')},showViewLoadingOverlay:function(){var e;this._headless||(this.hideViewLoadingOverlay(),(e=document.createElement("div")).id="catlab-view-loading-overlay",e.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;background:#000;display:flex;align-items:center;justify-content:center;z-index:99999;color:#fff;font-family:Arial,Helvetica,sans-serif;font-size:1.5em;",e.innerHTML="<p>Loading...</p>",document.body.appendChild(e))},hideViewLoadingOverlay:function(){var e=document.getElementById("catlab-view-loading-overlay");e&&e.parentNode&&e.parentNode.removeChild(e)},showConfirmTokenConnect:function(){var n=new Deferred,e=document.createElement("form"),t=(this.element.innerHTML="",this.element.appendChild(e),document.createElement("div")),i=(t.id="catlab-token-form",e.appendChild(t),document.createElement("h1")),i=(i.innerHTML=i18n.t("Welcome!"),t.appendChild(i),document.createElement("button"));return"l"===this.tokenAction?i.innerHTML=i18n.t("Login"):i.innerHTML=i18n.t("Join game"),i.type="submit",i.className="pulsating",t.appendChild(i),e.onsubmit=function(e){e.preventDefault();try{var t=(t=window.location.search.replace(/[?&]t=([^&]*)/gi,"")).replace(/[?&]token=([^&]*)/gi,"");window.history.pushState({},document.title,window.location.pathname+t+window.location.hash)}catch(e){}n.resolve()},n.promise()},showTokenForm:function(){var e=document.createElement("form"),t="undefined"!=typeof CONFIG_TOKEN?CONFIG_TOKEN:null,n=(!t&&this.token&&(t=this.token,this.token=null),!1),i=(t&&(n=!0),Cookies.getItem("last_token")),i=(!t&&i&&(t=i),document.createElement("div")),o=(i.id="catlab-token-form",e.innerHTML="",e.appendChild(i),document.createElement("input")),o=(o.type="tel",o.pattern="[0-9 ]{6,10}",o.name="token",o.id="token",o.value=t||"",o.placeholder=i18n.t("Enter code"),o.addEventListener("click",function(){this.setSelectionRange(0,this.value.length)}),i.appendChild(o),document.createElement("button"));o.innerHTML=i18n.t("Connect"),i.appendChild(o),n&&this.handleTokenInput(t),e.onsubmit=function(e){e.preventDefault();e=document.getElementById("token").value;if(e)return this.handleTokenInput(e),!1}.bind(this),this.element.innerHTML="",this.element.appendChild(e)},handleTokenInput:function(e){var t=this.connect(e);e!==Cookies.getItem("last_token")&&Cookies.removeItem("last_token"),t.then(function(){Cookies.setItem("last_token",e,.25)}.bind(this)),t.fail(function(e){this.showTokenForm(),screenfull.enabled&&screenfull.isFullscreen&&screenfull.exit(),AlertPopup(e)}.bind(this)),this.showLoading(),this.trigger("remote:token:submit"),this.trigger("user:interaction")},requestFullScreen:function(){screenfull.enabled&&!screenfull.isFullscreen&&screenfull.request()},connect:function(e){return e=e.replace(" ",""),null!==this._connectingDfd&&(this._connectingDfd.reject(),this._connectingDfd=null),this._connectingDfd=new Deferred,this._connectedToken=e,this._connectingDfd.fail(function(){this.provider.disconnect(!1)}.bind(this)),this.connectProvider(e).fail(function(){setTimeout(function(){this._connectingDfd.reject(i18n.t("Game not found. Please check your token."))}.bind(this),1)}.bind(this)).then(function(t){var n=!0;"0"===getParameterByName("reconnect")&&(n=!1),this._restoreGameData().then(function(e){e&&n?this.reconnect(function(){this._connectingDfd.resolve()}.bind(this)):this.provider.emit("user:join",{token:t})}.bind(this))}.bind(this)),this._connectingDfd.promise()},setLabel:function(e){this._currentView&&this._currentView.setLabel(e.id,Tools.nl2br(Tools.sanitize(e.label)))},setClass:function(e){this._currentView&&this._currentView.setClass(e.id,e.styles)},setPlayerColor:function(e){if(this.color=e,void 0!==dynamicStylesheet&&dynamicStylesheet){var t,n,i="",o=(dynamicStylesheet.innerHTML=(i+=".player-color-border { border-color:"+e+"; }")+(".player-color-background { background-color: "+e+"; }")+(".player-color { color: "+e+"; }"),{"theme-color":e,"msapplication-navbutton-color":e,"apple-mobile-web-app-status-bar-style":e});for(t in o)o.hasOwnProperty(t)&&((n=document.createElement("meta")).httpEquiv=t,n.content=o[t],document.getElementsByTagName("head")[0].appendChild(n))}},setSmiley:function(t){this.smiley=t,this._currentSmileyViews.forEach(function(e){e.setSmiley(t)})},getSmiley:function(){return this.smiley},selectSmiley:function(e){this.provider.toMaster("user:smiley",{smiley:e})},setUser:function(e){user=e,this.updateUser(),user?(this.provider.toMaster("user:login",{access_token:user.getAccessToken()}),Storage.set("currentuser",user.getAccessToken()),this.getSmiley()&&(e=user.getAvatarSmiley())&&this.selectSmiley(e)):(this.provider.toMaster("user:logout"),Storage.set("currentuser",null))},getUser:function(){return user},_resendCurrentUserLogin:function(){user&&this.provider.toMaster("user:login",{access_token:user.getAccessToken()})},listViews:function(){var e,t=[];for(e in this.views)this.views.hasOwnProperty(e)&&t.push({name:e});return t},getRandomText:function(e,t){var n="abcdefghijklmnopqrstuvwyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";void 0===t&&(t=40);for(var i="",o=(e=void 0===e?10:e)+Math.random()*t,r=0;r<o;r++)i+=n.charAt(Math.floor(Math.random()*n.length)),.8<Math.random()&&(r++,i+=" ");return i},randomLabels:function(e,t){for(var n=domelement.querySelectorAll("[data-button-label]"),i=0;i<n.length;i++)n[i].innerHTML=this.getRandomText(e,t);this.update()},setOrientation:function(){if(window.innerHeight>=window.innerWidth)try{document.body.classList.remove("landscape"),document.body.classList.add("portrait")}catch(e){document.body.className="portrait"}else try{document.body.classList.add("landscape"),document.body.classList.remove("portrait")}catch(e){document.body.className="landscape"}this.components.resize()},domAppend:function(e){this._currentView&&(this._currentView.domAppend(e.id,e.html),this.components.update())},domReplace:function(e){this._currentView&&(this._currentView.domReplace(e.id,e.html),this.components.update())},domAttribute:function(e){this._currentView&&(this._currentView.domAttribute(e.id,e.name,e.value),this.components.update())},changeValue:function(e){this._currentView&&this._currentView.changeValue(e)},vibrate:function(e){this._currentView&&this._currentView.vibrate(e)},pause:function(e){void 0===this._gamePausedView&&(this._gamePausedView=this.getGamePausedView()),this._gamePausedView.show()},unpause:function(e){void 0!==this._gamePausedView&&this._gamePausedView.hide()},log:function(e){Config.debug()&&console.log(e)},canAuthenticate:function(){return this.isOauth2Set},getGroupIds:function(){return void 0===this.gamedata.groups?[]:this.gamedata.groups},resolveDataAttribute:function(e){if("token"===e)return this._connectedToken;var n,e=(e="data."===e.substring(0,5)?e.substring(5):e).split("."),t=(2!==e.length&&e.unshift("any"),e.shift()),e=e.shift();if(t===user)return this.userData.getFromIdentifier("user").get(e);if("group"===t.substring(0,5)){var i,o=this.getGroupIds();if(0===o.length)return null;if("group"===t)return this.groupData.getFromIdentifier("group:"+o[0]).get(e);if("]"===t.substring(t.length,1))return void 0===o[i=t.substr(t.substring(6,t.length-1))]?null:this.groupData.getFromIdentifier("group:"+o[i]).get(e)}return"any"===t&&(n=["user."+e],this.getGroupIds().forEach(function(e,t){n.push("group["+t+"]")}.bind(this))),null}},Webremote}),define("CatLab/Webremote/Tools/Colorwheel",[],function(){var e={index:0,colors:[{color:"#d84a38",name:"red"},{color:"#4d90fe",name:"blue"},{color:"#35aa47",name:"green"},{color:"#ffb848",name:"yellow"},{color:"#852b99",name:"purple"},{color:"#555555",name:"brown"},{color:"#F87217",name:"orange"},{color:"#FBBBB9",name:"pink"}],initialize:function(){this.index=Math.floor(Math.random()*this.colors.length)},next:function(){var e=this.colors[this.index%this.colors.length];return this.index++,e}};return e.initialize(),e}),define("CatLab/Webremote/Collections/Users",["CatLab/Webremote/Tools/Colorwheel"],function(n){return function(){this.users=[],this.userMap={},this.externalPlayerOffset=0,this.setExternalPlayerOffset=function(e){this.externalPlayerOffset=e||0},this.add=function(e){var t;e.isColorSet()||(t=n.next(),e.setColor(t.color,t.name)),e.hasPlayerId()||e.setPlayerId(this.externalPlayerOffset+this.count()+1),this.users.push(e),this.userMap[e.getId()]=e},this.clear=function(){this.users=[],this.userMap={}},this.remove=function(e){this.users.splice(users.indexOf(e),1),void 0!==this.users[e.getId()]&&delete this.users[e.getId()]},this.getFromId=function(e){return void 0!==this.userMap[e]?this.userMap[e]:null},this.getAll=function(){return this.users},this.count=function(){return this.users.length},this.each=function(e){for(var t=0;t<this.users.length;t++)e(this.users[t])},this.not=function(n){var i=[];return this.each(function(e){for(var t=0;t<n.length;t++)if(n[t].getId()===e.getId())return void i.push(n[t])}),i}}}),define("CatLab/Webremote/Collections/Groups",["CatLab/Webremote/Tools/Colorwheel"],function(n){return function(){var t;this.groups=[],this.groupMap={},this.add=function(e){var t;e.colorSet||(t=n.next(),e.setColor(t.color,t.name)),this.groupMap[e.getId()]=e,this.groups.push(e)},this.clear=function(){this.groups=[],this.groupMap=[]},this.addUser=function(t){var n=!1;return t.groupIds.forEach(function(e){e=this.getFromId(e);e&&(n=!0,e.addUser(t),e.isShareColor())&&t.setColor(e.getColor(),e.getColorName())}.bind(this)),n},this.remove=function(e){this.groups.splice(this.groups.indexOf(e),1),delete this.groupMap[e.getId()]},this.getFromId=function(e){return void 0!==this.groupMap[e]?this.groupMap[e]:null},this.getAll=function(){return this.groups},this.each=function(e){for(t=0;t<this.groups.length;t++)e(this.groups[t])}}}),define("CatLab/Webremote/Models/ControlBase",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred"],function(e,o){function t(){}e=t.prototype=new e;return e.initializeControlBase=function(){this.initializeEventable()},e.resetViews=function(e){var t=new o;return this.emit("view:reset",{},function(){void 0!==e&&e(),t.resolve()}),t.promise()},e.replaceViews=function(e,t,n){var i=new o;return this.resetViews(function(){this.loadViews(e,t,function(){void 0!==n&&n(),i.resolve()})}.bind(this)),i.promise()},e.loadViews=function(e,t,n){return this.Webcontrol.provider.loadViews(e,n,this).then(function(){void 0!==t&&t()})},e.parseViews=function(e,t,n){return this.Webcontrol.provider.parseViews(e,t,this).then(function(){void 0!==n&&n()})},e.registerComponent=function(e,t){return this.Webcontrol.provider.registerComponent(e,t,this)},t}),define("CatLab/Webremote/Models/Control",[],function(){return function(n,i,e){var o,r,s,a,l=0,c={},h=n,u=[];this.id=n,this.decoration="",this.label="",this.isGlobal=e,this.pushed=function(){return 0===l},this.scale=function(){return l},this.update=function(e,t){0<l&&0===e?((t=void 0===t?!0:t)&&this.trigger("click"),this.trigger("up")):0===l&&0<e&&this.trigger("down"),l=e},this.getLabel=function(e){return(e=void 0===e?!0:e)?'<span class="control-label '+r+'">'+h+"</span>":h},this.setStaticLabel=function(e,t,n,i){return h=e,r=t,s=n,a=i,this},this.getLabelImage=function(){return s},this.getLabelEmoji=function(){return a},this.getLabelData=function(){return{label:h,type:r,image:s,emoji:a}},this.setLabel=function(e,t){return this.label=e,i.emit("button:label",{id:n,label:e}),this},this.decorate=function(e){return this.decoration=e,i.emit("button:decorate",{id:n,styles:e}),this},this.click=function(e){return this.on("click",e),this},this.on=function(e,t){return this.log("Setting trigger "+e),void 0===c[e]&&(c[e]=[]),c[e].push(t),this},this.trigger=function(e){this.log("Triggering "+e);var t=[];if(void 0!==c[e])for(this.log("Found "+c[e].length+" events"),o=0;o<c[e].length;o++)t.push(c[e][o]);for(o=0;o<t.length;o++)t[o](i);return this},this.hasTriggers=function(e){return void 0===e?0<Object.keys(c).length:void 0!==c[e]&&0<c[e].length},this.off=function(e,t){if(void 0===e)c={};else if(void 0===t)c[e]=[];else if(void 0!==c[e])for(o=0;o<c[e].length;o++)c[e][o]===t&&(c[e].splice(o,1),o--);return this},this.clear=function(){return this.clearEvents(),this.decoration=null,this.label=null,this},this.clearEvents=function(){return c={},this},this.addDomElement=function(e){var t=this,n=[];return n.push(e.addEventListener("click",function(){t.trigger("click")})),u.push({element:e,listeners:n}),this},this.clearDomElements=function(){for(var e=0;e<u.length;e++)for(var t=0;t<u[e].listeners.length;t++)u[e].element.removeEventListener("click",u[e].listeners[t]);return u=[],this},this.isLocalAuthentication=function(){return!1},this.refreshTarget=function(e){this.decoration&&e.emit("button:decorate",{id:n,styles:this.decoration}),this.label&&e.emit("button:label",{id:n,label:this.label})},this.log=function(e){i.log("["+this.id+"] "+e)}}}),define("CatLab/Webremote/Synchronization/MultipleTargetControl",[],function(){function e(e,t){this.id=e,this.remoteView=t,this.label=null,this.decoration=null}var t=e.prototype;return t.pushed=function(){var t=[];return this.remoteView.targets.forEach(function(e){t=t||e.control(this.id).pushed()}.bind(this)),t},t.scale=function(){var t,n=0;this.remoteView.targets.forEach(function(e){(t=e.scale())>n&&(n=t)}.bind(this))},t.update=function(t){this.remoteView.targets.forEach(function(e){e.control(this.id).update(t)}.bind(this))},t.getLabel=function(){return this.label},t.setLabel=function(t){return this.label=t,this.remoteView.targets.forEach(function(e){e.control(this.id).setLabel(t)}.bind(this)),this},t.decorate=function(t){return this.decoration=t,this.remoteView.targets.forEach(function(e){e.control(this.id).decorate(t)}.bind(this)),this},t.click=function(e){return this.on("click",e),this},t.on=function(t,n){return this.remoteView.targets.forEach(function(e){e.control(this.id).on(t,n)}.bind(this)),this},t.off=function(e){var t=arguments;return this.remoteView.targets.forEach(function(e){e.control(this.id).off.apply(e.control(this.id),t)}.bind(this)),this},t.refreshTarget=function(t){return this.remoteView.targets.forEach(function(e){e.control(this.id).refreshTarget(t)}.bind(this)),this},e}),define("CatLab/Webremote/Synchronization/RemoteView",["CatLab/Webremote/Models/Control","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Synchronization/MultipleTargetControl","CatLab/Webremote/Synchronization/DataSynchronizer"],function(e,t,n,i){function o(e,t,n,i,o){this.initializeEventable(),this.id=t,this.viewId=e,this.targets=[],this.Webcontrol=i,this.groupId=void 0!==o?o:null,this.controls={},this.valueMap={},this.newUserStack=[],this.factory=null,this.listeners=[],n.map(function(e){this.addTarget(e)}.bind(this))}t=o.prototype=new t;return t.clearValues=function(){this.valueMap={}},t.addTarget=function(e){this.targets.push(e),this.refreshTarget(e)},t.refreshTarget=function(t){var e,n={id:this.id,viewId:this.viewId};for(this.tmpid in this.groupId&&(n.group=this.groupId),t.emit("view:set",n),this.newUserStack.map(function(e){t.emit(e.action,e.data)}.bind(this)),t.controls)t.controls.hasOwnProperty(this.tmpid)&&t.controls[this.tmpid].isGlobal&&t.controls[this.tmpid].refreshTarget(t);for(this.tmpid in this.controls)this.controls.hasOwnProperty(this.tmpid)&&(void 0!==this.controls[this.tmpid].refreshTarget?this.controls[this.tmpid].refreshTarget(t):console.error("Unexpected control:",this.controls[this.tmpid]));for(e in this.valueMap)this.valueMap.hasOwnProperty(e)&&t.emit("value:change",{id:e,value:this.valueMap[e]})},t.emit=function(t,n){this.targets.map(function(e){e.emit(t,n)})},t.clearControls=function(){for(var e=this.Webcontrol.getViewLabels(this.currentView),t=0;t<e.length;t++)this.control(e[t].id).setStaticLabel(e[t].label,"mobile")},t.control=function(e){return void 0===this.controls[e]&&(this.controls[e]=new n(e,this)),this.controls[e]},t.trigger=function(e,t){"value:change"==e&&this.changeValue(t.id,t.value)},t.changeValue=function(e,t){this.valueMap[e]=t,this.emit("value:change",{id:e,value:t}),this.eventableTrigger("value:change",e,t)},t.refreshControls=function(){for(this.tmpid in this.controls)this.controls.hasOwnProperty(this.tmpid)&&this.controls[this.tmpid].refreshControl()},t.getValues=function(){return this.valueMap},t.log=function(e){this.Webcontrol.log(e)},t.domAppend=function(e,t){this._stackAndEmit("dom:append",{id:e,html:t})},t.domReplace=function(t,e){this._clearStack(function(e){return("dom:append"===e.action||"dom:replace"===e.action)&&e.data.id===t}),this._stackAndEmit("dom:replace",{id:t,html:e})},t.domAttribute=function(t,n,e){this._clearStack(function(e){return"dom:attribute"===e.action&&e.data.id===t&&e.data.name===n}),this._stackAndEmit("dom:attribute",{id:t,name:n,value:e})},t.vibrate=function(e){Array.isArray(e)?this.emit("device:vibrate",{pattern:e}):console.error("Vibrate pattern must be an array.")},t.listenTo=function(e,t,n){this.listeners.push(e.on(t,n))},t.stopListening=function(){this.listeners.forEach(function(e){e.unbind()})},t._clearStack=function(t){this.newUserStack=this.newUserStack.filter(function(e){return!t(e)})},t._stackAndEmit=function(e,t){this.newUserStack.push({action:e,data:t}),this.emit(e,t)},t.destroy=function(){this.stopListening(),this.factory.destroy(this)},o}),define("CatLab/Webremote/Synchronization/RemoteViewFactory",["CatLab/Webremote/Synchronization/RemoteView"],function(o){function e(){this.viewCounter=0,this.views={}}var t=e.prototype;return t.create=function(e,t,n,i){return this.viewCounter++,this.views[this.viewCounter]=new o(this.viewCounter,e,t,n,i),(this.views[this.viewCounter].factory=this).views[this.viewCounter]},t.createDummy=function(e,t){return this.create(e,[],t)},t.getFromId=function(e){return this.views[e]},t.destroy=function(e){e=e.id;delete this.views[e]},new e}),define("CatLab/Webremote/Models/Users/ControlUser",["CatLab/Webremote/Models/ControlBase","CatLab/Webremote/Models/User","CatLab/Webremote/Models/Control","CatLab/Webremote/Synchronization/RemoteViewFactory","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler"],function(e,t,n,i,o,r,s,a){function l(e,t){this.initializeControlBase(),(t=void 0===t?{}:t).id=e,t.playerId=null,this.initialize(t)}e=l.prototype=new e;return e.hasPlayerId=function(){return 0<this.playerId},e.setPlayerId=function(e){return this.playerId=e,this},e.control=function(e,t){return void 0===t&&(t=!1),void 0===this.controls[e]&&(this.controls[e]=new n(e,this,t)),this.controls[e]},e.getAvailableControls=function(){return["a","b","x","y","up","down","right","left","start","back"]},e.hasControl=function(e){return!0},e.setWebcontrol=function(e){this.Webcontrol=e},e.initialize=function(e){this.id=e.id,e.playerId&&(this.playerId=e.playerId),this.groups=[],this.currentView=null,this.color="orange",this.colorName="orange",this.colorSet=!1,this.tmpid=null,this.active=!1,this.smiley=null,this.email=null,this.nickname=null,this.userdata=e,this.profiledata={},this.access_token=null,this.user=null,this.master=!1,this.authenticated=!1,void 0!==e&&void 0!==e.groups?this.groupIds=e.groups:this.groupIds=[],this.controls={},this.dataSynchronizer=new s("user",this.emit.bind(this),"master"),this.data=this.dataSynchronizer.getFromIdentifier("user"),this.events=new a("user",this.emit.bind(this)),this.settings={}},e.setSettings=function(e){return this.settings=e,this},e.trigger=function(t,n){0<=s.eventsToListenFor.indexOf(t)?(this.dataSynchronizer.checkNamespace(n)&&this.dataSynchronizer.processMessage(t,n),this.getGroups().forEach(function(e){e.dataSynchronizer.checkNamespace(n)&&e.dataSynchronizer.processMessage(t,n)}.bind(this))):0<=a.eventsToListenFor.indexOf(t)?(this.events.checkNamespace(n)&&this.events.processMessage(t,n),this.getGroups().forEach(function(e){e.events.checkNamespace(n)&&e.events.processMessage(t,n)}.bind(this))):"button:down"===t?this.control(n.id).update(1):"button:up"===t?this.control(n.id).update(0,n.click):"user:login"===t?this.login(n):"user:logout"===t?this.logout(n):"user:smiley"===t?this.setSmiley(n.smiley):"sync:audio"===t&&this.eventableTrigger("sync:audio",n)},e.setSmiley=function(t){this.smiley=t;var n=null;this.getGroups().forEach(function(e){n=!0,e.setSmiley(t,this)}.bind(this)),n||this.Webcontrol.smileys.reserve(t,this.getIdentifier())?this.emit("user:smiley",{smiley:t}):this.emit("dom:alert",{message:o.t("Smiley is already taken. Please select a different smiley.")})},e.setNickname=function(e){return this.nickname=e,this.eventableTrigger("user:nickname",e),this},e.getNickname=function(){var e=this.getData();return this.nickname||(e&&e.username?e.username:this.playerId?"Player "+this.playerId:"Player "+this.id)},e.clearSmiley=function(){this.smiley=null,this.getGroups().forEach(function(e){e.clearSmiley(this)}.bind(this)),this.emit("user:smiley",{smiley:null})},e.getSmiley=function(){return this.smiley},e.getSmileyImage=function(){return this.Webcontrol.smileys.getImage(this.getSmiley())},e.getSmileyHtml=function(){return this.Webcontrol.smileys.getHtml(this.getSmiley())},e.getSmileyUrl=function(){return this.Webcontrol.smileys.getUrl(this.getSmiley())},e.login=function(e){},e.logout=function(e){},e.clearControls=function(){for(this.tmpid in this.setStaticLabels(),null!==this.currentView&&this.currentView.clearControls(),this.controls)!this.controls.hasOwnProperty(this.tmpid)||this.controls[this.tmpid].isGlobal||this.controls[this.tmpid].clear()},e.setStaticLabels=function(){},e.clearEvents=function(){this.clearControls(),this.clearEventableEvents()},e.emit=function(e,t,n){return this.Webcontrol.provider.toPlayer(this,e,t,n),!0},e.getId=function(){return this.id},e.getName=function(){return"User "+this.getId()},e.getType=function(){return"mobile"},e.getEntityType=function(){return"user"},e.getIcon=function(){return"fa fa-mobile-phone"},e.loginFromAuthUser=function(e,t){e={access_token:e.getAccessToken()};this.login(e,t)},e.login=function(t,n){var i=this;this._pendingLogin=null,this.Webcontrol.getOAuthClient(function(e){e?(this.setAccessToken(t.access_token),e.profile(i.access_token,function(e,t){e&&e.user?(i.authenticated=!0,this.setProfiledata(e.user),void 0!==n&&n()):(i.authenticated=!1,i.eventableTrigger("login:failed",i,t),void 0!==n&&((e=new Error("Could not load user profile"+(t?" ("+t+")":""))).status=t,n(e)))}.bind(this))):this._pendingLogin={data:t,callback:n}}.bind(this))},e.flushPendingLogin=function(){var e;this._pendingLogin&&(e=this._pendingLogin,this._pendingLogin=null,this.login(e.data,e.callback))},e.setAccessToken=function(e){this.access_token=e},e.getAccessToken=function(){return this.access_token},e.setProfiledata=function(e){e=void 0!==(this.profiledata=e).accessToken?e.accessToken:null,e=new t(e);void 0!==this.profiledata.id&&e.setId(this.profiledata.id),void 0!==this.profiledata.username&&e.setName(this.profiledata.username),void 0!==this.profiledata.avatar&&e.setAvatar(this.profiledata.avatar),this.setUser(e),this.eventableTrigger("login",this),this.eventableTrigger("user:nickname",this.getNickname())},e.isAuthenticated=function(){return this.authenticated},e.getData=function(){return this.profiledata},e.logout=function(e){this.profiledata=null,this.access_token=null,this.authenticated=!1},e.setColor=function(e,t){this.colorSet=!0,this.color=e,this.colorName=t,this.emit("color:set",{color:e,name:t})},e.isColorSet=function(){return this.colorSet},e.getColor=function(){return this.color},e.getColorName=function(){return this.colorName},e.isActive=function(){return this.active},e.toggleActive=function(){this.setActive(!this.active),this.setJoinLabel()},e.setJoinLabel=function(){!0===this.active?this.control("a").setLabel("LEAVE"):this.control("a").setLabel("JOIN")},e.setActive=function(e,t){this.active=e,this.eventableTrigger("active:change",e),this.active&&this.eventableTrigger("active:activate"),void 0!==t&&t&&this.setJoinLabel()},e.setView=function(e){return this.clearView(),this.currentView=i.create(e,[this],this.Webcontrol),this.currentView},e.clearView=function(e){var t;this.currentView&&(t=this.currentView,this.currentView=null,this.clearControls(),void 0!==e?setTimeout(function(){t.destroy()},e):t.destroy())},e.refreshView=function(){this.currentView&&this.currentView.refreshTarget(this)},e.getValues=function(){return this.currentView?this.currentView.getValues():null},e.clearValues=function(){this.currentView&&this.currentView.clearValues()},e.setUser=function(e){return this.usermodel=e,this},e.hasUser=function(){return void 0!==this.usermodel&&this.usermodel},e.getUser=function(){return this.usermodel},e.isLocalAuthentication=function(){return!0},e.log=function(e){this.Webcontrol&&this.Webcontrol.log("[u:"+this.getId()+"] "+e)},e.getGroups=function(){return this.groups},e.hasDisplay=function(){return!0},e.hasKeyboardInput=function(){return!0},e.hasTouchInput=function(){return!0},e.getIdentifier=function(){return{id:this.getId(),type:this.getEntityType()}},e.represents=function(e){if(void 0===e.id||void 0===e.type)throw"Attribute is not an identifier.";var t=this.getIdentifier();return t.type===e.type&&t.id===e.id},e.getPortalControls=function(){return{start:"start",back:"back",toggleActive:"up",authenticate:"y",left:"left",right:"right"}},e.isMainGroup=function(){if(0===this.groups.length)return!0;for(var e=0;e<this.groups.length;e++)if(this.groups[e].isMainGroup())return!0;return!1},e.isMaster=function(){return this.master},e.setMaster=function(e){var t=this.master!==(e=!!(e=void 0===e?!0:e));return this.master=e,t&&this.eventableTrigger("master:change"),this},e.getConnectToken=function(){return this.Webcontrol.getConnectToken()},e.getConnectTokenForDisplay=function(){return this.Webcontrol.getConnectTokenForDisplay()},e.serialize=function(){return{id:this.getId(),playerId:this.playerId,userdata:this.userdata,profiledata:this.profiledata,email:this.email,nickname:this.nickname,access_token:this.access_token,color:this.color,colorName:this.colorName,smiley:this.smiley,data:this.dataSynchronizer.serialize(),events:this.events.serialize()}},e.unserialize=function(e){void 0!==e.profiledata&&this.setProfiledata(e.profiledata),void 0!==e.playerId&&(this.playerId=e.playerId),void 0!==e.access_token&&this.setAccessToken(e.access_token),void 0!==e.color&&(this.color=e.color),void 0!==e.colorName&&(this.colorName=e.colorName),void 0!==e.nickname&&(this.nickname=e.nickname),void 0!==e.email&&(this.email=e.email),void 0!==e.smiley&&(this.smiley=e.smiley),void 0!==e.data&&this.dataSynchronizer.unserialize(e.data),void 0!==e.events&&this.events.unserialize(e.events)},l}),define("CatLab/Webremote/Models/GroupControl",[],function(){return function(e,i,t){var o,n,r,s,a,l,c=e,h={};this.label=null,this.decoration="",this.group=i,this.isGlobal=t,this.pushed=function(){for(r=i.getUsers(),o=0;o<r.length;o++)if(r[o].control(c,this.isGlobal).pushed())return!0;return!1},this.scale=function(){for(r=i.getUsers(),o=s=0;o<r.length;o++)(a=r[o].control(c,this.isGlobal)).value>s&&(s=a.value);return s},this.getLabel=function(e){return r=i.getUsers(),(o=0)<r.length?(a=r[o].control(c,this.isGlobal)).getLabel(e):null},this.getLabelImage=function(){return r=i.getUsers(),(o=0)<r.length?(a=r[o].control(c,this.isGlobal)).getLabelImage():null},this.setStaticLabel=function(e,t,n){for(r=i.getUsers(),o=0;o<r.length;o++)r[o].control(c).setStaticLabel(e,t,n);return null},this.setLabel=function(e,t){return this.label=e,i.emit("button:label",{id:c,label:e}),this},this.decorate=function(e){return this.decoration=e,i.emit("button:decorate",{id:c,styles:e}),this},this.click=function(e){return this.on("click",e),this},this.on=function(e,t){for(void 0===h[e]&&(h[e]=[]),h[e].push(t),this.log("Setting group trigger "+e),r=i.getUsers(),o=0;o<r.length;o++)r[o].control(c,this.isGlobal).on(e,t);return this},this.hasTriggers=function(e){for(r=i.getUsers(),o=0;o<r.length;o++)if(r[o].control(c,this.isGlobal).hasTriggers(e))return!0;return!1},this.off=function(e){for(delete h[e],r=i.getUsers(),o=0;o<r.length;o++)r[o].controls.hasOwnProperty(c)&&r[o].control(c,this.isGlobal).off(e);return this},this.clearEvents=function(){for(h={},r=i.getUsers(),o=0;o<r.length;o++)r[o].controls.hasOwnProperty(c)&&r[o].control(c,this.isGlobal).clearEvents();return this},this.clear=function(){for(h={},this.decoration=null,this.label=null,r=i.getUsers(),o=0;o<r.length;o++)r[o].controls.hasOwnProperty(c)&&r[o].control(c,this.isGlobal).clear();return this},this.isLocalAuthentication=function(){return!1},this.refreshControl=function(){for(r=i.getUsers(),o=0;o<r.length;o++){for(l in r[o].control(c,this.isGlobal).clearEvents(),h)if(h.hasOwnProperty(l))for(n=0;n<h[l].length;n++)r[o].control(c,this.isGlobal).on(l,h[l][n]);this.label&&r[o].control(c,this.isGlobal).setLabel(this.label)}return this},this.refreshTarget=function(e){this.decoration&&e.emit("button:decorate",{id:c,styles:this.decoration}),this.label&&e.emit("button:label",{id:c,label:this.label})},this.log=function(e){i.log("["+c+"] "+e)}}}),define("CatLab/Webremote/Models/ControlGroup",["CatLab/Webremote/Config","CatLab/Webremote/Models/ControlBase","CatLab/Webremote/Models/User","CatLab/Webremote/Models/Control","CatLab/Webremote/Models/GroupControl","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Synchronization/RemoteViewFactory","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler","CatLab/Webremote/Tools/Tools"],function(e,t,n,i,o,r,s,a,l,c){function h(e,t){this.initializeControlBase(),this.id=e,this.initialize(t)}t=h.prototype=new t;return t.setWebcontrol=function(e){this.Webcontrol=e},t.initialize=function(e){this.token=e.token,this.connectURL=e.connectURL,this.currentView=null,this.color="orange",this.colorName="orange",this.colorSet=!1,this.shareColor=!1,this.tmpid=null,this.active=!1,this.smiley=null,this.email=null,this.userdata=e,this.profiledata={},this.access_token=null,this.master=!1,this.users=[],this.controls=[],this.dataSynchronizer=new a("group",this.emit.bind(this),"master"),this.data=this.dataSynchronizer.getFromIdentifier("group:"+this.getId()),this.events=new l("group",this.emit.bind(this)),this.options={}},t.setOptions=function(e){return this.options=e,this},t.getOption=function(e){return void 0!==this.options[e]?this.options[e]:null},t.hasControl=function(e){return!0},t.setAccessToken=function(e){this.access_token=e},t.setProfiledata=function(e){this.profiledata=e,this.eventableTrigger("user:nickname",this.getNickname())},t.clearControls=function(){for(this.tmpid in null!=this.currentView&&this.currentView.clearControls(),this.controls)!this.controls.hasOwnProperty(this.tmpid)||this.controls[this.tmpid].isGlobal||(this.controls[this.tmpid].clear(),delete this.controls[this.tmpid])},t.clearEvents=function(){this.clearControls(),this.clearEventableEvents()},t.isMainGroup=function(){return this.Webcontrol.getConnectToken()===this.getConnectToken()},t.emit=function(e,t,n){return this.Webcontrol.provider.toGroup(this,e,t,n),!0},t.getId=function(){return this.id},t.getName=function(){return"Group "+this.getId()},t.setNickname=function(e){return this.nickname=e,this.eventableTrigger("user:nickname",e),this},t.getNickname=function(){return this.nickname||(this.getData().username?this.getData().username:"Group "+this.getId())},t.getType=function(){return"mobile"},t.getEntityType=function(){return"group"},t.getIcon=function(){return"fa fa-mobile-phone"},t.getData=function(){return this.profiledata},t.setColor=function(e,t,n){void 0===n&&(n=this.shareColor),this.colorSet=!0,this.color=e,this.colorName=t,this.shareColor=n,this.emit("color:set",{color:e,name:t,shareColor:n})},t.getColor=function(){return this.color},t.setShareColor=function(e){this.shareColor=e},t.isShareColor=function(){return this.shareColor},t.getColorName=function(){return this.colorName},t.setView=function(e){return this.clearView(),this.currentView=s.create(e,[this],this.Webcontrol,this.getId()),this.currentView},t.clearView=function(t){var e;this.currentView&&(e=this.currentView,this.currentView=null,this.clearControls(),void 0!==t?setTimeout(function(){e.destroy()},t):e.destroy(),this.users.forEach(function(e){e.clearView(t)}))},t.isAuthenticated=function(){return!1},t.isLocalAuthentication=function(){return!0},t.log=function(e){this.Webcontrol.log("[g:"+this.getId()+"] "+e)},t.getConnectToken=function(){return this.Webcontrol.provider.getConnectToken(this.token)},t.getConnectTokenForDisplay=function(){return c.getConnectTokenForDisplay(this.getConnectToken())},t.getConnectURL=function(){return this.Webcontrol.provider.getConnectURL(this.connectURL)},t.addUser=function(t){for(this.tmpid in c.findIndex(this.users,function(e){return e.id===t.id})<0&&this.users.push(t),c.findIndex(t.groups,function(e){return e.id===this.id})<0&&t.groups.push(this),this.currentView&&(this.currentView.refreshTarget(t),t.currentView=this.currentView),this.controls)this.controls.hasOwnProperty(this.tmpid)&&this.controls[this.tmpid].refreshControl();this.events.refreshTarget(t.emit.bind(t)),this.dataSynchronizer.refreshTarget(t.emit.bind(t)),this.smiley&&(t.emit("user:smiley",{smiley:this.smiley}),t.smiley=this.smiley),this.eventableTrigger("user:join",t)},t.removeUser=function(t){var e=c.findIndex(this.users,function(e){return e.id===t.id});0<=e&&this.users.splice(e,1)},t.getUsers=function(){return this.users},t.getIdentifier=function(){return{id:this.getId(),type:this.getEntityType()}},t.represents=function(e){if(void 0===e.id||void 0===e.type)throw"Attribute is not an identifier.";var t=this.getIdentifier();return t.type==e.type&&t.id==e.id},t.getValues=function(){return this.currentView?this.currentView.getValues():null},t.clearValues=function(){this.currentView&&this.currentView.clearValues()},t.control=function(e,t){return void 0===t&&(t=!1),void 0===this.controls[e]&&(this.controls[e]=new o(e,this,t)),this.controls[e]},t.isMaster=function(){return this.master},t.setMaster=function(e){return this.master=e=void 0===e?!0:e,this},t.hasDisplay=function(){return!0},t.hasKeyboardInput=function(){return!0},t.hasTouchInput=function(){return!0},t.getPortalControls=function(){return{start:"start",back:"back",toggleActive:"up",authenticate:"y",left:"left",right:"right"}},t.setOAuthSettings=function(e){this.emit("oauth:set",e)},t.setSmiley=function(e,t){this.Webcontrol.smileys.reserve(e,this.getIdentifier())?(this.emit("user:smiley",{smiley:e}),this.smiley=e):t.emit("dom:alert",{message:r.t("Smiley is already taken. Please select a different smiley.")})},t.clearSmiley=function(e){this.Webcontrol.smileys.unreserve(this.getIdentifier()),this.emit("user:smiley",{smiley:null}),this.smiley=null},t.getSmiley=function(){return this.smiley},t.getSmileyImage=function(){return this.Webcontrol.smileys.getImage(this.getSmiley())},t.getSmileyHtml=function(){return this.Webcontrol.smileys.getHtml(this.getSmiley())},t.getSmileyUrl=function(){return this.Webcontrol.smileys.getUrl(this.getSmiley())},t.setMaxUsers=function(e){this.emit("config:set",{maxUsers:e})},t.isActive=function(){return this.active},t.toggleActive=function(){this.active=!this.active,this.setJoinLabel()},t.setJoinLabel=function(){!0===this.active?this.control("a").setLabel("LEAVE"):this.control("a").setLabel("JOIN")},t.setActive=function(e,t){this.active=e,this.eventableTrigger("active:change",e),this.active&&this.eventableTrigger("active:activate")},t.serialize=function(){return{id:this.getId(),token:this.token,userdata:this.userdata,nickname:this.nickname,profiledata:this.profiledata,email:this.email,access_token:this.access_token,shareColor:this.shareColor,color:this.color,colorName:this.colorName,smiley:this.smiley,data:this.dataSynchronizer.serialize(),events:this.events.serialize()}},t.unserialize=function(e){void 0!==e.profiledata&&this.setProfiledata(e.profiledata),void 0!==e.access_token&&this.setAccessToken(e.access_token),void 0!==e.token&&(this.token=e.token),void 0!==e.shareColor&&(this.shareColor=e.shareColor),void 0!==e.color&&(this.color=e.color),void 0!==e.colorName&&(this.colorName=e.colorName),void 0!==e.nickname&&(this.nickname=e.nickname),void 0!==e.email&&(this.email=e.email),void 0!==e.smiley&&(this.smiley=e.smiley,this.emit("user:smiley",{smiley:this.smiley})),void 0!==e.data&&this.dataSynchronizer.unserialize(e.data),void 0!==e.events&&this.events.unserialize(e.events)},h}),define("CatLab/Webremote/Models/State",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Preloader"],function(n,i){function e(e){this.Webcontrol=e}var t=e.prototype;return t.reconnect=function(e,t){void 0!==e.provider&&this.Webcontrol.provider.restoreProviderSettings(e.provider),this.Webcontrol.disconnect(),setTimeout(function(){this.Webcontrol.initialize(n.getAll()).then(function(){this.Webcontrol._reconnect(e.token,e.accessToken,function(){this._setCollectionDetails(e.groups,this.Webcontrol._grouplibrary),this._setCollectionDetails(e.users,this.Webcontrol._userlibrary),this.Webcontrol.preloader=i.unserialize(this.Webcontrol.provider,e.preloader),t()}.bind(this))}.bind(this))}.bind(this),1)},t._setCollectionDetails=function(e,t){var n,i;if(void 0!==e)for(n=0;n<e.length;n++)(i=t.getFromId(e[n].id))?i.unserialize(e[n]):(console.log("Trying to set data for non existing user/group."),console.log(e[n]))},t.getData=function(){var t=[],n=(this.Webcontrol._grouplibrary.each(function(e){t.push(e.serialize())}.bind(this)),[]),e=(this.Webcontrol._userlibrary.each(function(e){n.push(e.serialize())}),{users:n,groups:t,token:this.Webcontrol._gamedata.token,accessToken:this.Webcontrol._gamedata.accessToken,preloader:this.Webcontrol.preloader.serialize()});return e.provider=this.Webcontrol.provider.serializeProviderSettings(),e},t.serialize=function(){var e=this.getData();return JSON.stringify(e)},t.unserialize=function(e){e=JSON.parse(e);this.reconnect(e)},e}),define("CatLab/Webremote/Messages/MessageBus",[],function(){function e(){this.controllerListeners=[],this.viewListeners=[]}var t=e.prototype;return t.toController=function(e,t){this.handleControllerMessage(e,t)},t.handleControllerMessage=function(e,t){for(var n=0;n<this.controllerListeners.length;n++)this.controllerListeners[n].handleIncomingMessage(e,t)},t.toView=function(e,t,n){this.handleViewMessage(e,t,n)},t.handleViewMessage=function(e,t,n){if(void 0===n)for(var i=0;i<this.viewListeners.length;i++)this.viewListeners[i].handleIncomingMessage(e,t);else this.viewListeners[n].handleIncomingMessage(e,t)},t.addControllerListener=function(e){if(void 0===e.handleIncomingMessage)throw new Error("Controller listener does not have a handleIncomingMessage");this.controllerListeners.push(e)},t.removeControllerListener=function(e){e=this.controllerListeners.indexOf(e);-1!==e&&this.controllerListeners.splice(e,1)},t.addViewListener=function(e){if(void 0===e.handleIncomingMessage)throw new Error("Controller listener does not have a handleIncomingMessage");e=this.viewListeners.push(e);this.toController("subscribe",{listener:e})},t.removeViewListener=function(e){e=this.viewListeners.indexOf(e);-1!==e&&this.viewListeners.splice(e,1)},t.destroy=function(){this.controllerListeners=[],this.viewListeners=[]},e}),define("CatLab/Webremote/Messages/NavigateableProxy",[],function(){function n(e){var t,n,i,o;return e?(o=n=t=null,{deviceId:t=void 0===(t="function"==typeof e.getDeviceId?e.getDeviceId():t)?null:t,kind:n=null===(n="function"==typeof e.getProfile&&(i=e.getProfile())&&i.kind?i.kind:n)&&"function"==typeof e.getKind?e.getKind()||null:n,userId:o=null===t&&"function"==typeof e.getId?void 0===(i=e.getId())?null:i:o}):null}function o(e){return e&&null!=e.actor?e.actor:null}function e(e,t){this.prefix=t||"",this.controls={navigation:["left","right"],toggle:["a"],manipulation:["down","up"],back:["b","back"]},this.views=[],this.keyInputCallbacks={},this.boundCallbacks={},e.addControllerListener(this),this.messageBus=e}var t=e.prototype;return t.handleIncomingMessage=function(e,t){if(e===this.prefix+"nav:controls")return this.controls=t.controls,this.views.forEach(function(e){this.refreshView(e)}.bind(this)),!0},t.addView=function(e){this.views.push(e),this.refreshView(e)},t.refreshView=function(n){this.reattachClick(n.control(this.controls.navigation[0]),this.previous),this.reattachClick(n.control(this.controls.navigation[1]),this.next),this.reattachClick(n.control(this.controls.manipulation[0]),this.down),this.reattachClick(n.control(this.controls.manipulation[1]),this.up),this.controls.toggle.forEach(function(t){void 0===this.keyInputCallbacks[t]&&(this.keyInputCallbacks[t]=function(e){this.keyInput(t,e)}),this.reattachClick(n.control(t),this.keyInputCallbacks[t].bind(this))}.bind(this)),this.controls.back.forEach(function(e){this.reattachClick(n.control(e),this.back)}.bind(this))},t.reattachClick=function(e,t){this.boundCallbacks[t]||(this.boundCallbacks[t]=t.bind(this)),e.off("click",this.boundCallbacks[t]),e.click(this.boundCallbacks[t])},t.keyInput=function(e,t){this.messageBus.toView(this.prefix+"nav:keyInput",{button:e,actor:n(t)})},t.previous=function(){this.messageBus.toView(this.prefix+"nav:previous")},t.next=function(){this.messageBus.toView(this.prefix+"nav:next")},t.up=function(e){this.keyInput("up",e)},t.down=function(e){this.keyInput("down",e)},t.back=function(e){this.messageBus.toView(this.prefix+"nav:back",{actor:n(e)})},t.destroy=function(){this.messageBus.removeControllerListener(this)},e.handleMessage=function(e,t,n,i){if(e.substring(0,(i=void 0===i?"":i).length)===i){switch(e=e.replace(i,"")){case"nav:previous":return n.previous(),!0;case"nav:next":return n.next(),!0;case"nav:keyInput":return n.keyInput(t.button,o(t)),!0;case"nav:back":return n.triggerBack(o(t)),!0}return!1}},e.describeActor=n,e}),define("CatLab/Webremote/Controllers/Portal",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Messages/MessageBus","CatLab/Webremote/Messages/NavigateableProxy"],function(n,e,t,o,i,r){function s(e,t){this.initializeEventable(),this.Webcontrol=e,this.options=t,this.controlDisabled=!1,this.users=[],this._externalActivePlayers=0,this._externalUsers=[],this.ensureOption("allowChangeNickname",!0),this.ensureOption("allowNonDisplayPlayers",!0),this.ensureOption("customFunctions",{}),this.ensureOption("minPlayers",1),this.ensureOption("maxPlayers",4),this.ensureOption("activePlayersPanel",!1),this.ensureOption("customViews",!1),this.ensureOption("authentication",e.AUTH_NOT_REQUIRED),this.ensureOption("localAuthenticatable",!1),this.ensureOption("allowPlayersWithoutDisplay",!0),this.ensureOption("start",function(){alert("This is where the game would start, if one would have set a 'start' option.")}),this.Webcontrol.getMessageBus().addControllerListener(this),this.messageBus=e.getMessageBus(),this.navigatableProxy=new r(this.messageBus,"portal:"),this.useCatLabViews()&&e.loadViews(n.getSocketURL(!0)+"/webremote/views/default.xml"),this.eventListeners=[],this.initialize()}e=s.prototype=new e;return e.handleIncomingMessage=function(e,t){switch(e){case"subscribe":this.updateUsers();break;case"start":this.startGame();break;case"back":this.back()}},e.initialize=function(){var e=this.Webcontrol.on("user:join",function(e){e.isMainGroup()&&(this.userConnect(e),this.eventListeners.push(e.on("login",function(){this.updateUsers()}.bind(this))))}.bind(this));this.eventListeners.push(e),this.Webcontrol.getUsers().forEach(function(e){e.isMainGroup()&&this.userConnect(e)}.bind(this))},e.updateUsers=function(){this.updateState();var e=this.serializePortalUsers();this.trigger("active:count",this.getActiveUsers().length),this.trigger("users:change",e),this.sendUsersToView(e)},e.serializePortalUsers=function(){var i=[];return this.Webcontrol.getUsers().forEach(function(e){var t,n;e.isMainGroup()&&(n=null,(t=e.getUser())&&(n={image:t.avatar}),i.push({active:e.isActive(),authenticated:e.isAuthenticated(),color:e.getColor(),profile:n,type:e.getType()}))}),i},e.sendUsersToView=function(e){this.messageBus.toView("users:update",{users:e.concat(this._externalUsers)})},e.updateState=function(){var e={activePlayers:this.countActiveUsers(),minPlayers:this.options.minPlayers,maxPlayers:this.options.maxPlayers,connectInstructions:this.getConnectInstructions(),startAndLoginInstructions:this.getStartAndLoginInstructions(),showInactivePlayers:this.supportInactivePlayers(),qrUrl:this.getQrCodeUrl()};this.messageBus.toView("state:change",{state:e})},e.ensureOption=function(e,t){void 0===this.options[e]&&(this.options[e]=t)},e.useCatLabViews=function(){return!1===this.options.customViews},e.getToggleView=function(e){var t="",t=this.supportInactivePlayers()?"catlab-portal-toggle":"catlab-portal";return this.isMaster(e)||(t+="-nostart"),t},e.addUser=function(e){e.clearControls(),this.users.push(e),this.supportInactivePlayers()||this.forceToggleableUser(e)||this.activateUser(e),this.trigger("users:update"),this.updateUsers()},e.activateUser=function(e){e.isActive()||(e.hasDisplay()||this.options.allowPlayersWithoutDisplay?(this.trigger("user:activate",e),e.setActive(!0,this.supportInactivePlayers()),this.updateUsers()):this.deactivateUser(e))},e.deactivateUser=function(e){e.isActive()&&(this.trigger("user:deactivate",e),e.setActive(!1,this.supportInactivePlayers()),this.updateUsers())},e.toggleActive=function(e){(this.supportInactivePlayers()||this.forceToggleableUser(e))&&(e.isActive()?this.deactivateUser(e):this.activateUser(e),this.trigger("users:update"))},e.forceToggleableUser=function(e){return!e.hasDisplay()&&!!this.options.allowPlayersWithoutDisplay},e.hasUsersWithoutDisplay=function(){if(this.options.allowPlayersWithoutDisplay)for(var e=0;e<this.users.length;e++)if(!this.users[e].hasDisplay())return!0;return!1},e.countActiveUsers=function(){return this.getActiveUsers().length+this._externalActivePlayers},e.setExternalActivePlayers=function(e){this._externalActivePlayers=e||0,this.updateState()},e.setExternalUsers=function(e){this._externalUsers=e||[],this.sendUsersToView(this.serializePortalUsers())},e.getActiveUsers=function(){for(var e=[],t=0;t<this.users.length;t++)this.users[t].isActive()&&e.push(this.users[t]);return e},e.userConnect=function(e){this.eventListeners.push(e.on("master:change",function(){this.updateUserView(e)},this)),this.addUser(e),this.updateUserView(e),this.trigger("user:connect",e)},e.updateUserView=function(e){var t=e.setView(this.getToggleView(e));this.controlDisabled||this.enableControls(e,t),this.enableDefaultPlayerControls(e,t)},e.disableControls=function(){this.controlDisabled=!0;for(var e=0;e<this.users.length;e++)this.users[e].clearControls()},e.enableControls=function(e,t){var n;void 0!==e?(n=e.getPortalControls(),t.control(n.toggleActive).click(function(){this.toggleActive(e)}.bind(this)),t.control(n.start).click(function(){this.startGame()}.bind(this)),t.control(n.back).click(function(){this.back()}.bind(this)),this.supportsLocalAuthentication()&&t.control(n.authenticate).click(function(){e.isLocalAuthentication()||this.authenticate(e)}.bind(this)),this.navigatableProxy.addView(t)):(this.controlDisabled=!1,this.users.forEach(function(e){this.updateUserView(e)}.bind(this)))},e.enableDefaultPlayerControls=function(n,i){if(i.control("name").setLabel(n.getNickname()),i.listenTo(n,"login",function(){i.control("name").setLabel(n.getNickname())}),this.options.allowChangeNickname&&i.control("change-nickname").click(function(){this.changeNickname(n).then(function(){this.updateUserView(n)}.bind(this))}.bind(this)),this.options.customFunctions)for(var e in this.options.customFunctions)this.options.customFunctions.hasOwnProperty(e)&&function(e,t){i.control(e).click(function(){t(n).then(function(){this.updateUserView(n)}.bind(this))}.bind(this))}.bind(this)(e,this.options.customFunctions[e])},e.changeNickname=function(t){var n=new o,i=t.setView("catlab-nickname");return i.changeValue("name",t.getNickname()),i.control("a").click(function(){var e=i.getValues().name;!e||32<e.length||(t.setNickname(e),n.resolve())}),n.promise()},e.supportInactivePlayers=function(){return this.options.activePlayersPanel},e.supportsLocalAuthentication=function(){return this.options.localAuthenticatable&&this.Webcontrol.canAuthenticate()},e.isMaster=function(e){return e.isMaster()},e.getPortalLabels=function(){var o={start:[],back:[],toggleActive:[],authenticate:[]};return this.Webcontrol._userlibrary.each(function(e){var t,n=e.getPortalControls();for(t in n)if(n.hasOwnProperty(t)){var i=e.control(n[t]).getLabelData();if(!i)continue;void 0===o[t]&&(o[t]=[]),-1===o[t].findIndex(function(e){return e.label===i.label&&e.image===i.image})&&o[t].push(i)}}.bind(this)),o},e.authenticate=function(e){this.activateUser(e),this.disableControls();var t=this.Webcontrol.authenticationController(e,{messageBus:this.messageBus});this.messageBus.toView("auth:open",{}),t.controller.setNavigatableUsers([e]),t.controller.on("close",function(){this.restoreInputAfterAuthentication(e),this.enableControls(),this.updateUsers()}.bind(this))},e.restoreInputAfterAuthentication=function(e){if(e&&"function"==typeof e.resumeListening&&e.resumeListening(),"undefined"!=typeof window&&"function"==typeof window.focus)try{window.focus()}catch(e){}if("undefined"!=typeof document&&document.body&&"function"==typeof document.body.focus)try{document.body.focus()}catch(e){}},e.countAuthenticated=function(e){void 0===e&&(e=!0);for(var t=0,n=0;n<this.users.length;n++)!this.users[n].isAuthenticated()||e&&!this.users[n].isActive()||t++;return t},e.countExternalAuthenticated=function(e){for(var t=0,n=0;n<this._externalUsers.length;n++){var i=this._externalUsers[n];i&&i.authenticated&&(e&&!i.active||t++)}return t},e.checkAuthentication=function(){var e=this.countAuthenticated();switch(this.options.authentication){case this.Webcontrol.AUTH_REQUIRED_ALL:return e===this.countActiveUsers();case this.Webcontrol.AUTH_REQUIRED_ONE:return 0<e+this.countExternalAuthenticated(!0);case this.Webcontrol.AUTH_REQUIRED_ONE_INACTIVE:return 0<this.countAuthenticated(!1)+this.countExternalAuthenticated(!1);case this.Webcontrol.AUTH_NOT_REQUIRED:return!0;default:throw"Authentication requirement "+this.options.authentication+" not found."}},e.startGame=function(){var e=this.countActiveUsers();if(e<this.options.minPlayers)this.messageBus.toView("alert",{message:"You need "+this.options.minPlayers+" players to start playing",localized:["You need %s players to start playing",this.options.minPlayers],id:"not-enough-players"});else if(e>this.options.maxPlayers)this.messageBus.toView("alert",{message:"Your license is limited to "+this.options.maxPlayers+" players",localized:["Your license is limited to %s players",this.options.maxPlayers],id:"exceeds-max-players"});else if(this.checkAuthentication())this.finalizeStart();else switch(this.options.authentication){case this.Webcontrol.AUTH_REQUIRED_ALL:this.messageBus.toView("alert",{message:"All active players must be authenticated.",localized:["All active players must be authenticated."],id:"not-all-authenticated"});break;case this.Webcontrol.AUTH_REQUIRED_ONE:case this.Webcontrol.AUTH_REQUIRED_ONE_INACTIVE:this.messageBus.toView("alert",{message:"At least one player must be authenticated.",localized:["At least one player must be authenticated."],id:"not-one-authenticated"})}},e.finalizeStart=function(){this.Webcontrol.setView("catlab-game-already-started",this.Webcontrol._userlibrary.not(this.getActiveUsers())),this.Webcontrol.setView("catlab-game-starting",this.getActiveUsers()),this.destroy(),this.options.start(this.getActiveUsers())},e.back=function(){void 0!==this.options.back&&(this.destroy(),this.options.back())},e.getConnectURL=function(){return this._publicConnectInfo&&this._publicConnectInfo.connectUrl?this._publicConnectInfo.connectUrl:this.Webcontrol.getConnectURL()},e.getConnectToken=function(){return this._publicConnectInfo&&this._publicConnectInfo.connectTokenForDisplay?this._publicConnectInfo.connectTokenForDisplay:this.Webcontrol.getConnectTokenForDisplay()},e.getQrCodeUrl=function(){var e=this.getConnectURL();return(e=e&&"http"!==e.substring(0,4)?"https://"+e:e)+"?t="+(this._publicConnectInfo&&this._publicConnectInfo.connectToken||this.Webcontrol.getConnectToken())},e._publicConnectInfo=null,e.setPublicConnectInfo=function(e){this._publicConnectInfo=e||null,this.updateState()},e.getUsers=function(){return this.users},e.setMinPlayers=function(e){return this.options.minPlayers=e,this.trigger("options:change"),this.updateState(),this},e.setMaxPlayers=function(e){return this.options.maxPlayers=e,this.trigger("options:change"),this.updateState(),this},e.getMessageBus=function(){return this.messageBus},e.getConnectInstructions=function(){return void 0!==this.Webcontrol.provider.getConnectInstructions?this.Webcontrol.provider.getConnectInstructions():["Use your tablet or smartphone to surf to %s and enter code %s.",this.getConnectURL(),this.getConnectToken()]},e.getStartAndLoginInstructions=function(){var e;return void 0!==this.Webcontrol.provider.getStartAndLoginInstructions?this.Webcontrol.provider.getStartAndLoginInstructions():this.hasUsersWithoutDisplay()?(e=this.getPortalLabels(),this.supportsLocalAuthentication()&&(this.showInactivePlayers||this.hasUsersWithoutDisplay())?["Press %s to join, %s to login and %s to start.",e.toggleActive,e.authenticate,e.start]:this.supportsLocalAuthentication()?["Press %s to login and %s to start.",e.authenticate,e.start]:this.showInactivePlayers||this.hasUsersWithoutDisplay()?["Press %s to join and %s to start.",e.toggleActive,e.start]:["Press %s to start.",e.start]):[""]},e.destroy=function(){this._destroyed||(this._destroyed=!0,this.trigger("destroy"),this.eventListeners&&this.eventListeners.forEach(function(e){e.unbind()}),this.messageBus.toView("portal:destroy"),this.messageBus.removeControllerListener(this),this.navigatableProxy.destroy())},s}),define("CatLab/Webremote/Controllers/RemoteAuthentication",["CatLab/Webremote/Controllers/OAuth2"],function(t){return function(e){e.setView("remote:authenticate"),e.on("user:join",function(e){e.on("login",function(e){t.addAccessToken(e.getAccessToken())}.bind(this))}.bind(this))}}),define("CatLab/Webremote/Controllers/Authentication",["CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Controllers/RemoteAuthentication","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Cookies","CatLab/Webremote/Messages/MessageBus","CatLab/Webremote/Messages/NavigateableProxy"],function(i,o,r,e,s,a,t,l){function n(e,t,n){this.initializeEventable(),this.messageBus=e.getMessageBus(),this.navigatableProxy=new l(this.messageBus,"auth:"),this.Webcontrol=e,this.user=t,this.user&&"function"==typeof this.user.control&&this.user.control("x").click(function(){this.messageBus.toView("auth:request-remove-selected-profile")}.bind(this)),r.on("update",this.updateUsers,this),i.on("update",function(){this.updateUsers()},this),this.messageBus.addControllerListener(this)}var c=null,h=null,e=n.prototype=new e;return e.handleIncomingMessage=function(e,t){switch(e){case"subscribe":this.getLoginUrl().then(function(e){this.loginUrl=e,this.messageBus.toView("auth:loginurl",{url:e})}.bind(this)),this.updateUsers();break;case"auth:close":this.close();break;case"auth:select-user":this.selectUser(t.user);break;case"auth:add-access-token":this.addAccessToken(t);break;case"auth:remove-user":this.removeUser(t.user)}},e.link=function(){i.link(function(e){this.selectUser(e)}.bind(this))},e.addAccessToken=function(t){t&&t.accessToken&&r.addFromAccessToken(t.accessToken,function(e){e&&t.select&&this.selectUser(e)}.bind(this))},e.updateUsers=function(){this.messageBus.toView("auth:users:update",{users:r.getAll().map(function(e){return{id:e.getId(),name:e.getName(),image:e.avatar}})})},e.selectUser=function(t){var n;(t=r.getFromId(t.id))&&(n=this).user.loginFromAuthUser(t,function(e){e?401!==e.status&&403!==e.status||r.remove(t):(a.setCookie("ctlb_ps_"+this.user.id,t.id),n.close())}.bind(this))},e.removeUser=function(e){(e=r.getFromId(e.id))&&(r.remove(e),this.updateUsers())},e.getUsers=function(){return r},e.close=function(){this._closed||(this._closed=!0,this.trigger("close"),this.messageBus.toView("auth:close"),this.destroy())},e.getLoginUrl=function(){var t,e,n=new s;return t=this.Webcontrol,(null!==c?((e=new s).resolve(c),e):(null===h&&(h=new s,t.newGroup().then(function(e){new o(c=e),e.setOAuthSettings(t.getOAuthSettings()),h.resolve(e)})),h)).promise().then(function(e){n.resolve(e.getConnectURL()+"/"+e.getConnectToken())}),n.promise()},e.setNavigatableUsers=function(e){e.forEach(function(e){this.navigatableProxy.addView(e)}.bind(this)),this.messageBus.toView("labels:update",{labels:{selectProfile:[this.user.control("a").getLabelData()],removeProfile:[this.user.control("x").getLabelData()],close:[this.user.control("b").getLabelData()]}})},e.attemptLastLogin=function(){var e=a.getCookie("ctlb_ps_"+this.user.id);if(e){e=r.getFromId(e);if(e)return this.selectUser(e),!0}return!1},e.destroy=function(){this.messageBus.toView("auth:destroy"),this.messageBus.removeControllerListener(this),this.navigatableProxy.destroy()},n}),define("CatLab/Webremote/Tools/MessageCounter",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e){this.interval=e||1e3,this.initializeEventable(),this.countIncoming=0,this.countOutgoing=0;var t,n,i=(new Date).getTime();setInterval(function(){t=(new Date).getTime(),n=t-i,i=t,this.trigger("tick",{in:this.countIncoming,out:this.countOutgoing,dt:n}),this.countIncoming=0,this.countOutgoing=0}.bind(this),this.interval)}e=t.prototype=new e;return e.incoming=function(){this.countIncoming++},e.outgoing=function(){this.countOutgoing++},t}),define("CatLab/Webremote/Views/Portal",["CatLab/Webremote/Config"],function(N){return function(e){var o=e.element||document.body,t=o,n=e.countdown||5e3,i=e.done||function(){alert("Game should start now... yet it doesn't.")},r=e["min-players"]||1,s=(r<1&&(r=1),e["max-players"]||1e3);s<r&&(s=r);var a,l,c,h,u,d,f,p,g,m,v,b=!e.customViews,y=[],w=!1,_=!1,C=null,O=this;function k(e){var t=document.createElement("div");return t.innerHTML=e.trim(),t.firstChild}function L(o){o.setView("catlab-portal-toggle"),o.control("join-game").click(function(){(e=>{if(A(e)){e.control("join-game").setLabel("JOIN");for(var t=e,n=0;n<y.length;n++)if(y[n].getId()==t.getId())return y.splice(n,1)}else e.control("join-game").setLabel("LEAVE"),y.push(e)})(o),M(),W(),U()}),o.control("start-game").click(function(){var e;w?U():y.length<r?D(r+" players are required to start the game. Please gather more friends."):y.length>s?D("This game can have only "+s+" players."):(e=n,U(),w=!0,(f=new Date).setTime((new Date).getTime()+e),u.style.display="",d=setInterval(V,100))}),o.control("down").click(function(){T(o)}),o.control("right").click(function(){T(o)}),o.control("left").click(function(){P(o)}),o.control("up").click(function(){P(o)}),o.control("a").click(function(){var e,t,i,n;e=o,_&&S(e)?(t=v.querySelector(".available-accounts li.selected"))&&(t=WebcontrolOAuthClient.getFromToken(t.getAttribute("data-accessToken")))&&(n=t.access_token,C.setUserData(n,t.user),E()):(w&&U(),_||(i=e,Webcontrol.getOAuthClient(function(n){n.onInit(function(){I(n)}),WebcontrolAccessKeyLibrary.init(function(){_=!0,C=i,m.style.display="",v.style.display="";var e=document.createElement("a"),t=(e.href="javascript:void(0);",e.textContent="Link new account",e.addEventListener("click",function(){n.getNewAccessToken(function(){I(n)})}),v.querySelector(".link-new-account"));t.innerHTML="",t.appendChild(e)}),I(n)})))}),o.control("b").click(function(){_&&S(o)&&(C.setUserData(!1),E())}),x(),W()}function P(e){if(_&&S(e)){for(var e=v.querySelector(".available-accounts"),t=e.querySelectorAll("li"),e=e.querySelector("li.selected"),n=0;n<t.length;n++)t[n].classList.remove("selected"),t[n].classList.add("unselected");e&&e.previousElementSibling?(e.previousElementSibling.classList.add("selected"),e.previousElementSibling.classList.remove("unselected")):0<t.length&&(t[t.length-1].classList.add("selected"),t[t.length-1].classList.remove("unselected"))}}function T(e){if(_&&S(e)){for(var e=v.querySelector(".available-accounts"),t=e.querySelectorAll("li"),e=e.querySelector("li.selected"),n=0;n<t.length;n++)t[n].classList.remove("selected"),t[n].classList.add("unselected");e&&e.nextElementSibling?(e.nextElementSibling.classList.add("selected"),e.nextElementSibling.classList.remove("unselected")):0<t.length&&(t[0].classList.add("selected"),t[0].classList.remove("unselected"))}}function S(e){return C&&e.getId()==C.getId()}function E(){m.style.display="none",v.style.display="none",_=!1,C=null}function I(e){var t=v.querySelector(".available-accounts");t.innerHTML="";for(var n=e.listUsers(),i=0;i<n.length;i++){var o=document.createElement("li");o.textContent=n[i].user.username,o.className="unselected",o.setAttribute("data-accessToken",n[i].access_token),t.appendChild(o)}}function W(){if(0<Webcontrol.getControlLabels("join-game").length){for(var e=document.querySelectorAll(".buttoninstructions.join-game"),t=0;t<e.length;t++){e[t].style.display="";var n=e[t].querySelector(".labels");n&&(n.innerHTML=Webcontrol.getControlLabels("join-game").join(", "))}for(var i=document.querySelectorAll(".buttoninstructions.start-game"),o=0;o<i.length;o++){i[o].style.display="";var r=i[o].querySelector(".labels");r&&(r.innerHTML=Webcontrol.getControlLabels("start-game").join(", "))}}else{for(var s=document.querySelectorAll(".buttoninstructions.join-game"),a=0;a<s.length;a++)s[a].style.display="none";h.style.display="none"}}function A(e){for(var t=0;t<y.length;t++)if(y[t].getId()==e.getId())return 1}function x(){var e=Webcontrol.getUsers();a.innerHTML="";for(var t=[],n=0;n<e.length;n++)A(e[n])||t.push(e[n]);0==t.length&&(a.innerHTML='<li class="empty"><span>More players? Add devices!</span></li>');for(var i="",n=0;n<t.length;n++)i+='<li class="user '+t[n].getType()+'" style="background-color: '+t[n].getColor()+'"><i class="'+t[n].getIcon()+'"></i><span>'+t[n].getName()+"</span></li>";i&&(a.innerHTML=i)}function M(){l.innerHTML="",0==y.length&&(l.innerHTML='<li class="empty"><span class="buttoninstructions join-game">Press <span class="labels"></span> to join the game.</span></li>');for(var e="",t=0;t<y.length;t++)e+='<li class="user '+y[t].getType()+'" style="background-color: '+y[t].getColor()+'"><i class="'+y[t].getIcon()+'"></i><span>'+y[t].getName()+"</span></li>";e&&(l.innerHTML=e),x()}function V(){p=Math.ceil((f.getTime()-(new Date).getTime())/1e3);var e=u.querySelector(".counter");e&&(e.innerHTML=p),p<0&&(void 0!==t&&void 0!==t.style&&(t.style.display="none"),U(),i(y))}function U(){w=!1,d&&(D("Countdown stopped!"),u.style.display="none",clearInterval(d),d=null)}function D(e){var t=document.createElement("p");t.innerHTML=e,g.appendChild(t),setTimeout(function(){t.style.transition="opacity 1s",t.style.opacity="0",setTimeout(function(){t.parentNode&&t.parentNode.removeChild(t)},1e3)},3e3)}this.loginInformation="Login into your account and get access to more game features now!",o.classList?o.classList.add("webremote-portal"):o.className=o.className+" webremote-portal",void 0!==e.theme&&(e=N.getSocketURL()+"/webremote/themes/"+e.theme+"/"+e.theme+".css",Webcontrol._loadCSS(e),Webcontrol._loadCSS(N.getSocketURL()+"/webremote/themes/font-awesome/css/font-awesome.min.css")),o.innerHTML='<div class="loading"><p>Please wait, loading socket.io.</p></div>',Webcontrol.initialize(function(){o.innerHTML="";var e=document.createElement("div"),e=(e.className="webremote-portal-inner",o.appendChild(e),(o=e).innerHTML='<div class="loading"><p>Please wait, connecting to server.</p></div>',b&&Webcontrol.loadViews(N.getSocketURL(!0)+"/webremote/views/default.xml"),o.innerHTML="<h1>Player lobby</h1>",m=document.createElement("div"),v=k('<div><h2>Select account</h2><div class="information"><p>'+O.loginInformation+'</p></div><ul class="available-accounts"></ul><p class="link-new-account"></p></div>'),m.className="accounts-overlay",v.className="accounts",m.style.display="none",v.style.display="none",o.appendChild(m),o.appendChild(v),k('<div class="connected-users"><div class="inner"><h2>Connected devices</h2></div></div>')),t=((a=document.createElement("ul")).className="connected-users",e.querySelector(".inner").appendChild(a),k('<div class="active-users"><div class="inner"><h2>Active users</h2></div></div>'));(l=document.createElement("ul")).className="active-users",t.querySelector(".inner").appendChild(l),o.appendChild(e),o.appendChild(t),(e=k('<div class="connection-information"><div class="inner"><h2>Instructions</h2><p>Take your smartphone, navigate to <span class="url"></span> and use token <span class="token"></span></p></div></div>')).querySelector(".token").innerHTML=Webcontrol.getConnectToken(),e.querySelector(".url").innerHTML=Webcontrol.getConnectURL(),c=k('<p class="buttoninstructions join-game">Press <span class="labels"></span> to join the game.</p>'),h=k('<p class="buttoninstructions start-game">Press <span class="labels"></span> to start the game.</p>'),(g=document.createElement("div")).className="errors",o.appendChild(g),e.appendChild(c),e.appendChild(h),o.appendChild(e),(t=document.createElement("div")).innerHTML='<div class="countdown-background"></div><div class="countdown"><p>Game will start in <span class="counter">5</span></p></div>',t.style.display="none",o.appendChild(t),u=t,Webcontrol.on("user:join",function(e){L(e)});for(var n=Webcontrol.getUsers(),i=0;i<n.length;i++)L(n[i]);Webcontrol.on("user:leave",x),x(),M(),W()})}}),define("CatLab/Webremote/ViewFactory/ViewFactory",["CatLab/Webremote/Views/Portal"],function(t){function e(){}return e.prototype.getPortal=function(e){return new t(e)},e}),define("CatLab/Webremote/Controllers/Webcontrol",["CatLab/Webremote/Config","CatLab/Webremote/Collections/Users","CatLab/Webremote/Collections/Groups","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Models/Users/ControlUser","CatLab/Webremote/Models/ControlGroup","CatLab/Webremote/Models/State","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Controllers/Portal","CatLab/Webremote/Controllers/Authentication","CatLab/Webremote/Tools/Colorwheel","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Preloader","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/MessageCounter","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Synchronization/RemoteViewFactory","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler","CatLab/Webremote/ViewFactory/ViewFactory","CatLab/Webremote/Views/ConnectionTrouble","CatLab/Webremote/Providers/SocketIO","CatLab/Webremote/SonicSync/Client","CatLab/Webremote/Messages/MessageBus"],function(a,e,t,n,i,o,l,r,s,c,h,u,d,f,p,g,m,v,b,y,w,_,C,k,L,P){function T(){this.initializeEventable(),this.provider=null,this._gamedata=null,this._userlibrary=null,this._grouplibrary=null,this._cssloads=[],this._labeldata={},this._initialized=!1,this._oauthsettings=!1,this._oauthClient=null,this._authentication=!1,this._lastView=null,this._options={},this._groupCallbacks={id:1},this._viewFactory=null,this.state=null,this.connected=!1,this._userlibrary=new e,this._grouplibrary=new t,this._messageBus=new P,this._pendingVitalEvent=null,this._licenseToken=null}T.GAME_HANDSHAKE_GRACE_MS=6e4;g=T.prototype=new g;return Object.assign(g,{AUTH_REQUIRED_ALL:"ALL",AUTH_REQUIRED_ONE:"ONE",AUTH_REQUIRED_ONE_INACTIVE:"ONE-INACTIVE",AUTH_NOT_REQUIRED:"NONE",initialize:function(e){function t(){o.resolve(),i()}var n,i=function(){},o=(void 0!==(e=void 0===(e="function"==typeof e?{callback:e}:e)?{}:e).callback&&(i=e.callback),new u);return this._initialized?t():(this.sonicSyncClient=null,delete e.callback,e.headless,(n=!!e.headless)||void 0===e.assets||this.setAssets(e.assets),a.set(e),a.initialize(function(){null===this.provider&&(void 0===e.provider&&(e.provider=new k),this.provider=e.provider),this.smileys=new p(this.provider),void 0!==e.translator&&d.setTranslator(e.translator),this._initialize(n,t)}.bind(this))),o.promise()},disconnect:function(){this._initialized=!1,this._licenseToken=null,this.provider.disconnect()},_initialize:function(o,e){var r,s=new u;return(e&&s.then(e),this._initialized)?s.resolve(this.connected):(setTimeout(function(){s.resolve(!1)},T.GAME_HANDSHAKE_GRACE_MS),this.state=new l(this),this._initialized=!0,(r=this).provider.initMaster(this),this.preloader=new f(this.provider),this.getProviderSettings().then(function(e){this.provider.connect("control",e).then(function(){this.connected=!0,this.provider.on("disconnect",function(){var e=this.getConnectionIssuesView();e.show(),e.text(d.t("Connection lost... reconnecting"))}.bind(this)),this.provider.on("reconnect",function(){this.recover(function(){this.getConnectionIssuesView().hide()}.bind(this))}.bind(this)),this.provider.on("master:initialize",function(e){this.log("Initializing"),this._gamedata=e,this.log("Game initialize; URL "+this.getConnectURL()+", token "+this.getConnectToken()),this.trigger("game:initialized",e),s.resolve(this.connected)}.bind(this)),this.provider.on("master:error",function(e){alert(e.message)}.bind(this)),this.provider.on("license:capped",function(e){this._onLicenseCapped(e)}.bind(this)),this.provider.on("user:join",function(e){this._playerJoin(e)}.bind(this)),this.provider.on("user:reconnect",function(e){this._playerReconnect(e)}.bind(this)),this.provider.on("user:leave",function(e){this._playerLeave(e)}.bind(this)),this.provider.on("view:labels",function(e){this._setViewLabels(e)}.bind(this)),this.provider.on("group:create",function(e){this._onNewGroup(e)}.bind(this)),this.provider.on("user:smiley",function(e){this._playerTrigger("user:smiley",e),this._userlibrary.each(function(e){this.smileys.refreshTakenSmileys(e)}.bind(this))}.bind(this)),this.provider.on("smileys:slingshot",function(e){var t=this._userlibrary.getFromId(e.user);t?(t.trigger("smileys:slingshot",e),e.user=t,this.trigger("smileys:slingshot",e)):console.log("User not found: "+e.user)}.bind(this));for(var e=(e=(e=["user:login","user:logout","button:down","button:up","sync:audio"]).concat(y.eventsToListenFor)).concat(w.eventsToListenFor),t=0;t<e.length;t++)(t=>{r.provider.on(t,function(e){r._playerTrigger(t,e)})})(e[t]);var n=["value:change"];for(var i=0;i<n.length;i++)(t=>{r.provider.on(t,function(e){r._viewTrigger(t,e)})})(n[i]);this._oauthsettings&&this.provider.setOAuthSettings(this._oauthsettings),this.provider.setup(a.getProviderConfig()),!o&&a.useAudioSync()&&(this.sonicSyncClient=new L(this),this.sonicSyncClient.startSender())}.bind(this))}.bind(this))),s.promise()},setLogger:function(e){var t;"string"==typeof e?(t=document.getElementById(e),this.log=this.getDomLogger(t)):this.log=e},getProviderSettings:function(){return this.provider.getProviderSettings()},setMessageCounter:function(e){e=new m(e);return this.provider.setMessageCounter(e),e},setName:function(e){this.provider.toMaster("master:name",{name:e})},setMaxUsers:function(e){this.provider.toMaster("config:set",{maxUsers:e})},setLicenseToken:function(e){this.provider&&e&&e!==this._licenseToken&&(this._licenseToken=e,this.provider.toMaster("license:update",{token:e}))},_onLicenseCapped:function(e){this.trigger("license:capped",e)},setViewFactory:function(e){return this._viewFactory=e,this._viewFactory.initialize()},getViewFactory:function(){return"undefined"===this._viewFactory&&(this._viewFactory=new _),this._viewFactory},getDomLogger:function(t){return function(e){t.innerHTML=e+"\n"+t.innerHTML}},oAuth:function(e,t){void 0===t&&(t=!1),this._authentication=!0,this._oauthsettings=e,this.provider&&!t&&this.provider.setOAuthSettings(this._oauthsettings),r.initialize(e),n.initialize(this,r),this._userlibrary&&this._userlibrary.each(function(e){"function"==typeof e.flushPendingLogin&&e.flushPendingLogin()})},getOAuthClient:function(e){this._oauthsettings?(null===this._oauthClient&&(this._oauthClient=r,this._oauthClient.initialize(this._oauthsettings)),e(this._oauthClient)):e(null)},getOAuthSettings:function(){return this._oauthsettings},clearEvents:function(e){if(e=void 0===e?!1:e)for(var t=this._userlibrary.getAll(),n=0;n<t.length;n++)t[n].clearEvents()},getConnectURL:function(){return this.provider.getConnectURL(this._gamedata?this._gamedata.connectURL:null)},getConnectToken:function(){return this.provider.getConnectToken(this._gamedata?this._gamedata.token:null)},getConnectTokenForDisplay:function(){return v.getConnectTokenForDisplay(this.getConnectToken())},loadViews:function(e,t,n){return this.provider.loadViews(e,n,t)},parseViews:function(e,t){return this.provider.parseViews(e,t)},registerComponent:function(e,t,n){return this.provider.registerComponent(e,t,n)},getUsers:function(){return this._userlibrary.getAll()},setExternalPlayerOffset:function(e){this._userlibrary&&this._userlibrary.setExternalPlayerOffset(e)},portal:function(e){var t=this.portalController(e),e=this.portalView(t.messageBus,e);return{controller:t.controller,view:e,promise:t.promise}},portalController:function(e){var t;if(this._initialized)return t=new u,e=new s(this,e),t.resolve(e),{controller:e,messageBus:this.getMessageBus(),promise:t};throw new Error("Please initialize Webcontrol first.")},portalView:function(e,t){var n;if(this._initialized)return n=this.getViewFactory(),e=Object.assign({},t,{messageBus:e,Webcontrol:this}),void 0!==t.element&&(e.element=t.element),(t=n.portal(e)).loading(),(e=n.getContainer()).easelboneLayer.setView(t),t.render(),e;throw new Error("Please initialize Webcontrol first.")},authentication:function(e,t){var n;if(this._initialized)return n=this.authenticationController(e,t),t=this.authenticationView(n.controller.messageBus,t),n.controller.setNavigatableUsers([e]),{controller:n.controller,view:t,promise:n.promise};throw new Error("Please initialize Webcontrol first.")},authenticationController:function(e,t){var n=new u,e=new c(this,e,t);return n.resolve(e),{controller:e,promise:n.promise(),messageBus:this.getMessageBus()}},authenticationView:function(e,t){var n=this.getViewFactory(),t=n.authentication(Object.assign({},t,{messageBus:e})),e=n.getContainer();return e.easelboneLayer.setView(t),t.render(),e},alertView:function(e,t){var n=this.getViewFactory(),t=n.alert(Object.assign({},t,{message:e})),e=n.getContainer();return e.easelboneLayer.setView(t),t.render(),e},getConnectionIssuesView:function(){return void 0===this.connectionTrouble&&(this.connectionTrouble=new C),this.connectionTrouble},setView:function(e,t){var n;return void 0===t?(n=b.create(e,[this],this),this._lastView=n):n=b.create(e,t,this),n},beacon:function(e,t){this.provider.toMaster("master:beacon",{beacon:e,token:t})},emit:function(e,t){this.provider.emit(e,t)},getControlLabels:function(e,t){for(var n=[],i={},o=this.getUsers(),r=0;r<o.length;r++){var s=o[r].control(e).getLabel(t);void 0===i[s]&&n.push(i[s]=s)}return n},addCustomControl:function(e){this.log("adding "+e.getType()),e.setWebcontrol(this),this._userlibrary.add(e),this._initializeSmiley(e,{}),this.trigger("user:join",e)},newGroup:function(e){var t=new u,n={},i=(void 0===e?e={}:"function"==typeof e&&(e={callback:e}),void 0===e.callback&&(e.callback=function(){}),!0),o=(void 0!==e.globalViews&&(i=e.globalViews),!0),r=(void 0!==e.shareColor&&(o=e.shareColor),[]),s=(void 0!==e.tags&&(r=e.tags),!0),s=(void 0!==e.smiley&&(s=!!e.smiley),n.smiley=s,this._groupCallbacks.id);return this._groupCallbacks.id++,this._groupCallbacks[s]={id:s,callback:e.callback,deferred:t,options:n},this.provider.createGroup(s,i,o,r),t.promise()},preload:function(e){var t;return this.preloader&&this.connected?this.preloader.preload(e):((t=new u).resolve(e),t.promise())},getPreloadedUrl:function(e){return this.preloader&&this.connected?this.preloader.getPreloadedUrl(e):e},_reset:function(){this._userlibrary.clear(),this._grouplibrary.clear()},reset:function(){var e=new u;return this.provider.reset(function(){e.resolve()}.bind(this)),e.promise()},_playerJoin:function(e){var t;this._userlibrary.getFromId(e.id)||((t=new i(e.id,e)).setWebcontrol(this),void 0!==e.color&&t.setColor(e.color.color,e.color.name),this._grouplibrary.addUser(t)||(this._lastView&&this._lastView.addTarget(t),this._initializeSmiley(t,e)),this._userlibrary.add(t),this.log(t),t&&this.trigger("user:join",t),this.preloader.sendPreloadFileCommandToPlayer(t))},_playerReconnect:function(e){var t=this._userlibrary.getFromId(e.id);t?(t.getSmiley()&&t.emit("user:smiley",{smiley:t.getSmiley()}),this._refreshPlayerViews(t),this.trigger("user:rejoin",t),t.eventableTrigger("rejoined"),this.smileys.refreshTakenSmileys(t),this.preloader.sendPreloadFileCommandToPlayer(t)):this._playerJoin(e)},_refreshPlayerViews:function(e){this._grouplibrary.addUser(e)||this._lastView&&this._lastView.addTarget(e),e.refreshView()},_playerLeave:function(e){e=this._userlibrary.getFromId(e.id);e&&(this.trigger("user:leave",e),e.eventableTrigger("left"))},_onNewGroup:function(e){var t,n=new o(e.id,e),i=(n.setWebcontrol(this),!1);void 0!==e.shareColor&&(i=e.shareColor),void 0!==e.color?n.setColor(e.color.color,e.color.name):n.setShareColor(i),this._grouplibrary.getFromId(e.id)||(i=function(){},void 0!==(t=e.externalId)&&void 0!==this._groupCallbacks[t]&&(n.setOptions(this._groupCallbacks[t].options),i=function(){this._groupCallbacks[t].callback(n),this._groupCallbacks[t].deferred.resolve(n)}.bind(this)),this._grouplibrary.add(n),n.getOption("smiley")&&this._initializeSmiley(n,e),this.trigger("group:create",n),this.log("New group "+n.getId()+"; URL "+n.getConnectURL()+", token "+n.getConnectToken()),i())},_initializeSmiley:function(e,t){var n;a.useSmileys()?void 0===t.smiley?null!==(n=this.smileys.getRandom(e.getIdentifier()))&&e.setSmiley(n):e.setSmiley(t.smiley):e.clearSmiley(),this.smileys.refreshTakenSmileys(e)},_playerTrigger:function(e,t){var n=this._userlibrary.getFromId(t.user);n?n.trigger(e,t):console.log("User not found: "+t.user)},_viewTrigger:function(e,t){var n=b.getFromId(t.viewId);n&&n.trigger(e,t)},_loadCSS:function(e){for(var t=0;t<this._cssloads.length;t++)if(this._cssloads[t]==e)return;this._cssloads.push(e);var n=document.createElement("link");n.setAttribute("rel","stylesheet"),n.setAttribute("type","text/css"),n.setAttribute("href",e),document.body.appendChild(n)},_setViewLabels:function(e){this._labeldata[e.id]=e.labels;for(var t=this.getUsers(),n=0;n<t.length;n++)for(var i=0;i<e.labels.length;i++)t[n].control(e.id).setStaticLabel(e.labels[i].label,"mobile")},getViewLabels:function(e){return void 0!==this._labeldata[e]?this._labeldata[e]:[]},getFromIdentifier:function(e){switch(e.type){case"user":return this._userlibrary.getFromId(e.id);case"group":return this._grouplibrary.getFromId(e.id)}return null},log:function(e){a.debug()&&(console.log(a),console.log(e))},canAuthenticate:function(){return this._authentication},pause:function(){this._pendingVitalEvent={action:"master:pause",data:{}},this._initialized&&this.provider.emit("master:pause",{})},unpause:function(){this._pendingVitalEvent={action:"master:unpause",data:{}},this._initialized&&this.provider.emit("master:unpause",{})},audioSync:function(){if(this.sonicSyncClient)return this.sonicSyncClient.sync()},getMessageBus:function(){return this._messageBus},recover:function(e){var t=this.state.getData();this._reconnect(t.token,t.accessToken,e).then(function(){this._userlibrary.each(function(e){this._refreshPlayerViews(e)}.bind(this)),this._resendVitalEvent(),this._licenseToken&&this.provider.toMaster("license:update",{token:this._licenseToken})}.bind(this))},_resendVitalEvent:function(){this._pendingVitalEvent&&this.provider.emit(this._pendingVitalEvent.action,this._pendingVitalEvent.data)},_reconnect:function(e,t,n){return this.provider.reconnect(e,t,a.getProviderConfig(),n)},getIceCredentials:function(){var t=new u;return this.provider.toMaster("webrct:stun+turn",{},function(e){void 0===e.error?t.resolve(e):t.fail(e.error)}),t.promise()}}),T}),define("CatLab/Webremote/Models/Users/DummyUser",["CatLab/Webremote/Models/Users/ControlUser"],function(e){function t(e){this.initialize({id:e}),this.clearControls=function(){},this.getType=function(){return"dummy"},this.getIcon=function(){return"fa fa-keyboard-o"},this.emit=function(e,t){return!1},this.isLocalAuthentication=function(){return!1},this.log=function(e){this.Webcontrol&&this.Webcontrol.log("[u:"+this.getId()+"] "+e)},this.hasDisplay=function(){return!0},this.hasKeyboardInput=function(){return!0},this.hasTouchInput=function(){return!0},this.clearControls()}return(t.prototype=Object.create(e.prototype)).constructor=t}),define("CatLab/Webremote/Tools/ParseXML",[],function(){function e(){}var t=null;"undefined"!=typeof window&&(void 0!==window.DOMParser?t=function(e){return(new window.DOMParser).parseFromString(e,"text/xml")}:void 0!==window.ActiveXObject&&new window.ActiveXObject("Microsoft.XMLDOM")&&(t=function(e){var t=new window.ActiveXObject("Microsoft.XMLDOM");return t.async="false",t.loadXML(e),t}));return e.prototype.parse=function(e){if(t)return t(e);throw new Error("No XML parser found")},new e}),define("CatLab/Webremote/Providers/Airconsole",["CatLab/Webremote/Providers/Provider","CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Proxy","CatLab/Webremote/Tools/ParseXML","CatLab/Webremote/Synchronization/MessageQueue","CatLab/Webremote/Models/User"],function(e,t,n,i,o,r,s){function a(e){e&&(this.airconsole=e),this.showTokenForm=!1,this.oauth={},this.views=[],this.knownUsers={},this.started=!1,this.userId=null,this.sendBurstDelay=50,this.connectCode=null}e=a.prototype=new e;return e.connect=function(e){return this.log("Airconsole connecting"),this.setInitialized(),this.path=e,this._trigger("connect",null),this.readyState.promise()},e.noTokenConnect=function(){return this.connect("remote")},e.setUserId=function(e){return this.userId=e,this},e.initMaster=function(e){this.master=e,this.airconsole||(this.airconsole=new AirConsole),this.airconsole.onMessage=this.onMessage.bind(this),this.airconsole.onConnect=function(e){this.emitAirConsole(e,"airconsole:well-hello-there",{user:e})}.bind(this),this.readyState=new n,this.airconsole.onReady=function(e){this.connectCode=e,this.readyState.resolve()}.bind(this),this.airconsole.onDeviceProfileChange=function(e){this.updateDeviceProfile(e)}.bind(this),this.on("player:join",function(e){this.onPlayerConnect(e.user)}.bind(this)),this.once("connect",function(){setTimeout(function(){this.started=!0}.bind(this),1)}.bind(this))},e.initPlayer=function(e){this.master=e,this.airconsole=new AirConsole,this.airconsole.onMessage=this.onMessage.bind(this),this.readyState=new n,this.readyState.resolve(),this.once("airconsole:well-hello-there",function(e){this.emitAirConsole(0,"player:join",{})}.bind(this))},e.onMessage=function(t,e){var n;void 0!==(e="string"==typeof e?JSON.parse(e):e).b&&Array.isArray(e.b)?(n=0,e.b.forEach(function(e){setTimeout(function(){this.processMessage(t,e)}.bind(this),n++)}.bind(this))):this.processMessage(t,e)},e.processMessage=function(e,t){var n;t&&t[0]&&(n=t[0],t=t[1],this.isMaster()&&(0<e&&"player:join"!==n&&void 0===this.knownUsers[e]&&this.onPlayerConnect(e),0<e)&&(t.user=e),r.unpack(t,"user").forEach(function(e){this.isRemote()&&void 0!==e.user&&e.user!==this.airconsole.getDeviceId()||this._trigger(n,e)}.bind(this)))},e.onPlayerConnect=function(e){this.log("Welcoming our newest player "+e),this.knownUsers[e]=!0;for(var t=0;t<this.views.length;t++)this.emitAirConsole(e,"view:load",{xml:this.views[t]}),this.emitAirConsole(e,"view:set",{id:"loading"});this._trigger("user:join",{id:e}),this.updateDeviceProfile(e)},e.updateDeviceProfile=function(e){var t,n,i=this.master._userlibrary.getFromId(e);i&&(t={username:this.airconsole.getNickname(e)},(n=this.airconsole.getProfilePicture(e))&&(t.avatar=n),this.airconsole.getMasterControllerDeviceId()===e&&i.setMaster(!0),i.setProfiledata(t))},e.emitAll=function(){this.isMaster()&&this.emitMaster(),this.isRemote()&&this.emitClient()},e.isMaster=function(){return"control"===this.path},e.isRemote=function(){return"remote"===this.path},e.emitClient=function(){this.queue.flush().forEach(function(e){this.emitAirConsole(0,e.action,e.data)}.bind(this))},e.emitMaster=function(){var t,n,e=this.queue.compactFlush();e.length&&(t=5<e.length,n=[],e.forEach(function(e){t||void 0===e.data.user||Array.isArray(e.data.user)&&1<e.data.user.length?n.push(e):this.emitAirConsole(e.user,e.action,e.data)}.bind(this)),0<n.length)&&this.broadcastAirconsole(n)},e.emitAirConsole=function(e,t,n){t=[t,n],delete t[1].action,n=JSON.stringify(t);this.airconsole.message(e,n)},e.broadcastAirconsole=function(e){var t=[],e=(e.forEach(function(e){t.push([e.action,e.data])}),JSON.stringify({b:t}));this.airconsole.broadcast(e)},e.setOAuthSettings=function(e){this.oauth=e,this.emit("oauth:set",e)},e.onParseViews=function(e){this.views.push(e)},e.log=function(){this.master.log.apply(arguments)},e.setup=function(e){this._trigger("master:initialize",{})},e.toMaster=function(e,t){t.user=0,this.emit(e,t)},e.log=function(e){var t=[],n=(Array.prototype.push.apply(t,arguments),"["+this.path+"]");"remote"===this.path&&(n="["+this.path+":"+this.airconsole.getDeviceId()+"]"),t.unshift(n),console.log.apply(console,t)},e.getConnectInstructions=function(){return["Open the Airconsole app on your smartphone and connect with code %s.",this.connectCode]},e.getStartAndLoginInstructions=function(){return["Use the onscreen button to start the game."]},a}),define("CatLab/Webremote/Providers/Dummy",["CatLab/Webremote/Providers/Provider","CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Tools"],function(e,t,i,n){function o(){this.initializeProvider(),this.userId=null,this.randomToken=n.getUuid(),this.loadBalancerSessionToken="connid",this.socket=null,this._registeredEvents={}}e=o.prototype=new e;return e.connect=function(e,t){var n=new i;return this.setInitialized(),n.resolve(),n.promise()},e.setup=function(e){this._trigger("master:initialize",{})},e.emitAll=function(e,t){},o}),define("CatLab/Webremote/Transport/Errors",[],function(){function e(e,t){return e.prototype=Object.create(Error.prototype),(e.prototype.constructor=e).prototype.name=t,e}return{TransportError:e(function(e,t){var e=t?t+": "+e:e,n=new Error(e);this.message=e,this.path=t||null,this.stack=n.stack},"TransportError"),RemoteError:e(function(e){e=e||{};var t=new Error(e.message||"");this.name=e.name||"RemoteError",this.message=e.message||"",this.data=void 0===e.data?null:e.data,this.remoteStack=e.stack||"",this.isRemote=!0,this.stack=this.name+": "+this.message+"\n--- remote stack ---\n"+this.remoteStack+"\n--- local stack ---\n"+t.stack},"RemoteError"),RpcTimeoutError:e(function(e,t,n){var i=new Error(e+" on pool "+t+" timed out after "+n+"ms");this.message=i.message,this.method=e,this.pool=t,this.timeoutMs=n,this.stack=i.stack},"RpcTimeoutError"),PoolBootError:e(function(e,t,n){var i=new Error("pool boot failed on "+e+" host: "+t);this.message=i.message,this.kind=e,this.reason=t,this.cause=void 0===n?null:n,this.stack=i.stack},"PoolBootError")}}),define("CatLab/Webremote/Providers/BridgeContract",[],function(){return{TARGET_FIRST:{toPlayer:!0,toGroup:!0},TARGET_INDEX:{loadViews:2,parseViews:2,registerComponent:2}}}),define("CatLab/Webremote/Providers/BridgedProvider",["CatLab/Webremote/Providers/Provider","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/Errors","CatLab/Webremote/Providers/BridgeContract"],function(e,l,a,t){function n(e){this.initializeProvider(),this._channels=e,this._providerInfo={},this._seq=0,this._pending={},this._acks={},this._ackSeq=0,this._subscribed={};var n=this;e.on("provider",function(e,t){n._onMessage(e,t)}),"function"==typeof e.onClose&&e.onClose(function(){n._failAll(new a.TransportError("provider channel closed"))}),this._post("hello",{})}var c=t.TARGET_FIRST,h=t.TARGET_INDEX,t=n.prototype=new e;return t.constructor=n,t._post=function(e,t){"function"==typeof this._channels.isClosed&&this._channels.isClosed()||this._channels.sendNow("provider",e,t)},t._call=function(t,e,n,i){for(var o=++this._seq,r=new l,s=(e||[]).slice();0<s.length&&void 0===s[s.length-1];)s.pop();var e={id:o,method:t,args:s},a=null;"function"==typeof n&&(a=++this._ackSeq,this._acks[a]={fn:n,method:t},e.ack=a),i&&(e.target=i),this._pending[o]={deferred:r,method:t};try{this._post("call",e)}catch(t){null!==a&&delete this._acks[a],this._settle(o,function(e){e.deferred.reject(t)})}return r.promise()},t._settle=function(e,t){var n=this._pending[e];n&&(delete this._pending[e],t(n))},t._failAll=function(t){var n=this,e=(Object.keys(this._pending).forEach(function(e){n._settle(e,function(e){e.deferred.reject(t)})}),Object.keys(this._acks));0<e.length&&(this._acks={},console.warn("[BridgedProvider] "+e.length+" pending device ack(s) failed: "+t.message))},t._onMessage=function(e,n){var t;switch(e){case"result":return void this._settle(n.id,function(e){e.deferred.resolve(n.value)});case"error":return void this._settle(n.id,function(e){var t=n.error;t instanceof Error||(t=new a.RemoteError({name:"RemoteError",message:String(t)})),e.deferred.reject(t)});case"ack":return(t=this._acks[n.ack])?(delete this._acks[n.ack],n.error?void console.warn("[BridgedProvider] ack for "+t.method+" failed",n.error):void t.fn(n.result)):void console.warn("[BridgedProvider] ack for an unknown call ignored",n.ack);case"event":return"settings"===n.event&&n.data&&this._applyProviderInfo(n.data),void this._trigger(n.event,n.data);default:console.warn("[BridgedProvider] unknown provider message",e)}},t._applyProviderInfo=function(e){e=e||{},(this._providerInfo=e).connectInstructions?this.getConnectInstructions=function(){return e.connectInstructions}:delete this.getConnectInstructions,e.startAndLoginInstructions?this.getStartAndLoginInstructions=function(){return e.startAndLoginInstructions}:delete this.getStartAndLoginInstructions},t.initMaster=function(e){return this.master=e,this._call("initMaster",[])},t.connect=function(e,t){var n=this,e=this._call("connect",[e,t]);return e.done(function(){n.setInitialized(),n._trigger("connect")}),e},t.disconnect=function(){this._call("disconnect",[]),e.prototype.disconnect.call(this)},t.setUserId=function(e){return this._call("setUserId",[e]),this.userId=e,this},t.emit=function(e,t,n){this.initialized?this.emitOne(e,t,n):this.postInitializeQueue.push({action:e,data:t,ack:n})},t.emitOne=function(e,t,n){this._call("emit",[e,t],n)},t.emitAll=function(){var t=this;this.queue.compactFlush().forEach(function(e){t.emitOne(e.action,e.data,e.ack)})},t.toMaster=function(e,t,n){return this._call("toMaster",[e,t||{}],n)},t.toPlayers=function(e,t,n){return this._call("toPlayers",[e,t||{}],n)},t.toPlayer=function(e,t,n,i){return this._callWithTarget("toPlayer",[t,n||{}],i,e,"user")},t.toGroup=function(e,t,n,i){return this._callWithTarget("toGroup",[t,n||{}],i,e,"group")},t.createGroup=function(e,t,n,i){return this._call("createGroup",[e,t,n,i||[]])},t.setOAuthSettings=function(e){return this._call("setOAuthSettings",[e])},t.setup=function(e){return this._call("setup",[e])},t.reset=function(e){return this._call("reset",[],e)},t.proxyFile=function(e){return this._call("proxyFile",[e])},t.reconnect=function(e,t,n,i){return this._call("reconnect",[e,t,n],i)},t.loadViews=function(e,t,n){return this._callWithTarget("loadViews",[e,!!t],void 0,n,"user",!0)},t.parseViews=function(e,t,n){return this._callWithTarget("parseViews",[e,t],void 0,n,"user",!0)},t.registerComponent=function(e,t,n){return this._callWithTarget("registerComponent",[e,t],void 0,n,"user",!0)},t._callWithTarget=function(e,t,n,i,o,r){var s=null;if(i&&"function"==typeof i.getId)s={id:i.getId(),type:"function"==typeof i.getEntityType?i.getEntityType():o};else if(i&&!r)return(o=new l).reject(new a.TransportError("BridgedProvider."+e+": target has no getId()","provider."+e+".target")),o.promise();return s||c[e]||void 0!==h[e]?this._call(e,t,n,s):this._call(e,t,n)},t.getProviderSettings=function(){var e=new l;return e.resolve(this._providerInfo.settings||{}),e.promise()},t.canProviderLoadExternalXml=function(){return!!this._providerInfo.canLoadExternalXml},t.canProxyFiles=function(){return!!this._providerInfo.canProxyFiles},t.getStaticUrl=function(e){var t=this._providerInfo.staticUrlBase;return("string"==typeof t?t:"")+e},t.getConnectURL=function(e){return this._fact("connectUrl",e)},t.getConnectToken=function(e){return this._fact("connectToken",e)},t._fact=function(e,t){e=this._providerInfo[e];return null==e?void 0===t?null:t:e},t._touchEvent=function(e){this._subscribed[e]||(this._subscribed[e]=!0,this._post("subscribe",{event:e}))},n}),define("CatLab/Webremote/CreateJS/LayerContainer",["easeljs","easelbone"],function(i,o){function e(e,t){if(!o)throw console.log("When using the createjs module of the remote, you need to have the easelbone module loaded."),console.log("Check https://github.com/catlabinteractive/easelbone"),new Error("easelbone could not be loaded.");this.width=e,this.height=t,this.initialize(),this.easelboneLayer=new o.Views.Layer({container:this});var n=this;this.easelboneLayer.on("all",function(e){e=new i.Event(e);n.dispatchEvent(e)})}var t=e.prototype=new i.Container;return t.Container_initialize=t.initialize,t.initialize=function(){this.Container_initialize(),this.setBounds(0,0,this.width,this.height),this.on("click",function(e){e.stopPropagation()})},t.loading=function(){},t.render=function(){this.easelboneLayer.render()},e}),define("CatLab/Webremote/CreateJS/Views/BaseView",["easelbone","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Images"],function(r,s,e){var a=new e;return r.Views.Navigatable.extend({intitializeBaseView:function(e){this.initializeNavigatable(e),this.labels={},this.replacedEmojis={},this.navigatableOverride=null},getLabelSubstitutionOrNull:function(e,t){return void 0!==this.labels[e]?this.substituteLabelsForInstructionMessage(t,this.labels[e]):null},substituteLabelsForInstructionMessage:function(e){for(var t=[],n=1;n<arguments.length;n++){var i,o=arguments[n];"string"!=typeof o?(i=[],o.forEach(function(e){e.emoji?(i.push(e.emoji),void 0!==e.image&&(this.replacedEmojis[e.emoji]=a.getUrl(e.image,128))):e.label&&i.push(e.label)}.bind(this)),t.push(i.join(" / "))):t.push(o)}return s.t.apply(s,[e].concat(t))},getEmojiSubstitutedMessage:function(e){var e=new r.EaselJS.BigText(e),o=this.replacedEmojis;return e.textConstructor=function(e,t,n,i){e=new r.EaselJS.EmojiText(e,t,n,i);return e.setEmojis(o),e},e},alert:function(e,t){var t=this.Webcontrol.getViewFactory().alert(Object.assign({},t,{message:e})),n=this.Webcontrol.getViewFactory().getContainer();n.easelboneLayer.setView(t),t.render(),this.navigatableOverride=t,this.el.addChild(n),r.suppressPins(n),t.on("view:close",function(){n.easelboneLayer.view.trigger("stage:removed"),r.releasePins(n),this.el.removeChild(n),this.navigatableOverride=null}.bind(this))}})}),define("CatLab/Webremote/Tools/ImageLoader",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred"],function(i,o){return{loadedImages:{},loadImage:function(e){var t,n=new o;return this.loadedImages[e]?n.resolve(this.loadedImages[e]):((t=new Image).crossOrigin="anonymous",t.onload=function(){this.loadedImages[e]=t,n.resolve(this.loadedImages[e])}.bind(this),t.src=i.getProxiedImage(e)),n.promise()}}}),define("CatLab/Webremote/Tools/QrGenerator",["easelbone","qrious"],function(r,s){return{generateQrCode:function(e,t){var n=200,i=200,t=(e.getBounds()&&e.getBounds().width&&!e.getBounds().height&&(n=e.getBounds().width,i=e.getBounds().height),this.getGeneratedQrCode(t,Math.max(n,i)));return e.addChild(t),r.pinToTop(t),t},getGeneratedQrCode(e,t,n,i){void 0===n&&(n="#000000"),void 0===i&&(i="#ffffff");var o=new s,t=(o.level="H",o.size=2*t,o.value=e,o.background=i,o.foreground=n,new Image);return t.src=o.toDataURL(),new r.EaselJS.Fill(t,{zoom:"minimum"})}}}),define("CatLab/Webremote/CreateJS/Views/PortalView",["easeljs","easelbone","CatLab/Webremote/CreateJS/Views/BaseView","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/ImageLoader","CatLab/Webremote/Tools/QrGenerator","CatLab/Webremote/Messages/NavigateableProxy"],function(e,i,t,o,r,n,s){return t.extend({initialize:function(e){this.Webcontrol=e.Webcontrol,this.controllerState={activePlayers:0,minPlayers:0,maxPlayers:0,connectInstructions:[""],startAndLoginInstructions:[""],showInactivePlayers:!1,qrUrl:null},this.intitializeBaseView({orientation:this.ORIENTATION.HORIZONTAL}),this.messageBus=e.messageBus,this.assets=e.assets,this.initialized=!1,this.leanback=void 0!==e.leanback&&e.leanback,this.users=[],this.messageBus.toController("nav:controls",{controls:this._controls}),this.purchaseSeatsCallback=null,e.purchaseSeatsCallback&&(this.purchaseSeatsCallback=e.purchaseSeatsCallback),this.attachMessageBus(this.messageBus),this.on("stage:removed",this.destroy.bind(this))},initializeContent:function(){this.initialized||(this.initialized=!0,this.controllerState.showInactivePlayers?this.setScreen(new this.assets.PortalView):this.setScreen(new this.assets.PortalViewNoInactive),this.showInactivePlayers=this.controllerState.showInactivePlayers||!1,this.showInactivePlayers&&(this.connectedUsersContainer=new i.EaselJS.Placeholder(this.getScreen().connectedUsers),this.connectedUsers=new i.Controls.FloatContainer(function(e){return this.getUserIcon(e)}.bind(this),6),this.connectedUsersContainer.addChild(this.connectedUsers)),this.activeUsersContainer=new i.EaselJS.Placeholder(this.getScreen().activeUsers),this.activeUsers=new i.Controls.FloatContainer(function(e){return this.getUserIcon(e)}.bind(this),this.showInactivePlayers?6:9),this.activeUsersContainer.addChild(this.activeUsers),void 0!==this.getScreen().start&&(this.start=new i.Controls.Button(this.getScreen().start),this.start.setText(o.t("Start")),this.start.on("click",function(){this.messageBus.toController("start")}.bind(this)),this.addControl(this.start)),void 0!==this.getScreen().back&&(this.back=new i.Controls.Button(this.getScreen().back),this.back.setText(o.t("Back")),this.back.on("click",function(){this.messageBus.toController("back")}.bind(this)),this.addControl(this.back)),this.findPlaceholders("instructionHeader").forEach(function(e){e.addChild(new i.EaselJS.BigText(o.t("Instructions")))}),this.findPlaceholders("activePlayersHeader").forEach(function(e){e.addChild(new i.EaselJS.BigText(o.t("Active devices")))}),this.findPlaceholders("connectedPlayersHeader").forEach(function(e){e.addChild(new i.EaselJS.BigText(o.t("Connected devices")))}),this.instructionTexts=[],this.instructionTexts=this.findPlaceholders("instructionText"),this.updateInstructionText(),this.activePlayerTexts=[],this.findPlaceholders("activePlayers").forEach(function(e){var t=new i.EaselJS.BigText(this.getActiveUsersText());this.activePlayerTexts.push(t),e.addChild(t)}.bind(this)),this.qrContainers=this.findPlaceholders("qr"),this.qrInstructionsContainers=this.findPlaceholders("qrInstructions"))},attachMessageBus:function(e){e.addViewListener(this)},handleIncomingMessage:function(e,t){var n=this.navigatableOverride||this;if(!s.handleMessage(e,t,n,"portal:"))switch(e){case"state:change":var i=this.controllerState;this.controllerState=t.state,this.initialized?!i||JSON.stringify(i.connectInstructions)===JSON.stringify(t.state.connectInstructions)&&i.qrUrl===t.state.qrUrl||this.showInformation():this.initializeContent(),this.showCurrentAndMaxUsers();break;case"alert":if(t.id&&"exceeds-max-players"===t.id)if(this.purchaseSeatsCallback)return void this.alert(o.t(t.localized),{type:"confirm",okLabel:o.t("Purchase seats"),ok:function(e){e.close(),this.purchaseSeatsCallback()}.bind(this),cancelLabel:o.t("Cancel")});this.alert(o.t(t.localized));break;case"users:update":this.users=t.users,this.refreshUsers();break;case"auth:open":this.addAuthenticationView();break;case"portal:destroy":this.destroy()}},getActiveUsersText:function(){return this.controllerState.activePlayers+"/"+this.controllerState.maxPlayers},getInstructionText:function(){return this.substituteLabelsForInstructionMessage.apply(this,this.controllerState.connectInstructions)+"\n"+this.substituteLabelsForInstructionMessage.apply(this,this.controllerState.startAndLoginInstructions)},getUserIcon:function(e){var t,n;return e?e.profile?(t=new this.assets.UserIconAuthenticated,this.addControllerIcon(t,e)):t=this.getControllerIcon(e):t=this.getControllerIcon(),e&&(n=t.PlayerColor)&&new i.EaselJS.Placeholder(n).addChild(new i.EaselJS.Fill(e.color)),e&&this.setUserDetails(t,e),t},addControllerIcon:function(e,t){var n;e.ControllerIcon&&(e=new i.EaselJS.Placeholder(e.ControllerIcon),n=this.getControllerIcon(t),e.addChild(n),n.scaleX=n.scaleY=.5,t)&&(e=n.PlayerColor)&&new i.EaselJS.Placeholder(e).addChild(new i.EaselJS.Fill(t.color))},getControllerIcon:function(e){if(e)switch(e.type){case"keyboard":return new this.assets.UserIconKeyboard;case"tablet":return new this.assets.UserIconTablet;case"phone":return new this.assets.UserIconPhone;case"gamepad":return new this.assets.UserIconGamepad}return new this.assets.UserIcon},loading:function(){},refreshUsers:function(){this.getScreen()&&(this.showCurrentAndMaxUsers(),this.showInformation(),this.reloadUserIcons())},showCurrentAndMaxUsers:function(){var e=this.getScreen();e&&(e.playercount&&(e.playercount.text=this.controllerState.activePlayers+"/"+this.controllerState.maxPlayers),this.activePlayerTexts.forEach(function(e){e.setText(this.controllerState.activePlayers+"/"+this.controllerState.maxPlayers)}.bind(this)),e.login)&&(e.login.text=o.t(this.controllerState.startAndLoginInstructions))},showInformation:function(){var e,t=this.getScreen();t&&(e=o.t(this.controllerState.connectInstructions),t.login?t.login.text=o.t(this.controllerState.startAndLoginInstructions):e+="\n "+o.t(this.controllerState.startAndLoginInstructions),t.token&&(t.token.text=e),this.updateInstructionText(),this.updateQrCode())},updateInstructionText:function(){this.instructionTexts.forEach(function(e){var t=this.getEmojiSubstitutedMessage(this.getInstructionText());e.removeAllChildren(),e.addChild(t)}.bind(this))},updateQrCode:function(){this.qrContainers.forEach(function(e){e.removeAllChildren(),this.controllerState.qrUrl&&n.generateQrCode(e,this.controllerState.qrUrl)}.bind(this)),this.qrInstructionsContainers.forEach(function(e){var t;e.removeAllChildren(),this.controllerState.qrUrl&&(t=this.getEmojiSubstitutedMessage(o.t("Scan QR code to connect")),e.addChild(t))}.bind(this))},removeAllUserIcons:function(){this.showInactivePlayers&&this.connectedUsers.removeAllChildren(),this.activeUsers.removeAllChildren()},reloadUserIcons:function(){var t=24,n=24;this.showInactivePlayers||(n=45),this.removeAllUserIcons(),this.users.forEach(function(e){e.active?n<=0||(n--,this.activeUsers.createElement(e)):!this.showInactivePlayers||t<=0||(t--,this.connectedUsers.createElement(e))}.bind(this))},setUserDetails:function(e,t){var n;t.profile&&e.userimage&&(n=new i.EaselJS.Placeholder(e.userimage),r.loadImage(t.profile.image).then(function(e){n.addChild(new i.EaselJS.Fill(e))}))},addAuthenticationView:function(){var e=this.Webcontrol.authenticationView(this.messageBus,{leanback:this.leanback}),t=(this.el.addChild(e),!1),n=function(){t||(t=!0,e.easelboneLayer&&e.easelboneLayer.view&&e.easelboneLayer.view.trigger("stage:removed"),this.el.removeChild(e))}.bind(this);e.on("view:close",function(){n(),this.messageBus.toController("auth:close")}.bind(this)),e.on("close",n)},render:function(){var e=this.getScreen();e&&this.el&&(this.el.addChild(e),this.refreshUsers())},destroy:function(){this.messageBus.removeViewListener(this)}})}),define("CatLab/Webremote/CreateJS/Views/AuthenticationView",["easelbone","CatLab/Webremote/CreateJS/Views/BaseView","CatLab/Webremote/Tools/Images","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/ImageLoader","CatLab/Webremote/Tools/QrGenerator","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/Controllers/OAuth2"],function(o,e,t,r,s,a,n,i){return e.extend({initialize:function(e){var t;this.intitializeBaseView(),this.assets=e.assets,this.leanback=void 0!==e.leanback&&e.leanback,this.leanback?this.screen=new e.assets.SigninLeanback:this.screen=new e.assets.Signin,this.findFromNames(["close"],[this.screen]).forEach(function(e){e.on("click",function(){this.close()}.bind(this))}.bind(this)),this.screen.linkAccount&&(this.linkAccount=new o.Controls.Button(this.screen.linkAccount),this.linkAccount.on("click",function(){i.link(function(e){e&&"function"==typeof e.getAccessToken&&this.messageBus.toController("auth:add-access-token",{accessToken:e.getAccessToken(),select:!0})}.bind(this))}.bind(this))),this.titlePlaceholder=null,this.explanationPlaceholder=null,o.Helpers.MovieClipHelper.findFromNames(["title"],[this.screen]).forEach(function(e){this.titlePlaceholder=new o.EaselJS.Placeholder(e)}.bind(this)),o.Helpers.MovieClipHelper.findFromNames(["explanation"],[this.screen]).forEach(function(e){this.explanationPlaceholder=new o.EaselJS.Placeholder(e)}.bind(this)),this.titlePlaceholder&&(t=new o.EaselJS.BigText(r.t("Select your profile"),null,null,"left"),this.titlePlaceholder.addChild(t)),this.qrContainers=this.findPlaceholders("qr",this.screen),this.qrInstructionsContainer=this.findPlaceholders("qrInstructions",this.screen),this.setLoginUrlText(),o.Helpers.MovieClipHelper.findFromNames("accounts",[this.screen]).forEach(function(e){e=new o.Controls.ScrollArea(e);this.users=new o.Controls.FloatContainer(function(e){return this.getUserObject(e)}.bind(this),4),e.content.addChild(this.users)}.bind(this)),this.updateUsers([]),this.on("removed",function(){this.trigger("close")}.bind(this)),this.setBack(function(){this.close()}.bind(this)),this.on("close",this.releasePinSuppression.bind(this)),this.attachMessageBus(e.messageBus),this.on("stage:removed",this.destroy.bind(this))},attachMessageBus:function(e){(this.messageBus=e).addViewListener(this)},handleIncomingMessage:function(e,t){if(!n.handleMessage(e,t,this,"auth:"))switch(e){case"auth:users:update":this.updateUsers(t.users);break;case"auth:close":this.close();break;case"auth:loginurl":this.setLoginUrl(t.url);break;case"auth:destroy":this.destroy();break;case"labels:update":this.labels=t.labels,this.setLoginUrlText();break;case"auth:request-remove-selected-profile":this.removeSelectedUser()}},updateUsers:function(e){this.resetOptions(),this.users.removeAllChildren();for(var t=0;t<e.length;t++)this.users.createElement(e[t]);this.linkAccount&&this.addControl(this.linkAccount)},getUserObject:function(e){var t,n=new this.assets.UserModel,i=(n.namePlaceholder?n.text=n.namePlaceholder:n.name&&(n.text=n.name),new o.Controls.Button(n));return e&&(i.setText(e.name),t=new o.EaselJS.Placeholder(n.picture),s.loadImage(e.image).then(function(e){t.addChild(new o.EaselJS.Fill(e))}),i._userModel=e,i.on("click",function(){this.selectUser(e)}.bind(this)),this.addControl(i)),n},selectUser:function(e){this.messageBus.toController("auth:select-user",{user:{id:e.id}})},close:function(){this._closed||(this._closed=!0,this.trigger("close"),this.messageBus.toController("auth:close"))},render:function(){this.el.addChild(this.screen),o.suppressPins(this.el)},releasePinSuppression:function(){o.releasePins(this.el)},setLoginUrl:function(e){this.loginUrl=e,this.setLoginUrlText()},setLoginUrlText:function(){if(this.linkAccount&&this.linkAccount.setText(r.t("Login to add profile")),this.explanationPlaceholder){var e,t=[],n={selectProfile:"%s to select",removeProfile:"%s to remove",close:"%s to close"};for(e in n){var i=this.getLabelSubstitutionOrNull(e,n[e]);i&&t.push(i)}this.explanationPlaceholder.removeAllChildren(),0<t.length&&this.explanationPlaceholder.addChild(this.getEmojiSubstitutedMessage(t.join(", ")+"."))}this.loginUrl&&(this.qrContainers.forEach(function(e){"http"!==this.loginUrl.substring(0,4)&&(this.loginUrl="https://"+this.loginUrl),e.removeAllChildren(),a.generateQrCode(e,this.loginUrl)}.bind(this)),this.qrInstructionsContainer.forEach(function(e){var t=r.t("Scan to login or surf to %s",this.loginUrl);e.addChild(new o.EaselJS.BigText(t))}.bind(this)))},removeSelectedUser:function(){var e=this._current;e&&e._userModel?this.messageBus.toController("auth:remove-user",{user:{id:this._current._userModel.id}}):console.log("No current control")},destroy:function(){this.releasePinSuppression(),this.messageBus.removeViewListener(this)}})}),define("CatLab/Webremote/CreateJS/Views/AlertView",["easelbone","CatLab/Webremote/Tools/Translator","CatLab/Webremote/CreateJS/Views/BaseView"],function(o,r,e){return e.extend({initialize:function(n){"confirm"===(this.intitializeBaseView(),this.easelScreen=new n.assets.Alert,this.findPlaceholders("message").forEach(function(e){var t=new o.EaselJS.BigText(n.message);e.addChild(t)}),void 0===n.type&&(n.type="alert"),n.type.toLowerCase())?this.initializeConfirm(n):this.initializeAlert(n)},initializeAlert:function(e){var t=r.t("OK");void 0!==e.buttonLabel&&(t=e.buttonLabel),this.findFromNames("button").forEach(function(e){e=new o.Controls.Button(e);e.setText(t),this.addControl(e),e.click(function(){this.close()}.bind(this))}.bind(this)),setTimeout(function(){this.jumpToFrame("oneButton")}.bind(this),0)},initializeConfirm:function(t){var n=r.t("OK"),i=(void 0!==t.okLabel&&(n=t.okLabel),r.t("Cancel"));void 0!==t.cancelLabel&&(i=t.cancelLabel),this.findFromNames("button1").forEach(function(e){e=new o.Controls.Button(e);e.setText(n),this.addControl(e),e.click(function(){"function"!=typeof t.ok?this.close():t.ok(this)}.bind(this))}.bind(this)),this.findFromNames("button2").forEach(function(e){e=new o.Controls.Button(e);e.setText(i),this.addControl(e),e.click(function(){"function"!=typeof t.cancel?this.close():t.cancel(this)}.bind(this))}.bind(this)),setTimeout(function(){this.jumpToFrame("twoButtons")}.bind(this),0)},close:function(){this.trigger("view:close")},render:function(){this.el.addChild(this.easelScreen)}})}),define("CatLab/Webremote/ViewFactory/CreatejsViewFactory",["CatLab/Webremote/Tools/Deferred"],function(t){function e(e){void 0!==e&&this.setAssets(e)}var r,s,a,l,n=e.prototype;return n.initialize=function(){var e=new t;return this.loadAssets().then(function(){this.setAssets(this.assets),e.resolve()}.bind(this)),e},n.loadAssets=function(){var o=new t;return require(["CatLab/Webremote/CreateJS/LayerContainer","CatLab/Webremote/CreateJS/Views/PortalView","CatLab/Webremote/CreateJS/Views/AuthenticationView","CatLab/Webremote/CreateJS/Views/AlertView"],function(e,t,n,i){r=e,s=t,a=n,l=i,o.resolve()}.bind(this)),o.promise()},n.portal=function(e){return e.assets=this.assets,new s(e)},n.authentication=function(e){return e.assets=this.assets,new a(e)},n.alert=function(e){return e.assets=this.assets,new l(e)},n.setAssets=function(e){void 0!==e&&(this.assets=e)},n.getContainer=function(){var e=new r;return e.setBounds(0,0,this.assets.properties.width,this.assets.properties.height),e.loading(),e},e}),define("CatLab/Webremote/PlayerPool/GameLogic",["CatLab/Webremote/Tools/Deferred"],function(n){function e(){}var t=e.prototype;return t.setPool=function(e){return this.pool=e,this},t.createPlayer=function(e,t){return null},t.createPlayerConnection=function(e,t){return null},t.onPlayerJoined=function(e){},t.onPlayerActivated=function(e,t){},t.onPlayerJoinedComplete=function(e){},t.getDefaultPlayerName=function(e,t){return null},t.serializePlayer=function(e,t){return e.serialize()},t.playerMatchesFilter=function(e,t){return!1},t.onReset=function(){},t.onResetGameState=function(){},t.comparePlayers=function(e,t){return 0},t.getRandomPickComparator=function(e){return null},t.getMaxPlayers=function(){return null},t.getMaxPlayersForMode=function(e){return this.getMaxPlayers()},t.setMaxPlayers=function(e){return!1},t.addAccessToken=function(e){},t.checkForLicenses=function(e){var t=new n;return t.resolve(e),t.promise()},t.decorateWebcontrolOptions=function(e,t){},t.onWebcontrolInitialized=function(e,t){},t.onGroupCreating=function(e,t){},t.onKeyboardUserChanged=function(e,t){},t.onGroupCreated=function(e,t){},t.getViewId=function(e){return null},t.getDefaultAvatarUrl=function(){return null},t.getPortalCustomFunctions=function(){return{}},t.serializeGameState=function(){return{}},t.restoreGameState=function(e,t){},e}),define("CatLab/Webremote/PlayerPool/Player",["backbone"],function(e){var n=e.Model.extend({initialize:function(e,t){this._getGameLogic=t&&t.getGameLogic||null,void 0!==this.get("hasAnsweredAnyQuestion")&&void 0===this.get("hasParticipated")&&this.set("hasParticipated",this.get("hasAnsweredAnyQuestion"))},getGameLogic:function(){return this._getGameLogic?this._getGameLogic():null},getName:function(e){return this.getUser().getNickname()},getPosition:function(){return this.collection?this.collection.getPosition(this):null},getColor:function(){return this.get("user").color},getLocale:function(){return this.getDefaultLocale()},getDefaultLocale:function(){return null},getAvatar:function(){if(!this.getUserField("avatar")){if(!this.getUser())return null;if(void 0===this.getUser().getSmileyUrl)return null;var e=this.getUser().getSmileyUrl();if(e)return e}e=this.getGameLogic(),e=e?e.getDefaultAvatarUrl():null,e=this.getUserField("avatar",e);return e?this.resolveAvatarUrl(e):null},resolveAvatarUrl:function(e){return e},getUserField:function(e,t){t=t||null;var n=this.get("user");return(n=n&&n.getData())&&void 0!==n[e]?n[e]:t},getUser:function(){return this.get("user")},isActive:function(){return!this.get("noShow")||this.get("noShow")<5},setInactive:function(){this.set("noShow",1e3)},pingActive:function(){this.set("noShow",0),this.set("hasParticipated",1)},pingNoShow:function(){this.get("noShow")?this.set("noShow",this.get("noShow")+1):this.set("noShow",1)},isPlaying:function(){return this.get("hasParticipated")||this.isActive()},getId:function(){return this.get("id")?this.get("id"):this.id},hasDisplay:function(){return!!this.get("user")&&this.get("user").hasDisplay()},getLanguage:function(){return this.get("language")},setLanguage:function(e){return this.set("language",e),this},isActivated:function(){return this.get("wasActivated")},activate:function(){this.set("wasActivated",!0)},deactivate:function(){this.set("wasActivated",!1)},kick:function(){this.deactivate()},matchesPlayerFilter:function(e){var t;return null==e||void 0!==e.ids&&0<=e.ids.indexOf(this.getId())||!!(t=this.getGameLogic())&&t.playerMatchesFilter(this,e)},serialize:function(){return{id:this.get("id"),user:this.get("user").getIdentifier(),language:this.get("language"),hasParticipated:this.get("hasParticipated"),extraData:this.get("extraData")}}});return n.unserialize=function(e,t){return new n(e,t)},n}),define("CatLab/Webremote/PlayerPool/DeviceConnection",[],function(){function e(e,t){this.player=t,this.pool=e,this.user=this.player.get("user"),this.cheatsDetected=0,this.lastCheatDetected=null,this.cheatDetectedSincePrompt=!1,"group"===this.player.get("user").getEntityType()&&this.player.get("user").on("user:join",function(){this.player.pingActive()}.bind(this)),this.user.events.on("cheat:detected",function(){this.cheatsDetected++,this.lastCheatDetected=new Date,this.cheatDetectedSincePrompt=!0}.bind(this)),this.lastClick=null,this.beforeNextViewChange=null}var t=e.prototype;return t.isAuthenticated=function(){return this.player.get("user").isAuthenticated()},t.quickClickProtect=function(){return!(this.lastClick&&Date.now()-this.lastClick<500||(this.lastClick=Date.now(),0))},t.beginTimedPrompt=function(e,t,n){void 0!==n&&!n||(this.cheatDetectedSincePrompt=!1),this._setTimerDurationAttribute(e,t)},t._setTimerDurationAttribute=function(e,t){this.pool.isLargeGroup()||(e.domAttribute("timer-countdown","to",Date.now()+t),e.domAttribute("timer-countdown","start",Date.now()))},t.setView=function(e){return"function"==typeof this.beforeNextViewChange&&(this.player.get("user").currentView&&this.beforeNextViewChange(this.player.get("user").currentView),this.beforeNextViewChange=null),this.player.get("user").setView(e)},t.matchesPlayerFilter=function(e){return this.player.matchesPlayerFilter(e)},t.kick=function(){this.player.kick();var e=this.pool.getGameLogic().getViewId("kicked");e&&this.setView(e).control("name").setLabel(this.player.getName())},t.wait=function(){},e}),define("CatLab/Webremote/Collections/PlayerCollection",["backbone","CatLab/Webremote/PlayerPool/Player"],function(e,o){var r=e.Collection.extend({model:o,initialize:function(e,t){this._getKeyboardUser=(t=t||{}).getKeyboardUser||function(){return null},this._getGameLogic=t.getGameLogic||function(){return null}},getPosition:function(e){return this.indexOf(e)+1},getFromId:function(e){return this.findWhere({id:e})},getFromUser:function(t){var n=null;return this.each(function(e){e.get("user").represents(t.getIdentifier())&&(n=e)}),n},hasKeyboardPlayer:function(){var e=this._getKeyboardUser();return!!e&&!!this.getFromUser(e)},comparator:function(e,t){var n=this._getGameLogic();return n?n.comparePlayers(e,t):0},whereActive:function(){return new r(this.filter(function(e){return e.get("user").isActive()}),{getGameLogic:this._getGameLogic,getKeyboardUser:this._getKeyboardUser})},serialize:function(){var t=[];return this.each(function(e){t.push(e.serialize())}),t}});return r.unserialize=function(e,t){for(var n=new r(null,t=t||{}),i=0;i<e.length;i++)n.add(o.unserialize(e[i],t));return n},r}),define("CatLab/Webremote/PlayerPool/RandomPlayerList",["underscore"],function(o){function e(e,t){this.playerPool=e,this._getGameLogic=(t=t||{}).getGameLogic||function(){return null},this.nextRandomPlayers=[],this.tmpNextRandomPlayers=[],this.tmpSelectedRandomPlayers=[]}var t=e.prototype;return t.getRandomPlayers=function(e,t,n,i){void 0===n&&(n=!0);for(var o=[],r=0;r<e;r++)o.push(this.getRandomPlayer(t,n,i));return o},t.resetRandomPlayers=function(e){this.tmpNextRandomPlayers=this.refillRandomPlayers(e,[]),this.commitRandomPlayers()},t.commitRandomPlayers=function(){this.nextRandomPlayers=this.tmpNextRandomPlayers,this.tmpSelectedRandomPlayers=[]},t.addPlayer=function(e){this.nextRandomPlayers.push(e.getId()),this.tmpNextRandomPlayers.push(e.getId())},t.getRandomPlayer=function(e,t,n){if(void 0===t&&(t=!0),0===this.playerPool.activePlayers.length)return null;for(var i=0;;){0===this.tmpNextRandomPlayers.length&&(this.tmpSelectedRandomPlayers.length>=this.playerPool.activePlayers.length?this.tmpNextRandomPlayers=this.refillRandomPlayers(e,[]):this.tmpNextRandomPlayers=this.refillRandomPlayers(e,this.tmpSelectedRandomPlayers));var o=this.tmpNextRandomPlayers.shift(),r=this.playerPool.activePlayers.getFromId(o),s=this.playerPool.getPlayerConnection(r);if(r.isActivated()&&((!t||r.isActive())&&s.matchesPlayerFilter(n)||s.matchesPlayerFilter(n)&&i>this.playerPool.activePlayers.length-1||i>=2*this.playerPool.activePlayers.length))return this.tmpSelectedRandomPlayers.push(o),r;i++}},t.refillRandomPlayers=function(e,t){var n=this.playerPool.activePlayers.filter(function(e){return!!e.isActivated()&&t.indexOf(e.getId())<0}),i=this._getGameLogic(),i=i?i.getRandomPickComparator(e):null,n=i?n.sort(i):o.shuffle(n);return o.map(n,function(e){return e.getId()})},t.serialize=function(){return{nextRandomTeams:this.nextRandomPlayers}},t.unserialize=function(e){this.tmpNextRandomPlayers=[],void 0!==e.nextRandomPlayers?this.tmpNextRandomPlayers=e.nextRandomPlayers:void 0!==e.nextRandomTeams&&(this.tmpNextRandomPlayers=e.nextRandomTeams),this.tmpSelectedRandomPlayers=[]},e}),define("CatLab/Webremote/Tools/Timer/Timer",[],function(){return function(e,t,n){var i,o,r=n;this.id=e,this.callback=t,this.pause=function(){window.clearTimeout(i),r-=new Date-o},this.resume=function(){o=new Date,window.clearTimeout(i),i=window.setTimeout(function(){this.onFinished(),t()}.bind(this),r)},this.stop=function(){window.clearTimeout(i),this.onFinished()},this.onFinished=function(){},this.resume()}}),define("CatLab/Webremote/Tools/Timer/Interval",[],function(){return function(e,t,n,i){var o,r,s,a=0,l=0,c=!0;this.id=e,this.callback=t,this.pause=function(){c||(c=!0,window.clearTimeout(o),window.clearInterval(r),a=n-(new Date-s)%n)},this.resume=function(){c&&(c=!1,s=new Date,window.clearTimeout(o),window.clearInterval(r),o=window.setTimeout(function(){s=new Date,r=window.setInterval(function(){l++,null!==i&&i<=l&&this.stop(),t()}.bind(this),n)}.bind(this),a))},this.stop=function(){window.clearTimeout(o),window.clearInterval(r),this.onFinished()},this.onFinished=function(){},this.resume()}}),define("CatLab/Webremote/Tools/Timer/TimerCollection",["CatLab/Webremote/Tools/Timer/Timer","CatLab/Webremote/Tools/Timer/Interval"],function(i,o){return function(){this.timers=[],this.paused=!1,this.id=0,this.setTimeout=function(e,t){var n=new i(this.id++,e,t);return this.paused&&n.pause(),n.onFinished=function(){this.deleteTimer(n)}.bind(this),this.timers.push(n),n},this.setInterval=function(e,t,n){var i=new o(this.id++,e,t,n);return this.paused&&i.pause(),i.onFinished=function(){this.deleteTimer(i)}.bind(this),this.timers.push(i),i},this.deleteTimer=function(e){e=this.timers.indexOf(e);-1<e&&this.timers.splice(e,1)},this.pause=function(){this.paused=!0,this.timers.forEach(function(e){e.pause()})},this.resume=function(){this.paused=!1,this.timers.forEach(function(e){e.resume()})},this.stop=function(){for(;0<this.timers.length;)this.timers.pop().stop()}}}),define("CatLab/Webremote/PlayerPool/PlayerPool",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/Models/Users/DummyUser","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/PlayerPool/GameLogic","CatLab/Webremote/PlayerPool/Player","CatLab/Webremote/PlayerPool/DeviceConnection","CatLab/Webremote/Collections/PlayerCollection","CatLab/Webremote/PlayerPool/RandomPlayerList","CatLab/Webremote/Tools/Timer/TimerCollection","underscore"],function(e,s,t,o,i,n,r,a,l,c,h,u,d){function f(){this.initializeEventable(),this.globalAccessTokens=[],this.keyboardUser=null,this._localDevices=null,this.reset(),this.timers=new u,this.config={DELAY:0,USE_SMILEYS:!1,MAX_PLAYERS:8,DISABLE_PROXY:!0,ALLOW_LOGIN:!0,oauth2:null,PROXY_URL:null,getWebcontrolOptions:function(){return{}},applyOverrides:function(e){if(e)for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}}}var e=f.prototype=new e,p=(e._poolNumber=1,e.mode="regular",e.reset=function(){this.users=[],this.connectController=null,this._playercount=0,this.maxPlayers=8;var e=this;this.activePlayers=new c(null,{getKeyboardUser:function(){return e.getKeyboardUser()},getGameLogic:function(){return e.getGameLogic()}}),this.playerMap={},this.playerConnections=[],this.rejectedPlayers=[],this._playerTypeCount={},this.currentPlayerMethod=null,this.randomPlayerLists={},this.lastAction=new Date,this._leasedSeats=void 0,this._portalMaxPlayers=void 0,this._cachedMaxPlayers=null,this.onboardView=null,this.onboardViewListener=null,this.pleaseWaitListener=null,this.Webcontrol||(this.Webcontrol=new t),this.resetGameState(),this.pleaseWaitListener&&(this.Webcontrol.off("user:join",this.pleaseWaitListener),this.pleaseWaitListener=null),this.onboardViewListener&&(this.Webcontrol.off("user:join",this.onboardViewListener),this.onboardViewListener=null),this.getGameLogic().onReset()},e.resetGameState=function(){this.started=!1,this.admissionsClosed=!1,this._totalPausedDuration=0,this._pauseStartTime=null,this._pausedSinceWindowStart=!1,this.getGameLogic().onResetGameState()},e.setGameLogic=function(e){return this.gameLogic=e.setPool(this),this},e.getGameLogic=function(){return this.gameLogic||(this.gameLogic=(new r).setPool(this)),this.gameLogic},e._showView=function(e,t){t=this.getGameLogic().getViewId(t);return t&&e.setView(t),t},e.invokePoolMethod=function(e,t){if("function"==typeof this[e])return this[e].apply(this,p(this[e],t));var n=this.getGameLogic();if("function"==typeof n[e])return n[e].apply(n,p(n[e],t));throw new Error("PlayerPool: unknown method "+e)},function(e,t){if(!t||0===t.length||!(i=t[t.length-1])||"object"!=typeof i||!Object.prototype.hasOwnProperty.call(i,"__playerFilters")||1!==Object.keys(i).length)return t;for(var n=t.slice(0,-1),i=t[t.length-1].__playerFilters;n.length<e.length-1;)n.push(void 0);return n.push(i),n});return e.initialize=function(n){(n=void 0===n?{}:n).config&&(this.config=n.config),this._workerHosted=!!n.headless,void 0!==n.playerPoolMode&&(this.mode=n.playerPoolMode),"number"==typeof n.poolNumber&&(this._poolNumber=n.poolNumber),this.trigger("change:mode",this.mode);var t=new s,e=function(){var e,t=new s;return void 0!==n.headless&&n.headless?t.resolve():(this.log("Starting webremote createjs initialization"),void 0!==n.portalAssets?(e=new i(n.portalAssets),this.Webcontrol.setViewFactory(e).then(function(){this.timers.setTimeout(function(){t.resolve()},1)}.bind(this))):(console.error("Portal assets not found!!!"),t.resolve())),t.promise()}.bind(this)();return s.when(e).done(function(){this.log("Start webremote");var e=this.initializeWebcontrol(n);e.done(function(){this.log("Webcontrol loaded")}.bind(this)),s.when(e).done(function(){t.resolve()}.bind(this))}.bind(this)),t.promise()},e.initializeWebcontrol=function(t){var n=new s,i=this,o=this.config.getWebcontrolOptions(),r=t.webcontrolOptions||{};return Object.keys(r).forEach(function(e){o[e]=r[e]}),void 0!==t.headless&&!t.headless||(o.headless=!1),this.getGameLogic().decorateWebcontrolOptions(o,t),this.Webcontrol.initialize(o).then(function(){i.config.DISABLE_PROXY||i.Webcontrol._gamedata&&i.Webcontrol._gamedata.content_proxy&&(i.config.PROXY_URL=i.Webcontrol._gamedata.content_proxy),i.Webcontrol.setMaxUsers(i.config.MAX_PLAYERS),i._licenseToken&&i.Webcontrol.setLicenseToken(i._licenseToken),i.Webcontrol.on("license:capped",function(e){i.trigger("license:capped",e)}),i.config.oauth2&&i.Webcontrol.oAuth(i.config.oauth2,!i.config.ALLOW_LOGIN);function e(){var e=i.Webcontrol.getUsers().filter(function(e){return!e.getEntityType||"group"!==e.getEntityType()||!!(e.users&&0<e.users.length)}).length;i.trigger("change:connections",e)}i.Webcontrol.on("user:join",e),i.Webcontrol.on("user:leave",e),i._notifyConnectedDevices=e,i.getGameLogic().onWebcontrolInitialized(i.Webcontrol,t),n.resolve()}),n.promise()},e.getConnectController=function(n){this.reset(),this._pendingPortalClose=null,this._portalOpening=!0,n.customFunctions=d.extend({},this.getGameLogic().getPortalCustomFunctions(),n.customFunctions||{});var e=this.Webcontrol.portalController(n),t=void 0!==n.start?n.start:function(){};return n.start=function(e){e.forEach(function(e){e.setActive(!0),this.clearConnectScreen(),this.addUser(e)}.bind(this)),t(e)}.bind(this),e.promise.then(function(t){var e;this._portalOpening=!1,this.connectController=t,this._pendingPortalClose?(e=this._pendingPortalClose,this._pendingPortalClose=null,this.closeConnectController(e)):("function"==typeof t.on&&(t.on("active:count",function(e){this.trigger("portal:active:count",e)}.bind(this)),t.on("users:change",function(e){this.trigger("portal:users",e)}.bind(this)),"function"==typeof t.updateUsers)&&t.updateUsers(),t.setMaxPlayers(this._effectivePortalMax(n.maxPlayers)),this.checkForLicenses(this.Webcontrol.getUsers()).then(function(){t.setMaxPlayers(this._effectivePortalMax(this.getMaxPlayersForMode(this.mode)))}.bind(this)),this.Webcontrol.getUsers().forEach(function(e){e.on("login",function(e){this.checkForLicenses([e]).then(function(){t.setMaxPlayers(this._effectivePortalMax(this.getMaxPlayersForMode(this.mode)))}.bind(this))}.bind(this))}.bind(this)),t.on("user:connect",function(e){e.on("login",function(e){this.checkForLicenses([e]).then(function(){t.setMaxPlayers(this._effectivePortalMax(this.getMaxPlayersForMode(this.mode)))}.bind(this))}.bind(this))}.bind(this)))}.bind(this)),e},e.closeConnectController=function(e){var t=this.connectController;t?(this.connectController=null,"start"===e&&"function"==typeof t.finalizeStart?t.finalizeStart():t.destroy()):this._portalOpening&&(this._pendingPortalClose=e)},e.getConnectScreen=function(e){var t=this.getConnectController(e);return this.Webcontrol.portalView(t.messageBus,e)},e.setPublicConnectInfo=function(e){this.connectController&&"function"==typeof this.connectController.setPublicConnectInfo&&this.connectController.setPublicConnectInfo(e)},e.setExternalActivePlayers=function(e){this.connectController&&"function"==typeof this.connectController.setExternalActivePlayers&&this.connectController.setExternalActivePlayers(e)},e.setExternalUsers=function(e){e=e||[],"function"==typeof this.Webcontrol.setExternalPlayerOffset&&this.Webcontrol.setExternalPlayerOffset(e.length),this.connectController&&"function"==typeof this.connectController.setExternalUsers&&this.connectController.setExternalUsers(e)},e.clearConnectScreen=function(){this.connectController=null},e.getAccessTokens=function(){for(var e=new s,t=this.globalAccessTokens.slice(),n=this.Webcontrol.getUsers(),i=0;i<n.length;i++){var o=n[i];o.isAuthenticated()&&t.push(o.getAccessToken())}return e.resolve(t),e.promise()},e.getConnectTokenForDisplay=function(){return this.Webcontrol.getConnectTokenForDisplay()},e.getConnectURL=function(){return this.Webcontrol.getConnectURL()},e.getConnectToken=function(){return this.Webcontrol.getConnectToken()},e.setLocalDeviceRegistry=function(e){this._localDevices=e},e.getLocalDevice=function(e){return this._localDevices?this._localDevices.get(e):null},e.getLocalDevices=function(){return this._localDevices?this._localDevices.list():[]},e.setKeyboardUser=function(e){if("string"==typeof e){var t=this.getLocalDevice(e);if(!(t=!t&&this.Webcontrol&&"function"==typeof this.Webcontrol.getFromIdentifier?this.Webcontrol.getFromIdentifier({type:"user",id:e}):t))throw new Error('setKeyboardUser: unknown device or user "'+e+'"');e=t}e!==this.keyboardUser&&(this.keyboardUser&&(this.keyboardUser.setActive(!1),t=this.getConnectedPlayer(this.keyboardUser))&&t.deactivate(),t=this.keyboardUser,this.keyboardUser=e,this.getGameLogic().onKeyboardUserChanged(e,t))},e.activateKeyboardUser=function(e){var t=this.keyboardUser;if(!t)return!1;t.setActive(!0);var n=this.addUser(t);return void 0!==e&&n&&(e.name&&t.setNickname(e.name),e.email&&(n.get("user").email=e.email),n.set("extraData",e)),!0},e.hasKeyboardPlayer=function(){return this.activePlayers.hasKeyboardPlayer()},e.startGame=function(){var e=new s;return this.ping(!1).then(function(){this.callPlayerConnectionMethod(function(e){e.startGame()})}.bind(this)),e.resolve(),e.promise()},e.newGroup=function(n,i,o){2===arguments.length&&(o=i,i=void 0);var r=new s;return this.Webcontrol.newGroup({shareColor:!0}).then(function(e){e.profiledata.username=n,e.data.set("name",n,!1),e.setNickname(n),e.startInactive=!0,this.getGameLogic().onGroupCreating(e,{name:n,departmentName:i,extra:o});var t=this.addUser(e);void 0!==o&&0<Object.keys(o).length&&(void 0!==o.email&&(t.get("user").email=o.email),t.set("extraData",o)),this.getGameLogic().onGroupCreated(e,{name:n,departmentName:i,extra:o,user:t}),r.resolve(t)}.bind(this)),r.promise()},e.showIndexScreen=function(){var n=new s,i=this;function t(e){var t;e.isMainGroup()&&(t=i.getGameLogic().getViewId("start"))&&((e=e.setView(t)).control("start").click(function(){n.resolve()}),e.control("a").click(function(){n.resolve()}))}var o=this.Webcontrol.on("user:join",function(e){t(e)});return this.Webcontrol.getUsers().forEach(function(e){t(e)}),n.then(function(){var e=new s;return this.Webcontrol.off("user:join",o),this.Webcontrol.getUsers().forEach(function(e){this._showView(e,"pleasewait")}.bind(this)),this.pleaseWaitListener=this.Webcontrol.on("user:join",function(e){e.isMainGroup()&&this._showView(e,"pleasewait")}.bind(this)),e.resolve(),e.promise()}.bind(this))},e.disconnect=function(){var e=new s;return this.Webcontrol.disconnect(),this.log("webremote disconnected"),e.resolve(),e.promise()},e.getAuthenticationController=function(e){return this.Webcontrol.authenticationController(this.getKeyboardUser(),e)},e.refreshConnectedDevices=function(){this._notifyConnectedDevices&&this._notifyConnectedDevices()},e.setLeasedSeats=function(e){var t=this._leasedSeats;this._leasedSeats=e,"number"==typeof t&&t<e&&this.retryRejectedPlayers()},e.setLicenseToken=function(e){this._licenseToken=e,this.Webcontrol&&this.Webcontrol.setLicenseToken(e)},e.setPortalMaxPlayers=function(e){var t=e;"live"!==this.mode&&"presentation"!==this.mode&&(t=Math.min(100,e)),this._portalMaxPlayers=t,this.connectController&&this.connectController.setMaxPlayers(t)},e._effectivePortalMax=function(e){return"number"!=typeof this._portalMaxPlayers?e:"number"!=typeof e?this._portalMaxPlayers:Math.max(e,this._portalMaxPlayers)},e.hasGlobalAccessTokens=function(){return 0<this.globalAccessTokens.length},e.setOnboardView=function(e){this.onboardView=e,this.pleaseWaitListener&&(this.Webcontrol.off("user:join",this.pleaseWaitListener),this.pleaseWaitListener=null),this.onboardViewListener&&this.Webcontrol.off("user:join",this.onboardViewListener),this.Webcontrol.getUsers().forEach(function(e){e.isMainGroup()&&this.addUser(e)}.bind(this)),this.onboardViewListener=this.Webcontrol.on("user:join",function(e){e.isMainGroup()&&this.addUser(e)}.bind(this))},e.showOnboardingView=function(e){"function"==typeof e.showOnboardingView&&e.showOnboardingView(this.onboardView).then(function(){this.callCurrentPlayerConnectionMethod(e)}.bind(this))},e.getMaxPlayers=function(){var e=this.getGameLogic().getMaxPlayers();return null!=e?e:this.maxPlayers},e.getMaxPlayersForMode=function(e){void 0===e&&(e=this.mode);e=this.getGameLogic().getMaxPlayersForMode(e);return null!=e?e:this.getMaxPlayers()},e.setMaxPlayers=function(e){this.getGameLogic().setMaxPlayers(e)||(this.maxPlayers=e,this.connectController&&this.connectController.setMaxPlayers(e),e=this.getMaxPlayers(),this._cachedMaxPlayers!==e&&(this._cachedMaxPlayers=e,this.trigger("change:maxplayers",e)))},e.addAccessToken=function(e){this.getGameLogic().addAccessToken(e)},e.checkForLicenses=function(e){return this.getGameLogic().checkForLicenses(e)},e.getKeyboardUser=function(){return this.keyboardUser},e.addFakePlayer=function(e,t){var n=this.userToPlayer(e);return e.setNickname(t),n.pingActive(),this.addPlayer(n),n},e.createDummyUser=function(e,t,n){n=n||{};var i=new o,i=(this.Webcontrol.addCustomControl(i),this.userToPlayer(i)),e=(i.get("user").setNickname(e),void 0!==n.smiley&&i.get("user").setSmiley(n.smiley),void 0!==t&&i.set("bot",t),n.autonomous&&i.set("autonomous",!0),this.addPlayer(i,!1));return this.addActivePlayer(i,e),i.pingActive(),"number"==typeof n.score&&i.set("score",n.score),this.trigger("player:dummy:created",e,!0===t,n),this.getGameLogic().serializePlayer(i,!0)},e.addUser=function(e){var t=this.getConnectedPlayer(e);return null!==t?this.log("User "+e.id+" was already connected"):(t=this.userToPlayer(e),this.addPlayer(t)),t},e.addPlayer=function(t,e){if(!(e=void 0===e?!0:e)||this.checkPlayerCapacity(t))return e=this.getGameLogic().createPlayerConnection(this,t)||new l(this,t),this.playerConnections.push(e),t.deactivate(),this.getRandomPlayerLists().forEach(function(e){e.addPlayer(t)}),this.connectController||this.getGameLogic().onPlayerJoined(e)||this.callCurrentPlayerConnectionMethod(e)||(this.addActivePlayer(t,e),e.wait()),this.trigger("user:join"),this.updateActivePlayers(),this.getGameLogic().onPlayerJoinedComplete(e),e},e.checkPlayerCapacity=function(e){var t;return"live"===this.mode||(t="number"==typeof this._leasedSeats?this._leasedSeats:this.getMaxPlayers(),!(this.actualPlayersLength>=t&&(this._showView(e.get("user"),"maxPlayers"),this.isPlayerRejected(e)||this.rejectedPlayers.push(e),1)))},e.retryRejectedPlayers=function(){var i;0!==this.rejectedPlayers.length&&(this.started?(this.log("Game already started, clearing rejected players list"),this.rejectedPlayers=[]):(this.log("Retrying "+this.rejectedPlayers.length+" rejected players after capacity increase"),i=this.Webcontrol.getUsers(),this.rejectedPlayers.slice().forEach(function(e){var t,n=e.get("user");this.isUserStillConnected(n,i)?(this.removeRejectedPlayer(e),this.log("Retrying player: "+n.id),(t=this.addPlayer(e,!0))?this.onboardView?this.showOnboardingView(t):this._showView(n,"pleasewait"):this.isPlayerRejected(e)||this.rejectedPlayers.push(e)):(this.removeRejectedPlayer(e),this.log("User "+n.id+" disconnected, skipping retry"))}.bind(this))))},e.removeRejectedPlayer=function(e){e=this.rejectedPlayers.indexOf(e);-1<e&&this.rejectedPlayers.splice(e,1)},e.isPlayerRejected=function(e){var t=e.get("user");return this.rejectedPlayers.some(function(e){return e.get("user")===t})},e.isUserStillConnected=function(t,e){return(e=e||this.Webcontrol.getUsers()).some(function(e){return e===t||e.id===t.id})},e.addActivePlayer=function(e,t){this.activePlayers.push(e),e.collection=this.activePlayers,e.activate(),this.getGameLogic().onPlayerActivated(e,t),this.admissionsClosed&&setTimeout(function(){t.eliminate()},1)},e.updateActivePlayers=function(){this.trigger("change:length",this.length)},e.getPlayers=function(){var e=new s;return e.resolve(this.activePlayers),e.promise()},e.forEachPlayer=function(t){return this.getPlayers().then(function(e){e.each(t)})},e.getPlayerConnection=function(t){var e=this.playerConnections.find(function(e){return e.player.getId()===t.id});if(e)return e;this.log("Connection for player not found!",t)},e.hasUser=function(e){return null!==this.getConnectedPlayer(e)},e.getConnectedPlayer=function(e){for(var t=0;t<this.playerConnections.length;t++)if(this.playerConnections[t].user===e)return this.playerConnections[t].player;return null},e._mintPlayerId=function(){return this._playercount++,this._poolNumber+"-"+this._playercount},e.userToPlayer=function(e){var t={id:this._mintPlayerId(),user:e,connectToken:e.getConnectToken(),connectTokenForDisplay:e.getConnectTokenForDisplay()},n=this,i={getGameLogic:function(){return n.getGameLogic()}},o=this.getGameLogic().createPlayer(t,i)||new a(t,i);return this.playerMap[o.getId()]=o,!e.startInactive&&e.isActive()||(o.setInactive(),e.isActive())||e.once("active:activate",function(){o.pingActive()}),e.on("active:change",this.updateActivePlayers,this),o},e.getDefaultPlayerName=function(e){var t=e.getType(),t=(void 0===this._playerTypeCount[t="mobile"===t?"player":t]&&(this._playerTypeCount[t]=0),this._playerTypeCount[t]++,this._playerTypeCount[t]),e=this.getGameLogic().getDefaultPlayerName(e,t);return null!=e?e:"Player "+t},e.hasNonDisplayUsers=function(e){for(var t,n=0;n<this.activePlayers.length;n++)if(!(t=this.activePlayers.at(n)).get("user").hasDisplay()){if(t.get("user").hasKeyboardInput()&&t.get("user").hasTouchInput()&&void 0!==e&&!0===e&&this.getKeyboardUser()&&t.get("user")===this.getKeyboardUser())continue;return!0}return!1},e.getNavigationUsers=function(e){var t;return(e=void 0===e?!0:e)?t=this.Webcontrol.getUsers():(t=[],this.Webcontrol.getUsers().forEach(function(e){e.hasDisplay()||t.push(e)})),t},e.callPlayerConnectionMethod=function(e,t,n){var i=[];return this.currentPlayerMethod=e,this.playerConnections.forEach(function(e){(n||e.player.isActivated())&&e.matchesPlayerFilter(t)&&i.push(this.currentPlayerMethod(e))}.bind(this)),s.when.apply(this,i)},e.clearPlayerConnectionMethod=function(){this.currentPlayerMethod=null},e.callCurrentPlayerConnectionMethod=function(e){return null!==this.currentPlayerMethod&&(this.currentPlayerMethod(e),!0)},e.countActivePlayers=function(){return this._countActivePlayers()},e._countActivePlayers=function(){var t=0;return this.activePlayers.each(function(e){e.isActive()&&t++}),t},e.sortPlayers=function(){this.activePlayers.sort()},e.isLargeGroup=function(){return this.length>(this.config.LARGE_GROUP_THRESHOLD||350)},e.getRandomPlayerLists=function(){var e,t=[];for(e in this.randomPlayerLists)this.randomPlayerLists.hasOwnProperty(e)&&t.push(this.randomPlayerLists[e]);return t},e.kickUser=function(e){e=this.getPlayerConnection(e);e.kick(),this.activePlayers.remove(e.player),this.updateActivePlayers()},e.requestNewNickname=function(e){var t=this.getPlayerConnection(e);if(!t)return!1;t.requestNewNickname().then(function(){this.callCurrentPlayerConnectionMethod(t)}.bind(this))},Object.defineProperty(e,"length",{get:function(){return this.activePlayers.size()}}),Object.defineProperty(e,"actualPlayersLength",{get:function(){return this.activePlayers.filter(function(e){return!e.get("bot")}).length}}),e.log=function(e){console.log("[PlayerPool] ",e)},e.pause=function(){this.Webcontrol.pause(),this.timers.pause(),this._pauseStartTime||(this._pauseStartTime=(new Date).getTime()),this._pausedSinceWindowStart=!0},e.resume=function(){this.Webcontrol.unpause(),this.timers.resume(),this._pauseStartTime&&(this._totalPausedDuration+=(new Date).getTime()-this._pauseStartTime,this._pauseStartTime=null)},e.getPausedDuration=function(){var e=this._totalPausedDuration;return this._pauseStartTime&&(e+=(new Date).getTime()-this._pauseStartTime),e},e.resetPauseWindow=function(){this._totalPausedDuration=0,this._pauseStartTime=this._pauseStartTime?(new Date).getTime():null,this._pausedSinceWindowStart=!1},e.wasPausedSinceWindowStart=function(){return this._pausedSinceWindowStart},e.ping=function(e){e&&(this.lastAction=new Date);var t=new s;return 0<this.config.DELAY?this.timers.setTimeout(function(){t.resolve()},this.config.DELAY):t.resolve(),t.promise()},e.isMajorityAuthenticated=function(){var t=0,n=0;return this.playerConnections.forEach(function(e){n++,e.isAuthenticated()&&t++}),.5<t/n},e.shouldShowAvatars=function(){return!!this.config.USE_SMILEYS||this.isMajorityAuthenticated()},e.isDelayed=function(e){return this.config.DELAY>((e=void 0===e?!0:e)?5e3:1e3)},e.preloadFiles=function(e){var t=new s;return this.Webcontrol.preload(e).then(function(){t.resolve()}),t.promise()},e.getPreloadedUrl=function(e){return this.Webcontrol.getPreloadedUrl(e)},e.getRandomPlayerList=function(e){var t;return void 0===this.randomPlayerLists[e]&&((t=this).randomPlayerLists[e]=new h(this,{getGameLogic:function(){return t.getGameLogic()}})),this.randomPlayerLists[e]},e.getRandomPlayers=function(e,t,n,i,o){for(var r=this.getRandomPlayerList(t).getRandomPlayers(e,n,i,o),s=[],a=0;a<r.length;a++)s.push(this.getGameLogic().serializePlayer(r[a]));return s},e.getAbsoluteRandomPlayers=function(e){var t=d.shuffle(this.activePlayers.toArray());return d.first(t,e).map(function(e){return this.getGameLogic().serializePlayer(e)}.bind(this))},e.resetRandomPlayers=function(e,t){this.getRandomPlayerList(e).resetRandomPlayers(t)},e.commitRandomPlayers=function(e){this.getRandomPlayerList(e).commitRandomPlayers()},e.serialize=function(){var e,t={};for(e in t.players=this.activePlayers.serialize(),t.remoteData=this.Webcontrol.state.getData(),t.playerCount=this._playercount,t.playerTypeCount=this._playerTypeCount,t.mode=this.mode,t.eliminateNewPlayers=this.admissionsClosed,t.poolNumber=this._poolNumber,t.randomPlayerLists=[],this.randomPlayerLists)this.randomPlayerLists.hasOwnProperty(e)&&t.randomPlayerLists.push({name:e,data:this.randomPlayerLists[e].serialize()});return d.extend(t,this.getGameLogic().serializeGameState()),t},e.restore=function(e,t){void 0===t&&(t=!1),void 0!==e.randomPlayerLists&&e.randomPlayerLists.forEach(function(e){this.getRandomPlayerList(e.name).unserialize(e.data)}.bind(this)),this._playercount=e.playerCount,this._playerTypeCount=e.playerTypeCount,"number"==typeof e.poolNumber&&(this._poolNumber=e.poolNumber),void 0!==e.admissionsClosed?this.admissionsClosed=e.admissionsClosed:void 0!==e.eliminateNewPlayers&&(this.admissionsClosed=e.eliminateNewPlayers);e=this.getGameLogic().restoreGameState(e,t);return e&&"function"==typeof e.promise?e.promise():e&&"function"==typeof e.then?e:((t=new s).resolve(),t.promise())},f}),define("CatLab/Webremote/PlayerPool/LocalDevices/LocalDeviceUser",["CatLab/Webremote/Models/Users/ControlUser"],function(n){function e(e,t,n,i){i=i||{},this._deviceId=e,this._profile=t,this._sink=n,this._deviceOptions=i,this._proxies={},this._backState={lastBackButtonClick:new Date(0)},this.initialize({id:e});var o=this;this.on("view:set",function(){o.clearControls()}),this.on("login",function(){o.pushState(),o._sink&&o._sink.output("login",{user:o.getUserSummary()})}),this.on("logout",function(){o.pushState(),o._sink&&o._sink.output("logout",{})}),this.on("login:failed",function(){o.pushState()}),this.on("active:change",function(){o.pushState()}),this.on("user:nickname",function(){o.pushState()}),this.clearControls()}var t=e.prototype=Object.create(n.prototype);return t.constructor=e,t.getDeviceId=function(){return this._deviceId},t.getProfile=function(){return this._profile},t.getType=function(){return this._profile.type},t.getIcon=function(){return this._profile.icon},t.hasDisplay=function(){return this._profile.capabilities.hasDisplay},t.hasKeyboardInput=function(){return this._profile.capabilities.hasKeyboardInput},t.hasTouchInput=function(){return this._profile.capabilities.hasTouchInput},t.getPortalControls=function(){return this._profile.portalControls},t.getAvailableControls=function(){return this._profile.keys.map(function(e){return e.id})},t.hasControl=function(e){return-1!==this.getAvailableControls().indexOf(e)},t.emit=function(){return!1},t.isLocalAuthentication=function(){return!1},t.setStaticLabels=function(){var n=this._profile.labelsFor(this._deviceOptions),i=this;Object.keys(n).forEach(function(e){var t=n[e];i.control(e).setStaticLabel(t.label,t.type,t.image,t.emoji)})},t.clearControls=function(){n.prototype.clearControls.call(this),this._proxies={},this._sink&&this._sink.output("controls:cleared",{})},t.setOptions=function(e){this._deviceOptions=e||{},this.clearControls()},t.logout=function(e){n.prototype.logout.call(this,e),this.eventableTrigger("logout")},t.getUserSummary=function(){var e,t=this.getUser();return t?{id:(e=function(e){e="function"==typeof t[e]?t[e]():null;return void 0===e?null:e})("getId"),name:e("getName"),avatar:e("getAvatar"),nickname:this.getNickname()}:null},t.pushState=function(){this._sink&&this._sink.output("state",{authenticated:this.isAuthenticated(),accessToken:this.getAccessToken(),nickname:this.getNickname(),active:this.isActive(),playerId:void 0===this.playerId?null:this.playerId})},t.bindProxy=function(e,t){var n,i;this._proxies[e]=this._proxies[e]||{},this._proxies[e][t]||((n=this)._proxies[e][t]=i=function(){n._sink&&n._sink.output("control:"+t,{id:e})},this.control(e).on(t,i))},t.unbindProxy=function(e,t){var n=this._proxies[e]&&this._proxies[e][t];n&&(this.control(e).off(t,n),delete this._proxies[e][t])},t.trigger=function(e,t){switch(t=t||{},e){case"button:down":if(this._profile.onButtonDown(this,t.id,this._sink))return;break;case"view:changeValue":return void(this.currentView&&"function"==typeof this.currentView.changeValue&&this.currentView.changeValue(t.key,t.value));case"control:bind":return void this.bindProxy(t.id,t.event);case"control:unbind":return void this.unbindProxy(t.id,t.event);case"nickname":return void this.setNickname(t.name);case"active":return void this.setActive(!!t.value);case"backbutton":return void this._profile.onBackButton(this,this._sink,this._backState)}n.prototype.trigger.call(this,e,t)},e}),define("CatLab/Webremote/PlayerPool/LocalDevices/Profiles/shared",[],function(){function i(e,t){return!!(Array.isArray(e)&&-1<e.indexOf(t))||e==t}return{keyMatches:i,mapKey:function(e,t){for(var n=0;n<e.length;n++){if(void 0!==e[n].code&&i(e[n].code,t.code))return e[n].id;if(void 0!==e[n].key&&i(e[n].key,t.key))return e[n].id;if(void 0!==e[n].keyCode&&i(e[n].keyCode,t.keyCode))return e[n].id}return null},labelsFor:function(t,e){var n={};return t.keys.forEach(function(e){n[e.id]={label:e.label,type:t.type,image:void 0===e.image?null:e.image,emoji:void 0===e.emoji?null:e.emoji}}),n}}}),define("CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Keyboard",["CatLab/Webremote/PlayerPool/LocalDevices/Profiles/shared"],function(t){var n=[{id:"up",label:"↑",code:"ArrowUp",emoji:"⬆️"},{id:"down",label:"↓",code:"ArrowDown",emoji:"⬇️"},{id:"right",label:"→",code:"ArrowRight",emoji:"➡️"},{id:"left",label:"←",code:"ArrowLeft",emoji:"⬅️"},{id:"a",label:"A",code:["KeyA","Enter","NumpadEnter"],emoji:"🅰"},{id:"b",label:"B",code:"KeyB",emoji:"🅱"},{id:"x",label:"X",code:"KeyX",emoji:"🆇"},{id:"y",label:"Y",code:"KeyY",emoji:"🆈"},{id:"back",label:"Escape",code:"Escape",emoji:"🇪"},{id:"start",label:"S",code:["KeyS"],emoji:"🆂"}],e={kind:"keyboard",keys:n,portalControls:{start:"start",back:"back",toggleActive:"up",authenticate:"y",left:"left",right:"right"},capabilities:{hasDisplay:!1,hasKeyboardInput:!0,hasTouchInput:!0},type:"keyboard",icon:"fa fa-keyboard-o",exitOnUnassignedBackButton:!1,backButtonControl:null,mapKey:function(e){return t.mapKey(n,e)},mapGamepadButton:function(){return null},labelsFor:function(){return t.labelsFor(e)},preventDefaultFor:function(e){for(var t=0;t<n.length;t++)if(n[t].id===e)return!!n[t].preventDefault;return!1},onButtonDown:function(e,t,n){return!("back"!==t||!this.exitOnUnassignedBackButton||e.control("back").hasTriggers("click")||e.control("back").hasTriggers("up")||e.control("back").hasTriggers("down")||(n.app("requestExit"),0))},onBackButton:function(){}};return e}),define("CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Cordova",["CatLab/Webremote/PlayerPool/LocalDevices/Profiles/shared"],function(t){var n=[{id:"up",label:"↑",key:38},{id:"down",label:"↓",key:40},{id:"right",label:"→",key:39},{id:"left",label:"←",key:37},{id:"start",label:"ENTER",key:13},{id:"back",label:"BACK",key:null}],e={kind:"cordova",keys:n,portalControls:{start:"start",back:"back",toggleActive:"up",authenticate:"y",left:"left",right:"right"},capabilities:{hasDisplay:!1,hasKeyboardInput:!0,hasTouchInput:!0},type:"keyboard",icon:"fa fa-keyboard-o",exitOnUnassignedBackButton:!0,backButtonControl:"back",mapKey:function(e){return t.mapKey(n,e)},mapGamepadButton:function(){return null},labelsFor:function(){return t.labelsFor(e)},preventDefaultFor:function(e){for(var t=0;t<n.length;t++)if(n[t].id===e)return!!n[t].preventDefault;return!1},onButtonDown:function(){return!1},onBackButton:function(e,t,n){var i,o=new Date;o.getTime()-n.lastBackButtonClick.getTime()<300?t.app("requestExit"):(n.lastBackButtonClick=o,!this.exitOnUnassignedBackButton||e.control("back").hasTriggers("click")||e.control("back").hasTriggers("up")||e.control("back").hasTriggers("down")?this.backButtonControl&&(e.control(this.backButtonControl).update(1),i=this,setTimeout(function(){e.control(i.backButtonControl).update(0)},1)):setTimeout(function(){t.app("minimize")},350))}};return e}),define("CatLab/Webremote/PlayerPool/LocalDevices/Profiles/AndroidRemote",["CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Cordova","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/shared"],function(i,t){var n=[{id:"up",label:"↑",keyCode:38,preventDefault:!0,image:"control-icons/android-tv/$SIZE/android-tv-up.gif",emoji:"⬆️"},{id:"down",label:"↓",keyCode:40,preventDefault:!0,image:"control-icons/android-tv/$SIZE/android-tv-down.gif",emoji:"⬇️"},{id:"right",label:"→",keyCode:39,preventDefault:!0,image:"control-icons/android-tv/$SIZE/android-tv-right.gif",emoji:"➡️"},{id:"left",label:"←",keyCode:37,preventDefault:!0,image:"control-icons/android-tv/$SIZE/android-tv-left.gif",emoji:"⬅️"},{id:"a",label:"ENTER",keyCode:13,preventDefault:!0,emoji:"🅰"},{id:"back",label:"BACK",keyCode:null},{id:"start",label:"⏯",keyCode:179},{id:"fastforward",label:"⏩",keyCode:228},{id:"fastforward",label:"⏪",keyCode:227}],e={kind:"androidremote",keys:n,portalControls:{start:"start",back:"back",toggleActive:"up",authenticate:"down",left:"left",right:"right"},capabilities:{hasDisplay:!1,hasKeyboardInput:!1,hasTouchInput:!1},type:"keyboard",icon:"fa fa-keyboard-o",exitOnUnassignedBackButton:!1,backButtonControl:"back",mapKey:function(e){return t.mapKey(n,e)},mapGamepadButton:function(){return null},labelsFor:function(){return t.labelsFor(e)},preventDefaultFor:function(e){for(var t=0;t<n.length;t++)if(n[t].id===e)return!!n[t].preventDefault;return!1},onButtonDown:function(){return!1},onBackButton:function(e,t,n){return i.onBackButton.call(this,e,t,n)}};return e}),define("CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Gamepad",[],function(){var i={12:"DPAD_UP",13:"DPAD_DOWN",15:"DPAD_RIGHT",14:"DPAD_LEFT",0:"FACE_1",1:"FACE_2",2:"FACE_3",3:"FACE_4",8:"SELECT_BACK",9:"START_FORWARD"},s=[{id:"up",label:"↑",key:"DPAD_UP",emojiKey:"up"},{id:"down",label:"↓",key:"DPAD_DOWN",emojiKey:"down"},{id:"right",label:"→",key:"DPAD_RIGHT",emojiKey:"right"},{id:"left",label:"←",key:"DPAD_LEFT",emojiKey:"left"},{id:"a",label:"A",key:"FACE_1",emojiKey:"a",hasImage:!0},{id:"b",label:"B",key:"FACE_2",emojiKey:"b",hasImage:!0},{id:"x",label:"X",key:"FACE_3",emojiKey:"x",hasImage:!0},{id:"y",label:"Y",key:"FACE_4",emojiKey:"y",hasImage:!0},{id:"back",label:"SELECT",key:"SELECT_BACK"},{id:"start",label:"START",key:"START_FORWARD"},{id:"l1",label:"L1",key:"L1",emojiKey:"l1"},{id:"r1",label:"R1",key:"R1",emojiKey:"r1"}],a={a:"🅰️",b:"🅱️",x:"❎",y:"❎",up:"⬆️",down:"⬇️",left:"⬅️",right:"➡️",l1:"🤜",r1:"🤛"},l={a:"❎",b:"⭕",x:"🟥",y:"🔺",up:"⬆️",down:"⬇️",left:"⬅️",right:"➡️",l1:"🤜",r1:"🤛"};return{kind:"gamepad",deviceIdPrefix:"gamepad",keys:s,portalControls:{start:"start",back:"back",toggleActive:"x",authenticate:"y",left:"left",right:"right"},capabilities:{hasDisplay:!1,hasKeyboardInput:!1,hasTouchInput:!1},type:"gamepad",icon:"fa fa-gamepad",exitOnUnassignedBackButton:!1,backButtonControl:null,mapKey:function(){return null},mapGamepadButton:function(e){var t=i[e];if(t)for(var n=0;n<s.length;n++)if(s[n].key===t)return s[n].id;return null},labelsFor:function(e){var e=void 0!==(e=(e=e||{}).id)&&(-1!==e.toLowerCase().indexOf("sony")||-1!==e.toLowerCase().indexOf("054c")),t=e?"control-icons/ps-controller/$SIZE/":"control-icons/gamepad/$SIZE/",n=e?"ps-controller-":"gamepad-",i=e?"🕹":"🎮",o=e?l:a,r={};return s.forEach(function(e){r[e.id]={label:e.label,type:"gamepad",image:e.hasImage?t+n+e.id+".gif":null,emoji:e.emojiKey?i+"‍"+o[e.emojiKey]:null}}),r},preventDefaultFor:function(){return!1},onButtonDown:function(){return!1},onBackButton:function(){}}}),define("CatLab/Webremote/PlayerPool/LocalDevices/Profiles/index",["CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Keyboard","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Cordova","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/AndroidRemote","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Gamepad"],function(e,t,n,i){var o={keyboard:e,cordova:t,androidremote:n,gamepad:i};return{keyboard:e,cordova:t,androidremote:n,gamepad:i,forKind:function(e){if(o[e])return o[e];throw new Error('LocalDevices: unknown device kind "'+e+'"')}}}),define("CatLab/Webremote/PlayerPool/LocalDevices/DeviceRegistry",["CatLab/Webremote/PlayerPool/LocalDevices/LocalDeviceUser","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/index","CatLab/Webremote/Transport/Errors"],function(i,o,n){function e(e,t){this._pool=e,this._channels=t,this._devices={},this._displayBus=null,this._originalToView=null}var r=["keyboard","cordova","androidremote"],t=e.prototype;return t._sinkFor=function(n){var i=this;return{output:function(e,t){i._channels.isClosed()||i._channels.send("device","output",{device:n,method:e,data:t||{}})},app:function(e){i._channels.isClosed()||i._channels.send("device","output",{device:n,method:"app",data:{action:e}})}}},t._syncPool=function(e,t){t?this._pool.Webcontrol.trigger("user:leave",e):"function"==typeof this._pool._notifyConnectedDevices&&this._pool._notifyConnectedDevices();t=this._pool.connectController;t&&"function"==typeof t.updateUsers&&t.updateUsers()},t.connect=function(e){var t,n=this;"display"===e.kind?(t=this._pool.Webcontrol.getMessageBus(),this._displayBus!==t&&(this._displayBus=t,this._originalToView=t.toView),t.toView=function(e,t){n._channels.isClosed()||n._channels.send("device","output",{device:"display",method:"bus",data:{action:e,content:t}})}):(t=this._devices[e.device])&&t.getProfile().kind===e.kind?(t.setOptions(e.options||{}),-1!==r.indexOf(e.kind)&&this._pool.setKeyboardUser(t),this._syncPool(t,!1),this._pool.trigger("device:reconnected",{device:e.device})):(t&&(t.setActive(!1),delete this._devices[e.device]),t=o.forKind(e.kind),t=new i(e.device,t,this._sinkFor(e.device),e.options||{}),this._devices[e.device]=t,this._pool.Webcontrol.addCustomControl(t),-1!==r.indexOf(e.kind)&&this._pool.setKeyboardUser(t),t.pushState())},t.disconnect=function(e){var t=this._devices[e.device];t&&(t.setActive(!1),this._syncPool(t,!0),this._pool.trigger("device:disconnected",{device:e.device}))},t.input=function(e){if("display"===e.device){if("bus"===e.method)return void this._pool.Webcontrol.getMessageBus().handleControllerMessage(e.data.action,e.data.content);throw new n.TransportError('unexpected display input "'+e.method+'"')}var t=this._devices[e.device];if(!t)throw new n.TransportError('input for unknown device "'+e.device+'"');t.trigger(e.method,e.data)},t.get=function(e){return this._devices[e]||null},t.each=function(t){var n=this;Object.keys(this._devices).forEach(function(e){t(n._devices[e],e)})},t.list=function(){return Object.keys(this._devices)},t.dispose=function(){this.each(function(e){"function"==typeof e.setActive&&e.setActive(!1)}),this._displayBus&&(this._displayBus.toView=this._originalToView,this._displayBus=null,this._originalToView=null)},e}),define("CatLab/Webremote/Transport/Codec",["CatLab/Webremote/Transport/Errors"],function(e){var d=e.TransportError,h=e.RemoteError,g=["__type","__date","__callback","__error"],m=[],u={};function v(e,t){e=new d(t+" cannot cross the worker boundary",e);throw e.transportKind=t,e}function b(e){e=Object.getPrototypeOf(e);return e===Object.prototype||null===e}function y(e){var t;return null===e?"null":"function"==typeof e?"function":"object"!=typeof e?typeof e:Array.isArray(e)?"Array":e instanceof Date?"Date":"Object"!==(t=(t=e.constructor)&&t.name?t.name:"Object")||b(e)?t:"anonymous class"}function w(e,t,n,i,o){if(i=i||[],o=o||0,null==e||"boolean"==typeof e||"string"==typeof e)return e;if("number"==typeof e)return e!=e&&v(t,"NaN"),e!==1/0&&e!==-1/0||v(t,"Infinity"),e;if("function"==typeof e){if(n&&"function"==typeof n.callback)return n.callback(e,t,o);v(t,"function")}if("object"!=typeof e&&v(t,typeof e),e instanceof Date)return e.getTime()!=e.getTime()&&v(t,"invalid Date"),{__date:e.toISOString()};if(-1!==i.indexOf(e)&&v(t,"cycle"),e instanceof Error)return _(e,t,n,i,o);var r,s=(e=>{for(var t=0;t<m.length;t++)if(m[t].test(e))return m[t];return null})(e);if(s)return i.push(e),r=w(s.serialize(e),t,n,i,o+1),i.pop(),{__type:s.name,data:r};if(Array.isArray(e)){i.push(e);for(var a=new Array(e.length),l=0;l<e.length;l++){var c=w(e[l],t+"["+l+"]",n,i,o+1);a[l]=void 0===c?null:c}return i.pop(),a}("function"==typeof e.then||"function"==typeof e.done&&"function"==typeof e.fail)&&v(t,"promise"),b(e)||v(t,"Map"===(s=y(e))||"Set"===s||/Array$/.test(s)?s:s+" instance"),i.push(e);for(var h={},u=Object.keys(e),d=0;d<u.length;d++){var f=u[d],p=(-1!==g.indexOf(f)&&v(t+"."+f,"reserved key"),w(e[f],t+"."+f,n,i,o+1));void 0!==p&&(h[f]=p)}return i.pop(),h}function _(e,t,n,i,o){o=o||0,(i=i||[]).push(e);for(var r={},s=!1,a=Object.keys(e),l=0;l<a.length;l++){var c=a[l];if(!("name"===c||"message"===c||"stack"===c||"remoteStack"===c||"isRemote"===c||"data"===c&&e.isRemote))try{var h=w(e[c],t+"."+c,n,i,o+1);void 0!==h&&(r[c]=h,s=!0)}catch(e){if(e instanceof d&&"cycle"===e.transportKind)throw e}}i.pop();var u=s?r:null;return e.isRemote&&(u=void 0===e.data?null:e.data),{__error:{name:e.name||"Error",message:e.message||String(e),stack:e.remoteStack||e.stack||"",data:u}}}return{encode:function(e,t,n){return w(e,t||"value",n)},decode:function e(t,n,i){if(i=i||"message",null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var o=new Array(t.length),r=0;r<t.length;r++)o[r]=e(t[r],n,i+"["+r+"]");return o}if(Object.prototype.hasOwnProperty.call(t,"__date")){if("string"!=typeof t.__date)throw new d("invalid date record",i);var s=new Date(t.__date);if(isNaN(s.getTime()))throw new d("invalid date record",i);return s}if(Object.prototype.hasOwnProperty.call(t,"__error"))return s=t.__error||{},new h({name:s.name,message:s.message,stack:s.stack,data:e(s.data,n,i+".__error.data")});if(Object.prototype.hasOwnProperty.call(t,"__callback")){if(n&&"function"==typeof n.callback)return n.callback(t.__callback,i);throw new d("callback record cannot be decoded here",i)}if(Object.prototype.hasOwnProperty.call(t,"__type")){s=u[t.__type];if(s)return s.unserialize(e(t.data,n,i+".data"));throw new d('unregistered type "'+t.__type+'"',i)}for(var a={},l=Object.keys(t),c=0;c<l.length;c++)a[l[c]]=e(t[l[c]],n,i+"."+l[c]);return a},encodeError:function(e){return _(e,"error",null,[],0)},isErrorRecord:function(e){return!!e&&"object"==typeof e&&Object.prototype.hasOwnProperty.call(e,"__error")},describe:y,registerType:function(e,t){if("string"!=typeof e||!e)throw new Error("Codec.registerType: name required");if(!t||"function"!=typeof t.test||"function"!=typeof t.serialize||"function"!=typeof t.unserialize)throw new Error("Codec.registerType("+e+"): {test, serialize, unserialize} required");if(u[e])throw new Error('Codec.registerType: "'+e+'" is already registered');t={name:e,test:t.test,serialize:t.serialize,unserialize:t.unserialize};m.push(t),u[e]=t},hasType:function(e){return!!u[e]},_reset:function(){m=[],u={}}}}),define("CatLab/Webremote/Transport/Channels",["CatLab/Webremote/Transport/Codec","CatLab/Webremote/Transport/Errors"],function(o,r){function e(e,t){t=t||{},this._port=e,this._open=!1,this._closed=!1,this._queue=[],this._handlers={},this._handlerErrorHandlers=[],this._closeHandlers=[],this._decodeHooks=null,this._onUnhandled=t.onUnhandled||function(e){console.error("[ChannelPort] unhandled message",e)};var n=this;this._unsubscribe=e.onMessage(function(e){n._receive(e)})}var t=e.prototype;return t.on=function(e,t,n){return this._handlers[e]={handler:t,raw:!(!n||!n.raw)},this},t.onHandlerError=function(e){this._handlerErrorHandlers.push(e)},t.setDecodeHooks=function(e){this._decodeHooks=e||null},t._receive=function(e){if(e&&"object"==typeof e&&"string"==typeof e.ch&&"string"==typeof e.type){var t,n=this._handlers[e.ch];if(n){if(n.raw)t=e;else try{t=o.decode(e,this._decodeHooks,e.ch+":"+e.type)}catch(e){return void this._reportHandlerError(e)}try{n.handler(t.type,t)}catch(e){this._reportHandlerError(e)}}else this._onUnhandled(e)}else this._onUnhandled(e)},t._reportHandlerError=function(t){0!==this._handlerErrorHandlers.length?this._handlerErrorHandlers.slice().forEach(function(e){e(t)}):console.error("[ChannelPort] handler threw:",t)},t._buildMessage=function(e,t,n){var i={ch:e,type:t};return n&&Object.keys(n).forEach(function(e){"ch"!==e&&"type"!==e&&(i[e]=n[e])}),i},t._post=function(e,t){this._port.post(e),"function"==typeof t&&t()},t.send=function(e,t,n,i){if(this._closed)throw new r.TransportError("ChannelPort: send after close");i=i||{};n=o.encode(this._buildMessage(e,t,n),e+":"+t,i.encodeHooks||null);this._dispatchOut(e,n,i.onSent)},t.sendEncoded=function(e,t,n,i){if(this._closed)throw new r.TransportError("ChannelPort: send after close");i=i||{},this._dispatchOut(e,this._buildMessage(e,t,n),i.onSent)},t.sendNow=function(e,t,n){if(this._closed)throw new r.TransportError("ChannelPort: send after close");n=o.encode(this._buildMessage(e,t,n),e+":"+t,null);this._post(n,null)},t._dispatchOut=function(e,t,n){this._open||"control"===e?this._post(t,n):this._queue.push({encoded:t,onSent:n})},t.open=function(){if(!this._closed){this._open=!0;var e=this._queue;this._queue=[];for(var t=0;t<e.length;t++)this._post(e[t].encoded,e[t].onSent)}},t.isOpen=function(){return this._open},t.isClosed=function(){return this._closed},t.takeQueue=function(){var e=this._queue;return this._queue=[],e},t.adoptQueue=function(e){if(e&&0!==e.length){if(this._closed)throw new r.TransportError("ChannelPort: adoptQueue after close");if(this._open)for(var t=0;t<e.length;t++)this._post(e[t].encoded,e[t].onSent);else this._queue=e.concat(this._queue)}},t.onClose=function(e){return this._closeHandlers.push(e),this},t.close=function(){if(!this._closed){this._closed=!0,this._open=!1,this._queue=[],this._unsubscribe();var e=this._closeHandlers.slice();this._closeHandlers=[];for(var t=0;t<e.length;t++)try{e[t]()}catch(e){this._reportHandlerError(e)}}},e}),define("CatLab/Webremote/Transport/RpcServer",["CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/Codec","CatLab/Webremote/Transport/Errors"],function(l,c,h){function e(e,t){if("function"!=typeof(t=t||{}).invoke)throw new Error("RpcServer: options.invoke(method, args) is required");this._channels=e,this._invoke=t.invoke,this._reportError=t.reportError||function(e,t){console.error("[RpcServer] "+e,t)};var n=this;e.on("rpc",function(e,t){n._onMessage(e,t)},{raw:!0})}var t=e.prototype;return t._onMessage=function(e,t){"call"===e?this._handleCall(t):this._reportError("rpc",new h.TransportError('unexpected rpc message type "'+e+'"'))},t._handleCall=function(e){function t(e){a||(a=!0,e instanceof Error||(e=new Error(String(e))),o._channels.sendEncoded("rpc","error",{id:r,error:c.encodeError(e)}))}var n,i,o=this,r=e.id,s=e.method,a=!1;try{n=c.decode(e.args||[],{callback:function(t,e){var n=e;return function(){if(a)throw e=new h.TransportError("late callback after "+s+" settled",n),o._reportError("rpc:callback",e),e;var e=Array.prototype.slice.call(arguments);o._channels.send("rpc","callback",{id:r,callbackId:t,args:e})}}},s+".args")}catch(e){return void t(e)}try{i=this._invoke(s,n)}catch(e){return void t(e)}l.when(i).done(function(){if(1<arguments.length)t(new h.TransportError(s+" resolved with "+arguments.length+" values; rpc results are single values"));else{var e;try{e=c.encode(arguments[0],s+".result")}catch(e){return void t(e)}a||(a=!0,o._channels.sendEncoded("rpc","result",{id:r,value:e}))}}).fail(function(e){t(e)})},e}),define("CatLab/Webremote/Transport/WorkerPort",[],function(){function i(e,t,n){n=n||{},this.kind=e,this._target=t,this._listenTarget=n.listenTarget||t,this._targetOrigin=n.targetOrigin||null,this._filter=n.filter||null,this._handlers=[],this._errorHandlers=[],this._closed=!1;var i=this;this._listener=function(e){i._closed||i._filter&&!i._filter(e)||i._deliver(e.data)},this._listenTarget.addEventListener("message",this._listener)}var e=i.prototype;return e._deliver=function(e){for(var t=this._handlers.slice(),n=0;n<t.length;n++)try{t[n](e)}catch(e){this._reportError(e)}},e._reportError=function(t){0!==this._errorHandlers.length?this._errorHandlers.slice().forEach(function(e){e(t)}):console.error("[WorkerPort] message handler threw:",t)},e.post=function(e){if(this._closed)throw new Error("WorkerPort: post after close");null!==this._targetOrigin?this._target.postMessage(e,this._targetOrigin):this._target.postMessage(e)},e.onMessage=function(t){var n=this;return this._handlers.push(t),function(){var e=n._handlers.indexOf(t);-1!==e&&n._handlers.splice(e,1)}},e.onError=function(t){var n=this;return this._errorHandlers.push(t),function(){var e=n._errorHandlers.indexOf(t);-1!==e&&n._errorHandlers.splice(e,1)}},e.close=function(){this._closed||(this._closed=!0,this._listenTarget.removeEventListener("message",this._listener),this._handlers=[],this._errorHandlers=[])},e.isClosed=function(){return this._closed},i.forWorker=function(e){return new i("worker",e)},i.forSelf=function(e){return new i("self",e)},i.forWindow=function(t,e){return new i("window",t,{listenTarget:e,targetOrigin:"*",filter:function(e){return e.source===t}})},i.detect=function(e){var e=e||{},t="importScripts"in e?e.importScripts:"function"==typeof importScripts?importScripts:void 0,n="self"in e?e.self:"undefined"!=typeof self?self:void 0,e="window"in e?e.window:"undefined"!=typeof window?window:void 0;if("function"==typeof t&&n)return i.forSelf(n);if(e&&e.parent&&e.parent!==e)return i.forWindow(e.parent,e);throw new Error("WorkerPort.detect: not in a worker or a frame")},i}),define("CatLab/Webremote/PlayerPool/PlayerPoolWorker",["CatLab/Webremote/Tools/Deferred","CatLab/Webremote/PlayerPool/PlayerPool","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/PlayerPool/LocalDevices/DeviceRegistry","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Transport/Channels","CatLab/Webremote/Transport/RpcServer","CatLab/Webremote/Transport/WorkerPort","CatLab/Webremote/Transport/Codec","CatLab/Webremote/Transport/Errors","CatLab/Webremote/Providers/BridgedProvider"],function(a,i,t,o,r,s,l,c,n,h,u){function d(e,t){this.channels=e,this._bootOptions=t||{},this.playerpool=new i,this.navProxy=null,this._declaredEvents={},this.devices=new o(this.playerpool,e),this.playerpool.setLocalDeviceRegistry(this.devices),this._portal=null,this._auth=null,this._started=!1,this._slingshotInterval=null;var n=this;this._rpc=new l(e,{invoke:function(e,t){return n._invoke(e,t)},reportError:function(e,t){n.reportError(e,t)}}),e.on("control",function(e,t){n._onControl(e,t)}),e.on("device",function(e,t){n._onDevice(e,t)}),e.on("host",function(e,t){n._onHost(e,t)}),e.onHandlerError(function(e){n.reportError("channel",e)}),e.onClose(function(){n.dispose()})}var f=["openPortal","closePortal","openAuthentication","enableNavigation","restore"],p=["applyConfigOverrides"],e=d.prototype;return e.dispose=function(){null!==this._slingshotInterval&&(clearInterval(this._slingshotInterval),this._slingshotInterval=null),this.devices&&this.devices.dispose(),r.setSyncSink(null)},e._onControl=function(e,t){switch(e){case"init":return this._started?void this.reportError("control",new h.TransportError("control:init received twice; this pool has already started")):void this.start(t.options||{});case"ping":return void this.channels.sendNow("control","pong",{id:t.id});default:this.reportError("control",new h.TransportError('unexpected control message "'+e+'"'))}},e.reportError=function(e,t){console.error("[PlayerPoolWorker] "+e,t);try{this.channels.sendEncoded("control","error",{context:e,error:n.encodeError(t instanceof Error?t:new Error(String(t)))})}catch(e){}},e.fatal=function(e){console.error("[PlayerPoolWorker] fatal",e);try{this.channels.sendEncoded("control","fatal",{error:n.encodeError(e instanceof Error?e:new Error(String(e)))})}catch(e){}},e.start=function(e){this._started=!0;var t=e||{},n=(t.headless=!0,(t.events||[]).forEach(function(e){this._declaredEvents[e]=!0},this),this),e=this._selectProvider(t),e=(e&&(t.webcontrolOptions=t.webcontrolOptions||{},(t.webcontrolOptions.provider=e).on("settings",function(){n.sendConnectInformation()})),this.bootstrapAuthStorage(t.authStorage||{}),r.setSyncSink(function(e){n.channels&&!n.channels.isClosed()&&n.channels.send("host","storage",{key:e.name,value:void 0===e.rawValue?null:e.rawValue})}),this._bootOptions.beforeStart),e="function"==typeof e?e(this.playerpool,t):void 0;a.when(e).fail(function(e){console.error("[PlayerPoolWorker] beforeStart rejected; booting anyway.",e)}).always(function(){n._bootOptions.config&&(t.config=n._bootOptions.config),n._startPlayerpool(t)})},e._selectProvider=function(e){e=e.provider;return void 0===e||"socketio"===e?null:"bridged"===e?new u(this.channels):(this.reportError("control",new h.TransportError('unknown provider "'+e+'"')),null)},e._startPlayerpool=function(e){var t=this;this.playerpool.initialize(e).done(function(){t.playerpool.Webcontrol.on("game:initialized",function(){t.sendConnectInformation()}),t._bindDeclaredEvents(),t.sendConnectInformation(),t._declaredEvents["change:mode"]&&t.emitEvent("change:mode",t.playerpool.mode),"function"==typeof t.playerpool.refreshConnectedDevices&&t.playerpool.refreshConnectedDevices(),t._bindSlingshots(),t.channels.sendNow("control","ready",{}),t.channels.open()}).fail(function(e){t.fatal(e||new Error("pool.initialize failed"))})},e.bootstrapAuthStorage=function(e){if("undefined"!=typeof localStorage&&e)for(var t in e)e.hasOwnProperty(t)&&null!==e[t]&&localStorage.setItem(t,e[t])},e.emitEvent=function(e,t){var n;if(!this._declaredEvents[e])throw n=new h.TransportError('undeclared event "'+e+'"'),this.reportError("event:"+e,n),n;try{this.channels.send("events","event",{name:e,data:void 0===t?null:t})}catch(t){throw this.reportError("event:"+e,t),t}},e._bindDeclaredEvents=function(){var t=this,n={"connectInfo:change":!0,"smileys:slingshot":!0,"transport:fallback":!0,"change:mode":!0};Object.keys(this._declaredEvents).forEach(function(e){n[e]||t.playerpool.on(e,function(){t.emitEvent(e,1<arguments.length?arguments[0]:void 0)})}),this._declaredEvents["change:mode"]&&this.playerpool.on("change:mode",function(e){t.emitEvent("change:mode",e)})},e._bindSlingshots=function(){var e,t,n=this;this._declaredEvents["smileys:slingshot"]&&(e=function(e){n.emitEvent("smileys:slingshot",{player:{id:e.user?e.user.getId():null,name:e.user?e.user.getNickname():null,smiley:e.user?e.user.getSmiley():null},angle:e.angle,speed:e.speed,smiley:e.smiley})},t=null,this._slingshotInterval=setInterval(function(){t&&n.playerpool.Webcontrol.off("smileys:slingshot",t),t=n.playerpool.Webcontrol.on("smileys:slingshot",e)},1e3))},e.sendConnectInformation=function(){var e,t;this._declaredEvents["connectInfo:change"]&&(e=this.playerpool.Webcontrol)&&"function"==typeof e.getConnectToken&&(t=e._gamedata||{},this.emitEvent("connectInfo:change",{connectToken:e.getConnectToken(),connectTokenForDisplay:e.getConnectTokenForDisplay(),connectUrl:e.getConnectURL(),server:this.playerpool.server||"",contentProxy:t.content_proxy||null,gameId:void 0===t.id?null:t.id,accessToken:t.accessToken||null}))},e._invoke=function(e,t){if(-1!==f.indexOf(e))return this[e].apply(this,t);if(-1!==p.indexOf(e))throw new h.TransportError("host method not rpc-callable: "+e);return this.playerpool.invokePoolMethod(e,t)},e.openPortal=function(e,t,n){var i=this,o=new a,r=(e=e||{},this._portal),r=(r&&(this._portal=null,r.controller?r.controller._destroyed||r.controller.destroy():r.pendingDestroy=!0),e.start=function(e){"function"==typeof t&&t(e.map(function(e){return{id:e.getId?e.getId():null,accessToken:e.getAccessToken?e.getAccessToken():null}}))},e.back=function(){"function"==typeof n&&n()},this.playerpool.getConnectController(e)),s={controller:null,deferred:o,pendingDestroy:!1};return this._portal=s,r.promise.done(function(e){(s.controller=e).on("destroy",function(){setTimeout(function(){i._portal===s&&(i._portal=null),o.resolve()},0)}),e._destroyed?o.resolve():s.pendingDestroy&&e.destroy()}),"function"==typeof r.promise.fail&&r.promise.fail(function(e){i._portal===s&&(i._portal=null),o.reject(e)}),o.promise()},e.closePortal=function(e){this.playerpool.closeConnectController(e)},e.openAuthentication=function(e){var t=this,n=new a,e=this.playerpool.getAuthenticationController(e||{}),i=this.playerpool.getNavigationUsers(!1);return e.controller.setNavigatableUsers(i),e.controller.on("close",function(){setTimeout(function(){n.resolve()},0),t._declaredEvents["authentication:close"]&&t.emitEvent("authentication:close",null)}),n.promise()},e.enableNavigation=function(e){e=this.playerpool.getNavigationUsers(e&&e.includeDisplayUsers);return this.navProxy&&this.navProxy.destroy(),this.navProxy=new t(this.playerpool.Webcontrol.getMessageBus()),e.forEach(function(e){e=e.setView("catlab-nes");this.navProxy.addView(e)}.bind(this)),null},e.restore=function(e,t){return this.playerpool.restore(e,t)},e._onDevice=function(e,t){this._dispatchDevice(e,t)},e._dispatchDevice=function(e,t){try{if("connect"===e)this.devices.connect(t);else if("disconnect"===e)this.devices.disconnect(t);else{if("input"!==e)throw new h.TransportError('unexpected device message type "'+e+'"');this.devices.input(t)}}catch(e){this.reportError("device",e)}},e._onHost=function(e,t){"config"!==e?"mods"!==e?this.reportError("host",new h.TransportError('unexpected host message "'+e+'"')):this._onHostMods(t||{}):this.playerpool.config&&"function"==typeof this.playerpool.config.applyOverrides?this.playerpool.config.applyOverrides(t.overrides||{}):this.reportError("host",new h.TransportError("host:config received but the pool config has no applyOverrides"))},e._onHostMods=function(e){function t(){i.channels.send("host","modsReady",{})}var n,i=this,o=this._bootOptions.onMods;if("function"==typeof o){try{n=o(e.descriptors,e.baseUrl,e.query)}catch(e){return this.reportError("host",e instanceof Error?e:new Error(String(e))),void t()}a.when(n).fail(function(e){i.reportError("host",e instanceof Error?e:new Error(String(e)))}).always(t)}else t()},d.bootWorker=function(e){var e=e||{},t=e.port||c.detect(),t=new s(t,{onUnhandled:function(e){console.error("[PlayerPoolWorker] unhandled message",e)}}),n=new d(t,e);return"function"==typeof e.createGameLogic&&n.playerpool.setGameLogic(e.createGameLogic()),t.sendNow("control","hello",{}),n},d}),define("CatLab/Webremote/PlayerPool/SeatAuthority",[],function(){function e(e){this._maxPerPool="number"==typeof(e=e||{}).maxPerPool?e.maxPerPool:1/0,this._budget=0,this._armed=!1,this._usage={},this._lease={},this._leaseListeners=[]}var t=e.prototype;return t.registerPool=function(e){this._usage.hasOwnProperty(e)||(this._usage[e]=0,this._lease[e]=0),this._recompute()},t.unregisterPool=function(e){delete this._usage[e],delete this._lease[e],this._recompute()},t.updateUsage=function(e,t){this._usage.hasOwnProperty(e)&&this._usage[e]!==(t=t||0)&&(this._usage[e]=t,this._recompute())},t.setBudget=function(e){this._budget=e||0,this._recompute()},t.getBudget=function(){return this._budget},t.getTotalUsage=function(){var e,t=0;for(e in this._usage)this._usage.hasOwnProperty(e)&&(t+=this._usage[e]);return t},t.getLease=function(e){return this._lease.hasOwnProperty(e)?this._lease[e]:0},t.onLeaseChange=function(e){this._leaseListeners.push(e)},t._recompute=function(){var e,t=[];for(e in this._usage)this._usage.hasOwnProperty(e)&&t.push(e);var n=t.length;if(this._budget<=0){if(this._armed)for(s=0;s<n;s++)this._setLease(a=t[s],this._usage[a])}else if(this._armed=!0,0!==n)for(var i=Math.max(0,this._budget-this.getTotalUsage()),o=Math.floor(i/n),r=i%n,s=0;s<n;s++){var a=t[s],l=this._usage[a]+(o+(s<r?1:0));1<n&&(l=Math.min(l,this._maxPerPool)),l=Math.max(l,this._usage[a]),this._setLease(a,l)}},t._setLease=function(e,t){if(this._lease[e]!==t){this._lease[e]=t;for(var n=0;n<this._leaseListeners.length;n++)try{this._leaseListeners[n](e,t)}catch(e){console.error("[SeatAuthority] lease listener failed:",e)}}},e}),define("CatLab/Webremote/PlayerPool/SeatAuthorityBinder",[],function(){function e(e,t){this._sa=e,this._adapter=t,this._poolById={},this._bind()}var t=e.prototype;return t._bind=function(){var n=this;this._sa.onLeaseChange(function(e,t){e=n._poolById[e];void 0!==e&&n._adapter.pushLease(e,t)}),this._adapter.eachPool(function(e,t){n._addPool(e,t)}),this._adapter.onPoolAdded(function(e,t){n._addPool(e,t)}),this._adapter.onPoolRemoved(function(e){delete n._poolById[e],n._sa.unregisterPool(e)}),this._adapter.onPoolUsage(function(e,t){n._sa.updateUsage(e,t)})},t._addPool=function(e,t){this._poolById[e]=t,this._sa.registerPool(e)},e}),define("CatLab/Webremote/PlayerPool/Managers/Manager",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred"],function(e,l){function t(){this.initializeEventable()}e=t.prototype=new e;return e.initializeManager=function(){this.hasOwnProperty("_eventableEvents")||this.initializeEventable()},e.call=function(){console.warn("[Manager] call() not implemented")},e.initialize=function(e){console.warn("[Manager] initialize() not implemented")},e.enableNavigation=function(e,t){console.warn("[Manager] enableNavigation() not implemented")},e.getConnectScreen=function(e){console.warn("[Manager] getConnectScreen() not implemented")},e.clearConnectScreen=function(e){console.warn("[Manager] clearConnectScreen() not implemented")},e.activateKeyboardUser=function(e){console.warn("[Manager] activateKeyboardUser() not implemented")},e.setKeyboardUser=function(e){console.warn("[Manager] setKeyboardUser() not implemented")},e.createDummyUser=function(e,t){console.warn("[Manager] createDummyUser() not implemented")},e.getAuthenticationScreen=function(){console.warn("[Manager] getAuthenticationScreen() not implemented")},e.getKeyboardUser=function(){return console.warn("[Manager] getKeyboardUser() not implemented"),null},e._trackCurrentNavigation=function(e,t){this._currentNavigatable=e,this._currentNavigatableIncludeDisplayUsers=!!t},e._clearCurrentNavigation=function(){},e.login=function(e){function t(){r&&i.enableNavigation(r,s)}function n(){i.off("authentication:close"),o.resolve()}var i=this,o=new l,r=this._currentNavigatable||null,s=this._currentNavigatableIncludeDisplayUsers,e=(this._clearCurrentNavigation(),this.getAuthenticationScreen(e)),a=this.getKeyboardUser();return a&&a.once("login",n),this.once("authentication:close",function(){a&&a.off("login",n),o.reject("closed")}),o.promise().done(t).fail(t),{view:e,done:o.promise()}},e.getAccessTokens=function(){return console.warn("[Manager] getAccessTokens() not implemented"),[]},e.countActivePlayers=function(){return console.warn("[Manager] countActivePlayers() not implemented"),0},e.shouldShowAvatars=function(){return!1},e.isDelayed=function(e){return!1},e.getHostProvider=function(){return"socketio"},e.disconnect=function(){console.warn("[Manager] disconnect() not implemented")},Object.defineProperty(e,"length",{get:function(){return 0}}),Object.defineProperty(e,"actualPlayersLength",{get:function(){return 0}}),t}),define("CatLab/Webremote/LocalInput/DeviceObject",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e,t,n){this._id=e,this._send=t,this._label=n,this._value=0,this._listeners={},this._bound={},this._domElements=[]}function r(e){this._device=e}function n(e,t,n,i,o){this.initializeEventable(),this._deviceId=e,this._kind=t,this._send=n,this._profile=i,this._options=o||{},this._labels=i.labelsFor(this._options),this._controls={},this._listeningListeners=[],this._listening=!0,this._authenticated=!1,this.access_token=null,this._nickname=null,this._active=!1,this.playerId=null,this.currentView=new r(this)}var i=t.prototype,i=(i.click=function(e){return this.on("click",e)},i.on=function(e,t){this._listeners[e]=this._listeners[e]||[];var n=0===this._listeners[e].length;return this._listeners[e].push(t),n&&!this._bound[e]&&(this._bound[e]=!0,this._send("control:bind",{id:this._id,event:e})),this},i.off=function(e,t){return void 0===e?Object.keys(this._listeners).forEach(function(e){this.off(e)},this):this._listeners[e]&&(void 0===t?this._listeners[e]=[]:-1!==(t=this._listeners[e].indexOf(t))&&this._listeners[e].splice(t,1),0===this._listeners[e].length)&&this._bound[e]&&(delete this._bound[e],this._send("control:unbind",{id:this._id,event:e})),this},i.hasTriggers=function(e){return void 0===e?Object.keys(this._listeners).some(function(e){return 0<this._listeners[e].length},this):!!(this._listeners[e]&&0<this._listeners[e].length)},i.update=function(e,t){0<this._value&&0===e?this._send("button:up",{id:this._id,click:t=void 0===t?!0:t}):0===this._value&&0<e&&this._send("button:down",{id:this._id}),this._value=e},i.getLabel=function(e){return(e=void 0===e?!0:e)?'<span class="control-label '+this._label.type+'">'+this._label.label+"</span>":this._label.label},i.getLabelData=function(){return this._label},i.addDomElement=function(e){function t(){n._send("button:down",{id:n._id}),n._send("button:up",{id:n._id,click:!0})}var n=this;return e&&e.addEventListener&&e.addEventListener("click",t),this._domElements.push({element:e,listener:t}),this},i.clearDomElements=function(){return this._domElements.forEach(function(e){e.element&&e.element.removeEventListener&&e.element.removeEventListener("click",e.listener)}),this._domElements=[],this},i._trigger=function(e){e=this._listeners[e];e&&e.slice().forEach(function(e){e()})},i._clearListeners=function(){this._listeners={},this._bound={}},i._setLabel=function(e){this._label=e},r.prototype.changeValue=function(e,t){this._device._send("view:changeValue",{key:e,value:t})},r.prototype.control=function(e){return this._device.control(e)},n.prototype=new e);return i.constructor=n,i.isShim=!0,i.getDeviceId=function(){return this._deviceId},i.getKind=function(){return this._kind},i.dispose=function(){Object.keys(this._controls).forEach(function(e){this._controls[e].clearDomElements(),this._controls[e]._clearListeners()},this),this._listeningListeners=[],this._eventableEvents={}},i.sendInput=function(e,t){this._send(e,t||{})},i.login=function(e){this._send("user:login",e||{})},i.logout=function(){this._send("user:logout",{})},i.setActive=function(e){this._send("active",{value:!!e})},i.setNickname=function(e){this._send("nickname",{name:e})},i.stopListening=function(){this._notifyListening(!1)},i.resumeListening=function(){this._notifyListening(!0)},i.isListening=function(){return this._listening},i.onListeningChange=function(t){this._listeningListeners.push(t);var n=this;return function(){var e=n._listeningListeners.indexOf(t);-1!==e&&n._listeningListeners.splice(e,1)}},i._notifyListening=function(t){this._listening=!!t,this._listeningListeners.slice().forEach(function(e){e(t)})},i.isAuthenticated=function(){return this._authenticated},i.getAccessToken=function(){return this.access_token},i.isActive=function(){return this._active},i.getNickname=function(){return this._nickname},i._labelFor=function(e){return this._labels[e]||{label:e,type:null,image:null,emoji:null}},i.control=function(e){return void 0===this._controls[e]&&(this._controls[e]=new t(e,this._send,this._labelFor(e))),this._controls[e]},i.setOptions=function(e){this._options=e||{},this._labels=this._profile.labelsFor(this._options),Object.keys(this._controls).forEach(function(e){this._controls[e]._setLabel(this._labelFor(e))},this)},i.handleOutput=function(e,t){switch(t=t||{},e){case"state":return void this._applyState(t);case"login":return void this.trigger("login",void 0===t.user?null:t.user);case"logout":return void this.trigger("logout");case"controls:cleared":return void Object.keys(this._controls).forEach(function(e){this._controls[e]._clearListeners()},this);default:var n,i;return void(0===e.indexOf("control:")&&(n=e.substr("control:".length),i=this._controls[t.id])&&i._trigger(n))}},i._applyState=function(e){void 0!==e.authenticated&&(this._authenticated=e.authenticated),void 0!==e.accessToken&&(this.access_token=e.accessToken),void 0!==e.nickname&&(this._nickname=e.nickname),void 0!==e.active&&(this._active=e.active),void 0!==e.playerId&&(this.playerId=e.playerId)},n}),define("CatLab/Webremote/LocalInput/KeyboardInput",[],function(){function e(e,t,n){this.initializeKeyboardInput(e,t,n)}var t=e.prototype;return t.initializeKeyboardInput=function(e,t,n){n=n||{},this._device=e,this._profile=t,this._window=n.window||("undefined"!=typeof window?window:null),this._document=n.document||(this._window?this._window.document:null),this._keyDocument=null,this._messageTarget=null,this._fullscreenTarget=null,this._destroyed=!1;var i=this;this._keydownListener=function(e){i._onKey(e,"down")},this._keyupListener=function(e){i._onKey(e,"up")},this._messageListener=function(e){i._onMessage(e)},this._fullscreenListener=function(){i.resumeListening()},this._unhookListening=e.onListeningChange(function(e){e?i.resumeListening():i.stopListening()}),this.resumeListening()},t.resumeListening=function(){if(!this._destroyed){this.stopListening();var e=this._window;if(e){try{var t=e.document;if((!t||!t.fullscreenElement)&&e.parent&&!(t=e.parent.document))throw new Error("Unaccessible");t.addEventListener("keydown",this._keydownListener),t.addEventListener("keyup",this._keyupListener),this._keyDocument=t}catch(t){try{e.addEventListener("message",this._messageListener,!1),this._messageTarget=e}catch(e){console.error(e)}}this._document&&"function"==typeof this._document.addEventListener&&(this._document.addEventListener("fullscreenchange",this._fullscreenListener),this._fullscreenTarget=this._document)}}},t.stopListening=function(){this._keyDocument&&(this._keyDocument.removeEventListener("keydown",this._keydownListener),this._keyDocument.removeEventListener("keyup",this._keyupListener),this._keyDocument=null),this._messageTarget&&(this._messageTarget.removeEventListener("message",this._messageListener,!1),this._messageTarget=null),this._fullscreenTarget&&(this._fullscreenTarget.removeEventListener("fullscreenchange",this._fullscreenListener),this._fullscreenTarget=null)},t.destroy=function(){this._destroyed=!0,this.stopListening(),this._unhookListening&&(this._unhookListening(),this._unhookListening=null)},t._onKey=function(e,t){var n;e&&(n=this._profile.mapKey(e))&&(this._device.sendInput("down"===t?"button:down":"button:up",{id:n}),this._profile.preventDefaultFor(n))&&"function"==typeof e.preventDefault&&e.preventDefault()},t._onMessage=function(e){e=e&&e.data;"object"!=typeof e||null===e||void 0===e.type||"catlab:keyboard"!==e.type||void 0===e.code||void 0===e.action||"down"!==e.action&&"up"!==e.action||this._onKey(e,e.action)},e}),define("CatLab/Webremote/LocalInput/CordovaInput",["CatLab/Webremote/LocalInput/KeyboardInput"],function(e){function t(e,t,n){this.initializeKeyboardInput(e,t,n);var i=this;this._backButtonListener=function(e){e&&"function"==typeof e.preventDefault&&e.preventDefault(),i._device.sendInput("backbutton",{})},this._backButtonTarget=null,this._document&&"function"==typeof this._document.addEventListener&&(this._document.addEventListener("backbutton",this._backButtonListener,!1),this._backButtonTarget=this._document)}var n=t.prototype=Object.create(e.prototype);return n.constructor=t,n.destroy=function(){this._backButtonTarget&&(this._backButtonTarget.removeEventListener("backbutton",this._backButtonListener,!1),this._backButtonTarget=null),e.prototype.destroy.call(this)},t}),define("CatLab/Webremote/LocalInput/AndroidRemoteInput",["CatLab/Webremote/LocalInput/CordovaInput"],function(e){return e}),define("CatLab/Webremote/LocalInput/GamepadInput",[],function(){function u(e){return String(null==e?"":e).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").replace(/-+$/,"")}function e(e,t,n){n=n||{},this._send=e,this._profile=t,this._window=n.window||("undefined"!=typeof window?window:null),this._navigator=n.navigator||("undefined"!=typeof navigator?navigator:null),this._devices={},this._detecting=!1,this._detectInterval=null,this._pollInterval=null,this._connectedListener=null,this._disconnectedListener=null}var t=e.prototype;return t.detect=function(){var i;!this._detecting&&this._available()&&(this._detecting=!0,(i=this)._window&&"ongamepadconnected"in this._window?(this._connectedListener=function(e){i._onSeen(e&&e.gamepad)},this._disconnectedListener=function(e){i._onGone(e&&e.gamepad)},this._window.addEventListener("gamepadconnected",this._connectedListener),this._window.addEventListener("gamepaddisconnected",this._disconnectedListener)):this._detectInterval=setInterval(function(){for(var e=i._getGamepads(),t=!1,n=0;n<e.length;n++)e[n]&&(t=!0,i._onSeen(e[n]));t&&(clearInterval(i._detectInterval),i._detectInterval=null)},1e3))},t.destroy=function(){var t=this;Object.keys(this._devices).forEach(function(e){e=t._devices[e];e&&e.unhookListening&&e.unhookListening()}),this._detecting=!1,this._detectInterval&&(clearInterval(this._detectInterval),this._detectInterval=null),this._pollInterval&&(clearInterval(this._pollInterval),this._pollInterval=null),this._window&&this._connectedListener&&(this._window.removeEventListener("gamepadconnected",this._connectedListener),this._window.removeEventListener("gamepaddisconnected",this._disconnectedListener)),this._connectedListener=null,this._disconnectedListener=null,this._devices={}},t._available=function(){return!!this._navigator&&("function"==typeof this._navigator.getGamepads||void 0!==this._navigator.webkitGetGamepads)},t._getGamepads=function(){return this._navigator?"function"==typeof this._navigator.getGamepads?this._navigator.getGamepads()||[]:this._navigator.webkitGetGamepads&&this._navigator.webkitGetGamepads()||[]:[]},t._deviceIdFor=function(e,t){for(var n=Object.keys(this._devices),i=0;i<n.length;i++){var o=this._devices[n[i]];if(o.idSlug===e&&o.index===t)return o.deviceId}return null},t._idFor=function(e,t){return this._profile.deviceIdPrefix+":"+e+"#"+t},t._lowestFreeOrdinal=function(e){for(var t=0;this._devices[this._idFor(e,t)];)t++;return t},t._onSeen=function(e){var t,n,i;e&&(i=u(e.id),this._deviceIdFor(i,e.index)||(t=this._idFor(i,this._lowestFreeOrdinal(i)),n={deviceId:t,idSlug:i,index:e.index,buttons:{},listening:!0,unhookListening:null},this._devices[t]=n,(i=this._send.connect(t,"gamepad",{id:e.id}))&&"function"==typeof i.onListeningChange&&("function"==typeof i.isListening&&(n.listening=i.isListening()),n.unhookListening=i.onListeningChange(function(e){n.listening=!!e})),this._startPolling()))},t._onGone=function(e){e&&(e=this._deviceIdFor(u(e.id),e.index))&&this._disconnect(e)},t._disconnect=function(e){var t=this._devices[e];t&&(t.unhookListening&&t.unhookListening(),delete this._devices[e],this._send.disconnect(e,"unplugged"),this._pollInterval)&&0===Object.keys(this._devices).length&&(clearInterval(this._pollInterval),this._pollInterval=null)},t._startPolling=function(){var e;this._pollInterval||((e=this)._pollInterval=setInterval(function(){e._poll()},50))},t._poll=function(){for(var t=this,e=this._getGamepads(),n={},i=0;i<e.length;i++){var o=e[i];if(o){var r=this._deviceIdFor(u(o.id),o.index);if(r){n[r]=!0;for(var s=this._devices[r],a=o.buttons||[],l=0;l<a.length;l++){var c,h=this._profile.mapGamepadButton(l);h&&(c=a[l]&&a[l].pressed?1:0)!==(s.buttons[h]||0)&&(s.buttons[h]=c,s.listening)&&this._send.input(r,c?"button:down":"button:up",{id:h})}}}}Object.keys(this._devices).forEach(function(e){n[e]||t._disconnect(e)})},e}),define("CatLab/Webremote/LocalInput/AppActions",[],function(){function e(e){this._window=(e=e||{}).window||("undefined"!=typeof window?window:null),this._navigator=e.navigator||("undefined"!=typeof navigator?navigator:null)}var t=e.prototype;return t.perform=function(e){var t,n=this._window,i=this._navigator,o=this;switch(e){case"minimize":return n&&n.plugins&&n.plugins.appMinimize?void n.plugins.appMinimize.minimize():void this.perform("exit");case"requestExit":return n&&n.onbeforeunload?void((t=n.onbeforeunload({}))&&this._confirm(t,function(e){e&&o.perform("exit")})):void this.perform("exit");case"exit":return i&&i.app&&"function"==typeof i.app.exitApp?void i.app.exitApp():void(n&&n.close())}},t._confirm=function(e,t){var n=this._navigator;n&&n.notification&&n.notification.confirm?n.notification.confirm(e,function(e){t(1===e)}):t(!!this._window&&this._window.confirm(e))},e}),define("CatLab/Webremote/LocalInput/DeviceChannel",["CatLab/Webremote/LocalInput/DeviceObject","CatLab/Webremote/LocalInput/KeyboardInput","CatLab/Webremote/LocalInput/CordovaInput","CatLab/Webremote/LocalInput/AndroidRemoteInput","CatLab/Webremote/LocalInput/GamepadInput","CatLab/Webremote/LocalInput/AppActions","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/index","CatLab/Webremote/Messages/NavigateableProxy"],function(r,e,t,n,i,o,s,a){function l(e,t){t=t||{},this._channels=e,this._keyboardEnabled=!1!==t.keyboard,this._platform=h[e=t.platform]?e:"keyboard",this._webcontrol=t.webcontrol||null,this._navigation="function"==typeof t.navigation?t.navigation:function(){return null},this._window=t.window||("undefined"!=typeof window?window:null),this._document=t.document||(this._window?this._window.document:null),this._navigator=t.navigator||("undefined"!=typeof navigator?navigator:null),this._installed=!1,this._listening=!0,this._devices={},this._keyboardAdapter=null,this._gamepadInput=null,this._bus=null,this._originalToController=null,this._appActions=new o({window:this._window,navigator:this._navigator})}var c=["nav:keyInput","nav:back"],h={keyboard:e,cordova:t,androidremote:n},e=l.prototype;return e.install=function(){var e,t,n;!this._installed&&(this._installed=!0,this._send("connect",{device:"display",kind:"display"}),this._bridgeDisplayBus(),this._keyboardEnabled)&&(e=s.forKind(this._platform),t=this._connectDevice("keyboard",this._platform,{}),n=h[this._platform],this._keyboardAdapter=new n(t,e,{window:this._window,document:this._document}),this._gamepadInput=new i(this._sender(),s.forKind("gamepad"),{window:this._window,navigator:this._navigator}),this._gamepadInput.detect(),this._listening||this._applyListeningToAll())},e.uninstall=function(){this._installed&&(this._installed=!1,this._keyboardAdapter&&(this._keyboardAdapter.destroy(),this._keyboardAdapter=null),this._gamepadInput&&(this._gamepadInput.destroy(),this._gamepadInput=null),this._bus&&(this._bus.toController=this._originalToController,this._bus=null,this._originalToController=null),this._devices={})},e.getKeyboardDevice=function(){return this._devices.keyboard||null},e.getDevice=function(e){return this._devices[e]||null},e.getAppActions=function(){return this._appActions},e.setListening=function(e){this._listening!==(e=!!e)&&(this._listening=e,this._applyListeningToAll())},e.isListening=function(){return this._listening},e._applyListeningToAll=function(){var t=this;Object.keys(this._devices).forEach(function(e){t._applyListening(t._devices[e])})},e._applyListening=function(e){this._listening?e.resumeListening():e.stopListening()},e.handleOutput=function(e){var t,n=e.data||{};"display"!==e.device?"app"!==e.method?(t=this._devices[e.device])?t.handleOutput(e.method,n):console.warn("[DeviceChannel] output for unknown device",e.device):this._appActions.perform(n.action):"bus"!==e.method?console.warn("[DeviceChannel] unexpected display output",e.method):(t=this._rehydrateActor(n.action,n.content),(e=this._navigation())&&a.handleMessage(n.action,t,e)||this._webcontrol&&this._webcontrol.getMessageBus().handleViewMessage(n.action,t))},e._rehydrateActor=function(e,t){var n;return(e=>{if("string"==typeof e)for(var t=0;t<c.length;t++){var n=c[t];if(e===n||e.substring(e.length-n.length-1)===":"+n)return 1}})(e)&&t&&t.actor&&"object"==typeof t.actor&&(e=(e=t.actor.deviceId)?this._devices[e]:null)?(n={},Object.keys(t).forEach(function(e){n[e]=t[e]}),n.actor=e,n):t},e._connectDevice=function(n,e,t){t=t||{};var i,o=this._devices[n];return o&&o.getKind()!==e&&(o.dispose(),delete this._devices[n],o=null),o?o.setOptions(t):(i=this,o=new r(n,e,function(e,t){i._sendInput(n,e,t)},s.forKind(e),t),this._devices[n]=o),this._listening||this._applyListening(o),this._send("connect",{device:n,kind:e,options:t}),o},e._sender=function(){var i=this;return{connect:function(e,t,n){return i._connectDevice(e,t,n||{})},disconnect:function(e,t){i._send("disconnect",{device:e,reason:t})},input:function(e,t,n){i._sendInput(e,t,n)}}},e._bridgeDisplayBus=function(){var n,e;this._webcontrol&&(e=(n=this)._webcontrol.getMessageBus(),this._bus=e,this._originalToController=e.toController,e.toController=function(e,t){n._sendInput("display","bus",{action:e,content:t})})},e._sendInput=function(e,t,n){this._send("input",{device:e,method:t,data:n||{}})},e._send=function(e,t){this._channels&&!this._channels.isClosed()&&this._channels.send("device",e,t)},l}),define("CatLab/Webremote/LocalInput/ProviderHost",["CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/Errors","CatLab/Webremote/Providers/BridgeContract"],function(c,h,e){function t(e,t){this._channels=e,this._instance=t,this._subscribed={},this._generation=1,this._publishedSettings=null,this._master=null,this._bindings=[],this._watchInstance()}var u=e.TARGET_FIRST,d=e.TARGET_INDEX,e=t.prototype;return e._bind=function(e,t){var n;"function"==typeof this._instance.on&&(n=this._instance.on(e,t),this._bindings.push({event:e,callback:t,binding:n}))},e.destroy=function(){var t=this._instance;this._bindings.forEach(function(e){e.binding&&"function"==typeof e.binding.unbind?e.binding.unbind():"function"==typeof t.off&&t.off(e.event,e.callback)}),this._bindings=[],this._subscribed={}},e._watchInstance=function(){var e,t;"function"==typeof this._instance.on&&((e=this)._bind("connect",t=function(){e.publishSettings()}),this._bind("reconnect",t))},e.handleMessage=function(e,t){"call"!==e?"subscribe"!==e?"hello"!==e?console.warn("[ProviderHost] unknown provider message",e):this._handleHello():this._handleSubscribe(t):this._handleCall(t)},e._handleHello=function(){this._generation++,this._publishedSettings=null,this.publishSettings()},e._handleCall=function(e){function t(t){if(!r&&s===n._generation){r=!0,t instanceof Error||(t=new Error(String(t)));try{n._send("error",{id:i,error:t})}catch(e){n._send("error",{id:i,error:new Error(String(t.message||t))})}}}var n=this,i=e.id,o=e.method,r=!1,s=this._generation;if("function"==typeof this._instance[o]){var a,l=(e.args||[]).slice();if("initMaster"!==o&&"initPlayer"!==o||(l=[this._masterStandIn()]),e.target)if(u[o])l.unshift(this._rebuildTarget(e.target));else{if("number"!=typeof d[o])return void t(new h.TransportError('BridgedProvider: "'+o+'" does not take a target'));l[d[o]]=this._rebuildTarget(e.target)}null!=e.ack&&l.push(this._makeAck(e.ack));try{a=this._instance[o].apply(this._instance,l)}catch(e){return void t(e)}c.when(a).done(function(e){if(!r&&s===n._generation){e=e===n._instance?void 0:e;try{n._send("result",{id:i,value:e})}catch(e){return void t(e)}r=!0,"connect"===o&&n.publishSettings()}}).fail(function(e){t(e)})}else t(new h.TransportError('BridgedProvider: unknown provider method "'+o+'"'))},e._makeAck=function(t){var n=this,i=this._generation;return function(e){i===n._generation&&n._send("ack",{ack:t,result:void 0===e?null:e})}},e._masterStandIn=function(){return this._master||(this._master={_userlibrary:{getFromId:function(){return null}},log:function(){}}),this._master},e._rebuildTarget=function(e){var i=this._instance,o="group"===e.type,r={getId:function(){return e.id},getEntityType:function(){return e.type},emit:function(e,t,n){return o?i.toGroup(r,e,t||{},n):i.toPlayer(r,e,t||{},n),!0}};return r},e._handleSubscribe=function(e){var t,n=e.event;this._subscribed[n]||(this._subscribed[n]=!0,t=this,"settings"!==n?this._bind(n,function(e){t._sendEvent(n,void 0===e?null:e)}):this._bind("settings",function(){t.publishSettings()}))},e._send=function(e,t){this._channels.send(e,t)},e._sendEvent=function(e,t){try{this._send("event",{event:e,data:t})}catch(t){this.reportError('provider:event "'+e+'"',t)}},e.reportError=function(e,t){console.error("[ProviderHost] could not send "+e,t)},e.publishSettings=function(){var n=this;this.describe().done(function(e){var t;try{t=JSON.stringify(e)}catch(e){t=null}null!==t&&t===n._publishedSettings||(n._publishedSettings=t,n._sendEvent("settings",e))})},e.describe=function(){function t(e){e={settings:e||{},canLoadExternalXml:!!n._read("canProviderLoadExternalXml",!1),canProxyFiles:!!n._read("canProxyFiles",!1),staticUrlBase:n._read("getStaticUrl","",[""]),connectUrl:n._read("getConnectURL",null,[null]),connectToken:n._read("getConnectToken",null,[null])},"function"==typeof n._instance.getConnectInstructions&&(e.connectInstructions=n._instance.getConnectInstructions()),"function"==typeof n._instance.getStartAndLoginInstructions&&(e.startAndLoginInstructions=n._instance.getStartAndLoginInstructions()),i.resolve(e)}var e,n=this,i=new c;try{e=this._instance.getProviderSettings()}catch(e){return t({}),i.promise()}return c.when(e).done(function(e){t(e)}).fail(function(){t({})}),i.promise()},e._read=function(e,t,n){if("function"!=typeof this._instance[e])return t;try{var i=this._instance[e].apply(this._instance,n||[]);return void 0===i?t:i}catch(e){return t}},t}),define("CatLab/Webremote/Transport/RpcClient",["CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/Codec","CatLab/Webremote/Transport/Errors"],function(h,u,d){function e(e,t){t=t||{},this._channels=null,this._poolName=t.poolName,this._pending={},this._pendingCount=0,this._seq=0,this._parked=[],e&&this.attach(e)}var t=e.prototype;return t.attach=function(e){var n=this;return(this._channels=e).on("rpc",function(e,t){n._onMessage(e,t)}),this._replayParked(),this},t._replayParked=function(){if(0!==this._parked.length){var e=this._parked;this._parked=[];for(var t=0;t<e.length;t++)this._post(e[t])}},t._post=function(e){if(this._channels&&!this._channels.isClosed())try{this._channels.sendEncoded(e.ch,e.type,e.fields,{onSent:e.onSent})}catch(t){this._settle(e.id,function(e){e.deferred.reject(t)})}else this._parked.push(e)},t.getPoolName=function(){return"function"==typeof this._poolName?this._poolName():this._poolName},t.call=function(n,e,t){if(!t||"number"!=typeof t.timeoutMs)throw new Error("RpcClient.call("+n+"): options.timeoutMs is required");for(var i=this,o=++this._seq,r={},s=0,a=(e||[]).slice();0<a.length&&void 0===a[a.length-1];)a.pop();var e=a.map(function(e,t){return void 0===e?null:u.encode(e,n+".args["+t+"]",{callback:function(e,t,n){if(0!==n)throw new d.TransportError("function cannot cross the worker boundary",t);n="cb"+ ++s;return r[n]=e,{__callback:n}}})}),l=new h,c={deferred:l,method:n,callbacks:r,timer:null};return this._pending[o]=c,this._pendingCount++,this._post({ch:"rpc",type:"call",id:o,fields:{id:o,method:n,args:e},onSent:function(){0<t.timeoutMs&&i._pending[o]===c&&(c.timer=setTimeout(function(){i._settle(o,function(e){e.deferred.reject(new d.RpcTimeoutError(n,i.getPoolName(),t.timeoutMs))})},t.timeoutMs))}}),l.promise()},t._settle=function(e,t){var n=this._pending[e];n&&(delete this._pending[e],this._pendingCount--,n.timer&&clearTimeout(n.timer),n.callbacks={},t(n))},t._onMessage=function(e,n){var t,i=this._pending[n.id];switch(e){case"result":return i?void this._settle(n.id,function(e){e.deferred.resolve(n.value)}):void console.warn("[RpcClient] response for a settled call ignored",n.id);case"error":return i?void this._settle(n.id,function(e){var t=n.error;t instanceof Error||(t=new d.RemoteError({name:"RemoteError",message:String(t)})),e.deferred.reject(t)}):void console.warn("[RpcClient] response for a settled call ignored",n.id);case"callback":return i?"function"!=typeof(t=i.callbacks[n.callbackId])?void console.warn("[RpcClient] unknown callback",n.callbackId,"for",i.method):void t.apply(null,n.args||[]):void console.warn("[RpcClient] callback for a settled call ignored",n.id,n.callbackId);default:console.warn("[RpcClient] unknown rpc message type",e)}},t.failAll=function(t){var n=this;this._parked=[],Object.keys(this._pending).forEach(function(e){n._settle(e,function(e){e.deferred.reject(t)})})},t.pendingCount=function(){return this._pendingCount},e}),define("CatLab/Webremote/Transport/Hosts/DedicatedWorkerHost",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/WorkerPort","CatLab/Webremote/Transport/Errors"],function(e,i,o,r){function t(e){this.initializeEventable(),e=e||{},this.kind="worker",this._url=e.workerUrl||"scripts/webworker.js",this._WorkerCtor="WorkerCtor"in e?e.WorkerCtor:"undefined"!=typeof Worker?Worker:void 0,this.worker=null,this.port=null,this._started=!1}e=t.prototype=new e;return e.start=function(){var t=new i,n=this;if(this._started)t.reject(new r.PoolBootError(this.kind,"host already started"));else if(this._started=!0,"function"!=typeof this._WorkerCtor)t.reject(new r.PoolBootError("worker","Worker is not defined"));else{try{this.worker=new this._WorkerCtor(this._url)}catch(e){return t.reject(new r.PoolBootError("worker",e&&e.message?e.message:String(e),e)),t.promise()}this.worker.onerror=function(e){n.trigger("error",e)},this.port=o.forWorker(this.worker),t.resolve(this.port)}return t.promise()},e.terminate=function(){if(this.port&&(this.port.close(),this.port=null),this.worker){try{this.worker.terminate()}catch(e){}this.worker=null}},t}),define("CatLab/Webremote/Transport/Hosts/IframeWorkerHost",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/WorkerPort","CatLab/Webremote/Transport/Errors"],function(e,n,i,o){function t(e){this.initializeEventable(),e=e||{},this.kind="iframe",this._frameUrl=e.frameUrl||"iframe-host.html",this._document=e.parentDocument||("undefined"!=typeof document?document:null),this._window=e.parentWindow||("undefined"!=typeof window?window:null),this.iframe=null,this.port=null,this._started=!1}e=t.prototype=new e;return e.start=function(){var t=new n;if(this._started)t.reject(new o.PoolBootError(this.kind,"host already started"));else if(this._started=!0,this._document&&this._window)if(this._document.body){var e=this._document.createElement("iframe");e.setAttribute("src",this._frameUrl),e.setAttribute("aria-hidden","true"),e.setAttribute("tabindex","-1"),e.setAttribute("title","pool host"),e.style.display="none",e.style.width="0",e.style.height="0",e.style.border="0";try{this._document.body.appendChild(e)}catch(e){return t.reject(new o.PoolBootError("iframe",e&&e.message?e.message:String(e),e)),t.promise()}this.iframe=e,this.port=i.forWindow(e.contentWindow,this._window),t.resolve(this.port)}else t.reject(new o.PoolBootError("iframe","document.body is not available"));else t.reject(new o.PoolBootError("iframe","no document/window on this thread"));return t.promise()},e.terminate=function(){this.port&&(this.port.close(),this.port=null),this.iframe&&(this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null)},t}),define("CatLab/Webremote/PlayerPool/Managers/WebworkerManager",["CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/LocalInput/DeviceChannel","CatLab/Webremote/LocalInput/ProviderHost","CatLab/Webremote/Providers/Dummy","CatLab/Webremote/Transport/Channels","CatLab/Webremote/Transport/RpcClient","CatLab/Webremote/Transport/Errors","CatLab/Webremote/Transport/Hosts/DedicatedWorkerHost","CatLab/Webremote/Transport/Hosts/IframeWorkerHost"],function(e,c,t,o,n,i,r,a,l,h,s,u){function d(e){this.initializeEventable(),this._managerOptions=e||{},this._manifest=this._managerOptions.manifest||null,this._hostKinds=this._managerOptions.hosts||g,this._bootTimeoutMs="number"==typeof this._managerOptions.bootTimeoutMs?this._managerOptions.bootTimeoutMs:9e4,this._helloTimeoutMs="number"==typeof this._managerOptions.helloTimeoutMs?this._managerOptions.helloTimeoutMs:1e4,this._hostFactories=this._managerOptions.hostFactories||{},this._length=0,this._connectedDevices=null,this._actualPlayersLength=0,this._mode="regular",this.devices=null,this._localInputListening=!0,this.currentNavigationView=null,this.host=null,this.channels=null,this._rpc=null,this._booted=!1,this._disconnected=!1,this._pingSeq=0,this._pings={},this._parkedQueue=[],this._pendingConfigOverrides=null,this._configOverridesQueued=!1,this._modsDeferred=null,this._providerHost=null,this._providerName="socketio"}var f=new t,p=["users","currentuser"],g=["worker","iframe"],t=d.prototype=new e;return t.constructor=d,t.getHostKind=function(){return this.host?this.host.kind:null},t.getHostProvider=function(){return this._providerName},t._createHost=function(e){if("function"==typeof this._hostFactories[e])return this._hostFactories[e](this._managerOptions);switch(e){case"worker":return new s({workerUrl:this._managerOptions.workerUrl||"scripts/webworker.js"});case"iframe":return new u({frameUrl:this._managerOptions.frameUrl||"iframe-host.html"});default:throw new Error('WebworkerManager: unknown host kind "'+e+'"')}},t._buildInitOptions=function(t){var n,e={};return(t=t||{}).webcontrolOptions&&(n={},Object.keys(t.webcontrolOptions).forEach(function(e){"provider"!==e&&(n[e]=t.webcontrolOptions[e])}),e.webcontrolOptions=n),t.oauth&&(e.oauth=t.oauth),e.authStorage=this.getPersistentAuthStorageSnapshot(),void 0!==t.keyboard&&(e.keyboard=t.keyboard),"string"==typeof t.controlUserType&&(e.controlUserType=t.controlUserType),void 0!==t.playerPoolMode&&(e.playerPoolMode=t.playerPoolMode),e.poolNumber="number"==typeof this.poolNumber?this.poolNumber:1,e.localInput=this._localInput,e.events=this._manifest&&this._manifest.events?this._manifest.events.slice():[],e.provider=this._providerName,e},t.initialize=function(e){this.initializeManager(),this._initOptions=e||{},this._disconnected=!1,this._booted=!1,this._parkedQueue=[],this._pendingConfigOverrides=null,this._configOverridesQueued=!1,this._localInput=void 0===this._initOptions.localInput||!!this._initOptions.localInput;var t=new c,n=this,e=(this._providerHost&&"function"==typeof this._providerHost.destroy&&this._providerHost.destroy(),this._providerHost=null,this._providerName="socketio",this._initOptions.webcontrolOptions&&this._initOptions.webcontrolOptions.provider);return e&&"object"==typeof e&&(this._providerName="bridged",this._providerHost=new i({send:function(e,t){n.channels&&!n.channels.isClosed()&&n.channels.sendNow("provider",e,t)}},e)),this.initializeWebcontrol(this._initOptions).done(function(){n._initOptions.oauth&&f.oAuth(n._initOptions.oauth),n._rpc=new l(null,{poolName:function(){return n.poolNumber||1}}),n._bootChain(n._hostKinds.slice(),null).done(function(){n._booted=!0,n._installLocalInput(),t.resolve()}).fail(function(e){t.reject(e)})}).fail(function(e){t.reject(e)}),t.promise()},t._bootChain=function(n,e){var i=new c,o=this,r=n.shift();return void 0===r?i.reject(e||new h.PoolBootError("none","no host kinds configured")):this._bootOne(r).done(function(){i.resolve()}).fail(function(e){var t,e=e instanceof h.PoolBootError?e:new h.PoolBootError(r,e&&e.message?e.message:String(e),e);0<n.length?(t=n[0],o._parkedQueue=o._teardownHost({preserveCalls:!0}),console.warn("[WebworkerManager] pool "+(o.poolNumber||1)+": "+r+" host failed ("+e.reason+"); falling back to "+t+"."),o.trigger("transport:fallback",{pool:o.poolNumber||1,from:r,to:t,reason:e.reason}),o._bootChain(n,e).done(function(){i.resolve()}).fail(function(e){i.reject(e)})):(o._failPendingDispatches(e),o._teardownHost(),i.reject(e))}),i.promise()},t._bootOne=function(t){var e,n=new c,i=this;try{e=this._createHost(t)}catch(e){return n.reject(new h.PoolBootError(t,e.message,e)),n.promise()}this.host=e;function o(){r||null!==a||(clearTimeout(s),s=null,a=setTimeout(function(){l(new h.PoolBootError(t,"control:ready did not arrive within "+i._bootTimeoutMs+"ms of control:hello"))},i._bootTimeoutMs))}var r=!1,s=null,a=null,l=function(e){r||(r=!0,clearTimeout(s),clearTimeout(a),e?n.reject(e):n.resolve())};e.on("error",function(e){r?i.trigger("worker:error",e):l(new h.PoolBootError(t,"host error during boot: "+(e&&e.message?e.message:String(e)),e))}),s=setTimeout(function(){l(new h.PoolBootError(t,"control:hello did not arrive within "+i._helloTimeoutMs+"ms"))},i._helloTimeoutMs);return e.start().done(function(e){i._attachPort(e,t,l,o)}).fail(function(e){l(e)}),n.promise()},t._attachPort=function(e,i,o,r){var s=this;this.channels=new a(e,{onUnhandled:function(e){console.error("[WebworkerManager] unhandled message from pool",e)}}),this.channels.onHandlerError(function(e){console.error("[WebworkerManager] handler threw",e),s.trigger("transport:error",e)}),null===this._pendingConfigOverrides||this._configOverridesQueued||(this.channels.send("host","config",{overrides:this._pendingConfigOverrides}),this._configOverridesQueued=!0),this._rpc?this._rpc.attach(this.channels):this._rpc=new l(this.channels,{poolName:function(){return s.poolNumber||1}}),this.channels.on("control",function(e,t){var n;switch(e){case"hello":"function"==typeof r&&r();try{s.channels.sendNow("control","init",{options:s._buildInitOptions(s._initOptions)})}catch(e){o(new h.PoolBootError(i,"control:init could not be encoded: "+e.message,e))}return;case"ready":return s.channels.open(),void o(null);case"pong":return void(s._pings[t.id]&&s._pings[t.id].pong());case"fatal":return n=t.error&&t.error.message||"unknown",s._booted?void s.trigger("worker:error",t.error):void o(new h.PoolBootError(i,"control:fatal: "+n,t.error));case"error":return console.error("[WebworkerManager] pool "+(s.poolNumber||1)+" reported: "+t.context,t.error),void s.trigger("transport:error",t.error);default:console.warn("[WebworkerManager] unknown control message",e)}}),this.channels.on("events",function(e,t){"event"===e&&(s._syncLengthFromPayload(t.name,t.data),s.trigger(t.name,t.data))}),this.channels.on("device",function(e,t){s._onDevice(e,t)}),this.channels.on("provider",function(e,t){s._providerHost?s._providerHost.handleMessage(e,t):console.warn("[WebworkerManager] provider message with no ProviderHost registered",e)}),this.channels.on("host",function(e,t){"storage"!==e?"modsReady"!==e?console.warn("[WebworkerManager] unknown host message",e):s._modsDeferred&&(e=s._modsDeferred,s._modsDeferred=null,e.resolve()):s.applyPersistentStorageSync({name:t.key,rawValue:t.value})}),0<this._parkedQueue.length&&(this.channels.adoptQueue(this._parkedQueue),this._parkedQueue=[])},t._teardownHost=function(e){var e=!(!e||!e.preserveCalls),t=[];return e?this.channels&&(t=this.channels.takeQueue()):this._rpc&&this._rpc.failAll(new Error("[WebworkerManager] pool host torn down")),this._failPendingPings(),this._teardownLocalInput(),this.channels&&(this.channels.close(),this.channels=null),this.host&&(this.host.off("error"),this.host.terminate(),this.host=null),e||(this._rpc=null),t},t.terminateHost=function(){this._teardownHost()},t.getPersistentAuthStorageSnapshot=function(){var n={};return"undefined"!=typeof window&&void 0!==window.localStorage&&p.forEach(function(e){var t=window.localStorage.getItem(e);null!==t&&(n[e]=t)}),n},t.applyPersistentStorageSync=function(e){e&&void 0!==e.name&&-1!==p.indexOf(e.name)&&"undefined"!=typeof window&&void 0!==window.localStorage&&(null!=e.rawValue?window.localStorage.setItem(e.name,e.rawValue):window.localStorage.removeItem(e.name))},t.initializeWebcontrol=function(e){function t(){f.initialize(i).done(function(){n.resolve()})}var n=new c,i={provider:new r};e.webcontrolOptions&&e.webcontrolOptions.translator&&(i.translator=e.webcontrolOptions.translator),e.webcontrolOptions&&e.webcontrolOptions.assetsUrl&&(i.assetsUrl=e.webcontrolOptions.assetsUrl);return e.portalAssets?f.setViewFactory(new o(e.portalAssets)).done(t):t(),n.promise()},t.getWebcontrol=function(){return f},t.getKeyboardUser=function(){return this.devices?this.devices.getKeyboardDevice():null},t.setLocalInputListening=function(e){return this._localInputListening=!!e,this.devices&&this.devices.setListening(this._localInputListening),this._localInputListening},t.isLocalInputListening=function(){return this.devices?this.devices.isListening():this._localInputListening},t._entryFor=function(e){if(!this._manifest)throw new Error('WebworkerManager: no manifest configured; cannot call "'+e+'"');var t=this._manifest.methods&&this._manifest.methods[e];if(t)return t;if(this._manifest.hostMethods&&this._manifest.hostMethods[e])throw new h.TransportError("host method not rpc-callable: "+e);throw new Error('WebworkerManager: "'+e+'" is not in the manifest')},t._hostEntryFor=function(e){if(!this._manifest)throw new Error('WebworkerManager: no manifest configured; cannot call "'+e+'"');var t=this._manifest.hostMethods&&this._manifest.hostMethods[e];if(t)return t;throw new Error('WebworkerManager: "'+e+'" is not in the manifest')},t.call=function(){var e=Array.prototype.slice.call(arguments),t=e.shift(),n=this._entryFor(t);return this.rpc(t,e,{timeoutMs:n.timeoutMs})},t.rpc=function(e,t,n){var i;return this._disconnected||!this._rpc?((i=new c).reject(new Error("[WebworkerManager] rpc after disconnect: "+e)),i.promise()):this._rpc.call(e,t||[],n)},t._failPendingDispatches=function(e){this._rpc&&this._rpc.failAll(e)},t._syncLengthFromPayload=function(e,t){"change:length"===e&&"number"==typeof t&&(this._length=t),"change:connections"===e&&"number"==typeof t&&(this._connectedDevices=t)},t.ping=function(e){e="number"==typeof e?e:3e3;var t,n,i,o=new c;return this.channels?(n=++(t=this)._pingSeq,i=setTimeout(function(){delete t._pings[n],o.reject(new Error("[WebworkerManager] ping timeout"))},e),this._pings[n]={pong:function(){clearTimeout(i),delete t._pings[n],o.resolve({pong:!0})},abort:function(){clearTimeout(i),delete t._pings[n],o.reject(new Error("[WebworkerManager] ping aborted: host torn down"))}},this.channels.sendNow("control","ping",{id:n})):o.reject(new Error("[WebworkerManager] ping without a host")),o.promise()},t._failPendingPings=function(){var t=this;Object.keys(this._pings).forEach(function(e){e=t._pings[e];e&&e.abort()}),this._pings={}},t.enableNavigation=function(e,t){return this._trackCurrentNavigation(e,t),this.currentNavigationView=e,this.rpc("enableNavigation",[{includeDisplayUsers:t}],{timeoutMs:this._hostEntryFor("enableNavigation").timeoutMs})},t._clearCurrentNavigation=function(){this.currentNavigationView=null},t.openPortal=function(t){t=t||{};var n={},e=(Object.keys(t).forEach(function(e){"start"!==e&&"back"!==e&&"purchaseSeatsCallback"!==e&&"leanback"!==e&&"element"!==e&&(n[e]=t[e])}),"function"==typeof t.start?t.start:function(){}),i="function"==typeof t.back?t.back:function(){};return this.rpc("openPortal",[n,e,i],{timeoutMs:this._hostEntryFor("openPortal").timeoutMs})},t.finalizePortal=function(e){return this.rpc("closePortal",[e],{timeoutMs:this._hostEntryFor("closePortal").timeoutMs})},t.getConnectScreen=function(t){this.openPortal(t).fail(function(e){console.error("[WebworkerManager] openPortal failed",e)});var n=f.getMessageBus(),i=n.addViewListener.bind(n);return n.addViewListener=function(e){i(e),n.handleViewMessage("state:change",{state:{activePlayers:0,minPlayers:t.minPlayers||1,maxPlayers:t.maxPlayers||4,connectInstructions:[""],startAndLoginInstructions:[""],showInactivePlayers:t.activePlayersPanel||!1,qrUrl:null}}),n.addViewListener=i},f.portalView(n,t)},t.setPublicConnectInfo=function(e){return this.channels?this.call("setPublicConnectInfo",e):((e=new c).resolve(),e.promise())},t.getAuthenticationScreen=function(t){t=t||{};var n={};return Object.keys(t).forEach(function(e){"function"!=typeof t[e]&&(n[e]=t[e])}),this.rpc("openAuthentication",[n],{timeoutMs:this._hostEntryFor("openAuthentication").timeoutMs}).fail(function(e){console.error("[WebworkerManager] openAuthentication failed",e)}),f.authenticationView(f.getMessageBus(),t)},t.clearConnectScreen=function(e){return this.call("clearConnectScreen",e)},t.activateKeyboardUser=function(e){return this.call("activateKeyboardUser",e)},t.setKeyboardUser=function(e){var t=e;if(e&&"function"==typeof e.getDeviceId)t=e.getDeviceId();else if(e&&"object"==typeof e&&(Object.prototype.hasOwnProperty.call(e,"deviceId")||Object.prototype.hasOwnProperty.call(e,"userId"))&&!(t=e.deviceId||e.userId||null))return(e=new c).resolve(),e.promise();return this.call("setKeyboardUser",t)},t.createDummyUser=function(e,t,n){return this.call("createDummyUser",e,t,n||{})},t.getAccessTokens=function(){return this.call("getAccessTokens")},t.countActivePlayers=function(){return this.call("countActivePlayers")},t.isDelayed=function(e){return this.call("isDelayed",e)},t.shouldShowAvatars=function(){return this.call("shouldShowAvatars")},t.restore=function(e,t){return this.rpc("restore",[e,t],{timeoutMs:this._hostEntryFor("restore").timeoutMs})},t.applyConfigOverrides=function(e){this._pendingConfigOverrides=e,this.channels?(this.channels.send("host","config",{overrides:e}),this._configOverridesQueued=!0):this._configOverridesQueued=!1;e=new c;return e.resolve(),e.promise()},t.initializePlayerpoolMods=function(e,t,n){var i=new c;return this.channels?(this._modsDeferred=i,this.channels.send("host","mods",{descriptors:e,baseUrl:t,query:n})):i.reject(new Error("[WebworkerManager] initializePlayerpoolMods without a host")),i.promise()},t.disconnect=function(){this._disconnected=!0,this._teardownHost();var e=new c;return e.resolve(),e.promise()},t._installLocalInput=function(){var e,t;this._localInput&&this.channels&&(e=this,t="undefined"!=typeof window&&window.cordova?void 0!==window.CORDOVA_TV&&window.CORDOVA_TV?"androidremote":"cordova":"keyboard","string"==typeof this._initOptions.controlUserType&&(t=this._initOptions.controlUserType),this.devices=new n(this.channels,{keyboard:!1!==this._initOptions.keyboard,platform:t,webcontrol:f,navigation:function(){return e.currentNavigationView}}),this.devices.setListening(this._localInputListening),this.devices.install())},t._teardownLocalInput=function(){this.devices&&(this.devices.uninstall(),this.devices=null)},t._onDevice=function(e,t){"output"===e?t&&null!=t.data?this.devices?this.devices.handleOutput(t):console.warn("[WebworkerManager] device output with no device channel",t):this.trigger("transport:error",new h.TransportError("malformed device:output frame (no data)")):console.warn("[WebworkerManager] unexpected device message",e)},Object.defineProperty(t,"length",{get:function(){return this._length}}),Object.defineProperty(t,"connectedDevices",{get:function(){return"number"==typeof this._connectedDevices?this._connectedDevices:this._length}}),Object.defineProperty(t,"actualPlayersLength",{get:function(){return this._actualPlayersLength}}),d}),define("CatLab/Webremote/PlayerPool/Protocol/whenAllSettled",["CatLab/Webremote/Tools/Deferred"],function(u){return function(e,n){var i,t,o,r=new u,s=[],a=[],l=e.length,c=!1,h=null;return 0===l?r.resolve({fulfilled:s,failed:a}):(i=e.map(function(){return!1}),t=function(){c||(c=!0,null!==h&&clearTimeout(h),r.resolve({fulfilled:s,failed:a}))},o=function(){0==--l&&t()},e.forEach(function(e,t){u.when(e).done(function(e){i[t]||c||(i[t]=!0,s.push({index:t,value:e}),o())}).fail(function(e){i[t]||c||(i[t]=!0,a.push({index:t,error:e}),o())})}),"number"==typeof n&&0<n&&!c&&(h=setTimeout(function(){i.forEach(function(e,t){e||(i[t]=!0,a.push({index:t,error:new Error("whenAllSettled: timeout after "+n+"ms")}))}),t()},n))),r.promise()}}),define("CatLab/Webremote/PlayerPool/Protocol/Aggregators",[],function(){var r={first:function(e){return e[0]},concat:function(e){var t=[];return e.forEach(function(e){Array.isArray(e)?Array.prototype.push.apply(t,e):null!=e&&t.push(e)}),t},sum:function(e){var t=0;return e.forEach(function(e){"number"==typeof e&&(t+=e)}),t},array:function(e){return e},wait:function(){},numeric:function(e){return"number"==typeof e?e:0},someTrue:function(){return function(e){for(var t=0;t<e.length;t++)if(e[t])return!0;return!1}},mergeSorted:function(e){var n=e.key,i=!1!==e.descending,o=e.trimArgIndex;return function(e,t){return 1===e.length&&Array.isArray(e[0])?e[0]:((e=r.concat(e)).sort(function(e,t){e=e&&"number"==typeof e[n]?e[n]:0,t=t&&"number"==typeof t[n]?t[n]:0;return i?t-e:e-t}),"number"==typeof o&&"number"==typeof t[o]?e.slice(0,t[o]):e)}},weightedRandomPick:function(e){var u=e.amountArgIndex;return function(e,t,i){if(1===e.length)return e[0];for(var n=e.map(function(e,t){var t=i&&i.hosts&&i.hosts[t]||{},e=Array.isArray(e)?e.slice():[],n=t.actualPlayersLength;return{candidates:e,weight:n="number"!=typeof(n="number"!=typeof n||n<=0?t.length:n)||n<=0?e.length:n}}),o="number"==typeof t[u]?t[u]:0,r=[];r.length<o;){var s=(()=>{var t=0;return n.forEach(function(e){0<e.candidates.length&&(t+=e.weight)}),t})();if(s<=0)break;for(var a=Math.random()*s,l=0,c=null,h=0;h<n.length;h++)if(0!==n[h].candidates.length&&a<(l+=n[h].weight)){c=n[h];break}if(!c)break;s=Math.floor(Math.random()*c.candidates.length);r.push(c.candidates.splice(s,1)[0])}return r}},sumByIndex:function(e){var r=(e=e||{}).sumField,t=e.shareField,s=e.copyFields||[];return function(e){var i,o;return 1===e.length?e[0]:(i=[],o=0,e.forEach(function(e){Array.isArray(e)&&e.forEach(function(t,n){i[n]||(i[n]={},i[n][r]=0,s.forEach(function(e){i[n][e]=t[e]}));var e=Number(t[r])||0;i[n][r]+=e,o+=e})}),t&&i.forEach(function(e){e[t]=0<o?e[r]/o:0}),i)}},sumByKey:function(e){var o=(e=e||{}).keyField,r=e.sumField,t=e.shareField,s=e.sortDescending;return function(e){var n,i;return 1===e.length?e[0]:(n={},i=0,e.forEach(function(e){Array.isArray(e)&&e.forEach(function(e){var t=e[o],e=(n[t]||(n[t]={},n[t][o]=e[o],n[t][r]=0),Number(e[r])||0);n[t][r]+=e,i+=e})}),e=Object.keys(n).map(function(e){return n[e]}),s&&e.sort(function(e,t){return t[o]-e[o]}),t&&e.forEach(function(e){e[t]=0<i?e[r]/i:0}),e)}}};return r}),define("CatLab/Webremote/PlayerPool/EngineManifest",["CatLab/Webremote/PlayerPool/Protocol/Aggregators"],function(e){return{methods:{serialize:{route:"all",aggregate:"array",timeoutMs:3e4},countActivePlayers:{route:"all",aggregate:"sum",timeoutMs:1e4},getRandomPlayers:{route:"all",aggregate:e.weightedRandomPick({amountArgIndex:0}),timeoutMs:1e4},getAbsoluteRandomPlayers:{route:"all",aggregate:e.weightedRandomPick({amountArgIndex:0}),timeoutMs:1e4},commitRandomPlayers:{route:"all",aggregate:"wait",timeoutMs:1e4},resetRandomPlayers:{route:"all",aggregate:"wait",timeoutMs:1e4},newGroup:{route:"leastFullOrSpawn",timeoutMs:1e4},hasKeyboardPlayer:{route:"primary",timeoutMs:1e4},isDelayed:{route:"primary",timeoutMs:1e4},shouldShowAvatars:{route:"primary",timeoutMs:1e4},getMaxPlayers:{route:"primary",timeoutMs:1e4},setMaxPlayers:{route:"all",aggregate:"first",timeoutMs:1e4,replayOnSpawn:!0},setPortalMaxPlayers:{route:"all",aggregate:"first",timeoutMs:1e4,replayOnSpawn:!0},setLicenseToken:{route:"all",aggregate:"first",timeoutMs:1e4,replayOnSpawn:!0},hasGlobalAccessTokens:{route:"primary",timeoutMs:1e4},preloadFiles:{route:"primary",timeoutMs:0},clearConnectScreen:{route:"all",aggregate:"wait",timeoutMs:1e4},activateKeyboardUser:{route:"primary",timeoutMs:1e4},setKeyboardUser:{route:"primary",timeoutMs:1e4},createDummyUser:{route:"primary",timeoutMs:1e4},getAccessTokens:{route:"primary",timeoutMs:1e4},pause:{route:"all",aggregate:"wait",timeoutMs:1e4},resume:{route:"all",aggregate:"wait",timeoutMs:1e4},setExternalActivePlayers:{route:"all",aggregate:"wait",timeoutMs:1e4},setExternalUsers:{route:"all",aggregate:"wait",timeoutMs:1e4},setLeasedSeats:{route:"all",aggregate:"wait",timeoutMs:1e4},setPublicConnectInfo:{route:"primary",timeoutMs:1e4},getLocalDevices:{route:"primary",timeoutMs:1e4}},hostMethods:{openPortal:{timeoutMs:0},closePortal:{timeoutMs:1e4},openAuthentication:{timeoutMs:0},enableNavigation:{timeoutMs:1e4},restore:{timeoutMs:3e4},applyConfigOverrides:{timeoutMs:1e4}},aliases:{createGroup:"newGroup"},events:["user:join","change:length","change:connections","change:maxplayers","change:mode","connectInfo:change","license:capped","portal:active:count","portal:users","authentication:close","smileys:slingshot","transport:fallback","device:disconnected","device:reconnected"],eventShapes:{"user:join":"none","change:length":"number","change:connections":"number","change:maxplayers":"number","change:mode":"string","connectInfo:change":{connectToken:"string",connectTokenForDisplay:"string",connectUrl:"string",server:"string",contentProxy:"string?",gameId:"string?",accessToken:"string?"},"license:capped":{max:"number",count:"number",relay_token:"string?"},"portal:active:count":"number","portal:users":"array","authentication:close":"none","smileys:slingshot":{player:{id:"string",name:"string",smiley:"string"},angle:"number",speed:"number",smiley:"string"},"transport:fallback":{pool:"number",from:"string",to:"string",reason:"string"},"device:disconnected":{device:"string"},"device:reconnected":{device:"string"}}}}),define("CatLab/Webremote/PlayerPool/Managers/WorkerManager",["CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/PlayerPool/Managers/WebworkerManager","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/PlayerPool/Protocol/whenAllSettled","CatLab/Webremote/PlayerPool/EngineManifest"],function(e,t,i,n,o){function r(e){this.initializeEventable(),this.workers=[],this._mode="regular",this._initOptions=null,this._totalLength=0,this._managerOptions=e||{},this._manifest=this._managerOptions.manifest||o,this._primaryBootSettled=!1,this._primaryBoot=null}var s=["change:length","connectInfo:change","change:mode","change:connections","portal:active:count","portal:users"],e=r.prototype=new e;return e.constructor=r,e._whenPrimaryReady=function(){return this._primaryBootSettled?null:(this._primaryBoot||(this._primaryBoot=new i),this._primaryBoot.promise())},e._settlePrimaryBoot=function(){this._primaryBootSettled=!0;var e=this._primaryBoot;this._primaryBoot=null,e&&e.resolve()},e.initialize=function(e){this.initializeManager(),(this._initOptions=e)&&e.playerPoolMode&&(this._mode=e.playerPoolMode);var t=new i,n=this;return this._createWorkerManager().initialize(e).done(function(){n._started=!0,n._settlePrimaryBoot(),t.resolve()}).fail(function(e){console.error("[WorkerManager] Primary pool failed to boot on every host:",e),n.workers=[],n._settlePrimaryBoot(),t.reject(e)}),t.promise()},e._createWorkerManager=function(){var e=Object.assign({},this._managerOptions,{manifest:this._manifest||null}),e=new t(e);return this.workers.push(e),this._bindWorkerEvents(e),e},e._getPrimaryWorker=function(){return this.workers[0]},e._bindWorkerEvents=function(n){var i=this,e=this._manifest&&this._manifest.events?this._manifest.events:[],o={};e.forEach(function(t){o[t]||-1!==s.indexOf(t)||(o[t]=!0,i._bindBarrierEvent&&i._bindBarrierEvent(n,t))||n.on(t,function(e){i.trigger(t,e)})}),n.on("change:length",function(){i._updateTotalLength(),i.trigger("change:length")}),n.on("connectInfo:change",function(e){i._onWorkerConnectInfo(n,e)}),n.on("change:mode",function(e){i._mode=e,i.trigger("change:mode",e)})},e._onWorkerConnectInfo=function(e,t){this.trigger("connectInfo:change",t)},e._updateTotalLength=function(){var t=0;this.workers.forEach(function(e){t+=e.length||0}),this._totalLength=t},e.enableNavigation=function(e,t){return this._trackCurrentNavigation(e,t),this._getPrimaryWorker().enableNavigation(e,t)},e._clearCurrentNavigation=function(){var e=this._getPrimaryWorker();e&&"function"==typeof e._clearCurrentNavigation&&e._clearCurrentNavigation()},e.getKeyboardUser=function(){var e=this._getPrimaryWorker();return e&&"function"==typeof e.getKeyboardUser?e.getKeyboardUser():null},e.setLocalInputListening=function(e){var t=this._getPrimaryWorker();return t&&"function"==typeof t.setLocalInputListening?t.setLocalInputListening(e):!!e},e.isLocalInputListening=function(){var e=this._getPrimaryWorker();return!e||"function"!=typeof e.isLocalInputListening||e.isLocalInputListening()},e.getConnectScreen=function(e){return this._getPrimaryWorker().getConnectScreen(e)},e.clearConnectScreen=function(e){return this._getPrimaryWorker().clearConnectScreen(e)},e.activateKeyboardUser=function(e){return this._getPrimaryWorker().activateKeyboardUser(e)},e.setKeyboardUser=function(e){return this._getPrimaryWorker().setKeyboardUser(e)},e.createDummyUser=function(e,t,n){return this._getPrimaryWorker().createDummyUser(e,t,n)},e.applyConfigOverrides=function(e){return this._getPrimaryWorker().applyConfigOverrides(e)},e.getAuthenticationScreen=function(e){return this._getPrimaryWorker().getAuthenticationScreen(e)},e.getAccessTokens=function(){return this._getPrimaryWorker().getAccessTokens()},e.countActivePlayers=function(){return this._getPrimaryWorker().countActivePlayers()},e.getWebcontrol=function(){var e=this._getPrimaryWorker();return e&&"function"==typeof e.getWebcontrol?e.getWebcontrol():null},e.disconnect=function(){var e=new i,t=this.workers,t=(this.workers=[],this._settlePrimaryBoot(),t.map(function(e){return e.disconnect()}));return n(t,0).done(function(){e.resolve()}),e.promise()},Object.defineProperty(e,"length",{get:function(){return this._totalLength}}),Object.defineProperty(e,"actualPlayersLength",{get:function(){return this._totalLength}}),r}),define("CatLab/Webremote/PlayerPool/Protocol/Router",[],function(){return{select:function(e,t){switch(e){case"primary":return t.length?[t[0]]:[];case"last":return t.length?[t[t.length-1]]:[];case"leastFull":case"leastFullOrSpawn":if(!t.length)return[];for(var n=t[0],i=1;i<t.length;i++)(t[i].length||0)<(n.length||0)&&(n=t[i]);return[n];default:return t.slice()}}}}),define("CatLab/Webremote/PlayerPool/Protocol/ManifestProxy",["CatLab/Webremote/Tools/Deferred","CatLab/Webremote/PlayerPool/Protocol/Aggregators","CatLab/Webremote/PlayerPool/Protocol/Router","CatLab/Webremote/PlayerPool/Protocol/whenAllSettled"],function(p,n,g,m){function s(e,t){e.constructor&&e.constructor!==Object||e._manifestConstructorWarned||(e._manifestConstructorWarned=!0,console.warn("[ManifestProxy] "+t+": target has no own constructor set; subclass prototypes must set p.constructor for override detection."))}function e(e){var t=[],n=e.methods||{},i=(Object.keys(n).forEach(function(e){"number"!=typeof n[e].timeoutMs&&t.push("methods."+e+" has no timeoutMs"),void 0!==n[e].settle&&"all"!==n[e].settle&&"primary"!==n[e].settle&&t.push("methods."+e+" has an invalid settle"),"leastFullOrSpawn"===n[e].route&&n[e].replayOnSpawn&&t.push("methods."+e+' cannot be both route "leastFullOrSpawn" and replayOnSpawn')}),e.hostMethods||{}),o=(Object.keys(i).forEach(function(e){"number"!=typeof i[e].timeoutMs&&t.push("hostMethods."+e+" has no timeoutMs")}),e.eventShapes||{});if((e.events||[]).forEach(function(e){Object.prototype.hasOwnProperty.call(o,e)||t.push('events: "'+e+'" has no eventShapes entry')}),0<t.length)throw new Error("manifest: "+t.join("; "));return[]}function a(e){return e&&e.aliases||{}}function l(c,h,e){var o=(e=>{if("function"==typeof e)return e;var t=n[e||"first"];if("function"!=typeof t)throw new Error("[ManifestProxy] Unknown aggregator: "+e);return t})(h.aggregate),u=h.route||"all",d=(e=>{if("number"!=typeof e.timeoutMs)throw new Error("manifest: methods."+c+" has no timeoutMs");return e.timeoutMs})(h),f=h.settle||"all";return function(){function e(){"leastFullOrSpawn"===u&&"function"==typeof r._ensureRosterCapacity?r._ensureRosterCapacity().always(function(){t(g.select(u,n()))}):t(g.select(u,n()))}var r=this,s=Array.prototype.slice.call(arguments),a=(h.replayOnSpawn&&"function"==typeof r._recordReplayableCall&&r._recordReplayableCall(c,s),new p),l=function(e,t){var n;try{n=o(e,s,t)}catch(e){return void a.reject(e)}a.resolve(n)},t=function(i){var o,e,n;0!==i.length?(o=i.map(function(e){return r.workers.indexOf(e)}),e=i.map(function(e){return n=s,i=h,v(e=e,t=c)?e[t].apply(e,n):"function"==typeof e.rpc?e.rpc(t,n,{timeoutMs:i.timeoutMs}):e.call.apply(e,[t].concat(n));var t,n,i}),"primary"===f?(-1===(n=i.indexOf(r.workers[0]))&&(n=0),e.forEach(function(e,t){t!==n&&e.fail(function(e){"function"==typeof r.trigger&&r.trigger("pool:degraded",{poolIndex:o[t],method:c,error:e})})}),e[n].done(function(e){a.resolve(e)}).fail(function(e){a.reject(e)})):m(e,d).done(function(e){var t,n;"function"==typeof r.trigger&&e.failed.forEach(function(e){r.trigger("pool:degraded",{poolIndex:o[e.index],method:c,error:e.error})}),0!==e.fulfilled.length?(t=(n=e.fulfilled.slice().sort(function(e,t){return e.index-t.index})).map(function(e){return e.value}),n={hosts:n.map(function(e){return i[e.index]})},l(t,n)):a.reject(e.failed[0].error)})):l([],{hosts:[]})},n=function(){return"leastFullOrSpawn"===u?r.workers.filter(function(e){return!e._bootInFlight}):r.workers},i=0===r.workers.length&&"function"==typeof r._whenPrimaryReady?r._whenPrimaryReady():null;return i?i.done(e):e(),a.promise()}}var v=function(e,t){return!("function"!=typeof e[t]||!Object.prototype.hasOwnProperty.call(e,t)&&!(e.constructor&&e.constructor.prototype&&Object.prototype.hasOwnProperty.call(e.constructor.prototype,t)))},c=["applyManifest","getWorkerForToken","call","dispatch","initialize","disconnect","restore"],r=["call","initialize","disconnect","filter","login","pause","resume"];return{validateManifest:e,applyToCoordinator:function(t,n){var i,o,r;s(t,"applyToCoordinator"),e(n),Object.keys(n.methods).concat(Object.keys(a(n))).forEach(function(e){if(-1!==c.indexOf(e)&&!v(t,e))throw new Error('[ManifestProxy] Manifest method "'+e+'" collides with coordinator infrastructure.')}),Array.isArray(t._manifestGeneratedMethods)&&t._manifestGeneratedMethods.forEach(function(e){Object.prototype.hasOwnProperty.call(t,e)&&delete t[e]}),t._manifestGeneratedMethods=[],Object.keys(n.methods).forEach(function(e){v(t,e)||(t[e]=l(e,n.methods[e]),t._manifestGeneratedMethods.push(e))}),o=(i=t)._manifestGeneratedMethods,r=a(n),Object.keys(r).forEach(function(e){var t,n;v(i,e)||(n=r[e],i[e]=(t=n,function(){return this[t].apply(this,arguments)}),o.push(e))})},applyToClient:function(t,e){for(var n in s(t,"applyToClient"),e.methods)if(Object.prototype.hasOwnProperty.call(e.methods,n)&&0<=r.indexOf(n)&&!v(t,n))throw new Error('ManifestProxy.applyToClient: manifest method "'+n+'" collides with a PlayerPoolClient infrastructure method.');var i,o;Object.keys(e.methods).forEach(function(e){v(t,e)||(t[e]=function(){return this.manager[e].apply(this.manager,arguments)})}),i=t,o=a(e),Object.keys(o).forEach(function(e){v(i,e)||(i[e]=function(){return this.manager[e].apply(this.manager,arguments)})})}}}),define("CatLab/Webremote/PlayerPool/Managers/PoolCoordinator",["CatLab/Webremote/PlayerPool/Managers/WorkerManager","CatLab/Webremote/PlayerPool/Protocol/ManifestProxy","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/PlayerPool/Protocol/whenAllSettled"],function(i,t,c,o){function e(e){i.call(this,e=e||{}),this.tokenRegistry={},this.maxPlayersPerPool=e.maxPlayersPerPool||100,this.spawnAheadRatio=e.spawnAheadRatio||.9,this._started=!1,this._spawnInFlight=!1,this._spawnPromise=null,this._spawnRetried=!1,this._capacityExhausted=!1,this._portalActive=!1,this._totalActualPlayersLength=0,this._publicConnectInfo=null,this._replayLog=[],this._eventBarriers={},this._poolSequence=0,this._manifest=null,e.manifest&&this.applyManifest(e.manifest)}var n=e.prototype=new i;return n.constructor=e,n.applyManifest=function(e){this._manifest=e,t.applyToCoordinator(this,e)},n.call=function(){var e=Array.prototype.slice.call(arguments),t=e.shift();if(this._isManifestName(t)&&"function"==typeof this[t])return this[t].apply(this,e);throw new Error('PoolCoordinator.call: "'+t+'" is not in the manifest')},n._isManifestName=function(e){var t=this._manifest;if(t){if(t.methods&&Object.prototype.hasOwnProperty.call(t.methods,e))return!0;if(t.aliases&&Object.prototype.hasOwnProperty.call(t.aliases,e))return!0}return!(!this._manifestGeneratedMethods||-1===this._manifestGeneratedMethods.indexOf(e))},n.disconnect=function(){var e=new c,t=this,n=this.workers,n=(this.workers=[],this.tokenRegistry={},this._settlePrimaryBoot(),n.map(function(e){return e.disconnect()}));return o(n,0).done(function(){t.workers=[],t.tokenRegistry={},e.resolve()}),e.promise()},n._bindWorkerEvents=function(t){i.prototype._bindWorkerEvents.call(this,t),"number"!=typeof t.poolNumber&&(t.poolNumber=++this._poolSequence);var n=this;t.on("worker:error",function(e){n._handleWorkerFailure(t,e)}),t.on("change:connections",function(){n._checkCapacity()}),t.on("portal:active:count",function(e){t._portalActiveCount=e||0,n._syncPortalCounts()}),t.on("portal:users",function(e){t._portalUsers=e||[],n._syncPortalUsers()}),"function"==typeof this._registerSeatPool&&this._registerSeatPool(t)},n._bindBarrierEvent=function(t,n){var i,o=this._manifest&&this._manifest.barrierEvents&&this._manifest.barrierEvents[n];return"function"==typeof o&&(i=this,t.on(n,function(e){i._recordBarrierEvent(n,String(o(e)),t,[e])}),!0)},n.getWorkerForToken=function(e){return this.tokenRegistry[e]||null},n._onWorkerConnectInfo=function(e,t){t&&t.connectToken&&(e._lastConnectInfo=t,(this.tokenRegistry[t.connectToken]=e)===this.workers[this.workers.length-1])&&this._setPublicConnectInfo(t)},n._setPublicConnectInfo=function(e){this._publicConnectInfo=e,this.trigger("connectInfo:change",e);var t=this._getPrimaryWorker();t&&"function"==typeof t.setPublicConnectInfo&&t.setPublicConnectInfo(e)},n._updateTotalLength=function(){var t=0,n=0;this.workers.forEach(function(e){t+=e.length||0,n+=e.actualPlayersLength||0}),this._totalLength=t,this._totalActualPlayersLength=n,this._checkCapacity()},n._handleWorkerFailure=function(t,n){var e,i;this._started&&-1!==(e=this.workers.indexOf(t))&&!t._bootInFlight&&("function"==typeof t.ping?t._probeInFlight||(t._probeInFlight=!0,i=this,t.ping().done(function(){t._probeInFlight=!1;var e=i.workers.indexOf(t);-1!==e&&console.log("[PoolCoordinator] Pool "+e+" survived worker error")}).fail(function(){t._probeInFlight=!1;var e=i.workers.indexOf(t);-1!==e&&i._killWorker(t,e,n)})):this._killWorker(t,e,n))},n._killWorker=function(t,e,n){var i=t.length||0,o=e===this.workers.length-1,r=(this.workers.splice(e,1),this);Object.keys(this.tokenRegistry).forEach(function(e){r.tokenRegistry[e]===t&&delete r.tokenRegistry[e]}),"function"==typeof t._failPendingDispatches&&t._failPendingDispatches(n);try{"function"==typeof t.terminateHost&&t.terminateHost()}catch(t){}console.error("[PoolCoordinator] Pool "+e+" lost ("+i+" players).",n),this.trigger("pool:lost",{poolIndex:e,playerCount:i,wasPrimary:0===e}),0===this.workers.length&&console.error("[PoolCoordinator] All pools lost."),o&&0<this.workers.length&&(n=this.workers[this.workers.length-1])._lastConnectInfo&&this._setPublicConnectInfo(n._lastConnectInfo);var s=this;Object.keys(this._eventBarriers).forEach(function(e){s._checkEventBarrier(e)}),this._updateTotalLength()},n._isPrimaryBridged=function(){var e=this.workers[0];return!!e&&"function"==typeof e.getHostProvider&&"bridged"===e.getHostProvider()},n._checkCapacity=function(){var e,t;this._spawnInFlight||this._capacityExhausted||this._isPrimaryBridged()||(e=Math.max(1,Math.floor(this.maxPlayersPerPool*this.spawnAheadRatio)),(t=this.workers[this.workers.length-1])&&("number"==typeof t.connectedDevices?t.connectedDevices:t.length||0)>=e&&this._spawnNewWorker())},n._spawnNewWorker=function(){var i,o,r;return this._spawnInFlight&&this._spawnPromise?this._spawnPromise:(i=new c,this._initOptions?(console.log("[PoolCoordinator] Spawning new pool ("+this.workers.length+" active)."),(o=this)._spawnInFlight=!0,this._spawnPromise=i.promise(),(r=function(){var n=o._createWorkerManager();n._bootInFlight=!0,n.initialize(o._buildSecondaryInitOptions()).done(function(){n._bootInFlight=!1,o._spawnInFlight=!1,o._spawnPromise=null,o._spawnRetried=!1,o._replayToWorker(n),o._syncPortalCounts(),o._syncPortalUsers(),o._afterSpawn(n),o.trigger("pool:spawned",{poolIndex:o.workers.indexOf(n)}),i.resolve(n)}).fail(function(e){n._bootInFlight=!1;var t=o.workers.indexOf(n);-1!==t&&o.workers.splice(t,1),o._spawnRetried?(console.error("[PoolCoordinator] Pool spawning failed twice; capacity exhausted.",e),o._spawnInFlight=!1,o._spawnPromise=null,o._capacityExhausted=!0,o.trigger("pool:capacity:exhausted",{pools:o.workers.length}),i.reject(e)):(console.warn("[PoolCoordinator] New pool failed to initialize, retrying once.",e),o._spawnRetried=!0,r())})})()):(console.error("[PoolCoordinator] Cannot spawn new pool: no init options."),i.reject(new Error("Cannot spawn new pool: no init options."))),i.promise())},n._ensureRosterCapacity=function(){var e=new c;if(this._capacityExhausted||0===this.workers.length||this._isPrimaryBridged())e.resolve();else{for(var t=null,n=0;n<this.workers.length;n++){var i=this.workers[n];i._bootInFlight||(null===t||(i.length||0)<(t.length||0))&&(t=i)}null!==t&&(t.length||0)<this.maxPlayersPerPool?e.resolve():this._spawnNewWorker().always(function(){e.resolve()})}return e.promise()},n._recordBarrierEvent=function(e,t,n,i){var t=e+"\0"+t,o=this._eventBarriers[t];(o=o||(this._eventBarriers[t]={event:e,expected:this.workers.filter(function(e){return 0<(e.length||0)}),fired:[]})).args=i,-1===o.fired.indexOf(n)&&o.fired.push(n),this._checkEventBarrier(t)},n._checkEventBarrier=function(e){var t,n=this._eventBarriers[e];!n||this._manifest&&this._manifest.barrierRequiresPlayers&&-1!==this._manifest.barrierRequiresPlayers.indexOf(n.event)&&!this.workers.some(function(e){return 0<(e.length||0)})||(t=this,0<n.expected.filter(function(e){return-1!==t.workers.indexOf(e)&&-1===n.fired.indexOf(e)}).length)||(Object.keys(this._eventBarriers).forEach(function(e){t._eventBarriers[e].event===n.event&&delete t._eventBarriers[e]}),this.trigger.apply(this,[n.event].concat(n.args)))},n.getSeatAdapter=function(){var i,o;return this._seatAdapter||((i=this)._seatAddedCbs=[],this._seatUsageCbs=[],this._seatRemovedCbs=[],this._seatTracked={},o=function(e){return void 0===e.__seatId&&(e.__seatId=e.poolNumber),e.__seatId},this._registerSeatPool=function(t){var n;"number"==typeof t.poolNumber&&(n=o(t),i._seatTracked[n]!==t)&&(i._seatTracked[n]=t,i._seatAddedCbs.forEach(function(e){e(n,t)}),t.__seatUsageHandler=function(){i._seatUsageCbs.forEach(function(e){e(t.__seatId,t.actualPlayersLength)})},t.on("change:length",t.__seatUsageHandler))},this._reconcileSeatPools=function(){Object.keys(i._seatTracked).forEach(function(e){var t,n=i._seatTracked[e];-1===i.workers.indexOf(n)&&(t=parseInt(e,10),delete i._seatTracked[e],"function"==typeof n.off&&n.__seatUsageHandler&&n.off("change:length",n.__seatUsageHandler),i._seatRemovedCbs.forEach(function(e){e(t)}))})},this.on("pool:lost",this._reconcileSeatPools),this._seatAdapter={eachPool:function(t){i.workers.forEach(function(e){i._registerSeatPool(e),t(o(e),e)})},onPoolAdded:function(e){i._seatAddedCbs.push(e)},onPoolRemoved:function(e){i._seatRemovedCbs.push(e)},onPoolUsage:function(e){i._seatUsageCbs.push(e)},pushLease:function(e,t){e.call("setLeasedSeats",t)}}),this._seatAdapter},n._recordReplayableCall=function(e,t){for(var n=0;n<this._replayLog.length;n++)if(this._replayLog[n].method===e)return void(this._replayLog[n].args=t);this._replayLog.push({method:e,args:t})},n._replayToWorker=function(n){this._replayLog.forEach(function(t){var e;(e="function"==typeof n[t.method]?n[t.method].apply(n,t.args):n.call.apply(n,[t.method].concat(t.args)))&&"function"==typeof e.fail&&e.fail(function(e){console.error('[PoolCoordinator] Replay of "'+t.method+'" onto spawned pool failed:',e)})})},n._afterSpawn=function(e){},n._buildSecondaryInitOptions=function(){var e,t={},n=this._initOptions||{};for(e in n)n.hasOwnProperty(e)&&(t[e]=n[e]);return t.localInput=!1,t.keyboard=!1,t},n.getConnectScreen=function(t){var n=this,i="function"==typeof t.start?t.start:function(){},e="function"==typeof t.back?t.back:function(){},o=(this._portalActive=!0,this.workers.forEach(function(e){e._portalActiveCount=0,e._portalUsers=[]}),t.start=function(e){n._onPortalEnd("start",function(){i(e)})},t.back=function(){n._onPortalEnd("back",function(){e()})},this._getPrimaryWorker()),r=o.getConnectScreen(t);return this.workers.forEach(function(e){e!==o&&"function"==typeof e.openPortal&&e.openPortal(t)}),this._recordReplayableCall("openPortal",[t]),r},n._onPortalEnd=function(t,e){this._portalActive&&(this._portalActive=!1,this._removeReplayableCall("openPortal"),this.workers.forEach(function(e){e._portalActiveCount=0,e._portalUsers=[],"function"==typeof e.finalizePortal&&e.finalizePortal(t)}),e())},n._syncPortalCounts=function(){var t;this._portalActive&&(t=0,this.workers.forEach(function(e){t+=e._portalActiveCount||0}),this.workers.forEach(function(e){"function"==typeof e.call&&e.call("setExternalActivePlayers",t-(e._portalActiveCount||0))}))},n._syncPortalUsers=function(){this._portalActive&&this.workers.forEach(function(t){var n;"function"==typeof t.call&&(n=[],this.workers.forEach(function(e){e!==t&&e._portalUsers&&(n=n.concat(e._portalUsers))}),t.call("setExternalUsers",n))}.bind(this))},n._removeReplayableCall=function(e){for(var t=0;t<this._replayLog.length;t++)if(this._replayLog[t].method===e)return void this._replayLog.splice(t,1)},n.clearConnectScreen=function(t){return this.workers.map(function(e){return e.clearConnectScreen(t)})[0]},n.applyConfigOverrides=function(t){this.workers.forEach(function(e){e.applyConfigOverrides(t)}),this._recordReplayableCall("applyConfigOverrides",[t]);var e=new c;return e.resolve(),e.promise()},n._adoptRestoredPoolNumbers=function(e){var t=this;e.forEach(function(e){e&&"number"==typeof e.poolNumber&&(t._poolSequence=Math.max(t._poolSequence,e.poolNumber))})},n._dropNonPrimaryWorkers=function(){var e;this.workers.length<=1||(e=this.workers.slice(1),this.workers=this.workers.slice(0,1),e.forEach(function(e){"function"==typeof e.disconnect&&e.disconnect()}),"function"==typeof this._reconcileSeatPools&&this._reconcileSeatPools())},n.restore=function(e,o){if(this._adoptRestoredPoolNumbers(Array.isArray(e)?e:[e]),this._dropNonPrimaryWorkers(),Array.isArray(e)&&1<e.length){var t=new c,r=this,n=[],i=this._getPrimaryWorker();e[0]&&"number"==typeof e[0].poolNumber&&(i.poolNumber=e[0].poolNumber),n.push(i.restore(e[0],o));for(var s=1;s<e.length;s++){var a=this._createWorkerManager();a._bootInFlight=!0,e[s]&&"number"==typeof e[s].poolNumber&&(a.poolNumber=e[s].poolNumber),n.push(((e,t)=>{var n=new c,i=(e.initialize(r._buildSecondaryInitOptions()).done(function(){e.restore(t,o).done(function(){n.resolve()}).fail(function(e){n.reject(e)})}).fail(function(e){n.reject(e)}),n.promise());return i.done(function(){e._bootInFlight=!1}),i.fail(function(){e._bootInFlight=!1}),i})(a,e[s]))}return c.when.apply(c,n).done(function(){t.resolve()}).fail(function(e){console.error("[PoolCoordinator] Multi-pool restore failed:",e),t.reject(e)}),t.promise()}var i=Array.isArray(e)?e[0]:e,l=this._getPrimaryWorker();return i&&"number"==typeof i.poolNumber&&(l.poolNumber=i.poolNumber),l.restore(i,o)},Object.defineProperty(n,"actualPlayersLength",{get:function(){return this._totalActualPlayersLength}}),e}),define("CatLab/Webremote/PlayerPool/PlayerPoolClient",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e,t){this.initializeEventable(),t=t||{},this.manager=e,this._config=t.config||null,this.connectToken="xxxxxx",this.connectTokenForDisplay="xxxxxx",this.connectUrl="...",this.server="...",this.contentProxy=null,this.gameId=null,this.accessToken=null,this.labels=[],this.keyboardPlayer=!1,this._cachedShouldShowAvatars=!1,this._cachedActivePlayerCount=0,this._cachedIsDelayed=!1,this.manager.on("connectInfo:change",function(e){this.connectToken=e.connectToken,this.connectTokenForDisplay=e.connectTokenForDisplay,this.connectUrl=e.connectUrl,this.server=e.server,this.contentProxy=void 0===e.contentProxy?null:e.contentProxy,this.gameId=void 0===e.gameId?null:e.gameId,this.accessToken=void 0===e.accessToken?null:e.accessToken}.bind(this));var e=i.concat(t.events||[]),n={};e.forEach(function(t){Object.prototype.hasOwnProperty.call(n,t)||(n[t]=!0,this.manager.on(t,function(){var e=Array.prototype.slice.call(arguments);e.unshift(t),this.trigger.apply(this,e)}.bind(this)))}.bind(this)),this.manager.on("change:length",function(){var e=this.manager.shouldShowAvatars();e&&"function"==typeof e.done?e.done(function(e){this._cachedShouldShowAvatars=!!e}.bind(this)):"boolean"==typeof e&&(this._cachedShouldShowAvatars=e),this.countActivePlayers()}.bind(this))}var i=["user:join","change:length","connectInfo:change","pool:degraded","pool:lost","pool:spawned","pool:capacity:exhausted"],e=t.prototype=new e;return e.call=function(){return this.manager.call.apply(this.manager,arguments)},e.initialize=function(e){return this.manager.initialize(e)},e.showIndexScreen=function(){return this.manager.call.apply(this.manager,["showIndexScreen"].concat(Array.prototype.slice.call(arguments)))},e.enableNavigation=function(e,t){return this.manager.enableNavigation(e,t)},e.getConnectScreen=function(e){return this.manager.getConnectScreen(e)},e.getAuthenticationScreen=function(e){return this.manager.getAuthenticationScreen(e)},e.login=function(e){return this.manager.login(e)},e.clearConnectScreen=function(e){return this.manager.clearConnectScreen(e)},e.activateKeyboardUser=function(e){return this.manager.activateKeyboardUser(e)},e.setKeyboardUser=function(e){return this.manager.setKeyboardUser(e)},e.createDummyUser=function(e,t,n){return this.manager.createDummyUser(e,t,n)},e.getAccessTokens=function(){return this.manager.getAccessTokens()},e.applyConfigOverrides=function(e){return this._config&&"function"==typeof this._config.applyOverrides&&this._config.applyOverrides(e),this.manager.applyConfigOverrides(e)},e.pause=function(){return this.manager.call.apply(this.manager,["pause"].concat(Array.prototype.slice.call(arguments)))},e.resume=function(){return this.manager.call.apply(this.manager,["resume"].concat(Array.prototype.slice.call(arguments)))},e.hasKeyboardPlayer=function(){return this.keyboardPlayer},e.startGame=function(){return this.manager.call.apply(this.manager,["startGame"].concat(Array.prototype.slice.call(arguments)))},e.getConnectToken=function(){return this.connectToken},e.getConnectTokenForDisplay=function(){return this.connectTokenForDisplay},e.getConnectURL=function(){return this.connectUrl},e.getServer=function(){return this.server},e.getContentProxy=function(){return this.contentProxy},e.getRelayGameId=function(){return this.gameId},e.getRelayAccessToken=function(){return this.accessToken},e.countActivePlayers=function(){var e=this.manager.countActivePlayers();return e&&"function"==typeof e.done?e.done(function(e){this._cachedActivePlayerCount=e}.bind(this)):"number"==typeof e&&(this._cachedActivePlayerCount=e),this._cachedActivePlayerCount},e.shouldShowAvatars=function(){var e=this.manager.shouldShowAvatars();return e&&"function"==typeof e.done?e.done(function(e){this._cachedShouldShowAvatars=!!e}.bind(this)):"boolean"==typeof e&&(this._cachedShouldShowAvatars=e),this._cachedShouldShowAvatars},e.isDelayed=function(e){e=this.manager.isDelayed(e);return e&&"function"==typeof e.done?e.done(function(e){this._cachedIsDelayed=!!e}.bind(this)):"boolean"==typeof e&&(this._cachedIsDelayed=e),this._cachedIsDelayed},e.disconnect=function(){return this.manager.disconnect()},Object.defineProperty(e,"length",{get:function(){return this.manager.length}}),Object.defineProperty(e,"actualPlayersLength",{get:function(){return this.manager.actualPlayersLength}}),e.filter=function(o){return"undefined"==typeof Proxy?(console.error("This browser is too old to do player-pool filtering."),this):new Proxy(this,{get:function(n,e,t){var i;return"function"!=typeof n[e]?n[e]:(i=n[e],function(){var e=Array.prototype.slice.call(arguments),t={};return t.__playerFilters=o,e.push(t),i.apply(n,e)})}})},t}),define("CatLab/Webremote/Transport/LoopbackPort",[],function(){function i(e){this.kind="loopback",this._queue=e,this._peer=null,this._handlers=[],this._errorHandlers=[],this._closed=!1}var e=i.prototype;function o(){this._pending=[],this._scheduled=!1}return e.post=function(e){if(this._closed)throw new Error("LoopbackPort: post after close");e=e;var t="function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e,function(e,t){if("function"==typeof t)throw new Error('LoopbackPort: value could not be cloned (function at "'+e+'")');return t})),n=this._peer;this._queue.enqueue(function(){n._closed||n._deliver(t)})},e._deliver=function(t){for(var e=this._handlers.slice(),n=0;n<e.length;n++)try{e[n](t)}catch(t){0===this._errorHandlers.length?console.error("[LoopbackPort] message handler threw:",t):this._errorHandlers.slice().forEach(function(e){e(t)})}},e.onMessage=function(t){var n=this;return this._handlers.push(t),function(){var e=n._handlers.indexOf(t);-1!==e&&n._handlers.splice(e,1)}},e.onError=function(t){var n=this;return this._errorHandlers.push(t),function(){var e=n._errorHandlers.indexOf(t);-1!==e&&n._errorHandlers.splice(e,1)}},e.close=function(){this._closed=!0,this._handlers=[],this._errorHandlers=[]},e.isClosed=function(){return this._closed},o.prototype.enqueue=function(e){var t;this._pending.push(e),this._scheduled||(this._scheduled=!0,t=this,Promise.resolve().then(function(){t._drain()}))},o.prototype._drain=function(){this._scheduled=!1;var e=this._pending;this._pending=[];for(var t=0;t<e.length;t++)e[t]()},o.prototype.flush=function(){var n=this;return new Promise(function(t){!function e(){0!==n._pending.length||n._scheduled?Promise.resolve().then(e):t()}()})},i.pair=function(){var e=new o,t=new i(e),n=new i(e);return{a:(t._peer=n)._peer=t,b:n,flush:function(){return e.flush()}}},i}),define("CatLab/Webremote/Transport/Hosts/LoopbackHost",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/LoopbackPort","CatLab/Webremote/Transport/Errors"],function(e,n,i,o){function t(e){if(this.initializeEventable(),this.kind="loopback",this._boot=e&&e.boot,this._pair=null,this._started=!1,"function"!=typeof this._boot)throw new Error("LoopbackHost: options.boot(port) is required")}e=t.prototype=new e;return e.start=function(){var t=new n;if(this._started)t.reject(new o.PoolBootError(this.kind,"host already started"));else{this._started=!0,this._pair=i.pair();try{this._boot(this._pair.b)}catch(e){return this._pair.a.close(),this._pair.b.close(),t.reject(e),t.promise()}t.resolve(this._pair.a)}return t.promise()},e.flush=function(){return this._pair?this._pair.flush():Promise.resolve()},e.terminate=function(){this._pair&&(this._pair.a.close(),this._pair.b.close())},t}),define("CatLab/Webremote/FrontController",["CatLab/Webremote/Config","CatLab/Webremote/Polyfills","CatLab/Webremote/Tools/Tracker","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Controllers/Webremote","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Images","CatLab/Webremote/Models/Users/DummyUser","CatLab/Webremote/Providers/SocketIO","CatLab/Webremote/Providers/Airconsole","CatLab/Webremote/Providers/Dummy","CatLab/Webremote/Providers/BridgedProvider","CatLab/Webremote/ViewFactory/ViewFactory","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/PlayerPool/PlayerPool","CatLab/Webremote/PlayerPool/GameLogic","CatLab/Webremote/PlayerPool/PlayerPoolWorker","CatLab/Webremote/PlayerPool/SeatAuthority","CatLab/Webremote/PlayerPool/SeatAuthorityBinder","CatLab/Webremote/PlayerPool/RandomPlayerList","CatLab/Webremote/PlayerPool/Player","CatLab/Webremote/PlayerPool/DeviceConnection","CatLab/Webremote/Collections/PlayerCollection","CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/PlayerPool/Managers/WebworkerManager","CatLab/Webremote/PlayerPool/Managers/WorkerManager","CatLab/Webremote/PlayerPool/Managers/PoolCoordinator","CatLab/Webremote/PlayerPool/PlayerPoolClient","CatLab/Webremote/PlayerPool/EngineManifest","CatLab/Webremote/PlayerPool/Protocol/Aggregators","CatLab/Webremote/PlayerPool/Protocol/Router","CatLab/Webremote/PlayerPool/Protocol/ManifestProxy","CatLab/Webremote/PlayerPool/Protocol/whenAllSettled","CatLab/Webremote/LocalInput/DeviceObject","CatLab/Webremote/LocalInput/DeviceChannel","CatLab/Webremote/LocalInput/KeyboardInput","CatLab/Webremote/LocalInput/CordovaInput","CatLab/Webremote/LocalInput/AndroidRemoteInput","CatLab/Webremote/LocalInput/GamepadInput","CatLab/Webremote/LocalInput/AppActions","CatLab/Webremote/LocalInput/ProviderHost","CatLab/Webremote/PlayerPool/LocalDevices/LocalDeviceUser","CatLab/Webremote/PlayerPool/LocalDevices/DeviceRegistry","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/index","CatLab/Webremote/Transport/Codec","CatLab/Webremote/Transport/Errors","CatLab/Webremote/Transport/WorkerPort","CatLab/Webremote/Transport/LoopbackPort","CatLab/Webremote/Transport/Hosts/DedicatedWorkerHost","CatLab/Webremote/Transport/Hosts/IframeWorkerHost","CatLab/Webremote/Transport/Hosts/LoopbackHost"],function(t,O,e,n,i,o,r,s,a,l,c,h,u,d,f,p,g,m,v,b,y,w,_,C,k,L,P,T,S,E,I,W,A,x,M,U,D,V,N,z,F,R,B,j,H,G,q,K,J,X,Q,Y,$,Z){return{Config:function(e){t.set(e)},Tracker:e,Tools:n,Webremote:new i,Webcontrol:new r,OAuth2:o,Controllers:{Webcontrol:r,Webremote:i},Models:{User:l},Controls:{Dummy:l},Providers:{SocketIO:c,Airconsole:h,Dummy:u,Bridged:d},Transport:{Codec:K,Errors:J,WorkerPort:X,LoopbackPort:Q,Hosts:{DedicatedWorkerHost:Y,IframeWorkerHost:$,LoopbackHost:Z}},ViewFactories:{HtmlViewFactory:f,CreatejsViewFactory:p},Smileys:s,Images:new a,NavigateableProxy:g,LocalInput:{DeviceObject:D,DeviceChannel:V,KeyboardInput:N,CordovaInput:z,AndroidRemoteInput:F,GamepadInput:R,AppActions:B,ProviderHost:j},LocalDevices:{LocalDeviceUser:H,DeviceRegistry:G,Profiles:q},PlayerPool:{PlayerPool:m,GameLogic:v,PlayerPoolWorker:b,bootWorker:b.bootWorker,SeatAuthority:y,SeatAuthorityBinder:w,RandomPlayerList:_,Player:C,DeviceConnection:k,Manager:P,WebworkerManager:T,WorkerManager:S,PoolCoordinator:E,PlayerPoolClient:I,EngineManifest:W,Protocol:{Aggregators:A,Router:x,ManifestProxy:M,whenAllSettled:U}},Collections:{Players:L}}}),define("catlabremote",["CatLab/Webremote/FrontController"],function(e){return e}),define("CatLab/EaselHacks/AlphaMaskFilter",[],function(e){function t(e){var n=this;this.createjs=e,Object.defineProperty(e.DisplayObject.prototype,"mask",{get:function(){return this.forceMask},set:function(e){var t;e?(this.originalMask=e,t=n.getFilterFromMask(e,this),this.filters=[t],this.cache(0,0,500,500)):null!==e&&(this.filters=null,this.cache(0,0,500,500))}}),e.DisplayObject.prototype.setMask=function(e){this.forceMask=e}}return t.prototype.getFilterFromMask=function(e,t){var n=this.createjs,i=e.graphics.getInstructions(),o=new n.Graphics;o.beginFill("#000000"),o.beginStroke("#000000");for(var r=0;r<i.length;r++)o.append(i[r]);e.graphics=o;var s=new n.Container,e=(s.addChild(e),s.scaleX=1/t.scaleX,s.scaleY=1/t.scaleY,s.y=-t.y,s.x=-t.x,new n.Container);return e.addChild(s),e.cache(0,0,1e3,1e3),new n.AlphaMaskFilter(e.cacheCanvas)},t}),define("CatLab/EaselHacks/FrontController",["CatLab/EaselHacks/AlphaMaskFilter"],function(e){return{AlphaMaskFilter:e}}),define("easelhacks",["CatLab/EaselHacks/FrontController"],function(e){return e}),define("CatLab/Webremote/Hacks",["easelhacks","easeljs"],function(e,t){new e.AlphaMaskFilter(t)});
1
+ var io;define("CatLab/Webremote/Tools/Net",[],function(){return{loadJSON:function(e,t,n){var i=new XMLHttpRequest;i.onreadystatechange=function(){i.readyState===XMLHttpRequest.DONE&&200===i.status&&t&&t(JSON.parse(i.responseText))},i.onerror=function(e){e&&n(i,e)},i.open("GET",e,!0),i.send()}}}),define("CatLab/Webremote/Tools/Deferred",[],function(){function c(e){return"[object Array]"===Object.prototype.toString.call(e)}function h(e,t){if(c(e))for(var n=0;n<e.length;n++)t(e[n]);else t(e)}function u(e){var i="pending",o=[],r=[],s=[],a=null,n={done:function(){for(var e=0;e<arguments.length;e++)if(arguments[e])if(c(arguments[e]))for(var t=arguments[e],n=0;n<t.length;n++)"resolved"===i&&t[n].apply(this,a),o.push(t[n]);else"resolved"===i&&arguments[e].apply(this,a),o.push(arguments[e]);return this},fail:function(){for(var e=0;e<arguments.length;e++)if(arguments[e])if(c(arguments[e]))for(var t=arguments[e],n=0;n<t.length;n++)"rejected"===i&&t[n].apply(this,a),r.push(t[n]);else"rejected"===i&&arguments[e].apply(this,a),r.push(arguments[e]);return this},always:function(){return this.done.apply(this,arguments).fail.apply(this,arguments)},progress:function(){for(var e=0;e<arguments.length;e++)if(arguments[e])if(c(arguments[e]))for(var t=arguments[e],n=0;n<t.length;n++)"pending"===i&&s.push(t[n]);else"pending"===i&&s.push(arguments[e]);return this},then:function(){return 1<arguments.length&&arguments[1]&&this.fail(arguments[1]),0<arguments.length&&arguments[0]&&this.done(arguments[0]),2<arguments.length&&arguments[2]&&this.progress(arguments[2]),this},promise:function(e){if(null==e)return n;for(var t in n)e[t]=n[t];return e},state:function(){return i},debug:function(){console.log("[debug]",o,r,i)},isRejected:function(){return"rejected"===i},isResolved:function(){return"resolved"===i},pipe:function(e,t,n){return u(function(n){h(e,function(t){"function"==typeof t?l.done(function(){var e=t.apply(this,arguments);e&&"function"==typeof e?e.promise().then(n.resolve,n.reject,n.notify):n.resolve(e)}):l.done(n.resolve)}),h(t,function(t){"function"==typeof t?l.fail(function(){var e=t.apply(this,arguments);e&&"function"==typeof e?e.promise().then(n.resolve,n.reject,n.notify):n.reject(e)}):l.fail(n.reject)})}).promise()}},l={resolveWith:function(e){if("pending"===i){i="resolved";for(var t=a=1<arguments.length?arguments[1]:[],n=0;n<o.length;n++)o[n].apply(e,t)}return this},rejectWith:function(e){if("pending"===i){i="rejected";for(var t=a=1<arguments.length?arguments[1]:[],n=0;n<r.length;n++)r[n].apply(e,t)}return this},notifyWith:function(e){if("pending"===i)for(var t=a=1<arguments.length?arguments[1]:[],n=0;n<s.length;n++)s[n].apply(e,t);return this},resolve:function(){return this.resolveWith(this,arguments)},reject:function(){return this.rejectWith(this,arguments)},notify:function(){return this.notifyWith(this,arguments)}},t=n.promise(l);return e&&e.apply(t,[t]),t}return u.when=function(){var e,t;if(arguments.length<2)return((e=arguments.length?arguments[0]:void 0)&&"function"==typeof e.isResolved&&"function"==typeof e.isRejected?e:e&&"function"==typeof e.done&&"function"==typeof e.fail?(t=u(),e.done(function(){t.resolve.apply(t,arguments)}),e.fail(function(){t.reject.apply(t,arguments)}),t):u().resolve(e)).promise();for(var n=arguments,i=u(),o=n.length,r=0,s=new Array(o),a=0;a<n.length;a++)(e=>{var t;n[e]&&n[e].done?n[e].done(function(){s[e]=arguments.length<2?arguments[0]:arguments,++r==o&&i.resolve.apply(i,s)}).fail(function(){i.reject(arguments)}):(t=n[e],n[e]=u(),n[e].done(function(){s[e]=arguments.length<2?arguments[0]:arguments,++r==o&&i.resolve.apply(i,s)}).fail(function(){i.reject(arguments)}).resolve(t))})(a);return i.promise()},u}),define("CatLab/Webremote/Collections/ServerList",["CatLab/Webremote/Tools/Deferred"],function(o){function e(e,t){this.defaultId=e.default,this.servers=e.servers,this.connectUrl=e.connectUrl,this.selectedServerId=null,this.preferredServer=t,this.assetsUrl=e.assetsUrl}var t=e.prototype;return t.getFromToken=function(e){if(e.length<8)return{host:this.getDefault().host,token:e};var t=e.substr(0,2);if(t){t=this.getFromId(t);if(t)return{host:t.host,token:e.substr(2)}}throw new Error("Code does not correspondent to any servers.")},t.getSelectedServer=function(){var t=new o;return this.selectedServerId?this.getFromId(this.selectedServerId)?t.resolve(this.getFromId(this.selectedServerId).host):t.reject("Selected remote server not found in server list. Please make sure you are connected to the right network."):this.selectBestServer().then(function(e){this.selectedServerId||(this.selectServer(e.id),t.resolve(e.host))}.bind(this)),t.promise()},t.selectBestServer=function(){var n=new o;if(this.preferredServer)for(var e=0;e<this.servers.length;e++)if(this.servers[e].id==this.preferredServer)return n.resolve(this.servers[e]),n.promise();var i=!1;return this.servers.forEach(function(t){t.discoverable&&this.measureRequestSpeed("https://"+t.host+"/info").then(function(e){console.log("[ServerList] "+t.host+" took "+e+"ms"),i||(i=!0,n.resolve(t))}.bind(this))}.bind(this)),n.promise()},t.selectServer=function(e){this.selectedServerId=e},t.measureRequestSpeed=function(e){var t=new Date,n=new o,i=new XMLHttpRequest;return i.onreadystatechange=function(){var e;4==this.readyState&&200==this.status&&(e=(new Date).getTime()-t.getTime(),n.resolve(e))},i.open("GET",e),i.send(),n.promise()},t.getConnectURL=function(){if(this.selectedServerId){var e=this.getFromId(this.selectedServerId);if(e.connectUrl)return e.connectUrl}return this.connectUrl},t.getAssetURL=function(){var e;return this.assetsUrl||((e=this.getConnectURL())?("http"!==e.substring(0,4)&&(e="https://"+e),this.assetsUrl=e+"/assets/",this.assetsUrl):void 0)},t.getConnectToken=function(e){return null==e?null:this.getFromId(this.selectedServerId).connectUrl?e:this.selectedServerId+e},t.getFromId=function(e){for(var t=0;t<this.servers.length;t++)if(this.servers[t].id==e)return this.servers[t];return null},t.getDefault=function(){return this.getFromId(this.defaultId)},t.serialize=function(){return{server:this.selectedServerId}},t.unserialize=function(e){this.selectServer(e.server)},e}),define("CatLab/Webremote/Config",["CatLab/Webremote/Tools/Net","CatLab/Webremote/Collections/ServerList"],function(i,e){var t="http";return{_options:{host:"www.catlab.tv",serverlist:null,preferredServer:null,protocol:t="undefined"!=typeof window&&void 0!==window.location&&void 0!==window.location.protocol?window.location.protocol.substr(0,window.location.protocol.length-1):t,debug:!1,proxy:"",imageproxy:"",smileys:!0,assetsUrl:null,vendorPath:"/vendor/",audioSync:!1,allowAuthentication:!0,canFullscreen:!0,oauth:{redirectUrl:null}},_initialized:!1,_serverlistSource:null,audioSyncConfig:{alphabet:"qwertyuiop",length:5,freqMin:524,freqMax:1593,freqError:25,debug:!1},set:function(e){void 0!==e&&(e.host,this._options.host=e.host,void 0!==e.protocol&&(this._options.protocol=e.protocol),void 0!==e.debug&&(this._options.debug=e.debug),void 0!==e.imageproxy&&(this._options.imageproxy=e.imageproxy),void 0!==e.proxy&&(this._options.proxy=e.proxy),void 0!==e.smileys&&(this._options.smileys=e.smileys),void 0!==e.assetsUrl&&(this._options.assetsUrl=e.assetsUrl),void 0!==e.vendorPath&&(this._options.vendorPath=e.vendorPath),void 0!==e.audioSync&&(this._options.audioSync=e.audioSync),void 0!==e.serverlist&&e.serverlist!==this._serverlistSource&&(this._options.serverlist=e.serverlist,this._serverlistSource=null,this.serverCollection=null),void 0!==e.preferredServer&&(this._options.preferredServer=e.preferredServer),void 0!==e.allowAuthentication&&(this._options.allowAuthentication=e.allowAuthentication),void 0!==e.audioSyncConfig&&(this.audioSyncConfig=e.audioSyncConfig),void 0!==e.canFullscreen&&(this._options.canFullscreen=e.canFullscreen),void 0!==e.oauth&&void 0!==e.oauth.redirectUrl&&(this._options.oauth.redirectUrl=e.oauth.redirectUrl),void 0!==e.APP_ID&&(this.APP_ID=e.APP_ID),void 0!==e.APP_SECRET)&&(this.APP_SECRET=e.APP_SECRET)},getAll:function(){return this._options},initialize:function(t){var e,n=this._options.serverlist;null===n||"string"!=typeof n||"http"!==n.substring(0,4)?(this._initialized=!0,t()):"json"===n.substring(n.length-4)?i.loadJSON(n,function(e){this._initialized=!0,this._serverlistSource=n,this._options.serverlist=e,t()}.bind(this),function(e,t){alert("Failed to connect to "+n+". Game cannot start."),console.log(t)}.bind(this)):((e=document.createElement("script")).onload=function(){this._initialized=!0,this._serverlistSource=n,this._options.serverlist=getCatLabRemoteServers(),t()}.bind(this),e.onerror=function(){alert("Failed to connect to "+n+". Game cannot start.")}.bind(this),e.src=n,document.head.appendChild(e))},getProtocol:function(e){var t=this._options.protocol;switch(t=void 0!==e&&e&&""===t?"http":t){case"http":case"https":break;default:t="https"}return t},getSocketURL:function(e){return this._options.host?((e=this.getProtocol(e))&&(e+=":"),e+"//"+this._options.host):"undefined"!=typeof window&&void 0!==window.location?window.location.protocol+"//"+window.location.hostname:""},getAssetsURL:function(e){var t;return this._options.assetsUrl||((t=this.getServerList())?t.getAssetURL():this.getSocketURL(e)+"/assets/")},debug:function(){return this._options.debug},getProxiedImage:function(e){return this._options.imageproxy?this._options.imageproxy+encodeURIComponent(e):e},getProxy:function(){return this._options.proxy},useSmileys:function(){return this._options.smileys},useAudioSync:function(){return this._options.audioSync},all:function(){return this._options},getAudioSyncConfig:function(){return this.audioSyncConfig},getProviderConfig:function(){var e={smileys:this.useSmileys(),audioSync:this.useAudioSync()};return this.useAudioSync()&&(e.audioSyncConfig=this.audioSyncConfig),this.APP_ID&&(e.app={id:this.APP_ID,secret:this.APP_SECRET||null}),e},getServerList:function(){return this._options.serverlist?(this.serverCollection||(this.serverCollection=new e(this._options.serverlist,this._options.preferredServer)),this.serverCollection):null},getVendorPath:function(){return this._options.vendorPath},supportsAuthentication:function(){return this._options.allowAuthentication},canFullscreen:function(){return this._options.canFullscreen}}}),define("CatLab/Webremote/Polyfills",[],function(){"function"!=typeof Object.assign&&(Object.assign=function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var n=Object(e),i=1;i<arguments.length;i++){var o=arguments[i];if(null!=o)for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(n[r]=o[r])}return n})}),define("CatLab/Webremote/Tools/Tracker",[],function(){var o=function(e,t,n,i){},t=function(e){o("Page",e,"-",0)};return{setTracker:function(e){o=e},setPageMethod:function(e){t=e},track:function(e,t,n,i){o(e,t,n,i)},page:function(e){t(e)}}}),define("CatLab/Webremote/Tools/Tools",[],function(){var o,r;return{popup:function(e,t){var n=this,i=(t=t||!1,document.createElement("iframe"));i.style.margin=0,i.style.padding=0,i.style.border=0,i.style.position="absolute",i.style.width="100%",i.style.height="100%",i.style.left=0,i.style.top=0,i.src=e,(r=document.createElement("div")).style.margin=0,r.style.padding=0,r.style.border=0,r.style.position="absolute",r.style.width="100%",r.style.height="100%",r.style.left=0,r.style.top=0,r.style.zIndex=9999,r.onclick=function(){n.closePopup()},(o=document.createElement("div")).appendChild(i),o.style.margin=0,o.style.padding=0,o.style.border=0,o.style.position="absolute",o.style.zIndex=1e4,o.style.overflow="auto",o.style.background="white",o.style.boxSizing="border-box",t?(o.style.border="0 none black",o.style.left="0",o.style.top="0",o.style.width="100%",o.style.height="100%"):(o.style.border="5px solid black",o.style.left="10%",o.style.top="10%",o.style.width="80%",o.style.height="80%"),document.body.appendChild(r),document.body.appendChild(o)},oauth2PopupMethod:function(e,t){return window.open(e,"oauth:catlab-remote")},oauth2Popup:function(e,t){return this._popupBridge?this._popupBridge(e,t):"undefined"==typeof window||"function"!=typeof window.open?(console.warn("[OAuth2] Cannot open popup — no bridge configured"),null):this.oauth2PopupMethod(e,t)},setPopupBridge:function(e){return this._popupBridge=e,this},closePopup:function(){o&&o.parentNode.removeChild(o),r&&r.parentNode.removeChild(r)},setOauth2Popup:function(e){return this.oauth2PopupMethod=e,this},sanitize:function(e){var t;return null==e?null:(t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"},String(e).replace(/[&<>"']/g,function(e){return t[e]}))},nl2br:function(e,t){return null==e?"":(e+"").replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,"$1"+(t||void 0===t?"<br />":"<br>")+"$2")},shuffle:function(e){for(var t,n,i=e.length-1;0<i;i--)t=Math.floor(Math.random()*(i+1)),n=e[i],e[i]=e[t],e[t]=n},getUuid:function(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)},findIndex:function(e,t){for(var n=0;n<e.length;n++)if(t(e[n]))return n;return-1},getConnectTokenForDisplay:function(e){return null===e?null:e.length%4==0?this.injectFillerInString(e,4," "):(e.length,this.injectFillerInString(e,3," "))},injectFillerInString:function(e,t,n){return e.match(new RegExp(".{1,"+t+"}","g")).join(n)}}}),define("CatLab/Webremote/Tools/Cookies",[],function(){var r=null,t={setCookieBridge:function(e){r=e},setCookie:function(e,t,n){return this.setItem(e,t,n)},getCookie:function(e){return this.getItem(e)},eraseCookie:function(e){return this.removeItem(e)},getItem:function(e){return r?r.get(e):"undefined"!=typeof document&&void 0!==document.cookie&&e&&this.hasOwnProperty(e)?unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"),"$1")):null},key:function(e){return r?r.key?r.key(e):null:"undefined"==typeof document||void 0===document.cookie?null:unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/,"").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[e])},setItem:function(e,t,n){if(e){if(r)return r.set(e,t,n);var i,o;"undefined"!=typeof document&&void 0!==document.cookie&&(i="",n&&((o=new Date).setTime(o.getTime()+Math.round(24*n*60*60*1e3)),i="; expires="+o.toUTCString()),document.cookie=escape(e)+"="+escape(t)+"; expires="+i+"; path=/; SameSite=Strict;",this.updateLength())}},length:0,removeItem:function(e){if(r)return r.erase(e);e&&this.hasOwnProperty(e)&&"undefined"!=typeof document&&void 0!==document.cookie&&(document.cookie=escape(e)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Strict;",this.length--)},hasOwnProperty:function(e){return r?null!=r.get(e):"undefined"!=typeof document&&void 0!==document.cookie&&new RegExp("(?:^|;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(document.cookie)},updateLength:function(){var e;!r&&"undefined"!=typeof document&&document.cookie&&(e=document.cookie.match(/\=/g),t.length=e?e.length:0)}};return t.updateLength(),t}),define("CatLab/Webremote/Tools/Images",["CatLab/Webremote/Config"],function(o){function e(e){this.images={},this.availableSizes=e=void 0===e?[512,256,128]:e}var t=e.prototype;return t.getImage=function(e,t){var n;return void 0!==t&&-1!==this.availableSizes.indexOf(t)||(t=this.availableSizes[0]),void 0===this.images[e+"_"+t]&&((n=new Image).crossOrigin="anonymous",n.src=this.getUrl(e,t),this.images[e+"_"+t]=n),this.images[e+"_"+t]},t.getUrl=function(e,t){if(!e)return e;if(this.isExternal(e))return e;void 0!==t&&-1!==this.availableSizes.indexOf(t)||(t=this.availableSizes[0]);for(var n=e.split("/"),i=0;i<n.length;i++)"$SIZE"===n[i]&&(n[i]=t);return e=n.join("/"),o.getAssetsURL()+e},t.isExternal=function(e){return"string"==typeof e&&0===e.indexOf("http")},e}),define("CatLab/Webremote/Tools/Smileys",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Tools/Images"],function(n,i,t){function e(e){this.provider=e,this.smileyKeys=["1f98d","1f61c","1f3b7","1f32e","1f621","1f61b","1f98f","1f34c","1f596","1f34d","2660","1f61a","2602","2665","1f0cf","1f427","1f918","1f98b","1f9df","1f344","1f983","1f338","2618","1f36a","1f383","270c","1f913","1f40d","1f910","1f57a","1f641","1f36c","1f579","1f333","1f40b","1f617","1f42b","1f60d","1f42c","1f339","1f414","1f42d","1f349","1f92e","1f437","1f367","1f62c","1f428","1f994","1f911","1f369","1f9d0","1f378","1f9dd-2640","1f34e","2666","1f47d","1f60a","1f60f","1f43b","1f47b","1f425","1f919","1f346","1f4a8","1f43f","1f37a","1f40c","1f334","1f4a3","1f42e","1f379","1f42f","1f417","1f9c0","1f601","1f41a","1f61d","1f997","26c4","1f34b","1f430","1f47a","1f37c","1f3b1","1f95d","1f433","1f41b","1f37f","1f36d","1f60e","1f354","1f63b","1f680","1f996","1f924","1f341","1f43a","1f922","1f436","1f43c","1f332","1f31a","1f335","1f336","2623","1f31e","1f63d","1f421","1f438","1f63a","1f32d","1f986","1f388","1f41e","1f98c","1f91e","1f64a","1f638","1f3b5","1f43d","1f363","1f373","1f435","1f628","1f635","1f377","1f47e","1f984","1f3a9","1f439","1f925","1f929","1f951","1f4a9","1f921","1f92a","1f96a","1f41f","1f419","1f420","2663","1f40a","1f989","1f91f","1f63c","1f3f3-1f308","1f98a","1f431","1f920","1f41d","1f608","1f612","1f987","1f3ba","1f355","270b","1f98e","1f41c","1f917"],this.taken={},this.takenAmount=0,this.playerKnowsAboutNonUniqueSmileys={},this.images=new t,this.randomSmileys=this.smileyKeys.slice(0),i.shuffle(this.randomSmileys)}var o=e.prototype;return o.shouldHaveUniqueSmileys=function(){return this.takenAmount<this.smileyKeys.length/3},o.setTakenSmileys=function(e){this.taken=e},o.getTakenSmileys=function(e){if(!this.shouldHaveUniqueSmileys())return{};e=this.identifierToText(e);var t,n={};for(t in this.taken)this.taken.hasOwnProperty(t)&&this.taken[t]!==e&&(n[t]=this.taken[t]);return n},o.getRandom=function(e){for(var t=null;null===t&&this.randomSmileys;)if(t=this.randomSmileys.shift(),this.reserve(t,e)||(t=null),0===this.randomSmileys.length)return this.randomSmileys=this.smileyKeys.slice(0),i.shuffle(this.randomSmileys),this.randomSmileys.shift();return t},o.reserve=function(e,t){return this.isExternalSmiley(e)?(this.unreserve(t),!0):(t=this.identifierToText(t),void 0!==this.taken[e]&&this.taken[e]===t?(this.taken[e]=t,!0):!!this.isAvailable(e)&&(this.unreserve(t),this.taken[e]=t,this.takenAmount++,!0))},o.unreserve=function(e){for(var t in e=this.identifierToText(e),this.taken)this.taken.hasOwnProperty(t)&&this.taken[t]===e&&(this.taken[t]=null,delete this.taken[t],this.takenAmount--)},o.isAvailable=function(e){return!this.shouldHaveUniqueSmileys()||!!this.isExternalSmiley(e)||null==this.taken[e]},o.identifierToText=function(e){return JSON.stringify(e)},o.isExternalSmiley=function(e){return"http"===e.substring(0,4).toLowerCase()},o.getUrl=function(e){var t=this.getImageUrl(e);return t?this.isExternalSmiley(e)?e:n.getAssetsURL()+t:null},o.getImageUrl=function(e){return null===e?null:this.isExternalSmiley(e)?e:"smileys/"+e+".png"},o.getHtml=function(e){return null===e?null:'<span class="smiley" style="width: 64px; height: 64px; display: inline-block; background-image: url(\''+this.getUrl(e)+"');\"></span>"},o.getElement=function(e){var t;return null===e?null:((t=document.createElement("div")).innerHTML=this.getHtml(e),t.firstChild)},o.getImage=function(e){return null===e?null:this.images.getImage(this.getImageUrl(e))},o.refreshTakenSmileys=function(e){if(!this.shouldHaveUniqueSmileys())return void 0!==this.playerKnowsAboutNonUniqueSmileys[this.getStringIdentifier(e)]?void 0:(this.playerKnowsAboutNonUniqueSmileys[this.getStringIdentifier(e)]=!0,void e.emit("smileys:taken",{smileys:[]}));e.emit("smileys:taken",{smileys:this.getTakenSmileys(e.getIdentifier())})},o.getStringIdentifier=function(e){return e.type+":"+e.id},e}),define("CatLab/Webremote/Tools/Preloader",["../Config","CatLab/Webremote/Tools/Deferred"],function(t,r){function n(e){this.provider=e,this.provider.on("file:preload",function(e){e&&e.url&&this.preloadClientFile(e.url)}.bind(this)),this.urlMap={}}var e=n.prototype;return e.preload=function(t){if(Array.isArray(t)){for(var e=new r,n=[],i=0;i<t.length;i++)n.push(this.preload(t[i]));return r.when.apply(r,n).then(function(){e.resolve(Array.prototype.slice.call(arguments))}),e.promise()}var o=new r;return this.urlMap[t]=t,this.provider.proxyFile(t).then(function(e){this.urlMap[t]=e.url,this.provider.emit("file:preload",{url:e.url}),o.resolve(e)}.bind(this)),o.promise()},e.sendPreloadFileCommandToPlayer=function(e){for(var t in this.urlMap)this.urlMap.hasOwnProperty(t)&&e.emit("file:preload",{url:this.urlMap[t]})},e.getPreloadedUrl=function(e){return this.urlMap[e]},e.preloadClientFile=function(e){void 0===this.urlMap[e]&&(e.toLowerCase().indexOf("http")<0&&(e=t.getProtocol()+":"+e),this.urlMap[e]=document.createElement("img"),this.urlMap[e].src=e)},e.serialize=function(){return{urlMap:this.urlMap}},n.unserialize=function(e,t){e=new n(e);return void 0!==t&&void 0!==t.urlMap&&(e.urlMap=t.urlMap),e},n}),define("CatLab/Webremote/Tools/Eventable",["CatLab/Webremote/Tools/Tools"],function(i){function e(){}var o=0,t=e.prototype;return t.initializeEventable=function(){this._eventableEvents=[]},t.trigger=function(e){this.eventableTrigger.apply(this,arguments)},t.eventableTrigger=function(e){if("string"!=typeof e)throw new Error("eventableTrigger must be a string");if(void 0!==this._eventableEvents){var t,n=Array.prototype.slice.call(arguments);for(t in n.push(n.shift()),this._eventableEvents)this._eventableEvents.hasOwnProperty(t)&&this.eventMatches(e,t)&&this._eventableEvents[t].slice().forEach(function(e){try{e.method.apply(e.scope,n)}catch(e){console.error(e)}}.bind(this))}},t.eventMatches=function(e,t){return"*"===t||e===t},t.on=function(e,t,n){void 0===this._eventableEvents&&(this._eventableEvents={}),void 0===this._eventableEvents[e]&&(this._eventableEvents[e]=[]),o++,this._eventableEvents[e].push({id:o,method:t,scope:void 0!==n?n:this});var i=[e,o];return{id:i,name:e,method:t,unbind:function(){this.off(null,{id:i,name:e})}.bind(this)}},t.once=function(e,t,n){var i=this.on(e,function(){i.unbind(),t.apply(n,arguments)});return i},t.off=function(e,t){if(void 0!==e||void 0!==t)if(void 0===e||void 0!==t){if(e=t.name,t=t.id,void 0===this._eventableEvents[e])return null;var n=i.findIndex(this._eventableEvents[e],function(e){return e.id===t[1]});0<=n&&this._eventableEvents[e].splice(n,1)}else this._eventableEvents[e]=[];else this._eventableEvents=[]},t.clearEvents=function(){this.clearEventableEvents()},t.clearEventableEvents=function(){this._eventableEvents={}},e}),define("CatLab/Webremote/Models/User",["CatLab/Webremote/Config"],function(t){return function(e){this.accessToken=e,this.name=null,this.avatar=null,this.id=null,this.image=null,this.imageCallbacks=[],this.imageLoaded=!1,this.getAccessToken=function(){return this.accessToken},this.setId=function(e){this.id=e},this.getId=function(){return this.id},this.setName=function(e){this.name=e},this.getName=function(){return this.name},this.setAvatar=function(e){this.avatar=e,this.imageLoaded=!1,this.imageCallbacks=[],this.image=null},this.loadAvatar=function(){this.image||(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=function(){this.afterImageLoad()}.bind(this),this.image.src=t.getProxiedImage(this.avatar))},this.getAvatar=function(){return this.avatar},this.getAvatarSmiley=function(e){var t=this.getAvatar();return t?(t=t.split("?")[0],t+="?shape=circle&size=64&borderWidth=4",e&&(t+="&borderColor="+e.substr(1)),t):null},this.afterImageLoad=function(){this.imageLoaded=!0;for(var e=0;e<this.imageCallbacks.length;e++)this.imageCallbacks[e](this.image);this.imageCallbacks=[]},this.getImage=function(e){this.loadAvatar(),this.imageLoaded?e(this.image):this.imageCallbacks.push(e)}}}),define("CatLab/Webremote/Tools/Storage",["CatLab/Webremote/Tools/Cookies"],function(e){var t={_syncKeys:["users","currentuser"],_syncSink:null,setSyncSink:function(e){this._syncSink="function"==typeof e?e:null},syncToBridge:function(e){-1!==this._syncKeys.indexOf(e)&&this._syncSink&&"undefined"!=typeof window&&void 0!==window.localStorage&&this._syncSink({name:e,rawValue:window.localStorage.getItem(e)})},clean:function(){if(this.isSupported())for(var e=Object.keys(window.localStorage),t=0;t<e.length;t++)this.get(e)},get:function(e,t){if(void 0===t&&(t=function(){}),this.isSupported())try{var n,i=window.localStorage.getItem(e);i?void 0!==(i=JSON.parse(i)).expires?(n=Date.now(),i.expires<n?(this.delete(e),t(null)):t(i.content)):t(i):t(null)}catch(e){t(null),console.log(e)}else t(null)},add:function(t,n,i,o){var r=this;i=i||function(){},this.isSupported()?this.get(t,function(e){(e=null!=e&&""!==e?e:[]).push(n),r.set(t,e,i,o)}):i(null)},set:function(e,t,n,i){if(void 0===n&&(n=function(){}),this.isSupported()){void 0===i&&(i=31536e6);try{var o=Date.now();o+=i,window.localStorage.setItem(e,JSON.stringify({expires:o,content:t}))}catch(e){console.log(e)}this.syncToBridge(e),n()}else n(null)},delete:function(e){this.isSupported()&&(window.localStorage.removeItem(e),this.syncToBridge(e))},remove:function(i,o){var r;this.isSupported()&&(r=this).get(i,function(e){null!=e&&""!=e||(e=[]);for(var t=JSON.stringify(o),n=0;n<e.length;n++)if(t===JSON.stringify(e[n]))return e.splice(n,1),void r.set(i,e)})},upsert:function(i,o,r,s){var a=this;s=s||function(){},this.isSupported()?this.get(i,function(e){null!=e&&""!==e||(e=[]);for(var t=!1,n=0;n<e.length;n++)if(e[n]&&e[n][o]===r[o]){e[n]=r,t=!0;break}t||e.push(r),a.set(i,e,s)}):s(null)},removeBy:function(i,o,r,s){var a=this;s=s||function(){},this.isSupported()?this.get(i,function(e){if(null!=e&&""!==e){for(var t=[],n=0;n<e.length;n++)e[n]&&e[n][o]===r||t.push(e[n]);a.set(i,t,s)}else s()}):s(null)},isSupported:function(){if("undefined"==typeof window)return!1;try{if(void 0===window.localStorage)return!1}catch(e){return console.log(e),!1}return!0}};try{t.clean()}catch(e){console.error(e)}return t}),define("CatLab/Webremote/Collections/AuthenticatedUsers",["CatLab/Webremote/Models/User","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Eventable"],function(n,o,e){var a,l,c=[];function h(e){return 401===e||403===e}function u(e){for(var t=0;t<c.length;t++)if(c[t].getId()==e)return t;return-1}function d(e,t){e=new n(e);return e.setId(t.id),e.setName(t.username),e.setAvatar(t.avatar),e}function t(){this.initializeEventable()}e=t.prototype=new e;return e.initialize=function(e,t){a=t,l=e;var s=this;o.get("users",function(r){r&&o.get("currentuser",function(i){for(var e=!1,t=0;t<r.length;t++){var n,o=r[t];o&&o.access_token&&void 0!==o.username&&-1===u(o.id)&&(n=d(o.access_token,{id:o.id,username:o.username,avatar:o.avatar}),c.push(n),e=!0,i)&&o.access_token===i&&void 0!==l.setUser&&l.setUser(n)}e&&s.trigger("update"),r.forEach(function(e){var n;e&&e.access_token&&(n=e.access_token,a.profile(n,function(e,t){e&&e.user?(e=s.add(n,e.user),i&&n===i&&void 0!==l.setUser&&l.setUser(e)):h(t)&&s.removeByToken(n)}))})})})},e.addFromAccessToken=function(n,i){i=i||function(){};var o=this;a.profile(n,function(e,t){e&&e.user?i(o.add(n,e.user)):(h(t)&&o.removeByToken(n),i(null))})},e.add=function(e,t){var n,i=u(t.id);return-1===i?(n=d(e,t),c.push(n)):((n=c[i]).accessToken=e,n.setName(t.username),n.setAvatar(t.avatar)),o.upsert("users","access_token",{access_token:e,id:t.id,username:t.username,avatar:t.avatar,updated_at:Date.now()}),this.trigger("update"),n},e.removeByToken=function(e){for(var t=0;t<c.length;t++)if(c[t].getAccessToken()===e){c.splice(t,1);break}o.removeBy("users","access_token",e),this.trigger("update")},e.remove=function(e){this.removeByToken(e.getAccessToken())},e.getFromId=function(e){e=u(e);return-1===e?null:c[e]},e.getAll=function(){return c},new t}),define("CatLab/Webremote/Controllers/OAuth2",["CatLab/Webremote/Tools/Tools","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Config"],function(r,s,e,o,t,i){var a,l,c,h,u,d=[],n=[],f=[],p=null;function g(){this.initializeEventable()}e=g.prototype=new e;return e.initialize=function(e){a=(e=e||{}).authorization,l=e.client_id||"none",c=e.authorization||"default",h=e.profile||"",u=e.profile+"/avatar",void 0===e.redirect_uri||i._options.oauth.redirectUrl||(i._options.oauth.redirectUrl=e.redirect_uri);var t=this;if("undefined"!=typeof window){var n,e=function(e){t.onMessage(e)};if(window.addEventListener){for(;n=f.pop();)removeEventListener("message",n);addEventListener("message",e,!1)}else{for(;n=f.pop();)detachEvent("onmessage",n);attachEvent("onmessage",e)}f.push(e)}},e.setRedirectUrl=function(e,t){this.redirectHost=e,this.redirectUrl=e+t},e.getAuthorizeURL=function(){var e="",e=(i.all().oauth&&i.all().oauth.redirectUrl&&(e=i.all().oauth.redirectUrl),a+"?client_id="+encodeURIComponent(l)+"&authorization="+encodeURIComponent(c)+"&response_type=token&redirect_uri="+encodeURIComponent(e)+"&reset=1&state=login");return void 0!==this.redirectUrl?this.redirectUrl+"?url="+encodeURIComponent(e):e},e.onMessage=function(e){if("I must've called a thousand times"!==e.data){var t;if("string"==typeof e.data&&e.data.match(/^oauth::/))try{t=JSON.parse(e.data.substring(7))}catch(e){return}else if("string"==typeof e.data)try{t=JSON.parse(e.data)}catch(e){return}else t=e.data;void 0!==t.access_token&&this.addAccessToken(t.access_token)}},e.addAccessToken=function(i){var e=function(e){if(e&&e.user){var t,n=o.add(i,e.user);for(r.closePopup();t=d.shift();)t(n);this.trigger("update")}}.bind(this);this.call(h,i,e)},e.call=function(e,t,n){var i,e=e+"?access_token="+t;"undefined"!=typeof window&&((i=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP")).onreadystatechange=function(){if(4==i.readyState&&200!=i.status&&n(null,i.status),4==i.readyState&&200==i.status){var e;try{e=JSON.parse(i.responseText)}catch(e){return void n(null,i.status)}n(e)}},i.open("GET",e,!0),i.send())},e.profile=function(e,t){this.call(h,e,t)},e.changeAvatar=function(t,e){var n,i,o;if(t.getAccessToken())return n=new s,(i=new FormData).append("avatar",e.files[0]),(o=new XMLHttpRequest).open("POST",u,!0),o.setRequestHeader("Authorization","Bearer "+t.getAccessToken()),o.onreadystatechange=function(){if(4===o.readyState)if(200<=o.status&&o.status<300)try{var e=JSON.parse(o.responseText);t.setAvatar(e.url),n.resolve(e)}catch(e){n.reject(e)}else n.reject(o.status)},o.send(i),n.promise()},e.link=function(t){var n=new s,e={},e=("object"==typeof(t=void 0===t?{}:t)&&(t=(e=t).callback||function(){}),e.fullscreen||!1),i=(p&&clearInterval(p),this.getAuthorizeURL()),o=r.oauth2Popup(i,e);return o&&(p=setInterval(function(){o&&"function"==typeof o.postMessage?o.postMessage("Hello from the other side","*"):clearInterval(p)}.bind(this),1e3)),d.push(function(e){t(e),n.resolve(e)}),n.promise()},e.onInit=function(e){n.push(e)},e.onAdds=function(){for(var e=0;e<n.length;e++)n[e]()},e.getParamsFromHash=function(e){if("undefined"!=typeof window)return e=(e=e||window.location.hash).slice(1),(e=decodeURIComponent(e)).split("&").reduce(function(e,t){return e[(t=t.split("="))[0]]=t[1],e},{})},e.finish=function(){var e='oauth::{"catlabremote":1,"event":"user:authenticated","access_token":"'+this.getParamsFromHash().access_token+'"}';setTimeout(function(){window.opener&&"function"==typeof window.opener.postMessage&&window.opener.postMessage(e,"*"),window.parent&&"function"==typeof window.parent.postMessage&&window.parent.postMessage(e,"*"),void 0!==window.dialogArguments&&window.dialogArguments.opener&&"function"==typeof window.dialogArguments.opener.postMessage&&window.dialogArguments.opener.postMessage(e,"*"),setTimeout(function(){p&&clearInterval(p),window.close()},1)},1)},new g}),define("CatLab/Webremote/Views/Popups/BasePopup",[],function(){function e(){this.scrollable=!1}var t=e.prototype;return t.render=function(e){this.popupContainer=document.createElement("div"),this.popupContainer.className="catlab-popup-container";var t=document.createElement("div"),t=(t.className="overlay",t.addEventListener("click",function(){this.close()}.bind(this)),this.popupContainer.appendChild(t),this.container=document.createElement("div"),this.container.className="popup",this.popupContainer.appendChild(this.container),this.container.addEventListener("click",function(e){e.stopPropagation()}),this.content=document.createElement("div"),this.container.appendChild(this.content),document.createElement("p")),n=(t.className="close",document.createElement("a"));n.href="javascript:void(0)",n.innerHTML="<span>Close</span>",n.onclick=function(){this.close()}.bind(this),t.appendChild(n),this.container.appendChild(t),e.appendChild(this.popupContainer),this.scrollable&&this.content.classList.add("scrollable"),this.renderContent(this.content)},t.renderContent=function(){},t.close=function(){this.popupContainer.parentNode.removeChild(this.popupContainer)},e}),define("CatLab/Webremote/Views/User",["CatLab/Webremote/Controllers/OAuth2"],function(i){return function(d){this.render=function(e,t,n){t=t||[];var i,o=d.getName(),r=document.createElement("div"),s=(r.className="catlab-user",document.createElement("div")),s=((this.avatardiv=s).className="catlab-avatar",r.appendChild(s),this.renderAvatar(),void 0!==n&&(s.onclick=n),document.createElement("div")),a=(s.className="catlab-info",r.appendChild(s),document.createElement("p"));void 0!==n?((i=document.createElement("a")).innerHTML=o,i.onclick=n,a.appendChild(i)):(a.innerHTML=o,s.appendChild(a)),s.appendChild(a);var l,c,h=document.createElement("ul");h.className="catlab-actions";for(var u=0;u<t.length;u++)(l=document.createElement("li")).className=t[u].token,h.appendChild(l),(c=document.createElement("a")).onclick=t[u].click,c.innerHTML=t[u].text,c.href="javascript:void(0)",l.appendChild(c);s.appendChild(h),e.innerHTML="",e.appendChild(r);n=document.createElement("div");n.className="clearer",r.appendChild(n)},this.renderAvatar=function(){var e=d.getAvatar(),t=document.createElement("img");t.src=e,t.alt="User avatar",this.avatardiv.innerHTML="",this.avatardiv.appendChild(t)},this.enableAvatarUpload=function(t){var n=document.createElement("input");n.type="file",n.accept="image/*",(this.avatarFileInput=n).addEventListener("change",function(){this.avatardiv.classList.add("loading");var e=i.changeAvatar(d,n);e&&e.then&&e.then(function(){this.avatardiv.classList.remove("loading"),this.renderAvatar(),t.setUser(d)}.bind(this))}.bind(this)),this.avatardiv.addEventListener("click",function(){n.click()})},this.uploadAvatar=function(){this.avatarFileInput&&this.avatarFileInput.click()}}}),define("CatLab/Webremote/Views/Popups/AuthenticationPopup",["CatLab/Webremote/Views/Popups/BasePopup","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Views/User","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Tracker"],function(e,l,c,h,t,u){return function(t){function e(){l.link(function(e){o.updateUsers(),o.selectUser(e)})}l.on("update",function(){this.updateUsers()}.bind(this));var o=this,n=document.createElement("div"),i=(n.className="catlab-popup-container",document.createElement("div")),i=(i.className="overlay",n.appendChild(i),document.createElement("div")),r=(i.className="popup",n.appendChild(i),i.innerHTML="<h2>Select account</h2>",document.createElement("ul")),s=(r.className="userlist",i.appendChild(r),document.createElement("div")),s=(s.className="clearer",i.appendChild(s),document.createElement("p")),a=(s.className="connect",document.createElement("a")),s=(a.href="javascript:void(0)",a.innerHTML='<span class="new-user">Connect new user</span>',a.onclick=function(){e()},s.appendChild(a),i.appendChild(a),document.createElement("p")),a=(s.className="close",document.createElement("a"));a.href="javascript:void(0)",a.innerHTML="<span>Close</span>",a.onclick=function(){o.close()},s.appendChild(a),i.appendChild(s),this.selectUser=function(e){t.setUser(e),o.close(),u.track("Click","Select user","AuthenticationPopup")},this.updateUsers=function(){r.innerHTML="";for(var e=c.getAll(),t=0;t<e.length;t++)((e,t)=>{var n=document.createElement("li"),i=[{token:"select",text:"select",click:function(){o.selectUser(t)}},{token:"logout",text:"logout",click:function(){c.remove(t),o.updateUsers(),u.track("Click","Logout","AuthenticationPopup")}}];new h(t).render(n,i,function(){o.selectUser(t)}),e.appendChild(n)})(r,e[t])},this.close=function(){n.parentNode.removeChild(n),u.track("Click","Close popup","AuthenticationPopup")},this.connect=function(){u.track("Click","Connect new","AuthenticationPopup"),e()},this.render=function(e){e.appendChild(n),this.updateUsers()},this.setLoginUrl=function(e){}}}),define("CatLab/Webremote/Views/Popups/SelectSmileyPopup",["CatLab/Webremote/Views/Popups/BasePopup"],function(e){function t(e,t,n){this.Webremote=e,this.callback=t,this.scrollable=!0,this.disableTaken=n}e=t.prototype=new e;return e.renderContent=function(e){e.classList.add("smileys-popup");var t=document.createElement("ul"),n=(t.className="smileys",e.appendChild(t),this.Webremote.smileys.smileyKeys.slice());this.Webremote.getUser()&&this.Webremote.getUser().getAvatar()&&(o=this.Webremote.getUser().getAvatarSmiley(this.Webremote.color))&&n.unshift(o);for(var i=0;i<n.length;i++)this.renderSmiley(t,n[i]);var o=document.createElement("div");o.className="clearer",e.appendChild(o)},e.renderSmiley=function(n,i){var o=document.createElement("li"),r=(o.appendChild(this.Webremote.smileys.getElement(i)),!this.disableTaken||this.Webremote.smileys.isAvailable(i));r||o.classList.add("unavailable"),this.Webremote.getSmiley()===i&&o.classList.add("selected"),o.addEventListener("click",function(){if(r){this.selectSmiley(i);for(var e=n.querySelectorAll(".selected"),t=0;t<e.length;t++)e[t].classList.remove("selected");o.classList.add("selected"),this.close()}}.bind(this)),n.appendChild(o)},e.selectSmiley=function(e){this.callback(e)},t}),define("CatLab/Webremote/Views/Blocks/CurrentUser",["CatLab/Webremote/Views/User","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Tracker"],function(r,s,e,a){return function(o){this.render=function(e){var t,n,i;e.innerHTML="",o.canAuthenticate()&&(i=o.getUser(),(t=document.createElement("div")).className="overlay player-color-background",e.appendChild(t),(t=document.createElement("div")).className="content",t.className+=" player-color-border",e.appendChild(t),i?(e=[{token:"switch",text:"Switch account",click:function(){o.showAuthenticationPopup(),a.track("Click","Switch account","CurrentUser")}},{token:"upload",text:"Upload photo",click:function(){n.uploadAvatar()}},{token:"logout",text:"Logout",click:function(){var e=o.getUser();s.remove(e),o.setUser(null),a.track("Click","Logout","CurrentUser")}}],(n=new r(i)).render(t,e),n.enableAvatarUpload(o)):((i=document.createElement("p")).className="catlab-not-loggedin",(e=document.createElement("a")).href="javascript:void(0);",e.innerHTML="Login",e.onclick=function(){o.showAuthenticationPopup(0===s.getAll().length),a.track("Click","Login","CurrentUser")},i.appendChild(e),t.appendChild(i)))}}}),(()=>{var p={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function g(e){for(var t,n,i,o,r,s,a,l=(e=>{if(m[e])return m[e];for(var t,n=e,i=[],o=0;n;){if(null!==(t=p.text.exec(n)))i.push(t[0]);else if(null!==(t=p.modulo.exec(n)))i.push("%");else{if(null===(t=p.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){o|=1;var r=[],s=t[2],a=[];if(null===(a=p.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(r.push(a[1]);""!==(s=s.substring(a[0].length));){if(null===(a=p.key_access.exec(s))&&null===(a=p.index_access.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");r.push(a[1])}t[2]=r}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");i.push({placeholder:t[0],param_no:t[1],keys:t[2],sign:t[3],pad_char:t[4],align:t[5],width:t[6],precision:t[7],type:t[8]})}n=n.substring(t[0].length)}return m[e]=i})(e),c=arguments,h=1,u=l.length,d="",f=0;f<u;f++)if("string"==typeof l[f])d+=l[f];else if("object"==typeof l[f]){if((i=l[f]).keys)for(t=c[h],n=0;n<i.keys.length;n++){if(null==t)throw new Error(g('[sprintf] Cannot access property "%s" of undefined value "%s"',i.keys[n],i.keys[n-1]));t=t[i.keys[n]]}else t=i.param_no?c[i.param_no]:c[h++];if(p.not_type.test(i.type)&&p.not_primitive.test(i.type)&&t instanceof Function&&(t=t()),p.numeric_arg.test(i.type)&&"number"!=typeof t&&isNaN(t))throw new TypeError(g("[sprintf] expecting number but found %T",t));switch(p.number.test(i.type)&&(s=0<=t),i.type){case"b":t=parseInt(t,10).toString(2);break;case"c":t=String.fromCharCode(parseInt(t,10));break;case"d":case"i":t=parseInt(t,10);break;case"j":t=JSON.stringify(t,null,i.width?parseInt(i.width):0);break;case"e":t=i.precision?parseFloat(t).toExponential(i.precision):parseFloat(t).toExponential();break;case"f":t=i.precision?parseFloat(t).toFixed(i.precision):parseFloat(t);break;case"g":t=i.precision?String(Number(t.toPrecision(i.precision))):parseFloat(t);break;case"o":t=(parseInt(t,10)>>>0).toString(8);break;case"s":t=String(t),t=i.precision?t.substring(0,i.precision):t;break;case"t":t=String(!!t),t=i.precision?t.substring(0,i.precision):t;break;case"T":t=Object.prototype.toString.call(t).slice(8,-1).toLowerCase(),t=i.precision?t.substring(0,i.precision):t;break;case"u":t=parseInt(t,10)>>>0;break;case"v":t=t.valueOf(),t=i.precision?t.substring(0,i.precision):t;break;case"x":t=(parseInt(t,10)>>>0).toString(16);break;case"X":t=(parseInt(t,10)>>>0).toString(16).toUpperCase()}p.json.test(i.type)?d+=t:(!p.number.test(i.type)||s&&!i.sign?a="":(a=s?"+":"-",t=t.toString().replace(p.sign,"")),o=i.pad_char?"0"===i.pad_char?"0":i.pad_char.charAt(1):" ",r=i.width-(a+t).length,r=i.width&&0<r?o.repeat(r):"",d+=i.align?a+t+r:"0"===o?a+r+t:r+a+t)}return d}function e(e,t){return g.apply(null,[e].concat(t||[]))}var m=Object.create(null);"undefined"!=typeof exports&&(exports.sprintf=g,exports.vsprintf=e),"undefined"!=typeof window&&(window.sprintf=g,window.vsprintf=e,"function"==typeof define)&&define.amd&&define("sprintf",[],function(){return{sprintf:g,vsprintf:e}})})(),define("CatLab/Webremote/Tools/Translator",["sprintf"],function(t){function e(){this.translator=null}var n,i,o=e.prototype;return o.setTranslator=function(e){this.translatorScope=this,"function"==typeof e?this.translator=e:("function"==typeof e.t?this.translator=e.t:(e._,this.translator=e._),this.translatorScope=e)},o.t=function(e){if(""===e)return"";if(Array.isArray(e))return this.t.apply(this,e);if(this.translator)return this.translator.apply(this.translatorScope,arguments);for(n=[],i=1;i<arguments.length;i++)n.push(arguments[i]);return t.vsprintf(e,n)},new e}),define("CatLab/Webremote/Views/Blocks/CurrentSmiley",["CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Deferred"],function(n,e){function i(e,t,n,i){this.Webremote=e,this.canSwitch=void 0!==t&&!!t,this.canDrag=void 0!==n&&!!n,this.isProfileSmiley=void 0===i||!!i,this.dragDisabled=!1,this.switchVerb="Switch"}i.initialize=function(){return i.isInitialized||(i.isInitialized=new e).resolve(),i.isInitialized.promise()}.bind(this),i.activeSmileys=["1f601","1f60d","1f60e"];var t=i.prototype;return t._makeDraggable=function(i,o){var r=this,s=null,a=null,l=!1,c=!1,h=0,u=0,d=0,f=0,p=0,g=0;function e(e){var t,n;r.dragDisabled||(l=!0,i.style.cursor="grabbing",n=(void 0!==e.clientX?e:e.touches[0]).clientX,t=(void 0!==e.clientY?e:e.touches[0]).clientY,h=n,u=t,s={left:d=p,top:f=g},n=i.getBoundingClientRect(),a={left:n.left+window.pageXOffset,top:n.top+window.pageYOffset},r.disableDrag(),i.classList.add("flinging"),e.preventDefault())}function t(e){var t,n;l&&(t=(void 0!==e.clientX?e:e.touches[0]).clientX,n=(void 0!==e.clientY?e:e.touches[0]).clientY,p=d+(t-h),g=f+(n-u),i.style.left=p+"px",i.style.top=g+"px",e.preventDefault())}function n(e){var t,n;l&&(l=!1,n={left:p,top:g},10<(t=r.getDistance(s,n))?(c=!0,n=r.getAngle(s,n),r.slingshot(a,n,t,i,o,function(){g=p=0,i.style.cursor="grab"})):(i.style.left="0px",i.style.top="0px",g=p=0,i.style.cursor="grab",r.enableDrag(),i.classList.remove("flinging")),e.preventDefault())}i.style.zIndex="10",i.style.position="relative",i.style.touchAction="none",i.style.cursor="grab",i.addEventListener("mousedown",e),i.addEventListener("touchstart",e,{passive:!1}),document.addEventListener("mousemove",t),document.addEventListener("touchmove",t,{passive:!1}),document.addEventListener("mouseup",n),document.addEventListener("touchend",n),document.addEventListener("touchcancel",function(){l&&(l=!1,i.style.left="0px",i.style.top="0px",g=p=0,i.style.cursor="grab",r.enableDrag(),i.classList.remove("flinging"))}),i.addEventListener("click",function(e){c&&(c=!1,e.stopPropagation(),e.preventDefault())},!0)},t._animateElement=function(s,a,l,c){for(var h={},u=Object.keys(a),e=0;e<u.length;e++){var t=u[e];h[t]=parseFloat(s.style[t])||0}var d=null;requestAnimationFrame(function e(t){d=d||t;for(var t=Math.min((t-d)/l,1),n=.5-Math.cos(t*Math.PI)/2,i=0;i<u.length;i++){var o=u[i],r=h[o]+(a[o]-h[o])*n;s.style[o]=r+("opacity"===o?"":"px")}t<1?requestAnimationFrame(e):c&&c()})},t.setSmiley=function(t){Array.isArray(t)||(t=[t]),this.smileys=t,i.initialize().then(function(){var e;this.selector&&(this.selector.innerHTML="",t.forEach(function(e){var t=this.Webremote.smileys.getElement(e);if(this.selector.appendChild(t),this.canDrag)try{this._makeDraggable(t,e)}catch(e){console.log(e)}}.bind(this)),this.canSwitch)&&((e=document.createElement("p")).className="switch",e.innerHTML='<a href="javascript:void(0)">'+n.t(this.switchVerb)+"</a>",this.selector.appendChild(e))}.bind(this))},t.disableDrag=function(){this.dragDisabled=!0,this.selector&&this.selector.classList.add("drag-disabled")},t.enableDrag=function(){this.dragDisabled=!1,this.selector&&this.selector.classList.remove("drag-disabled")},t.getMaxDistance=function(){var e;return this.selector?(e=this.selector.getBoundingClientRect(),window.innerHeight-e.top):200},t.getDistance=function(e,t){var n=e.left-t.left,e=e.top-t.top;return Math.sqrt(n*n+e*e)},t.getAngle=function(e,t){return Math.atan2(t.top-e.top,t.left-e.top)},t.slingshot=function(e,t,n,i,o,r){var s=Math.min(1,n/this.getMaxDistance());0<Math.sin(t-Math.PI)?this._animateElement(i,{left:0,top:0},1e3,function(){r&&r(),this.enableDrag(),i.classList.remove("flinging")}.bind(this)):(n=1.5*Math.max(e.left,e.top),this._animateElement(i,{left:Math.cos(t-Math.PI)*n,top:Math.sin(t-Math.PI)*n},1e3,function(){setTimeout(function(){i.style.left=-1*parseFloat(i.style.left)+"px",this._animateElement(i,{left:0,top:0},1e3,function(){r&&r(),this.enableDrag(),i.classList.remove("flinging")}.bind(this))}.bind(this),3e3*s)}.bind(this)),setTimeout(function(){this.Webremote.emit("smileys:slingshot",{angle:t,speed:s,smiley:o})}.bind(this),800))},t.render=function(e){i.initialize().then(function(){this.container=e,this.canSwitch||this.canDrag?(this.selector=document.createElement("div"),this.selector.className="smiley-selector"):(this.selector=document.createElement("div"),this.selector.className="smiley-view"),this.selector.innerHTML='<div class="placeholder"></div>',this.container.innerHTML="",this.container.appendChild(this.selector),this.canSwitch&&(this.container.addEventListener("click",function(){this._suppressClick?this._suppressClick=!1:this.isProfileSmiley?this.Webremote.showSmileyPopup():this.Webremote.showSmileyPopup(function(e){if(-1===i.activeSmileys.indexOf(e)){for(;2<i.activeSmileys.length;)i.activeSmileys.shift();i.activeSmileys.push(e),this.setSmiley(i.activeSmileys)}}.bind(this),!1)}.bind(this)),this.isProfileSmiley||this.setSmiley(i.activeSmileys))}.bind(this))},i}),define("CatLab/Webremote/Tools/HashParser",[],function(){return{getParameters:function(){for(var e,t={},n=/\+/g,i=/([^&;=]+)=?([^&;]*)/g,o=function(e){return decodeURIComponent(e.replace(n," "))},r=window.location.hash.substring(1);e=i.exec(r);)t[o(e[1])]=o(e[2]);return t},getParameter:function(e){var t=this.getParameters();return void 0!==t[e]?t[e]:null},clear:function(){history.pushState("",document.title,window.location.pathname+window.location.search)}}}),define("CatLab/Webremote/Tools/Screenfull",[],function(){var s="undefined"!=typeof window&&void 0!==window.document?window.document:{},a=(()=>{for(var e,t=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]],n=0,i=t.length,o={};n<i;n++)if((e=t[n])&&e[1]in s){for(n=0;n<e.length;n++)o[t[0][n]]=e[n];return o}return!1})(),n={change:a.fullscreenchange,error:a.fullscreenerror},e={request:function(o,r){return new Promise(function(e,t){var n=function(){this.off("change",n),e()}.bind(this),i=(this.on("change",n),(o=o||s.documentElement)[a.requestFullscreen](r));i instanceof Promise&&i.then(n).catch(t)}.bind(this))},exit:function(){return new Promise(function(e,t){var n,i;this.isFullscreen?(n=function(){this.off("change",n),e()}.bind(this),this.on("change",n),(i=s[a.exitFullscreen]())instanceof Promise&&i.then(n).catch(t)):e()}.bind(this))},toggle:function(e,t){return this.isFullscreen?this.exit():this.request(e,t)},onchange:function(e){this.on("change",e)},onerror:function(e){this.on("error",e)},on:function(e,t){e=n[e];e&&s.addEventListener(e,t,!1)},off:function(e,t){e=n[e];e&&s.removeEventListener(e,t,!1)},raw:a};return Object.defineProperties(e,{isFullscreen:{get:function(){return Boolean(s[a.fullscreenElement])}},element:{enumerable:!0,get:function(){return s[a.fullscreenElement]}},isEnabled:{enumerable:!0,get:function(){return Boolean(s[a.fullscreenEnabled])}}}),e}),define("CatLab/Webremote/Views/Alert",[],function(){return function(e,t){t=t||function(){},alert(e),t()}}),define("CatLab/Webremote/Views/Welcome",["CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Views/User","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Tracker"],function(e,t,n,r){return function(e){var t=this,n=document.createElement("div"),i=(n.className="catlab-popup-container",document.createElement("div")),i=(i.className="overlay",n.appendChild(i),document.createElement("div")),e=(i.className="popup thanks",n.appendChild(i),i.innerHTML=e,document.createElement("a")),o=(e.innerHTML="Start playing",e.onclick=function(){t.close()},e.href="javascript:void(0)",document.createElement("p"));o.appendChild(e),o.className="playnow",i.appendChild(o),this.close=function(){n.parentNode.removeChild(n),r.track("Click","Close popup","WelcomePopup")},this.render=function(e){e.appendChild(n)}}}),define("CatLab/Webremote/Views/ConnectionTrouble",["CatLab/Webremote/Tools/Translator"],function(e){function t(){this.visible=!1,this.div=null,this.timeoutTillShow=3e3,this.showTimeout=null,this.message=null}var n=t.prototype;return n.show=function(){this.visible||(this.visible=!0,this.div)||(this.showTimeout&&(clearTimeout(this.showTimeout),this.showTimeout=null),setTimeout(function(){this.div||this.visible&&(this.showTimeout=null,this.div=document.createElement("div"),document.body.appendChild(this.div),this.div.style.position="absolute",this.div.style.right="10px",this.div.style.top="10px",this.div.style.width="350px",this.div.style.padding="10px",this.div.style.border="1px solid red",this.div.style.background="black",this.div.style.zIndex="100000",this.div.style.textAlign="center",this.div.style.color="white",this.div.style.font="Sans-serif",this.div.style.fontSize="15px",this.message?this.text(this.message):this.text(e.t("Connection lost")))}.bind(this),this.timeoutTillShow))},n.text=function(e){this.message=e,this.div&&(this.div.innerHTML="<p>"+e+"</p>")},n.hide=function(){this.visible=!1,this.div&&this.div.parentNode&&this.div.parentNode.removeChild(this.div),this.showTimeout&&clearTimeout(this.showTimeout),this.message=null,this.div=null,this.showTimeout=null},t}),define("CatLab/Webremote/Views/GamePaused",["CatLab/Webremote/Tools/Translator"],function(e){function t(){this.visible=!1,this.div=null,this.timeoutTillShow=1,this.showTimeout=null,this.message=null}var n=t.prototype;return n.show=function(){this.visible||(this.visible=!0,this.div)||(this.showTimeout&&(clearTimeout(this.showTimeout),this.showTimeout=null),setTimeout(function(){this.div||this.visible&&(this.showTimeout=null,this.div=document.createElement("div"),document.body.appendChild(this.div),this.div.style.position="fixed",this.div.style.right="0",this.div.style.top="0",this.div.style.width="100%",this.div.style.height="100%",this.div.style.padding="0",this.div.style.background="black",this.div.style.zIndex="100000",this.div.style.textAlign="center",this.div.style.color="white",this.div.style.font="Sans-serif",this.div.style.fontSize="2em",this.div.style.opacity=.9,this.message?this.text(this.message):this.text(e.t("Please wait, the game is paused.")))}.bind(this),this.timeoutTillShow))},n.text=function(e){this.message=e,this.div&&(this.div.innerHTML='<p style="height: 100%; padding: 20% 0">'+e+"</p>")},n.hide=function(){this.visible=!1,this.div&&this.div.parentNode.removeChild(this.div),this.showTimeout&&clearTimeout(this.showTimeout),this.message=null,this.div=null,this.showTimeout=null},t}),define("CatLab/Webremote/Synchronization/ClientRemoteView",[],function(){function e(e,t,n,i,o,r){this.controller=e,this.html="<p>Loading</p>",this.context={},this.viewId=t,this.name=n,this.groupId=void 0!==i?i:null,this.synchronizedData=o,this.createdAt=new Date,this.iframe=r,this.currentValues=[],this.buttons=[]}var o={},t=e.prototype;return t.render=function(e){var t;this.iframe?((t=document.createElement("iframe")).style.width="100%",t.style.height="100%",t.style.border="none",t.style.margin="0",t.style.padding="0",t.style.position="absolute",t.style.left="0",t.style.top="0",e.innerHTML="",e.appendChild(t),this.element=t.contentDocument.body):this.element=e,this.el=e,this.$el=e,this.element.innerHTML=this.html,this.update(),this.controller.components.attach(this,document.body),this.updateEvents(),setTimeout(function(){this.updateEvents(),window.scrollTo(0,1)}.bind(this),10),setTimeout(function(){this.updateEvents()}.bind(this),100),setTimeout(function(){this.updateEvents()}.bind(this),1e3)},t.updateEvents=function(){var h=this;function e(i,t,o){var r,s,a,l,c;h.shouldSetEvents(i,"touch")&&(l=!1,c=null,i.addEventListener("touchstart",function(e){return r=new Date,s={x:e.touches[0].pageX,y:e.touches[0].pageY},a={x:e.touches[0].pageX,y:e.touches[0].pageY},l=!0,c&&clearTimeout(c),t.apply(h,[i])}),i.addEventListener("touchmove",function(e){a={x:e.touches[0].pageX,y:e.touches[0].pageY}}),i.addEventListener("touchend",function(e){var t,n;if(s)return n=Math.abs(a.x-s.x),t=Math.abs(a.y-s.y),s=null,n=(new Date).getTime()-r.getTime()<300&&n<20&&t<20,c=setTimeout(function(){l=!1},1e3),o.apply(h,[i,n])}),i.addEventListener("mousedown",function(e){if(e.preventDefault(),!l)return t.apply(h,[i])}),i.addEventListener("mouseup",function(e){if(e.preventDefault(),!l)return o.apply(h,[i,!0])}))}for(var t=this.element.querySelectorAll("[data-button-id]"),n=0;n<t.length;n++)e(t[n],h.buttonDown,h.buttonUp),this.buttons.push(t[n]);for(t=this.element.querySelectorAll("[data-authentication-button]"),n=0;n<t.length;n++)e(t[n],function(){},h.authenticate);for(t=this.element.querySelectorAll("[data-value-id]"),n=0;n<t.length;n++)(t=>{var n,e;h.shouldSetEvents(t,"change")&&(n=t.getAttribute("data-value-id"),h.currentValues[n]=h.getDataValue(t),t.addEventListener("change",function(e){o[n]=new Date,h.syncValue(t)}),e=null,t.addEventListener("keyup",function(){e&&clearTimeout(e),e=setTimeout(function(){o[n]=new Date,h.syncValue(t)},1e3)}))})(t[n])},t.getDataValue=function(e){return"checkbox"===e.type?e.checked?1:0:e.value},t.syncValues=function(){for(var e=this.element.querySelectorAll("[data-value-id]"),t=0;t<e.length;t++)this.syncValue(e[t])},t.syncValue=function(e){var t=this.getDataValue(e),n=e.getAttribute("data-value-id");void 0!==this.currentValues[n]&&this.currentValues[n]===t||(this.currentValues[n]=t,this.controller.syncValue(n,this.getDataValue(e),this.viewId))},t.update=function(){for(var e=this.element.querySelectorAll("[data-button-decorator]"),t=0;t<e.length;t++)void 0===e[t].dataset.initialClasses&&(e[t].dataset.initialClasses=e[t].className);this.updateBigTextSizes()},t.updateBigTextSizes=function(){for(var e=this.element,t=e.querySelectorAll(".bigtext"),n={},i=0;i<t.length;i++){var o,r=t[i],s=r.getAttribute("data-bigtext-group");if(s){if(void 0===n[s]){n[s]=0;for(var a=e.querySelectorAll('.bigtext[data-bigtext-group="'+s+'"]'),l=0;l<a.length;l++)n[s]=Math.max(n[s],a[l].textContent.length)}o=n[s]}else o=r.textContent.length;r.setAttribute("data-bigtext-length",o)}},t.shouldSetEvents=function(e,t){return void 0===e["hasCatlabEventsAlready"+t]&&(e["hasCatlabEventsAlready"+t]=!0)},t.buttonDown=function(e){try{this.syncValues()}catch(e){console.error(e)}return this.controller.buttonDown(e.getAttribute("data-button-id"),this.viewId),!1},t.buttonUp=function(e,t){return this.controller.buttonUp(e.getAttribute("data-button-id"),this.viewId,t),!1},t.setLabel=function(e,t){for(var n=this.element.querySelectorAll("[data-button-label="+e+"]"),i=0;i<n.length;i++)n[i].innerHTML=t;this.update()},t.setClass=function(e,t){for(var n=this.element.querySelectorAll("[data-button-decorator="+e+"]"),i=0;i<n.length;i++){var o=n[i];o.className=o.dataset.initialClasses+" "+t}this.update()},t.domAppend=function(e,t){var n=document.getElementById(e);if(n){for(var i=this.stringToDom(t),o=[];i.firstChild;)o.push(n.appendChild(i.firstChild));try{for(var r=0;r<o.length;r++)this.controller.components.attach(this._currentView,o[r],!1)}catch(e){console.log(e)}5e3<(new Date).getTime()-this.createdAt.getTime()&&0<o.length&&void 0!==o[0].scrollIntoView&&o[0].scrollIntoView(),this.update(),this.updateEvents()}},t.domReplace=function(e,t){e=document.getElementById(e);e&&(e.innerHTML=t,this.controller.components.attach(this._currentView,e,!1),this.update(),this.updateEvents())},t.domAttribute=function(e,t,n){for(var i=document.querySelectorAll(e),o=0;o<i.length;o++)i[o].setAttribute(t,n)},t.changeValue=function(e){if(void 0!==o[e.id]){if((t=Math.abs(o[e.id].getTime()-(new Date).getTime()))<5)return}else var t=9999999999999;for(var n=this.element.querySelectorAll("[data-value-id="+e.id+"]"),i=0;i<n.length;i++)document.activeElement==n[i]&&t<5e3||(this.currentValues[e.id]=e.value,n[i].value=e.value)},t.vibrate=function(e){void 0!==window.navigator.vibrate&&void 0!==e.pattern&&Array.isArray(e.pattern)&&window.navigator.vibrate(e.pattern)},t.stringToDom=function(e){var t;return(t=0<=e.toLowerCase().indexOf("<tr")?document.createElement("tbody"):document.createElement("div")).innerHTML=e,t},t.stringInterpolateDataElements=function(e,o){return e.replace(/{{(.+?)}}/g,function(e,t,n,i){t=this.controller.resolveDataAttribute(t.trim());return t=o?o(t):t}.bind(this))},t.destroy=function(){this.syncValues(),void 0!==this.synchronizedData&&this.synchronizedData.destroy()},e}),define("CatLab/Webremote/Synchronization/DataItem",[],function(){function n(e,t,n){this.key=e,this.shared=t,this.side=n}var e=n.prototype;return e.setValue=function(e){this.value=e},e.canWrite=function(e){return!!this.shared||this.side===e},e.serialize=function(){return{key:this.key,shared:this.shared,side:this.side,value:this.value}},n.unserialize=function(e){var t=new n(e.key,e.shared,e.side);return t.setValue(e.value),t},n}),define("CatLab/Webremote/Synchronization/SynchronizedData",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Synchronization/DataItem"],function(e,o){function t(e,t,n){this.initializeEventable(),this.id=e,this.synchronizer=t,this.side=n,this.data={}}e=t.prototype=new e;return e.set=function(e,t,n){if(void 0===this.data[e])this.data[e]=new o(e,n,this.side);else if(!this.data[e].canWrite(this.side))throw"Trying to overwrite a non shared data attribute: "+e;this.data[e].setValue(t),this.emit(this.data[e])},e.processMessage=function(e){var t=e.key,n=e.side,i=e.value;if(void 0===this.data[t])this.data[t]=new o(t,e.shared,n);else if(!this.data[t].canWrite(n))throw"Trying to overwrite a non shared data attribute: "+t;this.data[t].setValue(i)},e.get=function(e){return void 0===this.data[e]?null:this.data[e].value},e.emit=function(e,t){void 0===t&&(t=this.synchronizer.emit);e=e.serialize();e.namespace=this.synchronizer.namespace,e.container=this.id,t("data:set",e)},e.refreshTarget=function(e){for(var t in this.data)this.data.hasOwnProperty(t)&&this.emit(this.data[t],e)},e.destroy=function(){this.synchronizer.destroy(this)},e.serialize=function(){var e,t={};for(e in this.data)this.data.hasOwnProperty(e)&&(t[e]=this.data[e].serialize());return t},e.unserialize=function(e){for(var t in this.data={},e)e.hasOwnProperty(t)&&(this.data[t]=o.unserialize(e[t]))},t}),define("CatLab/Webremote/Synchronization/DataSynchronizer",["CatLab/Webremote/Synchronization/SynchronizedData"],function(t){function e(e,t,n){this.namespace=e,this.emit=t,this.dataModels={},this.side=n}e.eventsToListenFor=["data:set"];var n=e.prototype;return n.checkNamespace=function(e){return void 0!==e.namespace&&e.namespace===this.namespace},n.processMessage=function(e,t){void 0!==t.container&&this.getFromIdentifier(t.container).processMessage(t)},n.getFromIdentifier=function(e){return void 0===this.dataModels[e]&&(this.dataModels[e]=new t(e,this,this.side)),this.dataModels[e]},n.destroy=function(e){e=e.id;void 0===this.dataModels[e]&&delete this.dataModels[e]},n.refreshTarget=function(e){for(var t in this.dataModels)this.dataModels.hasOwnProperty(t)&&this.dataModels[t].refreshTarget(e)},n.serialize=function(){var e,t={};for(e in this.dataModels)this.dataModels.hasOwnProperty(e)&&(t[e]=this.dataModels[e].serialize());return{dataModels:t}},n.unserialize=function(e){for(var t in e.dataModels)e.dataModels.hasOwnProperty(t)&&this.getFromIdentifier(t).unserialize(e.dataModels[t])},e}),define("CatLab/Webremote/Synchronization/EventHandler",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e,t){this.initializeEventable(),this.namespace=e,this.emit=t}t.eventsToListenFor=["event:trigger"];e=t.prototype=new e;return e.checkNamespace=function(e){return void 0!==e.namespace&&e.namespace===this.namespace},e.processMessage=function(e,t){if("event:trigger"===e)return this.processTriggerEvent(t)},e.processTriggerEvent=function(e){void 0!==e.event&&this.eventableTrigger(e.event,void 0===e.parameters?{}:e.parameters)},e.trigger=function(e,t){this.emit("event:trigger",{namespace:this.namespace,event:e,parameters:t})},e.refreshTarget=function(e){},e.serialize=function(){return{}},e.unserialize=function(e){},t}),define("CatLab/Webremote/Synchronization/CombinedEventHandler",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e,t){this.initializeEventable(),this.handlers=[]}return(t.prototype=new e).addHandler=function(e){this.handlers.push(e),e.on("*",function(e,t){this.trigger(t,e)}.bind(this))},t}),define("CatLab/Webremote/Synchronization/MessageQueue",[],function(){function e(){this.queue=[]}var t=e.prototype;return t.add=function(e,t,n){this.queue.push({action:e,data:t,ack:n})},t.flush=function(){var e=this.queue;return this.queue=[],e},t.compactFlush=function(){var i,o,r,s,a=[],e=this.flush();return 0===e.length?e:(o={user:{},group:{}},r=0,s={},e.forEach(function(e){if(r++,this.canCompact(e)){var t=null;void 0!==e.data.user?t="user":void 0!==e.data.group&&(t="group"),void 0===o[t][e.action]&&(o[t][e.action]=[]);for(var n=0;n<o[t][e.action].length;n++)if(i=o[t][e.action][n],this.isSimilarMessage(i.event,e)&&(void 0===s[e.data[t]]||s[e.data[t]]<i.index))return s[e.data[t]]=i.index,i.event.data[t].push(e.data[t]),void i.event.data._d.push(this.getDifference(i.event,e));Array.isArray(e.data[t])||(e.data[t]=[e.data[t]]),e.data._d=[{}],s[e.data[t]]=r,o[t][e.action].push({event:e,index:r})}a.push(e)}.bind(this)),a)},t.moveToEnd=function(e,t){e.push(e.splice(e.indexOf(t),1)[0])},t.isSimilarMessage=function(e,t){return e.action===t.action&&this.getCompareDataString(e)===this.getCompareDataString(t)},t.getDifference=function(e,t){var n,i={};for(n in t.data)if(t.data.hasOwnProperty(n)){switch(n){case"user":case"group":case"_d":case"_i":continue}void 0!==e.data[n]&&e.data[n]===t.data[n]||(i[n]=t.data[n])}return i},t.getCompareDataString=function(e){e=Object.assign({},e.data);return delete e.user,delete e.group,delete e.viewId,delete e._d,delete e._i,JSON.stringify(e)},t.canCompact=function(e){return null==e.ack&&void 0!==e.data&&(void 0!==e.data.user||void 0!==e.data.group)},e.unpack=function(e,t){if(void 0===e[t])return[e];var n=Array.isArray(e[t])?e[t]:[e[t]],i=[];void 0!==e._d&&(i=Array.isArray(e._d)?e._d:[e._d]);for(var o=[],r=0;r<n.length;r++){(s={})[t]=n[r];var s=Object.assign({},e,s,void 0!==i[r]?i[r]:{});delete s._d,o.push(s)}return o},Object.defineProperty(t,"length",{get:function(){return this.queue.length}}),e}),define("CatLab/Webremote/Tools/Proxy",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred"],function(n,i){function e(){}function o(e,t,n){var i=(()=>{for(var e=!1,t=0;t<r.length;t++){try{e=r[t]()}catch(e){continue}break}return e})();i&&(i.open(n?"POST":"GET",e,!0),n&&i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=function(){4==i.readyState&&(200==i.status||304==i.status?t(i):console.error("CatLab Remote HTTP error "+i.status))},4!=i.readyState)&&i.send(n)}var r=[function(){return new XMLHttpRequest},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml3.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")}];return e.prototype.get=function(e){n.getProxy()&&(e=n.getProxy()+encodeURIComponent(e));var t=new i;return o(e,function(e){t.resolve(e.responseText)}),t.promise()},new e}),define("CatLab/Webremote/Providers/Provider",["CatLab/Webremote/Synchronization/MessageQueue","CatLab/Webremote/Tools/Proxy","CatLab/Webremote/Tools/Deferred"],function(e,o,r){function t(){this.initializeProvider()}var n=t.prototype;return n.initializeProvider=function(){this.queue=new e,this.postInitializeQueue=[],this.scheduled=!1,this.initialized=!1,this.sendBurstDelay=10,this.maxQueueSize=2500,this.messageCounter=null,this.events={},this.viewNameIdentifierMap={}},n.getProviderSettings=function(){var e=new r;return e.resolve({}),e.promise()},n.setMessageCounter=function(e){this.messageCounter=e},n.initMaster=function(e){this.master=e},n.initPlayer=function(e){this.master=e},n.connect=function(){var e=new r;return e.resolve(),e.promise()},n.disconnect=function(){this.off()},n.setOAuthSettings=function(e){this.emit("oauth:set",e)},n.canProviderLoadExternalXml=function(){return!1},n.canProxyFiles=function(){return!1},n.loadViews=function(t,e,n){var i=new r;return void 0===e&&(e=!1),void 0===n&&(n=this),this.canProviderLoadExternalXml()&&!e?n.emit("view:load",{url:t},function(){i.resolve()}):o.get(t).then(function(e){this.parseViews(e,t,n).then(function(){i.resolve()})}.bind(this)),i.promise()},n.parseViews=function(e,t,n){var i=new r,o=void 0!==t;return void 0===n&&(n=this),o&&void 0!==this.viewNameIdentifierMap[t]?n.emit("view:load",{identifier:this.viewNameIdentifierMap[t]},function(){i.resolve()}):(n.emit("view:load",{xml:e},function(e){o&&e&&e.identifier&&(this.viewNameIdentifierMap[t]=e.identifier),i.resolve()}.bind(this)),this.onParseViews(e)),i.promise()},n.onParseViews=function(e){},n.registerComponent=function(e,t,n){t="string"==typeof t?t:t&&void 0!==t.innerHTML?t.innerHTML:String(t),e='<views><component id="'+e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")+'" xmlns="http://www.w3.org/1999/xhtml">'+t+"</component></views>";return this.parseViews(e,void 0,n)},n.toMaster=function(e,t,n){this.emit(e,t,n)},n.toPlayers=function(e,t,n){this.emit(e,t,n)},n.toPlayer=function(e,t,n,i){n.user=e.getId(),this.emit(t,n,i)},n.toGroup=function(e,t,n,i){n.group=e.getId(),this.emit(t,n,i)},n.emit=function(e,t,n){this.initialized?this.queue?(this.queue.add(e,t,n),this.queue.length>this.maxQueueSize?(clearTimeout(this.scheduled),this.scheduled=null,this.executeQueue()):this.scheduled||(this.scheduled=setTimeout(function(){this.scheduled=null,this.executeQueue()}.bind(this),this.sendBurstDelay))):this.emitOne(e,t,n):this.postInitializeQueue.push({action:e,data:t,ack:n})},n.createGroup=function(e,t,n,i){this.emit("group:create",{externalId:e,globalViews:t,shareColor:n,tags:i=void 0===i?[]:i})},n.executeQueue=function(){this.initialized&&this.emitAll()},n.setInitialized=function(){var e;for(this.initialized=!0;e=this.postInitializeQueue.shift();)this.emit(e.action,e.data,e.ack)},n.setup=function(e){this.emit("master:setup",e)},n.reset=function(e){this.emit("master:reset",null,function(){e()})},n.getStaticUrl=function(e){return e},n.reconnect=function(e,t,n,i){var o=new r;return this.emit("master:reconnect",{token:e,accessToken:t,gameConfig:n},function(){i(),o.resolve()}.bind(this)),o.promise()},n.off=function(){this.events={}},n.on=function(e,t){this._addEvent(e,t,!1),this._touchEvent(e)},n.once=function(e,t){this._addEvent(e,t,!0),this._touchEvent(e)},n._addEvent=function(e,t,n){void 0===this.events[e]&&(this.events[e]=[]),this.events[e].push({callback:t,once:n})},n._touchEvents=function(){for(var e in this.events)this.events.hasOwnProperty(e)&&this._touchEvent(e)},n._touchEvent=function(e){},n._trigger=function(e,n){var i;void 0!==this.events[e]&&(i=[],this.events[e].forEach(function(e){var t=e.callback;e.once&&i.push(e);try{t.apply(this,[n])}catch(e){console.error(e)}}),0<i.length)&&(i.unshift(this.events),function(e){for(var t,n,i=arguments,o=i.length;1<o&&e.length;)for(t=i[--o];-1!==(n=e.indexOf(t));)e.splice(n,1);return e}.apply(this,i))},n.getConnectURL=function(e){return null},n.getConnectToken=function(e){return null},n.tokenConnect=function(e){var t=new r;return t.resolve(),t.promise()},n.noTokenConnect=function(){var e=new r;return e.resolve(),e.promise()},n.restoreProviderSettings=function(e){},n.serializeProviderSettings=function(){return{}},n.proxyFile=function(e){var t=new r;return this.emit("file:proxy",{url:e},function(e){t.resolve({url:e.url})}.bind(this)),t.promise()},t}),define("CatLab/Webremote/Providers/SocketIO",["CatLab/Webremote/Providers/Provider","CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Tools"],function(e,s,a,t){function n(){this.initializeProvider(),this.userId=null,this.randomToken=t.getUuid(),this.loadBalancerSessionToken="connid",this.socket=null,this._registeredEvents={},this._host=null}var l=null,e=n.prototype=new e;return e.getProviderSettings=function(){var t=new a;return s.getServerList()?s.getServerList().getSelectedServer().done(function(e){t.resolve({host:e})}.bind(this)).fail(function(e){alert(e),t.reject(e)}.bind(this)):t.resolve({}),t.promise()},e.canProviderLoadExternalXml=function(){return!0},e.canProxyFiles=function(){return!0},e.connect=function(i,o){var t,r=new a;return this.log("Loading socket.io"),t=function(){this.log("Connecting to socket.io");var e,t=s.getSocketURL(),n=(this._host?t=this._host:void 0!==o.host&&o.host&&(t=(e=s.getProtocol())?e+"://"+o.host:"//"+o.host,this._host=t),this.socket=l(t+"/"+i+"?"+this.loadBalancerSessionToken+"="+this.randomToken,{withCredentials:!1,reconnection:!0}),!1);this.socket.on("connect_error",function(e){n?this._trigger("disconnect"):(this.socket.off(),this.socket.disconnect(),this.socket=null,r.reject())}.bind(this)),this.socket.once("connect",function(){n||(n=!0,this.setInitialized(),this.socket.io.on("reconnect",function(e){this._trigger("reconnect")}.bind(this)),this._touchEvents(),r.resolve())}.bind(this))}.bind(this),require(["socket.io-client"],function(e){l=e,t()}),r.promise()},e.disconnect=function(e){void 0===e&&(e=!0),this.initialized=!1,this.socket&&((e?this:(this._registeredEvents={},this.socket)).off(),this.socket.disconnect(),this.socket=null)},e.off=function(){this._registeredEvents={},this.events={},this.socket.off()},e.setUserId=function(e){return this.userId=e,this},e.emitAll=function(){var e,t=this.queue.compactFlush();if(t.length)for(;e=t.shift();)this.emitOne(e.action,e.data,e.ack)},e.emitOne=function(e,t,n){this.socket.emit(e,t,n),this.messageCounter&&this.messageCounter.outgoing()},e.log=function(){this.master.log.apply(arguments)},e.getStaticUrl=function(e){return e.indexOf("?")<0?e+="?":e+="&",e+(this.loadBalancerSessionToken+"="+this.randomToken)},e._detachEvents=function(e){this.socket&&this.socket.off(e)},e._touchEvent=function(t){this.socket&&void 0===this._registeredEvents[t]&&(this.socket.on(t,function(e){this._trigger(t,e)}.bind(this)),this._registeredEvents[t]=!0)},e._handleSocketIoEvent=function(e,t){switch(e){case"connect":case"disconnect":break;default:return this._trigger(e,t)}},e.getConnectURL=function(e){return s.getServerList()?s.getServerList().getConnectURL():e},e.getConnectToken=function(e){return s.getServerList()?s.getServerList().getConnectToken(e):e},e.tokenConnect=function(e){var t=new a,n={};if(s.getServerList())try{var i=s.getServerList().getFromToken(e);n.host=i.host,e=i.token}catch(e){return t.reject(),t.promise()}return this.connect("remote",n).fail(function(){t.reject()}).then(function(){t.resolve(e)}),t.promise()},e.restoreProviderSettings=function(e){void 0!==e.serverlist&&s.getServerList()&&s.getServerList().unserialize(e.serverlist),void 0!==e.host&&(this._host=e.host)},e.serializeProviderSettings=function(){var e={host:this._host};return s.getServerList()&&(e.serverlist=s.getServerList().serialize()),e},n}),define("CatLab/Webremote/SonicSync/Library/ring-buffer",[],function(){function t(e){this.array=[],this.maxLength=e}return t.prototype.get=function(e){return e>=this.array.length?null:this.array[e]},t.prototype.last=function(){return 0==this.array.length?null:this.array[this.array.length-1]},t.prototype.add=function(e){this.array.push(e),this.array.length>=this.maxLength&&this.array.splice(0,1)},t.prototype.length=function(){return this.array.length},t.prototype.clear=function(){this.array=[]},t.prototype.copy=function(){var e=new t(this.maxLength);return e.array=this.array.slice(0),e},t.prototype.remove=function(e,t){this.array.splice(e,t)},t}),define("CatLab/Webremote/SonicSync/Library/sonic-coder",[],function(){function e(e){this.freqMin=(e=e||{}).freqMin||18500,this.freqMax=e.freqMax||19500,this.freqError=e.freqError||50,this.alphabetString=e.alphabet||"\n abcdefghijklmnopqrstuvwxyz0123456789,.!?@*",this.startChar=e.startChar||"^",this.endChar=e.endChar||"$",this.alphabet=this.startChar+this.alphabetString+this.endChar}return e.prototype.charToFreq=function(e){var t=this.alphabet.indexOf(e),e=(-1==t&&(console.error(e,"is an invalid character."),t=this.alphabet.length-1),this.freqMax-this.freqMin),t=t/this.alphabet.length,e=Math.round(e*t);return this.freqMin+e},e.prototype.freqToChar=function(e){if(!(this.freqMin<e&&e<this.freqMax))if(this.freqMin-e<this.freqError)e=this.freqMin;else{if(!(e-this.freqMax<this.freqError))return console.error(e,"is out of range."),null;e=this.freqMax}var t=this.freqMax-this.freqMin,e=(e-this.freqMin)/t,t=Math.round(this.alphabet.length*e);return this.alphabet[t]},e}),define("CatLab/Webremote/SonicSync/Library/sonic-server",["./ring-buffer","./sonic-coder"],function(t,n){function e(e){this.peakThreshold=(e=e||{}).peakThreshold||-65,this.minRunLength=e.minRunLength||2,this.coder=e.coder||new n(e),this.timeout=e.timeout||300,this.debug=!!e.debug,this.peakHistory=new t(16),this.peakTimes=new t(16),this.callbacks={},this.buffer="",this.state=i,this.isRunning=!1,this.iteration=0}var i=1,o=2;return e.prototype.start=function(){try{navigator.mediaDevices||console.log("No mediadevices found"),navigator.mediaDevices.getUserMedia({audio:{optional:[{echoCancellation:!1}]}}).then(this.onStream_.bind(this)).catch(this.onStreamError_.bind(this))}catch(e){console.log(e)}},e.prototype.stop=function(){this.isRunning=!1,this.track.stop()},e.prototype.on=function(e,t){"message"==e&&(this.callbacks.message=t),"character"==e&&(this.callbacks.character=t)},e.prototype.setDebug=function(e){this.debug=e;e=document.querySelector("canvas");e&&e.parentElement.removeChild(e)},e.prototype.fire_=function(e,t){"function"==typeof e&&e(t)},e.prototype.onStream_=function(e){var t;void 0!==e.getTracks()[0]?(this.track=e.getTracks()[0],t=new AudioContext,e=(this.audioContext=t).createMediaStreamSource(e),t=t.createAnalyser(),e.connect(t),this.freqs=new Float32Array(t.frequencyBinCount),this.analyser=t,this.isRunning=!0,this.raf_(this.loop.bind(this))):console.log("No microphone found.")},e.prototype.onStreamError_=function(e){console.error("Audio input error:",e)},e.prototype.getPeakFrequency=function(){for(var e=-1/0,t=-1,n=this.freqToIndex(this.coder.freqMin);n<this.freqs.length;n++)this.freqs[n]>e&&(e=this.freqs[n],t=n);return e>this.peakThreshold?this.indexToFreq(t):null},e.prototype.loop=function(){this.analyser.getFloatFrequencyData(this.freqs),(this.iteration+1)%300==0&&this.restartServerIfSanityCheckFails();var e=this.getPeakFrequency();e?(e=this.coder.freqToChar(e),this.debug&&console.log("Transcribed char: "+e),this.peakHistory.add(e),this.peakTimes.add(new Date)):(e=this.peakTimes.last())&&new Date-e>this.timeout&&(this.state=i,this.debug&&console.log("Token",this.buffer,"timed out"),this.peakTimes.clear()),this.analysePeaks(),this.debug&&this.debugDraw_(),this.isRunning&&this.raf_(this.loop.bind(this)),this.iteration+=1},e.prototype.indexToFreq=function(e){return this.audioContext.sampleRate/2/this.freqs.length*e},e.prototype.freqToIndex=function(e){var t=this.audioContext.sampleRate/2;return Math.round(e/t*this.freqs.length)},e.prototype.analysePeaks=function(){var e=this.getLastRun();e&&(this.state==i?e==this.coder.startChar&&(this.buffer="",this.state=o):this.state==o&&(e!=this.lastChar&&e!=this.coder.startChar&&e!=this.coder.endChar&&(this.buffer+=e,this.lastChar=e,this.fire_(this.callbacks.character,e)),e==this.coder.endChar)&&(this.state=i,this.fire_(this.callbacks.message,this.buffer),this.buffer=""))},e.prototype.getLastRun=function(){for(var e=this.peakHistory.last(),t=0,n=this.peakHistory.length()-2;0<=n&&this.peakHistory.get(n)==e;n--)t+=1;return t>this.minRunLength?(this.peakHistory.remove(n+1,t+1),e):null},e.prototype.debugDraw_=function(){var e=document.querySelector("canvas");e||(e=document.createElement("canvas"),document.body.appendChild(e)),e.width=document.body.offsetWidth,e.height=480,drawContext=e.getContext("2d");for(var t=0;t<this.freqs.length;t++){var n=this.freqs[t]+400,n=e.height-n-1,i=e.width/this.freqs.length;drawContext.fillStyle="black",drawContext.fillRect(t*i,n,1,1)}},e.prototype.raf_=function(e){"undefined"==typeof window||window.chrome&&chrome.extension?setTimeout(e,1e3/60):requestAnimationFrame(e)},e.prototype.restartServerIfSanityCheckFails=function(){if(this.freqs[0]<-300)console.error("freqs[0] < -300. Restarting."),this.restart();else{for(var e=!0,t=0;t<10;t++)-100==this.freqs[t]&&(e=!1);e||(console.error("freqs[0:10] == -100. Restarting."),this.restart())}},e.prototype.restart=function(){},e}),define("CatLab/Webremote/SonicSync/Library/sonic-socket",["./sonic-coder"],function(t){var n=!1;function e(e){this.coder=(e=e||{}).coder||new t,this.charDuration=e.charDuration||.5,this.coder=e.coder||new t(e),this.rampDuration=e.rampDuration||.001,this.audioContext=new n}return"undefined"!=typeof window&&(n=window.AudioContext||window.webkitAudioContext||!1),e.prototype.send=function(e,t){e=this.coder.startChar+e+this.coder.endChar;for(var n,i=0;i<e.length;i++){var o=e[i],o=this.coder.charToFreq(o),r=this.audioContext.currentTime+this.charDuration*i;this.scheduleToneAt(o,r,this.charDuration)}t&&(n=this.charDuration*e.length,setTimeout(t,1e3*n))},e.prototype.scheduleToneAt=function(e,t,n){var i=this.audioContext.createGain(),n=(i.gain.value=0,i.gain.setValueAtTime(0,t),i.gain.linearRampToValueAtTime(1,t+this.rampDuration),i.gain.setValueAtTime(1,t+n-this.rampDuration),i.gain.linearRampToValueAtTime(0,t+n),i.connect(this.audioContext.destination),this.audioContext.createOscillator());n.frequency.value=e,n.connect(i),n.start(t)},e}),define("CatLab/Webremote/SonicSync/Client",["CatLab/Webremote/Config","CatLab/Webremote/SonicSync/Library/ring-buffer","CatLab/Webremote/SonicSync/Library/sonic-coder","CatLab/Webremote/SonicSync/Library/sonic-server","CatLab/Webremote/SonicSync/Library/sonic-socket","CatLab/Webremote/Tools/Deferred"],function(t,e,n,i,o,r){function s(e){this.options=t.getAudioSyncConfig(),this.alphabet=this.options.alphabet.split(""),this.controller=e}var a=s.prototype;return a.startListener=function(){this.stop();var e=new i(this.options);e.start(),e.on("message",this.onIncomingMessage.bind(this)),this.sonicServer=e},a.startSender=function(){this.sonicSocket=new o(this.options)},a.stop=function(){this.sonicServer&&this.sonicServer.stop()},a.sync=function(){var e=new r,t=this.generateRandomSequence(this.options.length);return this.sonicSocket.send(t+this.getParityLetter(t),function(){this.controller.trigger("sync:audio",{secret:t})}.bind(this)),e.promise()},a.generateRandomSequence=function(e){for(var t,n="",i="",o=0;o<e;o++){for(;t=Math.floor(Math.random()*this.alphabet.length),(i=this.alphabet[t])===n.substr(n.length-1,1););n+=i}return n},a.getParityLetter=function(e){for(var t=0,n=e.split(""),i=0;i<n.length;i++)t+=this.alphabet.indexOf(n[i]);e=t%this.alphabet.length;return n[n.length-1]===this.alphabet[e]&&(e=(e+1)%this.alphabet.length),this.alphabet[e]},a.onIncomingMessage=function(e){var t=e.substr(0,e.length-1),n=this.getParityLetter(t);n===e[e.length-1]?this.onMessage(t):console.log("Parity check failed, expected "+n+", ignoring message")},a.onMessage=function(e){this.controller.emit("sync:audio",{secret:e})},a.generateAlphabet=function(e){for(var t="",n=0;n<Math.min(e.length,9);n++)t+=n.toString();return t},s}),define("CatLab/Webremote/Tools/ClientSniffer",[],function(){function e(){this._canPlayWebM=null}var t=e.prototype;return t.isMobileBrowser=function(){var e,t;return!(!this.isCordova()&&(e=!1,t=navigator.userAgent||navigator.vendor||window.opera,!/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t))&&!/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4)))||e},t.isCordova=function(){return"undefined"!=typeof cordova},t.isInternetExplorer=function(){var e=window.navigator.userAgent,t=e.indexOf("MSIE ");return 0<t?parseInt(e.substring(t+5,e.indexOf(".",t)),10):0<e.indexOf("Trident/")?(t=e.indexOf("rv:"),parseInt(e.substring(t+3,e.indexOf(".",t)),10)):0<(t=e.indexOf("Edge/"))&&parseInt(e.substring(t+5,e.indexOf(".",t)),10)},t.supportsLocalStorage=function(){try{if(window.localStorage)return!0}catch(e){return!1}},t.canPlayWebM=function(){if(null===this._canPlayWebM){this._canPlayWebM=!1;try{var e=document.createElement("video");e.canPlayType&&(this._canPlayWebM=e.canPlayType('video/webm; codecs="vp8, vorbis"'))}catch(e){console.error(e)}}return this._canPlayWebM},new e}),define("CatLab/Webremote/Components/ImagePositionInputComponent",["CatLab/Webremote/Tools/ClientSniffer"],function(o){function e(e,t){this.element=t,this.remotePlayerView=e,this.positions=[],this.canvas=null,this.isLoaded=!1,this.isRotated=!1,this.buttons=null,this.pointCountContainer=null,this.draw()}var t=e.prototype;return t.draw=function(){this.element.innerHTML="",this.rotatedImageElement=null,this.buttons=null,this.circleRadius=this.element.getAttribute("circleRadius")||2,this.circleStroke=this.element.getAttribute("circleStroke")||Math.max(.5,this.circleRadius/5),this.circleStrokeColor=this.element.getAttribute("circleStrokeColor")||"red",this.circleFillColor=this.element.getAttribute("circleFillColor")||"rgb(255,255,0,0.3)",this.image=this.element.getAttribute("src"),this.image&&(this.element.innerHTML='<div class="image"><img /></div>',this.imageElement=this.element.querySelector("img"),this.imageElement.addEventListener("load",function(){this.isLoaded=!0,this.resizeImage(),setTimeout(function(){this.resizeImage()}.bind(this),100)}.bind(this)),this.imageElement.setAttribute("src",this.image),this.resizeImage(),this.imageElement.addEventListener("dragstart",function(e){e.preventDefault()}),this.svgContainer=document.createElement("div"),this.svgContainer.className="pointer-container",this.element.querySelector(".image").appendChild(this.svgContainer),this.resizeSvgContainer(),this.svgContainer.addEventListener("click",function(e){this.svgClick(e)}.bind(this)))},t.resizeSvgContainer=function(){var e=this.imageElement;this.isRotated&&this.rotatedImageElement&&(e=this.rotatedImageElement),this.svgContainer.style.position="absolute",this.svgContainer.style.zIndex="1",this.svgContainer.style.width=e.offsetWidth+"px",this.svgContainer.style.height=e.offsetHeight+"px",this.svgContainer.style.left=e.offsetLeft+"px",this.svgContainer.style.top=e.offsetTop+"px"},t.resizeImage=function(){var e,t,n,i;this.isLoaded&&(e=this.element.clientWidth,t=this.element.clientHeight,n=this.imageElement.naturalWidth,i=this.imageElement.naturalHeight,o.isMobileBrowser()&&"1"==this.element.getAttribute("rotate")?this.isRotated=e/t<1!=n/i<1:this.isRotated=!1,this.isRotated?this.element.classList.add("rotated"):this.element.classList.remove("rotated"),this.isRotated?(this.generateCanvas(),this.rotatedImageElement.style.display="",this.resizeSvgContainer(),this.imageElement.style.display="none"):this.rotatedImageElement&&(this.rotatedImageElement.style.display="none",this.imageElement.style.display=""),this.imageElement.style.maxWidth=e+"px",this.imageElement.style.maxHeight=t+"px",this.rotatedImageElement&&(this.rotatedImageElement.style.maxWidth=e+"px",this.rotatedImageElement.style.maxHeight=t+"px"),this.resizeSvgContainer())},t.generateCanvas=function(){var e,t,n,i,o,r,s,a;this.rotatedImageElement||(o=this.imageElement,e=this.imageElement.naturalWidth,t=this.imageElement.naturalHeight,(n=document.createElement("canvas")).width=t,n.height=e,i=n.getContext("2d"),o=o,r=n.width/2,s=n.height/2,a=0-Math.PI/2,i.setTransform(1,0,0,1,r,s),i.rotate(a),i.drawImage(o,-e/2,-t/2),this.rotatedImageElement=n,this.element.querySelector("div.image").appendChild(this.rotatedImageElement))},t.imageClick=function(e){var t=e.offsetX/this.imageElement.offsetWidth,e=e.offsetY/this.imageElement.offsetHeight;this.selectPosition(t,e)},t.svgClick=function(e){var t=e.offsetX/this.svgContainer.offsetWidth,e=e.offsetY/this.svgContainer.offsetHeight;this.isRotated?this.selectPosition(1-e,t):this.selectPosition(t,e)},t.canvasClick=function(e){var t=e.offsetX/this.rotatedImageElement.offsetWidth,e=e.offsetY/this.rotatedImageElement.offsetHeight;this.selectPosition(1-e,t)},t.selectPosition=function(e,t){0<this.getMaxPoints()&&this.positions.length>=this.getMaxPoints()||(this.positions.push({x:e,y:t}),this.drawCircles(),this.shouldConfirmPosition()?(this.syncPositionData(!1),this.showSubmitButton()):this.submit())},t.shouldConfirmPosition=function(){return"1"==this.element.getAttribute("confirm-position")},t.getMinPoints=function(){return this.element.getAttribute("min-points")&&0<parseInt(this.element.getAttribute("min-points"))?parseInt(this.element.getAttribute("min-points")):1},t.getMaxPoints=function(){return this.element.getAttribute("max-points")&&0<parseInt(this.element.getAttribute("max-points"))?parseInt(this.element.getAttribute("max-points")):1},t.showSubmitButton=function(){var e;this.buttons?this.positionSubmitButton():((e=document.createElement("div")).className="imagemap-buttons",e.innerHTML='<button data-action="submit" class="imagemap-button pulsating">'+(2<this.getMaxPoints()?'<span class="point-counter"></span>':"")+'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 22"><path d="M20.285 2l-11.285 11.567-5.286-5.011-3.714 3.716 9 8.728 15-15.285z"/></svg></button><button data-action="reset" class="imagemap-button"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 22"><path d="M24 20.188l-8.315-8.209 8.2-8.282-3.697-3.697-8.212 8.318-8.31-8.203-3.666 3.666 8.321 8.24-8.206 8.313 3.666 3.666 8.237-8.318 8.285 8.203z" /></button>',this.buttons=e,this.element.appendChild(this.buttons),this.positionSubmitButton(),this.buttons.querySelector("button[data-action=submit]").addEventListener("click",function(){this.submit()}.bind(this)),this.buttons.querySelector("button[data-action=reset]").addEventListener("click",function(){this.reset(),this.hideSubmitButton()}.bind(this)),this.pointCountContainer=this.buttons.querySelector(".point-counter"),this.updatePointCount())},t.updatePointCount=function(){var e;this.pointCountContainer&&(this.pointCountContainer.innerHTML=this.positions.length,this.positions.length<this.getMinPoints()?this.pointCountContainer.classList.add("insufficient"):this.pointCountContainer.classList.remove("insufficient"),e=this.buttons.querySelector("button[data-action=submit]"),this.positions.length>=this.getMinPoints()?(e.classList.add("pulsating"),e.classList.remove("disabled")):(e.classList.remove("pulsating"),e.classList.add("disabled")))},t.hideSubmitButton=function(){this.buttons.style.display="none"},t.positionSubmitButton=function(){this.buttons.style.display="",.5<this.positions[0].x?(this.buttons.classList.add("left"),this.buttons.classList.remove("right")):(this.buttons.classList.add("right"),this.buttons.classList.remove("left"))},t.submit=function(){this.syncPositionData(!0)},t.syncPositionData=function(e){this.positions.length<this.getMinPoints()||this.remotePlayerView.controller.syncValue("position",{x:0<this.positions.length?this.positions[0].x:null,y:0<this.positions.length?this.positions[0].y:null,p:this.positions,c:e},this.remotePlayerView.viewId)},t.drawCircles=function(){this.updatePointCount(),this.svgContainer.innerHTML="",0!==this.positions.length&&this.positions.forEach(function(t){var e=this.imageElement,n=t.x,i=t.y,o=e.offsetWidth,e=e.offsetHeight,r=(this.isRotated&&this.rotatedImageElement&&(n=t.y,i=1-t.x,o=this.rotatedImageElement.offsetWidth,e=this.rotatedImageElement.offsetHeight),o/100*this.circleRadius),s=Math.max(1,o/100*this.circleStroke),a="http://www.w3.org/2000/svg",l=document.createElementNS(a,"svg"),a=document.createElementNS(a,"circle");l.appendChild(a),l.addEventListener("click",function(e){e.preventDefault(),e.stopPropagation(),this.removePoint(t),0===this.positions.length&&this.hideSubmitButton()}.bind(this)),this.svgContainer.appendChild(l),a.setAttribute("cx",r+s),a.setAttribute("cy",r+s),a.setAttribute("r",r),a.setAttribute("stroke-width",s),a.setAttribute("stroke",this.circleStrokeColor),a.setAttribute("fill",this.circleFillColor),l.setAttribute("width",2*(r+s)),l.setAttribute("height",2*(r+s)),l.style.position="absolute",l.style.left=o*n-r-s+"px",l.style.top=e*i-r-s+"px"}.bind(this))},t.removePoint=function(e){e=this.positions.indexOf(e);-1<e&&this.positions.splice(e,1),this.drawCircles()},t.resize=function(){this.resizeImage(),this.drawCircles()},t.update=function(){this.draw()},t.destroy=function(){},t.reset=function(){this.positions=[],this.drawCircles()},e.css=" \t\t\t\timage-position-input {\t\t\t\t\tdisplay: flex; \t\t\t\t\tjustify-content: center;\t\t\t\t\talign-content: center;\t\t\t\t\talign-items: center;\t\t\t\t\twidth: 100%;\t\t\t\t\theight: 100%;\t\t\t\t\tposition: relative;\t\t\t\t\toverflow: hidden;\t\t\t\t} \t\t\t\t \t\t\t\timage-position-input .image { \t\t\t\t\ttext-align: center;\t\t\t\t\ttransform-origin: 0 0; \t\t\t\t} \t\t\t\timage-position-input .image img, \t\t\t\timage-position-input .image canvas { \t\t\t\t\tdisplay: block;\t\t\t\t\tmax-width: 100%;\t\t\t\t\tmax-height: 100%;\t\t\t\t\theight: auto;\t\t\t\t\twidth: auto; \t\t\t\t} \t\t\t\timage-position-input button.imagemap-button svg { \t\t\t\t\theight: 48px; \t\t\t\t\twidth: 48px; \t\t\t\t} \t\t\t\timage-position-input button.imagemap-button { \t\t\t\t\tmargin-left: 10px; \t\t\t\t\tposition: relative; \t\t\t\t} \t\t\t\timage-position-input button.imagemap-button.disabled svg {\t\t\t\t\tfill: gray;\t\t\t\t}\t\t\t\timage-position-input .imagemap-buttons { \t\t\t\t\tposition: absolute; \t\t\t\t\tright: 10px; \t\t\t\t\tbottom: 10px; \t\t\t\t\tz-index: 10; \t\t\t\t} \t\t\t\t\t\t\t\timage-position-input .imagemap-buttons.left {\t\t\t\t\tleft: 10px;\t\t\t\t\tright: auto;\t\t\t\t}\t\t\t\t\t\t\t\timage-position-input.rotated .imagemap-buttons {\t\t\t\t\ttransform: rotate(-90deg);\t\t\t\t\ttransform-origin: 100% 0;\t\t\t\t\ttop: 10px;\t\t\t\t\tright: 80px;\t\t\t\t\tbottom: auto;\t\t\t\t\tleft: auto;\t\t\t\t}\t\t\t\timage-position-input.rotated .imagemap-buttons.left {\t\t\t\t\tbottom: 80px;\t\t\t\t\ttop: auto;\t\t\t\t\tright: 80px; \t\t\t\t\tleft: auto;\t\t\t\t\ttransform-origin: 100% 0;\t\t\t\t}\t\t\t\timage-position-input button.pulsating .point-counter {\t\t\t\t}\t\t\t\timage-position-input .point-counter {\t\t\t\t\tfont-size: 1em;\t\t\t\t\tvertical-align: middle;\t\t\t\t\tposition: absolute;\t\t\t\t\ttop: -1em;\t\t\t\t\tleft: -1em;\t\t\t\t\tborder: 1px solid black;\t\t\t\t\tborder-radius: 100%;\t\t\t\t\tpadding: 0.5em;\t\t\t\t\tbackground: white;\t\t\t\t\tmin-width: 1em;\t\t\t\t}\t\t\t\timage-position-input .point-counter.insufficient {\t\t\t\t\tborder-color: red;\t\t\t\t\tcolor: red;\t\t\t\t}\t\t",e.selector="image-position-input",e}),define("CatLab/Webremote/Components/FullscreenButtonComponent",["CatLab/Webremote/Tools/Screenfull","CatLab/Webremote/Config"],function(e,t){function n(e,t,n){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=n,this.draw()}var i=n.prototype;return i.draw=function(){t.canFullscreen()&&e&&e.isEnabled&&!e.isFullscreen?(this.element.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" style="display: block" width="100%" height="100%" viewBox="0 0 24 24"><path d="M6.426 10.668l-3.547-3.547-2.879 2.879v-10h10l-2.879 2.879 3.547 3.547-4.242 4.242zm11.148 2.664l3.547 3.547 2.879-2.879v10h-10l2.879-2.879-3.547-3.547 4.242-4.242zm-6.906 4.242l-3.547 3.547 2.879 2.879h-10v-10l2.879 2.879 3.547-3.547 4.242 4.242zm2.664-11.148l3.547-3.547-2.879-2.879h10v10l-2.879-2.879-3.547 3.547-4.242-4.242z"/></svg>',this.element.addEventListener("click",function(){e.request(null,{navigationUI:"hide"})}.bind(this))):this.element.innerHTML=""},i.resize=function(){this.draw()},i.update=function(){this.draw()},i.destroy=function(){},n.css=" ",n.selector="fullscreen-button",n}),define("CatLab/Webremote/Components/ViewDefinedComponent",[],function(){function e(e,t){this.element=t,this.remotePlayerView=e,this.position=null,this.draw()}var t=e.prototype;return t.draw=function(){if(this.element){this.element.innerHTML="";for(var e=0;e<this.content.childNodes.length;e++)this.element.appendChild(this.content.childNodes[e].cloneNode(!0));this.componentContainer.attachComponents(this.remotePlayerView,this.element)}},t.update=function(){this.draw()},t.resize=function(){this.draw()},t.destroy=function(){},e.css=" ",e.selector="view-defined-component",e.content="",e}),define("CatLab/Webremote/Views/Popups/IframePopup",["CatLab/Webremote/Views/Popups/BasePopup"],function(e){function t(e){this.url=e}return(t.prototype=new e).renderContent=function(e){this.container.className+=" iframe";var t=document.createElement("iframe");t.src=this.url,t.style.height="99%",t.style.width="100%",t.style.borderWidth="0",e.appendChild(t),e.style.position="relative",e.style.height="100%",e.style.width="100%",e.style.boxSizing="border-box",e.style.overflow="auto",e.style.webkitOverflowScrolling="touch"},t}),define("CatLab/Webremote/Components/ModalIframeLink",["CatLab/Webremote/Views/Popups/IframePopup"],function(t){function e(e,t,n){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=n,this.draw()}var n=e.prototype;return n.draw=function(){this._clickHandler&&this.element.removeEventListener("click",this._clickHandler),this._clickHandler=function(){var e=this.element.getAttribute("href"),e=this.remotePlayerView.stringInterpolateDataElements(e,encodeURIComponent);new t(e).render(document.body)}.bind(this),this.element.addEventListener("click",this._clickHandler)},n.resize=function(){this.draw()},n.update=function(){this.draw()},n.destroy=function(){},e.css=" ",e.selector="modal-iframe-link",e}),define("CatLab/Webremote/Views/Popups/TextPopup",["CatLab/Webremote/Views/Popups/BasePopup"],function(e){function t(e){this.message=e}return(t.prototype=new e).renderContent=function(e){var t=(t=this.message).replace(/(?:\r\n|\r|\n)/g,"<br>");e.innerHTML=t},t}),define("CatLab/Webremote/Components/TooltipComponent",["CatLab/Webremote/Views/Popups/TextPopup"],function(e){function t(e,t,n){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=n,this.draw()}var n=t.prototype;return n.draw=function(){this._clickHandler&&this.element.removeEventListener("click",this._clickHandler),this._clickHandler=function(){new e(this.element.getAttribute("data-tooltip")).render(document.body)}.bind(this),this.element.addEventListener("click",this._clickHandler)},n.resize=function(){},n.update=function(){},n.destroy=function(){},t.css=" ",t.selector="[data-tooltip]",t}),define("CatLab/Webremote/Components/VirtualKeyboardComponent",["SimpleKeyboard","CatLab/Webremote/Config"],function(i,o){var r,s=!1,a=null,e=0;function l(){for(var e=document.querySelectorAll(".simple-keyboard"),t=0;t<e.length;t++)e[t].classList.add("hidden");a=null}function t(e,t,n){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=n,this.inputType=t.getAttribute("type")?t.getAttribute("type").toLowerCase():"text",this.draw()}var n=t.prototype;return n.draw=function(){(function(){if(!s){var e=document.createElement("link"),e=(e.type="text/css",e.rel="stylesheet",e.href=o.getVendorPath()+"simple-keyboard/build/css/index.css",document.head.appendChild(e),document.createElement("div"));e.className="simple-keyboard",document.body.appendChild(e),r=new i.default({onChange:function(e){a&&a.onKeyboardChange(e)}.bind(this),onKeyPress:function(e){switch(e){case"{shift}":case"{lock}":t="default"===r.options.layoutName?"shift":"default",r.setOptions({layoutName:t});break;case"{numbers}":case"{abc}":t="numbers"!==r.options.layoutName?"numbers":"default",r.setOptions({layoutName:t});break;case"{ent}":l();break;case"{arrowup}":a.increaseValue(1);break;case"{arrowdown}":a.increaseValue(-1)}var t}.bind(this),layoutName:"default",layout:{default:["q w e r t y u i o p","a s d f g h j k l","{shift} z x c v b n m {backspace}","{numbers} {space} {ent}"],shift:["Q W E R T Y U I O P","A S D F G H J K L","{shift} Z X C V B N M {backspace}","{numbers} {space} {ent}"],numbers:["1 2 3","4 5 6","7 8 9","{abc} 0 {backspace}"]},physicalKeyboardHighlight:!0,disableCaretPositioning:!1,mergeDisplay:!0,display:{"{numbers}":"123","{ent}":"⇩","{escape}":"esc ⎋","{tab}":"tab ⇥","{backspace}":"⌫","{capslock}":"caps lock ⇪","{shift}":"⇧","{controlleft}":"ctrl ⌃","{controlright}":"ctrl ⌃","{altleft}":"alt ⌥","{altright}":"alt ⌥","{metaleft}":"cmd ⌘","{metaright}":"cmd ⌘","{abc}":"ABC"}});for(var t=document.querySelectorAll(".simple-keyboard"),n=0;n<t.length;n++)t[n].classList.add("hidden");s=!0}})(),this.element.id||(this.element.id="input_"+ ++e),this.element.type="text",/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)&&(this.element.readOnly=!0),this.element.addEventListener("input",this.onInputChange.bind(this)),this.element.addEventListener("focus",this.onInputFocus.bind(this)),this.element.classList.contains("visible")&&this.onInputFocus()},n.hideKeyboard=function(){l()},n.showKeyboard=function(){var e=this,t=this.inputType,n=e.element;"number"===t?r.setOptions({inputName:n.id,layoutName:"numbers",layout:{default:["q w e r t y u i o p","a s d f g h j k l","{shift} z x c v b n m {backspace}","{numbers} {space} {ent}"],numbers:["1 2 3 {arrowup}","4 5 6 {arrowdown}","7 8 9 "+1.1.toLocaleString().substring(1,2),"{backspace} 0 {ent}"]}}):r.setOptions({inputName:n.id,layoutName:"default",layout:{default:["q w e r t y u i o p","a s d f g h j k l","{shift} z x c v b n m {backspace}","{numbers} {space} {ent}"],shift:["Q W E R T Y U I O P","A S D F G H J K L","{shift} Z X C V B N M {backspace}","{numbers} {space} {ent}"],numbers:["1 2 3","4 5 6","7 8 9","{abc} 0 {backspace}"]}});for(var i=document.querySelectorAll(".simple-keyboard"),o=0;o<i.length;o++)i[o].classList.remove("hidden");a=e,r.setInput(n.value,n.id)},n.onKeyboardChange=function(e){this.element.value=e;var t=new Event("change",{bubbles:!0});this.element.dispatchEvent(t),this.element.getAttribute("data-value-realtime")&&(t=this.element.getAttribute("data-value-id"))&&this.remotePlayerView.controller.syncValue(t,e,this.remotePlayerView.viewId)},n.onInputChange=function(){r.setInput(this.element.value,this.element.id)},n.onInputFocus=function(){this.showKeyboard()},n.setInputCaretPosition=function(e){this.element.setSelectionRange&&(this.element.focus(),this.element.setSelectionRange(e,e))},n.increaseValue=function(e){var t;"number"===this.inputType&&(t=(t=parseFloat(this.element.value))||0,this.element.value=t+e)},n.submit=function(){this.hideKeyboard()},n.resize=function(){this.draw()},n.update=function(){this.draw()},n.destroy=function(){this.hideKeyboard()},t.css=" .simple-keyboard { position: fixed; bottom: 0; display: block; } .simple-keyboard.hidden { display: none; } ",t.selector="input.virtual",t}),define("CatLab/Webremote/Components/TimerComponent",[],function(){function e(e,t){this.element=t,this.remotePlayerView=e,this.draw(),this.countdownInterval=setInterval(function(){this.tick()}.bind(this),100),this.startDate=Date.now(),this.targetDate=null,this.counterHtml=null,this.progessBar=null}var t=e.prototype;return t.draw=function(){var e,t=this.element;t.innerHTML="",this.targetDate=this.element.getAttribute("to"),this.targetDate&&((e=this.element.getAttribute("start"))&&(this.startDate=e),(e=document.createElement("div")).className="timer-container",this.counterHtml=document.createElement("div"),this.counterHtml.className="countdown",e.appendChild(this.counterHtml),this.progessBar=document.createElement("div"),this.progessBar.className="progress-bar",this.progessBar.innerHTML="&nbsp;",e.appendChild(this.progessBar),t.appendChild(e))},t.tick=function(){var e,t;this.targetDate&&this.counterHtml&&this.progessBar&&((e=this.targetDate-Date.now())<0?this.counterHtml.innerHTML="0":(t=(Date.now()-this.startDate)/(this.targetDate-this.startDate)*100,this.counterHtml.innerHTML=Math.ceil(e/1e3),this.progessBar.style.width=t+"%"))},t.resize=function(){},t.update=function(){this.draw()},t.clearInterval=function(){this.countdownInterval&&(clearInterval(this.countdownInterval),this.countdownInterval=null)},t.destroy=function(){this.clearInterval()},e.css=" timer-countdown { position: fixed; bottom: 0px; left: 0px; width: 100%; color: white; z-index: 1000; } timer-countdown .progress-bar { position:absolute; height: 3px; bottom: 0; background: #eca93b; } timer-countdown .countdown { display: none; } ",e.selector="timer-countdown",e}),define("CatLab/Webremote/Components/SmileyFlingerComponent",["CatLab/Webremote/Views/Blocks/CurrentSmiley"],function(i){function e(e,t,n){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=n,this.smileySlinger=new i(n.Webremote,!0,!0,!1),this.draw()}var t=e.prototype;return t.draw=function(){this.smileySlinger.render(this.element)},t.resize=function(){this.draw()},t.update=function(){this.draw()},t.destroy=function(){},e.css=" ",e.selector="smiley-flinger",e}),define("CatLab/Webremote/Components/CheatDetectionComponent",[],function(){function e(e,t,n){this.element=t,this.remotePlayerView=e,this.componentContainer=n,this._cheatCheckTimer=null,this._hiddenAt=null,e=t.getAttribute("mode"),this._mode="prepare"===e?"prepare":"detect",n=t.getAttribute("report"),this._report=!("false"===n),this._onVisibilityChange=this._handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this._onVisibilityChange),"detect"===this._mode&&this._consumePrepareState()}var t=null,n=e.prototype;return n._consumePrepareState=function(){var e;t&&(e=t,t=null,Date.now()-e.hiddenAt<6e4)&&this._triggerCheatDetected()},n._handleVisibilityChange=function(){document.hidden?(this._hiddenAt=Date.now(),"detect"===this._mode&&(null!==this._cheatCheckTimer&&clearTimeout(this._cheatCheckTimer),this._cheatCheckTimer=setTimeout(function(){this._cheatCheckTimer=null,Date.now()-this._hiddenAt<5e3&&this._triggerCheatDetected()}.bind(this),1500))):(this._hiddenAt=null,"detect"===this._mode&&null!==this._cheatCheckTimer&&(clearTimeout(this._cheatCheckTimer),this._cheatCheckTimer=null))},n._triggerCheatDetected=function(){this._report&&this.componentContainer&&this.componentContainer.Webremote&&this.componentContainer.Webremote.userEvents&&(this.componentContainer.Webremote.userEvents.trigger("cheat:detected",{}),this.componentContainer.Webremote.groupEvents.trigger("cheat:detected",{}))},n.draw=function(){},n.update=function(){},n.destroy=function(){document.removeEventListener("visibilitychange",this._onVisibilityChange),null!==this._cheatCheckTimer&&(clearTimeout(this._cheatCheckTimer),this._cheatCheckTimer=null),"prepare"===this._mode&&null!==this._hiddenAt&&document.hidden&&(t={hiddenAt:this._hiddenAt})},n.resize=function(){},e.selector="cheat-detection",e}),define("CatLab/Webremote/Components/Components",["./ImagePositionInputComponent","./FullscreenButtonComponent","./ViewDefinedComponent","./ModalIframeLink","./TooltipComponent","./VirtualKeyboardComponent","./TimerComponent","./SmileyFlingerComponent","./CheatDetectionComponent"],function(t,n,o,i,r,s,a,l,c){function e(e){this.components=[t,n,i,r,s,a,l,c],this.Webremote=e,this.viewDefinedComponents=[],this.existingComponents=[]}var h=e.prototype;return h.initialize=function(){for(var e=0;e<this.components.length;e++)this.initializeComponent(this.components[e])},h.initializeComponent=function(e){e.css;var t=document.createElement("style");t.attributes.type="text/css",t.innerHTML=e.css,document.head.appendChild(t)},h.resetViewDefinedComponents=function(){for(var e=0;e<this.viewDefinedComponents.length;e++)this.removeComponent(this.viewDefinedComponents[e])},h.destroyExistingComponentsBySelector=function(e){for(var t=this.existingComponents.length-1;0<=t;t--)this.existingComponents[t].constructor&&this.existingComponents[t].constructor.selector===e&&(this.existingComponents[t].destroy(),this.existingComponents.splice(t,1))},h.removeComponent=function(e){this.destroyExistingComponentsBySelector(e);for(var t=0;t<this.components.length;t++)if(this.components[t].selector===e)return void this.components.splice(t,1)},h.addComponent=function(e){0<=this.components.indexOf(e)||(this.components.push(e),this.initializeComponent(e))},h.addViewDefinedComponent=function(e,i){for(var t=0;t<this.components.length;t++)if(this.components[t].selector===e){this.destroyExistingComponentsBySelector(e),this.components.splice(t,1);break}function n(e,t,n){this.element=t,this.remotePlayerView=e,this.position=null,this.content=i,this.componentContainer=n,this.draw()}this.viewDefinedComponents.push(e),((n.prototype=new o).constructor=n).selector=e,n.content=i,this.components.push(n),this.Webremote._currentView&&this.attachComponent(this.Webremote._currentView,document.body,n)},h.attach=function(e,t,n){(n=void 0===n?!0:n)&&(this.existingComponents.forEach(function(e){e.destroy()}.bind(this)),this.existingComponents=[]),this.attachComponents(e,t)},h.resize=function(){this.existingComponents.forEach(function(e){e.resize()}.bind(this))},h.update=function(){this.existingComponents.forEach(function(e){e.update()}.bind(this))},h.attachComponents=function(e,t){for(var n=0;n<this.components.length;n++)try{this.attachComponent(e,t,this.components[n])}catch(e){console.log(e)}},h.attachComponent=function(e,t,n){for(var i=(t instanceof HTMLElement?t:t[0]).querySelectorAll(n.selector),o=0;o<i.length;o++){var r=new n(e,i[o],this);this.existingComponents.push(r)}},e}),!function(){var e,t;e=this,t=function(){var a,l,c,n,e,i=!1,t=window.navigator.userAgent,h=/([+-]?[0-9.]+)(vh|vw|vmin|vmax)/g,o=/(https?:)?\/\//,u=[].forEach,d=/MSIE [0-9]\./i.test(t),f=/MSIE [0-8]\./i.test(t),p=-1<t.indexOf("Opera Mini"),g=/(iPhone|iPod|iPad).+AppleWebKit/i.test(t)&&(e=t.match(/OS (\d)/))&&1<e.length&&parseInt(e[1])<10,m=-1<t.indexOf(" Android ")&&-1<t.indexOf("Version/")&&parseFloat((t.match("Android ([0-9.]+)")||[])[1])<=4.4,d=d||!!navigator.userAgent.match(/MSIE 10\.|Trident.*rv[ :]*1[01]\.| Edge\/1\d\./);try{new v("test")}catch(a){var v=function(e,t){var n;return t=t||{bubbles:!1,cancelable:!1,detail:void 0},(n=document.createEvent("CustomEvent")).initCustomEvent(e,t.bubbles,t.cancelable,t.detail),n};v.prototype=window.Event.prototype,window.CustomEvent=v}function b(){i&&(r(),setTimeout(function(){n.textContent=y(),n.parentNode.appendChild(n),window.dispatchEvent(new v("viewport-units-buggyfill-style"))},1))}function r(){return c=[],u.call(document.styleSheets,function(e){var t=(e=>{try{if(!e.cssRules)return}catch(e){if("SecurityError"!==e.name)throw e;return}for(var t=[],n=0;n<e.cssRules.length;n++){var i=e.cssRules[n];t.push(i)}return t})(e);!t||"patched-viewport"===e.ownerNode.id||"ignore"===e.ownerNode.getAttribute("data-viewport-units-buggyfill")||e.media&&e.media.mediaText&&window.matchMedia&&!window.matchMedia(e.media.mediaText).matches||u.call(t,s)}),c}function s(n){if(7===n.type){var e;try{e=n.cssText}catch(e){return}h.lastIndex=0,h.test(e)&&!o.test(e)&&(c.push([n,null,e]),a.hacks)&&a.hacks.findDeclarations(c,n,null,e)}else n.style?u.call(n.style,function(e){var t=n.style.getPropertyValue(e);n.style.getPropertyPriority(e)&&(t+=" !important"),h.lastIndex=0,h.test(t)&&(c.push([n,e,t]),a.hacks)&&a.hacks.findDeclarations(c,n,e,t)}):n.cssRules&&u.call(n.cssRules,function(e){s(e)})}function y(){var e=window.innerHeight,t=window.innerWidth;l={vh:e,vw:t,vmax:Math.max(t,e),vmin:Math.min(t,e)};var i,o,r=[],s=[];return c.forEach(function(e){var e=function(e,t,n){var i=[];n=n.replace(h,w),a.hacks&&(n=a.hacks.overwriteDeclaration(e,t,n)),t&&(i.push(e.selectorText),n=t+": "+n+";");for(var o=e.parentRule;o;)o.media?i.unshift("@media "+o.media.mediaText):o.conditionText&&i.unshift("@supports "+o.conditionText),o=o.parentRule;return{selector:i,content:n}}.apply(null,e),t=e.selector.length?e.selector.join(" {\n")+" {\n":"",n=new Array(e.selector.length+1).join("\n}");t&&t===i?(t&&!i&&(i=t,o=n),s.push(e.content)):(s.length&&(r.push(i+s.join("\n")+o),s.length=0),t?(i=t,o=n,s.push(e.content)):(r.push(e.content),o=i=null))}),s.length&&r.push(i+s.join("\n")+o),p&&r.push("* { content: normal !important; }"),r.join("\n\n")}function w(e,t,n){n=l[n];return parseFloat(t)/100*n+"px"}function _(e){return e.slice(0,e.indexOf("/",e.indexOf("://")+3))}return{version:"0.6.1",findProperties:r,getCss:y,init:function(e){if(!i){if((a=(e=!0===e?{force:!0}:e)||{}).isMobileSafari=g,a.isBadStockAndroid=m,!a.ignoreVmax||a.force||f||(d=!1),f||!a.force&&!g&&!d&&!m&&!p&&(!a.hacks||!a.hacks.required(a)))return window.console&&f&&console.info("viewport-units-buggyfill requires a proper CSSOM and basic viewport unit support, which are not available in IE8 and below"),{init:function(){}};var t,r,s;window.dispatchEvent(new v("viewport-units-buggyfill-init")),a.hacks&&a.hacks.initialize(a),i=!0,(n=document.createElement("style")).id="patched-viewport",document[a.appendToBody?"body":"head"].appendChild(n),t=function(){function e(){var e=this,t=arguments;clearTimeout(o),o=setTimeout(function(){n.apply(e,t)},i)}var n,i,o;n=b,i=a.refreshDebounceWait||100;window.addEventListener("orientationchange",e,!0),window.addEventListener("pageshow",e,!0),(a.force||d||(()=>{try{return window.self!==window.top}catch(e){return 1}})())&&(window.addEventListener("resize",e,!0),a._listeningToResize=!0),a.hacks&&a.hacks.initializeEvents(a,b,e),b()},r=0,s=function(){--r||t()},u.call(document.styleSheets,function(e){if(e.href&&_(e.href)!==_(location.href)&&"ignore"!==e.ownerNode.getAttribute("data-viewport-units-buggyfill")){r++;var t=e.ownerNode,n=s,e=t.href,i=n,o=new XMLHttpRequest;if("withCredentials"in o)o.open("GET",e,!0);else{if("undefined"==typeof XDomainRequest)throw new Error("cross-domain XHR not supported");(o=new XDomainRequest).open("GET",e)}o.onload=function(){var e=document.createElement("style");e.media=t.media,e.setAttribute("data-href",t.href),e.textContent=this.responseText,t.parentNode.replaceChild(e,t),n()},o.onerror=i,o.send()}}),r||t()}},refresh:b}},"function"==typeof define&&define.amd?define("viewport-units-buggyfill",[],t):"object"==typeof exports?module.exports=t():e.viewportUnitsBuggyfill=t()}(),!function(){var e,t;e=this,t=function(){var s=/calc\(/g,a=/["']/g,e=window.navigator.userAgent,i=(i=/MSIE [0-9]\./i.test(e))||!!navigator.userAgent.match(/MSIE 10\.|Trident.*rv[ :]*1[01]\.| Edge\/1\d\./);return{required:function(e){return e.isMobileSafari||i},initialize:function(){},initializeEvents:function(e,t,n){e.force||i&&!e._listeningToResize&&(window.addEventListener("resize",n,!0),e._listeningToResize=!0)},findDeclarations:function(e,t,n,i){var o,r;null!==n&&(o=e,r=t,e=i,"content"===n)&&-1<e.indexOf("viewport-units-buggyfill")&&e.replace(a,"").split(";").forEach(function(e){var t,e=e.split(":");2===e.length&&"viewport-units-buggyfill"!==(t=e[0].trim())&&(e=e[1].trim(),o.push([r,t,e]),s.test(e))&&(e=e.replace(s,"-webkit-calc("),o.push([r,t,e]))})},overwriteDeclaration:function(e,t,n){return n=i&&"filter"===t?n.replace(/px/g,""):n}}},"function"==typeof define&&define.amd?define("viewport-units-buggyfill.hacks",[],t):"object"==typeof exports?module.exports=t():e.viewportUnitsBuggyfillHacks=t()}(),define("CatLab/Webremote/Controllers/Webremote",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Tracker","CatLab/Webremote/Tools/Cookies","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Preloader","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Views/Popups/AuthenticationPopup","CatLab/Webremote/Views/Popups/SelectSmileyPopup","CatLab/Webremote/Views/Blocks/CurrentUser","CatLab/Webremote/Views/Blocks/CurrentSmiley","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/HashParser","CatLab/Webremote/Tools/Screenfull","CatLab/Webremote/Views/Alert","CatLab/Webremote/Views/Welcome","CatLab/Webremote/Views/ConnectionTrouble","CatLab/Webremote/Views/GamePaused","CatLab/Webremote/Synchronization/ClientRemoteView","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler","CatLab/Webremote/Synchronization/CombinedEventHandler","CatLab/Webremote/Providers/SocketIO","CatLab/Webremote/SonicSync/Client","CatLab/Webremote/Components/Components","viewport-units-buggyfill","viewport-units-buggyfill.hacks"],function(Config,Tracker,Cookies,Tools,Deferred,Smileys,Preloader,OAuth2,AuthenticationPopup,SelectSmileyPopup,CurrentUser,CurrentSmiley,UsersCollection,Storage,i18n,HashParser,screenfull,AlertPopup,WelcomePopup,ConnectionTroubleView,GamePausedView,ClientRemoteView,DataSynchronizer,EventHandler,CombinedEventHandler,SocketIOProvider,SonicSyncClient,Components,ViewportUnitsBuggyFill,ViewportUnitsBuggyFillHacks){var domelement=null,user,dynamicStylesheet,triggers=[];function addEvent(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent?e.attachEvent("on"+t,n):e["on"+t]=n}var Webremote=function(){};function getParameterByName(e,t){t=t||window.location.href,e=e.replace(/[\[\]]/g,"\\$&");e=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)").exec(t);return e?e[2]?decodeURIComponent(e[2].replace(/\+/g," ")):"":null}return Webremote.prototype={provider:null,element:null,gamedata:null,stylesheets:[],links:[],scripts:[],views:{},userData:null,userEvents:null,groupData:null,groupEvents:null,smiley:null,isOauth2Set:!1,color:null,_currentSmileyViews:[],_currentViewId:null,_currentViewViewId:null,_currentViewGroupId:null,_currentView:null,_connectingDfd:null,_connectedToken:null,_headless:!1,_allowAuthentication:!0,token:null,tokenAction:null,confirmTokenConnect:!1,disableConnectConfirmation:!1,initialize:function(e,t){void 0!==(t=void 0===t?{}:t).disableConnectConfirmation&&(this.disableConnectConfirmation=!!t.disableConnectConfirmation),void 0!==t.token?this.token=t.token:(this.token=getParameterByName("token"),this.token||(this.token=getParameterByName("t")),this.token&&!this.disableConnectConfirmation&&(this.confirmTokenConnect=!0),this.tokenAction=getParameterByName("a")),this.setContainer(e),this.showLoading(),this.sonicSync=null,this.components=new Components(this),this.components.initialize(),this._initialize(t).then(function(){setTimeout(function(){void 0===this.provider.showTokenForm||this.provider.showTokenForm?this.confirmTokenConnect?this.showConfirmTokenConnect().then(function(){this.trigger("remote:initialized"),this.handleTokenInput(this.token)}.bind(this)):(this.showTokenForm(),this.trigger("remote:initialized")):this.provider.noTokenConnect()}.bind(this),2),ViewportUnitsBuggyFill.init({hacks:ViewportUnitsBuggyFillHacks})}.bind(this)),this.setPlayerColor("#000000"),this.setOrientation(),addEvent(window,"resize",this.setOrientation.bind(this))},headless:function(e){return(e=void 0===e?{}:e).headless=!0,this._initialize(e)},_initialize:function(t){var n=new Deferred;return Config.set(t),Config.initialize(function(){Tracker.track("App","Initialize"),void 0===t.provider&&(t.provider=new SocketIOProvider),void 0!==t.headless&&(this._headless=!!t.headless),this.provider=t.provider,this.smileys=new Smileys(this.provider),this.provider.initPlayer(this),this.provider.on("disconnect",function(e){var t=this.getConnectionIssuesView();console.log("Connection lost... reconnecting"),t.show(),t.text(i18n.t("Connection lost... reconnecting"))}.bind(this)),this.provider.on("reconnect",function(e){this.provider.emit("user:reconnect",{id:this.gamedata.id,accessToken:this.gamedata.accessToken}),this._resendCurrentUserLogin(),this.getConnectionIssuesView().hide()}.bind(this)),this.provider.on("user:error",function(e){var t;this._connectingDfd&&(t=this._connectingDfd,this._connectingDfd=null,t.reject(e.message))}.bind(this)),this.provider.on("user:initialize",function(e){this.gamedata=e,this.provider.setUserId(e.id),this._storeGameData(e),this._connectingDfd&&(e=this._connectingDfd,this._connectingDfd=null,e.resolve())}.bind(this)),this.provider.on("view:load",function(e){this.loadViewsXML(e.xml)}.bind(this)),this.provider.on("view:reset",function(e){this.resetViews()}.bind(this)),this.provider.on("config:set",function(e){if(Config.set(e),this.sonicSync&&this.sonicSync.stop(),Config.useAudioSync())try{this.sonicSync=new SonicSyncClient(this),this.sonicSync.startListener()}catch(e){console.error(e)}}.bind(this)),this.provider.on("view:set",function(e){this.showView(e.id,e.viewId,e.group),this.handleCombinedMessages(e)}.bind(this)),this.provider.on("button:label",function(e){this.setLabel(e)}.bind(this)),this.provider.on("button:decorate",function(e){this.setClass(e)}.bind(this)),this.provider.on("oauth:set",function(e){Config.supportsAuthentication()&&(OAuth2.initialize(e),this.isOauth2Set=!0,UsersCollection.initialize(this,OAuth2),this.updateUser(),HashParser.getParameter("access_token"))&&(e=HashParser.getParameter("access_token"),UsersCollection.addFromAccessToken(e,function(e){e&&this.setUser(e)}.bind(this)),HashParser.clear())}.bind(this)),this.provider.on("color:set",function(e){this.setPlayerColor(e.color)}.bind(this)),this.provider.on("user:smiley",function(e){this.setSmiley(e.smiley)}.bind(this)),this.provider.on("smileys:taken",function(e){this.smileys.setTakenSmileys(e.smileys)}.bind(this)),this.provider.on("game:disconnect",function(e){AlertPopup(i18n.t("You have been disconnected from the game."),function(){window.location.reload()})}.bind(this)),this.provider.on("dom:append",function(e){this.domAppend(e)}.bind(this)),this.provider.on("dom:replace",function(e){this.domReplace(e)}.bind(this)),this.provider.on("dom:attribute",function(e){this.domAttribute(e)}.bind(this)),this.provider.on("dom:alert",function(e){AlertPopup(e.message)}),this.provider.on("dom:open",function(e){void 0!==e.url&&window.open(e.url)}),this.provider.on("value:change",function(e){this.changeValue(e)}.bind(this)),this.provider.on("device:vibrate",function(e){this.vibrate(e)}.bind(this)),this.provider.on("game:pause",function(e){this.pause(e)}.bind(this)),this.provider.on("game:unpause",function(e){this.unpause(e)}.bind(this)),this.preloader=new Preloader(this.provider),this.userData=new DataSynchronizer("user",this.emit.bind(this),"client"),this.groupData=new DataSynchronizer("group",this.emit.bind(this),"client"),this.userEvents=new EventHandler("user",this.emit.bind(this)),this.groupEvents=new EventHandler("group",this.emit.bind(this));var e=[this.userData,this.groupData],i=[this.userEvents,this.groupEvents];DataSynchronizer.eventsToListenFor.forEach(function(n){this.provider.on(n,function(t){e.forEach(function(e){e.checkNamespace(t)&&e.processMessage(n,t)})}.bind(this))}.bind(this)),EventHandler.eventsToListenFor.forEach(function(n){this.provider.on(n,function(t){i.forEach(function(e){e.checkNamespace(t)&&e.processMessage(n,t)})}.bind(this))}.bind(this)),this.events=new CombinedEventHandler,this.events.addHandler(this.userEvents),this.events.addHandler(this.groupEvents),n.resolve()}.bind(this)),n.promise()},reconnect:function(e){this.gamedata?(this.provider.emit("user:reconnect",{id:this.gamedata.id,accessToken:this.gamedata.accessToken}),this.provider.once("user:reconnect",function(){e()})):e()},connectProvider:function(e){return this.provider.tokenConnect(e)},_storeGameData:function(){var e=new Deferred,t=this._connectedToken;return Storage.set("gamestate_"+t,this.gamedata,function(){e.resolve()},864e5),e.promise()},_restoreGameData:function(){var t=new Deferred,e=this._connectedToken;return Storage.get("gamestate_"+e,function(e){e?(this.gamedata=e,t.resolve(!0)):t.resolve(!1)}.bind(this)),t.promise()},handleCombinedMessages:function(e){for(var t=[{name:"button:label",method:this.setLabel.bind(this)},{name:"button:decorate",method:this.setClass.bind(this)}],n=0;n<t.length;n++){var i=t[n].name,o=t[n].method;if(void 0!==e[i])for(var r=0;r<e[i].length;r++)o(e[i][r])}},emit:function(e,t){this.provider.toMaster(e,t)},getConnectionIssuesView:function(){return void 0===this.connectionTrouble&&(this.connectionTrouble=new ConnectionTroubleView),this.connectionTrouble},setGamePausedView:function(e){this.gamePaused=e},getGamePausedView:function(){return void 0===this.gamePaused?new GamePausedView:this.gamePaused},setContainer:function(e){domelement=e,this.element=e,dynamicStylesheet=document.createElement("style"),document.body.appendChild(dynamicStylesheet),document.body.className="catlab-remote"},on:function(e,t){void 0===triggers[e]&&(triggers[e]=[]),triggers[e].push(t)},trigger:function(e){var t=[].slice.apply(arguments);if(t.shift(),void 0!==triggers[e])for(var n=0;n<triggers[e].length;n++)triggers[e][n].apply(this,t)},loadViews:function(e,t){var n;t=t||function(){},this._headless?t():((n=new XMLHttpRequest).open("GET",Config.getProxy()+e,!0),n.onreadystatechange=function(){4==n.readyState&&200==n.status&&(this.loadViewsXML(n.responseText),t())}.bind(this),n.send())},resetViews:function(){this.showViewLoadingOverlay(),this.views={},this.components.resetViewDefinedComponents();for(var e=0;e<this.stylesheets.length;e++)try{var t=this.stylesheets[e];t.parentNode&&t.parentNode.removeChild(t)}catch(e){console.error(e)}for(e=0;e<this.links.length;e++)try{var n=this.links[e];n.parentNode&&n.parentNode.removeChild(n)}catch(e){console.error(e)}this.stylesheets=[]},injectXmlns:function(e){return e.replace(/<views(\s[^>]*)?>/,function(e){return/\bxmlns\s*=/.test(e)?e:e.replace("<views",'<views xmlns="http://www.w3.org/1999/xhtml"')})},loadViewsXML:function(e,t){if(t=t||function(){},!this._headless){var n;if(Tracker.track("App","Load Views"),e=this.injectXmlns(e),window.DOMParser?n=(new DOMParser).parseFromString(e,"text/xml"):((n=new ActiveXObject("Microsoft.XMLDOM")).async=!1,n.loadXML(e)),0===n.getElementsByTagName("views").length)return!1;for(var i=n.getElementsByTagName("views").item(0).getElementsByTagName("component"),o=0;o<i.length;o++)this.loadComponent(i.item(o));for(var r=n.getElementsByTagName("views").item(0).getElementsByTagName("view"),o=0;o<r.length;o++)this.loadView(r.item(o));var s=n.getElementsByTagName("views").item(0).getElementsByTagName("stylesheet");for(o=0;o<s.length;o++){var a=s.item(o),l=document.createElement("style");this.stylesheets.push(l),l.innerHTML=a.textContent,document.body.appendChild(l)}var c=n.getElementsByTagName("views").item(0).getElementsByTagName("link");for(o=0;o<c.length;o++){var h=c.item(o).getAttribute("href"),u=document.createElement("link");u.rel="stylesheet",u.type="text/css",u.media="all",u.href=h,this.links.push(u),document.getElementsByTagName("head")[0].appendChild(u)}for(s=n.getElementsByTagName("views").item(0).getElementsByTagName("style"),o=0;o<s.length;o++)this.stylesheets.push(s.item(o)),document.body.appendChild(s.item(o));var d=n.getElementsByTagName("views").item(0).getElementsByTagName("script");for(o=0;o<d.length;o++)this.scripts.push(d.item(o)),this.evalScript(d.item(o));return ViewportUnitsBuggyFill.refresh(),t(),!0}t()},evalScript:function(xml){var aWebremote=Webremote;!function(){try{var Webremote=aWebremote;eval(xml.textContent)}catch(e){console.error(e)}}.bind(window)()},loadView:function(e){var t=e.getAttribute("id"),n=document.createElement("div"),i=!1;e.getAttribute("iframe")&&"false"!==e.getAttribute("iframe").toLowerCase()&&(i=!0);for(var o=0;o<e.childNodes.length;o++)n.appendChild(e.childNodes[o].cloneNode(!0));n.id=t,n.className="view "+e.className,this.views[t]={iframe:i,html:(new XMLSerializer).serializeToString(n)},this._currentViewId===t&&this.showView(this._currentViewId,this._currentViewViewId,this._currentViewGroupId)},loadComponent:function(e){for(var t=e.getAttribute("id"),n=document.createElement("div"),i=0;i<e.childNodes.length;i++)n.appendChild(e.childNodes[i].cloneNode(!0));this.components.addViewDefinedComponent(t,n)},showView:function(e,t,n){var i,o;this._headless||(this._currentView&&this._currentView.destroy(),"remote:authenticate"!==e?(this._currentViewId=e,this._currentViewViewId=t,this._currentViewGroupId=n,void 0!==this.views[e]?(i=(n?this.groupData:this.userData).getFromIdentifier("view:"+t),o=this.views[e],this._currentView=new ClientRemoteView(this,t,e,n,i,o.iframe),this._currentView.html=o.html,this._currentView.render(this.element),this.hideViewLoadingOverlay(),this.updateUser(),Tracker.track("App","Show View",e),this.trigger("remote:view:show",{id:e,view:this._currentView}),this.trigger("view:set",this._currentView)):this.element.innerHTML='<div class="loading"><p>Please wait, loading...</p><p>(Loading view: '+e+")</div></p>"):this.showAuthenticationView())},updateUser:function(){Tracker.track("App","Set user");var e=document.getElementById("authentication");e&&new CurrentUser(this).render(e),this._currentSmileyViews=[],Config.useSmileys()?(this.setSmileySelectViews(),this.setSmileyViews()):this.removeSmileyViews()},setSmileySelectViews:function(){for(var e=document.getElementsByTagName("smiley-select"),t=0;t<e.length;t++){var n=!e[t].hasAttribute("flingable")||"false"!==e[t].getAttribute("flingable"),n=new CurrentSmiley(this,!0,n);n.render(e[t]),this.smiley&&n.setSmiley(this.smiley),this._currentSmileyViews.push(n)}},setSmileyViews:function(){for(var e=document.getElementsByTagName("smiley"),t=0;t<e.length;t++){var n=e[t].hasAttribute("changeable")&&"false"!==e[t].getAttribute("changeable"),i=e[t].hasAttribute("flingable")&&"false"!==e[t].getAttribute("flingable"),n=new CurrentSmiley(this,n,i);n.render(e[t]),this.smiley&&n.setSmiley(this.smiley),this._currentSmileyViews.push(n)}},removeSmileyViews:function(){for(var e=document.getElementsByTagName("smiley-select"),t=0;t<e.length;t++)e[t].parentNode.removeChild(e[t]);for(e=document.getElementsByTagName("smiley"),t=0;t<e.length;t++)e[t].parentNode.removeChild(e[t]);for(var n=document.getElementsByClassName("if-config-smileys"),t=0;t<n.length;t++)n[t].parentNode.removeChild(n[t])},popup:function(e){new WelcomePopup(e).render(domelement)},showAuthenticationPopup:function(e){e=e||!1;var t=new AuthenticationPopup(this);t.render(domelement),e&&t.connect()},showSmileyPopup:function(e,t){void 0===e&&(e=function(e){this.selectSmiley(e)}.bind(this)),void 0===t&&(t=!0);for(var n=domelement.querySelectorAll(".catlab-popup-container"),i=0;i<n.length;i++)n[i].parentNode.removeChild(n[i]);new SelectSmileyPopup(this,e,t).render(domelement)},showAuthenticationView:function(){Cookies.removeItem("last_token"),this.element&&(this.element.innerHTML='<p id="catlab-message">'+i18n.t("Please login.")+"</p>",OAuth2.link({fullscreen:!0}).then(function(e){e?(this.setUser(e),this.element.innerHTML='<p id="catlab-message">'+i18n.t("Welcome! You may now close this screen.")+"</p>",this.provider.disconnect(!1),window.close()):this.showAuthenticationView()}.bind(this)))},buttonDown:function(e,t){this.provider.toMaster("button:down",{id:e})},buttonUp:function(e,t,n){this.provider.toMaster("button:up",{id:e,click:n=void 0!==n&&n}),this.trigger("user:interaction")},syncValue:function(e,t,n){return this.provider.toMaster("value:change",{id:e,value:t,viewId:n}),!1},showLoading:function(){this.element&&(this.element.innerHTML='<p id="catlab-loading">Connecting...</p>')},showViewLoadingOverlay:function(){var e;this._headless||(this.hideViewLoadingOverlay(),(e=document.createElement("div")).id="catlab-view-loading-overlay",e.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;background:#000;display:flex;align-items:center;justify-content:center;z-index:99999;color:#fff;font-family:Arial,Helvetica,sans-serif;font-size:1.5em;",e.innerHTML="<p>Loading...</p>",document.body.appendChild(e))},hideViewLoadingOverlay:function(){var e=document.getElementById("catlab-view-loading-overlay");e&&e.parentNode&&e.parentNode.removeChild(e)},showConfirmTokenConnect:function(){var n=new Deferred,e=document.createElement("form"),t=(this.element.innerHTML="",this.element.appendChild(e),document.createElement("div")),i=(t.id="catlab-token-form",e.appendChild(t),document.createElement("h1")),i=(i.innerHTML=i18n.t("Welcome!"),t.appendChild(i),document.createElement("button"));return"l"===this.tokenAction?i.innerHTML=i18n.t("Login"):i.innerHTML=i18n.t("Join game"),i.type="submit",i.className="pulsating",t.appendChild(i),e.onsubmit=function(e){e.preventDefault();try{var t=(t=window.location.search.replace(/[?&]t=([^&]*)/gi,"")).replace(/[?&]token=([^&]*)/gi,"");window.history.pushState({},document.title,window.location.pathname+t+window.location.hash)}catch(e){}n.resolve()},n.promise()},showTokenForm:function(){var e=document.createElement("form"),t="undefined"!=typeof CONFIG_TOKEN?CONFIG_TOKEN:null,n=(!t&&this.token&&(t=this.token,this.token=null),!1),i=(t&&(n=!0),Cookies.getItem("last_token")),i=(!t&&i&&(t=i),document.createElement("div")),o=(i.id="catlab-token-form",e.innerHTML="",e.appendChild(i),document.createElement("input")),o=(o.type="tel",o.pattern="[0-9 ]{6,10}",o.name="token",o.id="token",o.value=t||"",o.placeholder=i18n.t("Enter code"),o.addEventListener("click",function(){this.setSelectionRange(0,this.value.length)}),i.appendChild(o),document.createElement("button"));o.innerHTML=i18n.t("Connect"),i.appendChild(o),n&&this.handleTokenInput(t),e.onsubmit=function(e){e.preventDefault();e=document.getElementById("token").value;if(e)return this.handleTokenInput(e),!1}.bind(this),this.element.innerHTML="",this.element.appendChild(e)},handleTokenInput:function(e){var t=this.connect(e);e!==Cookies.getItem("last_token")&&Cookies.removeItem("last_token"),t.then(function(){Cookies.setItem("last_token",e,.25)}.bind(this)),t.fail(function(e){this.showTokenForm(),screenfull.enabled&&screenfull.isFullscreen&&screenfull.exit(),AlertPopup(e)}.bind(this)),this.showLoading(),this.trigger("remote:token:submit"),this.trigger("user:interaction")},requestFullScreen:function(){screenfull.enabled&&!screenfull.isFullscreen&&screenfull.request()},connect:function(e){return e=e.replace(" ",""),null!==this._connectingDfd&&(this._connectingDfd.reject(),this._connectingDfd=null),this._connectingDfd=new Deferred,this._connectedToken=e,this._connectingDfd.fail(function(){this.provider.disconnect(!1)}.bind(this)),this.connectProvider(e).fail(function(){setTimeout(function(){this._connectingDfd.reject(i18n.t("Game not found. Please check your token."))}.bind(this),1)}.bind(this)).then(function(t){var n=!0;"0"===getParameterByName("reconnect")&&(n=!1),this._restoreGameData().then(function(e){e&&n?this.reconnect(function(){this._connectingDfd.resolve()}.bind(this)):this.provider.emit("user:join",{token:t})}.bind(this))}.bind(this)),this._connectingDfd.promise()},setLabel:function(e){this._currentView&&this._currentView.setLabel(e.id,Tools.nl2br(Tools.sanitize(e.label)))},setClass:function(e){this._currentView&&this._currentView.setClass(e.id,e.styles)},setPlayerColor:function(e){if(this.color=e,void 0!==dynamicStylesheet&&dynamicStylesheet){var t,n,i="",o=(dynamicStylesheet.innerHTML=(i+=".player-color-border { border-color:"+e+"; }")+(".player-color-background { background-color: "+e+"; }")+(".player-color { color: "+e+"; }"),{"theme-color":e,"msapplication-navbutton-color":e,"apple-mobile-web-app-status-bar-style":e});for(t in o)o.hasOwnProperty(t)&&((n=document.createElement("meta")).httpEquiv=t,n.content=o[t],document.getElementsByTagName("head")[0].appendChild(n))}},setSmiley:function(t){this.smiley=t,this._currentSmileyViews.forEach(function(e){e.setSmiley(t)})},getSmiley:function(){return this.smiley},selectSmiley:function(e){this.provider.toMaster("user:smiley",{smiley:e})},setUser:function(e){user=e,this.updateUser(),user?(this.provider.toMaster("user:login",{access_token:user.getAccessToken()}),Storage.set("currentuser",user.getAccessToken()),this.getSmiley()&&(e=user.getAvatarSmiley())&&this.selectSmiley(e)):(this.provider.toMaster("user:logout"),Storage.set("currentuser",null))},getUser:function(){return user},_resendCurrentUserLogin:function(){user&&this.provider.toMaster("user:login",{access_token:user.getAccessToken()})},listViews:function(){var e,t=[];for(e in this.views)this.views.hasOwnProperty(e)&&t.push({name:e});return t},getRandomText:function(e,t){var n="abcdefghijklmnopqrstuvwyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";void 0===t&&(t=40);for(var i="",o=(e=void 0===e?10:e)+Math.random()*t,r=0;r<o;r++)i+=n.charAt(Math.floor(Math.random()*n.length)),.8<Math.random()&&(r++,i+=" ");return i},randomLabels:function(e,t){for(var n=domelement.querySelectorAll("[data-button-label]"),i=0;i<n.length;i++)n[i].innerHTML=this.getRandomText(e,t);this.update()},setOrientation:function(){if(window.innerHeight>=window.innerWidth)try{document.body.classList.remove("landscape"),document.body.classList.add("portrait")}catch(e){document.body.className="portrait"}else try{document.body.classList.add("landscape"),document.body.classList.remove("portrait")}catch(e){document.body.className="landscape"}this.components.resize()},domAppend:function(e){this._currentView&&(this._currentView.domAppend(e.id,e.html),this.components.update())},domReplace:function(e){this._currentView&&(this._currentView.domReplace(e.id,e.html),this.components.update())},domAttribute:function(e){this._currentView&&(this._currentView.domAttribute(e.id,e.name,e.value),this.components.update())},changeValue:function(e){this._currentView&&this._currentView.changeValue(e)},vibrate:function(e){this._currentView&&this._currentView.vibrate(e)},pause:function(e){void 0===this._gamePausedView&&(this._gamePausedView=this.getGamePausedView()),this._gamePausedView.show()},unpause:function(e){void 0!==this._gamePausedView&&this._gamePausedView.hide()},log:function(e){Config.debug()&&console.log(e)},canAuthenticate:function(){return this.isOauth2Set},getGroupIds:function(){return void 0===this.gamedata.groups?[]:this.gamedata.groups},resolveDataAttribute:function(e){if("token"===e)return this._connectedToken;var n,e=(e="data."===e.substring(0,5)?e.substring(5):e).split("."),t=(2!==e.length&&e.unshift("any"),e.shift()),e=e.shift();if(t===user)return this.userData.getFromIdentifier("user").get(e);if("group"===t.substring(0,5)){var i,o=this.getGroupIds();if(0===o.length)return null;if("group"===t)return this.groupData.getFromIdentifier("group:"+o[0]).get(e);if("]"===t.substring(t.length,1))return void 0===o[i=t.substr(t.substring(6,t.length-1))]?null:this.groupData.getFromIdentifier("group:"+o[i]).get(e)}return"any"===t&&(n=["user."+e],this.getGroupIds().forEach(function(e,t){n.push("group["+t+"]")}.bind(this))),null}},Webremote}),define("CatLab/Webremote/Tools/Colorwheel",[],function(){var e={index:0,colors:[{color:"#d84a38",name:"red"},{color:"#4d90fe",name:"blue"},{color:"#35aa47",name:"green"},{color:"#ffb848",name:"yellow"},{color:"#852b99",name:"purple"},{color:"#555555",name:"brown"},{color:"#F87217",name:"orange"},{color:"#FBBBB9",name:"pink"}],initialize:function(){this.index=Math.floor(Math.random()*this.colors.length)},next:function(){var e=this.colors[this.index%this.colors.length];return this.index++,e}};return e.initialize(),e}),define("CatLab/Webremote/Collections/Users",["CatLab/Webremote/Tools/Colorwheel"],function(n){return function(){this.users=[],this.userMap={},this.externalPlayerOffset=0,this.setExternalPlayerOffset=function(e){this.externalPlayerOffset=e||0},this.add=function(e){var t;e.isColorSet()||(t=n.next(),e.setColor(t.color,t.name)),e.hasPlayerId()||e.setPlayerId(this.externalPlayerOffset+this.count()+1),this.users.push(e),this.userMap[e.getId()]=e},this.clear=function(){this.users=[],this.userMap={}},this.remove=function(e){this.users.splice(users.indexOf(e),1),void 0!==this.users[e.getId()]&&delete this.users[e.getId()]},this.getFromId=function(e){return void 0!==this.userMap[e]?this.userMap[e]:null},this.getAll=function(){return this.users},this.count=function(){return this.users.length},this.each=function(e){for(var t=0;t<this.users.length;t++)e(this.users[t])},this.not=function(n){var i=[];return this.each(function(e){for(var t=0;t<n.length;t++)if(n[t].getId()===e.getId())return void i.push(n[t])}),i}}}),define("CatLab/Webremote/Collections/Groups",["CatLab/Webremote/Tools/Colorwheel"],function(n){return function(){var t;this.groups=[],this.groupMap={},this.add=function(e){var t;e.colorSet||(t=n.next(),e.setColor(t.color,t.name)),this.groupMap[e.getId()]=e,this.groups.push(e)},this.clear=function(){this.groups=[],this.groupMap=[]},this.addUser=function(t){var n=!1;return t.groupIds.forEach(function(e){e=this.getFromId(e);e&&(n=!0,e.addUser(t),e.isShareColor())&&t.setColor(e.getColor(),e.getColorName())}.bind(this)),n},this.remove=function(e){this.groups.splice(this.groups.indexOf(e),1),delete this.groupMap[e.getId()]},this.getFromId=function(e){return void 0!==this.groupMap[e]?this.groupMap[e]:null},this.getAll=function(){return this.groups},this.each=function(e){for(t=0;t<this.groups.length;t++)e(this.groups[t])}}}),define("CatLab/Webremote/Models/ControlBase",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred"],function(e,o){function t(){}e=t.prototype=new e;return e.initializeControlBase=function(){this.initializeEventable()},e.resetViews=function(e){var t=new o;return this.emit("view:reset",{},function(){void 0!==e&&e(),t.resolve()}),t.promise()},e.replaceViews=function(e,t,n){var i=new o;return this.resetViews(function(){this.loadViews(e,t,function(){void 0!==n&&n(),i.resolve()})}.bind(this)),i.promise()},e.loadViews=function(e,t,n){return this.Webcontrol.provider.loadViews(e,n,this).then(function(){void 0!==t&&t()})},e.parseViews=function(e,t,n){return this.Webcontrol.provider.parseViews(e,t,this).then(function(){void 0!==n&&n()})},e.registerComponent=function(e,t){return this.Webcontrol.provider.registerComponent(e,t,this)},t}),define("CatLab/Webremote/Models/Control",[],function(){return function(n,i,e){var o,r,s,a,l=0,c={},h=n,u=[];this.id=n,this.decoration="",this.label="",this.isGlobal=e,this.pushed=function(){return 0===l},this.scale=function(){return l},this.update=function(e,t){0<l&&0===e?((t=void 0===t?!0:t)&&this.trigger("click"),this.trigger("up")):0===l&&0<e&&this.trigger("down"),l=e},this.getLabel=function(e){return(e=void 0===e?!0:e)?'<span class="control-label '+r+'">'+h+"</span>":h},this.setStaticLabel=function(e,t,n,i){return h=e,r=t,s=n,a=i,this},this.getLabelImage=function(){return s},this.getLabelEmoji=function(){return a},this.getLabelData=function(){return{label:h,type:r,image:s,emoji:a}},this.setLabel=function(e,t){return this.label=e,i.emit("button:label",{id:n,label:e}),this},this.decorate=function(e){return this.decoration=e,i.emit("button:decorate",{id:n,styles:e}),this},this.click=function(e){return this.on("click",e),this},this.on=function(e,t){return this.log("Setting trigger "+e),void 0===c[e]&&(c[e]=[]),c[e].push(t),this},this.trigger=function(e){this.log("Triggering "+e);var t=[];if(void 0!==c[e])for(this.log("Found "+c[e].length+" events"),o=0;o<c[e].length;o++)t.push(c[e][o]);for(o=0;o<t.length;o++)t[o](i);return this},this.hasTriggers=function(e){return void 0===e?0<Object.keys(c).length:void 0!==c[e]&&0<c[e].length},this.off=function(e,t){if(void 0===e)c={};else if(void 0===t)c[e]=[];else if(void 0!==c[e])for(o=0;o<c[e].length;o++)c[e][o]===t&&(c[e].splice(o,1),o--);return this},this.clear=function(){return this.clearEvents(),this.decoration=null,this.label=null,this},this.clearEvents=function(){return c={},this},this.addDomElement=function(e){var t=this,n=[];return n.push(e.addEventListener("click",function(){t.trigger("click")})),u.push({element:e,listeners:n}),this},this.clearDomElements=function(){for(var e=0;e<u.length;e++)for(var t=0;t<u[e].listeners.length;t++)u[e].element.removeEventListener("click",u[e].listeners[t]);return u=[],this},this.isLocalAuthentication=function(){return!1},this.refreshTarget=function(e){this.decoration&&e.emit("button:decorate",{id:n,styles:this.decoration}),this.label&&e.emit("button:label",{id:n,label:this.label})},this.log=function(e){i.log("["+this.id+"] "+e)}}}),define("CatLab/Webremote/Synchronization/MultipleTargetControl",[],function(){function e(e,t){this.id=e,this.remoteView=t,this.label=null,this.decoration=null}var t=e.prototype;return t.pushed=function(){var t=[];return this.remoteView.targets.forEach(function(e){t=t||e.control(this.id).pushed()}.bind(this)),t},t.scale=function(){var t,n=0;this.remoteView.targets.forEach(function(e){(t=e.scale())>n&&(n=t)}.bind(this))},t.update=function(t){this.remoteView.targets.forEach(function(e){e.control(this.id).update(t)}.bind(this))},t.getLabel=function(){return this.label},t.setLabel=function(t){return this.label=t,this.remoteView.targets.forEach(function(e){e.control(this.id).setLabel(t)}.bind(this)),this},t.decorate=function(t){return this.decoration=t,this.remoteView.targets.forEach(function(e){e.control(this.id).decorate(t)}.bind(this)),this},t.click=function(e){return this.on("click",e),this},t.on=function(t,n){return this.remoteView.targets.forEach(function(e){e.control(this.id).on(t,n)}.bind(this)),this},t.off=function(e){var t=arguments;return this.remoteView.targets.forEach(function(e){e.control(this.id).off.apply(e.control(this.id),t)}.bind(this)),this},t.refreshTarget=function(t){return this.remoteView.targets.forEach(function(e){e.control(this.id).refreshTarget(t)}.bind(this)),this},e}),define("CatLab/Webremote/Synchronization/RemoteView",["CatLab/Webremote/Models/Control","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Synchronization/MultipleTargetControl","CatLab/Webremote/Synchronization/DataSynchronizer"],function(e,t,n,i){function o(e,t,n,i,o){this.initializeEventable(),this.id=t,this.viewId=e,this.targets=[],this.Webcontrol=i,this.groupId=void 0!==o?o:null,this.controls={},this.valueMap={},this.newUserStack=[],this.factory=null,this.listeners=[],n.map(function(e){this.addTarget(e)}.bind(this))}t=o.prototype=new t;return t.clearValues=function(){this.valueMap={}},t.addTarget=function(e){this.targets.push(e),this.refreshTarget(e)},t.refreshTarget=function(t){var e,n={id:this.id,viewId:this.viewId};for(this.tmpid in this.groupId&&(n.group=this.groupId),t.emit("view:set",n),this.newUserStack.map(function(e){t.emit(e.action,e.data)}.bind(this)),t.controls)t.controls.hasOwnProperty(this.tmpid)&&t.controls[this.tmpid].isGlobal&&t.controls[this.tmpid].refreshTarget(t);for(this.tmpid in this.controls)this.controls.hasOwnProperty(this.tmpid)&&(void 0!==this.controls[this.tmpid].refreshTarget?this.controls[this.tmpid].refreshTarget(t):console.error("Unexpected control:",this.controls[this.tmpid]));for(e in this.valueMap)this.valueMap.hasOwnProperty(e)&&t.emit("value:change",{id:e,value:this.valueMap[e]})},t.emit=function(t,n){this.targets.map(function(e){e.emit(t,n)})},t.clearControls=function(){for(var e=this.Webcontrol.getViewLabels(this.currentView),t=0;t<e.length;t++)this.control(e[t].id).setStaticLabel(e[t].label,"mobile")},t.control=function(e){return void 0===this.controls[e]&&(this.controls[e]=new n(e,this)),this.controls[e]},t.trigger=function(e,t){"value:change"==e&&this.changeValue(t.id,t.value)},t.changeValue=function(e,t){this.valueMap[e]=t,this.emit("value:change",{id:e,value:t}),this.eventableTrigger("value:change",e,t)},t.refreshControls=function(){for(this.tmpid in this.controls)this.controls.hasOwnProperty(this.tmpid)&&this.controls[this.tmpid].refreshControl()},t.getValues=function(){return this.valueMap},t.log=function(e){this.Webcontrol.log(e)},t.domAppend=function(e,t){this._stackAndEmit("dom:append",{id:e,html:t})},t.domReplace=function(t,e){this._clearStack(function(e){return("dom:append"===e.action||"dom:replace"===e.action)&&e.data.id===t}),this._stackAndEmit("dom:replace",{id:t,html:e})},t.domAttribute=function(t,n,e){this._clearStack(function(e){return"dom:attribute"===e.action&&e.data.id===t&&e.data.name===n}),this._stackAndEmit("dom:attribute",{id:t,name:n,value:e})},t.vibrate=function(e){Array.isArray(e)?this.emit("device:vibrate",{pattern:e}):console.error("Vibrate pattern must be an array.")},t.listenTo=function(e,t,n){this.listeners.push(e.on(t,n))},t.stopListening=function(){this.listeners.forEach(function(e){e.unbind()})},t._clearStack=function(t){this.newUserStack=this.newUserStack.filter(function(e){return!t(e)})},t._stackAndEmit=function(e,t){this.newUserStack.push({action:e,data:t}),this.emit(e,t)},t.destroy=function(){this.stopListening(),this.factory.destroy(this)},o}),define("CatLab/Webremote/Synchronization/RemoteViewFactory",["CatLab/Webremote/Synchronization/RemoteView"],function(o){function e(){this.viewCounter=0,this.views={}}var t=e.prototype;return t.create=function(e,t,n,i){return this.viewCounter++,this.views[this.viewCounter]=new o(this.viewCounter,e,t,n,i),(this.views[this.viewCounter].factory=this).views[this.viewCounter]},t.createDummy=function(e,t){return this.create(e,[],t)},t.getFromId=function(e){return this.views[e]},t.destroy=function(e){e=e.id;delete this.views[e]},new e}),define("CatLab/Webremote/Models/Users/ControlUser",["CatLab/Webremote/Models/ControlBase","CatLab/Webremote/Models/User","CatLab/Webremote/Models/Control","CatLab/Webremote/Synchronization/RemoteViewFactory","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler"],function(e,t,n,i,o,r,s,a){function l(e,t){this.initializeControlBase(),(t=void 0===t?{}:t).id=e,t.playerId=null,this.initialize(t)}e=l.prototype=new e;return e.hasPlayerId=function(){return 0<this.playerId},e.setPlayerId=function(e){return this.playerId=e,this},e.control=function(e,t){return void 0===t&&(t=!1),void 0===this.controls[e]&&(this.controls[e]=new n(e,this,t)),this.controls[e]},e.getAvailableControls=function(){return["a","b","x","y","up","down","right","left","start","back"]},e.hasControl=function(e){return!0},e.setWebcontrol=function(e){this.Webcontrol=e},e.initialize=function(e){this.id=e.id,e.playerId&&(this.playerId=e.playerId),this.groups=[],this.currentView=null,this.color="orange",this.colorName="orange",this.colorSet=!1,this.tmpid=null,this.active=!1,this.smiley=null,this.email=null,this.nickname=null,this.userdata=e,this.profiledata={},this.access_token=null,this.user=null,this.master=!1,this.authenticated=!1,void 0!==e&&void 0!==e.groups?this.groupIds=e.groups:this.groupIds=[],this.controls={},this.dataSynchronizer=new s("user",this.emit.bind(this),"master"),this.data=this.dataSynchronizer.getFromIdentifier("user"),this.events=new a("user",this.emit.bind(this)),this.settings={}},e.setSettings=function(e){return this.settings=e,this},e.trigger=function(t,n){0<=s.eventsToListenFor.indexOf(t)?(this.dataSynchronizer.checkNamespace(n)&&this.dataSynchronizer.processMessage(t,n),this.getGroups().forEach(function(e){e.dataSynchronizer.checkNamespace(n)&&e.dataSynchronizer.processMessage(t,n)}.bind(this))):0<=a.eventsToListenFor.indexOf(t)?(this.events.checkNamespace(n)&&this.events.processMessage(t,n),this.getGroups().forEach(function(e){e.events.checkNamespace(n)&&e.events.processMessage(t,n)}.bind(this))):"button:down"===t?this.control(n.id).update(1):"button:up"===t?this.control(n.id).update(0,n.click):"user:login"===t?this.login(n):"user:logout"===t?this.logout(n):"user:smiley"===t?this.setSmiley(n.smiley):"sync:audio"===t&&this.eventableTrigger("sync:audio",n)},e.setSmiley=function(t){this.smiley=t;var n=null;this.getGroups().forEach(function(e){n=!0,e.setSmiley(t,this)}.bind(this)),n||this.Webcontrol.smileys.reserve(t,this.getIdentifier())?this.emit("user:smiley",{smiley:t}):this.emit("dom:alert",{message:o.t("Smiley is already taken. Please select a different smiley.")})},e.setNickname=function(e){return this.nickname=e,this.eventableTrigger("user:nickname",e),this},e.getNickname=function(){var e=this.getData();return this.nickname||(e&&e.username?e.username:this.playerId?"Player "+this.playerId:"Player "+this.id)},e.clearSmiley=function(){this.smiley=null,this.getGroups().forEach(function(e){e.clearSmiley(this)}.bind(this)),this.emit("user:smiley",{smiley:null})},e.getSmiley=function(){return this.smiley},e.getSmileyImage=function(){return this.Webcontrol.smileys.getImage(this.getSmiley())},e.getSmileyHtml=function(){return this.Webcontrol.smileys.getHtml(this.getSmiley())},e.getSmileyUrl=function(){return this.Webcontrol.smileys.getUrl(this.getSmiley())},e.login=function(e){},e.logout=function(e){},e.clearControls=function(){for(this.tmpid in this.setStaticLabels(),null!==this.currentView&&this.currentView.clearControls(),this.controls)!this.controls.hasOwnProperty(this.tmpid)||this.controls[this.tmpid].isGlobal||this.controls[this.tmpid].clear()},e.setStaticLabels=function(){},e.clearEvents=function(){this.clearControls(),this.clearEventableEvents()},e.emit=function(e,t,n){return this.Webcontrol.provider.toPlayer(this,e,t,n),!0},e.getId=function(){return this.id},e.getName=function(){return"User "+this.getId()},e.getType=function(){return"mobile"},e.getEntityType=function(){return"user"},e.getIcon=function(){return"fa fa-mobile-phone"},e.loginFromAuthUser=function(e,t){e={access_token:e.getAccessToken()};this.login(e,t)},e.login=function(t,n){var i=this;this._pendingLogin=null,this.Webcontrol.getOAuthClient(function(e){e?(this.setAccessToken(t.access_token),e.profile(i.access_token,function(e,t){e&&e.user?(i.authenticated=!0,this.setProfiledata(e.user),void 0!==n&&n()):(i.authenticated=!1,i.eventableTrigger("login:failed",i,t),void 0!==n&&((e=new Error("Could not load user profile"+(t?" ("+t+")":""))).status=t,n(e)))}.bind(this))):this._pendingLogin={data:t,callback:n}}.bind(this))},e.flushPendingLogin=function(){var e;this._pendingLogin&&(e=this._pendingLogin,this._pendingLogin=null,this.login(e.data,e.callback))},e.setAccessToken=function(e){this.access_token=e},e.getAccessToken=function(){return this.access_token},e.setProfiledata=function(e){e=void 0!==(this.profiledata=e).accessToken?e.accessToken:null,e=new t(e);void 0!==this.profiledata.id&&e.setId(this.profiledata.id),void 0!==this.profiledata.username&&e.setName(this.profiledata.username),void 0!==this.profiledata.avatar&&e.setAvatar(this.profiledata.avatar),this.setUser(e),this.eventableTrigger("login",this),this.eventableTrigger("user:nickname",this.getNickname())},e.isAuthenticated=function(){return this.authenticated},e.getData=function(){return this.profiledata},e.logout=function(e){this.profiledata=null,this.access_token=null,this.authenticated=!1},e.setColor=function(e,t){this.colorSet=!0,this.color=e,this.colorName=t,this.emit("color:set",{color:e,name:t})},e.isColorSet=function(){return this.colorSet},e.getColor=function(){return this.color},e.getColorName=function(){return this.colorName},e.isActive=function(){return this.active},e.toggleActive=function(){this.setActive(!this.active),this.setJoinLabel()},e.setJoinLabel=function(){!0===this.active?this.control("a").setLabel("LEAVE"):this.control("a").setLabel("JOIN")},e.setActive=function(e,t){this.active=e,this.eventableTrigger("active:change",e),this.active&&this.eventableTrigger("active:activate"),void 0!==t&&t&&this.setJoinLabel()},e.setView=function(e){return this.clearView(),this.currentView=i.create(e,[this],this.Webcontrol),this.currentView},e.clearView=function(e){var t;this.currentView&&(t=this.currentView,this.currentView=null,this.clearControls(),void 0!==e?setTimeout(function(){t.destroy()},e):t.destroy())},e.refreshView=function(){this.currentView&&this.currentView.refreshTarget(this)},e.getValues=function(){return this.currentView?this.currentView.getValues():null},e.clearValues=function(){this.currentView&&this.currentView.clearValues()},e.setUser=function(e){return this.usermodel=e,this},e.hasUser=function(){return void 0!==this.usermodel&&this.usermodel},e.getUser=function(){return this.usermodel},e.isLocalAuthentication=function(){return!0},e.log=function(e){this.Webcontrol&&this.Webcontrol.log("[u:"+this.getId()+"] "+e)},e.getGroups=function(){return this.groups},e.hasDisplay=function(){return!0},e.hasKeyboardInput=function(){return!0},e.hasTouchInput=function(){return!0},e.getIdentifier=function(){return{id:this.getId(),type:this.getEntityType()}},e.represents=function(e){if(void 0===e.id||void 0===e.type)throw"Attribute is not an identifier.";var t=this.getIdentifier();return t.type===e.type&&t.id===e.id},e.getPortalControls=function(){return{start:"start",back:"back",toggleActive:"up",authenticate:"y",left:"left",right:"right"}},e.isMainGroup=function(){if(0===this.groups.length)return!0;for(var e=0;e<this.groups.length;e++)if(this.groups[e].isMainGroup())return!0;return!1},e.isMaster=function(){return this.master},e.setMaster=function(e){var t=this.master!==(e=!!(e=void 0===e?!0:e));return this.master=e,t&&this.eventableTrigger("master:change"),this},e.getConnectToken=function(){return this.Webcontrol.getConnectToken()},e.getConnectTokenForDisplay=function(){return this.Webcontrol.getConnectTokenForDisplay()},e.serialize=function(){return{id:this.getId(),playerId:this.playerId,userdata:this.userdata,profiledata:this.profiledata,email:this.email,nickname:this.nickname,access_token:this.access_token,color:this.color,colorName:this.colorName,smiley:this.smiley,data:this.dataSynchronizer.serialize(),events:this.events.serialize()}},e.unserialize=function(e){void 0!==e.profiledata&&this.setProfiledata(e.profiledata),void 0!==e.playerId&&(this.playerId=e.playerId),void 0!==e.access_token&&this.setAccessToken(e.access_token),void 0!==e.color&&(this.color=e.color),void 0!==e.colorName&&(this.colorName=e.colorName),void 0!==e.nickname&&(this.nickname=e.nickname),void 0!==e.email&&(this.email=e.email),void 0!==e.smiley&&(this.smiley=e.smiley),void 0!==e.data&&this.dataSynchronizer.unserialize(e.data),void 0!==e.events&&this.events.unserialize(e.events)},l}),define("CatLab/Webremote/Models/GroupControl",[],function(){return function(e,i,t){var o,n,r,s,a,l,c=e,h={};this.label=null,this.decoration="",this.group=i,this.isGlobal=t,this.pushed=function(){for(r=i.getUsers(),o=0;o<r.length;o++)if(r[o].control(c,this.isGlobal).pushed())return!0;return!1},this.scale=function(){for(r=i.getUsers(),o=s=0;o<r.length;o++)(a=r[o].control(c,this.isGlobal)).value>s&&(s=a.value);return s},this.getLabel=function(e){return r=i.getUsers(),(o=0)<r.length?(a=r[o].control(c,this.isGlobal)).getLabel(e):null},this.getLabelImage=function(){return r=i.getUsers(),(o=0)<r.length?(a=r[o].control(c,this.isGlobal)).getLabelImage():null},this.setStaticLabel=function(e,t,n){for(r=i.getUsers(),o=0;o<r.length;o++)r[o].control(c).setStaticLabel(e,t,n);return null},this.setLabel=function(e,t){return this.label=e,i.emit("button:label",{id:c,label:e}),this},this.decorate=function(e){return this.decoration=e,i.emit("button:decorate",{id:c,styles:e}),this},this.click=function(e){return this.on("click",e),this},this.on=function(e,t){for(void 0===h[e]&&(h[e]=[]),h[e].push(t),this.log("Setting group trigger "+e),r=i.getUsers(),o=0;o<r.length;o++)r[o].control(c,this.isGlobal).on(e,t);return this},this.hasTriggers=function(e){for(r=i.getUsers(),o=0;o<r.length;o++)if(r[o].control(c,this.isGlobal).hasTriggers(e))return!0;return!1},this.off=function(e){for(delete h[e],r=i.getUsers(),o=0;o<r.length;o++)r[o].controls.hasOwnProperty(c)&&r[o].control(c,this.isGlobal).off(e);return this},this.clearEvents=function(){for(h={},r=i.getUsers(),o=0;o<r.length;o++)r[o].controls.hasOwnProperty(c)&&r[o].control(c,this.isGlobal).clearEvents();return this},this.clear=function(){for(h={},this.decoration=null,this.label=null,r=i.getUsers(),o=0;o<r.length;o++)r[o].controls.hasOwnProperty(c)&&r[o].control(c,this.isGlobal).clear();return this},this.isLocalAuthentication=function(){return!1},this.refreshControl=function(){for(r=i.getUsers(),o=0;o<r.length;o++){for(l in r[o].control(c,this.isGlobal).clearEvents(),h)if(h.hasOwnProperty(l))for(n=0;n<h[l].length;n++)r[o].control(c,this.isGlobal).on(l,h[l][n]);this.label&&r[o].control(c,this.isGlobal).setLabel(this.label)}return this},this.refreshTarget=function(e){this.decoration&&e.emit("button:decorate",{id:c,styles:this.decoration}),this.label&&e.emit("button:label",{id:c,label:this.label})},this.log=function(e){i.log("["+c+"] "+e)}}}),define("CatLab/Webremote/Models/ControlGroup",["CatLab/Webremote/Config","CatLab/Webremote/Models/ControlBase","CatLab/Webremote/Models/User","CatLab/Webremote/Models/Control","CatLab/Webremote/Models/GroupControl","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Synchronization/RemoteViewFactory","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler","CatLab/Webremote/Tools/Tools"],function(e,t,n,i,o,r,s,a,l,c){function h(e,t){this.initializeControlBase(),this.id=e,this.initialize(t)}t=h.prototype=new t;return t.setWebcontrol=function(e){this.Webcontrol=e},t.initialize=function(e){this.token=e.token,this.connectURL=e.connectURL,this.currentView=null,this.color="orange",this.colorName="orange",this.colorSet=!1,this.shareColor=!1,this.tmpid=null,this.active=!1,this.smiley=null,this.email=null,this.userdata=e,this.profiledata={},this.access_token=null,this.master=!1,this.users=[],this.controls=[],this.dataSynchronizer=new a("group",this.emit.bind(this),"master"),this.data=this.dataSynchronizer.getFromIdentifier("group:"+this.getId()),this.events=new l("group",this.emit.bind(this)),this.options={}},t.setOptions=function(e){return this.options=e,this},t.getOption=function(e){return void 0!==this.options[e]?this.options[e]:null},t.hasControl=function(e){return!0},t.setAccessToken=function(e){this.access_token=e},t.setProfiledata=function(e){this.profiledata=e,this.eventableTrigger("user:nickname",this.getNickname())},t.clearControls=function(){for(this.tmpid in null!=this.currentView&&this.currentView.clearControls(),this.controls)!this.controls.hasOwnProperty(this.tmpid)||this.controls[this.tmpid].isGlobal||(this.controls[this.tmpid].clear(),delete this.controls[this.tmpid])},t.clearEvents=function(){this.clearControls(),this.clearEventableEvents()},t.isMainGroup=function(){return this.Webcontrol.getConnectToken()===this.getConnectToken()},t.emit=function(e,t,n){return this.Webcontrol.provider.toGroup(this,e,t,n),!0},t.getId=function(){return this.id},t.getName=function(){return"Group "+this.getId()},t.setNickname=function(e){return this.nickname=e,this.eventableTrigger("user:nickname",e),this},t.getNickname=function(){return this.nickname||(this.getData().username?this.getData().username:"Group "+this.getId())},t.getType=function(){return"mobile"},t.getEntityType=function(){return"group"},t.getIcon=function(){return"fa fa-mobile-phone"},t.getData=function(){return this.profiledata},t.setColor=function(e,t,n){void 0===n&&(n=this.shareColor),this.colorSet=!0,this.color=e,this.colorName=t,this.shareColor=n,this.emit("color:set",{color:e,name:t,shareColor:n})},t.getColor=function(){return this.color},t.setShareColor=function(e){this.shareColor=e},t.isShareColor=function(){return this.shareColor},t.getColorName=function(){return this.colorName},t.setView=function(e){return this.clearView(),this.currentView=s.create(e,[this],this.Webcontrol,this.getId()),this.currentView},t.clearView=function(t){var e;this.currentView&&(e=this.currentView,this.currentView=null,this.clearControls(),void 0!==t?setTimeout(function(){e.destroy()},t):e.destroy(),this.users.forEach(function(e){e.clearView(t)}))},t.isAuthenticated=function(){return!1},t.isLocalAuthentication=function(){return!0},t.log=function(e){this.Webcontrol.log("[g:"+this.getId()+"] "+e)},t.getConnectToken=function(){return this.Webcontrol.provider.getConnectToken(this.token)},t.getConnectTokenForDisplay=function(){return c.getConnectTokenForDisplay(this.getConnectToken())},t.getConnectURL=function(){return this.Webcontrol.provider.getConnectURL(this.connectURL)},t.addUser=function(t){for(this.tmpid in c.findIndex(this.users,function(e){return e.id===t.id})<0&&this.users.push(t),c.findIndex(t.groups,function(e){return e.id===this.id})<0&&t.groups.push(this),this.currentView&&(this.currentView.refreshTarget(t),t.currentView=this.currentView),this.controls)this.controls.hasOwnProperty(this.tmpid)&&this.controls[this.tmpid].refreshControl();this.events.refreshTarget(t.emit.bind(t)),this.dataSynchronizer.refreshTarget(t.emit.bind(t)),this.smiley&&(t.emit("user:smiley",{smiley:this.smiley}),t.smiley=this.smiley),this.eventableTrigger("user:join",t)},t.removeUser=function(t){var e=c.findIndex(this.users,function(e){return e.id===t.id});0<=e&&this.users.splice(e,1)},t.getUsers=function(){return this.users},t.getIdentifier=function(){return{id:this.getId(),type:this.getEntityType()}},t.represents=function(e){if(void 0===e.id||void 0===e.type)throw"Attribute is not an identifier.";var t=this.getIdentifier();return t.type==e.type&&t.id==e.id},t.getValues=function(){return this.currentView?this.currentView.getValues():null},t.clearValues=function(){this.currentView&&this.currentView.clearValues()},t.control=function(e,t){return void 0===t&&(t=!1),void 0===this.controls[e]&&(this.controls[e]=new o(e,this,t)),this.controls[e]},t.isMaster=function(){return this.master},t.setMaster=function(e){return this.master=e=void 0===e?!0:e,this},t.hasDisplay=function(){return!0},t.hasKeyboardInput=function(){return!0},t.hasTouchInput=function(){return!0},t.getPortalControls=function(){return{start:"start",back:"back",toggleActive:"up",authenticate:"y",left:"left",right:"right"}},t.setOAuthSettings=function(e){this.emit("oauth:set",e)},t.setSmiley=function(e,t){this.Webcontrol.smileys.reserve(e,this.getIdentifier())?(this.emit("user:smiley",{smiley:e}),this.smiley=e):t.emit("dom:alert",{message:r.t("Smiley is already taken. Please select a different smiley.")})},t.clearSmiley=function(e){this.Webcontrol.smileys.unreserve(this.getIdentifier()),this.emit("user:smiley",{smiley:null}),this.smiley=null},t.getSmiley=function(){return this.smiley},t.getSmileyImage=function(){return this.Webcontrol.smileys.getImage(this.getSmiley())},t.getSmileyHtml=function(){return this.Webcontrol.smileys.getHtml(this.getSmiley())},t.getSmileyUrl=function(){return this.Webcontrol.smileys.getUrl(this.getSmiley())},t.setMaxUsers=function(e){this.emit("config:set",{maxUsers:e})},t.isActive=function(){return this.active},t.toggleActive=function(){this.active=!this.active,this.setJoinLabel()},t.setJoinLabel=function(){!0===this.active?this.control("a").setLabel("LEAVE"):this.control("a").setLabel("JOIN")},t.setActive=function(e,t){this.active=e,this.eventableTrigger("active:change",e),this.active&&this.eventableTrigger("active:activate")},t.serialize=function(){return{id:this.getId(),token:this.token,userdata:this.userdata,nickname:this.nickname,profiledata:this.profiledata,email:this.email,access_token:this.access_token,shareColor:this.shareColor,color:this.color,colorName:this.colorName,smiley:this.smiley,data:this.dataSynchronizer.serialize(),events:this.events.serialize()}},t.unserialize=function(e){void 0!==e.profiledata&&this.setProfiledata(e.profiledata),void 0!==e.access_token&&this.setAccessToken(e.access_token),void 0!==e.token&&(this.token=e.token),void 0!==e.shareColor&&(this.shareColor=e.shareColor),void 0!==e.color&&(this.color=e.color),void 0!==e.colorName&&(this.colorName=e.colorName),void 0!==e.nickname&&(this.nickname=e.nickname),void 0!==e.email&&(this.email=e.email),void 0!==e.smiley&&(this.smiley=e.smiley,this.emit("user:smiley",{smiley:this.smiley})),void 0!==e.data&&this.dataSynchronizer.unserialize(e.data),void 0!==e.events&&this.events.unserialize(e.events)},h}),define("CatLab/Webremote/Models/State",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Preloader"],function(n,i){function e(e){this.Webcontrol=e}var t=e.prototype;return t.reconnect=function(e,t){void 0!==e.provider&&this.Webcontrol.provider.restoreProviderSettings(e.provider),this.Webcontrol.disconnect(),setTimeout(function(){this.Webcontrol.initialize(n.getAll()).then(function(){this.Webcontrol._reconnect(e.token,e.accessToken,function(){this._setCollectionDetails(e.groups,this.Webcontrol._grouplibrary),this._setCollectionDetails(e.users,this.Webcontrol._userlibrary),this.Webcontrol.preloader=i.unserialize(this.Webcontrol.provider,e.preloader),t()}.bind(this))}.bind(this))}.bind(this),1)},t._setCollectionDetails=function(e,t){var n,i;if(void 0!==e)for(n=0;n<e.length;n++)(i=t.getFromId(e[n].id))?i.unserialize(e[n]):(console.log("Trying to set data for non existing user/group."),console.log(e[n]))},t.getData=function(){var t=[],n=(this.Webcontrol._grouplibrary.each(function(e){t.push(e.serialize())}.bind(this)),[]),e=(this.Webcontrol._userlibrary.each(function(e){n.push(e.serialize())}),{users:n,groups:t,token:this.Webcontrol._gamedata.token,accessToken:this.Webcontrol._gamedata.accessToken,preloader:this.Webcontrol.preloader.serialize()});return e.provider=this.Webcontrol.provider.serializeProviderSettings(),e},t.serialize=function(){var e=this.getData();return JSON.stringify(e)},t.unserialize=function(e){e=JSON.parse(e);this.reconnect(e)},e}),define("CatLab/Webremote/Messages/MessageBus",[],function(){function e(){this.controllerListeners=[],this.viewListeners=[]}var t=e.prototype;return t.toController=function(e,t){this.handleControllerMessage(e,t)},t.handleControllerMessage=function(e,t){for(var n=0;n<this.controllerListeners.length;n++)this.controllerListeners[n].handleIncomingMessage(e,t)},t.toView=function(e,t,n){this.handleViewMessage(e,t,n)},t.handleViewMessage=function(e,t,n){if(void 0===n)for(var i=0;i<this.viewListeners.length;i++)this.viewListeners[i].handleIncomingMessage(e,t);else this.viewListeners[n].handleIncomingMessage(e,t)},t.addControllerListener=function(e){if(void 0===e.handleIncomingMessage)throw new Error("Controller listener does not have a handleIncomingMessage");this.controllerListeners.push(e)},t.removeControllerListener=function(e){e=this.controllerListeners.indexOf(e);-1!==e&&this.controllerListeners.splice(e,1)},t.addViewListener=function(e){if(void 0===e.handleIncomingMessage)throw new Error("Controller listener does not have a handleIncomingMessage");e=this.viewListeners.push(e);this.toController("subscribe",{listener:e})},t.removeViewListener=function(e){e=this.viewListeners.indexOf(e);-1!==e&&this.viewListeners.splice(e,1)},t.destroy=function(){this.controllerListeners=[],this.viewListeners=[]},e}),define("CatLab/Webremote/Messages/NavigateableProxy",[],function(){function n(e){var t,n,i,o;return e?(o=n=t=null,{deviceId:t=void 0===(t="function"==typeof e.getDeviceId?e.getDeviceId():t)?null:t,kind:n=null===(n="function"==typeof e.getProfile&&(i=e.getProfile())&&i.kind?i.kind:n)&&"function"==typeof e.getKind?e.getKind()||null:n,userId:o=null===t&&"function"==typeof e.getId?void 0===(i=e.getId())?null:i:o}):null}function o(e){return e&&null!=e.actor?e.actor:null}function e(e,t){this.prefix=t||"",this.controls={navigation:["left","right"],toggle:["a"],manipulation:["down","up"],back:["b","back"]},this.views=[],this.keyInputCallbacks={},this.boundCallbacks={},e.addControllerListener(this),this.messageBus=e}var t=e.prototype;return t.handleIncomingMessage=function(e,t){if(e===this.prefix+"nav:controls")return this.controls=t.controls,this.views.forEach(function(e){this.refreshView(e)}.bind(this)),!0},t.addView=function(e){this.views.push(e),this.refreshView(e)},t.refreshView=function(n){this.reattachClick(n.control(this.controls.navigation[0]),this.previous),this.reattachClick(n.control(this.controls.navigation[1]),this.next),this.reattachClick(n.control(this.controls.manipulation[0]),this.down),this.reattachClick(n.control(this.controls.manipulation[1]),this.up),this.controls.toggle.forEach(function(t){void 0===this.keyInputCallbacks[t]&&(this.keyInputCallbacks[t]=function(e){this.keyInput(t,e)}),this.reattachClick(n.control(t),this.keyInputCallbacks[t].bind(this))}.bind(this)),this.controls.back.forEach(function(e){this.reattachClick(n.control(e),this.back)}.bind(this))},t.reattachClick=function(e,t){this.boundCallbacks[t]||(this.boundCallbacks[t]=t.bind(this)),e.off("click",this.boundCallbacks[t]),e.click(this.boundCallbacks[t])},t.keyInput=function(e,t){this.messageBus.toView(this.prefix+"nav:keyInput",{button:e,actor:n(t)})},t.previous=function(){this.messageBus.toView(this.prefix+"nav:previous")},t.next=function(){this.messageBus.toView(this.prefix+"nav:next")},t.up=function(e){this.keyInput("up",e)},t.down=function(e){this.keyInput("down",e)},t.back=function(e){this.messageBus.toView(this.prefix+"nav:back",{actor:n(e)})},t.destroy=function(){this.messageBus.removeControllerListener(this)},e.handleMessage=function(e,t,n,i){if(e.substring(0,(i=void 0===i?"":i).length)===i){switch(e=e.replace(i,"")){case"nav:previous":return n.previous(),!0;case"nav:next":return n.next(),!0;case"nav:keyInput":return n.keyInput(t.button,o(t)),!0;case"nav:back":return n.triggerBack(o(t)),!0}return!1}},e.describeActor=n,e}),define("CatLab/Webremote/Controllers/Portal",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Messages/MessageBus","CatLab/Webremote/Messages/NavigateableProxy"],function(n,e,t,o,i,r){function s(e,t){this.initializeEventable(),this.Webcontrol=e,this.options=t,this.controlDisabled=!1,this.users=[],this._externalActivePlayers=0,this._externalUsers=[],this.ensureOption("allowChangeNickname",!0),this.ensureOption("allowNonDisplayPlayers",!0),this.ensureOption("customFunctions",{}),this.ensureOption("minPlayers",1),this.ensureOption("maxPlayers",4),this.ensureOption("activePlayersPanel",!1),this.ensureOption("customViews",!1),this.ensureOption("authentication",e.AUTH_NOT_REQUIRED),this.ensureOption("localAuthenticatable",!1),this.ensureOption("allowPlayersWithoutDisplay",!0),this.ensureOption("start",function(){alert("This is where the game would start, if one would have set a 'start' option.")}),this.Webcontrol.getMessageBus().addControllerListener(this),this.messageBus=e.getMessageBus(),this.navigatableProxy=new r(this.messageBus,"portal:"),this.useCatLabViews()&&e.loadViews(n.getSocketURL(!0)+"/webremote/views/default.xml"),this.eventListeners=[],this.initialize()}e=s.prototype=new e;return e.handleIncomingMessage=function(e,t){switch(e){case"subscribe":this.updateUsers();break;case"start":this.startGame();break;case"back":this.back()}},e.initialize=function(){var e=this.Webcontrol.on("user:join",function(e){e.isMainGroup()&&(this.userConnect(e),this.eventListeners.push(e.on("login",function(){this.updateUsers()}.bind(this))))}.bind(this));this.eventListeners.push(e),this.Webcontrol.getUsers().forEach(function(e){e.isMainGroup()&&this.userConnect(e)}.bind(this))},e.updateUsers=function(){this.updateState();var e=this.serializePortalUsers();this.trigger("active:count",this.getActiveUsers().length),this.trigger("users:change",e),this.sendUsersToView(e)},e.serializePortalUsers=function(){var i=[];return this.Webcontrol.getUsers().forEach(function(e){var t,n;e.isMainGroup()&&(n=null,(t=e.getUser())&&(n={image:t.avatar}),i.push({active:e.isActive(),authenticated:e.isAuthenticated(),color:e.getColor(),profile:n,type:e.getType()}))}),i},e.sendUsersToView=function(e){this.messageBus.toView("users:update",{users:e.concat(this._externalUsers)})},e.updateState=function(){var e={activePlayers:this.countActiveUsers(),minPlayers:this.options.minPlayers,maxPlayers:this.options.maxPlayers,connectInstructions:this.getConnectInstructions(),startAndLoginInstructions:this.getStartAndLoginInstructions(),showInactivePlayers:this.supportInactivePlayers(),qrUrl:this.getQrCodeUrl()};this.messageBus.toView("state:change",{state:e})},e.ensureOption=function(e,t){void 0===this.options[e]&&(this.options[e]=t)},e.useCatLabViews=function(){return!1===this.options.customViews},e.getToggleView=function(e){var t="",t=this.supportInactivePlayers()?"catlab-portal-toggle":"catlab-portal";return this.isMaster(e)||(t+="-nostart"),t},e.addUser=function(e){e.clearControls(),this.users.push(e),this.supportInactivePlayers()||this.forceToggleableUser(e)||this.activateUser(e),this.trigger("users:update"),this.updateUsers()},e.activateUser=function(e){e.isActive()||(e.hasDisplay()||this.options.allowPlayersWithoutDisplay?(this.trigger("user:activate",e),e.setActive(!0,this.supportInactivePlayers()),this.updateUsers()):this.deactivateUser(e))},e.deactivateUser=function(e){e.isActive()&&(this.trigger("user:deactivate",e),e.setActive(!1,this.supportInactivePlayers()),this.updateUsers())},e.toggleActive=function(e){(this.supportInactivePlayers()||this.forceToggleableUser(e))&&(e.isActive()?this.deactivateUser(e):this.activateUser(e),this.trigger("users:update"))},e.forceToggleableUser=function(e){return!e.hasDisplay()&&!!this.options.allowPlayersWithoutDisplay},e.hasUsersWithoutDisplay=function(){if(this.options.allowPlayersWithoutDisplay)for(var e=0;e<this.users.length;e++)if(!this.users[e].hasDisplay())return!0;return!1},e.countActiveUsers=function(){return this.getActiveUsers().length+this._externalActivePlayers},e.setExternalActivePlayers=function(e){this._externalActivePlayers=e||0,this.updateState()},e.setExternalUsers=function(e){this._externalUsers=e||[],this.sendUsersToView(this.serializePortalUsers())},e.getActiveUsers=function(){for(var e=[],t=0;t<this.users.length;t++)this.users[t].isActive()&&e.push(this.users[t]);return e},e.userConnect=function(e){this.eventListeners.push(e.on("master:change",function(){this.updateUserView(e)},this)),this.addUser(e),this.updateUserView(e),this.trigger("user:connect",e)},e.updateUserView=function(e){var t=e.setView(this.getToggleView(e));this.controlDisabled||this.enableControls(e,t),this.enableDefaultPlayerControls(e,t)},e.disableControls=function(){this.controlDisabled=!0;for(var e=0;e<this.users.length;e++)this.users[e].clearControls()},e.enableControls=function(e,t){var n;void 0!==e?(n=e.getPortalControls(),t.control(n.toggleActive).click(function(){this.toggleActive(e)}.bind(this)),t.control(n.start).click(function(){this.startGame()}.bind(this)),t.control(n.back).click(function(){this.back()}.bind(this)),this.supportsLocalAuthentication()&&t.control(n.authenticate).click(function(){e.isLocalAuthentication()||this.authenticate(e)}.bind(this)),this.navigatableProxy.addView(t)):(this.controlDisabled=!1,this.users.forEach(function(e){this.updateUserView(e)}.bind(this)))},e.enableDefaultPlayerControls=function(n,i){if(i.control("name").setLabel(n.getNickname()),i.listenTo(n,"login",function(){i.control("name").setLabel(n.getNickname())}),this.options.allowChangeNickname&&i.control("change-nickname").click(function(){this.changeNickname(n).then(function(){this.updateUserView(n)}.bind(this))}.bind(this)),this.options.customFunctions)for(var e in this.options.customFunctions)this.options.customFunctions.hasOwnProperty(e)&&function(e,t){i.control(e).click(function(){t(n).then(function(){this.updateUserView(n)}.bind(this))}.bind(this))}.bind(this)(e,this.options.customFunctions[e])},e.changeNickname=function(t){var n=new o,i=t.setView("catlab-nickname");return i.changeValue("name",t.getNickname()),i.control("a").click(function(){var e=i.getValues().name;!e||32<e.length||(t.setNickname(e),n.resolve())}),n.promise()},e.supportInactivePlayers=function(){return this.options.activePlayersPanel},e.supportsLocalAuthentication=function(){return this.options.localAuthenticatable&&this.Webcontrol.canAuthenticate()},e.isMaster=function(e){return e.isMaster()},e.getPortalLabels=function(){var o={start:[],back:[],toggleActive:[],authenticate:[]};return this.Webcontrol._userlibrary.each(function(e){var t,n=e.getPortalControls();for(t in n)if(n.hasOwnProperty(t)){var i=e.control(n[t]).getLabelData();if(!i)continue;void 0===o[t]&&(o[t]=[]),-1===o[t].findIndex(function(e){return e.label===i.label&&e.image===i.image})&&o[t].push(i)}}.bind(this)),o},e.authenticate=function(e){this.activateUser(e),this.disableControls();var t=this.Webcontrol.authenticationController(e,{messageBus:this.messageBus});this.messageBus.toView("auth:open",{}),t.controller.setNavigatableUsers([e]),t.controller.on("close",function(){this.restoreInputAfterAuthentication(e),this.enableControls(),this.updateUsers()}.bind(this))},e.restoreInputAfterAuthentication=function(e){if(e&&"function"==typeof e.resumeListening&&e.resumeListening(),"undefined"!=typeof window&&"function"==typeof window.focus)try{window.focus()}catch(e){}if("undefined"!=typeof document&&document.body&&"function"==typeof document.body.focus)try{document.body.focus()}catch(e){}},e.countAuthenticated=function(e){void 0===e&&(e=!0);for(var t=0,n=0;n<this.users.length;n++)!this.users[n].isAuthenticated()||e&&!this.users[n].isActive()||t++;return t},e.countExternalAuthenticated=function(e){for(var t=0,n=0;n<this._externalUsers.length;n++){var i=this._externalUsers[n];i&&i.authenticated&&(e&&!i.active||t++)}return t},e.checkAuthentication=function(){var e=this.countAuthenticated();switch(this.options.authentication){case this.Webcontrol.AUTH_REQUIRED_ALL:return e===this.countActiveUsers();case this.Webcontrol.AUTH_REQUIRED_ONE:return 0<e+this.countExternalAuthenticated(!0);case this.Webcontrol.AUTH_REQUIRED_ONE_INACTIVE:return 0<this.countAuthenticated(!1)+this.countExternalAuthenticated(!1);case this.Webcontrol.AUTH_NOT_REQUIRED:return!0;default:throw"Authentication requirement "+this.options.authentication+" not found."}},e.startGame=function(){var e=this.countActiveUsers();if(e<this.options.minPlayers)this.messageBus.toView("alert",{message:"You need "+this.options.minPlayers+" players to start playing",localized:["You need %s players to start playing",this.options.minPlayers],id:"not-enough-players"});else if(e>this.options.maxPlayers)this.messageBus.toView("alert",{message:"Your license is limited to "+this.options.maxPlayers+" players",localized:["Your license is limited to %s players",this.options.maxPlayers],id:"exceeds-max-players"});else if(this.checkAuthentication())this.finalizeStart();else switch(this.options.authentication){case this.Webcontrol.AUTH_REQUIRED_ALL:this.messageBus.toView("alert",{message:"All active players must be authenticated.",localized:["All active players must be authenticated."],id:"not-all-authenticated"});break;case this.Webcontrol.AUTH_REQUIRED_ONE:case this.Webcontrol.AUTH_REQUIRED_ONE_INACTIVE:this.messageBus.toView("alert",{message:"At least one player must be authenticated.",localized:["At least one player must be authenticated."],id:"not-one-authenticated"})}},e.finalizeStart=function(){this.Webcontrol.setView("catlab-game-already-started",this.Webcontrol._userlibrary.not(this.getActiveUsers())),this.Webcontrol.setView("catlab-game-starting",this.getActiveUsers()),this.destroy(),this.options.start(this.getActiveUsers())},e.back=function(){void 0!==this.options.back&&(this.destroy(),this.options.back())},e.getConnectURL=function(){return this._publicConnectInfo&&this._publicConnectInfo.connectUrl?this._publicConnectInfo.connectUrl:this.Webcontrol.getConnectURL()},e.getConnectToken=function(){return this._publicConnectInfo&&this._publicConnectInfo.connectTokenForDisplay?this._publicConnectInfo.connectTokenForDisplay:this.Webcontrol.getConnectTokenForDisplay()},e.getQrCodeUrl=function(){var e=this.getConnectURL();return(e=e&&"http"!==e.substring(0,4)?"https://"+e:e)+"?t="+(this._publicConnectInfo&&this._publicConnectInfo.connectToken||this.Webcontrol.getConnectToken())},e._publicConnectInfo=null,e.setPublicConnectInfo=function(e){this._publicConnectInfo=e||null,this.updateState()},e.getUsers=function(){return this.users},e.setMinPlayers=function(e){return this.options.minPlayers=e,this.trigger("options:change"),this.updateState(),this},e.setMaxPlayers=function(e){return this.options.maxPlayers=e,this.trigger("options:change"),this.updateState(),this},e.getMessageBus=function(){return this.messageBus},e.getConnectInstructions=function(){return void 0!==this.Webcontrol.provider.getConnectInstructions?this.Webcontrol.provider.getConnectInstructions():["Use your tablet or smartphone to surf to %s and enter code %s.",this.getConnectURL(),this.getConnectToken()]},e.getStartAndLoginInstructions=function(){var e;return void 0!==this.Webcontrol.provider.getStartAndLoginInstructions?this.Webcontrol.provider.getStartAndLoginInstructions():this.hasUsersWithoutDisplay()?(e=this.getPortalLabels(),this.supportsLocalAuthentication()&&(this.showInactivePlayers||this.hasUsersWithoutDisplay())?["Press %s to join, %s to login and %s to start.",e.toggleActive,e.authenticate,e.start]:this.supportsLocalAuthentication()?["Press %s to login and %s to start.",e.authenticate,e.start]:this.showInactivePlayers||this.hasUsersWithoutDisplay()?["Press %s to join and %s to start.",e.toggleActive,e.start]:["Press %s to start.",e.start]):[""]},e.destroy=function(){this._destroyed||(this._destroyed=!0,this.trigger("destroy"),this.eventListeners&&this.eventListeners.forEach(function(e){e.unbind()}),this.messageBus.toView("portal:destroy"),this.messageBus.removeControllerListener(this),this.navigatableProxy.destroy())},s}),define("CatLab/Webremote/Controllers/RemoteAuthentication",["CatLab/Webremote/Controllers/OAuth2"],function(t){return function(e){e.setView("remote:authenticate"),e.on("user:join",function(e){e.on("login",function(e){t.addAccessToken(e.getAccessToken())}.bind(this))}.bind(this))}}),define("CatLab/Webremote/Controllers/Authentication",["CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Controllers/RemoteAuthentication","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Cookies","CatLab/Webremote/Messages/MessageBus","CatLab/Webremote/Messages/NavigateableProxy"],function(i,o,r,e,s,a,t,l){function n(e,t,n){this.initializeEventable(),this.messageBus=e.getMessageBus(),this.navigatableProxy=new l(this.messageBus,"auth:"),this.Webcontrol=e,this.user=t,this.user&&"function"==typeof this.user.control&&this.user.control("x").click(function(){this.messageBus.toView("auth:request-remove-selected-profile")}.bind(this)),r.on("update",this.updateUsers,this),i.on("update",function(){this.updateUsers()},this),this.messageBus.addControllerListener(this)}var c=null,h=null,e=n.prototype=new e;return e.handleIncomingMessage=function(e,t){switch(e){case"subscribe":this.getLoginUrl().then(function(e){this.loginUrl=e,this.messageBus.toView("auth:loginurl",{url:e})}.bind(this)),this.updateUsers();break;case"auth:close":this.close();break;case"auth:select-user":this.selectUser(t.user);break;case"auth:add-access-token":this.addAccessToken(t);break;case"auth:remove-user":this.removeUser(t.user)}},e.link=function(){i.link(function(e){this.selectUser(e)}.bind(this))},e.addAccessToken=function(t){t&&t.accessToken&&r.addFromAccessToken(t.accessToken,function(e){e&&t.select&&this.selectUser(e)}.bind(this))},e.updateUsers=function(){this.messageBus.toView("auth:users:update",{users:r.getAll().map(function(e){return{id:e.getId(),name:e.getName(),image:e.avatar}})})},e.selectUser=function(t){var n;(t=r.getFromId(t.id))&&(n=this).user.loginFromAuthUser(t,function(e){e?401!==e.status&&403!==e.status||r.remove(t):(a.setCookie("ctlb_ps_"+this.user.id,t.id),n.close())}.bind(this))},e.removeUser=function(e){(e=r.getFromId(e.id))&&(r.remove(e),this.updateUsers())},e.getUsers=function(){return r},e.close=function(){this._closed||(this._closed=!0,this.trigger("close"),this.messageBus.toView("auth:close"),this.destroy())},e.getLoginUrl=function(){var t,e,n=new s;return t=this.Webcontrol,(null!==c?((e=new s).resolve(c),e):(null===h&&(h=new s,t.newGroup().then(function(e){new o(c=e),e.setOAuthSettings(t.getOAuthSettings()),h.resolve(e)})),h)).promise().then(function(e){n.resolve(e.getConnectURL()+"/"+e.getConnectToken())}),n.promise()},e.setNavigatableUsers=function(e){e.forEach(function(e){this.navigatableProxy.addView(e)}.bind(this)),this.messageBus.toView("labels:update",{labels:{selectProfile:[this.user.control("a").getLabelData()],removeProfile:[this.user.control("x").getLabelData()],close:[this.user.control("b").getLabelData()]}})},e.attemptLastLogin=function(){var e=a.getCookie("ctlb_ps_"+this.user.id);if(e){e=r.getFromId(e);if(e)return this.selectUser(e),!0}return!1},e.destroy=function(){this.messageBus.toView("auth:destroy"),this.messageBus.removeControllerListener(this),this.navigatableProxy.destroy()},n}),define("CatLab/Webremote/Tools/MessageCounter",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e){this.interval=e||1e3,this.initializeEventable(),this.countIncoming=0,this.countOutgoing=0;var t,n,i=(new Date).getTime();setInterval(function(){t=(new Date).getTime(),n=t-i,i=t,this.trigger("tick",{in:this.countIncoming,out:this.countOutgoing,dt:n}),this.countIncoming=0,this.countOutgoing=0}.bind(this),this.interval)}e=t.prototype=new e;return e.incoming=function(){this.countIncoming++},e.outgoing=function(){this.countOutgoing++},t}),define("CatLab/Webremote/Views/Portal",["CatLab/Webremote/Config"],function(N){return function(e){var o=e.element||document.body,t=o,n=e.countdown||5e3,i=e.done||function(){alert("Game should start now... yet it doesn't.")},r=e["min-players"]||1,s=(r<1&&(r=1),e["max-players"]||1e3);s<r&&(s=r);var a,l,c,h,u,d,f,p,g,m,v,b=!e.customViews,y=[],w=!1,_=!1,C=null,O=this;function k(e){var t=document.createElement("div");return t.innerHTML=e.trim(),t.firstChild}function P(o){o.setView("catlab-portal-toggle"),o.control("join-game").click(function(){(e=>{if(A(e)){e.control("join-game").setLabel("JOIN");for(var t=e,n=0;n<y.length;n++)if(y[n].getId()==t.getId())return y.splice(n,1)}else e.control("join-game").setLabel("LEAVE"),y.push(e)})(o),M(),W(),U()}),o.control("start-game").click(function(){var e;w?U():y.length<r?D(r+" players are required to start the game. Please gather more friends."):y.length>s?D("This game can have only "+s+" players."):(e=n,U(),w=!0,(f=new Date).setTime((new Date).getTime()+e),u.style.display="",d=setInterval(V,100))}),o.control("down").click(function(){T(o)}),o.control("right").click(function(){T(o)}),o.control("left").click(function(){L(o)}),o.control("up").click(function(){L(o)}),o.control("a").click(function(){var e,t,i,n;e=o,_&&S(e)?(t=v.querySelector(".available-accounts li.selected"))&&(t=WebcontrolOAuthClient.getFromToken(t.getAttribute("data-accessToken")))&&(n=t.access_token,C.setUserData(n,t.user),E()):(w&&U(),_||(i=e,Webcontrol.getOAuthClient(function(n){n.onInit(function(){I(n)}),WebcontrolAccessKeyLibrary.init(function(){_=!0,C=i,m.style.display="",v.style.display="";var e=document.createElement("a"),t=(e.href="javascript:void(0);",e.textContent="Link new account",e.addEventListener("click",function(){n.getNewAccessToken(function(){I(n)})}),v.querySelector(".link-new-account"));t.innerHTML="",t.appendChild(e)}),I(n)})))}),o.control("b").click(function(){_&&S(o)&&(C.setUserData(!1),E())}),x(),W()}function L(e){if(_&&S(e)){for(var e=v.querySelector(".available-accounts"),t=e.querySelectorAll("li"),e=e.querySelector("li.selected"),n=0;n<t.length;n++)t[n].classList.remove("selected"),t[n].classList.add("unselected");e&&e.previousElementSibling?(e.previousElementSibling.classList.add("selected"),e.previousElementSibling.classList.remove("unselected")):0<t.length&&(t[t.length-1].classList.add("selected"),t[t.length-1].classList.remove("unselected"))}}function T(e){if(_&&S(e)){for(var e=v.querySelector(".available-accounts"),t=e.querySelectorAll("li"),e=e.querySelector("li.selected"),n=0;n<t.length;n++)t[n].classList.remove("selected"),t[n].classList.add("unselected");e&&e.nextElementSibling?(e.nextElementSibling.classList.add("selected"),e.nextElementSibling.classList.remove("unselected")):0<t.length&&(t[0].classList.add("selected"),t[0].classList.remove("unselected"))}}function S(e){return C&&e.getId()==C.getId()}function E(){m.style.display="none",v.style.display="none",_=!1,C=null}function I(e){var t=v.querySelector(".available-accounts");t.innerHTML="";for(var n=e.listUsers(),i=0;i<n.length;i++){var o=document.createElement("li");o.textContent=n[i].user.username,o.className="unselected",o.setAttribute("data-accessToken",n[i].access_token),t.appendChild(o)}}function W(){if(0<Webcontrol.getControlLabels("join-game").length){for(var e=document.querySelectorAll(".buttoninstructions.join-game"),t=0;t<e.length;t++){e[t].style.display="";var n=e[t].querySelector(".labels");n&&(n.innerHTML=Webcontrol.getControlLabels("join-game").join(", "))}for(var i=document.querySelectorAll(".buttoninstructions.start-game"),o=0;o<i.length;o++){i[o].style.display="";var r=i[o].querySelector(".labels");r&&(r.innerHTML=Webcontrol.getControlLabels("start-game").join(", "))}}else{for(var s=document.querySelectorAll(".buttoninstructions.join-game"),a=0;a<s.length;a++)s[a].style.display="none";h.style.display="none"}}function A(e){for(var t=0;t<y.length;t++)if(y[t].getId()==e.getId())return 1}function x(){var e=Webcontrol.getUsers();a.innerHTML="";for(var t=[],n=0;n<e.length;n++)A(e[n])||t.push(e[n]);0==t.length&&(a.innerHTML='<li class="empty"><span>More players? Add devices!</span></li>');for(var i="",n=0;n<t.length;n++)i+='<li class="user '+t[n].getType()+'" style="background-color: '+t[n].getColor()+'"><i class="'+t[n].getIcon()+'"></i><span>'+t[n].getName()+"</span></li>";i&&(a.innerHTML=i)}function M(){l.innerHTML="",0==y.length&&(l.innerHTML='<li class="empty"><span class="buttoninstructions join-game">Press <span class="labels"></span> to join the game.</span></li>');for(var e="",t=0;t<y.length;t++)e+='<li class="user '+y[t].getType()+'" style="background-color: '+y[t].getColor()+'"><i class="'+y[t].getIcon()+'"></i><span>'+y[t].getName()+"</span></li>";e&&(l.innerHTML=e),x()}function V(){p=Math.ceil((f.getTime()-(new Date).getTime())/1e3);var e=u.querySelector(".counter");e&&(e.innerHTML=p),p<0&&(void 0!==t&&void 0!==t.style&&(t.style.display="none"),U(),i(y))}function U(){w=!1,d&&(D("Countdown stopped!"),u.style.display="none",clearInterval(d),d=null)}function D(e){var t=document.createElement("p");t.innerHTML=e,g.appendChild(t),setTimeout(function(){t.style.transition="opacity 1s",t.style.opacity="0",setTimeout(function(){t.parentNode&&t.parentNode.removeChild(t)},1e3)},3e3)}this.loginInformation="Login into your account and get access to more game features now!",o.classList?o.classList.add("webremote-portal"):o.className=o.className+" webremote-portal",void 0!==e.theme&&(e=N.getSocketURL()+"/webremote/themes/"+e.theme+"/"+e.theme+".css",Webcontrol._loadCSS(e),Webcontrol._loadCSS(N.getSocketURL()+"/webremote/themes/font-awesome/css/font-awesome.min.css")),o.innerHTML='<div class="loading"><p>Please wait, loading socket.io.</p></div>',Webcontrol.initialize(function(){o.innerHTML="";var e=document.createElement("div"),e=(e.className="webremote-portal-inner",o.appendChild(e),(o=e).innerHTML='<div class="loading"><p>Please wait, connecting to server.</p></div>',b&&Webcontrol.loadViews(N.getSocketURL(!0)+"/webremote/views/default.xml"),o.innerHTML="<h1>Player lobby</h1>",m=document.createElement("div"),v=k('<div><h2>Select account</h2><div class="information"><p>'+O.loginInformation+'</p></div><ul class="available-accounts"></ul><p class="link-new-account"></p></div>'),m.className="accounts-overlay",v.className="accounts",m.style.display="none",v.style.display="none",o.appendChild(m),o.appendChild(v),k('<div class="connected-users"><div class="inner"><h2>Connected devices</h2></div></div>')),t=((a=document.createElement("ul")).className="connected-users",e.querySelector(".inner").appendChild(a),k('<div class="active-users"><div class="inner"><h2>Active users</h2></div></div>'));(l=document.createElement("ul")).className="active-users",t.querySelector(".inner").appendChild(l),o.appendChild(e),o.appendChild(t),(e=k('<div class="connection-information"><div class="inner"><h2>Instructions</h2><p>Take your smartphone, navigate to <span class="url"></span> and use token <span class="token"></span></p></div></div>')).querySelector(".token").innerHTML=Webcontrol.getConnectToken(),e.querySelector(".url").innerHTML=Webcontrol.getConnectURL(),c=k('<p class="buttoninstructions join-game">Press <span class="labels"></span> to join the game.</p>'),h=k('<p class="buttoninstructions start-game">Press <span class="labels"></span> to start the game.</p>'),(g=document.createElement("div")).className="errors",o.appendChild(g),e.appendChild(c),e.appendChild(h),o.appendChild(e),(t=document.createElement("div")).innerHTML='<div class="countdown-background"></div><div class="countdown"><p>Game will start in <span class="counter">5</span></p></div>',t.style.display="none",o.appendChild(t),u=t,Webcontrol.on("user:join",function(e){P(e)});for(var n=Webcontrol.getUsers(),i=0;i<n.length;i++)P(n[i]);Webcontrol.on("user:leave",x),x(),M(),W()})}}),define("CatLab/Webremote/ViewFactory/ViewFactory",["CatLab/Webremote/Views/Portal"],function(t){function e(){}return e.prototype.getPortal=function(e){return new t(e)},e}),define("CatLab/Webremote/Controllers/Webcontrol",["CatLab/Webremote/Config","CatLab/Webremote/Collections/Users","CatLab/Webremote/Collections/Groups","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Models/Users/ControlUser","CatLab/Webremote/Models/ControlGroup","CatLab/Webremote/Models/State","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Controllers/Portal","CatLab/Webremote/Controllers/Authentication","CatLab/Webremote/Tools/Colorwheel","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Preloader","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/MessageCounter","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Synchronization/RemoteViewFactory","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler","CatLab/Webremote/ViewFactory/ViewFactory","CatLab/Webremote/Views/ConnectionTrouble","CatLab/Webremote/Providers/SocketIO","CatLab/Webremote/SonicSync/Client","CatLab/Webremote/Messages/MessageBus"],function(a,e,t,n,i,o,l,r,s,c,h,u,d,f,p,g,m,v,b,y,w,_,C,k,P,L){function T(){this.initializeEventable(),this.provider=null,this._gamedata=null,this._userlibrary=null,this._grouplibrary=null,this._cssloads=[],this._labeldata={},this._initialized=!1,this._oauthsettings=!1,this._oauthClient=null,this._authentication=!1,this._lastView=null,this._options={},this._groupCallbacks={id:1},this._viewFactory=null,this.state=null,this.connected=!1,this._userlibrary=new e,this._grouplibrary=new t,this._messageBus=new L,this._pendingVitalEvent=null,this._licenseToken=null}T.GAME_HANDSHAKE_GRACE_MS=6e4;g=T.prototype=new g;return Object.assign(g,{AUTH_REQUIRED_ALL:"ALL",AUTH_REQUIRED_ONE:"ONE",AUTH_REQUIRED_ONE_INACTIVE:"ONE-INACTIVE",AUTH_NOT_REQUIRED:"NONE",initialize:function(e){function t(){o.resolve(),i()}var n,i=function(){},o=(void 0!==(e=void 0===(e="function"==typeof e?{callback:e}:e)?{}:e).callback&&(i=e.callback),new u);return this._initialized?t():(this.sonicSyncClient=null,delete e.callback,e.headless,(n=!!e.headless)||void 0===e.assets||this.setAssets(e.assets),a.set(e),a.initialize(function(){null===this.provider&&(void 0===e.provider&&(e.provider=new k),this.provider=e.provider),this.smileys=new p(this.provider),void 0!==e.translator&&d.setTranslator(e.translator),this._initialize(n,t)}.bind(this))),o.promise()},disconnect:function(){this._initialized=!1,this._licenseToken=null,this.provider.disconnect()},_initialize:function(o,e){var r,s=new u;return(e&&s.then(e),this._initialized)?s.resolve(this.connected):(setTimeout(function(){s.resolve(!1)},T.GAME_HANDSHAKE_GRACE_MS),this.state=new l(this),this._initialized=!0,(r=this).provider.initMaster(this),this.preloader=new f(this.provider),this.getProviderSettings().then(function(e){this.provider.connect("control",e).then(function(){this.connected=!0,this.provider.on("disconnect",function(){var e=this.getConnectionIssuesView();e.show(),e.text(d.t("Connection lost... reconnecting"))}.bind(this)),this.provider.on("reconnect",function(){this.recover(function(){this.getConnectionIssuesView().hide()}.bind(this))}.bind(this)),this.provider.on("master:initialize",function(e){this.log("Initializing"),this._gamedata=e,this.log("Game initialize; URL "+this.getConnectURL()+", token "+this.getConnectToken()),this.trigger("game:initialized",e),s.resolve(this.connected)}.bind(this)),this.provider.on("master:error",function(e){alert(e.message)}.bind(this)),this.provider.on("license:capped",function(e){this._onLicenseCapped(e)}.bind(this)),this.provider.on("user:join",function(e){this._playerJoin(e)}.bind(this)),this.provider.on("user:reconnect",function(e){this._playerReconnect(e)}.bind(this)),this.provider.on("user:leave",function(e){this._playerLeave(e)}.bind(this)),this.provider.on("view:labels",function(e){this._setViewLabels(e)}.bind(this)),this.provider.on("group:create",function(e){this._onNewGroup(e)}.bind(this)),this.provider.on("user:smiley",function(e){this._playerTrigger("user:smiley",e),this._userlibrary.each(function(e){this.smileys.refreshTakenSmileys(e)}.bind(this))}.bind(this)),this.provider.on("smileys:slingshot",function(e){var t=this._userlibrary.getFromId(e.user);t?(t.trigger("smileys:slingshot",e),e.user=t,this.trigger("smileys:slingshot",e)):console.log("User not found: "+e.user)}.bind(this));for(var e=(e=(e=["user:login","user:logout","button:down","button:up","sync:audio"]).concat(y.eventsToListenFor)).concat(w.eventsToListenFor),t=0;t<e.length;t++)(t=>{r.provider.on(t,function(e){r._playerTrigger(t,e)})})(e[t]);var n=["value:change"];for(var i=0;i<n.length;i++)(t=>{r.provider.on(t,function(e){r._viewTrigger(t,e)})})(n[i]);this._oauthsettings&&this.provider.setOAuthSettings(this._oauthsettings),this.provider.setup(a.getProviderConfig()),!o&&a.useAudioSync()&&(this.sonicSyncClient=new P(this),this.sonicSyncClient.startSender())}.bind(this))}.bind(this))),s.promise()},setLogger:function(e){var t;"string"==typeof e?(t=document.getElementById(e),this.log=this.getDomLogger(t)):this.log=e},getProviderSettings:function(){return this.provider.getProviderSettings()},setMessageCounter:function(e){e=new m(e);return this.provider.setMessageCounter(e),e},setName:function(e){this.provider.toMaster("master:name",{name:e})},setMaxUsers:function(e){this.provider.toMaster("config:set",{maxUsers:e})},setLicenseToken:function(e){this.provider&&e&&e!==this._licenseToken&&(this._licenseToken=e,this.provider.toMaster("license:update",{token:e}))},_onLicenseCapped:function(e){this.trigger("license:capped",e)},setViewFactory:function(e){return this._viewFactory=e,this._viewFactory.initialize()},getViewFactory:function(){return"undefined"===this._viewFactory&&(this._viewFactory=new _),this._viewFactory},getDomLogger:function(t){return function(e){t.innerHTML=e+"\n"+t.innerHTML}},oAuth:function(e,t){void 0===t&&(t=!1),this._authentication=!0,this._oauthsettings=e,this.provider&&!t&&this.provider.setOAuthSettings(this._oauthsettings),r.initialize(e),n.initialize(this,r),this._userlibrary&&this._userlibrary.each(function(e){"function"==typeof e.flushPendingLogin&&e.flushPendingLogin()})},getOAuthClient:function(e){this._oauthsettings?(null===this._oauthClient&&(this._oauthClient=r,this._oauthClient.initialize(this._oauthsettings)),e(this._oauthClient)):e(null)},getOAuthSettings:function(){return this._oauthsettings},clearEvents:function(e){if(e=void 0===e?!1:e)for(var t=this._userlibrary.getAll(),n=0;n<t.length;n++)t[n].clearEvents()},getConnectURL:function(){return this.provider.getConnectURL(this._gamedata?this._gamedata.connectURL:null)},getConnectToken:function(){return this.provider.getConnectToken(this._gamedata?this._gamedata.token:null)},getConnectTokenForDisplay:function(){return v.getConnectTokenForDisplay(this.getConnectToken())},loadViews:function(e,t,n){return this.provider.loadViews(e,n,t)},parseViews:function(e,t){return this.provider.parseViews(e,t)},registerComponent:function(e,t,n){return this.provider.registerComponent(e,t,n)},getUsers:function(){return this._userlibrary.getAll()},setExternalPlayerOffset:function(e){this._userlibrary&&this._userlibrary.setExternalPlayerOffset(e)},portal:function(e){var t=this.portalController(e),e=this.portalView(t.messageBus,e);return{controller:t.controller,view:e,promise:t.promise}},portalController:function(e){var t;if(this._initialized)return t=new u,e=new s(this,e),t.resolve(e),{controller:e,messageBus:this.getMessageBus(),promise:t};throw new Error("Please initialize Webcontrol first.")},portalView:function(e,t){var n;if(this._initialized)return n=this.getViewFactory(),e=Object.assign({},t,{messageBus:e,Webcontrol:this}),void 0!==t.element&&(e.element=t.element),(t=n.portal(e)).loading(),(e=n.getContainer()).easelboneLayer.setView(t),t.render(),e;throw new Error("Please initialize Webcontrol first.")},authentication:function(e,t){var n;if(this._initialized)return n=this.authenticationController(e,t),t=this.authenticationView(n.controller.messageBus,t),n.controller.setNavigatableUsers([e]),{controller:n.controller,view:t,promise:n.promise};throw new Error("Please initialize Webcontrol first.")},authenticationController:function(e,t){var n=new u,e=new c(this,e,t);return n.resolve(e),{controller:e,promise:n.promise(),messageBus:this.getMessageBus()}},authenticationView:function(e,t){var n=this.getViewFactory(),t=n.authentication(Object.assign({},t,{messageBus:e})),e=n.getContainer();return e.easelboneLayer.setView(t),t.render(),e},alertView:function(e,t){var n=this.getViewFactory(),t=n.alert(Object.assign({},t,{message:e})),e=n.getContainer();return e.easelboneLayer.setView(t),t.render(),e},getConnectionIssuesView:function(){return void 0===this.connectionTrouble&&(this.connectionTrouble=new C),this.connectionTrouble},setView:function(e,t){var n;return void 0===t?(n=b.create(e,[this],this),this._lastView=n):n=b.create(e,t,this),n},beacon:function(e,t){this.provider.toMaster("master:beacon",{beacon:e,token:t})},emit:function(e,t){this.provider.emit(e,t)},getControlLabels:function(e,t){for(var n=[],i={},o=this.getUsers(),r=0;r<o.length;r++){var s=o[r].control(e).getLabel(t);void 0===i[s]&&n.push(i[s]=s)}return n},addCustomControl:function(e){this.log("adding "+e.getType()),e.setWebcontrol(this),this._userlibrary.add(e),this._initializeSmiley(e,{}),this.trigger("user:join",e)},newGroup:function(e){var t=new u,n={},i=(void 0===e?e={}:"function"==typeof e&&(e={callback:e}),void 0===e.callback&&(e.callback=function(){}),!0),o=(void 0!==e.globalViews&&(i=e.globalViews),!0),r=(void 0!==e.shareColor&&(o=e.shareColor),[]),s=(void 0!==e.tags&&(r=e.tags),!0),s=(void 0!==e.smiley&&(s=!!e.smiley),n.smiley=s,this._groupCallbacks.id);return this._groupCallbacks.id++,this._groupCallbacks[s]={id:s,callback:e.callback,deferred:t,options:n},this.provider.createGroup(s,i,o,r),t.promise()},preload:function(e){var t;return this.preloader&&this.connected?this.preloader.preload(e):((t=new u).resolve(e),t.promise())},getPreloadedUrl:function(e){var t;return!this.preloader||!this.connected||void 0===(t=this.preloader.getPreloadedUrl(e))?e:t},_reset:function(){this._userlibrary.clear(),this._grouplibrary.clear()},reset:function(){var e=new u;return this.provider.reset(function(){e.resolve()}.bind(this)),e.promise()},_playerJoin:function(e){var t;this._userlibrary.getFromId(e.id)||((t=new i(e.id,e)).setWebcontrol(this),void 0!==e.color&&t.setColor(e.color.color,e.color.name),this._grouplibrary.addUser(t)||(this._lastView&&this._lastView.addTarget(t),this._initializeSmiley(t,e)),this._userlibrary.add(t),this.log(t),t&&this.trigger("user:join",t),this.preloader.sendPreloadFileCommandToPlayer(t))},_playerReconnect:function(e){var t=this._userlibrary.getFromId(e.id);t?(t.getSmiley()&&t.emit("user:smiley",{smiley:t.getSmiley()}),this._refreshPlayerViews(t),this.trigger("user:rejoin",t),t.eventableTrigger("rejoined"),this.smileys.refreshTakenSmileys(t),this.preloader.sendPreloadFileCommandToPlayer(t)):this._playerJoin(e)},_refreshPlayerViews:function(e){this._grouplibrary.addUser(e)||this._lastView&&this._lastView.addTarget(e),e.refreshView()},_playerLeave:function(e){e=this._userlibrary.getFromId(e.id);e&&(this.trigger("user:leave",e),e.eventableTrigger("left"))},_onNewGroup:function(e){var t,n=new o(e.id,e),i=(n.setWebcontrol(this),!1);void 0!==e.shareColor&&(i=e.shareColor),void 0!==e.color?n.setColor(e.color.color,e.color.name):n.setShareColor(i),this._grouplibrary.getFromId(e.id)||(i=function(){},void 0!==(t=e.externalId)&&void 0!==this._groupCallbacks[t]&&(n.setOptions(this._groupCallbacks[t].options),i=function(){this._groupCallbacks[t].callback(n),this._groupCallbacks[t].deferred.resolve(n)}.bind(this)),this._grouplibrary.add(n),n.getOption("smiley")&&this._initializeSmiley(n,e),this.trigger("group:create",n),this.log("New group "+n.getId()+"; URL "+n.getConnectURL()+", token "+n.getConnectToken()),i())},_initializeSmiley:function(e,t){var n;a.useSmileys()?void 0===t.smiley?null!==(n=this.smileys.getRandom(e.getIdentifier()))&&e.setSmiley(n):e.setSmiley(t.smiley):e.clearSmiley(),this.smileys.refreshTakenSmileys(e)},_playerTrigger:function(e,t){var n=this._userlibrary.getFromId(t.user);n?n.trigger(e,t):console.log("User not found: "+t.user)},_viewTrigger:function(e,t){var n=b.getFromId(t.viewId);n&&n.trigger(e,t)},_loadCSS:function(e){for(var t=0;t<this._cssloads.length;t++)if(this._cssloads[t]==e)return;this._cssloads.push(e);var n=document.createElement("link");n.setAttribute("rel","stylesheet"),n.setAttribute("type","text/css"),n.setAttribute("href",e),document.body.appendChild(n)},_setViewLabels:function(e){this._labeldata[e.id]=e.labels;for(var t=this.getUsers(),n=0;n<t.length;n++)for(var i=0;i<e.labels.length;i++)t[n].control(e.id).setStaticLabel(e.labels[i].label,"mobile")},getViewLabels:function(e){return void 0!==this._labeldata[e]?this._labeldata[e]:[]},getFromIdentifier:function(e){switch(e.type){case"user":return this._userlibrary.getFromId(e.id);case"group":return this._grouplibrary.getFromId(e.id)}return null},log:function(e){a.debug()&&(console.log(a),console.log(e))},canAuthenticate:function(){return this._authentication},pause:function(){this._pendingVitalEvent={action:"master:pause",data:{}},this._initialized&&this.provider.emit("master:pause",{})},unpause:function(){this._pendingVitalEvent={action:"master:unpause",data:{}},this._initialized&&this.provider.emit("master:unpause",{})},audioSync:function(){if(this.sonicSyncClient)return this.sonicSyncClient.sync()},getMessageBus:function(){return this._messageBus},recover:function(e){var t=this.state.getData();this._reconnect(t.token,t.accessToken,e).then(function(){this._userlibrary.each(function(e){this._refreshPlayerViews(e)}.bind(this)),this._resendVitalEvent(),this._licenseToken&&this.provider.toMaster("license:update",{token:this._licenseToken})}.bind(this))},_resendVitalEvent:function(){this._pendingVitalEvent&&this.provider.emit(this._pendingVitalEvent.action,this._pendingVitalEvent.data)},_reconnect:function(e,t,n){return this.provider.reconnect(e,t,a.getProviderConfig(),n)},getIceCredentials:function(){var t=new u;return this.provider.toMaster("webrct:stun+turn",{},function(e){void 0===e.error?t.resolve(e):t.fail(e.error)}),t.promise()}}),T}),define("CatLab/Webremote/Models/Users/DummyUser",["CatLab/Webremote/Models/Users/ControlUser"],function(e){function t(e){this.initialize({id:e}),this.clearControls=function(){},this.getType=function(){return"dummy"},this.getIcon=function(){return"fa fa-keyboard-o"},this.emit=function(e,t){return!1},this.isLocalAuthentication=function(){return!1},this.log=function(e){this.Webcontrol&&this.Webcontrol.log("[u:"+this.getId()+"] "+e)},this.hasDisplay=function(){return!0},this.hasKeyboardInput=function(){return!0},this.hasTouchInput=function(){return!0},this.clearControls()}return(t.prototype=Object.create(e.prototype)).constructor=t}),define("CatLab/Webremote/Tools/ParseXML",[],function(){function e(){}var t=null;"undefined"!=typeof window&&(void 0!==window.DOMParser?t=function(e){return(new window.DOMParser).parseFromString(e,"text/xml")}:void 0!==window.ActiveXObject&&new window.ActiveXObject("Microsoft.XMLDOM")&&(t=function(e){var t=new window.ActiveXObject("Microsoft.XMLDOM");return t.async="false",t.loadXML(e),t}));return e.prototype.parse=function(e){if(t)return t(e);throw new Error("No XML parser found")},new e}),define("CatLab/Webremote/Providers/Airconsole",["CatLab/Webremote/Providers/Provider","CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Proxy","CatLab/Webremote/Tools/ParseXML","CatLab/Webremote/Synchronization/MessageQueue","CatLab/Webremote/Models/User"],function(e,t,n,i,o,r,s){function a(e){e&&(this.airconsole=e),this.showTokenForm=!1,this.oauth={},this.views=[],this.knownUsers={},this.started=!1,this.userId=null,this.sendBurstDelay=50,this.connectCode=null}e=a.prototype=new e;return e.connect=function(e){return this.log("Airconsole connecting"),this.setInitialized(),this.path=e,this._trigger("connect",null),this.readyState.promise()},e.noTokenConnect=function(){return this.connect("remote")},e.setUserId=function(e){return this.userId=e,this},e.initMaster=function(e){this.master=e,this.airconsole||(this.airconsole=new AirConsole),this.airconsole.onMessage=this.onMessage.bind(this),this.airconsole.onConnect=function(e){this.emitAirConsole(e,"airconsole:well-hello-there",{user:e})}.bind(this),this.readyState=new n,this.airconsole.onReady=function(e){this.connectCode=e,this.readyState.resolve()}.bind(this),this.airconsole.onDeviceProfileChange=function(e){this.updateDeviceProfile(e)}.bind(this),this.on("player:join",function(e){this.onPlayerConnect(e.user)}.bind(this)),this.once("connect",function(){setTimeout(function(){this.started=!0}.bind(this),1)}.bind(this))},e.initPlayer=function(e){this.master=e,this.airconsole=new AirConsole,this.airconsole.onMessage=this.onMessage.bind(this),this.readyState=new n,this.readyState.resolve(),this.once("airconsole:well-hello-there",function(e){this.emitAirConsole(0,"player:join",{})}.bind(this))},e.onMessage=function(t,e){var n;void 0!==(e="string"==typeof e?JSON.parse(e):e).b&&Array.isArray(e.b)?(n=0,e.b.forEach(function(e){setTimeout(function(){this.processMessage(t,e)}.bind(this),n++)}.bind(this))):this.processMessage(t,e)},e.processMessage=function(e,t){var n;t&&t[0]&&(n=t[0],t=t[1],this.isMaster()&&(0<e&&"player:join"!==n&&void 0===this.knownUsers[e]&&this.onPlayerConnect(e),0<e)&&(t.user=e),r.unpack(t,"user").forEach(function(e){this.isRemote()&&void 0!==e.user&&e.user!==this.airconsole.getDeviceId()||this._trigger(n,e)}.bind(this)))},e.onPlayerConnect=function(e){this.log("Welcoming our newest player "+e),this.knownUsers[e]=!0;for(var t=0;t<this.views.length;t++)this.emitAirConsole(e,"view:load",{xml:this.views[t]}),this.emitAirConsole(e,"view:set",{id:"loading"});this._trigger("user:join",{id:e}),this.updateDeviceProfile(e)},e.updateDeviceProfile=function(e){var t,n,i=this.master._userlibrary.getFromId(e);i&&(t={username:this.airconsole.getNickname(e)},(n=this.airconsole.getProfilePicture(e))&&(t.avatar=n),this.airconsole.getMasterControllerDeviceId()===e&&i.setMaster(!0),i.setProfiledata(t))},e.emitAll=function(){this.isMaster()&&this.emitMaster(),this.isRemote()&&this.emitClient()},e.isMaster=function(){return"control"===this.path},e.isRemote=function(){return"remote"===this.path},e.emitClient=function(){this.queue.flush().forEach(function(e){this.emitAirConsole(0,e.action,e.data)}.bind(this))},e.emitMaster=function(){var t,n,e=this.queue.compactFlush();e.length&&(t=5<e.length,n=[],e.forEach(function(e){t||void 0===e.data.user||Array.isArray(e.data.user)&&1<e.data.user.length?n.push(e):this.emitAirConsole(e.user,e.action,e.data)}.bind(this)),0<n.length)&&this.broadcastAirconsole(n)},e.emitAirConsole=function(e,t,n){t=[t,n],delete t[1].action,n=JSON.stringify(t);this.airconsole.message(e,n)},e.broadcastAirconsole=function(e){var t=[],e=(e.forEach(function(e){t.push([e.action,e.data])}),JSON.stringify({b:t}));this.airconsole.broadcast(e)},e.setOAuthSettings=function(e){this.oauth=e,this.emit("oauth:set",e)},e.onParseViews=function(e){this.views.push(e)},e.log=function(){this.master.log.apply(arguments)},e.setup=function(e){this._trigger("master:initialize",{})},e.toMaster=function(e,t){t.user=0,this.emit(e,t)},e.log=function(e){var t=[],n=(Array.prototype.push.apply(t,arguments),"["+this.path+"]");"remote"===this.path&&(n="["+this.path+":"+this.airconsole.getDeviceId()+"]"),t.unshift(n),console.log.apply(console,t)},e.getConnectInstructions=function(){return["Open the Airconsole app on your smartphone and connect with code %s.",this.connectCode]},e.getStartAndLoginInstructions=function(){return["Use the onscreen button to start the game."]},a}),define("CatLab/Webremote/Providers/Dummy",["CatLab/Webremote/Providers/Provider","CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Tools"],function(e,t,i,n){function o(){this.initializeProvider(),this.userId=null,this.randomToken=n.getUuid(),this.loadBalancerSessionToken="connid",this.socket=null,this._registeredEvents={}}e=o.prototype=new e;return e.connect=function(e,t){var n=new i;return this.setInitialized(),n.resolve(),n.promise()},e.setup=function(e){this._trigger("master:initialize",{})},e.emitAll=function(e,t){},o}),define("CatLab/Webremote/Transport/Errors",[],function(){function e(e,t){return e.prototype=Object.create(Error.prototype),(e.prototype.constructor=e).prototype.name=t,e}return{TransportError:e(function(e,t){var e=t?t+": "+e:e,n=new Error(e);this.message=e,this.path=t||null,this.stack=n.stack},"TransportError"),RemoteError:e(function(e){e=e||{};var t=new Error(e.message||"");this.name=e.name||"RemoteError",this.message=e.message||"",this.data=void 0===e.data?null:e.data,this.remoteStack=e.stack||"",this.isRemote=!0,this.stack=this.name+": "+this.message+"\n--- remote stack ---\n"+this.remoteStack+"\n--- local stack ---\n"+t.stack},"RemoteError"),RpcTimeoutError:e(function(e,t,n){var i=new Error(e+" on pool "+t+" timed out after "+n+"ms");this.message=i.message,this.method=e,this.pool=t,this.timeoutMs=n,this.stack=i.stack},"RpcTimeoutError"),PoolBootError:e(function(e,t,n){var i=new Error("pool boot failed on "+e+" host: "+t);this.message=i.message,this.kind=e,this.reason=t,this.cause=void 0===n?null:n,this.stack=i.stack},"PoolBootError")}}),define("CatLab/Webremote/Providers/BridgeContract",[],function(){return{TARGET_FIRST:{toPlayer:!0,toGroup:!0},TARGET_INDEX:{loadViews:2,parseViews:2,registerComponent:2}}}),define("CatLab/Webremote/Providers/BridgedProvider",["CatLab/Webremote/Providers/Provider","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/Errors","CatLab/Webremote/Providers/BridgeContract"],function(e,l,a,t){function n(e){this.initializeProvider(),this._channels=e,this._providerInfo={},this._seq=0,this._pending={},this._acks={},this._ackSeq=0,this._subscribed={};var n=this;e.on("provider",function(e,t){n._onMessage(e,t)}),"function"==typeof e.onClose&&e.onClose(function(){n._failAll(new a.TransportError("provider channel closed"))}),this._post("hello",{})}var c=t.TARGET_FIRST,h=t.TARGET_INDEX,t=n.prototype=new e;return t.constructor=n,t._post=function(e,t){"function"==typeof this._channels.isClosed&&this._channels.isClosed()||this._channels.sendNow("provider",e,t)},t._call=function(t,e,n,i){for(var o=++this._seq,r=new l,s=(e||[]).slice();0<s.length&&void 0===s[s.length-1];)s.pop();var e={id:o,method:t,args:s},a=null;"function"==typeof n&&(a=++this._ackSeq,this._acks[a]={fn:n,method:t},e.ack=a),i&&(e.target=i),this._pending[o]={deferred:r,method:t};try{this._post("call",e)}catch(t){null!==a&&delete this._acks[a],this._settle(o,function(e){e.deferred.reject(t)})}return r.promise()},t._settle=function(e,t){var n=this._pending[e];n&&(delete this._pending[e],t(n))},t._failAll=function(t){var n=this,e=(Object.keys(this._pending).forEach(function(e){n._settle(e,function(e){e.deferred.reject(t)})}),Object.keys(this._acks));0<e.length&&(this._acks={},console.warn("[BridgedProvider] "+e.length+" pending device ack(s) failed: "+t.message))},t._onMessage=function(e,n){var t;switch(e){case"result":return void this._settle(n.id,function(e){e.deferred.resolve(n.value)});case"error":return void this._settle(n.id,function(e){var t=n.error;t instanceof Error||(t=new a.RemoteError({name:"RemoteError",message:String(t)})),e.deferred.reject(t)});case"ack":return(t=this._acks[n.ack])?(delete this._acks[n.ack],n.error?void console.warn("[BridgedProvider] ack for "+t.method+" failed",n.error):void t.fn(n.result)):void console.warn("[BridgedProvider] ack for an unknown call ignored",n.ack);case"event":return"settings"===n.event&&n.data&&this._applyProviderInfo(n.data),void this._trigger(n.event,n.data);default:console.warn("[BridgedProvider] unknown provider message",e)}},t._applyProviderInfo=function(e){e=e||{},(this._providerInfo=e).connectInstructions?this.getConnectInstructions=function(){return e.connectInstructions}:delete this.getConnectInstructions,e.startAndLoginInstructions?this.getStartAndLoginInstructions=function(){return e.startAndLoginInstructions}:delete this.getStartAndLoginInstructions},t.initMaster=function(e){return this.master=e,this._call("initMaster",[])},t.connect=function(e,t){var n=this,e=this._call("connect",[e,t]);return e.done(function(){n.setInitialized(),n._trigger("connect")}),e},t.disconnect=function(){this._call("disconnect",[]),e.prototype.disconnect.call(this)},t.setUserId=function(e){return this._call("setUserId",[e]),this.userId=e,this},t.emit=function(e,t,n){this.initialized?this.emitOne(e,t,n):this.postInitializeQueue.push({action:e,data:t,ack:n})},t.emitOne=function(e,t,n){this._call("emit",[e,t],n)},t.emitAll=function(){var t=this;this.queue.compactFlush().forEach(function(e){t.emitOne(e.action,e.data,e.ack)})},t.toMaster=function(e,t,n){return this._call("toMaster",[e,t||{}],n)},t.toPlayers=function(e,t,n){return this._call("toPlayers",[e,t||{}],n)},t.toPlayer=function(e,t,n,i){return this._callWithTarget("toPlayer",[t,n||{}],i,e,"user")},t.toGroup=function(e,t,n,i){return this._callWithTarget("toGroup",[t,n||{}],i,e,"group")},t.createGroup=function(e,t,n,i){return this._call("createGroup",[e,t,n,i||[]])},t.setOAuthSettings=function(e){return this._call("setOAuthSettings",[e])},t.setup=function(e){return this._call("setup",[e])},t.reset=function(e){return this._call("reset",[],e)},t.proxyFile=function(e){return this._call("proxyFile",[e])},t.reconnect=function(e,t,n,i){return this._call("reconnect",[e,t,n],i)},t.loadViews=function(e,t,n){return this._callWithTarget("loadViews",[e,!!t],void 0,n,"user",!0)},t.parseViews=function(e,t,n){return this._callWithTarget("parseViews",[e,t],void 0,n,"user",!0)},t.registerComponent=function(e,t,n){return this._callWithTarget("registerComponent",[e,t],void 0,n,"user",!0)},t._callWithTarget=function(e,t,n,i,o,r){var s=null;if(i&&"function"==typeof i.getId)s={id:i.getId(),type:"function"==typeof i.getEntityType?i.getEntityType():o};else if(i&&!r)return(o=new l).reject(new a.TransportError("BridgedProvider."+e+": target has no getId()","provider."+e+".target")),o.promise();return s||c[e]||void 0!==h[e]?this._call(e,t,n,s):this._call(e,t,n)},t.getProviderSettings=function(){var e=new l;return e.resolve(this._providerInfo.settings||{}),e.promise()},t.canProviderLoadExternalXml=function(){return!!this._providerInfo.canLoadExternalXml},t.canProxyFiles=function(){return!!this._providerInfo.canProxyFiles},t.getStaticUrl=function(e){var t=this._providerInfo.staticUrlBase;return("string"==typeof t?t:"")+e},t.getConnectURL=function(e){return this._fact("connectUrl",e)},t.getConnectToken=function(e){return this._fact("connectToken",e)},t._fact=function(e,t){e=this._providerInfo[e];return null==e?void 0===t?null:t:e},t._touchEvent=function(e){this._subscribed[e]||(this._subscribed[e]=!0,this._post("subscribe",{event:e}))},n}),define("CatLab/Webremote/CreateJS/LayerContainer",["easeljs","easelbone"],function(i,o){function e(e,t){if(!o)throw console.log("When using the createjs module of the remote, you need to have the easelbone module loaded."),console.log("Check https://github.com/catlabinteractive/easelbone"),new Error("easelbone could not be loaded.");this.width=e,this.height=t,this.initialize(),this.easelboneLayer=new o.Views.Layer({container:this});var n=this;this.easelboneLayer.on("all",function(e){e=new i.Event(e);n.dispatchEvent(e)})}var t=e.prototype=new i.Container;return t.Container_initialize=t.initialize,t.initialize=function(){this.Container_initialize(),this.setBounds(0,0,this.width,this.height),this.on("click",function(e){e.stopPropagation()})},t.loading=function(){},t.render=function(){this.easelboneLayer.render()},e}),define("CatLab/Webremote/CreateJS/Views/BaseView",["easelbone","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Images"],function(r,s,e){var a=new e;return r.Views.Navigatable.extend({intitializeBaseView:function(e){this.initializeNavigatable(e),this.labels={},this.replacedEmojis={},this.navigatableOverride=null},getLabelSubstitutionOrNull:function(e,t){return void 0!==this.labels[e]?this.substituteLabelsForInstructionMessage(t,this.labels[e]):null},substituteLabelsForInstructionMessage:function(e){for(var t=[],n=1;n<arguments.length;n++){var i,o=arguments[n];"string"!=typeof o?(i=[],o.forEach(function(e){e.emoji?(i.push(e.emoji),e.image&&(this.replacedEmojis[e.emoji]=a.getUrl(e.image,128))):e.label&&i.push(e.label)}.bind(this)),t.push(i.join(" / "))):t.push(o)}return s.t.apply(s,[e].concat(t))},getEmojiSubstitutedMessage:function(e){var e=new r.EaselJS.BigText(e),o=this.replacedEmojis;return e.textConstructor=function(e,t,n,i){e=new r.EaselJS.EmojiText(e,t,n,i);return e.setEmojis(o),e},e},alert:function(e,t){var t=this.Webcontrol.getViewFactory().alert(Object.assign({},t,{message:e})),n=this.Webcontrol.getViewFactory().getContainer();n.easelboneLayer.setView(t),t.render(),this.navigatableOverride=t,this.el.addChild(n),r.suppressPins(n),t.on("view:close",function(){n.easelboneLayer.view.trigger("stage:removed"),r.releasePins(n),this.el.removeChild(n),this.navigatableOverride=null}.bind(this))}})}),define("CatLab/Webremote/Tools/ImageLoader",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred"],function(i,o){return{loadedImages:{},loadImage:function(e){var t,n=new o;return this.loadedImages[e]?n.resolve(this.loadedImages[e]):((t=new Image).crossOrigin="anonymous",t.onload=function(){this.loadedImages[e]=t,n.resolve(this.loadedImages[e])}.bind(this),t.src=i.getProxiedImage(e)),n.promise()}}}),define("CatLab/Webremote/Tools/QrGenerator",["easelbone","qrious"],function(r,s){return{generateQrCode:function(e,t){var n=200,i=200,t=(e.getBounds()&&e.getBounds().width&&!e.getBounds().height&&(n=e.getBounds().width,i=e.getBounds().height),this.getGeneratedQrCode(t,Math.max(n,i)));return e.addChild(t),r.pinToTop(t),t},getGeneratedQrCode(e,t,n,i){void 0===n&&(n="#000000"),void 0===i&&(i="#ffffff");var o=new s,t=(o.level="H",o.size=2*t,o.value=e,o.background=i,o.foreground=n,new Image);return t.src=o.toDataURL(),new r.EaselJS.Fill(t,{zoom:"minimum"})}}}),define("CatLab/Webremote/CreateJS/Views/PortalView",["easeljs","easelbone","CatLab/Webremote/CreateJS/Views/BaseView","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/ImageLoader","CatLab/Webremote/Tools/QrGenerator","CatLab/Webremote/Messages/NavigateableProxy"],function(e,i,t,o,r,n,s){return t.extend({initialize:function(e){this.Webcontrol=e.Webcontrol,this.controllerState={activePlayers:0,minPlayers:0,maxPlayers:0,connectInstructions:[""],startAndLoginInstructions:[""],showInactivePlayers:!1,qrUrl:null},this.intitializeBaseView({orientation:this.ORIENTATION.HORIZONTAL}),this.messageBus=e.messageBus,this.assets=e.assets,this.initialized=!1,this.leanback=void 0!==e.leanback&&e.leanback,this.users=[],this.messageBus.toController("nav:controls",{controls:this._controls}),this.purchaseSeatsCallback=null,e.purchaseSeatsCallback&&(this.purchaseSeatsCallback=e.purchaseSeatsCallback),this.attachMessageBus(this.messageBus),this.on("stage:removed",this.destroy.bind(this))},initializeContent:function(){this.initialized||(this.initialized=!0,this.controllerState.showInactivePlayers?this.setScreen(new this.assets.PortalView):this.setScreen(new this.assets.PortalViewNoInactive),this.showInactivePlayers=this.controllerState.showInactivePlayers||!1,this.showInactivePlayers&&(this.connectedUsersContainer=new i.EaselJS.Placeholder(this.getScreen().connectedUsers),this.connectedUsers=new i.Controls.FloatContainer(function(e){return this.getUserIcon(e)}.bind(this),6),this.connectedUsersContainer.addChild(this.connectedUsers)),this.activeUsersContainer=new i.EaselJS.Placeholder(this.getScreen().activeUsers),this.activeUsers=new i.Controls.FloatContainer(function(e){return this.getUserIcon(e)}.bind(this),this.showInactivePlayers?6:9),this.activeUsersContainer.addChild(this.activeUsers),void 0!==this.getScreen().start&&(this.start=new i.Controls.Button(this.getScreen().start),this.start.setText(o.t("Start")),this.start.on("click",function(){this.messageBus.toController("start")}.bind(this)),this.addControl(this.start)),void 0!==this.getScreen().back&&(this.back=new i.Controls.Button(this.getScreen().back),this.back.setText(o.t("Back")),this.back.on("click",function(){this.messageBus.toController("back")}.bind(this)),this.addControl(this.back)),this.findPlaceholders("instructionHeader").forEach(function(e){e.addChild(new i.EaselJS.BigText(o.t("Instructions")))}),this.findPlaceholders("activePlayersHeader").forEach(function(e){e.addChild(new i.EaselJS.BigText(o.t("Active devices")))}),this.findPlaceholders("connectedPlayersHeader").forEach(function(e){e.addChild(new i.EaselJS.BigText(o.t("Connected devices")))}),this.instructionTexts=[],this.instructionTexts=this.findPlaceholders("instructionText"),this.updateInstructionText(),this.activePlayerTexts=[],this.findPlaceholders("activePlayers").forEach(function(e){var t=new i.EaselJS.BigText(this.getActiveUsersText());this.activePlayerTexts.push(t),e.addChild(t)}.bind(this)),this.qrContainers=this.findPlaceholders("qr"),this.qrInstructionsContainers=this.findPlaceholders("qrInstructions"))},attachMessageBus:function(e){e.addViewListener(this)},handleIncomingMessage:function(e,t){var n=this.navigatableOverride||this;if(!s.handleMessage(e,t,n,"portal:"))switch(e){case"state:change":var i=this.controllerState;this.controllerState=t.state,this.initialized?!i||JSON.stringify(i.connectInstructions)===JSON.stringify(t.state.connectInstructions)&&i.qrUrl===t.state.qrUrl||this.showInformation():this.initializeContent(),this.showCurrentAndMaxUsers();break;case"alert":if(t.id&&"exceeds-max-players"===t.id)if(this.purchaseSeatsCallback)return void this.alert(o.t(t.localized),{type:"confirm",okLabel:o.t("Purchase seats"),ok:function(e){e.close(),this.purchaseSeatsCallback()}.bind(this),cancelLabel:o.t("Cancel")});this.alert(o.t(t.localized));break;case"users:update":this.users=t.users,this.refreshUsers();break;case"auth:open":this.addAuthenticationView();break;case"portal:destroy":this.destroy()}},getActiveUsersText:function(){return this.controllerState.activePlayers+"/"+this.controllerState.maxPlayers},getInstructionText:function(){return this.substituteLabelsForInstructionMessage.apply(this,this.controllerState.connectInstructions)+"\n"+this.substituteLabelsForInstructionMessage.apply(this,this.controllerState.startAndLoginInstructions)},getUserIcon:function(e){var t,n;return e?e.profile?(t=new this.assets.UserIconAuthenticated,this.addControllerIcon(t,e)):t=this.getControllerIcon(e):t=this.getControllerIcon(),e&&(n=t.PlayerColor)&&new i.EaselJS.Placeholder(n).addChild(new i.EaselJS.Fill(e.color)),e&&this.setUserDetails(t,e),t},addControllerIcon:function(e,t){var n;e.ControllerIcon&&(e=new i.EaselJS.Placeholder(e.ControllerIcon),n=this.getControllerIcon(t),e.addChild(n),n.scaleX=n.scaleY=.5,t)&&(e=n.PlayerColor)&&new i.EaselJS.Placeholder(e).addChild(new i.EaselJS.Fill(t.color))},getControllerIcon:function(e){if(e)switch(e.type){case"keyboard":return new this.assets.UserIconKeyboard;case"tablet":return new this.assets.UserIconTablet;case"phone":return new this.assets.UserIconPhone;case"gamepad":return new this.assets.UserIconGamepad}return new this.assets.UserIcon},loading:function(){},refreshUsers:function(){this.getScreen()&&(this.showCurrentAndMaxUsers(),this.showInformation(),this.reloadUserIcons())},showCurrentAndMaxUsers:function(){var e=this.getScreen();e&&(e.playercount&&(e.playercount.text=this.controllerState.activePlayers+"/"+this.controllerState.maxPlayers),this.activePlayerTexts.forEach(function(e){e.setText(this.controllerState.activePlayers+"/"+this.controllerState.maxPlayers)}.bind(this)),e.login)&&(e.login.text=o.t(this.controllerState.startAndLoginInstructions))},showInformation:function(){var e,t=this.getScreen();t&&(e=o.t(this.controllerState.connectInstructions),t.login?t.login.text=o.t(this.controllerState.startAndLoginInstructions):e+="\n "+o.t(this.controllerState.startAndLoginInstructions),t.token&&(t.token.text=e),this.updateInstructionText(),this.updateQrCode())},updateInstructionText:function(){this.instructionTexts.forEach(function(e){var t=this.getEmojiSubstitutedMessage(this.getInstructionText());e.removeAllChildren(),e.addChild(t)}.bind(this))},updateQrCode:function(){this.qrContainers.forEach(function(e){e.removeAllChildren(),this.controllerState.qrUrl&&n.generateQrCode(e,this.controllerState.qrUrl)}.bind(this)),this.qrInstructionsContainers.forEach(function(e){var t;e.removeAllChildren(),this.controllerState.qrUrl&&(t=this.getEmojiSubstitutedMessage(o.t("Scan QR code to connect")),e.addChild(t))}.bind(this))},removeAllUserIcons:function(){this.showInactivePlayers&&this.connectedUsers.removeAllChildren(),this.activeUsers.removeAllChildren()},reloadUserIcons:function(){var t=24,n=24;this.showInactivePlayers||(n=45),this.removeAllUserIcons(),this.users.forEach(function(e){e.active?n<=0||(n--,this.activeUsers.createElement(e)):!this.showInactivePlayers||t<=0||(t--,this.connectedUsers.createElement(e))}.bind(this))},setUserDetails:function(e,t){var n;t.profile&&e.userimage&&(n=new i.EaselJS.Placeholder(e.userimage),r.loadImage(t.profile.image).then(function(e){n.addChild(new i.EaselJS.Fill(e))}))},addAuthenticationView:function(){var e=this.Webcontrol.authenticationView(this.messageBus,{leanback:this.leanback}),t=(this.el.addChild(e),!1),n=function(){t||(t=!0,e.easelboneLayer&&e.easelboneLayer.view&&e.easelboneLayer.view.trigger("stage:removed"),this.el.removeChild(e))}.bind(this);e.on("view:close",function(){n(),this.messageBus.toController("auth:close")}.bind(this)),e.on("close",n)},render:function(){var e=this.getScreen();e&&this.el&&(this.el.addChild(e),this.refreshUsers())},destroy:function(){this.messageBus.removeViewListener(this)}})}),define("CatLab/Webremote/CreateJS/Views/AuthenticationView",["easelbone","CatLab/Webremote/CreateJS/Views/BaseView","CatLab/Webremote/Tools/Images","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/ImageLoader","CatLab/Webremote/Tools/QrGenerator","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/Controllers/OAuth2"],function(o,e,t,r,s,a,n,i){return e.extend({initialize:function(e){var t;this.intitializeBaseView(),this.assets=e.assets,this.leanback=void 0!==e.leanback&&e.leanback,this.leanback?this.screen=new e.assets.SigninLeanback:this.screen=new e.assets.Signin,this.findFromNames(["close"],[this.screen]).forEach(function(e){e.on("click",function(){this.close()}.bind(this))}.bind(this)),this.screen.linkAccount&&(this.linkAccount=new o.Controls.Button(this.screen.linkAccount),this.linkAccount.on("click",function(){i.link(function(e){e&&"function"==typeof e.getAccessToken&&this.messageBus.toController("auth:add-access-token",{accessToken:e.getAccessToken(),select:!0})}.bind(this))}.bind(this))),this.titlePlaceholder=null,this.explanationPlaceholder=null,o.Helpers.MovieClipHelper.findFromNames(["title"],[this.screen]).forEach(function(e){this.titlePlaceholder=new o.EaselJS.Placeholder(e)}.bind(this)),o.Helpers.MovieClipHelper.findFromNames(["explanation"],[this.screen]).forEach(function(e){this.explanationPlaceholder=new o.EaselJS.Placeholder(e)}.bind(this)),this.titlePlaceholder&&(t=new o.EaselJS.BigText(r.t("Select your profile"),null,null,"left"),this.titlePlaceholder.addChild(t)),this.qrContainers=this.findPlaceholders("qr",this.screen),this.qrInstructionsContainer=this.findPlaceholders("qrInstructions",this.screen),this.setLoginUrlText(),o.Helpers.MovieClipHelper.findFromNames("accounts",[this.screen]).forEach(function(e){e=new o.Controls.ScrollArea(e);this.users=new o.Controls.FloatContainer(function(e){return this.getUserObject(e)}.bind(this),4),e.content.addChild(this.users)}.bind(this)),this.updateUsers([]),this.on("removed",function(){this.trigger("close")}.bind(this)),this.setBack(function(){this.close()}.bind(this)),this.on("close",this.releasePinSuppression.bind(this)),this.attachMessageBus(e.messageBus),this.on("stage:removed",this.destroy.bind(this))},attachMessageBus:function(e){(this.messageBus=e).addViewListener(this)},handleIncomingMessage:function(e,t){if(!n.handleMessage(e,t,this,"auth:"))switch(e){case"auth:users:update":this.updateUsers(t.users);break;case"auth:close":this.close();break;case"auth:loginurl":this.setLoginUrl(t.url);break;case"auth:destroy":this.destroy();break;case"labels:update":this.labels=t.labels,this.setLoginUrlText();break;case"auth:request-remove-selected-profile":this.removeSelectedUser()}},updateUsers:function(e){this.resetOptions(),this.users.removeAllChildren();for(var t=0;t<e.length;t++)this.users.createElement(e[t]);this.linkAccount&&this.addControl(this.linkAccount)},getUserObject:function(e){var t,n=new this.assets.UserModel,i=(n.namePlaceholder?n.text=n.namePlaceholder:n.name&&(n.text=n.name),new o.Controls.Button(n));return e&&(i.setText(e.name),t=new o.EaselJS.Placeholder(n.picture),s.loadImage(e.image).then(function(e){t.addChild(new o.EaselJS.Fill(e))}),i._userModel=e,i.on("click",function(){this.selectUser(e)}.bind(this)),this.addControl(i)),n},selectUser:function(e){this.messageBus.toController("auth:select-user",{user:{id:e.id}})},close:function(){this._closed||(this._closed=!0,this.trigger("close"),this.messageBus.toController("auth:close"))},render:function(){this.el.addChild(this.screen),o.suppressPins(this.el)},releasePinSuppression:function(){o.releasePins(this.el)},setLoginUrl:function(e){this.loginUrl=e,this.setLoginUrlText()},setLoginUrlText:function(){if(this.linkAccount&&this.linkAccount.setText(r.t("Login to add profile")),this.explanationPlaceholder){var e,t=[],n={selectProfile:"%s to select",removeProfile:"%s to remove",close:"%s to close"};for(e in n){var i=this.getLabelSubstitutionOrNull(e,n[e]);i&&t.push(i)}this.explanationPlaceholder.removeAllChildren(),0<t.length&&this.explanationPlaceholder.addChild(this.getEmojiSubstitutedMessage(t.join(", ")+"."))}this.loginUrl&&(this.qrContainers.forEach(function(e){"http"!==this.loginUrl.substring(0,4)&&(this.loginUrl="https://"+this.loginUrl),e.removeAllChildren(),a.generateQrCode(e,this.loginUrl)}.bind(this)),this.qrInstructionsContainer.forEach(function(e){var t=r.t("Scan to login or surf to %s",this.loginUrl);e.addChild(new o.EaselJS.BigText(t))}.bind(this)))},removeSelectedUser:function(){var e=this._current;e&&e._userModel?this.messageBus.toController("auth:remove-user",{user:{id:this._current._userModel.id}}):console.log("No current control")},destroy:function(){this.releasePinSuppression(),this.messageBus.removeViewListener(this)}})}),define("CatLab/Webremote/CreateJS/Views/AlertView",["easelbone","CatLab/Webremote/Tools/Translator","CatLab/Webremote/CreateJS/Views/BaseView"],function(o,r,e){return e.extend({initialize:function(n){"confirm"===(this.intitializeBaseView(),this.easelScreen=new n.assets.Alert,this.findPlaceholders("message").forEach(function(e){var t=new o.EaselJS.BigText(n.message);e.addChild(t)}),void 0===n.type&&(n.type="alert"),n.type.toLowerCase())?this.initializeConfirm(n):this.initializeAlert(n)},initializeAlert:function(e){var t=r.t("OK");void 0!==e.buttonLabel&&(t=e.buttonLabel),this.findFromNames("button").forEach(function(e){e=new o.Controls.Button(e);e.setText(t),this.addControl(e),e.click(function(){this.close()}.bind(this))}.bind(this)),setTimeout(function(){this.jumpToFrame("oneButton")}.bind(this),0)},initializeConfirm:function(t){var n=r.t("OK"),i=(void 0!==t.okLabel&&(n=t.okLabel),r.t("Cancel"));void 0!==t.cancelLabel&&(i=t.cancelLabel),this.findFromNames("button1").forEach(function(e){e=new o.Controls.Button(e);e.setText(n),this.addControl(e),e.click(function(){"function"!=typeof t.ok?this.close():t.ok(this)}.bind(this))}.bind(this)),this.findFromNames("button2").forEach(function(e){e=new o.Controls.Button(e);e.setText(i),this.addControl(e),e.click(function(){"function"!=typeof t.cancel?this.close():t.cancel(this)}.bind(this))}.bind(this)),setTimeout(function(){this.jumpToFrame("twoButtons")}.bind(this),0)},close:function(){this.trigger("view:close")},render:function(){this.el.addChild(this.easelScreen)}})}),define("CatLab/Webremote/ViewFactory/CreatejsViewFactory",["CatLab/Webremote/Tools/Deferred"],function(t){function e(e){void 0!==e&&this.setAssets(e)}var r,s,a,l,n=e.prototype;return n.initialize=function(){var e=new t;return this.loadAssets().then(function(){this.setAssets(this.assets),e.resolve()}.bind(this)),e},n.loadAssets=function(){var o=new t;return require(["CatLab/Webremote/CreateJS/LayerContainer","CatLab/Webremote/CreateJS/Views/PortalView","CatLab/Webremote/CreateJS/Views/AuthenticationView","CatLab/Webremote/CreateJS/Views/AlertView"],function(e,t,n,i){r=e,s=t,a=n,l=i,o.resolve()}.bind(this)),o.promise()},n.portal=function(e){return e.assets=this.assets,new s(e)},n.authentication=function(e){return e.assets=this.assets,new a(e)},n.alert=function(e){return e.assets=this.assets,new l(e)},n.setAssets=function(e){void 0!==e&&(this.assets=e)},n.getContainer=function(){var e=new r;return e.setBounds(0,0,this.assets.properties.width,this.assets.properties.height),e.loading(),e},e}),define("CatLab/Webremote/PlayerPool/GameLogic",["CatLab/Webremote/Tools/Deferred"],function(n){function e(){}var t=e.prototype;return t.setPool=function(e){return this.pool=e,this},t.createPlayer=function(e,t){return null},t.createPlayerConnection=function(e,t){return null},t.onPlayerJoined=function(e){},t.onPlayerActivated=function(e,t){},t.onPlayerJoinedComplete=function(e){},t.getDefaultPlayerName=function(e,t){return null},t.serializePlayer=function(e,t){return e.serialize()},t.playerMatchesFilter=function(e,t){return!1},t.onReset=function(){},t.onResetGameState=function(){},t.comparePlayers=function(e,t){return 0},t.getRandomPickComparator=function(e){return null},t.getMaxPlayers=function(){return null},t.getMaxPlayersForMode=function(e){return this.getMaxPlayers()},t.setMaxPlayers=function(e){return!1},t.addAccessToken=function(e){},t.checkForLicenses=function(e){var t=new n;return t.resolve(e),t.promise()},t.decorateWebcontrolOptions=function(e,t){},t.onWebcontrolInitialized=function(e,t){},t.onGroupCreating=function(e,t){},t.onKeyboardUserChanged=function(e,t){},t.onGroupCreated=function(e,t){},t.getViewId=function(e){return null},t.getDefaultAvatarUrl=function(){return null},t.getPortalCustomFunctions=function(){return{}},t.serializeGameState=function(){return{}},t.restoreGameState=function(e,t){},e}),define("CatLab/Webremote/PlayerPool/Player",["backbone"],function(e){var n=e.Model.extend({initialize:function(e,t){this._getGameLogic=t&&t.getGameLogic||null,void 0!==this.get("hasAnsweredAnyQuestion")&&void 0===this.get("hasParticipated")&&this.set("hasParticipated",this.get("hasAnsweredAnyQuestion"))},getGameLogic:function(){return this._getGameLogic?this._getGameLogic():null},getName:function(e){return this.getUser().getNickname()},getPosition:function(){return this.collection?this.collection.getPosition(this):null},getColor:function(){return this.get("user").color},getLocale:function(){return this.getDefaultLocale()},getDefaultLocale:function(){return null},getAvatar:function(){if(!this.getUserField("avatar")){if(!this.getUser())return null;if(void 0===this.getUser().getSmileyUrl)return null;var e=this.getUser().getSmileyUrl();if(e)return e}e=this.getGameLogic(),e=e?e.getDefaultAvatarUrl():null,e=this.getUserField("avatar",e);return e?this.resolveAvatarUrl(e):null},resolveAvatarUrl:function(e){return e},getUserField:function(e,t){t=t||null;var n=this.get("user");return(n=n&&n.getData())&&void 0!==n[e]?n[e]:t},getUser:function(){return this.get("user")},isActive:function(){return!this.get("noShow")||this.get("noShow")<5},setInactive:function(){this.set("noShow",1e3)},pingActive:function(){this.set("noShow",0),this.set("hasParticipated",1)},pingNoShow:function(){this.get("noShow")?this.set("noShow",this.get("noShow")+1):this.set("noShow",1)},isPlaying:function(){return this.get("hasParticipated")||this.isActive()},getId:function(){return this.get("id")?this.get("id"):this.id},hasDisplay:function(){return!!this.get("user")&&this.get("user").hasDisplay()},getLanguage:function(){return this.get("language")},setLanguage:function(e){return this.set("language",e),this},isActivated:function(){return this.get("wasActivated")},activate:function(){this.set("wasActivated",!0)},deactivate:function(){this.set("wasActivated",!1)},kick:function(){this.deactivate()},matchesPlayerFilter:function(e){var t;return null==e||void 0!==e.ids&&0<=e.ids.indexOf(this.getId())||!!(t=this.getGameLogic())&&t.playerMatchesFilter(this,e)},serialize:function(){return{id:this.get("id"),user:this.get("user").getIdentifier(),language:this.get("language"),hasParticipated:this.get("hasParticipated"),extraData:this.get("extraData")}}});return n.unserialize=function(e,t){return new n(e,t)},n}),define("CatLab/Webremote/PlayerPool/DeviceConnection",[],function(){function e(e,t){this.player=t,this.pool=e,this.user=this.player.get("user"),this.cheatsDetected=0,this.lastCheatDetected=null,this.cheatDetectedSincePrompt=!1,"group"===this.player.get("user").getEntityType()&&this.player.get("user").on("user:join",function(){this.player.pingActive()}.bind(this)),this.user.events.on("cheat:detected",function(){this.cheatsDetected++,this.lastCheatDetected=new Date,this.cheatDetectedSincePrompt=!0}.bind(this)),this.lastClick=null,this.beforeNextViewChange=null}var t=e.prototype;return t.isAuthenticated=function(){return this.player.get("user").isAuthenticated()},t.quickClickProtect=function(){return!(this.lastClick&&Date.now()-this.lastClick<500||(this.lastClick=Date.now(),0))},t.beginTimedPrompt=function(e,t,n){void 0!==n&&!n||(this.cheatDetectedSincePrompt=!1),this._setTimerDurationAttribute(e,t)},t._setTimerDurationAttribute=function(e,t){this.pool.isLargeGroup()||(e.domAttribute("timer-countdown","to",Date.now()+t),e.domAttribute("timer-countdown","start",Date.now()))},t.setView=function(e){return"function"==typeof this.beforeNextViewChange&&(this.player.get("user").currentView&&this.beforeNextViewChange(this.player.get("user").currentView),this.beforeNextViewChange=null),this.player.get("user").setView(e)},t.matchesPlayerFilter=function(e){return this.player.matchesPlayerFilter(e)},t.kick=function(){this.player.kick();var e=this.pool.getGameLogic().getViewId("kicked");e&&this.setView(e).control("name").setLabel(this.player.getName())},t.wait=function(){},e}),define("CatLab/Webremote/Collections/PlayerCollection",["backbone","CatLab/Webremote/PlayerPool/Player"],function(e,o){var r=e.Collection.extend({model:o,initialize:function(e,t){this._getKeyboardUser=(t=t||{}).getKeyboardUser||function(){return null},this._getGameLogic=t.getGameLogic||function(){return null}},getPosition:function(e){return this.indexOf(e)+1},getFromId:function(e){return this.findWhere({id:e})},getFromUser:function(t){var n=null;return this.each(function(e){e.get("user").represents(t.getIdentifier())&&(n=e)}),n},hasKeyboardPlayer:function(){var e=this._getKeyboardUser();return!!e&&!!this.getFromUser(e)},comparator:function(e,t){var n=this._getGameLogic();return n?n.comparePlayers(e,t):0},whereActive:function(){return new r(this.filter(function(e){return e.get("user").isActive()}),{getGameLogic:this._getGameLogic,getKeyboardUser:this._getKeyboardUser})},serialize:function(){var t=[];return this.each(function(e){t.push(e.serialize())}),t}});return r.unserialize=function(e,t){for(var n=new r(null,t=t||{}),i=0;i<e.length;i++)n.add(o.unserialize(e[i],t));return n},r}),define("CatLab/Webremote/PlayerPool/RandomPlayerList",["underscore"],function(o){function e(e,t){this.playerPool=e,this._getGameLogic=(t=t||{}).getGameLogic||function(){return null},this.nextRandomPlayers=[],this.tmpNextRandomPlayers=[],this.tmpSelectedRandomPlayers=[]}var t=e.prototype;return t.getRandomPlayers=function(e,t,n,i){void 0===n&&(n=!0);for(var o=[],r=0;r<e;r++)o.push(this.getRandomPlayer(t,n,i));return o},t.resetRandomPlayers=function(e){this.tmpNextRandomPlayers=this.refillRandomPlayers(e,[]),this.commitRandomPlayers()},t.commitRandomPlayers=function(){this.nextRandomPlayers=this.tmpNextRandomPlayers,this.tmpSelectedRandomPlayers=[]},t.addPlayer=function(e){this.nextRandomPlayers.push(e.getId()),this.tmpNextRandomPlayers.push(e.getId())},t.getRandomPlayer=function(e,t,n){if(void 0===t&&(t=!0),0===this.playerPool.activePlayers.length)return null;for(var i=0;;){0===this.tmpNextRandomPlayers.length&&(this.tmpSelectedRandomPlayers.length>=this.playerPool.activePlayers.length?this.tmpNextRandomPlayers=this.refillRandomPlayers(e,[]):this.tmpNextRandomPlayers=this.refillRandomPlayers(e,this.tmpSelectedRandomPlayers));var o=this.tmpNextRandomPlayers.shift(),r=this.playerPool.activePlayers.getFromId(o),s=this.playerPool.getPlayerConnection(r);if(r.isActivated()&&((!t||r.isActive())&&s.matchesPlayerFilter(n)||s.matchesPlayerFilter(n)&&i>this.playerPool.activePlayers.length-1||i>=2*this.playerPool.activePlayers.length))return this.tmpSelectedRandomPlayers.push(o),r;i++}},t.refillRandomPlayers=function(e,t){var n=this.playerPool.activePlayers.filter(function(e){return!!e.isActivated()&&t.indexOf(e.getId())<0}),i=this._getGameLogic(),i=i?i.getRandomPickComparator(e):null,n=i?n.sort(i):o.shuffle(n);return o.map(n,function(e){return e.getId()})},t.serialize=function(){return{nextRandomTeams:this.nextRandomPlayers}},t.unserialize=function(e){this.tmpNextRandomPlayers=[],void 0!==e.nextRandomPlayers?this.tmpNextRandomPlayers=e.nextRandomPlayers:void 0!==e.nextRandomTeams&&(this.tmpNextRandomPlayers=e.nextRandomTeams),this.tmpSelectedRandomPlayers=[]},e}),define("CatLab/Webremote/Tools/Timer/Timer",[],function(){return function(e,t,n){var i,o,r=n;this.id=e,this.callback=t,this.pause=function(){window.clearTimeout(i),r-=new Date-o},this.resume=function(){o=new Date,window.clearTimeout(i),i=window.setTimeout(function(){this.onFinished(),t()}.bind(this),r)},this.stop=function(){window.clearTimeout(i),this.onFinished()},this.onFinished=function(){},this.resume()}}),define("CatLab/Webremote/Tools/Timer/Interval",[],function(){return function(e,t,n,i){var o,r,s,a=0,l=0,c=!0;this.id=e,this.callback=t,this.pause=function(){c||(c=!0,window.clearTimeout(o),window.clearInterval(r),a=n-(new Date-s)%n)},this.resume=function(){c&&(c=!1,s=new Date,window.clearTimeout(o),window.clearInterval(r),o=window.setTimeout(function(){s=new Date,r=window.setInterval(function(){l++,null!==i&&i<=l&&this.stop(),t()}.bind(this),n)}.bind(this),a))},this.stop=function(){window.clearTimeout(o),window.clearInterval(r),this.onFinished()},this.onFinished=function(){},this.resume()}}),define("CatLab/Webremote/Tools/Timer/TimerCollection",["CatLab/Webremote/Tools/Timer/Timer","CatLab/Webremote/Tools/Timer/Interval"],function(i,o){return function(){this.timers=[],this.paused=!1,this.id=0,this.setTimeout=function(e,t){var n=new i(this.id++,e,t);return this.paused&&n.pause(),n.onFinished=function(){this.deleteTimer(n)}.bind(this),this.timers.push(n),n},this.setInterval=function(e,t,n){var i=new o(this.id++,e,t,n);return this.paused&&i.pause(),i.onFinished=function(){this.deleteTimer(i)}.bind(this),this.timers.push(i),i},this.deleteTimer=function(e){e=this.timers.indexOf(e);-1<e&&this.timers.splice(e,1)},this.pause=function(){this.paused=!0,this.timers.forEach(function(e){e.pause()})},this.resume=function(){this.paused=!1,this.timers.forEach(function(e){e.resume()})},this.stop=function(){for(;0<this.timers.length;)this.timers.pop().stop()}}}),define("CatLab/Webremote/PlayerPool/PlayerPool",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/Models/Users/DummyUser","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/PlayerPool/GameLogic","CatLab/Webremote/PlayerPool/Player","CatLab/Webremote/PlayerPool/DeviceConnection","CatLab/Webremote/Collections/PlayerCollection","CatLab/Webremote/PlayerPool/RandomPlayerList","CatLab/Webremote/Tools/Timer/TimerCollection","underscore"],function(e,s,t,o,i,n,r,a,l,c,h,u,d){function f(){this.initializeEventable(),this.globalAccessTokens=[],this.keyboardUser=null,this._localDevices=null,this.reset(),this.timers=new u,this.config={DELAY:0,USE_SMILEYS:!1,MAX_PLAYERS:8,DISABLE_PROXY:!0,ALLOW_LOGIN:!0,oauth2:null,PROXY_URL:null,getWebcontrolOptions:function(){return{}},applyOverrides:function(e){if(e)for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}}}var e=f.prototype=new e,p=(e._poolNumber=1,e.mode="regular",e.reset=function(){this.users=[],this.connectController=null,this._playercount=0,this.maxPlayers=8;var e=this;this.activePlayers=new c(null,{getKeyboardUser:function(){return e.getKeyboardUser()},getGameLogic:function(){return e.getGameLogic()}}),this.playerMap={},this.playerConnections=[],this.rejectedPlayers=[],this._playerTypeCount={},this.currentPlayerMethod=null,this.randomPlayerLists={},this.lastAction=new Date,this._leasedSeats=void 0,this._portalMaxPlayers=void 0,this._cachedMaxPlayers=null,this.onboardView=null,this.onboardViewListener=null,this.pleaseWaitListener=null,this.Webcontrol||(this.Webcontrol=new t),this.resetGameState(),this.pleaseWaitListener&&(this.Webcontrol.off("user:join",this.pleaseWaitListener),this.pleaseWaitListener=null),this.onboardViewListener&&(this.Webcontrol.off("user:join",this.onboardViewListener),this.onboardViewListener=null),this.getGameLogic().onReset()},e.resetGameState=function(){this.started=!1,this.admissionsClosed=!1,this._totalPausedDuration=0,this._pauseStartTime=null,this._pausedSinceWindowStart=!1,this.getGameLogic().onResetGameState()},e.setGameLogic=function(e){return this.gameLogic=e.setPool(this),this},e.getGameLogic=function(){return this.gameLogic||(this.gameLogic=(new r).setPool(this)),this.gameLogic},e._showView=function(e,t){t=this.getGameLogic().getViewId(t);return t&&e.setView(t),t},e.invokePoolMethod=function(e,t){if("function"==typeof this[e])return this[e].apply(this,p(this[e],t));var n=this.getGameLogic();if("function"==typeof n[e])return n[e].apply(n,p(n[e],t));throw new Error("PlayerPool: unknown method "+e)},function(e,t){if(!t||0===t.length||!(i=t[t.length-1])||"object"!=typeof i||!Object.prototype.hasOwnProperty.call(i,"__playerFilters")||1!==Object.keys(i).length)return t;for(var n=t.slice(0,-1),i=t[t.length-1].__playerFilters;n.length<e.length-1;)n.push(void 0);return n.push(i),n});return e.initialize=function(n){(n=void 0===n?{}:n).config&&(this.config=n.config),this._workerHosted=!!n.headless,void 0!==n.playerPoolMode&&(this.mode=n.playerPoolMode),"number"==typeof n.poolNumber&&(this._poolNumber=n.poolNumber),this.trigger("change:mode",this.mode);var t=new s,e=function(){var e,t=new s;return void 0!==n.headless&&n.headless?t.resolve():(this.log("Starting webremote createjs initialization"),void 0!==n.portalAssets?(e=new i(n.portalAssets),this.Webcontrol.setViewFactory(e).then(function(){this.timers.setTimeout(function(){t.resolve()},1)}.bind(this))):(console.error("Portal assets not found!!!"),t.resolve())),t.promise()}.bind(this)();return s.when(e).done(function(){this.log("Start webremote");var e=this.initializeWebcontrol(n);e.done(function(){this.log("Webcontrol loaded")}.bind(this)),s.when(e).done(function(){t.resolve()}.bind(this))}.bind(this)),t.promise()},e.initializeWebcontrol=function(t){var n=new s,i=this,o=this.config.getWebcontrolOptions(),r=t.webcontrolOptions||{};return Object.keys(r).forEach(function(e){o[e]=r[e]}),void 0!==t.headless&&!t.headless||(o.headless=!1),this.getGameLogic().decorateWebcontrolOptions(o,t),this.Webcontrol.initialize(o).then(function(){i.config.DISABLE_PROXY||i.Webcontrol._gamedata&&i.Webcontrol._gamedata.content_proxy&&(i.config.PROXY_URL=i.Webcontrol._gamedata.content_proxy),i.Webcontrol.setMaxUsers(i.config.MAX_PLAYERS),i._licenseToken&&i.Webcontrol.setLicenseToken(i._licenseToken),i.Webcontrol.on("license:capped",function(e){i.trigger("license:capped",e)}),i.config.oauth2&&i.Webcontrol.oAuth(i.config.oauth2,!i.config.ALLOW_LOGIN);function e(){var e=i.Webcontrol.getUsers().filter(function(e){return!e.getEntityType||"group"!==e.getEntityType()||!!(e.users&&0<e.users.length)}).length;i.trigger("change:connections",e)}i.Webcontrol.on("user:join",e),i.Webcontrol.on("user:leave",e),i._notifyConnectedDevices=e,i.getGameLogic().onWebcontrolInitialized(i.Webcontrol,t),n.resolve()}),n.promise()},e.getConnectController=function(n){this.reset(),this._pendingPortalClose=null,this._portalOpening=!0,n.customFunctions=d.extend({},this.getGameLogic().getPortalCustomFunctions(),n.customFunctions||{});var e=this.Webcontrol.portalController(n),t=void 0!==n.start?n.start:function(){};return n.start=function(e){e.forEach(function(e){e.setActive(!0),this.clearConnectScreen(),this.addUser(e)}.bind(this)),t(e)}.bind(this),e.promise.then(function(t){var e;this._portalOpening=!1,this.connectController=t,this._pendingPortalClose?(e=this._pendingPortalClose,this._pendingPortalClose=null,this.closeConnectController(e)):("function"==typeof t.on&&(t.on("active:count",function(e){this.trigger("portal:active:count",e)}.bind(this)),t.on("users:change",function(e){this.trigger("portal:users",e)}.bind(this)),"function"==typeof t.updateUsers)&&t.updateUsers(),t.setMaxPlayers(this._effectivePortalMax(n.maxPlayers)),this.checkForLicenses(this.Webcontrol.getUsers()).then(function(){t.setMaxPlayers(this._effectivePortalMax(this.getMaxPlayersForMode(this.mode)))}.bind(this)),this.Webcontrol.getUsers().forEach(function(e){e.on("login",function(e){this.checkForLicenses([e]).then(function(){t.setMaxPlayers(this._effectivePortalMax(this.getMaxPlayersForMode(this.mode)))}.bind(this))}.bind(this))}.bind(this)),t.on("user:connect",function(e){e.on("login",function(e){this.checkForLicenses([e]).then(function(){t.setMaxPlayers(this._effectivePortalMax(this.getMaxPlayersForMode(this.mode)))}.bind(this))}.bind(this))}.bind(this)))}.bind(this)),e},e.closeConnectController=function(e){var t=this.connectController;t?(this.connectController=null,"start"===e&&"function"==typeof t.finalizeStart?t.finalizeStart():t.destroy()):this._portalOpening&&(this._pendingPortalClose=e)},e.getConnectScreen=function(e){var t=this.getConnectController(e);return this.Webcontrol.portalView(t.messageBus,e)},e.setPublicConnectInfo=function(e){this.connectController&&"function"==typeof this.connectController.setPublicConnectInfo&&this.connectController.setPublicConnectInfo(e)},e.setExternalActivePlayers=function(e){this.connectController&&"function"==typeof this.connectController.setExternalActivePlayers&&this.connectController.setExternalActivePlayers(e)},e.setExternalUsers=function(e){e=e||[],"function"==typeof this.Webcontrol.setExternalPlayerOffset&&this.Webcontrol.setExternalPlayerOffset(e.length),this.connectController&&"function"==typeof this.connectController.setExternalUsers&&this.connectController.setExternalUsers(e)},e.clearConnectScreen=function(){this.connectController=null},e.getAccessTokens=function(){for(var e=new s,t=this.globalAccessTokens.slice(),n=this.Webcontrol.getUsers(),i=0;i<n.length;i++){var o=n[i];o.isAuthenticated()&&t.push(o.getAccessToken())}return e.resolve(t),e.promise()},e.getConnectTokenForDisplay=function(){return this.Webcontrol.getConnectTokenForDisplay()},e.getConnectURL=function(){return this.Webcontrol.getConnectURL()},e.getConnectToken=function(){return this.Webcontrol.getConnectToken()},e.setLocalDeviceRegistry=function(e){this._localDevices=e},e.getLocalDevice=function(e){return this._localDevices?this._localDevices.get(e):null},e.getLocalDevices=function(){return this._localDevices?this._localDevices.list():[]},e.setKeyboardUser=function(e){if("string"==typeof e){var t=this.getLocalDevice(e);if(!(t=!t&&this.Webcontrol&&"function"==typeof this.Webcontrol.getFromIdentifier?this.Webcontrol.getFromIdentifier({type:"user",id:e}):t))throw new Error('setKeyboardUser: unknown device or user "'+e+'"');e=t}e!==this.keyboardUser&&(this.keyboardUser&&(this.keyboardUser.setActive(!1),t=this.getConnectedPlayer(this.keyboardUser))&&t.deactivate(),t=this.keyboardUser,this.keyboardUser=e,this.getGameLogic().onKeyboardUserChanged(e,t))},e.activateKeyboardUser=function(e){var t=this.keyboardUser;if(!t)return!1;t.setActive(!0);var n=this.addUser(t);return void 0!==e&&n&&(e.name&&t.setNickname(e.name),e.email&&(n.get("user").email=e.email),n.set("extraData",e)),!0},e.hasKeyboardPlayer=function(){return this.activePlayers.hasKeyboardPlayer()},e.startGame=function(){var e=new s;return this.ping(!1).then(function(){this.callPlayerConnectionMethod(function(e){e.startGame()})}.bind(this)),e.resolve(),e.promise()},e.newGroup=function(n,i,o){2===arguments.length&&(o=i,i=void 0);var r=new s;return this.Webcontrol.newGroup({shareColor:!0}).then(function(e){e.profiledata.username=n,e.data.set("name",n,!1),e.setNickname(n),e.startInactive=!0,this.getGameLogic().onGroupCreating(e,{name:n,departmentName:i,extra:o});var t=this.addUser(e);void 0!==o&&0<Object.keys(o).length&&(void 0!==o.email&&(t.get("user").email=o.email),t.set("extraData",o)),this.getGameLogic().onGroupCreated(e,{name:n,departmentName:i,extra:o,user:t}),r.resolve(t)}.bind(this)),r.promise()},e.showIndexScreen=function(){var n=new s,i=this;function t(e){var t;e.isMainGroup()&&(t=i.getGameLogic().getViewId("start"))&&((e=e.setView(t)).control("start").click(function(){n.resolve()}),e.control("a").click(function(){n.resolve()}))}var o=this.Webcontrol.on("user:join",function(e){t(e)});return this.Webcontrol.getUsers().forEach(function(e){t(e)}),n.then(function(){var e=new s;return this.Webcontrol.off("user:join",o),this.Webcontrol.getUsers().forEach(function(e){this._showView(e,"pleasewait")}.bind(this)),this.pleaseWaitListener=this.Webcontrol.on("user:join",function(e){e.isMainGroup()&&this._showView(e,"pleasewait")}.bind(this)),e.resolve(),e.promise()}.bind(this))},e.disconnect=function(){var e=new s;return this.Webcontrol.disconnect(),this.log("webremote disconnected"),e.resolve(),e.promise()},e.getAuthenticationController=function(e){return this.Webcontrol.authenticationController(this.getKeyboardUser(),e)},e.refreshConnectedDevices=function(){this._notifyConnectedDevices&&this._notifyConnectedDevices()},e.setLeasedSeats=function(e){var t=this._leasedSeats;this._leasedSeats=e,"number"==typeof t&&t<e&&this.retryRejectedPlayers()},e.setLicenseToken=function(e){this._licenseToken=e,this.Webcontrol&&this.Webcontrol.setLicenseToken(e)},e.setPortalMaxPlayers=function(e){var t=e;"live"!==this.mode&&"presentation"!==this.mode&&(t=Math.min(100,e)),this._portalMaxPlayers=t,this.connectController&&this.connectController.setMaxPlayers(t)},e._effectivePortalMax=function(e){return"number"!=typeof this._portalMaxPlayers?e:"number"!=typeof e?this._portalMaxPlayers:Math.max(e,this._portalMaxPlayers)},e.hasGlobalAccessTokens=function(){return 0<this.globalAccessTokens.length},e.setOnboardView=function(e){this.onboardView=e,this.pleaseWaitListener&&(this.Webcontrol.off("user:join",this.pleaseWaitListener),this.pleaseWaitListener=null),this.onboardViewListener&&this.Webcontrol.off("user:join",this.onboardViewListener),this.Webcontrol.getUsers().forEach(function(e){e.isMainGroup()&&this.addUser(e)}.bind(this)),this.onboardViewListener=this.Webcontrol.on("user:join",function(e){e.isMainGroup()&&this.addUser(e)}.bind(this))},e.showOnboardingView=function(e){"function"==typeof e.showOnboardingView&&e.showOnboardingView(this.onboardView).then(function(){this.callCurrentPlayerConnectionMethod(e)}.bind(this))},e.getMaxPlayers=function(){var e=this.getGameLogic().getMaxPlayers();return null!=e?e:this.maxPlayers},e.getMaxPlayersForMode=function(e){void 0===e&&(e=this.mode);e=this.getGameLogic().getMaxPlayersForMode(e);return null!=e?e:this.getMaxPlayers()},e.setMaxPlayers=function(e){this.getGameLogic().setMaxPlayers(e)||(this.maxPlayers=e,this.connectController&&this.connectController.setMaxPlayers(e),e=this.getMaxPlayers(),this._cachedMaxPlayers!==e&&(this._cachedMaxPlayers=e,this.trigger("change:maxplayers",e)))},e.addAccessToken=function(e){this.getGameLogic().addAccessToken(e)},e.checkForLicenses=function(e){return this.getGameLogic().checkForLicenses(e)},e.getKeyboardUser=function(){return this.keyboardUser},e.addFakePlayer=function(e,t){var n=this.userToPlayer(e);return e.setNickname(t),n.pingActive(),this.addPlayer(n),n},e.createDummyUser=function(e,t,n){n=n||{};var i=new o,i=(this.Webcontrol.addCustomControl(i),this.userToPlayer(i)),e=(i.get("user").setNickname(e),void 0!==n.smiley&&i.get("user").setSmiley(n.smiley),void 0!==t&&i.set("bot",t),n.autonomous&&i.set("autonomous",!0),this.addPlayer(i,!1));return this.addActivePlayer(i,e),i.pingActive(),"number"==typeof n.score&&i.set("score",n.score),this.trigger("player:dummy:created",e,!0===t,n),this.getGameLogic().serializePlayer(i,!0)},e.addUser=function(e){var t=this.getConnectedPlayer(e);return null!==t?this.log("User "+e.id+" was already connected"):(t=this.userToPlayer(e),this.addPlayer(t)),t},e.addPlayer=function(t,e){if(!(e=void 0===e?!0:e)||this.checkPlayerCapacity(t))return e=this.getGameLogic().createPlayerConnection(this,t)||new l(this,t),this.playerConnections.push(e),t.deactivate(),this.getRandomPlayerLists().forEach(function(e){e.addPlayer(t)}),this.connectController||this.getGameLogic().onPlayerJoined(e)||this.callCurrentPlayerConnectionMethod(e)||(this.addActivePlayer(t,e),e.wait()),this.trigger("user:join"),this.updateActivePlayers(),this.getGameLogic().onPlayerJoinedComplete(e),e},e.checkPlayerCapacity=function(e){var t;return"live"===this.mode||(t="number"==typeof this._leasedSeats?this._leasedSeats:this.getMaxPlayers(),!(this.actualPlayersLength>=t&&(this._showView(e.get("user"),"maxPlayers"),this.isPlayerRejected(e)||this.rejectedPlayers.push(e),1)))},e.retryRejectedPlayers=function(){var i;0!==this.rejectedPlayers.length&&(this.started?(this.log("Game already started, clearing rejected players list"),this.rejectedPlayers=[]):(this.log("Retrying "+this.rejectedPlayers.length+" rejected players after capacity increase"),i=this.Webcontrol.getUsers(),this.rejectedPlayers.slice().forEach(function(e){var t,n=e.get("user");this.isUserStillConnected(n,i)?(this.removeRejectedPlayer(e),this.log("Retrying player: "+n.id),(t=this.addPlayer(e,!0))?this.onboardView?this.showOnboardingView(t):this._showView(n,"pleasewait"):this.isPlayerRejected(e)||this.rejectedPlayers.push(e)):(this.removeRejectedPlayer(e),this.log("User "+n.id+" disconnected, skipping retry"))}.bind(this))))},e.removeRejectedPlayer=function(e){e=this.rejectedPlayers.indexOf(e);-1<e&&this.rejectedPlayers.splice(e,1)},e.isPlayerRejected=function(e){var t=e.get("user");return this.rejectedPlayers.some(function(e){return e.get("user")===t})},e.isUserStillConnected=function(t,e){return(e=e||this.Webcontrol.getUsers()).some(function(e){return e===t||e.id===t.id})},e.addActivePlayer=function(e,t){this.activePlayers.push(e),e.collection=this.activePlayers,e.activate(),this.getGameLogic().onPlayerActivated(e,t),this.admissionsClosed&&setTimeout(function(){t.eliminate()},1)},e.updateActivePlayers=function(){this.trigger("change:actualLength",this.actualPlayersLength),this.trigger("change:length",this.length)},e.getPlayers=function(){var e=new s;return e.resolve(this.activePlayers),e.promise()},e.forEachPlayer=function(t){return this.getPlayers().then(function(e){e.each(t)})},e.getPlayerConnection=function(t){var e=this.playerConnections.find(function(e){return e.player.getId()===t.id});if(e)return e;this.log("Connection for player not found!",t)},e.hasUser=function(e){return null!==this.getConnectedPlayer(e)},e.getConnectedPlayer=function(e){for(var t=0;t<this.playerConnections.length;t++)if(this.playerConnections[t].user===e)return this.playerConnections[t].player;return null},e._mintPlayerId=function(){return this._playercount++,this._poolNumber+"-"+this._playercount},e.userToPlayer=function(e){var t={id:this._mintPlayerId(),user:e,connectToken:e.getConnectToken(),connectTokenForDisplay:e.getConnectTokenForDisplay()},n=this,i={getGameLogic:function(){return n.getGameLogic()}},o=this.getGameLogic().createPlayer(t,i)||new a(t,i);return this.playerMap[o.getId()]=o,!e.startInactive&&e.isActive()||(o.setInactive(),e.isActive())||e.once("active:activate",function(){o.pingActive()}),e.on("active:change",this.updateActivePlayers,this),o},e.getDefaultPlayerName=function(e){var t=e.getType(),t=(void 0===this._playerTypeCount[t="mobile"===t?"player":t]&&(this._playerTypeCount[t]=0),this._playerTypeCount[t]++,this._playerTypeCount[t]),e=this.getGameLogic().getDefaultPlayerName(e,t);return null!=e?e:"Player "+t},e.hasNonDisplayUsers=function(e){for(var t,n=0;n<this.activePlayers.length;n++)if(!(t=this.activePlayers.at(n)).get("user").hasDisplay()){if(t.get("user").hasKeyboardInput()&&t.get("user").hasTouchInput()&&void 0!==e&&!0===e&&this.getKeyboardUser()&&t.get("user")===this.getKeyboardUser())continue;return!0}return!1},e.getNavigationUsers=function(e){var t;return(e=void 0===e?!0:e)?t=this.Webcontrol.getUsers():(t=[],this.Webcontrol.getUsers().forEach(function(e){e.hasDisplay()||t.push(e)})),t},e.callPlayerConnectionMethod=function(e,t,n){var i=[];return this.currentPlayerMethod=e,this.playerConnections.forEach(function(e){(n||e.player.isActivated())&&e.matchesPlayerFilter(t)&&i.push(this.currentPlayerMethod(e))}.bind(this)),s.when.apply(this,i)},e.clearPlayerConnectionMethod=function(){this.currentPlayerMethod=null},e.callCurrentPlayerConnectionMethod=function(e){return null!==this.currentPlayerMethod&&(this.currentPlayerMethod(e),!0)},e.countActivePlayers=function(){return this._countActivePlayers()},e._countActivePlayers=function(){var t=0;return this.activePlayers.each(function(e){e.isActive()&&t++}),t},e.sortPlayers=function(){this.activePlayers.sort()},e.isLargeGroup=function(){return this.length>(this.config.LARGE_GROUP_THRESHOLD||350)},e.getRandomPlayerLists=function(){var e,t=[];for(e in this.randomPlayerLists)this.randomPlayerLists.hasOwnProperty(e)&&t.push(this.randomPlayerLists[e]);return t},e.kickUser=function(e){e=this.getPlayerConnection(e);e.kick(),this.activePlayers.remove(e.player),this.updateActivePlayers()},e.requestNewNickname=function(e){var t=this.getPlayerConnection(e);if(!t)return!1;t.requestNewNickname().then(function(){this.callCurrentPlayerConnectionMethod(t)}.bind(this))},Object.defineProperty(e,"length",{get:function(){return this.activePlayers.size()}}),Object.defineProperty(e,"actualPlayersLength",{get:function(){return this.activePlayers.filter(function(e){return!e.get("bot")}).length}}),e.log=function(e){console.log("[PlayerPool] ",e)},e.pause=function(){this.Webcontrol.pause(),this.timers.pause(),this._pauseStartTime||(this._pauseStartTime=(new Date).getTime()),this._pausedSinceWindowStart=!0},e.resume=function(){this.Webcontrol.unpause(),this.timers.resume(),this._pauseStartTime&&(this._totalPausedDuration+=(new Date).getTime()-this._pauseStartTime,this._pauseStartTime=null)},e.getPausedDuration=function(){var e=this._totalPausedDuration;return this._pauseStartTime&&(e+=(new Date).getTime()-this._pauseStartTime),e},e.resetPauseWindow=function(){this._totalPausedDuration=0,this._pauseStartTime=this._pauseStartTime?(new Date).getTime():null,this._pausedSinceWindowStart=!1},e.wasPausedSinceWindowStart=function(){return this._pausedSinceWindowStart},e.ping=function(e){e&&(this.lastAction=new Date);var t=new s;return 0<this.config.DELAY?this.timers.setTimeout(function(){t.resolve()},this.config.DELAY):t.resolve(),t.promise()},e.isMajorityAuthenticated=function(){var t=0,n=0;return this.playerConnections.forEach(function(e){n++,e.isAuthenticated()&&t++}),.5<t/n},e.shouldShowAvatars=function(){return!!this.config.USE_SMILEYS||this.isMajorityAuthenticated()},e.isDelayed=function(e){return this.config.DELAY>((e=void 0===e?!0:e)?5e3:1e3)},e.preloadFiles=function(e){var t=new s;return this.Webcontrol.preload(e).then(function(){t.resolve()}),t.promise()},e.getPreloadedUrl=function(e){return this.Webcontrol.getPreloadedUrl(e)},e.getRandomPlayerList=function(e){var t;return void 0===this.randomPlayerLists[e]&&((t=this).randomPlayerLists[e]=new h(this,{getGameLogic:function(){return t.getGameLogic()}})),this.randomPlayerLists[e]},e.getRandomPlayers=function(e,t,n,i,o){for(var r=this.getRandomPlayerList(t).getRandomPlayers(e,n,i,o),s=[],a=0;a<r.length;a++)s.push(this.getGameLogic().serializePlayer(r[a]));return s},e.getAbsoluteRandomPlayers=function(e){var t=d.shuffle(this.activePlayers.toArray());return d.first(t,e).map(function(e){return this.getGameLogic().serializePlayer(e)}.bind(this))},e.resetRandomPlayers=function(e,t){this.getRandomPlayerList(e).resetRandomPlayers(t)},e.commitRandomPlayers=function(e){this.getRandomPlayerList(e).commitRandomPlayers()},e.serialize=function(){var e,t={};for(e in t.players=this.activePlayers.serialize(),t.remoteData=this.Webcontrol.state.getData(),t.playerCount=this._playercount,t.playerTypeCount=this._playerTypeCount,t.mode=this.mode,t.eliminateNewPlayers=this.admissionsClosed,t.poolNumber=this._poolNumber,t.randomPlayerLists=[],this.randomPlayerLists)this.randomPlayerLists.hasOwnProperty(e)&&t.randomPlayerLists.push({name:e,data:this.randomPlayerLists[e].serialize()});return d.extend(t,this.getGameLogic().serializeGameState()),t},e.restore=function(e,t){void 0===t&&(t=!1),void 0!==e.randomPlayerLists&&e.randomPlayerLists.forEach(function(e){this.getRandomPlayerList(e.name).unserialize(e.data)}.bind(this)),this._playercount=e.playerCount,this._playerTypeCount=e.playerTypeCount,"number"==typeof e.poolNumber&&(this._poolNumber=e.poolNumber),void 0!==e.admissionsClosed?this.admissionsClosed=e.admissionsClosed:void 0!==e.eliminateNewPlayers&&(this.admissionsClosed=e.eliminateNewPlayers);e=this.getGameLogic().restoreGameState(e,t);return e&&"function"==typeof e.promise?e.promise():e&&"function"==typeof e.then?e:((t=new s).resolve(),t.promise())},f}),define("CatLab/Webremote/PlayerPool/LocalDevices/LocalDeviceUser",["CatLab/Webremote/Models/Users/ControlUser"],function(n){function e(e,t,n,i){i=i||{},this._deviceId=e,this._profile=t,this._sink=n,this._deviceOptions=i,this._proxies={},this._backState={lastBackButtonClick:new Date(0)},this.initialize({id:e});var o=this;this.on("view:set",function(){o.clearControls()}),this.on("login",function(){o.pushState(),o._sink&&o._sink.output("login",{user:o.getUserSummary()})}),this.on("logout",function(){o.pushState(),o._sink&&o._sink.output("logout",{})}),this.on("login:failed",function(){o.pushState()}),this.on("active:change",function(){o.pushState()}),this.on("user:nickname",function(){o.pushState()}),this.clearControls()}var t=e.prototype=Object.create(n.prototype);return t.constructor=e,t.getDeviceId=function(){return this._deviceId},t.getProfile=function(){return this._profile},t.getType=function(){return this._profile.type},t.getIcon=function(){return this._profile.icon},t.hasDisplay=function(){return this._profile.capabilities.hasDisplay},t.hasKeyboardInput=function(){return this._profile.capabilities.hasKeyboardInput},t.hasTouchInput=function(){return this._profile.capabilities.hasTouchInput},t.getPortalControls=function(){return this._profile.portalControls},t.getAvailableControls=function(){return this._profile.keys.map(function(e){return e.id})},t.hasControl=function(e){return-1!==this.getAvailableControls().indexOf(e)},t.emit=function(){return!1},t.isLocalAuthentication=function(){return!1},t.setStaticLabels=function(){var n=this._profile.labelsFor(this._deviceOptions),i=this;Object.keys(n).forEach(function(e){var t=n[e];i.control(e).setStaticLabel(t.label,t.type,t.image,t.emoji)})},t.clearControls=function(){n.prototype.clearControls.call(this),this._proxies={},this._sink&&this._sink.output("controls:cleared",{})},t.setOptions=function(e){this._deviceOptions=e||{},this.clearControls()},t.logout=function(e){n.prototype.logout.call(this,e),this.eventableTrigger("logout")},t.getUserSummary=function(){var e,t=this.getUser();return t?{id:(e=function(e){e="function"==typeof t[e]?t[e]():null;return void 0===e?null:e})("getId"),name:e("getName"),avatar:e("getAvatar"),nickname:this.getNickname()}:null},t.pushState=function(){this._sink&&this._sink.output("state",{authenticated:this.isAuthenticated(),accessToken:this.getAccessToken(),nickname:this.getNickname(),active:this.isActive(),playerId:void 0===this.playerId?null:this.playerId})},t.bindProxy=function(e,t){var n,i;this._proxies[e]=this._proxies[e]||{},this._proxies[e][t]||((n=this)._proxies[e][t]=i=function(){n._sink&&n._sink.output("control:"+t,{id:e})},this.control(e).on(t,i))},t.unbindProxy=function(e,t){var n=this._proxies[e]&&this._proxies[e][t];n&&(this.control(e).off(t,n),delete this._proxies[e][t])},t.trigger=function(e,t){switch(t=t||{},e){case"button:down":if(this._profile.onButtonDown(this,t.id,this._sink))return;break;case"view:changeValue":return void(this.currentView&&"function"==typeof this.currentView.changeValue&&this.currentView.changeValue(t.key,t.value));case"control:bind":return void this.bindProxy(t.id,t.event);case"control:unbind":return void this.unbindProxy(t.id,t.event);case"nickname":return void this.setNickname(t.name);case"active":return void this.setActive(!!t.value);case"backbutton":return void this._profile.onBackButton(this,this._sink,this._backState)}n.prototype.trigger.call(this,e,t)},e}),define("CatLab/Webremote/PlayerPool/LocalDevices/Profiles/shared",[],function(){function i(e,t){return!!(Array.isArray(e)&&-1<e.indexOf(t))||e==t}return{keyMatches:i,mapKey:function(e,t){for(var n=0;n<e.length;n++){if(void 0!==e[n].code&&i(e[n].code,t.code))return e[n].id;if(void 0!==e[n].key&&i(e[n].key,t.key))return e[n].id;if(void 0!==e[n].keyCode&&i(e[n].keyCode,t.keyCode))return e[n].id}return null},labelsFor:function(t,e){var n={};return t.keys.forEach(function(e){n[e.id]={label:e.label,type:t.type,image:void 0===e.image?null:e.image,emoji:void 0===e.emoji?null:e.emoji}}),n}}}),define("CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Keyboard",["CatLab/Webremote/PlayerPool/LocalDevices/Profiles/shared"],function(t){var n=[{id:"up",label:"↑",code:"ArrowUp",emoji:"⬆️"},{id:"down",label:"↓",code:"ArrowDown",emoji:"⬇️"},{id:"right",label:"→",code:"ArrowRight",emoji:"➡️"},{id:"left",label:"←",code:"ArrowLeft",emoji:"⬅️"},{id:"a",label:"A",code:["KeyA","Enter","NumpadEnter"],emoji:"🅰"},{id:"b",label:"B",code:"KeyB",emoji:"🅱"},{id:"x",label:"X",code:"KeyX",emoji:"🆇"},{id:"y",label:"Y",code:"KeyY",emoji:"🆈"},{id:"back",label:"Escape",code:"Escape",emoji:"🇪"},{id:"start",label:"S",code:["KeyS"],emoji:"🆂"}],e={kind:"keyboard",keys:n,portalControls:{start:"start",back:"back",toggleActive:"up",authenticate:"y",left:"left",right:"right"},capabilities:{hasDisplay:!1,hasKeyboardInput:!0,hasTouchInput:!0},type:"keyboard",icon:"fa fa-keyboard-o",exitOnUnassignedBackButton:!1,backButtonControl:null,mapKey:function(e){return t.mapKey(n,e)},mapGamepadButton:function(){return null},labelsFor:function(){return t.labelsFor(e)},preventDefaultFor:function(e){for(var t=0;t<n.length;t++)if(n[t].id===e)return!!n[t].preventDefault;return!1},onButtonDown:function(e,t,n){return!("back"!==t||!this.exitOnUnassignedBackButton||e.control("back").hasTriggers("click")||e.control("back").hasTriggers("up")||e.control("back").hasTriggers("down")||(n.app("requestExit"),0))},onBackButton:function(){}};return e}),define("CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Cordova",["CatLab/Webremote/PlayerPool/LocalDevices/Profiles/shared"],function(t){var n=[{id:"up",label:"↑",key:38},{id:"down",label:"↓",key:40},{id:"right",label:"→",key:39},{id:"left",label:"←",key:37},{id:"start",label:"ENTER",key:13},{id:"back",label:"BACK",key:null}],e={kind:"cordova",keys:n,portalControls:{start:"start",back:"back",toggleActive:"up",authenticate:"y",left:"left",right:"right"},capabilities:{hasDisplay:!1,hasKeyboardInput:!0,hasTouchInput:!0},type:"keyboard",icon:"fa fa-keyboard-o",exitOnUnassignedBackButton:!0,backButtonControl:"back",mapKey:function(e){return t.mapKey(n,e)},mapGamepadButton:function(){return null},labelsFor:function(){return t.labelsFor(e)},preventDefaultFor:function(e){for(var t=0;t<n.length;t++)if(n[t].id===e)return!!n[t].preventDefault;return!1},onButtonDown:function(){return!1},onBackButton:function(e,t,n){var i,o=new Date;o.getTime()-n.lastBackButtonClick.getTime()<300?t.app("requestExit"):(n.lastBackButtonClick=o,!this.exitOnUnassignedBackButton||e.control("back").hasTriggers("click")||e.control("back").hasTriggers("up")||e.control("back").hasTriggers("down")?this.backButtonControl&&(e.control(this.backButtonControl).update(1),i=this,setTimeout(function(){e.control(i.backButtonControl).update(0)},1)):setTimeout(function(){t.app("minimize")},350))}};return e}),define("CatLab/Webremote/PlayerPool/LocalDevices/Profiles/AndroidRemote",["CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Cordova","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/shared"],function(i,t){var n=[{id:"up",label:"↑",keyCode:38,preventDefault:!0,image:"control-icons/android-tv/$SIZE/android-tv-up.gif",emoji:"⬆️"},{id:"down",label:"↓",keyCode:40,preventDefault:!0,image:"control-icons/android-tv/$SIZE/android-tv-down.gif",emoji:"⬇️"},{id:"right",label:"→",keyCode:39,preventDefault:!0,image:"control-icons/android-tv/$SIZE/android-tv-right.gif",emoji:"➡️"},{id:"left",label:"←",keyCode:37,preventDefault:!0,image:"control-icons/android-tv/$SIZE/android-tv-left.gif",emoji:"⬅️"},{id:"a",label:"ENTER",keyCode:13,preventDefault:!0,emoji:"🅰"},{id:"back",label:"BACK",keyCode:null},{id:"start",label:"⏯",keyCode:179},{id:"fastforward",label:"⏩",keyCode:228},{id:"fastforward",label:"⏪",keyCode:227}],e={kind:"androidremote",keys:n,portalControls:{start:"start",back:"back",toggleActive:"up",authenticate:"down",left:"left",right:"right"},capabilities:{hasDisplay:!1,hasKeyboardInput:!1,hasTouchInput:!1},type:"keyboard",icon:"fa fa-keyboard-o",exitOnUnassignedBackButton:!1,backButtonControl:"back",mapKey:function(e){return t.mapKey(n,e)},mapGamepadButton:function(){return null},labelsFor:function(){return t.labelsFor(e)},preventDefaultFor:function(e){for(var t=0;t<n.length;t++)if(n[t].id===e)return!!n[t].preventDefault;return!1},onButtonDown:function(){return!1},onBackButton:function(e,t,n){return i.onBackButton.call(this,e,t,n)}};return e}),define("CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Gamepad",[],function(){var i={12:"DPAD_UP",13:"DPAD_DOWN",15:"DPAD_RIGHT",14:"DPAD_LEFT",0:"FACE_1",1:"FACE_2",2:"FACE_3",3:"FACE_4",8:"SELECT_BACK",9:"START_FORWARD"},s=[{id:"up",label:"↑",key:"DPAD_UP",emojiKey:"up"},{id:"down",label:"↓",key:"DPAD_DOWN",emojiKey:"down"},{id:"right",label:"→",key:"DPAD_RIGHT",emojiKey:"right"},{id:"left",label:"←",key:"DPAD_LEFT",emojiKey:"left"},{id:"a",label:"A",key:"FACE_1",emojiKey:"a",hasImage:!0},{id:"b",label:"B",key:"FACE_2",emojiKey:"b",hasImage:!0},{id:"x",label:"X",key:"FACE_3",emojiKey:"x",hasImage:!0},{id:"y",label:"Y",key:"FACE_4",emojiKey:"y",hasImage:!0},{id:"back",label:"SELECT",key:"SELECT_BACK"},{id:"start",label:"START",key:"START_FORWARD"},{id:"l1",label:"L1",key:"L1",emojiKey:"l1"},{id:"r1",label:"R1",key:"R1",emojiKey:"r1"}],a={a:"🅰️",b:"🅱️",x:"❎",y:"❎",up:"⬆️",down:"⬇️",left:"⬅️",right:"➡️",l1:"🤜",r1:"🤛"},l={a:"❎",b:"⭕",x:"🟥",y:"🔺",up:"⬆️",down:"⬇️",left:"⬅️",right:"➡️",l1:"🤜",r1:"🤛"};return{kind:"gamepad",deviceIdPrefix:"gamepad",keys:s,portalControls:{start:"start",back:"back",toggleActive:"x",authenticate:"y",left:"left",right:"right"},capabilities:{hasDisplay:!1,hasKeyboardInput:!1,hasTouchInput:!1},type:"gamepad",icon:"fa fa-gamepad",exitOnUnassignedBackButton:!1,backButtonControl:null,mapKey:function(){return null},mapGamepadButton:function(e){var t=i[e];if(t)for(var n=0;n<s.length;n++)if(s[n].key===t)return s[n].id;return null},labelsFor:function(e){var e=void 0!==(e=(e=e||{}).id)&&(-1!==e.toLowerCase().indexOf("sony")||-1!==e.toLowerCase().indexOf("054c")),t=e?"control-icons/ps-controller/$SIZE/":"control-icons/gamepad/$SIZE/",n=e?"ps-controller-":"gamepad-",i=e?"🕹":"🎮",o=e?l:a,r={};return s.forEach(function(e){r[e.id]={label:e.label,type:"gamepad",image:e.hasImage?t+n+e.id+".gif":null,emoji:e.emojiKey?i+"‍"+o[e.emojiKey]:null}}),r},preventDefaultFor:function(){return!1},onButtonDown:function(){return!1},onBackButton:function(){}}}),define("CatLab/Webremote/PlayerPool/LocalDevices/Profiles/index",["CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Keyboard","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Cordova","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/AndroidRemote","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/Gamepad"],function(e,t,n,i){var o={keyboard:e,cordova:t,androidremote:n,gamepad:i};return{keyboard:e,cordova:t,androidremote:n,gamepad:i,forKind:function(e){if(o[e])return o[e];throw new Error('LocalDevices: unknown device kind "'+e+'"')}}}),define("CatLab/Webremote/PlayerPool/LocalDevices/DeviceRegistry",["CatLab/Webremote/PlayerPool/LocalDevices/LocalDeviceUser","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/index","CatLab/Webremote/Transport/Errors"],function(i,o,n){function e(e,t){this._pool=e,this._channels=t,this._devices={},this._displayBus=null,this._originalToView=null}var r=["keyboard","cordova","androidremote"],t=e.prototype;return t._sinkFor=function(n){var i=this;return{output:function(e,t){i._channels.isClosed()||i._channels.send("device","output",{device:n,method:e,data:t||{}})},app:function(e){i._channels.isClosed()||i._channels.send("device","output",{device:n,method:"app",data:{action:e}})}}},t._syncPool=function(e,t){t?this._pool.Webcontrol.trigger("user:leave",e):"function"==typeof this._pool._notifyConnectedDevices&&this._pool._notifyConnectedDevices();t=this._pool.connectController;t&&"function"==typeof t.updateUsers&&t.updateUsers()},t.connect=function(e){var t,n=this;"display"===e.kind?(t=this._pool.Webcontrol.getMessageBus(),this._displayBus!==t&&(this._displayBus=t,this._originalToView=t.toView),t.toView=function(e,t){n._channels.isClosed()||n._channels.send("device","output",{device:"display",method:"bus",data:{action:e,content:t}})}):(t=this._devices[e.device])&&t.getProfile().kind===e.kind?(t.setOptions(e.options||{}),-1!==r.indexOf(e.kind)&&this._pool.setKeyboardUser(t),this._syncPool(t,!1),this._pool.trigger("device:reconnected",{device:e.device})):(t&&(t.setActive(!1),delete this._devices[e.device]),t=o.forKind(e.kind),t=new i(e.device,t,this._sinkFor(e.device),e.options||{}),this._devices[e.device]=t,this._pool.Webcontrol.addCustomControl(t),-1!==r.indexOf(e.kind)&&this._pool.setKeyboardUser(t),t.pushState())},t.disconnect=function(e){var t=this._devices[e.device];t&&(t.setActive(!1),this._syncPool(t,!0),this._pool.trigger("device:disconnected",{device:e.device}))},t.input=function(e){if("display"===e.device){if("bus"===e.method)return void this._pool.Webcontrol.getMessageBus().handleControllerMessage(e.data.action,e.data.content);throw new n.TransportError('unexpected display input "'+e.method+'"')}var t=this._devices[e.device];if(!t)throw new n.TransportError('input for unknown device "'+e.device+'"');t.trigger(e.method,e.data)},t.get=function(e){return this._devices[e]||null},t.each=function(t){var n=this;Object.keys(this._devices).forEach(function(e){t(n._devices[e],e)})},t.list=function(){return Object.keys(this._devices)},t.dispose=function(){this.each(function(e){"function"==typeof e.setActive&&e.setActive(!1)}),this._displayBus&&(this._displayBus.toView=this._originalToView,this._displayBus=null,this._originalToView=null)},e}),define("CatLab/Webremote/Transport/Codec",["CatLab/Webremote/Transport/Errors"],function(e){var d=e.TransportError,h=e.RemoteError,g=["__type","__date","__callback","__error"],m=[],u={};function v(e,t){e=new d(t+" cannot cross the worker boundary",e);throw e.transportKind=t,e}function b(e){e=Object.getPrototypeOf(e);return e===Object.prototype||null===e}function y(e){var t;return null===e?"null":"function"==typeof e?"function":"object"!=typeof e?typeof e:Array.isArray(e)?"Array":e instanceof Date?"Date":"Object"!==(t=(t=e.constructor)&&t.name?t.name:"Object")||b(e)?t:"anonymous class"}function w(e,t,n,i,o){if(i=i||[],o=o||0,null==e||"boolean"==typeof e||"string"==typeof e)return e;if("number"==typeof e)return e!=e&&v(t,"NaN"),e!==1/0&&e!==-1/0||v(t,"Infinity"),e;if("function"==typeof e){if(n&&"function"==typeof n.callback)return n.callback(e,t,o);v(t,"function")}if("object"!=typeof e&&v(t,typeof e),e instanceof Date)return e.getTime()!=e.getTime()&&v(t,"invalid Date"),{__date:e.toISOString()};if(-1!==i.indexOf(e)&&v(t,"cycle"),e instanceof Error)return _(e,t,n,i,o);var r,s=(e=>{for(var t=0;t<m.length;t++)if(m[t].test(e))return m[t];return null})(e);if(s)return i.push(e),r=w(s.serialize(e),t,n,i,o+1),i.pop(),{__type:s.name,data:r};if(Array.isArray(e)){i.push(e);for(var a=new Array(e.length),l=0;l<e.length;l++){var c=w(e[l],t+"["+l+"]",n,i,o+1);a[l]=void 0===c?null:c}return i.pop(),a}("function"==typeof e.then||"function"==typeof e.done&&"function"==typeof e.fail)&&v(t,"promise"),b(e)||v(t,"Map"===(s=y(e))||"Set"===s||/Array$/.test(s)?s:s+" instance"),i.push(e);for(var h={},u=Object.keys(e),d=0;d<u.length;d++){var f=u[d],p=(-1!==g.indexOf(f)&&v(t+"."+f,"reserved key"),w(e[f],t+"."+f,n,i,o+1));void 0!==p&&(h[f]=p)}return i.pop(),h}function _(e,t,n,i,o){o=o||0,(i=i||[]).push(e);for(var r={},s=!1,a=Object.keys(e),l=0;l<a.length;l++){var c=a[l];if(!("name"===c||"message"===c||"stack"===c||"remoteStack"===c||"isRemote"===c||"data"===c&&e.isRemote))try{var h=w(e[c],t+"."+c,n,i,o+1);void 0!==h&&(r[c]=h,s=!0)}catch(e){if(e instanceof d&&"cycle"===e.transportKind)throw e}}i.pop();var u=s?r:null;return e.isRemote&&(u=void 0===e.data?null:e.data),{__error:{name:e.name||"Error",message:e.message||String(e),stack:e.remoteStack||e.stack||"",data:u}}}return{encode:function(e,t,n){return w(e,t||"value",n)},decode:function e(t,n,i){if(i=i||"message",null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var o=new Array(t.length),r=0;r<t.length;r++)o[r]=e(t[r],n,i+"["+r+"]");return o}if(Object.prototype.hasOwnProperty.call(t,"__date")){if("string"!=typeof t.__date)throw new d("invalid date record",i);var s=new Date(t.__date);if(isNaN(s.getTime()))throw new d("invalid date record",i);return s}if(Object.prototype.hasOwnProperty.call(t,"__error"))return s=t.__error||{},new h({name:s.name,message:s.message,stack:s.stack,data:e(s.data,n,i+".__error.data")});if(Object.prototype.hasOwnProperty.call(t,"__callback")){if(n&&"function"==typeof n.callback)return n.callback(t.__callback,i);throw new d("callback record cannot be decoded here",i)}if(Object.prototype.hasOwnProperty.call(t,"__type")){s=u[t.__type];if(s)return s.unserialize(e(t.data,n,i+".data"));throw new d('unregistered type "'+t.__type+'"',i)}for(var a={},l=Object.keys(t),c=0;c<l.length;c++)a[l[c]]=e(t[l[c]],n,i+"."+l[c]);return a},encodeError:function(e){return _(e,"error",null,[],0)},isErrorRecord:function(e){return!!e&&"object"==typeof e&&Object.prototype.hasOwnProperty.call(e,"__error")},describe:y,registerType:function(e,t){if("string"!=typeof e||!e)throw new Error("Codec.registerType: name required");if(!t||"function"!=typeof t.test||"function"!=typeof t.serialize||"function"!=typeof t.unserialize)throw new Error("Codec.registerType("+e+"): {test, serialize, unserialize} required");if(u[e])throw new Error('Codec.registerType: "'+e+'" is already registered');t={name:e,test:t.test,serialize:t.serialize,unserialize:t.unserialize};m.push(t),u[e]=t},hasType:function(e){return!!u[e]},_reset:function(){m=[],u={}}}}),define("CatLab/Webremote/Transport/Channels",["CatLab/Webremote/Transport/Codec","CatLab/Webremote/Transport/Errors"],function(o,r){function e(e,t){t=t||{},this._port=e,this._open=!1,this._closed=!1,this._queue=[],this._handlers={},this._handlerErrorHandlers=[],this._closeHandlers=[],this._decodeHooks=null,this._onUnhandled=t.onUnhandled||function(e){console.error("[ChannelPort] unhandled message",e)};var n=this;this._unsubscribe=e.onMessage(function(e){n._receive(e)})}var t=e.prototype;return t.on=function(e,t,n){return this._handlers[e]={handler:t,raw:!(!n||!n.raw)},this},t.onHandlerError=function(e){this._handlerErrorHandlers.push(e)},t.setDecodeHooks=function(e){this._decodeHooks=e||null},t._receive=function(e){if(e&&"object"==typeof e&&"string"==typeof e.ch&&"string"==typeof e.type){var t,n=this._handlers[e.ch];if(n){if(n.raw)t=e;else try{t=o.decode(e,this._decodeHooks,e.ch+":"+e.type)}catch(e){return void this._reportHandlerError(e)}try{n.handler(t.type,t)}catch(e){this._reportHandlerError(e)}}else this._onUnhandled(e)}else this._onUnhandled(e)},t._reportHandlerError=function(t){0!==this._handlerErrorHandlers.length?this._handlerErrorHandlers.slice().forEach(function(e){e(t)}):console.error("[ChannelPort] handler threw:",t)},t._buildMessage=function(e,t,n){var i={ch:e,type:t};return n&&Object.keys(n).forEach(function(e){"ch"!==e&&"type"!==e&&(i[e]=n[e])}),i},t._post=function(e,t){this._port.post(e),"function"==typeof t&&t()},t.send=function(e,t,n,i){if(this._closed)throw new r.TransportError("ChannelPort: send after close");i=i||{};n=o.encode(this._buildMessage(e,t,n),e+":"+t,i.encodeHooks||null);this._dispatchOut(e,n,i.onSent)},t.sendEncoded=function(e,t,n,i){if(this._closed)throw new r.TransportError("ChannelPort: send after close");i=i||{},this._dispatchOut(e,this._buildMessage(e,t,n),i.onSent)},t.sendNow=function(e,t,n){if(this._closed)throw new r.TransportError("ChannelPort: send after close");n=o.encode(this._buildMessage(e,t,n),e+":"+t,null);this._post(n,null)},t._dispatchOut=function(e,t,n){this._open||"control"===e?this._post(t,n):this._queue.push({encoded:t,onSent:n})},t.open=function(){if(!this._closed){var t=this._queue;this._queue=[];for(var n=0;n<t.length;n++)try{this._post(t[n].encoded,t[n].onSent)}catch(e){throw this._queue=t.slice(n).concat(this._queue),e}this._open=!0}},t.isOpen=function(){return this._open},t.isClosed=function(){return this._closed},t.takeQueue=function(){var e=this._queue;return this._queue=[],e},t.adoptQueue=function(e){if(e&&0!==e.length){if(this._closed)throw new r.TransportError("ChannelPort: adoptQueue after close");if(this._open)for(var t=0;t<e.length;t++)this._post(e[t].encoded,e[t].onSent);else this._queue=e.concat(this._queue)}},t.onClose=function(e){return this._closeHandlers.push(e),this},t.close=function(){if(!this._closed){this._closed=!0,this._open=!1,this._queue=[],this._unsubscribe();var e=this._closeHandlers.slice();this._closeHandlers=[];for(var t=0;t<e.length;t++)try{e[t]()}catch(e){this._reportHandlerError(e)}}},e}),define("CatLab/Webremote/Transport/RpcServer",["CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/Codec","CatLab/Webremote/Transport/Errors"],function(l,c,h){function e(e,t){if("function"!=typeof(t=t||{}).invoke)throw new Error("RpcServer: options.invoke(method, args) is required");this._channels=e,this._invoke=t.invoke,this._reportError=t.reportError||function(e,t){console.error("[RpcServer] "+e,t)};var n=this;e.on("rpc",function(e,t){n._onMessage(e,t)},{raw:!0})}var t=e.prototype;return t._onMessage=function(e,t){"call"===e?this._handleCall(t):this._reportError("rpc",new h.TransportError('unexpected rpc message type "'+e+'"'))},t._handleCall=function(e){function t(t){if(!a){var n;a=!0,t instanceof Error||(t=new Error(String(t)));try{n=c.encodeError(t)}catch(e){var i=new Error(t.message||String(t));i.name=t.name||"Error",i.stack=t.stack||"",n=c.encodeError(i)}try{o._channels.sendEncoded("rpc","error",{id:r,error:n})}catch(t){o._reportError("rpc",t)}}}var n,i,o=this,r=e.id,s=e.method,a=!1;try{n=c.decode(e.args||[],{callback:function(t,e){var n=e;return function(){if(a)throw e=new h.TransportError("late callback after "+s+" settled",n),o._reportError("rpc:callback",e),e;var e=Array.prototype.slice.call(arguments);o._channels.send("rpc","callback",{id:r,callbackId:t,args:e})}}},s+".args")}catch(e){return void t(e)}try{i=this._invoke(s,n)}catch(e){return void t(e)}l.when(i).done(function(){if(1<arguments.length)t(new h.TransportError(s+" resolved with "+arguments.length+" values; rpc results are single values"));else{var e;try{e=c.encode(arguments[0],s+".result")}catch(e){return void t(e)}a||(a=!0,o._channels.sendEncoded("rpc","result",{id:r,value:e}))}}).fail(function(e){t(e)})},e}),define("CatLab/Webremote/Transport/WorkerPort",[],function(){function i(e,t,n){n=n||{},this.kind=e,this._target=t,this._listenTarget=n.listenTarget||t,this._targetOrigin=n.targetOrigin||null,this._filter=n.filter||null,this._handlers=[],this._errorHandlers=[],this._closed=!1;var i=this;this._listener=function(e){i._closed||i._filter&&!i._filter(e)||i._deliver(e.data)},this._listenTarget.addEventListener("message",this._listener)}var e=i.prototype;return e._deliver=function(e){for(var t=this._handlers.slice(),n=0;n<t.length;n++)try{t[n](e)}catch(e){this._reportError(e)}},e._reportError=function(t){0!==this._errorHandlers.length?this._errorHandlers.slice().forEach(function(e){e(t)}):console.error("[WorkerPort] message handler threw:",t)},e.post=function(e){if(this._closed)throw new Error("WorkerPort: post after close");null!==this._targetOrigin?this._target.postMessage(e,this._targetOrigin):this._target.postMessage(e)},e.onMessage=function(t){var n=this;return this._handlers.push(t),function(){var e=n._handlers.indexOf(t);-1!==e&&n._handlers.splice(e,1)}},e.onError=function(t){var n=this;return this._errorHandlers.push(t),function(){var e=n._errorHandlers.indexOf(t);-1!==e&&n._errorHandlers.splice(e,1)}},e.close=function(){this._closed||(this._closed=!0,this._listenTarget.removeEventListener("message",this._listener),this._handlers=[],this._errorHandlers=[])},e.isClosed=function(){return this._closed},i.forWorker=function(e){return new i("worker",e)},i.forSelf=function(e){return new i("self",e)},i.forWindow=function(t,e){return new i("window",t,{listenTarget:e,targetOrigin:"*",filter:function(e){return e.source===t}})},i.detect=function(e){var e=e||{},t="importScripts"in e?e.importScripts:"function"==typeof importScripts?importScripts:void 0,n="self"in e?e.self:"undefined"!=typeof self?self:void 0,e="window"in e?e.window:"undefined"!=typeof window?window:void 0;if("function"==typeof t&&n)return i.forSelf(n);if(e&&e.parent&&e.parent!==e)return i.forWindow(e.parent,e);throw new Error("WorkerPort.detect: not in a worker or a frame")},i}),define("CatLab/Webremote/PlayerPool/PlayerPoolWorker",["CatLab/Webremote/Tools/Deferred","CatLab/Webremote/PlayerPool/PlayerPool","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/PlayerPool/LocalDevices/DeviceRegistry","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Transport/Channels","CatLab/Webremote/Transport/RpcServer","CatLab/Webremote/Transport/WorkerPort","CatLab/Webremote/Transport/Codec","CatLab/Webremote/Transport/Errors","CatLab/Webremote/Providers/BridgedProvider"],function(a,i,t,o,r,s,l,c,n,h,u){function d(e,t){this.channels=e,this._bootOptions=t||{},this.playerpool=new i,this.navProxy=null,this._declaredEvents={},this.devices=new o(this.playerpool,e),this.playerpool.setLocalDeviceRegistry(this.devices),this._portal=null,this._auth=null,this._started=!1,this._slingshotInterval=null;var n=this;this._rpc=new l(e,{invoke:function(e,t){return n._invoke(e,t)},reportError:function(e,t){n.reportError(e,t)}}),e.on("control",function(e,t){n._onControl(e,t)}),e.on("device",function(e,t){n._onDevice(e,t)}),e.on("host",function(e,t){n._onHost(e,t)}),e.onHandlerError(function(e){n.reportError("channel",e)}),e.onClose(function(){n.dispose()})}var f=["openPortal","closePortal","openAuthentication","enableNavigation","restore"],p=["applyConfigOverrides"],e=d.prototype;return e.dispose=function(){null!==this._slingshotInterval&&(clearInterval(this._slingshotInterval),this._slingshotInterval=null),this.devices&&this.devices.dispose(),r.setSyncSink(null)},e._onControl=function(e,t){switch(e){case"init":return this._started?void this.reportError("control",new h.TransportError("control:init received twice; this pool has already started")):void this.start(t.options||{});case"ping":return void this.channels.sendNow("control","pong",{id:t.id});default:this.reportError("control",new h.TransportError('unexpected control message "'+e+'"'))}},e.reportError=function(e,t){console.error("[PlayerPoolWorker] "+e,t);try{this.channels.sendEncoded("control","error",{context:e,error:n.encodeError(t instanceof Error?t:new Error(String(t)))})}catch(e){}},e.fatal=function(e){console.error("[PlayerPoolWorker] fatal",e);try{this.channels.sendEncoded("control","fatal",{error:n.encodeError(e instanceof Error?e:new Error(String(e)))})}catch(e){}},e.start=function(e){this._started=!0;var t=e||{},n=(t.headless=!0,(t.events||[]).forEach(function(e){this._declaredEvents[e]=!0},this),this),e=this._selectProvider(t),e=(e&&(t.webcontrolOptions=t.webcontrolOptions||{},(t.webcontrolOptions.provider=e).on("settings",function(){n.sendConnectInformation()})),this.bootstrapAuthStorage(t.authStorage||{}),r.setSyncSink(function(e){n.channels&&!n.channels.isClosed()&&n.channels.send("host","storage",{key:e.name,value:void 0===e.rawValue?null:e.rawValue})}),this._bootOptions.beforeStart),e="function"==typeof e?e(this.playerpool,t):void 0;a.when(e).fail(function(e){console.error("[PlayerPoolWorker] beforeStart rejected; booting anyway.",e)}).always(function(){n._bootOptions.config&&(t.config=n._bootOptions.config),n._startPlayerpool(t)})},e._selectProvider=function(e){e=e.provider;return void 0===e||"socketio"===e?null:"bridged"===e?new u(this.channels):(this.reportError("control",new h.TransportError('unknown provider "'+e+'"')),null)},e._startPlayerpool=function(e){var t=this;this.playerpool.initialize(e).done(function(){t.playerpool.Webcontrol.on("game:initialized",function(){t.sendConnectInformation()}),t._bindDeclaredEvents(),t.sendConnectInformation(),t._declaredEvents["change:mode"]&&t.emitEvent("change:mode",t.playerpool.mode),"function"==typeof t.playerpool.refreshConnectedDevices&&t.playerpool.refreshConnectedDevices(),t._bindSlingshots(),t.channels.sendNow("control","ready",{}),t.channels.open()}).fail(function(e){t.fatal(e||new Error("pool.initialize failed"))})},e.bootstrapAuthStorage=function(e){if("undefined"!=typeof localStorage&&e)for(var t in e)e.hasOwnProperty(t)&&null!==e[t]&&localStorage.setItem(t,e[t])},e.emitEvent=function(e,t){var n;if(!this._declaredEvents[e])throw n=new h.TransportError('undeclared event "'+e+'"'),this.reportError("event:"+e,n),n;try{this.channels.send("events","event",{name:e,data:void 0===t?null:t})}catch(t){throw this.reportError("event:"+e,t),t}},e._bindDeclaredEvents=function(){var t=this,n={"connectInfo:change":!0,"smileys:slingshot":!0,"transport:fallback":!0,"change:mode":!0};Object.keys(this._declaredEvents).forEach(function(e){n[e]||t.playerpool.on(e,function(){t.emitEvent(e,1<arguments.length?arguments[0]:void 0)})}),this._declaredEvents["change:mode"]&&this.playerpool.on("change:mode",function(e){t.emitEvent("change:mode",e)})},e._bindSlingshots=function(){var e,t,n=this;this._declaredEvents["smileys:slingshot"]&&(e=function(e){n.emitEvent("smileys:slingshot",{player:{id:e.user?e.user.getId():null,name:e.user?e.user.getNickname():null,smiley:e.user?e.user.getSmiley():null},angle:e.angle,speed:e.speed,smiley:e.smiley})},t=null,this._slingshotInterval=setInterval(function(){t&&n.playerpool.Webcontrol.off("smileys:slingshot",t),t=n.playerpool.Webcontrol.on("smileys:slingshot",e)},1e3))},e.sendConnectInformation=function(){var e,t;this._declaredEvents["connectInfo:change"]&&(e=this.playerpool.Webcontrol)&&"function"==typeof e.getConnectToken&&(t=e._gamedata||{},this.emitEvent("connectInfo:change",{connectToken:e.getConnectToken(),connectTokenForDisplay:e.getConnectTokenForDisplay(),connectUrl:e.getConnectURL(),server:this.playerpool.server||"",contentProxy:t.content_proxy||null,gameId:void 0===t.id?null:t.id,accessToken:t.accessToken||null}))},e._invoke=function(e,t){if(-1!==f.indexOf(e))return this[e].apply(this,t);if(-1!==p.indexOf(e))throw new h.TransportError("host method not rpc-callable: "+e);return this.playerpool.invokePoolMethod(e,t)},e.openPortal=function(e,t,n){var i=this,o=new a,r=(e=e||{},this.navProxy&&(this.navProxy.destroy(),this.navProxy=null),this._portal),r=(r&&(this._portal=null,r.controller?r.controller._destroyed||r.controller.destroy():r.pendingDestroy=!0),e.start=function(e){"function"==typeof t&&t(e.map(function(e){return{id:e.getId?e.getId():null,accessToken:e.getAccessToken?e.getAccessToken():null}}))},e.back=function(){"function"==typeof n&&n()},this.playerpool.getConnectController(e)),s={controller:null,deferred:o,pendingDestroy:!1};return this._portal=s,r.promise.done(function(e){(s.controller=e).on("destroy",function(){setTimeout(function(){i._portal===s&&(i._portal=null),o.resolve()},0)}),e._destroyed?o.resolve():s.pendingDestroy&&e.destroy()}),"function"==typeof r.promise.fail&&r.promise.fail(function(e){i._portal===s&&(i._portal=null),o.reject(e)}),o.promise()},e.closePortal=function(e){this.playerpool.closeConnectController(e)},e.openAuthentication=function(e){var t=this,n=new a,e=this.playerpool.getAuthenticationController(e||{}),i=this.playerpool.getNavigationUsers(!1);return e.controller.setNavigatableUsers(i),e.controller.on("close",function(){setTimeout(function(){n.resolve()},0),t._declaredEvents["authentication:close"]&&t.emitEvent("authentication:close",null)}),n.promise()},e.enableNavigation=function(e){e=this.playerpool.getNavigationUsers(e&&e.includeDisplayUsers);return this.navProxy&&this.navProxy.destroy(),this.navProxy=new t(this.playerpool.Webcontrol.getMessageBus()),e.forEach(function(e){e=e.setView("catlab-nes");this.navProxy.addView(e)}.bind(this)),null},e.restore=function(e,t){return this.playerpool.restore(e,t)},e._onDevice=function(e,t){this._dispatchDevice(e,t)},e._dispatchDevice=function(e,t){try{if("connect"===e)this.devices.connect(t);else if("disconnect"===e)this.devices.disconnect(t);else{if("input"!==e)throw new h.TransportError('unexpected device message type "'+e+'"');this.devices.input(t)}}catch(e){this.reportError("device",e)}},e._onHost=function(e,t){"config"!==e?"mods"!==e?this.reportError("host",new h.TransportError('unexpected host message "'+e+'"')):this._onHostMods(t||{}):this.playerpool.config&&"function"==typeof this.playerpool.config.applyOverrides?this.playerpool.config.applyOverrides(t.overrides||{}):this.reportError("host",new h.TransportError("host:config received but the pool config has no applyOverrides"))},e._onHostMods=function(e){function t(){i.channels.send("host","modsReady",{})}var n,i=this,o=this._bootOptions.onMods;if("function"==typeof o){try{n=o(e.descriptors,e.baseUrl,e.query)}catch(e){return this.reportError("host",e instanceof Error?e:new Error(String(e))),void t()}a.when(n).fail(function(e){i.reportError("host",e instanceof Error?e:new Error(String(e)))}).always(t)}else t()},d.bootWorker=function(e){var e=e||{},t=e.port||c.detect(),t=new s(t,{onUnhandled:function(e){console.error("[PlayerPoolWorker] unhandled message",e)}}),n=new d(t,e);return"function"==typeof e.createGameLogic&&n.playerpool.setGameLogic(e.createGameLogic()),t.sendNow("control","hello",{}),n},d}),define("CatLab/Webremote/PlayerPool/SeatAuthority",[],function(){function e(e){this._maxPerPool="number"==typeof(e=e||{}).maxPerPool?e.maxPerPool:1/0,this._budget=0,this._armed=!1,this._usage={},this._lease={},this._leaseListeners=[]}var t=e.prototype;return t.registerPool=function(e){this._usage.hasOwnProperty(e)||(this._usage[e]=0,this._lease[e]=0),this._recompute()},t.unregisterPool=function(e){delete this._usage[e],delete this._lease[e],this._recompute()},t.updateUsage=function(e,t){this._usage.hasOwnProperty(e)&&this._usage[e]!==(t=t||0)&&(this._usage[e]=t,this._recompute())},t.setBudget=function(e){this._budget=e||0,this._recompute()},t.getBudget=function(){return this._budget},t.getTotalUsage=function(){var e,t=0;for(e in this._usage)this._usage.hasOwnProperty(e)&&(t+=this._usage[e]);return t},t.getLease=function(e){return this._lease.hasOwnProperty(e)?this._lease[e]:0},t.onLeaseChange=function(e){this._leaseListeners.push(e)},t._recompute=function(){var e,t=[];for(e in this._usage)this._usage.hasOwnProperty(e)&&t.push(e);var n=t.length;if(this._budget<=0){if(this._armed)for(s=0;s<n;s++)this._setLease(a=t[s],this._usage[a])}else if(this._armed=!0,0!==n)for(var i=Math.max(0,this._budget-this.getTotalUsage()),o=Math.floor(i/n),r=i%n,s=0;s<n;s++){var a=t[s],l=this._usage[a]+(o+(s<r?1:0));1<n&&(l=Math.min(l,this._maxPerPool)),l=Math.max(l,this._usage[a]),this._setLease(a,l)}},t._setLease=function(e,t){if(this._lease[e]!==t){this._lease[e]=t;for(var n=0;n<this._leaseListeners.length;n++)try{this._leaseListeners[n](e,t)}catch(e){console.error("[SeatAuthority] lease listener failed:",e)}}},e}),define("CatLab/Webremote/PlayerPool/SeatAuthorityBinder",[],function(){function e(e,t){this._sa=e,this._adapter=t,this._poolById={},this._bind()}var t=e.prototype;return t._bind=function(){var n=this;this._sa.onLeaseChange(function(e,t){e=n._poolById[e];void 0!==e&&n._adapter.pushLease(e,t)}),this._adapter.eachPool(function(e,t){n._addPool(e,t)}),this._adapter.onPoolAdded(function(e,t){n._addPool(e,t)}),this._adapter.onPoolRemoved(function(e){delete n._poolById[e],n._sa.unregisterPool(e)}),this._adapter.onPoolUsage(function(e,t){n._sa.updateUsage(e,t)})},t._addPool=function(e,t){this._poolById[e]=t,this._sa.registerPool(e)},e}),define("CatLab/Webremote/PlayerPool/Managers/Manager",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred"],function(e,l){function t(){this.initializeEventable()}e=t.prototype=new e;return e.initializeManager=function(){this.hasOwnProperty("_eventableEvents")||this.initializeEventable()},e.call=function(){console.warn("[Manager] call() not implemented")},e.initialize=function(e){console.warn("[Manager] initialize() not implemented")},e.enableNavigation=function(e,t){console.warn("[Manager] enableNavigation() not implemented")},e.getConnectScreen=function(e){console.warn("[Manager] getConnectScreen() not implemented")},e.clearConnectScreen=function(e){console.warn("[Manager] clearConnectScreen() not implemented")},e.activateKeyboardUser=function(e){console.warn("[Manager] activateKeyboardUser() not implemented")},e.setKeyboardUser=function(e){console.warn("[Manager] setKeyboardUser() not implemented")},e.createDummyUser=function(e,t){console.warn("[Manager] createDummyUser() not implemented")},e.getAuthenticationScreen=function(){console.warn("[Manager] getAuthenticationScreen() not implemented")},e.getKeyboardUser=function(){return console.warn("[Manager] getKeyboardUser() not implemented"),null},e._trackCurrentNavigation=function(e,t){this._currentNavigatable=e,this._currentNavigatableIncludeDisplayUsers=!!t},e._suspendNavigationForPortal=function(){this._currentNavigatable=null,this._currentNavigatableIncludeDisplayUsers=!1,this._clearCurrentNavigation()},e._clearCurrentNavigation=function(){},e.login=function(e){function t(){r&&i.enableNavigation(r,s)}function n(){i.off("authentication:close"),o.resolve()}var i=this,o=new l,r=this._currentNavigatable||null,s=this._currentNavigatableIncludeDisplayUsers,e=(this._clearCurrentNavigation(),this.getAuthenticationScreen(e)),a=this.getKeyboardUser();return a&&a.once("login",n),this.once("authentication:close",function(){a&&a.off("login",n),o.reject("closed")}),o.promise().done(t).fail(t),{view:e,done:o.promise()}},e.getAccessTokens=function(){return console.warn("[Manager] getAccessTokens() not implemented"),[]},e.countActivePlayers=function(){return console.warn("[Manager] countActivePlayers() not implemented"),0},e.shouldShowAvatars=function(){return!1},e.isDelayed=function(e){return!1},e.getHostProvider=function(){return"socketio"},e.disconnect=function(){console.warn("[Manager] disconnect() not implemented")},Object.defineProperty(e,"length",{get:function(){return 0}}),Object.defineProperty(e,"actualPlayersLength",{get:function(){return 0}}),t}),define("CatLab/Webremote/LocalInput/DeviceObject",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e,t,n){this._id=e,this._send=t,this._label=n,this._value=0,this._listeners={},this._bound={},this._domElements=[]}function r(e){this._device=e}function n(e,t,n,i,o){this.initializeEventable(),this._deviceId=e,this._kind=t,this._send=n,this._profile=i,this._options=o||{},this._labels=i.labelsFor(this._options),this._controls={},this._listeningListeners=[],this._listening=!0,this._authenticated=!1,this.access_token=null,this._nickname=null,this._active=!1,this.playerId=null,this.currentView=new r(this)}var i=t.prototype,i=(i.click=function(e){return this.on("click",e)},i.on=function(e,t){this._listeners[e]=this._listeners[e]||[];var n=0===this._listeners[e].length;return this._listeners[e].push(t),n&&!this._bound[e]&&(this._bound[e]=!0,this._send("control:bind",{id:this._id,event:e})),this},i.off=function(e,t){return void 0===e?Object.keys(this._listeners).forEach(function(e){this.off(e)},this):this._listeners[e]&&(void 0===t?this._listeners[e]=[]:-1!==(t=this._listeners[e].indexOf(t))&&this._listeners[e].splice(t,1),0===this._listeners[e].length)&&this._bound[e]&&(delete this._bound[e],this._send("control:unbind",{id:this._id,event:e})),this},i.hasTriggers=function(e){return void 0===e?Object.keys(this._listeners).some(function(e){return 0<this._listeners[e].length},this):!!(this._listeners[e]&&0<this._listeners[e].length)},i.update=function(e,t){0<this._value&&0===e?this._send("button:up",{id:this._id,click:t=void 0===t?!0:t}):0===this._value&&0<e&&this._send("button:down",{id:this._id}),this._value=e},i.getLabel=function(e){return(e=void 0===e?!0:e)?'<span class="control-label '+this._label.type+'">'+this._label.label+"</span>":this._label.label},i.getLabelData=function(){return this._label},i.addDomElement=function(e){function t(){n._send("button:down",{id:n._id}),n._send("button:up",{id:n._id,click:!0})}var n=this;return e&&e.addEventListener&&e.addEventListener("click",t),this._domElements.push({element:e,listener:t}),this},i.clearDomElements=function(){return this._domElements.forEach(function(e){e.element&&e.element.removeEventListener&&e.element.removeEventListener("click",e.listener)}),this._domElements=[],this},i._trigger=function(e){e=this._listeners[e];e&&e.slice().forEach(function(e){e()})},i._clearListeners=function(){this._listeners={},this._bound={}},i._rebindAfterClear=function(){this._bound={},Object.keys(this._listeners).forEach(function(e){this._listeners[e]&&0<this._listeners[e].length&&(this._bound[e]=!0,this._send("control:bind",{id:this._id,event:e}))},this)},i._setLabel=function(e){this._label=e},r.prototype.changeValue=function(e,t){this._device._send("view:changeValue",{key:e,value:t})},r.prototype.control=function(e){return this._device.control(e)},n.prototype=new e);return i.constructor=n,i.isShim=!0,i.getDeviceId=function(){return this._deviceId},i.getKind=function(){return this._kind},i.dispose=function(){Object.keys(this._controls).forEach(function(e){this._controls[e].clearDomElements(),this._controls[e]._clearListeners()},this),this._listeningListeners=[],this._eventableEvents={}},i.sendInput=function(e,t){this._send(e,t||{})},i.login=function(e){this._send("user:login",e||{})},i.logout=function(){this._send("user:logout",{})},i.setActive=function(e){this._send("active",{value:!!e})},i.setNickname=function(e){this._send("nickname",{name:e})},i.stopListening=function(){this._notifyListening(!1)},i.resumeListening=function(){this._notifyListening(!0)},i.isListening=function(){return this._listening},i.onListeningChange=function(t){this._listeningListeners.push(t);var n=this;return function(){var e=n._listeningListeners.indexOf(t);-1!==e&&n._listeningListeners.splice(e,1)}},i._notifyListening=function(t){this._listening=!!t,this._listeningListeners.slice().forEach(function(e){e(t)})},i.isAuthenticated=function(){return this._authenticated},i.getAccessToken=function(){return this.access_token},i.isActive=function(){return this._active},i.getNickname=function(){return this._nickname},i._labelFor=function(e){return this._labels[e]||{label:e,type:null,image:null,emoji:null}},i.control=function(e){return void 0===this._controls[e]&&(this._controls[e]=new t(e,this._send,this._labelFor(e))),this._controls[e]},i.setOptions=function(e){this._options=e||{},this._labels=this._profile.labelsFor(this._options),Object.keys(this._controls).forEach(function(e){this._controls[e]._setLabel(this._labelFor(e))},this)},i.handleOutput=function(e,t){switch(t=t||{},e){case"state":return void this._applyState(t);case"login":return void this.trigger("login",void 0===t.user?null:t.user);case"logout":return void this.trigger("logout");case"controls:cleared":return void Object.keys(this._controls).forEach(function(e){this._controls[e]._rebindAfterClear()},this);default:var n,i;return void(0===e.indexOf("control:")&&(n=e.substr("control:".length),i=this._controls[t.id])&&i._trigger(n))}},i._applyState=function(e){void 0!==e.authenticated&&(this._authenticated=e.authenticated),void 0!==e.accessToken&&(this.access_token=e.accessToken),void 0!==e.nickname&&(this._nickname=e.nickname),void 0!==e.active&&(this._active=e.active),void 0!==e.playerId&&(this.playerId=e.playerId)},n}),define("CatLab/Webremote/LocalInput/KeyboardInput",[],function(){function e(e,t,n){this.initializeKeyboardInput(e,t,n)}var t=e.prototype;return t.initializeKeyboardInput=function(e,t,n){n=n||{},this._device=e,this._profile=t,this._window=n.window||("undefined"!=typeof window?window:null),this._document=n.document||(this._window?this._window.document:null),this._keyDocuments=[],this._messageTarget=null,this._fullscreenTarget=null,this._destroyed=!1;var i=this;this._keydownListener=function(e){i._onKey(e,"down")},this._keyupListener=function(e){i._onKey(e,"up")},this._messageListener=function(e){i._onMessage(e)},this._fullscreenListener=function(){i.resumeListening()},this._unhookListening=e.onListeningChange(function(e){e?i.resumeListening():i.stopListening()}),this.resumeListening()},t.resumeListening=function(){if(!this._destroyed){this.stopListening();var e=this._window;if(e){var t=e.document;if(t&&this._listenOn(t),(!t||!t.fullscreenElement)&&e.parent)try{var n=e.parent.document;if(!n)throw new Error("Unaccessible");n!==t&&this._listenOn(n)}catch(t){try{e.addEventListener("message",this._messageListener,!1),this._messageTarget=e}catch(e){console.error(e)}}this._document&&"function"==typeof this._document.addEventListener&&(this._document.addEventListener("fullscreenchange",this._fullscreenListener),this._fullscreenTarget=this._document)}}},t._listenOn=function(e){e.addEventListener("keydown",this._keydownListener),e.addEventListener("keyup",this._keyupListener),this._keyDocuments.push(e)},t.stopListening=function(){for(var e=0;e<this._keyDocuments.length;e++)this._keyDocuments[e].removeEventListener("keydown",this._keydownListener),this._keyDocuments[e].removeEventListener("keyup",this._keyupListener);this._keyDocuments=[],this._messageTarget&&(this._messageTarget.removeEventListener("message",this._messageListener,!1),this._messageTarget=null),this._fullscreenTarget&&(this._fullscreenTarget.removeEventListener("fullscreenchange",this._fullscreenListener),this._fullscreenTarget=null)},t.destroy=function(){this._destroyed=!0,this.stopListening(),this._unhookListening&&(this._unhookListening(),this._unhookListening=null)},t._onKey=function(e,t){var n;e&&(n=this._profile.mapKey(e))&&(this._device.sendInput("down"===t?"button:down":"button:up",{id:n}),this._profile.preventDefaultFor(n))&&"function"==typeof e.preventDefault&&e.preventDefault()},t._onMessage=function(e){e=e&&e.data;"object"!=typeof e||null===e||void 0===e.type||"catlab:keyboard"!==e.type||void 0===e.code||void 0===e.action||"down"!==e.action&&"up"!==e.action||this._onKey(e,e.action)},e}),define("CatLab/Webremote/LocalInput/CordovaInput",["CatLab/Webremote/LocalInput/KeyboardInput"],function(e){function t(e,t,n){this.initializeKeyboardInput(e,t,n);var i=this;this._backButtonListener=function(e){e&&"function"==typeof e.preventDefault&&e.preventDefault(),i._device.sendInput("backbutton",{})},this._backButtonTarget=null,this._document&&"function"==typeof this._document.addEventListener&&(this._document.addEventListener("backbutton",this._backButtonListener,!1),this._backButtonTarget=this._document)}var n=t.prototype=Object.create(e.prototype);return n.constructor=t,n.destroy=function(){this._backButtonTarget&&(this._backButtonTarget.removeEventListener("backbutton",this._backButtonListener,!1),this._backButtonTarget=null),e.prototype.destroy.call(this)},t}),define("CatLab/Webremote/LocalInput/AndroidRemoteInput",["CatLab/Webremote/LocalInput/CordovaInput"],function(e){return e}),define("CatLab/Webremote/LocalInput/GamepadInput",[],function(){function u(e){return String(null==e?"":e).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").replace(/-+$/,"")}function e(e,t,n){n=n||{},this._send=e,this._profile=t,this._window=n.window||("undefined"!=typeof window?window:null),this._navigator=n.navigator||("undefined"!=typeof navigator?navigator:null),this._devices={},this._detecting=!1,this._detectInterval=null,this._pollInterval=null,this._connectedListener=null,this._disconnectedListener=null}var t=e.prototype;return t.detect=function(){var i;!this._detecting&&this._available()&&(this._detecting=!0,(i=this)._window&&"ongamepadconnected"in this._window?(this._connectedListener=function(e){i._onSeen(e&&e.gamepad)},this._disconnectedListener=function(e){i._onGone(e&&e.gamepad)},this._window.addEventListener("gamepadconnected",this._connectedListener),this._window.addEventListener("gamepaddisconnected",this._disconnectedListener)):this._detectInterval=setInterval(function(){for(var e=i._getGamepads(),t=!1,n=0;n<e.length;n++)e[n]&&(t=!0,i._onSeen(e[n]));t&&(clearInterval(i._detectInterval),i._detectInterval=null)},1e3))},t.destroy=function(){var t=this;Object.keys(this._devices).forEach(function(e){e=t._devices[e];e&&e.unhookListening&&e.unhookListening()}),this._detecting=!1,this._detectInterval&&(clearInterval(this._detectInterval),this._detectInterval=null),this._pollInterval&&(clearInterval(this._pollInterval),this._pollInterval=null),this._window&&this._connectedListener&&(this._window.removeEventListener("gamepadconnected",this._connectedListener),this._window.removeEventListener("gamepaddisconnected",this._disconnectedListener)),this._connectedListener=null,this._disconnectedListener=null,this._devices={}},t._available=function(){return!!this._navigator&&("function"==typeof this._navigator.getGamepads||void 0!==this._navigator.webkitGetGamepads)},t._getGamepads=function(){return this._navigator?"function"==typeof this._navigator.getGamepads?this._navigator.getGamepads()||[]:this._navigator.webkitGetGamepads&&this._navigator.webkitGetGamepads()||[]:[]},t._deviceIdFor=function(e,t){for(var n=Object.keys(this._devices),i=0;i<n.length;i++){var o=this._devices[n[i]];if(o.idSlug===e&&o.index===t)return o.deviceId}return null},t._idFor=function(e,t){return this._profile.deviceIdPrefix+":"+e+"#"+t},t._lowestFreeOrdinal=function(e){for(var t=0;this._devices[this._idFor(e,t)];)t++;return t},t._onSeen=function(e){var t,n,i;e&&(i=u(e.id),this._deviceIdFor(i,e.index)||(t=this._idFor(i,this._lowestFreeOrdinal(i)),n={deviceId:t,idSlug:i,index:e.index,buttons:{},listening:!0,unhookListening:null},this._devices[t]=n,(i=this._send.connect(t,"gamepad",{id:e.id}))&&"function"==typeof i.onListeningChange&&("function"==typeof i.isListening&&(n.listening=i.isListening()),n.unhookListening=i.onListeningChange(function(e){n.listening=!!e})),this._startPolling()))},t._onGone=function(e){e&&(e=this._deviceIdFor(u(e.id),e.index))&&this._disconnect(e)},t._disconnect=function(e){var t=this._devices[e];t&&(t.unhookListening&&t.unhookListening(),delete this._devices[e],this._send.disconnect(e,"unplugged"),this._pollInterval)&&0===Object.keys(this._devices).length&&(clearInterval(this._pollInterval),this._pollInterval=null)},t._startPolling=function(){var e;this._pollInterval||((e=this)._pollInterval=setInterval(function(){e._poll()},50))},t._poll=function(){for(var t=this,e=this._getGamepads(),n={},i=0;i<e.length;i++){var o=e[i];if(o){var r=this._deviceIdFor(u(o.id),o.index);if(r){n[r]=!0;for(var s=this._devices[r],a=o.buttons||[],l=0;l<a.length;l++){var c,h=this._profile.mapGamepadButton(l);h&&(c=a[l]&&a[l].pressed?1:0)!==(s.buttons[h]||0)&&(s.buttons[h]=c,s.listening)&&this._send.input(r,c?"button:down":"button:up",{id:h})}}}}Object.keys(this._devices).forEach(function(e){n[e]||t._disconnect(e)})},e}),define("CatLab/Webremote/LocalInput/AppActions",[],function(){function e(e){this._window=(e=e||{}).window||("undefined"!=typeof window?window:null),this._navigator=e.navigator||("undefined"!=typeof navigator?navigator:null)}var t=e.prototype;return t.perform=function(e){var t,n=this._window,i=this._navigator,o=this;switch(e){case"minimize":return n&&n.plugins&&n.plugins.appMinimize?void n.plugins.appMinimize.minimize():void this.perform("exit");case"requestExit":return n&&n.onbeforeunload?void((t=n.onbeforeunload({}))&&this._confirm(t,function(e){e&&o.perform("exit")})):void this.perform("exit");case"exit":return i&&i.app&&"function"==typeof i.app.exitApp?void i.app.exitApp():void(n&&n.close())}},t._confirm=function(e,t){var n=this._navigator;n&&n.notification&&n.notification.confirm?n.notification.confirm(e,function(e){t(1===e)}):t(!!this._window&&this._window.confirm(e))},e}),define("CatLab/Webremote/LocalInput/DeviceChannel",["CatLab/Webremote/LocalInput/DeviceObject","CatLab/Webremote/LocalInput/KeyboardInput","CatLab/Webremote/LocalInput/CordovaInput","CatLab/Webremote/LocalInput/AndroidRemoteInput","CatLab/Webremote/LocalInput/GamepadInput","CatLab/Webremote/LocalInput/AppActions","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/index","CatLab/Webremote/Messages/NavigateableProxy"],function(r,e,t,n,i,o,s,a){function l(e,t){t=t||{},this._channels=e,this._keyboardEnabled=!1!==t.keyboard,this._platform=h[e=t.platform]?e:"keyboard",this._webcontrol=t.webcontrol||null,this._navigation="function"==typeof t.navigation?t.navigation:function(){return null},this._window=t.window||("undefined"!=typeof window?window:null),this._document=t.document||(this._window?this._window.document:null),this._navigator=t.navigator||("undefined"!=typeof navigator?navigator:null),this._installed=!1,this._listening=!0,this._devices={},this._keyboardAdapter=null,this._gamepadInput=null,this._bus=null,this._originalToController=null,this._appActions=new o({window:this._window,navigator:this._navigator})}var c=["nav:keyInput","nav:back"],h={keyboard:e,cordova:t,androidremote:n},e=l.prototype;return e.install=function(){var e,t,n;!this._installed&&(this._installed=!0,this._send("connect",{device:"display",kind:"display"}),this._bridgeDisplayBus(),this._keyboardEnabled)&&(e=s.forKind(this._platform),t=this._connectDevice("keyboard",this._platform,{}),n=h[this._platform],this._keyboardAdapter=new n(t,e,{window:this._window,document:this._document}),this._gamepadInput=new i(this._sender(),s.forKind("gamepad"),{window:this._window,navigator:this._navigator}),this._gamepadInput.detect(),this._listening||this._applyListeningToAll())},e.uninstall=function(){this._installed&&(this._installed=!1,this._keyboardAdapter&&(this._keyboardAdapter.destroy(),this._keyboardAdapter=null),this._gamepadInput&&(this._gamepadInput.destroy(),this._gamepadInput=null),this._bus&&(this._bus.toController=this._originalToController,this._bus=null,this._originalToController=null),this._devices={})},e.getKeyboardDevice=function(){return this._devices.keyboard||null},e.getDevice=function(e){return this._devices[e]||null},e.getAppActions=function(){return this._appActions},e.setListening=function(e){this._listening!==(e=!!e)&&(this._listening=e,this._applyListeningToAll())},e.isListening=function(){return this._listening},e._applyListeningToAll=function(){var t=this;Object.keys(this._devices).forEach(function(e){t._applyListening(t._devices[e])})},e._applyListening=function(e){this._listening?e.resumeListening():e.stopListening()},e.handleOutput=function(e){var t,n=e.data||{};"display"!==e.device?"app"!==e.method?(t=this._devices[e.device])?t.handleOutput(e.method,n):console.warn("[DeviceChannel] output for unknown device",e.device):this._appActions.perform(n.action):"bus"!==e.method?console.warn("[DeviceChannel] unexpected display output",e.method):(t=this._rehydrateActor(n.action,n.content),(e=this._navigation())&&a.handleMessage(n.action,t,e)||this._webcontrol&&this._webcontrol.getMessageBus().handleViewMessage(n.action,t))},e._rehydrateActor=function(e,t){var n;return(e=>{if("string"==typeof e)for(var t=0;t<c.length;t++){var n=c[t];if(e===n||e.substring(e.length-n.length-1)===":"+n)return 1}})(e)&&t&&t.actor&&"object"==typeof t.actor&&(e=(e=t.actor.deviceId)?this._devices[e]:null)?(n={},Object.keys(t).forEach(function(e){n[e]=t[e]}),n.actor=e,n):t},e._connectDevice=function(n,e,t){t=t||{};var i,o=this._devices[n];return o&&o.getKind()!==e&&(o.dispose(),delete this._devices[n],o=null),o?o.setOptions(t):(i=this,o=new r(n,e,function(e,t){i._sendInput(n,e,t)},s.forKind(e),t),this._devices[n]=o),this._listening||this._applyListening(o),this._send("connect",{device:n,kind:e,options:t}),o},e._sender=function(){var i=this;return{connect:function(e,t,n){return i._connectDevice(e,t,n||{})},disconnect:function(e,t){i._send("disconnect",{device:e,reason:t})},input:function(e,t,n){i._sendInput(e,t,n)}}},e._bridgeDisplayBus=function(){var n,e;this._webcontrol&&(e=(n=this)._webcontrol.getMessageBus(),this._bus=e,this._originalToController=e.toController,e.toController=function(e,t){n._sendInput("display","bus",{action:e,content:t})})},e._sendInput=function(e,t,n){this._send("input",{device:e,method:t,data:n||{}})},e._send=function(e,t){this._channels&&!this._channels.isClosed()&&this._channels.send("device",e,t)},l}),define("CatLab/Webremote/LocalInput/ProviderHost",["CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/Errors","CatLab/Webremote/Providers/BridgeContract"],function(c,h,e){function t(e,t){this._channels=e,this._instance=t,this._subscribed={},this._generation=1,this._publishedSettings=null,this._master=null,this._bindings=[],this._watchInstance()}var u=e.TARGET_FIRST,d=e.TARGET_INDEX,e=t.prototype;return e._bind=function(e,t){var n;"function"==typeof this._instance.on&&(n=this._instance.on(e,t),this._bindings.push({event:e,callback:t,binding:n}))},e.destroy=function(){var t=this._instance;this._bindings.forEach(function(e){e.binding&&"function"==typeof e.binding.unbind?e.binding.unbind():"function"==typeof t.off&&t.off(e.event,e.callback)}),this._bindings=[],this._subscribed={}},e._watchInstance=function(){var e,t;"function"==typeof this._instance.on&&((e=this)._bind("connect",t=function(){e.publishSettings()}),this._bind("reconnect",t))},e.handleMessage=function(e,t){"call"!==e?"subscribe"!==e?"hello"!==e?console.warn("[ProviderHost] unknown provider message",e):this._handleHello():this._handleSubscribe(t):this._handleCall(t)},e._handleHello=function(){this._generation++,this._publishedSettings=null,this.publishSettings()},e._handleCall=function(e){function t(t){if(!r&&s===n._generation){r=!0,t instanceof Error||(t=new Error(String(t)));try{n._send("error",{id:i,error:t})}catch(e){n._send("error",{id:i,error:new Error(String(t.message||t))})}}}var n=this,i=e.id,o=e.method,r=!1,s=this._generation;if("function"==typeof this._instance[o]){var a,l=(e.args||[]).slice();if("initMaster"!==o&&"initPlayer"!==o||(l=[this._masterStandIn()]),e.target)if(u[o])l.unshift(this._rebuildTarget(e.target));else{if("number"!=typeof d[o])return void t(new h.TransportError('BridgedProvider: "'+o+'" does not take a target'));l[d[o]]=this._rebuildTarget(e.target)}null!=e.ack&&l.push(this._makeAck(e.ack));try{a=this._instance[o].apply(this._instance,l)}catch(e){return void t(e)}c.when(a).done(function(e){if(!r&&s===n._generation){e=e===n._instance?void 0:e;try{n._send("result",{id:i,value:e})}catch(e){return void t(e)}r=!0,"connect"===o&&n.publishSettings()}}).fail(function(e){t(e)})}else t(new h.TransportError('BridgedProvider: unknown provider method "'+o+'"'))},e._makeAck=function(t){var n=this,i=this._generation;return function(e){i===n._generation&&n._send("ack",{ack:t,result:void 0===e?null:e})}},e._masterStandIn=function(){return this._master||(this._master={_userlibrary:{getFromId:function(){return null}},log:function(){}}),this._master},e._rebuildTarget=function(e){var i=this._instance,o="group"===e.type,r={getId:function(){return e.id},getEntityType:function(){return e.type},emit:function(e,t,n){return o?i.toGroup(r,e,t||{},n):i.toPlayer(r,e,t||{},n),!0}};return r},e._handleSubscribe=function(e){var t,n=e.event;this._subscribed[n]||(this._subscribed[n]=!0,t=this,"settings"!==n?this._bind(n,function(e){t._sendEvent(n,void 0===e?null:e)}):this._bind("settings",function(){t.publishSettings()}))},e._send=function(e,t){this._channels.send(e,t)},e._sendEvent=function(e,t){try{this._send("event",{event:e,data:t})}catch(t){this.reportError('provider:event "'+e+'"',t)}},e.reportError=function(e,t){console.error("[ProviderHost] could not send "+e,t)},e.publishSettings=function(){var n=this;this.describe().done(function(e){var t;try{t=JSON.stringify(e)}catch(e){t=null}null!==t&&t===n._publishedSettings||(n._publishedSettings=t,n._sendEvent("settings",e))})},e.describe=function(){function t(e){e={settings:e||{},canLoadExternalXml:!!n._read("canProviderLoadExternalXml",!1),canProxyFiles:!!n._read("canProxyFiles",!1),staticUrlBase:n._read("getStaticUrl","",[""]),connectUrl:n._read("getConnectURL",null,[null]),connectToken:n._read("getConnectToken",null,[null])},"function"==typeof n._instance.getConnectInstructions&&(e.connectInstructions=n._instance.getConnectInstructions()),"function"==typeof n._instance.getStartAndLoginInstructions&&(e.startAndLoginInstructions=n._instance.getStartAndLoginInstructions()),i.resolve(e)}var e,n=this,i=new c;try{e=this._instance.getProviderSettings()}catch(e){return t({}),i.promise()}return c.when(e).done(function(e){t(e)}).fail(function(){t({})}),i.promise()},e._read=function(e,t,n){if("function"!=typeof this._instance[e])return t;try{var i=this._instance[e].apply(this._instance,n||[]);return void 0===i?t:i}catch(e){return t}},t}),define("CatLab/Webremote/Transport/RpcClient",["CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/Codec","CatLab/Webremote/Transport/Errors"],function(h,u,d){function e(e,t){t=t||{},this._channels=null,this._poolName=t.poolName,this._pending={},this._pendingCount=0,this._seq=0,this._parked=[],e&&this.attach(e)}var t=e.prototype;return t.attach=function(e){var n=this;return(this._channels=e).on("rpc",function(e,t){n._onMessage(e,t)}),this._replayParked(),this},t._replayParked=function(){if(0!==this._parked.length){var e=this._parked;this._parked=[];for(var t=0;t<e.length;t++)this._post(e[t])}},t._post=function(e){if(this._channels&&!this._channels.isClosed())try{this._channels.sendEncoded(e.ch,e.type,e.fields,{onSent:e.onSent})}catch(t){this._settle(e.id,function(e){e.deferred.reject(t)})}else this._parked.push(e)},t.getPoolName=function(){return"function"==typeof this._poolName?this._poolName():this._poolName},t.call=function(n,e,t){if(!t||"number"!=typeof t.timeoutMs)throw new Error("RpcClient.call("+n+"): options.timeoutMs is required");for(var i=this,o=++this._seq,r={},s=0,a=(e||[]).slice();0<a.length&&void 0===a[a.length-1];)a.pop();var e=a.map(function(e,t){return void 0===e?null:u.encode(e,n+".args["+t+"]",{callback:function(e,t,n){if(0!==n)throw new d.TransportError("function cannot cross the worker boundary",t);n="cb"+ ++s;return r[n]=e,{__callback:n}}})}),l=new h,c={deferred:l,method:n,callbacks:r,timer:null};return this._pending[o]=c,this._pendingCount++,this._post({ch:"rpc",type:"call",id:o,fields:{id:o,method:n,args:e},onSent:function(){0<t.timeoutMs&&i._pending[o]===c&&(c.timer=setTimeout(function(){i._settle(o,function(e){e.deferred.reject(new d.RpcTimeoutError(n,i.getPoolName(),t.timeoutMs))})},t.timeoutMs))}}),l.promise()},t._settle=function(e,t){var n=this._pending[e];n&&(delete this._pending[e],this._pendingCount--,n.timer&&clearTimeout(n.timer),n.callbacks={},t(n))},t._onMessage=function(e,n){var t,i=this._pending[n.id];switch(e){case"result":return i?void this._settle(n.id,function(e){e.deferred.resolve(n.value)}):void console.warn("[RpcClient] response for a settled call ignored",n.id);case"error":return i?void this._settle(n.id,function(e){var t=n.error;t instanceof Error||(t=new d.RemoteError({name:"RemoteError",message:String(t)})),e.deferred.reject(t)}):void console.warn("[RpcClient] response for a settled call ignored",n.id);case"callback":return i?"function"!=typeof(t=i.callbacks[n.callbackId])?void console.warn("[RpcClient] unknown callback",n.callbackId,"for",i.method):void t.apply(null,n.args||[]):void console.warn("[RpcClient] callback for a settled call ignored",n.id,n.callbackId);default:console.warn("[RpcClient] unknown rpc message type",e)}},t.failAll=function(t){var n=this;this._parked=[],Object.keys(this._pending).forEach(function(e){n._settle(e,function(e){e.deferred.reject(t)})})},t.pendingCount=function(){return this._pendingCount},e}),define("CatLab/Webremote/Transport/Hosts/DedicatedWorkerHost",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/WorkerPort","CatLab/Webremote/Transport/Errors"],function(e,i,o,r){function t(e){this.initializeEventable(),e=e||{},this.kind="worker",this._url=e.workerUrl||"scripts/webworker.js",this._WorkerCtor="WorkerCtor"in e?e.WorkerCtor:"undefined"!=typeof Worker?Worker:void 0,this.worker=null,this.port=null,this._started=!1}e=t.prototype=new e;return e.start=function(){var t=new i,n=this;if(this._started)t.reject(new r.PoolBootError(this.kind,"host already started"));else if(this._started=!0,"function"!=typeof this._WorkerCtor)t.reject(new r.PoolBootError("worker","Worker is not defined"));else{try{this.worker=new this._WorkerCtor(this._url)}catch(e){return t.reject(new r.PoolBootError("worker",e&&e.message?e.message:String(e),e)),t.promise()}this.worker.onerror=function(e){n.trigger("error",e)},this.port=o.forWorker(this.worker),t.resolve(this.port)}return t.promise()},e.terminate=function(){if(this.port&&(this.port.close(),this.port=null),this.worker){try{this.worker.terminate()}catch(e){}this.worker=null}},t}),define("CatLab/Webremote/Transport/Hosts/IframeWorkerHost",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/WorkerPort","CatLab/Webremote/Transport/Errors"],function(e,n,i,o){function t(e){this.initializeEventable(),e=e||{},this.kind="iframe",this._frameUrl=e.frameUrl||"iframe-host.html",this._document=e.parentDocument||("undefined"!=typeof document?document:null),this._window=e.parentWindow||("undefined"!=typeof window?window:null),this.iframe=null,this.port=null,this._started=!1}e=t.prototype=new e;return e.start=function(){var t=new n;if(this._started)t.reject(new o.PoolBootError(this.kind,"host already started"));else if(this._started=!0,this._document&&this._window)if(this._document.body){var e=this._document.createElement("iframe");e.setAttribute("src",this._frameUrl),e.setAttribute("aria-hidden","true"),e.setAttribute("tabindex","-1"),e.setAttribute("title","pool host"),e.style.display="none",e.style.width="0",e.style.height="0",e.style.border="0";try{this._document.body.appendChild(e)}catch(e){return t.reject(new o.PoolBootError("iframe",e&&e.message?e.message:String(e),e)),t.promise()}this.iframe=e,this.port=i.forWindow(e.contentWindow,this._window),t.resolve(this.port)}else t.reject(new o.PoolBootError("iframe","document.body is not available"));else t.reject(new o.PoolBootError("iframe","no document/window on this thread"));return t.promise()},e.terminate=function(){this.port&&(this.port.close(),this.port=null),this.iframe&&(this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null)},t}),define("CatLab/Webremote/PlayerPool/Managers/WebworkerManager",["CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/LocalInput/DeviceChannel","CatLab/Webremote/LocalInput/ProviderHost","CatLab/Webremote/Providers/Dummy","CatLab/Webremote/Transport/Channels","CatLab/Webremote/Transport/RpcClient","CatLab/Webremote/Transport/Errors","CatLab/Webremote/Transport/Hosts/DedicatedWorkerHost","CatLab/Webremote/Transport/Hosts/IframeWorkerHost"],function(e,c,t,o,n,i,r,a,s,h,l,u){function d(e){this.initializeEventable(),this._managerOptions=e||{},this._manifest=this._managerOptions.manifest||null,this._hostKinds=this._managerOptions.hosts||g,this._bootTimeoutMs="number"==typeof this._managerOptions.bootTimeoutMs?this._managerOptions.bootTimeoutMs:9e4,this._helloTimeoutMs="number"==typeof this._managerOptions.helloTimeoutMs?this._managerOptions.helloTimeoutMs:1e4,this._hostFactories=this._managerOptions.hostFactories||{},this._length=0,this._connectedDevices=null,this._actualPlayersLength=0,this._mode="regular",this.devices=null,this._localInputListening=!0,this.currentNavigationView=null,this.host=null,this.channels=null,this._rpc=null,this._abortBoot=null,this._booted=!1,this._disconnected=!1,this._pingSeq=0,this._pings={},this._parkedQueue=[],this._pendingConfigOverrides=null,this._configOverridesQueued=!1,this._modsDeferred=null,this._providerHost=null,this._providerName="socketio"}var f=new t,p=["users","currentuser"],g=["worker","iframe"],t=d.prototype=new e;return t.constructor=d,t.getHostKind=function(){return this.host?this.host.kind:null},t.getHostProvider=function(){return this._providerName},t._createHost=function(e){if("function"==typeof this._hostFactories[e])return this._hostFactories[e](this._managerOptions);switch(e){case"worker":return new l({workerUrl:this._managerOptions.workerUrl||"scripts/webworker.js"});case"iframe":return new u({frameUrl:this._managerOptions.frameUrl||"iframe-host.html"});default:throw new Error('WebworkerManager: unknown host kind "'+e+'"')}},t._buildInitOptions=function(t){var n,e={};return(t=t||{}).webcontrolOptions&&(n={},Object.keys(t.webcontrolOptions).forEach(function(e){"provider"!==e&&"translator"!==e&&(n[e]=t.webcontrolOptions[e])}),e.webcontrolOptions=n),t.oauth&&(e.oauth=t.oauth),e.authStorage=this.getPersistentAuthStorageSnapshot(),void 0!==t.keyboard&&(e.keyboard=t.keyboard),"string"==typeof t.controlUserType&&(e.controlUserType=t.controlUserType),void 0!==t.playerPoolMode&&(e.playerPoolMode=t.playerPoolMode),e.poolNumber="number"==typeof this.poolNumber?this.poolNumber:1,e.localInput=this._localInput,e.events=this._manifest&&this._manifest.events?this._manifest.events.slice():[],e.provider=this._providerName,e},t.initialize=function(e){this.initializeManager(),this._initOptions=e||{},this._disconnected=!1,this._booted=!1,this._parkedQueue=[],this._pendingConfigOverrides=null,this._configOverridesQueued=!1,this._localInput=void 0===this._initOptions.localInput||!!this._initOptions.localInput;var t=new c,n=this,e=(this._rpc=new s(null,{poolName:function(){return n.poolNumber||1}}),this._providerHost&&"function"==typeof this._providerHost.destroy&&this._providerHost.destroy(),this._providerHost=null,this._providerName="socketio",this._initOptions.webcontrolOptions&&this._initOptions.webcontrolOptions.provider);return e&&"object"==typeof e&&(this._providerName="bridged",this._providerHost=new i({send:function(e,t){n.channels&&!n.channels.isClosed()&&n.channels.sendNow("provider",e,t)}},e)),this.initializeWebcontrol(this._initOptions).done(function(){n._initOptions.oauth&&f.oAuth(n._initOptions.oauth),n._bootChain(n._hostKinds.slice(),null).done(function(){n._booted=!0,n._installLocalInput(),t.resolve()}).fail(function(e){t.reject(e)})}).fail(function(e){t.reject(e)}),t.promise()},t._bootChain=function(n,e){var i=new c,o=this,r=n.shift();return void 0===r?i.reject(e||new h.PoolBootError("none","no host kinds configured")):this._bootOne(r).done(function(){i.resolve()}).fail(function(e){var t,e=e instanceof h.PoolBootError?e:new h.PoolBootError(r,e&&e.message?e.message:String(e),e);0<n.length&&!e.aborted?(t=n[0],o._parkedQueue=o._teardownHost({preserveCalls:!0}),console.warn("[WebworkerManager] pool "+(o.poolNumber||1)+": "+r+" host failed ("+e.reason+"); falling back to "+t+"."),o.trigger("transport:fallback",{pool:o.poolNumber||1,from:r,to:t,reason:e.reason}),o._bootChain(n,e).done(function(){i.resolve()}).fail(function(e){i.reject(e)})):(o._failPendingDispatches(e),o._teardownHost(),i.reject(e))}),i.promise()},t._bootOne=function(t){var e,n=new c,i=this;try{e=this._createHost(t)}catch(e){return n.reject(new h.PoolBootError(t,e.message,e)),n.promise()}this.host=e;function o(){r||null!==a||(clearTimeout(s),s=null,a=setTimeout(function(){l(new h.PoolBootError(t,"control:ready did not arrive within "+i._bootTimeoutMs+"ms of control:hello"))},i._bootTimeoutMs))}var r=!1,s=null,a=null,l=function(e){r||(r=!0,i._abortBoot=null,clearTimeout(s),clearTimeout(a),e?n.reject(e):n.resolve())};this._abortBoot=function(){var e=new h.PoolBootError(t,"host torn down during boot");e.aborted=!0,l(e)},e.on("error",function(e){r?i.trigger("worker:error",e):l(new h.PoolBootError(t,"host error during boot: "+(e&&e.message?e.message:String(e)),e))}),s=setTimeout(function(){l(new h.PoolBootError(t,"control:hello did not arrive within "+i._helloTimeoutMs+"ms"))},i._helloTimeoutMs);return e.start().done(function(e){i._attachPort(e,t,l,o)}).fail(function(e){l(e)}),n.promise()},t._attachPort=function(e,i,o,r){var s=this;this.channels=new a(e,{onUnhandled:function(e){console.error("[WebworkerManager] unhandled message from pool",e)}}),this.channels.onHandlerError(function(e){console.error("[WebworkerManager] handler threw",e),s.trigger("transport:error",e)}),null===this._pendingConfigOverrides||this._configOverridesQueued||(this.channels.send("host","config",{overrides:this._pendingConfigOverrides}),this._configOverridesQueued=!0),this._rpc.attach(this.channels),this.channels.on("control",function(e,t){var n;switch(e){case"hello":"function"==typeof r&&r();try{s.channels.sendNow("control","init",{options:s._buildInitOptions(s._initOptions)})}catch(e){o(new h.PoolBootError(i,"control:init could not be encoded: "+e.message,e))}return;case"ready":return s.channels.open(),void o(null);case"pong":return void(s._pings[t.id]&&s._pings[t.id].pong());case"fatal":return n=t.error&&t.error.message||"unknown",s._booted?void s.trigger("worker:error",t.error):void o(new h.PoolBootError(i,"control:fatal: "+n,t.error));case"error":return console.error("[WebworkerManager] pool "+(s.poolNumber||1)+" reported: "+t.context,t.error),void s.trigger("transport:error",t.error);default:console.warn("[WebworkerManager] unknown control message",e)}}),this.channels.on("events",function(e,t){"event"===e&&(s._syncLengthFromPayload(t.name,t.data),s.trigger(t.name,t.data))}),this.channels.on("device",function(e,t){s._onDevice(e,t)}),this.channels.on("provider",function(e,t){s._providerHost?s._providerHost.handleMessage(e,t):console.warn("[WebworkerManager] provider message with no ProviderHost registered",e)}),this.channels.on("host",function(e,t){"storage"!==e?"modsReady"!==e?console.warn("[WebworkerManager] unknown host message",e):s._modsDeferred&&(e=s._modsDeferred,s._modsDeferred=null,e.resolve()):s.applyPersistentStorageSync({name:t.key,rawValue:t.value})}),0<this._parkedQueue.length&&(this.channels.adoptQueue(this._parkedQueue),this._parkedQueue=[])},t._teardownHost=function(e){var e=!(!e||!e.preserveCalls),t=[];return e?this.channels&&(t=this.channels.takeQueue()):this._rpc&&this._rpc.failAll(new Error("[WebworkerManager] pool host torn down")),this._failPendingPings(),this._teardownLocalInput(),this.channels&&(this.channels.close(),this.channels=null),this.host&&(this.host.off("error"),this.host.terminate(),this.host=null),e||(this._rpc=null),!e&&this._abortBoot&&(e=this._abortBoot,this._abortBoot=null,e()),t},t.terminateHost=function(){this._teardownHost()},t.getPersistentAuthStorageSnapshot=function(){var n={};return"undefined"!=typeof window&&void 0!==window.localStorage&&p.forEach(function(e){var t=window.localStorage.getItem(e);null!==t&&(n[e]=t)}),n},t.applyPersistentStorageSync=function(e){e&&void 0!==e.name&&-1!==p.indexOf(e.name)&&"undefined"!=typeof window&&void 0!==window.localStorage&&(null!=e.rawValue?window.localStorage.setItem(e.name,e.rawValue):window.localStorage.removeItem(e.name))},t.initializeWebcontrol=function(e){function t(){f.initialize(i).done(function(){n.resolve()})}var n=new c,i={provider:new r};e.webcontrolOptions&&e.webcontrolOptions.translator&&(i.translator=e.webcontrolOptions.translator),e.webcontrolOptions&&e.webcontrolOptions.assetsUrl&&(i.assetsUrl=e.webcontrolOptions.assetsUrl);return e.portalAssets?f.setViewFactory(new o(e.portalAssets)).done(t):t(),n.promise()},t.getWebcontrol=function(){return f},t.getKeyboardUser=function(){return this.devices?this.devices.getKeyboardDevice():null},t.setLocalInputListening=function(e){return this._localInputListening=!!e,this.devices&&this.devices.setListening(this._localInputListening),this._localInputListening},t.isLocalInputListening=function(){return this.devices?this.devices.isListening():this._localInputListening},t._entryFor=function(e){if(!this._manifest)throw new Error('WebworkerManager: no manifest configured; cannot call "'+e+'"');var t=this._manifest.methods&&this._manifest.methods[e];if(t)return t;if(this._manifest.hostMethods&&this._manifest.hostMethods[e])throw new h.TransportError("host method not rpc-callable: "+e);throw new Error('WebworkerManager: "'+e+'" is not in the manifest')},t._hostEntryFor=function(e){if(!this._manifest)throw new Error('WebworkerManager: no manifest configured; cannot call "'+e+'"');var t=this._manifest.hostMethods&&this._manifest.hostMethods[e];if(t)return t;throw new Error('WebworkerManager: "'+e+'" is not in the manifest')},t.call=function(){var e=Array.prototype.slice.call(arguments),t=e.shift(),n=this._entryFor(t);return this.rpc(t,e,{timeoutMs:n.timeoutMs})},t.rpc=function(e,t,n){var i;return this._disconnected||!this._rpc?((i=new c).reject(new Error("[WebworkerManager] rpc after disconnect: "+e)),i.promise()):this._rpc.call(e,t||[],n)},t._failPendingDispatches=function(e){this._rpc&&this._rpc.failAll(e)},t._syncLengthFromPayload=function(e,t){"change:length"===e&&"number"==typeof t&&(this._length=t),"change:actualLength"===e&&"number"==typeof t&&(this._actualPlayersLength=t),"change:connections"===e&&"number"==typeof t&&(this._connectedDevices=t)},t.ping=function(e){e="number"==typeof e?e:3e3;var t,n,i,o=new c;return this.channels?(n=++(t=this)._pingSeq,i=setTimeout(function(){delete t._pings[n],o.reject(new Error("[WebworkerManager] ping timeout"))},e),this._pings[n]={pong:function(){clearTimeout(i),delete t._pings[n],o.resolve({pong:!0})},abort:function(){clearTimeout(i),delete t._pings[n],o.reject(new Error("[WebworkerManager] ping aborted: host torn down"))}},this.channels.sendNow("control","ping",{id:n})):o.reject(new Error("[WebworkerManager] ping without a host")),o.promise()},t._failPendingPings=function(){var t=this;Object.keys(this._pings).forEach(function(e){e=t._pings[e];e&&e.abort()}),this._pings={}},t.enableNavigation=function(e,t){return this._trackCurrentNavigation(e,t),this.currentNavigationView=e,this.rpc("enableNavigation",[{includeDisplayUsers:t}],{timeoutMs:this._hostEntryFor("enableNavigation").timeoutMs})},t._clearCurrentNavigation=function(){this.currentNavigationView=null},t.openPortal=function(t){t=t||{},this._suspendNavigationForPortal();var n={},e=(Object.keys(t).forEach(function(e){"start"!==e&&"back"!==e&&"purchaseSeatsCallback"!==e&&"leanback"!==e&&"element"!==e&&(n[e]=t[e])}),"function"==typeof t.start?t.start:function(){}),i="function"==typeof t.back?t.back:function(){};return this.rpc("openPortal",[n,e,i],{timeoutMs:this._hostEntryFor("openPortal").timeoutMs})},t.finalizePortal=function(e){return this.rpc("closePortal",[e],{timeoutMs:this._hostEntryFor("closePortal").timeoutMs})},t.getConnectScreen=function(t){this.openPortal(t).fail(function(e){console.error("[WebworkerManager] openPortal failed",e)});var n=f.getMessageBus(),i=n.addViewListener.bind(n);return n.addViewListener=function(e){i(e),n.handleViewMessage("state:change",{state:{activePlayers:0,minPlayers:t.minPlayers||1,maxPlayers:t.maxPlayers||4,connectInstructions:[""],startAndLoginInstructions:[""],showInactivePlayers:t.activePlayersPanel||!1,qrUrl:null}}),n.addViewListener=i},f.portalView(n,t)},t.setPublicConnectInfo=function(e){return this.channels?this.call("setPublicConnectInfo",e):((e=new c).resolve(),e.promise())},t.getAuthenticationScreen=function(t){t=t||{};var n={};return Object.keys(t).forEach(function(e){"function"!=typeof t[e]&&(n[e]=t[e])}),this.rpc("openAuthentication",[n],{timeoutMs:this._hostEntryFor("openAuthentication").timeoutMs}).fail(function(e){console.error("[WebworkerManager] openAuthentication failed",e)}),f.authenticationView(f.getMessageBus(),t)},t.clearConnectScreen=function(e){return this.call("clearConnectScreen",e)},t.activateKeyboardUser=function(e){return this.call("activateKeyboardUser",e)},t.setKeyboardUser=function(e){var t=e;if(e&&"function"==typeof e.getDeviceId)t=e.getDeviceId();else if(e&&"object"==typeof e&&(Object.prototype.hasOwnProperty.call(e,"deviceId")||Object.prototype.hasOwnProperty.call(e,"userId"))&&!(t=e.deviceId||e.userId||null))return(e=new c).resolve(),e.promise();return this.call("setKeyboardUser",t)},t.createDummyUser=function(e,t,n){return this.call("createDummyUser",e,t,n||{})},t.getAccessTokens=function(){return this.call("getAccessTokens")},t.countActivePlayers=function(){return this.call("countActivePlayers")},t.isDelayed=function(e){return this.call("isDelayed",e)},t.shouldShowAvatars=function(){return this.call("shouldShowAvatars")},t.restore=function(e,t){return this.rpc("restore",[e,t],{timeoutMs:this._hostEntryFor("restore").timeoutMs})},t.applyConfigOverrides=function(e){this._pendingConfigOverrides=e,this.channels?(this.channels.send("host","config",{overrides:e}),this._configOverridesQueued=!0):this._configOverridesQueued=!1;e=new c;return e.resolve(),e.promise()},t.initializePlayerpoolMods=function(e,t,n){var i=new c;return this.channels?(this._modsDeferred=i,this.channels.send("host","mods",{descriptors:e,baseUrl:t,query:n})):i.reject(new Error("[WebworkerManager] initializePlayerpoolMods without a host")),i.promise()},t.disconnect=function(){this._disconnected=!0,this._teardownHost();var e=new c;return e.resolve(),e.promise()},t._installLocalInput=function(){var e,t;this._localInput&&this.channels&&(e=this,t="undefined"!=typeof window&&window.cordova?void 0!==window.CORDOVA_TV&&window.CORDOVA_TV?"androidremote":"cordova":"keyboard","string"==typeof this._initOptions.controlUserType&&(t=this._initOptions.controlUserType),this.devices=new n(this.channels,{keyboard:!1!==this._initOptions.keyboard,platform:t,webcontrol:f,navigation:function(){return e.currentNavigationView}}),this.devices.setListening(this._localInputListening),this.devices.install())},t._teardownLocalInput=function(){this.devices&&(this.devices.uninstall(),this.devices=null)},t._onDevice=function(e,t){"output"===e?t&&null!=t.data?this.devices?this.devices.handleOutput(t):console.warn("[WebworkerManager] device output with no device channel",t):this.trigger("transport:error",new h.TransportError("malformed device:output frame (no data)")):console.warn("[WebworkerManager] unexpected device message",e)},Object.defineProperty(t,"length",{get:function(){return this._length}}),Object.defineProperty(t,"connectedDevices",{get:function(){return"number"==typeof this._connectedDevices?this._connectedDevices:this._length}}),Object.defineProperty(t,"actualPlayersLength",{get:function(){return this._actualPlayersLength}}),d}),define("CatLab/Webremote/PlayerPool/Protocol/whenAllSettled",["CatLab/Webremote/Tools/Deferred"],function(u){return function(e,n){var i,t,o,r=new u,s=[],a=[],l=e.length,c=!1,h=null;return 0===l?r.resolve({fulfilled:s,failed:a}):(i=e.map(function(){return!1}),t=function(){c||(c=!0,null!==h&&clearTimeout(h),r.resolve({fulfilled:s,failed:a}))},o=function(){0==--l&&t()},e.forEach(function(e,t){u.when(e).done(function(e){i[t]||c||(i[t]=!0,s.push({index:t,value:e}),o())}).fail(function(e){i[t]||c||(i[t]=!0,a.push({index:t,error:e}),o())})}),"number"==typeof n&&0<n&&!c&&(h=setTimeout(function(){i.forEach(function(e,t){e||(i[t]=!0,a.push({index:t,error:new Error("whenAllSettled: timeout after "+n+"ms")}))}),t()},n))),r.promise()}}),define("CatLab/Webremote/PlayerPool/Protocol/Aggregators",[],function(){var r={first:function(e){return e[0]},concat:function(e){var t=[];return e.forEach(function(e){Array.isArray(e)?Array.prototype.push.apply(t,e):null!=e&&t.push(e)}),t},sum:function(e){var t=0;return e.forEach(function(e){"number"==typeof e&&(t+=e)}),t},array:function(e){return e},wait:function(){},numeric:function(e){return"number"==typeof e?e:0},someTrue:function(){return function(e){for(var t=0;t<e.length;t++)if(e[t])return!0;return!1}},mergeSorted:function(e){var n=e.key,i=!1!==e.descending,o=e.trimArgIndex;return function(e,t){return 1===e.length&&Array.isArray(e[0])?e[0]:((e=r.concat(e)).sort(function(e,t){e=e&&"number"==typeof e[n]?e[n]:0,t=t&&"number"==typeof t[n]?t[n]:0;return i?t-e:e-t}),"number"==typeof o&&"number"==typeof t[o]?e.slice(0,t[o]):e)}},weightedRandomPick:function(e){var u=e.amountArgIndex;return function(e,t,i){if(1===e.length)return e[0];for(var n=e.map(function(e,t){var t=i&&i.hosts&&i.hosts[t]||{},e=Array.isArray(e)?e.slice():[],n=t.actualPlayersLength;return{candidates:e,weight:n="number"!=typeof(n="number"!=typeof n||n<=0?t.length:n)||n<=0?e.length:n}}),o="number"==typeof t[u]?t[u]:0,r=[];r.length<o;){var s=(()=>{var t=0;return n.forEach(function(e){0<e.candidates.length&&(t+=e.weight)}),t})();if(s<=0)break;for(var a=Math.random()*s,l=0,c=null,h=0;h<n.length;h++)if(0!==n[h].candidates.length&&a<(l+=n[h].weight)){c=n[h];break}if(!c)break;s=Math.floor(Math.random()*c.candidates.length);r.push(c.candidates.splice(s,1)[0])}return r}},sumByIndex:function(e){var r=(e=e||{}).sumField,t=e.shareField,s=e.copyFields||[];return function(e){var i,o;return 1===e.length?e[0]:(i=[],o=0,e.forEach(function(e){Array.isArray(e)&&e.forEach(function(t,n){i[n]||(i[n]={},i[n][r]=0,s.forEach(function(e){i[n][e]=t[e]}));var e=Number(t[r])||0;i[n][r]+=e,o+=e})}),t&&i.forEach(function(e){e[t]=0<o?e[r]/o:0}),i)}},sumByKey:function(e){var o=(e=e||{}).keyField,r=e.sumField,t=e.shareField,s=e.sortDescending;return function(e){var n,i;return 1===e.length?e[0]:(n={},i=0,e.forEach(function(e){Array.isArray(e)&&e.forEach(function(e){var t=e[o],e=(n[t]||(n[t]={},n[t][o]=e[o],n[t][r]=0),Number(e[r])||0);n[t][r]+=e,i+=e})}),e=Object.keys(n).map(function(e){return n[e]}),s&&e.sort(function(e,t){return t[o]-e[o]}),t&&e.forEach(function(e){e[t]=0<i?e[r]/i:0}),e)}}};return r}),define("CatLab/Webremote/PlayerPool/EngineManifest",["CatLab/Webremote/PlayerPool/Protocol/Aggregators"],function(e){return{methods:{serialize:{route:"all",aggregate:"array",timeoutMs:3e4},countActivePlayers:{route:"all",aggregate:"sum",timeoutMs:1e4},getRandomPlayers:{route:"all",aggregate:e.weightedRandomPick({amountArgIndex:0}),timeoutMs:1e4},getAbsoluteRandomPlayers:{route:"all",aggregate:e.weightedRandomPick({amountArgIndex:0}),timeoutMs:1e4},commitRandomPlayers:{route:"all",aggregate:"wait",timeoutMs:1e4},resetRandomPlayers:{route:"all",aggregate:"wait",timeoutMs:1e4},newGroup:{route:"leastFullOrSpawn",timeoutMs:1e4},hasKeyboardPlayer:{route:"primary",timeoutMs:1e4},isDelayed:{route:"primary",timeoutMs:1e4},shouldShowAvatars:{route:"primary",timeoutMs:1e4},getMaxPlayers:{route:"primary",timeoutMs:1e4},setMaxPlayers:{route:"all",aggregate:"first",timeoutMs:1e4,replayOnSpawn:!0},setPortalMaxPlayers:{route:"all",aggregate:"first",timeoutMs:1e4,replayOnSpawn:!0},setLicenseToken:{route:"all",aggregate:"first",timeoutMs:1e4,replayOnSpawn:!0},hasGlobalAccessTokens:{route:"primary",timeoutMs:1e4},preloadFiles:{route:"primary",timeoutMs:0},clearConnectScreen:{route:"all",aggregate:"wait",timeoutMs:1e4},activateKeyboardUser:{route:"primary",timeoutMs:1e4},setKeyboardUser:{route:"primary",timeoutMs:1e4},createDummyUser:{route:"primary",timeoutMs:1e4},getAccessTokens:{route:"primary",timeoutMs:1e4},pause:{route:"all",aggregate:"wait",timeoutMs:1e4},resume:{route:"all",aggregate:"wait",timeoutMs:1e4},setExternalActivePlayers:{route:"all",aggregate:"wait",timeoutMs:1e4},setExternalUsers:{route:"all",aggregate:"wait",timeoutMs:1e4},setLeasedSeats:{route:"all",aggregate:"wait",timeoutMs:1e4},setPublicConnectInfo:{route:"primary",timeoutMs:1e4},getLocalDevices:{route:"primary",timeoutMs:1e4}},hostMethods:{openPortal:{timeoutMs:0},closePortal:{timeoutMs:1e4},openAuthentication:{timeoutMs:0},enableNavigation:{timeoutMs:1e4},restore:{timeoutMs:3e4},applyConfigOverrides:{timeoutMs:1e4}},aliases:{createGroup:"newGroup"},events:["user:join","change:length","change:actualLength","change:connections","change:maxplayers","change:mode","connectInfo:change","license:capped","portal:active:count","portal:users","authentication:close","smileys:slingshot","transport:fallback","device:disconnected","device:reconnected"],eventShapes:{"user:join":"none","change:length":"number","change:actualLength":"number","change:connections":"number","change:maxplayers":"number","change:mode":"string","connectInfo:change":{connectToken:"string",connectTokenForDisplay:"string",connectUrl:"string",server:"string",contentProxy:"string?",gameId:"string?",accessToken:"string?"},"license:capped":{max:"number",count:"number",relay_token:"string?"},"portal:active:count":"number","portal:users":"array","authentication:close":"none","smileys:slingshot":{player:{id:"string",name:"string",smiley:"string"},angle:"number",speed:"number",smiley:"string"},"transport:fallback":{pool:"number",from:"string",to:"string",reason:"string"},"device:disconnected":{device:"string"},"device:reconnected":{device:"string"}}}}),define("CatLab/Webremote/PlayerPool/Managers/WorkerManager",["CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/PlayerPool/Managers/WebworkerManager","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/PlayerPool/Protocol/whenAllSettled","CatLab/Webremote/PlayerPool/EngineManifest"],function(e,t,i,n,o){function r(e){this.initializeEventable(),this.workers=[],this._mode="regular",this._initOptions=null,this._totalLength=0,this._managerOptions=e||{},this._manifest=this._managerOptions.manifest||o,this._primaryBootSettled=!1,this._primaryBoot=null}var s=["change:length","connectInfo:change","change:mode","change:connections","portal:active:count","portal:users"],e=r.prototype=new e;return e.constructor=r,e._whenPrimaryReady=function(){return this._primaryBootSettled?null:(this._primaryBoot||(this._primaryBoot=new i),this._primaryBoot.promise())},e._settlePrimaryBoot=function(){this._primaryBootSettled=!0;var e=this._primaryBoot;this._primaryBoot=null,e&&e.resolve()},e.initialize=function(e){this.initializeManager(),(this._initOptions=e)&&e.playerPoolMode&&(this._mode=e.playerPoolMode);var t=new i,n=this;return this._createWorkerManager().initialize(e).done(function(){n._started=!0,n._settlePrimaryBoot(),t.resolve()}).fail(function(e){console.error("[WorkerManager] Primary pool failed to boot on every host:",e),n.workers=[],n._settlePrimaryBoot(),t.reject(e)}),t.promise()},e._createWorkerManager=function(){var e=Object.assign({},this._managerOptions,{manifest:this._manifest||null}),e=new t(e);return this.workers.push(e),this._bindWorkerEvents(e),e},e._getPrimaryWorker=function(){return this.workers[0]},e._bindWorkerEvents=function(n){var i=this,e=this._manifest&&this._manifest.events?this._manifest.events:[],o={};e.forEach(function(t){o[t]||-1!==s.indexOf(t)||(o[t]=!0,i._bindBarrierEvent&&i._bindBarrierEvent(n,t))||n.on(t,function(e){i.trigger(t,e)})}),n.on("change:length",function(){i._updateTotalLength(),i.trigger("change:length")}),n.on("connectInfo:change",function(e){i._onWorkerConnectInfo(n,e)}),n.on("change:mode",function(e){i._mode=e,i.trigger("change:mode",e)})},e._onWorkerConnectInfo=function(e,t){this.trigger("connectInfo:change",t)},e._updateTotalLength=function(){var t=0;this.workers.forEach(function(e){t+=e.length||0}),this._totalLength=t},e.enableNavigation=function(e,t){return this._trackCurrentNavigation(e,t),this._getPrimaryWorker().enableNavigation(e,t)},e._clearCurrentNavigation=function(){var e=this._getPrimaryWorker();e&&"function"==typeof e._clearCurrentNavigation&&e._clearCurrentNavigation()},e.getKeyboardUser=function(){var e=this._getPrimaryWorker();return e&&"function"==typeof e.getKeyboardUser?e.getKeyboardUser():null},e.setLocalInputListening=function(e){var t=this._getPrimaryWorker();return t&&"function"==typeof t.setLocalInputListening?t.setLocalInputListening(e):!!e},e.isLocalInputListening=function(){var e=this._getPrimaryWorker();return!e||"function"!=typeof e.isLocalInputListening||e.isLocalInputListening()},e.getConnectScreen=function(e){return this._getPrimaryWorker().getConnectScreen(e)},e.clearConnectScreen=function(e){return this._getPrimaryWorker().clearConnectScreen(e)},e.activateKeyboardUser=function(e){return this._getPrimaryWorker().activateKeyboardUser(e)},e.setKeyboardUser=function(e){return this._getPrimaryWorker().setKeyboardUser(e)},e.createDummyUser=function(e,t,n){return this._getPrimaryWorker().createDummyUser(e,t,n)},e.applyConfigOverrides=function(e){return this._getPrimaryWorker().applyConfigOverrides(e)},e.getAuthenticationScreen=function(e){return this._getPrimaryWorker().getAuthenticationScreen(e)},e.getAccessTokens=function(){return this._getPrimaryWorker().getAccessTokens()},e.countActivePlayers=function(){return this._getPrimaryWorker().countActivePlayers()},e.getWebcontrol=function(){var e=this._getPrimaryWorker();return e&&"function"==typeof e.getWebcontrol?e.getWebcontrol():null},e.disconnect=function(){var e=new i,t=this.workers,t=(this.workers=[],this._settlePrimaryBoot(),t.map(function(e){return e.disconnect()}));return n(t,0).done(function(){e.resolve()}),e.promise()},Object.defineProperty(e,"length",{get:function(){return this._totalLength}}),Object.defineProperty(e,"actualPlayersLength",{get:function(){return this._totalLength}}),r}),define("CatLab/Webremote/PlayerPool/Protocol/Router",[],function(){return{select:function(e,t){switch(e){case"primary":return t.length?[t[0]]:[];case"last":return t.length?[t[t.length-1]]:[];case"leastFull":case"leastFullOrSpawn":if(!t.length)return[];for(var n=t[0],i=1;i<t.length;i++)(t[i].length||0)<(n.length||0)&&(n=t[i]);return[n];default:return t.slice()}}}}),define("CatLab/Webremote/PlayerPool/Protocol/ManifestProxy",["CatLab/Webremote/Tools/Deferred","CatLab/Webremote/PlayerPool/Protocol/Aggregators","CatLab/Webremote/PlayerPool/Protocol/Router","CatLab/Webremote/PlayerPool/Protocol/whenAllSettled"],function(p,n,g,m){function r(e,t){if("function"==typeof e[t])for(var n=e;n&&n!==Object.prototype;){if(Object.prototype.hasOwnProperty.call(n,t))return 1;n=Object.getPrototypeOf(n)}}function s(e,t){e.constructor&&e.constructor!==Object||e._manifestConstructorWarned||(e._manifestConstructorWarned=!0,console.warn("[ManifestProxy] "+t+": target has no own constructor set; subclass prototypes must set p.constructor for override detection."))}function e(e){var t=[],n=e.methods||{},i=(Object.keys(n).forEach(function(e){"number"!=typeof n[e].timeoutMs&&t.push("methods."+e+" has no timeoutMs"),void 0!==n[e].settle&&"all"!==n[e].settle&&"primary"!==n[e].settle&&t.push("methods."+e+" has an invalid settle"),"leastFullOrSpawn"===n[e].route&&n[e].replayOnSpawn&&t.push("methods."+e+' cannot be both route "leastFullOrSpawn" and replayOnSpawn')}),e.hostMethods||{}),o=(Object.keys(i).forEach(function(e){"number"!=typeof i[e].timeoutMs&&t.push("hostMethods."+e+" has no timeoutMs")}),e.eventShapes||{});if((e.events||[]).forEach(function(e){Object.prototype.hasOwnProperty.call(o,e)||t.push('events: "'+e+'" has no eventShapes entry')}),0<t.length)throw new Error("manifest: "+t.join("; "));return[]}function a(e){return e&&e.aliases||{}}function l(c,h,e){var o=(e=>{if("function"==typeof e)return e;var t=n[e||"first"];if("function"!=typeof t)throw new Error("[ManifestProxy] Unknown aggregator: "+e);return t})(h.aggregate),u=h.route||"all",d=(e=>{if("number"!=typeof e.timeoutMs)throw new Error("manifest: methods."+c+" has no timeoutMs");return e.timeoutMs})(h),f=h.settle||"all";return function(){function e(){"leastFullOrSpawn"===u&&"function"==typeof r._ensureRosterCapacity?r._ensureRosterCapacity().always(function(){t(g.select(u,n()))}):t(g.select(u,n()))}var r=this,s=Array.prototype.slice.call(arguments),a=(h.replayOnSpawn&&"function"==typeof r._recordReplayableCall&&r._recordReplayableCall(c,s),new p),l=function(e,t){var n;try{n=o(e,s,t)}catch(e){return void a.reject(e)}a.resolve(n)},t=function(i){var o,e,n;0!==i.length?(o=i.map(function(e){return r.workers.indexOf(e)}),e=i.map(function(e){return n=s,i=h,v(e=e,t=c)?e[t].apply(e,n):"function"==typeof e.rpc?e.rpc(t,n,{timeoutMs:i.timeoutMs}):e.call.apply(e,[t].concat(n));var t,n,i}),"primary"===f?(-1===(n=i.indexOf(r.workers[0]))&&(n=0),e.forEach(function(e,t){t!==n&&e.fail(function(e){"function"==typeof r.trigger&&r.trigger("pool:degraded",{poolIndex:o[t],method:c,error:e})})}),e[n].done(function(e){a.resolve(e)}).fail(function(e){a.reject(e)})):m(e,d).done(function(e){var t,n;"function"==typeof r.trigger&&e.failed.forEach(function(e){r.trigger("pool:degraded",{poolIndex:o[e.index],method:c,error:e.error})}),0!==e.fulfilled.length?(t=(n=e.fulfilled.slice().sort(function(e,t){return e.index-t.index})).map(function(e){return e.value}),n={hosts:n.map(function(e){return i[e.index]})},l(t,n)):a.reject(e.failed[0].error)})):l([],{hosts:[]})},n=function(){return"leastFullOrSpawn"===u?r.workers.filter(function(e){return!e._bootInFlight}):r.workers},i=0===r.workers.length&&"function"==typeof r._whenPrimaryReady?r._whenPrimaryReady():null;return i?i.done(e):e(),a.promise()}}var v=function(e,t){return!("function"!=typeof e[t]||!Object.prototype.hasOwnProperty.call(e,t)&&!(e.constructor&&e.constructor.prototype&&Object.prototype.hasOwnProperty.call(e.constructor.prototype,t)))},c=["applyManifest","getWorkerForToken","call","dispatch","initialize","disconnect","restore"],h=["call","initialize","disconnect","filter","login","pause","resume"];return{validateManifest:e,applyToCoordinator:function(t,n){var i,o,r;s(t,"applyToCoordinator"),e(n),Object.keys(n.methods).concat(Object.keys(a(n))).forEach(function(e){if(-1!==c.indexOf(e)&&!v(t,e))throw new Error('[ManifestProxy] Manifest method "'+e+'" collides with coordinator infrastructure.')}),Array.isArray(t._manifestGeneratedMethods)&&t._manifestGeneratedMethods.forEach(function(e){Object.prototype.hasOwnProperty.call(t,e)&&delete t[e]}),t._manifestGeneratedMethods=[],Object.keys(n.methods).forEach(function(e){v(t,e)||(t[e]=l(e,n.methods[e]),t._manifestGeneratedMethods.push(e))}),o=(i=t)._manifestGeneratedMethods,r=a(n),Object.keys(r).forEach(function(e){var t,n;v(i,e)||(n=r[e],i[e]=(t=n,function(){return this[t].apply(this,arguments)}),o.push(e))})},applyToClient:function(t,e){for(var n in s(t,"applyToClient"),e.methods)if(Object.prototype.hasOwnProperty.call(e.methods,n)&&0<=h.indexOf(n)&&!r(t,n))throw new Error('ManifestProxy.applyToClient: manifest method "'+n+'" collides with a PlayerPoolClient infrastructure method.');var i,o;Object.keys(e.methods).forEach(function(e){r(t,e)||(t[e]=function(){return this.manager[e].apply(this.manager,arguments)})}),i=t,o=a(e),Object.keys(o).forEach(function(e){v(i,e)||(i[e]=function(){return this.manager[e].apply(this.manager,arguments)})})}}}),define("CatLab/Webremote/PlayerPool/Managers/PoolCoordinator",["CatLab/Webremote/PlayerPool/Managers/WorkerManager","CatLab/Webremote/PlayerPool/Protocol/ManifestProxy","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/PlayerPool/Protocol/whenAllSettled"],function(i,t,c,o){function e(e){i.call(this,e=e||{}),this.tokenRegistry={},this.maxPlayersPerPool=e.maxPlayersPerPool||100,this.spawnAheadRatio=e.spawnAheadRatio||.9,this._started=!1,this._spawnInFlight=!1,this._spawnPromise=null,this._spawnRetried=!1,this._capacityExhausted=!1,this._portalActive=!1,this._totalActualPlayersLength=0,this._publicConnectInfo=null,this._replayLog=[],this._eventBarriers={},this._poolSequence=0,this.applyManifest(this._manifest)}var n=e.prototype=new i;return n.constructor=e,n.applyManifest=function(e){this._manifest=e,t.applyToCoordinator(this,e)},n.call=function(){var e=Array.prototype.slice.call(arguments),t=e.shift();if(this._isManifestName(t)&&"function"==typeof this[t])return this[t].apply(this,e);throw new Error('PoolCoordinator.call: "'+t+'" is not in the manifest')},n._isManifestName=function(e){var t=this._manifest;if(t){if(t.methods&&Object.prototype.hasOwnProperty.call(t.methods,e))return!0;if(t.aliases&&Object.prototype.hasOwnProperty.call(t.aliases,e))return!0}return!(!this._manifestGeneratedMethods||-1===this._manifestGeneratedMethods.indexOf(e))},n.disconnect=function(){var e=new c,t=this,n=this.workers,n=(this.workers=[],this.tokenRegistry={},this._settlePrimaryBoot(),n.map(function(e){return e.disconnect()}));return o(n,0).done(function(){t.workers=[],t.tokenRegistry={},e.resolve()}),e.promise()},n._bindWorkerEvents=function(t){i.prototype._bindWorkerEvents.call(this,t),"number"!=typeof t.poolNumber&&(t.poolNumber=++this._poolSequence);var n=this;t.on("worker:error",function(e){n._handleWorkerFailure(t,e)}),t.on("change:connections",function(){n._checkCapacity()}),t.on("portal:active:count",function(e){t._portalActiveCount=e||0,n._syncPortalCounts()}),t.on("portal:users",function(e){t._portalUsers=e||[],n._syncPortalUsers()}),"function"==typeof this._registerSeatPool&&this._registerSeatPool(t)},n._bindBarrierEvent=function(t,n){var i,o=this._manifest&&this._manifest.barrierEvents&&this._manifest.barrierEvents[n];return"function"==typeof o&&(i=this,t.on(n,function(e){i._recordBarrierEvent(n,String(o(e)),t,[e])}),!0)},n.getWorkerForToken=function(e){return this.tokenRegistry[e]||null},n._onWorkerConnectInfo=function(e,t){t&&t.connectToken&&(e._lastConnectInfo=t,(this.tokenRegistry[t.connectToken]=e)===this.workers[this.workers.length-1])&&this._setPublicConnectInfo(t)},n._setPublicConnectInfo=function(e){this._publicConnectInfo=e,this.trigger("connectInfo:change",e);var t=this._getPrimaryWorker();t&&"function"==typeof t.setPublicConnectInfo&&t.setPublicConnectInfo(e)},n._updateTotalLength=function(){var t=0,n=0;this.workers.forEach(function(e){t+=e.length||0,n+=e.actualPlayersLength||0}),this._totalLength=t,this._totalActualPlayersLength=n,this._checkCapacity()},n._handleWorkerFailure=function(t,n){var e,i;this._started&&-1!==(e=this.workers.indexOf(t))&&!t._bootInFlight&&("function"==typeof t.ping?t._probeInFlight||(t._probeInFlight=!0,i=this,t.ping().done(function(){t._probeInFlight=!1;var e=i.workers.indexOf(t);-1!==e&&console.log("[PoolCoordinator] Pool "+e+" survived worker error")}).fail(function(){t._probeInFlight=!1;var e=i.workers.indexOf(t);-1!==e&&i._killWorker(t,e,n)})):this._killWorker(t,e,n))},n._killWorker=function(t,e,n){var i=t.length||0,o=e===this.workers.length-1,r=(this.workers.splice(e,1),this);Object.keys(this.tokenRegistry).forEach(function(e){r.tokenRegistry[e]===t&&delete r.tokenRegistry[e]}),"function"==typeof t._failPendingDispatches&&t._failPendingDispatches(n);try{"function"==typeof t.terminateHost&&t.terminateHost()}catch(t){}console.error("[PoolCoordinator] Pool "+e+" lost ("+i+" players).",n),this.trigger("pool:lost",{poolIndex:e,playerCount:i,wasPrimary:0===e}),0===this.workers.length&&console.error("[PoolCoordinator] All pools lost."),o&&0<this.workers.length&&(n=this.workers[this.workers.length-1])._lastConnectInfo&&this._setPublicConnectInfo(n._lastConnectInfo);var s=this;Object.keys(this._eventBarriers).forEach(function(e){s._checkEventBarrier(e)}),this._updateTotalLength()},n._isPrimaryBridged=function(){var e=this.workers[0];return!!e&&"function"==typeof e.getHostProvider&&"bridged"===e.getHostProvider()},n._checkCapacity=function(){var e,t;this._spawnInFlight||this._capacityExhausted||this._isPrimaryBridged()||(e=Math.max(1,Math.floor(this.maxPlayersPerPool*this.spawnAheadRatio)),(t=this.workers[this.workers.length-1])&&("number"==typeof t.connectedDevices?t.connectedDevices:t.length||0)>=e&&this._spawnNewWorker())},n._spawnNewWorker=function(){var i,o,r;return this._spawnInFlight&&this._spawnPromise?this._spawnPromise:(i=new c,this._initOptions?(console.log("[PoolCoordinator] Spawning new pool ("+this.workers.length+" active)."),(o=this)._spawnInFlight=!0,this._spawnPromise=i.promise(),(r=function(){var n=o._createWorkerManager();n._bootInFlight=!0,n.initialize(o._buildSecondaryInitOptions()).done(function(){n._bootInFlight=!1,o._spawnInFlight=!1,o._spawnPromise=null,o._spawnRetried=!1,o._replayToWorker(n),o._syncPortalCounts(),o._syncPortalUsers(),o._afterSpawn(n),o.trigger("pool:spawned",{poolIndex:o.workers.indexOf(n)}),i.resolve(n)}).fail(function(e){n._bootInFlight=!1;var t=o.workers.indexOf(n);return-1!==t&&o.workers.splice(t,1),n._disconnected?(o._spawnInFlight=!1,o._spawnPromise=null,void i.reject(e)):o._spawnRetried?(console.error("[PoolCoordinator] Pool spawning failed twice; capacity exhausted.",e),o._spawnInFlight=!1,o._spawnPromise=null,o._capacityExhausted=!0,o.trigger("pool:capacity:exhausted",{pools:o.workers.length}),void i.reject(e)):(console.warn("[PoolCoordinator] New pool failed to initialize, retrying once.",e),o._spawnRetried=!0,void r())})})()):(console.error("[PoolCoordinator] Cannot spawn new pool: no init options."),i.reject(new Error("Cannot spawn new pool: no init options."))),i.promise())},n._ensureRosterCapacity=function(){var e=new c;if(this._capacityExhausted||0===this.workers.length||this._isPrimaryBridged())e.resolve();else{for(var t=null,n=0;n<this.workers.length;n++){var i=this.workers[n];i._bootInFlight||(null===t||(i.length||0)<(t.length||0))&&(t=i)}null!==t&&(t.length||0)<this.maxPlayersPerPool?e.resolve():this._spawnNewWorker().always(function(){e.resolve()})}return e.promise()},n._recordBarrierEvent=function(e,t,n,i){var t=e+"\0"+t,o=this._eventBarriers[t];(o=o||(this._eventBarriers[t]={event:e,expected:this.workers.filter(function(e){return 0<(e.length||0)}),fired:[]})).args=i,-1===o.fired.indexOf(n)&&o.fired.push(n),this._checkEventBarrier(t)},n._checkEventBarrier=function(e){var t,n=this._eventBarriers[e];!n||this._manifest&&this._manifest.barrierRequiresPlayers&&-1!==this._manifest.barrierRequiresPlayers.indexOf(n.event)&&!this.workers.some(function(e){return 0<(e.length||0)})||(t=this,0<n.expected.filter(function(e){return-1!==t.workers.indexOf(e)&&-1===n.fired.indexOf(e)}).length)||(Object.keys(this._eventBarriers).forEach(function(e){t._eventBarriers[e].event===n.event&&delete t._eventBarriers[e]}),this.trigger.apply(this,[n.event].concat(n.args)))},n.getSeatAdapter=function(){var i,o;return this._seatAdapter||((i=this)._seatAddedCbs=[],this._seatUsageCbs=[],this._seatRemovedCbs=[],this._seatTracked={},o=function(e){return void 0===e.__seatId&&(e.__seatId=e.poolNumber),e.__seatId},this._registerSeatPool=function(t){var n;"number"==typeof t.poolNumber&&(n=o(t),i._seatTracked[n]!==t)&&(i._seatTracked[n]=t,i._seatAddedCbs.forEach(function(e){e(n,t)}),t.__seatUsageHandler=function(){i._seatUsageCbs.forEach(function(e){e(t.__seatId,t.actualPlayersLength)})},t.on("change:length",t.__seatUsageHandler))},this._reconcileSeatPools=function(){Object.keys(i._seatTracked).forEach(function(e){var t,n=i._seatTracked[e];-1===i.workers.indexOf(n)&&(t=parseInt(e,10),delete i._seatTracked[e],"function"==typeof n.off&&n.__seatUsageHandler&&n.off("change:length",n.__seatUsageHandler),i._seatRemovedCbs.forEach(function(e){e(t)}))})},this.on("pool:lost",this._reconcileSeatPools),this._seatAdapter={eachPool:function(t){i.workers.forEach(function(e){i._registerSeatPool(e),t(o(e),e)})},onPoolAdded:function(e){i._seatAddedCbs.push(e)},onPoolRemoved:function(e){i._seatRemovedCbs.push(e)},onPoolUsage:function(e){i._seatUsageCbs.push(e)},pushLease:function(e,t){e.call("setLeasedSeats",t)}}),this._seatAdapter},n._recordReplayableCall=function(e,t){for(var n=0;n<this._replayLog.length;n++)if(this._replayLog[n].method===e)return void(this._replayLog[n].args=t);this._replayLog.push({method:e,args:t})},n._replayToWorker=function(n){this._replayLog.forEach(function(t){var e;(e="function"==typeof n[t.method]?n[t.method].apply(n,t.args):n.call.apply(n,[t.method].concat(t.args)))&&"function"==typeof e.fail&&e.fail(function(e){console.error('[PoolCoordinator] Replay of "'+t.method+'" onto spawned pool failed:',e)})})},n._afterSpawn=function(e){},n._buildSecondaryInitOptions=function(){var e,t={},n=this._initOptions||{};for(e in n)n.hasOwnProperty(e)&&(t[e]=n[e]);return t.localInput=!1,t.keyboard=!1,t},n.getConnectScreen=function(t){var n=this,i="function"==typeof t.start?t.start:function(){},e="function"==typeof t.back?t.back:function(){},o=(this._portalActive=!0,this._suspendNavigationForPortal(),this.workers.forEach(function(e){e._portalActiveCount=0,e._portalUsers=[]}),t.start=function(e){n._onPortalEnd("start",function(){i(e)})},t.back=function(){n._onPortalEnd("back",function(){e()})},this._getPrimaryWorker()),r=o.getConnectScreen(t);return this.workers.forEach(function(e){e!==o&&"function"==typeof e.openPortal&&e.openPortal(t)}),this._recordReplayableCall("openPortal",[t]),r},n._onPortalEnd=function(t,e){this._portalActive&&(this._portalActive=!1,this._removeReplayableCall("openPortal"),this.workers.forEach(function(e){e._portalActiveCount=0,e._portalUsers=[],"function"==typeof e.finalizePortal&&e.finalizePortal(t)}),e())},n._syncPortalCounts=function(){var t;this._portalActive&&(t=0,this.workers.forEach(function(e){t+=e._portalActiveCount||0}),this.workers.forEach(function(e){"function"==typeof e.call&&e.call("setExternalActivePlayers",t-(e._portalActiveCount||0))}))},n._syncPortalUsers=function(){this._portalActive&&this.workers.forEach(function(t){var n;"function"==typeof t.call&&(n=[],this.workers.forEach(function(e){e!==t&&e._portalUsers&&(n=n.concat(e._portalUsers))}),t.call("setExternalUsers",n))}.bind(this))},n._removeReplayableCall=function(e){for(var t=0;t<this._replayLog.length;t++)if(this._replayLog[t].method===e)return void this._replayLog.splice(t,1)},n.clearConnectScreen=function(t){return this.workers.map(function(e){return e.clearConnectScreen(t)})[0]},n.applyConfigOverrides=function(t){this.workers.forEach(function(e){e.applyConfigOverrides(t)}),this._recordReplayableCall("applyConfigOverrides",[t]);var e=new c;return e.resolve(),e.promise()},n._adoptRestoredPoolNumbers=function(e){var t=this;e.forEach(function(e){e&&"number"==typeof e.poolNumber&&(t._poolSequence=Math.max(t._poolSequence,e.poolNumber))})},n._dropNonPrimaryWorkers=function(){var e;this.workers.length<=1||(e=this.workers.slice(1),this.workers=this.workers.slice(0,1),e.forEach(function(e){"function"==typeof e.disconnect&&e.disconnect()}),"function"==typeof this._reconcileSeatPools&&this._reconcileSeatPools())},n.restore=function(e,o){if(this._adoptRestoredPoolNumbers(Array.isArray(e)?e:[e]),this._dropNonPrimaryWorkers(),Array.isArray(e)&&1<e.length){var t=new c,r=this,n=[],i=this._getPrimaryWorker();e[0]&&"number"==typeof e[0].poolNumber&&(i.poolNumber=e[0].poolNumber),n.push(i.restore(e[0],o));for(var s=1;s<e.length;s++){var a=this._createWorkerManager();a._bootInFlight=!0,e[s]&&"number"==typeof e[s].poolNumber&&(a.poolNumber=e[s].poolNumber),n.push(((e,t)=>{var n=new c,i=(e.initialize(r._buildSecondaryInitOptions()).done(function(){e.restore(t,o).done(function(){n.resolve()}).fail(function(e){n.reject(e)})}).fail(function(e){n.reject(e)}),n.promise());return i.done(function(){e._bootInFlight=!1}),i.fail(function(){e._bootInFlight=!1}),i})(a,e[s]))}return c.when.apply(c,n).done(function(){t.resolve()}).fail(function(e){console.error("[PoolCoordinator] Multi-pool restore failed:",e),t.reject(e)}),t.promise()}var i=Array.isArray(e)?e[0]:e,l=this._getPrimaryWorker();return i&&"number"==typeof i.poolNumber&&(l.poolNumber=i.poolNumber),l.restore(i,o)},Object.defineProperty(n,"actualPlayersLength",{get:function(){return this._totalActualPlayersLength}}),e}),define("CatLab/Webremote/PlayerPool/PlayerPoolClient",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e,t){this.initializeEventable(),t=t||{},this.manager=e,this._config=t.config||null,this.connectToken="xxxxxx",this.connectTokenForDisplay="xxxxxx",this.connectUrl="...",this.server="...",this.contentProxy=null,this.gameId=null,this.accessToken=null,this.labels=[],this.keyboardPlayer=!1,this._cachedShouldShowAvatars=!1,this._cachedActivePlayerCount=0,this._cachedIsDelayed=!1,this.manager.on("connectInfo:change",function(e){this.connectToken=e.connectToken,this.connectTokenForDisplay=e.connectTokenForDisplay,this.connectUrl=e.connectUrl,this.server=e.server,this.contentProxy=void 0===e.contentProxy?null:e.contentProxy,this.gameId=void 0===e.gameId?null:e.gameId,this.accessToken=void 0===e.accessToken?null:e.accessToken}.bind(this));var e=i.concat(t.events||[]),n={};e.forEach(function(t){Object.prototype.hasOwnProperty.call(n,t)||(n[t]=!0,this.manager.on(t,function(){var e=Array.prototype.slice.call(arguments);e.unshift(t),this.trigger.apply(this,e)}.bind(this)))}.bind(this)),this.manager.on("change:length",function(){var e=this.manager.shouldShowAvatars();e&&"function"==typeof e.done?e.done(function(e){this._cachedShouldShowAvatars=!!e}.bind(this)):"boolean"==typeof e&&(this._cachedShouldShowAvatars=e),this.countActivePlayers()}.bind(this))}var i=["user:join","change:length","connectInfo:change","pool:degraded","pool:lost","pool:spawned","pool:capacity:exhausted"],e=t.prototype=new e;return e.call=function(){return this.manager.call.apply(this.manager,arguments)},e.initialize=function(e){return this.manager.initialize(e)},e.showIndexScreen=function(){return this.manager.call.apply(this.manager,["showIndexScreen"].concat(Array.prototype.slice.call(arguments)))},e.enableNavigation=function(e,t){return this.manager.enableNavigation(e,t)},e.getConnectScreen=function(e){return this.manager.getConnectScreen(e)},e.getAuthenticationScreen=function(e){return this.manager.getAuthenticationScreen(e)},e.login=function(e){return this.manager.login(e)},e.clearConnectScreen=function(e){return this.manager.clearConnectScreen(e)},e.activateKeyboardUser=function(e){return this.manager.activateKeyboardUser(e)},e.setKeyboardUser=function(e){return this.manager.setKeyboardUser(e)},e.createDummyUser=function(e,t,n){return this.manager.createDummyUser(e,t,n)},e.getAccessTokens=function(){return this.manager.getAccessTokens()},e.applyConfigOverrides=function(e){return this._config&&"function"==typeof this._config.applyOverrides&&this._config.applyOverrides(e),this.manager.applyConfigOverrides(e)},e.pause=function(){return this.manager.call.apply(this.manager,["pause"].concat(Array.prototype.slice.call(arguments)))},e.resume=function(){return this.manager.call.apply(this.manager,["resume"].concat(Array.prototype.slice.call(arguments)))},e.hasKeyboardPlayer=function(){return this.keyboardPlayer},e.startGame=function(){return this.manager.call.apply(this.manager,["startGame"].concat(Array.prototype.slice.call(arguments)))},e.getConnectToken=function(){return this.connectToken},e.getConnectTokenForDisplay=function(){return this.connectTokenForDisplay},e.getConnectURL=function(){return this.connectUrl},e.getServer=function(){return this.server},e.getContentProxy=function(){return this.contentProxy},e.getRelayGameId=function(){return this.gameId},e.getRelayAccessToken=function(){return this.accessToken},e.countActivePlayers=function(){var e=this.manager.countActivePlayers();return e&&"function"==typeof e.done?e.done(function(e){this._cachedActivePlayerCount=e}.bind(this)):"number"==typeof e&&(this._cachedActivePlayerCount=e),this._cachedActivePlayerCount},e.shouldShowAvatars=function(){var e=this.manager.shouldShowAvatars();return e&&"function"==typeof e.done?e.done(function(e){this._cachedShouldShowAvatars=!!e}.bind(this)):"boolean"==typeof e&&(this._cachedShouldShowAvatars=e),this._cachedShouldShowAvatars},e.isDelayed=function(e){e=this.manager.isDelayed(e);return e&&"function"==typeof e.done?e.done(function(e){this._cachedIsDelayed=!!e}.bind(this)):"boolean"==typeof e&&(this._cachedIsDelayed=e),this._cachedIsDelayed},e.disconnect=function(){return this.manager.disconnect()},Object.defineProperty(e,"length",{get:function(){return this.manager.length}}),Object.defineProperty(e,"actualPlayersLength",{get:function(){return this.manager.actualPlayersLength}}),e.filter=function(o){return"undefined"==typeof Proxy?(console.error("This browser is too old to do player-pool filtering."),this):new Proxy(this,{get:function(n,e,t){var i;return"function"!=typeof n[e]?n[e]:(i=n[e],function(){var e=Array.prototype.slice.call(arguments),t={};return t.__playerFilters=o,e.push(t),i.apply(n,e)})}})},t}),define("CatLab/Webremote/Transport/LoopbackPort",[],function(){function i(e){this.kind="loopback",this._queue=e,this._peer=null,this._handlers=[],this._errorHandlers=[],this._closed=!1}var e=i.prototype;function o(){this._pending=[],this._scheduled=!1}return e.post=function(e){if(this._closed)throw new Error("LoopbackPort: post after close");e=e;var t="function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e,function(e,t){if("function"==typeof t)throw new Error('LoopbackPort: value could not be cloned (function at "'+e+'")');return t})),n=this._peer;this._queue.enqueue(function(){n._closed||n._deliver(t)})},e._deliver=function(t){for(var e=this._handlers.slice(),n=0;n<e.length;n++)try{e[n](t)}catch(t){0===this._errorHandlers.length?console.error("[LoopbackPort] message handler threw:",t):this._errorHandlers.slice().forEach(function(e){e(t)})}},e.onMessage=function(t){var n=this;return this._handlers.push(t),function(){var e=n._handlers.indexOf(t);-1!==e&&n._handlers.splice(e,1)}},e.onError=function(t){var n=this;return this._errorHandlers.push(t),function(){var e=n._errorHandlers.indexOf(t);-1!==e&&n._errorHandlers.splice(e,1)}},e.close=function(){this._closed=!0,this._handlers=[],this._errorHandlers=[]},e.isClosed=function(){return this._closed},o.prototype.enqueue=function(e){var t;this._pending.push(e),this._scheduled||(this._scheduled=!0,t=this,Promise.resolve().then(function(){t._drain()}))},o.prototype._drain=function(){this._scheduled=!1;var e=this._pending;this._pending=[];for(var t=0;t<e.length;t++)e[t]()},o.prototype.flush=function(){var n=this;return new Promise(function(t){!function e(){0!==n._pending.length||n._scheduled?Promise.resolve().then(e):t()}()})},i.pair=function(){var e=new o,t=new i(e),n=new i(e);return{a:(t._peer=n)._peer=t,b:n,flush:function(){return e.flush()}}},i}),define("CatLab/Webremote/Transport/Hosts/LoopbackHost",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Transport/LoopbackPort","CatLab/Webremote/Transport/Errors"],function(e,n,i,o){function t(e){if(this.initializeEventable(),this.kind="loopback",this._boot=e&&e.boot,this._pair=null,this._started=!1,"function"!=typeof this._boot)throw new Error("LoopbackHost: options.boot(port) is required")}e=t.prototype=new e;return e.start=function(){var t=new n;if(this._started)t.reject(new o.PoolBootError(this.kind,"host already started"));else{this._started=!0,this._pair=i.pair();try{this._boot(this._pair.b)}catch(e){return this._pair.a.close(),this._pair.b.close(),t.reject(e),t.promise()}t.resolve(this._pair.a)}return t.promise()},e.flush=function(){return this._pair?this._pair.flush():Promise.resolve()},e.terminate=function(){this._pair&&(this._pair.a.close(),this._pair.b.close())},t}),define("CatLab/Webremote/FrontController",["CatLab/Webremote/Config","CatLab/Webremote/Polyfills","CatLab/Webremote/Tools/Tracker","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Controllers/Webremote","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Images","CatLab/Webremote/Models/Users/DummyUser","CatLab/Webremote/Providers/SocketIO","CatLab/Webremote/Providers/Airconsole","CatLab/Webremote/Providers/Dummy","CatLab/Webremote/Providers/BridgedProvider","CatLab/Webremote/ViewFactory/ViewFactory","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/PlayerPool/PlayerPool","CatLab/Webremote/PlayerPool/GameLogic","CatLab/Webremote/PlayerPool/PlayerPoolWorker","CatLab/Webremote/PlayerPool/SeatAuthority","CatLab/Webremote/PlayerPool/SeatAuthorityBinder","CatLab/Webremote/PlayerPool/RandomPlayerList","CatLab/Webremote/PlayerPool/Player","CatLab/Webremote/PlayerPool/DeviceConnection","CatLab/Webremote/Collections/PlayerCollection","CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/PlayerPool/Managers/WebworkerManager","CatLab/Webremote/PlayerPool/Managers/WorkerManager","CatLab/Webremote/PlayerPool/Managers/PoolCoordinator","CatLab/Webremote/PlayerPool/PlayerPoolClient","CatLab/Webremote/PlayerPool/EngineManifest","CatLab/Webremote/PlayerPool/Protocol/Aggregators","CatLab/Webremote/PlayerPool/Protocol/Router","CatLab/Webremote/PlayerPool/Protocol/ManifestProxy","CatLab/Webremote/PlayerPool/Protocol/whenAllSettled","CatLab/Webremote/LocalInput/DeviceObject","CatLab/Webremote/LocalInput/DeviceChannel","CatLab/Webremote/LocalInput/KeyboardInput","CatLab/Webremote/LocalInput/CordovaInput","CatLab/Webremote/LocalInput/AndroidRemoteInput","CatLab/Webremote/LocalInput/GamepadInput","CatLab/Webremote/LocalInput/AppActions","CatLab/Webremote/LocalInput/ProviderHost","CatLab/Webremote/PlayerPool/LocalDevices/LocalDeviceUser","CatLab/Webremote/PlayerPool/LocalDevices/DeviceRegistry","CatLab/Webremote/PlayerPool/LocalDevices/Profiles/index","CatLab/Webremote/Transport/Codec","CatLab/Webremote/Transport/Errors","CatLab/Webremote/Transport/WorkerPort","CatLab/Webremote/Transport/LoopbackPort","CatLab/Webremote/Transport/Hosts/DedicatedWorkerHost","CatLab/Webremote/Transport/Hosts/IframeWorkerHost","CatLab/Webremote/Transport/Hosts/LoopbackHost"],function(t,O,e,n,i,o,r,s,a,l,c,h,u,d,f,p,g,m,v,b,y,w,_,C,k,P,L,T,S,E,I,W,A,x,M,U,D,V,N,z,F,B,R,j,H,q,G,K,J,X,Q,Y,$,Z){return{Config:function(e){t.set(e)},Tracker:e,Tools:n,Webremote:new i,Webcontrol:new r,OAuth2:o,Controllers:{Webcontrol:r,Webremote:i},Models:{User:l},Controls:{Dummy:l},Providers:{SocketIO:c,Airconsole:h,Dummy:u,Bridged:d},Transport:{Codec:K,Errors:J,WorkerPort:X,LoopbackPort:Q,Hosts:{DedicatedWorkerHost:Y,IframeWorkerHost:$,LoopbackHost:Z}},ViewFactories:{HtmlViewFactory:f,CreatejsViewFactory:p},Smileys:s,Images:new a,NavigateableProxy:g,LocalInput:{DeviceObject:D,DeviceChannel:V,KeyboardInput:N,CordovaInput:z,AndroidRemoteInput:F,GamepadInput:B,AppActions:R,ProviderHost:j},LocalDevices:{LocalDeviceUser:H,DeviceRegistry:q,Profiles:G},PlayerPool:{PlayerPool:m,GameLogic:v,PlayerPoolWorker:b,bootWorker:b.bootWorker,SeatAuthority:y,SeatAuthorityBinder:w,RandomPlayerList:_,Player:C,DeviceConnection:k,Manager:L,WebworkerManager:T,WorkerManager:S,PoolCoordinator:E,PlayerPoolClient:I,EngineManifest:W,Protocol:{Aggregators:A,Router:x,ManifestProxy:M,whenAllSettled:U}},Collections:{Players:P}}}),define("catlabremote",["CatLab/Webremote/FrontController"],function(e){return e}),define("CatLab/EaselHacks/AlphaMaskFilter",[],function(e){function t(e){var n=this;this.createjs=e,Object.defineProperty(e.DisplayObject.prototype,"mask",{get:function(){return this.forceMask},set:function(e){var t;e?(this.originalMask=e,t=n.getFilterFromMask(e,this),this.filters=[t],this.cache(0,0,500,500)):null!==e&&(this.filters=null,this.cache(0,0,500,500))}}),e.DisplayObject.prototype.setMask=function(e){this.forceMask=e}}return t.prototype.getFilterFromMask=function(e,t){var n=this.createjs,i=e.graphics.getInstructions(),o=new n.Graphics;o.beginFill("#000000"),o.beginStroke("#000000");for(var r=0;r<i.length;r++)o.append(i[r]);e.graphics=o;var s=new n.Container,e=(s.addChild(e),s.scaleX=1/t.scaleX,s.scaleY=1/t.scaleY,s.y=-t.y,s.x=-t.x,new n.Container);return e.addChild(s),e.cache(0,0,1e3,1e3),new n.AlphaMaskFilter(e.cacheCanvas)},t}),define("CatLab/EaselHacks/FrontController",["CatLab/EaselHacks/AlphaMaskFilter"],function(e){return{AlphaMaskFilter:e}}),define("easelhacks",["CatLab/EaselHacks/FrontController"],function(e){return e}),define("CatLab/Webremote/Hacks",["easelhacks","easeljs"],function(e,t){new e.AlphaMaskFilter(t)});