;(function(){'use strict';if(window.navigator.mozHour12||window.navigator.hour12){return;} window.navigator.mozHour12=undefined;var _setMozHour12=function(result){if(result===null){result=undefined;} if(window.navigator.mozHour12!==result){window.navigator.mozHour12=result;window.dispatchEvent(new CustomEvent('timeformatchange'));}};var _hour12Handler=function(event){_setMozHour12(event.settingValue);};var _kLocaleTime='locale.hour12';var req=window.navigator.mozSettings.createLock().get(_kLocaleTime);req.onsuccess=function(){_setMozHour12(req.result[_kLocaleTime]);};window.navigator.mozSettings.addObserver(_kLocaleTime,_hour12Handler);})();;;(function(global){'use strict';global.mozIntl={formatList:function(list){return navigator.mozL10n.formatValue('listSeparator_middle').then(sep=>list.join(sep));},DateTimeFormat:function(locales,options){const resolvedOptions=Object.assign({},options);if(resolvedOptions.dayperiod){if(resolvedOptions.hour===undefined){resolvedOptions.hour='numeric';}} if(resolvedOptions.hour!==undefined&&resolvedOptions.hour12===undefined){resolvedOptions.hour12=navigator.mozHour12;} if(resolvedOptions.dayperiod===undefined&&resolvedOptions.hour12===true){resolvedOptions.dayperiod=true;} var intlFormat=new Intl.DateTimeFormat(locales,resolvedOptions);resolvedOptions.locale=intlFormat.resolvedOptions().locale;resolvedOptions.hour12=intlFormat.resolvedOptions().hour12;var hourFormatter;if(resolvedOptions.dayperiod!==undefined&&resolvedOptions.hour12===true){hourFormatter=Intl.DateTimeFormat(locales,{hour:'numeric',hour12:false});} return{resolvedOptions(){return resolvedOptions;},format:function(date,tokenFormats){var dayPeriod;var string=intlFormat.format(date);if(resolvedOptions.dayperiod===false&&resolvedOptions.hour12===true){dayPeriod=getDayPeriodTokenForDate(date,hourFormatter);string=string.replace(dayPeriod,'').trim();}else if(resolvedOptions.dayperiod===true&&options.hour===undefined){dayPeriod=getDayPeriodTokenForDate(date,hourFormatter);const hour=date.toLocaleString(navigator.languages,{hour12:true,hour:'numeric'}).replace(dayPeriod,'').trim();string=string.replace(hour,'').trim();} for(var token in tokenFormats){if(token==='dayperiod'&&resolvedOptions.hour12===false){continue;} const localOptions={[token]:resolvedOptions[token],};var formatter=global.mozIntl.DateTimeFormat(navigator.languages,localOptions);var tokenString=formatter.format(date);string=string.replace(tokenString,tokenFormats[token]);} return string;},};},calendarInfo:function(token){switch(token){case'firstDayOfTheWeek':return navigator.mozL10n.formatValue('firstDayOfTheWeek').then(firstDayOfTheWeek=>parseInt(firstDayOfTheWeek)%7);default:throw new Error('Unknown token: '+token);}},DurationFormat:function(locales=navigator.languages,options={}){const resolvedOptions=Object.assign({locale:locales[0],maxUnit:'hour',minUnit:'second',},options);const numFormatter=Intl.NumberFormat(locales,{style:'decimal',useGrouping:false,minimumIntegerDigits:2});const maxUnitIdx=getDurationUnitIdx(resolvedOptions.maxUnit,0);const minUnitIdx=getDurationUnitIdx(resolvedOptions.minUnit,durationFormatOrder.length-1);return navigator.mozL10n.formatValue('durationPattern').then(fmt=>({resolvedOptions:function(){return resolvedOptions;},format:function(input){const minValue=durationFormatElements[resolvedOptions.minUnit].value;input=Math.round(input/minValue)*minValue;const duration=splitIntoTimeUnits(input,maxUnitIdx,minUnitIdx);var string=trimDurationPattern(fmt,resolvedOptions.maxUnit,resolvedOptions.minUnit);for(var unit in duration){const token=durationFormatElements[unit].token;string=string.replace(token,numFormatter.format(duration[unit]));} if(input<0){return'-'+string;} return string;}}));},RelativeTimeFormat:function(locales,options){return{resolvedOptions:function(){return options;},format:function(x){const{unit,value}=relativeTimeFormatId(x,options);return navigator.mozL10n.formatValue(unit,{value});},};},UnitFormat:function(locales,options){const unitGroup=getUnitFormatGroupName(options.unit);if(unitGroup===undefined){throw new RangeError(`invalid value ${options.unit} for option unit`);} if(!unitFormatGroups[unitGroup].styles.includes(options.style)){throw new RangeError(`invalid value ${options.style} for option style`);} const unit=`${unitGroup}-${options.unit}-${options.style}`;return{format:function(x){return document.l10n.formatValue(unit,{value:x});},};},_gaia:{relativePart:function(milliseconds){const units=computeTimeUnits(milliseconds);const unit=getBestMatchUnit(units);return{unit:unit+'s',value:Math.abs(units[unit])};},RelativeDate:function(locales,options){const style=options&&options.style||'long';const maxFormatter=Intl.DateTimeFormat(locales,{year:'numeric',month:'numeric',day:'numeric'});const relativeFmtOptions={unit:'bestFit',style:style,minUnit:'minute',};return{format:function(time,maxDiff){maxDiff=maxDiff||86400*10;const secDiff=(Date.now()-time)/1000;if(isNaN(secDiff)){return navigator.mozL10n.formatValue('incorrectDate');} if(secDiff>maxDiff){return Promise.resolve(maxFormatter.format(time));} const{unit,value}=relativeTimeFormatId(time,relativeFmtOptions);return navigator.mozL10n.formatValue(unit,{value});},formatElement:function(element,time,maxDiff){maxDiff=maxDiff||86400*10;const secDiff=(Date.now()-time)/1000;if(isNaN(secDiff)){element.setAttribute('data-l10n-id','incorrectDate');} element.removeAttribute('data-l10n-id');if(secDiff>maxDiff){element.textContent=maxFormatter.format(time);} const{unit,value}=relativeTimeFormatId(time,relativeFmtOptions);navigator.mozL10n.setAttributes(element,unit,{value});},};},getFormattedUnit:function(type,style,v){if(!unitFormatData.hasOwnProperty(type)){throw new RangeError(`invalid type ${type}`);} if(!unitFormatGroups[type].styles.includes(style)){throw new RangeError(`invalid style ${style} for type ${type}`);} var units=unitFormatData[type];var scale=0;for(let i=1;i part.type === 'dayPeriod').value;} function computeTimeUnits(v){const units={};const millisecond=Math.round(v);const second=Math.round(millisecond/1000);const minute=Math.round(second/60);const hour=Math.round(minute/60);const day=Math.round(hour/24);const rawYear=day*400/146097;units.millisecond=millisecond;units.second=second;units.minute=minute;units.hour=hour;units.day=day;units.week=Math.round(day/7);units.month=Math.round(rawYear*12);units.quarter=Math.round(rawYear*4);units.year=Math.round(rawYear);return units;} function getBestMatchUnit(units){if(Math.abs(units.minute)<45){return'minute';} if(Math.abs(units.hour)<22){return'hour';} if(Math.abs(units.day)<7){return'day';} if(Math.abs(units.week)<4){return'week';} if(Math.abs(units.month)<11){return'month';} return'year';} function relativeTimeFormatId(x,options){const ms=x-Date.now();const units=computeTimeUnits(ms);const unit=options.unit==='bestFit'?getBestMatchUnit(units):options.unit;const v=units[unit];const tl=v<0?'-ago':'-until';const style=options.style||'long';const entry=unit+'s'+tl+'-'+style;return{unit:entry,value:Math.abs(v)};} function getUnitFormatGroupName(unitName){for(let groupName in unitFormatGroups){if(unitFormatGroups[groupName].units.includes(unitName)){return groupName;}} return undefined;}})(this);;(function(window,undefined){'use strict';function L10nError(message,id,loc){this.name='L10nError';this.message=message;this.id=id;this.loc=loc;} L10nError.prototype=Object.create(Error.prototype);L10nError.prototype.constructor=L10nError;var io={_load:function(type,url,callback,sync){var xhr=new XMLHttpRequest();var needParse;if(xhr.overrideMimeType){xhr.overrideMimeType(type);} xhr.open('GET',url,!sync);if(type==='application/json'){if(sync){needParse=true;}else{xhr.responseType='json';}} xhr.addEventListener('load',function io_onload(e){if(e.target.status===200||e.target.status===0){var res=e.target.response||e.target.responseText;callback(null,needParse?JSON.parse(res):res);}else{callback(new L10nError('Not found: '+url));}});xhr.addEventListener('error',callback);xhr.addEventListener('timeout',callback);try{xhr.send(null);}catch(e){if(e.name==='NS_ERROR_FILE_NOT_FOUND'){callback(new L10nError('Not found: '+url));}else{throw e;}}},load:function(url,callback,sync){return io._load('text/plain',url,callback,sync);},loadJSON:function(url,callback,sync){return io._load('application/json',url,callback,sync);}};function EventEmitter(){} EventEmitter.prototype.emit=function ee_emit(){if(!this._listeners){return;} var args=Array.prototype.slice.call(arguments);var type=args.shift();if(!this._listeners[type]){return;} var typeListeners=this._listeners[type].slice();for(var i=0;i2){throw new L10nError('Error in ID: "'+name+'".'+' Nested attributes are not supported.');} var attr;if(nameElements.length>1){name=nameElements[0];attr=nameElements[1];if(attr[0]==='$'){throw new L10nError('Attribute can\'t start with "$"',id);}}else{attr=null;} this.setEntityValue(name,attr,key,this.unescapeString(value),ast);},setEntityValue:function(id,attr,key,rawValue,ast){var pos,v;var value=rawValue.indexOf('{{')>-1?this.parseString(rawValue):rawValue;if(attr){pos=this.entryIds[id];if(pos===undefined){v={$i:id};if(key){v[attr]={};v[attr][key]=value;}else{v[attr]=value;} ast.push(v);this.entryIds[id]=ast.length-1;return;} if(key){if(typeof(ast[pos][attr])==='string'){ast[pos][attr]={$x:this.parseIndex(ast[pos][attr]),$v:{}};} ast[pos][attr].$v[key]=value;return;} ast[pos][attr]=value;return;} if(key){pos=this.entryIds[id];if(pos===undefined){v={};v[key]=value;ast.push({$i:id,$v:v});this.entryIds[id]=ast.length-1;return;} if(typeof(ast[pos].$v)==='string'){ast[pos].$x=this.parseIndex(ast[pos].$v);ast[pos].$v={};} ast[pos].$v[key]=value;return;} ast.push({$i:id,$v:value});this.entryIds[id]=ast.length-1;},parseString:function(str){var chunks=str.split(this.patterns.placeables);var complexStr=[];var len=chunks.length;var placeablesCount=(len-1)/2;if(placeablesCount>=MAX_PLACEABLES){throw new L10nError('Too many placeables ('+placeablesCount+', max allowed is '+MAX_PLACEABLES+')');} for(var i=0;i-1){return[{},env['__'+id]];} if(args&&args.hasOwnProperty(id)){if(typeof args[id]==='string'||(typeof args[id]==='number'&&!isNaN(args[id]))){return[{},args[id]];}else{throw new L10nError('Arg must be a string or a number: '+id);}} if(id in env&&id!=='__proto__'){return format(args,env[id]);} throw new L10nError('Unknown reference: '+id);} function subPlaceable(locals,args,env,id){var res;try{res=resolveIdentifier(args,env,id);}catch(err){return[{error:err},'{{ '+id+' }}'];} var value=res[1];if(typeof value==='number'){return res;} if(typeof value==='string'){if(value.length>=MAX_PLACEABLE_LENGTH){throw new L10nError('Too many characters in placeable ('+ value.length+', max allowed is '+ MAX_PLACEABLE_LENGTH+')');} if(locals.contextIsNonLatin1||value.match(nonLatin1)){res[1]=FSI+value+PDI;} return res;} return[{},'{{ '+id+' }}'];} function interpolate(locals,args,env,arr){return arr.reduce(function(prev,cur){if(typeof cur==='string'){return[prev[0],prev[1]+cur];}else if(cur.t==='idOrVar'){var placeable=subPlaceable(locals,args,env,cur.v);return[prev[0],prev[1]+placeable[1]];}},[locals,'']);} function resolveSelector(args,env,expr,index){var selectorName=index[0].v;var selector=resolveIdentifier(args,env,selectorName)[1];if(typeof selector!=='function'){return selector;} var argValue=index[1]?resolveIdentifier(args,env,index[1])[1]:undefined;if(selector===env.__plural){if(argValue===0&&'zero'in expr){return'zero';} if(argValue===1&&'one'in expr){return'one';} if(argValue===2&&'two'in expr){return'two';}} return selector(argValue);} function resolveValue(locals,args,env,expr,index){if(!expr){return[locals,expr];} if(typeof expr==='string'||typeof expr==='boolean'||typeof expr==='number'){return[locals,expr];} if(Array.isArray(expr)){locals.contextIsNonLatin1=expr.some(function($_){return typeof($_)==='string'&&$_.match(nonLatin1);});return interpolate(locals,args,env,expr);} if(index){var selector=resolveSelector(args,env,expr,index);if(expr.hasOwnProperty(selector)){return resolveValue(locals,args,env,expr[selector]);}} if('other'in expr){return resolveValue(locals,args,env,expr.other);} throw new L10nError('Unresolvable value');} var Resolver={createEntry:createEntry,format:format,rePlaceables:rePlaceables};function walkContent(node,fn){if(typeof node==='string'){return fn(node);} if(node.t==='idOrVar'){return node;} var rv=Array.isArray(node)?[]:{};var keys=Object.keys(node);for(var i=0,key;(key=keys[i]);i++){if(key==='$i'||key==='$x'){rv[key]=node[key];}else{rv[key]=walkContent(node[key],fn);}} return rv;} var reAlphas=/[a-zA-Z]/g;var reVowels=/[aeiouAEIOU]/g;var ACCENTED_MAP='\u0226\u0181\u0187\u1E12\u1E16\u0191\u0193\u0126\u012A'+'\u0134\u0136\u013F\u1E3E\u0220\u01FE\u01A4\u024A\u0158'+'\u015E\u0166\u016C\u1E7C\u1E86\u1E8A\u1E8E\u1E90'+'[\\]^_`'+'\u0227\u0180\u0188\u1E13\u1E17\u0192\u0260\u0127\u012B'+'\u0135\u0137\u0140\u1E3F\u019E\u01FF\u01A5\u024B\u0159'+'\u015F\u0167\u016D\u1E7D\u1E87\u1E8B\u1E8F\u1E91';var FLIPPED_MAP='\u2200\u0510\u2183p\u018E\u025F\u05E4HI\u017F'+'\u04FC\u02E5WNO\u0500\xD2\u1D1AS\u22A5\u2229\u0245'+'\uFF2DX\u028EZ'+'[\\]\u1D65_,'+'\u0250q\u0254p\u01DD\u025F\u0183\u0265\u0131\u027E'+'\u029E\u0285\u026Fuodb\u0279s\u0287n\u028C\u028Dx\u028Ez';function makeLonger(val){return val.replace(reVowels,function(match){return match+match.toLowerCase();});} function replaceChars(map,val){return val.replace(reAlphas,function(match){return map.charAt(match.charCodeAt(0)-65);});} var reWords=/[^\W0-9_]+/g;function makeRTL(val){return val.replace(reWords,function(match){return'\u202e'+match+'\u202c';});} var reExcluded=/(%[EO]?\w|\{\s*.+?\s*\}|&[#\w]+;|<\s*.+?\s*>)/;function mapContent(fn,val){if(!val){return val;} var parts=val.split(reExcluded);var modified=parts.map(function(part){if(reExcluded.test(part)){return part;} return fn(part);});return modified.join('');} function Pseudo(id,name,charMap,modFn){this.id=id;this.translate=mapContent.bind(null,function(val){return replaceChars(charMap,modFn(val));});this.name=this.translate(name);} var PSEUDO={'fr-x-psaccent':new Pseudo('fr-x-psaccent','Runtime Accented',ACCENTED_MAP,makeLonger),'ar-x-psbidi':new Pseudo('ar-x-psbidi','Runtime Bidi',FLIPPED_MAP,makeRTL)};function Locale(id,ctx){this.id=id;this.ctx=ctx;this.isReady=false;this.entries=Object.create(null);this.entries.__plural=getPluralRule(this.isPseudo()?this.ctx.defaultLocale:id);} Locale.prototype.isPseudo=function(){return this.ctx.qps.indexOf(this.id)!==-1;};var bindingsIO={extra:function(id,ver,path,type,callback,errback){if(type==='properties'){type='text';} navigator.mozApps.getLocalizationResource(id,ver,path,type).then(callback.bind(null,null),errback);},app:function(id,ver,path,type,callback,errback,sync){switch(type){case'properties':io.load(path,callback,sync);break;case'json':io.loadJSON(path,callback,sync);break;}},};Locale.prototype.build=function L_build(callback){var sync=!callback;var ctx=this.ctx;var self=this;var l10nLoads=ctx.resLinks.length;function onL10nLoaded(err){if(err){ctx._emitter.emit('fetcherror',err);} if(--l10nLoads<=0){self.isReady=true;if(callback){callback();}}} if(l10nLoads===0){onL10nLoaded();return;} function onJSONLoaded(err,json){if(!err&&json){self.addAST(json);} onL10nLoaded(err);} function onPropLoaded(err,source){if(!err&&source){var ast=PropertiesParser.parse(ctx,source);self.addAST(ast);} onL10nLoaded(err);} var idToFetch=this.isPseudo()?ctx.defaultLocale:this.id;var appVersion=null;var source='app';if(typeof(navigator)!=='undefined'){source=navigator.mozL10n._config.localeSources[this.id]||'app';appVersion=navigator.mozL10n._config.appVersion;} for(var i=0;i=0)?'rtl':'ltr';} var readyStates={loading:0,interactive:1,complete:2};function whenInteractive(callback){if(readyStates[document.readyState]>=readyStates.interactive){callback();return;} document.addEventListener('readystatechange',function l10n_onrsc(){if(readyStates[document.readyState]>=readyStates.interactive){document.removeEventListener('readystatechange',l10n_onrsc);callback();}});} function initObserver(){nodeObserver=new MutationObserver(onMutations.bind(navigator.mozL10n));nodeObserver.observe(document,moConfig);} function init(pretranslate){if(!pretranslate){initObserver();} initResources.call(navigator.mozL10n);} function initResources(){var meta={};var nodes=document.head.querySelectorAll('link[rel="localization"],'+'meta[name="availableLanguages"],'+'meta[name="defaultLanguage"],'+'meta[name="appVersion"],'+'script[type="application/l10n"]');for(var i=0,node;node=nodes[i];i++){var type=node.getAttribute('rel')||node.nodeName.toLowerCase();switch(type){case'localization':this.ctx.resLinks.push(node.getAttribute('href'));break;case'meta':onMetaInjected.call(this,node,meta);break;case'script':onScriptInjected.call(this,node);break;}} var additionalLanguagesPromise;if(navigator.mozApps&&navigator.mozApps.getAdditionalLanguages){additionalLanguagesPromise=navigator.mozApps.getAdditionalLanguages().catch(function(e){console.error('Error while loading getAdditionalLanguages',e);});document.addEventListener('additionallanguageschange',function(evt){registerLocales.call(this,meta,evt.detail);this.ctx.requestLocales.apply(this.ctx,navigator.languages||[navigator.language]);}.bind(this));}else{additionalLanguagesPromise=Promise.resolve();} additionalLanguagesPromise.then(function(extraLangs){registerLocales.call(this,meta,extraLangs);initLocale.call(this);}.bind(this));} function registerLocales(meta,extraLangs){var locales=buildLocaleList.call(this,meta,extraLangs);navigator.mozL10n._config.localeSources=locales[1];this.ctx.registerLocales(locales[0],Object.keys(locales[1]));} function getMatchingLangpack(appVersion,langpacks){for(var i=0,langpack;(langpack=langpacks[i]);i++){if(langpack.target===appVersion){return langpack;}} return null;} function buildLocaleList(meta,extraLangs){var loc,lp;var localeSources=Object.create(null);var defaultLocale=meta.defaultLanguage||this.ctx.defaultLocale;if(meta.availableLanguages){for(loc in meta.availableLanguages){localeSources[loc]='app';}} if(extraLangs){for(loc in extraLangs){lp=getMatchingLangpack(this._config.appVersion,extraLangs[loc]);if(!lp){continue;} if(!(loc in localeSources)||!meta.availableLanguages[loc]||parseInt(lp.revision)>meta.availableLanguages[loc]){localeSources[loc]='extra';}}} if(!(defaultLocale in localeSources)){localeSources[defaultLocale]='app';} return[defaultLocale,localeSources];} function splitAvailableLanguagesString(str){var langs={};str.split(',').forEach(function(lang){lang=lang.trim().split(':');langs[lang[0]]=parseInt(lang[1]);});return langs;} function onMetaInjected(node,meta){switch(node.getAttribute('name')){case'availableLanguages':meta.availableLanguages=splitAvailableLanguagesString(node.getAttribute('content'));break;case'defaultLanguage':meta.defaultLanguage=node.getAttribute('content');break;case'appVersion':navigator.mozL10n._config.appVersion=node.getAttribute('content');break;}} function onScriptInjected(node){var lang=node.getAttribute('lang');var locale=this.ctx.getLocale(lang);locale.addAST(JSON.parse(node.textContent));} function initLocale(){this.ctx.requestLocales.apply(this.ctx,navigator.languages||[navigator.language]);window.addEventListener('languagechange',function l10n_langchange(){this.ctx.requestLocales.apply(this.ctx,navigator.languages||[navigator.language]);}.bind(this));} function localizeMutations(mutations){var mutation;var targets=new Set();for(var i=0;i]/g;var htmlEntities={'&':'&','<':'<','>':'>',};function translateDocument(){document.documentElement.lang=this.language.code;document.documentElement.dir=this.language.direction;translateFragment.call(this,document.documentElement);} function translateFragment(element){if(typeof element.hasAttribute==='function'&&element.hasAttribute('data-l10n-id')){translateElement.call(this,element);} var nodes=getTranslatableChildren(element);for(var i=0;iDate.now()){return;} this.lastClick=Date.now();var event=new MouseEvent('click',{view:window,bubbles:true,cancelable:true});this.dispatchEvent(event);if(!event.defaultPrevented){this.checked=!this.checked;this._wrapper.setAttribute('aria-checked',this.checked);} this.dispatchEvent(new CustomEvent('change',{bubbles:true,cancelable:false}));};proto.configureClass=function(){this._wrapper.className=this.className;};proto.attributeChangedCallback=function(name,from,to){if(name==='class'){this._wrapper.className=to;}};Object.defineProperty(proto,'checked',{get:function(){return this._checked||false;},set:function(value){this._wrapper.classList.toggle('checked',value);this._checked=value;}});Object.defineProperty(proto,'name',{get:function(){return this.getAttribute('name');},set:function(value){this.setAttribute('name',value);}});var template=document.createElement('template');template.innerHTML=` `;return document.registerElement('gaia-checkbox',{prototype:proto});})(window);;window.GaiaSwitch=(function(win){var proto=Object.create(HTMLElement.prototype);var baseurl=window.GaiaSwitchBaseurl||'/shared/elements/gaia_switch/';proto.createdCallback=function(){var shadow=this.createShadowRoot();this._template=template.content.cloneNode(true);this._input=this._template.querySelector('input[type="checkbox"]');var checked=this.getAttribute('checked');if(checked!==null){this._input.checked=true;} var wrapper=this._template.getElementById('switch');wrapper.addEventListener('click',this.handleClick.bind(this));shadow.appendChild(this._template);ComponentUtils.style.call(this,baseurl);var dirObserver=new MutationObserver(this.updateInternalDir.bind(this));dirObserver.observe(document.documentElement,{attributeFilter:['dir'],attributes:true});this.updateInternalDir();};proto.updateInternalDir=function(){var internal=this.shadowRoot.firstElementChild;if(document.documentElement.dir==='rtl'){internal.setAttribute('dir','rtl');}else{internal.removeAttribute('dir');}};proto.handleClick=function(e){if(e&&e.target.tagName==='A'){return;} e&&e.preventDefault();e&&e.stopImmediatePropagation();var event=new MouseEvent('click',{view:window,bubbles:true,cancelable:true});this.dispatchEvent(event);if(!event.defaultPrevented){this.checked=!this.checked;} this.dispatchEvent(new CustomEvent('change',{bubbles:true,cancelable:false}));};proto.click=function(){this.handleClick();};Object.defineProperty(proto,'checked',{get:function(){return this._input.checked;},set:function(value){this._input.checked=value;}});Object.defineProperty(proto,'disabled',{get:function(){return this.hasAttribute('disabled');},set:function(value){if(value){this.setAttribute('disabled',true);}else{this.removeAttribute('disabled');}}});Object.defineProperty(proto,'name',{get:function(){return this.getAttribute('name');},set:function(value){this.setAttribute('name',value);}});Object.defineProperty(proto,'type',{get:function(){return'gaia-switch';}});var template=document.createElement('template');template.innerHTML=`
`;return document.registerElement('gaia-switch',{prototype:proto});})(window);;window.COMPONENTS_BASE_URL='/shared/elements/';;(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.GaiaHeader=f()}})(function(){var define,module,exports;return(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;ospace&&fontSize!==min&&fontSize--);return{textWidth:textWidth,fontSize:fontSize,overflowing:textWidth>space};};function getTextWidth(text,font){var ctx=getCanvasContext(font);var width=ctx.measureText(text).width;debug('got text width',width);return width;} function getCanvasContext(font){debug('get canvas context',font);var cached=cache[font];if(cached){return cached;} var canvas=document.createElement('canvas');canvas.setAttribute('moz-opaque','true');canvas.setAttribute('width','1px');canvas.setAttribute('height','1px');debug('created canvas',canvas);var ctx=canvas.getContext('2d',{willReadFrequently:true});ctx.font=font;return cache[font]=ctx;} function trim(text){return text.replace(/\s+/g,' ').trim();}});})(typeof define=='function'&&define.amd?define:(function(n,w){'use strict';return typeof module=='object'?function(c){c(require,exports,module);}:function(c){var m={exports:{}};c(function(n){return w[n];},m.exports,m);w[n]=m.exports;};})('font-fit',this));},{}],2:[function(require,module,exports){;(function(define){'use strict';define(function(require,exports,module){var textContent=Object.getOwnPropertyDescriptor(Node.prototype,'textContent');var innerHTML=Object.getOwnPropertyDescriptor(Element.prototype,'innerHTML');var removeAttribute=Element.prototype.removeAttribute;var setAttribute=Element.prototype.setAttribute;var noop=function(){};exports.register=function(name,props){var baseProto=getBaseProto(props.extends);var template=props.template||baseProto.templateString;var extensible=props.extensible=props.hasOwnProperty('extensible')?props.extensible:true;delete props.extends;if(template){if(extensible&&props.template){props.templateString=props.template;} var output=processCss(template,name);props.template=document.createElement('template');props.template.innerHTML=output.template;props.lightCss=output.lightCss;props.globalCss=props.globalCss||'';props.globalCss+=output.globalCss;} injectGlobalCss(props.globalCss);delete props.globalCss;var descriptors=mixin(props.attrs||{},base.descriptors);props._attrs=props.attrs;delete props.attrs;var proto=createProto(baseProto,props);Object.defineProperties(proto,descriptors);try{return document.registerElement(name,{prototype:proto});}catch(e){if(e.name!=='NotSupportedError'){throw e;}}};var base={properties:{GaiaComponent:true,attributeChanged:noop,attached:noop,detached:noop,created:noop,createdCallback:function(){if(this.dirObserver){addDirObserver();} injectLightCss(this);this.created();},attributeChangedCallback:function(name,from,to){var prop=toCamelCase(name);if(this._attrs&&this._attrs[prop]){this[prop]=to;} this.attributeChanged(name,from,to);},attachedCallback:function(){if(this.dirObserver){this.setInnerDirAttributes=setInnerDirAttributes.bind(null,this);document.addEventListener('dirchanged',this.setInnerDirAttributes);} this.attached();},detachedCallback:function(){if(this.dirObserver){document.removeEventListener('dirchanged',this.setInnerDirAttributes);} this.detached();},setupShadowRoot:function(){if(!this.template){return;} var node=document.importNode(this.template.content,true);this.createShadowRoot().appendChild(node);if(this.dirObserver){setInnerDirAttributes(this);} return this.shadowRoot;},setAttr:function(name,value){var internal=this.shadowRoot.firstElementChild;setAttribute.call(internal,name,value);setAttribute.call(this,name,value);},removeAttr:function(name){var internal=this.shadowRoot.firstElementChild;removeAttribute.call(internal,name);removeAttribute.call(this,name);}},descriptors:{textContent:{set:function(value){textContent.set.call(this,value);if(this.lightStyle){this.appendChild(this.lightStyle);}},get:function(){return textContent.get();}},innerHTML:{set:function(value){innerHTML.set.call(this,value);if(this.lightStyle){this.appendChild(this.lightStyle);}},get:innerHTML.get}}};var defaultPrototype=createProto(HTMLElement.prototype,base.properties);function getBaseProto(proto){if(!proto){return defaultPrototype;} proto=proto.prototype||proto;return!proto.GaiaComponent?createProto(proto,base.properties):proto;} function createProto(proto,props){return mixin(Object.create(proto),props);} var hasShadowCSS=(function(){var div=document.createElement('div');try{div.querySelector(':host');div.querySelector('::content');return true;} catch(e){return false;}})();var regex={shadowCss:/(?:\:host|\:\:content)[^{]*\{[^}]*\}/g,':host':/(?:\:host)/g,':host()':/\:host\((.+)\)(?: \:\:content)?/g,':host-context':/\:host-context\((.+)\)([^{,]+)?/g,'::content':/(?:\:\:content)/g};function processCss(template,name){var globalCss='';var lightCss='';if(!hasShadowCSS){template=template.replace(regex.shadowCss,function(match){var hostContext=regex[':host-context'].exec(match);if(hostContext){globalCss+=match.replace(regex['::content'],'').replace(regex[':host-context'],'$1 '+name+'$2').replace(/ +/g,' ');}else{lightCss+=match.replace(regex[':host()'],name+'$1').replace(regex[':host'],name).replace(regex['::content'],name);} return'';});} return{template:template,lightCss:lightCss,globalCss:globalCss};} function injectGlobalCss(css){if(!css){return;} var style=document.createElement('style');style.innerHTML=css.trim();headReady().then(function(){document.head.appendChild(style);});} function headReady(){return new Promise(function(resolve){if(document.head){return resolve();} window.addEventListener('load',function fn(){window.removeEventListener('load',fn);resolve();});});} function injectLightCss(el){if(hasShadowCSS){return;} var stylesheet=el.querySelector('style');if(!stylesheet){stylesheet=document.createElement('style');stylesheet.setAttribute('scoped','');stylesheet.appendChild(document.createTextNode(el.lightCss));el.appendChild(stylesheet);} el.lightStyle=stylesheet;} function toCamelCase(string){return string.replace(/-(.)/g,function replacer(string,p1){return p1.toUpperCase();});} var dirObserver;function setInnerDirAttributes(component){var dir=component.dir||document.dir;Array.from(component.shadowRoot.children).forEach(element=>{if(element.nodeName!=='STYLE'){element.dir=dir;}});} function addDirObserver(){if(dirObserver){return;} dirObserver=new MutationObserver(onChanged);dirObserver.observe(document.documentElement,{attributeFilter:['dir'],attributes:true});function onChanged(mutations){document.dispatchEvent(new Event('dirchanged'));}} function mixin(target,source){for(var key in source){target[key]=source[key];} return target;}});})(typeof define=='function'&&define.amd?define:(function(n,w){'use strict';return typeof module=='object'?function(c){c(require,exports,module);}:function(c){var m={exports:{}};c(function(n){return w[n];},m.exports,m);w[n]=m.exports;};})('gaia-component',this));},{}],3:[function(require,module,exports){(function(define){'use strict';define(function(require,exports,module){var base=window.GAIA_ICONS_BASE_URL||window.COMPONENTS_BASE_URL||'bower_components/';if(!document.documentElement){window.addEventListener('load',load);}else{load();} function load(){if(isLoaded()){return;} var link=document.createElement('link');link.rel='stylesheet';link.type='text/css';link.href=base+'gaia-icons/gaia-icons.css';document.head.appendChild(link);exports.loaded=true;} function isLoaded(){return exports.loaded||document.querySelector('link[href*=gaia-icons]')||document.documentElement.classList.contains('gaia-icons-loaded');}});})(typeof define=='function'&&define.amd?define:(function(n,w){'use strict';return typeof module=='object'?function(c){c(require,exports,module);}:function(c){var m={exports:{}};c(function(n){return w[n];},m.exports,m);w[n]=m.exports;};})('gaia-icons',this));},{}],4:[function(require,module,exports){;(function(define){'use strict';define(function(require,exports,module){var component=require('gaia-component');var fontFit=require('font-fit');require('gaia-icons');var debug=0?console.log.bind(console):function(){};const KNOWN_ACTIONS={menu:'menu',back:'back',close:'close'};const TITLE_FONT='italic 300 24px FiraSans';const TITLE_PADDING=10;const MINIMUM_FONT_SIZE_CENTERED=20;const MINIMUM_FONT_SIZE_UNCENTERED=16;const MAXIMUM_FONT_SIZE=23;module.exports=component.register('gaia-header',{extensible:false,dirObserver:true,created:function(){debug('created');this.setupShadowRoot();this.els={actionButton:this.shadowRoot.querySelector('.action-button'),titles:this.getElementsByTagName('h1')};this.els.actionButton.addEventListener('click',e=>this.onActionButtonClick(e));this.observer=new MutationObserver(this.onMutation.bind(this));this.ignoreDir=this.hasAttribute('ignore-dir');this.titleEnd=this.getAttribute('title-end');this.titleStart=this.getAttribute('title-start');this.noFontFit=this.getAttribute('no-font-fit');this.notFlush=this.hasAttribute('not-flush');this.action=this.getAttribute('action');this.unresolved={};this.pending={};this._resizeThrottlingId=null;this.onResize=this.onResize.bind(this);},attached:function(){debug('attached');this.runFontFitSoon();this.observerStart();window.addEventListener('resize',this.onResize);},detached:function(){debug('detached');window.removeEventListener('resize',this.onResize);this.observerStop();this.clearPending();},clearPending:function(){for(var key in this.pending){this.pending[key].clear();delete this.pending[key];} window.cancelAnimationFrame(this._resizeThrottlingId);this._resizeThrottlingId=null;},runFontFit:function(){debug('run font-fit');if(this.noFontFit){return Promise.resolve();} var titles=this.els.titles;var space=this.getTitleSpace();var styles=[].map.call(titles,el=>this.getTitleStyle(el,space));return this.setTitleStylesSoon(styles);},runFontFitSoon:function(){debug('run font-fit soon');if(this.pending.runFontFitSoon){return;} this.pending.runFontFitSoon=this.nextTick(()=>{delete this.pending.runFontFitSoon;this.runFontFit();});},getTitleStyle:function(el,space){debug('get el style',el,space);var text=el.textContent;var styleId=space.start+text+space.end+'#'+space.value;if(!text||!text.trim()){return debug('exit: no text');} if(getStyleId(el)===styleId){return debug('exit: no change');} var marginStart=this.getTitleMarginStart();var textSpace=space.value-Math.abs(marginStart);var fontFitResult=this.fontFit(text,textSpace,{min:MINIMUM_FONT_SIZE_CENTERED});var overflowing=fontFitResult.overflowing;var padding={start:0,end:0};if(overflowing){debug('title overflowing');padding.start=!space.start?TITLE_PADDING:0;padding.end=!space.end?TITLE_PADDING:0;textSpace=space.value-padding.start-padding.end;fontFitResult=this.fontFit(text,textSpace);marginStart=0;} return{id:styleId,fontSize:fontFitResult.fontSize,marginStart:marginStart,overflowing:overflowing,padding:padding};},setTitleStylesSoon:function(styles){debug('set title styles soon',styles);var key='setStyleTitlesSoon';this._titleStyles=styles;if(this.unresolved[key]){return this.unresolved[key];} this.unresolved[key]=new Promise((resolve)=>{this.pending[key]=this.nextTick(()=>{var styles=this._titleStyles;var els=this.els.titles;[].forEach.call(els,(el,i)=>{if(!styles[i]){return debug('exit');} this.setTitleStyle(el,styles[i]);});delete this._titleStyles;delete this.unresolved[key];delete this.pending[key];resolve();});});},setTitleStyle:function(el,style){debug('set title style',style);this.observerStop();if(this.ignoreDir){el.style.marginLeft=style.marginStart+'px';el.style.paddingLeft=style.padding.start+'px';el.style.paddingRight=style.padding.end+'px';}else{el.style.marginInlineStart=style.marginStart+'px';el.style.paddingInlineStart=style.padding.start+'px';el.style.paddingInlineEnd=style.padding.end+'px';} el.style.fontSize=style.fontSize+'px';setStyleId(el,style.id);this.observerStart();},fontFit:function(text,space,opts={}){debug('font fit:',text,space,opts);var fontFitArgs={font:TITLE_FONT,min:opts.min||MINIMUM_FONT_SIZE_UNCENTERED,max:MAXIMUM_FONT_SIZE,text:text,space:space};return fontFit(fontFitArgs);},observerStart:function(){if(this.observing){return;} this.observer.observe(this,{childList:true,attributes:true,subtree:true});this.observing=true;debug('observer started');},observerStop:function(){if(!this.observing){return;} this.observer.disconnect();this.observing=false;debug('observer stopped');},onResize:function(e){debug('onResize',this._resizeThrottlingId);if(this._resizeThrottlingId!==null){return;} this._resizeThrottlingId=window.requestAnimationFrame(()=>{this._resizeThrottlingId=null;this.runFontFitSoon();});},onMutation:function(mutations){debug('on mutation',mutations);if(!this.pending.runFontFitSoon){this.runFontFit();}},getTitleSpace:function(){var start=this.titleStart;var end=this.titleEnd;var space=this.getWidth()-start-end;var result={value:space,start:start,end:end};debug('get title space',result);return result;},getWidth:function(){var value=this.notFlush?this.clientWidth:window.innerWidth;debug('get width',value);return value;},triggerAction:function(){if(this.action){this.els.actionButton.click();}},onActionButtonClick:function(){debug('action button click');var config={detail:{type:this.action}};var e=new CustomEvent('action',config);setTimeout(()=>this.dispatchEvent(e));},getTitleMarginStart:function(){var start=this.titleStart;var end=this.titleEnd;var marginStart=end-start;debug('get title margin start',marginStart);return marginStart;},getButtonsBeforeTitle:function(){var children=this.children;var l=children.length;var els=[];for(var i=0;i=0;i--){var el=children[i];if(el.tagName==='H1'){break;} if(!contributesToLayout(el)){continue;} els.push(el);} return els;},sumButtonWidths:function(buttons){var defaultWidth=50;var sum=buttons.reduce((prev,button)=>{var isStandardButton=button===this.els.actionButton;var width=isStandardButton?defaultWidth:button.clientWidth;return prev+width;},0);debug('sum button widths',buttons,sum);return sum;},attrs:{action:{get:function(){return this._action;},set:function(value){var action=KNOWN_ACTIONS[value];if(action===this._action){return;} this.setAttr('action',action);this._action=action;}},titleStart:{get:function(){debug('get title-start');if('_titleStart'in this){return this._titleStart;} var buttons=this.getButtonsBeforeTitle();var value=this.sumButtonWidths(buttons);debug('get title-start',buttons,value);return value;},set:function(value){debug('set title-start',value);value=parseInt(value,10);if(value===this._titleStart||isNaN(value)){return;} this.setAttr('title-start',value);this._titleStart=value;debug('set');}},titleEnd:{get:function(){debug('get title-end');if('_titleEnd'in this){return this._titleEnd;} var buttons=this.getButtonsAfterTitle();return this.sumButtonWidths(buttons);},set:function(value){debug('set title-end',value);value=parseInt(value,10);if(value===this._titleEnd||isNaN(value)){return;} this.setAttr('title-end',value);this._titleEnd=value;}},noFontFit:{get:function(){return this._noFontFit||false;},set:function(value){debug('set no-font-fit',value);value=!!(value||value==='');if(value===this.noFontFit){return;} this._noFontFit=value;if(value){this.setAttr('no-font-fit','');} else{this.removeAttr('no-font-fit');}}},ignoreDir:{get:function(){return this._ignoreDir||false;},set:function(value){debug('set ignore-dir',value);value=!!(value||value==='');if(value===this.ignoreDir){return;} this._ignoreDir=value;this.dirObserver=!value;if(value){this.setAttr('ignore-dir','');} else{this.removeAttr('ignore-dir');}}}},template:`
`,nextTick:nextTick});function contributesToLayout(el){return el.localName!=='style'&&!el.hasAttribute('l10n-action');} function setStyleId(el,id){el._styleId=id;} function getStyleId(el){return el._styleId;} function nextTick(fn){var cleared;Promise.resolve().then(()=>{if(!cleared){fn();}});return{clear:function(){cleared=true;}};}});})(typeof define=='function'&&define.amd?define:(function(n,w){'use strict';return typeof module=='object'?function(c){c(require,exports,module);}:function(c){var m={exports:{}};c(function(n){return w[n];},m.exports,m);w[n]=m.exports;};})('gaia-header',this));},{"font-fit":1,"gaia-component":2,"gaia-icons":3}]},{},[4])(4)});;(function(global){var version='0.8.11',curlName='curl',defineName='define',bootScriptAttr='data-curl-run',bootScript,userCfg,prevCurl,prevDefine,doc=global.document,head=doc&&(doc['head']||doc.getElementsByTagName('head')[0]),insertBeforeEl=head&&head.getElementsByTagName('base')[0]||null,msgUsingExports={},msgFactoryExecuted={},activeScripts={},readyStates='addEventListener'in global?{}:{'loaded':1,'complete':1},cleanPrototype={},toString=cleanPrototype.toString,undef,cache={},urlCache={},preload=false,argsNet,dontAddExtRx=/\?|\.js\b/,absUrlRx=/^\/|^[^:]+:\/\/|^[A-Za-z]:[\\/]/,findDotsRx=/(\.)(\.?)(?:$|\/([^\.\/]+.*)?)/g,removeCommentsRx=/\/\*[\s\S]*?\*\/|\/\/.*?[\n\r]/g,findRValueRequiresRx=/require\s*\(\s*(["'])(.*?[^\\])\1\s*\)|[^\\]?(["'])/g,splitCommaSepRx=/\s*,\s*/,cjsGetters,core;function noop(){} function isType(obj,type){return toString.call(obj).indexOf('[object '+type)==0;} function normalizePkgDescriptor(descriptor,isPkg){var main;descriptor.path=removeEndSlash(descriptor['path']||descriptor['location']||'');if(isPkg){main=descriptor['main']||'./main';if(!isRelUrl(main))main='./'+main;descriptor.main=reduceLeadingDots(main,descriptor.name+'/');} descriptor.config=descriptor['config'];return descriptor;} function isRelUrl(it){return it.charAt(0)=='.';} function isAbsUrl(it){return absUrlRx.test(it);} function joinPath(path,file){return removeEndSlash(path)+'/'+file;} function removeEndSlash(path){return path&&path.charAt(path.length-1)=='/'?path.substr(0,path.length-1):path;} function reduceLeadingDots(childId,baseId){var removeLevels,normId,levels,isRelative,diff;removeLevels=1;normId=childId;if(isRelUrl(normId)){isRelative=true;normId=normId.replace(findDotsRx,function(m,dot,doubleDot,remainder){if(doubleDot)removeLevels++;return remainder||'';});} if(isRelative){levels=baseId.split('/');diff=levels.length-removeLevels;if(diff<0){return childId;} levels.splice(diff,removeLevels);return levels.concat(normId||[]).join('/');} else{return normId;}} function pluginParts(id){var delPos=id.indexOf('!');return{resourceId:id.substr(delPos+1),pluginId:delPos>=0&&id.substr(0,delPos)};} function Begetter(){} function beget(parent,mixin){Begetter.prototype=parent||cleanPrototype;var child=new Begetter();Begetter.prototype=cleanPrototype;for(var p in mixin)child[p]=mixin[p];return child;} function Promise(){var self,thens,complete;self=this;thens=[];function then(resolved,rejected,progressed){thens.push([resolved,rejected,progressed]);} function notify(which,arg){var aThen,cb,i=0;while((aThen=thens[i++])){cb=aThen[which];if(cb)cb(arg);}} complete=function promiseComplete(success,arg){then=success?function(resolved,rejected){resolved&&resolved(arg);}:function(resolved,rejected){rejected&&rejected(arg);};complete=noop;notify(success?0:1,arg);notify=noop;thens=undef;};this.then=function(resolved,rejected,progressed){then(resolved,rejected,progressed);return self;};this.resolve=function(val){self.resolved=val;complete(true,val);};this.reject=function(ex){self.rejected=ex;complete(false,ex);};this.progress=function(msg){notify(2,msg);}} function isPromise(o){return o instanceof Promise||o instanceof CurlApi;} function when(promiseOrValue,callback,errback,progback){if(isPromise(promiseOrValue)){return promiseOrValue.then(callback,errback,progback);} else{return callback(promiseOrValue);}} function countdown(howMany,lambda,completed){var result;return function(){if(--howMany>=0&&lambda)result=lambda.apply(undef,arguments);if(howMany==0&&completed)completed(result);return result;}} core={toAbsId:function(id,parentId,cfg){var absId,pluginId,parts;absId=reduceLeadingDots(id,parentId);if(isRelUrl(absId))return absId;parts=pluginParts(absId);pluginId=parts.pluginId;absId=pluginId||parts.resourceId;if(absId in cfg.pathMap){absId=cfg.pathMap[absId].main||absId;} if(pluginId){if(pluginId.indexOf('/')<0&&!(pluginId in cfg.pathMap)){absId=joinPath(cfg.pluginPath,pluginId);} absId=absId+'!'+parts.resourceId;} return absId;},createContext:function(cfg,baseId,depNames,isPreload){var def;def=new Promise();def.id=baseId||'';def.isPreload=isPreload;def.depNames=depNames;def.config=cfg;function toAbsId(childId,checkPlugins){var absId,parts,plugin;absId=core.toAbsId(childId,def.id,cfg);if(!checkPlugins)return absId;parts=pluginParts(absId);if(!parts.pluginId)return absId;plugin=cache[parts.pluginId];if('normalize'in plugin){parts.resourceId=plugin['normalize'](parts.resourceId,toAbsId,def.config)||'';} else{parts.resourceId=toAbsId(parts.resourceId);} return parts.pluginId+'!'+parts.resourceId;} function toUrl(n){return core.resolvePathInfo(toAbsId(n,true),cfg).url;} function localRequire(ids,callback,errback){var cb,rvid,childDef,earlyExport;cb=callback&&function(){callback.apply(undef,arguments[0]);};if(isType(ids,'String')){if(cb){throw new Error('require(id, callback) not allowed');} rvid=toAbsId(ids,true);childDef=cache[rvid];if(!(rvid in cache)){throw new Error('Module not resolved: '+rvid);} earlyExport=isPromise(childDef)&&childDef.exports;return earlyExport||childDef;} else{when(core.getDeps(core.createContext(cfg,def.id,ids,isPreload)),cb,errback);}} def.require=localRequire;localRequire['toUrl']=toUrl;def.toAbsId=toAbsId;return def;},createResourceDef:function(cfg,id,isPreload){var def,origResolve,execute;def=core.createContext(cfg,id,undef,isPreload);origResolve=def.resolve;execute=countdown(1,function(deps){def.deps=deps;try{return core.executeDefFunc(def);} catch(ex){def.reject(ex);}});def.resolve=function resolve(deps){when(isPreload||preload,function(){origResolve((cache[def.id]=urlCache[def.url]=execute(deps)));});};def.exportsReady=function executeFactory(deps){when(isPreload||preload,function(){if(def.exports){execute(deps);def.progress(msgFactoryExecuted);}});};return def;},createPluginDef:function(cfg,id,resId,isPreload){var def;def=core.createContext(cfg,resId,undef,isPreload);return def;},getCjsRequire:function(def){return def.require;},getCjsExports:function(def){return def.exports||(def.exports={});},getCjsModule:function(def){var module=def.module;if(!module){module=def.module={'id':def.id,'uri':core.getDefUrl(def),'exports':core.getCjsExports(def),'config':function(){return def.config;}};module.exports=module['exports'];} return module;},getDefUrl:function(def){return def.url||(def.url=core.checkToAddJsExt(def.require['toUrl'](def.id),def.config));},setApi:function(cfg){var apiName,defName,apiObj,defObj,failMsg,okToOverwrite;apiName=curlName;defName=defineName;apiObj=defObj=global;failMsg=' already exists';if(cfg){okToOverwrite=cfg['overwriteApi']||cfg.overwriteApi;apiName=cfg['apiName']||cfg.apiName||apiName;apiObj=cfg['apiContext']||cfg.apiContext||apiObj;defName=cfg['defineName']||cfg.defineName||defName;defObj=cfg['defineContext']||cfg.defineContext||defObj;if(prevCurl&&isType(prevCurl,'Function')){global[curlName]=prevCurl;} prevCurl=null;if(prevDefine&&isType(prevDefine,'Function')){global[defineName]=prevDefine;} prevDefine=null;if(!okToOverwrite){if(apiObj[apiName]&&apiObj[apiName]!=_curl){throw new Error(apiName+failMsg);} if(defObj[defName]&&defObj[defName]!=define){throw new Error(defName+failMsg);}}} apiObj[apiName]=_curl;defObj[defName]=define;},config:function(cfg){var prevCfg,newCfg,pluginCfgs,p;if('baseUrl'in cfg)cfg.baseUrl=cfg['baseUrl'];if('main'in cfg)cfg.main=cfg['main'];if('preloads'in cfg)cfg.preloads=cfg['preloads'];if('pluginPath'in cfg)cfg.pluginPath=cfg['pluginPath'];if('dontAddFileExt'in cfg||cfg.dontAddFileExt){cfg.dontAddFileExt=new RegExp(cfg['dontAddFileExt']||cfg.dontAddFileExt);} prevCfg=userCfg;newCfg=beget(prevCfg,cfg);newCfg.pathMap=beget(prevCfg.pathMap);pluginCfgs=cfg['plugins']||{};newCfg.plugins=beget(prevCfg.plugins);newCfg.paths=beget(prevCfg.paths,cfg.paths);newCfg.packages=beget(prevCfg.packages,cfg.packages);newCfg.pathList=[];function fixAndPushPaths(coll,isPkg){var id,pluginId,data,parts,currCfg,info;for(var name in coll){data=coll[name];if(isType(data,'String'))data={path:coll[name]};data.name=data.name||name;currCfg=newCfg;parts=pluginParts(removeEndSlash(data.name));id=parts.resourceId;pluginId=parts.pluginId;if(pluginId){currCfg=pluginCfgs[pluginId];if(!currCfg){currCfg=pluginCfgs[pluginId]=beget(newCfg);currCfg.pathMap=beget(newCfg.pathMap);currCfg.pathList=[];} delete coll[name];} info=normalizePkgDescriptor(data,isPkg);if(info.config)info.config=beget(newCfg,info.config);info.specificity=id.split('/').length;if(id){currCfg.pathMap[id]=info;currCfg.pathList.push(id);} else{currCfg.baseUrl=core.resolveUrl(data.path,newCfg);}}} function convertPathMatcher(cfg){var pathMap=cfg.pathMap;cfg.pathRx=new RegExp('^('+ cfg.pathList.sort(function(a,b){return pathMap[b].specificity-pathMap[a].specificity;}).join('|').replace(/\/|\./g,'\\$&')+')(?=\\/|$)');delete cfg.pathList;} fixAndPushPaths(cfg['packages'],true);fixAndPushPaths(cfg['paths'],false);for(p in pluginCfgs){var absId=core.toAbsId(p+'!','',newCfg);newCfg.plugins[absId.substr(0,absId.length-1)]=pluginCfgs[p];} pluginCfgs=newCfg.plugins;for(p in pluginCfgs){pluginCfgs[p]=beget(newCfg,pluginCfgs[p]);var pathList=pluginCfgs[p].pathList;if(pathList){pluginCfgs[p].pathList=pathList.concat(newCfg.pathList);convertPathMatcher(pluginCfgs[p]);}} for(p in prevCfg.pathMap){if(!newCfg.pathMap.hasOwnProperty(p))newCfg.pathList.push(p);} convertPathMatcher(newCfg);return newCfg;},resolvePathInfo:function(absId,cfg){var pathMap,pathInfo,path,pkgCfg;pathMap=cfg.pathMap;if(!isAbsUrl(absId)){path=absId.replace(cfg.pathRx,function(match){pathInfo=pathMap[match]||{};pkgCfg=pathInfo.config;return pathInfo.path||'';});} else{path=absId;} return{config:pkgCfg||userCfg,url:core.resolveUrl(path,cfg)};},resolveUrl:function(path,cfg){var baseUrl=cfg.baseUrl;return baseUrl&&!isAbsUrl(path)?joinPath(baseUrl,path):path;},checkToAddJsExt:function(url,cfg){return url+((cfg||userCfg).dontAddFileExt.test(url)?'':'.js');},loadScript:function(def,success,failure){var el=doc.createElement('script');function process(ev){ev=ev||global.event;if(ev.type=='load'||readyStates[el.readyState]){delete activeScripts[def.id];el.onload=el.onreadystatechange=el.onerror='';success();}} function fail(e){failure(new Error('Syntax or http error: '+def.url));} el.onload=el.onreadystatechange=process;el.onerror=fail;el.type=def.mimetype||'text/javascript';el.charset='utf-8';el.async=!def.order;el.src=def.url;activeScripts[def.id]=el;head.insertBefore(el,insertBeforeEl);return el;},extractCjsDeps:function(defFunc){var source,ids=[],currQuote;source=typeof defFunc=='string'?defFunc:defFunc.toSource?defFunc.toSource():defFunc.toString();source.replace(removeCommentsRx,'').replace(findRValueRequiresRx,function(m,rq,id,qq){if(qq){currQuote=currQuote==qq?undef:currQuote;} else if(!currQuote){ids.push(id);} return'';});return ids;},fixArgs:function(args){var id,deps,defFunc,defFuncArity,len,cjs;len=args.length;defFunc=args[len-1];defFuncArity=isType(defFunc,'Function')?defFunc.length:-1;if(len==2){if(isType(args[0],'Array')){deps=args[0];} else{id=args[0];}} else if(len==3){id=args[0];deps=args[1];} if(!deps&&defFuncArity>0){cjs=true;deps=['require','exports','module'].slice(0,defFuncArity).concat(core.extractCjsDeps(defFunc));} return{id:id,deps:deps||[],res:defFuncArity>=0?defFunc:function(){return defFunc;},cjs:cjs};},executeDefFunc:function(def){var resource,moduleThis;moduleThis=def.cjs?def.exports:undef;resource=def.res.apply(moduleThis,def.deps);if(resource===undef&&def.exports){resource=def.module?(def.exports=def.module['exports']):def.exports;} return resource;},defineResource:function(def,args){def.res=args.res;def.cjs=args.cjs;def.depNames=args.deps;core.getDeps(def);},getDeps:function(parentDef){var i,names,deps,len,dep,completed,name,exportCollector,resolveCollector;deps=[];names=parentDef.depNames;len=names.length;if(names.length==0)allResolved();function collect(dep,index,alsoExport){deps[index]=dep;if(alsoExport)exportCollector(dep,index);} exportCollector=countdown(len,collect,allExportsReady);resolveCollector=countdown(len,collect,allResolved);for(i=0;i2){result=Array.prototype.slice.call(arguments,1);} deferred.resolve(result);});var returnValue=fn.apply(this,args);return typeof returnValue==='object'?returnValue:deferred.promise;};} exports.denodeify=denodeify;function denodeifyAll(object,methods){methods.forEach((method)=>{object[method]=exports.denodeify(object[method]);});} exports.denodeifyAll=denodeifyAll;function defer(){var deferred={};var promise=new Promise((resolve,reject)=>{deferred.resolve=resolve;deferred.reject=reject;});deferred.promise=promise;return deferred;}});define('common/next_tick',['require','exports','module'],function(require,exports,module){'use strict';var resolved=Promise.resolve();module.exports=function(callback){resolved.then(callback);};});define('provider/abstract',['require','exports','module','common/promise','common/next_tick'],function(require,exports,module){'use strict';var denodeifyAll=require('common/promise').denodeifyAll;var nextTick=require('common/next_tick');function Abstract(options){var key;for(key in options){if(options.hasOwnProperty(key)){this[key]=options[key];}} denodeifyAll(this,['eventCapabilities','getAccount','findCalendars','syncEvents','ensureRecurrencesExpanded','createEvent','updateEvent','deleteEvent']);} module.exports=Abstract;Abstract.prototype={defaultColor:'#F97C17',useCredentials:false,useUrl:false,canSync:false,canExpandRecurringEvents:false,getAccount:function(account,callback){},findCalendars:function(){},syncEvents:function(account,calendar,callback){},ensureRecurrencesExpanded:function(date,callback){},updateEvent:function(event,busytime,callback){},deleteEvent:function(event,busytime,callback){},createEvent:function(event,callback){},calendarCapabilities:function(calendar){return{canCreateEvent:true,canUpdateEvent:true,canDeleteEvent:true};},eventCapabilities:function(event,callback){var caps=this.calendarCapabilities();nextTick(function(){callback(null,{canCreate:caps.canCreateEvent,canUpdate:caps.canUpdateEvent,canDelete:caps.canDeleteEvent});});}};});define('core',['require','exports','module'],function(require,exports,module){'use strict';exports.db=null;exports.errorController=null;exports.notificationsController=null;exports.periodicSyncController=null;exports.providerFactory=null;exports.serviceController=null;exports.storeFactory=null;exports.syncController=null;exports.timeController=null;exports.viewFactory=null;});define('common/constants',['require','exports','module'],function(require,exports){'use strict';exports.localCalendarId='local-first';});define('common/timespan',['require','exports','module'],function(require,exports,module){'use strict';function Timespan(startDate,endDate){this.start=startDate.valueOf();this.end=endDate.valueOf();} module.exports=Timespan;Timespan.prototype={isEqual:function(inputSpan){return(this.start===inputSpan.start&&this.end===inputSpan.end);},trimOverlap:function(span){if(this.contains(span)||span.contains(this)){return null;} var start=span.start;var end=span.end;var ourEnd=this.end;var ourStart=this.start;var overlapsBefore=start>=ourStart&&start=start&&ourStart=ourStart&&start=start&&ourStart=date;}else if(date instanceof Timespan){return start<=date.start&&end>=date.end;}else{return this.containsNumeric(date);}},containsNumeric:function(timestamp){var start=this.start;var end=this.end;return start<=timestamp&&end>=timestamp;}};});!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define('ext/co',[],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.co=e()}}(function(){var define,module,exports;return(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o2)res=slice.call(arguments,1);resolve(res);});});} function arrayToPromise(obj){return Promise.all(obj.map(toPromise,this));} function objectToPromise(obj){var results=new obj.constructor();var keys=Object.keys(obj);var promises=[];for(var i=0;i1){type=parts.shift();switch(type){case'd':date=new Date(parts[0],parts[1],parts[2]);break;case'm':date=new Date(parts[0],parts[1]);break;}} return date;};exports.getMonthId=function(date){return['m',date.getFullYear(),date.getMonth()].join('-');};exports.createDay=function(date,day,month,year){return new Date(year!=null?year:date.getFullYear(),month!=null?month:date.getMonth(),day!=null?day:date.getDate());};exports.endOfDay=function(date){var day=exports.createDay(date,date.getDate()+1);day.setMilliseconds(-1);return day;};exports.monthStart=function(date,diff=0){return new Date(date.getFullYear(),date.getMonth()+diff,1);};exports.dayOfWeek=function(date){var number=date;if(typeof(date)!=='number'){number=date.getDay();} return exports.dayOfWeekFromStartDay(number);};exports.getWeekStartDate=function(date){var currentDay=exports.dayOfWeek(date);var startDay=(date.getDate()-currentDay);return exports.createDay(date,startDay);};exports.getWeekEndDate=function(date){var start=exports.getWeekStartDate(date);start.setDate(start.getDate()+7);start.setMilliseconds(-1);return start;};exports.daysBetween=function(start,end,includeTime){if(start instanceof Timespan){if(end){includeTime=end;} end=new Date(start.end);start=new Date(start.start);} if(start>end){var tmp=end;end=start;start=tmp;tmp=null;} var list=[];var last=start.getDate();if(exports.isSameDate(start,end)){if(includeTime){list.push(end);}else{list.push(exports.createDay(start));} return list;} while(true){var next=new Date(start.getFullYear(),start.getMonth(),++last);if(next>end){throw new Error('sanity fails next is greater then end');} if(!exports.isSameDate(next,end)){list.push(next);continue;} break;} if(includeTime){list.unshift(start);list.push(end);}else{list.unshift(exports.createDay(start));list.push(exports.createDay(end));} return list;},exports.getWeeksDays=function(startDate){var weeksDayStart=exports.getWeekStartDate(startDate);var result=[weeksDayStart];for(var i=1;i<7;i++){result.push(exports.createDay(weeksDayStart,weeksDayStart.getDate()+i));} return result;};exports.isPast=function(date){return(date.valueOf()=refEnd;return(startBefore&&endsAfter)||Number(startDate)===Number(endDate);};if(typeof(window)!=='undefined'){window.addEventListener('localized',co.wrap(function*(){exports.startDay=yield mozIntl.calendarInfo('firstDayOfTheWeek');}));}});(function(){var _global=this;var _rng;if(typeof(_global.require)=='function'&&typeof(module)!='undefined'&&module.exports){try{var _rb=_global.require('crypto').randomBytes;_rng=_rb&&function(){return _rb(16);};}catch(e){}} if(!_rng&&_global.crypto&&crypto.getRandomValues){var _rnds8=new Uint8Array(16);_rng=function whatwgRNG(){crypto.getRandomValues(_rnds8);return _rnds8;};} if(!_rng){var _rnds=new Array(16);_rng=function(){for(var i=0,r;i<16;i++){if((i&0x03)===0)r=Math.random()*0x100000000;_rnds[i]=r>>>((i&0x03)<<3)&0xff;} return _rnds;};} var BufferClass=typeof(_global.Buffer)=='function'?_global.Buffer:Array;var _byteToHex=[];var _hexToByte={};for(var i=0;i<256;i++){_byteToHex[i]=(i+0x100).toString(16).substr(1);_hexToByte[_byteToHex[i]]=i;} function parse(s,buf,offset){var i=(buf&&offset)||0,ii=0;buf=buf||[];s.toLowerCase().replace(/[0-9a-f]{2}/g,function(oct){if(ii<16){buf[i+ii++]=_hexToByte[oct];}});while(ii<16){buf[i+ii++]=0;} return buf;} function unparse(buf,offset){var i=offset||0,bth=_byteToHex;return bth[buf[i++]]+bth[buf[i++]]+ bth[buf[i++]]+bth[buf[i++]]+'-'+ bth[buf[i++]]+bth[buf[i++]]+'-'+ bth[buf[i++]]+bth[buf[i++]]+'-'+ bth[buf[i++]]+bth[buf[i++]]+'-'+ bth[buf[i++]]+bth[buf[i++]]+ bth[buf[i++]]+bth[buf[i++]]+ bth[buf[i++]]+bth[buf[i++]];} var _seedBytes=_rng();var _nodeId=[_seedBytes[0]|0x01,_seedBytes[1],_seedBytes[2],_seedBytes[3],_seedBytes[4],_seedBytes[5]];var _clockseq=(_seedBytes[6]<<8|_seedBytes[7])&0x3fff;var _lastMSecs=0,_lastNSecs=0;function v1(options,buf,offset){var i=buf&&offset||0;var b=buf||[];options=options||{};var clockseq=options.clockseq!=null?options.clockseq:_clockseq;var msecs=options.msecs!=null?options.msecs:new Date().getTime();var nsecs=options.nsecs!=null?options.nsecs:_lastNSecs+1;var dt=(msecs-_lastMSecs)+(nsecs-_lastNSecs)/10000;if(dt<0&&options.clockseq==null){clockseq=clockseq+1&0x3fff;} if((dt<0||msecs>_lastMSecs)&&options.nsecs==null){nsecs=0;} if(nsecs>=10000){throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');} _lastMSecs=msecs;_lastNSecs=nsecs;_clockseq=clockseq;msecs+=12219292800000;var tl=((msecs&0xfffffff)*10000+nsecs)%0x100000000;b[i++]=tl>>>24&0xff;b[i++]=tl>>>16&0xff;b[i++]=tl>>>8&0xff;b[i++]=tl&0xff;var tmh=(msecs/0x100000000*10000)&0xfffffff;b[i++]=tmh>>>8&0xff;b[i++]=tmh&0xff;b[i++]=tmh>>>24&0xf|0x10;b[i++]=tmh>>>16&0xff;b[i++]=clockseq>>>8|0x80;b[i++]=clockseq&0xff;var node=options.node||_nodeId;for(var n=0;n<6;n++){b[i+n]=node[n];} return buf?buf:unparse(b);} function v4(options,buf,offset){var i=buf&&offset||0;if(typeof(options)=='string'){buf=options=='binary'?new BufferClass(16):null;options=null;} options=options||{};var rnds=options.random||(options.rng||_rng)();rnds[6]=(rnds[6]&0x0f)|0x40;rnds[8]=(rnds[8]&0x3f)|0x80;if(buf){for(var ii=0;ii<16;ii++){buf[i+ii]=rnds[ii];}} return buf||unparse(rnds);} var uuid=v4;uuid.v1=v1;uuid.v4=v4;uuid.parse=parse;uuid.unparse=unparse;uuid.BufferClass=BufferClass;if(typeof define==='function'&&define.amd){define('ext/uuid',[],function(){return uuid;});}else if(typeof(module)!='undefined'&&module.exports){module.exports=uuid;}else{var _previousRoot=_global.uuid;uuid.noConflict=function(){_global.uuid=_previousRoot;return uuid;};_global.uuid=uuid;}}).call(this);define('event_mutations',['require','exports','module','common/calc','core','ext/uuid'],function(require,exports){'use strict';var Calc=require('common/calc');var core=require('core');var uuid=require('ext/uuid');function createBusytime(event){return{_id:event._id+'-'+uuid.v4(),eventId:event._id,calendarId:event.calendarId,start:event.remote.start,end:event.remote.end};} function Create(options){if(options){for(var key in options){if(options.hasOwnProperty(key)){this[key]=options[key];}}}} Create.prototype={commit:function(callback){var storeFactory=core.storeFactory;var alarmStore=storeFactory.get('Alarm');var eventStore=storeFactory.get('Event');var busytimeStore=storeFactory.get('Busytime');var componentStore=storeFactory.get('IcalComponent');var trans=core.db.transaction(eventStore._dependentStores,'readwrite');trans.oncomplete=function commitComplete(){callback(null);};trans.onerror=function commitError(e){callback(e.target.error);};eventStore.persist(this.event,trans);if(!this.busytime){this.busytime=createBusytime(this.event);} busytimeStore.persist(this.busytime,trans);if(this.icalComponent){componentStore.persist(this.icalComponent,trans);} var alarms=this.event.remote.alarms;if(alarms&&alarms.length){var i=0;var len=alarms.length;var now=Date.now();var alarmTrans=core.db.transaction(['alarms'],'readwrite');for(;i{args.unshift(topic);this.emit.apply(this,args);});return this;},emit:function emit(){var args=Array.prototype.slice.call(arguments),event=args.shift(),eventList,self=this;if(event in this._$events){eventList=this._$events[event];eventList.forEach(function(callback){if(typeof(callback)==='object'&&callback.handleEvent){callback.handleEvent({type:event,data:args});}else{callback.apply(self,args);}});} return this;},emitWhenListener:function emitWhenListener(){var args=Array.prototype.slice.call(arguments);var event=args.shift();if(event in this._$events&&this._$events[event].length){return this.emit.apply(this,arguments);} if(!(event in this.buffer)){this.buffer[event]=[];} this.buffer[event].push(args);return this;},removeAllEventListeners:function removeAllEventListeners(name){if(name in this._$events){this._$events[name].length=0;} return this;},removeEventListener:function removeEventListener(name,callback){var i,length,events;if(!(name in this._$events)){return false;} events=this._$events[name];for(i=0,length=events.length;i{if(body){options.body=body;} options.lang=document.documentElement.getAttribute('lang');var notification=new window.Notification(title,options);if(options.closeOnClick!==false){notification.addEventListener('click',function nh_click(){notification.removeEventListener('click',nh_click);notification.close();});} return notification;});},};function getL10n(l10nAttrs){if(!l10nAttrs){return;} if(typeof l10nAttrs==='string'){return document.l10n.formatValue(l10nAttrs);} if(typeof l10nAttrs.raw==="string"){return l10nAttrs.raw;} return document.l10n.formatValue(l10nAttrs.id,l10nAttrs.args);}})(this);define("shared/notification_helper",(function(global){return function(){var ret,fn;return ret||global.NotificationHelper;};}(this)));define('performance',['require','exports','module'],function(require,exports){'use strict';exports._isMonthAgendaInteractive=false;exports._isMonthReady=false;exports._isVisuallyActive=false;exports._isPendingReady=false;var dispatched={};function dispatch(markName){dispatched[markName]=true;window.performance.mark(markName);} exports.isComplete=function(markName){return dispatched[markName];};exports.domLoaded=function(){dispatch('navigationLoaded');};exports.chromeInteractive=function(){dispatch('navigationInteractive');};exports.monthsDayReady=function(){if(exports._isMonthAgendaInteractive){return;} exports._isMonthAgendaInteractive=true;dispatchVisuallyLoadedAndInteractive();};exports.monthReady=function(){if(exports._isMonthReady){return;} exports._isMonthReady=true;dispatchVisuallyLoadedAndInteractive();};function dispatchVisuallyLoadedAndInteractive(){if(exports._isVisuallyActive||!exports._isMonthAgendaInteractive||!exports._isMonthReady){return;} exports._isVisuallyActive=true;dispatch('visuallyLoaded');dispatch('contentInteractive');dispatchAppLoad();} exports.pendingReady=function(){if(exports._isPendingReady){return;} exports._isPendingReady=true;dispatchAppLoad();};function dispatchAppLoad(){if(!exports._isVisuallyActive||!exports._isPendingReady){return;} dispatch('fullyLoaded');window.dispatchEvent(new CustomEvent('fullyLoaded'));}});!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define('ext/page',[],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.page=e()}}(function(){var define,module,exports;return(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o-1)return;if(el.target)return;if(!sameOrigin(el.href))return;var path=el.pathname+el.search+(el.hash||'');var orig=path;path=path.replace(base,'');if(base&&orig===path)return;e.preventDefault();page.show(orig);} function which(e){e=e||window.event;return null===e.which?e.button:e.which;} function sameOrigin(href){var origin=location.protocol+'//'+location.hostname;if(location.port)origin+=':'+location.port;return(href&&(0===href.indexOf(origin)));} page.sameOrigin=sameOrigin;},{"path-to-regexp":2}],2:[function(require,module,exports){module.exports=pathtoRegexp;var PATH_REGEXP=new RegExp(['(\\\\.)','([\\/.])?(?:\\:(\\w+)(?:\\(((?:\\\\.|[^)])*)\\))?|\\(((?:\\\\.|[^)])*)\\))([+*?])?','([.+*?=^!:${}()[\\]|\\/])'].join('|'),'g');function escapeGroup(group){return group.replace(/([=!:$\/()])/g,'\\$1');} var attachKeys=function(re,keys){re.keys=keys;return re;};function pathtoRegexp(path,keys,options){if(keys&&!Array.isArray(keys)){options=keys;keys=null;} keys=keys||[];options=options||{};var strict=options.strict;var end=options.end!==false;var flags=options.sensitive?'':'i';var index=0;if(path instanceof RegExp){var groups=path.source.match(/\((?!\?)/g)||[];keys.push.apply(keys,groups.map(function(match,index){return{name:index,delimiter:null,optional:false,repeat:false};}));return attachKeys(path,keys);} if(Array.isArray(path)){path=path.map(function(value){return pathtoRegexp(value,keys,options).source;});return attachKeys(new RegExp('(?:'+path.join('|')+')',flags),keys);} path=path.replace(PATH_REGEXP,function(match,escaped,prefix,key,capture,group,suffix,escape){if(escaped){return escaped;} if(escape){return'\\'+escape;} var repeat=suffix==='+'||suffix==='*';var optional=suffix==='?'||suffix==='*';keys.push({name:key||index++,delimiter:prefix||'/',optional:optional,repeat:repeat});prefix=prefix?'\\'+prefix:'';capture=escapeGroup(capture||group||'[^'+(prefix||'\\/')+']+?');if(repeat){capture=capture+'(?:'+prefix+capture+')*';} if(optional){return'(?:'+prefix+'('+capture+'))?';} return prefix+'('+capture+')';});var endsWithSlash=path[path.length-1]==='/';if(!strict){path=(endsWithSlash?path.slice(0,-2):path)+'(?:\\/(?=$))?';} if(!end){path+=strict&&endsWithSlash?'':'(?=\\/|$)';} return attachKeys(new RegExp('^'+path+(end?'$':''),flags),keys);};},{}]},{},[1])(1)});define('router',['require','exports','module','core','ext/page'],function(require,exports,module){'use strict';var COPY_METHODS=['start','stop','show'];var core=require('core');var page=require('ext/page');function Router(){var i=0;var len=COPY_METHODS.length;this.page=page;this.page({hashbang:true});this._activeObjects=[];for(;ilaunch(url);});});exports.revokeNotificationsForEvent=co.wrap(function*(event){var id=event.remote.id;var notifications=yield Notification.get();notifications.forEach(notification=>{if(notification.data.id===id){notification.close();}});});function getSelf(){if(!cachedSelf){cachedSelf=new Promise((resolve,reject)=>{var request=navigator.mozApps.getSelf();request.onsuccess=(event)=>{resolve(event.target.result);};request.onerror=()=>{reject(new Error('mozApps.getSelf failed!'));};});} return cachedSelf;} function launch(url){closeNotifications(url);if(performance.isComplete('fullyLoaded')){return foreground(url);} window.addEventListener('fullyLoaded',function onMozAppLoaded(){window.removeEventListener('fullyLoaded',onMozAppLoaded);return foreground(url);});} exports.launch=launch;function foreground(url){return getSelf().then(app=>{router.go(url);return app&&app.launch();});} function closeNotifications(url){Notification.get({tag:url}).then(notifications=>{notifications.forEach(n=>n.close());});}});define('controllers/error',['require','exports','module','common/error','common/error','common/responder','common/next_tick','notification'],function(require,exports,module){'use strict';var Authentication=require('common/error').Authentication;var InvalidServer=require('common/error').InvalidServer;var Responder=require('common/responder');var nextTick=require('common/next_tick');var notification=require('notification');function ErrorController(){Responder.call(this);this._handlers=Object.create(null);} module.exports=ErrorController;ErrorController.prototype={__proto__:Responder.prototype,accountErrorUrl:'/update-account/',dispatch:function(error){if(error instanceof Authentication||error instanceof InvalidServer){this.handleAuthenticate(error.detail.account);} this.emit('error',error);},handleAuthenticate:function(account,callback){if(!account){return console.error('attempting to trigger reauth without an account');} if(!account.error||account.error.count!==1){return nextTick(callback);} var lock=navigator.requestWakeLock('cpu');var titleL10n='notification-error-sync-title';var bodyL10n='notification-error-sync-description';var url=this.accountErrorUrl+account._id;notification.sendNotification(titleL10n,bodyL10n,url).then(()=>{callback&&callback();lock.unlock();});}};});define('pending_manager',['require','exports','module','common/next_tick'],function(require,exports,module){'use strict';var nextTick=require('common/next_tick');function PendingManager(){this.objects=[];this.pending=0;this.onstart=this.onstart.bind(this);this.onend=this.onend.bind(this);} module.exports=PendingManager;PendingManager.prototype={register:function(object){object.on(object.startEvent,this.onstart);object.on(object.completeEvent,this.onend);if(!this.isPending()&&object.pending){nextTick(()=>this.onpending&&this.onpending());} this.objects.push(object);},unregister:function(object){this.objects=this.objects.filter(el=>el!==object);},isPending:function(){return this.objects.some(object=>object.pending);},onstart:function(){if(!this.pending){this.onpending&&this.onpending();} this.pending++;},onend:function(){this.pending--;if(!this.pending){this.oncomplete&&this.oncomplete();}}};});define('controllers/recurring_events',['require','exports','module','common/responder','core','common/debug','common/next_tick'],function(require,exports,module){'use strict';var Responder=require('common/responder');var core=require('core');var debug=require('common/debug')('controllers/recurring_events');var nextTick=require('common/next_tick');function RecurringEvents(){this.accounts=core.storeFactory.get('Account');Responder.call(this);} module.exports=RecurringEvents;RecurringEvents.prototype={__proto__:Responder.prototype,startEvent:'expandStart',completeEvent:'expandComplete',paddingInDays:85,waitBeforeMove:750,maximumExpansions:25,_moveTimeout:null,pending:false,unobserve:function(){core.timeController.removeEventListener('monthChange',this);core.syncController.removeEventListener('syncComplete',this);},observe:function(){var time=core.timeController;if(time.position){this.queueExpand(time.position);} time.on('monthChange',this);core.syncController.on('syncComplete',this);},handleEvent:function(event){switch(event.type){case'syncComplete':this.queueExpand(core.timeController.position);break;case'monthChange':if(this._moveTimeout!==null){clearTimeout(this._moveTimeout);this._moveTimeout=null;} this._moveTimeout=setTimeout(this.queueExpand.bind(this,event.data[0]),this.waitBeforeMove);break;}},_expandProvider:function(expandDate,provider,callback){debug('Will attempt to expand provider until:',expandDate);var tries=0;var max=this.maximumExpansions;function attemptCompleteExpand(){debug('Will try to complete expansion (tries = '+tries+')');if(tries>=max){return callback(new Error('could not complete expansion after "'+tries+'"'));} provider.ensureRecurrencesExpanded(expandDate,function(err,didExpand){if(err){return callback(err);} debug('Expansion attempt did expand:',didExpand);if(!didExpand){callback();}else{tries++;nextTick(attemptCompleteExpand);}});} attemptCompleteExpand();},queueExpand:function(expandTo){if(this.pending){if(!this._next){this._next=expandTo;}else if(expandTo>this._next){this._next=expandTo;} return;} this.pending=true;this.emit('expandStart');var self=this;function expandNext(date){self.expand(date,function(){if(date===self._next){self._next=null;} var next=self._next;if(!next){self.pending=false;self.emit('expandComplete');return;} expandNext(next);});} expandNext(expandTo);},expand:function(expandTo,callback){debug('expand',expandTo);this.accounts.all((err,accounts)=>{if(err){return callback(err);} var expandDate=new Date(expandTo.valueOf());expandDate.setDate(expandDate.getDate()+this.paddingInDays);var providers=this._getExpandableProviders(accounts);var pending=providers.length;if(!pending){return nextTick(callback);} providers.forEach(provider=>{this._expandProvider(expandDate,provider,()=>{if(--pending<=0){callback();}});});});},_getExpandableProviders:function(accounts){var providers=[];Object.keys(accounts).forEach(key=>{var account=accounts[key];var provider=core.providerFactory.get(account.providerType);if(provider&&provider.canExpandRecurringEvents&&providers.indexOf(provider)===-1){providers.push(provider);}});return providers;}};});define('worker/manager',['require','exports','module','common/responder','common/debug'],function(require,exports,module){'use strict';var Responder=require('common/responder');var debug=require('common/debug')('worker/manager');const IDLE_CLEANUP_TIME=5000;function Manager(){this._lastId=0;Responder.call(this);this.roles=Object.create(null);this.workers=[];} module.exports=Manager;Manager.prototype={Worker:Worker,__proto__:Responder.prototype,_onLog:debug,_formatData:function(data){if(data[1]&&data[1].stack&&data[1].constructorName){var err=data[1];var builtErr;if(window[err.constructorName]){builtErr=Object.create(window[err.constructorName].prototype);}else{builtErr=Object.create(Error.prototype);} var key;for(key in err){if(err.hasOwnProperty(key)){builtErr[key]=err[key];}} data[1]=builtErr;} return data;},_onWorkerError:function(worker,err){if(/reference to undefined property/.test(err.message)){return;} if(worker.instance){worker.instance.terminate();worker.instance=null;} var pending=worker.pending;worker.pending=Object.create(null);for(var id in pending){if(pending[id].stream){pending[id].stream.emit('error',err);} pending[id].callback(err);}},_onWorkerMessage:function(worker,event){var data=this._formatData(event.data);var type=data.shift();var match=type.match(/^(\d+) (end|stream)$/);if(type=='log'){this._onLog.apply(this,data);}else if(match){var pending=worker.pending[match[1]];if(pending){this._dispatchMessage(worker,pending,match[2],data);}else{throw new Error('Message arrived for unknown consumer: '+ type+' '+JSON.stringify(data));}}else{this.respond([type].concat(data));}},_dispatchMessage:function(worker,pending,type,data){if(type=='stream'){pending.stream.respond(data);}else{pending.callback.apply(null,data);delete worker.pending[pending.id];if(Object.keys(worker.pending).length){return;} this._scheduleCleanup(worker);}},_addPending:function(worker,pending){worker.pending[pending.id]=pending;clearTimeout(worker.cleanup);},_scheduleCleanup:function(worker){clearTimeout(worker.cleanup);worker.cleanup=setTimeout(function(){if(Object.keys(worker.pending).length){return;} if(!worker.instance){return;} worker.instance.terminate();worker.instance=null;},IDLE_CLEANUP_TIME);},add:function(role,workerURL){debug('Will add',role,'worker at',workerURL);var worker={instance:null,pending:Object.create(null),url:workerURL,cleanup:null};this.workers.push(worker);[].concat(role).forEach(function(role){if(!(role in this.roles)){this.roles[role]=[worker];}else{this.roles[role].push(worker);}},this);},_ensureActiveWorker:function(role){if(role in this.roles){var workers=this.roles[role];var worker=workers[Math.floor(Math.random()*workers.length)];if(worker.instance){return worker;}else{this._startWorker(worker);return worker;}}else{throw new Error('no worker with role "'+role+'" active');}},_startWorker:function(worker){worker.instance=new this.Worker(worker.url+'?time='+Date.now());worker.instance.onerror=this._onWorkerError.bind(this,worker);worker.instance.onmessage=this._onWorkerMessage.bind(this,worker);this._scheduleCleanup(worker);},request:function(role){var args=Array.prototype.slice.call(arguments,1);var callback=args.pop();var worker=null;try{worker=this._ensureActiveWorker(role);}catch(e){callback(e);return;} var data={id:this._lastId++,role:role,payload:args};this._addPending(worker,{id:data.id,callback:callback});worker.instance.postMessage(['_dispatch',data]);},stream:function(role){var args=Array.prototype.slice.call(arguments,1);var stream=new Responder();var self=this;var data={id:this._lastId++,role:role,payload:args,type:'stream'};stream.request=function(callback){var worker=null;stream.request=function(){throw new Error('stream request has been sent');};try{worker=self._ensureActiveWorker(role);}catch(e){callback(e);return;} self._addPending(worker,{id:data.id,stream:stream,callback:callback});worker.instance.postMessage(['_dispatch',data]);};return stream;}};});define('controllers/service',['require','exports','module','worker/manager','common/debug'],function(require,exports,module){'use strict';var Manager=require('worker/manager');var debug=require('common/debug')('controllers/service');function Service(){Manager.call(this);} module.exports=Service;Service.prototype={__proto__:Manager.prototype,start:function(){debug('Will load and initialize worker...');this.add('caldav','/js/caldav_worker.js');}};});define('common/is_offline',['require','exports','module'],function(require,exports,module){'use strict';module.exports=function(){return(navigator&&'onLine'in navigator)?!navigator.onLine:true;};});define('controllers/sync',['require','exports','module','common/responder','core','common/is_offline'],function(require,exports,module){'use strict';var Responder=require('common/responder');var core=require('core');var isOffline=require('common/is_offline');function Sync(){this.pending=0;Responder.call(this);} module.exports=Sync;Sync.prototype={__proto__:Responder.prototype,startEvent:'syncStart',completeEvent:'syncComplete',_incrementPending:function(){if(!this.pending){this.emit('syncStart');} this.pending++;},_resolvePending:function(){if(!(--this.pending)){this.emit('syncComplete');} if(this.pending<0){dump('\n\n Error calendar sync .pending is < 0 \n\n');}},all:function(callback){if(callback){this.once('syncComplete',callback);} if(isOffline()){this.emit('offline');this.emit('syncComplete');return;} var account=core.storeFactory.get('Account');account.all(function(err,list){for(var key in list){this.account(list[key]);} if(!this.pending){this.emit('syncComplete');}}.bind(this));},calendar:function(account,calendar,callback){var store=core.storeFactory.get('Calendar');var self=this;this._incrementPending();store.sync(account,calendar,err=>{self._resolvePending();this.handleError(err,callback);});},account:function(account,callback){var storeFactory=core.storeFactory;var accountStore=storeFactory.get('Account');var calendarStore=storeFactory.get('Calendar');var self=this;this._incrementPending();accountStore.sync(account,err=>{if(err){self._resolvePending();return this.handleError(err,callback);} var pending=0;function next(){if(!(--pending)){self._resolvePending();if(callback){callback();}}} function fetchCalendars(err,calendars){if(err){self._resolvePending();return self.handleError(err,callback);} for(var key in calendars){pending++;self.calendar(account,calendars[key],next);}} calendarStore.remotesByAccount(account._id,fetchCalendars);});},handleError:function(err,callback){if(callback){return callback(err);} core.errorController.dispatch(err);}};});define('controllers/time',['require','exports','module','common/calc','common/responder'],function(require,exports,module){'use strict';var isSameDate=require('common/calc').isSameDate;var Responder=require('common/responder');function Time(){Responder.call(this);this._timeCache=Object.create(null);} module.exports=Time;Time.prototype={__proto__:Responder.prototype,_position:null,_currentTimespan:null,_timeCache:null,_scale:null,_mostRecentDayType:'day',cacheLocked:false,get mostRecentDayType(){return this._mostRecentDayType;},get mostRecentDay(){if(this.mostRecentDayType==='selectedDay'){return this.selectedDay;}else{return this.position;}},get timespan(){return this._currentTimespan;},get scale(){return this._scale;},set scale(value){var oldValue=this._scale;if(value!==oldValue){this._scale=value;this.emit('scaleChange',value,oldValue);}},get selectedDay(){return this._selectedDay;},set selectedDay(value){var day=this._selectedDay;this._mostRecentDayType='selectedDay';if(!day||!isSameDate(day,value)){this._selectedDay=value;this.emit('selectedDayChange',value,day);}},moveToMostRecentDay:function(){if(this.mostRecentDayType==='selectedDay'){this.move(this.selectedDay);}},_updateCache:function(type,value){var old=this._timeCache[type];if(!old||!isSameDate(value,old)){this._timeCache[type]=value;this.emit(type+'Change',value,old);}},get month(){return this._timeCache.month;},get day(){return this._timeCache.day;},get year(){return this._timeCache.year;},get position(){return this._position;},move:function(date){var year=date.getFullYear();var month=date.getMonth();var yearDate=new Date(year,0,1);var monthDate=new Date(year,month,1);this._position=date;this._mostRecentDayType='day';this._updateCache('year',yearDate);this._updateCache('month',monthDate);this._updateCache('day',date);}};});define('common/async_require',['require','exports','module'],function(require,exports,module){'use strict';module.exports=function(ids){if(!Array.isArray(ids)){ids=[ids];} var requireFn=window.requirejs||window.require||require;return new Promise((resolve,reject)=>requireFn(ids,resolve,reject));};});;!function(undefined){var isArray=Array.isArray?Array.isArray:function _isArray(obj){return Object.prototype.toString.call(obj)==="[object Array]";};var defaultMaxListeners=10;function init(){this._events={};if(this._conf){configure.call(this,this._conf);}} function configure(conf){if(conf){this._conf=conf;conf.delimiter&&(this.delimiter=conf.delimiter);conf.maxListeners&&(this._events.maxListeners=conf.maxListeners);conf.wildcard&&(this.wildcard=conf.wildcard);conf.newListener&&(this.newListener=conf.newListener);if(this.wildcard){this.listenerTree={};}}} function EventEmitter(conf){this._events={};this.newListener=false;configure.call(this,conf);} function searchListenerTree(handlers,type,tree,i){if(!tree){return[];} var listeners=[],leaf,len,branch,xTree,xxTree,isolatedBranch,endReached,typeLength=type.length,currentType=type[i],nextType=type[i+1];if(i===typeLength&&tree._listeners){if(typeof tree._listeners==='function'){handlers&&handlers.push(tree._listeners);return[tree];}else{for(leaf=0,len=tree._listeners.length;leaf0&&tree._listeners.length>m){tree._listeners.warned=true;console.error('(node) warning: possible EventEmitter memory '+'leak detected. %d listeners added. '+'Use emitter.setMaxListeners() to increase limit.',tree._listeners.length);console.trace();}}} return true;} name=type.shift();} return true;} EventEmitter.prototype.delimiter='.';EventEmitter.prototype.setMaxListeners=function(n){this._events||init.call(this);this._events.maxListeners=n;if(!this._conf)this._conf={};this._conf.maxListeners=n;};EventEmitter.prototype.event='';EventEmitter.prototype.once=function(event,fn){this.many(event,1,fn);return this;};EventEmitter.prototype.many=function(event,ttl,fn){var self=this;if(typeof fn!=='function'){throw new Error('many only accepts instances of Function');} function listener(){if(--ttl===0){self.off(event,listener);} fn.apply(this,arguments);} listener._origin=fn;this.on(event,listener);return self;};EventEmitter.prototype.emit=function(){this._events||init.call(this);var type=arguments[0];if(type==='newListener'&&!this.newListener){if(!this._events.newListener){return false;}} if(this._all){var l=arguments.length;var args=new Array(l-1);for(var i=1;i1) switch(arguments.length){case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:var l=arguments.length;var args=new Array(l-1);for(var i=1;i0)||!!this._all;} else{return!!this._all;}};EventEmitter.prototype.on=function(type,listener){if(typeof type==='function'){this.onAny(type);return this;} if(typeof listener!=='function'){throw new Error('on only accepts instances of Function');} this._events||init.call(this);this.emit('newListener',type,listener);if(this.wildcard){growListenerTree.call(this,type,listener);return this;} if(!this._events[type]){this._events[type]=listener;} else if(typeof this._events[type]==='function'){this._events[type]=[this._events[type],listener];} else if(isArray(this._events[type])){this._events[type].push(listener);if(!this._events[type].warned){var m=defaultMaxListeners;if(typeof this._events.maxListeners!=='undefined'){m=this._events.maxListeners;} if(m>0&&this._events[type].length>m){this._events[type].warned=true;console.error('(node) warning: possible EventEmitter memory '+'leak detected. %d listeners added. '+'Use emitter.setMaxListeners() to increase limit.',this._events[type].length);console.trace();}}} return this;};EventEmitter.prototype.onAny=function(fn){if(typeof fn!=='function'){throw new Error('onAny only accepts instances of Function');} if(!this._all){this._all=[];} this._all.push(fn);return this;};EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prototype.off=function(type,listener){if(typeof listener!=='function'){throw new Error('removeListener only takes instances of Function');} var handlers,leafs=[];if(this.wildcard){var ns=typeof type==='string'?type.split(this.delimiter):type.slice();leafs=searchListenerTree.call(this,null,ns,this.listenerTree,0);} else{if(!this._events[type])return this;handlers=this._events[type];leafs.push({_listeners:handlers});} for(var iLeaf=0;iLeaf0){fns=this._all;for(i=0,l=fns.length;i0){low=mid+1;}else{return mid;}} return null;};exports.insert=function(list,seekVal,cmpfunc){if(!list.length){return 0;} var low=0,high=list.length-1,mid,cmpval;while(low<=high){mid=low+Math.floor((high-low)/2);cmpval=cmpfunc(seekVal,list[mid]);if(cmpval<0){high=mid-1;}else if(cmpval>0){low=mid+1;}else{break;}} if(cmpval<0){return mid;}else if(cmpval>0){return mid+1;}else{return mid;}};});define('common/compare',['require','exports','module'],function(require,exports,module){'use strict';module.exports=function(a,b){if(a>b){return 1;} if(amax?max:val);};exports.round=function round(value,radix){radix=radix||1;return Math.round(value/radix)*radix;};exports.floor=function floor(val,step){step=Math.abs(step||1);return Math.floor(val/step)*step;};exports.ceil=function ceil(val,step){step=Math.abs(step||1);return Math.ceil(val/step)*step;};exports.lerp=function lerp(ratio,start,end){return start+(end-start)*ratio;};exports.debounce=function debounce(fn,threshold,isAsap){var timeout,result;function debounced(){var args=arguments,context=this;function delayed(){if(!isAsap){result=fn.apply(context,args);} timeout=null;} if(timeout){clearTimeout(timeout);}else if(isAsap){result=fn.apply(context,args);} timeout=setTimeout(delayed,threshold);return result;} debounced.cancel=function(){clearTimeout(timeout);};return debounced;};exports.throttle=function throttle(fn,delay){var context,timeout,result,args,diff,prevCall=0;function delayed(){prevCall=Date.now();timeout=null;result=fn.apply(context,args);} function throttled(){context=this;args=arguments;diff=delay-(Date.now()-prevCall);if(diff<=0){clearTimeout(timeout);delayed();}else if(!timeout){timeout=setTimeout(delayed,diff);} return result;} throttled.cancel=function(){clearTimeout(timeout);};return throttled;};});define('day_observer',['require','exports','module','common/calc','ext/eventemitter2','common/binsearch','common/compare','core','utils/mout'],function(require,exports){'use strict';var Calc=require('common/calc');var EventEmitter2=require('ext/eventemitter2');var binsearch=require('common/binsearch');var compare=require('common/compare');var core=require('core');var daysBetween=Calc.daysBetween;var debounce=require('utils/mout').debounce;var getDayId=Calc.getDayId;var isAllDay=Calc.isAllDay;var spanOfMonth=Calc.spanOfMonth;var DISPATCH_DELAY=25;var MAX_CACHED_MONTHS=5;var busytimes=new Map();var events=new Map();var eventsToBusytimes=new Map();var cache=new Map();var dayQueue=new Set();var cachedSpans=[];var cacheLocked=false;var emitter=exports.emitter=new EventEmitter2();exports.init=function(){var eventStore=core.storeFactory.get('Event');eventStore.on('persist',(id,event)=>cacheEvent(event));eventStore.on('remove',removeEventById);var busytimeStore=core.storeFactory.get('Busytime');busytimeStore.on('persist',(id,busy)=>cacheBusytime(busy));busytimeStore.on('remove',removeBusytimeById);core.syncController.on('syncStart',()=>{cacheLocked=true;});core.syncController.on('syncComplete',()=>{cacheLocked=false;pruneCache();dispatch();});var calendarStore=core.storeFactory.get('Calendar');calendarStore.on('calendarVisibilityChange',(id,calendar)=>{var type=calendar.localDisplayed?'add':'remove';busytimes.forEach((busy,busyId)=>{if(busy.calendarId===id){registerBusytimeChange(busyId,type);}});});core.timeController.on('monthChange',loadMonth);var month=core.timeController.month;if(month){loadMonth(month);}};exports.on=function(date,callback){var dayId=getDayId(date);callback(getDay(dayId,date));emitter.on(dayId,callback);};function getDay(dayId,date){if(cache.has(dayId)){return cache.get(dayId);} var day={dayId:dayId,date:date,amount:0,basic:[],allday:[]};cache.set(dayId,day);return day;} exports.off=function(date,callback){emitter.off(getDayId(date),callback);};exports.removeAllListeners=function(){emitter.removeAllListeners();};exports.findAssociated=function(busytimeId){return queryBusytime(busytimeId).then(busytime=>{return queryEvent(busytime.eventId).then(event=>{return{busytime:busytime,event:event};});});};function queryBusytime(busytimeId){if(busytimes.has(busytimeId)){return Promise.resolve(busytimes.get(busytimeId));} var busytimeStore=core.storeFactory.get('Busytime');return busytimeStore.get(busytimeId);} function queryEvent(eventId){if(events.has(eventId)){return Promise.resolve(events.get(eventId));} var eventStore=core.storeFactory.get('Event');return eventStore.get(eventId);} function cacheBusytime(busy){var{_id,startDate,endDate,eventId}=busy;if(outsideSpans(startDate)&&outsideSpans(endDate)){return;} busytimes.set(_id,busy);eventsToBusytimes.get(eventId).push(_id);registerBusytimeChange(_id);} function removeBusytimeById(id){var busy=busytimes.get(id);if(!busy){return;} var eventId=busy.eventId;var ids=eventsToBusytimes.get(eventId).filter(i=>i!==id);eventsToBusytimes.set(eventId,ids);removeEventIfNoBusytimes(ids,eventId);registerBusytimeChange(id,'remove');busytimes.delete(id);} function cacheEvent(event){var id=event._id;events.set(id,event);if(!eventsToBusytimes.has(id)){eventsToBusytimes.set(id,[]);}} function removeEventById(id){events.delete(id);eventsToBusytimes.delete(id);} function registerBusytimeChange(id,type){var busy=busytimes.get(id);var{startDate,endDate}=busy;var end=new Date(endDate.getTime()-1);var calendarStore=core.storeFactory.get('Calendar');var isRemove=type==='remove'||!calendarStore.shouldDisplayCalendar(busy.calendarId);daysBetween(startDate,end).forEach(date=>{if(outsideSpans(date)){return;} var dayId=getDayId(date);if(isRemove&&!cache.has(dayId)){return;} var day=getDay(dayId,date);day.basic=day.basic.filter(r=>r.busytime._id!==id);day.allday=day.allday.filter(r=>r.busytime._id!==id);if(!isRemove){var group=isAllDay(date,startDate,endDate)?day.allday:day.basic;sortedInsert(group,busy);} day.amount=day.basic.length+day.allday.length;dayQueue.add(dayId);});dispatch();} function sortedInsert(group,busy){var index=binsearch.insert(group,busy.startDate,(date,record)=>{return compare(date,record.busytime.startDate);});var event=events.get(busy.eventId);var calendarStore=core.storeFactory.get('Calendar');group.splice(index,0,{event:event,busytime:busy,color:calendarStore.getColorByCalendarId(event.calendarId)});} var dispatch=debounce(function(){dayQueue.forEach(id=>{dayQueue.delete(id);if(cache.has(id)){emitter.emit(id,cache.get(id));}});},DISPATCH_DELAY);function loadMonth(newMonth){var span=spanOfMonth(newMonth);var toLoad=span;cachedSpans.every(cached=>toLoad=cached.trimOverlap(toLoad));if(!toLoad){return;} cachedSpans.push(span);var busytimeStore=core.storeFactory.get('Busytime');busytimeStore.loadSpan(toLoad,onBusytimeSpanLoad);} function onBusytimeSpanLoad(err,busytimes){if(err){console.error('Error loading Busytimes from TimeSpan:',err.toString());return;} var eventIds=Array.from(new Set(busytimes.map(b=>b.eventId).filter(id=>!events.has(id))));var eventStore=core.storeFactory.get('Event');eventStore.findByIds(eventIds).then(events=>{Object.keys(events).forEach(key=>cacheEvent(events[key]));busytimes.forEach(cacheBusytime);pruneCache();});} function pruneCache(){if(cacheLocked){return;} trimCachedSpans();cache.forEach(removeDayFromCacheIfOutsideSpans);eventsToBusytimes.forEach(removeEventIfNoBusytimes);} function trimCachedSpans(){while(cachedSpans.length>MAX_CACHED_MONTHS){var baseDate=core.timeController.month;var maxDiff=0;var maxDiffIndex=0;cachedSpans.forEach((span,i)=>{var diff=Math.abs(span.start-baseDate);if(diff>maxDiff){maxDiff=diff;maxDiffIndex=i;}});cachedSpans.splice(maxDiffIndex,1);}} function removeDayFromCacheIfOutsideSpans(day,id){if(outsideSpans(day.date)){day.basic.forEach(removeRecordIfOutsideSpans);day.allday.forEach(removeRecordIfOutsideSpans);cache.delete(id);}} function outsideSpans(date){return!cachedSpans.some(timespan=>timespan.contains(date));} function removeRecordIfOutsideSpans(record){removeBusytimeIfOutsideSpans(record.busytime);} function removeBusytimeIfOutsideSpans(busytime){var{_id,startDate,endDate}=busytime;if(outsideSpans(startDate)&&outsideSpans(endDate)){removeBusytimeById(_id);}} function removeEventIfNoBusytimes(ids,eventId){if(!ids.length){removeEventById(eventId);}}});define('common/object',['require','exports','module'],function(require,exports,module){'use strict';exports.filter=function(obj,fn,thisArg){var results=[];exports.forEach(obj,function(key,value){if(fn.call(thisArg,key,value)){results.push(value);}});return results;};exports.forEach=function(obj,fn,thisArg){exports.map(obj,fn,thisArg);};exports.map=function(obj,fn,thisArg){var results=[];Object.keys(obj).forEach((key)=>{var value=obj[key];var result=fn.call(thisArg,key,value);results.push(result);});return results;};exports.values=function(obj){return exports.map(obj,(key,value)=>{return value;});};});define('bridge',['require','exports','module','ext/eventemitter2','ext/co','core','day_observer','common/next_tick','common/object'],function(require,exports){'use strict';var EventEmitter2=require('ext/eventemitter2');var co=require('ext/co');var core=require('core');var dayObserver=require('day_observer');var nextTick=require('common/next_tick');var object=require('common/object');exports.fetchRecord=function(busytimeId){return co(function*(){var record=yield dayObserver.findAssociated(busytimeId);var eventStore=core.storeFactory.get('Event');var owners=yield eventStore.ownersOf(record.event);var provider=core.providerFactory.get(owners.account.providerType);var capabilities=yield provider.eventCapabilities(record.event);record.calendar=owners.calendar;record.account=owners.account;record.capabilities=capabilities;return record;});};exports.observeCalendars=function(){var stream=new FakeClientStream();var calendarStore=core.storeFactory.get('Calendar');var getAllAndWrite=co.wrap(function*(){var calendars=yield calendarStore.all();var data=yield object.map(calendars,co.wrap(function*(id,calendar){var caps;try{var provider=yield calendarStore.providerFor(calendar);caps=provider.calendarCapabilities(calendar);}catch(error){console.error(error);return false;} return{calendar:calendar,capabilities:caps};}));stream.write(data.filter(element=>!!element));});calendarStore.on('add',getAllAndWrite);calendarStore.on('remove',getAllAndWrite);calendarStore.on('update',getAllAndWrite);stream.cancel=function(){calendarStore.off('add',getAllAndWrite);calendarStore.off('remove',getAllAndWrite);calendarStore.off('update',getAllAndWrite);stream._cancel();};nextTick(getAllAndWrite);return stream;};exports.updateCalendar=function(calendar){var calendarStore=core.storeFactory.get('Calendar');return calendarStore.persist(calendar);};exports.createEvent=function(event){return persistEvent(event,'create','canCreate');};exports.updateEvent=function(event){return persistEvent(event,'update','canUpdate');};exports.deleteEvent=function(event){return persistEvent(event,'delete','canDelete');};var persistEvent=co.wrap(function*(event,action,capability){event=event.data||event;try{var eventStore=core.storeFactory.get('Event');var provider=yield eventStore.providerFor(event);var caps=yield provider.eventCapabilities(event);if(!caps[capability]){return Promise.reject(new Error(`Can't ${action} event`));} return provider[action+'Event'](event);}catch(err){console.error(`${action} Error for event "${event._id}" `+`on calendar "${event.calendarId}"`);console.error(err);return Promise.reject(err);}});exports.getSetting=function(id){var settingStore=core.storeFactory.get('Setting');return settingStore.getValue(id);};exports.setSetting=function(id,value){var settingStore=core.storeFactory.get('Setting');return settingStore.set(id,value);};exports.observeSetting=function(id){var stream=new FakeClientStream();var settingStore=core.storeFactory.get('Setting');var writeOnChange=function(value){stream.write(value);};settingStore.on(`${id}Change`,writeOnChange);stream.cancel=function(){settingStore.off(`${id}Change`,writeOnChange);stream._cancel();};exports.getSetting(id).then(writeOnChange);return stream;};exports.getAccount=function(id){var accountStore=core.storeFactory.get('Account');return accountStore.get(id);};exports.deleteAccount=function(id){var accountStore=core.storeFactory.get('Account');return accountStore.remove(id);};exports.createAccount=co.wrap(function*(model){var storeFactory=core.storeFactory;var accountStore=storeFactory.get('Account');var calendarStore=storeFactory.get('Calendar');var[,result]=yield accountStore.verifyAndPersist(model);yield accountStore.sync(result);var calendars=yield calendarStore.remotesByAccount(result._id);for(var key in calendars){core.syncController.calendar(result,calendars[key]);} return result;});exports.observeAccounts=function(){var stream=new FakeClientStream();var accountStore=core.storeFactory.get('Account');var getAllAndWrite=co.wrap(function*(){try{var accounts=yield accountStore.all();var data=object.map(accounts,(id,account)=>{return{account:account,provider:core.providerFactory.get(account.providerType)};});stream.write(data);}catch(err){console.error(`Error fetching accounts: ${err.message}`);}});accountStore.on('add',getAllAndWrite);accountStore.on('remove',getAllAndWrite);accountStore.on('update',getAllAndWrite);stream.cancel=function(){accountStore.off('add',getAllAndWrite);accountStore.off('remove',getAllAndWrite);accountStore.off('update',getAllAndWrite);stream._cancel();};nextTick(getAllAndWrite);return stream;};exports.observeDay=function(date){var stream=new FakeClientStream();var emit=stream.write.bind(stream);stream.cancel=function(){dayObserver.off(date,emit);stream._cancel();};nextTick(()=>dayObserver.on(date,emit));return stream;};exports.availablePresets=function(presetList){var accountStore=core.storeFactory.get('Account');return accountStore.availablePresets(presetList);};function FakeClientStream(){this._emitter=new EventEmitter2();this._enabled=true;} FakeClientStream.prototype.write=function(data){this._enabled&&this._emitter.emit('data',data);};FakeClientStream.prototype.listen=function(callback){this._enabled&&this._emitter.on('data',callback);};FakeClientStream.prototype.unlisten=function(callback){this._enabled&&this._emitter.off('data',callback);};FakeClientStream.prototype._cancel=function(){this._emitter.removeAllListeners();this._enabled=false;};});(function(global){'use strict';const helperCache=new Map();const knownObjects={datetime:{create:function(options){const customOptions=Object.assign({},options);if(options.hour){customOptions.hour12=navigator.mozHour12;} return Intl.DateTimeFormat(navigator.languages,customOptions);},isAffected:function(obj,reason){if(['languagechange','moztimechange'].includes(reason)){return true;} if(reason==='timeformatchange'){return'hour'in obj.options;} return false;}},mozdatetime:{create:function(options){const customOptions=Object.assign({},options);if(options.hour){customOptions.hour12=navigator.mozHour12;} return mozIntl.DateTimeFormat(navigator.languages,customOptions);},isAffected:function(obj,reason){if(['languagechange','moztimechange'].includes(reason)){return true;} if(reason==='timeformatchange'){return'hour'in obj.options;} return false;}},mozduration:{create:function(options){return mozIntl.DurationFormat(navigator.languages,options);},isAffected:function(obj,reason){return reason==='languagechange';}},number:{create:function(options){return Intl.NumberFormat(navigator.languages,options);},isAffected:function(obj,reason){return reason==='languagechange';}},collator:{create:function(options){return Intl.Collator(navigator.languages,options);},isAffected:function(obj,reason){return reason==='languagechange';}},};global.IntlHelper={define:function(name,type,options){if(!knownObjects.hasOwnProperty(type)){throw new Error('Unknown type: '+type);} if(helperCache.has(name)){throw new Error('Intl Object with name "'+name+'" already exists');} helperCache.set(name,{options,type,intlObject:undefined,listeners:new Set()});},get:function(name){if(!helperCache.has(name)){throw new Error('Intl Object with name "'+name+'" is not defined');} const obj=helperCache.get(name);if(!knownObjects.hasOwnProperty(obj.type)){throw new Error('Unknown type: '+obj.type);} if(obj.intlObject===undefined){obj.intlObject=knownObjects[obj.type].create(obj.options);} return obj.intlObject;},observe:function(names,cb){if(typeof names==='string'){names=[names];} for(var name of names){if(!helperCache.has(name)){throw new Error('Intl Object with name "'+name+'" is not defined');} const obj=helperCache.get(name);obj.listeners.add(cb);}},unobserve:function(name,cb){const obj=helperCache.get(name);obj.listeners.delete(cb);},_fireObservers:function(affectedObjects,...args){const affectedCallbacks=new Set();affectedObjects.forEach(obj=>obj.listeners.forEach(cb=>affectedCallbacks.add(cb)));affectedCallbacks.forEach(cb=>{try{cb(...args);}catch(e){console.error('Error in callback: '+e.toString());console.error(e.stack);}});},handleEvent:function(evt){const affectedObjects=resetObjects(evt.type);if(evt.type==='languagechange'&&navigator.mozL10n){waitOnDOMLocalized(()=>global.IntlHelper._fireObservers(affectedObjects));}else{global.IntlHelper._fireObservers(affectedObjects);}},_resetObjectCache:function(){helperCache.clear();}};function waitOnDOMLocalized(cb){const resolver=()=>{document.removeEventListener('DOMRetranslated',resolver);window.removeEventListener('localized',resolver);cb();};document.addEventListener('DOMRetranslated',resolver,false);window.addEventListener('localized',resolver,false);} function resetObjects(reason){const affectedObjects=new Set();helperCache.forEach((obj,name)=>{if(knownObjects[obj.type].isAffected(obj,reason)){obj.intlObject=undefined;affectedObjects.add(obj);}});return affectedObjects;} window.addEventListener('timeformatchange',global.IntlHelper,false);window.addEventListener('languagechange',global.IntlHelper,false);window.addEventListener('moztimechange',global.IntlHelper,false);})(this);define("shared/intl_helper",(function(global){return function(){var ret,fn;return ret||global.IntlHelper;};}(this)));define('date_l10n',['require','exports','module','shared/intl_helper'],function(require,exports){'use strict';var IntlHelper=require('shared/intl_helper');exports.init=function(){window.addEventListener('localized',exports._localizeElements);window.addEventListener('timeformatchange',exports._localizeElements);};exports._localizeElements=function(){var elements=document.querySelectorAll('[data-l10n-date-format]');for(var i=0;i