;'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;i2){throw new L10nError('Error in ID: "'+name+'".'+' Nested attributes are not supported.');} var attr;if(nameElements.length>1){name=nameElements[0];attr=nameElements[1];if(attr[0]==='$'){throw new L10nError('Attribute can\'t start with "$"',id);}}else{attr=null;} this.setEntityValue(name,attr,key,this.unescapeString(value),ast);},setEntityValue:function(id,attr,key,rawValue,ast){var pos,v;var value=rawValue.indexOf('{{')>-1?this.parseString(rawValue):rawValue;if(attr){pos=this.entryIds[id];if(pos===undefined){v={$i:id};if(key){v[attr]={};v[attr][key]=value;}else{v[attr]=value;} ast.push(v);this.entryIds[id]=ast.length-1;return;} if(key){if(typeof(ast[pos][attr])==='string'){ast[pos][attr]={$x:this.parseIndex(ast[pos][attr]),$v:{}};} ast[pos][attr].$v[key]=value;return;} ast[pos][attr]=value;return;} if(key){pos=this.entryIds[id];if(pos===undefined){v={};v[key]=value;ast.push({$i:id,$v:v});this.entryIds[id]=ast.length-1;return;} if(typeof(ast[pos].$v)==='string'){ast[pos].$x=this.parseIndex(ast[pos].$v);ast[pos].$v={};} ast[pos].$v[key]=value;return;} ast.push({$i:id,$v:value});this.entryIds[id]=ast.length-1;},parseString:function(str){var chunks=str.split(this.patterns.placeables);var complexStr=[];var len=chunks.length;var placeablesCount=(len-1)/2;if(placeablesCount>=MAX_PLACEABLES){throw new L10nError('Too many placeables ('+placeablesCount+', max allowed is '+MAX_PLACEABLES+')');} for(var i=0;i-1){return[{},env['__'+id]];} if(args&&args.hasOwnProperty(id)){if(typeof args[id]==='string'||(typeof args[id]==='number'&&!isNaN(args[id]))){return[{},args[id]];}else{throw new L10nError('Arg must be a string or a number: '+id);}} if(id in env&&id!=='__proto__'){return format(args,env[id]);} throw new L10nError('Unknown reference: '+id);} function subPlaceable(locals,args,env,id){var res;try{res=resolveIdentifier(args,env,id);}catch(err){return[{error:err},'{{ '+id+' }}'];} var value=res[1];if(typeof value==='number'){return res;} if(typeof value==='string'){if(value.length>=MAX_PLACEABLE_LENGTH){throw new L10nError('Too many characters in placeable ('+ value.length+', max allowed is '+ MAX_PLACEABLE_LENGTH+')');} if(locals.contextIsNonLatin1||value.match(nonLatin1)){res[1]=FSI+value+PDI;} return res;} return[{},'{{ '+id+' }}'];} function interpolate(locals,args,env,arr){return arr.reduce(function(prev,cur){if(typeof cur==='string'){return[prev[0],prev[1]+cur];}else if(cur.t==='idOrVar'){var placeable=subPlaceable(locals,args,env,cur.v);return[prev[0],prev[1]+placeable[1]];}},[locals,'']);} function resolveSelector(args,env,expr,index){var selectorName=index[0].v;var selector=resolveIdentifier(args,env,selectorName)[1];if(typeof selector!=='function'){return selector;} var argValue=index[1]?resolveIdentifier(args,env,index[1])[1]:undefined;if(selector===env.__plural){if(argValue===0&&'zero'in expr){return'zero';} if(argValue===1&&'one'in expr){return'one';} if(argValue===2&&'two'in expr){return'two';}} return selector(argValue);} function resolveValue(locals,args,env,expr,index){if(!expr){return[locals,expr];} if(typeof expr==='string'||typeof expr==='boolean'||typeof expr==='number'){return[locals,expr];} if(Array.isArray(expr)){locals.contextIsNonLatin1=expr.some(function($_){return typeof($_)==='string'&&$_.match(nonLatin1);});return interpolate(locals,args,env,expr);} if(index){var selector=resolveSelector(args,env,expr,index);if(expr.hasOwnProperty(selector)){return resolveValue(locals,args,env,expr[selector]);}} if('other'in expr){return resolveValue(locals,args,env,expr.other);} throw new L10nError('Unresolvable value');} var Resolver={createEntry:createEntry,format:format,rePlaceables:rePlaceables};function walkContent(node,fn){if(typeof node==='string'){return fn(node);} if(node.t==='idOrVar'){return node;} var rv=Array.isArray(node)?[]:{};var keys=Object.keys(node);for(var i=0,key;(key=keys[i]);i++){if(key==='$i'||key==='$x'){rv[key]=node[key];}else{rv[key]=walkContent(node[key],fn);}} return rv;} var reAlphas=/[a-zA-Z]/g;var reVowels=/[aeiouAEIOU]/g;var ACCENTED_MAP='\u0226\u0181\u0187\u1E12\u1E16\u0191\u0193\u0126\u012A'+'\u0134\u0136\u013F\u1E3E\u0220\u01FE\u01A4\u024A\u0158'+'\u015E\u0166\u016C\u1E7C\u1E86\u1E8A\u1E8E\u1E90'+'[\\]^_`'+'\u0227\u0180\u0188\u1E13\u1E17\u0192\u0260\u0127\u012B'+'\u0135\u0137\u0140\u1E3F\u019E\u01FF\u01A5\u024B\u0159'+'\u015F\u0167\u016D\u1E7D\u1E87\u1E8B\u1E8F\u1E91';var FLIPPED_MAP='\u2200\u0510\u2183p\u018E\u025F\u05E4HI\u017F'+'\u04FC\u02E5WNO\u0500\xD2\u1D1AS\u22A5\u2229\u0245'+'\uFF2DX\u028EZ'+'[\\]\u1D65_,'+'\u0250q\u0254p\u01DD\u025F\u0183\u0265\u0131\u027E'+'\u029E\u0285\u026Fuodb\u0279s\u0287n\u028C\u028Dx\u028Ez';function makeLonger(val){return val.replace(reVowels,function(match){return match+match.toLowerCase();});} function replaceChars(map,val){return val.replace(reAlphas,function(match){return map.charAt(match.charCodeAt(0)-65);});} var reWords=/[^\W0-9_]+/g;function makeRTL(val){return val.replace(reWords,function(match){return'\u202e'+match+'\u202c';});} var reExcluded=/(%[EO]?\w|\{\s*.+?\s*\}|&[#\w]+;|<\s*.+?\s*>)/;function mapContent(fn,val){if(!val){return val;} var parts=val.split(reExcluded);var modified=parts.map(function(part){if(reExcluded.test(part)){return part;} return fn(part);});return modified.join('');} function Pseudo(id,name,charMap,modFn){this.id=id;this.translate=mapContent.bind(null,function(val){return replaceChars(charMap,modFn(val));});this.name=this.translate(name);} var PSEUDO={'fr-x-psaccent':new Pseudo('fr-x-psaccent','Runtime Accented',ACCENTED_MAP,makeLonger),'ar-x-psbidi':new Pseudo('ar-x-psbidi','Runtime Bidi',FLIPPED_MAP,makeRTL)};function Locale(id,ctx){this.id=id;this.ctx=ctx;this.isReady=false;this.entries=Object.create(null);this.entries.__plural=getPluralRule(this.isPseudo()?this.ctx.defaultLocale:id);} Locale.prototype.isPseudo=function(){return this.ctx.qps.indexOf(this.id)!==-1;};var bindingsIO={extra:function(id,ver,path,type,callback,errback){if(type==='properties'){type='text';} navigator.mozApps.getLocalizationResource(id,ver,path,type).then(callback.bind(null,null),errback);},app:function(id,ver,path,type,callback,errback,sync){switch(type){case'properties':io.load(path,callback,sync);break;case'json':io.loadJSON(path,callback,sync);break;}},};Locale.prototype.build=function L_build(callback){var sync=!callback;var ctx=this.ctx;var self=this;var l10nLoads=ctx.resLinks.length;function onL10nLoaded(err){if(err){ctx._emitter.emit('fetcherror',err);} if(--l10nLoads<=0){self.isReady=true;if(callback){callback();}}} if(l10nLoads===0){onL10nLoaded();return;} function onJSONLoaded(err,json){if(!err&&json){self.addAST(json);} onL10nLoaded(err);} function onPropLoaded(err,source){if(!err&&source){var ast=PropertiesParser.parse(ctx,source);self.addAST(ast);} onL10nLoaded(err);} var idToFetch=this.isPseudo()?ctx.defaultLocale:this.id;var appVersion=null;var source='app';if(typeof(navigator)!=='undefined'){source=navigator.mozL10n._config.localeSources[this.id]||'app';appVersion=navigator.mozL10n._config.appVersion;} for(var i=0;i=0)?'rtl':'ltr';} var readyStates={loading:0,interactive:1,complete:2};function whenInteractive(callback){if(readyStates[document.readyState]>=readyStates.interactive){callback();return;} document.addEventListener('readystatechange',function l10n_onrsc(){if(readyStates[document.readyState]>=readyStates.interactive){document.removeEventListener('readystatechange',l10n_onrsc);callback();}});} function initObserver(){nodeObserver=new MutationObserver(onMutations.bind(navigator.mozL10n));nodeObserver.observe(document,moConfig);} function init(pretranslate){if(!pretranslate){initObserver();} initResources.call(navigator.mozL10n);} function initResources(){var meta={};var nodes=document.head.querySelectorAll('link[rel="localization"],'+'meta[name="availableLanguages"],'+'meta[name="defaultLanguage"],'+'meta[name="appVersion"],'+'script[type="application/l10n"]');for(var i=0,node;node=nodes[i];i++){var type=node.getAttribute('rel')||node.nodeName.toLowerCase();switch(type){case'localization':this.ctx.resLinks.push(node.getAttribute('href'));break;case'meta':onMetaInjected.call(this,node,meta);break;case'script':onScriptInjected.call(this,node);break;}} var additionalLanguagesPromise;if(navigator.mozApps&&navigator.mozApps.getAdditionalLanguages){additionalLanguagesPromise=navigator.mozApps.getAdditionalLanguages().catch(function(e){console.error('Error while loading getAdditionalLanguages',e);});document.addEventListener('additionallanguageschange',function(evt){registerLocales.call(this,meta,evt.detail);this.ctx.requestLocales.apply(this.ctx,navigator.languages||[navigator.language]);}.bind(this));}else{additionalLanguagesPromise=Promise.resolve();} additionalLanguagesPromise.then(function(extraLangs){registerLocales.call(this,meta,extraLangs);initLocale.call(this);}.bind(this));} function registerLocales(meta,extraLangs){var locales=buildLocaleList.call(this,meta,extraLangs);navigator.mozL10n._config.localeSources=locales[1];this.ctx.registerLocales(locales[0],Object.keys(locales[1]));} function getMatchingLangpack(appVersion,langpacks){for(var i=0,langpack;(langpack=langpacks[i]);i++){if(langpack.target===appVersion){return langpack;}} return null;} function buildLocaleList(meta,extraLangs){var loc,lp;var localeSources=Object.create(null);var defaultLocale=meta.defaultLanguage||this.ctx.defaultLocale;if(meta.availableLanguages){for(loc in meta.availableLanguages){localeSources[loc]='app';}} if(extraLangs){for(loc in extraLangs){lp=getMatchingLangpack(this._config.appVersion,extraLangs[loc]);if(!lp){continue;} if(!(loc in localeSources)||!meta.availableLanguages[loc]||parseInt(lp.revision)>meta.availableLanguages[loc]){localeSources[loc]='extra';}}} if(!(defaultLocale in localeSources)){localeSources[defaultLocale]='app';} return[defaultLocale,localeSources];} function splitAvailableLanguagesString(str){var langs={};str.split(',').forEach(function(lang){lang=lang.trim().split(':');langs[lang[0]]=parseInt(lang[1]);});return langs;} function onMetaInjected(node,meta){switch(node.getAttribute('name')){case'availableLanguages':meta.availableLanguages=splitAvailableLanguagesString(node.getAttribute('content'));break;case'defaultLanguage':meta.defaultLanguage=node.getAttribute('content');break;case'appVersion':navigator.mozL10n._config.appVersion=node.getAttribute('content');break;}} function onScriptInjected(node){var lang=node.getAttribute('lang');var locale=this.ctx.getLocale(lang);locale.addAST(JSON.parse(node.textContent));} function initLocale(){this.ctx.requestLocales.apply(this.ctx,navigator.languages||[navigator.language]);window.addEventListener('languagechange',function l10n_langchange(){this.ctx.requestLocales.apply(this.ctx,navigator.languages||[navigator.language]);}.bind(this));} function localizeMutations(mutations){var mutation;var targets=new Set();for(var i=0;i]/g;var htmlEntities={'&':'&','<':'<','>':'>',};function translateDocument(){document.documentElement.lang=this.language.code;document.documentElement.dir=this.language.direction;translateFragment.call(this,document.documentElement);} function translateFragment(element){if(typeof element.hasAttribute==='function'&&element.hasAttribute('data-l10n-id')){translateElement.call(this,element);} var nodes=getTranslatableChildren(element);for(var i=0;ilist.join(sep));},DateTimeFormat:function(locales,options){const resolvedOptions=Object.assign({},options);if(resolvedOptions.dayperiod){if(resolvedOptions.hour===undefined){resolvedOptions.hour='numeric';}} if(resolvedOptions.hour!==undefined&&resolvedOptions.hour12===undefined){resolvedOptions.hour12=navigator.mozHour12;} if(resolvedOptions.dayperiod===undefined&&resolvedOptions.hour12===true){resolvedOptions.dayperiod=true;} var intlFormat=new Intl.DateTimeFormat(locales,resolvedOptions);resolvedOptions.locale=intlFormat.resolvedOptions().locale;resolvedOptions.hour12=intlFormat.resolvedOptions().hour12;var hourFormatter;if(resolvedOptions.dayperiod!==undefined&&resolvedOptions.hour12===true){hourFormatter=Intl.DateTimeFormat(locales,{hour:'numeric',hour12:false});} return{resolvedOptions(){return resolvedOptions;},format:function(date,tokenFormats){var dayPeriod;var string=intlFormat.format(date);if(resolvedOptions.dayperiod===false&&resolvedOptions.hour12===true){dayPeriod=getDayPeriodTokenForDate(date,hourFormatter);string=string.replace(dayPeriod,'').trim();}else if(resolvedOptions.dayperiod===true&&options.hour===undefined){dayPeriod=getDayPeriodTokenForDate(date,hourFormatter);const hour=date.toLocaleString(navigator.languages,{hour12:true,hour:'numeric'}).replace(dayPeriod,'').trim();string=string.replace(hour,'').trim();} for(var token in tokenFormats){if(token==='dayperiod'&&resolvedOptions.hour12===false){continue;} const localOptions={[token]:resolvedOptions[token],};var formatter=global.mozIntl.DateTimeFormat(navigator.languages,localOptions);var tokenString=formatter.format(date);string=string.replace(tokenString,tokenFormats[token]);} return string;},};},calendarInfo:function(token){switch(token){case'firstDayOfTheWeek':return navigator.mozL10n.formatValue('firstDayOfTheWeek').then(firstDayOfTheWeek=>parseInt(firstDayOfTheWeek)%7);default:throw new Error('Unknown token: '+token);}},DurationFormat:function(locales=navigator.languages,options={}){const resolvedOptions=Object.assign({locale:locales[0],maxUnit:'hour',minUnit:'second',},options);const numFormatter=Intl.NumberFormat(locales,{style:'decimal',useGrouping:false,minimumIntegerDigits:2});const maxUnitIdx=getDurationUnitIdx(resolvedOptions.maxUnit,0);const minUnitIdx=getDurationUnitIdx(resolvedOptions.minUnit,durationFormatOrder.length-1);return navigator.mozL10n.formatValue('durationPattern').then(fmt=>({resolvedOptions:function(){return resolvedOptions;},format:function(input){const minValue=durationFormatElements[resolvedOptions.minUnit].value;input=Math.round(input/minValue)*minValue;const duration=splitIntoTimeUnits(input,maxUnitIdx,minUnitIdx);var string=trimDurationPattern(fmt,resolvedOptions.maxUnit,resolvedOptions.minUnit);for(var unit in duration){const token=durationFormatElements[unit].token;string=string.replace(token,numFormatter.format(duration[unit]));} if(input<0){return'-'+string;} return string;}}));},RelativeTimeFormat:function(locales,options){return{resolvedOptions:function(){return options;},format:function(x){const{unit,value}=relativeTimeFormatId(x,options);return navigator.mozL10n.formatValue(unit,{value});},};},UnitFormat:function(locales,options){const unitGroup=getUnitFormatGroupName(options.unit);if(unitGroup===undefined){throw new RangeError(`invalid value ${options.unit} for option unit`);} if(!unitFormatGroups[unitGroup].styles.includes(options.style)){throw new RangeError(`invalid value ${options.style} for option style`);} const unit=`${unitGroup}-${options.unit}-${options.style}`;return{format:function(x){return document.l10n.formatValue(unit,{value:x});},};},_gaia:{relativePart:function(milliseconds){const units=computeTimeUnits(milliseconds);const unit=getBestMatchUnit(units);return{unit:unit+'s',value:Math.abs(units[unit])};},RelativeDate:function(locales,options){const style=options&&options.style||'long';const maxFormatter=Intl.DateTimeFormat(locales,{year:'numeric',month:'numeric',day:'numeric'});const relativeFmtOptions={unit:'bestFit',style:style,minUnit:'minute',};return{format:function(time,maxDiff){maxDiff=maxDiff||86400*10;const secDiff=(Date.now()-time)/1000;if(isNaN(secDiff)){return navigator.mozL10n.formatValue('incorrectDate');} if(secDiff>maxDiff){return Promise.resolve(maxFormatter.format(time));} const{unit,value}=relativeTimeFormatId(time,relativeFmtOptions);return navigator.mozL10n.formatValue(unit,{value});},formatElement:function(element,time,maxDiff){maxDiff=maxDiff||86400*10;const secDiff=(Date.now()-time)/1000;if(isNaN(secDiff)){element.setAttribute('data-l10n-id','incorrectDate');} element.removeAttribute('data-l10n-id');if(secDiff>maxDiff){element.textContent=maxFormatter.format(time);} const{unit,value}=relativeTimeFormatId(time,relativeFmtOptions);navigator.mozL10n.setAttributes(element,unit,{value});},};},getFormattedUnit:function(type,style,v){if(!unitFormatData.hasOwnProperty(type)){throw new RangeError(`invalid type ${type}`);} if(!unitFormatGroups[type].styles.includes(style)){throw new RangeError(`invalid style ${style} for type ${type}`);} var units=unitFormatData[type];var scale=0;for(let i=1;i part.type === 'dayPeriod').value;} function computeTimeUnits(v){const units={};const millisecond=Math.round(v);const second=Math.round(millisecond/1000);const minute=Math.round(second/60);const hour=Math.round(minute/60);const day=Math.round(hour/24);const rawYear=day*400/146097;units.millisecond=millisecond;units.second=second;units.minute=minute;units.hour=hour;units.day=day;units.week=Math.round(day/7);units.month=Math.round(rawYear*12);units.quarter=Math.round(rawYear*4);units.year=Math.round(rawYear);return units;} function getBestMatchUnit(units){if(Math.abs(units.minute)<45){return'minute';} if(Math.abs(units.hour)<22){return'hour';} if(Math.abs(units.day)<7){return'day';} if(Math.abs(units.week)<4){return'week';} if(Math.abs(units.month)<11){return'month';} return'year';} function relativeTimeFormatId(x,options){const ms=x-Date.now();const units=computeTimeUnits(ms);const unit=options.unit==='bestFit'?getBestMatchUnit(units):options.unit;const v=units[unit];const tl=v<0?'-ago':'-until';const style=options.style||'long';const entry=unit+'s'+tl+'-'+style;return{unit:entry,value:Math.abs(v)};} function getUnitFormatGroupName(unitName){for(let groupName in unitFormatGroups){if(unitFormatGroups[groupName].units.includes(unitName)){return groupName;}} return undefined;}})(this);;'use strict';function onLoadCallScreen(evt){window.removeEventListener('load',onLoadCallScreen);CallsHandler.setup();CallScreen.init();KeypadManager.init(true);} function unloadCallScreen(evt){} window.addEventListener('load',onLoadCallScreen);window.addEventListener('unload',unloadCallScreen);;'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 SettingsURL(){this._url=null;this._isBlob=false;} SettingsURL.prototype={set:function(value){if(this._isBlob){window.URL.revokeObjectURL(this._url);} if(value instanceof Blob){this._isBlob=true;this._url=window.URL.createObjectURL(value);}else{this._isBlob=false;this._url=value;} return this._url;},get:function(){return this._url;}};;this.asyncStorage=(function(){'use strict';var DBNAME='asyncStorage';var DBVERSION=1;var STORENAME='keyvaluepairs';var db=null;function withDatabase(f){if(db){f();}else{var openreq=indexedDB.open(DBNAME,DBVERSION);openreq.onerror=function withStoreOnError(){console.error('asyncStorage: can\'t open database:',openreq.error.name);};openreq.onupgradeneeded=function withStoreOnUpgradeNeeded(){openreq.result.createObjectStore(STORENAME);};openreq.onsuccess=function withStoreOnSuccess(){db=openreq.result;f();};}} function withStore(type,callback,oncomplete){withDatabase(function(){var transaction=db.transaction(STORENAME,type);if(oncomplete){transaction.oncomplete=oncomplete;} callback(transaction.objectStore(STORENAME));});} function getItem(key,callback){var req;withStore('readonly',function getItemBody(store){req=store.get(key);req.onerror=function getItemOnError(){console.error('Error in asyncStorage.getItem(): ',req.error.name);};},function onComplete(){var value=req.result;if(value===undefined){value=null;} callback(value);});} function setItem(key,value,callback){withStore('readwrite',function setItemBody(store){var req=store.put(value,key);req.onerror=function setItemOnError(){console.error('Error in asyncStorage.setItem(): ',req.error.name);};},callback);} function removeItem(key,callback){withStore('readwrite',function removeItemBody(store){var req=store.delete(key);req.onerror=function removeItemOnError(){console.error('Error in asyncStorage.removeItem(): ',req.error.name);};},callback);} function clear(callback){withStore('readwrite',function clearBody(store){var req=store.clear();req.onerror=function clearOnError(){console.error('Error in asyncStorage.clear(): ',req.error.name);};},callback);} function length(callback){var req;withStore('readonly',function lengthBody(store){req=store.count();req.onerror=function lengthOnError(){console.error('Error in asyncStorage.length(): ',req.error.name);};},function onComplete(){callback(req.result);});} function key(n,callback){if(n<0){callback(null);return;} var req;withStore('readonly',function keyBody(store){var advanced=false;req=store.openCursor();req.onsuccess=function keyOnSuccess(){var cursor=req.result;if(!cursor){return;} if(n===0||advanced){return;} advanced=true;cursor.advance(n);};req.onerror=function keyOnError(){console.error('Error in asyncStorage.key(): ',req.error.name);};},function onComplete(){var cursor=req.result;callback(cursor?cursor.key:null);});} return{getItem:getItem,setItem:setItem,removeItem:removeItem,clear:clear,length:length,key:key};}());;(function(exports){'use strict';function getThumbnail(contact){return getOnePhoto(contact,'begin');} function getFullResolution(contact){return getOnePhoto(contact,'end');} function getOnePhoto(contact,position){if(!contact||!contact.photo||!contact.photo.length){return null;} if(contact.photo.length===1){return contact.photo[0];} var photos=contact.photo;var category=contact.category;if(Array.isArray(category)&&category.indexOf('fb_linked')!==-1){if(photos.length>=4){return photos[(position=='begin')?1:0];} return photos[0];} photos=photosBySize(contact);var index=(position=='begin')?0:photos.length-1;return photos[index];} function photosBySize(contact){var photos=contact.photo.slice(0);photos.sort(function(p1,p2){if(size(p1)size(p2)){return 1;} return 0;});return photos;} function size(photo){if(typeof photo=='string'){return photo.length;} return photo.size;} exports.ContactPhotoHelper={getThumbnail:getThumbnail,getFullResolution:getFullResolution};})(window);;(function(exports){'use strict';var FontSizeUtils={_cachedContexts:{},_getCachedContext:function(fontSize,fontFamily,fontStyle){fontStyle=fontStyle||'italic';var cache=this._cachedContexts;var ctx=cache[fontSize]&&cache[fontSize][fontFamily]?cache[fontSize][fontFamily][fontStyle]:null;if(!ctx){var canvas=document.createElement('canvas');canvas.setAttribute('moz-opaque','true');canvas.setAttribute('width','1');canvas.setAttribute('height','1');ctx=canvas.getContext('2d',{willReadFrequently:true});ctx.font=fontStyle+' '+fontSize+'px '+fontFamily;if(!cache[fontSize]){cache[fontSize]={};} if(!cache[fontSize][fontFamily]){cache[fontSize][fontFamily]={};} cache[fontSize][fontFamily][fontStyle]=ctx;} return ctx;},resetCache:function(){this._cachedContexts={};},getFontWidth:function(string,fontSize,fontFamily,fontStyle){var ctx=this._getCachedContext(fontSize,fontFamily,fontStyle);return ctx.measureText(string).width;},getMaxFontSizeInfo:function(string,allowedSizes,fontFamily,maxWidth){var fontSize;var resultWidth;var i=allowedSizes.length-1;do{fontSize=allowedSizes[i];resultWidth=this.getFontWidth(string,fontSize,fontFamily);i--;}while(resultWidth>maxWidth&&i>=0);return{fontSize:fontSize,overflow:resultWidth>maxWidth,textWidth:resultWidth};},_overflowCountCache:-1,getOverflowCount:function(string,fontSize,fontFamily,maxWidth){var substring;var resultWidth;var overflowCount=-1;if(string.length>this._overflowCountCache){substring=string.substr(0,string.length-this._overflowCountCache);resultWidth=this.getFontWidth(substring,fontSize,fontFamily);if(resultWidth>maxWidth){overflowCount=this._overflowCountCache;}} do{overflowCount++;substring=string.substr(0,string.length-overflowCount);resultWidth=this.getFontWidth(substring,fontSize,fontFamily);}while(substring.length>0&&resultWidth>maxWidth);this._overflowCountCache=overflowCount;return overflowCount;},getContentWidth:function(style){var width=parseInt(style.width,10);if(style.boxSizing==='border-box'){width-=(parseInt(style.paddingRight,10)+ parseInt(style.paddingLeft,10));} return width;},getStyleProperties:function(element){var style=window.getComputedStyle(element);var contentWidth=this.getContentWidth(style);if(isNaN(contentWidth)){contentWidth=0;} return{fontFamily:style.fontFamily,contentWidth:contentWidth,paddingRight:parseInt(style.paddingRight,10),paddingLeft:parseInt(style.paddingLeft,10),offsetLeft:element.offsetLeft};},getWindowWidth:function(){return window.innerWidth;}};exports.FontSizeUtils=FontSizeUtils;}(this));;(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 SimplePhoneMatcher={mcc:'724',sanitizedNumber:function spm_sanitizedNumber(number){var join=this._formattingChars.join('|\\');var regexp=new RegExp('(\\'+join+')','g');return number.replace(regexp,'');},generateVariants:function spm_generateVariants(number){var sanitizedNumber=this.sanitizedNumber(number);var variants=[];variants=variants.concat(this._internationalPrefixes(sanitizedNumber),this._trunkPrefixes(sanitizedNumber),this._carrierPrefixes(sanitizedNumber),this._areaPrefixes(sanitizedNumber));return variants.sort(function shortestFirst(a,b){return a.length>b.length;});},bestMatch:function spm_bestMatchIndex(variants,matches){var bestMatchIndex=0;var bestLocalIndex=0;var bestMatchLength=0;var allMatches=[];var matchNum=0;matches.forEach(function(match,matchIndex){var indexes=[];match.forEach(function(number,localIndex){var sanitizedNumber=this.sanitizedNumber(number);variants.forEach(function match(variant){if(variant.indexOf(sanitizedNumber)!==-1||sanitizedNumber.indexOf(variant)!==-1){var length=sanitizedNumber.length;if(indexes.indexOf(localIndex)===-1){indexes.push(localIndex);matchNum+=1;} if(length>bestMatchLength){bestMatchLength=length;bestMatchIndex=matchIndex;bestLocalIndex=localIndex;}}});},this);if(indexes.length){allMatches.push(indexes);}else{matchNum+=1;allMatches.push([0]);}},this);return{totalMatchNum:matchNum,allMatches:allMatches,bestMatchIndex:bestMatchIndex,localIndex:bestLocalIndex};},_formattingChars:['\s','-','.','(',')'],_mccWith00Prefix:['208','214','234','235','724'],_mccWith011Prefix:['310','311','312','313','314','315','316'],_countryPrefixes:[{p:'1',t:false},{p:'1242',t:false},{p:'1246',t:false},{p:'1264',t:false},{p:'1268',t:false},{p:'1284',t:false},{p:'1340',t:false},{p:'1345',t:false},{p:'1441',t:false},{p:'1473',t:false},{p:'1649',t:false},{p:'1664',t:false},{p:'1670',t:false},{p:'1671',t:false},{p:'1684',t:false},{p:'1721',t:false},{p:'1758',t:false},{p:'1767',t:false},{p:'1784',t:false},{p:'1787',t:false},{p:'1809',t:false},{p:'1829',t:false},{p:'1849',t:false},{p:'1868',t:false},{p:'1869',t:false},{p:'1876',t:false},{p:'1939',t:false},{p:'20',t:false},{p:'210',t:false},{p:'211',t:false},{p:'212',t:false},{p:'213',t:false},{p:'214',t:false},{p:'215',t:false},{p:'216',t:false},{p:'217',t:false},{p:'218',t:false},{p:'219',t:false},{p:'220',t:false},{p:'221',t:false},{p:'222',t:false},{p:'223',t:false},{p:'224',t:false},{p:'225',t:false},{p:'226',t:false},{p:'227',t:false},{p:'228',t:false},{p:'229',t:false},{p:'230',t:false},{p:'231',t:false},{p:'232',t:false},{p:'233',t:false},{p:'234',t:false},{p:'235',t:false},{p:'236',t:false},{p:'237',t:false},{p:'238',t:false},{p:'239',t:false},{p:'240',t:false},{p:'241',t:false},{p:'242',t:false},{p:'243',t:false},{p:'244',t:false},{p:'245',t:false},{p:'246',t:false},{p:'247',t:false},{p:'248',t:false},{p:'249',t:false},{p:'250',t:false},{p:'251',t:false},{p:'252',t:false},{p:'253',t:false},{p:'254',t:false},{p:'255',t:false},{p:'256',t:false},{p:'257',t:false},{p:'258',t:false},{p:'259',t:false},{p:'260',t:false},{p:'261',t:false},{p:'262',t:false},{p:'263',t:false},{p:'264',t:false},{p:'265',t:false},{p:'266',t:false},{p:'267',t:false},{p:'268',t:false},{p:'269',t:false},{p:'27',t:false},{p:'28',t:false},{p:'290',t:false},{p:'291',t:false},{p:'292',t:false},{p:'293',t:false},{p:'294',t:false},{p:'295',t:false},{p:'296',t:false},{p:'297',t:false},{p:'298',t:false},{p:'299',t:false},{p:'30',t:false},{p:'31',t:true},{p:'32',t:true},{p:'33',t:true},{p:'34',t:false},{p:'350',t:false},{p:'351',t:true},{p:'352',t:false},{p:'353',t:false},{p:'354',t:false},{p:'355',t:true},{p:'356',t:false},{p:'357',t:false},{p:'358',t:false},{p:'359',t:true},{p:'36',t:true},{p:'370',t:true},{p:'371',t:false},{p:'372',t:false},{p:'373',t:true},{p:'374',t:false},{p:'375',t:true},{p:'376',t:false},{p:'377',t:false},{p:'378',t:false},{p:'379',t:false},{p:'380',t:true},{p:'381',t:true},{p:'382',t:true},{p:'383',t:false},{p:'384',t:false},{p:'385',t:true},{p:'386',t:false},{p:'387',t:true},{p:'388',t:false},{p:'389',t:true},{p:'39',t:false},{p:'40',t:true},{p:'41',t:true},{p:'420',t:false},{p:'421',t:false},{p:'422',t:false},{p:'423',t:false},{p:'424',t:false},{p:'425',t:false},{p:'426',t:false},{p:'427',t:false},{p:'428',t:false},{p:'429',t:false},{p:'43',t:true},{p:'44',t:true},{p:'45',t:false},{p:'46',t:true},{p:'47',t:false},{p:'48',t:true},{p:'49',t:true},{p:'500',t:false},{p:'501',t:false},{p:'502',t:false},{p:'503',t:false},{p:'504',t:false},{p:'505',t:false},{p:'506',t:false},{p:'507',t:false},{p:'508',t:false},{p:'509',t:false},{p:'51',t:true},{p:'52',t:false},{p:'53',t:false},{p:'54',t:true},{p:'55',t:true},{p:'56',t:false},{p:'57',t:false},{p:'58',t:false},{p:'590',t:false},{p:'591',t:true},{p:'592',t:false},{p:'593',t:false},{p:'594',t:false},{p:'595',t:false},{p:'596',t:false},{p:'597',t:false},{p:'598',t:false},{p:'599',t:true},{p:'60',t:true},{p:'61',t:true},{p:'62',t:true},{p:'63',t:true},{p:'64',t:false},{p:'65',t:true},{p:'66',t:true},{p:'670',t:false},{p:'671',t:false},{p:'672',t:false},{p:'673',t:true},{p:'674',t:false},{p:'675',t:false},{p:'676',t:false},{p:'677',t:false},{p:'678',t:false},{p:'679',t:false},{p:'680',t:false},{p:'681',t:false},{p:'682',t:false},{p:'683',t:false},{p:'684',t:false},{p:'685',t:false},{p:'686',t:false},{p:'687',t:false},{p:'688',t:false},{p:'689',t:false},{p:'690',t:false},{p:'691',t:false},{p:'692',t:false},{p:'693',t:false},{p:'694',t:false},{p:'695',t:false},{p:'696',t:false},{p:'697',t:false},{p:'698',t:false},{p:'699',t:false},{p:'699',t:false},{p:'7',t:true},{p:'76',t:true},{p:'77',t:true},{p:'7840',t:false},{p:'7940',t:false},{p:'800',t:false},{p:'801',t:false},{p:'802',t:false},{p:'803',t:false},{p:'804',t:false},{p:'805',t:false},{p:'806',t:false},{p:'807',t:false},{p:'808',t:false},{p:'809',t:false},{p:'81',t:false},{p:'82',t:true},{p:'83',t:false},{p:'84',t:true},{p:'850',t:true},{p:'851',t:false},{p:'852',t:false},{p:'853',t:false},{p:'854',t:false},{p:'855',t:true},{p:'856',t:true},{p:'857',t:false},{p:'858',t:false},{p:'859',t:false},{p:'86',t:true},{p:'870',t:false},{p:'871',t:false},{p:'872',t:false},{p:'873',t:false},{p:'874',t:false},{p:'875',t:false},{p:'876',t:false},{p:'877',t:false},{p:'878',t:false},{p:'879',t:false},{p:'880',t:true},{p:'881',t:false},{p:'882',t:false},{p:'883',t:false},{p:'884',t:false},{p:'885',t:false},{p:'886',t:true},{p:'887',t:false},{p:'888',t:false},{p:'889',t:false},{p:'89',t:false},{p:'90',t:false},{p:'91',t:true},{p:'92',t:true},{p:'93',t:true},{p:'94',t:false},{p:'95',t:true},{p:'960',t:false},{p:'961',t:false},{p:'962',t:false},{p:'963',t:false},{p:'964',t:false},{p:'965',t:false},{p:'966',t:false},{p:'967',t:false},{p:'968',t:false},{p:'969',t:false},{p:'970',t:false},{p:'971',t:false},{p:'972',t:false},{p:'973',t:false},{p:'974',t:false},{p:'975',t:true},{p:'976',t:true},{p:'977',t:true},{p:'978',t:false},{p:'979',t:false},{p:'98',t:false},{p:'990',t:false},{p:'991',t:false},{p:'992',t:false},{p:'993',t:true},{p:'994',t:true},{p:'995',t:true},{p:'996',t:false},{p:'997',t:false},{p:'998',t:true},{p:'999',t:false}],_trunkCodes:['0'],_areaCodeSwipe:{'55':2,'44':3,'1':3},_internationalPrefixes:function spm_internatialPrefixes(number){var variants=[number];var internationalPrefix='';if(this._mccWith00Prefix.indexOf(this.mcc)!==-1){internationalPrefix='00';} if(this._mccWith011Prefix.indexOf(this.mcc)!==-1){internationalPrefix='011';} var plusRegexp=new RegExp('^\\+');if(number.match(plusRegexp)){variants.push(number.replace(plusRegexp,internationalPrefix));} var ipRegexp=new RegExp('^'+internationalPrefix);if(number.match(ipRegexp)){variants.push(number.replace(ipRegexp,'+'));} return variants;},_trunkPrefixes:function spm_trunkPrefixes(number){var variants=[];var prefixesWithTrunk0=[];var prefixesWithNoTrunk=[];this._countryPrefixes.forEach(function(prefix){if(prefix.t){prefixesWithTrunk0.push(prefix.p);}else{prefixesWithNoTrunk.push(prefix.p);}});var trunk0Join=prefixesWithTrunk0.join('|');var trunk0Regexp=new RegExp('^\\+('+trunk0Join+')');this._internationalPrefixes(number).some(variant=>{var match=variant.match(trunk0Regexp);if(match){variants.push(variant.replace(trunk0Regexp,'0'));variants.push(variant.replace(trunk0Regexp,''));} return match;});var noTrunkJoin=prefixesWithNoTrunk.join('|');var noTrunkRegexp=new RegExp('^\\+('+noTrunkJoin+')');this._internationalPrefixes(number).some(variant=>{var match=variant.match(noTrunkRegexp);if(match){variants.push(variant.replace(noTrunkRegexp,''));} return match;});var withTrunkRegexp=new RegExp('^('+this._trunkCodes.join('|')+')');if(number.match(withTrunkRegexp)){variants.push(number.replace(withTrunkRegexp,''));} return variants;},_areaPrefixes:function spm_areaPrefixes(number){var variants=[];Object.keys(this._areaCodeSwipe).forEach(function(country){var re=new RegExp('^\\+'+country);this._internationalPrefixes(number).some(variant=>{var match=variant.match(re);if(match){var afterArea=1+country.length+this._areaCodeSwipe[country];variants.push(variant.substring(afterArea));} return match;});},this);return variants;},_carrierPrefixes:function spm_carrierPrefix(number){if(this.mcc!='724'){return[];} var variants=[];var withTrunk=new RegExp('^0');if(number.length>=13&&number.match(withTrunk)){var afterCarrier=3;variants.push(number.substring(afterCarrier));} return variants;}};;'use strict';var Contacts={_FB_FILES:['/shared/js/fb/fb_request.js','/shared/js/fb/fb_data_reader.js','/shared/js/fb/fb_reader_utils.js'],getRevision:function getRevision(callback){var mozContacts=navigator.mozContacts;if(!mozContacts){callback(null);return;} var req=mozContacts.getRevision();req.onsuccess=function onsuccess(event){callback(event.target.result);};req.onerror=function onerror(event){console.log('Error '+event.target.error);callback(null);};},findByNumber:function findByNumber(number,callback){LazyLoader.load(this._FB_FILES,this._findByNumber.bind(this,number,callback));},_findByNumber:function _findByNumber(number,callback){if(!number){callback(null);return;} var options;var variants;if(number.length<7){variants=[number];options={filterBy:['tel'],filterOp:'equals',filterValue:number};}else{variants=SimplePhoneMatcher.generateVariants(number);var sanitizedNumber=SimplePhoneMatcher.sanitizedNumber(number);options={filterBy:['tel'],filterOp:'match',filterValue:sanitizedNumber};} var mozContacts=navigator.mozContacts;if(!mozContacts){callback(null);return;} var request=mozContacts.find(options);request.onsuccess=function findCallback(){var contacts=request.result;if(contacts.length===0){fb.getContactByNumber(number,function fb_ready(finalContact){var objMatching=null;if(finalContact){objMatching={value:number,type:'personal',carrier:null};} callback(finalContact,objMatching);},function fb_err(err){callback(null);});return;} var matches=contacts.map(function getTels(contact){return contact.tel.map(function getNumber(tel){return tel.value;});});var matchResult=SimplePhoneMatcher.bestMatch(variants,matches);var contact=contacts[matchResult.bestMatchIndex];var contactsWithSameNumber;if(contacts.length>1){contactsWithSameNumber=contacts.length-1;} var matchingTel=contact.tel[matchResult.localIndex];if(fb.isFbLinked(contact)){var req=fb.getData(contact);req.onsuccess=function(){callback(req.result,matchingTel,contactsWithSameNumber);};req.onerror=function(){window.console.error('Error while getting FB Data');callback(contact,matchingTel,contactsWithSameNumber);};} else{callback(contact,matchingTel,contactsWithSameNumber);}};request.onerror=function findError(){callback(null);};},_mergeOneFbContact:function _mergeOneFbContact(contacts,index){return new Promise(function(resolve,reject){var fbReq=fb.getData(contacts[index]);fbReq.onsuccess=function(){var originalTel=contacts[index].tel;contacts[index]=fbReq.result;contacts[index].tel=originalTel;resolve();};fbReq.onerror=function(){console.error('Could not merge Facebook data for',contacts[index].id);reject();};});},_mergeFbContacts:function _mergeFbContacts(contacts,callback){if(!callback||!(callback instanceof Function)){return;} if(!contacts){callback(null);} LazyLoader.load(this._FB_FILES,function(){var pending=contacts.length;var onContactMerged=function(){if(--pending===0){callback(contacts);}};for(var i=0,length=contacts.length;iduration-kReleaseDuration){factor*=(duration-t)/kReleaseDuration;} envelope.getChannelData(0)[i]=factor*kMasterVolume;} var gainNode=context.createGain();gainNode.connect(context.destination);if(!duration){this._gainNode=gainNode;} var envelopeNode=context.createBufferSource();envelopeNode.buffer=envelope;envelopeNode.start(when);envelopeNode.connect(gainNode.gain);gainNode.gain.setValueAtTime(duration?0.0:kToneVolume*kMasterVolume,0.0);for(i=0;i=this.kMaxDigits)){return;} if(key!='delete'){if(this._keypadSoundIsEnabled){TonePlayer.start(gTonesFrequencies[key],!this._onCall||this._shortTone);} if(this._vibrationEnabled){navigator.vibrate(this.kVibrationDuration);} this._playDtmfTone(key);} if(((key=='0'||key=='*')&&!this._onCall)||key=='delete'){this._holdTimer=setTimeout(function(self){self.restoreCaretPosition();if(key=='delete'){self._clearPhoneNumber();}else if(key==='0'){self._replaceLastKey('+');}else if(key==='*'){var isAtTheEnd=self._insertPosition===null;var isFirst=self._insertPosition===1||(isAtTheEnd&&self._phoneNumber.length===1);if(!isFirst){self._replaceLastKey(',');}else{self._deleteAtInsertPosition();}} self._longPress=true;self._updatePhoneNumberView('begin',false);},400,this);} if(key==='1'&&this._phoneNumber===''){this._holdTimer=setTimeout(function vm_call(self){self._longPress=true;self._callVoicemail();self._phoneNumber='';self._updatePhoneNumberView('begin',false);},400,this);} if(key=='delete'){this._deleteAtInsertPosition();}else if(this.phoneNumberViewContainer.classList.contains('keypad-visible')){if(!this._isKeypadClicked){this._isKeypadClicked=true;this._phoneNumber=key;this.replaceAdditionalContactInfo('');}else{this._insertAtCaret(key);}}else{this._insertAtCaret(key);} if(key==='#'&&!this._onCall){if(this._phoneNumber==='*#06#'){this.multiSimActionButton.performAction();return;}else if(this._isSpeedDialNumber(this._phoneNumber)){this._handleSpeedDial(this._phoneNumber.slice(0,-1));return;}} setTimeout(function(self){self._updatePhoneNumberView('begin',false);},0,this);},_touchMove:function kh_touchMove(touch){var target=document.elementFromPoint(touch.pageX,touch.pageY);var key=(target&&target.dataset)?target.dataset.value:null;if(key!==this._lastPressedKey||key==='delete'){this._stopDtmfTone();}},_touchEnd:function kh_touchEnd(key){this._lastPressedKey=null;if(key!=='delete'){this._stopDtmfTone();} if(this._keypadSoundIsEnabled){TonePlayer.stop();} this.restoreCaretPosition();if(this._longPress){this._longPress=false;this._holdTimer=null;return;} if(this._holdTimer){clearTimeout(this._holdTimer);}},keyHandler:function kh_keyHandler(event){event.preventDefault();if(event.type=='contextmenu'){return;} var key=event.target.dataset.value;if(!key){return;} event.stopPropagation();switch(event.type){case'touchstart':if(this._lastPressedKey){return;} event.target.classList.add('active');this._touchStart(key);break;case'touchmove':this._touchMove(event.touches[0]);break;case'touchend':case'touchcancel':if(key!==this._lastPressedKey){return;} event.target.classList.remove('active');this._touchEnd(key);break;}},_isSpeedDialNumber:function(number){return!!number.match(/^[0-9][0-9]{0,2}\#$/);},_getSpeedDialNumber:function(index){var self=this;var cardIndex;index--;return new Promise(function(resolve,reject){LazyLoader.load(['/shared/js/sim_settings_helper.js'],function(){SimSettingsHelper.getCardIndexFrom('outgoingCall',function(defaultCardIndex){if(defaultCardIndex==SimSettingsHelper.ALWAYS_ASK_OPTION_VALUE){LazyLoader.load(['/shared/js/component_utils.js','/shared/elements/gaia_sim_picker/script.js'],function(){var simPicker=document.getElementById('sim-picker');simPicker.getOrPick(defaultCardIndex,null,function(pickedCardIndex){cardIndex=pickedCardIndex;resolve();});});}else{cardIndex=defaultCardIndex;resolve();}});});}).then(function(){return self._getSimContactsList(cardIndex).then(function(simContactsList){if((index>=0)&&(indexb.id)?1:0;}else{return(a.id.length>b.id.length)?1:0;}});return numbers;},_getSimContactsList:function(cardIndex){var self=this;var canceled=false;return new Promise(function(resolve,reject){LazyLoader.load(['/shared/style/confirm.css','/shared/js/confirm.js',document.getElementById('confirmation-message')],function(){var iccId=navigator.mozIccManager.iccIds[cardIndex];var icc=navigator.mozIccManager.getIccById(iccId);if(!icc){reject('noSimCardToLoadContactsFrom');return;} var req=icc.readContacts('adn');req.onsuccess=function(event){var adnContacts=event.target.result;var contacts=self._createSimContactList(adnContacts);if(!canceled){ConfirmDialog.hide();} resolve(contacts);};req.onerror=function(error){console.error('Could not retrieve the ADN contacts from SIM card '+ cardIndex+', got error '+error.name);reject('noContactsWereFound');};ConfirmDialog.show('loadingSimContacts',null,{title:'cancel',callback:function(){canceled=true;ConfirmDialog.hide();reject();}});});});},sanitizePhoneNumber:function(number){return number.replace(/\s+/g,'');},updatePhoneNumber:function kh_updatePhoneNumber(number,ellipsisSide,forceMaxFontSize){number=this.sanitizePhoneNumber(number);this._phoneNumber=number;this._updatePhoneNumberView(ellipsisSide,forceMaxFontSize);},press:function(value){this._playDtmfTone(value);TonePlayer.start(gTonesFrequencies[value],true);setTimeout((function nextTick(){TonePlayer.stop();this._stopDtmfTone();}).bind(this));},_updatePhoneNumberView:function kh_updatePhoneNumberview(ellipsisSide,forceMaxFontSize){var phoneNumber=this._phoneNumber;if(this._onCall){this.renderPhoneNumber(phoneNumber,ellipsisSide);}else{var visibility;if(phoneNumber.length>0){visibility='visible';this.callBarAddContact.removeAttribute('disabled');}else{visibility='hidden';this.callBarAddContact.setAttribute('disabled','disabled');} this.deleteButton.style.visibility=visibility;this.phoneNumberView.blur();this.phoneNumberView.value=phoneNumber;FontSizeManager.adaptToSpace(FontSizeManager.DIAL_PAD,this.phoneNumberView,forceMaxFontSize,ellipsisSide);} if(this.onValueChanged){this.onValueChanged(this._phoneNumber);}},renderPhoneNumber:function kh_replacePhoneNumber(phoneNumber,ellipsisSide){if(this._onCall&&CallsHandler.activeCall){CallsHandler.activeCall.renderPhoneNumber({raw:phoneNumber},ellipsisSide);}},restorePhoneNumber:function kh_restorePhoneNumber(){if(this._onCall&&CallsHandler.activeCall){CallsHandler.activeCall.restorePhoneNumber();}},replaceAdditionalContactInfo:function kh_replaceAdditionalContactInfo(additionalContactInfo){var call=CallsHandler.activeCall;if(this._onCall&&call){call.replaceAdditionalContactInfo(additionalContactInfo);}},restoreAdditionalContactInfo:function kh_restoreAdditionalContactInfo(){if(this._onCall&&CallsHandler.activeCall){CallsHandler.activeCall.restoreAdditionalContactInfo();}},_callVoicemail:function(){if(navigator.mozIccManager.iccIds.length<=1){this._callVoicemailForSim(0);return;} var self=this;var key='ril.voicemail.defaultServiceId';var req=navigator.mozSettings.createLock().get(key);req.onsuccess=function(){LazyLoader.load(['/shared/js/component_utils.js','/shared/elements/gaia_sim_picker/script.js'],function(){var simPicker=document.getElementById('sim-picker');navigator.mozL10n.formatValue('voiceMail').then(string=>{simPicker.getOrPick(req.result[key],string,self._callVoicemailForSim.bind(self));});});};},_callVoicemailForSim:function(cardIndex){var settings=navigator.mozSettings;if(!settings){return;} var transaction=settings.createLock();var request=transaction.get('ril.iccInfo.mbdn');request.onsuccess=(function(){var numbers=request.result['ril.iccInfo.mbdn'];var number;if(typeof numbers=='string'){number=numbers;}else{number=numbers&&numbers[cardIndex];} var voicemail=navigator.mozVoicemail;if(!number&&voicemail){number=voicemail.getNumber(cardIndex);} if(number){CallHandler.call(number,cardIndex);}else{this._showNoVoicemailDialog();}}).bind(this);request.onerror=function(){};},_showNoVoicemailDialog:function hk_showNoVoicemailDialog(){var voicemailDialog={title:'voicemailNoNumberTitle',text:'voicemailNoNumberText',confirm:{title:'voicemailNoNumberSettings',recommend:true,callback:this.showVoicemailSettings},cancel:{title:'voicemailNoNumberCancel',callback:this._hideNoVoicemailDialog}};LazyLoader.load(['/shared/js/custom_dialog.js'],function(){CustomDialog.show(voicemailDialog.title,voicemailDialog.text,voicemailDialog.cancel,voicemailDialog.confirm);});},_hideNoVoicemailDialog:function kh_hideNoVoicemailDialog(){CustomDialog.hide();},showVoicemailSettings:function kh_showVoicemailSettings(){var activity=new window.MozActivity({name:'configure',data:{target:'device',section:'call'}});activity.onerror=function(){console.warn('Configure activity error:',activity.error.name);};},_observePreferences:function kh_observePreferences(){var self=this;LazyLoader.load('/shared/js/settings_listener.js',function(){SettingsListener.observe('phone.ring.keypad',false,function(value){self._keypadSoundIsEnabled=!!value;});SettingsListener.observe('phone.dtmf.type','long',function(value){self._shortTone=(value==='short');});SettingsListener.observe('keyboard.vibration',false,function(value){self._vibrationEnabled=!!value;});});},_updateInsertPosition:function kh_updateInsertPosition(){this._insertPosition=this._realStartPosition();},_replaceLastKey:function kh_replaceLastKey(newKey){this._deleteAtInsertPosition();this.restoreCaretPosition();this._insertAtCaret(newKey);},_insertAtCaret:function kh_insertAtCaret(key){if(this._insertPosition===null){this._phoneNumber+=key;}else{var start=this._realStartPosition();var end=this._realEndPosition();this._phoneNumber=this._phoneNumber.substring(0,start)+key+ this._phoneNumber.substring(end);this._insertPosition=start+1;}},_deleteAtInsertPosition:function kh_deleteAtInsertPosition(){if(this._insertPosition===null){this._phoneNumber=this._phoneNumber.slice(0,-1);}else{var start=this._realStartPosition();var end=this._realEndPosition();if(start>0&&start===end){start=end-1;} this._phoneNumber=this._phoneNumber.substring(0,start)+ this._phoneNumber.substring(end);this._insertPosition=this._phoneNumber?start:null;}},_clearPhoneNumber:function kh_clearPhoneNumber(){if(this._insertPosition===null){this._phoneNumber='';}else{var start=this._realStartPosition();this._phoneNumber=this._phoneNumber.substring(start);this._insertPosition=this._phoneNumber?0:null;}},restoreCaretPosition:function kh_restoreCaretPosition(){if(this._insertPosition!==null){var caretPosition=this._caretPosition(this._insertPosition);this.phoneNumberView.selectionStart=caretPosition;this.phoneNumberView.selectionEnd=caretPosition;this.phoneNumberView.focus();}else{this.phoneNumberView.blur();}},_realStartPosition:function kh_realStartPosition(){var start=this.phoneNumberView.selectionStart;return this._realPosition(this.phoneNumberView,start);},_realEndPosition:function kh_realEndPosition(){var end=this.phoneNumberView.selectionEnd;return this._realPosition(this.phoneNumberView,end);},_caretPosition:function kh_caretPosition(realPosition){return realPosition-this._ellipsisOffset(this.phoneNumberView);},_realPosition:function kh_realPosition(input,position){return position+this._ellipsisOffset(this.phoneNumberView);},_ellipsisOffset:function kh_ellipsisOffset(input){var ellipsedCharacters=+input.dataset.ellipsedCharacters;return ellipsedCharacters?(ellipsedCharacters-1):0;}};;'use strict';var Utils={prettyDate:function ut_prettyDate(time){var f=Intl.DateTimeFormat(navigator.languages,{hour12:navigator.mozHour12,hour:'numeric',minute:'numeric'});return f.format(new Date(time));},prettyDuration:function(node,duration,l10nPrefix){var elapsed=new Date(duration);var h=elapsed.getUTCHours();var m=elapsed.getUTCMinutes();var s=elapsed.getUTCSeconds();var l10nId=l10nPrefix||'callDuration';var durationL10n={h:h+'',m:m+'',s:s+''};if(l10nId==='callDuration'){durationL10n={h:(h>9?'':'0')+h,m:(m>9?'':'0')+m,s:(s>9?'':'0')+s};} if(l10nPrefix==='callDurationTextFormat'&&h===0&&m===0){l10nId+='Seconds';}else{l10nId+=h>0?'Hours':'Minutes';} navigator.mozL10n.setAttributes(node,l10nId,durationL10n);},setHeaderDate:function ut_setHeaderDate(elem,time){var diff=(Date.now()-time)/1000;var day_diff=Math.floor(diff/86400);var formattedTime;if(isNaN(day_diff)){elem.setAttribute('data-l10n-id','incorrectDate');return;}else if(day_diff===0){elem.setAttribute('data-l10n-id','today');return;}else if(day_diff===1){elem.setAttribute('data-l10n-id','yesterday');return;}else if(day_diff<6){formattedTime=(new Date(time)).toLocaleString(navigator.languages,{weekday:'long',});}else{formattedTime=(new Date(time)).toLocaleString(navigator.languages,{year:'2-digit',month:'2-digit',day:'2-digit'});} elem.removeAttribute('data-l10n-id');elem.textContent=formattedTime;},getPhoneNumberPrimaryInfo:function ut_getPhoneNumberPrimaryInfo(matchingTel,contact){if(contact){if(contact.name&&contact.name.length&&contact.name[0]!==''){return contact.name;}else if(contact.org&&contact.org.length&&contact.org[0]!==''){return contact.org;}} if(matchingTel){return matchingTel.value;} return null;},toCamelCase:function ut_toCamelCase(str){return str.replace(/\-(.)/g,function replacer(str,p1){return p1.toUpperCase();});},_phoneTypesL10n:{'mobile':'phone_type_mobile','home':'phone_type_home','work':'phone_type_work','personal':'phone_type_personal','faxHome':'phone_type_fax_home','faxOffice':'phone_type_fax_office','faxOther':'phone_type_fax_other','other':'phone_type_other'},getPhoneNumberAdditionalInfo:function ut_getPhoneNumberAdditionalInfo(matchingTel){var type=matchingTel.type||'mobile';var carrier=matchingTel.carrier;if(Array.isArray(type)){type=type[0];} var id;var args={};if(this._phoneTypesL10n.hasOwnProperty(type)){id=this._phoneTypesL10n[type];}else{id='phone_type_custom';args.type=type;} if(carrier){id+='_and_carrier';args.carrier=carrier;} return{id:id,args:Object.keys(args).length?args:null};},isPhoneType:function ut_isPhoneType(type){return this._phoneTypesL10n.hasOwnProperty(type);}};;'use strict';var FontSizeManager=(function fontSizeManager(){var DIAL_PAD=0,SINGLE_CALL=1,CALL_WAITING=2,STATUS_BAR=3,SECOND_INCOMING_CALL=4;var _sizes={};_sizes[DIAL_PAD]={min:2.6,max:4.1};_sizes[SINGLE_CALL]={min:2.3,max:3.4,line:3.4};_sizes[CALL_WAITING]={min:2.3,max:2.5,line:1.3};_sizes[STATUS_BAR]={min:1.7,max:1.7};_sizes[SECOND_INCOMING_CALL]={min:2.3,max:2.5,line:3.7};var _defaultFontSize;function _getRootFontSize(){_defaultFontSize=_defaultFontSize||parseInt(window.getComputedStyle(document.body,null).getPropertyValue('font-size'));return _defaultFontSize;} function _getMinFontSize(scenario){return Math.round(_sizes[scenario].min*_getRootFontSize());} function _getMaxFontSize(scenario){return Math.round(_sizes[scenario].max*_getRootFontSize());} function _getAllowedFontSizes(scenario){var minFontSize=_getMinFontSize(scenario);var maxFontSize=_getMaxFontSize(scenario);var allowedSizes=[];for(var size=minFontSize;size<=maxFontSize;size+=4){allowedSizes.push(size);} if(allowedSizes.indexOf(maxFontSize)===-1){allowedSizes.push(maxFontSize);} return allowedSizes;} function adaptToSpace(scenario,view,forceMaxFontSize,ellipsisSide){var computedStyle=window.getComputedStyle(view);if((!view.value&&!view.textContent)||!computedStyle){return;} var viewWidth=view.getBoundingClientRect().width;var viewFont=computedStyle.fontFamily;var allowedSizes;if(forceMaxFontSize){allowedSizes=[_getMaxFontSize(scenario)];}else{allowedSizes=_getAllowedFontSizes(scenario);} var infos=FontSizeUtils.getMaxFontSizeInfo(view.value||view.textContent,allowedSizes,viewFont,viewWidth);var newFontSize=infos.fontSize;if(view.style.fontSize!==newFontSize){view.style.fontSize=newFontSize+'px';} if(infos&&infos.overflow){var overflowCount=FontSizeUtils.getOverflowCount(view.value||view.textContent,newFontSize,viewFont,viewWidth);overflowCount+=2;_useEllipsis(view,overflowCount,ellipsisSide);view.dataset.ellipsedCharacters=overflowCount;}else{view.dataset.ellipsedCharacters=0;}} function _useEllipsis(view,overflowCount,ellipsisSide){var side=ellipsisSide||'begin';var localizedSide=(side==='begin'?'left':'right');var value=view.value||view.textContent;if(localizedSide=='left'){value='\u2026'+value.substr(-value.length+overflowCount);}else if(localizedSide=='right'){value=value.substr(0,value.length-overflowCount)+'\u2026';} if(view.value){view.value=value;}else{var el=view.querySelector('bdi')||view;el.textContent=value;}} function ensureFixedBaseline(scenario,view){var initialLineHeight=_sizes[scenario].line;if(!initialLineHeight){return;} var maxFontSize=_getMaxFontSize(scenario);var fontSize=parseInt(window.getComputedStyle(view).fontSize,10);view.style.lineHeight=initialLineHeight*_getRootFontSize()+ (maxFontSize-fontSize)/2+'px';} function resetFixedBaseline(view){view.style.removeProperty('line-height');} return{DIAL_PAD:DIAL_PAD,SINGLE_CALL:SINGLE_CALL,CALL_WAITING:CALL_WAITING,STATUS_BAR:STATUS_BAR,SECOND_INCOMING_CALL:SECOND_INCOMING_CALL,adaptToSpace:adaptToSpace,ensureFixedBaseline:ensureFixedBaseline,resetFixedBaseline:resetFixedBaseline};})();;'use strict';(function(exports){var Voicemail={check:function vm_check(number,cardIndex){return new Promise(function(resolve,reject){if(!number){resolve(false);return;} var serviceId=cardIndex;var voicemail=navigator.mozVoicemail;if(voicemail){var voicemailNumber=voicemail.getNumber(serviceId);if(voicemailNumber===number){resolve(true);return;}} var settings=navigator.mozSettings;var req=settings.createLock().get('ril.iccInfo.mbdn');req.onsuccess=function getVoicemailNumber(){var isVoicemailNumber=false;var voicemailNumbers=req.result['ril.iccInfo.mbdn'];var voicemailNumber;if(typeof voicemailNumbers==='string'){voicemailNumber=voicemailNumbers;}else{voicemailNumber=voicemailNumbers&&voicemailNumbers[serviceId];} if(voicemailNumber===number){isVoicemailNumber=true;} resolve(isVoicemailNumber);};req.onerror=function getVoicemailNumberError(){resolve(false);};});}};exports.Voicemail=Voicemail;}(window));;'use strict';var BluetoothHelper=function(){var profiles={'HFP':0x111E,'A2DP':0x110D};var _bluetooth=window.navigator.mozBluetooth;var _isReady=false;var _callbacks=[];var _adapter=null;var _oldAdapter=null;var _v2=true;var _ready=function(callback){if(!callback||!_bluetooth){return;} if(_isReady){callback();}else{_callbacks.push(callback);}};var _handleRequest=function(request,callback,errorcb){request.onsuccess=function(){if(callback){callback(request.result);}};request.onerror=function(){console.log('Error handling bluetooth request');if(errorcb){errorcb();}};};var _processCallbacks=function(){if(_adapter){_isReady=true;_callbacks.forEach(function(callback){callback();});_callbacks=[];}else{console.log('BluetoothHelper(): connot get default adapter yet');}};var _fetchAdapterV2=function(){_bluetooth.onattributechanged=function onManagerAttributeChanged(evt){for(var i in evt.attrs){switch(evt.attrs[i]){case'defaultAdapter':console.log('defaultAdapter changed. address:',_bluetooth.defaultAdapter.address);_adapter=_bluetooth.defaultAdapter;_processCallbacks();break;default:break;}}};_adapter=_bluetooth.defaultAdapter;if(_adapter){_processCallbacks();}};var _fetchAdapter=function(){var req=_bluetooth.getDefaultAdapter();if(req){req.onsuccess=function(){if(_adapter){_oldAdapter=_adapter;} _isReady=true;_adapter=req.result;if(_oldAdapter&&_oldAdapter.onpairedstatuschanged){_adapter.onpairedstatuschanged=_oldAdapter.onpairedstatuschanged;} _callbacks.forEach(function(callback){callback();});_callbacks=[];};req.onerror=function(){console.log('BluetoothHelper(): connot get default adapter!!!');};}};var _getAdapter=function(){if(_v2){_fetchAdapterV2();}else{_fetchAdapter();}};var _resetAdapter=function(){if(_adapter){_oldAdapter=_adapter;} _isReady=false;_adapter=null;};if(_bluetooth){if(typeof(_bluetooth.onattributechanged)==='undefined'){_v2=false;} if(_v2){_bluetooth.onadapteradded=function onAdapterAdded(evt){_getAdapter();};}else{_bluetooth.addEventListener('enabled',_getAdapter);_bluetooth.addEventListener('adapteradded',_getAdapter);_bluetooth.addEventListener('disabled',_resetAdapter);} _getAdapter();} return{profiles:profiles,answerWaitingCall:function(){_ready(function(){_adapter.answerWaitingCall();});},ignoreWaitingCall:function(){_ready(function(){_adapter.ignoreWaitingCall();});},toggleCalls:function(){_ready(function(){_adapter.toggleCalls();});},getConnectedDevicesByProfile:function(profileID,cb){_ready(function(){_handleRequest(_adapter.getConnectedDevices(profileID),cb);});},connectSco:function(cb){_ready(function(){_handleRequest(_adapter.connectSco(),cb);});},disconnectSco:function(cb){_ready(function(){_handleRequest(_adapter.disconnectSco(),cb);});},getPairedDevices:function(cb){_ready(function(){_handleRequest(_adapter.getPairedDevices(),cb);});},getAddress:function(cb){if(_v2){console.log('getAddress function is deprecated');return;} _ready(function(){var address=_adapter.address;cb(address);});},setPairingConfirmation:function(address,confirmed){if(_v2){console.log('setPairingConfirmation API is deprecated');return;} _ready(function(){_adapter.setPairingConfirmation(address,confirmed);});},setPinCode:function(address,pincode){if(_v2){console.log('setPairingConfirmation API is deprecated');return;} _ready(function(){_adapter.setPinCode(address,pincode);});},setPasskey:function(address,key){if(_v2){console.log('setPairingConfirmation API is deprecated');return;} _ready(function(){_adapter.setPasskey(address,key);});},isScoConnected:function(cb,errorcb){_ready(function(){_handleRequest(_adapter.isScoConnected(),cb,errorcb);});},sendMediaMetaData:function(metadata,cb,errorcb){_ready(function(){_handleRequest(_adapter.sendMediaMetaData(metadata),cb,errorcb);});},sendMediaPlayStatus:function(metadata,cb,errorcb){_ready(function(){_handleRequest(_adapter.sendMediaPlayStatus(metadata),cb,errorcb);});},set onhfpstatuschanged(callback){_ready(function(){_adapter.onhfpstatuschanged=callback;});},set onscostatuschanged(callback){_ready(function(){_adapter.onscostatuschanged=callback;});},set ona2dpstatuschanged(callback){_ready(function(){_adapter.ona2dpstatuschanged=callback;});},set onrequestmediaplaystatus(callback){_ready(function(){_adapter.onrequestmediaplaystatus=callback;});},set onpairedstatuschanged(callback){if(_v2){console.log('onpairedstatuschanged API is deprecated');return;} _ready(function(){_adapter.onpairedstatuschanged=callback;});},v2:_v2,enable:function(){if(_v2){_ready(function(){_adapter.enable();});}else{console.log('enable is not support in v1 API!');}},disable:function(){if(_v2){_ready(function(){_adapter.disable();});}else{console.log('disable is not support in v1 API!');}}};};;'use strict';var CallScreen={_ticker:null,_screenWakeLock:null,_typedNumber:'',callEndPromptTime:2000,body:document.body,screen:document.getElementById('call-screen'),lockscreenConnStates:document.getElementById('lockscreen-conn-states'),views:document.getElementById('views'),calls:document.getElementById('calls'),mainContainer:document.getElementById('main-container'),contactBackground:document.getElementById('contact-background'),callOptions:document.getElementById('call-options'),callToolbar:document.getElementById('co-advanced'),muteButton:document.getElementById('mute'),speakerButton:document.getElementById('speaker'),bluetoothButton:document.getElementById('bt'),keypadButton:document.getElementById('keypad-visibility'),placeNewCallButton:document.getElementById('place-new-call'),holdButton:document.getElementById('on-hold'),mergeButton:document.getElementById('merge'),holdAndMergeContainer:document.getElementById('hold-and-merge-container'),hideBarMuteButton:document.getElementById('keypad-hidebar-mute-action'),bluetoothMenu:document.getElementById('bluetooth-menu'),switchToDeviceButton:document.getElementById('btmenu-btdevice'),switchToReceiverButton:document.getElementById('btmenu-receiver'),switchToSpeakerButton:document.getElementById('btmenu-speaker'),bluetoothMenuCancel:document.getElementById('btmenu-cancel'),answerButton:document.getElementById('callbar-answer'),rejectButton:document.getElementById('callbar-hang-up'),incomingContainer:document.getElementById('incoming-container'),incomingInfo:document.getElementById('incoming-info'),incomingNumber:document.getElementById('incoming-number'),incomingSim:document.getElementById('incoming-sim'),incomingNumberAdditionalTel:document.getElementById('incoming-number-additional-info-tel'),incomingNumberAdditionalTelType:document.getElementById('incoming-number-additional-info-tel-type'),incomingAnswer:document.getElementById('incoming-answer'),incomingEnd:document.getElementById('incoming-end'),incomingIgnore:document.getElementById('incoming-ignore'),lockedClockTime:document.getElementById('lockscreen-clock-time'),lockedDate:document.getElementById('lockscreen-date'),statusMessage:document.getElementById('statusMsg'),showStatusMessage:function cs_showStatusMessage(message){var STATUS_TIME=2000;var paragraph=this.statusMessage.querySelector('p');var self=this;if(typeof(message)==='string'){navigator.mozL10n.setAttributes(paragraph,message);}else if(message.id){navigator.mozL10n.setAttributes(paragraph,message.id,message.args);} this.statusMessage.classList.add('visible');this.statusMessage.addEventListener('transitionend',function tend(evt){evt.stopPropagation();self.statusMessage.removeEventListener('transitionend',tend);setTimeout(function hide(){self.statusMessage.classList.remove('visible');},STATUS_TIME);});},updateCallsDisplay:function cs_updateCallsDisplay(){var visibleCalls=this.calls.querySelectorAll('section:not([hidden])').length;this.body.classList.toggle('single-line',visibleCalls<=1);this.calls.classList.toggle('big-duration',visibleCalls<=1);CallsHandler.updateAllPhoneNumberDisplays();},hidePlaceNewCallButton:function cs_hidePlaceNewCallButton(){this.callToolbar.classList.add('no-add-call');},showPlaceNewCallButton:function cs_showPlaceNewCallButton(){this.callToolbar.classList.remove('no-add-call');},set holdAndAnswerOnly(enabled){this.incomingContainer.classList.toggle('hold-and-answer-only',enabled);},set cdmaCallWaiting(enabled){this.calls.classList.toggle('switch',enabled);this.callToolbar.classList.toggle('no-add-call',enabled);},get inStatusBarMode(){return window.innerHeight<=40;},init:function cs_init(){this.muteButton.addEventListener('click',this.toggleMute.bind(this));this.hideBarMuteButton.addEventListener('click',this.toggleMute.bind(this));this.keypadButton.addEventListener('click',this.showKeypad.bind(this));this.placeNewCallButton.addEventListener('click',this.placeNewCall.bind(this));this.speakerButton.addEventListener('click',this.toggleSpeaker.bind(this));this.bluetoothButton.addEventListener('click',this.toggleBluetoothMenu.bind(this));this.holdButton.addEventListener('click',CallsHandler.holdOrResumeSingleCall.bind(this));this.mergeButton.addEventListener('click',CallsHandler.mergeCalls.bind(this));this.answerButton.addEventListener('click',CallsHandler.answer);this.rejectButton.addEventListener('click',CallsHandler.end);this.switchToDeviceButton.addEventListener('click',this.switchToDefaultOut.bind(this,false));this.switchToReceiverButton.addEventListener('click',this.switchToReceiver.bind(this));this.switchToSpeakerButton.addEventListener('click',this.switchToSpeaker.bind(this));this.bluetoothMenuCancel.addEventListener('click',this.toggleBluetoothMenu.bind(this));this.incomingAnswer.addEventListener('click',CallsHandler.holdAndAnswer);this.incomingEnd.addEventListener('click',CallsHandler.endAndAnswer);this.incomingIgnore.addEventListener('click',CallsHandler.ignore);this.calls.addEventListener('click',CallsHandler.toggleCalls.bind(this));window.addEventListener('resize',this.resizeHandler.bind(this));SettingsListener.observe('wallpaper.image',null,this._wallpaperImageHandler.bind(this));this._lockScreenLayoutInitialized=false;navigator.mozSettings.addObserver('lockscreen.locked',this._lockscreenStateChange.bind(this));this.syncSpeakerEnabled();},initLockScreenConnInfoManager:function cs_initLockScreenConnInfoManager(){if(window.navigator.mozMobileConnections){new window.LockScreenConnInfoManager(CallScreen.lockscreenConnStates);}},initLockScreenSlide:function cs_initLockScreenSlide(){this.hangUpIcon=document.getElementById('lockscreen-area-hangup');this.pickUpIcon=document.getElementById('lockscreen-area-pickup');this.initUnlockerEvents();new LockScreenSlide({useNewStyle:true,IDs:{overlay:'main-container',areas:{left:'lockscreen-area-hangup',right:'lockscreen-area-pickup'},},trackNew:{strokeColorTop:'rgba(0, 0, 0, 0)',strokeColorBottom:'rgba(0, 0, 0, 0)',fillColorTop:'rgba(0, 0, 0, 0.1)',fillColorBottom:'rgba(0, 0, 0, 0.1)'},colors:{left:{touchedColor:'224, 0, 0',touchedColorStop:'255, 255, 255'},right:{touchedColor:'0, 173, 173',touchedColorStop:'255, 255, 255'}},iconBG:{left:{color:'rgba(224, 0, 0, 0.80)'},right:{color:'rgba(0, 173, 173, 0.80)'}},resourcesNew:{larrow:'/style/images/lock_screen/lockscreen_toggle_arrow_left.png',rarrow:'/style/images/lock_screen/lockscreen_toggle_arrow_right.png'}});},_lockscreenStateChange:function cs_lockscreenStateChange(event){if(event.settingValue){if(this.screen.dataset.layout==='incoming'){this.initLockScreenLayout();this.render('incoming-locked');} this.initUnlockerEvents();}else{if(this.screen.dataset.layout==='incoming-locked'){this.render('incoming');} this.suspendUnlockerEvents();}},_wallpaperImageHandler:function cs_wallpaperImageHandler(image){this.mainContainer.style.backgroundImage='url('+ (typeof image==='string'?image:URL.createObjectURL(image))+')';},setCallerContactImage:function cs_setCallerContactImage(){var activeCallForContactImage=CallsHandler.activeCallForContactImage;var blob=activeCallForContactImage&&activeCallForContactImage.photo;var background=blob?'url('+URL.createObjectURL(blob)+')':'';this.contactBackground.style.backgroundImage=background;},insertCall:function cs_insertCall(node){this.calls.appendChild(node);this.updateCallsDisplay();},removeCall:function cs_removeCall(node){if(node.parentNode){node.parentNode.removeChild(node);this.updateCallsDisplay();}},resizeHandler:function cs_resizeHandler(){if(!this.body.classList.contains('showKeypad')){this.updateCallsDisplay(this.inStatusBarMode);}else if(this.inStatusBarMode){this._typedNumber=KeypadManager._phoneNumber;KeypadManager.restorePhoneNumber();}else{KeypadManager.updatePhoneNumber(this._typedNumber,'begin',true);}},_lockScreenLayoutInitialized:false,initLockScreenLayout:function cs_initLockScreenLayout(){this.showClock(new Date());if(!this._lockScreenLayoutInitialized){this.initLockScreenConnInfoManager();this.initLockScreenSlide();this._lockScreenLayoutInitialized=true;}},toggleMute:function cs_toggleMute(){this.muteButton.classList.toggle('active-state');this.hideBarMuteButton.classList.toggle('active-state');this.calls.classList.toggle('muted');CallsHandler.toggleMute();},unmute:function cs_unmute(){this.muteButton.classList.remove('active-state');this.hideBarMuteButton.classList.remove('active-state');this.calls.classList.remove('muted');CallsHandler.unmute();},toggleSpeaker:function cs_toggleSpeaker(){this.speakerButton.classList.toggle('active-state');CallsHandler.toggleSpeaker();},toggleBluetoothMenu:function cs_toggleBluetoothMenu(value){if(typeof value!='boolean'){this.bluetoothMenu.classList.toggle('display');}else{this.bluetoothMenu.classList.toggle('display',value);}},switchToSpeaker:function cs_switchToReceiver(){this.speakerButton.classList.add('active-state');this.bluetoothButton.classList.add('active-state');CallsHandler.switchToSpeaker();this.toggleBluetoothMenu(false);},switchToReceiver:function cs_switchToReceiver(){this.speakerButton.classList.remove('active-state');this.bluetoothButton.classList.remove('active-state');CallsHandler.switchToReceiver();this.toggleBluetoothMenu(false);},setShowIsHeld:function cs_setShowIsHeld(enabled){this.holdButton.classList.toggle('active-state',enabled);},switchToDefaultOut:function cs_switchToDefaultOut(doNotConnect){this.speakerButton.classList.remove('active-state');this.bluetoothButton.classList.add('active-state');CallsHandler.switchToDefaultOut(doNotConnect);this.toggleBluetoothMenu(false);},setBTReceiverIcon:function cs_setBTReceiverIcon(enabled){if(enabled){this.speakerButton.classList.add('hide');this.bluetoothButton.classList.remove('hide');}else{this.speakerButton.classList.remove('hide');this.bluetoothButton.classList.add('hide');}},showKeypad:function cs_showKeypad(){KeypadManager.render('oncall');this.body.classList.add('showKeypad');},hideKeypad:function cs_hideKeypad(){KeypadManager.restorePhoneNumber();KeypadManager.restoreAdditionalContactInfo();this.body.classList.remove('showKeypad');},placeNewCall:function cs_placeNewCall(){new MozActivity({name:'dial',data:{type:'webtelephony/number',number:''}});},render:function cs_render(layout_type){this.screen.dataset.layout=layout_type;},showClock:function cs_showClock(now){var formatter=mozIntl.DateTimeFormat(navigator.languages,{hour12:navigator.mozHour12,dayperiod:false,hour:'numeric',minute:'numeric'});var timeText=formatter.format(now);var dateText=now.toLocaleString(navigator.languages,{weekday:'long',month:'long',day:'numeric'});this.lockedClockTime.textContent=timeText;this.lockedDate.textContent=dateText;},showIncoming:function cs_showIncoming(){this.body.classList.remove('showKeypad');this.callOptions.classList.add('transparent');this.incomingContainer.classList.add('displayed');this._screenWakeLock=navigator.requestWakeLock('screen');},hideIncoming:function cs_hideIncoming(){this.callOptions.classList.remove('transparent');this.incomingContainer.classList.remove('displayed');if(this._screenWakeLock){this._screenWakeLock.unlock();this._screenWakeLock=null;} this.setCallerContactImage();},enableKeypadButton:function cs_enableKeypadButton(){this.keypadButton.removeAttribute('disabled');},disableKeypadButton:function cs_disableKeypadButton(){this.keypadButton.setAttribute('disabled','disabled');},syncSpeakerEnabled:function cs_syncSpeakerEnabled(){if(navigator.mozTelephony.speakerEnabled){this.speakerButton.classList.add('active-state');}else{this.speakerButton.classList.remove('active-state');}},enableMuteButton:function cs_enableMuteButton(){this.muteButton.removeAttribute('disabled');},disableMuteButton:function cs_disableMuteButton(){this.muteButton.setAttribute('disabled','disabled');},enablePlaceNewCallButton:function cs_enablePlaceNewCallButton(){this.placeNewCallButton.removeAttribute('disabled');},disablePlaceNewCallButton:function cs_disablePlaceNewCallButton(){this.placeNewCallButton.setAttribute('disabled','disabled');},enableSpeakerButton:function cs_enableSpeakerButton(){this.speakerButton.removeAttribute('disabled');},disableSpeakerButton:function cs_disableSpeakerButton(){this.speakerButton.setAttribute('disabled','disabled');},showOnHoldButton:function cs_showOnHoldButton(){this.holdButton.classList.remove('hide');},hideOnHoldButton:function cs_hideOnHoldButton(){this.holdButton.classList.add('hide');},enableOnHoldButton:function cs_enableOnHoldButton(){this.holdButton.removeAttribute('disabled');},disableOnHoldButton:function cs_disableOnHoldButton(){this.holdButton.setAttribute('disabled','disabled');},showMergeButton:function cs_showMergeButton(){this.mergeButton.classList.remove('hide');},hideMergeButton:function cs_hideMergeButton(){this.mergeButton.classList.add('hide');},showOnHoldAndMergeContainer:function cs_showOnHoldAndMergeContainer(){this.holdAndMergeContainer.style.display='block';},hideOnHoldAndMergeContainer:function cs_hideOnHoldAndMergeContainer(){this.holdAndMergeContainer.style.display='none';},createTicker:function(durationNode){var durationChildNode=durationNode.querySelector('span');if(durationNode.dataset.tickerId){return false;} durationChildNode.removeAttribute('data-l10n-id');durationChildNode.textContent='00:00';durationNode.classList.add('isTimer');var ticker=setInterval(function ut_updateTimer(startTime){var delta=Math.round((Date.now()-startTime)/1000)*1000;Utils.prettyDuration(durationChildNode,delta);},1000,Date.now());durationNode.dataset.tickerId=ticker;return true;},stopTicker:function(durationNode){durationNode.classList.remove('isTimer');clearInterval(durationNode.dataset.tickerId);delete durationNode.dataset.tickerId;},handleEvent:function cs_handleEvent(evt){var state=null,statePrev=null;switch(evt.type){case'lockscreenslide-unlocker-initializer':break;case'lockscreenslide-near-left':state=evt.detail.state;statePrev=evt.detail.statePrev;if(state==='accelerating'){CallScreen.hangUpIcon.classList.add('triggered');}else{CallScreen.hangUpIcon.classList.remove('triggered');} break;case'lockscreenslide-near-right':state=evt.detail.state;statePrev=evt.detail.statePrev;if(state==='accelerating'){CallScreen.pickUpIcon.classList.add('triggered');}else{CallScreen.pickUpIcon.classList.remove('triggered');} break;case'lockscreenslide-unlocking-start':break;case'lockscreenslide-unlocking-stop':break;case'lockscreenslide-activate-left':CallsHandler.end();break;case'lockscreenslide-activate-right':CallsHandler.answer();break;}},cdmaConferenceCall:function cs_cdmaConferenceCall(){this.hidePlaceNewCallButton();this.calls.classList.add('cdma-conference-call');},initUnlockerEvents:function cs_initUnlockerEvents(){window.addEventListener('lockscreenslide-unlocker-initializer',this);window.addEventListener('lockscreenslide-near-left',this);window.addEventListener('lockscreenslide-near-right',this);window.addEventListener('lockscreenslide-unlocking-start',this);window.addEventListener('lockscreenslide-activate-left',this);window.addEventListener('lockscreenslide-activate-right',this);window.addEventListener('lockscreenslide-unlocking-stop',this);},suspendUnlockerEvents:function cs_initUnlockerEvents(){window.removeEventListener('lockscreenslide-unlocker-initializer',this);window.removeEventListener('lockscreenslide-near-left',this);window.removeEventListener('lockscreenslide-near-right',this);window.removeEventListener('lockscreenslide-unlocking-start',this);window.removeEventListener('lockscreenslide-activate-left',this);window.removeEventListener('lockscreenslide-activate-right',this);window.removeEventListener('lockscreenslide-unlocking-stop',this);},getScenario:function cs_getScenario(){var scenario;if(this.inStatusBarMode){scenario=FontSizeManager.STATUS_BAR;}else if(this.body.classList.contains('single-line')){scenario=FontSizeManager.SINGLE_CALL;}else{scenario=FontSizeManager.CALL_WAITING;} return scenario;}};;'use strict';var CallsHandler=(function callsHandler(){var CALLS_LIMIT=2;var CDMA_CALLS_LIMIT=2;var handledCalls=[];var exitCallScreenTimeout=null;var toneInterval=null;var telephony=window.navigator.mozTelephony;telephony.oncallschanged=onCallsChanged;var conn=window.navigator.mozMobileConnections&&window.navigator.mozMobileConnections[0];if(conn&&conn.voice&&conn.voice.network&&conn.voice.network.mcc){SimplePhoneMatcher.mcc=conn.voice.network.mcc;} var btHelper=new BluetoothHelper();var screenLock;function setup(){if(telephony){telephony.muted=false;if(telephony.ownAudioChannel){telephony.ownAudioChannel();}} btHelper.getConnectedDevicesByProfile(btHelper.profiles.HFP,function(result){CallScreen.setBTReceiverIcon(!!(result&&result.length));});btHelper.onhfpstatuschanged=function(evt){CallScreen.setBTReceiverIcon(evt.status);};var acm=navigator.mozAudioChannelManager;if(acm){acm.addEventListener('headphoneschange',function onheadphoneschange(){if(acm.headphones){CallScreen.switchToDefaultOut();}});} btHelper.onscostatuschanged=function onscostatuschanged(evt){if(evt.status){CallScreen.switchToDefaultOut();}};navigator.mozSetMessageHandler('headset-button',handleHSCommand);navigator.mozSetMessageHandler('bluetooth-dialer-command',handleBTCommand);} var highPriorityWakeLock=null;function onCallsChanged(){if(!highPriorityWakeLock&&telephony.calls.length>0){highPriorityWakeLock=navigator.requestWakeLock('high-priority');} if(highPriorityWakeLock&&telephony.calls.length===0){highPriorityWakeLock.unlock();highPriorityWakeLock=null;} if(telephony.active){telephony.active.addEventListener('disconnected',handleDisconnectAndPlayBusyTone);} telephony.calls.forEach(function callIterator(call){var alreadyAdded=handledCalls.some(function hcIterator(hc){return(hc.call===call);});if(!alreadyAdded){addCall(call);}});function hcIterator(call){return(call===hc.call);} for(var index=(handledCalls.length-1);index>=0;index--){var hc=handledCalls[index];var stillHere=telephony.calls.some(hcIterator)||telephony.conferenceGroup.calls.some(hcIterator);if(!stillHere){removeCall(index);}} if(cdmaCallWaiting()){handleCallWaiting(telephony.calls[0]);}else{if(isCdma3WayCall()){CallScreen.hidePlaceNewCallButton();}else if(handledCalls.length!==0){CallScreen.showPlaceNewCallButton();}} updateMergeAndOnHoldStatus();updateMuteAndSpeakerStatus();CallScreen.setCallerContactImage();exitCallScreenIfNoCalls(CallScreen.callEndPromptTime);} function addCall(call){if(handledCalls.length&&(call.state!='incoming')&&(call.state!='dialing')){return;} if(telephony.calls.length>CALLS_LIMIT){HandledCall(call);call.hangUp();return;} if(handledCalls.length===0){CallScreen.unmute();CallScreen.enableKeypadButton();CallScreen.switchToDefaultOut(true);} var hc=new HandledCall(call);handledCalls.push(hc);CallScreen.insertCall(hc.node);if(call.state==='incoming'){turnScreenOn(call);} if(handledCalls.length>1){if(call.state==='incoming'){hc.hide();handleCallWaiting(call);}else{updatePlaceNewCall();hc.show();}}else{if(window.location.hash.startsWith('#locked')&&(call.state==='incoming')){CallScreen.initLockScreenLayout();CallScreen.render('incoming-locked');}else{CallScreen.render(call.state);}}} function removeCall(index){handledCalls.splice(index,1);if(handledCalls.length===0){CallScreen.disableKeypadButton();return;} CallScreen.hideIncoming();var remainingCall=handledCalls[0];if(remainingCall.call.state==='incoming'){remainingCall.show();setTimeout(function nextTick(){if(remainingCall.call.state==='incoming'){CallScreen.render('incoming');}});return;}} function turnScreenOn(call){screenLock=navigator.requestWakeLock('screen');call.addEventListener('statechange',function callStateChange(){call.removeEventListener('statechange',callStateChange);if(screenLock){screenLock.unlock();screenLock=null;}});} function handleDisconnectAndPlayBusyTone(evt){if(evt.call.disconnectedReason==='Busy'){var sequence=[[480,620,500],[0,0,500],[480,620,500],[0,0,500],[480,620,500],[0,0,500]];var sequenceDuration=sequence.reduce(function(prev,curr){return prev+curr[2];},0);TonePlayer.playSequence(sequence);exitCallScreenIfNoCalls(sequenceDuration);}} function handleCallWaiting(call){var number=call.secondId?call.secondId.number:call.id.number;if(!number){navigator.mozL10n.setAttributes(CallScreen.incomingNumber,'withheld-number');navigator.mozL10n.translateFragment(CallScreen.incomingNumber);FontSizeManager.adaptToSpace(FontSizeManager.SECOND_INCOMING_CALL,CallScreen.incomingNumber,false,'end');return;} if(navigator.mozIccManager.iccIds.length>1){navigator.mozL10n.setAttributes(CallScreen.incomingSim,'sim-number',{n:call.serviceId+1});}else{CallScreen.incomingSim.hidden=true;} Contacts.findByNumber(number,function lookupContact(contact,matchingTel){if(contact&&contact.name){CallScreen.incomingInfo.classList.add('additionalInfo');CallScreen.incomingNumber.textContent=contact.name;var additionalL10n=Utils.getPhoneNumberAdditionalInfo(matchingTel);navigator.mozL10n.setAttributes(CallScreen.incomingNumberAdditionalTelType,additionalL10n.id,additionalL10n.args);CallScreen.incomingNumberAdditionalTel.textContent=number;}else{CallScreen.incomingInfo.classList.remove('additionalInfo');CallScreen.incomingNumber.textContent=number;CallScreen.incomingNumberAdditionalTelType.removeAttribute('data-l10n-id');CallScreen.incomingNumberAdditionalTelType.textContent='';CallScreen.incomingNumberAdditionalTel.textContent='';} FontSizeManager.adaptToSpace(FontSizeManager.SECOND_INCOMING_CALL,CallScreen.incomingNumber,false,'end');if(contact&&contact.name){FontSizeManager.ensureFixedBaseline(FontSizeManager.SECOND_INCOMING_CALL,CallScreen.incomingNumber);}});if(cdmaCallWaiting()){CallScreen.holdAndAnswerOnly=true;} CallScreen.showIncoming();playWaitingTone(call);} function exitCallScreenIfNoCalls(timeout){if(handledCalls.length===0){document.body.classList.toggle('no-handled-calls',true);if(exitCallScreenTimeout!==null){clearTimeout(exitCallScreenTimeout);exitCallScreenTimeout=null;} exitCallScreenTimeout=setTimeout(function(evt){exitCallScreenTimeout=null;if(handledCalls.length===0){window.close();}else{document.body.classList.toggle('no-handled-calls',false);}},timeout);}} function updateAllPhoneNumberDisplays(){handledCalls.forEach(function(call){if(!call._leftGroup){call.restorePhoneNumber();}});} window.addEventListener('resize',updateAllPhoneNumberDisplays);function numOpenLines(){return telephony.calls.length+ (telephony.conferenceGroup.calls.length?1:0);} function handleBTCommand(message){var command=message.command;switch(command){case'CHUP':end();break;case'ATA':answer();break;case'CHLD=0':hangupWaitingCalls();break;case'CHLD=1':if((handledCalls.length===1)&&!cdmaCallWaiting()){end();}else{endAndAnswer();} break;case'CHLD=2':if((handledCalls.length===1)&&!cdmaCallWaiting()){holdOrResumeSingleCall();}else{holdAndAnswer();} break;case'CHLD=3':mergeCalls();break;default:var partialCommand=command.substring(0,3);if(partialCommand==='VTS'){KeypadManager.press(command.substring(4));} break;}} var lastHeadsetPress=0;function handleHSCommand(message){switch(message){case'headset-button-press':lastHeadsetPress=Date.now();return;case'headset-button-release':if((Date.now()-lastHeadsetPress)>1000){return;} break;default:return;} if(telephony.active){end();}else if((handledCalls.length>1)||cdmaCallWaiting()){holdAndAnswer();}else{answer();}} function answer(){if(!handledCalls.length){return;} handledCalls[0].call.answer();} function holdAndAnswer(){if((handledCalls.length<2)&&!cdmaCallWaiting()){return;} if(telephony.active){telephony.active.hold();if(cdmaCallWaiting()){btHelper.answerWaitingCall();}}else if(handledCalls.length>=2){var lastCall=handledCalls[handledCalls.length-1].call;lastCall.answer();}else{handledCalls[0].call.hold();} CallScreen.hideIncoming();if(cdmaCallWaiting()){handledCalls[0].updateCallNumber();CallScreen.cdmaCallWaiting=true;stopWaitingTone();}} function endAndAnswer(){if((handledCalls.length<2)&&!cdmaCallWaiting()){return;} if(telephony.active===telephony.conferenceGroup){endConferenceCall().then(function(){CallScreen.hideIncoming();},function(){});return;} if(cdmaCallWaiting()){handledCalls[0].call.hold();stopWaitingTone();btHelper.answerWaitingCall();}else{var callToEnd=telephony.active||handledCalls[handledCalls.length-2].call;var callToAnswer;handledCalls.some(function(handledCall){if(handledCall.call!==callToEnd){callToAnswer=handledCall.call;return true;}});if(callToEnd&&callToAnswer){callToEnd.addEventListener('disconnected',function ondisconnected(){callToEnd.removeEventListener('disconnected',ondisconnected);callToAnswer.answer();});callToEnd.hangUp();}else if(callToEnd){callToEnd.hangUp();}else if(callToAnswer){callToAnswer.answer();}} CallScreen.hideIncoming();if(cdmaCallWaiting()){handledCalls[0].updateCallNumber();CallScreen.cdmaCallWaiting=true;}} function toggleCalls(){if(CallScreen.incomingContainer.classList.contains('displayed')&&!cdmaCallWaiting()){return;} if(numOpenLines()<2&&!cdmaCallWaiting()){if(!telephony.active){holdOrResumeSingleCall();} return;} telephony.active.hold();btHelper.toggleCalls();} function holdOrResumeSingleCall(){if(numOpenLines()!==1||(telephony.calls.length&&(telephony.calls[0].state==='incoming'||!telephony.calls[0].switchable))){return;} if(telephony.active){telephony.active.hold();}else{var line=telephony.calls.length?telephony.calls[0]:telephony.conferenceGroup;line.resume();}} function hangupWaitingCalls(){handledCalls.forEach(function(handledCall){var callState=handledCall.call.state;if(callState==='held'||(callState==='incoming'&&handledCalls.length>1)){handledCall.call.hangUp();}});} function ignore(){if(cdmaCallWaiting()){stopWaitingTone();btHelper.ignoreWaitingCall();}else{var ignoreIndex=handledCalls.length-1;handledCalls[ignoreIndex].call.hangUp();} CallScreen.hideIncoming();} function endConferenceCall(){return telephony.conferenceGroup.hangUp().then(function(){ConferenceGroupHandler.signalConferenceEnded();},function(){console.error('Failed to hangup Conference Call');});} function end(){var callToEnd;if(telephony.active){callToEnd=telephony.active;}else if(numOpenLines()===1){if(telephony.conferenceGroup.calls.length){callToEnd=telephony.conferenceGroup;}else{callToEnd=telephony.calls[0];}}else{if(!handledCalls.length){return;} var lastCallIndex=handledCalls.length-1;callToEnd=handledCalls[lastCallIndex].call;} if(callToEnd.calls){endConferenceCall();}else{callToEnd.hangUp();}} function unmute(){telephony.muted=false;} function switchToSpeaker(){btHelper.disconnectSco();if(!telephony.speakerEnabled){telephony.speakerEnabled=true;}} function switchToDefaultOut(doNotConnect){if(telephony.speakerEnabled){telephony.speakerEnabled=false;} if(!doNotConnect&&telephony.active&&!document.hidden){btHelper.connectSco();}} function switchToReceiver(){btHelper.disconnectSco();if(telephony.speakerEnabled){telephony.speakerEnabled=false;}} function toggleMute(){telephony.muted=!telephony.muted;} function toggleSpeaker(){if(telephony.speakerEnabled){CallsHandler.switchToDefaultOut();}else{CallsHandler.switchToSpeaker();}} function playWaitingTone(call){var sequence=[[440,440,100],[0,0,100],[440,440,100]];toneInterval=window.setInterval(function playTone(){TonePlayer.playSequence(sequence);},10000);TonePlayer.playSequence(sequence);call.addEventListener('statechange',function callStateChange(){call.removeEventListener('statechange',callStateChange);window.clearInterval(toneInterval);});} function stopWaitingTone(){window.clearInterval(toneInterval);} function activeCall(){var telephonyActiveCall=telephony.active;var active=null;for(var i=0;i0));} function mergeCalls(){if(telephony.conferenceGroup.calls.length===0&&telephony.calls.length===2){telephony.conferenceGroup.add(telephony.calls[0],telephony.calls[1]).catch(function(){CallScreen.showStatusMessage('conferenceAddError');});}else if(telephony.conferenceGroup.calls.length>0&&telephony.calls.length===1){telephony.conferenceGroup.add(telephony.calls[0]).catch(function(){CallScreen.showStatusMessage('conferenceAddError');});}else{console.warn('Cannot join conference call.');}} function isEstablishingCall(){return telephony.calls.some(function(call){return call.state==='dialing'||call.state==='alerting';});} function isAnyCallOnHold(){return telephony.calls.some(call=>call.state==='held')||(telephony.conferenceGroup&&telephony.conferenceGroup.state==='held');} function isAnyCallSwitchable(){return telephony.calls.some(call=>call.switchable)||((telephony.conferenceGroup.calls.length>0)&&telephony.conferenceGroup.calls.every(call=>call.switchable));} function isEveryCallMergeable(){return telephony.calls.every(call=>call.mergeable);} function updatePlaceNewCall(){if(isEstablishingCall()||(numOpenLines()===0)){CallScreen.disablePlaceNewCallButton();}else{CallScreen.enablePlaceNewCallButton();}} function updateMergeAndOnHoldStatus(){var isEstablishing=isEstablishingCall();if(numOpenLines()===0){CallScreen.disableOnHoldButton();}else if(numOpenLines()>1&&!isEstablishing){CallScreen.hideOnHoldButton();if(isEveryCallMergeable()){CallScreen.showOnHoldAndMergeContainer();CallScreen.showMergeButton();}else{CallScreen.hideOnHoldAndMergeContainer();}}else{CallScreen.hideMergeButton();CallScreen.setShowIsHeld(!telephony.active&&isAnyCallOnHold());if(isEstablishing){CallScreen.disableOnHoldButton();}else{CallScreen.enableOnHoldButton();} if(isAnyCallSwitchable()){CallScreen.showOnHoldAndMergeContainer();CallScreen.showOnHoldButton();}else{CallScreen.hideOnHoldAndMergeContainer();}}} function updateMuteAndSpeakerStatus(){if(telephony.active){CallScreen.enableMuteButton();CallScreen.enableSpeakerButton();}else{CallScreen.disableMuteButton();CallScreen.disableSpeakerButton();}} return{setup:setup,answer:answer,holdAndAnswer:holdAndAnswer,endAndAnswer:endAndAnswer,toggleCalls:toggleCalls,ignore:ignore,end:end,toggleMute:toggleMute,toggleSpeaker:toggleSpeaker,unmute:unmute,switchToReceiver:switchToReceiver,switchToSpeaker:switchToSpeaker,switchToDefaultOut:switchToDefaultOut,holdOrResumeSingleCall:holdOrResumeSingleCall,checkCalls:onCallsChanged,mergeCalls:mergeCalls,updateAllPhoneNumberDisplays:updateAllPhoneNumberDisplays,updatePlaceNewCall:updatePlaceNewCall,exitCallScreenIfNoCalls:exitCallScreenIfNoCalls,updateMergeAndOnHoldStatus:updateMergeAndOnHoldStatus,updateMuteAndSpeakerStatus:updateMuteAndSpeakerStatus,get activeCall(){return activeCall();},get activeCallForContactImage(){return activeCallForContactImage();},isFirstCallOnCdmaNetwork:isFirstCallOnCdmaNetwork};})();;'use strict';var ConferenceGroupHandler=(function(){function initStringAutoResize(){var mutationObserverConfig={childList:true};var mutationObserver=new MutationObserver(function(mutations){if(groupDurationChildNode.hasAttribute('data-l10n-id')&&groupDurationChildNode.getAttribute('data-l10n-id')==='callEnded'){mutationObserver.disconnect();FontSizeManager.adaptToSpace(CallScreen.getScenario(),groupLabel,false,'end');mutationObserver.observe(groupDurationChildNode,mutationObserverConfig);}});mutationObserver.observe(groupDurationChildNode,mutationObserverConfig);} var bdiCount=document.createElement('bdi');var groupLine=document.getElementById('group-call');var groupLabel=document.getElementById('group-call-label');groupLabel.appendChild(bdiCount);var groupDuration=document.querySelector('#group-call > .duration');var groupDurationChildNode=groupDuration.querySelector('span');var groupTotalDurationChildNode=groupDuration.querySelector('.total-duration');var telephony=window.navigator.mozTelephony;if(telephony.conferenceGroup){telephony.conferenceGroup.oncallschanged=onCallsChanged;telephony.conferenceGroup.onstatechange=onStateChange;} initStringAutoResize();function onCallsChanged(){var calls=telephony.conferenceGroup.calls;CallScreen.updateCallsDisplay();if(!calls.length){ConferenceGroupUI.hideGroupDetails();} var id='conferenceCall';var args={n:calls.length};navigator.mozL10n.setAttributes(bdiCount,id,args);ConferenceGroupUI.setGroupDetailsHeader({id:id,args:args});if(telephony.conferenceGroup.calls.length>=2){CallsHandler.checkCalls();} if(CallsHandler.isFirstCallOnCdmaNetwork()){CallScreen.cdmaConferenceCall();}} function show(){groupLine.hidden=false;groupLine.classList.remove('ended');groupLine.classList.remove('held');CallScreen.createTicker(groupDuration);CallScreen.setCallerContactImage();} function end(){groupTotalDurationChildNode.textContent=groupDurationChildNode.textContent;navigator.mozL10n.setAttributes(groupDurationChildNode,'callEnded');groupLine.classList.add('ended');groupLine.classList.remove('held');CallScreen.stopTicker(groupDuration);setTimeout(function(evt){groupLine.hidden=true;CallScreen.updateCallsDisplay();},CallScreen.callEndPromptTime);} function onStateChange(){switch(telephony.conferenceGroup.state){case'connected':show();CallScreen.render('connected');break;case'held':groupLine.classList.add('held');CallScreen.render('connected-hold');break;case'':end();CallsHandler.checkCalls();break;}} function signalConferenceEnded(){ConferenceGroupUI.markCallsAsEnded();} function addToGroupDetails(node){ConferenceGroupUI.addCall(node);} function removeFromGroupDetails(node){ConferenceGroupUI.removeCall(node);} function isGroupDetailsShown(){return ConferenceGroupUI.isGroupDetailsShown();} return{addToGroupDetails:addToGroupDetails,removeFromGroupDetails:removeFromGroupDetails,signalConferenceEnded:signalConferenceEnded,isGroupDetailsShown:isGroupDetailsShown,get currentDuration(){return groupDurationChildNode.textContent;}};})();;'use strict';var ConferenceGroupUI=(function(){var groupCalls=document.getElementById('group-call-details'),groupCallsList,groupCallsHeader,initialized=false,bdiGroupCallsCountElt;document.getElementById('group-show').addEventListener('click',showGroupDetails);function _init(callback){if(initialized){callback();} LazyLoader.load([groupCalls],function(){groupCallsHeader=groupCalls.querySelector('header');groupCallsList=document.getElementById('group-call-details-list');document.getElementById('group-hide').addEventListener('click',_hideGroupDetails);if(!initialized){bdiGroupCallsCountElt=document.createElement('bdi');groupCallsHeader.appendChild(bdiGroupCallsCountElt);} initialized=true;callback();});} function _hideGroupDetails(evt){if(evt){evt.preventDefault();} if(!navigator.mozTelephony.conferenceGroup.calls.length){_removeAllCalls();} groupCalls.classList.remove('display');} function _removeAllCalls(){var callNodes=groupCalls.querySelectorAll('.handled-call');for(var i=0;i1){this.node.classList.add('sim-info');var n=this.call.serviceId+1;navigator.mozL10n.setAttributes(this.viaSimNode,'via-sim',{n:n});navigator.mozL10n.setAttributes(this.simNumberNode,'sim-number',{n:n});}else{this.viaSimNode.hidden=true;this.simNumberNode.hidden=true;} if(this._initialState==='connected'){this.connected();}} HandledCall.prototype.createCustomStyles=function hc_createCustomStyles(){const CUSTOM_STYLE_ID='call-ended-custom-style';var style=document.getElementById(CUSTOM_STYLE_ID);if(!style){style=document.createElement('style');style.id=CUSTOM_STYLE_ID;document.head.appendChild(style);} this.callEndedStyleSheet=style.sheet;};HandledCall.prototype.computeCallEndedFontSizeRules=function hc_computeCallEndedFontSizeRules(){while(this.callEndedStyleSheet.cssRules.length>0){this.callEndedStyleSheet.deleteRule(0);} var computedStyle=window.getComputedStyle(this.durationChildNode);var fontFamily=computedStyle.fontFamily;var allowedSizes=[16,17,18,19,20,21,22,23,24,25,26,27];var info=FontSizeUtils.getMaxFontSizeInfo(this.durationChildNode.textContent,allowedSizes,fontFamily,180);var rule='@media (min-height: 4.5em) {'+' #calls.big-duration > section.ended .duration > span,'+' #calls.big-duration > section.ended .total-duration {'+' font-size: '+(info.fontSize/10.0)+'rem;'+' }'+'}';this.callEndedStyleSheet.insertRule(rule,this.callEndedStyleSheet.cssRules.length);};HandledCall.prototype.observeMutation=function hc_observeMutation(mutations){if(this.durationChildNode.hasAttribute('data-l10n-id')&&this.durationChildNode.getAttribute('data-l10n-id')==='callEnded'){this.mutationObserver.disconnect();this.computeCallEndedFontSizeRules();this.mutationObserver.observe(this.durationChildNode,this.mutationObserverConfig);}};HandledCall.prototype._wasUnmerged=function hc_wasUnmerged(){return!this.node.dataset.groupHangup&&this.call.state!='disconnecting'&&this.call.state!='disconnected';};HandledCall.prototype.handleEvent=function hc_handle(evt){CallsHandler.updatePlaceNewCall();CallsHandler.updateMergeAndOnHoldStatus();CallsHandler.updateMuteAndSpeakerStatus();switch(evt.call.state){case'connected':CallScreen.render('connected');this.connected();break;case'disconnected':this.disconnected();break;case'held':this.node.classList.add('held');CallScreen.render('connected-hold');break;}};HandledCall.prototype.updateCallNumber=function hc_updateCallNumber(){var number=this.call.id.number;var self=this;CallScreen.setCallerContactImage();if(this.call.secondId){this.replacePhoneNumber('switch-calls');this.replaceAdditionalContactInfo(null,null);return;} if(!number){this.replacePhoneNumber('withheld-number');return;} var isEmergencyNumber=this.call.emergency;if(isEmergencyNumber){this.node.classList.add('emergency');this.replacePhoneNumber({raw:number},'end');this.replaceAdditionalContactInfo('emergencyNumber');return;} Voicemail.check(number,this.call.serviceId).then(function(isVoicemailNumber){if(isVoicemailNumber){self.replacePhoneNumber('voiceMail');}else{Contacts.findByNumber(number,lookupContact);checkICCMessage();}});function checkICCMessage(){var callMessageReq=navigator.mozSettings.createLock().get('icc.callmessage');callMessageReq.onsuccess=function onCallMessageSuccess(){self._iccCallMessage=callMessageReq.result['icc.callmessage'];if(self._iccCallMessage){self.replacePhoneNumber({raw:self._iccCallMessage},'end');navigator.mozSettings.createLock().set({'icc.callmessage':null});}};} function lookupContact(contact,matchingTel,contactsWithSameNumber){if(self._iccCallMessage){return;} if(contact){var primaryInfo=Utils.getPhoneNumberPrimaryInfo(matchingTel,contact);if(primaryInfo){self.replacePhoneNumber({raw:primaryInfo},'end');}else{self.replacePhoneNumber('withheld-number');} self.replaceAdditionalContactInfo({raw:matchingTel.value},Utils.getPhoneNumberAdditionalInfo(matchingTel));var photo=ContactPhotoHelper.getFullResolution(contact);if(photo){self.photo=photo;CallScreen.setCallerContactImage();} return;} self.replacePhoneNumber({raw:number},'end');self.replaceAdditionalContactInfo(self._cachedAdditionalTel,self._cachedAdditionalTelType);}};HandledCall.prototype.replaceAdditionalContactInfo=function hc_replaceAdditionalContactInfo(additionalTel,additionalTelType){if(!additionalTel&&!additionalTelType){this.additionalTelNode.removeAttribute('data-l10n-id');this.additionalTelNode.textContent='';this.additionalTelTypeNode.removeAttribute('data-l10n-id');this.additionalTelTypeNode.textContent='';this.node.classList.remove('additionalInfo');}else{if(typeof(additionalTel)==='string'){navigator.mozL10n.setAttributes(this.additionalTelNode,additionalTel);}else if(additionalTel.id){navigator.mozL10n.setAttributes(this.additionalTelNode,additionalTel.id,additionalTel.args);}else if(additionalTel.raw){this.additionalTelNode.removeAttribute('data-l10n-id');this.additionalTelNode.textContent=additionalTel.raw;} if(additionalTelType){navigator.mozL10n.setAttributes(this.additionalTelTypeNode,additionalTelType.id,additionalTelType.args);} this.node.classList.add('additionalInfo');} this._cachedAdditionalTel=additionalTel;this._cachedAdditionalTelType=additionalTelType||null;};HandledCall.prototype.restoreAdditionalContactInfo=function hc_restoreAdditionalContactInfo(){this.replaceAdditionalContactInfo(this._cachedAdditionalTel,this._cachedAdditionalTelType);};HandledCall.prototype.formatPhoneNumber=function hc_formatPhoneNumber(ellipsisSide){if(this._removed){return;} if(this.call.group){this.numberNode.style='';return;} var scenario=CallScreen.getScenario();if(scenario===FontSizeManager.CALL_WAITING&&this.call.state==='incoming'&&CallScreen.incomingContainer.classList.contains('displayed')){scenario=FontSizeManager.SECOND_INCOMING_CALL;} FontSizeManager.adaptToSpace(scenario,this.outerNode,false,ellipsisSide);if(this.node.classList.contains('additionalInfo')){FontSizeManager.ensureFixedBaseline(scenario,this.numberNode);}else{FontSizeManager.resetFixedBaseline(this.numberNode);}};HandledCall.prototype.renderPhoneNumber=function hc_renderPhoneNumber(number,ellipsisSide){if(typeof(number)==='string'){navigator.mozL10n.setAttributes(this.numberNode,number);}else if(number.id){navigator.mozL10n.setAttributes(this.numberNode,number.id,number.args);this.numberNode.style.fontSize='';}else if(number.raw){this.numberNode.removeAttribute('data-l10n-id');this.numberNode.textContent=number.raw;this.formatPhoneNumber(ellipsisSide);}};HandledCall.prototype.replacePhoneNumber=function hc_replacePhoneNumber(number,ellipsisSide){this.renderPhoneNumber(number,ellipsisSide);this._cachedInfo=number;};HandledCall.prototype.restorePhoneNumber=function hc_restorePhoneNumber(){this._cachedInfo&&this.replacePhoneNumber(this._cachedInfo,'end');};HandledCall.prototype.updateDirection=function hc_updateDirection(){var classList=this.node.classList;if(this._initialState==='incoming'){classList.add('incoming');this.node.setAttribute('data-l10n-id','incoming_screen_reader');}else{classList.add('outgoing');this.node.setAttribute('data-l10n-id','outgoing_screen_reader');} if(this.call.state==='connected'){classList.add('ongoing');}};HandledCall.prototype.remove=function hc_remove(){this._removed=true;this.call.removeEventListener('statechange',this);this.photo=null;var self=this;CallScreen.stopTicker(this.durationNode);var currentDuration=ConferenceGroupHandler.isGroupDetailsShown()?ConferenceGroupHandler.currentDuration:this.durationChildNode.textContent;this.node.classList.add('ended');this.durationNode.classList.remove('isTimer');navigator.mozL10n.setAttributes(this.durationChildNode,'callEnded');var totalDuration=!!currentDuration.match(/\d+/g)?currentDuration:'';this.totalDurationNode.textContent=totalDuration;setTimeout(function(evt){CallScreen.removeCall(self.node);self.node=null;},CallScreen.callEndPromptTime);};HandledCall.prototype.connected=function hc_connected(){this.show();this.node.classList.remove('held');this.updateDirection();CallScreen.createTicker(this.durationNode);CallScreen.syncSpeakerEnabled();this.updateCallNumber();this._wasConnected=true;};HandledCall.prototype.disconnected=function hc_disconnected(){if(this._leftGroup){if(typeof(this._cachedInfo)==='string'){CallScreen.showStatusMessage(this._cachedInfo);}else if(this._cachedInfo.id){const disconnectedMessageL10n={'withheld-number':'withheld-number-left-call','voiceMail':'voicemail-left-call'};var id=disconnectedMessageL10n[this._cachedInfo.id];CallScreen.showStatusMessage(id);}else if(this._cachedInfo.raw){CallScreen.showStatusMessage({id:'caller-left-call',args:{caller:this._cachedInfo.raw}});} this._leftGroup=false;} if(this._wasConnected){TonePlayer.playSequence([[480,620,250]]);} this._wasConnected=false;this.remove();};HandledCall.prototype.show=function hc_show(){if(this.node){this.node.hidden=false;} CallScreen.updateCallsDisplay();};HandledCall.prototype.hide=function hc_hide(){if(this.node){this.node.hidden=true;} CallScreen.updateCallsDisplay();};;;'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';var MobileInfo={brazil:{carriers:{'00':'NEXTEL','02':'TIM','03':'TIM','04':'TIM','05':'CLARO','06':'VIVO','07':'CTBC','08':'TIM','10':'VIVO','11':'VIVO','15':'SERCOMTEL','16':'OI','23':'VIVO','24':'OI','31':'OI','32':'CTBC','33':'CTBC','34':'CTBC','37':'AEIOU'},regions:{'11':'SP','12':'SP','13':'SP','14':'SP','15':'SP','16':'SP','17':'SP','18':'SP','19':'SP','21':'RJ','22':'RJ','24':'RJ','27':'ES','28':'ES','31':'MG','32':'MG','33':'MG','34':'MG','35':'MG','37':'MG','38':'MG','41':'PR','42':'PR','43':'PR','44':'PR','45':'PR','46':'PR','47':'SC','48':'SC','49':'SC','51':'RS','53':'RS','54':'RS','55':'RS','61':'DF','62':'GO','63':'TO','64':'GO','65':'MT','66':'MT','67':'MS','68':'AC','69':'RO','71':'BA','73':'BA','74':'BA','75':'BA','77':'BA','79':'SE','81':'PE','82':'AL','83':'PB','84':'RN','85':'CE','86':'PI','87':'PE','88':'CE','89':'PI','91':'PA','92':'AM','93':'PA','94':'PA','95':'RR','96':'AP','97':'AM','98':'MA','99':'MA'}}};var MobileOperator={BRAZIL_MCC:'724',BRAZIL_CELLBROADCAST_CHANNEL:50,userFacingInfo:function mo_userFacingInfo(mobileConnection){var network=mobileConnection.voice.network;var iccid=mobileConnection.iccId;var iccObj=navigator.mozIccManager.getIccById(iccid);var iccInfo=iccObj?iccObj.iccInfo:null;var operator=network?(network.shortName||network.longName):null;if(operator&&iccInfo&&iccInfo.isDisplaySpnRequired&&iccInfo.spn){if(iccInfo.isDisplayNetworkNameRequired&&operator!==iccInfo.spn){operator=operator+' '+iccInfo.spn;}else{operator=iccInfo.spn;}} var carrier,region;if(this.isBrazil(mobileConnection)){var lac=mobileConnection.voice.cell.gsmLocationAreaCode%100;var carriers=MobileInfo.brazil.carriers;var regions=MobileInfo.brazil.regions;carrier=carriers[network.mnc]||(this.BRAZIL_MCC+network.mnc);region=(regions[lac]?regions[lac]+' '+lac:'');} return{'operator':operator,'carrier':carrier,'region':region};},isBrazil:function mo_isBrazil(mobileConnection){var cell=mobileConnection.voice.cell;var net=mobileConnection.voice.network;return net?(net.mcc===this.BRAZIL_MCC&&cell&&cell.gsmLocationAreaCode):null;}};;'use strict';(function(exports){var LockScreenSlide=function(opts){this.initialize(opts);};var LockScreenSlidePrototype={stopped:false,canvas:null,layout:'',useNewStyle:false,track:{length:{tiny:'280',large:'410'},color:'rgba(255, 255, 255, 0.4)',backgroundColor:'rgba(0, 0, 0, 0)',from:0,to:0,radius:0,width:0},trackNew:{length:{tiny:'276',large:'406'},strokeColorTop:'rgba(0, 0, 0, 0.2)',strokeColorBottom:'rgba(0, 0, 0, 0)',fillColorTop:'rgba(0, 0, 0, 0.2)',fillColorBottom:'rgba(0, 0, 0, 0)',backColor:'rgba(51, 51, 51, 0.15)',from:0,to:0,radius:0,width:0},arrows:{left:null,right:null,ldraw:{x:null,y:null},rdraw:{x:null,y:null}},iconBG:{radius:20,left:{color:'rgba(255, 255, 255, 0.25)'},right:{color:'rgba(255, 255, 255, 0.25)'}},slides:{left:null,right:null},areas:{left:null,right:null},area:null,overlay:null,width:0,height:80,center:{x:null,y:null},handle:{autoExpand:{accState:'normal',accFactor:1.02,sentinelOffset:40,sentinelWidth:0},bounceBackTime:200,radius:28,lineWidth:1.6,maxWidth:0,touchedColor:'0, 170, 204',touchedColorStop:'178, 229, 239',color:'255, 255, 255',backgroundColor:'255, 255, 255',backgroundAlpha:0},handleNew:{autoExpand:{accState:'normal',accFactor:1.02,sentinelOffset:40,sentinelWidth:0},bounceBackTime:200,radius:30,innerRadius:15,outerColor:'rgba(255, 255, 255, 0.9)',innerColor:'rgba(0, 0, 0, 0.05)',lineWidth:1.6,maxWidth:0,towardLeft:false,touchedColor:'0, 170, 204',touchedColorStop:'178, 229, 239'},colors:{left:{touchedColor:'255, 255, 255',touchedColorStop:'255, 255, 255'},right:{touchedColor:'255, 255, 255',touchedColorStop:'255, 255, 255'}},states:{initialized:false,sliding:false,slideReachEnd:false,slidingColorful:false,slidingColorGradientEnd:false,touch:{id:'',touched:false,initX:-1,pageX:-1,pageY:-1,tx:-1,prevX:-1,deltaX:0}},IDs:{overlay:'lockscreen',area:'lockscreen-area',canvas:'lockscreen-canvas',areas:{left:'lockscreen-area-camera',right:'lockscreen-area-unlock'}},resources:{larrow:'/lockscreen/style/images/larrow.png',rarrow:'/lockscreen/style/images/rarrow.png'},resourcesNew:{larrow:'/lockscreen/style/images/lockscreen_toggle_arrow_left.png',rarrow:'/lockscreen/style/images/lockscreen_toggle_arrow_right.png'}};LockScreenSlidePrototype.initialize=function(opts){if(opts){this._overwriteSettings(opts);} if(opts.useNewStyle){this.track=this.trackNew;this.handle=this.handleNew;this.resources=this.resourcesNew;} this._initializeCanvas();this.publish('lockscreenslide-unlocker-initializer');this.states.initialized=true;};LockScreenSlidePrototype.reset=function lss_reset(){this._clearCanvas();this._drawTrack();this._resetHandle();this._resetArrows();this._drawIconBG();};LockScreenSlidePrototype._overwriteSettings=function(options){var iterate=function _iterate(opts,settings){for(var property in opts){if(opts.hasOwnProperty(property)){if('object'===typeof opts[property]){iterate(opts[property],settings[property]);} else{settings[property]=opts[property];}}}};iterate(options,this);};LockScreenSlidePrototype.handleEvent=function(evt){switch(evt.type){case'screenchange':if(evt.detail.screenOffBy=='proximity'){break;} this._clearCanvas();this._drawTrack();this._resetHandle();this._resetArrows();this._drawIconBG();break;case'touchstart':evt.preventDefault();if(evt.target!==this.area||evt.touches.length>1){return;} this.states.touch.id=evt.touches[0].identifier;this._onSlideBegin(this._dpx(evt.touches[0].pageX));window.addEventListener('touchend',this);window.addEventListener('touchmove',this);break;case'touchmove':if(evt.touches.length>1){this._endGesture();return;} this._onTouchMove(this._dpx(evt.touches[0].pageX),this._dpx(evt.touches[0].pageY));if(this.states.sliding){this._onSliding(this._dpx(evt.touches[0].pageX));} break;case'touchend':if(evt.changedTouches[0].identifier!==this.states.touch.id){return;} this._endGesture();break;case'click':if(evt.mozInputSource===0){evt.preventDefault();if(this.areas.left===evt.target){this.publish('lockscreenslide-activate-left');}else if(this.areas.right===evt.target){this.publish('lockscreenslide-activate-right');}} break;}};LockScreenSlidePrototype._initializeCanvas=function lss_initializeCanvas(){this.overlay=document.getElementById(this.IDs.overlay);this.area=document.getElementById(this.IDs.area);this.canvas=document.getElementById(this.IDs.canvas);this.areas.left=document.getElementById(this.IDs.areas.left);this.areas.right=document.getElementById(this.IDs.areas.right);this.area.addEventListener('touchstart',this);this.areas.left.addEventListener('click',this);this.areas.right.addEventListener('click',this);this.layout=(ScreenLayout&&ScreenLayout.getCurrentLayout&&ScreenLayout.getCurrentLayout())?ScreenLayout.getCurrentLayout():'tiny';var center=this.center;this.arrows.left=new Image();this.arrows.right=new Image();var larrow=this.arrows.left;var rarrow=this.arrows.right;larrow.src=this.resources.larrow;rarrow.src=this.resources.rarrow;larrow.onload=(function(){var offset=this.useNewStyle?(this.arrows.left.width+this.handle.radius):(this.arrows.left.width<<1);this.arrows.ldraw.x=center.x-offset;this.arrows.ldraw.y=center.y-(this.arrows.left.height>>1);var ctx=this.canvas.getContext('2d');ctx.drawImage(this.arrows.left,this.arrows.ldraw.x,this.arrows.ldraw.y,this.arrows.left.width,this.arrows.left.height);}).bind(this);rarrow.onload=(function(){var offset=this.useNewStyle?this.handle.radius:this.arrows.right.width;this.arrows.rdraw.x=center.x+offset;this.arrows.rdraw.y=center.y-(this.arrows.right.height>>1);var ctx=this.canvas.getContext('2d');ctx.drawImage(this.arrows.right,this.arrows.rdraw.x,this.arrows.rdraw.y,this.arrows.right.width,this.arrows.right.height);}).bind(this);this.width=this._dpx(window.innerWidth);this.height=this._dpx(80);this.canvas.width=this.width;this.canvas.height=this.height;this.canvas.style.width=window.innerWidth+'px';this.canvas.style.height=80+'px';this.center.x=this.canvas.offsetLeft+this.canvas.width>>1;this.center.y=this.canvas.offsetTop+this.canvas.height>>1;this.handle.radius=this._dpx(this.handle.radius);if(this.useNewStyle){this.handle.innerRadius=this._dpx(this.handle.innerRadius);} this.track.radius=this.handle.radius+this._dpx(this.useNewStyle?2:1);this.handle.lineWidth=this._dpx(this.handle.lineWidth);this.handle.autoExpand.sentinelOffset=this._dpx(this.handle.autoExpand.sentinelOffset);this.iconBG.radius=this._dpx(this.iconBG.radius);this.canvas.getContext('2d').save();this.canvas.getContext('2d',this.handle.radius<<1,0);var trackLength='tiny'===this.layout?this.track.length.tiny:this.track.length.large;trackLength=this._dpx(trackLength);var maxWidth=(trackLength- (this.handle.radius<<1))>>1;maxWidth-=2;this.handle.maxWidth=maxWidth;this.handle.autoExpand.sentinelWidth=maxWidth-this.handle.autoExpand.sentinelOffset;this.track.width=trackLength;this.track.from=this.center.x-maxWidth;this.track.to=this.center.x+maxWidth;this.track.y=this.center.y;this._drawTrack();this._drawIconBG();this._resetHandle();this._resetTouchStates();};LockScreenSlidePrototype._finalizeCanvas=function lss_finalizeCanvas(){this.states.slidingColorful=false;this.states.slidingColorGradientEnd=false,this._clearCanvas();};LockScreenSlidePrototype._onSliding=function lss_onSliding(tx){var mtx=this._mapCoord(tx,0)[0];var isLeft=tx-this.center.x<0;var prevState;var currentState;this._clearCanvas();var expandSentinelR=this.center.x+ this.handle.autoExpand.sentinelWidth;var expandSentinelL=this.center.x- this.handle.autoExpand.sentinelWidth;if(tx>expandSentinelR||tx0;if(prevState!==currentState){this.publish('lockscreenslide-near-left',{'currentState':currentState,'prevState':prevState});}}else{slow=this.states.touch.deltaX<0;if(prevState!==currentState){this.publish('lockscreenslide-near-right',{'currentState':currentState,'prevState':prevState});}}}else{prevState=this.handle.autoExpand.accState;this.handle.autoExpand.accState='normal';currentState=this.handle.autoExpand.accState;if(prevState!==currentState){if(isLeft){if(prevState!==currentState){this.publish('lockscreenslide-near-left',{'currentState':currentState,'prevState':prevState});}}else{if(prevState!==currentState){this.publish('lockscreenslide-near-right',{'currentState':currentState,'prevState':prevState});}}}} mtx=this._accelerateSlide(tx);this._drawTrack();this._drawArrowsTo(mtx);this._drawIconBG();this._drawSlideTo(mtx);};LockScreenSlidePrototype._onSlideBegin=function lss_onSlideBegin(tx){var center=this.center;var boundaryR=center.x+this.handle.radius;var boundaryL=center.x-this.handle.radius;if(tx>boundaryR||tx=center.x)){this._clearCanvas();this._drawTrack();this._drawArrowsTo(nextTx);this._drawIconBG();this._drawSlideTo(nextTx);} requestAnimationFrame(drawIt);}else{this._clearCanvas();this._drawTrack();this._drawArrowsTo(center.x);this._drawIconBG();this._drawSlideTo(center.x);if(cb){cb();}}}).bind(this);requestAnimationFrame(drawIt);};LockScreenSlidePrototype._darkIcons=function lss_darkIcons(){this.areas.left.classList.add('dark');this.areas.right.classList.add('dark');};LockScreenSlidePrototype._drawArrowsTo=function lss_drawArrows(tx){var canvas=this.canvas;var ctx=canvas.getContext('2d');var center=this.center;var offset=tx-center.x;var isLeft=offset<0;var alpha=1-Math.min(1,Math.abs(offset)/this._dpx(30));var position;var oldAlpha;if(this.handle.maxWidth0?center.x+maxWidth:center.x-maxWidth;} var counterclock=false;if(offset-center.x<0){counterclock=true;} var isLeft=counterclock;var isRight=offset-center.x>0;if(isLeft){this.handle.touchedColor=this.colors.left.touchedColor;this.handle.touchedColorStop=this.colors.left.touchedColorStop;}else if(isRight){this.handle.touchedColor=this.colors.right.touchedColor;this.handle.touchedColorStop=this.colors.right.touchedColorStop;} var startAngle=1.5*Math.PI;var endAngle=0.5*Math.PI;var fillAlpha=0.0;var strokeStyle='white';const GRADIENT_LENGTH=50;if(this.useNewStyle){if(0===urw){ctx.beginPath();ctx.arc(center.x,center.y,radius,0,2*Math.PI,false);ctx.fillStyle=this.handle.outerColor;ctx.closePath();ctx.fill();ctx.beginPath();ctx.arc(center.x,center.y,this.handle.innerRadius,0,2*Math.PI,false);ctx.fillStyle=this.handle.innerColor;ctx.closePath();ctx.fill();}else{fillAlpha=0.9-Math.min(0.7,(urw/this.handle.maxWidth)*0.7);strokeStyle='transparent';ctx.fillStyle='rgba('+this.handle.touchedColor+', '+ fillAlpha+')';ctx.strokeStyle=strokeStyle;ctx.beginPath();ctx.arc(center.x,center.y,radius,endAngle,startAngle,counterclock);ctx.lineTo(center.x,center.y-radius);ctx.lineTo(center.x+(offset-center.x),center.y-radius);ctx.arc(offset,center.y,radius,startAngle,endAngle,counterclock);ctx.lineTo(center.x,center.y+radius);ctx.fill();ctx.stroke();ctx.closePath();}}else{var fillColor;var strokeColor;var borderAlpha;if(urw>15&&true!==this.states.slidingColorful){fillAlpha=(urw-15)/GRADIENT_LENGTH;if(fillAlpha>1.0){fillAlpha=1.0;this.states.slidingColorGradientEnd=true;} borderAlpha=1.0-fillAlpha;strokeStyle='rgba('+this.handle.touchedColorStop+','+borderAlpha+')';this.states.slidingColorful=true;}else{if(0===urw){fillAlpha=this.handle.backgroundAlpha;strokeColor=this.handle.color;fillColor=this.handle.backgroundColor;}else{fillAlpha=(urw-15)/GRADIENT_LENGTH;if(fillAlpha>1.0){fillAlpha=1.0;} strokeColor=this.handle.touchedColorStop;fillColor=this.handle.touchedColor;} borderAlpha=1.0-fillAlpha;strokeStyle='rgba('+strokeColor+','+borderAlpha+')';} ctx.fillStyle='rgba('+fillColor+','+fillAlpha+')';ctx.lineWidth=this.handle.lineWidth;ctx.strokeStyle=strokeStyle;ctx.beginPath();ctx.arc(center.x,center.y,radius,endAngle,startAngle,counterclock);ctx.lineTo(center.x,center.y-radius);ctx.lineTo(center.x+(offset-center.x),center.y-radius);ctx.arc(offset,center.y,radius,startAngle,endAngle,counterclock);ctx.lineTo(center.x,center.y+radius);ctx.fill();ctx.stroke();ctx.closePath();}};LockScreenSlidePrototype._drawIconBG=function lss_dibg(){if(!this.useNewStyle){return;} var canvas=this.canvas;var ctx=canvas.getContext('2d');ctx.fillStyle=this.iconBG.left.color;ctx.strokeStyle='transparent';ctx.beginPath();ctx.arc(this.track.from,this.track.y,this.iconBG.radius,0,2*Math.PI,false);ctx.stroke();ctx.closePath();ctx.fill();ctx.fillStyle=this.iconBG.right.color;ctx.beginPath();ctx.arc(this.track.to,this.track.y,this.iconBG.radius,0,2*Math.PI,false);ctx.fill();ctx.stroke();ctx.closePath();};LockScreenSlidePrototype._dpx=function lss_dpx(px){return px*window.devicePixelRatio;};LockScreenSlidePrototype._lightIcons=function lss_lightIcons(){this.areas.left.classList.remove('dark');this.areas.right.classList.remove('dark');};LockScreenSlidePrototype._mapCoord=function lss_mapCoord(x,y){var cw=this.canvas.clientWidth;var ch=this.canvas.clientHeight;return[cw*x/window.innerWidth,ch*y/window.innerHeight];};LockScreenSlidePrototype._resetArrows=function lss_restoreArrows(){var canvas=this.canvas;var ctx=canvas.getContext('2d');ctx.drawImage(this.arrows.left,this.arrows.ldraw.x,this.arrows.ldraw.y,this.arrows.left.width,this.arrows.left.height);ctx.drawImage(this.arrows.right,this.arrows.rdraw.x,this.arrows.rdraw.y,this.arrows.right.width,this.arrows.right.height);};LockScreenSlidePrototype._resetHandle=function lss_resetHandle(){this.states.slidingColorful=false;this.states.slidingColorGradientEnd=false;var centerx=this.center.x;this._drawSlideTo(centerx);};LockScreenSlidePrototype._resetTouchStates=function lss_resetTouchStates(){this.states.touch={id:null,touched:false,initX:this.center.x,pageX:this.center.x,pageY:this.center.y,tx:0,prevX:this.center.x,deltaX:0};};LockScreenSlidePrototype.publish=function lss_publish(type,detail){window.dispatchEvent(new CustomEvent(type,{'detail':detail}));};LockScreenSlide.prototype=LockScreenSlidePrototype;exports.LockScreenSlide=LockScreenSlide;})(window);;'use strict';var ScreenLayout={defaultQueries:{tiny:'(max-width: 767px)',small:'(min-width: 768px) and (max-width: 991px)',medium:'(min-width: 992px) and (max-width: 1200px)',large:'(min-width: 1201px)',hardwareHomeButton:window.VulpesCompat?'(min-width: 0px)':'(-moz-physical-home-button)'},init:function sl_init(){this.queries=(function(qs){var result={};for(var key in qs){result[key]=window.matchMedia(qs[key]);} return result;})(this.defaultQueries);},_isOnRealDevice:undefined,isOnRealDevice:function sl_isOnRealDevice(){if(typeof(this._isOnRealDevice)!=='undefined'){return this._isOnRealDevice;} if(window.innerWidth===screen.availWidth){this._isOnRealDevice=true;}else{this._isOnRealDevice=false;} return this._isOnRealDevice;},getCurrentLayout:function sl_getCurrentLayout(type){if(type===undefined){for(var name in this.defaultQueries){if(this.queries[name]&&this.queries[name].matches){return name;}}} if(typeof this.queries[type]!=='undefined'){return this.queries[type].matches;} return false;},watch:function sl_watch(name,media){var mediaString=media||this.queries[name].media;if(!mediaString){return;} this.unwatch(name);this.queries[name]=window.matchMedia(mediaString);this.boundHandleChange=this.handleChange.bind(this);this.queries[name].addListener(this.boundHandleChange);},unwatch:function sl_unwatch(name){if(this.queries[name]){this.queries[name].removeListener(this.boundHandleChange);}},handleChange:function sl_handleChange(evt){for(var key in this.queries){if(this.queries[key].media!==evt.media){continue;} window.dispatchEvent(new CustomEvent('screenlayoutchange',{detail:{name:key,status:evt.matches}}));}}};ScreenLayout.init();;'use strict';(function(window){var _start=Date.now();var DEBUG=false;window.SIMSlot=function SIMSlot(conn,index,card){this.index=index;this.conn=conn;if(card){this.update(card);} this.publish('created');};SIMSlot.EVENTS=['cardstatechange','iccinfochange','stkcommand','stksessionend'];SIMSlot.METHODS=['sendStkResponse','sendStkMenuSelection','sendStkTimerExpiration','sendStkEventDownload'];SIMSlot.DOM_REQUEST_METHODS=['getCardLock','unlockCardLock','setCardLock','getCardLockRetryCount','readContacts','updateContact','iccOpenChannel','iccExchangeAPDU','iccCloseChannel'];SIMSlot.ABSENT_TYPES=['permanentBlocked'];SIMSlot.LOCK_TYPES=['pinRequired','pukRequired','networkLocked','corporateLocked','serviceProviderLocked','network1Locked','network2Locked','hrpdNetworkLocked','ruimCorporateLocked','ruimServiceProviderLocked'];SIMSlot.prototype.update=function ss_update(iccObj){this.simCard=iccObj;this.constructor.EVENTS.forEach(function iterater(evt){iccObj.addEventListener(evt,this);},this);this.constructor.DOM_REQUEST_METHODS.forEach(function iterator(domRequest){this[domRequest]=function(){return iccObj[domRequest].apply(iccObj,arguments);};},this);this.constructor.METHODS.forEach(function iterator(method){this[method]=function(){return iccObj[method].apply(iccObj,arguments);};},this);this.publish('updated');};SIMSlot.prototype.EVENT_PREFIX='simslot-';SIMSlot.prototype.CLASS_NAME='SIMSLOT';SIMSlot.prototype.publish=function ss_publish(eventName){this.debug(' publish: '+eventName);window.dispatchEvent(new CustomEvent(this.EVENT_PREFIX+eventName,{detail:this}));};SIMSlot.prototype.handleEvent=function ss_handleEvent(evt){switch(evt.type){default:this.publish(evt.type);if(this.simCard){this.debug(this.simCard.cardState);} break;}};SIMSlot.prototype.debug=function(){if(DEBUG){console.log('['+this.CLASS_NAME+']'+'['+(this.index)+']'+'['+(new Date().getTime()/1000-_start).toFixed(3)+']'+ Array.slice(arguments).concat());}};SIMSlot.prototype.isAbsent=function ss_isAbsent(){return(!this.simCard||this.constructor.ABSENT_TYPES.indexOf(this.simCard.cardState)>=0||this.simCard&&this.simCard.iccInfo&&this.simCard.iccInfo.iccid===null);};SIMSlot.prototype.getSmsc=function ss_getSmsc(cb){var mobileMessage=window.navigator.mozMobileMessage;if(!mobileMessage){console.error('can\'t access mozMobileMessage');cb(null);}else{mobileMessage.getSmscAddress(this.index).then((result)=>{var smsc;if(typeof result==='string'||result instanceof String){smsc=result.split(',')[0].replace(/"/g,'');}else{smsc=result.address;} cb(smsc);},(error)=>{console.error(error);cb(null);});}};SIMSlot.prototype.isUnknownState=function ss_isUnknownState(){var empty=(this.simCard.cardState==='');var unknown=(this.simCard.cardState==='unknown');return!this.simCard.cardState||unknown||empty;};SIMSlot.prototype.isLocked=function ss_isLocked(){return this.constructor.LOCK_TYPES.indexOf(this.simCard.cardState)>=0;};SIMSlot.prototype.getCardState=function ss_getCardState(){return this.simCard.cardState;};}(window));;'use strict';(function(window){var IccManager=navigator.mozIccManager;window.SIMSlotManager={length:0,_instances:[],TIMEOUT_FOR_SIM2:2000,_timerForSIM2:null,ready:false,init:function ssm_init(){if(!IccManager){return;} this._conns=Array.prototype.slice.call(navigator.mozMobileConnections);this.length=this._conns.length;if(this._conns.length===0){return;} var allSIMCardDetected=true;this._conns.forEach(function iterator(conn,index){var slot=new SIMSlot(conn,index,IccManager.getIccById(conn.iccId));this._instances.push(slot);if(slot.isAbsent()){allSIMCardDetected=false;}},this);if(allSIMCardDetected){this.publishSIMSlotIsReady();}else if(this.isMultiSIM()&&this.hasOnlyOneSIMCardDetected()){this.waitForSecondSIM();} IccManager.addEventListener('iccdetected',this);window.dispatchEvent(new CustomEvent('simslotmanagerstarted'));},isMultiSIM:function(){return(this.length>1);},isSIMCardAbsent:function ssm_isSIMCardAbsent(index){var slot=this.get(index);if(slot){return slot.isAbsent();}else{return true;}},hasOnlyOneSIMCardDetected:function(){var sim0Absent=this.isSIMCardAbsent(0);var sim1Absent=this.isSIMCardAbsent(1);var hasOneSim=(sim0Absent&&!sim1Absent)||(!sim0Absent&&sim1Absent);return hasOneSim;},noSIMCardOnDevice:function ssm_noSIMCardOnDevice(){if(!IccManager||!IccManager.iccIds){return true;} return(IccManager.iccIds.length===0);},noSIMCardConnectedToNetwork:function ssm_noSIMCardConnectedToNetwork(){if(!IccManager||!IccManager.iccIds){return true;} return this._instances.every(function iterator(instance){return instance.conn.voice&&instance.conn.voice.emergencyCallsOnly;});},get:function ssm_get(index){if(index>this.length-1){return null;} return this._instances[index];},getMobileConnection:function ssm_getMobileConnection(index){if(index>this.length-1){return null;} return this._instances[index].conn;},getSlots:function ssm_getSlots(){return this._instances;},getSlotByIccId:function ssm_getSlotByIccId(iccId){var found=null;this._instances.some(function iterator(slot,index){if(slot.conn.iccId&&slot.conn.iccId===iccId){found=slot;return true;}else{return false;}},this);return found;},waitForSecondSIM:function(){var self=this;this._timerForSIM2=setTimeout(function(){clearTimeout(self._timerForSIM2);self.publishSIMSlotIsReady();},this.TIMEOUT_FOR_SIM2);},publishSIMSlotIsReady:function(){if(!this.ready){this.ready=true;window.dispatchEvent(new CustomEvent('simslotready'));}},handleEvent:function ssm_handleEvent(evt){switch(evt.type){case'iccdetected':var slot=this.getSlotByIccId(evt.iccId);if(slot){slot.update(IccManager.getIccById(evt.iccId));if(!this.isMultiSIM()){this.publishSIMSlotIsReady();}else{if(this.hasOnlyOneSIMCardDetected()){this.waitForSecondSIM();}else{clearTimeout(this._timerForSIM2);this.publishSIMSlotIsReady();}}} break;}}};SIMSlotManager.init();}(window));;'use strict';(function(exports){var _lockedStateMsgMap={'unknown':'emergencyCallsOnly-unknownSIMState','pinRequired':'emergencyCallsOnly-pinRequired','pukRequired':'emergencyCallsOnly-pukRequired','networkLocked':'emergencyCallsOnly-networkLocked','serviceProviderLocked':'emergencyCallsOnly-serviceProviderLocked','corporateLocked':'emergencyCallsOnly-corporateLocked','network1Locked':'emergencyCallsOnly-network1Locked','network2Locked':'emergencyCallsOnly-network2Locked','hrpdNetworkLocked':'emergencyCallsOnly-hrpdNetworkLocked','ruimCorporateLocked':'emergencyCallsOnly-ruimCorporateLocked','ruimServiceProviderLocked':'emergencyCallsOnly-ruimServiceProviderLocked'};var _NETWORKS_2G=['gsm','gprs','edge'];var LockScreenConnInfoManager=function(root){if(root){this._initialize(root);}};var LockScreenConnInfoManagerPrototype={_connStates:null,_settings:null,_cellbroadcastLabel:null,_telephonyDefaultServiceId:0,_airplaneMode:false};LockScreenConnInfoManagerPrototype._initialize=function lscs_initialize(root){this._connStates=root;this._settings=navigator.mozSettings;this._connStates.hidden=false;SIMSlotManager.getSlots().forEach(function(simslot,index){this._connStates.appendChild(this._createConnStateElement());simslot.conn.addEventListener('voicechange',(function(index){this.updateConnState(simslot);}).bind(this));},this);this.simSlotCardStateChangeListener=(function(evt){this.updateConnState(evt.detail);}).bind(this);window.addEventListener('simslot-cardstatechange',this.simSlotCardStateChangeListener);this.simSlotIccInfoChangeListener=(function(evt){this.updateConnState(evt.detail);}).bind(this);window.addEventListener('simslot-iccinfochange',this.simSlotIccInfoChangeListener);this.cellBroadcastMsgChangedListener=(function(evt){this._cellbroadcastLabel=evt.detail;this.updateConnStates();}).bind(this);window.addEventListener('cellbroadcastmsgchanged',this.cellBroadcastMsgChangedListener);this._settings.addObserver('ril.radio.disabled',(function(evt){this._airplaneMode=evt.settingValue;this.updateConnStates();}).bind(this));this._settings.addObserver('ril.telephony.defaultServiceId',(function(evt){this._telephonyDefaultServiceId=evt.settingValue;this.updateConnStates();}).bind(this));var req=SettingsListener.getSettingsLock().get('ril.radio.disabled');req.onsuccess=(function(){this._airplaneMode=!!req.result['ril.radio.disabled'];var req2=SettingsListener.getSettingsLock().get('ril.telephony.defaultServiceId');req2.onsuccess=(function(){this._telephonyDefaultServiceId=req2.result['ril.telephony.defaultServiceId']||0;this.updateConnStates();}).bind(this);}).bind(this);this.updateConnStates();};LockScreenConnInfoManagerPrototype.teardown=function lscs_teardown(){window.removeEventListener('simslot-cardstatechange',this.simSlotCardStateChangeListener);window.removeEventListener('simslot-iccinfochange',this.simSlotIccInfoChangeListener);window.removeEventListener('cellbroadcastmsgchanged',this.cellBroadcastMsgChangedListener);};LockScreenConnInfoManagerPrototype._createConnStateElement=function lscs_createConnStateElement(){var div=document.createElement('div');var span=document.createElement('span');var line1=document.createElement('span');var line2=document.createElement('span');line1.className=line2.className='connstate-line';div.appendChild(span);div.appendChild(line1);div.appendChild(line2);return div;};LockScreenConnInfoManagerPrototype.updateConnStates=function lscs_updateConnStates(){SIMSlotManager.getSlots().forEach((function(simslot){this.updateConnState(simslot);}).bind(this));};function lineText(node,l10nId,l10nArgs,text){if(!l10nId&&!text){node.setAttribute('data-content',true);}else{node.removeAttribute('data-content');} if(l10nId){navigator.mozL10n.setAttributes(node,l10nId,l10nArgs);}else{node.removeAttribute('data-l10n-id');if(text){node.textContent=text;}else{node.textContent='';}}} LockScreenConnInfoManagerPrototype.updateConnState=function lscs_updateConnState(simslot){var conn=simslot.conn;var index=simslot.index;var connstate=this._connStates.children[index];var simIDLine=connstate.children[0];var connstateLines=Array.prototype.slice.call(connstate.querySelectorAll('.connstate-line'));var iccObj=simslot.simCard;var voice=conn.voice;connstate.hidden=false;if(SIMSlotManager.isMultiSIM()){simIDLine.hidden=false;lineText(simIDLine,'lockscreen-sim-id',{n:(index+1)});}else{simIDLine.hidden=true;} connstateLines.forEach(function(line){lineText(line);});var nextLine=function(){for(var i=0;i