;var _createClass=(function(){function defineProperties(target,props){for(var i=0;ilistener.apply(this,args));} if(listeners[type]){listeners[type].slice().forEach(listener=>listener.apply(this,args));}} function addEventListener(listeners,type,listener){if(!(type in listeners)){listeners[type]=[];} listeners[type].push(listener);} function removeEventListener(listeners,type,listener){const typeListeners=listeners[type];const pos=typeListeners.indexOf(listener);if(pos===-1){return;} typeListeners.splice(pos,1);} let Client=(function(){function Client(remote){_classCallCheck(this,Client);this.id=this;this.remote=remote;const listeners={};this.on=(...args)=>addEventListener(listeners,...args);this.emit=(...args)=>emit(listeners,...args);} _createClass(Client,[{key:'method',value:function method(name,...args){return this.remote[name](...args);}}]);return Client;})();function broadcast(type,data){Array.from(this.ctxs.keys()).forEach(client=>client.emit(type,data));} function L10nError(message,id,lang){this.name='L10nError';this.message=message;this.id=id;this.lang=lang;} L10nError.prototype=Object.create(Error.prototype);L10nError.prototype.constructor=L10nError;function load(type,url){return new Promise(function(resolve,reject){const xhr=new XMLHttpRequest();if(xhr.overrideMimeType){xhr.overrideMimeType(type);} xhr.open('GET',url,true);if(type==='application/json'){xhr.responseType='json';} xhr.addEventListener('load',function io_onload(e){if(e.target.status===200||e.target.status===0){resolve(e.target.response||e.target.responseText);}else{reject(new L10nError('Not found: '+url));}});xhr.addEventListener('error',reject);xhr.addEventListener('timeout',reject);try{xhr.send(null);}catch(e){if(e.name==='NS_ERROR_FILE_NOT_FOUND'){reject(new L10nError('Not found: '+url));}else{throw e;}}});} const io={extra:function(code,ver,path,type){return navigator.mozApps.getLocalizationResource(code,ver,path,type);},app:function(code,ver,path,type){switch(type){case'text':return load('text/plain',path);case'json':return load('application/json',path);default:throw new L10nError('Unknown file type: '+type);}}};function fetchResource(res,{code,src,ver}){const url=res.replace('{locale}',code);const type=res.endsWith('.json')?'json':'text';return io[src](code,ver,url,type);} const KNOWN_MACROS=['plural'];const MAX_PLACEABLE_LENGTH=2500;const FSI='⁨';const PDI='⁩';const resolutionChain=new WeakSet();function format(ctx,lang,args,entity){if(typeof entity==='string'){return[{},entity];} if(resolutionChain.has(entity)){throw new L10nError('Cyclic reference detected');} resolutionChain.add(entity);let rv;try{rv=resolveValue({},ctx,lang,args,entity.value,entity.index);}finally{resolutionChain.delete(entity);} return rv;} function resolveIdentifier(ctx,lang,args,id){if(KNOWN_MACROS.indexOf(id)>-1){return[{},ctx._getMacro(lang,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==='__proto__'){throw new L10nError('Illegal id: '+id);} const entity=ctx._getEntity(lang,id);if(entity){return format(ctx,lang,args,entity);} throw new L10nError('Unknown reference: '+id);} function subPlaceable(locals,ctx,lang,args,id){let newLocals,value;try{[newLocals,value]=resolveIdentifier(ctx,lang,args,id);}catch(err){return[{error:err},FSI+'{{ '+id+' }}'+PDI];} if(typeof value==='number'){const formatter=ctx._getNumberFormatter(lang);return[newLocals,formatter.format(value)];} 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+')');} return[newLocals,FSI+value+PDI];} return[{},FSI+'{{ '+id+' }}'+PDI];} function interpolate(locals,ctx,lang,args,arr){return arr.reduce(function([localsSeq,valueSeq],cur){if(typeof cur==='string'){return[localsSeq,valueSeq+cur];}else{const[,value]=subPlaceable(locals,ctx,lang,args,cur.name);return[localsSeq,valueSeq+value];}},[locals,'']);} function resolveSelector(ctx,lang,args,expr,index){let selectorName;if(index[0].type==='call'&&index[0].expr.type==='prop'&&index[0].expr.expr.name==='cldr'){selectorName='plural';}else{selectorName=index[0].name;} const selector=resolveIdentifier(ctx,lang,args,selectorName)[1];if(typeof selector!=='function'){return selector;} const argValue=index[0].args?resolveIdentifier(ctx,lang,args,index[0].args[0].name)[1]:undefined;if(selectorName==='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,ctx,lang,args,expr,index){if(!expr){return[locals,expr];} if(typeof expr==='string'||typeof expr==='boolean'||typeof expr==='number'){return[locals,expr];} if(Array.isArray(expr)){return interpolate(locals,ctx,lang,args,expr);} if(index){const selector=resolveSelector(ctx,lang,args,expr,index);if(selector in expr){return resolveValue(locals,ctx,lang,args,expr[selector]);}} const defaultKey=expr.__default||'other';if(defaultKey in expr){return resolveValue(locals,ctx,lang,args,expr[defaultKey]);} throw new L10nError('Unresolvable value');} const locales2rules={'af':3,'ak':4,'am':4,'ar':1,'asa':3,'az':0,'be':11,'bem':3,'bez':3,'bg':3,'bh':4,'bm':0,'bn':3,'bo':0,'br':20,'brx':3,'bs':11,'ca':3,'cgg':3,'chr':3,'cs':12,'cy':17,'da':3,'de':3,'dv':3,'dz':0,'ee':3,'el':3,'en':3,'eo':3,'es':3,'et':3,'eu':3,'fa':0,'ff':5,'fi':3,'fil':4,'fo':3,'fr':5,'fur':3,'fy':3,'ga':8,'gd':24,'gl':3,'gsw':3,'gu':3,'guw':4,'gv':23,'ha':3,'haw':3,'he':2,'hi':4,'hr':11,'hu':0,'id':0,'ig':0,'ii':0,'is':3,'it':3,'iu':7,'ja':0,'jmc':3,'jv':0,'ka':0,'kab':5,'kaj':3,'kcg':3,'kde':0,'kea':0,'kk':3,'kl':3,'km':0,'kn':0,'ko':0,'ksb':3,'ksh':21,'ku':3,'kw':7,'lag':18,'lb':3,'lg':3,'ln':4,'lo':0,'lt':10,'lv':6,'mas':3,'mg':4,'mk':16,'ml':3,'mn':3,'mo':9,'mr':3,'ms':0,'mt':15,'my':0,'nah':3,'naq':7,'nb':3,'nd':3,'ne':3,'nl':3,'nn':3,'no':3,'nr':3,'nso':4,'ny':3,'nyn':3,'om':3,'or':3,'pa':3,'pap':3,'pl':13,'ps':3,'pt':3,'rm':3,'ro':9,'rof':3,'ru':11,'rwk':3,'sah':0,'saq':3,'se':7,'seh':3,'ses':0,'sg':0,'sh':11,'shi':19,'sk':12,'sl':14,'sma':7,'smi':7,'smj':7,'smn':7,'sms':7,'sn':3,'so':3,'sq':3,'sr':11,'ss':3,'ssy':3,'st':3,'sv':3,'sw':3,'syr':3,'ta':3,'te':3,'teo':3,'th':0,'ti':4,'tig':3,'tk':3,'tl':4,'tn':3,'to':0,'tr':0,'ts':3,'tzm':22,'uk':11,'ur':3,'ve':3,'vi':0,'vun':3,'wa':4,'wae':3,'wo':0,'xh':3,'xog':3,'yo':0,'zh':0,'zu':3};function isIn(n,list){return list.indexOf(n)!==-1;} function isBetween(n,start,end){return typeof n===typeof start&&start<=n&&n<=end;} const pluralRules={'0':function(){return'other';},'1':function(n){if(isBetween(n%100,3,10)){return'few';} if(n===0){return'zero';} if(isBetween(n%100,11,99)){return'many';} if(n===2){return'two';} if(n===1){return'one';} return'other';},'2':function(n){if(n!==0&&n%10===0){return'many';} if(n===2){return'two';} if(n===1){return'one';} return'other';},'3':function(n){if(n===1){return'one';} return'other';},'4':function(n){if(isBetween(n,0,1)){return'one';} return'other';},'5':function(n){if(isBetween(n,0,2)&&n!==2){return'one';} return'other';},'6':function(n){if(n===0){return'zero';} if(n%10===1&&n%100!==11){return'one';} return'other';},'7':function(n){if(n===2){return'two';} if(n===1){return'one';} return'other';},'8':function(n){if(isBetween(n,3,6)){return'few';} if(isBetween(n,7,10)){return'many';} if(n===2){return'two';} if(n===1){return'one';} return'other';},'9':function(n){if(n===0||n!==1&&isBetween(n%100,1,19)){return'few';} if(n===1){return'one';} return'other';},'10':function(n){if(isBetween(n%10,2,9)&&!isBetween(n%100,11,19)){return'few';} if(n%10===1&&!isBetween(n%100,11,19)){return'one';} return'other';},'11':function(n){if(isBetween(n%10,2,4)&&!isBetween(n%100,12,14)){return'few';} if(n%10===0||isBetween(n%10,5,9)||isBetween(n%100,11,14)){return'many';} if(n%10===1&&n%100!==11){return'one';} return'other';},'12':function(n){if(isBetween(n,2,4)){return'few';} if(n===1){return'one';} return'other';},'13':function(n){if(isBetween(n%10,2,4)&&!isBetween(n%100,12,14)){return'few';} if(n!==1&&isBetween(n%10,0,1)||isBetween(n%10,5,9)||isBetween(n%100,12,14)){return'many';} if(n===1){return'one';} return'other';},'14':function(n){if(isBetween(n%100,3,4)){return'few';} if(n%100===2){return'two';} if(n%100===1){return'one';} return'other';},'15':function(n){if(n===0||isBetween(n%100,2,10)){return'few';} if(isBetween(n%100,11,19)){return'many';} if(n===1){return'one';} return'other';},'16':function(n){if(n%10===1&&n!==11){return'one';} return'other';},'17':function(n){if(n===3){return'few';} if(n===0){return'zero';} if(n===6){return'many';} if(n===2){return'two';} if(n===1){return'one';} return'other';},'18':function(n){if(n===0){return'zero';} if(isBetween(n,0,2)&&n!==0&&n!==2){return'one';} return'other';},'19':function(n){if(isBetween(n,2,10)){return'few';} if(isBetween(n,0,1)){return'one';} return'other';},'20':function(n){if((isBetween(n%10,3,4)||n%10===9)&&!(isBetween(n%100,10,19)||isBetween(n%100,70,79)||isBetween(n%100,90,99))){return'few';} if(n%1000000===0&&n!==0){return'many';} if(n%10===2&&!isIn(n%100,[12,72,92])){return'two';} if(n%10===1&&!isIn(n%100,[11,71,91])){return'one';} return'other';},'21':function(n){if(n===0){return'zero';} if(n===1){return'one';} return'other';},'22':function(n){if(isBetween(n,0,1)||isBetween(n,11,99)){return'one';} return'other';},'23':function(n){if(isBetween(n%10,1,2)||n%20===0){return'one';} return'other';},'24':function(n){if(isBetween(n,3,10)||isBetween(n,13,19)){return'few';} if(isIn(n,[2,12])){return'two';} if(isIn(n,[1,11])){return'one';} return'other';}};function getPluralRule(code){const index=locales2rules[code.replace(/-.*$/,'')];if(!(index in pluralRules)){return function(){return'other';};} return pluralRules[index];} const L20nIntl=typeof Intl!=='undefined'?Intl:{NumberFormat:function(){return{format:function(v){return v;}};}};let Context=(function(){function Context(env,langs,resIds){_classCallCheck(this,Context);this.langs=langs;this.resIds=resIds;this.env=env;this.emit=(type,evt)=>env.emit(type,evt,this);} _createClass(Context,[{key:'_formatTuple',value:function _formatTuple(lang,args,entity,id,key){try{return format(this,lang,args,entity);}catch(err){err.id=key?id+'::'+key:id;err.lang=lang;this.emit('resolveerror',err);return[{error:err},err.id];}}},{key:'_formatEntity',value:function _formatEntity(lang,args,entity,id){const[,value]=this._formatTuple(lang,args,entity,id);const formatted={value,attrs:null};if(entity.attrs){formatted.attrs=Object.create(null);for(let key in entity.attrs){const[,attrValue]=this._formatTuple(lang,args,entity.attrs[key],id,key);formatted.attrs[key]=attrValue;}} return formatted;}},{key:'_formatValue',value:function _formatValue(lang,args,entity,id){return this._formatTuple(lang,args,entity,id)[1];}},{key:'fetch',value:function fetch(langs=this.langs){if(langs.length===0){return Promise.resolve(langs);} return Promise.all(this.resIds.map(resId=>this.env._getResource(langs[0],resId))).then(()=>langs);}},{key:'_resolve',value:function _resolve(langs,keys,formatter,prevResolved){const lang=langs[0];if(!lang){return reportMissing.call(this,keys,formatter,prevResolved);} let hasUnresolved=false;const resolved=keys.map((key,i)=>{if(prevResolved&&prevResolved[i]!==undefined){return prevResolved[i];} const[id,args]=Array.isArray(key)?key:[key,undefined];const entity=this._getEntity(lang,id);if(entity){return formatter.call(this,lang,args,entity,id);} this.emit('notfounderror',new L10nError('"'+id+'"'+' not found in '+lang.code,id,lang));hasUnresolved=true;});if(!hasUnresolved){return resolved;} return this.fetch(langs.slice(1)).then(nextLangs=>this._resolve(nextLangs,keys,formatter,resolved));}},{key:'formatEntities',value:function formatEntities(...keys){return this.fetch().then(langs=>this._resolve(langs,keys,this._formatEntity));}},{key:'formatValues',value:function formatValues(...keys){return this.fetch().then(langs=>this._resolve(langs,keys,this._formatValue));}},{key:'_getEntity',value:function _getEntity(lang,id){const cache=this.env.resCache;for(let i=0,resId;resId=this.resIds[i];i++){const resource=cache.get(resId+lang.code+lang.src);if(resource instanceof L10nError){continue;} if(id in resource){return resource[id];}} return undefined;}},{key:'_getNumberFormatter',value:function _getNumberFormatter(lang){if(!this.env.numberFormatters){this.env.numberFormatters=new Map();} if(!this.env.numberFormatters.has(lang)){const formatter=L20nIntl.NumberFormat(lang);this.env.numberFormatters.set(lang,formatter);return formatter;} return this.env.numberFormatters.get(lang);}},{key:'_getMacro',value:function _getMacro(lang,id){switch(id){case'plural':return getPluralRule(lang.code);default:return undefined;}}}]);return Context;})();function reportMissing(keys,formatter,resolved){const missingIds=new Set();keys.forEach((key,i)=>{if(resolved&&resolved[i]!==undefined){return;} const id=Array.isArray(key)?key[0]:key;missingIds.add(id);resolved[i]=formatter===this._formatValue?id:{value:id,attrs:null};});this.emit('notfounderror',new L10nError('"'+Array.from(missingIds).join(', ')+'"'+' not found in any language',missingIds));return resolved;} var MAX_PLACEABLES=100;var PropertiesParser={patterns:null,entryIds:null,emit:null,init:function(){this.patterns={comment:/^\s*#|^\s*$/,entity:/^([^=\s]+)\s*=\s*(.*)$/,multiline:/[^\\]\\$/,index:/\{\[\s*(\w+)(?:\(([^\)]*)\))?\s*\]\}/i,unicode:/\\u([0-9a-fA-F]{1,4})/g,entries:/[^\r\n]+/g,controlChars:/\\([\\\n\r\t\b\f\{\}\"\'])/g,placeables:/\{\{\s*([^\s]*?)\s*\}\}/};},parse:function(emit,source){if(!this.patterns){this.init();} this.emit=emit;var entries={};var lines=source.match(this.patterns.entries);if(!lines){return entries;} for(var i=0;i2){throw this.error('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 this.error('Attribute can\'t start with "$"');}}else{attr=null;} this.setEntityValue(name,attr,key,this.unescapeString(value),entries);},setEntityValue:function(id,attr,key,rawValue,entries){var value=rawValue.indexOf('{{')>-1?this.parseString(rawValue):rawValue;var isSimpleValue=typeof value==='string';var root=entries;var isSimpleNode=typeof entries[id]==='string';if(!entries[id]&&(attr||key||!isSimpleValue)){entries[id]=Object.create(null);isSimpleNode=false;} if(attr){if(isSimpleNode){const val=entries[id];entries[id]=Object.create(null);entries[id].value=val;} if(!entries[id].attrs){entries[id].attrs=Object.create(null);} if(!entries[id].attrs&&!isSimpleValue){entries[id].attrs[attr]=Object.create(null);} root=entries[id].attrs;id=attr;} if(key){isSimpleNode=false;if(typeof root[id]==='string'){const val=root[id];root[id]=Object.create(null);root[id].index=this.parseIndex(val);root[id].value=Object.create(null);} root=root[id].value;id=key;isSimpleValue=true;} if(isSimpleValue){if(id in root){throw this.error('Duplicated id: '+id);} root[id]=value;}else{if(!root[id]){root[id]=Object.create(null);} root[id].value=value;}},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 this.error('Too many placeables ('+placeablesCount+', max allowed is '+MAX_PLACEABLES+')');} for(var i=0;i'){throw this.error('Expected ">"');} attrs=this.getAttributes();}else{const ws1=this.getRequiredWS();if(this._source[this._index]!=='>'){if(!ws1){throw this.error('Expected ">"');} attrs=this.getAttributes();}} ++this._index;if(id in this.entries){throw this.error('Duplicate entry ID "'+id,'duplicateerror');} if(!attrs&&!index&&typeof value==='string'){this.entries[id]=value;}else{this.entries[id]={value,attrs,index};}},getValue:function(ch=this._source[this._index],index=false,required=true){switch(ch){case'\'':case'"':return this.getString(ch,1);case'{':return this.getHash(index);} if(required){throw this.error('Unknown value type');} return;},getWS:function(){let cc=this._source.charCodeAt(this._index);while(cc===32||cc===10||cc===9||cc===13){cc=this._source.charCodeAt(++this._index);}},getRequiredWS:function(){const pos=this._index;let cc=this._source.charCodeAt(pos);while(cc===32||cc===10||cc===9||cc===13){cc=this._source.charCodeAt(++this._index);} return this._index!==pos;},getIdentifier:function(){const start=this._index;let cc=this._source.charCodeAt(this._index);if(cc>=97&&cc<=122||cc>=65&&cc<=90||cc===95){cc=this._source.charCodeAt(++this._index);}else{throw this.error('Identifier has to start with [a-zA-Z_]');} while(cc>=97&&cc<=122||cc>=65&&cc<=90||cc>=48&&cc<=57||cc===95){cc=this._source.charCodeAt(++this._index);} return this._source.slice(start,this._index);},getUnicodeChar:function(){for(let i=0;i<4;i++){let cc=this._source.charCodeAt(++this._index);if(cc>96&&cc<103||cc>64&&cc<71||cc>47&&cc<58){continue;} throw this.error('Illegal unicode escape sequence');} this._index++;return String.fromCharCode(parseInt(this._source.slice(this._index-4,this._index),16));},stringRe:/"|'|{{|\\/g,getString:function(opchar,opcharLen){const body=[];let placeables=0;this._index+=opcharLen;const start=this._index;let bufStart=start;let buf='';while(true){this.stringRe.lastIndex=this._index;const match=this.stringRe.exec(this._source);if(!match){throw this.error('Unclosed string literal');} if(match[0]==='"'||match[0]==='\''){if(match[0]!==opchar){this._index+=opcharLen;continue;} this._index=match.index+opcharLen;break;} if(match[0]==='{{'){if(placeables>MAX_PLACEABLES$1-1){throw this.error('Too many placeables, maximum allowed is '+MAX_PLACEABLES$1);} placeables++;if(match.index>bufStart||buf.length>0){body.push(buf+this._source.slice(bufStart,match.index));buf='';} this._index=match.index+2;this.getWS();body.push(this.getExpression());this.getWS();this._index+=2;bufStart=this._index;continue;} if(match[0]==='\\'){this._index=match.index+1;const ch2=this._source[this._index];if(ch2==='u'){buf+=this._source.slice(bufStart,match.index)+this.getUnicodeChar();}else if(ch2===opchar||ch2==='\\'){buf+=this._source.slice(bufStart,match.index)+ch2;this._index++;}else if(this._source.startsWith('{{',this._index)){buf+=this._source.slice(bufStart,match.index)+'{{';this._index+=2;}else{throw this.error('Illegal escape sequence');} bufStart=this._index;}} if(body.length===0){return buf+this._source.slice(bufStart,this._index-opcharLen);} if(this._index-opcharLen>bufStart||buf.length>0){body.push(buf+this._source.slice(bufStart,this._index-opcharLen));} return body;},getAttributes:function(){const attrs=Object.create(null);while(true){this.getAttribute(attrs);const ws1=this.getRequiredWS();const ch=this._source.charAt(this._index);if(ch==='>'){break;}else if(!ws1){throw this.error('Expected ">"');}} return attrs;},getAttribute:function(attrs){const key=this.getIdentifier();let index;if(this._source[this._index]==='['){++this._index;this.getWS();index=this.getItemList(this.getExpression,']');} this.getWS();if(this._source[this._index]!==':'){throw this.error('Expected ":"');} ++this._index;this.getWS();const hasIndex=index!==undefined;const value=this.getValue(undefined,hasIndex);if(key in attrs){throw this.error('Duplicate attribute "'+key,'duplicateerror');} if(!index&&typeof value==='string'){attrs[key]=value;}else{attrs[key]={value,index};}},getHash:function(index){const items=Object.create(null);++this._index;this.getWS();let defKey;while(true){const[key,value,def]=this.getHashItem();items[key]=value;if(def){if(defKey){throw this.error('Default item redefinition forbidden');} defKey=key;} this.getWS();const comma=this._source[this._index]===',';if(comma){++this._index;this.getWS();} if(this._source[this._index]==='}'){++this._index;break;} if(!comma){throw this.error('Expected "}"');}} if(defKey){items.__default=defKey;}else if(!index){throw this.error('Unresolvable Hash Value');} return items;},getHashItem:function(){let defItem=false;if(this._source[this._index]==='*'){++this._index;defItem=true;} const key=this.getIdentifier();this.getWS();if(this._source[this._index]!==':'){throw this.error('Expected ":"');} ++this._index;this.getWS();return[key,this.getValue(),defItem];},getComment:function(){this._index+=2;const start=this._index;const end=this._source.indexOf('*/',start);if(end===-1){throw this.error('Comment without a closing tag');} this._index=end+2;},getExpression:function(){let exp=this.getPrimaryExpression();while(true){let ch=this._source[this._index];if(ch==='.'||ch==='['){++this._index;exp=this.getPropertyExpression(exp,ch==='[');}else if(ch==='('){++this._index;exp=this.getCallExpression(exp);}else{break;}} return exp;},getPropertyExpression:function(idref,computed){let exp;if(computed){this.getWS();exp=this.getExpression();this.getWS();if(this._source[this._index]!==']'){throw this.error('Expected "]"');} ++this._index;}else{exp=this.getIdentifier();} return{type:'prop',expr:idref,prop:exp,cmpt:computed};},getCallExpression:function(callee){this.getWS();return{type:'call',expr:callee,args:this.getItemList(this.getExpression,')')};},getPrimaryExpression:function(){const ch=this._source[this._index];switch(ch){case'$':++this._index;return{type:'var',name:this.getIdentifier()};case'@':++this._index;return{type:'glob',name:this.getIdentifier()};default:return{type:'id',name:this.getIdentifier()};}},getItemList:function(callback,closeChar){const items=[];let closed=false;this.getWS();if(this._source[this._index]===closeChar){++this._index;closed=true;} while(!closed){items.push(callback.call(this));this.getWS();let ch=this._source.charAt(this._index);switch(ch){case',':++this._index;this.getWS();break;case closeChar:++this._index;closed=true;break;default:throw this.error('Expected "," or "'+closeChar+'"');}} return items;},getJunkEntry:function(){const pos=this._index;let nextEntity=this._source.indexOf('<',pos);let nextComment=this._source.indexOf('/*',pos);if(nextEntity===-1){nextEntity=this._length;} if(nextComment===-1){nextComment=this._length;} let nextEntry=Math.min(nextEntity,nextComment);this._index=nextEntry;},error:function(message,type='parsererror'){const pos=this._index;let start=this._source.lastIndexOf('<',pos-1);const lastClose=this._source.lastIndexOf('>',pos-1);start=lastClose>start?lastClose+1:start;const context=this._source.slice(start,pos+10);const msg=message+' at pos '+pos+': `'+context+'`';const err=new L10nError(msg);if(this.emit){this.emit(type,err);} return err;}};function walkEntry(entry,fn){if(typeof entry==='string'){return fn(entry);} const newEntry=Object.create(null);if(entry.value){newEntry.value=walkValue(entry.value,fn);} if(entry.index){newEntry.index=entry.index;} if(entry.attrs){newEntry.attrs=Object.create(null);for(let key in entry.attrs){newEntry.attrs[key]=walkEntry(entry.attrs[key],fn);}} return newEntry;} function walkValue(value,fn){if(typeof value==='string'){return fn(value);} if(value.type){return value;} const newValue=Array.isArray(value)?[]:Object.create(null);const keys=Object.keys(value);for(let i=0,key;key=keys[i];i++){newValue[key]=walkValue(value[key],fn);} return newValue;} function createGetter(id,name){let _pseudo=null;return function getPseudo(){if(_pseudo){return _pseudo;} const reAlphas=/[a-zA-Z]/g;const reVowels=/[aeiouAEIOU]/g;const reWords=/[^\W0-9_]+/g;const reExcluded=/(%[EO]?\w|\{\s*.+?\s*\}|&[#\w]+;|<\s*.+?\s*>)/;const charMaps={'fr-x-psaccent':'ȦƁƇḒḖƑƓĦĪĴĶĿḾȠǾƤɊŘŞŦŬṼẆẊẎẐ[\\]^_`ȧƀƈḓḗƒɠħīĵķŀḿƞǿƥɋřşŧŭṽẇẋẏẑ','ar-x-psbidi':'∀ԐↃpƎɟפHIſӼ˥WNOԀÒᴚS⊥∩ɅMXʎZ[\\]ᵥ_,ɐqɔpǝɟƃɥıɾʞʅɯuodbɹsʇnʌʍxʎz'};const mods={'fr-x-psaccent':val=>val.replace(reVowels,match=>match+match.toLowerCase()),'ar-x-psbidi':val=>val.replace(reWords,match=>'‮'+match+'‬')};const replaceChars=(map,val)=>val.replace(reAlphas,match=>map.charAt(match.charCodeAt(0)-65));const transform=val=>replaceChars(charMaps[id],mods[id](val));const apply=(fn,val)=>{if(!val){return val;} const parts=val.split(reExcluded);const modified=parts.map(function(part){if(reExcluded.test(part)){return part;} return fn(part);});return modified.join('');};return _pseudo={name:transform(name),process:str=>apply(transform,str)};};} const pseudo=Object.defineProperties(Object.create(null),{'fr-x-psaccent':{enumerable:true,get:createGetter('fr-x-psaccent','Runtime Accented')},'ar-x-psbidi':{enumerable:true,get:createGetter('ar-x-psbidi','Runtime Bidi')}});let Env=(function(){function Env(fetchResource){_classCallCheck(this,Env);this.fetchResource=fetchResource;this.resCache=new Map();this.resRefs=new Map();this.numberFormatters=null;this.parsers={properties:PropertiesParser,l20n:L20nParser};const listeners={};this.emit=emit.bind(this,listeners);this.addEventListener=addEventListener.bind(this,listeners);this.removeEventListener=removeEventListener.bind(this,listeners);} _createClass(Env,[{key:'createContext',value:function createContext(langs,resIds){const ctx=new Context(this,langs,resIds);resIds.forEach(resId=>{const usedBy=this.resRefs.get(resId)||0;this.resRefs.set(resId,usedBy+1);});return ctx;}},{key:'destroyContext',value:function destroyContext(ctx){ctx.resIds.forEach(resId=>{const usedBy=this.resRefs.get(resId)||0;if(usedBy>1){return this.resRefs.set(resId,usedBy-1);} this.resRefs.delete(resId);this.resCache.forEach((val,key)=>key.startsWith(resId)?this.resCache.delete(key):null);});}},{key:'_parse',value:function _parse(syntax,lang,data){const parser=this.parsers[syntax];if(!parser){return data;} const emit=(type,err)=>this.emit(type,amendError(lang,err));return parser.parse.call(parser,emit,data);}},{key:'_create',value:function _create(lang,entries){if(lang.src!=='pseudo'){return entries;} const pseudoentries=Object.create(null);for(let key in entries){pseudoentries[key]=walkEntry(entries[key],pseudo[lang.code].process);} return pseudoentries;}},{key:'_getResource',value:function _getResource(lang,res){const cache=this.resCache;const id=res+lang.code+lang.src;if(cache.has(id)){return cache.get(id);} const syntax=res.substr(res.lastIndexOf('.')+1);const saveEntries=data=>{const entries=this._parse(syntax,lang,data);cache.set(id,this._create(lang,entries));};const recover=err=>{err.lang=lang;this.emit('fetcherror',err);cache.set(id,err);};const langToFetch=lang.src==='pseudo'?{code:'en-US',src:'app',ver:lang.ver}:lang;const resource=this.fetchResource(res,langToFetch).then(saveEntries,recover);cache.set(id,resource);return resource;}}]);return Env;})();function amendError(lang,err){err.lang=lang;return err;} function prioritizeLocales(def,availableLangs,requested){let supportedLocale;for(let i=0;i({code:code,src:getLangSource(appVersion,availableLangs,additionalLangs,code),ver:appVersion}));return{langs,haveChanged:!arrEqual(prevLangs,newLangs)};} function arrEqual(arr1,arr2){return arr1.length===arr2.length&&arr1.every((elem,i)=>elem===arr2[i]);} function getMatchingLangpack(appVersion,langpacks){for(let i=0,langpack;langpack=langpacks[i];i++){if(langpack.target===appVersion){return langpack;}} return null;} function getLangSource(appVersion,availableLangs,additionalLangs,code){if(additionalLangs&&additionalLangs[code]){const lp=getMatchingLangpack(appVersion,additionalLangs[code]);if(lp&&(!(code in availableLangs)||parseInt(lp.revision)>availableLangs[code])){return'extra';}} if(code in pseudo&&!(code in availableLangs)){return'pseudo';} return'app';} let Remote=(function(){function Remote(fetchResource,broadcast){_classCallCheck(this,Remote);this.broadcast=broadcast;this.env=new Env(fetchResource);this.ctxs=new Map();} _createClass(Remote,[{key:'registerView',value:function registerView(view,resources,meta,additionalLangs,requestedLangs){const{langs}=negotiateLanguages(meta,additionalLangs,[],requestedLangs);this.ctxs.set(view,this.env.createContext(langs,resources));return langs;}},{key:'unregisterView',value:function unregisterView(view){this.ctxs.delete(view);return true;}},{key:'formatEntities',value:function formatEntities(view,keys){return this.ctxs.get(view).formatEntities(...keys);}},{key:'formatValues',value:function formatValues(view,keys){return this.ctxs.get(view).formatValues(...keys);}},{key:'changeLanguages',value:function changeLanguages(view,meta,additionalLangs,requestedLangs){const oldCtx=this.ctxs.get(view);const prevLangs=oldCtx.langs;const newLangs=negotiateLanguages(meta,additionalLangs,prevLangs,requestedLangs);this.ctxs.set(view,this.env.createContext(newLangs.langs,oldCtx.resIds));return newLangs;}},{key:'requestLanguages',value:function requestLanguages(requestedLangs){this.broadcast('languageschangerequest',requestedLangs);}},{key:'getName',value:function getName(code){return pseudo[code].name;}},{key:'processString',value:function processString(code,str){return pseudo[code].process(str);}}]);return Remote;})();const observerConfig={attributes:true,characterData:false,childList:true,subtree:true,attributeFilter:['data-l10n-id','data-l10n-args']};const observers=new WeakMap();function initMutationObserver(view){observers.set(view,{roots:new Set(),observer:new MutationObserver(mutations=>translateMutations(view,mutations))});} function translateRoots(view){return Promise.all([...observers.get(view).roots].map(root=>_translateFragment(view,root)));} function observe(view,root){const obs=observers.get(view);if(obs){obs.roots.add(root);obs.observer.observe(root,observerConfig);}} function disconnect(view,root,allRoots){const obs=observers.get(view);if(obs){obs.observer.disconnect();if(allRoots){return;} obs.roots.delete(root);obs.roots.forEach(other=>obs.observer.observe(other,observerConfig));}} function reconnect(view){const obs=observers.get(view);if(obs){obs.roots.forEach(root=>obs.observer.observe(root,observerConfig));}} const reOverlay=/<|&#?\w+;/;const allowed={elements:['a','em','strong','small','s','cite','q','dfn','abbr','data','time','code','var','samp','kbd','sub','sup','i','b','u','mark','ruby','rt','rp','bdi','bdo','span','br','wbr'],attributes:{global:['title','aria-label','aria-valuetext','aria-moz-hint'],a:['download'],area:['download','alt'],input:['alt','placeholder'],menuitem:['label'],menu:['label'],optgroup:['label'],option:['label'],track:['label'],img:['alt'],textarea:['placeholder'],th:['abbr']}};function overlayElement(element,translation){const value=translation.value;if(typeof value==='string'){if(!reOverlay.test(value)){element.textContent=value;}else{const tmpl=element.ownerDocument.createElement('template');tmpl.innerHTML=value;overlay(element,tmpl.content);}} for(let key in translation.attrs){const attrName=camelCaseToDashed(key);if(isAttrAllowed({name:attrName},element)){element.setAttribute(attrName,translation.attrs[key]);}}} function overlay(sourceElement,translationElement){const result=translationElement.ownerDocument.createDocumentFragment();let k,attr;let childElement;while(childElement=translationElement.childNodes[0]){translationElement.removeChild(childElement);if(childElement.nodeType===childElement.TEXT_NODE){result.appendChild(childElement);continue;} const index=getIndexOfType(childElement);const sourceChild=getNthElementOfType(sourceElement,childElement,index);if(sourceChild){overlay(sourceChild,childElement);result.appendChild(sourceChild);continue;} if(isElementAllowed(childElement)){const sanitizedChild=childElement.ownerDocument.createElement(childElement.nodeName);overlay(sanitizedChild,childElement);result.appendChild(sanitizedChild);continue;} result.appendChild(translationElement.ownerDocument.createTextNode(childElement.textContent));} sourceElement.textContent='';sourceElement.appendChild(result);if(translationElement.attributes){for(k=0,attr;attr=translationElement.attributes[k];k++){if(isAttrAllowed(attr,sourceElement)){sourceElement.setAttribute(attr.name,attr.value);}}}} function isElementAllowed(element){return allowed.elements.indexOf(element.tagName.toLowerCase())!==-1;} function isAttrAllowed(attr,element){const attrName=attr.name.toLowerCase();const tagName=element.tagName.toLowerCase();if(allowed.attributes.global.indexOf(attrName)!==-1){return true;} if(!allowed.attributes[tagName]){return false;} if(allowed.attributes[tagName].indexOf(attrName)!==-1){return true;} if(tagName==='input'&&attrName==='value'){const type=element.type.toLowerCase();if(type==='submit'||type==='button'||type==='reset'){return true;}} return false;} function getNthElementOfType(context,element,index){let nthOfType=0;for(let i=0,child;child=context.children[i];i++){if(child.nodeType===child.ELEMENT_NODE&&child.tagName===element.tagName){if(nthOfType===index){return child;} nthOfType++;}} return null;} function getIndexOfType(element){let index=0;let child;while(child=element.previousElementSibling){if(child.tagName===element.tagName){index++;}} return index;} function camelCaseToDashed(string){if(string==='ariaValueText'){return'aria-valuetext';} return string.replace(/[A-Z]/g,function(match){return'-'+match.toLowerCase();}).replace(/^-/,'');} const reHtml=/[&<>]/g;const htmlEntities={'&':'&','<':'<','>':'>'};function setAttributes(element,id,args){element.setAttribute('data-l10n-id',id);if(args){element.setAttribute('data-l10n-args',JSON.stringify(args));}} function getAttributes(element){return{id:element.getAttribute('data-l10n-id'),args:JSON.parse(element.getAttribute('data-l10n-args'))};} function getTranslatables(element){const nodes=Array.from(element.querySelectorAll('[data-l10n-id]'));if(typeof element.hasAttribute==='function'&&element.hasAttribute('data-l10n-id')){nodes.push(element);} return nodes;} function translateMutations(view,mutations){const targets=new Set();for(let mutation of mutations){switch(mutation.type){case'attributes':targets.add(mutation.target);break;case'childList':for(let addedNode of mutation.addedNodes){if(addedNode.nodeType===addedNode.ELEMENT_NODE){if(addedNode.childElementCount){getTranslatables(addedNode).forEach(targets.add.bind(targets));}else{if(addedNode.hasAttribute('data-l10n-id')){targets.add(addedNode);}}}} break;}} if(targets.size===0){return;} translateElements(view,Array.from(targets));} function _translateFragment(view,frag){return translateElements(view,getTranslatables(frag));} function getElementsTranslation(view,elems){const keys=elems.map(elem=>{const id=elem.getAttribute('data-l10n-id');const args=elem.getAttribute('data-l10n-args');return args?[id,JSON.parse(args.replace(reHtml,match=>htmlEntities[match]))]:id;});return view.formatEntities(...keys);} function translateElements(view,elements){return getElementsTranslation(view,elements).then(translations=>applyTranslations(view,elements,translations));} function applyTranslations(view,elems,translations){disconnect(view,null,true);for(let i=0;i{document.addEventListener('readystatechange',function onrsc(){document.removeEventListener('readystatechange',onrsc);resolve();});});} function getDirection(code){const tag=code.split('-')[0];return['ar','he','fa','ps','ur'].indexOf(tag)>=0?'rtl':'ltr';} if(navigator.languages===undefined){navigator.languages=[navigator.language];} function getResourceLinks(head){return Array.prototype.map.call(head.querySelectorAll('link[rel="localization"]'),el=>el.getAttribute('href'));} function getMeta(head){let availableLangs=Object.create(null);let defaultLang=null;let appVersion=null;const metas=Array.from(head.querySelectorAll('meta[name="availableLanguages"],'+'meta[name="defaultLanguage"],'+'meta[name="appVersion"]'));for(let meta of metas){const name=meta.getAttribute('name');const content=meta.getAttribute('content').trim();switch(name){case'availableLanguages':availableLangs=getLangRevisionMap(availableLangs,content);break;case'defaultLanguage':const[lang,rev]=getLangRevisionTuple(content);defaultLang=lang;if(!(lang in availableLangs)){availableLangs[lang]=rev;} break;case'appVersion':appVersion=content;}} return{defaultLang,availableLangs,appVersion};} function getLangRevisionMap(seq,str){return str.split(',').reduce((seq,cur)=>{const[lang,rev]=getLangRevisionTuple(cur);seq[lang]=rev;return seq;},seq);} function getLangRevisionTuple(str){const[lang,rev]=str.trim().split(':');return[lang,parseInt(rev)];} const viewProps=new WeakMap();let View=(function(){function View(client,doc){_classCallCheck(this,View);this.pseudo={'fr-x-psaccent':createPseudo(this,'fr-x-psaccent'),'ar-x-psbidi':createPseudo(this,'ar-x-psbidi')};const initialized=documentReady().then(()=>init(this,client));this._interactive=initialized.then(()=>client);this.ready=initialized.then(langs=>translateView(this,langs));initMutationObserver(this);viewProps.set(this,{doc:doc,ready:false});client.on('languageschangerequest',requestedLangs=>this.requestLanguages(requestedLangs));} _createClass(View,[{key:'requestLanguages',value:function requestLanguages(requestedLangs,isGlobal){const method=isGlobal?client=>client.method('requestLanguages',requestedLangs):client=>changeLanguages(this,client,requestedLangs);return this._interactive.then(method);}},{key:'handleEvent',value:function handleEvent(){return this.requestLanguages(navigator.languages);}},{key:'formatEntities',value:function formatEntities(...keys){return this._interactive.then(client=>client.method('formatEntities',client.id,keys));}},{key:'formatValue',value:function formatValue(id,args){return this._interactive.then(client=>client.method('formatValues',client.id,[[id,args]])).then(values=>values[0]);}},{key:'formatValues',value:function formatValues(...keys){return this._interactive.then(client=>client.method('formatValues',client.id,keys));}},{key:'translateFragment',value:function translateFragment(frag){return _translateFragment(this,frag);}},{key:'observeRoot',value:function observeRoot(root){observe(this,root);}},{key:'disconnectRoot',value:function disconnectRoot(root){disconnect(this,root);}}]);return View;})();View.prototype.setAttributes=setAttributes;View.prototype.getAttributes=getAttributes;function createPseudo(view,code){return{getName:()=>view._interactive.then(client=>client.method('getName',code)),processString:str=>view._interactive.then(client=>client.method('processString',code,str))};} function init(view,client){const doc=viewProps.get(view).doc;const resources=getResourceLinks(doc.head);const meta=getMeta(doc.head);view.observeRoot(doc.documentElement);return getAdditionalLanguages().then(additionalLangs=>client.method('registerView',client.id,resources,meta,additionalLangs,navigator.languages));} function changeLanguages(view,client,requestedLangs){const doc=viewProps.get(view).doc;const meta=getMeta(doc.head);return getAdditionalLanguages().then(additionalLangs=>client.method('changeLanguages',client.id,meta,additionalLangs,requestedLangs)).then(({langs,haveChanged})=>haveChanged?translateView(view,langs):undefined);} function getAdditionalLanguages(){if(navigator.mozApps&&navigator.mozApps.getAdditionalLanguages){return navigator.mozApps.getAdditionalLanguages().catch(()=>Object.create(null));} return Promise.resolve(Object.create(null));} function translateView(view,langs){const props=viewProps.get(view);const html=props.doc.documentElement;if(props.ready){return translateRoots(view).then(()=>setAllAndEmit(html,langs));} const translated=langs[0].code===html.getAttribute('lang')?Promise.resolve():translateRoots(view).then(()=>setLangDir(html,langs));return translated.then(()=>{setLangs(html,langs);props.ready=true;});} function setLangs(html,langs){const codes=langs.map(lang=>lang.code);html.setAttribute('langs',codes.join(' '));} function setLangDir(html,langs){const code=langs[0].code;html.setAttribute('lang',code);html.setAttribute('dir',getDirection(code));} function setAllAndEmit(html,langs){setLangDir(html,langs);setLangs(html,langs);html.parentNode.dispatchEvent(new CustomEvent('DOMRetranslated',{bubbles:false,cancelable:false}));} const remote=new Remote(fetchResource,broadcast);const client=new Client(remote);document.l10n=new View(client,document);window.addEventListener('languagechange',document.l10n);document.addEventListener('additionallanguageschange',document.l10n);navigator.mozL10n={setAttributes:document.l10n.setAttributes,getAttributes:document.l10n.getAttributes,formatValue:(...args)=>document.l10n.formatValue(...args),translateFragment:(...args)=>document.l10n.translateFragment(...args),once:cb=>document.l10n.ready.then(cb),ready:cb=>document.l10n.ready.then(()=>{document.addEventListener('DOMRetranslated',cb);cb();})};})();;'use strict';function tzSelect(regionSelector,citySelector,onchange,onload){const TIMEZONE_FILE='/shared/resources/tz.json';const APN_TZ_FILE='/shared/resources/apn_tz.json';const TIMEZONE_NONE='NONE';const TIMEZONE_NETWORK='NETWORK';const TIMEZONE_SIM='SIM';const TIMEZONE_USER='USER';const TIMEZONE_PREVIOUS_SETTING='PREVIOUS_SETTING';function loadJSON(href,callback){var xhr=new XMLHttpRequest();xhr.open('GET',href,true);xhr.responseType='json';xhr.onerror=callback;xhr.onload=function(){callback(xhr.response);};xhr.onerror=function(){console.error('Error getting file');callback(xhr.response);};xhr.send();} function getDefaultTimezoneID(callback){if(!callback){return;} var tzDefault='America/New_York';var source=TIMEZONE_NONE;var mcc,mnc;var connections=window.navigator.mozMobileConnections||[];for(var i=0;ib.text);});for(var i=0;i{const item=document.createElement('option');item.setAttribute('data-l10n-id',option.l10nId);item.selected=option.selected;item.value=option.value;frag.appendChild(item);return item;});return document.l10n.translateFragment(frag).then(()=>{items.sort((a,b)=>collator.compare(a.textContent,b.textContent));items.forEach(item=>frag.appendChild(item));selector.appendChild(frag);});} function getSelectedText(selector){var options=selector.querySelectorAll('option');return options[selector.selectedIndex].textContent;} function fillRegions(){var options=[];for(var c in gTZ){options.push({l10nId:'tzRegion-'+c,value:c,selected:(c===gRegion)});} fillSelectL10nElement(regionSelector,options).then(fillCities);} function fillCities(){gRegion=regionSelector.value;var list=gTZ[gRegion];var options=[];for(var i=0;i"'/]/g,_entities:{'&':'&','<':'<','>':'>','"':'"','\'':''','/':'/'},getEntity:function(s){return Sanitizer._entities[s];},escapeHTML:function(strings,...values){var result='';for(var i=0;i=Object.keys(SETTINGS_KEYS).length){waitingForSettings.forEach(function(callback){callback();});waitingForSettings=[];kh_updateWatchers({settings:true});}} function kh_withSettings(callback){if(loadedSettings.size>=Object.keys(SETTINGS_KEYS).length){callback();}else{waitingForSettings.push(callback);}} function kh_getSettings(){loadedSettings=new Set();var lock=window.navigator.mozSettings.createLock();lock.get(SETTINGS_KEYS.DEFAULT).onsuccess=kh_parseDefault;lock.get(SETTINGS_KEYS.ENABLED).onsuccess=kh_parseEnabled;} function kh_parseDefault(){var value=this.result[SETTINGS_KEYS.DEFAULT];if(value){currentSettings.defaultLayouts=value;} kh_loadedSetting(SETTINGS_KEYS.DEFAULT);} function kh_parseEnabled(){var value=this.result[SETTINGS_KEYS.ENABLED];var needsSave=false;if(!value){currentSettings.enabledLayouts=map2dClone(currentSettings.defaultLayouts);needsSave=true;}else{var type=typeof value;if(type==='string'){try{currentSettings.enabledLayouts={};var oldSettings=JSON.parse(value);oldSettings.forEach(function(layout){if(layout.enabled){var manifestURL=layout.manifestURL;if(!manifestURL){manifestURL=layout.appOrigin+'/manifest.webapp';} map2dSet.call(currentSettings.enabledLayouts,manifestURL,layout.layoutId);}});}catch(e){currentSettings.enabledLayouts=map2dClone(currentSettings.defaultLayouts);needsSave=true;}}else{currentSettings.enabledLayouts=value;}} kh_loadedSetting(SETTINGS_KEYS.ENABLED);if(needsSave){KeyboardHelper.saveToSettings();}} function kh_migrateDeprecatedSettings(deprecatedSettings){var settingEntry=DEPRECATE_KEYBOARD_SETTINGS.en;if(deprecatedSettings[settingEntry]===undefined){return;} currentSettings.enabledLayouts[defaultKeyboardManifestURL]={number:true};var hasEnabledLayout=false;for(var key in DEPRECATE_KEYBOARD_SETTINGS){settingEntry=DEPRECATE_KEYBOARD_SETTINGS[key];if(deprecatedSettings[settingEntry]){hasEnabledLayout=true;if(key in MULTI_LAYOUT_MAP){MULTI_LAYOUT_MAP[key].forEach(function enableLayout(layoutId){map2dSet.call(currentSettings.enabledLayouts,defaultKeyboardManifestURL,layoutId);});}else{map2dSet.call(currentSettings.enabledLayouts,defaultKeyboardManifestURL,key);}}} if(!hasEnabledLayout){map2dSet.call(currentSettings.enabledLayouts,defaultKeyboardManifestURL,'en');} var deprecatedSettingsQuery={};for(key in DEPRECATE_KEYBOARD_SETTINGS){settingEntry=DEPRECATE_KEYBOARD_SETTINGS[key];deprecatedSettingsQuery[settingEntry]=null;} window.navigator.mozSettings.createLock().set(deprecatedSettingsQuery);KeyboardHelper.saveToSettings();} function kh_loadJSON(href,callback){if(!callback){return;} var xhr=new XMLHttpRequest();xhr.onerror=function(){console.error('Failed to fetch file: '+href,xhr.statusText);};xhr.onload=function(){callback(xhr.response);};xhr.open('GET',href,true);xhr.responseType='json';xhr.send();} function kh_getMultiSettings(settings,callback){var results={};try{var lock=navigator.mozSettings.createLock();} catch(e){console.warn('Exception in mozSettings.createLock():',e,'\nUsing default values');for(var p in settings){results[p]=settings[p];} callback(results);} var settingNames=Object.keys(settings);var numSettings=settingNames.length;var numResults=0;for(var i=0;i=0;i--){this.setLayoutIsDefault(kbManifestURL,langIndependentLayouts[i].layoutId,true);} if(reset){currentSettings.enabledLayouts=map2dClone(currentSettings.defaultLayouts);} for(i=newKbLayouts.length-1;i>=0;i--){this.setLayoutIsDefault(kbManifestURL,newKbLayouts[i].layoutId,true);this.setLayoutEnabled(kbManifestURL,newKbLayouts[i].layoutId,true);} this.saveToSettings();}.bind(this));}};KeyboardHelper.init();}(window));;'use strict';(function(exports){var LOCALES_FILE='/shared/resources/languages.json';function readFile(file,callback){return new Promise(function(resolve,reject){var xhr=new XMLHttpRequest();xhr.onreadystatechange=function loadFile(){if(xhr.readyState===4){if(xhr.status===0||xhr.status===200){resolve(xhr.response);}else{reject(xhr.statusText);}}};xhr.open('GET',file,true);xhr.responseType='json';xhr.send();});} function onError(name){console.error('Error checking setting '+name);} function readSetting(name,callback){var settings=window.navigator.mozSettings;if(!settings||!settings.createLock){return callback(null);} return settings.createLock().get(name).then(function(res){return res[name];},onError.bind(null,name));} exports.LanguageList={_languages:null,_readFile:readFile,_readSetting:readSetting,_extendPseudo:function(languages,currentLang,pseudoEnabled){if(!pseudoEnabled){for(var code in languages){var isCurrent=(code===currentLang);if(code.indexOf('-x-ps')>-1&&!isCurrent){delete languages[code];}}} if(!document.l10n){return Promise.resolve(languages);} var runtimePseudoCodes=Object.keys(document.l10n.pseudo).filter(code=>!(code in languages)&&(code===currentLang||pseudoEnabled));function obj(arr1,arr2){const zipped=[];arr1.forEach(x=>{arr2.forEach(y=>{zipped.push([x,y]);});});return zipped.reduce((obj,[x,y])=>Object.assign(obj,{[x]:y}),{});} return Promise.all(runtimePseudoCodes.map(code=>document.l10n.pseudo[code].getName())).then(names=>Object.assign(languages,obj(runtimePseudoCodes,names)));},_extendAdditional:function(languages,ver,additional){for(var lang in additional){for(var i=0,locale;locale=additional[lang][i];i++){if(locale.target===ver){languages[lang]=locale.name;break;}}}},_removeWithNoSpeech:function(languages,srEnabled){if(srEnabled){var speechLangs=new Set(window.speechSynthesis.getVoices().map(v=>v.lang.split('-')[0]));for(var langName in languages){if(!speechLangs.has(langName.split('-')[0])){delete languages[langName];}}}},_copyObj:function(obj){var copy=Object.create(null);for(var prop in obj){copy[prop]=obj[prop];} return copy;},_parseVersion:function(ver){return ver.split('.').slice(0,2).join('.');},_build:function(){return Promise.all([this._languages||(this._languages=this._readFile(LOCALES_FILE)),this._readSetting('language.current'),this._readSetting('devtools.pseudolocalization.enabled')]).then(([langsFromFile,current,pseudoEnabled])=>{var langs=this._copyObj(langsFromFile);return Promise.all([this._extendPseudo(langs,current,pseudoEnabled),this._readSetting('langpack.channel'),current,this._readSetting('accessibility.screenreader'),navigator.mozApps.getAdditionalLanguages()]);}).then(([langs,ver,current,srEnabled,addl])=>{this._extendAdditional(langs,this._parseVersion(ver),addl);this._removeWithNoSpeech(langs,srEnabled);return[langs,current];});},get:function(callback){if(!callback){return;} this._build().then(Function.prototype.apply.bind(callback,null));},wrapBidi:function(langCode,langName){var rtlList=['ar','he','fa','ps','ar-x-psbidi','ur'];var lEmbedBegin=(rtlList.indexOf(langCode)>=0)?'\u202b':'\u202a';var lEmbedEnd='\u202c';return lEmbedBegin+langName+lEmbedEnd;}};}(window));;'use strict';var SettingsListener={_lock:null,_observers:[],getSettingsLock:function sl_getSettingsLock(){if(this._lock&&!this._lock.closed){return this._lock;} var settings=window.navigator.mozSettings;return(this._lock=settings.createLock());},observe:function sl_observe(name,defaultValue,callback){var settings=window.navigator.mozSettings;if(!settings){window.setTimeout(function(){callback(defaultValue);});return;} var req;try{req=this.getSettingsLock().get(name);}catch(e){console.warn('Stale lock in settings_listener.js.','See https://bugzilla.mozilla.org/show_bug.cgi?id=793239');this._lock=null;req=this.getSettingsLock().get(name);} req.addEventListener('success',(function onsuccess(){callback(typeof(req.result[name])!='undefined'?req.result[name]:defaultValue);}));var settingChanged=function settingChanged(evt){callback(evt.settingValue);};settings.addObserver(name,settingChanged);this._observers.push({name:name,callback:callback,observer:settingChanged});},unobserve:function sl_unobserve(name,callback){var settings=window.navigator.mozSettings;var that=this;this._observers.forEach(function(value,index){if(value.name===name&&value.callback===callback){settings.removeObserver(name,value.observer);that._observers.splice(index,1);}});}};;'use strict';(function(exports){function Version(str){str=str||'0.0';var parts=str.split('.');this.major=parts[0];this.minor=parts[1];this.toString=function(){return''+str;};} function InfoResult(current,previous){this.current=current;this.previous=previous;} InfoResult.prototype.isUpgrade=function(){var prev=this.previous,curr=this.current,isUpgrade=false;if(prev&&curr){isUpgrade=curr.major>prev.major||curr.minor>prev.minor;} return isUpgrade;};InfoResult.prototype.delta=function(){var prev=this.previous,curr=this.current;var delta='';if(prev){delta+=prev.major+'.'+prev.minor;} delta+='..';if(curr){delta+=curr.major+'.'+curr.minor;} return delta;};function getSetting(setting,cb,errback){var req=navigator.mozSettings.createLock().get(setting);req.onsuccess=function(){var value=req.result[setting];if(typeof cb==='function'){cb(value);}};req.onerror=function(){if(typeof errback==='function'){errback(req.error);}};} function getCurrent(){return new Promise(function(resolve,reject){getSetting('deviceinfo.os',function(value){resolve(value?new Version(value):null);},function(err){reject(err);});});} function getPrevious(){return new Promise(function(resolve,reject){getSetting('deviceinfo.previous_os',function(value){resolve(value?new Version(value):null);},function(err){resolve(null);});});} function updatePrevious(str){var currentPromise=str?Promise.resolve(new Version(str)):getCurrent();var setPromise=new Promise(function(resolve,reject){currentPromise.then(function(version){if(version){var req=navigator.mozSettings.createLock().set({'deviceinfo.previous_os':version.toString()});req.onsuccess=function(){resolve(version);};req.onerror=function(){var reason=req.error;reject(reason);};}else{resolve(null);}},function(err){reject('Error getting previous version: ',err);});});return setPromise;} function getVersionInfo(){var info=new InfoResult();var infoPromise=new Promise(function(resolve,reject){Promise.all([getCurrent().then(function(version){info.current=version;}),getPrevious().then(function(version){info.previous=version;})]).then(function(){resolve(info);},reject);});return infoPromise;} exports.VersionHelper={updatePrevious:updatePrevious,getVersionInfo:getVersionInfo};})(window);;'use strict';function eventSafety(obj,event,callback,timeout){if(typeof callback==='number'){timeout=callback;callback=null;} if(!timeout){throw new Error('You must pass a valid timeout value to `eventSafety`.');} return new Promise((resolve)=>{var finishTimeout;function done(e){if(e&&e.target!==obj&&(e.type==='transitionend'||e.type==='animationend')){return;} clearTimeout(finishTimeout);obj.removeEventListener(event,done);if(callback){resolve(callback.apply(this,arguments));}else{resolve(e);}} finishTimeout=setTimeout(done,timeout);obj.addEventListener(event,done);});};(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);})();;'use strict';var utils=window.utils||{};utils.status=(function(){var STATUS_TIME=2000;var statusMsg=document.querySelector('#statusMsg');var hidingTimeout;var transitionEndTimeout;var additionalLine;var hideAnimationDone=function(){statusMsg.removeEventListener('transitionend',hideAnimationDone);statusMsg.classList.add('hidden');};var showAnimationDone=function(){if(transitionEndTimeout){clearTimeout(transitionEndTimeout);} statusMsg.removeEventListener('transitionend',showAnimationDone);hidingTimeout=setTimeout(utils.status.hide,STATUS_TIME);};var hideStatus=function(){statusMsg.addEventListener('transitionend',hideAnimationDone);statusMsg.classList.remove('opening');statusMsg.classList.remove('bannerStart');statusMsg.querySelector('p').removeAttribute('data-l10n-id');if(additionalLine){statusMsg.removeChild(additionalLine);additionalLine=null;}};var setL10nAttributes=function(node,l10n){if(l10n&&l10n.id){navigator.mozL10n.setAttributes(node,l10n.id,l10n.args);return true;}else{console.error('Status arguments must be objects');return false;}};var showStatus=function(mainMessage,extra){statusMsg.removeEventListener('transitionend',showAnimationDone);statusMsg.removeEventListener('transitionend',hideAnimationDone);LazyLoader.load([statusMsg],function _loaded(){if(!setL10nAttributes(statusMsg.querySelector('p'),mainMessage)){return;} if(extra){additionalLine=document.createElement('p');statusMsg.appendChild(additionalLine);setL10nAttributes(additionalLine,extra);} if(statusMsg.classList.contains('opening')){clearTimeout(hidingTimeout);hidingTimeout=setTimeout(hideStatus,STATUS_TIME);return;} statusMsg.classList.remove('hidden');statusMsg.addEventListener('transitionend',showAnimationDone);setTimeout(function displaying(){statusMsg.classList.add('opening');statusMsg.classList.add('bannerStart');transitionEndTimeout=setTimeout(showAnimationDone,STATUS_TIME);},10);});};return{show:showStatus,hide:hideStatus};})();;'use strict';var utils=window.utils||{};(function(){utils.overlay={};var overlay=document.querySelector('#loading-overlay'),statusContainer=overlay.querySelector('p[role="status"]'),progressActivity=document.querySelector('#progress-activity'),progressTitle=document.querySelector('#progress-title'),progressElement=document.querySelector('#progress-element'),progressMsg=document.querySelector('#progress-msg'),menu=document.querySelector('#loading-overlay menu'),cancelButton=document.querySelector('#cancel-overlay');function ProgressBar(pMsgId,pClass){var counter=0;var total=0;var progressTextId=pMsgId||'genericProgress';var clazz=pClass;progressElement.setAttribute('value',0);function showMessage(){var attributes=progressTextId=='infiniteProgress'?{n:counter}:{current:counter,total:total};document.l10n.setAttributes(progressMsg,progressTextId,attributes);} this.update=function(value){if(value&&value<=total&&value>=counter){counter=value;}else{counter++;} progressElement.setAttribute('value',((counter*100)/total).toFixed());showMessage();};this.setTotal=function(ptotal){total=ptotal;};this.setClass=function(clazzName){setClass(clazzName);clazz=clazzName;if(clazzName==='activityBar'||clazzName==='spinner'){progressMsg.removeAttribute('data-l10n-id');}};this.setHeaderMsg=function(headerMsgId){progressTitle.setAttribute('data-l10n-id',headerMsgId);};} utils.overlay.isAnimationPlaying=false;utils.overlay.isShown=false;utils.overlay._show=function _show(messageId,progressClass,textId){progressActivity.classList.remove('hide');if(typeof messageId==='string'){progressTitle.setAttribute('data-l10n-id',messageId);}else{document.l10n.setAttributes(progressTitle,messageId.id,messageId.args);} progressMsg.textContent=null;progressMsg.removeAttribute('data-l10n-id');if(utils.overlay.isShown){return;} overlay.classList.remove('hide');overlay.classList.remove('fade-out');overlay.classList.add('fade-in');utils.overlay.isAnimationPlaying=true;window.dispatchEvent(new CustomEvent('loadingoverlayshowing'));overlay.addEventListener('animationend',function ov_onFadeIn(ev){utils.overlay.isAnimationPlaying=false;overlay.removeEventListener('animationend',ov_onFadeIn);overlay.classList.remove('no-opacity');utils.overlay.isShown=true;});};utils.overlay.show=function show(messageId,progressClass,textId){var out;out=new ProgressBar(textId,progressClass);setClass(progressClass);utils.overlay.hideMenu();if(!utils.overlay.isAnimationPlaying){utils.overlay._show(messageId,progressClass,textId);return out;} overlay.addEventListener('animationend',function ov_showWhenFinished(ev){overlay.removeEventListener('animationend',ov_showWhenFinished);utils.overlay._show(messageId,progressClass,textId);});return out;};utils.overlay.showMenu=function showMenu(){menu.classList.add('showed');};utils.overlay.hideMenu=function hideMenu(){menu.classList.remove('showed');};Object.defineProperty(utils.overlay,'oncancel',{set:function(cancelCb){if(typeof cancelCb==='function'){cancelButton.disabled=false;cancelButton.onclick=function on_cancel(e){delete cancelButton.onclick;cancelCb();return false;};}}});function setAsProgress(){statusContainer.classList.remove('loading-icon');progressElement.setAttribute('max','100');progressElement.setAttribute('value','0');} function setClass(clazzName){switch(clazzName){case'spinner':progressElement.classList.remove('pack-activity');statusContainer.classList.add('loading-icon');progressElement.removeAttribute('max');progressElement.removeAttribute('value');break;case'activityBar':case'progressActivity':progressElement.classList.add('pack-activity');setAsProgress();break;case'progressBar':progressElement.classList.remove('pack-activity');setAsProgress();break;}} utils.overlay._hide=function ov__hide(){if(!utils.overlay.isShown){return;} overlay.classList.remove('fade-in');overlay.classList.add('fade-out');utils.overlay.isAnimationPlaying=true;window.dispatchEvent(new CustomEvent('loadingoverlayhiding'));overlay.addEventListener('animationend',function ov_onFadeOut(ev){utils.overlay.isAnimationPlaying=false;overlay.removeEventListener('animationend',ov_onFadeOut);progressActivity.classList.add('hide');overlay.classList.add('no-opacity');overlay.classList.add('hide');utils.overlay.isShown=false;});};utils.overlay.hide=function ov_hide(){if(!utils.overlay.isAnimationPlaying){utils.overlay._hide();return;} overlay.addEventListener('animationend',function ov_hideWhenFinished(ev){overlay.removeEventListener('animationend',ov_hideWhenFinished);utils.overlay._hide();});};})();;'use strict';var utils=window.utils||{};if(typeof utils.config==='undefined'){(function(){var configs={};var initializing={};var initialized={};var EVENT_INITIALIZED='config_initialized';utils.config=utils.config||{};utils.config.reset=function(){configs={};initializing={};initialized={};};function onLoad(xhr,file,resolveCb){configs[file]=xhr.response;delete initializing[file];initialized[file]=true;document.dispatchEvent(new CustomEvent(EVENT_INITIALIZED,{detail:{file:file,success:true}}));resolveCb(configs[file]);} utils.config.load=function(file){return new Promise(function(resolve,reject){var isInitialized=initialized[file];if(isInitialized===true){resolve(configs[file]);return;} var isInitializing=initializing[file];if(isInitializing){var handler=function(expectedFile,e){document.removeEventListener(EVENT_INITIALIZED,handler);var file=e.detail.file;if(expectedFile!==file){return;} if(e.detail.success){resolve(configs[file]);} else{reject();}}.bind(null,file);document.addEventListener(EVENT_INITIALIZED,handler);return;} initializing[file]=true;var xhr=new XMLHttpRequest();xhr.open('GET',file,true);xhr.responseType='json';xhr.onload=function(){var resolvedCb=resolve;if(xhr.status!==200){resolvedCb=reject;} onLoad(xhr,file,resolvedCb);};xhr.onerror=function(){document.dispatchEvent(new CustomEvent(EVENT_INITIALIZED,{detail:{file:file,success:false}}));delete initializing[file];reject(xhr.error);};try{xhr.send(null);} catch(e){console.error('Error while loading config file: ',e.message);onLoad({status:404},file,reject);}});};})();};'use strict';var utils=window.utils||{};var SCALE_RATIO=window.devicePixelRatio||1;var LAST_IMPORT_TIMESTAMP_SUFFIX='_last_import_timestamp';function scale(size){return Math.round(SCALE_RATIO*size);} if(!utils.misc){utils.misc={};utils.misc.toMozContact=function(contact){var outContact=contact;if(!(contact instanceof mozContact)){outContact=new mozContact(contact);outContact.id=contact.id||outContact.id;} return outContact;};const FLAG_YEAR_IGNORED=9996;utils.misc.FLAG_YEAR_IGNORED=FLAG_YEAR_IGNORED;utils.misc.formatDate=function(date,customFormat){var dateString=null;try{var format=customFormat||{month:'short',day:'numeric'};var offset=date.getTimezoneOffset()*60*1000;var normalizedDate=new Date(date.getTime()+offset);var year=normalizedDate.getFullYear();if(year!==FLAG_YEAR_IGNORED){format.year='numeric';} var f=new Intl.DateTimeFormat(navigator.languages,format);dateString=f.format(normalizedDate);}catch(err){console.error('Error parsing date: ',err);throw err;} return dateString;};utils.misc.parseName=function(nameString){var MIN_LENGHT_SIGNIFICATIVE=3;var MIN_LENGHT_FN=2;var out={givenName:'',familyName:''};if(!nameString){return out;} var str=nameString.trim();if(!str){return out;} function startsWithUpper(str){var firstLetter=str.charAt(0);var capFirstLetter=firstLetter.toLocaleUpperCase();return(capFirstLetter===firstLetter);} var tokens=nameString.split(/\s+/);var significativeTokens={};for(var j=0;jMIN_LENGHT_SIGNIFICATIVE||startsWithUpper(token)){significativeTokens[token]=true;}} var totalTokens=tokens.length;var lastToken=totalTokens-1;var rolePrevToken;var remainingTokens=Object.keys(significativeTokens).length;var outGivenNames=[],outFamilyNames=[];var numFns=0;while(lastToken>=0){if(significativeTokens[tokens[lastToken]]){remainingTokens--;} var currToken=tokens[lastToken],nextToken=tokens[lastToken+1],prevToken=tokens[lastToken-1];if(!nextToken&&prevToken){outFamilyNames.push(currToken);numFns++;rolePrevToken='FN';} else if(!prevToken){outGivenNames.push(currToken);rolePrevToken='GN';} else if(nextToken){if(!significativeTokens[currToken]){if(rolePrevToken==='FN'){outFamilyNames.push(currToken);} else{outGivenNames.push(currToken);}} else if(currToken.length=2&&numFns<2){outFamilyNames.push(currToken);numFns++;rolePrevToken='FN';} else{outGivenNames.push(currToken);rolePrevToken='GN';}}} lastToken--;} out.givenName=outGivenNames.reverse().join(' ').trim();out.familyName=outFamilyNames.reverse().join(' ').trim();return out;};utils.misc.getPreferredPictureBox=function(){var imgThumbSize=oauthflow.params.facebook.imgThumbSize;var out={width:scale(imgThumbSize)};out.height=out.width;return out;};utils.misc.getPreferredPictureDetail=function(){var imgDetailWidth=oauthflow.params.facebook.imgDetailWidth;return scale(imgDetailWidth);};utils.misc.setTimestamp=function(type,callback){ImportStatusData.put(type+LAST_IMPORT_TIMESTAMP_SUFFIX,Date.now()).then(callback);};utils.misc.getTimestamp=function(type,callback){ImportStatusData.get(type+LAST_IMPORT_TIMESTAMP_SUFFIX).then(callback);};};'use strict';var utils=window.utils||{};if(!utils.sdcard){var SdCard=utils.sdcard={NOT_INITIALIZED:0,NOT_AVAILABLE:1,AVAILABLE:2,SHARED:3,observers:{}};SdCard.status=SdCard.NOT_INITIALIZED;SdCard.deviceStorages=navigator.getDeviceStorages('sdcard');SdCard.deviceStorage=Array.isArray(SdCard.deviceStorages)&&SdCard.deviceStorages[0];SdCard._toStatus=function toStatus(state){switch(state){case'available':SdCard.status=SdCard.AVAILABLE;break;case'shared':SdCard.status=SdCard.SHARED;break;case'unavailable':case'deleted':SdCard.status=SdCard.NOT_AVAILABLE;break;}};SdCard.updateStorageState=function sd_updateStorageState(state){SdCard._toStatus(state);Object.keys(this.observers).forEach(function onObserver(name){if(typeof(SdCard.observers[name])==='function'){SdCard.observers[name].call(null,state);}});};if(SdCard.deviceStorage){SdCard.deviceStorage.addEventListener('change',function sd_deviceStorageChangeHandler(e){SdCard.updateStorageState(e.reason);});if(SdCard.status===SdCard.NOT_INITIALIZED){SdCard.deviceStorage.available().onsuccess=(function(e){SdCard.updateStorageState(e.target.result);});}} SdCard.checkStorageCard=function sd_checkStorageCard(){return SdCard.status===SdCard.AVAILABLE;};SdCard.getStatus=function(cb){if(!SdCard.deviceStorage){SdCard._toStatus('unavailable');cb(SdCard.status);return;} var req=SdCard.deviceStorage.available();req.onsuccess=function(){SdCard._toStatus(req.result);cb(SdCard.status);};req.onerror=function(){console.error('Error while determining SD Status',req.error.name);cb(SdCard.status);};};SdCard.retrieveFiles=function retrieveFilesContent(mimes,exts,cb){var fileArray=[];var forbiddenDirectories=['.Trash'];var storages=navigator.getDeviceStorages('sdcard');var numberOfStorages=storages.length;var currentStorage=0;var cursorOnError=function(){cb(this.error.name);};var reExt=new RegExp('.('+exts.join('|')+')$');var cursorOnSuccess=function(e){var file=e.target.result;if(!file){if(++currentStorage{const END_VCARD='end:vcard';const CHUNK_SIZE=1*1024*1024;var fileReader=new FileReader();var result=0;(function readChunk(offset,buffer){if(offset>=file.size){resolve(result);return;} var chunk=file.slice(offset,offset+CHUNK_SIZE);offset+=CHUNK_SIZE;fileReader.readAsText(chunk);fileReader.onload=function(){buffer+=fileReader.result;if(!buffer.match(/end:vcard/gi)){readChunk(offset,buffer);return;} var lastContactInChunk=buffer.toLowerCase().lastIndexOf(END_VCARD)+END_VCARD.length;cb(buffer.substr(0,lastContactInChunk)).then(partialResult=>{result+=partialResult;readChunk(offset,buffer.substr(lastContactInChunk+1));}).catch(error=>{console.warn(error);});};})(0,'');});};SdCard.subscribeToChanges=function(name,func,force){if(this.observers[name]!==undefined&&!force){return false;} this.observers[name]=func;return true;};SdCard.unsubscribeToChanges=function(name){if(this.observers[name]){delete this.observers[name];return true;}else{return false;}};};'use strict';function parseDataUri(str){var re=/^data:(.+);(charset=([^;]+))?;?base64,(.*)$/;var matches=re.exec(str);if(matches){return{mime:matches[1],charset:matches[3],value:matches[4]};} return null;} function ensureMimeType(type){type=type.toLowerCase();if(!MimeMapper.isSupportedType(type)){type=MimeMapper.guessTypeFromExtension(type)||type;} return type||'';} function b64toBlob(b64Data,contentType,sliceSize){if(!b64Data){console.error('No b64 data provided to convert to blob.');return;} contentType=contentType||'';sliceSize=sliceSize||1024;function charCodeFromCharacter(c){return c.charCodeAt(0);} var blob;try{var byteCharacters=atob(b64Data);var byteArrays=[];for(var offset=0;offset=4&&ch==='"'){inLabel=!inLabel;currentLine+=ch;continue;} if(multiline===true){if((/[\r\t\s\n]/).test(ch)){continue;}else{multiline=false;}} var next=this.contents[i+1];if(inLabel||(ch!=='\n'&&ch!=='\r')){if(!(/^PHOTO/i).test(currentLine)&&ch==='='&&next&&next.search(/(\r|\n)/)!==-1){multiline=true;continue;} currentLine+=ch;if(i!==l-1){continue;}} var firstCharNextLine=this.contents[i+2];if((firstCharNextLine===WHITE_SPACE)&&(/[\r\t\s\n]/).test(next)&&(/^PHOTO/i).test(currentLine)){multiline=true;continue;} if(next&&(next===WHITE_SPACE||next==='\t')){multiline=true;continue;} if(reBeginCard.test(currentLine)){currentLine='';currentVersion=0;continue;} if(reEndCard.test(currentLine)){cardsProcessed+=1;if(cardsProcessed===VCFReader.CONCURRENCY||(cardsProcessed+this.processed)===this.total){_parseEntries(cardArray,callPost);break;} currentLine='';cardArray.push([]);continue;} if(currentLine){var matches=reVersion.exec(currentLine);if(matches===null){cardArray[cardArray.length-1].push(currentLine);}else{currentVersion=parseFloat(matches[1]||'0');}} currentLine='';}};VCFReader._decodeQuoted=_decodeQuoted;VCFReader.processAddr=_processAddr;VCFReader.processName=_processName;VCFReader.vcardToContact=vcardToContact;VCFReader.utils={parseDataUri:parseDataUri,b64toBlob:b64toBlob};return VCFReader;})();;'use strict';var utils=window.utils||{};utils.importFromVcard=function(file,callback){var MERGE_DEPENDENCIES=['/shared/js/simple_phone_matcher.js','/shared/js/contacts/merger_adapter.js','/shared/js/contacts/contacts_merger.js','/shared/js/contacts/contacts_matcher.js'];Loader.utility('Overlay',function(){LazyLoader.load(MERGE_DEPENDENCIES,_loaded);});function _loaded(){var importedContacts=0;var cancelled=false;var importer=null;var text=null;var progress=utils.overlay.show('memoryCardContacts-reading','activityBar');utils.overlay.showMenu();utils.overlay.oncancel=function oncancel(){cancelled=true;if(importer){importer.finish();}else{utils.overlay.hide();}};readVCard(function(vcardText){if(vcardText){processTextFromFile(vcardText);}else{callback();}});function readVCard(cb){var reader;if(typeof file==='string'){cb(file);}else{reader=new FileReader();reader.onloadend=function(){text=reader.result;if(text){cb(text);}};try{reader.readAsText(file);} catch(ex){console.error('Error reading the file '+ex.message);import_error();cb();}}} function processTextFromFile(textFromFile){if(cancelled){return;} var reader=new VCardReader(textFromFile);var match=textFromFile&&textFromFile.match(/END:VCARD/g);var cursor=reader.getAll();var numContacts=match?match.length:0;var numDupsMerged=0;var firstContact=null;var _doContinue=function(savedContact){if(savedContact){if(!firstContact){firstContact=savedContact;} imported_contact();} if(!cancelled){cursor.continue();}};cursor.onsuccess=function(evt){if(evt.target.result){var contact=evt.target.result;Matcher.match(contact,'passive',{onmatch:function(matches){var callbacks={success:function(mergedContact){numDupsMerged++;_doContinue(mergedContact);},error:_doContinue};contacts.adaptAndMerge(contact,matches,callbacks);},onmismatch:function(){var req=navigator.mozContacts.save(contact);req.onsuccess=function(){_doContinue(contact);};}});}else{utils.overlay.hide();if(!cancelled){var msgImported={id:'memoryCardContacts-imported3',args:{n:importedContacts}};var msgDupsMerged=numDupsMerged?{id:'contactsMerged',args:{numDups:numDupsMerged}}:null;utils.status.show(msgImported,msgDupsMerged);} if(importedContacts>0){callback(importedContacts,firstContact.id);}else{callback(importedContacts);}}};import_read(numContacts);} function import_read(n){progress.setClass('progressBar');progress.setHeaderMsg('memoryCardContacts-importing');progress.setTotal(n);} function imported_contact(){importedContacts++;if(!cancelled){progress.update();}} function import_error(e){console.error('Error importing from vcard: '+e.message);var cancel={title:'cancel',callback:function(){ConfirmDialog.hide();}};var retry={title:'retry',isRecommend:true,callback:function(){ConfirmDialog.hide();processTextFromFile(text);}};ConfirmDialog.show(null,'memoryCardContacts-error',cancel,retry);utils.overlay.hide();}}};;'use strict';function SimContactsImporter(targetIcc){if(targetIcc===null){throw new Error('We need an icc to continue with this operation');} var pointer=0;var CHUNK_SIZE=5;var numResponses=0;var self=this;var mustFinish=false;var loadedMatch=false;var DEFAULT_TEL_TYPE='other';var icc=targetIcc;var iccId=icc.iccInfo&&icc.iccInfo.iccid;var numDupsMerged=0;function generateIccContactUrl(contactid){var urlValue='urn:'+'uuid:'+(iccId||'iccId')+'-'+contactid;return[{type:['source','sim'],value:urlValue}];} function notifyFinish(){if(typeof self.onfinish==='function'){window.setTimeout(self.onfinish,0,numDupsMerged,iccId);}} function notifyImported(){if(typeof self.onimported==='function'){window.setTimeout(self.onimported,0);}} function continueCb(){numResponses++;pointer++;notifyImported();if(pointer=self.items.length){notifyFinish();}} function startMigration(){if(!mustFinish&&Array.isArray(self.items)&&self.items.length>0){importSlice(0);} else{notifyFinish();}} function onContactsReadyForImport(){if(typeof self.onread==='function'){self.onread(self.items.length);} if(loadedMatch){startMigration();} else{document.addEventListener('matchLoaded',function mloaded(){document.removeEventListener('matchLoaded',mloaded);startMigration();});}} this.start=function(){numDupsMerged=0;if(mustFinish){notifyFinish();return;} LazyLoader.load(['/shared/js/simple_phone_matcher.js','/shared/js/contacts/contacts_matcher.js','/shared/js/contacts/contacts_merger.js','/shared/js/contacts/utilities/image_thumbnail.js','/shared/js/contacts/merger_adapter.js'],function loaded(){loadedMatch=true;document.dispatchEvent(new CustomEvent('matchLoaded'));});var requestAdn,requestSdn;if(icc&&icc.readContacts){requestAdn=icc.readContacts('adn');}else{throw new Error('Not able to obtain a SIM import function from platform');} requestAdn.onsuccess=function onsuccess(){if(mustFinish){notifyFinish();return;} self.items=requestAdn.result||[];requestSdn=icc.readContacts('sdn');requestSdn.onsuccess=function onsuccess(){if(mustFinish){notifyFinish();return;} if(Array.isArray(requestSdn.result)){self.items=self.items.concat(requestSdn.result);} onContactsReadyForImport();};requestSdn.onerror=function error(){if(mustFinish){notifyFinish();return;} console.warn('Could not read SDN Contacts from SIM Card',error.name);onContactsReadyForImport();};};requestAdn.onerror=function error(){if(typeof self.onerror==='function'){self.onerror(requestAdn.error);}};};this.finish=function(){mustFinish=true;};function importSlice(from){for(var i=from;i=0;i--){this._toAsciiForm[accentedForms[i]]=letter;}}},toAscii:function normalizer_toAscii(str){if(!str||typeof str!='string'){return'';} if(!this._toAsciiForm){Normalizer.initAsciiNormalizer();} var result='';for(var i=0,len=str.length;i/g,'>');if(escapeQuotes){return escaped.replace(/"/g,'"').replace(/'/g,''');} return escaped;},unescapeHTML:function normalizer_unescapeHTML(text){return text.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,'\'');},escapeRegExp:function normalizer_escapeRegExp(str){return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,'\\$&');}};;'use strict';var LazyLoader=(function(){function LazyLoader(){this._loaded={};this._isLoading={};} LazyLoader.prototype={_js:function(file,callback){var script=document.createElement('script');script.src=file;script.async=false;script.addEventListener('load',callback);document.head.appendChild(script);this._isLoading[file]=script;},_css:function(file,callback){var style=document.createElement('link');style.type='text/css';style.rel='stylesheet';style.href=file;document.head.appendChild(style);callback();},_html:function(domNode,callback){if(domNode.getAttribute('is')){this.load(['/shared/js/html_imports.js'],function(){HtmlImports.populate(callback);}.bind(this));return;} for(var i=0;i{deferred.resolve=resolve;});if(!Array.isArray(files)){files=[files];} var loadsRemaining=files.length,self=this;function perFileCallback(file){if(self._isLoading[file]){delete self._isLoading[file];} self._loaded[file]=true;if(--loadsRemaining===0){deferred.resolve();if(callback){callback();}}} for(var i=0;i0;},isWpsAvailable:function(network){var capabilities=this.getCapabilities(network);for(var i=0;inetworksObject[key].relSignalStrength){networksObject[key]=network;}});return networksObject;},_onReqProxySuccess:function(reqProxy,availableNetworks,knownNetworks){reqProxy.result=this._unionOfNetworks(availableNetworks,knownNetworks);reqProxy.onsuccess();},getAvailableAndKnownNetworks:function(){var self=this;var reqProxy={onsuccess:function(){},onerror:function(){}};var knownNetworks={};var availableNetworks={};var knownNetworksReq=null;var availableNetworksReq=this.getWifiManager().getNetworks();availableNetworksReq.onsuccess=function anrOnSuccess(){availableNetworks=self._networksArrayToObject(availableNetworksReq.result);knownNetworksReq=self.getWifiManager().getKnownNetworks();knownNetworksReq.onsuccess=function knrOnSuccess(){knownNetworks=self._networksArrayToObject(knownNetworksReq.result);self._onReqProxySuccess(reqProxy,availableNetworks,knownNetworks);};knownNetworksReq.onerror=function knrOnError(){self._onReqProxySuccess(reqProxy,availableNetworks,knownNetworks);};};availableNetworksReq.onerror=function anrOnError(){reqProxy.error=availableNetworksReq.error;reqProxy.onerror();};return reqProxy;},getSignalLevel:function(network){return Math.min(Math.floor(network.relSignalStrength/20),4);}};;'use strict';var FxAccountsIACHelper=function FxAccountsIACHelper(){var DEFAULT_CONNECTION_STRING='fxa-mgmt';var default_rules={'manifestURLs':['app://system.gaiamobile.org/manifest.webapp','app://smart-system.gaiamobile.org/manifest.webapp']};var CONNECTION_STRING=DEFAULT_CONNECTION_STRING;var rules=default_rules;var port;var callbacks={};var eventListeners={};var init=function init(options){if(!options){return;} if(options.keyword&&typeof(options.keyword)=='string'&&options.keyword.length>0){CONNECTION_STRING=options.keyword;} if(options.rules&&typeof(options.rules)=='object'){rules=options.rules;}};var addEventListener=function addEventListener(eventName,listener){if(!eventListeners[eventName]){eventListeners[eventName]=[];} eventListeners[eventName].push(listener);};var removeEventListener=function removeEventListener(eventName,listener){var listeners=eventListeners[eventName];if(!listeners){return;} var index=listeners.indexOf(listener);if(index===-1){return;} listeners.splice(index,1);};var reset=function reset(){CONNECTION_STRING=DEFAULT_CONNECTION_STRING;rules=default_rules;eventListeners={};callbacks={};port=null;};var onMessage=function onMessage(evt){if(evt&&evt.data){var message=evt.data;if(message.eventName){var listeners=eventListeners[message.eventName];if(!listeners){return;} for(var listener in listeners){if(listeners[listener]&&typeof listeners[listener]==='function'){listeners[listener]();}} return;} var cbs,cb;if(message.methodName){cbs=callbacks[message.methodName];if(!cbs||!cbs.length){console.warn('No callbacks for method '+message.methodName);return;} while(cbs.length){cb=cbs.shift();if(!message.error){cb.successCb(message.data);}else{cb.errorCb(message.error);}}}}else{console.error('Unknown');}};var getSelf=function getSelf(cb,error){var request=navigator.mozApps.getSelf();request.onsuccess=function onSuccess(evt){cb(evt.target.result);};request.onerror=function onError(){if(error&&typeof(error)==='function'){error();}};};var requestQueue=[];var isConnecting=false;var connect=function connect(cb){if(isConnecting){return requestQueue.push(cb);} isConnecting=true;_connect(function onConnect(err){var next;isConnecting=false;if(typeof cb==='function'){cb(err);} while(!!(next=requestQueue.shift())){next&&next(err);}});};var _connect=function _connect(callback){getSelf(function onApp(app){if(!app){return;} app.connect(CONNECTION_STRING,rules).then(function(ports){if(!ports||ports.length!==1){return;} port=ports[0];callback&&callback();});});};var sendMessage=function sendMessage(message,successCb,errorCb){if(port){_sendMessage(message,successCb,errorCb);return;} connect(function(){_sendMessage(message,successCb,errorCb);});};var _sendMessage=function _sendMessage(message,successCb,errorCb){var name=message.name;if(!name){return;} if(!callbacks[name]){callbacks[name]=[];} callbacks[name].push({successCb:successCb,errorCb:errorCb});port.onmessage=onMessage;port.postMessage(message);};var getAccount=function getAccount(successCb,errorCb){sendMessage({'name':'getAccount'},successCb,errorCb);};var openFlow=function openFlow(successCb,errorCb){sendMessage({'name':'openFlow'},successCb,errorCb);};var logout=function logout(successCb,errorCb){sendMessage({'name':'logout'},successCb,errorCb);};var refreshAuthentication=function refreshAuthentication(email,successCb,errorCb){sendMessage({'name':'refreshAuthentication','email':email},successCb,errorCb);};var resendVerificationEmail=function resendVerificationEmail(email,successCb,errorCb){sendMessage({'name':'resendVerificationEmail','email':email},successCb,errorCb);};connect();return{'addEventListener':addEventListener,'getAccount':getAccount,'init':init,'logout':logout,'openFlow':openFlow,'refreshAuthentication':refreshAuthentication,'removeEventListener':removeEventListener,'resendVerificationEmail':resendVerificationEmail,'reset':reset};}();;'use strict';var SimManager=(function(){function Icc(mozIcc){this.mozIcc=mozIcc;} Icc.prototype={skipped:false,unlocked:false,alreadyImported:false,mozIcc:null,isLocked:function(){return!this.unlocked&&lockStates.indexOf(this.mozIcc.cardState)!==-1;}};function showRetryCount(icc,lockType,uiElement){var request=icc.mozIcc.getCardLockRetryCount(lockType);request.onsuccess=function(){var retryCount=request.result.retryCount;if(retryCount){var l10nArgs={n:retryCount};document.l10n.setAttributes(uiElement,'inputCodeRetriesLeft',l10nArgs);uiElement.classList.remove('hidden');}};request.onerror=function(){console.error('Could not fetch CardLockRetryCount',request.error.name);};} var lockStates=['pinRequired','pukRequired','networkLocked','corporateLocked','serviceProviderLocked','network1Locked','network2Locked','hrpdNetworkLocked','ruimCorporateLocked','ruimServiceProviderLocked'];return{icc0:null,icc1:null,simSlots:window.navigator.mozMobileConnections?window.navigator.mozMobileConnections.length:0,_unlockingIcc:null,init:function sm_init(){this.mobConn=window.navigator.mozMobileConnections;if(!this.mobConn){return;} this.iccManager=window.navigator.mozIccManager;if(!this.iccManager){return;} this.icc0=null;this.icc1=null;if(this.iccManager.iccIds[0]){this.updateIccState(this.iccManager.iccIds[0]);} if(this.iccManager.iccIds[1]){this.updateIccState(this.iccManager.iccIds[1]);} this.iccManager.addEventListener('iccdetected',this.handleIccState.bind(this));this.alreadyImported=false;},handleUnlockError:function sm_handleUnlockError(lockType,retryCount){var l10nArgs={n:retryCount};switch(lockType){case'pin':if(retryCount===0){this.showPukScreen(this._unlockingIcc);break;} UIManager.pinInput.value='';UIManager.pinInput.classList.add('onerror');UIManager.pinError.classList.remove('hidden');document.l10n.setAttributes(UIManager.pinRetriesLeft,'inputCodeRetriesLeft',l10nArgs);UIManager.pinRetriesLeft.classList.remove('hidden');if(retryCount===1){UIManager.pinError.querySelector('.lastchance').classList.remove('hidden');}else{document.l10n.setAttributes(UIManager.pinError.querySelector('.main'),'pinAttemptMsg2',l10nArgs);UIManager.pinError.querySelector('.main').classList.remove('hidden');} break;case'puk':UIManager.pukInput.value='';UIManager.pukInput.classList.add('onerror');UIManager.pukError.classList.remove('hidden');UIManager.pukInfo.classList.add('hidden');document.l10n.setAttributes(UIManager.pukRetriesLeft,'inputCodeRetriesLeft',l10nArgs);UIManager.pukRetriesLeft.classList.remove('hidden');if(retryCount===1){UIManager.pukError.querySelector('.lastchance').classList.remove('hidden');}else{document.l10n.setAttributes(UIManager.pukError.querySelector('.main'),'pukAttemptMsg2',l10nArgs);UIManager.pukError.querySelector('.main').classList.remove('hidden');} break;case'nck':case'cck':case'spck':UIManager.xckInput.value='';UIManager.xckInput.classList.add('onerror');UIManager.xckError.classList.remove('hidden');document.l10n.setAttributes(UIManager.xckRetriesLeft,'inputCodeRetriesLeft',l10nArgs);UIManager.xckRetriesLeft.classList.remove('hidden');if(retryCount==1){UIManager.xckError.querySelector('.lastchance').classList.remove('hidden');}else{document.l10n.setAttributes(UIManager.xckError.querySelector('.main'),'nckAttemptMsg2',l10nArgs);UIManager.xckError.querySelector('.main').classList.remove('hidden');} break;}},available:function sm_available(){var icc=this.guessIcc();return(icc&&icc.cardState==='ready');},handleIccState:function sm_handleIccState(event){this.updateIccState(event.iccId);},updateIccState:function(iccId){var iccInfo=this.iccManager.getIccById(iccId);if(!iccInfo){throw new Error('Unrecognized iccID: '+iccId);} if(this.mobConn[0]&&iccId===this.mobConn[0].iccId){this.icc0=new Icc(iccInfo);}else if(this.mobConn[1]&&iccId===this.mobConn[1].iccId){this.icc1=new Icc(iccInfo);}else{console.warn('ICC detected in unsupported slot',iccId);}},handleCardState:function sm_handleCardState(callback,skipUnlockScreen){this._unlockingIcc=null;SimManager.checkSIMButton();if(typeof callback==='function'){this.finishCallback=callback;} if(this.shouldShowUnlockScreen(this.icc0)&&!skipUnlockScreen){this.showUnlockScreen(this.icc0);}else if(this.shouldShowUnlockScreen(this.icc1)&&!skipUnlockScreen){this.showUnlockScreen(this.icc1);}else if(this.shouldShowSIMInfoScreen()){this.resetSkipped();this.showSIMInfoScreen();}else{this.resetSkipped();this.finish();}},finish:function(){this.hideScreen();this.hideSIMInfoScreen();var showCellData=(this.icc0&&!this.icc0.isLocked())||(this.icc1&&!this.icc1.isLocked());this.finishCallback&&this.finishCallback(showCellData);},shouldShowUnlockScreen:function sm_shouldShowLockScreen(icc){return icc&&!icc.skipped&&icc.isLocked();},shouldShowSIMInfoScreen:function sm_shouldShowSIMInfoScreen(){return(this.icc0&&this.icc1);},showUnlockScreen:function sm_showUnlockScreen(icc){if(icc.unlocked){return;} this._unlockingIcc=icc;switch(icc.mozIcc.cardState){case'pinRequired':this.showPinScreen(icc);break;case'pukRequired':this.showPukScreen(icc);break;case'networkLocked':case'corporateLocked':case'serviceProviderLocked':case'network1Locked':case'network2Locked':case'hrpdNetworkLocked':case'ruimCorporateLocked':case'ruimServiceProviderLocked':this.showXckScreen(icc);break;default:throw new Error('Cannot show SIM unlock screen, unknown cardState '+ icc.mozIcc.cardState);}},voiceChangeListeners:[],updateSIMInfoText:function sm_updateSIMInfoText(icc){var iccNumber=(icc===this.icc0)?1:2;if(icc&&icc.isLocked()){UIManager['simInfo'+iccNumber].classList.add('locked');UIManager['simCarrier'+iccNumber].setAttribute('data-l10n-id','simPinLocked');UIManager['simNumber'+iccNumber].removeAttribute('data-l10n-id');UIManager['simNumber'+iccNumber].textContent='';}else{UIManager['simInfo'+iccNumber].classList.remove('locked');var mobConn=this.mobConn[iccNumber-1];var operator=MobileOperator.userFacingInfo(mobConn).operator;if(!operator&&!this.voiceChangeListeners[iccNumber-1]){this.voiceChangeListeners[iccNumber-1]=function(evt){var operator=MobileOperator.userFacingInfo(mobConn).operator;if(operator){UIManager['simCarrier'+iccNumber].removeAttribute('data-l10n-id');UIManager['simCarrier'+iccNumber].textContent=operator;mobConn.removeEventListener('voicechange',this.voiceChangeListeners[iccNumber-1]);this.voiceChangeListeners[iccNumber-1]=null;}}.bind(this);mobConn.addEventListener('voicechange',this.voiceChangeListeners[iccNumber-1]);} if(operator){UIManager['simCarrier'+iccNumber].removeAttribute('data-l10n-id');UIManager['simCarrier'+iccNumber].textContent=operator;}else{UIManager['simCarrier'+iccNumber].setAttribute('data-l10n-id','searchingOperator');} var number=icc.mozIcc.iccInfo.msisdn||icc.mozIcc.iccInfo.mdn||'';if(number){UIManager['simNumber'+iccNumber].textContent=number;UIManager['simInfo'+iccNumber].classList.remove('no-number');}else{UIManager['simInfo'+iccNumber].classList.add('no-number');}}},showSIMInfoScreen:function sm_showSIMInfoScreen(){this.updateSIMInfoText(this.icc0);this.updateSIMInfoText(this.icc1);UIManager.activationScreen.classList.remove('show');UIManager.simInfoScreen.classList.add('show');},hideSIMInfoScreen:function sm_hidescreen(){UIManager.simInfoScreen.classList.remove('show');UIManager.activationScreen.classList.add('show');},checkSIMButton:function sm_checkSIMButton(){if(!this.mobConn){UIManager.simImport.classList.add('hidden');return;} var simOption=UIManager.simImportButton;if(!SimManager.alreadyImported&&SimManager.available()){simOption.removeAttribute('disabled');UIManager.noSim.classList.add('hidden');}else{simOption.setAttribute('disabled','disabled');if(!SimManager.alreadyImported){UIManager.noSim.classList.remove('hidden');}}},showPinScreen:function sm_showPinScreen(icc){showRetryCount(icc,'pin',UIManager.pinRetriesLeft);UIManager.unlockSimButton.disabled=true;UIManager.pinInput.addEventListener('input',function sm_checkInput(event){UIManager.unlockSimButton.disabled=(event.target.value.length<4);});UIManager.activationScreen.classList.remove('show');UIManager.unlockSimScreen.classList.add('show');UIManager.pincodeScreen.classList.add('show');UIManager.xckcodeScreen.classList.remove('show');UIManager.unlockSimHeader.setAttribute('data-l10n-id','pincode2');if(this.simSlots>1){var simNumber=icc===this.icc0?1:2;document.l10n.setAttributes(UIManager.pinLabel,'pincodeLabel',{n:simNumber});}else{UIManager.pinLabel.setAttribute('data-l10n-id','type_pin');} UIManager.pinInput.focus();},showPukScreen:function sm_showPukScreen(icc){showRetryCount(icc,'puk',UIManager.pukRetriesLeft);UIManager.unlockSimScreen.classList.add('show');UIManager.activationScreen.classList.remove('show');UIManager.pincodeScreen.classList.remove('show');UIManager.pukcodeScreen.classList.add('show');UIManager.xckcodeScreen.classList.remove('show');UIManager.unlockSimHeader.setAttribute('data-l10n-id','pukcode');if(this.simSlots>1){var simNumber=icc===this.icc0?1:2;document.l10n.setAttributes(UIManager.pukLabel,'pukcodeLabel',{n:simNumber});}else{UIManager.pukLabel.setAttribute('data-l10n-id','type_puk');} UIManager.pukInput.focus();},showXckScreen:function sm_showXckScreen(icc){var lockType;switch(icc.mozIcc.cardState){case'networkLocked':lockType='nck';break;case'corporateLocked':lockType='cck';break;case'serviceProviderLocked':lockType='spck';break;case'network1Locked':lockType='nck1';break;case'network2Locked':lockType='nck2';break;case'hrpdNetworkLocked':lockType='hnck';break;case'ruimCorporateLocked':lockType='rcck';break;case'ruimServiceProviderLocked':lockType='rspck';break;default:return;} showRetryCount(icc,lockType,UIManager.xckRetriesLeft);UIManager.unlockSimScreen.classList.add('show');UIManager.activationScreen.classList.remove('show');UIManager.pincodeScreen.classList.remove('show');UIManager.pukcodeScreen.classList.remove('show');UIManager.xckcodeScreen.classList.add('show');var simNumber=icc===this.icc0?1:2;switch(icc.mozIcc.cardState){case'networkLocked':document.l10n.setAttributes(UIManager.unlockSimHeader,'nckcodeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'nckcodeLabel',{n:simNumber});break;case'corporateLocked':document.l10n.setAttributes(UIManager.unlockSimHeader,'cckcodeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'cckcodeLabel',{n:simNumber});break;case'serviceProviderLocked':document.l10n.setAttributes(UIManager.unlockSimHeader,'spckcodeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'spckcodeLabel',{n:simNumber});break;case'network1Locked':document.l10n.setAttributes(UIManager.unlockSimHeader,'nck1codeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'nck1codeLabel',{n:simNumber});break;case'network2Locked':document.l10n.setAttributes(UIManager.unlockSimHeader,'nck2codeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'nck2codeLabel',{n:simNumber});break;case'hrpdNetworkLocked':document.l10n.setAttributes(UIManager.unlockSimHeader,'hnckcodeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'hnckcodeLabel',{n:simNumber});break;case'ruimCorporateLocked':document.l10n.setAttributes(UIManager.unlockSimHeader,'rcckcodeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'rcckcodeLabel',{n:simNumber});break;case'ruimServiceProviderLocked':document.l10n.setAttributes(UIManager.unlockSimHeader,'rspckcodeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'rspckcodeLabel',{n:simNumber});break;} UIManager.xckInput.focus();},resetForm:function sm_clearInputs(){this.clearFields();UIManager.newpinInput.value='';UIManager.confirmNewpinInput.value='';UIManager.pinInput.value='';UIManager.pukInput.value='';UIManager.pukInfo.classList.remove('hidden');UIManager.xckInput.value='';UIManager.unlockSimButton.disabled=false;},hideScreen:function sm_hideScreen(){UIManager.unlockSimScreen.classList.remove('show');UIManager.pincodeScreen.classList.remove('show');UIManager.pukcodeScreen.classList.remove('show');UIManager.xckcodeScreen.classList.remove('show');UIManager.activationScreen.classList.add('show');},skip:function sm_skip(){if(this._unlockingIcc){this._unlockingIcc.skipped=true;} this.resetForm();this.hideScreen();this.handleCardState();},resetSkipped:function sm_resetSkipped(){if(this.icc0){this.icc0.skipped=false;} if(this.icc1){this.icc1.skipped=false;}},back:function sm_back(){this.resetForm();this.resetSkipped();this.hideScreen();this.hideSIMInfoScreen();Navigation.back();},simUnlockBack:function sm_simUnlockBack(){if(this.icc0&&this.icc0.skipped){this.icc0.skipped=false;this.hideScreen();this.handleCardState();}else{this.back();}},unlock:function sm_unlock(){var icc=this._unlockingIcc;if(!icc){throw new Error('Cannot unlock SIM, no current ICC');} this.clearFields();switch(icc.mozIcc.cardState){case'pinRequired':this.unlockPin(icc);break;case'pukRequired':this.unlockPuk(icc);break;case'networkLocked':case'corporateLocked':case'serviceProviderLocked':case'network1Locked':case'network2Locked':case'hrpdNetworkLocked':case'ruimCorporateLocked':case'ruimServiceProviderLocked':this.unlockXck(icc);break;}},unlockPin:function sm_unlockPin(icc){var pin=UIManager.pinInput.value;if(pin.length<4||pin.length>8){UIManager.pinError.querySelector('.main').setAttribute('data-l10n-id','pinValidation');UIManager.pinInput.classList.add('onerror');UIManager.pinError.classList.remove('hidden');UIManager.pinInput.focus();return;}else{UIManager.pinInput.classList.remove('onerror');UIManager.pinError.classList.add('hidden');} this.attemptUnlock(icc,{lockType:'pin',pin:pin});},clearFields:function sm_clearFields(){UIManager.pukInput.classList.remove('onerror');UIManager.pukError.classList.add('hidden');UIManager.newpinInput.classList.remove('onerror');UIManager.newpinError.classList.add('hidden');UIManager.confirmNewpinInput.classList.remove('onerror');UIManager.confirmNewpinError.classList.add('hidden');UIManager.pinError.classList.add('hidden');UIManager.pinError.querySelector('.main').classList.add('hidden');UIManager.pinError.querySelector('.lastchance').classList.add('hidden');UIManager.pinRetriesLeft.classList.add('hidden');UIManager.pukError.classList.add('hidden');UIManager.pukError.querySelector('.main').classList.add('hidden');UIManager.pukError.querySelector('.lastchance').classList.add('hidden');UIManager.pukRetriesLeft.classList.add('hidden');UIManager.xckError.classList.add('hidden');UIManager.xckError.querySelector('.main').classList.add('hidden');UIManager.xckError.querySelector('.lastchance').classList.add('hidden');UIManager.xckRetriesLeft.classList.add('hidden');},unlockPuk:function sm_unlockPuk(icc){var pukCode=UIManager.pukInput.value;if(pukCode.length!==8){UIManager.pukError.querySelector('.main').setAttribute('data-l10n-id','pukValidation');UIManager.pukError.classList.remove('hidden');UIManager.pukInfo.classList.add('hidden');UIManager.pukInput.classList.add('onerror');UIManager.pukError.focus();return;} var newpinCode=UIManager.newpinInput.value;var confirmNewpin=UIManager.confirmNewpinInput.value;if(newpinCode.length<4||newpinCode.length>8){UIManager.newpinError.setAttribute('data-l10n-id','pinValidation');UIManager.newpinError.classList.remove('hidden');UIManager.newpinInput.classList.add('onerror');UIManager.newpinError.focus();return;} if(newpinCode!=confirmNewpin){UIManager.confirmNewpinError.setAttribute('data-l10n-id','newpinConfirmation');UIManager.confirmNewpinError.classList.remove('hidden');UIManager.newpinInput.classList.add('onerror');UIManager.confirmNewpinInput.classList.add('onerror');UIManager.confirmNewpinError.focus();return;} var options={lockType:'puk',puk:pukCode,newPin:newpinCode};this.attemptUnlock(icc,options);},unlockXck:function sm_unlockXck(icc){var xck=UIManager.xckInput.value;var lockType;switch(icc.mozIcc.cardState){case'networkLocked':lockType='nck';break;case'corporateLocked':lockType='cck';break;case'serviceProviderLocked':lockType='spck';break;case'network1Locked':lockType='nck1';break;case'network2Locked':lockType='nck2';break;case'hrpdNetworkLocked':lockType='hnck';break;case'ruimCorporateLocked':lockType='rcck';break;case'ruimServiceProviderLocked':lockType='rspck';break;} if(xck.length<8||xck.length>16){UIManager.xckInput.classList.add('onerror');UIManager.xckError.classList.remove('hidden');UIManager.xckError.querySelector('.main').setAttribute('data-l10n-id',lockType+'Validation');UIManager.xckInput.focus();return;}else{UIManager.pinInput.classList.remove('onerror');UIManager.pinError.classList.add('hidden');} var options={lockType:lockType,pin:xck};this.attemptUnlock(icc,options);},attemptUnlock:function sm_attemptUnlock(icc,options){var req=icc.mozIcc.unlockCardLock(options);req.onsuccess=(function sm_unlockSuccess(){icc.unlocked=true;this.resetForm();this.hideScreen();this.handleCardState();}).bind(this);req.onerror=(function sm_unlockError(){this.handleUnlockError(options.lockType,req.error.retryCount);}).bind(this);},guessIcc:function guessIcc(){var tempIcc=null;if(navigator.mozMobileConnections){for(var i=0;i0){progress.setClass('progressBar');progress.setHeaderMsg('simContacts-importing');progress.setTotal(n);}};importer.onimported=function imported_contact(){importedContacts++;if(!cancelled){progress.update();}};importer.onfinish=function sim_import_finish(numDupsMerged,iccId){window.setTimeout(function do_sim_import_finish(){UIManager.navBar.removeAttribute('aria-disabled');utils.overlay.hide();if(importedContacts>0){utils.misc.setTimestamp('sim-'+iccId);} if(!cancelled){SimManager.alreadyImported=true;importButton.setAttribute('disabled','disabled');utils.status.show({id:'simContacts-imported3',args:{n:importedContacts}});}},DELAY_FEEDBACK);importer.onfinish=null;};importer.onerror=function sim_import_error(){UIManager.navBar.removeAttribute('aria-disabled');utils.overlay.hide();importButton.removeAttribute('disabled');var cancel={title:'cancel',callback:function(){ConfirmDialog.hide();}};var retry={title:'retry',isRecommend:true,callback:function(){ConfirmDialog.hide();importButton.click();}};ConfirmDialog.show(null,'simContacts-error',cancel,retry);};importer.start();}};})();;'use strict';var SdManager={available:function(){return utils.sdcard.checkStorageCard();},checkSDButton:function sm_checkSDButton(){var sdOption=UIManager.sdImportButton;if(!SdManager.alreadyImported&&SdManager.available()){sdOption.removeAttribute('disabled');UIManager.noMemorycard.classList.add('hidden');}else{sdOption.setAttribute('disabled','disabled');if(!SdManager.alreadyImported){UIManager.noMemorycard.classList.remove('hidden');}}},importContacts:function sm_importContacts(){var importedContacts=0;UIManager.navBar.setAttribute('aria-disabled','true');var cancelled=false;var importer=null;var importButton;var progress=utils.overlay.show('memoryCardContacts-importing','activityBar','infiniteProgress');utils.overlay.showMenu();return new Promise((resolve,reject)=>{utils.overlay.oncancel=()=>{cancelled=true;if(importer){importer.finish();}else{UIManager.navBar.removeAttribute('aria-disabled');utils.overlay.hide();} resolve();};importButton=UIManager.sdImportButton;utils.sdcard.retrieveFiles(['text/vcard','text/directory;profile=vCard','text/directory'],['vcf','vcard'],(error,fileArray)=>{if(!error&&!fileArray.length){error='No contacts were found';} if(error){reject(error);return import_error(error);} if(cancelled){resolve();return;} var promises=[];fileArray.forEach(file=>{promises.push(utils.sdcard.getTextFromFile(file,onContacts));});Promise.all(promises).then(()=>{utils.misc.setTimestamp('sd');UIManager.navBar.removeAttribute('aria-disabled');utils.overlay.hide();if(cancelled){resolve();return;} SdManager.alreadyImported=true;importButton.setAttribute('disabled','disabled');utils.status.show({id:'memoryCardContacts-imported3',args:{n:importedContacts}});resolve();}).catch(reject);});});function onContacts(text){if(cancelled){return Promise.reject();} return new Promise((resolve,reject)=>{importer=new VCFReader(text);if(!text||!importer){var error='No contacts were found';import_error(error);reject(error);return;} importer.onimported=imported_contact;importer.onerror=error=>{import_error(error);reject(error);};importer.process(()=>{if(cancelled){reject('Cancelled');utils.overlay.hide();return;} resolve();});});} function imported_contact(){importedContacts++;progress.update();} function import_error(e){UIManager.navBar.removeAttribute('aria-disabled');utils.overlay.hide();importButton.removeAttribute('disabled');var cancel={title:'cancel',callback:function(){ConfirmDialog.hide();}};var retry={title:'retry',isRecommend:true,callback:function(){ConfirmDialog.hide();importButton.click();}};ConfirmDialog.show(null,'memoryCardContacts-error',cancel,retry);}}};;(function(exports){'use strict';const WIFI_STATUS={connecting:'connecting',associated:'associated',connected:'connected',connectingfailed:'connectingfailed',disconnected:'disconnected'};var WifiManager={STATUS:Object.freeze(WIFI_STATUS),init:function wn_init(){this.api=WifiHelper.getWifiManager();this.changeStatus();if(navigator.mozSettings){var lock=window.navigator.mozSettings.createLock();this.enable(lock);this.enableDebugging(lock);} this.gCurrentNetwork=this.api?this.api.connection.network:null;if(this.gCurrentNetwork!==null){this.api.forget(this.gCurrentNetwork);this.gCurrentNetwork=null;}},getNetworks:function wn_getNetworks(callback){this.networks?callback(this.networks):this.scan(callback);},scan:function wn_scan(callback){if(this._scanning){return;} this._scanning=true;utils.overlay.show('scanningNetworks','spinner');var SCAN_TIMEOUT=10000;var self=this;self.onScan=callback;var req=this.api?this.api.getNetworks():null;if(!req){setTimeout(function(){self._scanning=false;callback();});return;} var handleRequest=function handleRequest(){self._scanning=false;clearTimeout(self.scanTimeout);self.scanTimeout=null;self.onScan(self.networks);self.onScan=null;};req.onsuccess=function onScanSuccess(){self.networks=req.result;handleRequest();};req.onerror=function onScanError(){console.error('Error reading networks: '+req.error.name);self.networks=[];handleRequest();};if(!self.scanTimeout){self.scanTimeout=setTimeout(function(){self._scanning=false;console.warn('Timeout while reading networks');self.onScan();},SCAN_TIMEOUT);}},enable:function wn_enable(lock){lock.set({'wifi.enabled':true});},enableDebugging:function wn_enableDebugging(lock){this._prevDebuggingValue=false;var req=lock.get('wifi.debugging.enabled');req.onsuccess=function wn_getDebuggingSuccess(){this._prevDebuggingValue=req.result['wifi.debugging.enabled'];};lock.set({'wifi.debugging.enabled':true});},finish:function wn_finish(){if(!this._prevDebuggingValue&&navigator.mozSettings){var resetLock=window.navigator.mozSettings.createLock();resetLock.set({'wifi.debugging.enabled':false});}},getNetwork:function wm_gn(ssid){var list=this.networks;for(var i=0;i{this._selectNetworkItem(networkSelected,networkSelected===newWifi);});WifiManager.connect(ssid,password,user);},chooseNetwork:function wui_cn(event){var ssid=event.target.dataset.ssid;var selectedNetwork=WifiManager.getNetwork(ssid);if(!selectedNetwork){console.error('Network not found');return;} if(WifiHelper.isOpen(selectedNetwork)){WifiUI.connect(ssid);return;} UIManager.activationScreen.classList.add('no-options');UIManager.mainTitle.textContent=ssid;var ssidHeader=document.getElementById('wifi_ssid');var userInput=document.getElementById('wifi_user');var passwordInput=document.getElementById('wifi_password');var showPassword=document.querySelector('gaia-checkbox[name=show_password]');var joinButton=UIManager.wifiJoinButton;joinButton.disabled=true;passwordInput.addEventListener('input',function validatePassword(){joinButton.disabled=!WifiHelper.isValidInput(WifiHelper.getKeyManagement(selectedNetwork),passwordInput.value,userInput.value);});passwordInput.type='password';passwordInput.value='';showPassword.checked=false;showPassword.addEventListener('change',e=>{passwordInput.type=e.target.checked?'text':'password';});passwordInput.value='';ssidHeader.value=ssid;UIManager.navBar.classList.add('secondary-menu');if(WifiHelper.isEap(selectedNetwork)){userInput.parentNode.classList.remove('hidden');}else{userInput.parentNode.classList.add('hidden');} window.location.hash='#configure_network';},addHiddenNetwork:function wui_addHiddenNetwork(){UIManager.activationScreen.classList.add('no-options');UIManager.mainTitle.setAttribute('data-l10n-id','authentication');UIManager.navBar.classList.add('secondary-menu');UIManager.hiddenWifiSsid.value='';UIManager.hiddenWifiPassword.value='';UIManager.hiddenWifiIdentity.value='';UIManager.wifiJoinButton.disabled=true;window.location.hash='#hidden-wifi-authentication';},handleHiddenWifiSecurity:function wui_handleSecurity(securityType){if(securityType===''){UIManager.hiddenWifiPasswordBox.classList.add('hidden');}else{UIManager.hiddenWifiPasswordBox.classList.remove('hidden');} if(securityType.indexOf('EAP')!==-1){UIManager.hiddenWifiIdentityBox.classList.remove('hidden');}else{UIManager.hiddenWifiIdentityBox.classList.add('hidden');}},renderNetworks:function wui_rn(networks){var networksDOM=document.getElementById('networks');networksDOM.innerHTML='';var networksList;if(!networks||networks.length===0){var noResult='
'+'
'+'

'+'
'+'
';networksDOM.innerHTML=noResult;}else{networksList=document.createElement('ul');networksList.id='networks-list';networksList.setAttribute('role','listbox');networksList.setAttribute('data-l10n-id','networksList');var networksShown=[];networks.sort(function(a,b){return b.relSignalStrength-a.relSignalStrength;});for(var i=0,max=networks.length;i{if(evt.type!=='error'&&mediaElement.nodeName==='VIDEO'){mediaElement.play();}});},fileExists:function(src){return new Promise((resolve)=>{window.fetch(src,{method:'HEAD'}).then((response)=>{resolve(response.ok);}).catch(()=>{resolve(false);});});},getBestAssetForDirection:function(src){var dir=document.dir||'ltr';var re=/(-rtl|ltr)?\.(png|gif|jpg|webm|mp4|m4v|ogg|ogv)$/;var directionSrc=src.replace(re,'-'+dir+'.$2');return this.fileExists(directionSrc).then((result)=>{return result?directionSrc:src;}).catch((e)=>{console.log('Exception from getBestAssetForDirection: ',e);});},Sequence:function(){var sequence=Array.slice(arguments);var aborted=false;sequence.abort=function(){aborted=true;this.length=0;if(typeof this.onabort==='function'){this.onabort();}};sequence.complete=function(result){if(!aborted&&typeof this.oncomplete==='function'){this.oncomplete(result);}};sequence.fail=function(reason){this.complete(reason);};sequence.next=function(previousTaskResult){var result,exception;if(aborted){return;} var task=this.shift();if(task){try{result=task.apply(null,arguments);}catch(e){exception=e;} if(exception){this.fail(exception);}else if(result&&typeof result.then==='function'){result.then(this.next.bind(this),this.fail.bind(this));}else{this.next(result);}}else{this.complete(previousTaskResult);}};return sequence;}};exports.TutorialUtils=TutorialUtils;})(window);;(function(exports){'use strict';var currentLayout='tiny';var dom={};var elementIDs=['tutorial','tutorial-step-title','tutorial-step-media','tutorial-step-image','tutorial-step-video','forward-tutorial','back-tutorial'];var Tutorial={config:null,_stepsConfig:{},_stepsKey:'',_currentStep:1,_initialized:false,init:function(stepsKey,onLoaded){if(this._initialized||this._initialization){return;} var initTasks=this._initialization=new TutorialUtils.Sequence(this.loadConfig.bind(this),this._initWithConfig.bind(this,stepsKey));initTasks.onabort=this._onAbortInitialization.bind(this);initTasks.oncomplete=this._onCompleteInitialization.bind(this,onLoaded);elementIDs.forEach(function(name){dom[Utils.camelCase(name)]=document.getElementById(name);if(!dom[Utils.camelCase(name)]){console.error('Cache DOM elements: couldnt cache: '+name);}},this);initTasks.next();var mediaEvents=this._mediaEvents=['abort','canplay','canplaythrough','durationchange','emptied','ended','error','interruptbegin','interruptend','loadeddata','loadedmetadata','loadstart','mozaudioavailable','pause','play','playing','stalled','suspend','waiting'];this._debugEventHandler={handleEvent:function(evt){var errCodes={'1':'MEDIA_ERR_ABORTED','2':'MEDIA_ERR_NETWORK','3':'MEDIA_ERR_DECODE','4':'MEDIA_ERR_SRC_NOT_SUPPORTED'};console.log('TUTORIAL: media-event: '+evt.type);if(evt.type=='error'){var errtype=errCodes[evt.target.error.code]||'unknown';console.log('TUTORIAL: media-event, '+errtype+' error');}}};mediaEvents.forEach(name=>{dom.tutorialStepVideo.addEventListener(name,this._debugEventHandler);});},start:function(onReady){var sequence;var initInProgress=false;if(this._initialization){sequence=this._initialization;initInProgress=true;}else{this._initialization=sequence=new TutorialUtils.Sequence();sequence.onabort=this._onAbortInitialization.bind(this);sequence.oncomplete=this._onCompleteInitialization.bind(this);} sequence.push(function setInitialStep(){console.log('TUTORIAL: setInitialStep');return this._setStep();}.bind(this));sequence.push(function showTutorialAndFinishInit(){dom.tutorial.classList.add('show');console.log('TUTORIAL: dispatching tutorialinitialized');window.dispatchEvent(new CustomEvent('tutorialinitialized'));});if(typeof onReady==='function'){sequence.push(onReady);} if(!initInProgress){sequence.next();}},_initWithConfig:function(stepsKey){stepsKey=stepsKey||'default';this._stepsKey=stepsKey;this._stepsConfig=this.config[stepsKey]||this.config['default'];dom.forwardTutorial.addEventListener('click',this);dom.backTutorial.addEventListener('click',this);this._currentStep=1;},_onAbortInitialization:function(){this._initialization=null;},_onCompleteInitialization:function(onReady){this._initialization=null;this._initialized=true;if(typeof onReady==='function'){onReady();}},_setStep:function(value){value=(typeof value==='number')?value:this._currentStep;var stepIndex=value-1;if(stepIndex>=this._stepsConfig.steps.length){return Promise.resolve().then(function(){Tutorial.done();});} var stepData=this._stepsConfig.steps[stepIndex];if(!stepData){return Promise.reject('No data for step: '+value);} dom.tutorial.dataset.step=this._currentStep;document.l10n.setAttributes(dom.tutorialStepTitle,stepData.l10nKey);var imgElement=dom.tutorialStepImage,videoElement=dom.tutorialStepVideo;var stepPromise;if(stepData.video){stepPromise=TutorialUtils.getBestAssetForDirection(stepData.video).then((bestSrc)=>{return TutorialUtils.loadAndPlayMedia(videoElement,bestSrc);});videoElement.hidden=false;imgElement.hidden=true;}else{imgElement.hidden=false;stepPromise=TutorialUtils.loadMedia(imgElement,stepData.image);imgElement.hidden=false;videoElement.hidden=true;} return stepPromise;},handleEvent:function(evt){if(evt.type==='click'){switch(evt.target){case dom.forwardTutorial:this.next(evt);break;case dom.backTutorial:this.back(evt);break;}}},next:function(){return this._setStep(++this._currentStep);},back:function(){return this._setStep(--this._currentStep);},done:function(){var isUpgrade=this._stepsKey&&this._stepsKey!=='default';FinishScreen.init(isUpgrade);dom.tutorial.classList.remove('show');dom.tutorialStepVideo.removeAttribute('src');dom.tutorialStepImage.removeAttribute('src');},loadConfig:function(){if(!this._configPromise){currentLayout=ScreenLayout.getCurrentLayout()==='tiny'?'tiny':'large';var configUrl='/config/'+currentLayout+'.json';this._configPromise=LazyLoader.getJSON(configUrl).then(function(json){Tutorial.config=json;return Tutorial.config;},function(){return new Error('Tutorial config failed to load from: '+configUrl);});} return this._configPromise;},reset:function(){var resetPromise=Promise.resolve();if(dom.tutorialStepVideo){this._mediaEvents.forEach(name=>{dom.tutorialStepVideo.removeEventListener(name,this._debugEventHandler);});dom.tutorialStepVideo.hidden=true;if(dom.tutorialStepVideo.src){resetPromise=new Promise((resolve,reject)=>{dom.tutorialStepVideo.addEventListener('emptied',()=>{resolve();});dom.tutorialStepVideo.removeAttribute('src');dom.tutorialStepVideo.load();});}} if(this._initialization){this._initialization.abort();this._initialization=null;} this._configPromise=null;this._currentStep=1;this._stepsConfig=this.config=null;if(this._initialized){dom.tutorial.classList.remove('show');this._initialized=false;} document.getElementById('tutorial').classList.remove('show');return resetPromise;}};exports.Tutorial=Tutorial;})(this);;(function(exports){'use strict';const DOGFOODSETTING='debug.performance_data.dogfooding';const METRICSSETTING='metrics.selectedMetrics.level';var steps=[{onlyForward:true,hash:'#languages',requireSIM:false},{onlyForward:false,hash:'#data_3g',requireSIM:true},{onlyForward:false,hash:'#wifi',requireSIM:false},{onlyForward:false,hash:'#date_and_time',requireSIM:false},{onlyForward:false,hash:'#geolocation',requireSIM:false},{onlyForward:false,hash:'#import_contacts',requireSIM:false},{onlyForward:false,hash:'#firefox_accounts',requireSIM:false},{onlyForward:false,hash:'#welcome_browser',requireSIM:false},{onlyForward:false,hash:'#browser_privacy',requireSIM:false}];exports.Navigation={get stepCount(){return this._stepOrder?this._stepOrder.length:0;},currentStepIndex:0,previousStepIndex:0,simMandatory:false,skipMobileDataScreen:false,skipDateTimeScreen:false,tzInitialized:false,_stepsById:null,_stepOrder:null,init:function n_init(){this._stepOrder=[];this._stepsById={};var settings=navigator.mozSettings;var forward=document.getElementById('forward');var back=document.getElementById('back');this._onForwardClick=this.forward.bind(this);this._onBackClick=this.back.bind(this);forward.addEventListener('click',this._onForwardClick);back.addEventListener('click',this._onBackClick);window.addEventListener('hashchange',this);this._onActivationScreenClick=this.handleExternalLinksClick.bind(this);UIManager.activationScreen.addEventListener('click',this._onActivationScreenClick);steps.forEach(step=>{this.registerStep(step);});var self=this;var reqSIM=settings&&settings.createLock().get('ftu.sim.mandatory')||{};reqSIM.onsuccess=function onSuccess(){self.simMandatory=reqSIM.result['ftu.sim.mandatory']||false;};navigator.mozApps.getSelf().onsuccess=function(evt){var app=evt.target.result;app.connect('ftucomms').then(function onConnAccepted(ports){self.ports=ports;ports.forEach(port=>port.postMessage('started'));},function onConnRejected(reason){console.warn('FTU navigation cannot use IAC: '+reason);});};},uninit:function(){this._stepOrder=null;this._stepsById=null;this.currentStepIndex=0;this.previousStepIndex=0;this.ports=null;var forward=document.getElementById('forward');var back=document.getElementById('back');var activationScreen=UIManager&&UIManager.activationScreen;if(forward&&this._onForwardClick){forward.removeEventListener('click',this._onForwardClick);} if(back&&this._onBackClick){back.removeEventListener('click',this._onBackClick);} if(activationScreen&&this._onActivationScreenClick){activationScreen.removeEventListener('click',this._onActivationScreenClick);} window.removeEventListener('hashchange',this);},registerStep:function(step){if(!step.id){step.id=step.hash.substring(1);} var id=step.id;this._stepsById[id]=step;var beforeStepIdx=step.hasOwnProperty('beforeStep')?this._stepOrder.indexOf(step.beforeStep):-1;var afterStepIdx=step.hasOwnProperty('afterStep')?this._stepOrder.indexOf(step.afterStep):-1;if(beforeStepIdx>-1){this._stepOrder.splice(beforeStepIdx,0,id);}else if(afterStepIdx>-1){this._stepOrder.splice(afterStepIdx+1,0,id);}else{this._stepOrder.push(id);}},stepAt:function(idx){var stepId=this._stepOrder[idx];if(stepId){return this._stepsById[stepId];}},indexOfStep:function(step){var id=(typeof id==='string')?step.id:step;return this._stepOrder.indexOf(id);},back:function n_back(event){var currentStep=this.stepAt(this.currentStepIndex);var actualHash=window.location.hash;if(actualHash!=currentStep.hash){window.history.back();}else{var self=this;var goToStep=function(){self.previousStepIndex=self.currentStepIndex;self.currentStepIndex--;if(self.currentStepIndex>=0){self.manageStep();}};goToStep();}},forward:function n_forward(event){var self=this;var goToStepForward=function(){self.previousStepIndex=self.currentStepIndex;self.currentStepIndex++;if(self.currentStepIndex>=self.stepCount){UIManager.sendNewsletter(function newsletterSent(result){if(result){UIManager.activationScreen.classList.remove('show');UIManager.changeStatusBarColor(UIManager.DARK_THEME);UIManager.finishScreen.classList.add('show');UIManager.hideActivationScreenFromScreenReader();}else{self.currentStepIndex--;}});return;} self.manageStep();};goToStepForward();},handleExternalLinksClick:function n_handleExternalLinksClick(e){var link=e.target;if(!link.mozMatchesSelector('a.external')){return;} e.preventDefault();var href=link.href,title=link.getAttribute('title')||link.textContent;if(navigator.onLine){this.displayExternalLink(href,title);}else{UIManager.displayOfflineDialog(href,title);}},displayExternalLink:function n_displayExternalLink(href,title){window.open(href,'','dialog');},ensureTZInitialized:function(){if(!this.tzInitialized){return UIManager.initTZ().then(()=>{this.skipDateTimeScreen=!UIManager.timeZoneNeedsConfirmation;this.tzInitialized=true;});}else{return Promise.resolve();}},handleEvent:function n_handleEvent(event){var actualHash=window.location.hash;switch(actualHash){case'#languages':UIManager.mainTitle.setAttribute('data-l10n-id','language');break;case'#data_3g':UIManager.mainTitle.setAttribute('data-l10n-id','3g');DataMobile.getStatus(UIManager.updateDataConnectionStatus.bind(UIManager));break;case'#wifi':DataMobile.removeSVStatusObserver();UIManager.mainTitle.setAttribute('data-l10n-id','selectNetwork');UIManager.activationScreen.classList.remove('no-options');if(UIManager.navBar.classList.contains('secondary-menu')){UIManager.navBar.classList.remove('secondary-menu');return;} WifiManager.getNetworks(networks=>{this.ensureTZInitialized().then(()=>{WifiUI.renderNetworks(networks);});});break;case'#date_and_time':UIManager.mainTitle.setAttribute('data-l10n-id','dateAndTime');break;case'#geolocation':UIManager.mainTitle.setAttribute('data-l10n-id','geolocation');break;case'#import_contacts':UIManager.mainTitle.setAttribute('data-l10n-id','importContacts3');SimManager.checkSIMButton();SdManager.checkSDButton();var onlineState;if(!WifiManager.api){ImportIntegration.checkImport('enabled');break;} onlineState=window.navigator.onLine?'enabled':'disabled';ImportIntegration.checkImport(onlineState);break;case'#firefox_accounts':UIManager.mainTitle.setAttribute('data-l10n-id','firefox-accounts');break;case'#welcome_browser':UIManager.mainTitle.setAttribute('data-l10n-id','aboutBrowser');var settings=navigator.mozSettings;var basicMetrics=document.getElementById('metrics-basic');var enhancedMetrics=document.getElementById('metrics-enhanced');var noneMetrics=document.getElementById('metrics-none');var defaultLevel=settings&&settings.createLock().get(METRICSSETTING);if(defaultLevel){defaultLevel.onsuccess=function(){var result=defaultLevel.result[METRICSSETTING];if(result==='Basic'){basicMetrics.checked=true;}else if(result==='Enhanced'){enhancedMetrics.checked=true;}else if(result==='None'){noneMetrics.checked=true;}};} var dogfood=settings&&settings.createLock().get(DOGFOODSETTING);if(dogfood){dogfood.onsuccess=function(){if(dogfood.result[DOGFOODSETTING]){basicMetrics.setAttribute('disabled','true');enhancedMetrics.setAttribute('disabled','true');noneMetrics.setAttribute('disabled','true');}else{basicMetrics.removeAttribute('disabled');enhancedMetrics.removeAttribute('disabled');noneMetrics.removeAttribute('disabled');}};} break;case'#browser_privacy':UIManager.mainTitle.setAttribute('data-l10n-id','aboutBrowser');break;case'#SIM_mandatory':UIManager.mainTitle.setAttribute('data-l10n-id','SIM_mandatory');break;case'#about-your-rights':case'#about-your-privacy':UIManager.mainTitle.setAttribute('data-l10n-id','aboutBrowser');UIManager.navBar.classList.add('back-only');break;case'#sharing-performance-data':UIManager.mainTitle.setAttribute('data-l10n-id','aboutBrowser');UIManager.navBar.classList.add('back-only');break;} if(this.simMandatory){UIManager.skipPinButton.classList.add('hidden');UIManager.backSimButton.classList.remove('hidden');}else{UIManager.skipPinButton.classList.remove('hidden');UIManager.backSimButton.classList.add('hidden');} var lastIndex=this.stepCount-1;if(this.currentStepIndex<=lastIndex&&(this.stepAt(this.currentStepIndex).hash!=='#wifi')){UIManager.activationScreen.classList.add('no-options');} if(this.currentStepIndex<=lastIndex&&this.stepAt(this.currentStepIndex).hash===actualHash){UIManager.navBar.classList.remove('back-only');}},postStepMessage:function n_postStepMessage(stepIndex){if(!this.ports){return;} var step=this.stepAt(stepIndex);this.ports.forEach(function(port){port.postMessage({type:'step',hash:step.hash});});},skipStep:function n_skipStep(){var stepIndex=this.currentStepIndex;stepIndex+=stepIndex>this.previousStepIndex?1:-1;if(stepIndex<=0){this.previousStepIndex=stepIndex=0;} if(stepIndex>this.stepCount){this.previousStepIndex=stepIndex=this.stepCount;} this.currentStepIndex=stepIndex;this.manageStep();},manageStep:function n_manageStep(){var self=this;if(self.currentStepIndex>self.previousStepIndex){self.postStepMessage(self.previousStepIndex);} if(self.currentStepIndex>=self.stepCount){OperatorVariant.setSIMOnFirstBootState();} if(self.currentStepIndex===0){self.skipMobileDataScreen=false;} var futureLocation=this.stepAt(self.currentStepIndex);if(this.simMandatory&&!IccHelper.cardState&&futureLocation.requireSIM){futureLocation.hash='#SIM_mandatory';futureLocation.requireSIM=false;futureLocation.onlyBackward=true;} if(this.stepAt(this.currentStepIndex).onlyForward){UIManager.navBar.classList.add('forward-only');}else{UIManager.navBar.classList.remove('forward-only');} var nextButton=document.getElementById('forward');if(this.stepAt(this.currentStepIndex).onlyBackward){nextButton.setAttribute('disabled','disabled');}else{nextButton.removeAttribute('disabled');} if(this.currentStepIndex===this.stepCount){nextButton.setAttribute('data-l10n-id','done');}else{nextButton.setAttribute('data-l10n-id','navbar-next');} if(futureLocation.hash==='#firefox_accounts'){nextButton.setAttribute('data-l10n-id','skip');} window.location.hash=futureLocation.hash;if(futureLocation.requireSIM){var check_cardState=function(response){if(!response||(!SimManager.available()&&futureLocation.hash!=='#data_3g')){self.skipStep();if(self.currentStepIndex>self.previousStepIndex){self.skipMobileDataScreen=true;}}};var skipUnlockScreens=this.currentStepIndex{this.skipFxA=false;this.onFxALogin(account);},()=>{FxAccountsIACHelper.logout(()=>{this.skipFxA=false;});});},createFirefoxAccount:function ui_createFirefoxAccount(){FxAccountsIACHelper.openFlow(UIManager.onFxAFlowDone,UIManager.onFxAError);},onFxAFlowDone:function ui_onFxAFlowDone(){FxAccountsIACHelper.getAccount((account)=>{if(!account){return;} UIManager.onFxALogin(account);UIManager.setForwardButtonLabel('navbar-next');},UIManager.onFxAError);},onFxALogin:function ui_onFxALogin(account){if(!account){return;} UIManager.newsletterInput.value=account.email;UIManager.fxaIntro.innerHTML='';document.l10n.setAttributes(UIManager.fxaIntro,account.verified?'fxa-signed-in':'fxa-email-sent',{email:account.email});UIManager.fxaCreateAccount.disabled=true;},onFxAError:function ui_onFxAError(response){console.error('Create FxA Error: '+JSON.stringify(response));UIManager.newsletterInput.value='';document.l10n.setAttributes(UIManager.fxaIntro,'fxa-upsell');UIManager.fxaCreateAccount.disabled=false;UIManager.setForwardButtonLabel('skip');},displayOfflineDialog:function ui_displayOfflineDialog(href,title){var dialog=this.offlineErrorDialog;document.l10n.setAttributes(dialog.querySelector('small'),'offline-dialog-text',{url:href});dialog.classList.add('visible');this.hideActivationScreenFromScreenReader();},onOfflineDialogButtonClick:function ui_onOfflineDialogButtonClick(e){this.offlineErrorDialog.classList.remove('visible');this.showActivationScreenToScreenReader();},hideActivationScreenFromScreenReader:function ui_hideActivationScreenFromScreenReader(){this.activationScreen.setAttribute('aria-hidden',true);},showActivationScreenToScreenReader:function ui_showActivationScreenToScreenReader(){this.activationScreen.setAttribute('aria-hidden',false);},setDate:function ui_sd(){if(!!this.lock){return;} var now=new Date();var currentDate=this.dateConfiguration.value;var currentTime=now.toLocaleFormat('%H:%M');var timeToSet=new Date(currentDate+'T'+currentTime);TimeManager.set(timeToSet);this.dateConfigurationLabel.textContent=timeToSet.toLocaleString(navigator.languages,{year:'numeric',month:'numeric',day:'numeric'});},setTime:function ui_st(){if(!!this.lock){return;} var timeLabel=document.getElementById('time-configuration-label');var now=new Date();var currentTime=document.getElementById('time-configuration').value;if(currentTime.indexOf(':')===1){currentTime='0'+currentTime;} var currentDate=now.toLocaleFormat('%Y-%m-%d');var timeToSet=new Date(currentDate+'T'+currentTime);TimeManager.set(timeToSet);timeLabel.textContent=timeToSet.toLocaleString(navigator.languages,{hour12:navigator.mozHour12,hour:'numeric',minute:'numeric',second:'numeric'});},setTimeZone:function ui_stz(timezone,needsConfirmation){this.timeZoneNeedsConfirmation=!!needsConfirmation;var utcOffset=timezone.utcOffset;document.getElementById('time_zone_overlay').className='UTC'+utcOffset.replace(/[+:]/g,'');var timezoneTitle=document.getElementById('time-zone-title');document.l10n.setAttributes(timezoneTitle,'timezoneTitle',{utcOffset:utcOffset,region:timezone.region,city:timezone.city});document.getElementById('tz-region-label').textContent=timezone.region;document.getElementById('tz-city-label').textContent=timezone.city;var now=new Date();var timeLabel=document.getElementById('time-configuration-label');timeLabel.textContent=now.toLocaleString(navigator.languages,{hour12:navigator.mozHour12,hour:'numeric',minute:'numeric',second:'numeric'});},updateDataConnectionStatus:function ui_udcs(status){this.dataConnectionSwitch.checked=status;},changeStatusBarColor:function ui_csbc(color){var themeMeta=document.head.querySelector('meta[name="theme-color"]');themeMeta.setAttribute('content',color);}};function toCamelCase(str){return str.replace(/\-(.)/g,function replacer(str,p1){return p1.toUpperCase();});};'use strict';var LanguageManager={settings:window.navigator.mozSettings,init:function init(){this.buildLanguageList();document.getElementById('languages').addEventListener('change',this);var onSettingChange=this._boundHandleSettingChange=this.handleSettingChange.bind(this);this.settings.addObserver('language.current',onSettingChange);this.settings.addObserver('accessibility.screenreader',onSettingChange);},uninit:function uninit(){if(this._boundHandleSettingChange){this.settings.removeObserver('language.current',this._boundHandleSettingChange);this.settings.removeObserver('accessibility.screenreader',this._boundHandleSettingChange);}},handleSettingChange:function(evt){switch(evt.settingName){case'accessibility.screenreader':this.buildLanguageList();break;case'language.current':KeyboardHelper.changeDefaultLayouts(evt.settingValue,true);break;}},handleEvent:function handleEvent(evt){if(!this.settings||evt.target.name!='language.current'){return true;} this.setLanguage(evt.target.value);return false;},setLanguage:function settings_setLanguage(language){this.settings.createLock().set({'language.current':language});},buildLanguageList:function settings_buildLanguageList(){var panel=document.querySelector('#languages');var container=panel.querySelector('ul');container.innerHTML='';LanguageList.get(function fillLanguageList(allLanguages,currentLanguage){for(var lang in allLanguages){var label=document.createElement('label');label.textContent=LanguageList.wrapBidi(lang,allLanguages[lang]);var radio=document.createElement('gaia-radio');radio.className='checkone';radio.setAttribute('name','language.current');radio.setAttribute('value',lang);radio.checked=(lang===currentLanguage);radio.appendChild(label);radio.configureClass();var li=document.createElement('li');li.dataset.value=lang;li.appendChild(radio);container.appendChild(li);} panel.dataset.languagesReady=true;window.dispatchEvent(new CustomEvent('languagelistready'));});}};;'use strict';var AppManager={EVENT_PREFIX:'ftu-',init:function init(versionInfo){window.performance.mark('initialize');this.isInitialized=true;LanguageManager.init();UIManager.init();Navigation.init();window.performance.mark('navigationLoaded');this.publish('setup');var splashTimeout=1025;var splashScreenHidden=this.whenEvent(UIManager.splashScreen,'transitionend',splashTimeout).then(()=>{UIManager.container.removeAttribute('aria-hidden');window.performance.mark('visuallyLoaded');});var languageListReady=this.whenEvent(window,'languagelistready');Promise.all([splashScreenHidden,languageListReady]).then(()=>{window.performance.mark('fullyLoaded');});if(versionInfo&&versionInfo.isUpgrade()){var stepsKey=versionInfo.delta();UIManager.changeStatusBarColor(UIManager.DARK_THEME);UIManager.splashScreen.classList.remove('show');UIManager.activationScreen.classList.remove('show');UIManager.updateScreen.classList.add('show');Tutorial.init(stepsKey,function(){Tutorial.start();});return;} SimManager.init();WifiManager.init();ImportIntegration.init();TimeManager.init();DataMobile.init();Tutorial.init();var kSplashTimeout=700;var conn=window.navigator.mozMobileConnections&&window.navigator.mozMobileConnections[0];if(!conn){setTimeout(function(){window.location.hash='#';UIManager.activationScreen.classList.add('show');window.location.hash='#languages';UIManager.splashScreen.classList.remove('show');window.performance.mark('navigationInteractive');window.performance.mark('contentInteractive');},kSplashTimeout);return;} setTimeout(function(){Navigation.manageStep();UIManager.activationScreen.classList.add('show');UIManager.splashScreen.classList.remove('show');window.performance.mark('navigationInteractive');window.performance.mark('contentInteractive');},kSplashTimeout);},whenEvent:function(target,name,timeoutMs){return new Promise((resolve,reject)=>{eventSafety(target,name,resolve,timeoutMs||1000);});},publish:function(name,detail){var evt=new CustomEvent(this.EVENT_PREFIX+name,{bubbles:true,detail:detail||this});window.dispatchEvent(evt);}};function init(){VersionHelper.getVersionInfo().then(function(versionInfo){if(!AppManager.isInitialized){AppManager.init(versionInfo);}else{UIManager.initTZ();if(!UIManager.mainTitle.hasAttribute('data-l10n-id')){UIManager.mainTitle.setAttribute('data-l10n-id','language');}}});} init();document.addEventListener('DOMRetranslated',init);document.l10n.ready.then(()=>{window.performance.mark('l10nready');});;'use strict';var OperatorVariant=(function(){var NO_SIM='000-000';function setSIMOnFirstBootState(){var cardValue;function normalizeCode(aCode){var ncode=''+aCode;while(ncode.length<3){ncode='0'+ncode;} return ncode;} try{if(!IccHelper||!IccHelper.cardState){cardValue=NO_SIM;}else{var mcc=IccHelper.iccInfo.mcc;var mnc=IccHelper.iccInfo.mnc;if((mcc!==undefined)&&(mcc!==null)&&(mnc!==undefined)&&(mnc!==null)){cardValue=normalizeCode(mcc)+'-'+normalizeCode(mnc);}else{cardValue=NO_SIM;}} var settings=navigator.mozSettings;if(!settings){console.log('Settings is not available');return;} var req=settings.createLock().get('ftu.simPresentOnFirstBoot');req.onsuccess=function ov_onsuccess(){var currentStatus=req.result['ftu.simPresentOnFirstBoot'];if(currentStatus===undefined||currentStatus===null){var result=navigator.mozSettings.createLock().set({'ftu.simPresentOnFirstBoot':cardValue});result.onerror=function ov_error(){console.error('An error occurre setting '+'ftu.simPresentOnFirstBoot: '+cardValue);};} cardValue=null;};req.onerror=function ov_error(){console.error('Error retrieving ftu.simPresentOnFirstBoot');};}catch(e){console.error('Error setSIMOnFirstBootState. '+e);}} return{setSIMOnFirstBootState:setSIMOnFirstBootState};})();;'use strict';var ConfirmDialog=(function(){var isAnimationPlaying=false;var isShown=false;var doc=document;try{if(!document.getElementById("confirmation-message"))doc=parent.document;}catch(_){}var screen=doc.getElementById('confirmation-message');var titleNode=screen.querySelector('h1');var messageNode=screen.querySelector('p');var action1Node=screen.querySelector('button:nth-of-type(1)');var action1Callback;var action2Node=screen.querySelector('button:nth-of-type(2)');var action2Callback;var oldzIndex;var callBackAndPreventDefault=function callBackAndPreventDefault(ev){if(ev.target===action1Node){action1Callback();ev.preventDefault();return false;}else if(ev.target===action2Node){action2Callback();ev.preventDefault();return false;}};var _hide=function _hide(){if(!isShown){return;} titleNode.removeAttribute('data-l10n-id');titleNode.className='';messageNode.removeAttribute('data-l10n-id');messageNode.className='';action1Node.removeAttribute('data-l10n-id');action1Node.onclick=null;action2Node.removeAttribute('data-l10n-id');action2Node.onclick=null;screen.classList.remove('fade-in');screen.classList.add('fade-out');isAnimationPlaying=true;window.dispatchEvent(new CustomEvent('confirmdialoghiding'));screen.addEventListener('animationend',function cd_fadeOut(ev){action1Node.className='';action2Node.className='';isAnimationPlaying=false;screen.removeEventListener('animationend',cd_fadeOut);screen.classList.add('no-opacity');screen.classList.add('hide');isShown=false;});};var _show=function _show(title,msg,action1,action2,options){var setL10nAttributes=function(element,options){if('string'===typeof options){document.l10n.setAttributes(element,options);} if(options.id){document.l10n.setAttributes(element,options.id,options.args);}};if(options&&options.zIndex){oldzIndex=screen.style.zIndex;screen.style.zIndex=options.zIndex;} else{oldzIndex=null;} if(title){setL10nAttributes(titleNode,title);}else{titleNode.classList.add('hide');} if(msg){setL10nAttributes(messageNode,msg);}else{messageNode.classList.add('hide');} if(action1){if(action1.title){setL10nAttributes(action1Node,action1.title);} if(action1.isDanger){action1Node.classList.add('danger');} if(action1.isRecommend){action1Node.classList.add('recommend');} if(action1.callback){action1Callback=action1.callback;action1Node.onclick=callBackAndPreventDefault;} if(!action2){action2Node.classList.add('hide');action1Node.classList.add('full');}} if(action2){if(action2.title){setL10nAttributes(action2Node,action2.title);} if(action2.isDanger){action2Node.classList.add('danger');} if(action2.isRecommend){action2Node.classList.add('recommend');} if(action2.callback){action2Callback=action2.callback;action2Node.onclick=callBackAndPreventDefault;} if(!action1){action1Node.classList.add('hide');action2Node.classList.add('full');}} if(isShown){return;} screen.classList.remove('hide');screen.classList.remove('fade-out');screen.classList.add('fade-in');isAnimationPlaying=true;window.dispatchEvent(new CustomEvent('confirmdialogshowing'));screen.addEventListener('animationend',function cd_fadeIn(ev){isAnimationPlaying=false;screen.removeEventListener('animationend',cd_fadeIn);screen.classList.remove('no-opacity');isShown=true;});};return{hide:function dialog_hide(){if(oldzIndex){screen.style.zIndex=oldzIndex;oldzIndex=null;} if(!isAnimationPlaying){_hide();return;} screen.addEventListener('animationend',function cd_hideWhenFinished(ev){screen.removeEventListener('animationend',cd_hideWhenFinished);_hide();});},show:function dialog_show(title,msg,action1,action2,options){if(!isAnimationPlaying){_show(title,msg,action1,action2,options);return;} screen.addEventListener('animationend',function cd_showWhenFinished(ev){screen.removeEventListener('animationend',cd_showWhenFinished);_show(title,msg,action1,action2,options);});}};}());;(function(exports){'use strict';exports.ComponentUtils={style:function(baseUrl){if(window.VulpesCompat){window.VulpesCompat.componentStyle(this,baseUrl).catch(console.error);return;}var style=document.createElement('style');var url=baseUrl+'style.css';var self=this;style.setAttribute('scoped','');style.innerHTML='@import url('+url+');';this.appendChild(style);this.style.visibility='hidden';style.addEventListener('load',function(){if(self.shadowRoot){self.shadowRoot.appendChild(style.cloneNode(true));} self.style.visibility='';});}};}(window));;'use strict';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);;'use strict';window.GaiaCheckbox=(function(win){var proto=Object.create(HTMLElement.prototype);var baseurl=window.GaiaCheckboxBaseurl||'/shared/elements/gaia_checkbox/';proto.createdCallback=function(){this.lastClick=0;this.throttleTime=250;var shadow=this.createShadowRoot();this._template=template.content.cloneNode(true);this._wrapper=this._template.getElementById('checkbox');this._wrapper.addEventListener('click',this.handleClick.bind(this));this.configureClass();this.checked=this.hasAttribute('checked');this._wrapper.setAttribute('aria-checked',this.checked);this.setAttribute('role','presentation');shadow.appendChild(this._template);ComponentUtils.style.call(this,baseurl);};proto.handleClick=function(e){e.preventDefault();e.stopImmediatePropagation();if(this.lastClick+this.throttleTime>Date.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);;'use strict';window.GaiaRadio=(function(win){var proto=Object.create(HTMLElement.prototype);var baseurl=window.GaiaRadioBaseurl||'/shared/elements/gaia_radio/';proto.createdCallback=function(){var shadow=this.createShadowRoot();this._template=template.content.cloneNode(true);this._wrapper=this._template.getElementById('radio');this._wrapper.addEventListener('click',this.handleClick.bind(this));if(this.dataset.role){this._wrapper.setAttribute('role',this.dataset.role);} if(!this.hasAttribute('role')){this.setAttribute('role','presentation');} this.configureClass();shadow.appendChild(this._template);this.checked=this.hasAttribute('checked');this._wrapper.setAttribute('aria-checked',this.checked);setTimeout(function nextTick(){var label=this.querySelector('label, p');if(!label){return;} label.addEventListener('click',this.handleClick.bind(this));}.bind(this));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){e.stopImmediatePropagation();var event=new MouseEvent('click',{view:window,bubbles:true,cancelable:true});this.dispatchEvent(event);if(this.checked){return;} if(!event.defaultPrevented){this.checked=!this.checked;} this.dispatchEvent(new CustomEvent('change',{bubbles:true,cancelable:false}));};proto.configureClass=function(){this._wrapper.className=this.className;this._wrapper.classList.toggle('checked',this._checked);};proto.hideDetails=function(){this.shadowRoot.querySelector('.details').style.display='none';};proto.attributeChangedCallback=function(name,from,to){if(name==='class'){this._wrapper.className=to;}};Object.defineProperty(proto,'checked',{get:function(){return this._checked;},set:function(value){if(!this._template){return;} if(value){var relevant=document.querySelectorAll('gaia-radio[name="'+this.getAttribute('name')+'"]');for(var i=0,iLen=relevant.length;i'+''+'
'+'
'+'';return document.registerElement('gaia-radio',{prototype:proto});})(window);;'use strict';window.GaiaButtons=(function(win){var proto=Object.create(HTMLElement.prototype);var baseurl=window.GaiaButtonsBaseurl||'/shared/elements/gaia_buttons/';proto.createdCallback=function(){ComponentUtils.style.call(this,baseurl);};return document.registerElement('gaia-buttons',{prototype:proto});})(window);;'use strict';window.GaiaSubheader=(function(win){var proto=Object.create(HTMLElement.prototype);var baseurl=window.GaiaSubheaderBaseurl||'/shared/elements/gaia_subheader/';proto.createdCallback=function(){ComponentUtils.style.call(this,baseurl);};return document.registerElement('gaia-subheader',{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)});;'use strict';(function IconsHelper(exports){const ICON_CACHE_PERIOD=24*60*60*1000;const FETCH_XHR_TIMEOUT=10000;const DEBUG=false;var dataStore=null;function getDefaultIconSize(){var dpr=window.devicePixelRatio;return(dpr&&dpr>1)?142:84;} function sizeIsNearer(size1,size2,targetSize){var delta1=Math.abs(targetSize-size1);var delta2=Math.abs(targetSize-size2);return(delta1<=delta2);} function getIcon(uri,iconTargetSize,placeObj={},siteObj={}){var iconUrl=null;iconTargetSize=iconTargetSize*window.devicePixelRatio;if(siteObj.webManifestUrl&&siteObj.webManifest){iconUrl=getBestIconFromWebManifest(siteObj.webManifest,iconTargetSize);if(DEBUG&&iconUrl){console.log('Icon from Web Manifest');}} if(!iconUrl&&siteObj.manifest&&siteObj.manifest.icons){iconUrl=getBestIconFromWebManifest({icons:_convertToWebManifestIcons(siteObj.manifest,siteObj.origin||siteObj.manifest.origin)},iconTargetSize);if(DEBUG&&iconUrl){console.log('Icon from Firefox App Manifest');}} if(!iconUrl&&placeObj&&placeObj.icons){iconUrl=getBestIconFromMetaTags(placeObj.icons,iconTargetSize);if(DEBUG&&iconUrl){console.log('Icon from Meta tags');}} if(!iconUrl){var a=document.createElement('a');a.href=uri;iconUrl=a.origin+'/favicon.ico';if(iconTargetSize){iconUrl+='#-moz-resolution='+iconTargetSize+','+iconTargetSize;} DEBUG&&console.log('Icon from favicon.ico');} return new Promise(resolve=>{resolve(iconUrl);});} function getIconBlob(uri,iconTargetSize,placeObj={},siteObj={}){return new Promise((resolve,reject)=>{getIcon(uri,iconTargetSize,placeObj,siteObj).then(iconUrl=>{getStore().then(iconStore=>{iconStore.get(iconUrl).then(iconObj=>{if(!iconObj||!iconObj.timestamp||Date.now()-iconObj.timestamp>=ICON_CACHE_PERIOD){return fetchIconBlob(iconUrl).then(iconBlob=>{var img=document.createElement('img');var icon=new Icon(img,uri);icon.renderBlob(iconBlob,{size:iconTargetSize,onLoad:function(blob){var iconObj={blob:blob,originalUrl:iconUrl.toString(),timestamp:Date.now()};resolve(iconObj);iconStore.add(iconObj,iconUrl);},onerror:function(e){reject(`Failed to fetch icon ${iconUrl}`);}});}).catch(err=>{reject(`Failed to fetch icon ${iconUrl}: ${err}`);});} return resolve(iconObj);}).catch(err=>{reject(`Failed to get icon from dataStore: ${err}`);});}).catch(err=>{reject(`Error opening the dataStore: ${err}`);});});});} function setElementIcon(icon,targetSize){return getIconBlob(icon.bookmark.url,targetSize,icon.bookmark,icon.bookmark).then(iconObj=>{if(iconObj.blob){icon.icon=iconObj.blob;return Promise.resolve();}else if(icon.bookmark.icon){return fetchIconBlob(icon.bookmark.icon).then(iconBlob=>{icon.icon=iconBlob;return Promise.resolve();},Promise.reject.bind(Promise));} return Promise.reject('No icon data found');},Promise.reject.bind(Promise));} function getBestIconFromWebManifest(webManifest,iconSize){var icons=webManifest.icons;if(!icons){return null;} var maxSize=10000;var bestSize=maxSize;var iconURL=null;iconSize=iconSize||getDefaultIconSize();icons.forEach((potentialIcon)=>{if(!iconURL){iconURL=potentialIcon.src;} var sizes=Array.from(potentialIcon.sizes);var nearestSize=getNearestSize(sizes,iconSize,bestSize);if(nearestSize!==bestSize&&sizeIsNearer(nearestSize,bestSize,iconSize)){iconURL=potentialIcon.src;bestSize=nearestSize;}});return iconURL?iconURL:null;} function _convertToWebManifestIcons(manifest,origin){return Object.keys(manifest.icons).map(function(size){var url=manifest.icons[size];var sizes=[size+'x'+size];url=url.indexOf('http')>-1?url:origin+url;return{src:new URL(url),sizes:sizes};});} function getBestIconFromMetaTags(icons,iconSize){if(!icons){return null;} iconSize=iconSize||getDefaultIconSize();var iconURL=null;var bestSize=10000;Object.keys(icons).forEach((uri)=>{var potentialIcon=icons[uri];if(!iconURL){iconURL=uri;} var sizes=Array.from(potentialIcon.sizes);var nearestSize=getNearestSize(sizes,iconSize,bestSize);if(nearestSize!==bestSize&&sizeIsNearer(nearestSize,bestSize,iconSize)){iconURL=uri;bestSize=nearestSize;} if(potentialIcon.rel==='apple-touch-icon'||potentialIcon.rel==='apple-touch-icon-precomposed'){var moreInfoUrl='https://developer.mozilla.org/en-US/'+'Apps/Build/Icon_implementation_for_apps#General_icons_for_web_apps';console.warn('Warning: The apple-touch icons are being used '+'as a fallback only. They will be deprecated in '+'the future. See '+moreInfoUrl);}});return iconURL||null;} function getNearestSize(sizes,iconSize,bestSize){var bogusSize=10000;if(!bestSize){bestSize=bogusSize;} var nearestSize=sizes.reduce(function(nearestSize,sizeString,idx){var size=widthFromSizeString(sizeString);if(isNaN(size)){return nearestSize;} if(sizeIsNearer(size,nearestSize,iconSize)){return size;}else{return nearestSize;}},bestSize);return nearestSize===bogusSize?-1:nearestSize;} function widthFromSizeString(size){size=size||'';var xIndex=size.indexOf('x');if(!xIndex){return NaN;} return parseInt(size.substr(0,xIndex));} function getStore(){return new Promise(resolve=>{if(dataStore){return resolve(dataStore);} navigator.getDataStores('icons').then(stores=>{dataStore=stores[0];return resolve(dataStore);});});} function clear(){return getStore().then(iconStore=>{iconStore.clear();});} function fetchIcon(iconUrl){return new Promise((resolve,reject)=>{fetchIconBlob(iconUrl).then((iconBlob)=>{var img=document.createElement('img');img.src=URL.createObjectURL(iconBlob);img.onload=()=>{var iconSize=Math.max(img.naturalWidth,img.naturalHeight);resolve({blob:iconBlob,url:iconUrl,size:iconSize,timestamp:Date.now()});};img.onerror=()=>{reject(new Error(`Error while loading image.`));};}).catch((e)=>{reject(new Error(`Error while loading image: ${e}`));});});} function fetchIconBlob(iconUrl){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest({mozAnon:true,mozSystem:true});xhr.open('GET',iconUrl,true);xhr.responseType='blob';xhr.timeout=FETCH_XHR_TIMEOUT;xhr.send();xhr.onload=()=>{if(xhr.readyState===XMLHttpRequest.DONE&&xhr.status===200){var iconBlob=xhr.response;resolve(iconBlob);return;} reject(new Error(`Got HTTP status ${xhr.status} trying to load ${iconUrl}.`));};xhr.onerror=xhr.ontimeout=()=>{reject(new Error(`Error while getting ${iconUrl}.`));};});} exports.IconsHelper={getIcon:getIcon,getIconBlob:getIconBlob,setElementIcon:setElementIcon,getBestIconFromWebManifest:getBestIconFromWebManifest,getBestIconFromMetaTags:getBestIconFromMetaTags,fetchIcon:fetchIcon,fetchIconBlob:fetchIconBlob,get defaultIconSize(){return getDefaultIconSize();},clear:clear,getNearestSize:getNearestSize,};})(window);;(function(exports){'use strict';const MANIFEST_SETTING_NAME='latecustomization.url';const OPERATOR_INFO_SETTING_NAME='latecustomization.operatorInfo';const COMMS_CHANNEL='ftucomms';const ICON_SIZE=32;const IMG_PATH='style/images/late_customization';const ICON_INSTALLING_URL=`${IMG_PATH}/app_installing.svg`;const ICON_FAILED_URL=`${IMG_PATH}/app_install_unrecoverable.svg`;const ICON_DEFAULT_URL=`${IMG_PATH}/default_icon.svg`;function LateCustomizationPanel(){this.debug('LateCustomizationPanel ctor');} LateCustomizationPanel.prototype={DEBUG:false,name:'LateCustomizationPanel',constructor:LateCustomizationPanel,_initialized:false,_downloadPossible:false,_customizationManifestUrl:'',get enabled(){return Boolean(this._customizationManifestUrl&&(this._operatorInfo||this._predefinedOperatorInfo));},get operatorInfo(){var info={};Object.assign(info,this._operatorInfo||this.getInfoFromMobileConnection(),this._predefinedOperatorInfo);return info;},get carrierName(){var info=this.operatorInfo;return info.carrier||info.operator;},get region(){return this.operatorInfo.region||'';},start:function(){window.addEventListener('hashchange',this);window.addEventListener('ftu-done',this);window.addEventListener('online',this);window.addEventListener('offline',this);this._operatorInfo=this.getInfoFromMobileConnection();this.waitForSettingValues().then((results)=>{var[url,predefinedInfo]=results;if(url){this._customizationManifestUrl=url;} if(predefinedInfo){this._predefinedOperatorInfo=predefinedInfo;} this.debug('start, resolved manifest url: '+this._customizationManifestUrl,' is enabled? '+this.enabled,' operatorInfo: ',this._operatorInfo);if(this.enabled){this.init();}else{this.debug('Not enabled; not initializing');if(!this._operatorInfo){this.waitForOperatorInfo().then((info)=>{if(!this._initialized&&this.enabled){this.init();}});}}}).catch(e=>{this.debug('start: didnt init, error from waitForSettingValues: ',e);});},init:function(){if(this._initialized||!this.enabled){return;} this._initialized=true;this.appManifestUrls=[];this.render();Navigation.registerStep({hash:'#late_customization',afterStep:'firefox_accounts'});this.attemptToPopulateAppList();},postConnectMessage:function(message){navigator.mozApps.getSelf().onsuccess=function(evt){var app=evt.target.result;if(app.connect){app.connect(COMMS_CHANNEL).then(function onConnAccepted(ports){ports.forEach(function(port){port.postMessage(message);});},function onConnRejected(reason){console.error('Cannot connect to comms channel: ',reason);});}else{console.error('mozApps does not have a connect method. '+'Cannot connect to the comms channel.');}};},attemptToPopulateAppList:function(){this.debug('attemptToPopulateAppList, waiting to go online');var connected=this.whenUsableConnection();connected.then(()=>{this.debug('attemptToPopulateAppList, came online');return this.fetchAppsToInstall().then((appsMap)=>{if(!(this._appsToInstall&&this._appsToInstall.size)){this.debug('No apps in response from '+ this._customizationManifestUrl+', bailing');return;} var urls=Array.from(this._appsToInstall.keys());var postMessageDetail={type:'late-customization-apps',urls:urls};this.postConnectMessage(postMessageDetail);this.updateAppList(this._appsToInstall);}).catch(err=>{console.warn('LateCustomizationPanel, error fetching customization '+'manifest from: '+this._customizationManifestUrl,err.message);});}).catch((e)=>{this.debug('No connection available in time to '+'fetch late customization manifest:',e);});return connected;},fetchAppsToInstall:function(){if(this._appsToInstall){return Promise.resolve(this._appsToInstall);} return this.fetchManifest().then((manifestResp)=>{var appsMap=this.getAppsFromManifest(manifestResp);if(!appsMap){return Promise.reject('getAppsFromManifest didnt return appsMap');} return(this._appsToInstall=appsMap);},(err)=>{console.warn('LateCustomization: ',err.message||err);});},waitForSettingValues:function(){var haveUrl,haveInfo;var lock=navigator.mozSettings.createLock();function getSetting(name){return new Promise((resolve,reject)=>{lock=(lock&&!lock.closed)?lock:navigator.mozSettings.createLock();var get=lock.get(name);get.addEventListener('success',(function(){resolve(get.result[name]);}));get.addEventListener('error',(function(){reject();}));});} if(this._customizationManifestUrl){haveUrl=Promise.resolve(this._customizationManifestUrl);}else{haveUrl=getSetting(MANIFEST_SETTING_NAME);} haveInfo=getSetting(OPERATOR_INFO_SETTING_NAME);return Promise.all([haveUrl,haveInfo]);},waitForOperatorInfo:function(){var info=this.getInfoFromMobileConnection();if(info){this._operatorInfo=info;return Promise.resolve(info);} return new Promise((resolve,reject)=>{this._operatorInfoRequest={resolve:resolve,reject:reject};});},getInfoFromMobileConnection:function(){var connections=navigator.mozMobileConnections;if(connections){for(var i=0,conn;i{return app.is_disabled!==true&&(new Set(app.device_types)).has('firefoxos');}).forEach((appData)=>{appData.manifestURL=appData.manifest_url;var appName='';langs.some(function tryLanguage(lang){if(this[lang]){appName=this[lang];return true;}},appData.name);appData.displayName=appName;this.debug('app data: ',appData.displayName,appData);apps.set(appData.manifestURL,appData);});return apps;},attemptInstalls:function(){this._installQueue=[];if(this._appsToInstall&&this._appsToInstall.size){var attempts=[];this._appsToInstall.forEach((appData,manifestURL)=>{if(appData.installState=='installed'||appData.installState=='pending'){this.debug('attemptInstalls: app install already underway: ',manifestURL,appData.installState);}else{attempts.push(this.enqueAppInstall(appData));}});return Promise.all(attempts);}else{return Promise.resolve();}},installApp:function(appData){this.debug('installApp: ',appData.manifestURL);return this.whenUsableConnection().then(()=>{return new Promise((resolve,reject)=>{var req=window.navigator.mozApps.install(appData.manifestURL);var onOutcome=(arg)=>{var selector=`li[data-manifest-url="${appData.manifestURL}"]`;var itemNode=this.appListNode.querySelector(selector);var manifestURL=req.result&&req.result.manifestURL;this.debug('appinstall DOMRequest outcome:',arg,req.result);if(req.error){delete appData.installState;itemNode&&itemNode.classList.add('failed');console.warn('Install error: ',req.error);}else if(req.result){appData.installState=req.result.installState;this.debug('Install success, app: ',manifestURL,appData.installState);} itemNode&&itemNode.classList.remove('pending');resolve(req);};req.onsuccess=req.onerror=onOutcome;});}).catch(()=>{this.debug('Lost connection while attempting install of '+ appData.manifestURL);});},enqueAppInstall:function(app){var installQueue=this._installQueue;installQueue.push(app);this.debug('enqueAppInstall, queue: ',app.manifestURL);var currentInstallAttempt=this._installAttempt||Promise.resolve();return currentInstallAttempt.then(req=>{if(req&&req.error){console.warn('install error:',req.error);} if(this._installQueue.length){this._installAttempt=this.installApp(this._installQueue.shift());}});},debug:function(){if(!this.DEBUG){return;} var args=Array.from(arguments);args.unshift('LateCustomizationPanel');console.log.apply(console,args);},buildManifestUrl:function(url,infos={}){var apiURL=new URL(url);var params=new URLSearchParams(apiURL.search.substr(1));for(var key in infos){if(typeof infos[key]!=='undefined'){params.set(key,infos[key]);}} apiURL.search=params.toString();return apiURL.href;},fetchManifest:function(){var url=this.buildManifestUrl(this._customizationManifestUrl,this.operatorInfo);if(!url){return Promise.reject(new Error('No manifest URL available'));} this.debug('fetchManifest at: '+url);return new Promise((resolve,reject)=>{LazyLoader.getJSON(url,true).then((resp)=>{if(resp.objects){resolve(resp);}else{reject('No apps in reponse to: '+url);}}).catch(ex=>{reject(ex);});});},whenUsableConnection:function(){if(this._pendingNextOnline){return this._pendingNextOnline;} var canDownload=navigator.onLine;if(canDownload){return Promise.resolve(true);} return new Promise((resolve,reject)=>{this._nextOnlineRequest={resolve:resolve,reject:reject};});},handleEvent:function(evt){switch(evt.type){case'hashchange':if(this.enabled&&evt.target.location.hash==='#late_customization'){if(this._appsToInstall&&this._appsToInstall.size){this.onPanelShown();}else{Navigation.skipStep();}} if(this._operatorInfoRequest){var info=this.getInfoFromMobileConnection();if(info){this._operatorInfo=info;this._operatorInfoRequest.resolve(info);this._operatorInfoRequest=null;}} break;case'online':case'offline':if(navigator.onLine&&this._installQueue&&this._installQueue.length){return this.attemptInstalls();} if(navigator.onLine&&this._nextOnlineRequest){this._nextOnlineRequest.resolve(true);}else if(this._nextOnlineRequest){this._nextOnlineRequest.reject(new Error('offline'));if(!this._appsToInstall){this.attemptToPopulateAppList();}} this._nextOnlineRequest=null;break;case'ftu-done':if(this._operatorInfoRequest){this._operatorInfoRequest.reject(new Error('FTU complete with no viable operator'));this._operatorInfoRequest=null;} if(this._nextOnlineRequest){this._nextOnlineRequest.reject(new Error('done before connection became available'));this._nextOnlineRequest=null;} break;}},onPanelShown:function(){UIManager.mainTitle.setAttribute('data-l10n-id','late-customization');this.finalizeRender();this.attemptInstalls();},_createElement:function(name,options){var elm=document.createElement(name);if(options.id){elm.id=options.id;} if(options.className){elm.className=options.className;} if(options.dataset){for(var p in options.dataset){elm.dataset[p]=options.dataset[p];}} if(options.attributes){for(var a in options.attributes){elm.setAttribute(a,options.attributes[a]);}} if('textContent'in options){elm.textContent=options.textContent;} return elm;},render:function(){var section=this.element=document.getElementById('late_customization');if(!section){section=this._createElement('section',{attributes:{role:'region'},id:'late_customization'});this.element=section;} section.innerHTML=Sanitizer.escapeHTML`

`;function setTranslationById(domId,l10Id,attrs){var elem=section.querySelector('#'+domId);document.l10n.setAttributes(elem,l10Id,attrs);} var carrierName=this.carrierName;if(carrierName){setTranslationById('late_customization-downloading-message','late-customization-downloading-message',{carrierName:this.carrierName});setTranslationById('late_customization-download-later-message','late-customization-download-later',{carrierName:this.carrierName});}else{setTranslationById('late_customization-downloading-message','late-customization-downloading-message-default');setTranslationById('late_customization-download-later-message','late-customization-download-later-default');} setTranslationById('late_customization-download-later-marketplace','late-customization-download-later-marketplace',{carrierName:this.carrierName});if(!section.parentNode){document.querySelector('#activation-screen > article').appendChild(section);} this.appListNode=document.querySelector('#late_customization-applist');},renderAppItem:function(appData){var itemNode=this._createElement('li',{dataset:{manifestUrl:appData.manifestURL},className:'pending'});var listNode=this.element.querySelector('#late_customization-applist');if(!listNode){this.debug('No element found to render app details into');return;} itemNode.innerHTML=Sanitizer.escapeHTML`

${appData.displayName}

`;listNode.appendChild(itemNode);var iconElem=itemNode.querySelector('.icon');this.getAppIconUrl(appData).then((iconUrl)=>{this.debug('getAppIconUrl returned:',iconUrl);var img=new Image();img.onload=()=>{iconElem.style.backgroundImage='url('+img.src+')';};img.onerror=()=>{iconElem.style.backgroundImage='url('+ICON_DEFAULT_URL+')';};img.src=iconUrl.href;});return itemNode;},getAppIconUrl:function(appData,iconSize=ICON_SIZE){var siteObj={};var manifest=appData;var manifestURL=appData.manifest_url;var origin=manifest.origin=new URL(manifestURL).origin;var hasIcons=(manifest.icons&&Object.keys(manifest.icons).length);if(!hasIcons){return Promise.resolve(new URL(ICON_DEFAULT_URL));} siteObj.manifestURL=manifestURL;siteObj.manifest=manifest;var gotIcon=new Promise((resolve,reject)=>{IconsHelper.getIcon(origin,iconSize,null,siteObj).then((iconUrl)=>{this.debug('getIcon returned: ',iconUrl);resolve(iconUrl);}).catch(err=>{this.debug('Failed to load icon from: '+ JSON.stringify(appData.icons));console.warn('getIcon errback, err: ',err);resolve(new URL(ICON_FAILED_URL));});});return gotIcon;},finalizeRender:function(){var container=this.element;var appsMap=this._appsToInstall;var hasApps=(appsMap&&appsMap.size);var canDoElm=container.querySelector('#late-customization-cando');var noCanDoElm=container.querySelector('#late-customization-nocando');var appListElm=container.querySelector('#late_customization-applist');canDoElm.classList.toggle('hidden',!hasApps);appListElm.classList.toggle('hidden',!hasApps);noCanDoElm.classList.toggle('hidden',!!hasApps);},updateAppList:function(appsMap){var list=this.element.querySelector('#late_customization-applist');this.debug('updateAppList: ',appsMap);while(list.firstChild){list.firstChild.remove();} if(appsMap&&appsMap.size){for(var appData of appsMap.values()){this.debug('calling renderAppItem with app: ',appData.manifestURL);this.renderAppItem(appData);}} this.finalizeRender();}};exports.LateCustomizationPanel=LateCustomizationPanel;var panel;document.l10n.ready.then(()=>{panel=exports.lateCustomizationPanel=new LateCustomizationPanel();});window.addEventListener('ftu-setup',function onSetup(evt){window.removeEventListener('ftu-setup',onSetup);panel&&(panel.manager=evt.detail);panel&&panel.start();});})(window);