catlab-remote-client 2.2.4 → 2.2.5
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
|
-
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].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]=new Deferred,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)},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),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={"&":"&","<":"<",">":">",'"':""","'":"'"},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/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/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/Storage",["CatLab/Webremote/Tools/Cookies"],function(e){var t={_syncKeys:["users","currentuser"],syncToBridge:function(e){-1!==this._syncKeys.indexOf(e)&&"undefined"!=typeof window&&window.__catlabStorageBridge&&"function"==typeof window.__catlabStorageBridge&&void 0!==window.localStorage&&window.__catlabStorageBridge({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/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/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/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}),(()=>{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(b[e])return b[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 b[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 b=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/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/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(){return this.nickname||(this.getData().username?this.getData().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/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/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 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(t){this.reattachClick(t.control(this.controls.navigation[0]),this.previous),this.reattachClick(t.control(this.controls.navigation[1]),this.next),this.reattachClick(t.control(this.controls.manipulation[0]),this.down),this.reattachClick(t.control(this.controls.manipulation[1]),this.up),this.controls.toggle.forEach(function(e){void 0===this.keyInputCallbacks[e]&&(this.keyInputCallbacks[e]=function(){this.keyInput(e)}),this.reattachClick(t.control(e),this.keyInputCallbacks[e].bind(this))}.bind(this)),this.controls.back.forEach(function(e){this.reattachClick(t.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){this.messageBus.toView(this.prefix+"nav:keyInput",{button:e})},t.previous=function(){this.messageBus.toView(this.prefix+"nav:previous")},t.next=function(){this.messageBus.toView(this.prefix+"nav:next")},t.up=function(){this.keyInput("up")},t.down=function(){this.keyInput("down")},t.back=function(){this.messageBus.toView(this.prefix+"nav:back")},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),!0;case"nav:back":return n.triggerBack(),!0}return!1}},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.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/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/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(D){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,b,m,v=!e.customViews,y=[],w=!1,C=!1,k=null,V=this;function _(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(E(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(),I(),x()}),o.control("start-game").click(function(){var e;w?x():y.length<r?z(r+" players are required to start the game. Please gather more friends."):y.length>s?z("This game can have only "+s+" players."):(e=n,x(),w=!0,(f=new Date).setTime((new Date).getTime()+e),u.style.display="",d=setInterval(O,100))}),o.control("down").click(function(){P(o)}),o.control("right").click(function(){P(o)}),o.control("left").click(function(){S(o)}),o.control("up").click(function(){S(o)}),o.control("a").click(function(){var e,t,i,n;e=o,C&&T(e)?(t=m.querySelector(".available-accounts li.selected"))&&(t=WebcontrolOAuthClient.getFromToken(t.getAttribute("data-accessToken")))&&(n=t.access_token,k.setUserData(n,t.user),A()):(w&&x(),C||(i=e,Webcontrol.getOAuthClient(function(n){n.onInit(function(){W(n)}),WebcontrolAccessKeyLibrary.init(function(){C=!0,k=i,b.style.display="",m.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(){W(n)})}),m.querySelector(".link-new-account"));t.innerHTML="",t.appendChild(e)}),W(n)})))}),o.control("b").click(function(){C&&T(o)&&(k.setUserData(!1),A())}),U(),I()}function S(e){if(C&&T(e)){for(var e=m.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 P(e){if(C&&T(e)){for(var e=m.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 T(e){return k&&e.getId()==k.getId()}function A(){b.style.display="none",m.style.display="none",C=!1,k=null}function W(e){var t=m.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 I(){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 E(e){for(var t=0;t<y.length;t++)if(y[t].getId()==e.getId())return 1}function U(){var e=Webcontrol.getUsers();a.innerHTML="";for(var t=[],n=0;n<e.length;n++)E(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),U()}function O(){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"),x(),i(y))}function x(){w=!1,d&&(z("Countdown stopped!"),u.style.display="none",clearInterval(d),d=null)}function z(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=D.getSocketURL()+"/webremote/themes/"+e.theme+"/"+e.theme+".css",Webcontrol._loadCSS(e),Webcontrol._loadCSS(D.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>',v&&Webcontrol.loadViews(D.getSocketURL(!0)+"/webremote/views/default.xml"),o.innerHTML="<h1>Player lobby</h1>",b=document.createElement("div"),m=_('<div><h2>Select account</h2><div class="information"><p>'+V.loginInformation+'</p></div><ul class="available-accounts"></ul><p class="link-new-account"></p></div>'),b.className="accounts-overlay",m.className="accounts",b.style.display="none",m.style.display="none",o.appendChild(b),o.appendChild(m),_('<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),_('<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=_('<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=_('<p class="buttoninstructions join-game">Press <span class="labels"></span> to join the game.</p>'),h=_('<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",U),U(),M(),I()})}}),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/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/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,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")+'" 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/Models/Users/GamepadUser",["CatLab/Webremote/Models/Users/ControlUser"],function(e){function t(e){var t=e.id||"1";this.initialize({id:"gamepad_"+t}),this.keys=this.getDefaultKeys(e),this.clearControls()}e=t.prototype=new e;return e.getType=function(){return"gamepad"},e.getIcon=function(){return"fa fa-gamepad"},e.emit=function(){return!1},e.isLocalAuthentication=function(){return!1},e.controlFromKey=function(e){return this.control(this.keys[e].id)},e.hasDisplay=function(){return!1},e.hasKeyboardInput=function(){return!1},e.hasTouchInput=function(){return!1},e.getPortalControls=function(){return{start:"start",back:"back",toggleActive:"x",authenticate:"y",left:"left",right:"right"}},e.getDefaultKeys=function(e){var t="control-icons/gamepad/$SIZE/",n="gamepad-",i="🎮",o={a:"🅰️",b:"🅱️",x:"❎",y:"❎",up:"⬆️",down:"⬇️",left:"⬅️",right:"➡️",l1:"🤜",r1:"🤛"};return void 0===e.id||-1===e.id.toLowerCase().indexOf("sony")&&-1===e.id.toLowerCase().indexOf("054c")||(t="control-icons/ps-controller/$SIZE/",n="ps-controller-",i="🕹",o={a:"❎",b:"⭕",x:"🟥",y:"🔺",up:"⬆️",down:"⬇️",left:"⬅️",right:"➡️",l1:"🤜",r1:"🤛"}),{DPAD_UP:{id:"up",label:"↑",key:"DPAD_UP",emoji:i+""+o.up},DPAD_DOWN:{id:"down",label:"↓",key:"DPAD_DOWN",emoji:i+""+o.down},DPAD_RIGHT:{id:"right",label:"→",key:"DPAD_RIGHT",emoji:i+""+o.right},DPAD_LEFT:{id:"left",label:"←",key:"DPAD_LEFT",emoji:i+""+o.left},FACE_1:{id:"a",label:"A",key:"FACE_1",image:t+n+"a.gif",emoji:i+""+o.a},FACE_2:{id:"b",label:"B",key:"FACE_2",image:t+n+"b.gif",emoji:i+""+o.b},FACE_3:{id:"x",label:"X",key:"FACE_3",image:t+n+"x.gif",emoji:i+""+o.x},FACE_4:{id:"y",label:"Y",key:"FACE_4",image:t+n+"y.gif",emoji:i+""+o.y},SELECT_BACK:{id:"back",label:"SELECT",key:"SELECT_BACK"},START_FORWARD:{id:"start",label:"START",key:"START_FORWARD"},L1:{id:"l1",label:"L1",key:"L1",emoji:i+""+o.l1},R1:{id:"r1",label:"R1",key:"R1",emoji:i+""+o.r1}}},e.setStaticLabels=function(){for(var e in this.keys)this.keys.hasOwnProperty(e)&&this.control(this.keys[e].id).setStaticLabel(this.keys[e].label,"gamepad",this.keys[e].image,this.keys[e].emoji)},t}),define("CatLab/Webremote/Gamepads/GamepadAPI",["CatLab/Webremote/Models/Users/GamepadUser"],function(i){function e(){this.gamepads={},this.initialized=!1,this.Webcontrol=null,this._forwarding=!1,this._forwardPollInterval=null,this._pollInterval=null}var c={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"},t=e.prototype;return t._gamepadApiAvailable=function(){return"undefined"!=typeof navigator&&("function"==typeof navigator.getGamepads||void 0!==navigator.webkitGetGamepads)},t._getGamepads=function(){return"function"==typeof navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[]},t._detectGamepads=function(i){var o,r=this;"undefined"!=typeof window&&"ongamepadconnected"in window?(window.addEventListener("gamepadconnected",function(e){i(e.gamepad)}),window.addEventListener("gamepaddisconnected",function(e){r.onDisconnect(e.gamepad)})):o=setInterval(function(){for(var e=r._getGamepads(),t=!1,n=0;n<e.length;n++)e[n]&&(t=!0,i(e[n]));t&&clearInterval(o)},1e3)},t.initialize=function(e){var t;this.Webcontrol=e,!this.initialized&&this._gamepadApiAvailable()&&(this.initialized=!0,(t=this)._detectGamepads(function(e){t.gamepads[e.index]||t.onConnect(e)}))},t.initializeForwarding=function(i){var o,r,s;!this._forwarding&&this._gamepadApiAvailable()&&(this._forwarding=!0,r={},s={},(o=this)._detectGamepads(function(e){if(!r[e.index]){r[e.index]=!0;var t,n={};for(t in c)c.hasOwnProperty(t)&&(n[c[t]]=0);s[e.index]=n,i({type:"gamepad:connect",index:e.index,id:e.id}),o._startForwardPolling(i,s)}}))},t._startForwardPolling=function(s,a){var l;this._forwardPollInterval||((l=this)._forwardPollInterval=setInterval(function(){for(var e=l._getGamepads(),t=0;t<e.length;t++){var n=e[t];if(n&&a[n.index])for(var i=0;i<n.buttons.length;i++){var o,r=c[i];void 0!==r&&(o=n.buttons[i].pressed?1:0,a[n.index][r]!==o)&&(a[n.index][r]=o,s({type:"gamepad:button",index:n.index,control:r,value:o}))}}},50))},t.remoteConnect=function(e,t,n){n=new i({id:n});this.gamepads[t]={user:n},e.addCustomControl(n)},t.remoteButton=function(e,t,n){e=this.gamepads[e];e&&e.user&&e.user.controlFromKey(t).update(n)},t.startGamepadPolling=function(){this._pollInterval||(this._pollInterval=setInterval(this.poll.bind(this),50))},t.poll=function(){for(var e=this._getGamepads(),t=0;t<e.length;t++)if(e[t]){var n=this.gamepads[e[t].index];if(n&&n.user)for(var i=0;i<e[t].buttons.length;i++)void 0!==c[i]&&n.user.controlFromKey(c[i]).update(e[t].buttons[i].pressed?1:0)}},t.onConnect=function(e){var t=new i({id:e.id});this.gamepads[e.index]={user:t},this.Webcontrol.addCustomControl(t),this.startGamepadPolling()},t.onDisconnect=function(e){},new e}),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/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/Gamepads/GamepadAPI","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,b,m,v,y,w,C,k,_,L,S,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}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 _),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.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.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("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()),this.preloader=new f(this.provider),!o&&a.useAudioSync()&&(this.sonicSyncClient=new S(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 b(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})},setViewFactory:function(e){return this._viewFactory=e,this._viewFactory.initialize()},getViewFactory:function(){return"undefined"===this._viewFactory&&(this._viewFactory=new C),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 m.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 k),this.connectionTrouble},setView:function(e,t){var n;return void 0===t?(n=v.create(e,[this],this),this._lastView=n):n=v.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)},enableGamepads:function(){L.initialize(this)},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){return this.preloader.preload(e)},getPreloadedUrl:function(e){return this.preloader.getPreloadedUrl(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=v.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()}.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/KeyboardUser",["CatLab/Webremote/Models/Users/ControlUser"],function(e){function t(e,t){var n="keyboard"+ ++i;this.initializeKeyboardUser({id:n,keys:e}),this.exitOnUnassignedBackButton=t}var i=0,e=((t.prototype=Object.create(e.prototype)).constructor=t).prototype;return e.initializeKeyboardUser=function(e){this.initialize({id:e.id}),void 0===e.keys&&(e.keys=this.getDefaultKeys()),this.keys=e.keys,this.attachKeyboardEvents(),"undefined"!=typeof document&&document.addEventListener("fullscreenchange",this.attachKeyboardEvents.bind(this)),this.setStaticLabels=function(){for(var e=0;e<this.keys.length;e++)this.control(this.keys[e].id).setStaticLabel(this.keys[e].label,"keyboard",this.keys[e].image,this.keys[e].emoji)},this.on("view:set",function(e){this.clearControls()}.bind(this)),this.getType=function(){return"keyboard"},this.getIcon=function(){return"fa fa-keyboard-o"},this.emit=function(e,t){return!1},this.isLocalAuthentication=function(){return!1},this.clearControls()},e.getAvailableControls=function(){for(var e=[],t=0;t<this.keys.length;t++)e.push(this.keys[t].id);return e},e.getDefaultKeys=function(){return[{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.hasControl=function(e){return-1!==this.getAvailableControls().indexOf(e)},e.hasDisplay=function(){return!1},e.hasKeyboardInput=function(){return!0},e.hasTouchInput=function(){return!0},e.stopListening=function(){try{if("undefined"==typeof window)self.removeEventListener("message",this.messageListener,!1);else{var e=null;try{e=window.document}catch(e){}e&&(this._keydownListener&&window.document.removeEventListener("keydown",this._keydownListener),this._keyupListener)&&window.document.removeEventListener("keyup",this._keyupListener),this.messageListener&&window.removeEventListener("message",this.messageListener,!1);var t=null;try{t=window.parent.document}catch(e){}t&&(t.removeEventListener("keyup",this._keydownListener),t.removeEventListener("keydown",this._keydownListener))}}catch(e){console.log(e)}},e.resumeListening=function(){this.attachKeyboardEvents()},e.attachKeyboardEvents=function(){if(this.stopListening(),"undefined"==typeof window)this.messageListener=this._onMessage.bind(this),self.addEventListener("message",this.messageListener,!1);else try{var e=window.document;if(!document.fullscreenElement&&window.parent&&!(e=window.parent.document))throw new Error("Unaccessible");this._keydownListener=this._keyDown.bind(this),this._keyupListener=this._keyUp.bind(this),e.addEventListener("keydown",this._keydownListener),e.addEventListener("keyup",this._keyupListener)}catch(e){try{this.messageListener=this._onMessage.bind(this),window.addEventListener("message",this.messageListener,!1)}catch(e){console.error(e)}}},e.getConfigFromKey=function(e){for(var t=0;t<this.keys.length;t++){if(void 0!==this.keys[t].code&&this._keyMatches(this.keys[t].code,e.code))return this.keys[t];if(void 0!==this.keys[t].key&&this._keyMatches(this.keys[t].key,e.key))return this.keys[t];if(void 0!==this.keys[t].keyCode&&this._keyMatches(this.keys[t].keyCode,e.keyCode))return this.keys[t]}return null},e._keyMatches=function(e,t){return!!(Array.isArray(e)&&-1<e.indexOf(t))||e==t},e._onMessage=function(e){var t=e.data;if("object"==typeof t&&void 0!==t.type&&"catlab:keyboard"===t.type&&void 0!==t.code&&void 0!==t.action)switch(t.action){case"down":return void this._keyDown(e.data);case"up":return void this._keyUp(e.data)}},e._keyDown=function(e){var t;"Escape"!==e.key||!this.exitOnUnassignedBackButton||this.control("back").hasTriggers("click")||this.control("back").hasTriggers("up")||this.control("back").hasTriggers("down")?(t=this.getConfigFromKey(e))&&(this.control(t.id).update(1),void 0!==t.preventDefault)&&t.preventDefault&&e.preventDefault():this.requestExitApp()},e._keyUp=function(e){var t=this.getConfigFromKey(e);t&&(this.control(t.id).update(0),void 0!==t.preventDefault)&&t.preventDefault&&e.preventDefault()},e.requestExitApp=function(){var e;"undefined"!=typeof window&&window.__catlabAppBridge?window.__catlabAppBridge("requestExit"):window.onbeforeunload?(e=window.onbeforeunload({}))&&this.confirm(e,function(e){e&&this.exitApp()}.bind(this)):this.exitApp()},e.exitApp=function(){"undefined"!=typeof window&&window.__catlabAppBridge?window.__catlabAppBridge("exit"):window.close()},e.confirm=function(e,t){t(window.confirm(e))},t}),define("CatLab/Webremote/Models/Users/CordovaUser",["CatLab/Webremote/Models/Users/KeyboardUser"],function(e){function t(e,t,n){void 0===n&&(n=!0),void 0===t&&(t="back"),this.initializeKeyboardUser({id:"cordova",keys:e}),this.initializeBackButtonExit(t,n)}e=((t.prototype=Object.create(e.prototype)).constructor=t).prototype;return e.initializeBackButtonExit=function(n,i){void 0===i&&(i=!0);var o=new Date;document.addEventListener("backbutton",function(e){var t=new Date;t.getTime()-o.getTime()<300?this.requestExitApp():(o=t,e.preventDefault(),!i||this.control("back").hasTriggers("click")||this.control("back").hasTriggers("up")||this.control("back").hasTriggers("down")?n&&(this.control(n).update(1),setTimeout(function(){this.control(n).update(0)}.bind(this),1)):setTimeout(function(){"undefined"!=typeof window&&window.__catlabAppBridge?window.__catlabAppBridge("minimize"):void 0!==window.plugins.appMinimize?window.plugins.appMinimize.minimize():this.exitApp()}.bind(this),350))}.bind(this),!1)},e.exitApp=function(){"undefined"!=typeof window&&window.__catlabAppBridge?window.__catlabAppBridge("exit"):navigator.app.exitApp()},e.confirm=function(e,t){navigator.notification.confirm(e,function(e){t(1===e)})},e.getDefaultKeys=function(){return[{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.hasDisplay=function(){return!1},e.hasKeyboardInput=function(){return!0},e.hasTouchInput=function(){return!0},t}),define("CatLab/Webremote/Models/Users/AndroidRemoteUser",["CatLab/Webremote/Models/Users/CordovaUser"],function(e){function t(e,t,n){this.initializeKeyboardUser({id:"cordova",keys:e}),this.initializeBackButtonExit(t,n)}e=((t.prototype=Object.create(e.prototype)).constructor=t).prototype;return e.getDefaultKeys=function(){return[{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.getPortalControls=function(){return{start:"start",back:"back",toggleActive:"up",authenticate:"down",left:"left",right:"right"}},e.hasDisplay=function(){return!1},e.hasKeyboardInput=function(){return!1},e.hasTouchInput=function(){return!1},this.getType=function(){return"android-keyboard"},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/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/PlayerPool",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/Models/Users/KeyboardUser","CatLab/Webremote/Models/Users/DummyUser","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/Messages/NavigateableProxy"],function(e,s,t,a,o,l,n){function i(){this.initializeEventable(),this.reset()}e=i.prototype=new e;return e.reset=function(){this.users=[],this.connectController=null,this._playercount=0,this.maxPlayers=8,this.keyboardUser=null,this.started=!1,this.Webcontrol||(this.Webcontrol=new t)},e.initialize=function(e){return this.initializeWebcontrol(e=void 0===e?{}:e)},e.initializeWebcontrol=function(t){var e,n=new s,i=this,o=void 0!==t.headless&&!!t.headless,r=new s;return o||void 0===t.portalAssets?r.resolve():(e=new l(t.portalAssets),this.Webcontrol.setViewFactory(e).then(function(){r.resolve()})),r.then(function(){var e=t.webcontrolOptions||{};o&&(e.headless=!1),i.Webcontrol.initialize(e).then(function(){t.oauth&&i.Webcontrol.oAuth(t.oauth),void 0!==t.keyboard&&!t.keyboard||(i.keyboardUser=new a,i.Webcontrol.addCustomControl(i.keyboardUser),i.keyboardUser.on("login",function(){i.trigger("keyboard:login")}),i.Webcontrol.enableGamepads()),n.resolve()})}),n.promise()},e.getConnectController=function(n){this.reset();var i=this,e=(this._pendingPortalClose=null,this._portalOpening=!0,this.Webcontrol.portalController(n)),t=void 0!==n.start?n.start:function(){};return n.start=function(e){e.forEach(function(e){e.setActive(!0),i.clearConnectScreen(),i.addUser(e)}),t(e)},e.promise.then(function(e){var t;i._portalOpening=!1,i.connectController=e,i._pendingPortalClose?(t=i._pendingPortalClose,i._pendingPortalClose=null,i.closeConnectController(t)):("function"==typeof e.on&&(e.on("active:count",function(e){i.trigger("portal:active:count",e)}),e.on("users:change",function(e){i.trigger("portal:users",e)}),"function"==typeof e.updateUsers)&&e.updateUsers(),n.maxPlayers&&e.setMaxPlayers(n.maxPlayers))}),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.addUser=function(e){this.users.push(e),this._playercount++,this.trigger("change:length",this._playercount)},e.countActivePlayers=function(){for(var e=0,t=0;t<this.users.length;t++)this.users[t].isActive()&&e++;return e},e.getAccessTokens=function(){for(var e=new s,t=[],n=this.Webcontrol.getUsers(),i=0;i<n.length;i++)n[i].isAuthenticated()&&t.push(n[i].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.setKeyboardUser=function(e){e!==this.keyboardUser&&(this.keyboardUser&&this.keyboardUser.setActive(!1),this.keyboardUser=e)},e.activateKeyboardUser=function(e){this.keyboardUser&&this.keyboardUser.setActive(!0)},e.hasKeyboardPlayer=function(){return!!this.keyboardUser},e.getNavigationUsers=function(e){var t=this.Webcontrol.getUsers();return e?t:t.filter(function(e){return!e.hasDisplay()})},e.startGame=function(){this.started=!0;for(var e=this.Webcontrol.getUsers(),t=0;t<e.length;t++)e[t].isActive()&&e[t].setView("catlab-game-starting");this.trigger("game:start")},e.newGroup=function(e,t,n){var i=new s,e=this.Webcontrol.createGroup({name:e,department:t,additionalProperties:n});return i.resolve(e),i.promise()},e.createDummyUser=function(e,t,n){var i=new o(e||"Dummy");return this.Webcontrol.addCustomControl(i),this.trigger("player:dummy:created",i,!0===t,n||{}),{id:"function"==typeof i.getId?i.getId():null,nickname:"function"==typeof i.getNickname?i.getNickname():e||"Dummy"}},e.showIndexScreen=function(){var e=new s;return e.resolve(),e.promise()},e.disconnect=function(){this.Webcontrol.disconnect()},i}),define("CatLab/Webremote/PlayerPool/KeyboardUserShim",[],function(){function t(e,t){this._id=e,this._worker=t,this._listeners={},this._label=e,this._labelType=null,this._domElements=[]}function n(e){this._worker=e,this._controls={}}function e(e){this._worker=e,this._controls={},this._events={},this._active=!1,this._accessToken=null,this._authenticated=!1,this.currentView=new n(e)}var i=t.prototype,o=(i.click=function(e){return this.on("click",e)},i.on=function(e,t){return void 0===this._listeners[e]&&(this._listeners[e]=[]),this._listeners[e].push(t),this},i.off=function(e){return void 0===e?this._listeners={}:this._listeners[e]=[],this},i.update=function(e,t){this._worker.postMessage({type:"keyboard:control:update",controlId:this._id,value:e,isClick:t})},i.getLabel=function(e){return(e=void 0===e?!0:e)?'<span class="control-label '+(this._labelType||"")+'">'+this._label+"</span>":this._label},i.addDomElement=function(e){function t(){n._trigger("click"),n._worker.postMessage({type:"keyboard:control:update",controlId:n._id,value:1,isClick:!1}),n._worker.postMessage({type:"keyboard:control:update",controlId:n._id,value:0,isClick:!0})}var n=this;return e&&e.addEventListener&&e.addEventListener("click",t),this._domElements.push({element:e,listener:t}),this},i.clearDomElements=function(){for(var e=0;e<this._domElements.length;e++){var t=this._domElements[e];t.element&&t.element.removeEventListener&&t.element.removeEventListener("click",t.listener)}return this._domElements=[],this},i._trigger=function(e){e=this._listeners[e];e&&e.slice().forEach(function(e){try{e()}catch(e){console.error(e)}})},n.prototype.changeValue=function(e,t){this._worker.postMessage({type:"keyboard:view:changeValue",key:e,value:t})},n.prototype.control=function(e){return void 0===this._controls[e]&&(this._controls[e]=new o(e,this._worker)),this._controls[e]},function(e,t){this._id=e,this._worker=t}),i=(o.prototype.update=function(e,t){this._worker.postMessage({type:"keyboard:view:control:update",controlId:this._id,value:e,isClick:t})},e.prototype);return i.isShim=!0,i.isActive=function(){return this._active},i.isAuthenticated=function(){return this._authenticated},i.getAccessToken=function(){return this._accessToken},i.login=function(e){this._worker.postMessage({type:"keyboard:login",data:e})},i.setActive=function(e){this._worker.postMessage({type:"keyboard:setActive",value:!!e})},i.setNickname=function(e){this._worker.postMessage({type:"keyboard:setNickname",name:e})},i.resumeListening=function(){this._worker.postMessage({type:"keyboard:resumeListening"})},i.stopListening=function(){this._worker.postMessage({type:"keyboard:stopListening"})},i.control=function(e){return void 0===this._controls[e]&&(this._controls[e]=new t(e,this._worker)),this._controls[e]},i.on=function(e,t){return void 0===this._events[e]&&(this._events[e]=[]),this._events[e].push(t),this},i.once=function(e,t){function n(){i.off(e,n),t.apply(this,arguments)}var i=this;return this.on(e,n)},i.off=function(e,t){return void 0===e?this._events={}:void 0===t?this._events[e]=[]:this._events[e]&&-1!==(t=this._events[e].indexOf(t))&&this._events[e].splice(t,1),this},i._triggerEvent=function(e){e=this._events[e];e&&e.slice().forEach(function(e){try{e()}catch(e){console.error(e)}})},i.handleMessage=function(e){switch(e.type){case"keyboard:state":if(void 0!==e.active&&(this._active=e.active),void 0!==e.accessToken&&(this._accessToken=e.accessToken),void 0!==e.authenticated&&(this._authenticated=e.authenticated),e.labels)for(var t in e.labels){var n;e.labels.hasOwnProperty(t)&&((n=this.control(t))._label=e.labels[t].label||t,n._labelType=e.labels[t].type||null)}break;case"keyboard:control:click":var i=e.controlId;this._controls[i]&&this._controls[i]._trigger("click");break;case"keyboard:login":void 0!==e.accessToken&&(this._accessToken=e.accessToken),this._authenticated=!0,this._triggerEvent("login")}},e}),define("CatLab/Webremote/PlayerPool/PlayerPoolWorker",["CatLab/Webremote/Tools/Deferred","CatLab/Webremote/PlayerPool/PlayerPool","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/Gamepads/GamepadAPI"],function(s,e,a,t){function n(){this.playerpool=new e,this.navProxy=null}var i=n.prototype;return i.start=function(e){var i=self,e=e||{};e.headless=!0,this.bootstrapAuthStorage(e.authStorage||{}),this.initializeStorageBridge(),this.initializeAppBridge(),this.playerpool.initialize(e).then(function(){this.playerpool.Webcontrol.on("game:initialized",function(){this.sendConnectInformation()}.bind(this)),this.sendConnectInformation(),this.initializeKeyboardBridge(),i.onmessage=function(n){if(void 0!==n.data.type)switch(n.data.type){case"catlab:keyboard":var e="down"===n.data.action?"keydown":"keyup";return void("undefined"!=typeof document&&document.dispatchEvent&&document.dispatchEvent({type:e,key:n.data.key,keyCode:n.data.keyCode,code:n.data.code,preventDefault:function(){},stopPropagation:function(){}}));case"keyboard:control:update":case"keyboard:view:changeValue":case"keyboard:view:control:update":case"keyboard:login":case"keyboard:setActive":case"keyboard:setNickname":case"keyboard:resumeListening":case"keyboard:stopListening":return void this.handleKeyboardMessage(n.data);case"webcontrol:publicConnectInfo":return void this.playerpool.setPublicConnectInfo(n.data.data);case"catlab:event":return void("undefined"!=typeof document&&document.dispatchEvent&&document.dispatchEvent({type:n.data.event,preventDefault:function(){},stopPropagation:function(){}}));case"gamepad:connect":return void t.remoteConnect(this.playerpool.Webcontrol,n.data.index,n.data.id);case"gamepad:button":return void t.remoteButton(n.data.index,n.data.control,n.data.value)}void 0!==n.data.a&&this.dispatch(n.data.a,n.data.data,function(e){try{i.postMessage({cb:n.data.cb,data:e})}catch(e){if("DataCloneError"!==e.name)throw e;var t=n.data.a;n.data.data&&n.data.data.method&&(t+=" ("+n.data.data.method+")"),console.warn('[PlayerPoolWorker] DataCloneError responding to "'+t+'": response contains non-cloneable values. Sending null.',e),i.postMessage({cb:n.data.cb,data:null})}})}.bind(this),this.playerpool.on("user:join",function(){this.triggerEvent("user:join")}.bind(this)),this.playerpool.on("change:length",function(e){this.triggerEvent("change:length",e)}.bind(this)),this.playerpool.on("change:maxconnections",function(e){this.triggerEvent("change:maxconnections",e)}.bind(this)),this.playerpool.on("portal:active:count",function(e){this.triggerEvent("portal:active:count",e)}.bind(this)),this.playerpool.on("portal:users",function(e){this.triggerEvent("portal:users",e)}.bind(this)),i.postMessage({cb:"initialized"})}.bind(this))},i.bootstrapAuthStorage=function(e){if("undefined"!=typeof localStorage&&e)for(var t in e)e.hasOwnProperty(t)&&null!==e[t]&&localStorage.setItem(t,e[t])},i.initializeStorageBridge=function(){"undefined"!=typeof window&&(window.__catlabStorageBridge=function(e){self.postMessage({type:"storage:sync",data:e})})},i.initializeAppBridge=function(){"undefined"!=typeof window&&(window.__catlabAppBridge=function(e){self.postMessage({type:"app:action",action:e})})},i.sendConnectInformation=function(){this.sendEvent("connectInfo:change",{connectToken:this.playerpool.Webcontrol.getConnectToken(),connectTokenForDisplay:this.playerpool.Webcontrol.getConnectTokenForDisplay(),connectUrl:this.playerpool.Webcontrol.getConnectURL(),server:""})},i.sendEvent=function(e,t){try{self.postMessage({e:e,data:t})}catch(t){if("DataCloneError"!==t.name)throw t;console.warn('[PlayerPoolWorker] DataCloneError sending "'+e+'". Event data contains non-cloneable values. Skipping.')}},i.triggerEvent=function(){var e=Array.prototype.slice.call(arguments);this.sendEvent(e.shift(),e)},i.initializeKeyboardBridge=function(){var t=this.playerpool.keyboardUser;if(t){this.sendKeyboardState();for(var e=t.getAvailableControls(),n=0;n<e.length;n++)(e=>{t.control(e).on("click",function(){self.postMessage({type:"keyboard:control:click",controlId:e})})})(e[n]);t.on("login",function(){self.postMessage({type:"keyboard:login",accessToken:t.getAccessToken(),authenticated:t.isAuthenticated()})}),t.on("active:change",function(){self.postMessage({type:"keyboard:state",active:t.isActive(),accessToken:t.getAccessToken()})})}},i.sendKeyboardState=function(){var e=this.playerpool.keyboardUser;if(e){for(var t={},n=e.getAvailableControls(),i=0;i<n.length;i++){var o=n[i],r=e.control(o);t[o]=r.getLabelData()}self.postMessage({type:"keyboard:state",active:e.isActive(),accessToken:e.getAccessToken(),authenticated:e.isAuthenticated(),labels:t})}},i.handleKeyboardMessage=function(e){var t=this.playerpool.keyboardUser;if(t)switch(e.type){case"keyboard:control:update":t.control(e.controlId).update(e.value,e.isClick);break;case"keyboard:view:changeValue":t.currentView&&t.currentView.changeValue(e.key,e.value);break;case"keyboard:view:control:update":t.currentView&&t.currentView.control(e.controlId).update(e.value,e.isClick);break;case"keyboard:login":t.login(e.data);break;case"keyboard:setActive":t.setActive(e.value);break;case"keyboard:setNickname":t.setNickname(e.name);break;case"keyboard:resumeListening":"function"==typeof t.resumeListening&&t.resumeListening();break;case"keyboard:stopListening":"function"==typeof t.stopListening&&t.stopListening()}else console.warn("[PlayerPoolWorker] Keyboard message but no KeyboardUser.")},i.dispatch=function(e,i,t){switch(e){case"webcontrol:setup":this.workerId=i.workerId,this.playerpool.Webcontrol.getMessageBus().toView=function(e,t,n){self.postMessage({id:i.workerId,type:"webcontrol:message",action:e,content:t,listener:n})};break;case"webcontrol:message":this.playerpool.Webcontrol.getMessageBus().handleControllerMessage(i.action,i.content);break;case"webcontrol:portal":var n=i.content||{};n.start=function(e){e=e.map(function(e){return{id:e.getId?e.getId():null,accessToken:e.getAccessToken?e.getAccessToken():null}});self.postMessage({type:"portal:game:start",users:e})},n.back=function(){self.postMessage({type:"portal:game:back"})},this.playerpool.getConnectController(n);break;case"webcontrol:portal:close":this.playerpool.closeConnectController(i.reason);break;case"webcontrol:authentication":n=this.playerpool.keyboardUser;n&&this.playerpool.Webcontrol.authenticationController(n,i.content||{}).controller.on("close",function(){self.postMessage({e:"authentication:close"})});break;case"call":var o,n=i.method,r=(i.args||[]).map(function(e){var t;return e&&"object"==typeof e&&"string"==typeof e.__remoteCallback?(t=e.__remoteCallback,function(){self.postMessage({cb:t,data:Array.prototype.slice.call(arguments),keep:!0})}):e});if("function"==typeof this.playerpool[n]){try{o=this.playerpool[n].apply(this.playerpool,r)}catch(e){t({__workerCallError:e&&e.message?e.message:String(e)||"Unknown worker error"});break}s.when(o).done(function(e){t(e)}).fail(function(e){t({__workerCallError:e&&e.message?e.message:String(e)||"Unknown worker error"})})}else console.warn("[PlayerPoolWorker] Unknown method:",n),t(null);break;case"ping":t({pong:!0});break;case"enableNavigation":r=this.playerpool.getNavigationUsers(i.includeDisplayUsers);this.navProxy&&this.navProxy.destroy(),this.navProxy=new a(this.playerpool.Webcontrol.getMessageBus()),r.forEach(function(e){e=e.setView("catlab-nes");this.navProxy.addView(e)}.bind(this)),t({});break;default:console.warn("[PlayerPoolWorker] Unknown action:",e),t&&t(null)}},n}),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.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/PlayerPool/Managers/SynchronizedManager",["CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/PlayerPool/PlayerPool","CatLab/Webremote/Tools/Deferred"],function(e,t,n){function i(){this.initializeEventable(),this.playerpool=new t,this._mode="regular"}e=i.prototype=new e;return e.initialize=function(e){this.initializeManager();e=this.playerpool.initialize(e);return e.then(function(){var t=function(){this.trigger("connectInfo:change",{server:this.settings?this.settings.host:"",connectToken:this.playerpool.Webcontrol.getConnectToken(),connectUrl:this.playerpool.Webcontrol.getConnectURL(),connectTokenForDisplay:this.playerpool.Webcontrol.getConnectTokenForDisplay()})}.bind(this);this.playerpool.Webcontrol.getProviderSettings().then(function(e){this.settings=e,t()}.bind(this)),this.playerpool.Webcontrol.on("game:initialized",function(){t()}),this.playerpool.on("user:join",function(){this.trigger("user:join")}.bind(this)),this.playerpool.on("change:length",function(e){this.trigger("change:length",e)}.bind(this)),this.playerpool.on("change:maxconnections",function(e){this.trigger("change:maxconnections",e)}.bind(this))}.bind(this)),e},e.call=function(){var e=Array.prototype.slice.call(arguments),t=e.shift();return n.when(this.playerpool[t].apply(this.playerpool,e))},e.enableNavigation=function(e,t){this._trackCurrentNavigation(e,t);t=this.playerpool.getNavigationUsers(t);return e.setUsers(t)},e._clearCurrentNavigation=function(){this._currentNavigatable&&"function"==typeof this._currentNavigatable.setUsers&&this._currentNavigatable.setUsers([])},e.getConnectScreen=function(e){var t=this.playerpool.getConnectController(e);return this.playerpool.Webcontrol.portalView(t.messageBus,e)},e.clearConnectScreen=function(e){return this.playerpool.clearConnectScreen(e)},e.activateKeyboardUser=function(e){return this.playerpool.activateKeyboardUser(e)},e.setKeyboardUser=function(e){return this.playerpool.setKeyboardUser(e)},e.createDummyUser=function(e,t,n){return this.playerpool.createDummyUser(e,t,n)},e.getAuthenticationScreen=function(e){var t=this.playerpool.getAuthenticationController(e),n=this.playerpool.getNavigationUsers(!1);return this._authenticationKeyboardUser=t.controller.user||null,t.controller.setNavigatableUsers(n),t.controller.on("close",function(){this.trigger("authentication:close")}.bind(this)),this.playerpool.Webcontrol.authenticationView(t.controller.messageBus,e)},e.getAccessTokens=function(){return this.playerpool.getAccessTokens()},e.getKeyboardUser=function(){return this._authenticationKeyboardUser||this.playerpool.keyboardUser||null},e.countActivePlayers=function(){return this.playerpool.countActivePlayers()},e.disconnect=function(){this.playerpool.disconnect();var e=new n;return e.resolve(),e.promise()},Object.defineProperty(e,"length",{get:function(){return this.playerpool._playercount}}),Object.defineProperty(e,"actualPlayersLength",{get:function(){return this.playerpool._playercount}}),i}),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/PlayerPool/Managers/WebworkerManager",["CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/PlayerPool/KeyboardUserShim","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/Providers/Dummy","CatLab/Webremote/Gamepads/GamepadAPI"],function(e,s,t,i,a,l,o,c){function n(e){this.initializeEventable(),this.callbacks={},this._pendingDispatches={},this._persistentCallbacks={},this.callbackCount=1,this._length=0,this._connectedDevices=null,this._actualPlayersLength=0,this._mode="regular",this.keyboardShim=null,this.currentNavigationView=null,this.worker=null,this._preBootQueue=[],this._disconnected=!1,this._managerOptions=e||{}}var h=new t,r=["users","currentuser"],t=n.prototype=new e;return t._buildWorkerInitOptions=function(e){var t={};if((e=e||{}).webcontrolOptions){var n,i,o={};for(n in e.webcontrolOptions)e.webcontrolOptions.hasOwnProperty(n)&&("function"!=typeof(i=e.webcontrolOptions[n])&&"object"!=typeof i||null===i)&&(o[n]=i);t.webcontrolOptions=o}return e.oauth&&(t.oauth=e.oauth),t.authStorage=this.getPersistentAuthStorageSnapshot(),void 0!==e.keyboard&&(t.keyboard=e.keyboard),"string"==typeof e.controlUserType&&(t.controlUserType=e.controlUserType),t.poolNumber="number"==typeof this.poolNumber?this.poolNumber:1,t},t.initialize=function(i){this.initializeManager(),this._initOptions=i,this._disconnected=!1,this._localInput=void 0===i.localInput||!!i.localInput;var o=new s,r=this;return this.initializeWebcontrol(i).then(function(){i.oauth&&h.oAuth(i.oauth),r.registerCallback(function(){r._localInput&&r.worker.postMessage({a:"webcontrol:setup",data:{workerId:r.webworkerId}}),r._flushPreBootQueue(),o.resolve()},"initialized");function t(e){e.data&&"worker:modules-ready"===e.data.type&&(r.worker.removeEventListener("message",t),r.worker.postMessage({type:"worker:init",options:n}))}var e=r._managerOptions.workerUrl||"scripts/webworker.js",n=(r.worker=new Worker(e),r.worker.onerror=function(e){console.error("[WebworkerManager] Worker failed to initialize:",e),r.trigger("worker:error",e)},r.webworkerId=Math.random().toString(36).substring(7),r._buildWorkerInitOptions(i));r.worker.addEventListener("message",t),r._localInput&&(h.getMessageBus().toController=function(e,t){r.worker.postMessage({a:"webcontrol:message",data:{action:e,content:t}})}),r.worker.onmessage=function(e){var t;void 0===e.data.type||"webcontrol:message"!==e.data.type||e.data.id!==r.webworkerId?void 0!==e.data.type&&0===e.data.type.indexOf("keyboard:")&&r.keyboardShim?r.keyboardShim.handleMessage(e.data):void 0===e.data.type||"app:action"!==e.data.type?void 0===e.data.type||"storage:sync"!==e.data.type?void 0===e.data.cb?void 0!==e.data.e&&(t=[e.data.e],Array.isArray(e.data.data)?t=t.concat(e.data.data):void 0!==e.data.data&&t.push(e.data.data),r._syncLengthFromPayload(e.data.e,t[1]),r.trigger.apply(r,t)):r.handleCallback(e.data):r.applyPersistentStorageSync(e.data.data||{}):r.handleAppAction(e.data.action):r.currentNavigationView&&l.handleMessage(e.data.action,e.data.content,r.currentNavigationView)||h.getMessageBus().handleViewMessage(e.data.action,e.data.content)},r.on("change:length",function(e){"number"!=typeof e&&r.call("countActivePlayers").then(function(e){r._length=e})}),r._localInput&&(window.addEventListener("keydown",function(e){r.worker.postMessage({type:"catlab:keyboard",key:e.key,keyCode:e.keyCode,code:e.code,action:"down"})}),window.addEventListener("keyup",function(e){r.worker.postMessage({type:"catlab:keyboard",key:e.key,keyCode:e.keyCode,code:e.code,action:"up"})}),r.keyboardShim=new a(r.worker),c.initializeForwarding(function(e){r.worker.postMessage(e)}),"undefined"!=typeof document)&&document.addEventListener("backbutton",function(e){e&&e.preventDefault&&e.preventDefault(),r.worker.postMessage({type:"catlab:event",event:"backbutton"})},!1)}),o.promise()},t.getPersistentAuthStorageSnapshot=function(){var n={};return"undefined"!=typeof window&&void 0!==window.localStorage&&r.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!==r.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.handleAppAction=function(e){switch(e){case"minimize":return"undefined"!=typeof window&&window.plugins&&window.plugins.appMinimize?void window.plugins.appMinimize.minimize():void this.handleAppAction("exit");case"requestExit":var t,n;return window.onbeforeunload?void((t=window.onbeforeunload({}))&&(n=this)._confirmDialog(t,function(e){e&&n.handleAppAction("exit")})):void this.handleAppAction("exit");case"exit":return"undefined"!=typeof navigator&&navigator.app&&"function"==typeof navigator.app.exitApp?void navigator.app.exitApp():void window.close()}},t._confirmDialog=function(e,t){"undefined"!=typeof navigator&&navigator.notification&&navigator.notification.confirm?navigator.notification.confirm(e,function(e){t(1===e)}):t(window.confirm(e))},t.initializeWebcontrol=function(e){var t=new s,n=Object.assign({},e.webcontrolOptions||{},{provider:new o});return e.portalAssets?(e=new i(e.portalAssets),h.setViewFactory(e).then(function(){h.initialize(n).then(function(){t.resolve()})})):h.initialize(n).then(function(){t.resolve()}),t.promise()},t.getWebcontrol=function(){return h},t.getKeyboardShim=function(){return this.keyboardShim},t.getKeyboardUser=function(){return this.keyboardShim||null},t.dispatch=function(e,t){var n,i=new s,o=this;return!this.worker&&this._disconnected?i.reject(new Error("[WebworkerManager] dispatch after disconnect: "+e)):(n=this.registerCallback(function(e){delete o._pendingDispatches[n],e&&e.__workerCallError?i.reject(new Error(e.__workerCallError)):i.resolve(e)}),e=(this._pendingDispatches[n]=i,{a:e,cb:n,data:t}),this.worker?this.worker.postMessage(e):this._preBootQueue.push(e)),i.promise()},t._failPendingDispatches=function(t){this._preBootQueue=[];var n=this._pendingDispatches;this._pendingDispatches={},Object.keys(n).forEach(function(e){delete this.callbacks[e],n[e].reject(t)}.bind(this))},t._flushPreBootQueue=function(){var e,t;this.worker&&(e=this._preBootQueue,this._preBootQueue=[],t=this,e.forEach(function(e){t.worker.postMessage(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=this,n=new s,i=!1,o=null,r=this.registerCallback(function(e){i||(i=!0,clearTimeout(o),delete t._pendingDispatches[r],n.resolve(e))});return this._pendingDispatches[r]=n,o=setTimeout(function(){i||(i=!0,delete t.callbacks[r],delete t._pendingDispatches[r],n.reject(new Error("[WebworkerManager] ping timeout")))},e),this.worker.postMessage({a:"ping",cb:r,data:{}}),n.promise()},t.registerCallback=function(e,t,n){return void 0===t&&(t="cb:"+ ++this.callbackCount),this.callbacks[t]=e,n&&(this._persistentCallbacks[t]=!0),t},t.handleCallback=function(e){void 0!==this.callbacks[e.cb]&&(this.callbacks[e.cb](e.data),e.keep||this._persistentCallbacks[e.cb]||delete this.callbacks[e.cb])},t._encodeCallbackArg=function(t){return{__remoteCallback:this.registerCallback(function(e){t.apply(null,Array.isArray(e)?e:[e])},void 0,!0)}},t.call=function(){for(var e=Array.prototype.slice.call(arguments),t=e.shift(),n=[],i=0;i<e.length;i++)n.push("function"==typeof e[i]?this._encodeCallbackArg(e[i]):e[i]);return this.dispatch("call",{method:t,args:n})},t.enableNavigation=function(e,t){this._trackCurrentNavigation(e,t),this.currentNavigationView=e,this.dispatch("enableNavigation",{includeDisplayUsers:t})},t._clearCurrentNavigation=function(){this.currentNavigationView=null},t.openPortal=function(e){var t={};if(e)for(var n in e)e.hasOwnProperty(n)&&"function"!=typeof e[n]&&(t[n]=e[n]);var i="function"==typeof e.start?e.start:function(){},o="function"==typeof e.back?e.back:function(){},r=this,s=function(e){void 0!==e.data.type&&("portal:game:start"===e.data.type?(r.worker.removeEventListener("message",s),i(e.data.users||[])):"portal:game:back"===e.data.type&&(r.worker.removeEventListener("message",s),o()))};this.worker.addEventListener("message",s),this.dispatch("webcontrol:portal",{content:t})},t.finalizePortal=function(e){this.dispatch("webcontrol:portal:close",{reason:e})},t.getConnectScreen=function(t){this.openPortal(t);var n=h.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},h.portalView(n,t)},t.setPublicConnectInfo=function(e){this.worker&&this.worker.postMessage({type:"webcontrol:publicConnectInfo",data:e})},t.clearConnectScreen=function(){return this.call("clearConnectScreen")},t.activateKeyboardUser=function(e){return this.call("activateKeyboardUser",e)},t.setKeyboardUser=function(e){return this.call("setKeyboardUser",e)},t.createDummyUser=function(e,t,n){return this.call("createDummyUser",e,t,n||{})},t.getAuthenticationScreen=function(e){var t,n={};for(t in e=e||{})e.hasOwnProperty(t)&&"function"!=typeof e[t]&&(n[t]=e[t]);this.dispatch("webcontrol:authentication",{content:n});var i=h.getMessageBus();return h.authenticationView(i,e)},t.getAccessTokens=function(){return this.call("getAccessTokens")},t.countActivePlayers=function(){return this.call("countActivePlayers")},t.disconnect=function(){this._disconnected=!0,this._preBootQueue=[],this.worker&&(this.worker.terminate(),this.worker=null);var e=new s;return e.resolve(),e.promise()},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}}),n}),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/Managers/WorkerManager",["CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/PlayerPool/Managers/WebworkerManager","CatLab/Webremote/PlayerPool/Managers/SynchronizedManager","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/PlayerPool/Protocol/whenAllSettled"],function(e,t,n,s,i){function o(e){this.initializeEventable(),this.workers=[],this.useFallback=!1,this._mode="regular",this._initOptions=null,this._totalLength=0,this._managerOptions=e||{}}e=o.prototype=new e;return e.constructor=o,e.initialize=function(e){var t,n,i,o,r;return this.initializeManager(),this._initOptions=e,"undefined"==typeof Worker?(console.warn("[WorkerManager] WebWorkers not supported, falling back."),this._initFallback(e)):(t=new s,n=!1,o=(i=this)._createWorkerManager(),r=function(){n||(n=!0,i.workers=[],i._initFallback(e).done(function(){t.resolve()}).fail(function(e){t.reject(e)}))},o.initialize(e).done(function(){n||(n=!0,i._started=!0,t.resolve())}).fail(function(e){console.error("[WorkerManager] Primary worker failed to initialize:",e),r()}),o.on("worker:error",function(e){console.error("[WorkerManager] Primary worker failed:",e),1!==i.workers.length||n||r()}),t.promise())},e._initFallback=function(e){this.useFallback=!0,this._started=!0;var t=new n;return this.workers=[t],this._bindWorkerEvents(t),t.initialize(e)},e._createWorkerManager=function(){var e=new t(this._managerOptions);return this.workers.push(e),this._bindWorkerEvents(e),e},e._getPrimaryWorker=function(){return this.workers[0]},e._bindWorkerEvents=function(n){var i=this;["user:join","change:maxconnections","change:maxplayers","authentication:close"].forEach(function(t){n.on(t,function(){var e=Array.prototype.slice.call(arguments);e.unshift(t),i.trigger.apply(i,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.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.getAuthenticationScreen=function(){return this._getPrimaryWorker().getAuthenticationScreen()},e.getAccessTokens=function(){return this._getPrimaryWorker().getAccessTokens()},e.countActivePlayers=function(){return this._getPrimaryWorker().countActivePlayers()},e.getKeyboardShim=function(){var e=this._getPrimaryWorker();return e&&"function"==typeof e.getKeyboardShim?e.getKeyboardShim():null},e.getWebcontrol=function(){var e=this._getPrimaryWorker();return e&&"function"==typeof e.getWebcontrol?e.getWebcontrol():e&&e.playerpool?e.playerpool.Webcontrol:null},e.disconnect=function(){var e=new s,t=this.workers.map(function(e){return e.disconnect()});return this.workers=[],i(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}}),o}),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(){},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)}}};return 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(u,r,d,f){function i(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)))}function o(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 s(c,n,e){var i=(e=>{if("function"==typeof e)return e;var t=r[e||"first"];if("function"!=typeof t)throw new Error("[ManifestProxy] Unknown aggregator: "+e);return t})(n.aggregate),o=n.route||"all",h="number"==typeof n.timeoutMs?n.timeoutMs:e&&"number"==typeof e.defaultTimeoutMs?e.defaultTimeoutMs:1e4;return function(){function e(i){var o,e;0!==i.length?(o=i.map(function(e){return r.workers.indexOf(e)}),e=i.map(function(e){return n=s,"function"==typeof(e=e)[t=c]?e[t].apply(e,n):e.call.apply(e,[t].concat(n));var t,n}),f(e,h).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:[]})}function t(){return"leastFullOrSpawn"===o?r.workers.filter(function(e){return!e._bootInFlight}):r.workers}var r=this,s=Array.prototype.slice.call(arguments),a=(n.replayOnSpawn&&"function"==typeof r._recordReplayableCall&&r._recordReplayableCall(c,s),new u),l=function(e,t){var n;try{n=i(e,s,t)}catch(e){return void a.reject(e)}a.resolve(n)};return"leastFullOrSpawn"===o&&"function"==typeof r._ensureRosterCapacity?r._ensureRosterCapacity().always(function(){e(d.select(o,t()))}):e(d.select(o,t())),a.promise()}}var a=["applyManifest","getWorkerForToken","call","dispatch","initialize","disconnect","restore"];return{applyToCoordinator:function(t,n){o(t,"applyToCoordinator"),Object.keys(n.methods).forEach(function(e){if(-1!==a.indexOf(e)&&!i(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){i(t,e)||(t[e]=s(e,n.methods[e],n),t._manifestGeneratedMethods.push(e))})},applyToClient:function(t,e){o(t,"applyToClient"),Object.keys(e.methods).forEach(function(e){i(t,e)||(t[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"],function(t,n,s){function e(e){t.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 i=e.prototype=new t;return i.constructor=e,i.applyManifest=function(e){this._manifest=e,n.applyToCoordinator(this,e)},i._bindWorkerEvents=function(i){t.prototype._bindWorkerEvents.call(this,i),"number"!=typeof i.poolNumber&&(i.poolNumber=++this._poolSequence);var o=this;this._manifest&&this._manifest.events&&this._manifest.events.forEach(function(t){var n=o._manifest.barrierEvents&&o._manifest.barrierEvents[t];"function"!=typeof n?i.on(t,function(){var e=Array.prototype.slice.call(arguments);e.unshift(t),o.trigger.apply(o,e)}):i.on(t,function(){var e=Array.prototype.slice.call(arguments);o._recordBarrierEvent(t,String(n.apply(null,e)),i,e)})}),i.on("worker:error",function(e){o._handleWorkerFailure(i,e)}),i.on("change:connections",function(){o._checkCapacity()}),i.on("portal:active:count",function(e){i._portalActiveCount=e||0,o._syncPortalCounts()}),i.on("portal:users",function(e){i._portalUsers=e||[],o._syncPortalUsers()})},i.getWorkerForToken=function(e){return this.tokenRegistry[e]||null},i._onWorkerConnectInfo=function(e,t){t&&t.connectToken&&(e._lastConnectInfo=t,(this.tokenRegistry[t.connectToken]=e)===this.workers[this.workers.length-1])&&this._setPublicConnectInfo(t)},i._setPublicConnectInfo=function(e){this._publicConnectInfo=e,this.trigger("connectInfo:change",e);var t=this._getPrimaryWorker();t&&"function"==typeof t.setPublicConnectInfo&&t.setPublicConnectInfo(e)},i._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()},i._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"),i.trigger("pool:error:survived",{poolIndex:e,error:n}))}).fail(function(){t._probeInFlight=!1;var e=i.workers.indexOf(t);-1!==e&&i._killWorker(t,e,n)})):this._killWorker(t,e,n))},i._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{t.worker&&"function"==typeof t.worker.terminate&&t.worker.terminate()}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."),this.trigger("pool:all: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()},i._checkCapacity=function(){var e,t;this.useFallback||this._spawnInFlight||this._capacityExhausted||(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())},i._spawnNewWorker=function(){var i,o,r;return this._spawnInFlight&&this._spawnPromise?this._spawnPromise:(i=new s,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())},i._ensureRosterCapacity=function(){var e=new s;if(this.useFallback||this._capacityExhausted||0===this.workers.length)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()},i._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)},i._checkEventBarrier=function(e){var t,n=this._eventBarriers[e];n&&(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))))},i._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})},i._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)})})},i._afterSpawn=function(e){},i._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},i.getConnectScreen=function(t){var n,e,i,o,r=this;return this.useFallback?this._getPrimaryWorker().getConnectScreen(t):(n="function"==typeof t.start?t.start:function(){},e="function"==typeof t.back?t.back:function(){},this._portalActive=!0,this.workers.forEach(function(e){e._portalActiveCount=0,e._portalUsers=[]}),t.start=function(e){r._onPortalEnd("start",function(){n(e)})},t.back=function(){r._onPortalEnd("back",function(){e()})},o=(i=this._getPrimaryWorker()).getConnectScreen(t),this.workers.forEach(function(e){e!==i&&"function"==typeof e.openPortal&&e.openPortal(t)}),this._recordReplayableCall("openPortal",[t]),o)},i._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())},i._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))}))},i._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))},i._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)},i.clearConnectScreen=function(t){return this.workers.map(function(e){return e.clearConnectScreen(t)})[0]},Object.defineProperty(i,"actualPlayersLength",{get:function(){return this._totalActualPlayersLength}}),e}),define("CatLab/Webremote/FrontWebcontrol",["CatLab/Webremote/Config","CatLab/Webremote/Polyfills","CatLab/Webremote/Tools/Tracker","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Images","CatLab/Webremote/Models/Users/KeyboardUser","CatLab/Webremote/Models/Users/CordovaUser","CatLab/Webremote/Models/Users/AndroidRemoteUser","CatLab/Webremote/Models/Users/DummyUser","CatLab/Webremote/Providers/SocketIO","CatLab/Webremote/Providers/Airconsole","CatLab/Webremote/ViewFactory/ViewFactory","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/PlayerPool/PlayerPool","CatLab/Webremote/PlayerPool/KeyboardUserShim","CatLab/Webremote/PlayerPool/PlayerPoolWorker","CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/PlayerPool/Managers/SynchronizedManager","CatLab/Webremote/PlayerPool/Managers/WebworkerManager","CatLab/Webremote/PlayerPool/Managers/WorkerManager","CatLab/Webremote/PlayerPool/Managers/PoolCoordinator","CatLab/Webremote/PlayerPool/Protocol/Aggregators","CatLab/Webremote/PlayerPool/Protocol/Router","CatLab/Webremote/PlayerPool/Protocol/ManifestProxy","CatLab/Webremote/PlayerPool/Protocol/whenAllSettled"],function(t,e,n,i,o,r,s,a,l,c,h,u,d,f,p,g,b,m,v,y,w,C,k,_,L,S,P,T,A){return{Config:function(e){t.set(e)},Tracker:n,Tools:i,Webcontrol:new r,OAuth2:o,Controls:{Keyboard:l,Cordova:c,AndroidRemote:h,Dummy:u},Controllers:{Webcontrol:r},Models:{User:u},Providers:{SocketIO:d,Airconsole:f},ViewFactories:{HtmlViewFactory:p,CreatejsViewFactory:g},Smileys:s,Images:new a,NavigateableProxy:b,PlayerPool:{PlayerPool:m,KeyboardUserShim:v,PlayerPoolWorker:y,Manager:w,SynchronizedManager:C,WebworkerManager:k,WorkerManager:_,PoolCoordinator:L,Protocol:{Aggregators:S,Router:P,ManifestProxy:T,whenAllSettled:A}}}}),define("webcontrol",["CatLab/Webremote/FrontWebcontrol"],function(e){return e}),define("CatLab/EaselHacks/AlphaMaskFilter",[],function(e){function t(e){var i=this;this.createjs=e,Object.defineProperty(e.DisplayObject.prototype,"mask",{get:function(){return this.forceMask},set:function(e){var t,n=this;e?(n.originalMask=e,t=i.getFilterFromMask(e,n),n.filters=[t],n.cache(0,0,500,500)):null!==e&&(n.filters=null,n.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
|
+
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].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]=new Deferred,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)},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),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={"&":"&","<":"<",">":">",'"':""","'":"'"},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/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/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/Storage",["CatLab/Webremote/Tools/Cookies"],function(e){var t={_syncKeys:["users","currentuser"],syncToBridge:function(e){-1!==this._syncKeys.indexOf(e)&&"undefined"!=typeof window&&window.__catlabStorageBridge&&"function"==typeof window.__catlabStorageBridge&&void 0!==window.localStorage&&window.__catlabStorageBridge({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/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/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/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}),(()=>{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(b[e])return b[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 b[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 b=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/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/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(){return this.nickname||(this.getData().username?this.getData().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/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/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 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(t){this.reattachClick(t.control(this.controls.navigation[0]),this.previous),this.reattachClick(t.control(this.controls.navigation[1]),this.next),this.reattachClick(t.control(this.controls.manipulation[0]),this.down),this.reattachClick(t.control(this.controls.manipulation[1]),this.up),this.controls.toggle.forEach(function(e){void 0===this.keyInputCallbacks[e]&&(this.keyInputCallbacks[e]=function(){this.keyInput(e)}),this.reattachClick(t.control(e),this.keyInputCallbacks[e].bind(this))}.bind(this)),this.controls.back.forEach(function(e){this.reattachClick(t.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){this.messageBus.toView(this.prefix+"nav:keyInput",{button:e})},t.previous=function(){this.messageBus.toView(this.prefix+"nav:previous")},t.next=function(){this.messageBus.toView(this.prefix+"nav:next")},t.up=function(){this.keyInput("up")},t.down=function(){this.keyInput("down")},t.back=function(){this.messageBus.toView(this.prefix+"nav:back")},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),!0;case"nav:back":return n.triggerBack(),!0}return!1}},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.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/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/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(D){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,b,m,v=!e.customViews,y=[],w=!1,C=!1,k=null,V=this;function _(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(E(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(),I(),x()}),o.control("start-game").click(function(){var e;w?x():y.length<r?z(r+" players are required to start the game. Please gather more friends."):y.length>s?z("This game can have only "+s+" players."):(e=n,x(),w=!0,(f=new Date).setTime((new Date).getTime()+e),u.style.display="",d=setInterval(O,100))}),o.control("down").click(function(){P(o)}),o.control("right").click(function(){P(o)}),o.control("left").click(function(){S(o)}),o.control("up").click(function(){S(o)}),o.control("a").click(function(){var e,t,i,n;e=o,C&&T(e)?(t=m.querySelector(".available-accounts li.selected"))&&(t=WebcontrolOAuthClient.getFromToken(t.getAttribute("data-accessToken")))&&(n=t.access_token,k.setUserData(n,t.user),A()):(w&&x(),C||(i=e,Webcontrol.getOAuthClient(function(n){n.onInit(function(){W(n)}),WebcontrolAccessKeyLibrary.init(function(){C=!0,k=i,b.style.display="",m.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(){W(n)})}),m.querySelector(".link-new-account"));t.innerHTML="",t.appendChild(e)}),W(n)})))}),o.control("b").click(function(){C&&T(o)&&(k.setUserData(!1),A())}),U(),I()}function S(e){if(C&&T(e)){for(var e=m.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 P(e){if(C&&T(e)){for(var e=m.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 T(e){return k&&e.getId()==k.getId()}function A(){b.style.display="none",m.style.display="none",C=!1,k=null}function W(e){var t=m.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 I(){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 E(e){for(var t=0;t<y.length;t++)if(y[t].getId()==e.getId())return 1}function U(){var e=Webcontrol.getUsers();a.innerHTML="";for(var t=[],n=0;n<e.length;n++)E(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),U()}function O(){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"),x(),i(y))}function x(){w=!1,d&&(z("Countdown stopped!"),u.style.display="none",clearInterval(d),d=null)}function z(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=D.getSocketURL()+"/webremote/themes/"+e.theme+"/"+e.theme+".css",Webcontrol._loadCSS(e),Webcontrol._loadCSS(D.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>',v&&Webcontrol.loadViews(D.getSocketURL(!0)+"/webremote/views/default.xml"),o.innerHTML="<h1>Player lobby</h1>",b=document.createElement("div"),m=_('<div><h2>Select account</h2><div class="information"><p>'+V.loginInformation+'</p></div><ul class="available-accounts"></ul><p class="link-new-account"></p></div>'),b.className="accounts-overlay",m.className="accounts",b.style.display="none",m.style.display="none",o.appendChild(b),o.appendChild(m),_('<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),_('<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=_('<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=_('<p class="buttoninstructions join-game">Press <span class="labels"></span> to join the game.</p>'),h=_('<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",U),U(),M(),I()})}}),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/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/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,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")+'" 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/Models/Users/GamepadUser",["CatLab/Webremote/Models/Users/ControlUser"],function(e){function t(e){var t=e.id||"1";this.initialize({id:"gamepad_"+t}),this.keys=this.getDefaultKeys(e),this.clearControls()}e=t.prototype=new e;return e.getType=function(){return"gamepad"},e.getIcon=function(){return"fa fa-gamepad"},e.emit=function(){return!1},e.isLocalAuthentication=function(){return!1},e.controlFromKey=function(e){return this.control(this.keys[e].id)},e.hasDisplay=function(){return!1},e.hasKeyboardInput=function(){return!1},e.hasTouchInput=function(){return!1},e.getPortalControls=function(){return{start:"start",back:"back",toggleActive:"x",authenticate:"y",left:"left",right:"right"}},e.getDefaultKeys=function(e){var t="control-icons/gamepad/$SIZE/",n="gamepad-",i="🎮",o={a:"🅰️",b:"🅱️",x:"❎",y:"❎",up:"⬆️",down:"⬇️",left:"⬅️",right:"➡️",l1:"🤜",r1:"🤛"};return void 0===e.id||-1===e.id.toLowerCase().indexOf("sony")&&-1===e.id.toLowerCase().indexOf("054c")||(t="control-icons/ps-controller/$SIZE/",n="ps-controller-",i="🕹",o={a:"❎",b:"⭕",x:"🟥",y:"🔺",up:"⬆️",down:"⬇️",left:"⬅️",right:"➡️",l1:"🤜",r1:"🤛"}),{DPAD_UP:{id:"up",label:"↑",key:"DPAD_UP",emoji:i+""+o.up},DPAD_DOWN:{id:"down",label:"↓",key:"DPAD_DOWN",emoji:i+""+o.down},DPAD_RIGHT:{id:"right",label:"→",key:"DPAD_RIGHT",emoji:i+""+o.right},DPAD_LEFT:{id:"left",label:"←",key:"DPAD_LEFT",emoji:i+""+o.left},FACE_1:{id:"a",label:"A",key:"FACE_1",image:t+n+"a.gif",emoji:i+""+o.a},FACE_2:{id:"b",label:"B",key:"FACE_2",image:t+n+"b.gif",emoji:i+""+o.b},FACE_3:{id:"x",label:"X",key:"FACE_3",image:t+n+"x.gif",emoji:i+""+o.x},FACE_4:{id:"y",label:"Y",key:"FACE_4",image:t+n+"y.gif",emoji:i+""+o.y},SELECT_BACK:{id:"back",label:"SELECT",key:"SELECT_BACK"},START_FORWARD:{id:"start",label:"START",key:"START_FORWARD"},L1:{id:"l1",label:"L1",key:"L1",emoji:i+""+o.l1},R1:{id:"r1",label:"R1",key:"R1",emoji:i+""+o.r1}}},e.setStaticLabels=function(){for(var e in this.keys)this.keys.hasOwnProperty(e)&&this.control(this.keys[e].id).setStaticLabel(this.keys[e].label,"gamepad",this.keys[e].image,this.keys[e].emoji)},t}),define("CatLab/Webremote/Gamepads/GamepadAPI",["CatLab/Webremote/Models/Users/GamepadUser"],function(i){function e(){this.gamepads={},this.initialized=!1,this.Webcontrol=null,this._forwarding=!1,this._forwardPollInterval=null,this._pollInterval=null}var c={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"},t=e.prototype;return t._gamepadApiAvailable=function(){return"undefined"!=typeof navigator&&("function"==typeof navigator.getGamepads||void 0!==navigator.webkitGetGamepads)},t._getGamepads=function(){return"function"==typeof navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[]},t._detectGamepads=function(i){var o,r=this;"undefined"!=typeof window&&"ongamepadconnected"in window?(window.addEventListener("gamepadconnected",function(e){i(e.gamepad)}),window.addEventListener("gamepaddisconnected",function(e){r.onDisconnect(e.gamepad)})):o=setInterval(function(){for(var e=r._getGamepads(),t=!1,n=0;n<e.length;n++)e[n]&&(t=!0,i(e[n]));t&&clearInterval(o)},1e3)},t.initialize=function(e){var t;this.Webcontrol=e,!this.initialized&&this._gamepadApiAvailable()&&(this.initialized=!0,(t=this)._detectGamepads(function(e){t.gamepads[e.index]||t.onConnect(e)}))},t.initializeForwarding=function(i){var o,r,s;!this._forwarding&&this._gamepadApiAvailable()&&(this._forwarding=!0,r={},s={},(o=this)._detectGamepads(function(e){if(!r[e.index]){r[e.index]=!0;var t,n={};for(t in c)c.hasOwnProperty(t)&&(n[c[t]]=0);s[e.index]=n,i({type:"gamepad:connect",index:e.index,id:e.id}),o._startForwardPolling(i,s)}}))},t._startForwardPolling=function(s,a){var l;this._forwardPollInterval||((l=this)._forwardPollInterval=setInterval(function(){for(var e=l._getGamepads(),t=0;t<e.length;t++){var n=e[t];if(n&&a[n.index])for(var i=0;i<n.buttons.length;i++){var o,r=c[i];void 0!==r&&(o=n.buttons[i].pressed?1:0,a[n.index][r]!==o)&&(a[n.index][r]=o,s({type:"gamepad:button",index:n.index,control:r,value:o}))}}},50))},t.remoteConnect=function(e,t,n){n=new i({id:n});this.gamepads[t]={user:n},e.addCustomControl(n)},t.remoteButton=function(e,t,n){e=this.gamepads[e];e&&e.user&&e.user.controlFromKey(t).update(n)},t.startGamepadPolling=function(){this._pollInterval||(this._pollInterval=setInterval(this.poll.bind(this),50))},t.poll=function(){for(var e=this._getGamepads(),t=0;t<e.length;t++)if(e[t]){var n=this.gamepads[e[t].index];if(n&&n.user)for(var i=0;i<e[t].buttons.length;i++)void 0!==c[i]&&n.user.controlFromKey(c[i]).update(e[t].buttons[i].pressed?1:0)}},t.onConnect=function(e){var t=new i({id:e.id});this.gamepads[e.index]={user:t},this.Webcontrol.addCustomControl(t),this.startGamepadPolling()},t.onDisconnect=function(e){},new e}),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/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/Gamepads/GamepadAPI","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,b,m,v,y,w,C,k,_,L,S,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}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 _),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.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("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 S(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 b(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})},setViewFactory:function(e){return this._viewFactory=e,this._viewFactory.initialize()},getViewFactory:function(){return"undefined"===this._viewFactory&&(this._viewFactory=new C),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 m.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 k),this.connectionTrouble},setView:function(e,t){var n;return void 0===t?(n=v.create(e,[this],this),this._lastView=n):n=v.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)},enableGamepads:function(){L.initialize(this)},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=v.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()}.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/KeyboardUser",["CatLab/Webremote/Models/Users/ControlUser"],function(e){function t(e,t){var n="keyboard"+ ++i;this.initializeKeyboardUser({id:n,keys:e}),this.exitOnUnassignedBackButton=t}var i=0,e=((t.prototype=Object.create(e.prototype)).constructor=t).prototype;return e.initializeKeyboardUser=function(e){this.initialize({id:e.id}),void 0===e.keys&&(e.keys=this.getDefaultKeys()),this.keys=e.keys,this.attachKeyboardEvents(),"undefined"!=typeof document&&document.addEventListener("fullscreenchange",this.attachKeyboardEvents.bind(this)),this.setStaticLabels=function(){for(var e=0;e<this.keys.length;e++)this.control(this.keys[e].id).setStaticLabel(this.keys[e].label,"keyboard",this.keys[e].image,this.keys[e].emoji)},this.on("view:set",function(e){this.clearControls()}.bind(this)),this.getType=function(){return"keyboard"},this.getIcon=function(){return"fa fa-keyboard-o"},this.emit=function(e,t){return!1},this.isLocalAuthentication=function(){return!1},this.clearControls()},e.getAvailableControls=function(){for(var e=[],t=0;t<this.keys.length;t++)e.push(this.keys[t].id);return e},e.getDefaultKeys=function(){return[{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.hasControl=function(e){return-1!==this.getAvailableControls().indexOf(e)},e.hasDisplay=function(){return!1},e.hasKeyboardInput=function(){return!0},e.hasTouchInput=function(){return!0},e.stopListening=function(){try{if("undefined"==typeof window)self.removeEventListener("message",this.messageListener,!1);else{var e=null;try{e=window.document}catch(e){}e&&(this._keydownListener&&window.document.removeEventListener("keydown",this._keydownListener),this._keyupListener)&&window.document.removeEventListener("keyup",this._keyupListener),this.messageListener&&window.removeEventListener("message",this.messageListener,!1);var t=null;try{t=window.parent.document}catch(e){}t&&(t.removeEventListener("keyup",this._keydownListener),t.removeEventListener("keydown",this._keydownListener))}}catch(e){console.log(e)}},e.resumeListening=function(){this.attachKeyboardEvents()},e.attachKeyboardEvents=function(){if(this.stopListening(),"undefined"==typeof window)this.messageListener=this._onMessage.bind(this),self.addEventListener("message",this.messageListener,!1);else try{var e=window.document;if(!document.fullscreenElement&&window.parent&&!(e=window.parent.document))throw new Error("Unaccessible");this._keydownListener=this._keyDown.bind(this),this._keyupListener=this._keyUp.bind(this),e.addEventListener("keydown",this._keydownListener),e.addEventListener("keyup",this._keyupListener)}catch(e){try{this.messageListener=this._onMessage.bind(this),window.addEventListener("message",this.messageListener,!1)}catch(e){console.error(e)}}},e.getConfigFromKey=function(e){for(var t=0;t<this.keys.length;t++){if(void 0!==this.keys[t].code&&this._keyMatches(this.keys[t].code,e.code))return this.keys[t];if(void 0!==this.keys[t].key&&this._keyMatches(this.keys[t].key,e.key))return this.keys[t];if(void 0!==this.keys[t].keyCode&&this._keyMatches(this.keys[t].keyCode,e.keyCode))return this.keys[t]}return null},e._keyMatches=function(e,t){return!!(Array.isArray(e)&&-1<e.indexOf(t))||e==t},e._onMessage=function(e){var t=e.data;if("object"==typeof t&&void 0!==t.type&&"catlab:keyboard"===t.type&&void 0!==t.code&&void 0!==t.action)switch(t.action){case"down":return void this._keyDown(e.data);case"up":return void this._keyUp(e.data)}},e._keyDown=function(e){var t;"Escape"!==e.key||!this.exitOnUnassignedBackButton||this.control("back").hasTriggers("click")||this.control("back").hasTriggers("up")||this.control("back").hasTriggers("down")?(t=this.getConfigFromKey(e))&&(this.control(t.id).update(1),void 0!==t.preventDefault)&&t.preventDefault&&e.preventDefault():this.requestExitApp()},e._keyUp=function(e){var t=this.getConfigFromKey(e);t&&(this.control(t.id).update(0),void 0!==t.preventDefault)&&t.preventDefault&&e.preventDefault()},e.requestExitApp=function(){var e;"undefined"!=typeof window&&window.__catlabAppBridge?window.__catlabAppBridge("requestExit"):window.onbeforeunload?(e=window.onbeforeunload({}))&&this.confirm(e,function(e){e&&this.exitApp()}.bind(this)):this.exitApp()},e.exitApp=function(){"undefined"!=typeof window&&window.__catlabAppBridge?window.__catlabAppBridge("exit"):window.close()},e.confirm=function(e,t){t(window.confirm(e))},t}),define("CatLab/Webremote/Models/Users/CordovaUser",["CatLab/Webremote/Models/Users/KeyboardUser"],function(e){function t(e,t,n){void 0===n&&(n=!0),void 0===t&&(t="back"),this.initializeKeyboardUser({id:"cordova",keys:e}),this.initializeBackButtonExit(t,n)}e=((t.prototype=Object.create(e.prototype)).constructor=t).prototype;return e.initializeBackButtonExit=function(n,i){void 0===i&&(i=!0);var o=new Date;document.addEventListener("backbutton",function(e){var t=new Date;t.getTime()-o.getTime()<300?this.requestExitApp():(o=t,e.preventDefault(),!i||this.control("back").hasTriggers("click")||this.control("back").hasTriggers("up")||this.control("back").hasTriggers("down")?n&&(this.control(n).update(1),setTimeout(function(){this.control(n).update(0)}.bind(this),1)):setTimeout(function(){"undefined"!=typeof window&&window.__catlabAppBridge?window.__catlabAppBridge("minimize"):void 0!==window.plugins.appMinimize?window.plugins.appMinimize.minimize():this.exitApp()}.bind(this),350))}.bind(this),!1)},e.exitApp=function(){"undefined"!=typeof window&&window.__catlabAppBridge?window.__catlabAppBridge("exit"):navigator.app.exitApp()},e.confirm=function(e,t){navigator.notification.confirm(e,function(e){t(1===e)})},e.getDefaultKeys=function(){return[{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.hasDisplay=function(){return!1},e.hasKeyboardInput=function(){return!0},e.hasTouchInput=function(){return!0},t}),define("CatLab/Webremote/Models/Users/AndroidRemoteUser",["CatLab/Webremote/Models/Users/CordovaUser"],function(e){function t(e,t,n){this.initializeKeyboardUser({id:"cordova",keys:e}),this.initializeBackButtonExit(t,n)}e=((t.prototype=Object.create(e.prototype)).constructor=t).prototype;return e.getDefaultKeys=function(){return[{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.getPortalControls=function(){return{start:"start",back:"back",toggleActive:"up",authenticate:"down",left:"left",right:"right"}},e.hasDisplay=function(){return!1},e.hasKeyboardInput=function(){return!1},e.hasTouchInput=function(){return!1},this.getType=function(){return"android-keyboard"},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/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/PlayerPool",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/Models/Users/KeyboardUser","CatLab/Webremote/Models/Users/DummyUser","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/Messages/NavigateableProxy"],function(e,s,t,a,o,l,n){function i(){this.initializeEventable(),this.reset()}e=i.prototype=new e;return e.reset=function(){this.users=[],this.connectController=null,this._playercount=0,this.maxPlayers=8,this.keyboardUser=null,this.started=!1,this.Webcontrol||(this.Webcontrol=new t)},e.initialize=function(e){return this.initializeWebcontrol(e=void 0===e?{}:e)},e.initializeWebcontrol=function(t){var e,n=new s,i=this,o=void 0!==t.headless&&!!t.headless,r=new s;return o||void 0===t.portalAssets?r.resolve():(e=new l(t.portalAssets),this.Webcontrol.setViewFactory(e).then(function(){r.resolve()})),r.then(function(){var e=t.webcontrolOptions||{};o&&(e.headless=!1),i.Webcontrol.initialize(e).then(function(){t.oauth&&i.Webcontrol.oAuth(t.oauth),void 0!==t.keyboard&&!t.keyboard||(i.keyboardUser=new a,i.Webcontrol.addCustomControl(i.keyboardUser),i.keyboardUser.on("login",function(){i.trigger("keyboard:login")}),i.Webcontrol.enableGamepads()),n.resolve()})}),n.promise()},e.getConnectController=function(n){this.reset();var i=this,e=(this._pendingPortalClose=null,this._portalOpening=!0,this.Webcontrol.portalController(n)),t=void 0!==n.start?n.start:function(){};return n.start=function(e){e.forEach(function(e){e.setActive(!0),i.clearConnectScreen(),i.addUser(e)}),t(e)},e.promise.then(function(e){var t;i._portalOpening=!1,i.connectController=e,i._pendingPortalClose?(t=i._pendingPortalClose,i._pendingPortalClose=null,i.closeConnectController(t)):("function"==typeof e.on&&(e.on("active:count",function(e){i.trigger("portal:active:count",e)}),e.on("users:change",function(e){i.trigger("portal:users",e)}),"function"==typeof e.updateUsers)&&e.updateUsers(),n.maxPlayers&&e.setMaxPlayers(n.maxPlayers))}),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.addUser=function(e){this.users.push(e),this._playercount++,this.trigger("change:length",this._playercount)},e.countActivePlayers=function(){for(var e=0,t=0;t<this.users.length;t++)this.users[t].isActive()&&e++;return e},e.getAccessTokens=function(){for(var e=new s,t=[],n=this.Webcontrol.getUsers(),i=0;i<n.length;i++)n[i].isAuthenticated()&&t.push(n[i].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.setKeyboardUser=function(e){e!==this.keyboardUser&&(this.keyboardUser&&this.keyboardUser.setActive(!1),this.keyboardUser=e)},e.activateKeyboardUser=function(e){this.keyboardUser&&this.keyboardUser.setActive(!0)},e.hasKeyboardPlayer=function(){return!!this.keyboardUser},e.getNavigationUsers=function(e){var t=this.Webcontrol.getUsers();return e?t:t.filter(function(e){return!e.hasDisplay()})},e.startGame=function(){this.started=!0;for(var e=this.Webcontrol.getUsers(),t=0;t<e.length;t++)e[t].isActive()&&e[t].setView("catlab-game-starting");this.trigger("game:start")},e.newGroup=function(e,t,n){var i=new s,e=this.Webcontrol.createGroup({name:e,department:t,additionalProperties:n});return i.resolve(e),i.promise()},e.createDummyUser=function(e,t,n){var i=new o(e||"Dummy");return this.Webcontrol.addCustomControl(i),this.trigger("player:dummy:created",i,!0===t,n||{}),{id:"function"==typeof i.getId?i.getId():null,nickname:"function"==typeof i.getNickname?i.getNickname():e||"Dummy"}},e.showIndexScreen=function(){var e=new s;return e.resolve(),e.promise()},e.disconnect=function(){this.Webcontrol.disconnect()},i}),define("CatLab/Webremote/PlayerPool/KeyboardUserShim",[],function(){function t(e,t){this._id=e,this._worker=t,this._listeners={},this._label=e,this._labelType=null,this._domElements=[]}function n(e){this._worker=e,this._controls={}}function e(e){this._worker=e,this._controls={},this._events={},this._active=!1,this._accessToken=null,this._authenticated=!1,this.currentView=new n(e)}var i=t.prototype,o=(i.click=function(e){return this.on("click",e)},i.on=function(e,t){return void 0===this._listeners[e]&&(this._listeners[e]=[]),this._listeners[e].push(t),this},i.off=function(e){return void 0===e?this._listeners={}:this._listeners[e]=[],this},i.update=function(e,t){this._worker.postMessage({type:"keyboard:control:update",controlId:this._id,value:e,isClick:t})},i.getLabel=function(e){return(e=void 0===e?!0:e)?'<span class="control-label '+(this._labelType||"")+'">'+this._label+"</span>":this._label},i.addDomElement=function(e){function t(){n._trigger("click"),n._worker.postMessage({type:"keyboard:control:update",controlId:n._id,value:1,isClick:!1}),n._worker.postMessage({type:"keyboard:control:update",controlId:n._id,value:0,isClick:!0})}var n=this;return e&&e.addEventListener&&e.addEventListener("click",t),this._domElements.push({element:e,listener:t}),this},i.clearDomElements=function(){for(var e=0;e<this._domElements.length;e++){var t=this._domElements[e];t.element&&t.element.removeEventListener&&t.element.removeEventListener("click",t.listener)}return this._domElements=[],this},i._trigger=function(e){e=this._listeners[e];e&&e.slice().forEach(function(e){try{e()}catch(e){console.error(e)}})},n.prototype.changeValue=function(e,t){this._worker.postMessage({type:"keyboard:view:changeValue",key:e,value:t})},n.prototype.control=function(e){return void 0===this._controls[e]&&(this._controls[e]=new o(e,this._worker)),this._controls[e]},function(e,t){this._id=e,this._worker=t}),i=(o.prototype.update=function(e,t){this._worker.postMessage({type:"keyboard:view:control:update",controlId:this._id,value:e,isClick:t})},e.prototype);return i.isShim=!0,i.isActive=function(){return this._active},i.isAuthenticated=function(){return this._authenticated},i.getAccessToken=function(){return this._accessToken},i.login=function(e){this._worker.postMessage({type:"keyboard:login",data:e})},i.setActive=function(e){this._worker.postMessage({type:"keyboard:setActive",value:!!e})},i.setNickname=function(e){this._worker.postMessage({type:"keyboard:setNickname",name:e})},i.resumeListening=function(){this._worker.postMessage({type:"keyboard:resumeListening"})},i.stopListening=function(){this._worker.postMessage({type:"keyboard:stopListening"})},i.control=function(e){return void 0===this._controls[e]&&(this._controls[e]=new t(e,this._worker)),this._controls[e]},i.on=function(e,t){return void 0===this._events[e]&&(this._events[e]=[]),this._events[e].push(t),this},i.once=function(e,t){function n(){i.off(e,n),t.apply(this,arguments)}var i=this;return this.on(e,n)},i.off=function(e,t){return void 0===e?this._events={}:void 0===t?this._events[e]=[]:this._events[e]&&-1!==(t=this._events[e].indexOf(t))&&this._events[e].splice(t,1),this},i._triggerEvent=function(e){e=this._events[e];e&&e.slice().forEach(function(e){try{e()}catch(e){console.error(e)}})},i.handleMessage=function(e){switch(e.type){case"keyboard:state":if(void 0!==e.active&&(this._active=e.active),void 0!==e.accessToken&&(this._accessToken=e.accessToken),void 0!==e.authenticated&&(this._authenticated=e.authenticated),e.labels)for(var t in e.labels){var n;e.labels.hasOwnProperty(t)&&((n=this.control(t))._label=e.labels[t].label||t,n._labelType=e.labels[t].type||null)}break;case"keyboard:control:click":var i=e.controlId;this._controls[i]&&this._controls[i]._trigger("click");break;case"keyboard:login":void 0!==e.accessToken&&(this._accessToken=e.accessToken),this._authenticated=!0,this._triggerEvent("login")}},e}),define("CatLab/Webremote/PlayerPool/PlayerPoolWorker",["CatLab/Webremote/Tools/Deferred","CatLab/Webremote/PlayerPool/PlayerPool","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/Gamepads/GamepadAPI"],function(s,e,a,t){function n(){this.playerpool=new e,this.navProxy=null}var i=n.prototype;return i.start=function(e){var i=self,e=e||{};e.headless=!0,this.bootstrapAuthStorage(e.authStorage||{}),this.initializeStorageBridge(),this.initializeAppBridge(),this.playerpool.initialize(e).then(function(){this.playerpool.Webcontrol.on("game:initialized",function(){this.sendConnectInformation()}.bind(this)),this.sendConnectInformation(),this.initializeKeyboardBridge(),i.onmessage=function(n){if(void 0!==n.data.type)switch(n.data.type){case"catlab:keyboard":var e="down"===n.data.action?"keydown":"keyup";return void("undefined"!=typeof document&&document.dispatchEvent&&document.dispatchEvent({type:e,key:n.data.key,keyCode:n.data.keyCode,code:n.data.code,preventDefault:function(){},stopPropagation:function(){}}));case"keyboard:control:update":case"keyboard:view:changeValue":case"keyboard:view:control:update":case"keyboard:login":case"keyboard:setActive":case"keyboard:setNickname":case"keyboard:resumeListening":case"keyboard:stopListening":return void this.handleKeyboardMessage(n.data);case"webcontrol:publicConnectInfo":return void this.playerpool.setPublicConnectInfo(n.data.data);case"catlab:event":return void("undefined"!=typeof document&&document.dispatchEvent&&document.dispatchEvent({type:n.data.event,preventDefault:function(){},stopPropagation:function(){}}));case"gamepad:connect":return void t.remoteConnect(this.playerpool.Webcontrol,n.data.index,n.data.id);case"gamepad:button":return void t.remoteButton(n.data.index,n.data.control,n.data.value)}void 0!==n.data.a&&this.dispatch(n.data.a,n.data.data,function(e){try{i.postMessage({cb:n.data.cb,data:e})}catch(e){if("DataCloneError"!==e.name)throw e;var t=n.data.a;n.data.data&&n.data.data.method&&(t+=" ("+n.data.data.method+")"),console.warn('[PlayerPoolWorker] DataCloneError responding to "'+t+'": response contains non-cloneable values. Sending null.',e),i.postMessage({cb:n.data.cb,data:null})}})}.bind(this),this.playerpool.on("user:join",function(){this.triggerEvent("user:join")}.bind(this)),this.playerpool.on("change:length",function(e){this.triggerEvent("change:length",e)}.bind(this)),this.playerpool.on("change:maxconnections",function(e){this.triggerEvent("change:maxconnections",e)}.bind(this)),this.playerpool.on("portal:active:count",function(e){this.triggerEvent("portal:active:count",e)}.bind(this)),this.playerpool.on("portal:users",function(e){this.triggerEvent("portal:users",e)}.bind(this)),i.postMessage({cb:"initialized"})}.bind(this))},i.bootstrapAuthStorage=function(e){if("undefined"!=typeof localStorage&&e)for(var t in e)e.hasOwnProperty(t)&&null!==e[t]&&localStorage.setItem(t,e[t])},i.initializeStorageBridge=function(){"undefined"!=typeof window&&(window.__catlabStorageBridge=function(e){self.postMessage({type:"storage:sync",data:e})})},i.initializeAppBridge=function(){"undefined"!=typeof window&&(window.__catlabAppBridge=function(e){self.postMessage({type:"app:action",action:e})})},i.sendConnectInformation=function(){this.sendEvent("connectInfo:change",{connectToken:this.playerpool.Webcontrol.getConnectToken(),connectTokenForDisplay:this.playerpool.Webcontrol.getConnectTokenForDisplay(),connectUrl:this.playerpool.Webcontrol.getConnectURL(),server:""})},i.sendEvent=function(e,t){try{self.postMessage({e:e,data:t})}catch(t){if("DataCloneError"!==t.name)throw t;console.warn('[PlayerPoolWorker] DataCloneError sending "'+e+'". Event data contains non-cloneable values. Skipping.')}},i.triggerEvent=function(){var e=Array.prototype.slice.call(arguments);this.sendEvent(e.shift(),e)},i.initializeKeyboardBridge=function(){var t=this.playerpool.keyboardUser;if(t){this.sendKeyboardState();for(var e=t.getAvailableControls(),n=0;n<e.length;n++)(e=>{t.control(e).on("click",function(){self.postMessage({type:"keyboard:control:click",controlId:e})})})(e[n]);t.on("login",function(){self.postMessage({type:"keyboard:login",accessToken:t.getAccessToken(),authenticated:t.isAuthenticated()})}),t.on("active:change",function(){self.postMessage({type:"keyboard:state",active:t.isActive(),accessToken:t.getAccessToken()})})}},i.sendKeyboardState=function(){var e=this.playerpool.keyboardUser;if(e){for(var t={},n=e.getAvailableControls(),i=0;i<n.length;i++){var o=n[i],r=e.control(o);t[o]=r.getLabelData()}self.postMessage({type:"keyboard:state",active:e.isActive(),accessToken:e.getAccessToken(),authenticated:e.isAuthenticated(),labels:t})}},i.handleKeyboardMessage=function(e){var t=this.playerpool.keyboardUser;if(t)switch(e.type){case"keyboard:control:update":t.control(e.controlId).update(e.value,e.isClick);break;case"keyboard:view:changeValue":t.currentView&&t.currentView.changeValue(e.key,e.value);break;case"keyboard:view:control:update":t.currentView&&t.currentView.control(e.controlId).update(e.value,e.isClick);break;case"keyboard:login":t.login(e.data);break;case"keyboard:setActive":t.setActive(e.value);break;case"keyboard:setNickname":t.setNickname(e.name);break;case"keyboard:resumeListening":"function"==typeof t.resumeListening&&t.resumeListening();break;case"keyboard:stopListening":"function"==typeof t.stopListening&&t.stopListening()}else console.warn("[PlayerPoolWorker] Keyboard message but no KeyboardUser.")},i.dispatch=function(e,i,t){switch(e){case"webcontrol:setup":this.workerId=i.workerId,this.playerpool.Webcontrol.getMessageBus().toView=function(e,t,n){self.postMessage({id:i.workerId,type:"webcontrol:message",action:e,content:t,listener:n})};break;case"webcontrol:message":this.playerpool.Webcontrol.getMessageBus().handleControllerMessage(i.action,i.content);break;case"webcontrol:portal":var n=i.content||{};n.start=function(e){e=e.map(function(e){return{id:e.getId?e.getId():null,accessToken:e.getAccessToken?e.getAccessToken():null}});self.postMessage({type:"portal:game:start",users:e})},n.back=function(){self.postMessage({type:"portal:game:back"})},this.playerpool.getConnectController(n);break;case"webcontrol:portal:close":this.playerpool.closeConnectController(i.reason);break;case"webcontrol:authentication":n=this.playerpool.keyboardUser;n&&this.playerpool.Webcontrol.authenticationController(n,i.content||{}).controller.on("close",function(){self.postMessage({e:"authentication:close"})});break;case"call":var o,n=i.method,r=(i.args||[]).map(function(e){var t;return e&&"object"==typeof e&&"string"==typeof e.__remoteCallback?(t=e.__remoteCallback,function(){self.postMessage({cb:t,data:Array.prototype.slice.call(arguments),keep:!0})}):e});if("function"==typeof this.playerpool[n]){try{o=this.playerpool[n].apply(this.playerpool,r)}catch(e){t({__workerCallError:e&&e.message?e.message:String(e)||"Unknown worker error"});break}s.when(o).done(function(e){t(e)}).fail(function(e){t({__workerCallError:e&&e.message?e.message:String(e)||"Unknown worker error"})})}else console.warn("[PlayerPoolWorker] Unknown method:",n),t(null);break;case"ping":t({pong:!0});break;case"enableNavigation":r=this.playerpool.getNavigationUsers(i.includeDisplayUsers);this.navProxy&&this.navProxy.destroy(),this.navProxy=new a(this.playerpool.Webcontrol.getMessageBus()),r.forEach(function(e){e=e.setView("catlab-nes");this.navProxy.addView(e)}.bind(this)),t({});break;default:console.warn("[PlayerPoolWorker] Unknown action:",e),t&&t(null)}},n}),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.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/PlayerPool/Managers/SynchronizedManager",["CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/PlayerPool/PlayerPool","CatLab/Webremote/Tools/Deferred"],function(e,t,n){function i(){this.initializeEventable(),this.playerpool=new t,this._mode="regular"}e=i.prototype=new e;return e.initialize=function(e){this.initializeManager();e=this.playerpool.initialize(e);return e.then(function(){var t=function(){this.trigger("connectInfo:change",{server:this.settings?this.settings.host:"",connectToken:this.playerpool.Webcontrol.getConnectToken(),connectUrl:this.playerpool.Webcontrol.getConnectURL(),connectTokenForDisplay:this.playerpool.Webcontrol.getConnectTokenForDisplay()})}.bind(this);this.playerpool.Webcontrol.getProviderSettings().then(function(e){this.settings=e,t()}.bind(this)),this.playerpool.Webcontrol.on("game:initialized",function(){t()}),this.playerpool.on("user:join",function(){this.trigger("user:join")}.bind(this)),this.playerpool.on("change:length",function(e){this.trigger("change:length",e)}.bind(this)),this.playerpool.on("change:maxconnections",function(e){this.trigger("change:maxconnections",e)}.bind(this))}.bind(this)),e},e.call=function(){var e=Array.prototype.slice.call(arguments),t=e.shift();return n.when(this.playerpool[t].apply(this.playerpool,e))},e.enableNavigation=function(e,t){this._trackCurrentNavigation(e,t);t=this.playerpool.getNavigationUsers(t);return e.setUsers(t)},e._clearCurrentNavigation=function(){this._currentNavigatable&&"function"==typeof this._currentNavigatable.setUsers&&this._currentNavigatable.setUsers([])},e.getConnectScreen=function(e){var t=this.playerpool.getConnectController(e);return this.playerpool.Webcontrol.portalView(t.messageBus,e)},e.clearConnectScreen=function(e){return this.playerpool.clearConnectScreen(e)},e.activateKeyboardUser=function(e){return this.playerpool.activateKeyboardUser(e)},e.setKeyboardUser=function(e){return this.playerpool.setKeyboardUser(e)},e.createDummyUser=function(e,t,n){return this.playerpool.createDummyUser(e,t,n)},e.getAuthenticationScreen=function(e){var t=this.playerpool.getAuthenticationController(e),n=this.playerpool.getNavigationUsers(!1);return this._authenticationKeyboardUser=t.controller.user||null,t.controller.setNavigatableUsers(n),t.controller.on("close",function(){this.trigger("authentication:close")}.bind(this)),this.playerpool.Webcontrol.authenticationView(t.controller.messageBus,e)},e.getAccessTokens=function(){return this.playerpool.getAccessTokens()},e.getKeyboardUser=function(){return this._authenticationKeyboardUser||this.playerpool.keyboardUser||null},e.countActivePlayers=function(){return this.playerpool.countActivePlayers()},e.disconnect=function(){this.playerpool.disconnect();var e=new n;return e.resolve(),e.promise()},Object.defineProperty(e,"length",{get:function(){return this.playerpool._playercount}}),Object.defineProperty(e,"actualPlayersLength",{get:function(){return this.playerpool._playercount}}),i}),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/PlayerPool/Managers/WebworkerManager",["CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/PlayerPool/KeyboardUserShim","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/Providers/Dummy","CatLab/Webremote/Gamepads/GamepadAPI"],function(e,s,t,i,a,l,o,c){function n(e){this.initializeEventable(),this.callbacks={},this._pendingDispatches={},this._persistentCallbacks={},this.callbackCount=1,this._length=0,this._connectedDevices=null,this._actualPlayersLength=0,this._mode="regular",this.keyboardShim=null,this.currentNavigationView=null,this.worker=null,this._preBootQueue=[],this._disconnected=!1,this._managerOptions=e||{}}var h=new t,r=["users","currentuser"],t=n.prototype=new e;return t._buildWorkerInitOptions=function(e){var t={};if((e=e||{}).webcontrolOptions){var n,i,o={};for(n in e.webcontrolOptions)e.webcontrolOptions.hasOwnProperty(n)&&("function"!=typeof(i=e.webcontrolOptions[n])&&"object"!=typeof i||null===i)&&(o[n]=i);t.webcontrolOptions=o}return e.oauth&&(t.oauth=e.oauth),t.authStorage=this.getPersistentAuthStorageSnapshot(),void 0!==e.keyboard&&(t.keyboard=e.keyboard),"string"==typeof e.controlUserType&&(t.controlUserType=e.controlUserType),t.poolNumber="number"==typeof this.poolNumber?this.poolNumber:1,t},t.initialize=function(i){this.initializeManager(),this._initOptions=i,this._disconnected=!1,this._localInput=void 0===i.localInput||!!i.localInput;var o=new s,r=this;return this.initializeWebcontrol(i).then(function(){i.oauth&&h.oAuth(i.oauth),r.registerCallback(function(){r._localInput&&r.worker.postMessage({a:"webcontrol:setup",data:{workerId:r.webworkerId}}),r._flushPreBootQueue(),o.resolve()},"initialized");function t(e){e.data&&"worker:modules-ready"===e.data.type&&(r.worker.removeEventListener("message",t),r.worker.postMessage({type:"worker:init",options:n}))}var e=r._managerOptions.workerUrl||"scripts/webworker.js",n=(r.worker=new Worker(e),r.worker.onerror=function(e){console.error("[WebworkerManager] Worker failed to initialize:",e),r.trigger("worker:error",e)},r.webworkerId=Math.random().toString(36).substring(7),r._buildWorkerInitOptions(i));r.worker.addEventListener("message",t),r._localInput&&(h.getMessageBus().toController=function(e,t){r.worker.postMessage({a:"webcontrol:message",data:{action:e,content:t}})}),r.worker.onmessage=function(e){var t;void 0===e.data.type||"webcontrol:message"!==e.data.type||e.data.id!==r.webworkerId?void 0!==e.data.type&&0===e.data.type.indexOf("keyboard:")&&r.keyboardShim?r.keyboardShim.handleMessage(e.data):void 0===e.data.type||"app:action"!==e.data.type?void 0===e.data.type||"storage:sync"!==e.data.type?void 0===e.data.cb?void 0!==e.data.e&&(t=[e.data.e],Array.isArray(e.data.data)?t=t.concat(e.data.data):void 0!==e.data.data&&t.push(e.data.data),r._syncLengthFromPayload(e.data.e,t[1]),r.trigger.apply(r,t)):r.handleCallback(e.data):r.applyPersistentStorageSync(e.data.data||{}):r.handleAppAction(e.data.action):r.currentNavigationView&&l.handleMessage(e.data.action,e.data.content,r.currentNavigationView)||h.getMessageBus().handleViewMessage(e.data.action,e.data.content)},r.on("change:length",function(e){"number"!=typeof e&&r.call("countActivePlayers").then(function(e){r._length=e})}),r._localInput&&(window.addEventListener("keydown",function(e){r.worker.postMessage({type:"catlab:keyboard",key:e.key,keyCode:e.keyCode,code:e.code,action:"down"})}),window.addEventListener("keyup",function(e){r.worker.postMessage({type:"catlab:keyboard",key:e.key,keyCode:e.keyCode,code:e.code,action:"up"})}),r.keyboardShim=new a(r.worker),c.initializeForwarding(function(e){r.worker.postMessage(e)}),"undefined"!=typeof document)&&document.addEventListener("backbutton",function(e){e&&e.preventDefault&&e.preventDefault(),r.worker.postMessage({type:"catlab:event",event:"backbutton"})},!1)}),o.promise()},t.getPersistentAuthStorageSnapshot=function(){var n={};return"undefined"!=typeof window&&void 0!==window.localStorage&&r.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!==r.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.handleAppAction=function(e){switch(e){case"minimize":return"undefined"!=typeof window&&window.plugins&&window.plugins.appMinimize?void window.plugins.appMinimize.minimize():void this.handleAppAction("exit");case"requestExit":var t,n;return window.onbeforeunload?void((t=window.onbeforeunload({}))&&(n=this)._confirmDialog(t,function(e){e&&n.handleAppAction("exit")})):void this.handleAppAction("exit");case"exit":return"undefined"!=typeof navigator&&navigator.app&&"function"==typeof navigator.app.exitApp?void navigator.app.exitApp():void window.close()}},t._confirmDialog=function(e,t){"undefined"!=typeof navigator&&navigator.notification&&navigator.notification.confirm?navigator.notification.confirm(e,function(e){t(1===e)}):t(window.confirm(e))},t.initializeWebcontrol=function(e){var t=new s,n=Object.assign({},e.webcontrolOptions||{},{provider:new o});return e.portalAssets?(e=new i(e.portalAssets),h.setViewFactory(e).then(function(){h.initialize(n).then(function(){t.resolve()})})):h.initialize(n).then(function(){t.resolve()}),t.promise()},t.getWebcontrol=function(){return h},t.getKeyboardShim=function(){return this.keyboardShim},t.getKeyboardUser=function(){return this.keyboardShim||null},t.dispatch=function(e,t){var n,i=new s,o=this;return!this.worker&&this._disconnected?i.reject(new Error("[WebworkerManager] dispatch after disconnect: "+e)):(n=this.registerCallback(function(e){delete o._pendingDispatches[n],e&&e.__workerCallError?i.reject(new Error(e.__workerCallError)):i.resolve(e)}),e=(this._pendingDispatches[n]=i,{a:e,cb:n,data:t}),this.worker?this.worker.postMessage(e):this._preBootQueue.push(e)),i.promise()},t._failPendingDispatches=function(t){this._preBootQueue=[];var n=this._pendingDispatches;this._pendingDispatches={},Object.keys(n).forEach(function(e){delete this.callbacks[e],n[e].reject(t)}.bind(this))},t._flushPreBootQueue=function(){var e,t;this.worker&&(e=this._preBootQueue,this._preBootQueue=[],t=this,e.forEach(function(e){t.worker.postMessage(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=this,n=new s,i=!1,o=null,r=this.registerCallback(function(e){i||(i=!0,clearTimeout(o),delete t._pendingDispatches[r],n.resolve(e))});return this._pendingDispatches[r]=n,o=setTimeout(function(){i||(i=!0,delete t.callbacks[r],delete t._pendingDispatches[r],n.reject(new Error("[WebworkerManager] ping timeout")))},e),this.worker.postMessage({a:"ping",cb:r,data:{}}),n.promise()},t.registerCallback=function(e,t,n){return void 0===t&&(t="cb:"+ ++this.callbackCount),this.callbacks[t]=e,n&&(this._persistentCallbacks[t]=!0),t},t.handleCallback=function(e){void 0!==this.callbacks[e.cb]&&(this.callbacks[e.cb](e.data),e.keep||this._persistentCallbacks[e.cb]||delete this.callbacks[e.cb])},t._encodeCallbackArg=function(t){return{__remoteCallback:this.registerCallback(function(e){t.apply(null,Array.isArray(e)?e:[e])},void 0,!0)}},t.call=function(){for(var e=Array.prototype.slice.call(arguments),t=e.shift(),n=[],i=0;i<e.length;i++)n.push("function"==typeof e[i]?this._encodeCallbackArg(e[i]):e[i]);return this.dispatch("call",{method:t,args:n})},t.enableNavigation=function(e,t){this._trackCurrentNavigation(e,t),this.currentNavigationView=e,this.dispatch("enableNavigation",{includeDisplayUsers:t})},t._clearCurrentNavigation=function(){this.currentNavigationView=null},t.openPortal=function(e){var t={};if(e)for(var n in e)e.hasOwnProperty(n)&&"function"!=typeof e[n]&&(t[n]=e[n]);var i="function"==typeof e.start?e.start:function(){},o="function"==typeof e.back?e.back:function(){},r=this,s=function(e){void 0!==e.data.type&&("portal:game:start"===e.data.type?(r.worker.removeEventListener("message",s),i(e.data.users||[])):"portal:game:back"===e.data.type&&(r.worker.removeEventListener("message",s),o()))};this.worker.addEventListener("message",s),this.dispatch("webcontrol:portal",{content:t})},t.finalizePortal=function(e){this.dispatch("webcontrol:portal:close",{reason:e})},t.getConnectScreen=function(t){this.openPortal(t);var n=h.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},h.portalView(n,t)},t.setPublicConnectInfo=function(e){this.worker&&this.worker.postMessage({type:"webcontrol:publicConnectInfo",data:e})},t.clearConnectScreen=function(){return this.call("clearConnectScreen")},t.activateKeyboardUser=function(e){return this.call("activateKeyboardUser",e)},t.setKeyboardUser=function(e){return this.call("setKeyboardUser",e)},t.createDummyUser=function(e,t,n){return this.call("createDummyUser",e,t,n||{})},t.getAuthenticationScreen=function(e){var t,n={};for(t in e=e||{})e.hasOwnProperty(t)&&"function"!=typeof e[t]&&(n[t]=e[t]);this.dispatch("webcontrol:authentication",{content:n});var i=h.getMessageBus();return h.authenticationView(i,e)},t.getAccessTokens=function(){return this.call("getAccessTokens")},t.countActivePlayers=function(){return this.call("countActivePlayers")},t.disconnect=function(){this._disconnected=!0,this._preBootQueue=[],this.worker&&(this.worker.terminate(),this.worker=null);var e=new s;return e.resolve(),e.promise()},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}}),n}),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/Managers/WorkerManager",["CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/PlayerPool/Managers/WebworkerManager","CatLab/Webremote/PlayerPool/Managers/SynchronizedManager","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/PlayerPool/Protocol/whenAllSettled"],function(e,t,n,s,i){function o(e){this.initializeEventable(),this.workers=[],this.useFallback=!1,this._mode="regular",this._initOptions=null,this._totalLength=0,this._managerOptions=e||{}}e=o.prototype=new e;return e.constructor=o,e.initialize=function(e){var t,n,i,o,r;return this.initializeManager(),this._initOptions=e,"undefined"==typeof Worker?(console.warn("[WorkerManager] WebWorkers not supported, falling back."),this._initFallback(e)):(t=new s,n=!1,o=(i=this)._createWorkerManager(),r=function(){n||(n=!0,i.workers=[],i._initFallback(e).done(function(){t.resolve()}).fail(function(e){t.reject(e)}))},o.initialize(e).done(function(){n||(n=!0,i._started=!0,t.resolve())}).fail(function(e){console.error("[WorkerManager] Primary worker failed to initialize:",e),r()}),o.on("worker:error",function(e){console.error("[WorkerManager] Primary worker failed:",e),1!==i.workers.length||n||r()}),t.promise())},e._initFallback=function(e){this.useFallback=!0,this._started=!0;var t=new n;return this.workers=[t],this._bindWorkerEvents(t),t.initialize(e)},e._createWorkerManager=function(){var e=new t(this._managerOptions);return this.workers.push(e),this._bindWorkerEvents(e),e},e._getPrimaryWorker=function(){return this.workers[0]},e._bindWorkerEvents=function(n){var i=this;["user:join","change:maxconnections","change:maxplayers","authentication:close"].forEach(function(t){n.on(t,function(){var e=Array.prototype.slice.call(arguments);e.unshift(t),i.trigger.apply(i,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.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.getAuthenticationScreen=function(){return this._getPrimaryWorker().getAuthenticationScreen()},e.getAccessTokens=function(){return this._getPrimaryWorker().getAccessTokens()},e.countActivePlayers=function(){return this._getPrimaryWorker().countActivePlayers()},e.getKeyboardShim=function(){var e=this._getPrimaryWorker();return e&&"function"==typeof e.getKeyboardShim?e.getKeyboardShim():null},e.getWebcontrol=function(){var e=this._getPrimaryWorker();return e&&"function"==typeof e.getWebcontrol?e.getWebcontrol():e&&e.playerpool?e.playerpool.Webcontrol:null},e.disconnect=function(){var e=new s,t=this.workers.map(function(e){return e.disconnect()});return this.workers=[],i(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}}),o}),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(){},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)}}};return 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(u,r,d,f){function i(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)))}function o(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 s(c,n,e){var i=(e=>{if("function"==typeof e)return e;var t=r[e||"first"];if("function"!=typeof t)throw new Error("[ManifestProxy] Unknown aggregator: "+e);return t})(n.aggregate),o=n.route||"all",h="number"==typeof n.timeoutMs?n.timeoutMs:e&&"number"==typeof e.defaultTimeoutMs?e.defaultTimeoutMs:1e4;return function(){function e(i){var o,e;0!==i.length?(o=i.map(function(e){return r.workers.indexOf(e)}),e=i.map(function(e){return n=s,"function"==typeof(e=e)[t=c]?e[t].apply(e,n):e.call.apply(e,[t].concat(n));var t,n}),f(e,h).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:[]})}function t(){return"leastFullOrSpawn"===o?r.workers.filter(function(e){return!e._bootInFlight}):r.workers}var r=this,s=Array.prototype.slice.call(arguments),a=(n.replayOnSpawn&&"function"==typeof r._recordReplayableCall&&r._recordReplayableCall(c,s),new u),l=function(e,t){var n;try{n=i(e,s,t)}catch(e){return void a.reject(e)}a.resolve(n)};return"leastFullOrSpawn"===o&&"function"==typeof r._ensureRosterCapacity?r._ensureRosterCapacity().always(function(){e(d.select(o,t()))}):e(d.select(o,t())),a.promise()}}var a=["applyManifest","getWorkerForToken","call","dispatch","initialize","disconnect","restore"];return{applyToCoordinator:function(t,n){o(t,"applyToCoordinator"),Object.keys(n.methods).forEach(function(e){if(-1!==a.indexOf(e)&&!i(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){i(t,e)||(t[e]=s(e,n.methods[e],n),t._manifestGeneratedMethods.push(e))})},applyToClient:function(t,e){o(t,"applyToClient"),Object.keys(e.methods).forEach(function(e){i(t,e)||(t[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"],function(t,n,s){function e(e){t.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 i=e.prototype=new t;return i.constructor=e,i.applyManifest=function(e){this._manifest=e,n.applyToCoordinator(this,e)},i._bindWorkerEvents=function(i){t.prototype._bindWorkerEvents.call(this,i),"number"!=typeof i.poolNumber&&(i.poolNumber=++this._poolSequence);var o=this;this._manifest&&this._manifest.events&&this._manifest.events.forEach(function(t){var n=o._manifest.barrierEvents&&o._manifest.barrierEvents[t];"function"!=typeof n?i.on(t,function(){var e=Array.prototype.slice.call(arguments);e.unshift(t),o.trigger.apply(o,e)}):i.on(t,function(){var e=Array.prototype.slice.call(arguments);o._recordBarrierEvent(t,String(n.apply(null,e)),i,e)})}),i.on("worker:error",function(e){o._handleWorkerFailure(i,e)}),i.on("change:connections",function(){o._checkCapacity()}),i.on("portal:active:count",function(e){i._portalActiveCount=e||0,o._syncPortalCounts()}),i.on("portal:users",function(e){i._portalUsers=e||[],o._syncPortalUsers()})},i.getWorkerForToken=function(e){return this.tokenRegistry[e]||null},i._onWorkerConnectInfo=function(e,t){t&&t.connectToken&&(e._lastConnectInfo=t,(this.tokenRegistry[t.connectToken]=e)===this.workers[this.workers.length-1])&&this._setPublicConnectInfo(t)},i._setPublicConnectInfo=function(e){this._publicConnectInfo=e,this.trigger("connectInfo:change",e);var t=this._getPrimaryWorker();t&&"function"==typeof t.setPublicConnectInfo&&t.setPublicConnectInfo(e)},i._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()},i._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"),i.trigger("pool:error:survived",{poolIndex:e,error:n}))}).fail(function(){t._probeInFlight=!1;var e=i.workers.indexOf(t);-1!==e&&i._killWorker(t,e,n)})):this._killWorker(t,e,n))},i._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{t.worker&&"function"==typeof t.worker.terminate&&t.worker.terminate()}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."),this.trigger("pool:all: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()},i._checkCapacity=function(){var e,t;this.useFallback||this._spawnInFlight||this._capacityExhausted||(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())},i._spawnNewWorker=function(){var i,o,r;return this._spawnInFlight&&this._spawnPromise?this._spawnPromise:(i=new s,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())},i._ensureRosterCapacity=function(){var e=new s;if(this.useFallback||this._capacityExhausted||0===this.workers.length)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()},i._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)},i._checkEventBarrier=function(e){var t,n=this._eventBarriers[e];n&&(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))))},i._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})},i._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)})})},i._afterSpawn=function(e){},i._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},i.getConnectScreen=function(t){var n,e,i,o,r=this;return this.useFallback?this._getPrimaryWorker().getConnectScreen(t):(n="function"==typeof t.start?t.start:function(){},e="function"==typeof t.back?t.back:function(){},this._portalActive=!0,this.workers.forEach(function(e){e._portalActiveCount=0,e._portalUsers=[]}),t.start=function(e){r._onPortalEnd("start",function(){n(e)})},t.back=function(){r._onPortalEnd("back",function(){e()})},o=(i=this._getPrimaryWorker()).getConnectScreen(t),this.workers.forEach(function(e){e!==i&&"function"==typeof e.openPortal&&e.openPortal(t)}),this._recordReplayableCall("openPortal",[t]),o)},i._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())},i._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))}))},i._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))},i._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)},i.clearConnectScreen=function(t){return this.workers.map(function(e){return e.clearConnectScreen(t)})[0]},Object.defineProperty(i,"actualPlayersLength",{get:function(){return this._totalActualPlayersLength}}),e}),define("CatLab/Webremote/FrontWebcontrol",["CatLab/Webremote/Config","CatLab/Webremote/Polyfills","CatLab/Webremote/Tools/Tracker","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Images","CatLab/Webremote/Models/Users/KeyboardUser","CatLab/Webremote/Models/Users/CordovaUser","CatLab/Webremote/Models/Users/AndroidRemoteUser","CatLab/Webremote/Models/Users/DummyUser","CatLab/Webremote/Providers/SocketIO","CatLab/Webremote/Providers/Airconsole","CatLab/Webremote/ViewFactory/ViewFactory","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/Messages/NavigateableProxy","CatLab/Webremote/PlayerPool/PlayerPool","CatLab/Webremote/PlayerPool/KeyboardUserShim","CatLab/Webremote/PlayerPool/PlayerPoolWorker","CatLab/Webremote/PlayerPool/Managers/Manager","CatLab/Webremote/PlayerPool/Managers/SynchronizedManager","CatLab/Webremote/PlayerPool/Managers/WebworkerManager","CatLab/Webremote/PlayerPool/Managers/WorkerManager","CatLab/Webremote/PlayerPool/Managers/PoolCoordinator","CatLab/Webremote/PlayerPool/Protocol/Aggregators","CatLab/Webremote/PlayerPool/Protocol/Router","CatLab/Webremote/PlayerPool/Protocol/ManifestProxy","CatLab/Webremote/PlayerPool/Protocol/whenAllSettled"],function(t,e,n,i,o,r,s,a,l,c,h,u,d,f,p,g,b,m,v,y,w,C,k,_,L,S,P,T,A){return{Config:function(e){t.set(e)},Tracker:n,Tools:i,Webcontrol:new r,OAuth2:o,Controls:{Keyboard:l,Cordova:c,AndroidRemote:h,Dummy:u},Controllers:{Webcontrol:r},Models:{User:u},Providers:{SocketIO:d,Airconsole:f},ViewFactories:{HtmlViewFactory:p,CreatejsViewFactory:g},Smileys:s,Images:new a,NavigateableProxy:b,PlayerPool:{PlayerPool:m,KeyboardUserShim:v,PlayerPoolWorker:y,Manager:w,SynchronizedManager:C,WebworkerManager:k,WorkerManager:_,PoolCoordinator:L,Protocol:{Aggregators:S,Router:P,ManifestProxy:T,whenAllSettled:A}}}}),define("webcontrol",["CatLab/Webremote/FrontWebcontrol"],function(e){return e}),define("CatLab/EaselHacks/AlphaMaskFilter",[],function(e){function t(e){var i=this;this.createjs=e,Object.defineProperty(e.DisplayObject.prototype,"mask",{get:function(){return this.forceMask},set:function(e){var t,n=this;e?(n.originalMask=e,t=i.getFilterFromMask(e,n),n.filters=[t],n.cache(0,0,500,500)):null!==e&&(n.filters=null,n.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)});
|