catlab-remote-client 1.3.6 → 1.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var io;define("CatLab/Webremote/Tools/Net",[],function(){return{loadJSON:function(e,t,i){var n=new XMLHttpRequest;n.onreadystatechange=function(){n.readyState===XMLHttpRequest.DONE&&200===n.status&&t&&t(JSON.parse(n.responseText))},n.onerror=function(e){e&&i(n,e)},n.open("GET",e,!0),n.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 i=0;i<e.length;i++)t(e[i]);else t(e)}function u(e){var n="pending",s=[],o=[],r=[],a=null,i={done:function(){for(var e=0;e<arguments.length;e++)if(arguments[e])if(c(arguments[e]))for(var t=arguments[e],i=0;i<t.length;i++)"resolved"===n&&t[i].apply(this,a),s.push(t[i]);else"resolved"===n&&arguments[e].apply(this,a),s.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],i=0;i<t.length;i++)"rejected"===n&&t[i].apply(this,a),o.push(t[i]);else"rejected"===n&&arguments[e].apply(this,a),o.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],i=0;i<t.length;i++)"pending"===n&&r.push(t[i]);else"pending"===n&&r.push(arguments[e]);return this},then:function(){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])},promise:function(e){if(null==e)return i;for(var t in i)e[t]=i[t];return e},state:function(){return n},debug:function(){console.log("[debug]",s,o,n)},isRejected:function(){return"rejected"===n},isResolved:function(){return"resolved"===n},pipe:function(e,t,i){return u(function(i){h(e,function(t){"function"==typeof t?l.done(function(){var e=t.apply(this,arguments);e&&"function"==typeof e?e.promise().then(i.resolve,i.reject,i.notify):i.resolve(e)}):l.done(i.resolve)}),h(t,function(t){"function"==typeof t?l.fail(function(){var e=t.apply(this,arguments);e&&"function"==typeof e?e.promise().then(i.resolve,i.reject,i.notify):i.reject(e)}):l.fail(i.reject)})}).promise()}},l={resolveWith:function(e){if("pending"===n){n="resolved";for(var t=a=1<arguments.length?arguments[1]:[],i=0;i<s.length;i++)s[i].apply(e,t)}return this},rejectWith:function(e){if("pending"===n){n="rejected";for(var t=a=1<arguments.length?arguments[1]:[],i=0;i<o.length;i++)o[i].apply(e,t)}return this},notifyWith:function(e){if("pending"===n)for(var t=a=1<arguments.length?arguments[1]:[],i=0;i<r.length;i++)r[i].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=i.promise(l);return e&&e.apply(t,[t]),t}return u.when=function(){var e;if(arguments.length<2)return((e=arguments.length?arguments[0]:void 0)&&"function"==typeof e.isResolved&&"function"==typeof e.isRejected?e:u().resolve(e)).promise();for(var i=arguments,n=u(),s=i.length,o=0,r=new Array(s),t=0;t<i.length;t++)(e=>{var t;i[e].done?i[e].done(function(){r[e]=arguments.length<2?arguments[0]:arguments,++o==s&&n.resolve.apply(n,r)}).fail(function(){n.reject(arguments)}):(t=i[e],i[e]=new Deferred,i[e].done(function(){r[e]=arguments.length<2?arguments[0]:arguments,++o==s&&n.resolve.apply(n,r)}).fail(function(){n.reject(arguments)}).resolve(t))})(t);return n.promise()},u}),define("CatLab/Webremote/Collections/ServerList",["CatLab/Webremote/Tools/Deferred"],function(s){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 s;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 i=new s;if(this.preferredServer)for(var e=0;e<this.servers.length;e++)if(this.servers[e].id==this.preferredServer)return i.resolve(this.servers[e]),i.promise();var n=!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"),n||(n=!0,i.resolve(t))}.bind(this))}.bind(this)),i.promise()},t.selectServer=function(e){this.selectedServerId=e},t.measureRequestSpeed=function(e){var t=new Date,i=new s,n=new XMLHttpRequest;return n.onreadystatechange=function(){var e;4==this.readyState&&200==this.status&&(e=(new Date).getTime()-t.getTime(),i.resolve(e))},n.open("GET",e),n.send(),i.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 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,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&&(this._options.serverlist=e.serverlist),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;this._initialized?t():null===this._options.serverlist||"http"!==this._options.serverlist.substring(0,4)?(this._initialized=!0,t()):"json"===this._options.serverlist.substring(this._options.serverlist.length-4)?i.loadJSON(this._options.serverlist,function(e){this._initialized=!0,this._options.serverlist=e,t()}.bind(this),function(e,t){alert("Failed to connect to "+this._options.serverlist+". Game cannot start."),console.log(t)}.bind(this)):((e=document.createElement("script")).onload=function(){this._initialized=!0,this._options.serverlist=getCatLabRemoteServers(),t()}.bind(this),e.onerror=function(){alert("Failed to connect to "+this._options.serverlist+". Game cannot start.")}.bind(this),e.src=this._options.serverlist,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 i=Object(e),n=1;n<arguments.length;n++){var s=arguments[n];if(null!=s)for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(i[o]=s[o])}return i})}),define("CatLab/Webremote/Tools/Tracker",[],function(){var s=function(e,t,i,n){},t=function(e){s("Page",e,"-",0)};return{setTracker:function(e){s=e},setPageMethod:function(e){t=e},track:function(e,t,i,n){s(e,t,i,n)},page:function(e){t(e)}}}),define("CatLab/Webremote/Tools/Tools",[],function(){var s,o;return{popup:function(e,t){var i=this,n=(t=t||!1,document.createElement("iframe"));n.style.margin=0,n.style.padding=0,n.style.border=0,n.style.position="absolute",n.style.width="100%",n.style.height="100%",n.style.left=0,n.style.top=0,n.src=e,(o=document.createElement("div")).style.margin=0,o.style.padding=0,o.style.border=0,o.style.position="absolute",o.style.width="100%",o.style.height="100%",o.style.left=0,o.style.top=0,o.style.zIndex=9999,o.onclick=function(){i.closePopup()},(s=document.createElement("div")).appendChild(n),s.style.margin=0,s.style.padding=0,s.style.border=0,s.style.position="absolute",s.style.zIndex=1e4,s.style.overflow="auto",s.style.background="white",s.style.boxSizing="border-box",t?(s.style.border="0 none black",s.style.left="0",s.style.top="0",s.style.width="100%",s.style.height="100%"):(s.style.border="5px solid black",s.style.left="10%",s.style.top="10%",s.style.width="80%",s.style.height="80%"),document.body.appendChild(o),document.body.appendChild(s)},oauth2PopupMethod:function(e,t){return window.open(e,"oauth:catlab-remote")},oauth2Popup:function(e,t){return this.oauth2PopupMethod(e,t)},closePopup:function(){s&&s.parentNode.removeChild(s),o&&o.parentNode.removeChild(o)},setOauth2Popup:function(e){return this.oauth2PopupMethod=e,this},sanitize:function(e){var t;return null==e?null:(t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"},String(e).replace(/[&<>"']/g,function(e){return t[e]}))},nl2br:function(e,t){return null==e?"":(e+"").replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,"$1"+(t||void 0===t?"<br />":"<br>")+"$2")},shuffle:function(e){for(var t,i,n=e.length-1;0<n;n--)t=Math.floor(Math.random()*(n+1)),i=e[n],e[n]=e[t],e[t]=i},getUuid:function(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)},findIndex:function(e,t){for(var i=0;i<e.length;i++)if(t(e[i]))return i;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,i){return e.match(new RegExp(".{1,"+t+"}","g")).join(i)}}}),define("CatLab/Webremote/Tools/Cookies",[],function(){var t={setCookie:function(e,t,i){return this.setItem(e,t,i)},getCookie:function(e){return this.getItem(e)},eraseCookie:function(e){return this.removeItem(e)},getItem:function(e){if("undefined"!=typeof document)return e&&this.hasOwnProperty(e)?unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"),"$1")):null},key:function(e){if("undefined"!=typeof document)return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/,"").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[e])},setItem:function(e,t,i){var n,s;e&&"undefined"!=typeof document&&(n="",i&&((s=new Date).setTime(s.getTime()+Math.round(24*i*60*60*1e3)),n="; expires="+s.toUTCString()),document.cookie=escape(e)+"="+escape(t)+"; expires="+n+"; path=/; SameSite=Strict;",this.updateLength())},length:0,removeItem:function(e){e&&this.hasOwnProperty(e)&&"undefined"!=typeof document&&(document.cookie=escape(e)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Strict;",this.length--)},hasOwnProperty:function(e){if("undefined"!=typeof document)return new RegExp("(?:^|;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(document.cookie)},updateLength:function(){var e;"undefined"!=typeof document&&document.cookie&&(e=document.cookie.match(/\=/g),t.length=e?e.length:0)}};return t.updateLength(),t}),define("CatLab/Webremote/Tools/Images",["CatLab/Webremote/Config"],function(s){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 i;return void 0!==t&&-1!==this.availableSizes.indexOf(t)||(t=this.availableSizes[0]),void 0===this.images[e+"_"+t]&&((i=new Image).crossOrigin="anonymous",i.src=this.getUrl(e,t),this.images[e+"_"+t]=i),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 i=e.split("/"),n=0;n<i.length;n++)"$SIZE"===i[n]&&(i[n]=t);return e=i.join("/"),s.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(i,n,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),n.shuffle(this.randomSmileys)}var s=e.prototype;return s.shouldHaveUniqueSmileys=function(){return this.takenAmount<this.smileyKeys.length/3},s.setTakenSmileys=function(e){this.taken=e},s.getTakenSmileys=function(e){if(!this.shouldHaveUniqueSmileys())return{};e=this.identifierToText(e);var t,i={};for(t in this.taken)this.taken.hasOwnProperty(t)&&this.taken[t]!==e&&(i[t]=this.taken[t]);return i},s.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),n.shuffle(this.randomSmileys),this.randomSmileys.shift();return t},s.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))},s.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--)},s.isAvailable=function(e){return!this.shouldHaveUniqueSmileys()||!!this.isExternalSmiley(e)||null==this.taken[e]},s.identifierToText=function(e){return JSON.stringify(e)},s.isExternalSmiley=function(e){return"http"===e.substring(0,4).toLowerCase()},s.getUrl=function(e){var t=this.getImageUrl(e);return t?this.isExternalSmiley(e)?e:i.getAssetsURL()+t:null},s.getImageUrl=function(e){return null===e?null:this.isExternalSmiley(e)?e:"smileys/"+e+".png"},s.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>"},s.getElement=function(e){var t;return null===e?null:((t=document.createElement("div")).innerHTML=this.getHtml(e),t.firstChild)},s.getImage=function(e){return null===e?null:this.images.getImage(this.getImageUrl(e))},s.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())})},s.getStringIdentifier=function(e){return e.type+":"+e.id},e}),define("CatLab/Webremote/Tools/Preloader",["../Config","CatLab/Webremote/Tools/Deferred"],function(t,o){function i(e){this.provider=e,this.provider.on("file:preload",function(e){e&&e.url&&this.preloadClientFile(e.url)}.bind(this)),this.urlMap={}}var e=i.prototype;return e.preload=function(t){if(Array.isArray(t)){for(var e=new o,i=[],n=0;n<t.length;n++)i.push(this.preload(t[n]));return o.when.apply(o,i).then(function(){e.resolve(Array.prototype.slice.call(arguments))}),e.promise()}var s=new o;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}),s.resolve(e)}.bind(this)),s.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}},i.unserialize=function(e,t){e=new i(e);return void 0!==t&&void 0!==t.urlMap&&(e.urlMap=t.urlMap),e},i}),define("CatLab/Webremote/Tools/Eventable",["CatLab/Webremote/Tools/Tools"],function(n){function e(){}var s=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,i=Array.prototype.slice.call(arguments);for(t in i.push(i.shift()),this._eventableEvents)this._eventableEvents.hasOwnProperty(t)&&this.eventMatches(e,t)&&this._eventableEvents[t].slice().forEach(function(e){try{e.method.apply(e.scope,i)}catch(e){console.error(e)}}.bind(this))}},t.eventMatches=function(e,t){return"*"===t||e===t},t.on=function(e,t,i){void 0===this._eventableEvents&&(this._eventableEvents={}),void 0===this._eventableEvents[e]&&(this._eventableEvents[e]=[]),s++,this._eventableEvents[e].push({id:s,method:t,scope:void 0!==i?i:this});var n=[e,s];return{id:n,name:e,method:t,unbind:function(){this.off(null,{id:n,name:e})}.bind(this)}},t.once=function(e,t,i){var n=this.on(e,function(){n.unbind(),t.apply(i,arguments)});return n},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 i=n.findIndex(this._eventableEvents[e],function(e){return e.id===t[1]});0<=i&&this._eventableEvents[e].splice(i,1)}else this._eventableEvents[e]=[];else this._eventableEvents=[]},t.clearEvents=function(){this.clearEventableEvents()},t.clearEventableEvents=function(){this._eventableEvents={}},e}),define("CatLab/Webremote/Models/User",["CatLab/Webremote/Config"],function(t){return function(e){this.accessToken=e,this.name=null,this.avatar=null,this.id=null,this.image=null,this.imageCallbacks=[],this.imageLoaded=!1,this.getAccessToken=function(){return this.accessToken},this.setId=function(e){this.id=e},this.getId=function(){return this.id},this.setName=function(e){this.name=e},this.getName=function(){return this.name},this.setAvatar=function(e){this.avatar=e,this.imageLoaded=!1,this.imageCallbacks=[],this.image=null},this.loadAvatar=function(){this.image||(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=function(){this.afterImageLoad()}.bind(this),this.image.src=t.getProxiedImage(this.avatar))},this.getAvatar=function(){return this.avatar},this.getAvatarSmiley=function(e){var t=this.getAvatar();return t?(t=t.split("?")[0],t+="?shape=circle&size=64&borderWidth=4",e&&(t+="&borderColor="+e.substr(1)),t):null},this.afterImageLoad=function(){this.imageLoaded=!0;for(var e=0;e<this.imageCallbacks.length;e++)this.imageCallbacks[e](this.image);this.imageCallbacks=[]},this.getImage=function(e){this.loadAvatar(),this.imageLoaded?e(this.image):this.imageCallbacks.push(e)}}}),define("CatLab/Webremote/Tools/Storage",["CatLab/Webremote/Tools/Cookies"],function(e){var t={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 i,n=window.localStorage.getItem(e);n?void 0!==(n=JSON.parse(n)).expires?(i=Date.now(),n.expires<i?(this.delete(e),t(null)):t(n.content)):t(n):t(null)}catch(e){t(null),console.log(e)}else t(null)},add:function(t,i,n,s){var o=this;n=n||function(){},this.isSupported()?this.get(t,function(e){(e=null!=e&&""!==e?e:[]).push(i),o.set(t,e,n,s)}):n(null)},set:function(e,t,i,n){if(void 0===i&&(i=function(){}),this.isSupported()){void 0===n&&(n=31536e6);try{var s=Date.now();s+=n,window.localStorage.setItem(e,JSON.stringify({expires:s,content:t}))}catch(e){console.log(e)}i()}else i(null)},delete:function(e){this.isSupported()&&window.localStorage.removeItem(e)},remove:function(n,s){var o;this.isSupported()&&(o=this).get(n,function(e){null!=e&&""!=e||(e=[]);for(var t=JSON.stringify(s),i=0;i<e.length;i++)if(t===JSON.stringify(e[i]))return e.splice(i,1),void o.set(n,e)})},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){function t(){this.initializeEventable()}var r,s,a=[],e=t.prototype=new e;return e.initialize=function(e,t){r=t,s=e;var n=this;o.get("users",function(i){null!==i&&o.get("currentuser",function(t){for(var e=0;e<i.length;e++)n.addFromAccessToken(i[e].access_token,function(e){e&&t&&e.getAccessToken()===t&&void 0!==s.setUser&&s.setUser(e)})})})},e.addFromAccessToken=function(i,n){n=n||function(){};var s=this;r.profile(i,function(e,t){e?(e=s.add(i,e.user),n(e)):401!==t&&403!==t||o.remove("users",{access_token:i})})},e.add=function(e,t){var i=new n(e);return i.setId(t.id),i.setName(t.username),i.setAvatar(t.avatar),(e=>{for(var t=0;t<a.length;t++)if(a[t].getId()==e.getId())return;return a.push(e),1})(i)||o.remove("users",{access_token:e}),this.trigger("update"),i},e.remove=function(e){for(var t=0;t<a.length;t++)if(a[t].getId()==e.getId())return o.remove("users",{access_token:a[t].getAccessToken()}),a.splice(t,1),void this.trigger("update")},e.getFromId=function(e){for(var t=0;t<a.length;t++)if(a[t].getId()==e)return a[t];return null},e.getAll=function(){return a},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(o,r,e,s,a,n){var l,c,h,u,d,f=[],t=[],m=[],p=null;function i(){this.initializeEventable()}e=i.prototype=new e;return e.initialize=function(e){l=(e=e||{}).authorization,c=e.client_id||"none",h=e.authorization||"default",u=e.profile||"",d=e.profile+"/avatar",void 0===e.redirect_uri||n._options.oauth.redirectUrl||(n._options.oauth.redirectUrl=e.redirect_uri);var t=this;if("undefined"!=typeof window){var i,e=function(e){t.onMessage(e)};if(window.addEventListener){for(;i=m.pop();)removeEventListener("message",i);addEventListener("message",e,!1)}else{for(;i=m.pop();)detachEvent("onmessage",i);attachEvent("onmessage",e)}m.push(e)}},e.setRedirectUrl=function(e,t){this.redirectHost=e,this.redirectUrl=e+t},e.getAuthorizeURL=function(){var e="",e=(n.all().oauth&&n.all().oauth.redirectUrl&&(e=n.all().oauth.redirectUrl),l+"?client_id="+encodeURIComponent(c)+"&authorization="+encodeURIComponent(h)+"&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(n){var e=function(e){if(e&&e.user){var t,i=s.add(n,e.user);for(a.add("users",{access_token:n}),o.closePopup();t=f.shift();)t(i);this.trigger("update")}}.bind(this);this.call(u,n,e)},e.call=function(e,t,i){var n,e=e+"?access_token="+t;"undefined"!=typeof window&&((n=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP")).onreadystatechange=function(){if(4==n.readyState&&200!=n.status&&i(null,n.status),4==n.readyState&&200==n.status)try{i(JSON.parse(n.responseText))}catch(e){i(null,n.status)}},n.open("GET",e,!0),n.send())},e.profile=function(e,t){this.call(u,e,t)},e.changeAvatar=function(t,e){var i,n,s;if(t.getAccessToken())return i=new r,(n=new FormData).append("avatar",e.files[0]),(s=new XMLHttpRequest).open("POST",d,!0),s.setRequestHeader("Authorization","Bearer "+t.getAccessToken()),s.onreadystatechange=function(){if(4===s.readyState)if(200<=s.status&&s.status<300)try{var e=JSON.parse(s.responseText);t.setAvatar(e.url),i.resolve(e)}catch(e){i.reject(e)}else i.reject(s.status)},s.send(n),i.promise()},e.link=function(t){var i=new r,e={},e=("object"==typeof(t=void 0===t?{}:t)&&(t=(e=t).callback||function(){}),e.fullscreen||!1),n=(p&&clearInterval(p),this.getAuthorizeURL()),s=o.oauth2Popup(n,e);return s&&(p=setInterval(function(){s&&s.postMessage?s.postMessage("Hello from the other side","*"):clearInterval(p)}.bind(this),1e3)),f.push(function(e){t(e),i.resolve(e)}),i.promise()},e.onInit=function(e){t.push(e)},e.onAdds=function(){for(var e=0;e<t.length;e++)t[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&&window.opener.postMessage(e,"*"),window.parent&&window.parent.postMessage(e,"*"),void 0!==window.dialogArguments&&window.dialogArguments.opener&&window.dialogArguments.opener.postMessage(e,"*"),setTimeout(function(){p&&clearInterval(p),window.close()},1)},1)},new i}),define("CatLab/Webremote/Views/Popups/BasePopup",[],function(){function e(){this.scrollable=!1}var t=e.prototype;return t.render=function(e){this.popupContainer=document.createElement("div"),this.popupContainer.className="catlab-popup-container";var t=document.createElement("div"),t=(t.className="overlay",t.addEventListener("click",function(){this.close()}.bind(this)),this.popupContainer.appendChild(t),this.container=document.createElement("div"),this.container.className="popup",this.popupContainer.appendChild(this.container),this.container.addEventListener("click",function(e){e.stopPropagation()}),this.content=document.createElement("div"),this.container.appendChild(this.content),document.createElement("p")),i=(t.className="close",document.createElement("a"));i.href="javascript:void(0)",i.innerHTML="<span>Close</span>",i.onclick=function(){this.close()}.bind(this),t.appendChild(i),this.container.appendChild(t),e.appendChild(this.popupContainer),this.scrollable&&this.content.classList.add("scrollable"),this.renderContent(this.content)},t.renderContent=function(){},t.close=function(){this.popupContainer.parentNode.removeChild(this.popupContainer)},e}),define("CatLab/Webremote/Views/User",["CatLab/Webremote/Controllers/OAuth2"],function(n){return function(d){this.render=function(e,t,i){t=t||[];var n,s=d.getName(),o=document.createElement("div"),r=(o.className="catlab-user",document.createElement("div")),r=((this.avatardiv=r).className="catlab-avatar",o.appendChild(r),this.renderAvatar(),void 0!==i&&(r.onclick=i),document.createElement("div")),a=(r.className="catlab-info",o.appendChild(r),document.createElement("p"));void 0!==i?((n=document.createElement("a")).innerHTML=s,n.onclick=i,a.appendChild(n)):(a.innerHTML=s,r.appendChild(a)),r.appendChild(a);var l,c,h=document.createElement("ul");h.className="catlab-actions";for(var u=0;u<t.length;u++)(l=document.createElement("li")).className=t[u].token,h.appendChild(l),(c=document.createElement("a")).onclick=t[u].click,c.innerHTML=t[u].text,c.href="javascript:void(0)",l.appendChild(c);r.appendChild(h),e.innerHTML="",e.appendChild(o);i=document.createElement("div");i.className="clearer",o.appendChild(i)},this.renderAvatar=function(){var e=d.getAvatar(),t=document.createElement("img");t.src=e,t.alt="User avatar",this.avatardiv.innerHTML="",this.avatardiv.appendChild(t)},this.enableAvatarUpload=function(t){var i=document.createElement("input");i.type="file",i.accept="image/*",(this.avatarFileInput=i).addEventListener("change",function(){this.avatardiv.classList.add("loading");var e=n.changeAvatar(d,i);e&&e.then&&e.then(function(){this.avatardiv.classList.remove("loading"),this.renderAvatar(),t.setUser(d)}.bind(this))}.bind(this)),this.avatardiv.addEventListener("click",function(){i.click()})},this.uploadAvatar=function(){this.avatarFileInput&&this.avatarFileInput.click()}}}),define("CatLab/Webremote/Views/Popups/AuthenticationPopup",["CatLab/Webremote/Views/Popups/BasePopup","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Views/User","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Tracker"],function(e,l,c,h,u,d){return function(t){function e(){l.link(function(e){s.updateUsers(),s.selectUser(e)})}l.on("update",function(){this.updateUsers()}.bind(this));var s=this,i=document.createElement("div"),n=(i.className="catlab-popup-container",document.createElement("div")),n=(n.className="overlay",i.appendChild(n),document.createElement("div")),o=(n.className="popup",i.appendChild(n),n.innerHTML="<h2>Select account</h2>",document.createElement("ul")),r=(o.className="userlist",n.appendChild(o),document.createElement("div")),r=(r.className="clearer",n.appendChild(r),document.createElement("p")),a=(r.className="connect",document.createElement("a")),r=(a.href="javascript:void(0)",a.innerHTML='<span class="new-user">Connect new user</span>',a.onclick=function(){e()},r.appendChild(a),n.appendChild(a),document.createElement("p")),a=(r.className="close",document.createElement("a"));a.href="javascript:void(0)",a.innerHTML="<span>Close</span>",a.onclick=function(){s.close()},r.appendChild(a),n.appendChild(r),this.selectUser=function(e){t.setUser(e),s.close(),d.track("Click","Select user","AuthenticationPopup")},this.updateUsers=function(){o.innerHTML="";for(var e=c.getAll(),t=0;t<e.length;t++)((e,t)=>{var i=document.createElement("li"),n=[{token:"select",text:"select",click:function(){s.selectUser(t)}},{token:"logout",text:"logout",click:function(){c.remove(t),u.remove("users",{access_token:t.getAccessToken()}),s.updateUsers(),d.track("Click","Logout","AuthenticationPopup")}}];new h(t).render(i,n,function(){s.selectUser(t)}),e.appendChild(i)})(o,e[t])},this.close=function(){i.parentNode.removeChild(i),d.track("Click","Close popup","AuthenticationPopup")},this.connect=function(){d.track("Click","Connect new","AuthenticationPopup"),e()},this.render=function(e){e.appendChild(i),this.updateUsers()},this.setLoginUrl=function(e){}}}),define("CatLab/Webremote/Views/Popups/SelectSmileyPopup",["CatLab/Webremote/Views/Popups/BasePopup"],function(e){function t(e,t,i){this.Webremote=e,this.callback=t,this.scrollable=!0,this.disableTaken=i}e=t.prototype=new e;return e.renderContent=function(e){e.classList.add("smileys-popup");var t=document.createElement("ul"),i=(t.className="smileys",e.appendChild(t),this.Webremote.smileys.smileyKeys.slice());this.Webremote.getUser()&&this.Webremote.getUser().getAvatar()&&(s=this.Webremote.getUser().getAvatarSmiley(this.Webremote.color))&&i.unshift(s);for(var n=0;n<i.length;n++)this.renderSmiley(t,i[n]);var s=document.createElement("div");s.className="clearer",e.appendChild(s)},e.renderSmiley=function(i,n){var s=document.createElement("li"),o=(s.appendChild(this.Webremote.smileys.getElement(n)),!this.disableTaken||this.Webremote.smileys.isAvailable(n));o||s.classList.add("unavailable"),this.Webremote.getSmiley()===n&&s.classList.add("selected"),s.addEventListener("click",function(){if(o){this.selectSmiley(n);for(var e=i.querySelectorAll(".selected"),t=0;t<e.length;t++)e[t].classList.remove("selected");s.classList.add("selected"),this.close()}}.bind(this)),i.appendChild(s)},e.selectSmiley=function(e){this.callback(e)},t}),define("CatLab/Webremote/Views/Blocks/CurrentUser",["CatLab/Webremote/Views/User","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Tracker"],function(o,r,a,l){return function(s){this.render=function(e){var t,i,n;e.innerHTML="",s.canAuthenticate()&&(n=s.getUser(),(t=document.createElement("div")).className="overlay player-color-background",e.appendChild(t),(t=document.createElement("div")).className="content",t.className+=" player-color-border",e.appendChild(t),n?(e=[{token:"switch",text:"Switch account",click:function(){s.showAuthenticationPopup(),l.track("Click","Switch account","CurrentUser")}},{token:"upload",text:"Upload photo",click:function(){i.uploadAvatar()}},{token:"logout",text:"Logout",click:function(){var e=s.getUser();r.remove(e),s.setUser(null),a.remove("users",{access_token:e.getAccessToken()}),l.track("Click","Logout","CurrentUser")}}],(i=new o(n)).render(t,e),i.enableAvatarUpload(s)):((n=document.createElement("p")).className="catlab-not-loggedin",(e=document.createElement("a")).href="javascript:void(0);",e.innerHTML="Login",e.onclick=function(){s.showAuthenticationPopup(0===r.getAll().length),l.track("Click","Login","CurrentUser")},n.appendChild(e),t.appendChild(n)))}}}),(()=>{var m={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 p(e){for(var t,i,n,s,o,r,a,l=(e=>{if(g[e])return g[e];for(var t,i=e,n=[],s=0;i;){if(null!==(t=m.text.exec(i)))n.push(t[0]);else if(null!==(t=m.modulo.exec(i)))n.push("%");else{if(null===(t=m.placeholder.exec(i)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){s|=1;var o=[],r=t[2],a=[];if(null===(a=m.key.exec(r)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(o.push(a[1]);""!==(r=r.substring(a[0].length));){if(null===(a=m.key_access.exec(r))&&null===(a=m.index_access.exec(r)))throw new SyntaxError("[sprintf] failed to parse named argument key");o.push(a[1])}t[2]=o}else s|=2;if(3===s)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");n.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]})}i=i.substring(t[0].length)}return g[e]=n})(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((n=l[f]).keys)for(t=c[h],i=0;i<n.keys.length;i++){if(null==t)throw new Error(p('[sprintf] Cannot access property "%s" of undefined value "%s"',n.keys[i],n.keys[i-1]));t=t[n.keys[i]]}else t=n.param_no?c[n.param_no]:c[h++];if(m.not_type.test(n.type)&&m.not_primitive.test(n.type)&&t instanceof Function&&(t=t()),m.numeric_arg.test(n.type)&&"number"!=typeof t&&isNaN(t))throw new TypeError(p("[sprintf] expecting number but found %T",t));switch(m.number.test(n.type)&&(r=0<=t),n.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,n.width?parseInt(n.width):0);break;case"e":t=n.precision?parseFloat(t).toExponential(n.precision):parseFloat(t).toExponential();break;case"f":t=n.precision?parseFloat(t).toFixed(n.precision):parseFloat(t);break;case"g":t=n.precision?String(Number(t.toPrecision(n.precision))):parseFloat(t);break;case"o":t=(parseInt(t,10)>>>0).toString(8);break;case"s":t=String(t),t=n.precision?t.substring(0,n.precision):t;break;case"t":t=String(!!t),t=n.precision?t.substring(0,n.precision):t;break;case"T":t=Object.prototype.toString.call(t).slice(8,-1).toLowerCase(),t=n.precision?t.substring(0,n.precision):t;break;case"u":t=parseInt(t,10)>>>0;break;case"v":t=t.valueOf(),t=n.precision?t.substring(0,n.precision):t;break;case"x":t=(parseInt(t,10)>>>0).toString(16);break;case"X":t=(parseInt(t,10)>>>0).toString(16).toUpperCase()}m.json.test(n.type)?d+=t:(!m.number.test(n.type)||r&&!n.sign?a="":(a=r?"+":"-",t=t.toString().replace(m.sign,"")),s=n.pad_char?"0"===n.pad_char?"0":n.pad_char.charAt(1):" ",o=n.width-(a+t).length,o=n.width&&0<o?s.repeat(o):"",d+=n.align?a+t+o:"0"===s?a+o+t:o+a+t)}return d}function e(e,t){return p.apply(null,[e].concat(t||[]))}var g=Object.create(null);"undefined"!=typeof exports&&(exports.sprintf=p,exports.vsprintf=e),"undefined"!=typeof window&&(window.sprintf=p,window.vsprintf=e,"function"==typeof define)&&define.amd&&define("sprintf",[],function(){return{sprintf:p,vsprintf:e}})})(),define("CatLab/Webremote/Tools/Translator",["sprintf"],function(t){function e(){this.translator=null}var i,n,s=e.prototype;return s.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)},s.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(i=[],n=1;n<arguments.length;n++)i.push(arguments[n]);return t.vsprintf(e,i)},new e}),define("CatLab/Webremote/Views/Blocks/CurrentSmiley",["CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Deferred"],function(i,e){function n(e,t,i,n){this.Webremote=e,this.canSwitch=void 0!==t&&!!t,this.canDrag=void 0!==i&&!!i,this.isProfileSmiley=void 0===n||!!n,this.dragDisabled=!1,this.switchVerb="Switch"}n.initialize=function(){return n.isInitialized||(n.isInitialized=new e).resolve(),n.isInitialized.promise()}.bind(this),n.activeSmileys=["1f601","1f60d","1f60e"];var t=n.prototype;return t._makeDraggable=function(n,s){var o=this,r=null,a=null,l=!1,c=!1,h=0,u=0,d=0,f=0,m=0,p=0;function e(e){var t,i;o.dragDisabled||(l=!0,n.style.cursor="grabbing",i=(void 0!==e.clientX?e:e.touches[0]).clientX,t=(void 0!==e.clientY?e:e.touches[0]).clientY,h=i,u=t,r={left:d=m,top:f=p},i=n.getBoundingClientRect(),a={left:i.left+window.pageXOffset,top:i.top+window.pageYOffset},o.disableDrag(),n.classList.add("flinging"),e.preventDefault())}function t(e){var t,i;l&&(t=(void 0!==e.clientX?e:e.touches[0]).clientX,i=(void 0!==e.clientY?e:e.touches[0]).clientY,m=d+(t-h),p=f+(i-u),n.style.left=m+"px",n.style.top=p+"px",e.preventDefault())}function i(e){var t,i;l&&(l=!1,i={left:m,top:p},10<(t=o.getDistance(r,i))?(c=!0,i=o.getAngle(r,i),o.slingshot(a,i,t,n,s,function(){p=m=0,n.style.cursor="grab"})):(n.style.left="0px",n.style.top="0px",p=m=0,n.style.cursor="grab",o.enableDrag(),n.classList.remove("flinging")),e.preventDefault())}n.style.zIndex="10",n.style.position="relative",n.style.touchAction="none",n.style.cursor="grab",n.addEventListener("mousedown",e),n.addEventListener("touchstart",e,{passive:!1}),document.addEventListener("mousemove",t),document.addEventListener("touchmove",t,{passive:!1}),document.addEventListener("mouseup",i),document.addEventListener("touchend",i),document.addEventListener("touchcancel",function(){l&&(l=!1,n.style.left="0px",n.style.top="0px",p=m=0,n.style.cursor="grab",o.enableDrag(),n.classList.remove("flinging"))}),n.addEventListener("click",function(e){c&&(c=!1,e.stopPropagation(),e.preventDefault())},!0)},t._animateElement=function(r,a,l,c){for(var h={},u=Object.keys(a),e=0;e<u.length;e++){var t=u[e];h[t]=parseFloat(r.style[t])||0}var d=null;requestAnimationFrame(function e(t){d=d||t;for(var t=Math.min((t-d)/l,1),i=.5-Math.cos(t*Math.PI)/2,n=0;n<u.length;n++){var s=u[n],o=h[s]+(a[s]-h[s])*i;r.style[s]=o+("opacity"===s?"":"px")}t<1?requestAnimationFrame(e):c&&c()})},t.setSmiley=function(t){Array.isArray(t)||(t=[t]),this.smileys=t,n.initialize().then(function(){var e;this.selector&&(this.selector.innerHTML="",t.forEach(function(e){var t=this.Webremote.smileys.getElement(e);if(this.selector.appendChild(t),this.canDrag)try{this._makeDraggable(t,e)}catch(e){console.log(e)}}.bind(this)),this.canSwitch)&&((e=document.createElement("p")).className="switch",e.innerHTML='<a href="javascript:void(0)">'+i.t(this.switchVerb)+"</a>",this.selector.appendChild(e))}.bind(this))},t.disableDrag=function(){this.dragDisabled=!0,this.selector&&this.selector.classList.add("drag-disabled")},t.enableDrag=function(){this.dragDisabled=!1,this.selector&&this.selector.classList.remove("drag-disabled")},t.getMaxDistance=function(){var e;return this.selector?(e=this.selector.getBoundingClientRect(),window.innerHeight-e.top):200},t.getDistance=function(e,t){var i=e.left-t.left,e=e.top-t.top;return Math.sqrt(i*i+e*e)},t.getAngle=function(e,t){return Math.atan2(t.top-e.top,t.left-e.top)},t.slingshot=function(e,t,i,n,s,o){var r=Math.min(1,i/this.getMaxDistance());0<Math.sin(t-Math.PI)?this._animateElement(n,{left:0,top:0},1e3,function(){o&&o(),this.enableDrag(),n.classList.remove("flinging")}.bind(this)):(i=1.5*Math.max(e.left,e.top),this._animateElement(n,{left:Math.cos(t-Math.PI)*i,top:Math.sin(t-Math.PI)*i},1e3,function(){setTimeout(function(){n.style.left=-1*parseFloat(n.style.left)+"px",this._animateElement(n,{left:0,top:0},1e3,function(){o&&o(),this.enableDrag(),n.classList.remove("flinging")}.bind(this))}.bind(this),3e3*r)}.bind(this)),setTimeout(function(){this.Webremote.emit("smileys:slingshot",{angle:t,speed:r,smiley:s})}.bind(this),800))},t.render=function(e){n.initialize().then(function(){this.container=e,this.canSwitch||this.canDrag?(this.selector=document.createElement("div"),this.selector.className="smiley-selector"):(this.selector=document.createElement("div"),this.selector.className="smiley-view"),this.selector.innerHTML='<div class="placeholder"></div>',this.container.innerHTML="",this.container.appendChild(this.selector),this.canSwitch&&(this.container.addEventListener("click",function(){this.isProfileSmiley?this.Webremote.showSmileyPopup():this.Webremote.showSmileyPopup(function(e){if(-1===n.activeSmileys.indexOf(e)){for(;2<n.activeSmileys.length;)n.activeSmileys.shift();n.activeSmileys.push(e),this.setSmiley(n.activeSmileys)}}.bind(this),!1)}.bind(this)),this.isProfileSmiley||this.setSmiley(n.activeSmileys))}.bind(this))},n}),define("CatLab/Webremote/Tools/HashParser",[],function(){return{getParameters:function(){for(var e,t={},i=/\+/g,n=/([^&;=]+)=?([^&;]*)/g,s=function(e){return decodeURIComponent(e.replace(i," "))},o=window.location.hash.substring(1);e=n.exec(o);)t[s(e[1])]=s(e[2]);return t},getParameter:function(e){var t=this.getParameters();return void 0!==t[e]?t[e]:null},clear:function(){history.pushState("",document.title,window.location.pathname+window.location.search)}}}),define("CatLab/Webremote/Tools/Screenfull",[],function(){var r="undefined"!=typeof window&&void 0!==window.document?window.document:{},a=(()=>{for(var e,t=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]],i=0,n=t.length,s={};i<n;i++)if((e=t[i])&&e[1]in r){for(i=0;i<e.length;i++)s[t[0][i]]=e[i];return s}return!1})(),i={change:a.fullscreenchange,error:a.fullscreenerror},e={request:function(s,o){return new Promise(function(e,t){var i=function(){this.off("change",i),e()}.bind(this),n=(this.on("change",i),(s=s||r.documentElement)[a.requestFullscreen](o));n instanceof Promise&&n.then(i).catch(t)}.bind(this))},exit:function(){return new Promise(function(e,t){var i,n;this.isFullscreen?(i=function(){this.off("change",i),e()}.bind(this),this.on("change",i),(n=r[a.exitFullscreen]())instanceof Promise&&n.then(i).catch(t)):e()}.bind(this))},toggle:function(e,t){return this.isFullscreen?this.exit():this.request(e,t)},onchange:function(e){this.on("change",e)},onerror:function(e){this.on("error",e)},on:function(e,t){e=i[e];e&&r.addEventListener(e,t,!1)},off:function(e,t){e=i[e];e&&r.removeEventListener(e,t,!1)},raw:a};return Object.defineProperties(e,{isFullscreen:{get:function(){return Boolean(r[a.fullscreenElement])}},element:{enumerable:!0,get:function(){return r[a.fullscreenElement]}},isEnabled:{enumerable:!0,get:function(){return Boolean(r[a.fullscreenEnabled])}}}),e}),define("CatLab/Webremote/Views/Alert",[],function(){return function(e,t){t=t||function(){},alert(e),t()}}),define("CatLab/Webremote/Views/Welcome",["CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Views/User","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Tracker"],function(e,t,i,o){return function(e){var t=this,i=document.createElement("div"),n=(i.className="catlab-popup-container",document.createElement("div")),n=(n.className="overlay",i.appendChild(n),document.createElement("div")),e=(n.className="popup thanks",i.appendChild(n),n.innerHTML=e,document.createElement("a")),s=(e.innerHTML="Start playing",e.onclick=function(){t.close()},e.href="javascript:void(0)",document.createElement("p"));s.appendChild(e),s.className="playnow",n.appendChild(s),this.close=function(){i.parentNode.removeChild(i),o.track("Click","Close popup","WelcomePopup")},this.render=function(e){e.appendChild(i)}}}),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 i=t.prototype;return i.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))},i.text=function(e){this.message=e,this.div&&(this.div.innerHTML="<p>"+e+"</p>")},i.hide=function(){this.visible=!1,this.div&&this.div.parentNode&&this.div.parentNode.removeChild(this.div),this.showTimeout&&clearTimeout(this.showTimeout),this.message=null,this.div=null,this.showTimeout=null},t}),define("CatLab/Webremote/Views/GamePaused",["CatLab/Webremote/Tools/Translator"],function(e){function t(){this.visible=!1,this.div=null,this.timeoutTillShow=1,this.showTimeout=null,this.message=null}var i=t.prototype;return i.show=function(){this.visible||(this.visible=!0,this.div)||(this.showTimeout&&(clearTimeout(this.showTimeout),this.showTimeout=null),setTimeout(function(){this.div||this.visible&&(this.showTimeout=null,this.div=document.createElement("div"),document.body.appendChild(this.div),this.div.style.position="fixed",this.div.style.right="0",this.div.style.top="0",this.div.style.width="100%",this.div.style.height="100%",this.div.style.padding="0",this.div.style.background="black",this.div.style.zIndex="100000",this.div.style.textAlign="center",this.div.style.color="white",this.div.style.font="Sans-serif",this.div.style.fontSize="2em",this.div.style.opacity=.9,this.message?this.text(this.message):this.text(e.t("Please wait, the game is paused.")))}.bind(this),this.timeoutTillShow))},i.text=function(e){this.message=e,this.div&&(this.div.innerHTML='<p style="height: 100%; padding: 20% 0">'+e+"</p>")},i.hide=function(){this.visible=!1,this.div&&this.div.parentNode.removeChild(this.div),this.showTimeout&&clearTimeout(this.showTimeout),this.message=null,this.div=null,this.showTimeout=null},t}),define("CatLab/Webremote/Synchronization/ClientRemoteView",[],function(){function e(e,t,i,n,s,o){this.controller=e,this.html="<p>Loading</p>",this.context={},this.viewId=t,this.name=i,this.groupId=void 0!==n?n:null,this.synchronizedData=s,this.createdAt=new Date,this.iframe=o,this.currentValues=[],this.buttons=[]}var s={},t=e.prototype;return t.render=function(e){var t;this.iframe?((t=document.createElement("iframe")).style.width="100%",t.style.height="100%",t.style.border="none",t.style.margin="0",t.style.padding="0",t.style.position="absolute",t.style.left="0",t.style.top="0",e.innerHTML="",e.appendChild(t),this.element=t.contentDocument.body):this.element=e,this.el=e,this.$el=e,this.element.innerHTML=this.html,this.update(),this.controller.components.attach(this,document.body),this.updateEvents(),setTimeout(function(){this.updateEvents(),window.scrollTo(0,1)}.bind(this),10),setTimeout(function(){this.updateEvents()}.bind(this),100),setTimeout(function(){this.updateEvents()}.bind(this),1e3)},t.updateEvents=function(){var h=this;function e(n,t,s){var o,r,a,l,c;h.shouldSetEvents(n,"touch")&&(l=!1,c=null,n.addEventListener("touchstart",function(e){return o=new Date,r={x:e.touches[0].pageX,y:e.touches[0].pageY},a={x:e.touches[0].pageX,y:e.touches[0].pageY},l=!0,c&&clearTimeout(c),t.apply(h,[n])}),n.addEventListener("touchmove",function(e){a={x:e.touches[0].pageX,y:e.touches[0].pageY}}),n.addEventListener("touchend",function(e){var t,i;if(r)return i=Math.abs(a.x-r.x),t=Math.abs(a.y-r.y),r=null,i=(new Date).getTime()-o.getTime()<300&&i<20&&t<20,c=setTimeout(function(){l=!1},1e3),s.apply(h,[n,i])}),n.addEventListener("mousedown",function(e){if(e.preventDefault(),!l)return t.apply(h,[n])}),n.addEventListener("mouseup",function(e){if(e.preventDefault(),!l)return s.apply(h,[n,!0])}))}for(var t=this.element.querySelectorAll("[data-button-id]"),i=0;i<t.length;i++)e(t[i],h.buttonDown,h.buttonUp),this.buttons.push(t[i]);for(t=this.element.querySelectorAll("[data-authentication-button]"),i=0;i<t.length;i++)e(t[i],function(){},h.authenticate);for(t=this.element.querySelectorAll("[data-value-id]"),i=0;i<t.length;i++)(t=>{var i,e;h.shouldSetEvents(t,"change")&&(i=t.getAttribute("data-value-id"),h.currentValues[i]=h.getDataValue(t),t.addEventListener("change",function(e){s[i]=new Date,h.syncValue(t)}),e=null,t.addEventListener("keyup",function(){e&&clearTimeout(e),e=setTimeout(function(){s[i]=new Date,h.syncValue(t)},1e3)}))})(t[i])},t.getDataValue=function(e){return"checkbox"===e.type?e.checked?1:0:e.value},t.syncValues=function(){for(var e=this.element.querySelectorAll("[data-value-id]"),t=0;t<e.length;t++)this.syncValue(e[t])},t.syncValue=function(e){var t=this.getDataValue(e),i=e.getAttribute("data-value-id");void 0!==this.currentValues[i]&&this.currentValues[i]===t||(this.currentValues[i]=t,this.controller.syncValue(i,this.getDataValue(e),this.viewId))},t.update=function(){for(var e=this.element.querySelectorAll("[data-button-decorator]"),t=0;t<e.length;t++)void 0===e[t].dataset.initialClasses&&(e[t].dataset.initialClasses=e[t].className);this.updateBigTextSizes()},t.updateBigTextSizes=function(){for(var e=this.element,t=e.querySelectorAll(".bigtext"),i={},n=0;n<t.length;n++){var s,o=t[n],r=o.getAttribute("data-bigtext-group");if(r){if(void 0===i[r]){i[r]=0;for(var a=e.querySelectorAll('.bigtext[data-bigtext-group="'+r+'"]'),l=0;l<a.length;l++)i[r]=Math.max(i[r],a[l].textContent.length)}s=i[r]}else s=o.textContent.length;o.setAttribute("data-bigtext-length",s)}},t.shouldSetEvents=function(e,t){return void 0===e["hasCatlabEventsAlready"+t]&&(e["hasCatlabEventsAlready"+t]=!0)},t.buttonDown=function(e){try{this.syncValues()}catch(e){console.error(e)}return this.controller.buttonDown(e.getAttribute("data-button-id"),this.viewId),!1},t.buttonUp=function(e,t){return this.controller.buttonUp(e.getAttribute("data-button-id"),this.viewId,t),!1},t.setLabel=function(e,t){for(var i=this.element.querySelectorAll("[data-button-label="+e+"]"),n=0;n<i.length;n++)i[n].innerHTML=t;this.update()},t.setClass=function(e,t){for(var i=this.element.querySelectorAll("[data-button-decorator="+e+"]"),n=0;n<i.length;n++){var s=i[n];s.className=s.dataset.initialClasses+" "+t}this.update()},t.domAppend=function(e,t){var i=document.getElementById(e);if(i){for(var n=this.stringToDom(t),s=[];n.firstChild;)s.push(i.appendChild(n.firstChild));try{for(var o=0;o<s.length;o++)this.controller.components.attach(this._currentView,s[o],!1)}catch(e){console.log(e)}5e3<(new Date).getTime()-this.createdAt.getTime()&&0<s.length&&void 0!==s[0].scrollIntoView&&s[0].scrollIntoView(),this.update(),this.updateEvents()}},t.domReplace=function(e,t){e=document.getElementById(e);e&&(e.innerHTML=t,this.controller.components.attach(this._currentView,e,!1),this.update(),this.updateEvents())},t.domAttribute=function(e,t,i){for(var n=document.querySelectorAll(e),s=0;s<n.length;s++)n[s].setAttribute(t,i)},t.changeValue=function(e){if(void 0!==s[e.id]){if((t=Math.abs(s[e.id].getTime()-(new Date).getTime()))<5)return}else var t=9999999999999;for(var i=this.element.querySelectorAll("[data-value-id="+e.id+"]"),n=0;n<i.length;n++)document.activeElement==i[n]&&t<5e3||(this.currentValues[e.id]=e.value,i[n].value=e.value)},t.vibrate=function(e){void 0!==window.navigator.vibrate&&void 0!==e.pattern&&Array.isArray(e.pattern)&&window.navigator.vibrate(e.pattern)},t.stringToDom=function(e){var t;return(t=0<=e.toLowerCase().indexOf("<tr")?document.createElement("tbody"):document.createElement("div")).innerHTML=e,t},t.stringInterpolateDataElements=function(e,s){return e.replace(/{{(.+?)}}/g,function(e,t,i,n){t=this.controller.resolveDataAttribute(t.trim());return t=s?s(t):t}.bind(this))},t.destroy=function(){this.syncValues(),void 0!==this.synchronizedData&&this.synchronizedData.destroy()},e}),define("CatLab/Webremote/Synchronization/DataItem",[],function(){function i(e,t,i){this.key=e,this.shared=t,this.side=i}var e=i.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}},i.unserialize=function(e){var t=new i(e.key,e.shared,e.side);return t.setValue(e.value),t},i}),define("CatLab/Webremote/Synchronization/SynchronizedData",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Synchronization/DataItem"],function(e,s){function t(e,t,i){this.initializeEventable(),this.id=e,this.synchronizer=t,this.side=i,this.data={}}e=t.prototype=new e;return e.set=function(e,t,i){if(void 0===this.data[e])this.data[e]=new s(e,i,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,i=e.side,n=e.value;if(void 0===this.data[t])this.data[t]=new s(t,e.shared,i);else if(!this.data[t].canWrite(i))throw"Trying to overwrite a non shared data attribute: "+t;this.data[t].setValue(n)},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]=s.unserialize(e[t]))},t}),define("CatLab/Webremote/Synchronization/DataSynchronizer",["CatLab/Webremote/Synchronization/SynchronizedData"],function(t){function e(e,t,i){this.namespace=e,this.emit=t,this.dataModels={},this.side=i}e.eventsToListenFor=["data:set"];var i=e.prototype;return i.checkNamespace=function(e){return void 0!==e.namespace&&e.namespace===this.namespace},i.processMessage=function(e,t){void 0!==t.container&&this.getFromIdentifier(t.container).processMessage(t)},i.getFromIdentifier=function(e){return void 0===this.dataModels[e]&&(this.dataModels[e]=new t(e,this,this.side)),this.dataModels[e]},i.destroy=function(e){e=e.id;void 0===this.dataModels[e]&&delete this.dataModels[e]},i.refreshTarget=function(e){for(var t in this.dataModels)this.dataModels.hasOwnProperty(t)&&this.dataModels[t].refreshTarget(e)},i.serialize=function(){var e,t={};for(e in this.dataModels)this.dataModels.hasOwnProperty(e)&&(t[e]=this.dataModels[e].serialize());return{dataModels:t}},i.unserialize=function(e){for(var t in e.dataModels)e.dataModels.hasOwnProperty(t)&&this.getFromIdentifier(t).unserialize(e.dataModels[t])},e}),define("CatLab/Webremote/Synchronization/EventHandler",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e,t){this.initializeEventable(),this.namespace=e,this.emit=t}t.eventsToListenFor=["event:trigger"];e=t.prototype=new e;return e.checkNamespace=function(e){return void 0!==e.namespace&&e.namespace===this.namespace},e.processMessage=function(e,t){if("event:trigger"===e)return this.processTriggerEvent(t)},e.processTriggerEvent=function(e){void 0!==e.event&&this.eventableTrigger(e.event,void 0===e.parameters?{}:e.parameters)},e.trigger=function(e,t){this.emit("event:trigger",{namespace:this.namespace,event:e,parameters:t})},e.refreshTarget=function(e){},e.serialize=function(){return{}},e.unserialize=function(e){},t}),define("CatLab/Webremote/Synchronization/CombinedEventHandler",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e,t){this.initializeEventable(),this.handlers=[]}return(t.prototype=new e).addHandler=function(e){this.handlers.push(e),e.on("*",function(e,t){this.trigger(t,e)}.bind(this))},t}),define("CatLab/Webremote/Synchronization/MessageQueue",[],function(){function e(){this.queue=[]}var t=e.prototype;return t.add=function(e,t,i){this.queue.push({action:e,data:t,ack:i})},t.flush=function(){var e=this.queue;return this.queue=[],e},t.compactFlush=function(){var n,s,o,r,a=[],e=this.flush();return 0===e.length?e:(s={user:{},group:{}},o=0,r={},e.forEach(function(e){if(o++,this.canCompact(e)){var t=null;void 0!==e.data.user?t="user":void 0!==e.data.group&&(t="group"),void 0===s[t][e.action]&&(s[t][e.action]=[]);for(var i=0;i<s[t][e.action].length;i++)if(n=s[t][e.action][i],this.isSimilarMessage(n.event,e)&&(void 0===r[e.data[t]]||r[e.data[t]]<n.index))return r[e.data[t]]=n.index,n.event.data[t].push(e.data[t]),void n.event.data._d.push(this.getDifference(n.event,e));Array.isArray(e.data[t])||(e.data[t]=[e.data[t]]),e.data._d=[{}],r[e.data[t]]=o,s[t][e.action].push({event:e,index:o})}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 i,n={};for(i in t.data)if(t.data.hasOwnProperty(i)){switch(i){case"user":case"group":case"_d":case"_i":continue}void 0!==e.data[i]&&e.data[i]===t.data[i]||(n[i]=t.data[i])}return n},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 i=Array.isArray(e[t])?e[t]:[e[t]],n=[];void 0!==e._d&&(n=Array.isArray(e._d)?e._d:[e._d]);for(var s=[],o=0;o<i.length;o++){(r={})[t]=i[o];var r=Object.assign({},e,r,void 0!==n[o]?n[o]:{});delete r._d,s.push(r)}return s},Object.defineProperty(t,"length",{get:function(){return this.queue.length}}),e}),define("CatLab/Webremote/Tools/Proxy",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred"],function(i,n){function e(){}function s(e,t,i){var n=(()=>{for(var e=!1,t=0;t<o.length;t++){try{e=o[t]()}catch(e){continue}break}return e})();n&&(n.open(i?"POST":"GET",e,!0),i&&n.setRequestHeader("Content-type","application/x-www-form-urlencoded"),n.onreadystatechange=function(){4==n.readyState&&(200==n.status||304==n.status?t(n):console.error("CatLab Remote HTTP error "+n.status))},4!=n.readyState)&&n.send(i)}var o=[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){i.getProxy()&&(e=i.getProxy()+encodeURIComponent(e));var t=new n;return s(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,s,o){function t(){this.initializeProvider()}var i=t.prototype;return i.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={}},i.getProviderSettings=function(){var e=new o;return e.resolve({}),e.promise()},i.setMessageCounter=function(e){this.messageCounter=e},i.initMaster=function(e){this.master=e},i.initPlayer=function(e){this.master=e},i.connect=function(){var e=new o;return e.resolve(),e.promise()},i.disconnect=function(){this.off()},i.setOAuthSettings=function(e){this.emit("oauth:set",e)},i.canProviderLoadExternalXml=function(){return!1},i.canProxyFiles=function(){return!1},i.loadViews=function(t,e,i){var n=new o;return void 0===e&&(e=!1),void 0===i&&(i=this),this.canProviderLoadExternalXml()&&!e?i.emit("view:load",{url:t},function(){n.resolve()}):s.get(t).then(function(e){this.parseViews(e,t,i).then(function(){n.resolve()})}.bind(this)),n.promise()},i.parseViews=function(e,t,i){var n=new o,s=void 0!==t;return void 0===i&&(i=this),s&&void 0!==this.viewNameIdentifierMap[t]?i.emit("view:load",{identifier:this.viewNameIdentifierMap[t]},function(){n.resolve()}):(i.emit("view:load",{xml:e},function(e){s&&e&&e.identifier&&(this.viewNameIdentifierMap[t]=e.identifier),n.resolve()}.bind(this)),this.onParseViews(e)),n.promise()},i.onParseViews=function(e){},i.registerComponent=function(e,t,i){t="string"==typeof t?t:t&&void 0!==t.innerHTML?t.innerHTML:String(t),e='<views><component id="'+e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")+'" xmlns="http://www.w3.org/1999/xhtml">'+t+"</component></views>";return this.parseViews(e,void 0,i)},i.toMaster=function(e,t,i){this.emit(e,t,i)},i.toPlayers=function(e,t,i){this.emit(e,t,i)},i.toPlayer=function(e,t,i,n){i.user=e.getId(),this.emit(t,i,n)},i.toGroup=function(e,t,i,n){i.group=e.getId(),this.emit(t,i,n)},i.emit=function(e,t,i){this.initialized?this.queue?(this.queue.add(e,t,i),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,i):this.postInitializeQueue.push({action:e,data:t,ack:i})},i.createGroup=function(e,t,i,n){this.emit("group:create",{externalId:e,globalViews:t,shareColor:i,tags:n=void 0===n?[]:n})},i.executeQueue=function(){this.initialized&&this.emitAll()},i.setInitialized=function(){var e;for(this.initialized=!0;e=this.postInitializeQueue.shift();)this.emit(e.action,e.data,e.ack)},i.setup=function(e){this.emit("master:setup",e)},i.reset=function(e){this.emit("master:reset",null,function(){e()})},i.getStaticUrl=function(e){return e},i.reconnect=function(e,t,i,n){var s=new o;return this.emit("master:reconnect",{token:e,accessToken:t,gameConfig:i},function(){n(),s.resolve()}.bind(this)),s.promise()},i.off=function(){this.events={}},i.on=function(e,t){this._addEvent(e,t,!1),this._touchEvent(e)},i.once=function(e,t){this._addEvent(e,t,!0),this._touchEvent(e)},i._addEvent=function(e,t,i){void 0===this.events[e]&&(this.events[e]=[]),this.events[e].push({callback:t,once:i})},i._touchEvents=function(){for(var e in this.events)this.events.hasOwnProperty(e)&&this._touchEvent(e)},i._touchEvent=function(e){},i._trigger=function(e,i){var n;void 0!==this.events[e]&&(n=[],this.events[e].forEach(function(e){var t=e.callback;e.once&&n.push(e);try{t.apply(this,[i])}catch(e){console.error(e)}}),0<n.length)&&(n.unshift(this.events),function(e){for(var t,i,n=arguments,s=n.length;1<s&&e.length;)for(t=n[--s];-1!==(i=e.indexOf(t));)e.splice(i,1);return e}.apply(this,n))},i.getConnectURL=function(e){return null},i.getConnectToken=function(e){return null},i.tokenConnect=function(e){var t=new o;return t.resolve(),t.promise()},i.noTokenConnect=function(){var e=new o;return e.resolve(),e.promise()},i.restoreProviderSettings=function(e){},i.serializeProviderSettings=function(){return{}},i.proxyFile=function(e){var t=new o;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,r,a,t){function i(){this.initializeProvider(),this.userId=null,this.randomToken=t.getUuid(),this.loadBalancerSessionToken="connid",this.socket=null,this._registeredEvents={},this._host=null}var l=null,e=i.prototype=new e;return e.getProviderSettings=function(){var t=new a;return r.getServerList()?r.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(n,s){var t,o=new a;return this.log("Loading socket.io"),t=function(){this.log("Connecting to socket.io");var e,t=r.getSocketURL(),i=(this._host?t=this._host:void 0!==s.host&&s.host&&(t=(e=r.getProtocol())?e+"://"+s.host:"//"+s.host,this._host=t),this.socket=l(t+"/"+n+"?"+this.loadBalancerSessionToken+"="+this.randomToken,{withCredentials:!1,reconnection:!0}),!1);this.socket.on("connect_error",function(e){i?this._trigger("disconnect"):(this.socket.off(),this.socket.disconnect(),this.socket=null,o.reject())}.bind(this)),this.socket.once("connect",function(){i||(i=!0,this.setInitialized(),this.socket.io.on("reconnect",function(e){this._trigger("reconnect")}.bind(this)),this._touchEvents(),o.resolve())}.bind(this))}.bind(this),require(["socket.io-client"],function(e){l=e,t()}),o.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,i){this.socket.emit(e,t,i),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 r.getServerList()?r.getServerList().getConnectURL():e},e.getConnectToken=function(e){return r.getServerList()?r.getServerList().getConnectToken(e):e},e.tokenConnect=function(e){var t=new a,i={};if(r.getServerList())try{var n=r.getServerList().getFromToken(e);i.host=n.host,e=n.token}catch(e){return t.reject(),t.promise()}return this.connect("remote",i).fail(function(){t.reject()}).then(function(){t.resolve(e)}),t.promise()},e.restoreProviderSettings=function(e){void 0!==e.serverlist&&r.getServerList()&&r.getServerList().unserialize(e.serverlist),void 0!==e.host&&(this._host=e.host)},e.serializeProviderSettings=function(){var e={host:this._host};return r.getServerList()&&(e.serverlist=r.getServerList().serialize()),e},i}),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,i){function e(e){this.peakThreshold=(e=e||{}).peakThreshold||-65,this.minRunLength=e.minRunLength||2,this.coder=e.coder||new i(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=n,this.isRunning=!1,this.iteration=0}var n=1,s=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,i=this.freqToIndex(this.coder.freqMin);i<this.freqs.length;i++)this.freqs[i]>e&&(e=this.freqs[i],t=i);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=n,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==n?e==this.coder.startChar&&(this.buffer="",this.state=s):this.state==s&&(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=n,this.fire_(this.callbacks.message,this.buffer),this.buffer=""))},e.prototype.getLastRun=function(){for(var e=this.peakHistory.last(),t=0,i=this.peakHistory.length()-2;0<=i&&this.peakHistory.get(i)==e;i--)t+=1;return t>this.minRunLength?(this.peakHistory.remove(i+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 i=this.freqs[t]+400,i=e.height-i-1,n=e.width/this.freqs.length;drawContext.fillStyle="black",drawContext.fillRect(t*n,i,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 i=!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 i}return"undefined"!=typeof window&&(i=window.AudioContext||window.webkitAudioContext||!1),e.prototype.send=function(e,t){e=this.coder.startChar+e+this.coder.endChar;for(var i,n=0;n<e.length;n++){var s=e[n],s=this.coder.charToFreq(s),o=this.audioContext.currentTime+this.charDuration*n;this.scheduleToneAt(s,o,this.charDuration)}t&&(i=this.charDuration*e.length,setTimeout(t,1e3*i))},e.prototype.scheduleToneAt=function(e,t,i){var n=this.audioContext.createGain(),i=(n.gain.value=0,n.gain.setValueAtTime(0,t),n.gain.linearRampToValueAtTime(1,t+this.rampDuration),n.gain.setValueAtTime(1,t+i-this.rampDuration),n.gain.linearRampToValueAtTime(0,t+i),n.connect(this.audioContext.destination),this.audioContext.createOscillator());i.frequency.value=e,i.connect(n),i.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,i,n,s,o){function r(e){this.options=t.getAudioSyncConfig(),this.alphabet=this.options.alphabet.split(""),this.controller=e}var a=r.prototype;return a.startListener=function(){this.stop();var e=new n(this.options);e.start(),e.on("message",this.onIncomingMessage.bind(this)),this.sonicServer=e},a.startSender=function(){this.sonicSocket=new s(this.options)},a.stop=function(){this.sonicServer&&this.sonicServer.stop()},a.sync=function(){var e=new o,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,i="",n="",s=0;s<e;s++){for(;t=Math.floor(Math.random()*this.alphabet.length),(n=this.alphabet[t])===i.substr(i.length-1,1););i+=n}return i},a.getParityLetter=function(e){for(var t=0,i=e.split(""),n=0;n<i.length;n++)t+=this.alphabet.indexOf(i[n]);e=t%this.alphabet.length;return i[i.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),i=this.getParityLetter(t);i===e[e.length-1]?this.onMessage(t):console.log("Parity check failed, expected "+i+", ignoring message")},a.onMessage=function(e){this.controller.emit("sync:audio",{secret:e})},a.generateAlphabet=function(e){for(var t="",i=0;i<Math.min(e.length,9);i++)t+=i.toString();return t},r}),define("CatLab/Webremote/Tools/ClientSniffer",[],function(){function e(){this._canPlayWebM=null}var t=e.prototype;return t.isMobileBrowser=function(){var e,t;return!(!this.isCordova()&&(e=!1,t=navigator.userAgent||navigator.vendor||window.opera,!/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t))&&!/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4)))||e},t.isCordova=function(){return"undefined"!=typeof cordova},t.isInternetExplorer=function(){var e=window.navigator.userAgent,t=e.indexOf("MSIE ");return 0<t?parseInt(e.substring(t+5,e.indexOf(".",t)),10):0<e.indexOf("Trident/")?(t=e.indexOf("rv:"),parseInt(e.substring(t+3,e.indexOf(".",t)),10)):0<(t=e.indexOf("Edge/"))&&parseInt(e.substring(t+5,e.indexOf(".",t)),10)},t.supportsLocalStorage=function(){try{if(window.localStorage)return!0}catch(e){return!1}},t.canPlayWebM=function(){if(null===this._canPlayWebM){this._canPlayWebM=!1;try{var e=document.createElement("video");e.canPlayType&&(this._canPlayWebM=e.canPlayType('video/webm; codecs="vp8, vorbis"'))}catch(e){console.error(e)}}return this._canPlayWebM},new e}),define("CatLab/Webremote/Components/ImagePositionInputComponent",["CatLab/Webremote/Tools/ClientSniffer"],function(s){function e(e,t){this.element=t,this.remotePlayerView=e,this.positions=[],this.canvas=null,this.isLoaded=!1,this.isRotated=!1,this.buttons=null,this.pointCountContainer=null,this.draw()}var t=e.prototype;return t.draw=function(){this.element.innerHTML="",this.rotatedImageElement=null,this.buttons=null,this.circleRadius=this.element.getAttribute("circleRadius")||2,this.circleStroke=this.element.getAttribute("circleStroke")||Math.max(.5,this.circleRadius/5),this.circleStrokeColor=this.element.getAttribute("circleStrokeColor")||"red",this.circleFillColor=this.element.getAttribute("circleFillColor")||"rgb(255,255,0,0.3)",this.image=this.element.getAttribute("src"),this.image&&(this.element.innerHTML='<div class="image"><img /></div>',this.imageElement=this.element.querySelector("img"),this.imageElement.addEventListener("load",function(){this.isLoaded=!0,this.resizeImage()}.bind(this)),this.imageElement.setAttribute("src",this.image),this.resizeImage(),this.imageElement.addEventListener("dragstart",function(e){e.preventDefault()}),this.svgContainer=document.createElement("div"),this.svgContainer.className="pointer-container",this.element.querySelector(".image").appendChild(this.svgContainer),this.resizeSvgContainer(),this.svgContainer.addEventListener("click",function(e){this.svgClick(e)}.bind(this)))},t.resizeSvgContainer=function(){var e=this.imageElement;this.isRotated&&this.rotatedImageElement&&(e=this.rotatedImageElement),this.svgContainer.style.position="absolute",this.svgContainer.style.zIndex="1",this.svgContainer.style.width=e.offsetWidth+"px",this.svgContainer.style.height=e.offsetHeight+"px",this.svgContainer.style.left=e.offsetLeft+"px",this.svgContainer.style.top=e.offsetTop+"px"},t.resizeImage=function(){var e,t,i,n;this.isLoaded&&(e=this.element.clientWidth,t=this.element.clientHeight,i=this.imageElement.naturalWidth,n=this.imageElement.naturalHeight,s.isMobileBrowser()&&"1"==this.element.getAttribute("rotate")?this.isRotated=e/t<1!=i/n<1:this.isRotated=!1,this.isRotated?this.element.classList.add("rotated"):this.element.classList.remove("rotated"),this.isRotated?(this.generateCanvas(),this.rotatedImageElement.style.display="",this.resizeSvgContainer(),this.imageElement.style.display="none"):this.rotatedImageElement&&(this.rotatedImageElement.style.display="none",this.imageElement.style.display=""),this.imageElement.style.maxWidth=e+"px",this.imageElement.style.maxHeight=t+"px",this.rotatedImageElement&&(this.rotatedImageElement.style.maxWidth=e+"px",this.rotatedImageElement.style.maxHeight=t+"px"),this.resizeSvgContainer())},t.generateCanvas=function(){var e,t,i,n,s,o,r,a;this.rotatedImageElement||(s=this.imageElement,e=this.imageElement.naturalWidth,t=this.imageElement.naturalHeight,(i=document.createElement("canvas")).width=t,i.height=e,n=i.getContext("2d"),s=s,o=i.width/2,r=i.height/2,a=0-Math.PI/2,n.setTransform(1,0,0,1,o,r),n.rotate(a),n.drawImage(s,-e/2,-t/2),this.rotatedImageElement=i,this.element.querySelector("div.image").appendChild(this.rotatedImageElement))},t.imageClick=function(e){var t=e.offsetX/this.imageElement.offsetWidth,e=e.offsetY/this.imageElement.offsetHeight;this.selectPosition(t,e)},t.svgClick=function(e){var t=e.offsetX/this.svgContainer.offsetWidth,e=e.offsetY/this.svgContainer.offsetHeight;this.isRotated?this.selectPosition(1-e,t):this.selectPosition(t,e)},t.canvasClick=function(e){var t=e.offsetX/this.rotatedImageElement.offsetWidth,e=e.offsetY/this.rotatedImageElement.offsetHeight;this.selectPosition(1-e,t)},t.selectPosition=function(e,t){0<this.getMaxPoints()&&this.positions.length>=this.getMaxPoints()||(this.positions.push({x:e,y:t}),this.drawCircles(),this.shouldConfirmPosition()?(this.syncPositionData(!1),this.showSubmitButton()):this.submit())},t.shouldConfirmPosition=function(){return"1"==this.element.getAttribute("confirm-position")},t.getMinPoints=function(){return this.element.getAttribute("min-points")&&0<parseInt(this.element.getAttribute("min-points"))?parseInt(this.element.getAttribute("min-points")):1},t.getMaxPoints=function(){return this.element.getAttribute("max-points")&&0<parseInt(this.element.getAttribute("max-points"))?parseInt(this.element.getAttribute("max-points")):1},t.showSubmitButton=function(){var e;this.buttons?this.positionSubmitButton():((e=document.createElement("div")).className="imagemap-buttons",e.innerHTML='<button data-action="submit" class="imagemap-button pulsating">'+(2<this.getMaxPoints()?'<span class="point-counter"></span>':"")+'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 22"><path d="M20.285 2l-11.285 11.567-5.286-5.011-3.714 3.716 9 8.728 15-15.285z"/></svg></button><button data-action="reset" class="imagemap-button"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 22"><path d="M24 20.188l-8.315-8.209 8.2-8.282-3.697-3.697-8.212 8.318-8.31-8.203-3.666 3.666 8.321 8.24-8.206 8.313 3.666 3.666 8.237-8.318 8.285 8.203z" /></button>',this.buttons=e,this.element.appendChild(this.buttons),this.positionSubmitButton(),this.buttons.querySelector("button[data-action=submit]").addEventListener("click",function(){this.submit()}.bind(this)),this.buttons.querySelector("button[data-action=reset]").addEventListener("click",function(){this.reset(),this.hideSubmitButton()}.bind(this)),this.pointCountContainer=this.buttons.querySelector(".point-counter"),this.updatePointCount())},t.updatePointCount=function(){var e;this.pointCountContainer&&(this.pointCountContainer.innerHTML=this.positions.length,this.positions.length<this.getMinPoints()?this.pointCountContainer.classList.add("insufficient"):this.pointCountContainer.classList.remove("insufficient"),e=this.buttons.querySelector("button[data-action=submit]"),this.positions.length>=this.getMinPoints()?(e.classList.add("pulsating"),e.classList.remove("disabled")):(e.classList.remove("pulsating"),e.classList.add("disabled")))},t.hideSubmitButton=function(){this.buttons.style.display="none"},t.positionSubmitButton=function(){this.buttons.style.display="",.5<this.positions[0].x?(this.buttons.classList.add("left"),this.buttons.classList.remove("right")):(this.buttons.classList.add("right"),this.buttons.classList.remove("left"))},t.submit=function(){this.syncPositionData(!0)},t.syncPositionData=function(e){this.positions.length<this.getMinPoints()||this.remotePlayerView.controller.syncValue("position",{x:0<this.positions.length?this.positions[0].x:null,y:0<this.positions.length?this.positions[0].y:null,p:this.positions,c:e},this.remotePlayerView.viewId)},t.drawCircles=function(){this.updatePointCount(),this.svgContainer.innerHTML="",0!==this.positions.length&&this.positions.forEach(function(t){var e=this.imageElement,i=t.x,n=t.y,s=e.offsetWidth,e=e.offsetHeight,o=(this.isRotated&&this.rotatedImageElement&&(i=t.y,n=1-t.x,s=this.rotatedImageElement.offsetWidth,e=this.rotatedImageElement.offsetHeight),this.imageElement.offsetWidth/100*this.circleRadius),r=Math.max(1,this.imageElement.offsetWidth/100*this.circleStroke),a="http://www.w3.org/2000/svg",l=document.createElementNS(a,"svg"),a=document.createElementNS(a,"circle");l.appendChild(a),l.addEventListener("click",function(e){e.preventDefault(),e.stopPropagation(),this.removePoint(t),0===this.positions.length&&this.hideSubmitButton()}.bind(this)),this.svgContainer.appendChild(l),a.setAttribute("cx",o+r),a.setAttribute("cy",o+r),a.setAttribute("r",o),a.setAttribute("stroke-width",r),a.setAttribute("stroke",this.circleStrokeColor),a.setAttribute("fill",this.circleFillColor),l.setAttribute("width",2*(o+r)),l.setAttribute("height",2*(o+r)),l.style.position="absolute",l.style.left=s*i-o-r+"px",l.style.top=e*n-o-r+"px"}.bind(this))},t.removePoint=function(e){e=this.positions.indexOf(e);-1<e&&this.positions.splice(e,1),this.drawCircles()},t.resize=function(){this.resizeImage(),this.drawCircles()},t.update=function(){this.draw()},t.destroy=function(){},t.reset=function(){this.positions=[],this.drawCircles()},e.css=" \t\t\t\timage-position-input {\t\t\t\t\tdisplay: flex; \t\t\t\t\tjustify-content: center;\t\t\t\t\talign-content: center;\t\t\t\t\talign-items: center;\t\t\t\t\twidth: 100%;\t\t\t\t\theight: 100%;\t\t\t\t\tposition: relative;\t\t\t\t\toverflow: hidden;\t\t\t\t} \t\t\t\t \t\t\t\timage-position-input .image { \t\t\t\t\ttext-align: center;\t\t\t\t\ttransform-origin: 0 0; \t\t\t\t} \t\t\t\timage-position-input .image img, \t\t\t\timage-position-input .image canvas { \t\t\t\t\tdisplay: block;\t\t\t\t\tmax-width: 100%;\t\t\t\t\tmax-height: 100%;\t\t\t\t\theight: auto;\t\t\t\t\twidth: auto; \t\t\t\t} \t\t\t\timage-position-input button.imagemap-button svg { \t\t\t\t\theight: 48px; \t\t\t\t\twidth: 48px; \t\t\t\t} \t\t\t\timage-position-input button.imagemap-button { \t\t\t\t\tmargin-left: 10px; \t\t\t\t\tposition: relative; \t\t\t\t} \t\t\t\timage-position-input button.imagemap-button.disabled svg {\t\t\t\t\tfill: gray;\t\t\t\t}\t\t\t\timage-position-input .imagemap-buttons { \t\t\t\t\tposition: absolute; \t\t\t\t\tright: 10px; \t\t\t\t\tbottom: 10px; \t\t\t\t\tz-index: 10; \t\t\t\t} \t\t\t\t\t\t\t\timage-position-input .imagemap-buttons.left {\t\t\t\t\tleft: 10px;\t\t\t\t\tright: auto;\t\t\t\t}\t\t\t\t\t\t\t\timage-position-input.rotated .imagemap-buttons {\t\t\t\t\ttransform: rotate(-90deg);\t\t\t\t\ttransform-origin: 100% 0;\t\t\t\t\ttop: 10px;\t\t\t\t\tright: 80px;\t\t\t\t\tbottom: auto;\t\t\t\t\tleft: auto;\t\t\t\t}\t\t\t\timage-position-input.rotated .imagemap-buttons.left {\t\t\t\t\tbottom: 80px;\t\t\t\t\ttop: auto;\t\t\t\t\tright: 80px; \t\t\t\t\tleft: auto;\t\t\t\t\ttransform-origin: 100% 0;\t\t\t\t}\t\t\t\timage-position-input button.pulsating .point-counter {\t\t\t\t}\t\t\t\timage-position-input .point-counter {\t\t\t\t\tfont-size: 1em;\t\t\t\t\tvertical-align: middle;\t\t\t\t\tposition: absolute;\t\t\t\t\ttop: -1em;\t\t\t\t\tleft: -1em;\t\t\t\t\tborder: 1px solid black;\t\t\t\t\tborder-radius: 100%;\t\t\t\t\tpadding: 0.5em;\t\t\t\t\tbackground: white;\t\t\t\t\tmin-width: 1em;\t\t\t\t}\t\t\t\timage-position-input .point-counter.insufficient {\t\t\t\t\tborder-color: red;\t\t\t\t\tcolor: red;\t\t\t\t}\t\t",e.selector="image-position-input",e}),define("CatLab/Webremote/Components/FullscreenButtonComponent",["CatLab/Webremote/Tools/Screenfull","CatLab/Webremote/Config"],function(e,t){function i(e,t,i){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=i,this.draw()}var n=i.prototype;return n.draw=function(){t.canFullscreen()&&e&&e.isEnabled&&!e.isFullscreen?(this.element.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" style="display: block" width="100%" height="100%" viewBox="0 0 24 24"><path d="M6.426 10.668l-3.547-3.547-2.879 2.879v-10h10l-2.879 2.879 3.547 3.547-4.242 4.242zm11.148 2.664l3.547 3.547 2.879-2.879v10h-10l2.879-2.879-3.547-3.547 4.242-4.242zm-6.906 4.242l-3.547 3.547 2.879 2.879h-10v-10l2.879 2.879 3.547-3.547 4.242 4.242zm2.664-11.148l3.547-3.547-2.879-2.879h10v10l-2.879-2.879-3.547 3.547-4.242-4.242z"/></svg>',this.element.addEventListener("click",function(){e.request(null,{navigationUI:"hide"})}.bind(this))):this.element.innerHTML=""},n.resize=function(){this.draw()},n.update=function(){this.draw()},n.destroy=function(){},i.css=" ",i.selector="fullscreen-button",i}),define("CatLab/Webremote/Components/ViewDefinedComponent",[],function(){function e(e,t){this.element=t,this.remotePlayerView=e,this.position=null,this.draw()}var t=e.prototype;return t.draw=function(){if(this.element){this.element.innerHTML="";for(var e=0;e<this.content.childNodes.length;e++)this.element.appendChild(this.content.childNodes[e].cloneNode(!0));this.componentContainer.attachComponents(this.remotePlayerView,this.element)}},t.update=function(){this.draw()},t.resize=function(){this.draw()},t.destroy=function(){},e.css=" ",e.selector="view-defined-component",e.content="",e}),define("CatLab/Webremote/Views/Popups/IframePopup",["CatLab/Webremote/Views/Popups/BasePopup"],function(e){function t(e){this.url=e}return(t.prototype=new e).renderContent=function(e){this.container.className+=" iframe";var t=document.createElement("iframe");t.src=this.url,t.style.height="99%",t.style.width="100%",t.style.borderWidth="0",e.appendChild(t),e.style.position="relative",e.style.height="100%",e.style.width="100%",e.style.boxSizing="border-box",e.style.overflow="auto",e.style.webkitOverflowScrolling="touch"},t}),define("CatLab/Webremote/Components/ModalIframeLink",["CatLab/Webremote/Views/Popups/IframePopup"],function(t){function e(e,t,i){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=i,this.draw()}var i=e.prototype;return i.draw=function(){this._clickHandler&&this.element.removeEventListener("click",this._clickHandler),this._clickHandler=function(){var e=this.element.getAttribute("href"),e=this.remotePlayerView.stringInterpolateDataElements(e,encodeURIComponent);new t(e).render(document.body)}.bind(this),this.element.addEventListener("click",this._clickHandler)},i.resize=function(){this.draw()},i.update=function(){this.draw()},i.destroy=function(){},e.css=" ",e.selector="modal-iframe-link",e}),define("CatLab/Webremote/Views/Popups/TextPopup",["CatLab/Webremote/Views/Popups/BasePopup"],function(e){function t(e){this.message=e}return(t.prototype=new e).renderContent=function(e){var t=(t=this.message).replace(/(?:\r\n|\r|\n)/g,"<br>");e.innerHTML=t},t}),define("CatLab/Webremote/Components/TooltipComponent",["CatLab/Webremote/Views/Popups/TextPopup"],function(e){function t(e,t,i){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=i,this.draw()}var i=t.prototype;return i.draw=function(){this._clickHandler&&this.element.removeEventListener("click",this._clickHandler),this._clickHandler=function(){new e(this.element.getAttribute("data-tooltip")).render(document.body)}.bind(this),this.element.addEventListener("click",this._clickHandler)},i.resize=function(){},i.update=function(){},i.destroy=function(){},t.css=" ",t.selector="[data-tooltip]",t}),define("CatLab/Webremote/Components/VirtualKeyboardComponent",["SimpleKeyboard","CatLab/Webremote/Config"],function(n,s){var o,r=!1,a=null,e=0;function l(){for(var e=document.querySelectorAll(".simple-keyboard"),t=0;t<e.length;t++)e[t].classList.add("hidden");a=null}function t(e,t,i){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=i,this.inputType=t.getAttribute("type")?t.getAttribute("type").toLowerCase():"text",this.draw()}var i=t.prototype;return i.draw=function(){(function(){if(!r){var e=document.createElement("link"),e=(e.type="text/css",e.rel="stylesheet",e.href=s.getVendorPath()+"simple-keyboard/build/css/index.css",document.head.appendChild(e),document.createElement("div"));e.className="simple-keyboard",document.body.appendChild(e),o=new n.default({onChange:function(e){a&&a.onKeyboardChange(e)}.bind(this),onKeyPress:function(e){switch(e){case"{shift}":case"{lock}":t="default"===o.options.layoutName?"shift":"default",o.setOptions({layoutName:t});break;case"{numbers}":case"{abc}":t="numbers"!==o.options.layoutName?"numbers":"default",o.setOptions({layoutName:t});break;case"{ent}":l();break;case"{arrowup}":a.increaseValue(1);break;case"{arrowdown}":a.increaseValue(-1)}var t}.bind(this),layoutName:"default",layout:{default:["q w e r t y u i o p","a s d f g h j k l","{shift} z x c v b n m {backspace}","{numbers} {space} {ent}"],shift:["Q W E R T Y U I O P","A S D F G H J K L","{shift} Z X C V B N M {backspace}","{numbers} {space} {ent}"],numbers:["1 2 3","4 5 6","7 8 9","{abc} 0 {backspace}"]},physicalKeyboardHighlight:!0,disableCaretPositioning:!1,mergeDisplay:!0,display:{"{numbers}":"123","{ent}":"⇩","{escape}":"esc ⎋","{tab}":"tab ⇥","{backspace}":"⌫","{capslock}":"caps lock ⇪","{shift}":"⇧","{controlleft}":"ctrl ⌃","{controlright}":"ctrl ⌃","{altleft}":"alt ⌥","{altright}":"alt ⌥","{metaleft}":"cmd ⌘","{metaright}":"cmd ⌘","{abc}":"ABC"}});for(var t=document.querySelectorAll(".simple-keyboard"),i=0;i<t.length;i++)t[i].classList.add("hidden");r=!0}})(),this.element.id||(this.element.id="input_"+ ++e),this.element.type="text",/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)&&(this.element.readOnly=!0),this.element.addEventListener("input",this.onInputChange.bind(this)),this.element.addEventListener("focus",this.onInputFocus.bind(this)),this.element.classList.contains("visible")&&this.onInputFocus()},i.hideKeyboard=function(){l()},i.showKeyboard=function(){var e=this,t=this.inputType,i=e.element;"number"===t?o.setOptions({inputName:i.id,layoutName:"numbers",layout:{default:["q w e r t y u i o p","a s d f g h j k l","{shift} z x c v b n m {backspace}","{numbers} {space} {ent}"],numbers:["1 2 3 {arrowup}","4 5 6 {arrowdown}","7 8 9 "+1.1.toLocaleString().substring(1,2),"{backspace} 0 {ent}"]}}):o.setOptions({inputName:i.id,layoutName:"default",layout:{default:["q w e r t y u i o p","a s d f g h j k l","{shift} z x c v b n m {backspace}","{numbers} {space} {ent}"],shift:["Q W E R T Y U I O P","A S D F G H J K L","{shift} Z X C V B N M {backspace}","{numbers} {space} {ent}"],numbers:["1 2 3","4 5 6","7 8 9","{abc} 0 {backspace}"]}});for(var n=document.querySelectorAll(".simple-keyboard"),s=0;s<n.length;s++)n[s].classList.remove("hidden");a=e,o.setInput(i.value,i.id)},i.onKeyboardChange=function(e){this.element.value=e;var t=new Event("change",{bubbles:!0});this.element.dispatchEvent(t),this.element.getAttribute("data-value-realtime")&&(t=this.element.getAttribute("data-value-id"))&&this.remotePlayerView.controller.syncValue(t,e,this.remotePlayerView.viewId)},i.onInputChange=function(){o.setInput(this.element.value,this.element.id)},i.onInputFocus=function(){this.showKeyboard()},i.setInputCaretPosition=function(e){this.element.setSelectionRange&&(this.element.focus(),this.element.setSelectionRange(e,e))},i.increaseValue=function(e){var t;"number"===this.inputType&&(t=(t=parseFloat(this.element.value))||0,this.element.value=t+e)},i.submit=function(){this.hideKeyboard()},i.resize=function(){this.draw()},i.update=function(){this.draw()},i.destroy=function(){this.hideKeyboard()},t.css=" .simple-keyboard { position: fixed; bottom: 0; display: block; } .simple-keyboard.hidden { display: none; } ",t.selector="input.virtual",t}),define("CatLab/Webremote/Components/TimerComponent",[],function(){function e(e,t){this.element=t,this.remotePlayerView=e,this.draw(),this.countdownInterval=setInterval(function(){this.tick()}.bind(this),100),this.startDate=Date.now(),this.targetDate=null,this.counterHtml=null,this.progessBar=null}var t=e.prototype;return t.draw=function(){var e,t=this.element;t.innerHTML="",this.targetDate=this.element.getAttribute("to"),this.targetDate&&((e=this.element.getAttribute("start"))&&(this.startDate=e),(e=document.createElement("div")).className="timer-container",this.counterHtml=document.createElement("div"),this.counterHtml.className="countdown",e.appendChild(this.counterHtml),this.progessBar=document.createElement("div"),this.progessBar.className="progress-bar",this.progessBar.innerHTML="&nbsp;",e.appendChild(this.progessBar),t.appendChild(e))},t.tick=function(){var e,t;this.targetDate&&this.counterHtml&&this.progessBar&&((e=this.targetDate-Date.now())<0?this.counterHtml.innerHTML="0":(t=(Date.now()-this.startDate)/(this.targetDate-this.startDate)*100,this.counterHtml.innerHTML=Math.ceil(e/1e3),this.progessBar.style.width=t+"%"))},t.resize=function(){},t.update=function(){this.draw()},t.clearInterval=function(){this.countdownInterval&&(clearInterval(this.countdownInterval),this.countdownInterval=null)},t.destroy=function(){this.clearInterval()},e.css=" timer-countdown { position: fixed; bottom: 0px; left: 0px; width: 100%; color: white; z-index: 1000; } timer-countdown .progress-bar { position:absolute; height: 3px; bottom: 0; background: #eca93b; } timer-countdown .countdown { display: none; } ",e.selector="timer-countdown",e}),define("CatLab/Webremote/Components/SmileyFlingerComponent",["CatLab/Webremote/Views/Blocks/CurrentSmiley"],function(n){function e(e,t,i){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=i,this.smileySlinger=new n(i.Webremote,!0,!0,!1),this.draw()}var t=e.prototype;return t.draw=function(){this.smileySlinger.render(this.element)},t.resize=function(){this.draw()},t.update=function(){this.draw()},t.destroy=function(){},e.css=" ",e.selector="smiley-flinger",e}),define("CatLab/Webremote/Components/CheatDetectionComponent",[],function(){function e(e,t,i){this.element=t,this.remotePlayerView=e,this.componentContainer=i,this._cheatCheckTimer=null,this._hiddenAt=null,this._onVisibilityChange=this._handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this._onVisibilityChange)}var t=e.prototype;return t._handleVisibilityChange=function(){document.hidden?(this._hiddenAt=Date.now(),null!==this._cheatCheckTimer&&clearTimeout(this._cheatCheckTimer),this._cheatCheckTimer=setTimeout(function(){this._cheatCheckTimer=null,Date.now()-this._hiddenAt<5e3&&this._triggerCheatDetected()}.bind(this),1500)):null!==this._cheatCheckTimer&&(clearTimeout(this._cheatCheckTimer),this._cheatCheckTimer=null)},t._triggerCheatDetected=function(){this.componentContainer&&this.componentContainer.Webremote&&this.componentContainer.Webremote.userEvents&&(this.componentContainer.Webremote.userEvents.trigger("cheat:detected",{}),this.componentContainer.Webremote.groupEvents.trigger("cheat:detected",{}))},t.draw=function(){},t.update=function(){},t.destroy=function(){document.removeEventListener("visibilitychange",this._onVisibilityChange),null!==this._cheatCheckTimer&&(clearTimeout(this._cheatCheckTimer),this._cheatCheckTimer=null)},t.resize=function(){},e.selector="cheat-detection",e}),define("CatLab/Webremote/Components/Components",["./ImagePositionInputComponent","./FullscreenButtonComponent","./ViewDefinedComponent","./ModalIframeLink","./TooltipComponent","./VirtualKeyboardComponent","./TimerComponent","./SmileyFlingerComponent","./CheatDetectionComponent"],function(t,i,s,n,o,r,a,l,c){function e(e){this.components=[t,i,n,o,r,a,l,c],this.Webremote=e,this.viewDefinedComponents=[],this.existingComponents=[]}var h=e.prototype;return h.initialize=function(){for(var e=0;e<this.components.length;e++)this.initializeComponent(this.components[e])},h.initializeComponent=function(e){e.css;var t=document.createElement("style");t.attributes.type="text/css",t.innerHTML=e.css,document.head.appendChild(t)},h.resetViewDefinedComponents=function(){for(var e=0;e<this.viewDefinedComponents.length;e++)this.removeComponent(this.viewDefinedComponents[e])},h.destroyExistingComponentsBySelector=function(e){for(var t=this.existingComponents.length-1;0<=t;t--)this.existingComponents[t].constructor&&this.existingComponents[t].constructor.selector===e&&(this.existingComponents[t].destroy(),this.existingComponents.splice(t,1))},h.removeComponent=function(e){this.destroyExistingComponentsBySelector(e);for(var t=0;t<this.components.length;t++)if(this.components[t].selector===e)return void this.components.splice(t,1)},h.addComponent=function(e){0<=this.components.indexOf(e)||(this.components.push(e),this.initializeComponent(e))},h.addViewDefinedComponent=function(e,n){for(var t=0;t<this.components.length;t++)if(this.components[t].selector===e){this.destroyExistingComponentsBySelector(e),this.components.splice(t,1);break}function i(e,t,i){this.element=t,this.remotePlayerView=e,this.position=null,this.content=n,this.componentContainer=i,this.draw()}this.viewDefinedComponents.push(e),((i.prototype=new s).constructor=i).selector=e,i.content=n,this.components.push(i),this.Webremote._currentView&&this.attachComponent(this.Webremote._currentView,document.body,i)},h.attach=function(e,t,i){(i=void 0===i?!0:i)&&(this.existingComponents.forEach(function(e){e.destroy()}.bind(this)),this.existingComponents=[]),this.attachComponents(e,t)},h.resize=function(){this.existingComponents.forEach(function(e){e.resize()}.bind(this))},h.update=function(){this.existingComponents.forEach(function(e){e.update()}.bind(this))},h.attachComponents=function(e,t){for(var i=0;i<this.components.length;i++)try{this.attachComponent(e,t,this.components[i])}catch(e){console.log(e)}},h.attachComponent=function(e,t,i){for(var n=(t instanceof HTMLElement?t:t[0]).querySelectorAll(i.selector),s=0;s<n.length;s++){var o=new i(e,n[s],this);this.existingComponents.push(o)}},e}),!function(){var e,t;e=this,t=function(){var a,l,c,i,e,n=!1,t=window.navigator.userAgent,h=/([+-]?[0-9.]+)(vh|vw|vmin|vmax)/g,s=/(https?:)?\/\//,u=[].forEach,d=/MSIE [0-9]\./i.test(t),f=/MSIE [0-8]\./i.test(t),m=-1<t.indexOf("Opera Mini"),p=/(iPhone|iPod|iPad).+AppleWebKit/i.test(t)&&(e=t.match(/OS (\d)/))&&1<e.length&&parseInt(e[1])<10,g=-1<t.indexOf(" Android ")&&-1<t.indexOf("Version/")&&parseFloat((t.match("Android ([0-9.]+)")||[])[1])<=4.4,d=d||!!navigator.userAgent.match(/MSIE 10\.|Trident.*rv[ :]*1[01]\.| Edge\/1\d\./);try{new b("test")}catch(a){var b=function(e,t){var i;return t=t||{bubbles:!1,cancelable:!1,detail:void 0},(i=document.createEvent("CustomEvent")).initCustomEvent(e,t.bubbles,t.cancelable,t.detail),i};b.prototype=window.Event.prototype,window.CustomEvent=b}function v(){n&&(o(),setTimeout(function(){i.textContent=y(),i.parentNode.appendChild(i),window.dispatchEvent(new b("viewport-units-buggyfill-style"))},1))}function o(){return c=[],u.call(document.styleSheets,function(e){var t=(e=>{try{if(!e.cssRules)return}catch(e){if("SecurityError"!==e.name)throw e;return}for(var t=[],i=0;i<e.cssRules.length;i++){var n=e.cssRules[i];t.push(n)}return t})(e);!t||"patched-viewport"===e.ownerNode.id||"ignore"===e.ownerNode.getAttribute("data-viewport-units-buggyfill")||e.media&&e.media.mediaText&&window.matchMedia&&!window.matchMedia(e.media.mediaText).matches||u.call(t,r)}),c}function r(i){if(7===i.type){var e;try{e=i.cssText}catch(e){return}h.lastIndex=0,h.test(e)&&!s.test(e)&&(c.push([i,null,e]),a.hacks)&&a.hacks.findDeclarations(c,i,null,e)}else i.style?u.call(i.style,function(e){var t=i.style.getPropertyValue(e);i.style.getPropertyPriority(e)&&(t+=" !important"),h.lastIndex=0,h.test(t)&&(c.push([i,e,t]),a.hacks)&&a.hacks.findDeclarations(c,i,e,t)}):i.cssRules&&u.call(i.cssRules,function(e){r(e)})}function y(){var e=window.innerHeight,t=window.innerWidth;l={vh:e,vw:t,vmax:Math.max(t,e),vmin:Math.min(t,e)};var n,s,o=[],r=[];return c.forEach(function(e){var e=function(e,t,i){var n=[];i=i.replace(h,w),a.hacks&&(i=a.hacks.overwriteDeclaration(e,t,i)),t&&(n.push(e.selectorText),i=t+": "+i+";");for(var s=e.parentRule;s;)s.media?n.unshift("@media "+s.media.mediaText):s.conditionText&&n.unshift("@supports "+s.conditionText),s=s.parentRule;return{selector:n,content:i}}.apply(null,e),t=e.selector.length?e.selector.join(" {\n")+" {\n":"",i=new Array(e.selector.length+1).join("\n}");t&&t===n?(t&&!n&&(n=t,s=i),r.push(e.content)):(r.length&&(o.push(n+r.join("\n")+s),r.length=0),t?(n=t,s=i,r.push(e.content)):(o.push(e.content),s=n=null))}),r.length&&o.push(n+r.join("\n")+s),m&&o.push("* { content: normal !important; }"),o.join("\n\n")}function w(e,t,i){i=l[i];return parseFloat(t)/100*i+"px"}function C(e){return e.slice(0,e.indexOf("/",e.indexOf("://")+3))}return{version:"0.6.1",findProperties:o,getCss:y,init:function(e){if(!n){if((a=(e=!0===e?{force:!0}:e)||{}).isMobileSafari=p,a.isBadStockAndroid=g,!a.ignoreVmax||a.force||f||(d=!1),f||!a.force&&!p&&!d&&!g&&!m&&(!a.hacks||!a.hacks.required(a)))return window.console&&f&&console.info("viewport-units-buggyfill requires a proper CSSOM and basic viewport unit support, which are not available in IE8 and below"),{init:function(){}};var t,o,r;window.dispatchEvent(new b("viewport-units-buggyfill-init")),a.hacks&&a.hacks.initialize(a),n=!0,(i=document.createElement("style")).id="patched-viewport",document[a.appendToBody?"body":"head"].appendChild(i),t=function(){function e(){var e=this,t=arguments;clearTimeout(s),s=setTimeout(function(){i.apply(e,t)},n)}var i,n,s;i=v,n=a.refreshDebounceWait||100;window.addEventListener("orientationchange",e,!0),window.addEventListener("pageshow",e,!0),(a.force||d||(()=>{try{return window.self!==window.top}catch(e){return 1}})())&&(window.addEventListener("resize",e,!0),a._listeningToResize=!0),a.hacks&&a.hacks.initializeEvents(a,v,e),v()},o=0,r=function(){--o||t()},u.call(document.styleSheets,function(e){if(e.href&&C(e.href)!==C(location.href)&&"ignore"!==e.ownerNode.getAttribute("data-viewport-units-buggyfill")){o++;var t=e.ownerNode,i=r,e=t.href,n=i,s=new XMLHttpRequest;if("withCredentials"in s)s.open("GET",e,!0);else{if("undefined"==typeof XDomainRequest)throw new Error("cross-domain XHR not supported");(s=new XDomainRequest).open("GET",e)}s.onload=function(){var e=document.createElement("style");e.media=t.media,e.setAttribute("data-href",t.href),e.textContent=this.responseText,t.parentNode.replaceChild(e,t),i()},s.onerror=n,s.send()}}),o||t()}},refresh:v}},"function"==typeof define&&define.amd?define("viewport-units-buggyfill",[],t):"object"==typeof exports?module.exports=t():e.viewportUnitsBuggyfill=t()}(),!function(){var e,t;e=this,t=function(){var r=/calc\(/g,a=/["']/g,e=window.navigator.userAgent,n=(n=/MSIE [0-9]\./i.test(e))||!!navigator.userAgent.match(/MSIE 10\.|Trident.*rv[ :]*1[01]\.| Edge\/1\d\./);return{required:function(e){return e.isMobileSafari||n},initialize:function(){},initializeEvents:function(e,t,i){e.force||n&&!e._listeningToResize&&(window.addEventListener("resize",i,!0),e._listeningToResize=!0)},findDeclarations:function(e,t,i,n){var s,o;null!==i&&(s=e,o=t,e=n,"content"===i)&&-1<e.indexOf("viewport-units-buggyfill")&&e.replace(a,"").split(";").forEach(function(e){var t,e=e.split(":");2===e.length&&"viewport-units-buggyfill"!==(t=e[0].trim())&&(e=e[1].trim(),s.push([o,t,e]),r.test(e))&&(e=e.replace(r,"-webkit-calc("),s.push([o,t,e]))})},overwriteDeclaration:function(e,t,i){return i=n&&"filter"===t?i.replace(/px/g,""):i}}},"function"==typeof define&&define.amd?define("viewport-units-buggyfill.hacks",[],t):"object"==typeof exports?module.exports=t():e.viewportUnitsBuggyfillHacks=t()}(),define("CatLab/Webremote/Controllers/Webremote",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Tracker","CatLab/Webremote/Tools/Cookies","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Preloader","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Views/Popups/AuthenticationPopup","CatLab/Webremote/Views/Popups/SelectSmileyPopup","CatLab/Webremote/Views/Blocks/CurrentUser","CatLab/Webremote/Views/Blocks/CurrentSmiley","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/HashParser","CatLab/Webremote/Tools/Screenfull","CatLab/Webremote/Views/Alert","CatLab/Webremote/Views/Welcome","CatLab/Webremote/Views/ConnectionTrouble","CatLab/Webremote/Views/GamePaused","CatLab/Webremote/Synchronization/ClientRemoteView","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler","CatLab/Webremote/Synchronization/CombinedEventHandler","CatLab/Webremote/Providers/SocketIO","CatLab/Webremote/SonicSync/Client","CatLab/Webremote/Components/Components","viewport-units-buggyfill","viewport-units-buggyfill.hacks"],function(Config,Tracker,Cookies,Tools,Deferred,Smileys,Preloader,OAuth2,AuthenticationPopup,SelectSmileyPopup,CurrentUser,CurrentSmiley,UsersCollection,Storage,i18n,HashParser,Screenfull,AlertPopup,WelcomePopup,ConnectionTroubleView,GamePausedView,ClientRemoteView,DataSynchronizer,EventHandler,CombinedEventHandler,SocketIOProvider,SonicSyncClient,Components,ViewportUnitsBuggyFill,ViewportUnitsBuggyFillHacks){var domelement=null,user,dynamicStylesheet,triggers=[];function addEvent(e,t,i){e.addEventListener?e.addEventListener(t,i,!1):e.attachEvent?e.attachEvent("on"+t,i):e["on"+t]=i}var Webremote=function(){};function getParameterByName(e,t){t=t||window.location.href,e=e.replace(/[\[\]]/g,"\\$&");e=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)").exec(t);return e?e[2]?decodeURIComponent(e[2].replace(/\+/g," ")):"":null}return Webremote.prototype={provider:null,element:null,gamedata:null,stylesheets:[],links:[],scripts:[],views:{},userData:null,userEvents:null,groupData:null,groupEvents:null,smiley:null,isOauth2Set:!1,color:null,_currentSmileyViews:[],_currentViewId:null,_currentViewViewId:null,_currentViewGroupId:null,_currentView:null,_connectingDfd:null,_connectedToken:null,_headless:!1,_allowAuthentication:!0,token:null,tokenAction:null,confirmTokenConnect:!1,disableConnectConfirmation:!1,initialize:function(e,t){void 0!==(t=void 0===t?{}:t).disableConnectConfirmation&&(this.disableConnectConfirmation=!!t.disableConnectConfirmation),void 0!==t.token?this.token=t.token:(this.token=getParameterByName("token"),this.token||(this.token=getParameterByName("t")),this.token&&!this.disableConnectConfirmation&&(this.confirmTokenConnect=!0),this.tokenAction=getParameterByName("a")),this.setContainer(e),this.showLoading(),this.sonicSync=null,this.components=new Components(this),this.components.initialize(),this._initialize(t).then(function(){setTimeout(function(){void 0===this.provider.showTokenForm||this.provider.showTokenForm?this.confirmTokenConnect?this.showConfirmTokenConnect().then(function(){this.trigger("remote:initialized"),this.handleTokenInput(this.token)}.bind(this)):(this.showTokenForm(),this.trigger("remote:initialized")):this.provider.noTokenConnect()}.bind(this),2),ViewportUnitsBuggyFill.init({hacks:ViewportUnitsBuggyFillHacks})}.bind(this)),this.setPlayerColor("#000000"),this.setOrientation(),addEvent(window,"resize",this.setOrientation.bind(this))},headless:function(e){return(e=void 0===e?{}:e).headless=!0,this._initialize(e)},_initialize:function(t){var i=new Deferred;return Config.set(t),Config.initialize(function(){Tracker.track("App","Initialize"),void 0===t.provider&&(t.provider=new SocketIOProvider),void 0!==t.headless&&(this._headless=!!t.headless),this.provider=t.provider,this.smileys=new Smileys(this.provider),this.provider.initPlayer(this),this.provider.on("disconnect",function(e){var t=this.getConnectionIssuesView();console.log("Connection lost... reconnecting"),t.show(),t.text(i18n.t("Connection lost... reconnecting"))}.bind(this)),this.provider.on("reconnect",function(e){this.provider.emit("user:reconnect",{id:this.gamedata.id,accessToken:this.gamedata.accessToken}),this.getConnectionIssuesView().hide()}.bind(this)),this.provider.on("user:error",function(e){var t;this._connectingDfd&&(t=this._connectingDfd,this._connectingDfd=null,t.reject(e.message))}.bind(this)),this.provider.on("user:initialize",function(e){this.gamedata=e,this.provider.setUserId(e.id),this._storeGameData(e),this._connectingDfd&&(e=this._connectingDfd,this._connectingDfd=null,e.resolve())}.bind(this)),this.provider.on("view:load",function(e){this.loadViewsXML(e.xml)}.bind(this)),this.provider.on("view:reset",function(e){this.resetViews()}.bind(this)),this.provider.on("config:set",function(e){if(Config.set(e),this.sonicSync&&this.sonicSync.stop(),Config.useAudioSync())try{this.sonicSync=new SonicSyncClient(this),this.sonicSync.startListener()}catch(e){console.error(e)}}.bind(this)),this.provider.on("view:set",function(e){this.showView(e.id,e.viewId,e.group),this.handleCombinedMessages(e)}.bind(this)),this.provider.on("button:label",function(e){this.setLabel(e)}.bind(this)),this.provider.on("button:decorate",function(e){this.setClass(e)}.bind(this)),this.provider.on("oauth:set",function(e){Config.supportsAuthentication()&&(OAuth2.initialize(e),this.isOauth2Set=!0,UsersCollection.initialize(this,OAuth2),this.updateUser(),HashParser.getParameter("access_token"))&&(e=HashParser.getParameter("access_token"),UsersCollection.addFromAccessToken(e,function(e){e&&this.setUser(e)}.bind(this)),HashParser.clear())}.bind(this)),this.provider.on("color:set",function(e){this.setPlayerColor(e.color)}.bind(this)),this.provider.on("user:smiley",function(e){this.setSmiley(e.smiley)}.bind(this)),this.provider.on("smileys:taken",function(e){this.smileys.setTakenSmileys(e.smileys)}.bind(this)),this.provider.on("game:disconnect",function(e){AlertPopup(i18n.t("You have been disconnected from the game."),function(){window.location.reload()})}.bind(this)),this.provider.on("dom:append",function(e){this.domAppend(e)}.bind(this)),this.provider.on("dom:replace",function(e){this.domReplace(e)}.bind(this)),this.provider.on("dom:attribute",function(e){this.domAttribute(e)}.bind(this)),this.provider.on("dom:alert",function(e){AlertPopup(e.message)}),this.provider.on("dom:open",function(e){void 0!==e.url&&window.open(e.url)}),this.provider.on("value:change",function(e){this.changeValue(e)}.bind(this)),this.provider.on("device:vibrate",function(e){this.vibrate(e)}.bind(this)),this.provider.on("game:pause",function(e){this.pause(e)}.bind(this)),this.provider.on("game:unpause",function(e){this.unpause(e)}.bind(this)),this.preloader=new Preloader(this.provider),this.userData=new DataSynchronizer("user",this.emit.bind(this),"client"),this.groupData=new DataSynchronizer("group",this.emit.bind(this),"client"),this.userEvents=new EventHandler("user",this.emit.bind(this)),this.groupEvents=new EventHandler("group",this.emit.bind(this));var e=[this.userData,this.groupData],n=[this.userEvents,this.groupEvents];DataSynchronizer.eventsToListenFor.forEach(function(i){this.provider.on(i,function(t){e.forEach(function(e){e.checkNamespace(t)&&e.processMessage(i,t)})}.bind(this))}.bind(this)),EventHandler.eventsToListenFor.forEach(function(i){this.provider.on(i,function(t){n.forEach(function(e){e.checkNamespace(t)&&e.processMessage(i,t)})}.bind(this))}.bind(this)),this.events=new CombinedEventHandler,this.events.addHandler(this.userEvents),this.events.addHandler(this.groupEvents),i.resolve()}.bind(this)),i.promise()},reconnect:function(e){this.gamedata?(this.provider.emit("user:reconnect",{id:this.gamedata.id,accessToken:this.gamedata.accessToken}),this.provider.once("user:reconnect",function(){e()})):e()},connectProvider:function(e){return this.provider.tokenConnect(e)},_storeGameData:function(){var e=new Deferred,t=this._connectedToken;return Storage.set("gamestate_"+t,this.gamedata,function(){e.resolve()},864e5),e.promise()},_restoreGameData:function(){var t=new Deferred,e=this._connectedToken;return Storage.get("gamestate_"+e,function(e){e?(this.gamedata=e,t.resolve(!0)):t.resolve(!1)}.bind(this)),t.promise()},handleCombinedMessages:function(e){for(var t=[{name:"button:label",method:this.setLabel.bind(this)},{name:"button:decorate",method:this.setClass.bind(this)}],i=0;i<t.length;i++){var n=t[i].name,s=t[i].method;if(void 0!==e[n])for(var o=0;o<e[n].length;o++)s(e[n][o])}},emit:function(e,t){this.provider.toMaster(e,t)},getConnectionIssuesView:function(){return void 0===this.connectionTrouble&&(this.connectionTrouble=new ConnectionTroubleView),this.connectionTrouble},setGamePausedView:function(e){this.gamePaused=e},getGamePausedView:function(){return void 0===this.gamePaused?new GamePausedView:this.gamePaused},setContainer:function(e){domelement=e,this.element=e,dynamicStylesheet=document.createElement("style"),document.body.appendChild(dynamicStylesheet),document.body.className="catlab-remote"},on:function(e,t){void 0===triggers[e]&&(triggers[e]=[]),triggers[e].push(t)},trigger:function(e){var t=[].slice.apply(arguments);if(t.shift(),void 0!==triggers[e])for(var i=0;i<triggers[e].length;i++)triggers[e][i].apply(this,t)},loadViews:function(e,t){var i;t=t||function(){},this._headless?t():((i=new XMLHttpRequest).open("GET",Config.getProxy()+e,!0),i.onreadystatechange=function(){4==i.readyState&&200==i.status&&(this.loadViewsXML(i.responseText),t())}.bind(this),i.send())},resetViews:function(){this.showViewLoadingOverlay(),this.views={},this.components.resetViewDefinedComponents();for(var e=0;e<this.stylesheets.length;e++)try{var t=this.stylesheets[e];t.parentNode&&t.parentNode.removeChild(t)}catch(e){console.error(e)}for(e=0;e<this.links.length;e++)try{var i=this.links[e];i.parentNode&&i.parentNode.removeChild(i)}catch(e){console.error(e)}this.stylesheets=[]},injectXmlns:function(e){return e.replace(/<views(\s[^>]*)?>/,function(e){return/\bxmlns\s*=/.test(e)?e:e.replace("<views",'<views xmlns="http://www.w3.org/1999/xhtml"')})},loadViewsXML:function(e,t){if(t=t||function(){},!this._headless){var i;if(Tracker.track("App","Load Views"),e=this.injectXmlns(e),window.DOMParser?i=(new DOMParser).parseFromString(e,"text/xml"):((i=new ActiveXObject("Microsoft.XMLDOM")).async=!1,i.loadXML(e)),0===i.getElementsByTagName("views").length)return!1;for(var n=i.getElementsByTagName("views").item(0).getElementsByTagName("component"),s=0;s<n.length;s++)this.loadComponent(n.item(s));for(var o=i.getElementsByTagName("views").item(0).getElementsByTagName("view"),s=0;s<o.length;s++)this.loadView(o.item(s));var r=i.getElementsByTagName("views").item(0).getElementsByTagName("stylesheet");for(s=0;s<r.length;s++){var a=r.item(s),l=document.createElement("style");this.stylesheets.push(l),l.innerHTML=a.textContent,document.body.appendChild(l)}var c=i.getElementsByTagName("views").item(0).getElementsByTagName("link");for(s=0;s<c.length;s++){var h=c.item(s).getAttribute("href"),u=document.createElement("link");u.rel="stylesheet",u.type="text/css",u.media="all",u.href=h,this.links.push(u),document.getElementsByTagName("head")[0].appendChild(u)}for(r=i.getElementsByTagName("views").item(0).getElementsByTagName("style"),s=0;s<r.length;s++)this.stylesheets.push(r.item(s)),document.body.appendChild(r.item(s));var d=i.getElementsByTagName("views").item(0).getElementsByTagName("script");for(s=0;s<d.length;s++)this.scripts.push(d.item(s)),this.evalScript(d.item(s));return ViewportUnitsBuggyFill.refresh(),t(),!0}t()},evalScript:function(xml){var aWebremote=Webremote;!function(){try{var Webremote=aWebremote;eval(xml.textContent)}catch(e){console.error(e)}}.bind(window)()},loadView:function(e){var t=e.getAttribute("id"),i=document.createElement("div"),n=!1;e.getAttribute("iframe")&&"false"!==e.getAttribute("iframe").toLowerCase()&&(n=!0);for(var s=0;s<e.childNodes.length;s++)i.appendChild(e.childNodes[s].cloneNode(!0));i.id=t,i.className="view "+e.className,this.views[t]={iframe:n,html:(new XMLSerializer).serializeToString(i)},this._currentViewId===t&&this.showView(this._currentViewId,this._currentViewViewId,this._currentViewGroupId)},loadComponent:function(e){for(var t=e.getAttribute("id"),i=document.createElement("div"),n=0;n<e.childNodes.length;n++)i.appendChild(e.childNodes[n].cloneNode(!0));this.components.addViewDefinedComponent(t,i)},showView:function(e,t,i){var n,s;this._headless||(this._currentView&&this._currentView.destroy(),"remote:authenticate"!==e?(this._currentViewId=e,this._currentViewViewId=t,this._currentViewGroupId=i,void 0!==this.views[e]?(n=(i?this.groupData:this.userData).getFromIdentifier("view:"+t),s=this.views[e],this._currentView=new ClientRemoteView(this,t,e,i,n,s.iframe),this._currentView.html=s.html,this._currentView.render(this.element),this.hideViewLoadingOverlay(),this.updateUser(),Tracker.track("App","Show View",e),this.trigger("remote:view:show",{id:e,view:this._currentView}),this.trigger("view:set",this._currentView)):this.element.innerHTML='<div class="loading"><p>Please wait, loading...</p><p>(Loading view: '+e+")</div></p>"):this.showAuthenticationView())},updateUser:function(){Tracker.track("App","Set user");var e=document.getElementById("authentication");e&&new CurrentUser(this).render(e),this._currentSmileyViews=[],Config.useSmileys()?(this.setSmileySelectViews(),this.setSmileyViews()):this.removeSmileyViews()},setSmileySelectViews:function(){for(var e=document.getElementsByTagName("smiley-select"),t=0;t<e.length;t++){var i=!e[t].hasAttribute("flingable")||"false"!==e[t].getAttribute("flingable"),i=new CurrentSmiley(this,!0,i);i.render(e[t]),this.smiley&&i.setSmiley(this.smiley),this._currentSmileyViews.push(i)}},setSmileyViews:function(){for(var e=document.getElementsByTagName("smiley"),t=0;t<e.length;t++){var i=e[t].hasAttribute("changeable")&&"false"!==e[t].getAttribute("changeable"),n=e[t].hasAttribute("flingable")&&"false"!==e[t].getAttribute("flingable"),i=new CurrentSmiley(this,i,n);i.render(e[t]),this.smiley&&i.setSmiley(this.smiley),this._currentSmileyViews.push(i)}},removeSmileyViews:function(){for(var e=document.getElementsByTagName("smiley-select"),t=0;t<e.length;t++)e[t].parentNode.removeChild(e[t]);for(e=document.getElementsByTagName("smiley"),t=0;t<e.length;t++)e[t].parentNode.removeChild(e[t]);for(var i=document.getElementsByClassName("if-config-smileys"),t=0;t<i.length;t++)i[t].parentNode.removeChild(i[t])},popup:function(e){new WelcomePopup(e).render(domelement)},showAuthenticationPopup:function(e){e=e||!1;var t=new AuthenticationPopup(this);t.render(domelement),e&&t.connect()},showSmileyPopup:function(e,t){void 0===e&&(e=function(e){this.selectSmiley(e)}.bind(this)),void 0===t&&(t=!0);for(var i=domelement.querySelectorAll(".catlab-popup-container"),n=0;n<i.length;n++)i[n].parentNode.removeChild(i[n]);new SelectSmileyPopup(this,e,t).render(domelement)},showAuthenticationView:function(){Cookies.removeItem("last_token"),this.element&&(this.element.innerHTML='<p id="catlab-message">'+i18n.t("Please login.")+"</p>",OAuth2.link({fullscreen:!0}).then(function(e){e?(this.setUser(e),this.element.innerHTML='<p id="catlab-message">'+i18n.t("Welcome! You may now close this screen.")+"</p>",this.provider.disconnect(!1),window.close()):this.showAuthenticationView()}.bind(this)))},buttonDown:function(e,t){this.provider.toMaster("button:down",{id:e})},buttonUp:function(e,t,i){this.provider.toMaster("button:up",{id:e,click:i=void 0!==i&&i}),this.trigger("user:interaction")},syncValue:function(e,t,i){return this.provider.toMaster("value:change",{id:e,value:t,viewId:i}),!1},showLoading:function(){this.element&&(this.element.innerHTML='<p id="catlab-loading">Connecting...</p>')},showViewLoadingOverlay:function(){var e;this._headless||(this.hideViewLoadingOverlay(),(e=document.createElement("div")).id="catlab-view-loading-overlay",e.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;background:#000;display:flex;align-items:center;justify-content:center;z-index:99999;color:#fff;font-family:Arial,Helvetica,sans-serif;font-size:1.5em;",e.innerHTML="<p>Loading...</p>",document.body.appendChild(e))},hideViewLoadingOverlay:function(){var e=document.getElementById("catlab-view-loading-overlay");e&&e.parentNode&&e.parentNode.removeChild(e)},showConfirmTokenConnect:function(){var i=new Deferred,e=document.createElement("form"),t=(this.element.innerHTML="",this.element.appendChild(e),document.createElement("div")),n=(t.id="catlab-token-form",e.appendChild(t),document.createElement("h1")),n=(n.innerHTML=i18n.t("Welcome!"),t.appendChild(n),document.createElement("button"));return"l"===this.tokenAction?n.innerHTML=i18n.t("Login"):n.innerHTML=i18n.t("Join game"),n.type="submit",n.className="pulsating",t.appendChild(n),e.onsubmit=function(e){e.preventDefault();try{var t=(t=window.location.search.replace(/[?&]t=([^&]*)/gi,"")).replace(/[?&]token=([^&]*)/gi,"");window.history.pushState({},document.title,window.location.pathname+t+window.location.hash)}catch(e){}i.resolve()},i.promise()},showTokenForm:function(){var e=document.createElement("form"),t="undefined"!=typeof CONFIG_TOKEN?CONFIG_TOKEN:null,i=(!t&&this.token&&(t=this.token,this.token=null),!1),n=(t&&(i=!0),Cookies.getItem("last_token")),n=(!t&&n&&(t=n),document.createElement("div")),s=(n.id="catlab-token-form",e.innerHTML="",e.appendChild(n),document.createElement("input")),s=(s.type="tel",s.pattern="[0-9 ]{6,10}",s.name="token",s.id="token",s.value=t||"",s.placeholder=i18n.t("Enter code"),s.addEventListener("click",function(){this.setSelectionRange(0,this.value.length)}),n.appendChild(s),document.createElement("button"));s.innerHTML=i18n.t("Connect"),n.appendChild(s),i&&this.handleTokenInput(t),e.onsubmit=function(e){e.preventDefault();e=document.getElementById("token").value;if(e)return this.handleTokenInput(e),!1}.bind(this),this.element.innerHTML="",this.element.appendChild(e)},handleTokenInput:function(e){var t=this.connect(e);e!==Cookies.getItem("last_token")&&Cookies.removeItem("last_token"),t.then(function(){Cookies.setItem("last_token",e,.25)}.bind(this)),t.fail(function(e){this.showTokenForm(),screenfull.enabled&&screenfull.isFullscreen&&screenfull.exit(),AlertPopup(e)}.bind(this)),this.showLoading(),this.trigger("remote:token:submit"),this.trigger("user:interaction")},requestFullScreen:function(){screenfull.enabled&&!screenfull.isFullscreen&&screenfull.request()},connect:function(e){return e=e.replace(" ",""),null!==this._connectingDfd&&(this._connectingDfd.reject(),this._connectingDfd=null),this._connectingDfd=new Deferred,this._connectedToken=e,this._connectingDfd.fail(function(){this.provider.disconnect(!1)}.bind(this)),this.connectProvider(e).fail(function(){setTimeout(function(){this._connectingDfd.reject(i18n.t("Game not found. Please check your token."))}.bind(this),1)}.bind(this)).then(function(t){var i=!0;"0"===getParameterByName("reconnect")&&(i=!1),this._restoreGameData().then(function(e){e&&i?this.reconnect(function(){this._connectingDfd.resolve()}.bind(this)):this.provider.emit("user:join",{token:t})}.bind(this))}.bind(this)),this._connectingDfd.promise()},setLabel:function(e){this._currentView&&this._currentView.setLabel(e.id,Tools.nl2br(Tools.sanitize(e.label)))},setClass:function(e){this._currentView&&this._currentView.setClass(e.id,e.styles)},setPlayerColor:function(e){if(this.color=e,void 0!==dynamicStylesheet&&dynamicStylesheet){var t,i,n="",s=(dynamicStylesheet.innerHTML=(n+=".player-color-border { border-color:"+e+"; }")+(".player-color-background { background-color: "+e+"; }")+(".player-color { color: "+e+"; }"),{"theme-color":e,"msapplication-navbutton-color":e,"apple-mobile-web-app-status-bar-style":e});for(t in s)s.hasOwnProperty(t)&&((i=document.createElement("meta")).httpEquiv=t,i.content=s[t],document.getElementsByTagName("head")[0].appendChild(i))}},setSmiley:function(t){this.smiley=t,this._currentSmileyViews.forEach(function(e){e.setSmiley(t)})},getSmiley:function(){return this.smiley},selectSmiley:function(e){this.provider.toMaster("user:smiley",{smiley:e})},setUser:function(e){user=e,this.updateUser(),user?(this.provider.toMaster("user:login",{access_token:user.getAccessToken()}),Storage.set("currentuser",user.getAccessToken()),this.getSmiley()&&(e=user.getAvatarSmiley())&&this.selectSmiley(e)):(this.provider.toMaster("user:logout"),Storage.set("currentuser",null))},getUser:function(){return user},listViews:function(){var e,t=[];for(e in this.views)this.views.hasOwnProperty(e)&&t.push({name:e});return t},getRandomText:function(e,t){var i="abcdefghijklmnopqrstuvwyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";void 0===t&&(t=40);for(var n="",s=(e=void 0===e?10:e)+Math.random()*t,o=0;o<s;o++)n+=i.charAt(Math.floor(Math.random()*i.length)),.8<Math.random()&&(o++,n+=" ");return n},randomLabels:function(e,t){for(var i=domelement.querySelectorAll("[data-button-label]"),n=0;n<i.length;n++)i[n].innerHTML=this.getRandomText(e,t);this.update()},setOrientation:function(){if(window.innerHeight>=window.innerWidth)try{document.body.classList.remove("landscape"),document.body.classList.add("portrait")}catch(e){document.body.className="portrait"}else try{document.body.classList.add("landscape"),document.body.classList.remove("portrait")}catch(e){document.body.className="landscape"}this.components.resize()},domAppend:function(e){this._currentView&&(this._currentView.domAppend(e.id,e.html),this.components.update())},domReplace:function(e){this._currentView&&(this._currentView.domReplace(e.id,e.html),this.components.update())},domAttribute:function(e){this._currentView&&(this._currentView.domAttribute(e.id,e.name,e.value),this.components.update())},changeValue:function(e){this._currentView&&this._currentView.changeValue(e)},vibrate:function(e){this._currentView&&this._currentView.vibrate(e)},pause:function(e){void 0===this._gamePausedView&&(this._gamePausedView=this.getGamePausedView()),this._gamePausedView.show()},unpause:function(e){void 0!==this._gamePausedView&&this._gamePausedView.hide()},log:function(e){Config.debug()&&console.log(e)},canAuthenticate:function(){return this.isOauth2Set},getGroupIds:function(){return void 0===this.gamedata.groups?[]:this.gamedata.groups},resolveDataAttribute:function(e){if("token"===e)return this._connectedToken;var i,e=(e="data."===e.substring(0,5)?e.substring(5):e).split("."),t=(2!==e.length&&e.unshift("any"),e.shift()),e=e.shift();if(t===user)return this.userData.getFromIdentifier("user").get(e);if("group"===t.substring(0,5)){var n,s=this.getGroupIds();if(0===s.length)return null;if("group"===t)return this.groupData.getFromIdentifier("group:"+s[0]).get(e);if("]"===t.substring(t.length,1))return void 0===s[n=t.substr(t.substring(6,t.length-1))]?null:this.groupData.getFromIdentifier("group:"+s[n]).get(e)}return"any"===t&&(i=["user."+e],this.getGroupIds().forEach(function(e,t){i.push("group["+t+"]")}.bind(this))),null}},Webremote}),define("CatLab/Webremote/Tools/Colorwheel",[],function(){var e={index:0,colors:[{color:"#d84a38",name:"red"},{color:"#4d90fe",name:"blue"},{color:"#35aa47",name:"green"},{color:"#ffb848",name:"yellow"},{color:"#852b99",name:"purple"},{color:"#555555",name:"brown"},{color:"#F87217",name:"orange"},{color:"#FBBBB9",name:"pink"}],initialize:function(){this.index=Math.floor(Math.random()*this.colors.length)},next:function(){var e=this.colors[this.index%this.colors.length];return this.index++,e}};return e.initialize(),e}),define("CatLab/Webremote/Collections/Users",["CatLab/Webremote/Tools/Colorwheel"],function(i){return function(){this.users=[],this.userMap={},this.add=function(e){var t;e.isColorSet()||(t=i.next(),e.setColor(t.color,t.name)),e.hasPlayerId()||e.setPlayerId(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(i){var n=[];return this.each(function(e){for(var t=0;t<i.length;t++)if(i[t].getId()===e.getId())return void n.push(i[t])}),n}}}),define("CatLab/Webremote/Collections/Groups",["CatLab/Webremote/Tools/Colorwheel"],function(i){return function(){var t;this.groups=[],this.groupMap={},this.add=function(e){var t;e.colorSet||(t=i.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 i=!1;return t.groupIds.forEach(function(e){e=this.getFromId(e);e&&(i=!0,e.addUser(t),e.isShareColor())&&t.setColor(e.getColor(),e.getColorName())}.bind(this)),i},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,s){function t(){}e=t.prototype=new e;return e.initializeControlBase=function(){this.initializeEventable()},e.resetViews=function(e){var t=new s;return this.emit("view:reset",{},function(){void 0!==e&&e(),t.resolve()}),t.promise()},e.replaceViews=function(e,t,i){var n=new s;return this.resetViews(function(){this.loadViews(e,t,function(){void 0!==i&&i(),n.resolve()})}.bind(this)),n.promise()},e.loadViews=function(e,t,i){return this.Webcontrol.provider.loadViews(e,i,this).then(function(){void 0!==t&&t()})},e.parseViews=function(e,t,i){return this.Webcontrol.provider.parseViews(e,t,this).then(function(){void 0!==i&&i()})},e.registerComponent=function(e,t){return this.Webcontrol.provider.registerComponent(e,t,this)},t}),define("CatLab/Webremote/Models/Control",[],function(){return function(i,n,e){var s,o,r,a,l=0,c={},h=i,u=[];this.id=i,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 '+o+'">'+h+"</span>":h},this.setStaticLabel=function(e,t,i,n){return h=e,o=t,r=i,a=n,this},this.getLabelImage=function(){return r},this.getLabelEmoji=function(){return a},this.getLabelData=function(){return{label:h,type:o,image:r,emoji:a}},this.setLabel=function(e,t){return this.label=e,n.emit("button:label",{id:i,label:e}),this},this.decorate=function(e){return this.decoration=e,n.emit("button:decorate",{id:i,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"),s=0;s<c[e].length;s++)t.push(c[e][s]);for(s=0;s<t.length;s++)t[s](n);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(s=0;s<c[e].length;s++)c[e][s]===t&&(c[e].splice(s,1),s--);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,i=[];return i.push(e.addEventListener("click",function(){t.trigger("click")})),u.push({element:e,listeners:i}),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:i,styles:this.decoration}),this.label&&e.emit("button:label",{id:i,label:this.label})},this.log=function(e){n.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,i=0;this.remoteView.targets.forEach(function(e){(t=e.scale())>i&&(i=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,i){return this.remoteView.targets.forEach(function(e){e.control(this.id).on(t,i)}.bind(this)),this},t.off=function(e){var t=arguments;return this.remoteView.targets.forEach(function(e){e.control(this.id).off.apply(e.control(this.id),t)}.bind(this)),this},t.refreshTarget=function(t){return this.remoteView.targets.forEach(function(e){e.control(this.id).refreshTarget(t)}.bind(this)),this},e}),define("CatLab/Webremote/Synchronization/RemoteView",["CatLab/Webremote/Models/Control","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Synchronization/MultipleTargetControl","CatLab/Webremote/Synchronization/DataSynchronizer"],function(e,t,i,n){function s(e,t,i,n,s){this.initializeEventable(),this.id=t,this.viewId=e,this.targets=[],this.Webcontrol=n,this.groupId=void 0!==s?s:null,this.controls={},this.valueMap={},this.newUserStack=[],this.factory=null,this.listeners=[],i.map(function(e){this.addTarget(e)}.bind(this))}t=s.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,i={id:this.id,viewId:this.viewId};for(this.tmpid in this.groupId&&(i.group=this.groupId),t.emit("view:set",i),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,i){this.targets.map(function(e){e.emit(t,i)})},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 i(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,i,e){this._clearStack(function(e){return"dom:attribute"===e.action&&e.data.id===t&&e.data.name===i}),this._stackAndEmit("dom:attribute",{id:t,name:i,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,i){this.listeners.push(e.on(t,i))},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)},s}),define("CatLab/Webremote/Synchronization/RemoteViewFactory",["CatLab/Webremote/Synchronization/RemoteView"],function(s){function e(){this.viewCounter=0,this.views={}}var t=e.prototype;return t.create=function(e,t,i,n){return this.viewCounter++,this.views[this.viewCounter]=new s(this.viewCounter,e,t,i,n),(this.views[this.viewCounter].factory=this).views[this.viewCounter]},t.createDummy=function(e,t){return this.create(e,[],t)},t.getFromId=function(e){return this.views[e]},t.destroy=function(e){e=e.id;delete this.views[e]},new e}),define("CatLab/Webremote/Models/Users/ControlUser",["CatLab/Webremote/Models/ControlBase","CatLab/Webremote/Models/User","CatLab/Webremote/Models/Control","CatLab/Webremote/Synchronization/RemoteViewFactory","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler"],function(e,t,i,n,s,o,r,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 i(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 r("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,i){0<=r.eventsToListenFor.indexOf(t)?(this.dataSynchronizer.checkNamespace(i)&&this.dataSynchronizer.processMessage(t,i),this.getGroups().forEach(function(e){e.dataSynchronizer.checkNamespace(i)&&e.dataSynchronizer.processMessage(t,i)}.bind(this))):0<=a.eventsToListenFor.indexOf(t)?(this.events.checkNamespace(i)&&this.events.processMessage(t,i),this.getGroups().forEach(function(e){e.events.checkNamespace(i)&&e.events.processMessage(t,i)}.bind(this))):"button:down"===t?this.control(i.id).update(1):"button:up"===t?this.control(i.id).update(0,i.click):"user:login"===t?this.login(i):"user:logout"===t?this.logout(i):"user:smiley"===t?this.setSmiley(i.smiley):"sync:audio"===t&&this.eventableTrigger("sync:audio",i)},e.setSmiley=function(t){this.smiley=t;var i=null;this.getGroups().forEach(function(e){i=!0,e.setSmiley(t,this)}.bind(this)),i||this.Webcontrol.smileys.reserve(t,this.getIdentifier())?this.emit("user:smiley",{smiley:t}):this.emit("dom:alert",{message:s.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,i){return this.Webcontrol.provider.toPlayer(this,e,t,i),!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,i){var n=this;this.Webcontrol.getOAuthClient(function(e){e&&(this.setAccessToken(t.access_token),e.profile(n.access_token,function(e){n.authenticated=!0,this.setProfiledata(e.user),void 0!==i&&i()}.bind(this)))}.bind(this))},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=n.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,n,t){var s,i,o,r,a,l,c=e,h={};this.label=null,this.decoration="",this.group=n,this.isGlobal=t,this.pushed=function(){for(o=n.getUsers(),s=0;s<o.length;s++)if(o[s].control(c,this.isGlobal).pushed())return!0;return!1},this.scale=function(){for(o=n.getUsers(),s=r=0;s<o.length;s++)(a=o[s].control(c,this.isGlobal)).value>r&&(r=a.value);return r},this.getLabel=function(e){return o=n.getUsers(),(s=0)<o.length?(a=o[s].control(c,this.isGlobal)).getLabel(e):null},this.getLabelImage=function(){return o=n.getUsers(),(s=0)<o.length?(a=o[s].control(c,this.isGlobal)).getLabelImage():null},this.setStaticLabel=function(e,t,i){for(o=n.getUsers(),s=0;s<o.length;s++)o[s].control(c).setStaticLabel(e,t,i);return null},this.setLabel=function(e,t){return this.label=e,n.emit("button:label",{id:c,label:e}),this},this.decorate=function(e){return this.decoration=e,n.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),o=n.getUsers(),s=0;s<o.length;s++)o[s].control(c,this.isGlobal).on(e,t);return this},this.hasTriggers=function(e){for(o=n.getUsers(),s=0;s<o.length;s++)if(o[s].control(c,this.isGlobal).hasTriggers(e))return!0;return!1},this.off=function(e){for(delete h[e],o=n.getUsers(),s=0;s<o.length;s++)o[s].control(c,this.isGlobal).off(e);return this},this.clearEvents=function(){for(h={},o=n.getUsers(),s=0;s<o.length;s++)o[s].control(c,this.isGlobal).clearEvents();return this},this.clear=function(){for(h={},this.decoration=null,this.label=null,o=n.getUsers(),s=0;s<o.length;s++)o[s].control(c,this.isGlobal).clear();return this},this.isLocalAuthentication=function(){return!1},this.refreshControl=function(){for(o=n.getUsers(),s=0;s<o.length;s++){for(l in o[s].control(c,this.isGlobal).clearEvents(),h)if(h.hasOwnProperty(l))for(i=0;i<h[l].length;i++)o[s].control(c,this.isGlobal).on(l,h[l][i]);this.label&&o[s].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){n.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,i,n,s,o,r,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()},t.clearEvents=function(){this.clearControls(),this.clearEventableEvents()},t.isMainGroup=function(){return this.Webcontrol.getConnectToken()===this.getConnectToken()},t.emit=function(e,t,i){return this.Webcontrol.provider.toGroup(this,e,t,i),!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,i){void 0===i&&(i=this.shareColor),this.colorSet=!0,this.color=e,this.colorName=t,this.shareColor=i,this.emit("color:set",{color:e,name:t,shareColor:i})},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=r.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 s(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:o.t("Smiley is already taken. Please select a different smiley.")})},t.clearSmiley=function(e){this.Webcontrol.smileys.unreserve(this.getIdentifier()),this.emit("user:smiley",{smiley:null}),this.smiley=null},t.getSmiley=function(){return this.smiley},t.getSmileyImage=function(){return this.Webcontrol.smileys.getImage(this.getSmiley())},t.getSmileyHtml=function(){return this.Webcontrol.smileys.getHtml(this.getSmiley())},t.getSmileyUrl=function(){return this.Webcontrol.smileys.getUrl(this.getSmiley())},t.setMaxUsers=function(e){this.emit("config:set",{maxUsers:e})},t.isActive=function(){return this.active},t.toggleActive=function(){this.active=!this.active,this.setJoinLabel()},t.setJoinLabel=function(){!0===this.active?this.control("a").setLabel("LEAVE"):this.control("a").setLabel("JOIN")},t.setActive=function(e,t){this.active=e,this.eventableTrigger("active:change",e),this.active&&this.eventableTrigger("active:activate")},t.serialize=function(){return{id:this.getId(),token:this.token,userdata:this.userdata,nickname:this.nickname,profiledata:this.profiledata,email:this.email,access_token:this.access_token,shareColor:this.shareColor,color:this.color,colorName:this.colorName,smiley:this.smiley,data:this.dataSynchronizer.serialize(),events:this.events.serialize()}},t.unserialize=function(e){void 0!==e.profiledata&&this.setProfiledata(e.profiledata),void 0!==e.access_token&&this.setAccessToken(e.access_token),void 0!==e.token&&(this.token=e.token),void 0!==e.shareColor&&(this.shareColor=e.shareColor),void 0!==e.color&&(this.color=e.color),void 0!==e.colorName&&(this.colorName=e.colorName),void 0!==e.nickname&&(this.nickname=e.nickname),void 0!==e.email&&(this.email=e.email),void 0!==e.smiley&&(this.smiley=e.smiley,this.emit("user:smiley",{smiley:this.smiley})),void 0!==e.data&&this.dataSynchronizer.unserialize(e.data),void 0!==e.events&&this.events.unserialize(e.events)},h}),define("CatLab/Webremote/Models/State",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Preloader"],function(i,n){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(i.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=n.unserialize(this.Webcontrol.provider,e.preloader),t()}.bind(this))}.bind(this))}.bind(this),1)},t._setCollectionDetails=function(e,t){var i,n;if(void 0!==e)for(i=0;i<e.length;i++)(n=t.getFromId(e[i].id))?n.unserialize(e[i]):(console.log("Trying to set data for non existing user/group."),console.log(e[i]))},t.getData=function(){var t=[],i=(this.Webcontrol._grouplibrary.each(function(e){t.push(e.serialize())}.bind(this)),[]),e=(this.Webcontrol._userlibrary.each(function(e){i.push(e.serialize())}),{users:i,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 i=0;i<this.controllerListeners.length;i++)this.controllerListeners[i].handleIncomingMessage(e,t)},t.toView=function(e,t,i){this.handleViewMessage(e,t,i)},t.handleViewMessage=function(e,t,i){if(void 0===i)for(var n=0;n<this.viewListeners.length;n++)this.viewListeners[n].handleIncomingMessage(e,t);else this.viewListeners[i].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,i,n){if(e.substring(0,(n=void 0===n?"":n).length)===n){switch(e=e.replace(n,"")){case"nav:previous":return i.previous(),!0;case"nav:next":return i.next(),!0;case"nav:keyInput":return i.keyInput(t.button),!0;case"nav:back":return i.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(i,e,t,s,n,o){function r(e,t){this.initializeEventable(),this.Webcontrol=e,this.options=t,this.controlDisabled=!1,this.users=[],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 o(this.messageBus,"portal:"),this.useCatLabViews()&&e.loadViews(i.getSocketURL(!0)+"/webremote/views/default.xml"),this.eventListeners=[],this.initialize()}e=r.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();let n=[];this.Webcontrol.getUsers().forEach(function(e){var t,i;e.isMainGroup()&&(i=null,(t=e.getUser())&&(i={image:t.avatar}),n.push({active:e.isActive(),color:e.getColor(),profile:i,type:e.getType()}))}),this.messageBus.toView("users:update",{users:n})},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},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 i;void 0!==e?(i=e.getPortalControls(),t.control(i.toggleActive).click(function(){this.toggleActive(e)}.bind(this)),t.control(i.start).click(function(){this.startGame()}.bind(this)),t.control(i.back).click(function(){this.back()}.bind(this)),this.supportsLocalAuthentication()&&t.control(i.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(i,n){if(n.control("name").setLabel(i.getNickname()),n.listenTo(i,"login",function(){n.control("name").setLabel(i.getNickname())}),this.options.allowChangeNickname&&n.control("change-nickname").click(function(){this.changeNickname(i).then(function(){this.updateUserView(i)}.bind(this))}.bind(this)),this.options.customFunctions)for(var e in this.options.customFunctions)this.options.customFunctions.hasOwnProperty(e)&&function(e,t){n.control(e).click(function(){t(i).then(function(){this.updateUserView(i)}.bind(this))}.bind(this))}.bind(this)(e,this.options.customFunctions[e])},e.changeNickname=function(t){var i=new s,n=t.setView("catlab-nickname");return n.changeValue("name",t.getNickname()),n.control("a").click(function(){var e=n.getValues().name;!e||32<e.length||(t.setNickname(e),i.resolve())}),i.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 s={start:[],back:[],toggleActive:[],authenticate:[]};return this.Webcontrol._userlibrary.each(function(e){var t,i=e.getPortalControls();for(t in i)if(i.hasOwnProperty(t)){var n=e.control(i[t]).getLabelData();if(!n)continue;void 0===s[t]&&(s[t]=[]),-1===s[t].findIndex(function(e){return e.label===n.label&&e.image===n.image})&&s[t].push(n)}}.bind(this)),s},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.enableControls(),this.updateUsers()}.bind(this))},e.countAuthenticated=function(e){void 0===e&&(e=!0);for(var t=0,i=0;i<this.users.length;i++)!this.users[i].isAuthenticated()||e&&!this.users[i].isActive()||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;case this.Webcontrol.AUTH_REQUIRED_ONE_INACTIVE:return 0<this.countAuthenticated(!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.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());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.back=function(){void 0!==this.options.back&&(this.destroy(),this.options.back())},e.getConnectURL=function(){return this.Webcontrol.getConnectURL()},e.getConnectToken=function(){return this.Webcontrol.getConnectTokenForDisplay()},e.getQrCodeUrl=function(){var e=this.getConnectURL();return(e=e&&"http"!==e.substring(0,4)?"https://"+e:e)+"?t="+this.Webcontrol.getConnectToken()},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.eventListeners&&this.eventListeners.forEach(function(e){e.unbind()}),this.messageBus.toView("portal:destroy"),this.messageBus.removeControllerListener(this),this.navigatableProxy.destroy()},r}),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(n,s,o,e,r,i,t,a){function l(e,t,i){this.initializeEventable(),this.messageBus=e.getMessageBus(),this.navigatableProxy=new a(this.messageBus,"auth:"),this.Webcontrol=e,this.user=t,this.user.control("x").click(function(){this.messageBus.toView("auth:request-remove-selected-profile")}.bind(this)),o.on("update",this.updateUsers,this),n.on("update",function(){this.updateUsers()},this),this.messageBus.addControllerListener(this)}var c=null,h=null,e=l.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.trigger("close");break;case"auth:select-user":this.selectUser(t.user);break;case"auth:remove-user":this.removeUser(t.user)}},e.link=function(){n.link(function(e){this.selectUser(e)}.bind(this))},e.updateUsers=function(){this.messageBus.toView("auth:users:update",{users:o.getAll().map(function(e){return{id:e.getId(),name:e.getName(),image:e.avatar}})})},e.selectUser=function(e){var t;(e=o.getFromId(e.id))&&(t=this).user.loginFromAuthUser(e,function(){i.setCookie("ctlb_ps_"+this.user.id,e.id),t.close()}.bind(this))},e.removeUser=function(e){(e=o.getFromId(e.id))&&(o.remove(e),this.updateUsers())},e.getUsers=function(){return o},e.close=function(){this.messageBus.toView("auth:close"),this.destroy()},e.getLoginUrl=function(){var t,e,i=new r;return t=this.Webcontrol,(null!==c?((e=new r).resolve(c),e):(null===h&&(h=new r,t.newGroup().then(function(e){new s(c=e),e.setOAuthSettings(t.getOAuthSettings()),h.resolve(e)})),h)).promise().then(function(e){i.resolve(e.getConnectURL()+"/"+e.getConnectToken())}),i.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=i.getCookie("ctlb_ps_"+this.user.id);if(e){e=o.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()},l}),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,i,n=(new Date).getTime();setInterval(function(){t=(new Date).getTime(),i=t-n,n=t,this.trigger("tick",{in:this.countIncoming,out:this.countOutgoing,dt:i}),this.countIncoming=0,this.countOutgoing=0}.bind(this),this.interval)}e=t.prototype=new e;return e.incoming=function(){this.countIncoming++},e.outgoing=function(){this.countOutgoing++},t}),define("CatLab/Webremote/Views/Portal",["CatLab/Webremote/Config"],function(N){return function(e){var s=e.element||document.body,t=s,i=e.countdown||5e3,n=e.done||function(){alert("Game should start now... yet it doesn't.")},o=e["min-players"]||1,r=(o<1&&(o=1),e["max-players"]||1e3);r<o&&(r=o);var a,l,c,h,u,d,f,m,p,g,b,v=!e.customViews,y=[],w=!1,C=!1,k=null,D=this;function L(e){var t=document.createElement("div");return t.innerHTML=e.trim(),t.firstChild}function S(s){s.setView("catlab-portal-toggle"),s.control("join-game").click(function(){(e=>{if(x(e)){e.control("join-game").setLabel("JOIN");for(var t=e,i=0;i<y.length;i++)if(y[i].getId()==t.getId())return y.splice(i,1)}else e.control("join-game").setLabel("LEAVE"),y.push(e)})(s),M(),W(),V()}),s.control("start-game").click(function(){var e;w?V():y.length<o?U(o+" players are required to start the game. Please gather more friends."):y.length>r?U("This game can have only "+r+" players."):(e=i,V(),w=!0,(f=new Date).setTime((new Date).getTime()+e),u.style.display="",d=setInterval(z,100))}),s.control("down").click(function(){E(s)}),s.control("right").click(function(){E(s)}),s.control("left").click(function(){T(s)}),s.control("up").click(function(){T(s)}),s.control("a").click(function(){var e,t,n,i;e=s,C&&A(e)?(t=b.querySelector(".available-accounts li.selected"))&&(t=WebcontrolOAuthClient.getFromToken(t.getAttribute("data-accessToken")))&&(i=t.access_token,k.setUserData(i,t.user),I()):(w&&V(),C||(n=e,Webcontrol.getOAuthClient(function(i){i.onInit(function(){_(i)}),WebcontrolAccessKeyLibrary.init(function(){C=!0,k=n,g.style.display="",b.style.display="";var e=document.createElement("a"),t=(e.href="javascript:void(0);",e.textContent="Link new account",e.addEventListener("click",function(){i.getNewAccessToken(function(){_(i)})}),b.querySelector(".link-new-account"));t.innerHTML="",t.appendChild(e)}),_(i)})))}),s.control("b").click(function(){C&&A(s)&&(k.setUserData(!1),I())}),P(),W()}function T(e){if(C&&A(e)){for(var e=b.querySelector(".available-accounts"),t=e.querySelectorAll("li"),e=e.querySelector("li.selected"),i=0;i<t.length;i++)t[i].classList.remove("selected"),t[i].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 E(e){if(C&&A(e)){for(var e=b.querySelector(".available-accounts"),t=e.querySelectorAll("li"),e=e.querySelector("li.selected"),i=0;i<t.length;i++)t[i].classList.remove("selected"),t[i].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 A(e){return k&&e.getId()==k.getId()}function I(){g.style.display="none",b.style.display="none",C=!1,k=null}function _(e){var t=b.querySelector(".available-accounts");t.innerHTML="";for(var i=e.listUsers(),n=0;n<i.length;n++){var s=document.createElement("li");s.textContent=i[n].user.username,s.className="unselected",s.setAttribute("data-accessToken",i[n].access_token),t.appendChild(s)}}function W(){if(0<Webcontrol.getControlLabels("join-game").length){for(var e=document.querySelectorAll(".buttoninstructions.join-game"),t=0;t<e.length;t++){e[t].style.display="";var i=e[t].querySelector(".labels");i&&(i.innerHTML=Webcontrol.getControlLabels("join-game").join(", "))}for(var n=document.querySelectorAll(".buttoninstructions.start-game"),s=0;s<n.length;s++){n[s].style.display="";var o=n[s].querySelector(".labels");o&&(o.innerHTML=Webcontrol.getControlLabels("start-game").join(", "))}}else{for(var r=document.querySelectorAll(".buttoninstructions.join-game"),a=0;a<r.length;a++)r[a].style.display="none";h.style.display="none"}}function x(e){for(var t=0;t<y.length;t++)if(y[t].getId()==e.getId())return 1}function P(){var e=Webcontrol.getUsers();a.innerHTML="";for(var t=[],i=0;i<e.length;i++)x(e[i])||t.push(e[i]);0==t.length&&(a.innerHTML='<li class="empty"><span>More players? Add devices!</span></li>');for(var n="",i=0;i<t.length;i++)n+='<li class="user '+t[i].getType()+'" style="background-color: '+t[i].getColor()+'"><i class="'+t[i].getIcon()+'"></i><span>'+t[i].getName()+"</span></li>";n&&(a.innerHTML=n)}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),P()}function z(){m=Math.ceil((f.getTime()-(new Date).getTime())/1e3);var e=u.querySelector(".counter");e&&(e.innerHTML=m),m<0&&(void 0!==t&&void 0!==t.style&&(t.style.display="none"),V(),n(y))}function V(){w=!1,d&&(U("Countdown stopped!"),u.style.display="none",clearInterval(d),d=null)}function U(e){var t=document.createElement("p");t.innerHTML=e,p.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!",s.classList?s.classList.add("webremote-portal"):s.className=s.className+" webremote-portal",void 0!==e.theme&&(e=N.getSocketURL()+"/webremote/themes/"+e.theme+"/"+e.theme+".css",Webcontrol._loadCSS(e),Webcontrol._loadCSS(N.getSocketURL()+"/webremote/themes/font-awesome/css/font-awesome.min.css")),s.innerHTML='<div class="loading"><p>Please wait, loading socket.io.</p></div>',Webcontrol.initialize(function(){s.innerHTML="";var e=document.createElement("div"),e=(e.className="webremote-portal-inner",s.appendChild(e),(s=e).innerHTML='<div class="loading"><p>Please wait, connecting to server.</p></div>',v&&Webcontrol.loadViews(N.getSocketURL(!0)+"/webremote/views/default.xml"),s.innerHTML="<h1>Player lobby</h1>",g=document.createElement("div"),b=L('<div><h2>Select account</h2><div class="information"><p>'+D.loginInformation+'</p></div><ul class="available-accounts"></ul><p class="link-new-account"></p></div>'),g.className="accounts-overlay",b.className="accounts",g.style.display="none",b.style.display="none",s.appendChild(g),s.appendChild(b),L('<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),L('<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),s.appendChild(e),s.appendChild(t),(e=L('<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=L('<p class="buttoninstructions join-game">Press <span class="labels"></span> to join the game.</p>'),h=L('<p class="buttoninstructions start-game">Press <span class="labels"></span> to start the game.</p>'),(p=document.createElement("div")).className="errors",s.appendChild(p),e.appendChild(c),e.appendChild(h),s.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",s.appendChild(t),u=t,Webcontrol.on("user:join",function(e){S(e)});for(var i=Webcontrol.getUsers(),n=0;n<i.length;n++)S(i[n]);Webcontrol.on("user:leave",P),P(),M(),W()})}}),define("CatLab/Webremote/ViewFactory/ViewFactory",["CatLab/Webremote/Views/Portal"],function(t){function e(){}return e.prototype.getPortal=function(e){return new t(e)},e}),define("CatLab/Webremote/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/",i="gamepad-",n="🎮",s={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/",i="ps-controller-",n="🕹",s={a:"❎",b:"⭕",x:"🟥",y:"🔺",up:"⬆️",down:"⬇️",left:"⬅️",right:"➡️",l1:"🤜",r1:"🤛"}),{DPAD_UP:{id:"up",label:"↑",key:"DPAD_UP",emoji:n+"‍"+s.up},DPAD_DOWN:{id:"down",label:"↓",key:"DPAD_DOWN",emoji:n+"‍"+s.down},DPAD_RIGHT:{id:"right",label:"→",key:"DPAD_RIGHT",emoji:n+"‍"+s.right},DPAD_LEFT:{id:"left",label:"←",key:"DPAD_LEFT",emoji:n+"‍"+s.left},FACE_1:{id:"a",label:"A",key:"FACE_1",image:t+i+"a.gif",emoji:n+"‍"+s.a},FACE_2:{id:"b",label:"B",key:"FACE_2",image:t+i+"b.gif",emoji:n+"‍"+s.b},FACE_3:{id:"x",label:"X",key:"FACE_3",image:t+i+"x.gif",emoji:n+"‍"+s.x},FACE_4:{id:"y",label:"Y",key:"FACE_4",image:t+i+"y.gif",emoji:n+"‍"+s.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:n+"‍"+s.l1},R1:{id:"r1",label:"R1",key:"R1",emoji:n+"‍"+s.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}var n,t,s={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"},o=e.prototype;return o.initialize=function(e){var t;this.Webcontrol=e,this.initialized||(this.initialized=!0,e=function(){var e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads||[];for(n=0;n<e.length;n++)if(e[n]){for(n=0;n<e.length;n++)e[n]&&this.onConnect(e[n]);this.startGamepadPolling(),clearInterval(t)}}.bind(this),"undefined"!=typeof window&&("ongamepadconnected"in window?(window.addEventListener("gamepadconnected",function(e){this.onConnect(e.gamepad)}.bind(this)),window.addEventListener("gamepaddisconnected",function(e){this.onDisconnect(e.gamepad)}.bind(this))):t=setInterval(e,1e3)))},o.startGamepadPolling=function(){setInterval(this.poll.bind(this),50)},o.poll=function(){var e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads||[];for(n=0;n<e.length;n++)if(e[n])for(t=0;t<e[n].buttons.length;t++)this.gamepads[e[n].index].user&&void 0!==s[t]&&this.gamepads[e[n].index].user.controlFromKey(s[t]).update(e[n].buttons[t].pressed?1:0)},o.onConnect=function(e){var t=new i({id:e.id});this.gamepads[e.index]={user:t},this.Webcontrol.addCustomControl(t),this.startGamepadPolling()},o.onDisconnect=function(e){},new e}),define("CatLab/Webremote/Controllers/Webcontrol",["CatLab/Webremote/Config","CatLab/Webremote/Collections/Users","CatLab/Webremote/Collections/Groups","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Models/Users/ControlUser","CatLab/Webremote/Models/ControlGroup","CatLab/Webremote/Models/State","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Controllers/Portal","CatLab/Webremote/Controllers/Authentication","CatLab/Webremote/Tools/Colorwheel","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Preloader","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/MessageCounter","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Synchronization/RemoteViewFactory","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler","CatLab/Webremote/ViewFactory/ViewFactory","CatLab/Webremote/Views/ConnectionTrouble","CatLab/Webremote/Providers/SocketIO","CatLab/Webremote/Gamepads/GamepadAPI","CatLab/Webremote/SonicSync/Client","CatLab/Webremote/Messages/MessageBus"],function(a,e,t,i,n,s,l,o,r,c,h,u,d,f,m,p,g,b,v,y,w,C,k,L,S,T,E){function A(){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 E}p=A.prototype=new p;return Object.assign(p,{AUTH_REQUIRED_ALL:"ALL",AUTH_REQUIRED_ONE:"ONE",AUTH_REQUIRED_ONE_INACTIVE:"ONE-INACTIVE",AUTH_NOT_REQUIRED:"NONE",initialize:function(e){function t(){s.resolve(),n()}var i,n=function(){},s=(void 0!==(e=void 0===(e="function"==typeof e?{callback:e}:e)?{}:e).callback&&(n=e.callback),new u);return this._initialized?t():(this.sonicSyncClient=null,delete e.callback,e.headless,(i=!!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 L),this.provider=e.provider),this.smileys=new m(this.provider),void 0!==e.translator&&d.setTranslator(e.translator),this._initialize(i,t)}.bind(this))),s.promise()},disconnect:function(){this._initialized=!1,this.provider.disconnect()},_initialize:function(s,e){var o,r=new u;return(e&&r.then(e),this._initialized)?r.resolve(this.connected):(setTimeout(function(){r.resolve(!1)},3e4),this.state=new l(this),this._initialized=!0,(o=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()),r.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=>{o.provider.on(t,function(e){o._playerTrigger(t,e)})})(e[t]);var i=["value:change"];for(var n=0;n<i.length;n++)(t=>{o.provider.on(t,function(e){o._viewTrigger(t,e)})})(i[n]);this._oauthsettings&&this.provider.setOAuthSettings(this._oauthsettings),this.provider.setup(a.getProviderConfig()),this.preloader=new f(this.provider),!s&&a.useAudioSync()&&(this.sonicSyncClient=new T(this),this.sonicSyncClient.startSender())}.bind(this))}.bind(this))),r.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 g(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),o.initialize(e),i.initialize(this,o)},getOAuthClient:function(e){this._oauthsettings?(null===this._oauthClient&&(this._oauthClient=o,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(),i=0;i<t.length;i++)t[i].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 b.getConnectTokenForDisplay(this.getConnectToken())},loadViews:function(e,t,i){return this.provider.loadViews(e,i,t)},parseViews:function(e,t){return this.provider.parseViews(e,t)},registerComponent:function(e,t,i){return this.provider.registerComponent(e,t,i)},getUsers:function(){return this._userlibrary.getAll()},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 r(this,e),t.resolve(e),{controller:e,messageBus:this.getMessageBus(),promise:t};throw new Error("Please initialize Webcontrol first.")},portalView:function(e,t){var i;if(this._initialized)return i=this.getViewFactory(),e=Object.assign({},t,{messageBus:e,Webcontrol:this}),void 0!==t.element&&(e.element=t.element),(t=i.portal(e)).loading(),(e=i.getContainer()).easelboneLayer.setView(t),t.render(),e;throw new Error("Please initialize Webcontrol first.")},authentication:function(e,t){var i;if(this._initialized)return i=this.authenticationController(e,t),t=this.authenticationView(i.controller.messageBus,t),i.controller.setNavigatableUsers([e]),{controller:i.controller,view:t,promise:i.promise};throw new Error("Please initialize Webcontrol first.")},authenticationController:function(e,t){var i=new u,e=new c(this,e,t);return i.resolve(e),{controller:e,promise:i.promise()}},authenticationView:function(e,t){var i=this.getViewFactory(),t=i.authentication(Object.assign({},t,{messageBus:e})),e=i.getContainer();return e.easelboneLayer.setView(t),t.render(),e},alertView:function(e,t){var i=this.getViewFactory(),t=i.alert(Object.assign({},t,{message:e})),e=i.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 i;return void 0===t?(i=v.create(e,[this],this),this._lastView=i):i=v.create(e,t,this),i},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 i=[],n={},s=this.getUsers(),o=0;o<s.length;o++){var r=s[o].control(e).getLabel(t);void 0===n[r]&&i.push(n[r]=r)}return i},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(){S.initialize(this)},newGroup:function(e){var t=new u,i={},n=(void 0===e?e={}:"function"==typeof e&&(e={callback:e}),void 0===e.callback&&(e.callback=function(){}),!0),s=(void 0!==e.globalViews&&(n=e.globalViews),!0),o=(void 0!==e.shareColor&&(s=e.shareColor),[]),r=(void 0!==e.tags&&(o=e.tags),!0),r=(void 0!==e.smiley&&(r=!!e.smiley),i.smiley=r,this._groupCallbacks.id);return this._groupCallbacks.id++,this._groupCallbacks[r]={id:r,callback:e.callback,deferred:t,options:i},this.provider.createGroup(r,n,s,o),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 n(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,i=new s(e.id,e),n=(i.setWebcontrol(this),!1);void 0!==e.shareColor&&(n=e.shareColor),void 0!==e.color?i.setColor(e.color.color,e.color.name):i.setShareColor(n),this._grouplibrary.getFromId(e.id)||(n=function(){},void 0!==(t=e.externalId)&&void 0!==this._groupCallbacks[t]&&(i.setOptions(this._groupCallbacks[t].options),n=function(){this._groupCallbacks[t].callback(i),this._groupCallbacks[t].deferred.resolve(i)}.bind(this)),this._grouplibrary.add(i),i.getOption("smiley")&&this._initializeSmiley(i,e),this.trigger("group:create",i),this.log("New group "+i.getId()+"; URL "+i.getConnectURL()+", token "+i.getConnectToken()),n())},_initializeSmiley:function(e,t){var i;a.useSmileys()?void 0===t.smiley?null!==(i=this.smileys.getRandom(e.getIdentifier()))&&e.setSmiley(i):e.setSmiley(t.smiley):e.clearSmiley(),this.smileys.refreshTakenSmileys(e)},_playerTrigger:function(e,t){var i=this._userlibrary.getFromId(t.user);i?i.trigger(e,t):console.log("User not found: "+t.user)},_viewTrigger:function(e,t){var i=v.getFromId(t.viewId);i&&i.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 i=document.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute("type","text/css"),i.setAttribute("href",e),document.body.appendChild(i)},_setViewLabels:function(e){this._labeldata[e.id]=e.labels;for(var t=this.getUsers(),i=0;i<t.length;i++)for(var n=0;n<e.labels.length;n++)t[i].control(e.id).setStaticLabel(e.labels[n].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._initialized&&this.provider.emit("master:pause",{})},unpause:function(){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))}.bind(this))},_reconnect:function(e,t,i){return this.provider.reconnect(e,t,a.getProviderConfig(),i)},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()}}),A}),define("CatLab/Webremote/Models/Users/KeyboardUser",["CatLab/Webremote/Models/Users/ControlUser"],function(e){function t(e,t){var i="keyboard"+ ++n;this.initializeKeyboardUser({id:i,keys:e}),this.exitOnUnassignedBackButton=t}var n=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;window.onbeforeunload?(e=window.onbeforeunload({}))&&this.confirm(e,function(e){e&&this.exitApp()}.bind(this)):this.exitApp()},e.exitApp=function(){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,i){void 0===i&&(i=!0),void 0===t&&(t="back"),this.initializeKeyboardUser({id:"cordova",keys:e}),this.initializeBackButtonExit(t,i)}e=((t.prototype=Object.create(e.prototype)).constructor=t).prototype;return e.initializeBackButtonExit=function(i,n){void 0===n&&(n=!0);var s=new Date;document.addEventListener("backbutton",function(e){var t=new Date;t.getTime()-s.getTime()<300?this.requestExitApp():(s=t,e.preventDefault(),!n||this.control("back").hasTriggers("click")||this.control("back").hasTriggers("up")||this.control("back").hasTriggers("down")?i&&(this.control(i).update(1),setTimeout(function(){this.control(i).update(0)}.bind(this),1)):setTimeout(function(){void 0!==window.plugins.appMinimize?window.plugins.appMinimize.minimize():this.exitApp()},350))}.bind(this),!1)},e.exitApp=function(){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,i){this.initializeKeyboardUser({id:"cordova",keys:e}),this.initializeBackButtonExit(t,i)}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,i,n,s,o,r){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 i,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 i,this.readyState.resolve(),this.once("airconsole:well-hello-there",function(e){this.emitAirConsole(0,"player:join",{})}.bind(this))},e.onMessage=function(t,e){var i;void 0!==(e="string"==typeof e?JSON.parse(e):e).b&&Array.isArray(e.b)?(i=0,e.b.forEach(function(e){setTimeout(function(){this.processMessage(t,e)}.bind(this),i++)}.bind(this))):this.processMessage(t,e)},e.processMessage=function(e,t){var i;t&&t[0]&&(i=t[0],t=t[1],this.isMaster()&&(0<e&&"player:join"!==i&&void 0===this.knownUsers[e]&&this.onPlayerConnect(e),0<e)&&(t.user=e),o.unpack(t,"user").forEach(function(e){this.isRemote()&&void 0!==e.user&&e.user!==this.airconsole.getDeviceId()||this._trigger(i,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,i,n=this.master._userlibrary.getFromId(e);n&&(t={username:this.airconsole.getNickname(e)},(i=this.airconsole.getProfilePicture(e))&&(t.avatar=i),this.airconsole.getMasterControllerDeviceId()===e&&n.setMaster(!0),n.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,i,e=this.queue.compactFlush();e.length&&(t=5<e.length,i=[],e.forEach(function(e){t||void 0===e.data.user||Array.isArray(e.data.user)&&1<e.data.user.length?i.push(e):this.emitAirConsole(e.user,e.action,e.data)}.bind(this)),0<i.length)&&this.broadcastAirconsole(i)},e.emitAirConsole=function(e,t,i){t=[t,i],delete t[1].action,i=JSON.stringify(t);this.airconsole.message(e,i)},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=[],i=(Array.prototype.push.apply(t,arguments),"["+this.path+"]");"remote"===this.path&&(i="["+this.path+":"+this.airconsole.getDeviceId()+"]"),t.unshift(i),console.log.apply(console,t)},e.getConnectInstructions=function(){return["Open the Airconsole app on your smartphone and connect with code %s.",this.connectCode]},e.getStartAndLoginInstructions=function(){return["Use the onscreen button to start the game."]},a}),define("CatLab/Webremote/Providers/Dummy",["CatLab/Webremote/Providers/Provider","CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Tools"],function(e,t,n,i){function s(){this.initializeProvider(),this.userId=null,this.randomToken=i.getUuid(),this.loadBalancerSessionToken="connid",this.socket=null,this._registeredEvents={}}e=s.prototype=new e;return e.connect=function(e,t){var i=new n;return this.setInitialized(),i.resolve(),i.promise()},e.setup=function(e){this._trigger("master:initialize",{})},e.emitAll=function(e,t){},s}),define("CatLab/Webremote/CreateJS/LayerContainer",["easeljs","easelbone"],function(n,s){function e(e,t){if(!s)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 s.Views.Layer({container:this});var i=this;this.easelboneLayer.on("all",function(e){e=new n.Event(e);i.dispatchEvent(e)})}var t=e.prototype=new n.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(o,r,e){var a=new e;return o.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=[],i=1;i<arguments.length;i++){var n,s=arguments[i];"string"!=typeof s?(n=[],s.forEach(function(e){e.emoji?(n.push(e.emoji),void 0!==e.image&&(this.replacedEmojis[e.emoji]=a.getUrl(e.image,128))):e.label&&n.push(e.label)}.bind(this)),t.push(n.join(" / "))):t.push(s)}return r.t.apply(r,[e].concat(t))},getEmojiSubstitutedMessage:function(e){var e=new o.EaselJS.BigText(e),s=this.replacedEmojis;return e.textConstructor=function(e,t,i,n){e=new o.EaselJS.EmojiText(e,t,i,n);return e.setEmojis(s),e},e},alert:function(e,t){var t=this.Webcontrol.getViewFactory().alert(Object.assign({},t,{message:e})),i=this.Webcontrol.getViewFactory().getContainer();i.easelboneLayer.setView(t),t.render(),this.navigatableOverride=t,this.el.addChild(i),t.on("view:close",function(){i.easelboneLayer.view.trigger("stage:removed"),this.el.removeChild(i),this.navigatableOverride=null}.bind(this))}})}),define("CatLab/Webremote/Tools/ImageLoader",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred"],function(n,s){return{loadedImages:{},loadImage:function(e){var t,i=new s;return this.loadedImages[e]?i.resolve(this.loadedImages[e]):((t=new Image).crossOrigin="anonymous",t.onload=function(){this.loadedImages[e]=t,i.resolve(this.loadedImages[e])}.bind(this),t.src=n.getProxiedImage(e)),i.promise()}}}),define("CatLab/Webremote/Tools/QrGenerator",["easelbone","qrious"],function(o,r){return{generateQrCode:function(e,t){var i=200,n=200;e.getBounds()&&e.getBounds().width&&!e.getBounds().height&&(i=e.getBounds().width,n=e.getBounds().height),e.addChild(this.getGeneratedQrCode(t,Math.max(i,n)))},getGeneratedQrCode(e,t,i,n){void 0===i&&(i="#000000"),void 0===n&&(n="#ffffff");var s=new r,t=(s.level="H",s.size=2*t,s.value=e,s.background=n,s.foreground=i,new Image);return t.src=s.toDataURL(),new o.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,n,t,s,o,i,r){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 n.EaselJS.Placeholder(this.getScreen().connectedUsers),this.connectedUsers=new n.Controls.FloatContainer(function(e){return this.getUserIcon(e)}.bind(this),6),this.connectedUsersContainer.addChild(this.connectedUsers)),this.activeUsersContainer=new n.EaselJS.Placeholder(this.getScreen().activeUsers),this.activeUsers=new n.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 n.Controls.Button(this.getScreen().start),this.start.setText(s.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 n.Controls.Button(this.getScreen().back),this.back.setText(s.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 n.EaselJS.BigText(s.t("Instructions")))}),this.findPlaceholders("activePlayersHeader").forEach(function(e){e.addChild(new n.EaselJS.BigText(s.t("Active devices")))}),this.findPlaceholders("connectedPlayersHeader").forEach(function(e){e.addChild(new n.EaselJS.BigText(s.t("Connected devices")))}),this.instructionTexts=[],this.instructionTexts=this.findPlaceholders("instructionText"),this.updateInstructionText(),this.activePlayerTexts=[],this.findPlaceholders("activePlayers").forEach(function(e){var t=new n.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 i=this.navigatableOverride||this;if(!r.handleMessage(e,t,i,"portal:"))switch(e){case"state:change":this.controllerState=t.state,this.initialized||this.initializeContent(),this.showCurrentAndMaxUsers();break;case"alert":if(t.id&&"exceeds-max-players"===t.id)if(this.purchaseSeatsCallback)return void this.alert(s.t(t.localized),{type:"confirm",okLabel:s.t("Purchase seats"),ok:function(e){e.close(),this.purchaseSeatsCallback()}.bind(this),cancelLabel:s.t("Cancel")});this.alert(s.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,i;return e?e.profile?(t=new this.assets.UserIconAuthenticated,this.addControllerIcon(t,e)):t=this.getControllerIcon(e):t=this.getControllerIcon(),e&&(i=t.PlayerColor)&&new n.EaselJS.Placeholder(i).addChild(new n.EaselJS.Fill(e.color)),e&&this.setUserDetails(t,e),t},addControllerIcon:function(e,t){var i;e.ControllerIcon&&(e=new n.EaselJS.Placeholder(e.ControllerIcon),i=this.getControllerIcon(t),e.addChild(i),i.scaleX=i.scaleY=.5,t)&&(e=i.PlayerColor)&&new n.EaselJS.Placeholder(e).addChild(new n.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=s.t(this.controllerState.startAndLoginInstructions))},showInformation:function(){var e,t=this.getScreen();t&&(e=s.t(this.controllerState.connectInstructions),t.login?t.login.text=s.t(this.controllerState.startAndLoginInstructions):e+="\n "+s.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&&i.generateQrCode(e,this.controllerState.qrUrl)}.bind(this)),this.qrInstructionsContainers.forEach(function(e){var t;e.removeAllChildren(),this.controllerState.qrUrl&&(t=this.getEmojiSubstitutedMessage(s.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,i=24;this.showInactivePlayers||(i=45),this.removeAllUserIcons(),this.users.forEach(function(e){e.active?i<=0||(i--,this.activeUsers.createElement(e)):!this.showInactivePlayers||t<=0||(t--,this.connectedUsers.createElement(e))}.bind(this))},setUserDetails:function(e,t){var i;t.profile&&e.userimage&&(i=new n.EaselJS.Placeholder(e.userimage),o.loadImage(t.profile.image).then(function(e){i.addChild(new n.EaselJS.Fill(e))}))},addAuthenticationView:function(){var e=this.Webcontrol.authenticationView(this.messageBus,{leanback:this.leanback});this.el.addChild(e),e.on("view:close",function(){e.easelboneLayer.view.trigger("stage:removed"),this.el.removeChild(e),this.messageBus.toController("auth:close")}.bind(this))},render:function(){var e=this.getScreen();e&&(console.log(this.el),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(s,e,t,o,r,a,i,n){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 s.Controls.Button(this.screen.linkAccount),this.linkAccount.on("click",function(){n.link(function(e){this.selectUser(e)}.bind(this))}.bind(this))),this.titlePlaceholder=null,this.explanationPlaceholder=null,s.Helpers.MovieClipHelper.findFromNames(["title"],[this.screen]).forEach(function(e){this.titlePlaceholder=new s.EaselJS.Placeholder(e)}.bind(this)),s.Helpers.MovieClipHelper.findFromNames(["explanation"],[this.screen]).forEach(function(e){this.explanationPlaceholder=new s.EaselJS.Placeholder(e)}.bind(this)),this.titlePlaceholder&&(t=new s.EaselJS.BigText(o.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(),s.Helpers.MovieClipHelper.findFromNames("accounts",[this.screen]).forEach(function(e){e=new s.Controls.ScrollArea(e);this.users=new s.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.attachMessageBus(e.messageBus),this.on("stage:removed",this.destroy.bind(this))},attachMessageBus:function(e){(this.messageBus=e).addViewListener(this)},handleIncomingMessage:function(e,t){if(!i.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,i=new this.assets.UserModel,n=(i.namePlaceholder?i.text=i.namePlaceholder:i.name&&(i.text=i.name),new s.Controls.Button(i));return e&&(n.setText(e.name),t=new s.EaselJS.Placeholder(i.picture),r.loadImage(e.image).then(function(e){t.addChild(new s.EaselJS.Fill(e))}),n._userModel=e,n.on("click",function(){this.selectUser(e)}.bind(this)),this.addControl(n)),i},selectUser:function(e){this.messageBus.toController("auth:select-user",{user:{id:e.id}})},close:function(){this.trigger("close"),this.messageBus.toController("auth:close")},render:function(){this.el.addChild(this.screen)},setLoginUrl:function(e){this.loginUrl=e,this.setLoginUrlText()},setLoginUrlText:function(){if(this.linkAccount&&this.linkAccount.setText(o.t("Login to add profile")),this.explanationPlaceholder){var e,t=[],i={selectProfile:"%s to select",removeProfile:"%s to remove",close:"%s to close"};for(e in i){var n=this.getLabelSubstitutionOrNull(e,i[e]);n&&t.push(n)}this.explanationPlaceholder.removeAllChildren(),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=o.t("Scan to login or surf to %s",this.loginUrl);e.addChild(new s.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.messageBus.removeViewListener(this)}})}),define("CatLab/Webremote/CreateJS/Views/AlertView",["easelbone","CatLab/Webremote/Tools/Translator","CatLab/Webremote/CreateJS/Views/BaseView"],function(s,o,e){return e.extend({initialize:function(i){"confirm"===(this.intitializeBaseView(),this.easelScreen=new i.assets.Alert,this.findPlaceholders("message").forEach(function(e){var t=new s.EaselJS.BigText(i.message);e.addChild(t)}),void 0===i.type&&(i.type="alert"),i.type.toLowerCase())?this.initializeConfirm(i):this.initializeAlert(i)},initializeAlert:function(e){var t=o.t("OK");void 0!==e.buttonLabel&&(t=e.buttonLabel),this.findFromNames("button").forEach(function(e){e=new s.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 i=o.t("OK"),n=(void 0!==t.okLabel&&(i=t.okLabel),o.t("Cancel"));void 0!==t.cancelLabel&&(n=t.cancelLabel),this.findFromNames("button1").forEach(function(e){e=new s.Controls.Button(e);e.setText(i),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 s.Controls.Button(e);e.setText(n),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 o,r,a,l,i=e.prototype;return i.initialize=function(){var e=new t;return this.loadAssets().then(function(){this.setAssets(this.assets),e.resolve()}.bind(this)),e},i.loadAssets=function(){var s=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,i,n){o=e,r=t,a=i,l=n,s.resolve()}.bind(this)),s.promise()},i.portal=function(e){return e.assets=this.assets,new r(e)},i.authentication=function(e){return e.assets=this.assets,new a(e)},i.alert=function(e){return e.assets=this.assets,new l(e)},i.setAssets=function(e){void 0!==e&&(this.assets=e)},i.getContainer=function(){var e=new o;return e.setBounds(0,0,this.assets.properties.width,this.assets.properties.height),e.loading(),e},e}),define("CatLab/Webremote/FrontController",["CatLab/Webremote/Config","CatLab/Webremote/Polyfills","CatLab/Webremote/Tools/Tracker","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Controllers/Webremote","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Images","CatLab/Webremote/Models/Users/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/Providers/Dummy","CatLab/Webremote/ViewFactory/ViewFactory","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/Messages/NavigateableProxy"],function(t,e,i,n,s,o,r,a,l,c,h,u,d,f,m,p,g,b,v){return{Config:function(e){t.set(e)},Tracker:i,Tools:n,Webremote:new s,Webcontrol:new r,OAuth2:o,Controls:{Keyboard:c,Cordova:h,AndroidRemote:u,Dummy:d},Controllers:{Webcontrol:r,Webremote:s},Models:{User:d},Providers:{SocketIO:f,Airconsole:m,Dummy:p},ViewFactories:{HtmlViewFactory:g,CreatejsViewFactory:b},Smileys:a,Images:new l,NavigateableProxy:v}}),define("catlabremote",["CatLab/Webremote/FrontController"],function(e){return e}),define("CatLab/EaselHacks/AlphaMaskFilter",[],function(e){function t(e){var n=this;this.createjs=e,Object.defineProperty(e.DisplayObject.prototype,"mask",{get:function(){return this.forceMask},set:function(e){var t,i=this;e?(i.originalMask=e,t=n.getFilterFromMask(e,i),i.filters=[t],i.cache(0,0,500,500)):null!==e&&(i.filters=null,i.cache(0,0,500,500))}}),e.DisplayObject.prototype.setMask=function(e){this.forceMask=e}}return t.prototype.getFilterFromMask=function(e,t){var i=this.createjs,n=e.graphics.getInstructions(),s=new i.Graphics;s.beginFill("#000000"),s.beginStroke("#000000");for(var o=0;o<n.length;o++)s.append(n[o]);e.graphics=s;var r=new i.Container,e=(r.addChild(e),r.scaleX=1/t.scaleX,r.scaleY=1/t.scaleY,r.y=-t.y,r.x=-t.x,new i.Container);return e.addChild(r),e.cache(0,0,1e3,1e3),new i.AlphaMaskFilter(e.cacheCanvas)},t}),define("CatLab/EaselHacks/FrontController",["CatLab/EaselHacks/AlphaMaskFilter"],function(e){return{AlphaMaskFilter:e}}),define("easelhacks",["CatLab/EaselHacks/FrontController"],function(e){return e}),define("CatLab/Webremote/Hacks",["easelhacks","easeljs"],function(e,t){new e.AlphaMaskFilter(t)});
1
+ var io;define("CatLab/Webremote/Tools/Net",[],function(){return{loadJSON:function(e,t,i){var n=new XMLHttpRequest;n.onreadystatechange=function(){n.readyState===XMLHttpRequest.DONE&&200===n.status&&t&&t(JSON.parse(n.responseText))},n.onerror=function(e){e&&i(n,e)},n.open("GET",e,!0),n.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 i=0;i<e.length;i++)t(e[i]);else t(e)}function u(e){var n="pending",s=[],o=[],r=[],a=null,i={done:function(){for(var e=0;e<arguments.length;e++)if(arguments[e])if(c(arguments[e]))for(var t=arguments[e],i=0;i<t.length;i++)"resolved"===n&&t[i].apply(this,a),s.push(t[i]);else"resolved"===n&&arguments[e].apply(this,a),s.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],i=0;i<t.length;i++)"rejected"===n&&t[i].apply(this,a),o.push(t[i]);else"rejected"===n&&arguments[e].apply(this,a),o.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],i=0;i<t.length;i++)"pending"===n&&r.push(t[i]);else"pending"===n&&r.push(arguments[e]);return this},then:function(){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])},promise:function(e){if(null==e)return i;for(var t in i)e[t]=i[t];return e},state:function(){return n},debug:function(){console.log("[debug]",s,o,n)},isRejected:function(){return"rejected"===n},isResolved:function(){return"resolved"===n},pipe:function(e,t,i){return u(function(i){h(e,function(t){"function"==typeof t?l.done(function(){var e=t.apply(this,arguments);e&&"function"==typeof e?e.promise().then(i.resolve,i.reject,i.notify):i.resolve(e)}):l.done(i.resolve)}),h(t,function(t){"function"==typeof t?l.fail(function(){var e=t.apply(this,arguments);e&&"function"==typeof e?e.promise().then(i.resolve,i.reject,i.notify):i.reject(e)}):l.fail(i.reject)})}).promise()}},l={resolveWith:function(e){if("pending"===n){n="resolved";for(var t=a=1<arguments.length?arguments[1]:[],i=0;i<s.length;i++)s[i].apply(e,t)}return this},rejectWith:function(e){if("pending"===n){n="rejected";for(var t=a=1<arguments.length?arguments[1]:[],i=0;i<o.length;i++)o[i].apply(e,t)}return this},notifyWith:function(e){if("pending"===n)for(var t=a=1<arguments.length?arguments[1]:[],i=0;i<r.length;i++)r[i].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=i.promise(l);return e&&e.apply(t,[t]),t}return u.when=function(){var e;if(arguments.length<2)return((e=arguments.length?arguments[0]:void 0)&&"function"==typeof e.isResolved&&"function"==typeof e.isRejected?e:u().resolve(e)).promise();for(var i=arguments,n=u(),s=i.length,o=0,r=new Array(s),t=0;t<i.length;t++)(e=>{var t;i[e].done?i[e].done(function(){r[e]=arguments.length<2?arguments[0]:arguments,++o==s&&n.resolve.apply(n,r)}).fail(function(){n.reject(arguments)}):(t=i[e],i[e]=new Deferred,i[e].done(function(){r[e]=arguments.length<2?arguments[0]:arguments,++o==s&&n.resolve.apply(n,r)}).fail(function(){n.reject(arguments)}).resolve(t))})(t);return n.promise()},u}),define("CatLab/Webremote/Collections/ServerList",["CatLab/Webremote/Tools/Deferred"],function(s){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 s;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 i=new s;if(this.preferredServer)for(var e=0;e<this.servers.length;e++)if(this.servers[e].id==this.preferredServer)return i.resolve(this.servers[e]),i.promise();var n=!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"),n||(n=!0,i.resolve(t))}.bind(this))}.bind(this)),i.promise()},t.selectServer=function(e){this.selectedServerId=e},t.measureRequestSpeed=function(e){var t=new Date,i=new s,n=new XMLHttpRequest;return n.onreadystatechange=function(){var e;4==this.readyState&&200==this.status&&(e=(new Date).getTime()-t.getTime(),i.resolve(e))},n.open("GET",e),n.send(),i.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 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,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&&(this._options.serverlist=e.serverlist),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;this._initialized?t():null===this._options.serverlist||"http"!==this._options.serverlist.substring(0,4)?(this._initialized=!0,t()):"json"===this._options.serverlist.substring(this._options.serverlist.length-4)?i.loadJSON(this._options.serverlist,function(e){this._initialized=!0,this._options.serverlist=e,t()}.bind(this),function(e,t){alert("Failed to connect to "+this._options.serverlist+". Game cannot start."),console.log(t)}.bind(this)):((e=document.createElement("script")).onload=function(){this._initialized=!0,this._options.serverlist=getCatLabRemoteServers(),t()}.bind(this),e.onerror=function(){alert("Failed to connect to "+this._options.serverlist+". Game cannot start.")}.bind(this),e.src=this._options.serverlist,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 i=Object(e),n=1;n<arguments.length;n++){var s=arguments[n];if(null!=s)for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(i[o]=s[o])}return i})}),define("CatLab/Webremote/Tools/Tracker",[],function(){var s=function(e,t,i,n){},t=function(e){s("Page",e,"-",0)};return{setTracker:function(e){s=e},setPageMethod:function(e){t=e},track:function(e,t,i,n){s(e,t,i,n)},page:function(e){t(e)}}}),define("CatLab/Webremote/Tools/Tools",[],function(){var s,o;return{popup:function(e,t){var i=this,n=(t=t||!1,document.createElement("iframe"));n.style.margin=0,n.style.padding=0,n.style.border=0,n.style.position="absolute",n.style.width="100%",n.style.height="100%",n.style.left=0,n.style.top=0,n.src=e,(o=document.createElement("div")).style.margin=0,o.style.padding=0,o.style.border=0,o.style.position="absolute",o.style.width="100%",o.style.height="100%",o.style.left=0,o.style.top=0,o.style.zIndex=9999,o.onclick=function(){i.closePopup()},(s=document.createElement("div")).appendChild(n),s.style.margin=0,s.style.padding=0,s.style.border=0,s.style.position="absolute",s.style.zIndex=1e4,s.style.overflow="auto",s.style.background="white",s.style.boxSizing="border-box",t?(s.style.border="0 none black",s.style.left="0",s.style.top="0",s.style.width="100%",s.style.height="100%"):(s.style.border="5px solid black",s.style.left="10%",s.style.top="10%",s.style.width="80%",s.style.height="80%"),document.body.appendChild(o),document.body.appendChild(s)},oauth2PopupMethod:function(e,t){return window.open(e,"oauth:catlab-remote")},oauth2Popup:function(e,t){return this.oauth2PopupMethod(e,t)},closePopup:function(){s&&s.parentNode.removeChild(s),o&&o.parentNode.removeChild(o)},setOauth2Popup:function(e){return this.oauth2PopupMethod=e,this},sanitize:function(e){var t;return null==e?null:(t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"},String(e).replace(/[&<>"']/g,function(e){return t[e]}))},nl2br:function(e,t){return null==e?"":(e+"").replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,"$1"+(t||void 0===t?"<br />":"<br>")+"$2")},shuffle:function(e){for(var t,i,n=e.length-1;0<n;n--)t=Math.floor(Math.random()*(n+1)),i=e[n],e[n]=e[t],e[t]=i},getUuid:function(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)},findIndex:function(e,t){for(var i=0;i<e.length;i++)if(t(e[i]))return i;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,i){return e.match(new RegExp(".{1,"+t+"}","g")).join(i)}}}),define("CatLab/Webremote/Tools/Cookies",[],function(){var t={setCookie:function(e,t,i){return this.setItem(e,t,i)},getCookie:function(e){return this.getItem(e)},eraseCookie:function(e){return this.removeItem(e)},getItem:function(e){if("undefined"!=typeof document)return e&&this.hasOwnProperty(e)?unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"),"$1")):null},key:function(e){if("undefined"!=typeof document)return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/,"").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[e])},setItem:function(e,t,i){var n,s;e&&"undefined"!=typeof document&&(n="",i&&((s=new Date).setTime(s.getTime()+Math.round(24*i*60*60*1e3)),n="; expires="+s.toUTCString()),document.cookie=escape(e)+"="+escape(t)+"; expires="+n+"; path=/; SameSite=Strict;",this.updateLength())},length:0,removeItem:function(e){e&&this.hasOwnProperty(e)&&"undefined"!=typeof document&&(document.cookie=escape(e)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Strict;",this.length--)},hasOwnProperty:function(e){if("undefined"!=typeof document)return new RegExp("(?:^|;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(document.cookie)},updateLength:function(){var e;"undefined"!=typeof document&&document.cookie&&(e=document.cookie.match(/\=/g),t.length=e?e.length:0)}};return t.updateLength(),t}),define("CatLab/Webremote/Tools/Images",["CatLab/Webremote/Config"],function(s){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 i;return void 0!==t&&-1!==this.availableSizes.indexOf(t)||(t=this.availableSizes[0]),void 0===this.images[e+"_"+t]&&((i=new Image).crossOrigin="anonymous",i.src=this.getUrl(e,t),this.images[e+"_"+t]=i),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 i=e.split("/"),n=0;n<i.length;n++)"$SIZE"===i[n]&&(i[n]=t);return e=i.join("/"),s.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(i,n,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),n.shuffle(this.randomSmileys)}var s=e.prototype;return s.shouldHaveUniqueSmileys=function(){return this.takenAmount<this.smileyKeys.length/3},s.setTakenSmileys=function(e){this.taken=e},s.getTakenSmileys=function(e){if(!this.shouldHaveUniqueSmileys())return{};e=this.identifierToText(e);var t,i={};for(t in this.taken)this.taken.hasOwnProperty(t)&&this.taken[t]!==e&&(i[t]=this.taken[t]);return i},s.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),n.shuffle(this.randomSmileys),this.randomSmileys.shift();return t},s.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))},s.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--)},s.isAvailable=function(e){return!this.shouldHaveUniqueSmileys()||!!this.isExternalSmiley(e)||null==this.taken[e]},s.identifierToText=function(e){return JSON.stringify(e)},s.isExternalSmiley=function(e){return"http"===e.substring(0,4).toLowerCase()},s.getUrl=function(e){var t=this.getImageUrl(e);return t?this.isExternalSmiley(e)?e:i.getAssetsURL()+t:null},s.getImageUrl=function(e){return null===e?null:this.isExternalSmiley(e)?e:"smileys/"+e+".png"},s.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>"},s.getElement=function(e){var t;return null===e?null:((t=document.createElement("div")).innerHTML=this.getHtml(e),t.firstChild)},s.getImage=function(e){return null===e?null:this.images.getImage(this.getImageUrl(e))},s.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())})},s.getStringIdentifier=function(e){return e.type+":"+e.id},e}),define("CatLab/Webremote/Tools/Preloader",["../Config","CatLab/Webremote/Tools/Deferred"],function(t,o){function i(e){this.provider=e,this.provider.on("file:preload",function(e){e&&e.url&&this.preloadClientFile(e.url)}.bind(this)),this.urlMap={}}var e=i.prototype;return e.preload=function(t){if(Array.isArray(t)){for(var e=new o,i=[],n=0;n<t.length;n++)i.push(this.preload(t[n]));return o.when.apply(o,i).then(function(){e.resolve(Array.prototype.slice.call(arguments))}),e.promise()}var s=new o;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}),s.resolve(e)}.bind(this)),s.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}},i.unserialize=function(e,t){e=new i(e);return void 0!==t&&void 0!==t.urlMap&&(e.urlMap=t.urlMap),e},i}),define("CatLab/Webremote/Tools/Eventable",["CatLab/Webremote/Tools/Tools"],function(n){function e(){}var s=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,i=Array.prototype.slice.call(arguments);for(t in i.push(i.shift()),this._eventableEvents)this._eventableEvents.hasOwnProperty(t)&&this.eventMatches(e,t)&&this._eventableEvents[t].slice().forEach(function(e){try{e.method.apply(e.scope,i)}catch(e){console.error(e)}}.bind(this))}},t.eventMatches=function(e,t){return"*"===t||e===t},t.on=function(e,t,i){void 0===this._eventableEvents&&(this._eventableEvents={}),void 0===this._eventableEvents[e]&&(this._eventableEvents[e]=[]),s++,this._eventableEvents[e].push({id:s,method:t,scope:void 0!==i?i:this});var n=[e,s];return{id:n,name:e,method:t,unbind:function(){this.off(null,{id:n,name:e})}.bind(this)}},t.once=function(e,t,i){var n=this.on(e,function(){n.unbind(),t.apply(i,arguments)});return n},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 i=n.findIndex(this._eventableEvents[e],function(e){return e.id===t[1]});0<=i&&this._eventableEvents[e].splice(i,1)}else this._eventableEvents[e]=[];else this._eventableEvents=[]},t.clearEvents=function(){this.clearEventableEvents()},t.clearEventableEvents=function(){this._eventableEvents={}},e}),define("CatLab/Webremote/Models/User",["CatLab/Webremote/Config"],function(t){return function(e){this.accessToken=e,this.name=null,this.avatar=null,this.id=null,this.image=null,this.imageCallbacks=[],this.imageLoaded=!1,this.getAccessToken=function(){return this.accessToken},this.setId=function(e){this.id=e},this.getId=function(){return this.id},this.setName=function(e){this.name=e},this.getName=function(){return this.name},this.setAvatar=function(e){this.avatar=e,this.imageLoaded=!1,this.imageCallbacks=[],this.image=null},this.loadAvatar=function(){this.image||(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=function(){this.afterImageLoad()}.bind(this),this.image.src=t.getProxiedImage(this.avatar))},this.getAvatar=function(){return this.avatar},this.getAvatarSmiley=function(e){var t=this.getAvatar();return t?(t=t.split("?")[0],t+="?shape=circle&size=64&borderWidth=4",e&&(t+="&borderColor="+e.substr(1)),t):null},this.afterImageLoad=function(){this.imageLoaded=!0;for(var e=0;e<this.imageCallbacks.length;e++)this.imageCallbacks[e](this.image);this.imageCallbacks=[]},this.getImage=function(e){this.loadAvatar(),this.imageLoaded?e(this.image):this.imageCallbacks.push(e)}}}),define("CatLab/Webremote/Tools/Storage",["CatLab/Webremote/Tools/Cookies"],function(e){var t={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 i,n=window.localStorage.getItem(e);n?void 0!==(n=JSON.parse(n)).expires?(i=Date.now(),n.expires<i?(this.delete(e),t(null)):t(n.content)):t(n):t(null)}catch(e){t(null),console.log(e)}else t(null)},add:function(t,i,n,s){var o=this;n=n||function(){},this.isSupported()?this.get(t,function(e){(e=null!=e&&""!==e?e:[]).push(i),o.set(t,e,n,s)}):n(null)},set:function(e,t,i,n){if(void 0===i&&(i=function(){}),this.isSupported()){void 0===n&&(n=31536e6);try{var s=Date.now();s+=n,window.localStorage.setItem(e,JSON.stringify({expires:s,content:t}))}catch(e){console.log(e)}i()}else i(null)},delete:function(e){this.isSupported()&&window.localStorage.removeItem(e)},remove:function(n,s){var o;this.isSupported()&&(o=this).get(n,function(e){null!=e&&""!=e||(e=[]);for(var t=JSON.stringify(s),i=0;i<e.length;i++)if(t===JSON.stringify(e[i]))return e.splice(i,1),void o.set(n,e)})},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){function t(){this.initializeEventable()}var r,s,a=[],e=t.prototype=new e;return e.initialize=function(e,t){r=t,s=e;var n=this;o.get("users",function(i){null!==i&&o.get("currentuser",function(t){for(var e=0;e<i.length;e++)n.addFromAccessToken(i[e].access_token,function(e){e&&t&&e.getAccessToken()===t&&void 0!==s.setUser&&s.setUser(e)})})})},e.addFromAccessToken=function(i,n){n=n||function(){};var s=this;r.profile(i,function(e,t){e?(e=s.add(i,e.user),n(e)):401!==t&&403!==t||o.remove("users",{access_token:i})})},e.add=function(e,t){var i=new n(e);return i.setId(t.id),i.setName(t.username),i.setAvatar(t.avatar),(e=>{for(var t=0;t<a.length;t++)if(a[t].getId()==e.getId())return;return a.push(e),1})(i)||o.remove("users",{access_token:e}),this.trigger("update"),i},e.remove=function(e){for(var t=0;t<a.length;t++)if(a[t].getId()==e.getId())return o.remove("users",{access_token:a[t].getAccessToken()}),a.splice(t,1),void this.trigger("update")},e.getFromId=function(e){for(var t=0;t<a.length;t++)if(a[t].getId()==e)return a[t];return null},e.getAll=function(){return a},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(o,r,e,s,a,n){var l,c,h,u,d,f=[],t=[],m=[],p=null;function i(){this.initializeEventable()}e=i.prototype=new e;return e.initialize=function(e){l=(e=e||{}).authorization,c=e.client_id||"none",h=e.authorization||"default",u=e.profile||"",d=e.profile+"/avatar",void 0===e.redirect_uri||n._options.oauth.redirectUrl||(n._options.oauth.redirectUrl=e.redirect_uri);var t=this;if("undefined"!=typeof window){var i,e=function(e){t.onMessage(e)};if(window.addEventListener){for(;i=m.pop();)removeEventListener("message",i);addEventListener("message",e,!1)}else{for(;i=m.pop();)detachEvent("onmessage",i);attachEvent("onmessage",e)}m.push(e)}},e.setRedirectUrl=function(e,t){this.redirectHost=e,this.redirectUrl=e+t},e.getAuthorizeURL=function(){var e="",e=(n.all().oauth&&n.all().oauth.redirectUrl&&(e=n.all().oauth.redirectUrl),l+"?client_id="+encodeURIComponent(c)+"&authorization="+encodeURIComponent(h)+"&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(n){var e=function(e){if(e&&e.user){var t,i=s.add(n,e.user);for(a.add("users",{access_token:n}),o.closePopup();t=f.shift();)t(i);this.trigger("update")}}.bind(this);this.call(u,n,e)},e.call=function(e,t,i){var n,e=e+"?access_token="+t;"undefined"!=typeof window&&((n=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP")).onreadystatechange=function(){if(4==n.readyState&&200!=n.status&&i(null,n.status),4==n.readyState&&200==n.status)try{i(JSON.parse(n.responseText))}catch(e){i(null,n.status)}},n.open("GET",e,!0),n.send())},e.profile=function(e,t){this.call(u,e,t)},e.changeAvatar=function(t,e){var i,n,s;if(t.getAccessToken())return i=new r,(n=new FormData).append("avatar",e.files[0]),(s=new XMLHttpRequest).open("POST",d,!0),s.setRequestHeader("Authorization","Bearer "+t.getAccessToken()),s.onreadystatechange=function(){if(4===s.readyState)if(200<=s.status&&s.status<300)try{var e=JSON.parse(s.responseText);t.setAvatar(e.url),i.resolve(e)}catch(e){i.reject(e)}else i.reject(s.status)},s.send(n),i.promise()},e.link=function(t){var i=new r,e={},e=("object"==typeof(t=void 0===t?{}:t)&&(t=(e=t).callback||function(){}),e.fullscreen||!1),n=(p&&clearInterval(p),this.getAuthorizeURL()),s=o.oauth2Popup(n,e);return s&&(p=setInterval(function(){s&&s.postMessage?s.postMessage("Hello from the other side","*"):clearInterval(p)}.bind(this),1e3)),f.push(function(e){t(e),i.resolve(e)}),i.promise()},e.onInit=function(e){t.push(e)},e.onAdds=function(){for(var e=0;e<t.length;e++)t[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&&window.opener.postMessage(e,"*"),window.parent&&window.parent.postMessage(e,"*"),void 0!==window.dialogArguments&&window.dialogArguments.opener&&window.dialogArguments.opener.postMessage(e,"*"),setTimeout(function(){p&&clearInterval(p),window.close()},1)},1)},new i}),define("CatLab/Webremote/Views/Popups/BasePopup",[],function(){function e(){this.scrollable=!1}var t=e.prototype;return t.render=function(e){this.popupContainer=document.createElement("div"),this.popupContainer.className="catlab-popup-container";var t=document.createElement("div"),t=(t.className="overlay",t.addEventListener("click",function(){this.close()}.bind(this)),this.popupContainer.appendChild(t),this.container=document.createElement("div"),this.container.className="popup",this.popupContainer.appendChild(this.container),this.container.addEventListener("click",function(e){e.stopPropagation()}),this.content=document.createElement("div"),this.container.appendChild(this.content),document.createElement("p")),i=(t.className="close",document.createElement("a"));i.href="javascript:void(0)",i.innerHTML="<span>Close</span>",i.onclick=function(){this.close()}.bind(this),t.appendChild(i),this.container.appendChild(t),e.appendChild(this.popupContainer),this.scrollable&&this.content.classList.add("scrollable"),this.renderContent(this.content)},t.renderContent=function(){},t.close=function(){this.popupContainer.parentNode.removeChild(this.popupContainer)},e}),define("CatLab/Webremote/Views/User",["CatLab/Webremote/Controllers/OAuth2"],function(n){return function(d){this.render=function(e,t,i){t=t||[];var n,s=d.getName(),o=document.createElement("div"),r=(o.className="catlab-user",document.createElement("div")),r=((this.avatardiv=r).className="catlab-avatar",o.appendChild(r),this.renderAvatar(),void 0!==i&&(r.onclick=i),document.createElement("div")),a=(r.className="catlab-info",o.appendChild(r),document.createElement("p"));void 0!==i?((n=document.createElement("a")).innerHTML=s,n.onclick=i,a.appendChild(n)):(a.innerHTML=s,r.appendChild(a)),r.appendChild(a);var l,c,h=document.createElement("ul");h.className="catlab-actions";for(var u=0;u<t.length;u++)(l=document.createElement("li")).className=t[u].token,h.appendChild(l),(c=document.createElement("a")).onclick=t[u].click,c.innerHTML=t[u].text,c.href="javascript:void(0)",l.appendChild(c);r.appendChild(h),e.innerHTML="",e.appendChild(o);i=document.createElement("div");i.className="clearer",o.appendChild(i)},this.renderAvatar=function(){var e=d.getAvatar(),t=document.createElement("img");t.src=e,t.alt="User avatar",this.avatardiv.innerHTML="",this.avatardiv.appendChild(t)},this.enableAvatarUpload=function(t){var i=document.createElement("input");i.type="file",i.accept="image/*",(this.avatarFileInput=i).addEventListener("change",function(){this.avatardiv.classList.add("loading");var e=n.changeAvatar(d,i);e&&e.then&&e.then(function(){this.avatardiv.classList.remove("loading"),this.renderAvatar(),t.setUser(d)}.bind(this))}.bind(this)),this.avatardiv.addEventListener("click",function(){i.click()})},this.uploadAvatar=function(){this.avatarFileInput&&this.avatarFileInput.click()}}}),define("CatLab/Webremote/Views/Popups/AuthenticationPopup",["CatLab/Webremote/Views/Popups/BasePopup","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Views/User","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Tracker"],function(e,l,c,h,u,d){return function(t){function e(){l.link(function(e){s.updateUsers(),s.selectUser(e)})}l.on("update",function(){this.updateUsers()}.bind(this));var s=this,i=document.createElement("div"),n=(i.className="catlab-popup-container",document.createElement("div")),n=(n.className="overlay",i.appendChild(n),document.createElement("div")),o=(n.className="popup",i.appendChild(n),n.innerHTML="<h2>Select account</h2>",document.createElement("ul")),r=(o.className="userlist",n.appendChild(o),document.createElement("div")),r=(r.className="clearer",n.appendChild(r),document.createElement("p")),a=(r.className="connect",document.createElement("a")),r=(a.href="javascript:void(0)",a.innerHTML='<span class="new-user">Connect new user</span>',a.onclick=function(){e()},r.appendChild(a),n.appendChild(a),document.createElement("p")),a=(r.className="close",document.createElement("a"));a.href="javascript:void(0)",a.innerHTML="<span>Close</span>",a.onclick=function(){s.close()},r.appendChild(a),n.appendChild(r),this.selectUser=function(e){t.setUser(e),s.close(),d.track("Click","Select user","AuthenticationPopup")},this.updateUsers=function(){o.innerHTML="";for(var e=c.getAll(),t=0;t<e.length;t++)((e,t)=>{var i=document.createElement("li"),n=[{token:"select",text:"select",click:function(){s.selectUser(t)}},{token:"logout",text:"logout",click:function(){c.remove(t),u.remove("users",{access_token:t.getAccessToken()}),s.updateUsers(),d.track("Click","Logout","AuthenticationPopup")}}];new h(t).render(i,n,function(){s.selectUser(t)}),e.appendChild(i)})(o,e[t])},this.close=function(){i.parentNode.removeChild(i),d.track("Click","Close popup","AuthenticationPopup")},this.connect=function(){d.track("Click","Connect new","AuthenticationPopup"),e()},this.render=function(e){e.appendChild(i),this.updateUsers()},this.setLoginUrl=function(e){}}}),define("CatLab/Webremote/Views/Popups/SelectSmileyPopup",["CatLab/Webremote/Views/Popups/BasePopup"],function(e){function t(e,t,i){this.Webremote=e,this.callback=t,this.scrollable=!0,this.disableTaken=i}e=t.prototype=new e;return e.renderContent=function(e){e.classList.add("smileys-popup");var t=document.createElement("ul"),i=(t.className="smileys",e.appendChild(t),this.Webremote.smileys.smileyKeys.slice());this.Webremote.getUser()&&this.Webremote.getUser().getAvatar()&&(s=this.Webremote.getUser().getAvatarSmiley(this.Webremote.color))&&i.unshift(s);for(var n=0;n<i.length;n++)this.renderSmiley(t,i[n]);var s=document.createElement("div");s.className="clearer",e.appendChild(s)},e.renderSmiley=function(i,n){var s=document.createElement("li"),o=(s.appendChild(this.Webremote.smileys.getElement(n)),!this.disableTaken||this.Webremote.smileys.isAvailable(n));o||s.classList.add("unavailable"),this.Webremote.getSmiley()===n&&s.classList.add("selected"),s.addEventListener("click",function(){if(o){this.selectSmiley(n);for(var e=i.querySelectorAll(".selected"),t=0;t<e.length;t++)e[t].classList.remove("selected");s.classList.add("selected"),this.close()}}.bind(this)),i.appendChild(s)},e.selectSmiley=function(e){this.callback(e)},t}),define("CatLab/Webremote/Views/Blocks/CurrentUser",["CatLab/Webremote/Views/User","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Tracker"],function(o,r,a,l){return function(s){this.render=function(e){var t,i,n;e.innerHTML="",s.canAuthenticate()&&(n=s.getUser(),(t=document.createElement("div")).className="overlay player-color-background",e.appendChild(t),(t=document.createElement("div")).className="content",t.className+=" player-color-border",e.appendChild(t),n?(e=[{token:"switch",text:"Switch account",click:function(){s.showAuthenticationPopup(),l.track("Click","Switch account","CurrentUser")}},{token:"upload",text:"Upload photo",click:function(){i.uploadAvatar()}},{token:"logout",text:"Logout",click:function(){var e=s.getUser();r.remove(e),s.setUser(null),a.remove("users",{access_token:e.getAccessToken()}),l.track("Click","Logout","CurrentUser")}}],(i=new o(n)).render(t,e),i.enableAvatarUpload(s)):((n=document.createElement("p")).className="catlab-not-loggedin",(e=document.createElement("a")).href="javascript:void(0);",e.innerHTML="Login",e.onclick=function(){s.showAuthenticationPopup(0===r.getAll().length),l.track("Click","Login","CurrentUser")},n.appendChild(e),t.appendChild(n)))}}}),(()=>{var m={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 p(e){for(var t,i,n,s,o,r,a,l=(e=>{if(g[e])return g[e];for(var t,i=e,n=[],s=0;i;){if(null!==(t=m.text.exec(i)))n.push(t[0]);else if(null!==(t=m.modulo.exec(i)))n.push("%");else{if(null===(t=m.placeholder.exec(i)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){s|=1;var o=[],r=t[2],a=[];if(null===(a=m.key.exec(r)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(o.push(a[1]);""!==(r=r.substring(a[0].length));){if(null===(a=m.key_access.exec(r))&&null===(a=m.index_access.exec(r)))throw new SyntaxError("[sprintf] failed to parse named argument key");o.push(a[1])}t[2]=o}else s|=2;if(3===s)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");n.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]})}i=i.substring(t[0].length)}return g[e]=n})(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((n=l[f]).keys)for(t=c[h],i=0;i<n.keys.length;i++){if(null==t)throw new Error(p('[sprintf] Cannot access property "%s" of undefined value "%s"',n.keys[i],n.keys[i-1]));t=t[n.keys[i]]}else t=n.param_no?c[n.param_no]:c[h++];if(m.not_type.test(n.type)&&m.not_primitive.test(n.type)&&t instanceof Function&&(t=t()),m.numeric_arg.test(n.type)&&"number"!=typeof t&&isNaN(t))throw new TypeError(p("[sprintf] expecting number but found %T",t));switch(m.number.test(n.type)&&(r=0<=t),n.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,n.width?parseInt(n.width):0);break;case"e":t=n.precision?parseFloat(t).toExponential(n.precision):parseFloat(t).toExponential();break;case"f":t=n.precision?parseFloat(t).toFixed(n.precision):parseFloat(t);break;case"g":t=n.precision?String(Number(t.toPrecision(n.precision))):parseFloat(t);break;case"o":t=(parseInt(t,10)>>>0).toString(8);break;case"s":t=String(t),t=n.precision?t.substring(0,n.precision):t;break;case"t":t=String(!!t),t=n.precision?t.substring(0,n.precision):t;break;case"T":t=Object.prototype.toString.call(t).slice(8,-1).toLowerCase(),t=n.precision?t.substring(0,n.precision):t;break;case"u":t=parseInt(t,10)>>>0;break;case"v":t=t.valueOf(),t=n.precision?t.substring(0,n.precision):t;break;case"x":t=(parseInt(t,10)>>>0).toString(16);break;case"X":t=(parseInt(t,10)>>>0).toString(16).toUpperCase()}m.json.test(n.type)?d+=t:(!m.number.test(n.type)||r&&!n.sign?a="":(a=r?"+":"-",t=t.toString().replace(m.sign,"")),s=n.pad_char?"0"===n.pad_char?"0":n.pad_char.charAt(1):" ",o=n.width-(a+t).length,o=n.width&&0<o?s.repeat(o):"",d+=n.align?a+t+o:"0"===s?a+o+t:o+a+t)}return d}function e(e,t){return p.apply(null,[e].concat(t||[]))}var g=Object.create(null);"undefined"!=typeof exports&&(exports.sprintf=p,exports.vsprintf=e),"undefined"!=typeof window&&(window.sprintf=p,window.vsprintf=e,"function"==typeof define)&&define.amd&&define("sprintf",[],function(){return{sprintf:p,vsprintf:e}})})(),define("CatLab/Webremote/Tools/Translator",["sprintf"],function(t){function e(){this.translator=null}var i,n,s=e.prototype;return s.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)},s.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(i=[],n=1;n<arguments.length;n++)i.push(arguments[n]);return t.vsprintf(e,i)},new e}),define("CatLab/Webremote/Views/Blocks/CurrentSmiley",["CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Deferred"],function(i,e){function n(e,t,i,n){this.Webremote=e,this.canSwitch=void 0!==t&&!!t,this.canDrag=void 0!==i&&!!i,this.isProfileSmiley=void 0===n||!!n,this.dragDisabled=!1,this.switchVerb="Switch"}n.initialize=function(){return n.isInitialized||(n.isInitialized=new e).resolve(),n.isInitialized.promise()}.bind(this),n.activeSmileys=["1f601","1f60d","1f60e"];var t=n.prototype;return t._makeDraggable=function(n,s){var o=this,r=null,a=null,l=!1,c=!1,h=0,u=0,d=0,f=0,m=0,p=0;function e(e){var t,i;o.dragDisabled||(l=!0,n.style.cursor="grabbing",i=(void 0!==e.clientX?e:e.touches[0]).clientX,t=(void 0!==e.clientY?e:e.touches[0]).clientY,h=i,u=t,r={left:d=m,top:f=p},i=n.getBoundingClientRect(),a={left:i.left+window.pageXOffset,top:i.top+window.pageYOffset},o.disableDrag(),n.classList.add("flinging"),e.preventDefault())}function t(e){var t,i;l&&(t=(void 0!==e.clientX?e:e.touches[0]).clientX,i=(void 0!==e.clientY?e:e.touches[0]).clientY,m=d+(t-h),p=f+(i-u),n.style.left=m+"px",n.style.top=p+"px",e.preventDefault())}function i(e){var t,i;l&&(l=!1,i={left:m,top:p},10<(t=o.getDistance(r,i))?(c=!0,i=o.getAngle(r,i),o.slingshot(a,i,t,n,s,function(){p=m=0,n.style.cursor="grab"})):(n.style.left="0px",n.style.top="0px",p=m=0,n.style.cursor="grab",o.enableDrag(),n.classList.remove("flinging")),e.preventDefault())}n.style.zIndex="10",n.style.position="relative",n.style.touchAction="none",n.style.cursor="grab",n.addEventListener("mousedown",e),n.addEventListener("touchstart",e,{passive:!1}),document.addEventListener("mousemove",t),document.addEventListener("touchmove",t,{passive:!1}),document.addEventListener("mouseup",i),document.addEventListener("touchend",i),document.addEventListener("touchcancel",function(){l&&(l=!1,n.style.left="0px",n.style.top="0px",p=m=0,n.style.cursor="grab",o.enableDrag(),n.classList.remove("flinging"))}),n.addEventListener("click",function(e){c&&(c=!1,e.stopPropagation(),e.preventDefault())},!0)},t._animateElement=function(r,a,l,c){for(var h={},u=Object.keys(a),e=0;e<u.length;e++){var t=u[e];h[t]=parseFloat(r.style[t])||0}var d=null;requestAnimationFrame(function e(t){d=d||t;for(var t=Math.min((t-d)/l,1),i=.5-Math.cos(t*Math.PI)/2,n=0;n<u.length;n++){var s=u[n],o=h[s]+(a[s]-h[s])*i;r.style[s]=o+("opacity"===s?"":"px")}t<1?requestAnimationFrame(e):c&&c()})},t.setSmiley=function(t){Array.isArray(t)||(t=[t]),this.smileys=t,n.initialize().then(function(){var e;this.selector&&(this.selector.innerHTML="",t.forEach(function(e){var t=this.Webremote.smileys.getElement(e);if(this.selector.appendChild(t),this.canDrag)try{this._makeDraggable(t,e)}catch(e){console.log(e)}}.bind(this)),this.canSwitch)&&((e=document.createElement("p")).className="switch",e.innerHTML='<a href="javascript:void(0)">'+i.t(this.switchVerb)+"</a>",this.selector.appendChild(e))}.bind(this))},t.disableDrag=function(){this.dragDisabled=!0,this.selector&&this.selector.classList.add("drag-disabled")},t.enableDrag=function(){this.dragDisabled=!1,this.selector&&this.selector.classList.remove("drag-disabled")},t.getMaxDistance=function(){var e;return this.selector?(e=this.selector.getBoundingClientRect(),window.innerHeight-e.top):200},t.getDistance=function(e,t){var i=e.left-t.left,e=e.top-t.top;return Math.sqrt(i*i+e*e)},t.getAngle=function(e,t){return Math.atan2(t.top-e.top,t.left-e.top)},t.slingshot=function(e,t,i,n,s,o){var r=Math.min(1,i/this.getMaxDistance());0<Math.sin(t-Math.PI)?this._animateElement(n,{left:0,top:0},1e3,function(){o&&o(),this.enableDrag(),n.classList.remove("flinging")}.bind(this)):(i=1.5*Math.max(e.left,e.top),this._animateElement(n,{left:Math.cos(t-Math.PI)*i,top:Math.sin(t-Math.PI)*i},1e3,function(){setTimeout(function(){n.style.left=-1*parseFloat(n.style.left)+"px",this._animateElement(n,{left:0,top:0},1e3,function(){o&&o(),this.enableDrag(),n.classList.remove("flinging")}.bind(this))}.bind(this),3e3*r)}.bind(this)),setTimeout(function(){this.Webremote.emit("smileys:slingshot",{angle:t,speed:r,smiley:s})}.bind(this),800))},t.render=function(e){n.initialize().then(function(){this.container=e,this.canSwitch||this.canDrag?(this.selector=document.createElement("div"),this.selector.className="smiley-selector"):(this.selector=document.createElement("div"),this.selector.className="smiley-view"),this.selector.innerHTML='<div class="placeholder"></div>',this.container.innerHTML="",this.container.appendChild(this.selector),this.canSwitch&&(this.container.addEventListener("click",function(){this.isProfileSmiley?this.Webremote.showSmileyPopup():this.Webremote.showSmileyPopup(function(e){if(-1===n.activeSmileys.indexOf(e)){for(;2<n.activeSmileys.length;)n.activeSmileys.shift();n.activeSmileys.push(e),this.setSmiley(n.activeSmileys)}}.bind(this),!1)}.bind(this)),this.isProfileSmiley||this.setSmiley(n.activeSmileys))}.bind(this))},n}),define("CatLab/Webremote/Tools/HashParser",[],function(){return{getParameters:function(){for(var e,t={},i=/\+/g,n=/([^&;=]+)=?([^&;]*)/g,s=function(e){return decodeURIComponent(e.replace(i," "))},o=window.location.hash.substring(1);e=n.exec(o);)t[s(e[1])]=s(e[2]);return t},getParameter:function(e){var t=this.getParameters();return void 0!==t[e]?t[e]:null},clear:function(){history.pushState("",document.title,window.location.pathname+window.location.search)}}}),define("CatLab/Webremote/Tools/Screenfull",[],function(){var r="undefined"!=typeof window&&void 0!==window.document?window.document:{},a=(()=>{for(var e,t=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]],i=0,n=t.length,s={};i<n;i++)if((e=t[i])&&e[1]in r){for(i=0;i<e.length;i++)s[t[0][i]]=e[i];return s}return!1})(),i={change:a.fullscreenchange,error:a.fullscreenerror},e={request:function(s,o){return new Promise(function(e,t){var i=function(){this.off("change",i),e()}.bind(this),n=(this.on("change",i),(s=s||r.documentElement)[a.requestFullscreen](o));n instanceof Promise&&n.then(i).catch(t)}.bind(this))},exit:function(){return new Promise(function(e,t){var i,n;this.isFullscreen?(i=function(){this.off("change",i),e()}.bind(this),this.on("change",i),(n=r[a.exitFullscreen]())instanceof Promise&&n.then(i).catch(t)):e()}.bind(this))},toggle:function(e,t){return this.isFullscreen?this.exit():this.request(e,t)},onchange:function(e){this.on("change",e)},onerror:function(e){this.on("error",e)},on:function(e,t){e=i[e];e&&r.addEventListener(e,t,!1)},off:function(e,t){e=i[e];e&&r.removeEventListener(e,t,!1)},raw:a};return Object.defineProperties(e,{isFullscreen:{get:function(){return Boolean(r[a.fullscreenElement])}},element:{enumerable:!0,get:function(){return r[a.fullscreenElement]}},isEnabled:{enumerable:!0,get:function(){return Boolean(r[a.fullscreenEnabled])}}}),e}),define("CatLab/Webremote/Views/Alert",[],function(){return function(e,t){t=t||function(){},alert(e),t()}}),define("CatLab/Webremote/Views/Welcome",["CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Views/User","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Tracker"],function(e,t,i,o){return function(e){var t=this,i=document.createElement("div"),n=(i.className="catlab-popup-container",document.createElement("div")),n=(n.className="overlay",i.appendChild(n),document.createElement("div")),e=(n.className="popup thanks",i.appendChild(n),n.innerHTML=e,document.createElement("a")),s=(e.innerHTML="Start playing",e.onclick=function(){t.close()},e.href="javascript:void(0)",document.createElement("p"));s.appendChild(e),s.className="playnow",n.appendChild(s),this.close=function(){i.parentNode.removeChild(i),o.track("Click","Close popup","WelcomePopup")},this.render=function(e){e.appendChild(i)}}}),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 i=t.prototype;return i.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))},i.text=function(e){this.message=e,this.div&&(this.div.innerHTML="<p>"+e+"</p>")},i.hide=function(){this.visible=!1,this.div&&this.div.parentNode&&this.div.parentNode.removeChild(this.div),this.showTimeout&&clearTimeout(this.showTimeout),this.message=null,this.div=null,this.showTimeout=null},t}),define("CatLab/Webremote/Views/GamePaused",["CatLab/Webremote/Tools/Translator"],function(e){function t(){this.visible=!1,this.div=null,this.timeoutTillShow=1,this.showTimeout=null,this.message=null}var i=t.prototype;return i.show=function(){this.visible||(this.visible=!0,this.div)||(this.showTimeout&&(clearTimeout(this.showTimeout),this.showTimeout=null),setTimeout(function(){this.div||this.visible&&(this.showTimeout=null,this.div=document.createElement("div"),document.body.appendChild(this.div),this.div.style.position="fixed",this.div.style.right="0",this.div.style.top="0",this.div.style.width="100%",this.div.style.height="100%",this.div.style.padding="0",this.div.style.background="black",this.div.style.zIndex="100000",this.div.style.textAlign="center",this.div.style.color="white",this.div.style.font="Sans-serif",this.div.style.fontSize="2em",this.div.style.opacity=.9,this.message?this.text(this.message):this.text(e.t("Please wait, the game is paused.")))}.bind(this),this.timeoutTillShow))},i.text=function(e){this.message=e,this.div&&(this.div.innerHTML='<p style="height: 100%; padding: 20% 0">'+e+"</p>")},i.hide=function(){this.visible=!1,this.div&&this.div.parentNode.removeChild(this.div),this.showTimeout&&clearTimeout(this.showTimeout),this.message=null,this.div=null,this.showTimeout=null},t}),define("CatLab/Webremote/Synchronization/ClientRemoteView",[],function(){function e(e,t,i,n,s,o){this.controller=e,this.html="<p>Loading</p>",this.context={},this.viewId=t,this.name=i,this.groupId=void 0!==n?n:null,this.synchronizedData=s,this.createdAt=new Date,this.iframe=o,this.currentValues=[],this.buttons=[]}var s={},t=e.prototype;return t.render=function(e){var t;this.iframe?((t=document.createElement("iframe")).style.width="100%",t.style.height="100%",t.style.border="none",t.style.margin="0",t.style.padding="0",t.style.position="absolute",t.style.left="0",t.style.top="0",e.innerHTML="",e.appendChild(t),this.element=t.contentDocument.body):this.element=e,this.el=e,this.$el=e,this.element.innerHTML=this.html,this.update(),this.controller.components.attach(this,document.body),this.updateEvents(),setTimeout(function(){this.updateEvents(),window.scrollTo(0,1)}.bind(this),10),setTimeout(function(){this.updateEvents()}.bind(this),100),setTimeout(function(){this.updateEvents()}.bind(this),1e3)},t.updateEvents=function(){var h=this;function e(n,t,s){var o,r,a,l,c;h.shouldSetEvents(n,"touch")&&(l=!1,c=null,n.addEventListener("touchstart",function(e){return o=new Date,r={x:e.touches[0].pageX,y:e.touches[0].pageY},a={x:e.touches[0].pageX,y:e.touches[0].pageY},l=!0,c&&clearTimeout(c),t.apply(h,[n])}),n.addEventListener("touchmove",function(e){a={x:e.touches[0].pageX,y:e.touches[0].pageY}}),n.addEventListener("touchend",function(e){var t,i;if(r)return i=Math.abs(a.x-r.x),t=Math.abs(a.y-r.y),r=null,i=(new Date).getTime()-o.getTime()<300&&i<20&&t<20,c=setTimeout(function(){l=!1},1e3),s.apply(h,[n,i])}),n.addEventListener("mousedown",function(e){if(e.preventDefault(),!l)return t.apply(h,[n])}),n.addEventListener("mouseup",function(e){if(e.preventDefault(),!l)return s.apply(h,[n,!0])}))}for(var t=this.element.querySelectorAll("[data-button-id]"),i=0;i<t.length;i++)e(t[i],h.buttonDown,h.buttonUp),this.buttons.push(t[i]);for(t=this.element.querySelectorAll("[data-authentication-button]"),i=0;i<t.length;i++)e(t[i],function(){},h.authenticate);for(t=this.element.querySelectorAll("[data-value-id]"),i=0;i<t.length;i++)(t=>{var i,e;h.shouldSetEvents(t,"change")&&(i=t.getAttribute("data-value-id"),h.currentValues[i]=h.getDataValue(t),t.addEventListener("change",function(e){s[i]=new Date,h.syncValue(t)}),e=null,t.addEventListener("keyup",function(){e&&clearTimeout(e),e=setTimeout(function(){s[i]=new Date,h.syncValue(t)},1e3)}))})(t[i])},t.getDataValue=function(e){return"checkbox"===e.type?e.checked?1:0:e.value},t.syncValues=function(){for(var e=this.element.querySelectorAll("[data-value-id]"),t=0;t<e.length;t++)this.syncValue(e[t])},t.syncValue=function(e){var t=this.getDataValue(e),i=e.getAttribute("data-value-id");void 0!==this.currentValues[i]&&this.currentValues[i]===t||(this.currentValues[i]=t,this.controller.syncValue(i,this.getDataValue(e),this.viewId))},t.update=function(){for(var e=this.element.querySelectorAll("[data-button-decorator]"),t=0;t<e.length;t++)void 0===e[t].dataset.initialClasses&&(e[t].dataset.initialClasses=e[t].className);this.updateBigTextSizes()},t.updateBigTextSizes=function(){for(var e=this.element,t=e.querySelectorAll(".bigtext"),i={},n=0;n<t.length;n++){var s,o=t[n],r=o.getAttribute("data-bigtext-group");if(r){if(void 0===i[r]){i[r]=0;for(var a=e.querySelectorAll('.bigtext[data-bigtext-group="'+r+'"]'),l=0;l<a.length;l++)i[r]=Math.max(i[r],a[l].textContent.length)}s=i[r]}else s=o.textContent.length;o.setAttribute("data-bigtext-length",s)}},t.shouldSetEvents=function(e,t){return void 0===e["hasCatlabEventsAlready"+t]&&(e["hasCatlabEventsAlready"+t]=!0)},t.buttonDown=function(e){try{this.syncValues()}catch(e){console.error(e)}return this.controller.buttonDown(e.getAttribute("data-button-id"),this.viewId),!1},t.buttonUp=function(e,t){return this.controller.buttonUp(e.getAttribute("data-button-id"),this.viewId,t),!1},t.setLabel=function(e,t){for(var i=this.element.querySelectorAll("[data-button-label="+e+"]"),n=0;n<i.length;n++)i[n].innerHTML=t;this.update()},t.setClass=function(e,t){for(var i=this.element.querySelectorAll("[data-button-decorator="+e+"]"),n=0;n<i.length;n++){var s=i[n];s.className=s.dataset.initialClasses+" "+t}this.update()},t.domAppend=function(e,t){var i=document.getElementById(e);if(i){for(var n=this.stringToDom(t),s=[];n.firstChild;)s.push(i.appendChild(n.firstChild));try{for(var o=0;o<s.length;o++)this.controller.components.attach(this._currentView,s[o],!1)}catch(e){console.log(e)}5e3<(new Date).getTime()-this.createdAt.getTime()&&0<s.length&&void 0!==s[0].scrollIntoView&&s[0].scrollIntoView(),this.update(),this.updateEvents()}},t.domReplace=function(e,t){e=document.getElementById(e);e&&(e.innerHTML=t,this.controller.components.attach(this._currentView,e,!1),this.update(),this.updateEvents())},t.domAttribute=function(e,t,i){for(var n=document.querySelectorAll(e),s=0;s<n.length;s++)n[s].setAttribute(t,i)},t.changeValue=function(e){if(void 0!==s[e.id]){if((t=Math.abs(s[e.id].getTime()-(new Date).getTime()))<5)return}else var t=9999999999999;for(var i=this.element.querySelectorAll("[data-value-id="+e.id+"]"),n=0;n<i.length;n++)document.activeElement==i[n]&&t<5e3||(this.currentValues[e.id]=e.value,i[n].value=e.value)},t.vibrate=function(e){void 0!==window.navigator.vibrate&&void 0!==e.pattern&&Array.isArray(e.pattern)&&window.navigator.vibrate(e.pattern)},t.stringToDom=function(e){var t;return(t=0<=e.toLowerCase().indexOf("<tr")?document.createElement("tbody"):document.createElement("div")).innerHTML=e,t},t.stringInterpolateDataElements=function(e,s){return e.replace(/{{(.+?)}}/g,function(e,t,i,n){t=this.controller.resolveDataAttribute(t.trim());return t=s?s(t):t}.bind(this))},t.destroy=function(){this.syncValues(),void 0!==this.synchronizedData&&this.synchronizedData.destroy()},e}),define("CatLab/Webremote/Synchronization/DataItem",[],function(){function i(e,t,i){this.key=e,this.shared=t,this.side=i}var e=i.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}},i.unserialize=function(e){var t=new i(e.key,e.shared,e.side);return t.setValue(e.value),t},i}),define("CatLab/Webremote/Synchronization/SynchronizedData",["CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Synchronization/DataItem"],function(e,s){function t(e,t,i){this.initializeEventable(),this.id=e,this.synchronizer=t,this.side=i,this.data={}}e=t.prototype=new e;return e.set=function(e,t,i){if(void 0===this.data[e])this.data[e]=new s(e,i,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,i=e.side,n=e.value;if(void 0===this.data[t])this.data[t]=new s(t,e.shared,i);else if(!this.data[t].canWrite(i))throw"Trying to overwrite a non shared data attribute: "+t;this.data[t].setValue(n)},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]=s.unserialize(e[t]))},t}),define("CatLab/Webremote/Synchronization/DataSynchronizer",["CatLab/Webremote/Synchronization/SynchronizedData"],function(t){function e(e,t,i){this.namespace=e,this.emit=t,this.dataModels={},this.side=i}e.eventsToListenFor=["data:set"];var i=e.prototype;return i.checkNamespace=function(e){return void 0!==e.namespace&&e.namespace===this.namespace},i.processMessage=function(e,t){void 0!==t.container&&this.getFromIdentifier(t.container).processMessage(t)},i.getFromIdentifier=function(e){return void 0===this.dataModels[e]&&(this.dataModels[e]=new t(e,this,this.side)),this.dataModels[e]},i.destroy=function(e){e=e.id;void 0===this.dataModels[e]&&delete this.dataModels[e]},i.refreshTarget=function(e){for(var t in this.dataModels)this.dataModels.hasOwnProperty(t)&&this.dataModels[t].refreshTarget(e)},i.serialize=function(){var e,t={};for(e in this.dataModels)this.dataModels.hasOwnProperty(e)&&(t[e]=this.dataModels[e].serialize());return{dataModels:t}},i.unserialize=function(e){for(var t in e.dataModels)e.dataModels.hasOwnProperty(t)&&this.getFromIdentifier(t).unserialize(e.dataModels[t])},e}),define("CatLab/Webremote/Synchronization/EventHandler",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e,t){this.initializeEventable(),this.namespace=e,this.emit=t}t.eventsToListenFor=["event:trigger"];e=t.prototype=new e;return e.checkNamespace=function(e){return void 0!==e.namespace&&e.namespace===this.namespace},e.processMessage=function(e,t){if("event:trigger"===e)return this.processTriggerEvent(t)},e.processTriggerEvent=function(e){void 0!==e.event&&this.eventableTrigger(e.event,void 0===e.parameters?{}:e.parameters)},e.trigger=function(e,t){this.emit("event:trigger",{namespace:this.namespace,event:e,parameters:t})},e.refreshTarget=function(e){},e.serialize=function(){return{}},e.unserialize=function(e){},t}),define("CatLab/Webremote/Synchronization/CombinedEventHandler",["CatLab/Webremote/Tools/Eventable"],function(e){function t(e,t){this.initializeEventable(),this.handlers=[]}return(t.prototype=new e).addHandler=function(e){this.handlers.push(e),e.on("*",function(e,t){this.trigger(t,e)}.bind(this))},t}),define("CatLab/Webremote/Synchronization/MessageQueue",[],function(){function e(){this.queue=[]}var t=e.prototype;return t.add=function(e,t,i){this.queue.push({action:e,data:t,ack:i})},t.flush=function(){var e=this.queue;return this.queue=[],e},t.compactFlush=function(){var n,s,o,r,a=[],e=this.flush();return 0===e.length?e:(s={user:{},group:{}},o=0,r={},e.forEach(function(e){if(o++,this.canCompact(e)){var t=null;void 0!==e.data.user?t="user":void 0!==e.data.group&&(t="group"),void 0===s[t][e.action]&&(s[t][e.action]=[]);for(var i=0;i<s[t][e.action].length;i++)if(n=s[t][e.action][i],this.isSimilarMessage(n.event,e)&&(void 0===r[e.data[t]]||r[e.data[t]]<n.index))return r[e.data[t]]=n.index,n.event.data[t].push(e.data[t]),void n.event.data._d.push(this.getDifference(n.event,e));Array.isArray(e.data[t])||(e.data[t]=[e.data[t]]),e.data._d=[{}],r[e.data[t]]=o,s[t][e.action].push({event:e,index:o})}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 i,n={};for(i in t.data)if(t.data.hasOwnProperty(i)){switch(i){case"user":case"group":case"_d":case"_i":continue}void 0!==e.data[i]&&e.data[i]===t.data[i]||(n[i]=t.data[i])}return n},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 i=Array.isArray(e[t])?e[t]:[e[t]],n=[];void 0!==e._d&&(n=Array.isArray(e._d)?e._d:[e._d]);for(var s=[],o=0;o<i.length;o++){(r={})[t]=i[o];var r=Object.assign({},e,r,void 0!==n[o]?n[o]:{});delete r._d,s.push(r)}return s},Object.defineProperty(t,"length",{get:function(){return this.queue.length}}),e}),define("CatLab/Webremote/Tools/Proxy",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred"],function(i,n){function e(){}function s(e,t,i){var n=(()=>{for(var e=!1,t=0;t<o.length;t++){try{e=o[t]()}catch(e){continue}break}return e})();n&&(n.open(i?"POST":"GET",e,!0),i&&n.setRequestHeader("Content-type","application/x-www-form-urlencoded"),n.onreadystatechange=function(){4==n.readyState&&(200==n.status||304==n.status?t(n):console.error("CatLab Remote HTTP error "+n.status))},4!=n.readyState)&&n.send(i)}var o=[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){i.getProxy()&&(e=i.getProxy()+encodeURIComponent(e));var t=new n;return s(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,s,o){function t(){this.initializeProvider()}var i=t.prototype;return i.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={}},i.getProviderSettings=function(){var e=new o;return e.resolve({}),e.promise()},i.setMessageCounter=function(e){this.messageCounter=e},i.initMaster=function(e){this.master=e},i.initPlayer=function(e){this.master=e},i.connect=function(){var e=new o;return e.resolve(),e.promise()},i.disconnect=function(){this.off()},i.setOAuthSettings=function(e){this.emit("oauth:set",e)},i.canProviderLoadExternalXml=function(){return!1},i.canProxyFiles=function(){return!1},i.loadViews=function(t,e,i){var n=new o;return void 0===e&&(e=!1),void 0===i&&(i=this),this.canProviderLoadExternalXml()&&!e?i.emit("view:load",{url:t},function(){n.resolve()}):s.get(t).then(function(e){this.parseViews(e,t,i).then(function(){n.resolve()})}.bind(this)),n.promise()},i.parseViews=function(e,t,i){var n=new o,s=void 0!==t;return void 0===i&&(i=this),s&&void 0!==this.viewNameIdentifierMap[t]?i.emit("view:load",{identifier:this.viewNameIdentifierMap[t]},function(){n.resolve()}):(i.emit("view:load",{xml:e},function(e){s&&e&&e.identifier&&(this.viewNameIdentifierMap[t]=e.identifier),n.resolve()}.bind(this)),this.onParseViews(e)),n.promise()},i.onParseViews=function(e){},i.registerComponent=function(e,t,i){t="string"==typeof t?t:t&&void 0!==t.innerHTML?t.innerHTML:String(t),e='<views><component id="'+e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")+'" xmlns="http://www.w3.org/1999/xhtml">'+t+"</component></views>";return this.parseViews(e,void 0,i)},i.toMaster=function(e,t,i){this.emit(e,t,i)},i.toPlayers=function(e,t,i){this.emit(e,t,i)},i.toPlayer=function(e,t,i,n){i.user=e.getId(),this.emit(t,i,n)},i.toGroup=function(e,t,i,n){i.group=e.getId(),this.emit(t,i,n)},i.emit=function(e,t,i){this.initialized?this.queue?(this.queue.add(e,t,i),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,i):this.postInitializeQueue.push({action:e,data:t,ack:i})},i.createGroup=function(e,t,i,n){this.emit("group:create",{externalId:e,globalViews:t,shareColor:i,tags:n=void 0===n?[]:n})},i.executeQueue=function(){this.initialized&&this.emitAll()},i.setInitialized=function(){var e;for(this.initialized=!0;e=this.postInitializeQueue.shift();)this.emit(e.action,e.data,e.ack)},i.setup=function(e){this.emit("master:setup",e)},i.reset=function(e){this.emit("master:reset",null,function(){e()})},i.getStaticUrl=function(e){return e},i.reconnect=function(e,t,i,n){var s=new o;return this.emit("master:reconnect",{token:e,accessToken:t,gameConfig:i},function(){n(),s.resolve()}.bind(this)),s.promise()},i.off=function(){this.events={}},i.on=function(e,t){this._addEvent(e,t,!1),this._touchEvent(e)},i.once=function(e,t){this._addEvent(e,t,!0),this._touchEvent(e)},i._addEvent=function(e,t,i){void 0===this.events[e]&&(this.events[e]=[]),this.events[e].push({callback:t,once:i})},i._touchEvents=function(){for(var e in this.events)this.events.hasOwnProperty(e)&&this._touchEvent(e)},i._touchEvent=function(e){},i._trigger=function(e,i){var n;void 0!==this.events[e]&&(n=[],this.events[e].forEach(function(e){var t=e.callback;e.once&&n.push(e);try{t.apply(this,[i])}catch(e){console.error(e)}}),0<n.length)&&(n.unshift(this.events),function(e){for(var t,i,n=arguments,s=n.length;1<s&&e.length;)for(t=n[--s];-1!==(i=e.indexOf(t));)e.splice(i,1);return e}.apply(this,n))},i.getConnectURL=function(e){return null},i.getConnectToken=function(e){return null},i.tokenConnect=function(e){var t=new o;return t.resolve(),t.promise()},i.noTokenConnect=function(){var e=new o;return e.resolve(),e.promise()},i.restoreProviderSettings=function(e){},i.serializeProviderSettings=function(){return{}},i.proxyFile=function(e){var t=new o;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,r,a,t){function i(){this.initializeProvider(),this.userId=null,this.randomToken=t.getUuid(),this.loadBalancerSessionToken="connid",this.socket=null,this._registeredEvents={},this._host=null}var l=null,e=i.prototype=new e;return e.getProviderSettings=function(){var t=new a;return r.getServerList()?r.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(n,s){var t,o=new a;return this.log("Loading socket.io"),t=function(){this.log("Connecting to socket.io");var e,t=r.getSocketURL(),i=(this._host?t=this._host:void 0!==s.host&&s.host&&(t=(e=r.getProtocol())?e+"://"+s.host:"//"+s.host,this._host=t),this.socket=l(t+"/"+n+"?"+this.loadBalancerSessionToken+"="+this.randomToken,{withCredentials:!1,reconnection:!0}),!1);this.socket.on("connect_error",function(e){i?this._trigger("disconnect"):(this.socket.off(),this.socket.disconnect(),this.socket=null,o.reject())}.bind(this)),this.socket.once("connect",function(){i||(i=!0,this.setInitialized(),this.socket.io.on("reconnect",function(e){this._trigger("reconnect")}.bind(this)),this._touchEvents(),o.resolve())}.bind(this))}.bind(this),require(["socket.io-client"],function(e){l=e,t()}),o.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,i){this.socket.emit(e,t,i),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 r.getServerList()?r.getServerList().getConnectURL():e},e.getConnectToken=function(e){return r.getServerList()?r.getServerList().getConnectToken(e):e},e.tokenConnect=function(e){var t=new a,i={};if(r.getServerList())try{var n=r.getServerList().getFromToken(e);i.host=n.host,e=n.token}catch(e){return t.reject(),t.promise()}return this.connect("remote",i).fail(function(){t.reject()}).then(function(){t.resolve(e)}),t.promise()},e.restoreProviderSettings=function(e){void 0!==e.serverlist&&r.getServerList()&&r.getServerList().unserialize(e.serverlist),void 0!==e.host&&(this._host=e.host)},e.serializeProviderSettings=function(){var e={host:this._host};return r.getServerList()&&(e.serverlist=r.getServerList().serialize()),e},i}),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,i){function e(e){this.peakThreshold=(e=e||{}).peakThreshold||-65,this.minRunLength=e.minRunLength||2,this.coder=e.coder||new i(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=n,this.isRunning=!1,this.iteration=0}var n=1,s=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,i=this.freqToIndex(this.coder.freqMin);i<this.freqs.length;i++)this.freqs[i]>e&&(e=this.freqs[i],t=i);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=n,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==n?e==this.coder.startChar&&(this.buffer="",this.state=s):this.state==s&&(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=n,this.fire_(this.callbacks.message,this.buffer),this.buffer=""))},e.prototype.getLastRun=function(){for(var e=this.peakHistory.last(),t=0,i=this.peakHistory.length()-2;0<=i&&this.peakHistory.get(i)==e;i--)t+=1;return t>this.minRunLength?(this.peakHistory.remove(i+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 i=this.freqs[t]+400,i=e.height-i-1,n=e.width/this.freqs.length;drawContext.fillStyle="black",drawContext.fillRect(t*n,i,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 i=!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 i}return"undefined"!=typeof window&&(i=window.AudioContext||window.webkitAudioContext||!1),e.prototype.send=function(e,t){e=this.coder.startChar+e+this.coder.endChar;for(var i,n=0;n<e.length;n++){var s=e[n],s=this.coder.charToFreq(s),o=this.audioContext.currentTime+this.charDuration*n;this.scheduleToneAt(s,o,this.charDuration)}t&&(i=this.charDuration*e.length,setTimeout(t,1e3*i))},e.prototype.scheduleToneAt=function(e,t,i){var n=this.audioContext.createGain(),i=(n.gain.value=0,n.gain.setValueAtTime(0,t),n.gain.linearRampToValueAtTime(1,t+this.rampDuration),n.gain.setValueAtTime(1,t+i-this.rampDuration),n.gain.linearRampToValueAtTime(0,t+i),n.connect(this.audioContext.destination),this.audioContext.createOscillator());i.frequency.value=e,i.connect(n),i.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,i,n,s,o){function r(e){this.options=t.getAudioSyncConfig(),this.alphabet=this.options.alphabet.split(""),this.controller=e}var a=r.prototype;return a.startListener=function(){this.stop();var e=new n(this.options);e.start(),e.on("message",this.onIncomingMessage.bind(this)),this.sonicServer=e},a.startSender=function(){this.sonicSocket=new s(this.options)},a.stop=function(){this.sonicServer&&this.sonicServer.stop()},a.sync=function(){var e=new o,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,i="",n="",s=0;s<e;s++){for(;t=Math.floor(Math.random()*this.alphabet.length),(n=this.alphabet[t])===i.substr(i.length-1,1););i+=n}return i},a.getParityLetter=function(e){for(var t=0,i=e.split(""),n=0;n<i.length;n++)t+=this.alphabet.indexOf(i[n]);e=t%this.alphabet.length;return i[i.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),i=this.getParityLetter(t);i===e[e.length-1]?this.onMessage(t):console.log("Parity check failed, expected "+i+", ignoring message")},a.onMessage=function(e){this.controller.emit("sync:audio",{secret:e})},a.generateAlphabet=function(e){for(var t="",i=0;i<Math.min(e.length,9);i++)t+=i.toString();return t},r}),define("CatLab/Webremote/Tools/ClientSniffer",[],function(){function e(){this._canPlayWebM=null}var t=e.prototype;return t.isMobileBrowser=function(){var e,t;return!(!this.isCordova()&&(e=!1,t=navigator.userAgent||navigator.vendor||window.opera,!/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t))&&!/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4)))||e},t.isCordova=function(){return"undefined"!=typeof cordova},t.isInternetExplorer=function(){var e=window.navigator.userAgent,t=e.indexOf("MSIE ");return 0<t?parseInt(e.substring(t+5,e.indexOf(".",t)),10):0<e.indexOf("Trident/")?(t=e.indexOf("rv:"),parseInt(e.substring(t+3,e.indexOf(".",t)),10)):0<(t=e.indexOf("Edge/"))&&parseInt(e.substring(t+5,e.indexOf(".",t)),10)},t.supportsLocalStorage=function(){try{if(window.localStorage)return!0}catch(e){return!1}},t.canPlayWebM=function(){if(null===this._canPlayWebM){this._canPlayWebM=!1;try{var e=document.createElement("video");e.canPlayType&&(this._canPlayWebM=e.canPlayType('video/webm; codecs="vp8, vorbis"'))}catch(e){console.error(e)}}return this._canPlayWebM},new e}),define("CatLab/Webremote/Components/ImagePositionInputComponent",["CatLab/Webremote/Tools/ClientSniffer"],function(s){function e(e,t){this.element=t,this.remotePlayerView=e,this.positions=[],this.canvas=null,this.isLoaded=!1,this.isRotated=!1,this.buttons=null,this.pointCountContainer=null,this.draw()}var t=e.prototype;return t.draw=function(){this.element.innerHTML="",this.rotatedImageElement=null,this.buttons=null,this.circleRadius=this.element.getAttribute("circleRadius")||2,this.circleStroke=this.element.getAttribute("circleStroke")||Math.max(.5,this.circleRadius/5),this.circleStrokeColor=this.element.getAttribute("circleStrokeColor")||"red",this.circleFillColor=this.element.getAttribute("circleFillColor")||"rgb(255,255,0,0.3)",this.image=this.element.getAttribute("src"),this.image&&(this.element.innerHTML='<div class="image"><img /></div>',this.imageElement=this.element.querySelector("img"),this.imageElement.addEventListener("load",function(){this.isLoaded=!0,this.resizeImage()}.bind(this)),this.imageElement.setAttribute("src",this.image),this.resizeImage(),this.imageElement.addEventListener("dragstart",function(e){e.preventDefault()}),this.svgContainer=document.createElement("div"),this.svgContainer.className="pointer-container",this.element.querySelector(".image").appendChild(this.svgContainer),this.resizeSvgContainer(),this.svgContainer.addEventListener("click",function(e){this.svgClick(e)}.bind(this)))},t.resizeSvgContainer=function(){var e=this.imageElement;this.isRotated&&this.rotatedImageElement&&(e=this.rotatedImageElement),this.svgContainer.style.position="absolute",this.svgContainer.style.zIndex="1",this.svgContainer.style.width=e.offsetWidth+"px",this.svgContainer.style.height=e.offsetHeight+"px",this.svgContainer.style.left=e.offsetLeft+"px",this.svgContainer.style.top=e.offsetTop+"px"},t.resizeImage=function(){var e,t,i,n;this.isLoaded&&(e=this.element.clientWidth,t=this.element.clientHeight,i=this.imageElement.naturalWidth,n=this.imageElement.naturalHeight,s.isMobileBrowser()&&"1"==this.element.getAttribute("rotate")?this.isRotated=e/t<1!=i/n<1:this.isRotated=!1,this.isRotated?this.element.classList.add("rotated"):this.element.classList.remove("rotated"),this.isRotated?(this.generateCanvas(),this.rotatedImageElement.style.display="",this.resizeSvgContainer(),this.imageElement.style.display="none"):this.rotatedImageElement&&(this.rotatedImageElement.style.display="none",this.imageElement.style.display=""),this.imageElement.style.maxWidth=e+"px",this.imageElement.style.maxHeight=t+"px",this.rotatedImageElement&&(this.rotatedImageElement.style.maxWidth=e+"px",this.rotatedImageElement.style.maxHeight=t+"px"),this.resizeSvgContainer())},t.generateCanvas=function(){var e,t,i,n,s,o,r,a;this.rotatedImageElement||(s=this.imageElement,e=this.imageElement.naturalWidth,t=this.imageElement.naturalHeight,(i=document.createElement("canvas")).width=t,i.height=e,n=i.getContext("2d"),s=s,o=i.width/2,r=i.height/2,a=0-Math.PI/2,n.setTransform(1,0,0,1,o,r),n.rotate(a),n.drawImage(s,-e/2,-t/2),this.rotatedImageElement=i,this.element.querySelector("div.image").appendChild(this.rotatedImageElement))},t.imageClick=function(e){var t=e.offsetX/this.imageElement.offsetWidth,e=e.offsetY/this.imageElement.offsetHeight;this.selectPosition(t,e)},t.svgClick=function(e){var t=e.offsetX/this.svgContainer.offsetWidth,e=e.offsetY/this.svgContainer.offsetHeight;this.isRotated?this.selectPosition(1-e,t):this.selectPosition(t,e)},t.canvasClick=function(e){var t=e.offsetX/this.rotatedImageElement.offsetWidth,e=e.offsetY/this.rotatedImageElement.offsetHeight;this.selectPosition(1-e,t)},t.selectPosition=function(e,t){0<this.getMaxPoints()&&this.positions.length>=this.getMaxPoints()||(this.positions.push({x:e,y:t}),this.drawCircles(),this.shouldConfirmPosition()?(this.syncPositionData(!1),this.showSubmitButton()):this.submit())},t.shouldConfirmPosition=function(){return"1"==this.element.getAttribute("confirm-position")},t.getMinPoints=function(){return this.element.getAttribute("min-points")&&0<parseInt(this.element.getAttribute("min-points"))?parseInt(this.element.getAttribute("min-points")):1},t.getMaxPoints=function(){return this.element.getAttribute("max-points")&&0<parseInt(this.element.getAttribute("max-points"))?parseInt(this.element.getAttribute("max-points")):1},t.showSubmitButton=function(){var e;this.buttons?this.positionSubmitButton():((e=document.createElement("div")).className="imagemap-buttons",e.innerHTML='<button data-action="submit" class="imagemap-button pulsating">'+(2<this.getMaxPoints()?'<span class="point-counter"></span>':"")+'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 22"><path d="M20.285 2l-11.285 11.567-5.286-5.011-3.714 3.716 9 8.728 15-15.285z"/></svg></button><button data-action="reset" class="imagemap-button"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 22"><path d="M24 20.188l-8.315-8.209 8.2-8.282-3.697-3.697-8.212 8.318-8.31-8.203-3.666 3.666 8.321 8.24-8.206 8.313 3.666 3.666 8.237-8.318 8.285 8.203z" /></button>',this.buttons=e,this.element.appendChild(this.buttons),this.positionSubmitButton(),this.buttons.querySelector("button[data-action=submit]").addEventListener("click",function(){this.submit()}.bind(this)),this.buttons.querySelector("button[data-action=reset]").addEventListener("click",function(){this.reset(),this.hideSubmitButton()}.bind(this)),this.pointCountContainer=this.buttons.querySelector(".point-counter"),this.updatePointCount())},t.updatePointCount=function(){var e;this.pointCountContainer&&(this.pointCountContainer.innerHTML=this.positions.length,this.positions.length<this.getMinPoints()?this.pointCountContainer.classList.add("insufficient"):this.pointCountContainer.classList.remove("insufficient"),e=this.buttons.querySelector("button[data-action=submit]"),this.positions.length>=this.getMinPoints()?(e.classList.add("pulsating"),e.classList.remove("disabled")):(e.classList.remove("pulsating"),e.classList.add("disabled")))},t.hideSubmitButton=function(){this.buttons.style.display="none"},t.positionSubmitButton=function(){this.buttons.style.display="",.5<this.positions[0].x?(this.buttons.classList.add("left"),this.buttons.classList.remove("right")):(this.buttons.classList.add("right"),this.buttons.classList.remove("left"))},t.submit=function(){this.syncPositionData(!0)},t.syncPositionData=function(e){this.positions.length<this.getMinPoints()||this.remotePlayerView.controller.syncValue("position",{x:0<this.positions.length?this.positions[0].x:null,y:0<this.positions.length?this.positions[0].y:null,p:this.positions,c:e},this.remotePlayerView.viewId)},t.drawCircles=function(){this.updatePointCount(),this.svgContainer.innerHTML="",0!==this.positions.length&&this.positions.forEach(function(t){var e=this.imageElement,i=t.x,n=t.y,s=e.offsetWidth,e=e.offsetHeight,o=(this.isRotated&&this.rotatedImageElement&&(i=t.y,n=1-t.x,s=this.rotatedImageElement.offsetWidth,e=this.rotatedImageElement.offsetHeight),this.imageElement.offsetWidth/100*this.circleRadius),r=Math.max(1,this.imageElement.offsetWidth/100*this.circleStroke),a="http://www.w3.org/2000/svg",l=document.createElementNS(a,"svg"),a=document.createElementNS(a,"circle");l.appendChild(a),l.addEventListener("click",function(e){e.preventDefault(),e.stopPropagation(),this.removePoint(t),0===this.positions.length&&this.hideSubmitButton()}.bind(this)),this.svgContainer.appendChild(l),a.setAttribute("cx",o+r),a.setAttribute("cy",o+r),a.setAttribute("r",o),a.setAttribute("stroke-width",r),a.setAttribute("stroke",this.circleStrokeColor),a.setAttribute("fill",this.circleFillColor),l.setAttribute("width",2*(o+r)),l.setAttribute("height",2*(o+r)),l.style.position="absolute",l.style.left=s*i-o-r+"px",l.style.top=e*n-o-r+"px"}.bind(this))},t.removePoint=function(e){e=this.positions.indexOf(e);-1<e&&this.positions.splice(e,1),this.drawCircles()},t.resize=function(){this.resizeImage(),this.drawCircles()},t.update=function(){this.draw()},t.destroy=function(){},t.reset=function(){this.positions=[],this.drawCircles()},e.css=" \t\t\t\timage-position-input {\t\t\t\t\tdisplay: flex; \t\t\t\t\tjustify-content: center;\t\t\t\t\talign-content: center;\t\t\t\t\talign-items: center;\t\t\t\t\twidth: 100%;\t\t\t\t\theight: 100%;\t\t\t\t\tposition: relative;\t\t\t\t\toverflow: hidden;\t\t\t\t} \t\t\t\t \t\t\t\timage-position-input .image { \t\t\t\t\ttext-align: center;\t\t\t\t\ttransform-origin: 0 0; \t\t\t\t} \t\t\t\timage-position-input .image img, \t\t\t\timage-position-input .image canvas { \t\t\t\t\tdisplay: block;\t\t\t\t\tmax-width: 100%;\t\t\t\t\tmax-height: 100%;\t\t\t\t\theight: auto;\t\t\t\t\twidth: auto; \t\t\t\t} \t\t\t\timage-position-input button.imagemap-button svg { \t\t\t\t\theight: 48px; \t\t\t\t\twidth: 48px; \t\t\t\t} \t\t\t\timage-position-input button.imagemap-button { \t\t\t\t\tmargin-left: 10px; \t\t\t\t\tposition: relative; \t\t\t\t} \t\t\t\timage-position-input button.imagemap-button.disabled svg {\t\t\t\t\tfill: gray;\t\t\t\t}\t\t\t\timage-position-input .imagemap-buttons { \t\t\t\t\tposition: absolute; \t\t\t\t\tright: 10px; \t\t\t\t\tbottom: 10px; \t\t\t\t\tz-index: 10; \t\t\t\t} \t\t\t\t\t\t\t\timage-position-input .imagemap-buttons.left {\t\t\t\t\tleft: 10px;\t\t\t\t\tright: auto;\t\t\t\t}\t\t\t\t\t\t\t\timage-position-input.rotated .imagemap-buttons {\t\t\t\t\ttransform: rotate(-90deg);\t\t\t\t\ttransform-origin: 100% 0;\t\t\t\t\ttop: 10px;\t\t\t\t\tright: 80px;\t\t\t\t\tbottom: auto;\t\t\t\t\tleft: auto;\t\t\t\t}\t\t\t\timage-position-input.rotated .imagemap-buttons.left {\t\t\t\t\tbottom: 80px;\t\t\t\t\ttop: auto;\t\t\t\t\tright: 80px; \t\t\t\t\tleft: auto;\t\t\t\t\ttransform-origin: 100% 0;\t\t\t\t}\t\t\t\timage-position-input button.pulsating .point-counter {\t\t\t\t}\t\t\t\timage-position-input .point-counter {\t\t\t\t\tfont-size: 1em;\t\t\t\t\tvertical-align: middle;\t\t\t\t\tposition: absolute;\t\t\t\t\ttop: -1em;\t\t\t\t\tleft: -1em;\t\t\t\t\tborder: 1px solid black;\t\t\t\t\tborder-radius: 100%;\t\t\t\t\tpadding: 0.5em;\t\t\t\t\tbackground: white;\t\t\t\t\tmin-width: 1em;\t\t\t\t}\t\t\t\timage-position-input .point-counter.insufficient {\t\t\t\t\tborder-color: red;\t\t\t\t\tcolor: red;\t\t\t\t}\t\t",e.selector="image-position-input",e}),define("CatLab/Webremote/Components/FullscreenButtonComponent",["CatLab/Webremote/Tools/Screenfull","CatLab/Webremote/Config"],function(e,t){function i(e,t,i){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=i,this.draw()}var n=i.prototype;return n.draw=function(){t.canFullscreen()&&e&&e.isEnabled&&!e.isFullscreen?(this.element.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" style="display: block" width="100%" height="100%" viewBox="0 0 24 24"><path d="M6.426 10.668l-3.547-3.547-2.879 2.879v-10h10l-2.879 2.879 3.547 3.547-4.242 4.242zm11.148 2.664l3.547 3.547 2.879-2.879v10h-10l2.879-2.879-3.547-3.547 4.242-4.242zm-6.906 4.242l-3.547 3.547 2.879 2.879h-10v-10l2.879 2.879 3.547-3.547 4.242 4.242zm2.664-11.148l3.547-3.547-2.879-2.879h10v10l-2.879-2.879-3.547 3.547-4.242-4.242z"/></svg>',this.element.addEventListener("click",function(){e.request(null,{navigationUI:"hide"})}.bind(this))):this.element.innerHTML=""},n.resize=function(){this.draw()},n.update=function(){this.draw()},n.destroy=function(){},i.css=" ",i.selector="fullscreen-button",i}),define("CatLab/Webremote/Components/ViewDefinedComponent",[],function(){function e(e,t){this.element=t,this.remotePlayerView=e,this.position=null,this.draw()}var t=e.prototype;return t.draw=function(){if(this.element){this.element.innerHTML="";for(var e=0;e<this.content.childNodes.length;e++)this.element.appendChild(this.content.childNodes[e].cloneNode(!0));this.componentContainer.attachComponents(this.remotePlayerView,this.element)}},t.update=function(){this.draw()},t.resize=function(){this.draw()},t.destroy=function(){},e.css=" ",e.selector="view-defined-component",e.content="",e}),define("CatLab/Webremote/Views/Popups/IframePopup",["CatLab/Webremote/Views/Popups/BasePopup"],function(e){function t(e){this.url=e}return(t.prototype=new e).renderContent=function(e){this.container.className+=" iframe";var t=document.createElement("iframe");t.src=this.url,t.style.height="99%",t.style.width="100%",t.style.borderWidth="0",e.appendChild(t),e.style.position="relative",e.style.height="100%",e.style.width="100%",e.style.boxSizing="border-box",e.style.overflow="auto",e.style.webkitOverflowScrolling="touch"},t}),define("CatLab/Webremote/Components/ModalIframeLink",["CatLab/Webremote/Views/Popups/IframePopup"],function(t){function e(e,t,i){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=i,this.draw()}var i=e.prototype;return i.draw=function(){this._clickHandler&&this.element.removeEventListener("click",this._clickHandler),this._clickHandler=function(){var e=this.element.getAttribute("href"),e=this.remotePlayerView.stringInterpolateDataElements(e,encodeURIComponent);new t(e).render(document.body)}.bind(this),this.element.addEventListener("click",this._clickHandler)},i.resize=function(){this.draw()},i.update=function(){this.draw()},i.destroy=function(){},e.css=" ",e.selector="modal-iframe-link",e}),define("CatLab/Webremote/Views/Popups/TextPopup",["CatLab/Webremote/Views/Popups/BasePopup"],function(e){function t(e){this.message=e}return(t.prototype=new e).renderContent=function(e){var t=(t=this.message).replace(/(?:\r\n|\r|\n)/g,"<br>");e.innerHTML=t},t}),define("CatLab/Webremote/Components/TooltipComponent",["CatLab/Webremote/Views/Popups/TextPopup"],function(e){function t(e,t,i){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=i,this.draw()}var i=t.prototype;return i.draw=function(){this._clickHandler&&this.element.removeEventListener("click",this._clickHandler),this._clickHandler=function(){new e(this.element.getAttribute("data-tooltip")).render(document.body)}.bind(this),this.element.addEventListener("click",this._clickHandler)},i.resize=function(){},i.update=function(){},i.destroy=function(){},t.css=" ",t.selector="[data-tooltip]",t}),define("CatLab/Webremote/Components/VirtualKeyboardComponent",["SimpleKeyboard","CatLab/Webremote/Config"],function(n,s){var o,r=!1,a=null,e=0;function l(){for(var e=document.querySelectorAll(".simple-keyboard"),t=0;t<e.length;t++)e[t].classList.add("hidden");a=null}function t(e,t,i){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=i,this.inputType=t.getAttribute("type")?t.getAttribute("type").toLowerCase():"text",this.draw()}var i=t.prototype;return i.draw=function(){(function(){if(!r){var e=document.createElement("link"),e=(e.type="text/css",e.rel="stylesheet",e.href=s.getVendorPath()+"simple-keyboard/build/css/index.css",document.head.appendChild(e),document.createElement("div"));e.className="simple-keyboard",document.body.appendChild(e),o=new n.default({onChange:function(e){a&&a.onKeyboardChange(e)}.bind(this),onKeyPress:function(e){switch(e){case"{shift}":case"{lock}":t="default"===o.options.layoutName?"shift":"default",o.setOptions({layoutName:t});break;case"{numbers}":case"{abc}":t="numbers"!==o.options.layoutName?"numbers":"default",o.setOptions({layoutName:t});break;case"{ent}":l();break;case"{arrowup}":a.increaseValue(1);break;case"{arrowdown}":a.increaseValue(-1)}var t}.bind(this),layoutName:"default",layout:{default:["q w e r t y u i o p","a s d f g h j k l","{shift} z x c v b n m {backspace}","{numbers} {space} {ent}"],shift:["Q W E R T Y U I O P","A S D F G H J K L","{shift} Z X C V B N M {backspace}","{numbers} {space} {ent}"],numbers:["1 2 3","4 5 6","7 8 9","{abc} 0 {backspace}"]},physicalKeyboardHighlight:!0,disableCaretPositioning:!1,mergeDisplay:!0,display:{"{numbers}":"123","{ent}":"⇩","{escape}":"esc ⎋","{tab}":"tab ⇥","{backspace}":"⌫","{capslock}":"caps lock ⇪","{shift}":"⇧","{controlleft}":"ctrl ⌃","{controlright}":"ctrl ⌃","{altleft}":"alt ⌥","{altright}":"alt ⌥","{metaleft}":"cmd ⌘","{metaright}":"cmd ⌘","{abc}":"ABC"}});for(var t=document.querySelectorAll(".simple-keyboard"),i=0;i<t.length;i++)t[i].classList.add("hidden");r=!0}})(),this.element.id||(this.element.id="input_"+ ++e),this.element.type="text",/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)&&(this.element.readOnly=!0),this.element.addEventListener("input",this.onInputChange.bind(this)),this.element.addEventListener("focus",this.onInputFocus.bind(this)),this.element.classList.contains("visible")&&this.onInputFocus()},i.hideKeyboard=function(){l()},i.showKeyboard=function(){var e=this,t=this.inputType,i=e.element;"number"===t?o.setOptions({inputName:i.id,layoutName:"numbers",layout:{default:["q w e r t y u i o p","a s d f g h j k l","{shift} z x c v b n m {backspace}","{numbers} {space} {ent}"],numbers:["1 2 3 {arrowup}","4 5 6 {arrowdown}","7 8 9 "+1.1.toLocaleString().substring(1,2),"{backspace} 0 {ent}"]}}):o.setOptions({inputName:i.id,layoutName:"default",layout:{default:["q w e r t y u i o p","a s d f g h j k l","{shift} z x c v b n m {backspace}","{numbers} {space} {ent}"],shift:["Q W E R T Y U I O P","A S D F G H J K L","{shift} Z X C V B N M {backspace}","{numbers} {space} {ent}"],numbers:["1 2 3","4 5 6","7 8 9","{abc} 0 {backspace}"]}});for(var n=document.querySelectorAll(".simple-keyboard"),s=0;s<n.length;s++)n[s].classList.remove("hidden");a=e,o.setInput(i.value,i.id)},i.onKeyboardChange=function(e){this.element.value=e;var t=new Event("change",{bubbles:!0});this.element.dispatchEvent(t),this.element.getAttribute("data-value-realtime")&&(t=this.element.getAttribute("data-value-id"))&&this.remotePlayerView.controller.syncValue(t,e,this.remotePlayerView.viewId)},i.onInputChange=function(){o.setInput(this.element.value,this.element.id)},i.onInputFocus=function(){this.showKeyboard()},i.setInputCaretPosition=function(e){this.element.setSelectionRange&&(this.element.focus(),this.element.setSelectionRange(e,e))},i.increaseValue=function(e){var t;"number"===this.inputType&&(t=(t=parseFloat(this.element.value))||0,this.element.value=t+e)},i.submit=function(){this.hideKeyboard()},i.resize=function(){this.draw()},i.update=function(){this.draw()},i.destroy=function(){this.hideKeyboard()},t.css=" .simple-keyboard { position: fixed; bottom: 0; display: block; } .simple-keyboard.hidden { display: none; } ",t.selector="input.virtual",t}),define("CatLab/Webremote/Components/TimerComponent",[],function(){function e(e,t){this.element=t,this.remotePlayerView=e,this.draw(),this.countdownInterval=setInterval(function(){this.tick()}.bind(this),100),this.startDate=Date.now(),this.targetDate=null,this.counterHtml=null,this.progessBar=null}var t=e.prototype;return t.draw=function(){var e,t=this.element;t.innerHTML="",this.targetDate=this.element.getAttribute("to"),this.targetDate&&((e=this.element.getAttribute("start"))&&(this.startDate=e),(e=document.createElement("div")).className="timer-container",this.counterHtml=document.createElement("div"),this.counterHtml.className="countdown",e.appendChild(this.counterHtml),this.progessBar=document.createElement("div"),this.progessBar.className="progress-bar",this.progessBar.innerHTML="&nbsp;",e.appendChild(this.progessBar),t.appendChild(e))},t.tick=function(){var e,t;this.targetDate&&this.counterHtml&&this.progessBar&&((e=this.targetDate-Date.now())<0?this.counterHtml.innerHTML="0":(t=(Date.now()-this.startDate)/(this.targetDate-this.startDate)*100,this.counterHtml.innerHTML=Math.ceil(e/1e3),this.progessBar.style.width=t+"%"))},t.resize=function(){},t.update=function(){this.draw()},t.clearInterval=function(){this.countdownInterval&&(clearInterval(this.countdownInterval),this.countdownInterval=null)},t.destroy=function(){this.clearInterval()},e.css=" timer-countdown { position: fixed; bottom: 0px; left: 0px; width: 100%; color: white; z-index: 1000; } timer-countdown .progress-bar { position:absolute; height: 3px; bottom: 0; background: #eca93b; } timer-countdown .countdown { display: none; } ",e.selector="timer-countdown",e}),define("CatLab/Webremote/Components/SmileyFlingerComponent",["CatLab/Webremote/Views/Blocks/CurrentSmiley"],function(n){function e(e,t,i){this.element=t,this.remotePlayerView=e,this.position=null,this.componentContainer=i,this.smileySlinger=new n(i.Webremote,!0,!0,!1),this.draw()}var t=e.prototype;return t.draw=function(){this.smileySlinger.render(this.element)},t.resize=function(){this.draw()},t.update=function(){this.draw()},t.destroy=function(){},e.css=" ",e.selector="smiley-flinger",e}),define("CatLab/Webremote/Components/CheatDetectionComponent",[],function(){function e(e,t,i){this.element=t,this.remotePlayerView=e,this.componentContainer=i,this._cheatCheckTimer=null,this._hiddenAt=null,this._onVisibilityChange=this._handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this._onVisibilityChange)}var t=e.prototype;return t._handleVisibilityChange=function(){document.hidden?(this._hiddenAt=Date.now(),null!==this._cheatCheckTimer&&clearTimeout(this._cheatCheckTimer),this._cheatCheckTimer=setTimeout(function(){this._cheatCheckTimer=null,Date.now()-this._hiddenAt<5e3&&this._triggerCheatDetected()}.bind(this),1500)):null!==this._cheatCheckTimer&&(clearTimeout(this._cheatCheckTimer),this._cheatCheckTimer=null)},t._triggerCheatDetected=function(){this.componentContainer&&this.componentContainer.Webremote&&this.componentContainer.Webremote.userEvents&&(this.componentContainer.Webremote.userEvents.trigger("cheat:detected",{}),this.componentContainer.Webremote.groupEvents.trigger("cheat:detected",{}))},t.draw=function(){},t.update=function(){},t.destroy=function(){document.removeEventListener("visibilitychange",this._onVisibilityChange),null!==this._cheatCheckTimer&&(clearTimeout(this._cheatCheckTimer),this._cheatCheckTimer=null)},t.resize=function(){},e.selector="cheat-detection",e}),define("CatLab/Webremote/Components/Components",["./ImagePositionInputComponent","./FullscreenButtonComponent","./ViewDefinedComponent","./ModalIframeLink","./TooltipComponent","./VirtualKeyboardComponent","./TimerComponent","./SmileyFlingerComponent","./CheatDetectionComponent"],function(t,i,s,n,o,r,a,l,c){function e(e){this.components=[t,i,n,o,r,a,l,c],this.Webremote=e,this.viewDefinedComponents=[],this.existingComponents=[]}var h=e.prototype;return h.initialize=function(){for(var e=0;e<this.components.length;e++)this.initializeComponent(this.components[e])},h.initializeComponent=function(e){e.css;var t=document.createElement("style");t.attributes.type="text/css",t.innerHTML=e.css,document.head.appendChild(t)},h.resetViewDefinedComponents=function(){for(var e=0;e<this.viewDefinedComponents.length;e++)this.removeComponent(this.viewDefinedComponents[e])},h.destroyExistingComponentsBySelector=function(e){for(var t=this.existingComponents.length-1;0<=t;t--)this.existingComponents[t].constructor&&this.existingComponents[t].constructor.selector===e&&(this.existingComponents[t].destroy(),this.existingComponents.splice(t,1))},h.removeComponent=function(e){this.destroyExistingComponentsBySelector(e);for(var t=0;t<this.components.length;t++)if(this.components[t].selector===e)return void this.components.splice(t,1)},h.addComponent=function(e){0<=this.components.indexOf(e)||(this.components.push(e),this.initializeComponent(e))},h.addViewDefinedComponent=function(e,n){for(var t=0;t<this.components.length;t++)if(this.components[t].selector===e){this.destroyExistingComponentsBySelector(e),this.components.splice(t,1);break}function i(e,t,i){this.element=t,this.remotePlayerView=e,this.position=null,this.content=n,this.componentContainer=i,this.draw()}this.viewDefinedComponents.push(e),((i.prototype=new s).constructor=i).selector=e,i.content=n,this.components.push(i),this.Webremote._currentView&&this.attachComponent(this.Webremote._currentView,document.body,i)},h.attach=function(e,t,i){(i=void 0===i?!0:i)&&(this.existingComponents.forEach(function(e){e.destroy()}.bind(this)),this.existingComponents=[]),this.attachComponents(e,t)},h.resize=function(){this.existingComponents.forEach(function(e){e.resize()}.bind(this))},h.update=function(){this.existingComponents.forEach(function(e){e.update()}.bind(this))},h.attachComponents=function(e,t){for(var i=0;i<this.components.length;i++)try{this.attachComponent(e,t,this.components[i])}catch(e){console.log(e)}},h.attachComponent=function(e,t,i){for(var n=(t instanceof HTMLElement?t:t[0]).querySelectorAll(i.selector),s=0;s<n.length;s++){var o=new i(e,n[s],this);this.existingComponents.push(o)}},e}),!function(){var e,t;e=this,t=function(){var a,l,c,i,e,n=!1,t=window.navigator.userAgent,h=/([+-]?[0-9.]+)(vh|vw|vmin|vmax)/g,s=/(https?:)?\/\//,u=[].forEach,d=/MSIE [0-9]\./i.test(t),f=/MSIE [0-8]\./i.test(t),m=-1<t.indexOf("Opera Mini"),p=/(iPhone|iPod|iPad).+AppleWebKit/i.test(t)&&(e=t.match(/OS (\d)/))&&1<e.length&&parseInt(e[1])<10,g=-1<t.indexOf(" Android ")&&-1<t.indexOf("Version/")&&parseFloat((t.match("Android ([0-9.]+)")||[])[1])<=4.4,d=d||!!navigator.userAgent.match(/MSIE 10\.|Trident.*rv[ :]*1[01]\.| Edge\/1\d\./);try{new b("test")}catch(a){var b=function(e,t){var i;return t=t||{bubbles:!1,cancelable:!1,detail:void 0},(i=document.createEvent("CustomEvent")).initCustomEvent(e,t.bubbles,t.cancelable,t.detail),i};b.prototype=window.Event.prototype,window.CustomEvent=b}function v(){n&&(o(),setTimeout(function(){i.textContent=y(),i.parentNode.appendChild(i),window.dispatchEvent(new b("viewport-units-buggyfill-style"))},1))}function o(){return c=[],u.call(document.styleSheets,function(e){var t=(e=>{try{if(!e.cssRules)return}catch(e){if("SecurityError"!==e.name)throw e;return}for(var t=[],i=0;i<e.cssRules.length;i++){var n=e.cssRules[i];t.push(n)}return t})(e);!t||"patched-viewport"===e.ownerNode.id||"ignore"===e.ownerNode.getAttribute("data-viewport-units-buggyfill")||e.media&&e.media.mediaText&&window.matchMedia&&!window.matchMedia(e.media.mediaText).matches||u.call(t,r)}),c}function r(i){if(7===i.type){var e;try{e=i.cssText}catch(e){return}h.lastIndex=0,h.test(e)&&!s.test(e)&&(c.push([i,null,e]),a.hacks)&&a.hacks.findDeclarations(c,i,null,e)}else i.style?u.call(i.style,function(e){var t=i.style.getPropertyValue(e);i.style.getPropertyPriority(e)&&(t+=" !important"),h.lastIndex=0,h.test(t)&&(c.push([i,e,t]),a.hacks)&&a.hacks.findDeclarations(c,i,e,t)}):i.cssRules&&u.call(i.cssRules,function(e){r(e)})}function y(){var e=window.innerHeight,t=window.innerWidth;l={vh:e,vw:t,vmax:Math.max(t,e),vmin:Math.min(t,e)};var n,s,o=[],r=[];return c.forEach(function(e){var e=function(e,t,i){var n=[];i=i.replace(h,w),a.hacks&&(i=a.hacks.overwriteDeclaration(e,t,i)),t&&(n.push(e.selectorText),i=t+": "+i+";");for(var s=e.parentRule;s;)s.media?n.unshift("@media "+s.media.mediaText):s.conditionText&&n.unshift("@supports "+s.conditionText),s=s.parentRule;return{selector:n,content:i}}.apply(null,e),t=e.selector.length?e.selector.join(" {\n")+" {\n":"",i=new Array(e.selector.length+1).join("\n}");t&&t===n?(t&&!n&&(n=t,s=i),r.push(e.content)):(r.length&&(o.push(n+r.join("\n")+s),r.length=0),t?(n=t,s=i,r.push(e.content)):(o.push(e.content),s=n=null))}),r.length&&o.push(n+r.join("\n")+s),m&&o.push("* { content: normal !important; }"),o.join("\n\n")}function w(e,t,i){i=l[i];return parseFloat(t)/100*i+"px"}function C(e){return e.slice(0,e.indexOf("/",e.indexOf("://")+3))}return{version:"0.6.1",findProperties:o,getCss:y,init:function(e){if(!n){if((a=(e=!0===e?{force:!0}:e)||{}).isMobileSafari=p,a.isBadStockAndroid=g,!a.ignoreVmax||a.force||f||(d=!1),f||!a.force&&!p&&!d&&!g&&!m&&(!a.hacks||!a.hacks.required(a)))return window.console&&f&&console.info("viewport-units-buggyfill requires a proper CSSOM and basic viewport unit support, which are not available in IE8 and below"),{init:function(){}};var t,o,r;window.dispatchEvent(new b("viewport-units-buggyfill-init")),a.hacks&&a.hacks.initialize(a),n=!0,(i=document.createElement("style")).id="patched-viewport",document[a.appendToBody?"body":"head"].appendChild(i),t=function(){function e(){var e=this,t=arguments;clearTimeout(s),s=setTimeout(function(){i.apply(e,t)},n)}var i,n,s;i=v,n=a.refreshDebounceWait||100;window.addEventListener("orientationchange",e,!0),window.addEventListener("pageshow",e,!0),(a.force||d||(()=>{try{return window.self!==window.top}catch(e){return 1}})())&&(window.addEventListener("resize",e,!0),a._listeningToResize=!0),a.hacks&&a.hacks.initializeEvents(a,v,e),v()},o=0,r=function(){--o||t()},u.call(document.styleSheets,function(e){if(e.href&&C(e.href)!==C(location.href)&&"ignore"!==e.ownerNode.getAttribute("data-viewport-units-buggyfill")){o++;var t=e.ownerNode,i=r,e=t.href,n=i,s=new XMLHttpRequest;if("withCredentials"in s)s.open("GET",e,!0);else{if("undefined"==typeof XDomainRequest)throw new Error("cross-domain XHR not supported");(s=new XDomainRequest).open("GET",e)}s.onload=function(){var e=document.createElement("style");e.media=t.media,e.setAttribute("data-href",t.href),e.textContent=this.responseText,t.parentNode.replaceChild(e,t),i()},s.onerror=n,s.send()}}),o||t()}},refresh:v}},"function"==typeof define&&define.amd?define("viewport-units-buggyfill",[],t):"object"==typeof exports?module.exports=t():e.viewportUnitsBuggyfill=t()}(),!function(){var e,t;e=this,t=function(){var r=/calc\(/g,a=/["']/g,e=window.navigator.userAgent,n=(n=/MSIE [0-9]\./i.test(e))||!!navigator.userAgent.match(/MSIE 10\.|Trident.*rv[ :]*1[01]\.| Edge\/1\d\./);return{required:function(e){return e.isMobileSafari||n},initialize:function(){},initializeEvents:function(e,t,i){e.force||n&&!e._listeningToResize&&(window.addEventListener("resize",i,!0),e._listeningToResize=!0)},findDeclarations:function(e,t,i,n){var s,o;null!==i&&(s=e,o=t,e=n,"content"===i)&&-1<e.indexOf("viewport-units-buggyfill")&&e.replace(a,"").split(";").forEach(function(e){var t,e=e.split(":");2===e.length&&"viewport-units-buggyfill"!==(t=e[0].trim())&&(e=e[1].trim(),s.push([o,t,e]),r.test(e))&&(e=e.replace(r,"-webkit-calc("),s.push([o,t,e]))})},overwriteDeclaration:function(e,t,i){return i=n&&"filter"===t?i.replace(/px/g,""):i}}},"function"==typeof define&&define.amd?define("viewport-units-buggyfill.hacks",[],t):"object"==typeof exports?module.exports=t():e.viewportUnitsBuggyfillHacks=t()}(),define("CatLab/Webremote/Controllers/Webremote",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Tracker","CatLab/Webremote/Tools/Cookies","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Preloader","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Views/Popups/AuthenticationPopup","CatLab/Webremote/Views/Popups/SelectSmileyPopup","CatLab/Webremote/Views/Blocks/CurrentUser","CatLab/Webremote/Views/Blocks/CurrentSmiley","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Tools/Storage","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/HashParser","CatLab/Webremote/Tools/Screenfull","CatLab/Webremote/Views/Alert","CatLab/Webremote/Views/Welcome","CatLab/Webremote/Views/ConnectionTrouble","CatLab/Webremote/Views/GamePaused","CatLab/Webremote/Synchronization/ClientRemoteView","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler","CatLab/Webremote/Synchronization/CombinedEventHandler","CatLab/Webremote/Providers/SocketIO","CatLab/Webremote/SonicSync/Client","CatLab/Webremote/Components/Components","viewport-units-buggyfill","viewport-units-buggyfill.hacks"],function(Config,Tracker,Cookies,Tools,Deferred,Smileys,Preloader,OAuth2,AuthenticationPopup,SelectSmileyPopup,CurrentUser,CurrentSmiley,UsersCollection,Storage,i18n,HashParser,screenfull,AlertPopup,WelcomePopup,ConnectionTroubleView,GamePausedView,ClientRemoteView,DataSynchronizer,EventHandler,CombinedEventHandler,SocketIOProvider,SonicSyncClient,Components,ViewportUnitsBuggyFill,ViewportUnitsBuggyFillHacks){var domelement=null,user,dynamicStylesheet,triggers=[];function addEvent(e,t,i){e.addEventListener?e.addEventListener(t,i,!1):e.attachEvent?e.attachEvent("on"+t,i):e["on"+t]=i}var Webremote=function(){};function getParameterByName(e,t){t=t||window.location.href,e=e.replace(/[\[\]]/g,"\\$&");e=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)").exec(t);return e?e[2]?decodeURIComponent(e[2].replace(/\+/g," ")):"":null}return Webremote.prototype={provider:null,element:null,gamedata:null,stylesheets:[],links:[],scripts:[],views:{},userData:null,userEvents:null,groupData:null,groupEvents:null,smiley:null,isOauth2Set:!1,color:null,_currentSmileyViews:[],_currentViewId:null,_currentViewViewId:null,_currentViewGroupId:null,_currentView:null,_connectingDfd:null,_connectedToken:null,_headless:!1,_allowAuthentication:!0,token:null,tokenAction:null,confirmTokenConnect:!1,disableConnectConfirmation:!1,initialize:function(e,t){void 0!==(t=void 0===t?{}:t).disableConnectConfirmation&&(this.disableConnectConfirmation=!!t.disableConnectConfirmation),void 0!==t.token?this.token=t.token:(this.token=getParameterByName("token"),this.token||(this.token=getParameterByName("t")),this.token&&!this.disableConnectConfirmation&&(this.confirmTokenConnect=!0),this.tokenAction=getParameterByName("a")),this.setContainer(e),this.showLoading(),this.sonicSync=null,this.components=new Components(this),this.components.initialize(),this._initialize(t).then(function(){setTimeout(function(){void 0===this.provider.showTokenForm||this.provider.showTokenForm?this.confirmTokenConnect?this.showConfirmTokenConnect().then(function(){this.trigger("remote:initialized"),this.handleTokenInput(this.token)}.bind(this)):(this.showTokenForm(),this.trigger("remote:initialized")):this.provider.noTokenConnect()}.bind(this),2),ViewportUnitsBuggyFill.init({hacks:ViewportUnitsBuggyFillHacks})}.bind(this)),this.setPlayerColor("#000000"),this.setOrientation(),addEvent(window,"resize",this.setOrientation.bind(this))},headless:function(e){return(e=void 0===e?{}:e).headless=!0,this._initialize(e)},_initialize:function(t){var i=new Deferred;return Config.set(t),Config.initialize(function(){Tracker.track("App","Initialize"),void 0===t.provider&&(t.provider=new SocketIOProvider),void 0!==t.headless&&(this._headless=!!t.headless),this.provider=t.provider,this.smileys=new Smileys(this.provider),this.provider.initPlayer(this),this.provider.on("disconnect",function(e){var t=this.getConnectionIssuesView();console.log("Connection lost... reconnecting"),t.show(),t.text(i18n.t("Connection lost... reconnecting"))}.bind(this)),this.provider.on("reconnect",function(e){this.provider.emit("user:reconnect",{id:this.gamedata.id,accessToken:this.gamedata.accessToken}),this.getConnectionIssuesView().hide()}.bind(this)),this.provider.on("user:error",function(e){var t;this._connectingDfd&&(t=this._connectingDfd,this._connectingDfd=null,t.reject(e.message))}.bind(this)),this.provider.on("user:initialize",function(e){this.gamedata=e,this.provider.setUserId(e.id),this._storeGameData(e),this._connectingDfd&&(e=this._connectingDfd,this._connectingDfd=null,e.resolve())}.bind(this)),this.provider.on("view:load",function(e){this.loadViewsXML(e.xml)}.bind(this)),this.provider.on("view:reset",function(e){this.resetViews()}.bind(this)),this.provider.on("config:set",function(e){if(Config.set(e),this.sonicSync&&this.sonicSync.stop(),Config.useAudioSync())try{this.sonicSync=new SonicSyncClient(this),this.sonicSync.startListener()}catch(e){console.error(e)}}.bind(this)),this.provider.on("view:set",function(e){this.showView(e.id,e.viewId,e.group),this.handleCombinedMessages(e)}.bind(this)),this.provider.on("button:label",function(e){this.setLabel(e)}.bind(this)),this.provider.on("button:decorate",function(e){this.setClass(e)}.bind(this)),this.provider.on("oauth:set",function(e){Config.supportsAuthentication()&&(OAuth2.initialize(e),this.isOauth2Set=!0,UsersCollection.initialize(this,OAuth2),this.updateUser(),HashParser.getParameter("access_token"))&&(e=HashParser.getParameter("access_token"),UsersCollection.addFromAccessToken(e,function(e){e&&this.setUser(e)}.bind(this)),HashParser.clear())}.bind(this)),this.provider.on("color:set",function(e){this.setPlayerColor(e.color)}.bind(this)),this.provider.on("user:smiley",function(e){this.setSmiley(e.smiley)}.bind(this)),this.provider.on("smileys:taken",function(e){this.smileys.setTakenSmileys(e.smileys)}.bind(this)),this.provider.on("game:disconnect",function(e){AlertPopup(i18n.t("You have been disconnected from the game."),function(){window.location.reload()})}.bind(this)),this.provider.on("dom:append",function(e){this.domAppend(e)}.bind(this)),this.provider.on("dom:replace",function(e){this.domReplace(e)}.bind(this)),this.provider.on("dom:attribute",function(e){this.domAttribute(e)}.bind(this)),this.provider.on("dom:alert",function(e){AlertPopup(e.message)}),this.provider.on("dom:open",function(e){void 0!==e.url&&window.open(e.url)}),this.provider.on("value:change",function(e){this.changeValue(e)}.bind(this)),this.provider.on("device:vibrate",function(e){this.vibrate(e)}.bind(this)),this.provider.on("game:pause",function(e){this.pause(e)}.bind(this)),this.provider.on("game:unpause",function(e){this.unpause(e)}.bind(this)),this.preloader=new Preloader(this.provider),this.userData=new DataSynchronizer("user",this.emit.bind(this),"client"),this.groupData=new DataSynchronizer("group",this.emit.bind(this),"client"),this.userEvents=new EventHandler("user",this.emit.bind(this)),this.groupEvents=new EventHandler("group",this.emit.bind(this));var e=[this.userData,this.groupData],n=[this.userEvents,this.groupEvents];DataSynchronizer.eventsToListenFor.forEach(function(i){this.provider.on(i,function(t){e.forEach(function(e){e.checkNamespace(t)&&e.processMessage(i,t)})}.bind(this))}.bind(this)),EventHandler.eventsToListenFor.forEach(function(i){this.provider.on(i,function(t){n.forEach(function(e){e.checkNamespace(t)&&e.processMessage(i,t)})}.bind(this))}.bind(this)),this.events=new CombinedEventHandler,this.events.addHandler(this.userEvents),this.events.addHandler(this.groupEvents),i.resolve()}.bind(this)),i.promise()},reconnect:function(e){this.gamedata?(this.provider.emit("user:reconnect",{id:this.gamedata.id,accessToken:this.gamedata.accessToken}),this.provider.once("user:reconnect",function(){e()})):e()},connectProvider:function(e){return this.provider.tokenConnect(e)},_storeGameData:function(){var e=new Deferred,t=this._connectedToken;return Storage.set("gamestate_"+t,this.gamedata,function(){e.resolve()},864e5),e.promise()},_restoreGameData:function(){var t=new Deferred,e=this._connectedToken;return Storage.get("gamestate_"+e,function(e){e?(this.gamedata=e,t.resolve(!0)):t.resolve(!1)}.bind(this)),t.promise()},handleCombinedMessages:function(e){for(var t=[{name:"button:label",method:this.setLabel.bind(this)},{name:"button:decorate",method:this.setClass.bind(this)}],i=0;i<t.length;i++){var n=t[i].name,s=t[i].method;if(void 0!==e[n])for(var o=0;o<e[n].length;o++)s(e[n][o])}},emit:function(e,t){this.provider.toMaster(e,t)},getConnectionIssuesView:function(){return void 0===this.connectionTrouble&&(this.connectionTrouble=new ConnectionTroubleView),this.connectionTrouble},setGamePausedView:function(e){this.gamePaused=e},getGamePausedView:function(){return void 0===this.gamePaused?new GamePausedView:this.gamePaused},setContainer:function(e){domelement=e,this.element=e,dynamicStylesheet=document.createElement("style"),document.body.appendChild(dynamicStylesheet),document.body.className="catlab-remote"},on:function(e,t){void 0===triggers[e]&&(triggers[e]=[]),triggers[e].push(t)},trigger:function(e){var t=[].slice.apply(arguments);if(t.shift(),void 0!==triggers[e])for(var i=0;i<triggers[e].length;i++)triggers[e][i].apply(this,t)},loadViews:function(e,t){var i;t=t||function(){},this._headless?t():((i=new XMLHttpRequest).open("GET",Config.getProxy()+e,!0),i.onreadystatechange=function(){4==i.readyState&&200==i.status&&(this.loadViewsXML(i.responseText),t())}.bind(this),i.send())},resetViews:function(){this.showViewLoadingOverlay(),this.views={},this.components.resetViewDefinedComponents();for(var e=0;e<this.stylesheets.length;e++)try{var t=this.stylesheets[e];t.parentNode&&t.parentNode.removeChild(t)}catch(e){console.error(e)}for(e=0;e<this.links.length;e++)try{var i=this.links[e];i.parentNode&&i.parentNode.removeChild(i)}catch(e){console.error(e)}this.stylesheets=[]},injectXmlns:function(e){return e.replace(/<views(\s[^>]*)?>/,function(e){return/\bxmlns\s*=/.test(e)?e:e.replace("<views",'<views xmlns="http://www.w3.org/1999/xhtml"')})},loadViewsXML:function(e,t){if(t=t||function(){},!this._headless){var i;if(Tracker.track("App","Load Views"),e=this.injectXmlns(e),window.DOMParser?i=(new DOMParser).parseFromString(e,"text/xml"):((i=new ActiveXObject("Microsoft.XMLDOM")).async=!1,i.loadXML(e)),0===i.getElementsByTagName("views").length)return!1;for(var n=i.getElementsByTagName("views").item(0).getElementsByTagName("component"),s=0;s<n.length;s++)this.loadComponent(n.item(s));for(var o=i.getElementsByTagName("views").item(0).getElementsByTagName("view"),s=0;s<o.length;s++)this.loadView(o.item(s));var r=i.getElementsByTagName("views").item(0).getElementsByTagName("stylesheet");for(s=0;s<r.length;s++){var a=r.item(s),l=document.createElement("style");this.stylesheets.push(l),l.innerHTML=a.textContent,document.body.appendChild(l)}var c=i.getElementsByTagName("views").item(0).getElementsByTagName("link");for(s=0;s<c.length;s++){var h=c.item(s).getAttribute("href"),u=document.createElement("link");u.rel="stylesheet",u.type="text/css",u.media="all",u.href=h,this.links.push(u),document.getElementsByTagName("head")[0].appendChild(u)}for(r=i.getElementsByTagName("views").item(0).getElementsByTagName("style"),s=0;s<r.length;s++)this.stylesheets.push(r.item(s)),document.body.appendChild(r.item(s));var d=i.getElementsByTagName("views").item(0).getElementsByTagName("script");for(s=0;s<d.length;s++)this.scripts.push(d.item(s)),this.evalScript(d.item(s));return ViewportUnitsBuggyFill.refresh(),t(),!0}t()},evalScript:function(xml){var aWebremote=Webremote;!function(){try{var Webremote=aWebremote;eval(xml.textContent)}catch(e){console.error(e)}}.bind(window)()},loadView:function(e){var t=e.getAttribute("id"),i=document.createElement("div"),n=!1;e.getAttribute("iframe")&&"false"!==e.getAttribute("iframe").toLowerCase()&&(n=!0);for(var s=0;s<e.childNodes.length;s++)i.appendChild(e.childNodes[s].cloneNode(!0));i.id=t,i.className="view "+e.className,this.views[t]={iframe:n,html:(new XMLSerializer).serializeToString(i)},this._currentViewId===t&&this.showView(this._currentViewId,this._currentViewViewId,this._currentViewGroupId)},loadComponent:function(e){for(var t=e.getAttribute("id"),i=document.createElement("div"),n=0;n<e.childNodes.length;n++)i.appendChild(e.childNodes[n].cloneNode(!0));this.components.addViewDefinedComponent(t,i)},showView:function(e,t,i){var n,s;this._headless||(this._currentView&&this._currentView.destroy(),"remote:authenticate"!==e?(this._currentViewId=e,this._currentViewViewId=t,this._currentViewGroupId=i,void 0!==this.views[e]?(n=(i?this.groupData:this.userData).getFromIdentifier("view:"+t),s=this.views[e],this._currentView=new ClientRemoteView(this,t,e,i,n,s.iframe),this._currentView.html=s.html,this._currentView.render(this.element),this.hideViewLoadingOverlay(),this.updateUser(),Tracker.track("App","Show View",e),this.trigger("remote:view:show",{id:e,view:this._currentView}),this.trigger("view:set",this._currentView)):this.element.innerHTML='<div class="loading"><p>Please wait, loading...</p><p>(Loading view: '+e+")</div></p>"):this.showAuthenticationView())},updateUser:function(){Tracker.track("App","Set user");var e=document.getElementById("authentication");e&&new CurrentUser(this).render(e),this._currentSmileyViews=[],Config.useSmileys()?(this.setSmileySelectViews(),this.setSmileyViews()):this.removeSmileyViews()},setSmileySelectViews:function(){for(var e=document.getElementsByTagName("smiley-select"),t=0;t<e.length;t++){var i=!e[t].hasAttribute("flingable")||"false"!==e[t].getAttribute("flingable"),i=new CurrentSmiley(this,!0,i);i.render(e[t]),this.smiley&&i.setSmiley(this.smiley),this._currentSmileyViews.push(i)}},setSmileyViews:function(){for(var e=document.getElementsByTagName("smiley"),t=0;t<e.length;t++){var i=e[t].hasAttribute("changeable")&&"false"!==e[t].getAttribute("changeable"),n=e[t].hasAttribute("flingable")&&"false"!==e[t].getAttribute("flingable"),i=new CurrentSmiley(this,i,n);i.render(e[t]),this.smiley&&i.setSmiley(this.smiley),this._currentSmileyViews.push(i)}},removeSmileyViews:function(){for(var e=document.getElementsByTagName("smiley-select"),t=0;t<e.length;t++)e[t].parentNode.removeChild(e[t]);for(e=document.getElementsByTagName("smiley"),t=0;t<e.length;t++)e[t].parentNode.removeChild(e[t]);for(var i=document.getElementsByClassName("if-config-smileys"),t=0;t<i.length;t++)i[t].parentNode.removeChild(i[t])},popup:function(e){new WelcomePopup(e).render(domelement)},showAuthenticationPopup:function(e){e=e||!1;var t=new AuthenticationPopup(this);t.render(domelement),e&&t.connect()},showSmileyPopup:function(e,t){void 0===e&&(e=function(e){this.selectSmiley(e)}.bind(this)),void 0===t&&(t=!0);for(var i=domelement.querySelectorAll(".catlab-popup-container"),n=0;n<i.length;n++)i[n].parentNode.removeChild(i[n]);new SelectSmileyPopup(this,e,t).render(domelement)},showAuthenticationView:function(){Cookies.removeItem("last_token"),this.element&&(this.element.innerHTML='<p id="catlab-message">'+i18n.t("Please login.")+"</p>",OAuth2.link({fullscreen:!0}).then(function(e){e?(this.setUser(e),this.element.innerHTML='<p id="catlab-message">'+i18n.t("Welcome! You may now close this screen.")+"</p>",this.provider.disconnect(!1),window.close()):this.showAuthenticationView()}.bind(this)))},buttonDown:function(e,t){this.provider.toMaster("button:down",{id:e})},buttonUp:function(e,t,i){this.provider.toMaster("button:up",{id:e,click:i=void 0!==i&&i}),this.trigger("user:interaction")},syncValue:function(e,t,i){return this.provider.toMaster("value:change",{id:e,value:t,viewId:i}),!1},showLoading:function(){this.element&&(this.element.innerHTML='<p id="catlab-loading">Connecting...</p>')},showViewLoadingOverlay:function(){var e;this._headless||(this.hideViewLoadingOverlay(),(e=document.createElement("div")).id="catlab-view-loading-overlay",e.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;background:#000;display:flex;align-items:center;justify-content:center;z-index:99999;color:#fff;font-family:Arial,Helvetica,sans-serif;font-size:1.5em;",e.innerHTML="<p>Loading...</p>",document.body.appendChild(e))},hideViewLoadingOverlay:function(){var e=document.getElementById("catlab-view-loading-overlay");e&&e.parentNode&&e.parentNode.removeChild(e)},showConfirmTokenConnect:function(){var i=new Deferred,e=document.createElement("form"),t=(this.element.innerHTML="",this.element.appendChild(e),document.createElement("div")),n=(t.id="catlab-token-form",e.appendChild(t),document.createElement("h1")),n=(n.innerHTML=i18n.t("Welcome!"),t.appendChild(n),document.createElement("button"));return"l"===this.tokenAction?n.innerHTML=i18n.t("Login"):n.innerHTML=i18n.t("Join game"),n.type="submit",n.className="pulsating",t.appendChild(n),e.onsubmit=function(e){e.preventDefault();try{var t=(t=window.location.search.replace(/[?&]t=([^&]*)/gi,"")).replace(/[?&]token=([^&]*)/gi,"");window.history.pushState({},document.title,window.location.pathname+t+window.location.hash)}catch(e){}i.resolve()},i.promise()},showTokenForm:function(){var e=document.createElement("form"),t="undefined"!=typeof CONFIG_TOKEN?CONFIG_TOKEN:null,i=(!t&&this.token&&(t=this.token,this.token=null),!1),n=(t&&(i=!0),Cookies.getItem("last_token")),n=(!t&&n&&(t=n),document.createElement("div")),s=(n.id="catlab-token-form",e.innerHTML="",e.appendChild(n),document.createElement("input")),s=(s.type="tel",s.pattern="[0-9 ]{6,10}",s.name="token",s.id="token",s.value=t||"",s.placeholder=i18n.t("Enter code"),s.addEventListener("click",function(){this.setSelectionRange(0,this.value.length)}),n.appendChild(s),document.createElement("button"));s.innerHTML=i18n.t("Connect"),n.appendChild(s),i&&this.handleTokenInput(t),e.onsubmit=function(e){e.preventDefault();e=document.getElementById("token").value;if(e)return this.handleTokenInput(e),!1}.bind(this),this.element.innerHTML="",this.element.appendChild(e)},handleTokenInput:function(e){var t=this.connect(e);e!==Cookies.getItem("last_token")&&Cookies.removeItem("last_token"),t.then(function(){Cookies.setItem("last_token",e,.25)}.bind(this)),t.fail(function(e){this.showTokenForm(),screenfull.enabled&&screenfull.isFullscreen&&screenfull.exit(),AlertPopup(e)}.bind(this)),this.showLoading(),this.trigger("remote:token:submit"),this.trigger("user:interaction")},requestFullScreen:function(){screenfull.enabled&&!screenfull.isFullscreen&&screenfull.request()},connect:function(e){return e=e.replace(" ",""),null!==this._connectingDfd&&(this._connectingDfd.reject(),this._connectingDfd=null),this._connectingDfd=new Deferred,this._connectedToken=e,this._connectingDfd.fail(function(){this.provider.disconnect(!1)}.bind(this)),this.connectProvider(e).fail(function(){setTimeout(function(){this._connectingDfd.reject(i18n.t("Game not found. Please check your token."))}.bind(this),1)}.bind(this)).then(function(t){var i=!0;"0"===getParameterByName("reconnect")&&(i=!1),this._restoreGameData().then(function(e){e&&i?this.reconnect(function(){this._connectingDfd.resolve()}.bind(this)):this.provider.emit("user:join",{token:t})}.bind(this))}.bind(this)),this._connectingDfd.promise()},setLabel:function(e){this._currentView&&this._currentView.setLabel(e.id,Tools.nl2br(Tools.sanitize(e.label)))},setClass:function(e){this._currentView&&this._currentView.setClass(e.id,e.styles)},setPlayerColor:function(e){if(this.color=e,void 0!==dynamicStylesheet&&dynamicStylesheet){var t,i,n="",s=(dynamicStylesheet.innerHTML=(n+=".player-color-border { border-color:"+e+"; }")+(".player-color-background { background-color: "+e+"; }")+(".player-color { color: "+e+"; }"),{"theme-color":e,"msapplication-navbutton-color":e,"apple-mobile-web-app-status-bar-style":e});for(t in s)s.hasOwnProperty(t)&&((i=document.createElement("meta")).httpEquiv=t,i.content=s[t],document.getElementsByTagName("head")[0].appendChild(i))}},setSmiley:function(t){this.smiley=t,this._currentSmileyViews.forEach(function(e){e.setSmiley(t)})},getSmiley:function(){return this.smiley},selectSmiley:function(e){this.provider.toMaster("user:smiley",{smiley:e})},setUser:function(e){user=e,this.updateUser(),user?(this.provider.toMaster("user:login",{access_token:user.getAccessToken()}),Storage.set("currentuser",user.getAccessToken()),this.getSmiley()&&(e=user.getAvatarSmiley())&&this.selectSmiley(e)):(this.provider.toMaster("user:logout"),Storage.set("currentuser",null))},getUser:function(){return user},listViews:function(){var e,t=[];for(e in this.views)this.views.hasOwnProperty(e)&&t.push({name:e});return t},getRandomText:function(e,t){var i="abcdefghijklmnopqrstuvwyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";void 0===t&&(t=40);for(var n="",s=(e=void 0===e?10:e)+Math.random()*t,o=0;o<s;o++)n+=i.charAt(Math.floor(Math.random()*i.length)),.8<Math.random()&&(o++,n+=" ");return n},randomLabels:function(e,t){for(var i=domelement.querySelectorAll("[data-button-label]"),n=0;n<i.length;n++)i[n].innerHTML=this.getRandomText(e,t);this.update()},setOrientation:function(){if(window.innerHeight>=window.innerWidth)try{document.body.classList.remove("landscape"),document.body.classList.add("portrait")}catch(e){document.body.className="portrait"}else try{document.body.classList.add("landscape"),document.body.classList.remove("portrait")}catch(e){document.body.className="landscape"}this.components.resize()},domAppend:function(e){this._currentView&&(this._currentView.domAppend(e.id,e.html),this.components.update())},domReplace:function(e){this._currentView&&(this._currentView.domReplace(e.id,e.html),this.components.update())},domAttribute:function(e){this._currentView&&(this._currentView.domAttribute(e.id,e.name,e.value),this.components.update())},changeValue:function(e){this._currentView&&this._currentView.changeValue(e)},vibrate:function(e){this._currentView&&this._currentView.vibrate(e)},pause:function(e){void 0===this._gamePausedView&&(this._gamePausedView=this.getGamePausedView()),this._gamePausedView.show()},unpause:function(e){void 0!==this._gamePausedView&&this._gamePausedView.hide()},log:function(e){Config.debug()&&console.log(e)},canAuthenticate:function(){return this.isOauth2Set},getGroupIds:function(){return void 0===this.gamedata.groups?[]:this.gamedata.groups},resolveDataAttribute:function(e){if("token"===e)return this._connectedToken;var i,e=(e="data."===e.substring(0,5)?e.substring(5):e).split("."),t=(2!==e.length&&e.unshift("any"),e.shift()),e=e.shift();if(t===user)return this.userData.getFromIdentifier("user").get(e);if("group"===t.substring(0,5)){var n,s=this.getGroupIds();if(0===s.length)return null;if("group"===t)return this.groupData.getFromIdentifier("group:"+s[0]).get(e);if("]"===t.substring(t.length,1))return void 0===s[n=t.substr(t.substring(6,t.length-1))]?null:this.groupData.getFromIdentifier("group:"+s[n]).get(e)}return"any"===t&&(i=["user."+e],this.getGroupIds().forEach(function(e,t){i.push("group["+t+"]")}.bind(this))),null}},Webremote}),define("CatLab/Webremote/Tools/Colorwheel",[],function(){var e={index:0,colors:[{color:"#d84a38",name:"red"},{color:"#4d90fe",name:"blue"},{color:"#35aa47",name:"green"},{color:"#ffb848",name:"yellow"},{color:"#852b99",name:"purple"},{color:"#555555",name:"brown"},{color:"#F87217",name:"orange"},{color:"#FBBBB9",name:"pink"}],initialize:function(){this.index=Math.floor(Math.random()*this.colors.length)},next:function(){var e=this.colors[this.index%this.colors.length];return this.index++,e}};return e.initialize(),e}),define("CatLab/Webremote/Collections/Users",["CatLab/Webremote/Tools/Colorwheel"],function(i){return function(){this.users=[],this.userMap={},this.add=function(e){var t;e.isColorSet()||(t=i.next(),e.setColor(t.color,t.name)),e.hasPlayerId()||e.setPlayerId(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(i){var n=[];return this.each(function(e){for(var t=0;t<i.length;t++)if(i[t].getId()===e.getId())return void n.push(i[t])}),n}}}),define("CatLab/Webremote/Collections/Groups",["CatLab/Webremote/Tools/Colorwheel"],function(i){return function(){var t;this.groups=[],this.groupMap={},this.add=function(e){var t;e.colorSet||(t=i.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 i=!1;return t.groupIds.forEach(function(e){e=this.getFromId(e);e&&(i=!0,e.addUser(t),e.isShareColor())&&t.setColor(e.getColor(),e.getColorName())}.bind(this)),i},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,s){function t(){}e=t.prototype=new e;return e.initializeControlBase=function(){this.initializeEventable()},e.resetViews=function(e){var t=new s;return this.emit("view:reset",{},function(){void 0!==e&&e(),t.resolve()}),t.promise()},e.replaceViews=function(e,t,i){var n=new s;return this.resetViews(function(){this.loadViews(e,t,function(){void 0!==i&&i(),n.resolve()})}.bind(this)),n.promise()},e.loadViews=function(e,t,i){return this.Webcontrol.provider.loadViews(e,i,this).then(function(){void 0!==t&&t()})},e.parseViews=function(e,t,i){return this.Webcontrol.provider.parseViews(e,t,this).then(function(){void 0!==i&&i()})},e.registerComponent=function(e,t){return this.Webcontrol.provider.registerComponent(e,t,this)},t}),define("CatLab/Webremote/Models/Control",[],function(){return function(i,n,e){var s,o,r,a,l=0,c={},h=i,u=[];this.id=i,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 '+o+'">'+h+"</span>":h},this.setStaticLabel=function(e,t,i,n){return h=e,o=t,r=i,a=n,this},this.getLabelImage=function(){return r},this.getLabelEmoji=function(){return a},this.getLabelData=function(){return{label:h,type:o,image:r,emoji:a}},this.setLabel=function(e,t){return this.label=e,n.emit("button:label",{id:i,label:e}),this},this.decorate=function(e){return this.decoration=e,n.emit("button:decorate",{id:i,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"),s=0;s<c[e].length;s++)t.push(c[e][s]);for(s=0;s<t.length;s++)t[s](n);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(s=0;s<c[e].length;s++)c[e][s]===t&&(c[e].splice(s,1),s--);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,i=[];return i.push(e.addEventListener("click",function(){t.trigger("click")})),u.push({element:e,listeners:i}),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:i,styles:this.decoration}),this.label&&e.emit("button:label",{id:i,label:this.label})},this.log=function(e){n.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,i=0;this.remoteView.targets.forEach(function(e){(t=e.scale())>i&&(i=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,i){return this.remoteView.targets.forEach(function(e){e.control(this.id).on(t,i)}.bind(this)),this},t.off=function(e){var t=arguments;return this.remoteView.targets.forEach(function(e){e.control(this.id).off.apply(e.control(this.id),t)}.bind(this)),this},t.refreshTarget=function(t){return this.remoteView.targets.forEach(function(e){e.control(this.id).refreshTarget(t)}.bind(this)),this},e}),define("CatLab/Webremote/Synchronization/RemoteView",["CatLab/Webremote/Models/Control","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Synchronization/MultipleTargetControl","CatLab/Webremote/Synchronization/DataSynchronizer"],function(e,t,i,n){function s(e,t,i,n,s){this.initializeEventable(),this.id=t,this.viewId=e,this.targets=[],this.Webcontrol=n,this.groupId=void 0!==s?s:null,this.controls={},this.valueMap={},this.newUserStack=[],this.factory=null,this.listeners=[],i.map(function(e){this.addTarget(e)}.bind(this))}t=s.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,i={id:this.id,viewId:this.viewId};for(this.tmpid in this.groupId&&(i.group=this.groupId),t.emit("view:set",i),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,i){this.targets.map(function(e){e.emit(t,i)})},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 i(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,i,e){this._clearStack(function(e){return"dom:attribute"===e.action&&e.data.id===t&&e.data.name===i}),this._stackAndEmit("dom:attribute",{id:t,name:i,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,i){this.listeners.push(e.on(t,i))},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)},s}),define("CatLab/Webremote/Synchronization/RemoteViewFactory",["CatLab/Webremote/Synchronization/RemoteView"],function(s){function e(){this.viewCounter=0,this.views={}}var t=e.prototype;return t.create=function(e,t,i,n){return this.viewCounter++,this.views[this.viewCounter]=new s(this.viewCounter,e,t,i,n),(this.views[this.viewCounter].factory=this).views[this.viewCounter]},t.createDummy=function(e,t){return this.create(e,[],t)},t.getFromId=function(e){return this.views[e]},t.destroy=function(e){e=e.id;delete this.views[e]},new e}),define("CatLab/Webremote/Models/Users/ControlUser",["CatLab/Webremote/Models/ControlBase","CatLab/Webremote/Models/User","CatLab/Webremote/Models/Control","CatLab/Webremote/Synchronization/RemoteViewFactory","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler"],function(e,t,i,n,s,o,r,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 i(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 r("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,i){0<=r.eventsToListenFor.indexOf(t)?(this.dataSynchronizer.checkNamespace(i)&&this.dataSynchronizer.processMessage(t,i),this.getGroups().forEach(function(e){e.dataSynchronizer.checkNamespace(i)&&e.dataSynchronizer.processMessage(t,i)}.bind(this))):0<=a.eventsToListenFor.indexOf(t)?(this.events.checkNamespace(i)&&this.events.processMessage(t,i),this.getGroups().forEach(function(e){e.events.checkNamespace(i)&&e.events.processMessage(t,i)}.bind(this))):"button:down"===t?this.control(i.id).update(1):"button:up"===t?this.control(i.id).update(0,i.click):"user:login"===t?this.login(i):"user:logout"===t?this.logout(i):"user:smiley"===t?this.setSmiley(i.smiley):"sync:audio"===t&&this.eventableTrigger("sync:audio",i)},e.setSmiley=function(t){this.smiley=t;var i=null;this.getGroups().forEach(function(e){i=!0,e.setSmiley(t,this)}.bind(this)),i||this.Webcontrol.smileys.reserve(t,this.getIdentifier())?this.emit("user:smiley",{smiley:t}):this.emit("dom:alert",{message:s.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,i){return this.Webcontrol.provider.toPlayer(this,e,t,i),!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,i){var n=this;this.Webcontrol.getOAuthClient(function(e){e&&(this.setAccessToken(t.access_token),e.profile(n.access_token,function(e){n.authenticated=!0,this.setProfiledata(e.user),void 0!==i&&i()}.bind(this)))}.bind(this))},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=n.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,n,t){var s,i,o,r,a,l,c=e,h={};this.label=null,this.decoration="",this.group=n,this.isGlobal=t,this.pushed=function(){for(o=n.getUsers(),s=0;s<o.length;s++)if(o[s].control(c,this.isGlobal).pushed())return!0;return!1},this.scale=function(){for(o=n.getUsers(),s=r=0;s<o.length;s++)(a=o[s].control(c,this.isGlobal)).value>r&&(r=a.value);return r},this.getLabel=function(e){return o=n.getUsers(),(s=0)<o.length?(a=o[s].control(c,this.isGlobal)).getLabel(e):null},this.getLabelImage=function(){return o=n.getUsers(),(s=0)<o.length?(a=o[s].control(c,this.isGlobal)).getLabelImage():null},this.setStaticLabel=function(e,t,i){for(o=n.getUsers(),s=0;s<o.length;s++)o[s].control(c).setStaticLabel(e,t,i);return null},this.setLabel=function(e,t){return this.label=e,n.emit("button:label",{id:c,label:e}),this},this.decorate=function(e){return this.decoration=e,n.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),o=n.getUsers(),s=0;s<o.length;s++)o[s].control(c,this.isGlobal).on(e,t);return this},this.hasTriggers=function(e){for(o=n.getUsers(),s=0;s<o.length;s++)if(o[s].control(c,this.isGlobal).hasTriggers(e))return!0;return!1},this.off=function(e){for(delete h[e],o=n.getUsers(),s=0;s<o.length;s++)o[s].control(c,this.isGlobal).off(e);return this},this.clearEvents=function(){for(h={},o=n.getUsers(),s=0;s<o.length;s++)o[s].control(c,this.isGlobal).clearEvents();return this},this.clear=function(){for(h={},this.decoration=null,this.label=null,o=n.getUsers(),s=0;s<o.length;s++)o[s].control(c,this.isGlobal).clear();return this},this.isLocalAuthentication=function(){return!1},this.refreshControl=function(){for(o=n.getUsers(),s=0;s<o.length;s++){for(l in o[s].control(c,this.isGlobal).clearEvents(),h)if(h.hasOwnProperty(l))for(i=0;i<h[l].length;i++)o[s].control(c,this.isGlobal).on(l,h[l][i]);this.label&&o[s].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){n.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,i,n,s,o,r,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()},t.clearEvents=function(){this.clearControls(),this.clearEventableEvents()},t.isMainGroup=function(){return this.Webcontrol.getConnectToken()===this.getConnectToken()},t.emit=function(e,t,i){return this.Webcontrol.provider.toGroup(this,e,t,i),!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,i){void 0===i&&(i=this.shareColor),this.colorSet=!0,this.color=e,this.colorName=t,this.shareColor=i,this.emit("color:set",{color:e,name:t,shareColor:i})},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=r.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 s(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:o.t("Smiley is already taken. Please select a different smiley.")})},t.clearSmiley=function(e){this.Webcontrol.smileys.unreserve(this.getIdentifier()),this.emit("user:smiley",{smiley:null}),this.smiley=null},t.getSmiley=function(){return this.smiley},t.getSmileyImage=function(){return this.Webcontrol.smileys.getImage(this.getSmiley())},t.getSmileyHtml=function(){return this.Webcontrol.smileys.getHtml(this.getSmiley())},t.getSmileyUrl=function(){return this.Webcontrol.smileys.getUrl(this.getSmiley())},t.setMaxUsers=function(e){this.emit("config:set",{maxUsers:e})},t.isActive=function(){return this.active},t.toggleActive=function(){this.active=!this.active,this.setJoinLabel()},t.setJoinLabel=function(){!0===this.active?this.control("a").setLabel("LEAVE"):this.control("a").setLabel("JOIN")},t.setActive=function(e,t){this.active=e,this.eventableTrigger("active:change",e),this.active&&this.eventableTrigger("active:activate")},t.serialize=function(){return{id:this.getId(),token:this.token,userdata:this.userdata,nickname:this.nickname,profiledata:this.profiledata,email:this.email,access_token:this.access_token,shareColor:this.shareColor,color:this.color,colorName:this.colorName,smiley:this.smiley,data:this.dataSynchronizer.serialize(),events:this.events.serialize()}},t.unserialize=function(e){void 0!==e.profiledata&&this.setProfiledata(e.profiledata),void 0!==e.access_token&&this.setAccessToken(e.access_token),void 0!==e.token&&(this.token=e.token),void 0!==e.shareColor&&(this.shareColor=e.shareColor),void 0!==e.color&&(this.color=e.color),void 0!==e.colorName&&(this.colorName=e.colorName),void 0!==e.nickname&&(this.nickname=e.nickname),void 0!==e.email&&(this.email=e.email),void 0!==e.smiley&&(this.smiley=e.smiley,this.emit("user:smiley",{smiley:this.smiley})),void 0!==e.data&&this.dataSynchronizer.unserialize(e.data),void 0!==e.events&&this.events.unserialize(e.events)},h}),define("CatLab/Webremote/Models/State",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Preloader"],function(i,n){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(i.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=n.unserialize(this.Webcontrol.provider,e.preloader),t()}.bind(this))}.bind(this))}.bind(this),1)},t._setCollectionDetails=function(e,t){var i,n;if(void 0!==e)for(i=0;i<e.length;i++)(n=t.getFromId(e[i].id))?n.unserialize(e[i]):(console.log("Trying to set data for non existing user/group."),console.log(e[i]))},t.getData=function(){var t=[],i=(this.Webcontrol._grouplibrary.each(function(e){t.push(e.serialize())}.bind(this)),[]),e=(this.Webcontrol._userlibrary.each(function(e){i.push(e.serialize())}),{users:i,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 i=0;i<this.controllerListeners.length;i++)this.controllerListeners[i].handleIncomingMessage(e,t)},t.toView=function(e,t,i){this.handleViewMessage(e,t,i)},t.handleViewMessage=function(e,t,i){if(void 0===i)for(var n=0;n<this.viewListeners.length;n++)this.viewListeners[n].handleIncomingMessage(e,t);else this.viewListeners[i].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,i,n){if(e.substring(0,(n=void 0===n?"":n).length)===n){switch(e=e.replace(n,"")){case"nav:previous":return i.previous(),!0;case"nav:next":return i.next(),!0;case"nav:keyInput":return i.keyInput(t.button),!0;case"nav:back":return i.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(i,e,t,s,n,o){function r(e,t){this.initializeEventable(),this.Webcontrol=e,this.options=t,this.controlDisabled=!1,this.users=[],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 o(this.messageBus,"portal:"),this.useCatLabViews()&&e.loadViews(i.getSocketURL(!0)+"/webremote/views/default.xml"),this.eventListeners=[],this.initialize()}e=r.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();let n=[];this.Webcontrol.getUsers().forEach(function(e){var t,i;e.isMainGroup()&&(i=null,(t=e.getUser())&&(i={image:t.avatar}),n.push({active:e.isActive(),color:e.getColor(),profile:i,type:e.getType()}))}),this.messageBus.toView("users:update",{users:n})},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},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 i;void 0!==e?(i=e.getPortalControls(),t.control(i.toggleActive).click(function(){this.toggleActive(e)}.bind(this)),t.control(i.start).click(function(){this.startGame()}.bind(this)),t.control(i.back).click(function(){this.back()}.bind(this)),this.supportsLocalAuthentication()&&t.control(i.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(i,n){if(n.control("name").setLabel(i.getNickname()),n.listenTo(i,"login",function(){n.control("name").setLabel(i.getNickname())}),this.options.allowChangeNickname&&n.control("change-nickname").click(function(){this.changeNickname(i).then(function(){this.updateUserView(i)}.bind(this))}.bind(this)),this.options.customFunctions)for(var e in this.options.customFunctions)this.options.customFunctions.hasOwnProperty(e)&&function(e,t){n.control(e).click(function(){t(i).then(function(){this.updateUserView(i)}.bind(this))}.bind(this))}.bind(this)(e,this.options.customFunctions[e])},e.changeNickname=function(t){var i=new s,n=t.setView("catlab-nickname");return n.changeValue("name",t.getNickname()),n.control("a").click(function(){var e=n.getValues().name;!e||32<e.length||(t.setNickname(e),i.resolve())}),i.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 s={start:[],back:[],toggleActive:[],authenticate:[]};return this.Webcontrol._userlibrary.each(function(e){var t,i=e.getPortalControls();for(t in i)if(i.hasOwnProperty(t)){var n=e.control(i[t]).getLabelData();if(!n)continue;void 0===s[t]&&(s[t]=[]),-1===s[t].findIndex(function(e){return e.label===n.label&&e.image===n.image})&&s[t].push(n)}}.bind(this)),s},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.enableControls(),this.updateUsers()}.bind(this))},e.countAuthenticated=function(e){void 0===e&&(e=!0);for(var t=0,i=0;i<this.users.length;i++)!this.users[i].isAuthenticated()||e&&!this.users[i].isActive()||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;case this.Webcontrol.AUTH_REQUIRED_ONE_INACTIVE:return 0<this.countAuthenticated(!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.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());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.back=function(){void 0!==this.options.back&&(this.destroy(),this.options.back())},e.getConnectURL=function(){return this.Webcontrol.getConnectURL()},e.getConnectToken=function(){return this.Webcontrol.getConnectTokenForDisplay()},e.getQrCodeUrl=function(){var e=this.getConnectURL();return(e=e&&"http"!==e.substring(0,4)?"https://"+e:e)+"?t="+this.Webcontrol.getConnectToken()},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.eventListeners&&this.eventListeners.forEach(function(e){e.unbind()}),this.messageBus.toView("portal:destroy"),this.messageBus.removeControllerListener(this),this.navigatableProxy.destroy()},r}),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(n,s,o,e,r,i,t,a){function l(e,t,i){this.initializeEventable(),this.messageBus=e.getMessageBus(),this.navigatableProxy=new a(this.messageBus,"auth:"),this.Webcontrol=e,this.user=t,this.user.control("x").click(function(){this.messageBus.toView("auth:request-remove-selected-profile")}.bind(this)),o.on("update",this.updateUsers,this),n.on("update",function(){this.updateUsers()},this),this.messageBus.addControllerListener(this)}var c=null,h=null,e=l.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.trigger("close");break;case"auth:select-user":this.selectUser(t.user);break;case"auth:remove-user":this.removeUser(t.user)}},e.link=function(){n.link(function(e){this.selectUser(e)}.bind(this))},e.updateUsers=function(){this.messageBus.toView("auth:users:update",{users:o.getAll().map(function(e){return{id:e.getId(),name:e.getName(),image:e.avatar}})})},e.selectUser=function(e){var t;(e=o.getFromId(e.id))&&(t=this).user.loginFromAuthUser(e,function(){i.setCookie("ctlb_ps_"+this.user.id,e.id),t.close()}.bind(this))},e.removeUser=function(e){(e=o.getFromId(e.id))&&(o.remove(e),this.updateUsers())},e.getUsers=function(){return o},e.close=function(){this.messageBus.toView("auth:close"),this.destroy()},e.getLoginUrl=function(){var t,e,i=new r;return t=this.Webcontrol,(null!==c?((e=new r).resolve(c),e):(null===h&&(h=new r,t.newGroup().then(function(e){new s(c=e),e.setOAuthSettings(t.getOAuthSettings()),h.resolve(e)})),h)).promise().then(function(e){i.resolve(e.getConnectURL()+"/"+e.getConnectToken())}),i.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=i.getCookie("ctlb_ps_"+this.user.id);if(e){e=o.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()},l}),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,i,n=(new Date).getTime();setInterval(function(){t=(new Date).getTime(),i=t-n,n=t,this.trigger("tick",{in:this.countIncoming,out:this.countOutgoing,dt:i}),this.countIncoming=0,this.countOutgoing=0}.bind(this),this.interval)}e=t.prototype=new e;return e.incoming=function(){this.countIncoming++},e.outgoing=function(){this.countOutgoing++},t}),define("CatLab/Webremote/Views/Portal",["CatLab/Webremote/Config"],function(N){return function(e){var s=e.element||document.body,t=s,i=e.countdown||5e3,n=e.done||function(){alert("Game should start now... yet it doesn't.")},o=e["min-players"]||1,r=(o<1&&(o=1),e["max-players"]||1e3);r<o&&(r=o);var a,l,c,h,u,d,f,m,p,g,b,v=!e.customViews,y=[],w=!1,C=!1,k=null,D=this;function L(e){var t=document.createElement("div");return t.innerHTML=e.trim(),t.firstChild}function S(s){s.setView("catlab-portal-toggle"),s.control("join-game").click(function(){(e=>{if(x(e)){e.control("join-game").setLabel("JOIN");for(var t=e,i=0;i<y.length;i++)if(y[i].getId()==t.getId())return y.splice(i,1)}else e.control("join-game").setLabel("LEAVE"),y.push(e)})(s),M(),W(),V()}),s.control("start-game").click(function(){var e;w?V():y.length<o?U(o+" players are required to start the game. Please gather more friends."):y.length>r?U("This game can have only "+r+" players."):(e=i,V(),w=!0,(f=new Date).setTime((new Date).getTime()+e),u.style.display="",d=setInterval(z,100))}),s.control("down").click(function(){E(s)}),s.control("right").click(function(){E(s)}),s.control("left").click(function(){T(s)}),s.control("up").click(function(){T(s)}),s.control("a").click(function(){var e,t,n,i;e=s,C&&A(e)?(t=b.querySelector(".available-accounts li.selected"))&&(t=WebcontrolOAuthClient.getFromToken(t.getAttribute("data-accessToken")))&&(i=t.access_token,k.setUserData(i,t.user),I()):(w&&V(),C||(n=e,Webcontrol.getOAuthClient(function(i){i.onInit(function(){_(i)}),WebcontrolAccessKeyLibrary.init(function(){C=!0,k=n,g.style.display="",b.style.display="";var e=document.createElement("a"),t=(e.href="javascript:void(0);",e.textContent="Link new account",e.addEventListener("click",function(){i.getNewAccessToken(function(){_(i)})}),b.querySelector(".link-new-account"));t.innerHTML="",t.appendChild(e)}),_(i)})))}),s.control("b").click(function(){C&&A(s)&&(k.setUserData(!1),I())}),P(),W()}function T(e){if(C&&A(e)){for(var e=b.querySelector(".available-accounts"),t=e.querySelectorAll("li"),e=e.querySelector("li.selected"),i=0;i<t.length;i++)t[i].classList.remove("selected"),t[i].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 E(e){if(C&&A(e)){for(var e=b.querySelector(".available-accounts"),t=e.querySelectorAll("li"),e=e.querySelector("li.selected"),i=0;i<t.length;i++)t[i].classList.remove("selected"),t[i].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 A(e){return k&&e.getId()==k.getId()}function I(){g.style.display="none",b.style.display="none",C=!1,k=null}function _(e){var t=b.querySelector(".available-accounts");t.innerHTML="";for(var i=e.listUsers(),n=0;n<i.length;n++){var s=document.createElement("li");s.textContent=i[n].user.username,s.className="unselected",s.setAttribute("data-accessToken",i[n].access_token),t.appendChild(s)}}function W(){if(0<Webcontrol.getControlLabels("join-game").length){for(var e=document.querySelectorAll(".buttoninstructions.join-game"),t=0;t<e.length;t++){e[t].style.display="";var i=e[t].querySelector(".labels");i&&(i.innerHTML=Webcontrol.getControlLabels("join-game").join(", "))}for(var n=document.querySelectorAll(".buttoninstructions.start-game"),s=0;s<n.length;s++){n[s].style.display="";var o=n[s].querySelector(".labels");o&&(o.innerHTML=Webcontrol.getControlLabels("start-game").join(", "))}}else{for(var r=document.querySelectorAll(".buttoninstructions.join-game"),a=0;a<r.length;a++)r[a].style.display="none";h.style.display="none"}}function x(e){for(var t=0;t<y.length;t++)if(y[t].getId()==e.getId())return 1}function P(){var e=Webcontrol.getUsers();a.innerHTML="";for(var t=[],i=0;i<e.length;i++)x(e[i])||t.push(e[i]);0==t.length&&(a.innerHTML='<li class="empty"><span>More players? Add devices!</span></li>');for(var n="",i=0;i<t.length;i++)n+='<li class="user '+t[i].getType()+'" style="background-color: '+t[i].getColor()+'"><i class="'+t[i].getIcon()+'"></i><span>'+t[i].getName()+"</span></li>";n&&(a.innerHTML=n)}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),P()}function z(){m=Math.ceil((f.getTime()-(new Date).getTime())/1e3);var e=u.querySelector(".counter");e&&(e.innerHTML=m),m<0&&(void 0!==t&&void 0!==t.style&&(t.style.display="none"),V(),n(y))}function V(){w=!1,d&&(U("Countdown stopped!"),u.style.display="none",clearInterval(d),d=null)}function U(e){var t=document.createElement("p");t.innerHTML=e,p.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!",s.classList?s.classList.add("webremote-portal"):s.className=s.className+" webremote-portal",void 0!==e.theme&&(e=N.getSocketURL()+"/webremote/themes/"+e.theme+"/"+e.theme+".css",Webcontrol._loadCSS(e),Webcontrol._loadCSS(N.getSocketURL()+"/webremote/themes/font-awesome/css/font-awesome.min.css")),s.innerHTML='<div class="loading"><p>Please wait, loading socket.io.</p></div>',Webcontrol.initialize(function(){s.innerHTML="";var e=document.createElement("div"),e=(e.className="webremote-portal-inner",s.appendChild(e),(s=e).innerHTML='<div class="loading"><p>Please wait, connecting to server.</p></div>',v&&Webcontrol.loadViews(N.getSocketURL(!0)+"/webremote/views/default.xml"),s.innerHTML="<h1>Player lobby</h1>",g=document.createElement("div"),b=L('<div><h2>Select account</h2><div class="information"><p>'+D.loginInformation+'</p></div><ul class="available-accounts"></ul><p class="link-new-account"></p></div>'),g.className="accounts-overlay",b.className="accounts",g.style.display="none",b.style.display="none",s.appendChild(g),s.appendChild(b),L('<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),L('<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),s.appendChild(e),s.appendChild(t),(e=L('<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=L('<p class="buttoninstructions join-game">Press <span class="labels"></span> to join the game.</p>'),h=L('<p class="buttoninstructions start-game">Press <span class="labels"></span> to start the game.</p>'),(p=document.createElement("div")).className="errors",s.appendChild(p),e.appendChild(c),e.appendChild(h),s.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",s.appendChild(t),u=t,Webcontrol.on("user:join",function(e){S(e)});for(var i=Webcontrol.getUsers(),n=0;n<i.length;n++)S(i[n]);Webcontrol.on("user:leave",P),P(),M(),W()})}}),define("CatLab/Webremote/ViewFactory/ViewFactory",["CatLab/Webremote/Views/Portal"],function(t){function e(){}return e.prototype.getPortal=function(e){return new t(e)},e}),define("CatLab/Webremote/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/",i="gamepad-",n="🎮",s={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/",i="ps-controller-",n="🕹",s={a:"❎",b:"⭕",x:"🟥",y:"🔺",up:"⬆️",down:"⬇️",left:"⬅️",right:"➡️",l1:"🤜",r1:"🤛"}),{DPAD_UP:{id:"up",label:"↑",key:"DPAD_UP",emoji:n+"‍"+s.up},DPAD_DOWN:{id:"down",label:"↓",key:"DPAD_DOWN",emoji:n+"‍"+s.down},DPAD_RIGHT:{id:"right",label:"→",key:"DPAD_RIGHT",emoji:n+"‍"+s.right},DPAD_LEFT:{id:"left",label:"←",key:"DPAD_LEFT",emoji:n+"‍"+s.left},FACE_1:{id:"a",label:"A",key:"FACE_1",image:t+i+"a.gif",emoji:n+"‍"+s.a},FACE_2:{id:"b",label:"B",key:"FACE_2",image:t+i+"b.gif",emoji:n+"‍"+s.b},FACE_3:{id:"x",label:"X",key:"FACE_3",image:t+i+"x.gif",emoji:n+"‍"+s.x},FACE_4:{id:"y",label:"Y",key:"FACE_4",image:t+i+"y.gif",emoji:n+"‍"+s.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:n+"‍"+s.l1},R1:{id:"r1",label:"R1",key:"R1",emoji:n+"‍"+s.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}var n,t,s={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"},o=e.prototype;return o.initialize=function(e){var t;this.Webcontrol=e,this.initialized||(this.initialized=!0,e=function(){var e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads||[];for(n=0;n<e.length;n++)if(e[n]){for(n=0;n<e.length;n++)e[n]&&this.onConnect(e[n]);this.startGamepadPolling(),clearInterval(t)}}.bind(this),"undefined"!=typeof window&&("ongamepadconnected"in window?(window.addEventListener("gamepadconnected",function(e){this.onConnect(e.gamepad)}.bind(this)),window.addEventListener("gamepaddisconnected",function(e){this.onDisconnect(e.gamepad)}.bind(this))):t=setInterval(e,1e3)))},o.startGamepadPolling=function(){setInterval(this.poll.bind(this),50)},o.poll=function(){var e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads||[];for(n=0;n<e.length;n++)if(e[n])for(t=0;t<e[n].buttons.length;t++)this.gamepads[e[n].index].user&&void 0!==s[t]&&this.gamepads[e[n].index].user.controlFromKey(s[t]).update(e[n].buttons[t].pressed?1:0)},o.onConnect=function(e){var t=new i({id:e.id});this.gamepads[e.index]={user:t},this.Webcontrol.addCustomControl(t),this.startGamepadPolling()},o.onDisconnect=function(e){},new e}),define("CatLab/Webremote/Controllers/Webcontrol",["CatLab/Webremote/Config","CatLab/Webremote/Collections/Users","CatLab/Webremote/Collections/Groups","CatLab/Webremote/Collections/AuthenticatedUsers","CatLab/Webremote/Models/Users/ControlUser","CatLab/Webremote/Models/ControlGroup","CatLab/Webremote/Models/State","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Controllers/Portal","CatLab/Webremote/Controllers/Authentication","CatLab/Webremote/Tools/Colorwheel","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Translator","CatLab/Webremote/Tools/Preloader","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Eventable","CatLab/Webremote/Tools/MessageCounter","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Synchronization/RemoteViewFactory","CatLab/Webremote/Synchronization/DataSynchronizer","CatLab/Webremote/Synchronization/EventHandler","CatLab/Webremote/ViewFactory/ViewFactory","CatLab/Webremote/Views/ConnectionTrouble","CatLab/Webremote/Providers/SocketIO","CatLab/Webremote/Gamepads/GamepadAPI","CatLab/Webremote/SonicSync/Client","CatLab/Webremote/Messages/MessageBus"],function(a,e,t,i,n,s,l,o,r,c,h,u,d,f,m,p,g,b,v,y,w,C,k,L,S,T,E){function A(){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 E}p=A.prototype=new p;return Object.assign(p,{AUTH_REQUIRED_ALL:"ALL",AUTH_REQUIRED_ONE:"ONE",AUTH_REQUIRED_ONE_INACTIVE:"ONE-INACTIVE",AUTH_NOT_REQUIRED:"NONE",initialize:function(e){function t(){s.resolve(),n()}var i,n=function(){},s=(void 0!==(e=void 0===(e="function"==typeof e?{callback:e}:e)?{}:e).callback&&(n=e.callback),new u);return this._initialized?t():(this.sonicSyncClient=null,delete e.callback,e.headless,(i=!!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 L),this.provider=e.provider),this.smileys=new m(this.provider),void 0!==e.translator&&d.setTranslator(e.translator),this._initialize(i,t)}.bind(this))),s.promise()},disconnect:function(){this._initialized=!1,this.provider.disconnect()},_initialize:function(s,e){var o,r=new u;return(e&&r.then(e),this._initialized)?r.resolve(this.connected):(setTimeout(function(){r.resolve(!1)},3e4),this.state=new l(this),this._initialized=!0,(o=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()),r.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=>{o.provider.on(t,function(e){o._playerTrigger(t,e)})})(e[t]);var i=["value:change"];for(var n=0;n<i.length;n++)(t=>{o.provider.on(t,function(e){o._viewTrigger(t,e)})})(i[n]);this._oauthsettings&&this.provider.setOAuthSettings(this._oauthsettings),this.provider.setup(a.getProviderConfig()),this.preloader=new f(this.provider),!s&&a.useAudioSync()&&(this.sonicSyncClient=new T(this),this.sonicSyncClient.startSender())}.bind(this))}.bind(this))),r.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 g(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),o.initialize(e),i.initialize(this,o)},getOAuthClient:function(e){this._oauthsettings?(null===this._oauthClient&&(this._oauthClient=o,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(),i=0;i<t.length;i++)t[i].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 b.getConnectTokenForDisplay(this.getConnectToken())},loadViews:function(e,t,i){return this.provider.loadViews(e,i,t)},parseViews:function(e,t){return this.provider.parseViews(e,t)},registerComponent:function(e,t,i){return this.provider.registerComponent(e,t,i)},getUsers:function(){return this._userlibrary.getAll()},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 r(this,e),t.resolve(e),{controller:e,messageBus:this.getMessageBus(),promise:t};throw new Error("Please initialize Webcontrol first.")},portalView:function(e,t){var i;if(this._initialized)return i=this.getViewFactory(),e=Object.assign({},t,{messageBus:e,Webcontrol:this}),void 0!==t.element&&(e.element=t.element),(t=i.portal(e)).loading(),(e=i.getContainer()).easelboneLayer.setView(t),t.render(),e;throw new Error("Please initialize Webcontrol first.")},authentication:function(e,t){var i;if(this._initialized)return i=this.authenticationController(e,t),t=this.authenticationView(i.controller.messageBus,t),i.controller.setNavigatableUsers([e]),{controller:i.controller,view:t,promise:i.promise};throw new Error("Please initialize Webcontrol first.")},authenticationController:function(e,t){var i=new u,e=new c(this,e,t);return i.resolve(e),{controller:e,promise:i.promise()}},authenticationView:function(e,t){var i=this.getViewFactory(),t=i.authentication(Object.assign({},t,{messageBus:e})),e=i.getContainer();return e.easelboneLayer.setView(t),t.render(),e},alertView:function(e,t){var i=this.getViewFactory(),t=i.alert(Object.assign({},t,{message:e})),e=i.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 i;return void 0===t?(i=v.create(e,[this],this),this._lastView=i):i=v.create(e,t,this),i},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 i=[],n={},s=this.getUsers(),o=0;o<s.length;o++){var r=s[o].control(e).getLabel(t);void 0===n[r]&&i.push(n[r]=r)}return i},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(){S.initialize(this)},newGroup:function(e){var t=new u,i={},n=(void 0===e?e={}:"function"==typeof e&&(e={callback:e}),void 0===e.callback&&(e.callback=function(){}),!0),s=(void 0!==e.globalViews&&(n=e.globalViews),!0),o=(void 0!==e.shareColor&&(s=e.shareColor),[]),r=(void 0!==e.tags&&(o=e.tags),!0),r=(void 0!==e.smiley&&(r=!!e.smiley),i.smiley=r,this._groupCallbacks.id);return this._groupCallbacks.id++,this._groupCallbacks[r]={id:r,callback:e.callback,deferred:t,options:i},this.provider.createGroup(r,n,s,o),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 n(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,i=new s(e.id,e),n=(i.setWebcontrol(this),!1);void 0!==e.shareColor&&(n=e.shareColor),void 0!==e.color?i.setColor(e.color.color,e.color.name):i.setShareColor(n),this._grouplibrary.getFromId(e.id)||(n=function(){},void 0!==(t=e.externalId)&&void 0!==this._groupCallbacks[t]&&(i.setOptions(this._groupCallbacks[t].options),n=function(){this._groupCallbacks[t].callback(i),this._groupCallbacks[t].deferred.resolve(i)}.bind(this)),this._grouplibrary.add(i),i.getOption("smiley")&&this._initializeSmiley(i,e),this.trigger("group:create",i),this.log("New group "+i.getId()+"; URL "+i.getConnectURL()+", token "+i.getConnectToken()),n())},_initializeSmiley:function(e,t){var i;a.useSmileys()?void 0===t.smiley?null!==(i=this.smileys.getRandom(e.getIdentifier()))&&e.setSmiley(i):e.setSmiley(t.smiley):e.clearSmiley(),this.smileys.refreshTakenSmileys(e)},_playerTrigger:function(e,t){var i=this._userlibrary.getFromId(t.user);i?i.trigger(e,t):console.log("User not found: "+t.user)},_viewTrigger:function(e,t){var i=v.getFromId(t.viewId);i&&i.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 i=document.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute("type","text/css"),i.setAttribute("href",e),document.body.appendChild(i)},_setViewLabels:function(e){this._labeldata[e.id]=e.labels;for(var t=this.getUsers(),i=0;i<t.length;i++)for(var n=0;n<e.labels.length;n++)t[i].control(e.id).setStaticLabel(e.labels[n].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._initialized&&this.provider.emit("master:pause",{})},unpause:function(){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))}.bind(this))},_reconnect:function(e,t,i){return this.provider.reconnect(e,t,a.getProviderConfig(),i)},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()}}),A}),define("CatLab/Webremote/Models/Users/KeyboardUser",["CatLab/Webremote/Models/Users/ControlUser"],function(e){function t(e,t){var i="keyboard"+ ++n;this.initializeKeyboardUser({id:i,keys:e}),this.exitOnUnassignedBackButton=t}var n=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;window.onbeforeunload?(e=window.onbeforeunload({}))&&this.confirm(e,function(e){e&&this.exitApp()}.bind(this)):this.exitApp()},e.exitApp=function(){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,i){void 0===i&&(i=!0),void 0===t&&(t="back"),this.initializeKeyboardUser({id:"cordova",keys:e}),this.initializeBackButtonExit(t,i)}e=((t.prototype=Object.create(e.prototype)).constructor=t).prototype;return e.initializeBackButtonExit=function(i,n){void 0===n&&(n=!0);var s=new Date;document.addEventListener("backbutton",function(e){var t=new Date;t.getTime()-s.getTime()<300?this.requestExitApp():(s=t,e.preventDefault(),!n||this.control("back").hasTriggers("click")||this.control("back").hasTriggers("up")||this.control("back").hasTriggers("down")?i&&(this.control(i).update(1),setTimeout(function(){this.control(i).update(0)}.bind(this),1)):setTimeout(function(){void 0!==window.plugins.appMinimize?window.plugins.appMinimize.minimize():this.exitApp()},350))}.bind(this),!1)},e.exitApp=function(){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,i){this.initializeKeyboardUser({id:"cordova",keys:e}),this.initializeBackButtonExit(t,i)}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,i,n,s,o,r){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 i,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 i,this.readyState.resolve(),this.once("airconsole:well-hello-there",function(e){this.emitAirConsole(0,"player:join",{})}.bind(this))},e.onMessage=function(t,e){var i;void 0!==(e="string"==typeof e?JSON.parse(e):e).b&&Array.isArray(e.b)?(i=0,e.b.forEach(function(e){setTimeout(function(){this.processMessage(t,e)}.bind(this),i++)}.bind(this))):this.processMessage(t,e)},e.processMessage=function(e,t){var i;t&&t[0]&&(i=t[0],t=t[1],this.isMaster()&&(0<e&&"player:join"!==i&&void 0===this.knownUsers[e]&&this.onPlayerConnect(e),0<e)&&(t.user=e),o.unpack(t,"user").forEach(function(e){this.isRemote()&&void 0!==e.user&&e.user!==this.airconsole.getDeviceId()||this._trigger(i,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,i,n=this.master._userlibrary.getFromId(e);n&&(t={username:this.airconsole.getNickname(e)},(i=this.airconsole.getProfilePicture(e))&&(t.avatar=i),this.airconsole.getMasterControllerDeviceId()===e&&n.setMaster(!0),n.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,i,e=this.queue.compactFlush();e.length&&(t=5<e.length,i=[],e.forEach(function(e){t||void 0===e.data.user||Array.isArray(e.data.user)&&1<e.data.user.length?i.push(e):this.emitAirConsole(e.user,e.action,e.data)}.bind(this)),0<i.length)&&this.broadcastAirconsole(i)},e.emitAirConsole=function(e,t,i){t=[t,i],delete t[1].action,i=JSON.stringify(t);this.airconsole.message(e,i)},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=[],i=(Array.prototype.push.apply(t,arguments),"["+this.path+"]");"remote"===this.path&&(i="["+this.path+":"+this.airconsole.getDeviceId()+"]"),t.unshift(i),console.log.apply(console,t)},e.getConnectInstructions=function(){return["Open the Airconsole app on your smartphone and connect with code %s.",this.connectCode]},e.getStartAndLoginInstructions=function(){return["Use the onscreen button to start the game."]},a}),define("CatLab/Webremote/Providers/Dummy",["CatLab/Webremote/Providers/Provider","CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred","CatLab/Webremote/Tools/Tools"],function(e,t,n,i){function s(){this.initializeProvider(),this.userId=null,this.randomToken=i.getUuid(),this.loadBalancerSessionToken="connid",this.socket=null,this._registeredEvents={}}e=s.prototype=new e;return e.connect=function(e,t){var i=new n;return this.setInitialized(),i.resolve(),i.promise()},e.setup=function(e){this._trigger("master:initialize",{})},e.emitAll=function(e,t){},s}),define("CatLab/Webremote/CreateJS/LayerContainer",["easeljs","easelbone"],function(n,s){function e(e,t){if(!s)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 s.Views.Layer({container:this});var i=this;this.easelboneLayer.on("all",function(e){e=new n.Event(e);i.dispatchEvent(e)})}var t=e.prototype=new n.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(o,r,e){var a=new e;return o.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=[],i=1;i<arguments.length;i++){var n,s=arguments[i];"string"!=typeof s?(n=[],s.forEach(function(e){e.emoji?(n.push(e.emoji),void 0!==e.image&&(this.replacedEmojis[e.emoji]=a.getUrl(e.image,128))):e.label&&n.push(e.label)}.bind(this)),t.push(n.join(" / "))):t.push(s)}return r.t.apply(r,[e].concat(t))},getEmojiSubstitutedMessage:function(e){var e=new o.EaselJS.BigText(e),s=this.replacedEmojis;return e.textConstructor=function(e,t,i,n){e=new o.EaselJS.EmojiText(e,t,i,n);return e.setEmojis(s),e},e},alert:function(e,t){var t=this.Webcontrol.getViewFactory().alert(Object.assign({},t,{message:e})),i=this.Webcontrol.getViewFactory().getContainer();i.easelboneLayer.setView(t),t.render(),this.navigatableOverride=t,this.el.addChild(i),t.on("view:close",function(){i.easelboneLayer.view.trigger("stage:removed"),this.el.removeChild(i),this.navigatableOverride=null}.bind(this))}})}),define("CatLab/Webremote/Tools/ImageLoader",["CatLab/Webremote/Config","CatLab/Webremote/Tools/Deferred"],function(n,s){return{loadedImages:{},loadImage:function(e){var t,i=new s;return this.loadedImages[e]?i.resolve(this.loadedImages[e]):((t=new Image).crossOrigin="anonymous",t.onload=function(){this.loadedImages[e]=t,i.resolve(this.loadedImages[e])}.bind(this),t.src=n.getProxiedImage(e)),i.promise()}}}),define("CatLab/Webremote/Tools/QrGenerator",["easelbone","qrious"],function(o,r){return{generateQrCode:function(e,t){var i=200,n=200;e.getBounds()&&e.getBounds().width&&!e.getBounds().height&&(i=e.getBounds().width,n=e.getBounds().height),e.addChild(this.getGeneratedQrCode(t,Math.max(i,n)))},getGeneratedQrCode(e,t,i,n){void 0===i&&(i="#000000"),void 0===n&&(n="#ffffff");var s=new r,t=(s.level="H",s.size=2*t,s.value=e,s.background=n,s.foreground=i,new Image);return t.src=s.toDataURL(),new o.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,n,t,s,o,i,r){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 n.EaselJS.Placeholder(this.getScreen().connectedUsers),this.connectedUsers=new n.Controls.FloatContainer(function(e){return this.getUserIcon(e)}.bind(this),6),this.connectedUsersContainer.addChild(this.connectedUsers)),this.activeUsersContainer=new n.EaselJS.Placeholder(this.getScreen().activeUsers),this.activeUsers=new n.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 n.Controls.Button(this.getScreen().start),this.start.setText(s.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 n.Controls.Button(this.getScreen().back),this.back.setText(s.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 n.EaselJS.BigText(s.t("Instructions")))}),this.findPlaceholders("activePlayersHeader").forEach(function(e){e.addChild(new n.EaselJS.BigText(s.t("Active devices")))}),this.findPlaceholders("connectedPlayersHeader").forEach(function(e){e.addChild(new n.EaselJS.BigText(s.t("Connected devices")))}),this.instructionTexts=[],this.instructionTexts=this.findPlaceholders("instructionText"),this.updateInstructionText(),this.activePlayerTexts=[],this.findPlaceholders("activePlayers").forEach(function(e){var t=new n.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 i=this.navigatableOverride||this;if(!r.handleMessage(e,t,i,"portal:"))switch(e){case"state:change":this.controllerState=t.state,this.initialized||this.initializeContent(),this.showCurrentAndMaxUsers();break;case"alert":if(t.id&&"exceeds-max-players"===t.id)if(this.purchaseSeatsCallback)return void this.alert(s.t(t.localized),{type:"confirm",okLabel:s.t("Purchase seats"),ok:function(e){e.close(),this.purchaseSeatsCallback()}.bind(this),cancelLabel:s.t("Cancel")});this.alert(s.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,i;return e?e.profile?(t=new this.assets.UserIconAuthenticated,this.addControllerIcon(t,e)):t=this.getControllerIcon(e):t=this.getControllerIcon(),e&&(i=t.PlayerColor)&&new n.EaselJS.Placeholder(i).addChild(new n.EaselJS.Fill(e.color)),e&&this.setUserDetails(t,e),t},addControllerIcon:function(e,t){var i;e.ControllerIcon&&(e=new n.EaselJS.Placeholder(e.ControllerIcon),i=this.getControllerIcon(t),e.addChild(i),i.scaleX=i.scaleY=.5,t)&&(e=i.PlayerColor)&&new n.EaselJS.Placeholder(e).addChild(new n.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=s.t(this.controllerState.startAndLoginInstructions))},showInformation:function(){var e,t=this.getScreen();t&&(e=s.t(this.controllerState.connectInstructions),t.login?t.login.text=s.t(this.controllerState.startAndLoginInstructions):e+="\n "+s.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&&i.generateQrCode(e,this.controllerState.qrUrl)}.bind(this)),this.qrInstructionsContainers.forEach(function(e){var t;e.removeAllChildren(),this.controllerState.qrUrl&&(t=this.getEmojiSubstitutedMessage(s.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,i=24;this.showInactivePlayers||(i=45),this.removeAllUserIcons(),this.users.forEach(function(e){e.active?i<=0||(i--,this.activeUsers.createElement(e)):!this.showInactivePlayers||t<=0||(t--,this.connectedUsers.createElement(e))}.bind(this))},setUserDetails:function(e,t){var i;t.profile&&e.userimage&&(i=new n.EaselJS.Placeholder(e.userimage),o.loadImage(t.profile.image).then(function(e){i.addChild(new n.EaselJS.Fill(e))}))},addAuthenticationView:function(){var e=this.Webcontrol.authenticationView(this.messageBus,{leanback:this.leanback});this.el.addChild(e),e.on("view:close",function(){e.easelboneLayer.view.trigger("stage:removed"),this.el.removeChild(e),this.messageBus.toController("auth:close")}.bind(this))},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(s,e,t,o,r,a,i,n){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 s.Controls.Button(this.screen.linkAccount),this.linkAccount.on("click",function(){n.link(function(e){this.selectUser(e)}.bind(this))}.bind(this))),this.titlePlaceholder=null,this.explanationPlaceholder=null,s.Helpers.MovieClipHelper.findFromNames(["title"],[this.screen]).forEach(function(e){this.titlePlaceholder=new s.EaselJS.Placeholder(e)}.bind(this)),s.Helpers.MovieClipHelper.findFromNames(["explanation"],[this.screen]).forEach(function(e){this.explanationPlaceholder=new s.EaselJS.Placeholder(e)}.bind(this)),this.titlePlaceholder&&(t=new s.EaselJS.BigText(o.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(),s.Helpers.MovieClipHelper.findFromNames("accounts",[this.screen]).forEach(function(e){e=new s.Controls.ScrollArea(e);this.users=new s.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.attachMessageBus(e.messageBus),this.on("stage:removed",this.destroy.bind(this))},attachMessageBus:function(e){(this.messageBus=e).addViewListener(this)},handleIncomingMessage:function(e,t){if(!i.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,i=new this.assets.UserModel,n=(i.namePlaceholder?i.text=i.namePlaceholder:i.name&&(i.text=i.name),new s.Controls.Button(i));return e&&(n.setText(e.name),t=new s.EaselJS.Placeholder(i.picture),r.loadImage(e.image).then(function(e){t.addChild(new s.EaselJS.Fill(e))}),n._userModel=e,n.on("click",function(){this.selectUser(e)}.bind(this)),this.addControl(n)),i},selectUser:function(e){this.messageBus.toController("auth:select-user",{user:{id:e.id}})},close:function(){this.trigger("close"),this.messageBus.toController("auth:close")},render:function(){this.el.addChild(this.screen)},setLoginUrl:function(e){this.loginUrl=e,this.setLoginUrlText()},setLoginUrlText:function(){if(this.linkAccount&&this.linkAccount.setText(o.t("Login to add profile")),this.explanationPlaceholder){var e,t=[],i={selectProfile:"%s to select",removeProfile:"%s to remove",close:"%s to close"};for(e in i){var n=this.getLabelSubstitutionOrNull(e,i[e]);n&&t.push(n)}this.explanationPlaceholder.removeAllChildren(),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=o.t("Scan to login or surf to %s",this.loginUrl);e.addChild(new s.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.messageBus.removeViewListener(this)}})}),define("CatLab/Webremote/CreateJS/Views/AlertView",["easelbone","CatLab/Webremote/Tools/Translator","CatLab/Webremote/CreateJS/Views/BaseView"],function(s,o,e){return e.extend({initialize:function(i){"confirm"===(this.intitializeBaseView(),this.easelScreen=new i.assets.Alert,this.findPlaceholders("message").forEach(function(e){var t=new s.EaselJS.BigText(i.message);e.addChild(t)}),void 0===i.type&&(i.type="alert"),i.type.toLowerCase())?this.initializeConfirm(i):this.initializeAlert(i)},initializeAlert:function(e){var t=o.t("OK");void 0!==e.buttonLabel&&(t=e.buttonLabel),this.findFromNames("button").forEach(function(e){e=new s.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 i=o.t("OK"),n=(void 0!==t.okLabel&&(i=t.okLabel),o.t("Cancel"));void 0!==t.cancelLabel&&(n=t.cancelLabel),this.findFromNames("button1").forEach(function(e){e=new s.Controls.Button(e);e.setText(i),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 s.Controls.Button(e);e.setText(n),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 o,r,a,l,i=e.prototype;return i.initialize=function(){var e=new t;return this.loadAssets().then(function(){this.setAssets(this.assets),e.resolve()}.bind(this)),e},i.loadAssets=function(){var s=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,i,n){o=e,r=t,a=i,l=n,s.resolve()}.bind(this)),s.promise()},i.portal=function(e){return e.assets=this.assets,new r(e)},i.authentication=function(e){return e.assets=this.assets,new a(e)},i.alert=function(e){return e.assets=this.assets,new l(e)},i.setAssets=function(e){void 0!==e&&(this.assets=e)},i.getContainer=function(){var e=new o;return e.setBounds(0,0,this.assets.properties.width,this.assets.properties.height),e.loading(),e},e}),define("CatLab/Webremote/FrontController",["CatLab/Webremote/Config","CatLab/Webremote/Polyfills","CatLab/Webremote/Tools/Tracker","CatLab/Webremote/Tools/Tools","CatLab/Webremote/Controllers/Webremote","CatLab/Webremote/Controllers/OAuth2","CatLab/Webremote/Controllers/Webcontrol","CatLab/Webremote/Tools/Smileys","CatLab/Webremote/Tools/Images","CatLab/Webremote/Models/Users/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/Providers/Dummy","CatLab/Webremote/ViewFactory/ViewFactory","CatLab/Webremote/ViewFactory/CreatejsViewFactory","CatLab/Webremote/Messages/NavigateableProxy"],function(t,e,i,n,s,o,r,a,l,c,h,u,d,f,m,p,g,b,v){return{Config:function(e){t.set(e)},Tracker:i,Tools:n,Webremote:new s,Webcontrol:new r,OAuth2:o,Controls:{Keyboard:c,Cordova:h,AndroidRemote:u,Dummy:d},Controllers:{Webcontrol:r,Webremote:s},Models:{User:d},Providers:{SocketIO:f,Airconsole:m,Dummy:p},ViewFactories:{HtmlViewFactory:g,CreatejsViewFactory:b},Smileys:a,Images:new l,NavigateableProxy:v}}),define("catlabremote",["CatLab/Webremote/FrontController"],function(e){return e}),define("CatLab/EaselHacks/AlphaMaskFilter",[],function(e){function t(e){var n=this;this.createjs=e,Object.defineProperty(e.DisplayObject.prototype,"mask",{get:function(){return this.forceMask},set:function(e){var t,i=this;e?(i.originalMask=e,t=n.getFilterFromMask(e,i),i.filters=[t],i.cache(0,0,500,500)):null!==e&&(i.filters=null,i.cache(0,0,500,500))}}),e.DisplayObject.prototype.setMask=function(e){this.forceMask=e}}return t.prototype.getFilterFromMask=function(e,t){var i=this.createjs,n=e.graphics.getInstructions(),s=new i.Graphics;s.beginFill("#000000"),s.beginStroke("#000000");for(var o=0;o<n.length;o++)s.append(n[o]);e.graphics=s;var r=new i.Container,e=(r.addChild(e),r.scaleX=1/t.scaleX,r.scaleY=1/t.scaleY,r.y=-t.y,r.x=-t.x,new i.Container);return e.addChild(r),e.cache(0,0,1e3,1e3),new i.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)});