/* minified */ function e(e,n){"use strict";var t=this;n&&n.length?_.forEach(n,(function(n){t[n]=e[n]})):["currency","issuer","medianTime","number","version","powMin","dividend","membersCount","hash","identities","joiners","actives","leavers","revoked","excluded","certifications","transactions"].forEach((function(n){t[n]=e[n]})),t.identitiesCount=t.identities?t.identities.length:0,t.joinersCount=t.joiners?t.joiners.length:0,t.activesCount=t.actives?t.actives.length:0,t.leaversCount=t.leavers?t.leavers.length:0,t.revokedCount=t.revoked?t.revoked.length:0,t.excludedCount=t.excluded?t.excluded.length:0,t.certificationsCount=t.certifications?t.certifications.length:0,t.transactionsCount=t.transactions?t.transactions.length:0,t.empty=t.isEmpty()}function n(e,n){e.extensionPoint=n.extensions.points.current.get()}function t(e,n,t,i,a,o,s,r,l,c,u,d,p,m,E,g,h,b){e.walletData=p.data,e.search={},e.login=p.isLogin(),e.motion=u.motion.default,e.fullscreen=u.screen.fullscreen.isEnabled(),e.showHome=function(){return s.nextViewOptions({historyRoot:!0}),t.go("app.home").then(u.loading.hide)},e.createHelptipScope=function(t){if(t||!n.tour&&n.settings.helptip.enable&&!u.screen.isSmall()){var i=e.$new();return r("HelpTipCtrl",{$scope:i}),i}},e.startHelpTour=function(t){if(n.tour=!0,!t)return s.clearHistory(),s.clearCache().then((function(){e.startHelpTour(!0)}));var i=e.createHelptipScope(!0);return i.startHelpTour().then((function(){i.$destroy(),delete n.tour})).catch((function(e){delete n.tour}))},e.isLogin=function(){return e.login},e.loadWalletData=function(e){return console.warn("[app-controller] DEPRECATED - Please use csWallet.load() instead of $scope.loadWalletData()",new Error),e=e||{},p.loadData(e).then((function(e){if(!e)throw"CANCELLED";return e}))},e.loadWallet=function(n){return console.warn("[app-controller] DEPRECATED - Please use csWallet.loadData() instead of $scope.loadWallet()",new Error),c.isStarted()?(n=n||{},p.isLogin()?p.data.loaded?a.when(p.data):p.loadData(n):e.showLoginModal(n).then((function(e){if(e)return n&&n.minData&&(n.minData=!1),p.loadData(n)})).then((function(e){if(e)return e;throw"CANCELLED"}))):c.ready().then((function(){return e.loadWallet(n)}))},e.loginAndGo=function(n,i){if(e.closeProfilePopover(),n=n||"app.view_wallet",p.isLogin())return t.go(n,i);if(h.httpsMode&&l.location&&"https:"!==l.location.protocol){var a=l.location.href,o=a.indexOf("#"),s=-1!==o?a.substr(0,o):a;if(a=(s="https"+s.substr(4))+t.href(n),!h.httpsModeDebug)return void(l.location.href=a);console.debug("[httpsMode] --- Should redirect to: "+a)}return e.showLoginModal().then((function(e){if(e)return t.go(n,i).then(u.loading.hide)}))},e.showLoginModal=function(t){return(t=t||{}).templateUrl=t.templateUrl||h.login&&h.login.templateUrl,t.controller=t.controller||h.login&&h.login.controller,E.showLogin(t).then((function(e){if(e)return g.data.rememberMe!==e.rememberMe&&(g.data.rememberMe=e.rememberMe,g.data.useLocalStorage=!!g.data.rememberMe||g.data.useLocalStorage,g.store()),p.login(e.username,e.password)})).then((function(e){return e&&(n.walletData=e),e})).catch((function(n){if("RETRY"===n)return u.loading.hide(),e.showLoginModal(t);u.onError("ERROR.CRYPTO_UNKNOWN_ERROR")(n)}))},e.logout=function(n){return!(n=n||{}).force&&e.profilePopover?e.profilePopover.hide().then((function(){return n.force=!0,e.logout(n)})):n.askConfirm?u.alert.confirm("CONFIRM.LOGOUT").then((function(t){if(t)return n.askConfirm=!1,e.logout(n)})):(u.loading.show(),p.logout().then((function(){return i.isOpenLeft()&&i.toggleLeft(),s.clearHistory(),s.clearCache().then((function(){return e.showHome()}))})).catch(u.onError()))},e.isUserPubkey=function(e){return p.isUserPubkey(e)},p.api.data.on.login(e,(function(n,t){return e.login=!0,t?t.resolve():a.when()})),p.api.data.on.logout(e,(function(){e.login=!1})),e.showTransferModal=function(e){},e.showAboutModal=function(){return E.showAbout()},e.showJoinModal=function(){return e.closeProfilePopover(),E.showJoin()},e.showSettings=function(){return e.closeProfilePopover(),t.go("app.settings")},e.showHelpModal=function(e){return E.showHelp(e)},e.showProfilePopover=function(n){return u.popover.show(n,{templateUrl:"templates/common/popover_profile.html",scope:e,autoremove:!0,afterShow:function(n){e.profilePopover=n,o((function(){u.ink({selector:"#profile-popover .ink, #profile-popover .ink-dark"})}),100)}})},e.closeProfilePopover=function(){e.profilePopover&&e.profilePopover.isShown()&&o((function(){e.profilePopover.hide()}))},e.showPeerInfoPopover=function(n){return u.popover.show(n,{templateUrl:"templates/network/popover_peer_info.html",autoremove:!0,scope:e.$new(!0)})},e.openLink=function(e,n,t){return e.stopPropagation(),e.preventDefault(),(t=t||{}).onError=function(){return u.popover.copy(e,n)},b.uri.open(n,t),!1},e.showFab=function(e,n){u.motion.toggleOn({selector:"#"+e+".button-fab"},n)},e.hideFab=function(e,n){u.motion.toggleOff({selector:"#"+e+".button-fab"},n)},e.doMotion=function(n){return e.motion.show(n)},e.askFullscreen=function(){if(!e.fullscreen&&u.screen.isSmall()&&m.isWeb())return u.alert.confirm("CONFIRM.FULLSCREEN",null,{cancelText:"COMMON.BTN_NO",okText:"COMMON.BTN_YES"}).then((function(n){n&&e.toggleFullscreen()}))},e.toggleFullscreen=function(){e.fullscreen=!u.screen.fullscreen.isEnabled(),u.screen.fullscreen.toggleAll()},e.askFullscreen()}function i(e,n,t,i,a,o,s,r,l){e.loading=!0,e.locales=angular.copy(l.locales),e.bgImage=function(){var e;if(Math.random()<.5)e="service";else{var n=moment().format("D"),t=moment().format("M");e=t<3||3==t&&n<21||12==t&&n>=21?"winter":3==t&&n>=21||t<6||6==t&&n<21?"spring":6==t&&n>=21||t<9||9==t&&n<21?"summer":"autumn"}var i={service:12,spring:7,summer:11,autumn:7,winter:5}[e],a=Math.floor(Math.random()*i)+1;return"./img/bg/{0}-{1}.jpg".format(e,a)}(),e.enter=function(t,a){ionic.Platform.isIOS()&&window.StatusBar&&(StatusBar.overlaysWebView(!1),StatusBar.overlaysWebView(!0)),a&&a.stateParams&&a.stateParams.error?(e.error=a.stateParams.error,e.node=r.data.node,e.loading=!1,i.nextViewOptions({disableAnimate:!0,disableBack:!0,historyRoot:!0}),n.go("app.home",{error:void 0},{reload:!1,inherit:!0,notify:!1})):s.ready().then((function(){e.loading=!1})).catch((function(n){e.node=r.data.node,e.loading=!1,e.error=n}))},e.$on("$ionicView.enter",e.enter),e.reload=function(){e.loading=!0,delete e.error,t(e.enter,200)},e.doQuickFix=function(e){"settings"===e&&(i.nextViewOptions({historyRoot:!0}),n.go("app.settings"))},e.changeLanguage=function(n){a.use(n),e.hideLocalesPopover(),l.data.locale=_.findWhere(e.locales,{id:n})},e.showLocalesPopover=function(n){o.popover.show(n,{templateUrl:"templates/api/locales_popover.html",scope:e,autoremove:!0,afterShow:function(n){e.localesPopover=n}})},e.hideLocalesPopover=function(){e.localesPopover&&(e.localesPopover.hide(),e.localesPopover=null)}}function a(e,n){e((function(){n.showJoin()}),100)}function o(e,n,t,i,a,o,s,r,l){e.formData={pseudo:""},e.slides={slider:null,options:{loop:!1,effect:"slide",speed:500}},e.isLastSlide=!1,e.search={looking:!0},e.showUsername=!1,e.showPassword=!1,e.smallscreen=t.screen.isSmall(),e.userIdPattern=l.constants.regex.USER_ID,e.slidePrev=function(){e.slides.slider.unlockSwipes(),e.slides.slider.slidePrev(),e.slides.slider.lockSwipes(),e.isLastSlide=!1},e.slideNext=function(){e.slides.slider.unlockSwipes(),e.slides.slider.slideNext(),e.slides.slider.lockSwipes(),e.isLastSlide=4===e.slides.slider.activeIndex},e.showAccountPubkey=function(){e.formData.computing=!0,i.scryptKeypair(e.formData.username,e.formData.password).then((function(n){e.formData.pubkey=i.util.encode_base58(n.signPk),e.formData.computing=!1})).catch((function(n){e.formData.computing=!1,console.error(">>>>>>>",n),t.alert.error("ERROR.CRYPTO_UNKNOWN_ERROR")}))},e.formDataChanged=function(){e.formData.computing=!1,e.formData.pubkey=null},e.doNext=function(n){if(console.debug("[join] form "+n+" OK. index="+e.slides.slider.activeIndex),n||(n=1===e.slides.slider.activeIndex?"passwordForm":2===e.slides.slider.activeIndex?"pseudoForm":n),n){if(e[n].$submitted=!0,!e[n].$valid)return;"passwordForm"===n?(e.slideNext(),e.showAccountPubkey()):(e.slideNext(),"pseudoForm"===n&&e.showAccountPubkey())}},e.doNewAccount=function(i){if(!i)return t.alert.confirm("ACCOUNT.NEW.CONFIRMATION_WALLET_ACCOUNT").then((function(n){n&&e.doNewAccount(!0)}));t.loading.show(),s.login(e.formData.username,e.formData.password).then((function(t){e.closeModal(),a.data.wallet=a.data.wallet||{},a.data.wallet.alertIfUnusedWallet=!1,r.setDefaultProfile({title:e.formData.pseudo}),n.go("app.view_wallet")})).catch((function(e){t.loading.hide(),console.error(">>>>>>>",e),t.alert.error("ERROR.CRYPTO_UNKNOWN_ERROR")}))},e.showHelpModal=function(n){n||(n=1==e.slides.slider.activeIndex?"join-salt":2==e.slides.slider.activeIndex?"join-password":"join-pseudo"),o.showHelp({anchor:n})}}function s(e,n,t,i,a,o,s){e.computing=!1,e.pubkey=null,e.formData={rememberMe:o.data.rememberMe},e.showSalt=o.data.showLoginSalt,e.showPubkeyButton=!1,e.autoComputePubkey=!1,s.ready().then((function(){e.autoComputePubkey="a"===ionic.Platform.grade.toLowerCase()&&!i.screen.isSmall()})),e.doLogin=function(){e.form.$valid&&(i.loading.show(),e.closeModal(e.formData))},e.formDataChanged=function(){e.computing=!1,e.pubkey=null,e.autoComputePubkey&&e.formData.username&&e.formData.password?e.showPubkey():e.showPubkeyButton=e.formData.username&&e.formData.password},e.$watch("formData.username",e.formDataChanged,!0),e.$watch("formData.password",e.formDataChanged,!0),e.showPubkey=function(){e.computing=!0,e.showPubkeyButton=!1,e.pubkey="",n((function(){var n=e.formData.username,a=e.formData.password;t.scryptKeypair(n,a).then((function(i){n!==e.formData.username||a!==e.formData.password?e.showPubkey():(e.pubkey=t.util.encode_base58(i.signPk),e.computing=!1)})).catch((function(n){e.pubkey="",e.computing=!1,i.loading.hide(),console.error(">>>>>>>",n),i.alert.error("ERROR.CRYPTO_UNKNOWN_ERROR")}))}),500)},e.showJoinModal=function(){e.closeModal(),n((function(){a.showJoin()}),300)},e.showAccountSecurityModal=function(){e.closeModal(),n((function(){a.showAccountSecurity()}),300)}}function r(e,n,t,i,a){e.$on("$ionicView.enter",(function(o){e.locale=a.data.locale.id,n.stateParams&&n.stateParams.anchor&&t((function(){i(n.stateParams.anchor)}),100)}))}function l(e,n,t,i,a){e.locale=i.data.locale.id,a&&a.anchor&&n((function(){t(a.anchor)}),100)}function c(e,n,t,i,a,o,s,r,l,c,u,d,p,m){e.tour=!1,e.continue=!0,e.executeStep=function(n,t,i){if((i=angular.isDefined(i)?i:0)>=t.length)return s.when(!0);var a=t[i];if("function"!=typeof a)throw new Error("[helptip] Invalid step at index {0} of '{1}' tour: step must be a function".format(i,n));var o=a();return"boolean"==typeof o&&(o=s.when(o)),o.then((function(a){return angular.isUndefined(a)?(e.continue=!1,i):a&&i!==t.length-1?e.executeStep(n,t,i+1):a?-1:i+1})).catch((function(t){return t&&"transition prevented"==t.message?console.error("ERROR: in help tour [{0}], in step [{1}] -> use large if exists, to prevent [transition prevented] error".format(n,i)):console.error("ERROR: in help tour [{0}], in step [{1}] : {2}".format(n,i,t)),e.continue=!1,i}))},e.showHelpTip=function(n,t){return(t=t||{}).bindings=t.bindings||{},t.bindings.value=t.bindings.value||"",t.bindings.hasNext=!angular.isDefined(t.bindings.hasNext)||t.bindings.hasNext,t.timeout=t.timeout||(p.enable?900:500),t.autoremove=!0,t.bindings.tour=e.tour,t.backdropClickToClose=!e.tour,l.popover.helptip(n,t)},e.showHelpModal=function(e){Modals.showHelp({anchor:e})},e.startHelpTour=function(){return e.tour=!0,e.continue=!0,e.startCurrencyTour(0,!0).then((function(n){return!(!n||e.cancelled)&&(u.data.helptip.currency=n,u.store(),e.continue)})).then((function(n){return!!n&&e.startNetworkTour(0,!0).then((function(n){return!(!n||e.cancelled)&&(u.data.helptip.network=n,u.store(),e.continue)}))})).then((function(n){return!!n&&e.startWotTour(0,!0).then((function(n){return!(!n||e.cancelled)&&(u.data.helptip.wot=n,u.store(),e.continue)}))})).then((function(n){return!!n&&e.startWotCertTour(0,!0).then((function(n){return!!n&&(u.data.helptip.wotCerts=n,u.store(),e.continue)}))})).then((function(n){return!!n&&e.startWalletNoLoginTour(0,!0)})).then((function(n){return!!n&&(!m.isLogin()||e.startWalletTour(0,!0).then((function(n){return!!n&&(u.data.helptip.wallet=n,u.store(),e.continue)})))})).then((function(n){return!!n&&(!m.isLogin()||e.startWalletCertTour(0,!0).then((function(n){return!!n&&(u.data.helptip.walletCerts=n,u.store(),e.continue)})))})).then((function(n){return!!n&&(!m.isLogin()||e.startTxTour(0,!0).then((function(n){return!!n&&(u.data.helptip.tx=n,u.store(),e.continue)})))})).then((function(n){return!!n&&e.startHeaderTour(0,!0)})).then((function(n){return!!n&&e.startSettingsTour(0,!0)})).then((function(n){return!!n&&e.finishTour()}))},e.startCurrencyTour=function(n,i){var o,s=[function(){return a.toggleLeft(!0),e.showHelpTip("helptip-menu-btn-currency",{bindings:{content:"HELP.TIP.MENU_BTN_CURRENCY",icon:{position:"left"}}})},function(){return a.isOpen()&&a.toggleLeft(!1),t.go(l.screen.isSmall()?"app.currency":"app.currency_view_lg").then((function(){return e.showHelpTip("helptip-currency-mass-member",{bindings:{content:"HELP.TIP.CURRENCY_MASS",icon:{position:"center"}}})}))},function(){return!u.data.useRelative||e.showHelpTip("helptip-currency-mass-member-unit",{bindings:{content:"HELP.TIP.CURRENCY_UNIT_RELATIVE",contentParams:o,icon:{position:l.screen.isSmall()?"right":"center"}}})},function(){return!u.data.useRelative||e.showHelpTip("helptip-currency-change-unit",{bindings:{content:"HELP.TIP.CURRENCY_CHANGE_UNIT",contentParams:o,icon:{position:l.screen.isSmall()?"right":"center"}}})},function(){return!!u.data.useRelative||e.showHelpTip("helptip-currency-change-unit",{bindings:{content:"HELP.TIP.CURRENCY_CHANGE_UNIT_TO_RELATIVE",contentParams:o,icon:{position:l.screen.isSmall()?"right":"center"}}})},function(){return l.screen.isSmall()&&r("helptip-currency-rules-anchor"),e.showHelpTip("helptip-currency-rules",{bindings:{content:"HELP.TIP.CURRENCY_RULES",icon:{position:"center",glyph:"ion-information-circled"}}})},function(){return t.is("app.currency.tab_parameters")&&t.go("app.currency.tab_wot"),e.showHelpTip("helptip-currency-newcomers",{bindings:{content:"HELP.TIP.CURRENCY_WOT",icon:{position:"center"}},timeout:1200})}];return d.default().then((function(t){return o=t.parameters,e.executeStep("currency",s,n)}))},e.startNetworkTour=function(n,s){var r=function(){t.is("app.currency")&&o((function(){var e=i.document.querySelectorAll("ion-tabs .tabs a");e&&3==e.length&&angular.element(e[2]).triggerHandler("click")}),100)},p=[function(){return!!l.screen.isSmall()||(a.toggleLeft(!0),e.showHelpTip("helptip-menu-btn-network",{bindings:{content:"HELP.TIP.MENU_BTN_NETWORK",icon:{position:"left"}}}))},function(){return a.isOpen()&&a.toggleLeft(!1),t.go(l.screen.isSmall()?"app.currency.tab_network":"app.network").then((function(){return r(),e.showHelpTip("helptip-network-peers",{bindings:{content:"HELP.TIP.NETWORK_BLOCKCHAIN",icon:{position:"center",glyph:"ion-information-circled"}},timeout:1200})}))},function(){return r(),e.showHelpTip("helptip-network-peer-0",{bindings:{content:"HELP.TIP.NETWORK_PEERS",icon:{position:l.screen.isSmall()?void 0:"center"}},timeout:1e3,retry:20})},function(){return r(),e.showHelpTip("helptip-network-peer-0-block",{bindings:{content:"HELP.TIP.NETWORK_PEERS_BLOCK_NUMBER",icon:{position:l.screen.isSmall()?void 0:"center"}}})},function(){r();var n=u.data.locale.id;return e.showHelpTip("helptip-network-peers",{bindings:{content:"HELP.TIP.NETWORK_PEERS_PARTICIPATE",contentParams:{installDocUrl:c.helptip&&c.helptip.installDocUrl?c.helptip.installDocUrl[n]?c.helptip.installDocUrl[n]:c.helptip.installDocUrl:"http://duniter.org"},icon:{position:"center",glyph:"ion-information-circled"},hasNext:s}})}];return d.default().then((function(t){return t.parameters,e.executeStep("network",p,n)}))},e.startWotTour=function(s,r){var c,u=[function(){return a.toggleLeft(!0),e.showHelpTip("helptip-menu-btn-wot",{bindings:{content:"HELP.TIP.MENU_BTN_WOT",icon:{position:"left"}},onError:"continue"})},function(){return a.isOpen()&&a.toggleLeft(!1),t.go("app.wot_lookup").then((function(){return e.showHelpTip("helptip-wot-search-text",{bindings:{content:l.screen.isSmall()?"HELP.TIP.WOT_SEARCH_TEXT_XS":"HELP.TIP.WOT_SEARCH_TEXT",icon:{position:"center"}}})}))},function(){return e.showHelpTip("helptip-wot-search-result-0",{bindings:{content:"HELP.TIP.WOT_SEARCH_RESULT",icon:{position:"center"}},timeout:700,retry:15})},function(){var n=i.document.getElementById("helptip-wot-search-result-0");return!n||(o((function(){angular.element(n).triggerHandler("click")})),e.showHelpTip("helptip-wot-view-certifications",{bindings:{content:"HELP.TIP.WOT_VIEW_CERTIFICATIONS"},timeout:2500}))},function(){return e.showHelpTip("helptip-wot-view-certifications",{bindings:{content:"HELP.TIP.WOT_VIEW_CERTIFICATIONS_COUNT",contentParams:c,icon:{position:"center",glyph:"ion-information-circled"}}})},function(){return e.showHelpTip("helptip-wot-view-certifications-count",{bindings:{content:"HELP.TIP.WOT_VIEW_CERTIFICATIONS_CLICK",icon:{position:"center"},hasNext:r}})}];return d.default().then((function(t){return(c=t.parameters).currentUD=n.walletData.currentUD,e.executeStep("wot",u,s)}))},e.startWotCertTour=function(n,a){var s=[function(){if(t.is("app.wot_identity")){var n=i.document.getElementById("helptip-wot-view-certifications");if(!n)return!0;o((function(){angular.element(n).triggerHandler("click")}))}return e.showHelpTip(l.screen.isSmall()?"fab-certify":"helptip-certs-certify",{bindings:{content:"HELP.TIP.WOT_VIEW_CERTIFY",icon:{position:l.screen.isSmall()?"bottom-right":"center"}},timeout:l.screen.isSmall()?2e3:1e3,retry:10})},function(){return e.showHelpTip(l.screen.isSmall()?"fab-certify":"helptip-certs-certify",{bindings:{content:"HELP.TIP.CERTIFY_RULES",icon:{position:"center",glyph:"ion-alert-circled"},hasNext:a}})}];return e.executeStep("certs",s,n)},e.startWalletNoLoginTour=function(t,i){if(m.isLogin())return s.when(!0);var o=[function(){return a.toggleLeft(!0),e.showHelpTip("helptip-menu-btn-account",{bindings:{content:n.walletData.isMember?"HELP.TIP.MENU_BTN_ACCOUNT_MEMBER":"HELP.TIP.MENU_BTN_ACCOUNT",icon:{position:"left"},hasNext:i}})}];return e.executeStep("wallet-no-login",o,t)},e.startWalletTour=function(i,o){if(!m.isLogin())return s.when(!0);var c=[function(){return a.toggleLeft(!0),e.showHelpTip("helptip-menu-btn-account",{bindings:{content:n.walletData.isMember?"HELP.TIP.MENU_BTN_ACCOUNT_MEMBER":"HELP.TIP.MENU_BTN_ACCOUNT",icon:{position:"left"}}})},function(){return a.isOpen()&&a.toggleLeft(!1),t.go("app.view_wallet").then((function(){return e.showHelpTip(l.screen.isSmall()?"helptip-wallet-options-xs":"helptip-wallet-options",{bindings:{content:"HELP.TIP.WALLET_OPTIONS",icon:{position:l.screen.isSmall()?"right":"center"}}})}))},function(){return r("helptip-wallet-pubkey"),e.showHelpTip("helptip-wallet-pubkey",{bindings:{content:"HELP.TIP.WALLET_PUBKEY",icon:{position:"bottom-center"}},timeout:l.screen.isSmall()?2e3:500,retry:10})},function(){return r("helptip-wallet-certifications"),e.showHelpTip("helptip-wallet-certifications",{bindings:{content:l.screen.isSmall()?"HELP.TIP.WALLET_RECEIVED_CERTIFICATIONS":"HELP.TIP.WALLET_CERTIFICATIONS",icon:{position:"center"}},timeout:500,onError:"continue",hasNext:o})}];return d.default().then((function(t){return t.parameters.currentUD=n.walletData.currentUD,e.executeStep("wallet",c,i)}))},e.startWalletCertTour=function(n,a){if(!m.isLogin())return s.when(!0);var r=!1,c=[function(){if(t.is("app.view_wallet")){var n=i.document.getElementById("helptip-wallet-certifications");if(!n)return r=!0,!0;o((function(){angular.element(n).triggerHandler("click")}))}return!l.screen.isSmall()||e.showHelpTip("helptip-received-certs",{bindings:{content:"HELP.TIP.WALLET_RECEIVED_CERTS"}})},function(){return!(!r&&l.screen.isSmall())||t.go("app.view_wallet").then((function(){return e.showHelpTip("helptip-wallet-given-certifications",{bindings:{content:"HELP.TIP.WALLET_GIVEN_CERTIFICATIONS",icon:{position:"center"}},timeout:500})}))},function(){if(r)return!0;if(t.is("app.view_wallet")){var n=i.document.getElementById("helptip-wallet-given-certifications");if(!n)return r=!0,!0;o((function(){angular.element(n).triggerHandler("click")}),500)}return e.showHelpTip(l.screen.isSmall()?"fab-select-certify":"helptip-certs-select-certify",{bindings:{content:"HELP.TIP.WALLET_CERTIFY",icon:{position:l.screen.isSmall()?"bottom-right":"center"}},timeout:l.screen.isSmall()?2e3:500,retry:10})},function(){return e.tour||r?a:e.showHelpTip("helptip-certs-stock",{bindings:{content:"HELP.TIP.CERTIFY_RULES",icon:{position:"center",glyph:"ion-alert-circled"},hasNext:a}})}];return d.default().then((function(t){return t.parameters,e.executeStep("certs",c,n)}))},e.startTxTour=function(i,o){if(!m.isLogin())return s.when(!0);var r,l=[function(){return a.toggleLeft(!0),e.showHelpTip("helptip-menu-btn-tx",{bindings:{content:n.walletData.isMember?"HELP.TIP.MENU_BTN_TX_MEMBER":"HELP.TIP.MENU_BTN_TX",icon:{position:"left"}}})},function(){return a.isOpen()&&a.toggleLeft(!1),t.go("app.view_wallet_tx").then((function(){return e.showHelpTip("helptip-wallet-balance",{bindings:{content:u.data.useRelative?"HELP.TIP.WALLET_BALANCE_RELATIVE":"HELP.TIP.WALLET_BALANCE",contentParams:r,icon:{position:"center"}},retry:20})}))},function(){return e.showHelpTip("helptip-wallet-balance",{bindings:{content:"HELP.TIP.WALLET_BALANCE_CHANGE_UNIT",contentParams:r,icon:{position:"center",glyph:"ion-information-circled"}}})}];return d.default().then((function(t){return(r=t.parameters).currentUD=n.walletData.currentUD,e.executeStep("tx",l,i)}))},e.startHeaderTour=function(n,t){if(l.screen.isSmall())return s.when(!0);function r(){var e=i.document.querySelectorAll("#helptip-header-bar-btn-profile");return e&&e.length?_.find(e,(function(e){return e.offsetWidth>0})):null}var c=[function(){if(l.screen.isSmall())return!0;var n=r();return!n||e.showHelpTip(n,{bindings:{content:"HELP.TIP.HEADER_BAR_BTN_PROFILE",icon:{position:"right"}}})},function(){if(l.screen.isSmall())return a.toggleLeft(!0),e.showHelpTip("helptip-menu-btn-settings",{bindings:{content:"HELP.TIP.MENU_BTN_SETTINGS",icon:{position:"left"},hasNext:t},timeout:1e3});var n=r();return!n||(o((function(){angular.element(n).triggerHandler("click")})),e.showHelpTip("helptip-popover-profile-btn-settings",{bindings:{content:"HELP.TIP.MENU_BTN_SETTINGS",icon:{position:"center"},hasNext:t},timeout:1e3}).then((function(n){return e.closeProfilePopover(),n})))}];return e.executeStep("header",c,n)},e.startSettingsTour=function(n,i){var o,s=[function(){return!l.screen.isSmall()||(a.toggleLeft(!0),e.showHelpTip("helptip-menu-btn-settings",{bindings:{content:"HELP.TIP.MENU_BTN_SETTINGS",icon:{position:"left"}},timeout:1e3}))},function(){return a.isOpen()&&a.toggleLeft(!1),t.go("app.settings").then((function(){return e.showHelpTip("helptip-settings-btn-unit-relative",{bindings:{content:"HELP.TIP.SETTINGS_CHANGE_UNIT",contentParams:o,icon:{position:"right",style:"margin-right: 60px"},hasNext:i},timeout:1e3})}))}];return d.default().then((function(t){return o=t.parameters,e.executeStep("settings",s,n)}))},e.finishTour=function(){return a.isOpen()&&a.toggleLeft(!1),m.isLogin()?t.go("app.view_wallet").then((function(){return e.showHelpTip("helptip-wallet-certifications",{bindings:{content:"HELP.TIP.END_LOGIN",hasNext:!1}})})):s.all([e.showHome(),d.default().then((function(e){n=e}))]).then((function(){return e.showHelpTip("helptip-home-logo",{bindings:{content:"HELP.TIP.END_NOT_LOGIN",contentParams:n,hasNext:!1}})}));var n}}function u(e){e.$on("$ionicView.enter",(function(n,t){e.startHelpTour()}))}function d(e,n,t,i,a,o,s,r,l,c,u,d){e.loading=!0,e.settings=u.data,e.likeData={views:{},likes:{},follows:{},abuses:{},stars:{}},e.$on("$ionicView.enter",(function(n,t){e.loading?e.loadWallet().then((function(n){e.formData=n,e.loading=!1,e.updateView(),o.loading.hide()})).catch((function(n){"CANCELLED"===n&&e.showHome()})):e.updateView(),e.$broadcast("$recordView.enter",t)})),e.updateView=function(){e.motion.show({selector:"#wallet .item"}),e.$broadcast("$$rebind::rebind")},e.$watchCollection("formData.events",(function(n,t){!t||e.loading||angular.equals(n,t)||e.updateView()})),e.setRegisterForm=function(n){e.registerForm=n},e.onWalletLogout=function(){delete e.qrcode,delete e.formData,e.loading=!0},s.api.data.on.logout(e,e.onWalletLogout),e.showUidPopup=function(){return n((function(n,i){r(["ACCOUNT.NEW.TITLE","ACCOUNT.POPUP_REGISTER.TITLE","ACCOUNT.POPUP_REGISTER.HELP","COMMON.BTN_OK","COMMON.BTN_CANCEL"]).then((function(i){e.formData.newUid=e.formData.uid?""+e.formData.uid:"",t.show({templateUrl:"templates/wallet/popup_register.html",title:i["ACCOUNT.POPUP_REGISTER.TITLE"],subTitle:i["ACCOUNT.POPUP_REGISTER.HELP"],scope:e,buttons:[{text:i["COMMON.BTN_CANCEL"]},{text:i["COMMON.BTN_OK"],type:"button-positive",onTap:function(n){if(e.registerForm.$submitted=!0,e.registerForm.$valid&&e.formData.newUid)return e.formData.newUid;n.preventDefault()}}]}).then((function(t){if(!t)return delete e.formData.uid,void o.loading.hide();n(t)}))}))}))},e.self=function(){return e.hideActionsPopover(),e.showUidPopup().then((function(n){return o.loading.show(),s.self(n).then((function(){e.updateView(),o.loading.hide()})).catch((function(n){o.onError("ERROR.SEND_IDENTITY_FAILED")(n).then((function(){e.self()}))}))}))},e.doMembershipIn=function(n){return s.membership.inside().then((function(){e.updateView(),o.loading.hide()})).catch((function(t){!n||n<=2?i((function(){e.doMembershipIn(n?n+1:1)}),1e3):o.onError("ERROR.SEND_MEMBERSHIP_IN_FAILED")(t).then((function(){e.membershipIn()}))}))},e.membershipIn=function(){return e.hideActionsPopover(),e.formData.isMember?o.alert.info("INFO.NOT_NEED_MEMBERSHIP"):e.showUidPopup().then((function(n){o.loading.show(),e.formData.blockUid&&n==e.formData.uid?e.doMembershipIn():(e.formData.blockUid=null,e.formData.uid=n,s.self(n,!1).then((function(){e.doMembershipIn()})).catch((function(n){o.onError("ERROR.SEND_IDENTITY_FAILED")(n).then((function(){e.membershipIn()}))})))})).catch((function(n){o.loading.hide(),o.alert.info(n),e.membershipIn()}))},e.membershipOut=function(n,t){return e.hideActionsPopover(),n?t?(o.loading.show(),s.membership.out().then((function(){o.loading.hide(),o.toast.show("INFO.MEMBERSHIP_OUT_SENT")})).catch(o.onError("ERROR.SEND_MEMBERSHIP_OUT_FAILED"))):o.alert.confirm("CONFIRM.MEMBERSHIP_OUT_2","CONFIRM.POPUP_TITLE",{cssClass:"warning",okText:"COMMON.BTN_YES",okType:"button-assertive"}).then((function(n){n&&e.membershipOut(!0,!0)})):o.alert.confirm("CONFIRM.MEMBERSHIP_OUT","CONFIRM.POPUP_WARNING_TITLE",{cssClass:"warning",okText:"COMMON.BTN_YES",okType:"button-assertive"}).then((function(n){n&&e.membershipOut(!0)}))},e.doUpdate=function(){return console.debug("[wallet] Updating wallet..."),o.loading.show().then((function(){return s.refreshData()})).then((function(){return o.loading.hide()})).then((function(){e.updateView()})).catch(o.onError("ERROR.REFRESH_WALLET_DATA"))},e.renewMembership=function(n){return e.formData.isMember?n||e.formData.requirements.needRenew?o.alert.confirm("CONFIRM.RENEW_MEMBERSHIP").then((function(n){if(n)return o.loading.show(),e.doMembershipIn()})).catch((function(n){o.loading.hide(),o.alert.error(n).then(e.renewMembership)})):r("CONFIRM.NOT_NEED_RENEW_MEMBERSHIP",{membershipExpiresIn:e.formData.requirements.membershipExpiresIn}).then((function(e){return o.alert.confirm(e)})).then((function(n){n&&e.renewMembership(!0)})):o.alert.error("ERROR.ONLY_MEMBER_CAN_EXECUTE_THIS_ACTION")},e.fixIdentity=function(){if(e.formData.uid)return r("CONFIRM.FIX_IDENTITY",{uid:e.formData.uid}).then((function(e){return o.alert.confirm(e)})).then((function(n){if(n)return o.loading.show(),e.formData.blockUid=null,e.formData.sigDate=null,s.self(e.formData.uid)})).then((function(){return e.doMembershipIn()})).catch((function(n){o.loading.hide(),o.alert.error(n).then((function(){e.fixIdentity()}))}))},e.fixMembership=function(){if(e.formData.uid)return o.alert.confirm("CONFIRM.FIX_MEMBERSHIP").then((function(n){if(n)return o.loading.show(),e.formData.blockUid=null,e.formData.sigDate=null,Wallet.self(e.formData.uid,!1)})).then((function(){return e.doMembershipIn()})).catch((function(n){o.loading.hide(),o.alert.info(n),e.fixMembership()}))},e.doQuickFix=function(n){"renew"===n?e.renewMembership():"fixMembership"===n?e.fixMembership():"fixIdentity"===n&&e.fixIdentity()},e.showTransferModal=function(){e.walletData.balance&&e.walletData.balance>0?c.showTransfer().then((function(n){n&&(o.toast.show("INFO.TRANSFER_SENT"),e.$broadcast("$$rebind::balance"),e.motion.show({selector:".item-pending"}))})):o.alert.info("INFO.NOT_ENOUGH_CREDIT")},e.startWalletTour=function(){return e.hideActionsPopover(),e.showHelpTip(0,!0)},e.showHelpTip=function(n,t){if(n=angular.isDefined(n)?n:u.data.helptip.wallet,t=!!angular.isDefined(t)&&t,!(n<0)){var i=e.createHelptipScope(t);if(i)return i.tour=t,i.startWalletTour(n,!1).then((function(e){i.$destroy(),t||(u.data.helptip.wallet=e,u.store())}))}},e.showQRCode=function(n,t,i){e.qrcode||(e.qrcode=new QRCode(n,{text:t,width:200,height:200,correctLevel:QRCode.CorrectLevel.L}),o.motion.toggleOn({selector:"#wallet #"+n+".qrcode"},i||1100))},e.showCertifications=function(){a.go(o.screen.isSmall()?"app.wallet_cert":"app.wallet_cert_lg",{pubkey:e.formData.pubkey,uid:e.formData.name||e.formData.uid,type:"received"})},e.showGivenCertifications=function(){a.go(o.screen.isSmall()?"app.wallet_cert":"app.wallet_cert_lg",{pubkey:e.formData.pubkey,uid:e.formData.name||e.formData.uid,type:"given"})},e.showActionsPopover=function(n){e.actionsPopover?e.actionsPopover.show(n):l.fromTemplateUrl("templates/wallet/popover_actions.html",{scope:e}).then((function(t){e.actionsPopover=t,e.$on("$destroy",(function(){e.actionsPopover.remove()})),e.actionsPopover.show(n)}))},e.hideActionsPopover=function(){e.actionsPopover&&e.actionsPopover.hide()},e.showSharePopover=function(n){e.hideActionsPopover();var t=e.formData.name||e.formData.uid||e.formData.pubkey,i=d.getUrl("/user/profile/"+e.formData.pubkey+"/_share");o.screen.isSmall()&&(n=angular.element(document.querySelector("#wallet-share-anchor"))||n),o.popover.share(n,{bindings:{url:i,titleKey:"WOT.VIEW.POPOVER_SHARE_TITLE",titleValues:{title:t},postMessage:t}})},e.showSecurityModal=function(){e.hideActionsPopover(),c.showAccountSecurity()}}function p(e,n,t,i,a,o,s,r,l,c,u,d,p,m,E){e.search={text:"",loading:!0,type:null,results:[]},e._source=["issuer","title","city","time","avatar._content_type"],e.entered=!1,e.wotSearchTextId="wotSearchText",e.enableFilter=!0,e.allowMultiple=!1,e.selection=[],e.showResultLabel=!0,e.parameters={},e.enter=function(n,a){e.entered||(a.stateParams&&a.stateParams.q?(e.search.text=a.stateParams.q,t((function(){e.doSearch()}),100)):a.stateParams&&a.stateParams.hash?(e.search.text="#"+a.stateParams.hash,t((function(){e.doSearch()}),100)):t((function(){"newcomers"!==a.stateParams.type&&(r.initPhase||a.stateParams.type)||e.doGetNewcomers(0,void 0,!0)}),100),i(e.wotSearchTextId),e.entered=!0,t(s.ink,100),e.showHelpTip())},e.$on("$ionicView.enter",e.enter),e.resetWotSearch=function(){e.search={text:null,loading:!1,type:"newcomers",results:[]}},e.updateLocationHref=function(){var t={q:void 0,hash:void 0,type:void 0};if("text"===e.search.type){var i=e.search.text.trim();i.match(/^#[\wḡĞǦğàáâãäåçèéêëìíîïðòóôõöùúûüýÿ]+$/)?t.hash=i.substr(1):t.q=i}else t.type=e.search.type;o.nextViewOptions({disableAnimate:!0,disableBack:!0,historyRoot:!0}),n.go("app.wot_lookup",t,{reload:!1,inherit:!0,notify:!1})},e.doSearchText=function(){e.doSearch(),e.updateLocationHref()},e.doSearch=function(n,t){var i=e.search.text.trim();if(s.screen.isSmall()&&i.length<3||!i.length)return e.search.results=[],e.search.type="none",$q.when();e.search.loading=!0;var a={from:n||0,size:t||10,_source:e._source};return e.search.type="text",E.searchText(i,a).then((function(a){"text"===e.search.type&&e.search.text.trim()===i&&(a&&a.length||!d.regexp.PUBKEY.test(i)?e.doDisplayResult(a,n,t):e.doDisplayResult([{pubkey:i}]))})).catch(s.onError("ERROR.WOT_LOOKUP_FAILED"))},e.doGetNewcomers=function(n,t,i){n=n||0,(t=t||10)<10&&(t=10),e.hideActionsPopover(),e.search.loading=0===n,e.search.type="newcomers",n||i||e.updateLocationHref();var a={index:"user",type:"profile",from:n,size:t,sort:{time:"desc"}};return E.search(a).then((function(i){return"newcomers"===e.search.type&&(e.doDisplayResult(i,n,t),!0)})).catch((function(t){e.search.loading=!1,e.search.results=n>0?e.search.results:[],e.search.hasMore=!1,s.onError("ERROR.LOAD_NEWCOMERS_FAILED")(t)}))},e.showMore=function(){var n=e.search.results?e.search.results.length:0;return e.search.loadingMore=!0,("newcomers"===e.search.type?e.doGetNewcomers:e.doGetPending)(n).then((function(n){n&&(e.search.loadingMore=!1,e.$broadcast("scroll.infiniteScrollComplete"))})).catch((function(n){console.error(n),e.search.loadingMore=!1,e.search.hasMore=!1,e.$broadcast("scroll.infiniteScrollComplete")}))},e.select=function(e){p.isUserPubkey(e.pubkey)?n.go("app.view_wallet"):n.go("app.wot_identity",{pubkey:e.pubkey,uid:e.uid})},e.next=function(){alert("Selected identities:",e.selection)},e.toggleCheck=function(n,t){var i=e.search.results[n];i.checked?e.addToSelection(i):e.removeSelection(i,t)},e.toggleSelect=function(e){e.selected=!e.selected},e.addToSelection=function(n){var t=angular.copy(n);t.name&&(t.name=t.name.replace("","").replace("","")),e.selection.push(t)},e.removeSelection=function(n,t){var i=_.findWhere(e.selection,{id:n.id});if(i&&e.selection.splice(e.selection.indexOf(i),1),!e.search.loading){var a=_.findWhere(e.search.results,{id:n.id});a&&a.checked&&(a.checked=!1)}},e.scanQrCode=function(){u.barcode.enable&&u.barcode.scan().then((function(n){n&&d.uri.parse(n).then((function(t){t.pubkey?e.search.text=t.pubkey:n.uid?e.search.text=t.uid:e.search.text=n,e.doSearch()}))})).catch(s.onError("ERROR.SCAN_FAILED"))},e.showHelpTip=function(){if(e.isLogin()){var n=angular.isDefined(n)?n:c.data.helptip.wot;if(!(n<0)){0===n&&(n=1);var t=e.createHelptipScope();if(t)return t.startWotTour(n,!1).then((function(e){t.$destroy(),c.data.helptip.wot=e,c.store()}))}}},e.doDisplayResult=function(n,t,i){n=n||{},e.allowMultiple&&n.length&&e.selection.length&&_.forEach(e.selection,(function(e){var t=_.findWhere(n,{id:e.id});t&&(t.checked=!0)})),e.search.results=t?e.search.results.concat(n):n||[],e.search.loading=!1,e.search.hasMore=n.length&&e.search.results.length>=t+i,e.smallscreen=s.screen.isSmall(),e.search.results.length&&n.length>0&&e.motion&&e.motion.show({selector:".lookupForm .list .item",ink:!0})},e.showActionsPopover=function(n){e.actionsPopover?e.actionsPopover.show(n):a.fromTemplateUrl("templates/wot/lookup_popover_actions.html",{scope:e}).then((function(t){e.actionsPopover=t,e.$on("$destroy",(function(){e.actionsPopover.remove()})),e.actionsPopover.show(n)}))},e.hideActionsPopover=function(){e.actionsPopover&&e.actionsPopover.hide()}}function m(e,n,t,i){angular.extend(this,n("WotLookupCtrl",{$scope:e})),i=i||{},e.search.loading=!1,e.enableFilter=!!angular.isDefined(i.enableFilter)&&i.enableFilter,e.allowMultiple=!!angular.isDefined(i.allowMultiple)&&i.allowMultiple,e.parameters=i,e.showResultLabel=!1,e.wotSearchTextId="wotSearchTextModal",e.allowMultiple&&i.selection&&(e.selection=i.selection),e.cancel=function(){e.closeModal()},e.select=function(n){e.closeModal({pubkey:n.pubkey,uid:n.uid,name:n.name&&n.name.replace(/<\/?em>/gi,"")})},e.next=function(){e.closeModal(e.selection)},e.updateLocationHref=function(){},e.showHelpTip=function(){},t(e.wotSearchTextId)}function E(e,n,t,i,a,o,s,r,l,c,u){e.formData={hasSelf:!0},e.disableCertifyButton=!0,e.loading=!0,e.load=function(n,t,i){return c.load(n,t,i).then((function(t){if(!t)return o.onError("ERROR.IDENTITY_NOT_FOUND")().then(e.showHome);e.formData=t,e.revoked=t.requirements&&(t.requirements.revoked||t.requirements.pendingRevocation),e.canCertify=t.hasSelf&&(!u.isLogin()||!u.isUserPubkey(n))&&!e.revoked,e.canSelectAndCertify=t.hasSelf&&u.isUserPubkey(n),e.alreadyCertified=!(!e.canCertify||!u.isLogin()||!_.findWhere(t.received_cert,{pubkey:u.data.pubkey,valid:!0})&&!_.findWhere(t.received_cert_pending,{pubkey:u.data.pubkey,valid:!0})),e.disableCertifyButton=e.alreadyCertified||e.revoked,e.loading=!1})).catch((function(n){e.loading=!1,o.onError("ERROR.LOAD_IDENTITY_FAILED")(n)}))},e.removeActionParamInLocationHref=function(e){if(e&&e.stateParams&&e.stateParams.action){var n=angular.copy(e.stateParams);n.action=null,a.nextViewOptions({disableAnimate:!0,disableBack:!1,historyRoot:!1}),t.go(e.stateName,n,{reload:!1,inherit:!0,notify:!1})}},e.showSharePopover=function(n){var t=e.formData.name||e.formData.uid||e.formData.pubkey,i=r.getUrl("/user/profile/"+e.formData.pubkey+"/_share");o.screen.isSmall()&&(n=angular.element(document.querySelector("#wot-share-anchor-"+e.formData.pubkey))||n),o.popover.share(n,{bindings:{url:i,titleKey:"WOT.VIEW.POPOVER_SHARE_TITLE",titleValues:{title:t},postMessage:t}})}}function g(e,n,t,i,a,o){angular.extend(this,t("WotIdentityAbstractCtrl",{$scope:e})),e.motion=a.motion.fadeSlideInRight,e.options=e.options||{},e.options.like={kinds:["VIEW","LIKE","ABUSE","FOLLOW","STAR"],index:"user",type:"profile"},e.likeData={views:{},likes:{},follows:{},abuses:{},stars:{}},e.$on("$ionicView.enter",(function(n,t){var a=function(){e.doMotion(),t.stateParams&&t.stateParams.action&&(i((function(){e.doAction(t.stateParams.action.trim())}),100),e.removeActionParamInLocationHref(t),e.likeData.id=e.formData.pubkey)};if(t.stateParams&&t.stateParams.pubkey&&t.stateParams.pubkey.trim().length>0){if(e.loading)return e.load(t.stateParams.pubkey.trim(),!0,t.stateParams.uid).then(a)}else if(t.stateParams&&t.stateParams.uid&&t.stateParams.uid.trim().length>0){if(e.loading)return e.load(null,!0,t.stateParams.uid).then(a)}else if(o.isLogin()){if(e.loading)return e.load(o.data.pubkey,!0,o.data.uid).then(a)}else e.showHome()})),e.doMotion=function(){e.motion.show({selector:".view-identity .list .item"}),e.$broadcast("$csExtension.motion")}}function h(e,n,t,i,a,o,s,r,l,c,u,d,p,m){e.formData=angular.copy(p.data),e.popupData={},e.loading=!0,e.nodePopup={},e.bma=c,e.$on("$ionicView.enter",(function(){p.ready().then(e.load)})),e.setPopupForm=function(n){e.popupForm=n},e.load=function(){return e.loading=!0,e.locales=angular.copy(p.locales),angular.merge(e.formData,p.data),e.formData.locale=p.data.locale&&p.data.locale.id&&_.findWhere(e.locales,{id:p.data.locale.id})||_.findWhere(e.locales,{id:p.defaultSettings.locale.id}),o((function(){e.loading=!1,r.ink({selector:".item"}),e.showHelpTip()}),100)},e.reset=function(){e.actionsPopover&&e.actionsPopover.hide(),e.pendingSaving=!0,p.reset().then(m.restart).then((function(){e.load(),e.pendingSaving=!1}))},e.changeLanguage=function(e){s.use(e)},e.changeNode=function(n){var t=e.formData.node.port&&80!=e.formData.node.port&&443!=e.formData.node.port?e.formData.node.port:void 0;n=n||{host:e.formData.node.host,port:t,useSsl:angular.isDefined(e.formData.node.useSsl)?e.formData.node.useSsl:443==e.formData.node.port},e.showNodePopup(n).then((function(n){if(n.host!==e.formData.node.host||n.port!==e.formData.node.port||n.useSsl!==e.formData.node.useSsl||e.formData.node.temporary){r.loading.show();var t=c.instance(n.host,n.port,n.useSsl,!0);t.isAlive().then((function(a){return a?(r.loading.hide(),angular.merge(e.formData.node,n),delete e.formData.node.temporary,c.copy(t),e.bma=c,m.restart(),i.clearCache()):(r.loading.hide(),r.alert.error("ERROR.INVALID_NODE_SUMMARY").then((function(){e.changeNode(n)})))}))}}))},e.showNodeList=function(){var n=!!("true"===d.httpsMode||!0===d.httpsMode||"force"===d.httpsMode||t.location&&"https:"===t.location.protocol);return a._popupStack[0].responseDeferred.promise.close(),l.showNetworkLookup({enableFilter:!0,bma:!0,ssl:!!n||void 0}).then((function(e){if(e){var n=e.getBMA();return{host:n.dns?n.dns:e.hasValid4(n)?n.ipv4:n.ipv6,port:n.port||80,useSsl:n.useSsl||443==n.port}}})).then((function(n){e.changeNode(n)}))},e.showNodePopup=function(t){return n((function(n,i){e.popupData.newNode=t.port?[t.host,t.port].join(":"):t.host,e.popupData.useSsl=t.useSsl,e.popupForm&&e.popupForm.$setPristine(),s(["SETTINGS.POPUP_PEER.TITLE","COMMON.BTN_OK","COMMON.BTN_CANCEL"]).then((function(t){a.show({templateUrl:"templates/settings/popup_node.html",title:t["SETTINGS.POPUP_PEER.TITLE"],scope:e,buttons:[{text:t["COMMON.BTN_CANCEL"]},{text:t["COMMON.BTN_OK"],type:"button-positive",onTap:function(n){if(e.popupForm.$submitted=!0,e.popupForm.$valid&&e.popupForm.newNode)return{server:e.popupData.newNode,useSsl:e.popupData.useSsl};n.preventDefault()}}]}).then((function(e){if(e){var t=e.server.split(":");t[1]=t[1]?t[1]:e.useSsl?443:80,n({host:t[0],port:t[1],useSsl:e.useSsl})}else r.loading.hide()}))}))}))},e.save=function(){return e.loading||e.pendingSaving?n.when():e.saving?(e.pendingSaving=!0,o((function(){return e.pendingSaving=!1,e.save()}),500)):(e.saving=!0,o((function(){return e.cleanupHelpTip(),p.apply(e.formData),p.store()}),100).then((function(){e.saving=!1})))},e.onDataChanged=function(t,i,a){return e.loading||e.pendingSaving?n.when():e.saving?(e.pendingSaving=!0,o((function(){return e.pendingSaving=!1,e.onDataChanged(t,i,a)}),500)):void(a!==e||angular.equals(t,i)||e.save())},e.$watch("formData",e.onDataChanged,!0),e.getServer=function(){return e.formData.node&&e.formData.node.host?u.getServer(e.formData.node.host,e.formData.node.port):""},e.cleanupHelpTip=function(){if(e.formData.helptip.enable!==p.data.helptip.enable){var n=e.formData.helptip.enable;e.formData.helptip=angular.merge({},p.defaultSettings.helptip),e.formData.helptip.enable=n}},e.showActionsPopover=function(n){r.popover.show(n,{templateUrl:"templates/settings/popover_actions.html",scope:e,autoremove:!0,afterShow:function(n){e.actionsPopover=n}})},e.hideActionsPopover=function(){e.actionsPopover&&(e.actionsPopover.hide(),e.actionsPopover=null)},e.startSettingsTour=function(){return e.hideActionsPopover(),e.showHelpTip(0,!0)},e.showHelpTip=function(n,t){if((e.isLogin()||t)&&!((n=angular.isDefined(n)?n:p.data.helptip.settings)<0)){0===n&&(n=1);var i=e.createHelptipScope(t);if(i)return i.startSettingsTour(n,!1).then((function(e){i.$destroy(),p.data.helptip.settings=e,p.store()}))}}}function b(e){var n=this;Object.keys(e).forEach((function(t){n[t]=e[t]})),n.endpoints=n.endpoints||[]}function f(e,n){var t,i={user:"EVENT.USER.",page:"EVENT.PAGE.",market:"EVENT.MARKET."},a=this;function o(e){return e?e.substr(0,4)+e.substr(e.length-4):""}if(e=e||{},a.id=e.id||""+Date.now(),a.type=e.type&&e.type.toLowerCase(),a.time=e.time,a.hash=e.hash,a.read=!!e.read_signature,a.message=e.reference&&i[e.reference.index]?i[e.reference.index]+e.code:"EVENT."+e.code,a.params=e.params,n&&"function"==typeof n&&(a.markAsReadCallback=n),a.markAsRead=function(){a.markAsReadCallback&&a.markAsReadCallback(a)},e.code=e.code||"",e.code.startsWith("MEMBER_"))a.avatarIcon="ion-person",a.icon="ion-information-circled positive",a.state="app.view_wallet",a.medianTime=a.time;else if(e.code.startsWith("TX_"))a.avatarIcon="ion-card",a.icon="TX_SENT"===e.code?"ion-paper-airplane dark":"ion-archive balanced",a.medianTime=a.time,(t=e.params.length>0?e.params[0]:null)&&-1==t.indexOf(",")&&(a.pubkey=t),a.state="app.view_wallet_tx",a.stateParams={refresh:!0};else if(e.code.startsWith("CERT_"))a.avatarIcon="CERT_RECEIVED"===e.code?"ion-ribbon-b":"ion-ribbon-a",a.icon="CERT_RECEIVED"===e.code?"ion-ribbon-b balanced":"ion-ribbon-a gray",a.pubkey=e.params.length>0?e.params[0]:null,a.medianTime=a.time,a.state="app.wallet_cert",a.stateParams={type:"CERT_RECEIVED"===e.code?"received":"given"};else if(e.code.startsWith("MESSAGE_"))a.avatarIcon="ion-email",a.icon="ion-email dark",(t=e.params.length>0?e.params[0]:null)&&-1===t.indexOf(",")&&(a.pubkey=t),a.id=e.reference.id;else if(e.reference&&"user"===e.reference.index&&"profile"===e.reference.type)if(a.pubkey=e.params.length>0?e.params[0]:null,a.state="app.wot_identity",a.stateParams={pubkey:a.pubkey,uid:e.params&&e.params[3]},e.code.startsWith("LIKE_")?(a.avatarIcon="ion-person",a.icon="ion-ios-heart positive"):e.code.startsWith("STAR_")?(a.avatarIcon="ion-person",a.icon="ion-star gray"):e.code.startsWith("FOLLOW_")?(a.avatarIcon="ion-person",a.icon="ion-ios-people gray"):e.code.startsWith("ABUSE_")&&(a.avatarIcon="ion-person",a.icon="ion-android-warning assertive"),e.code.startsWith("MODERATION_")){a.state="app.wot_identity",a.stateParams={pubkey:e.reference.id,uid:e.params&&e.params[3]},a.avatarIcon="ion-alert-circled",a.icon="ion-alert-circled energized";var s=e.params&&e.params[4]||0;"MODERATION_RECEIVED"===e.code&&5==s&&(a.message="EVENT.USER.DELETION_RECEIVED",a.icon="ion-trash-a assertive")}else a.icon="ion-person dark",a.state="app.view_wallet";else e.reference&&"page"===e.reference.index?(a.pubkey=e.params.length>0?e.params[0]:null,a.avatarIcon="ion-social-buffer",e.reference.anchor?(a.icon="ion-ios-chatbubble-outline dark",a.state="app.view_page_anchor",a.stateParams={id:e.reference.id,title:e.params[1],anchor:o(e.reference.anchor)}):(a.icon="ion-social-buffer dark",a.state="app.view_page",a.stateParams={id:e.reference.id,title:e.params[1]}),e.code.startsWith("LIKE_")?(a.icon="ion-ios-heart positive",a.state="app.wot_identity",a.stateParams={pubkey:a.pubkey,uid:e.params&&e.params[3]}):e.code.startsWith("FOLLOW_")?(a.avatarIcon="ion-person",a.state="app.wot_identity",a.stateParams={pubkey:a.pubkey,uid:e.params&&e.params[3]}):e.code.startsWith("ABUSE_")?(a.icon="ion-alert-circled energized",a.state="app.wot_identity",a.stateParams={pubkey:a.pubkey,uid:e.params&&e.params[3]}):e.code.startsWith("MODERATION_")&&(a.avatarIcon="ion-alert-circled",a.icon="ion-alert-circled energized",s=e.params&&e.params[4]||0,"MODERATION_RECEIVED"===e.code&&5==s&&(a.message="EVENT.PAGE.DELETION_RECEIVED",a.icon="ion-trash-a assertive"))):e.reference&&"market"===e.reference.index?(a.avatarIcon="ion-speakerphone",a.pubkey=e.params.length>0?e.params[0]:null,e.reference.anchor?(a.icon="ion-ios-chatbubble-outline dark",a.state="app.market_view_record_anchor",a.stateParams={id:e.reference.id,title:e.params[2],anchor:o(e.reference.anchor)}):(a.icon="ion-speakerphone dark",a.state="app.market_view_record",a.stateParams={id:e.reference.id,title:e.params[2]}),e.code.startsWith("LIKE_")?a.icon="ion-ios-heart positive":e.code.startsWith("FOLLOW_")?a.avatarIcon="ion-person":e.code.startsWith("ABUSE_")?a.icon="ion-alert-circled energized":e.code.startsWith("MODERATION_")&&(a.avatarIcon="ion-alert-circled",a.icon="ion-alert-circled energized","MODERATION_RECEIVED"===e.code&&5==s&&(a.message="EVENT.MARKET.DELETION_RECEIVED",a.icon="ion-trash-a assertive"))):"INFO"===e.type?(a.avatarIcon="ion-information",a.icon="ion-information-circled positive"):"WARN"===e.type?(a.avatarIcon="ion-alert-circled",a.icon="ion-alert-circled energized"):"ERROR"===e.type&&(a.avatarIcon="ion-close",a.icon="ion-close-circled assertive");return a}function T(e,n){var t=this;t.id=e,t.message=null,t.html=null,t.issuer=null,t.time=null,t.creationTime=null,t.reply_to=null,t.replyCount=0,t.parent=null,t.replies=[],t.onRemoveListeners=[],t.copy=function(e){t.message=e.message,t.html=e.html,t.issuer=e.issuer,t.time=e.time,t.creationTime=e.creationTime||t.time,t.id=e.id||t.id,t.reply_to=e.reply_to||t.reply_to,t.uid=e.uid||t.uid,t.name=e.name||t.name,t.avatarStyle=e.avatarStyle||t.avatarStyle,e.parent&&(t.parent=e.parent),e.replies&&t.setReplies(e.replies)},t.copyFromJson=function(e){t.message=e.message,t.issuer=e.issuer,t.time=e.time,t.creationTime=e.creationTime||t.time,t.reply_to=e.reply_to},t.addOnRemoveListener=function(e){e&&"function"==typeof e&&t.onRemoveListeners.push(e)},t.cleanAllListeners=function(){t.onRemoveListeners=[]},t.setReplies=function(e){t.removeAllReplies(),t.addReplies(e)},t.addReplies=function(e){e&&e.length&&(e=e.sort((function(e,n){return e.time-n.time})),_.forEach(e,(function(e){e.parent=t,t.replies.push(e)})),t.replyCount+=e.length)},t.containsReply=function(e){return-1!=t.replies.indexOf(e)},t.addReply=function(e){t.replyCount+=1,t.replies.push(e),t.replies=t.replies.sort((function(e,n){return e.time-n.time})),e.parent=t},t.removeAllReplies=function(){if(t.replyCount){var e=t.replies.splice(0,t.replies.length);t.replyCount=0,_.forEach(e,(function(e){e.remove()}))}},t.removeReply=function(e){var n=_.findIndex(t.replies,{id:e});-1!=n&&(t.replyCount--,delete t.replies.splice(n,1)[0].parent)},t.remove=function(){t.parent&&(t.parent.removeReply(t.id),delete t.parent),t.onRemoveListeners.length&&(_.forEach(t.onRemoveListeners,(function(e){e(t)})),t.issuer=null,t.message=null,t.cleanAllListeners())},n&&"object"==typeof n&&t.copyFromJson(n)}function v(e,n,t,i){e.selectNewPicture=function(n){if(i.enable)e.openPicturePopup();else{var t=angular.element(document.querySelector(n||"#pictureFile"));t&&t.length>0&&t[0].click()}},e.openPicturePopup=function(){i.camera.getPicture().then((function(n){e.pictures.push({src:"data:image/png;base64,"+n,isnew:!0})})).catch(n.onError("ERROR.TAKE_PICTURE_FAILED"))},e.fileChanged=function(t){if(t.target.files&&t.target.files.length){n.loading.show();var i=t.target.files[0];return n.image.resizeFile(i).then((function(i){e.pictures.push({src:i,isnew:!0}),t.target.value="",n.loading.hide(100)})).catch((function(e){console.error(e),t.target.value="",n.loading.hide()}))}},e.removePicture=function(n){e.pictures.splice(n,1)},e.favoritePicture=function(n){if(n>0){var t=e.pictures[n];e.pictures.splice(n,1),e.pictures.splice(0,0,t)}},e.rotatePicture=function(t){var i=e.pictures[t];n.image.rotateSrc(i.src).then((function(e){i.src=e}))}}function O(e,n,t,i){e.loading=!0,e.allCategories=[],e.categories=[],this.searchText="",this.title=i&&i.title,e.afterLoad=function(i){e.categories=i,e.allCategories=i,e.loading=!1,t((function(){n.ink()}),10)},this.doSearch=function(){var n=this.searchText.toLowerCase().trim();n.length>1?(e.loading=!0,e.categories=e.allCategories.reduce((function(e,t){return t.parent&&-1!=t.name.toLowerCase().search(n)?e.concat(t):e}),[]),e.loading=!1):e.categories=e.allCategories},i&&i.categories?e.afterLoad(i.categories):i&&i.load&&i.load().then((function(n){e.afterLoad(n)}))}function R(e,n,t,i,a,o,s){e.loading=!0,e.defaultCommentSize=5,e.formData={},e.comments={},e.$on("$recordView.enter",(function(n,t){e.loading?e.anchor=t&&t.stateParams.anchor:e.id&&e.load(e.id,{animate:!1})})),e.$on("$recordView.load",(function(n,t,i){e.id=t||e.id,e.service=i.comment||e.service,console.debug("[ES] [comment] Will use {"+e.service.index+"} service"),e.id&&e.load(e.id).then((function(){return a((function(){e.scrollToAnchor()}),500)}))})),e.load=function(n,t){return(t=t||{}).from=t.from||0,t.size=t.size||e.anchor&&-1,t.size=t.size||e.defaultCommentSize,t.animate=!angular.isDefined(t.animate)||t.animate,t.loadAvatarAllParent=!angular.isDefined(t.loadAvatarAllParent)||t.loadAvatarAllParent,e.loading=!0,e.service.load(n,t).then((function(i){!t.animate&&i.result.length&&_.forEach(i.result,(function(e){e.isnew=!0})),e.comments=i,e.comments.hasMore=i.total>i.result.length,e.loading=!1,e.service.changes.start(n,i,e),e.motion.show({selector:".comments .item",ink:!1})}))},e.$on("$recordView.beforeLeave",(function(){if(e.comments){if(!e.service)return void console.error("[comment] Comment controller has no service ! Unable to listen changes...");e.service.changes.stop(e.comments)}})),e.scrollToAnchor=function(){if(e.anchor){var n=document.getElementsByName(e.anchor);if(!n||!n.length)return a(e.scrollToAnchor,500);for(var t=0;t0&&e[0].click()},e.fileChanged=function(n){var t=n.target.files,i=new FileReader;i.readAsDataURL(t[0]),i.onload=function(n){var t=this.result;e.$applyAsync((function(){e.formData.imgSrc=t}))}},e.doNext=function(){2==e.formData.imageCropStep?e.doCrop():3==e.formData.imageCropStep&&e.closeModal(e.formData.result)},e.doCrop=function(){e.formData.initCrop=!0},e.clear=function(){e.formData={initCrop:!1,imageCropStep:1,imgSrc:void 0,result:void 0,resultBlob:void 0}}}function A(e,n,t,i){var a=n.plugins&&n.plugins.es&&n.plugins.es.defaultCountry,o=!1;e.options=e.options||{},e.options.position=e.options.position||{showCheckbox:!0,required:!1},e.formPosition={loading:!1,enable:!!angular.isDefined(e.options.position.required)&&e.options.position.required},e.tryToLocalize=function(){if(!e.formPosition.loading&&!o){var n=e.getAddressToSearch();return n?(e.formPosition.loading=!0,t.point.searchByAddress(n).then((function(t){return t&&1==t.length?e.updateGeoPoint(t[0]):e.openSearchLocationModal({text:n,results:t||[],forceFallback:!t||!t.length})})).then((function(){e.formPosition.loading=!1})).catch((function(n){console.error(n),e.formPosition.loading=!1}))):(o=!0,t.point.current().then(e.updateGeoPoint).then((function(){o=!1})).catch((function(e){console.error(e),o=!1})))}},e.onCityChanged=function(){if(!e.loading)return e.formPosition.enable?(e.formData.geoPoint&&(e.formData.geoPoint.lat=void 0,e.formData.geoPoint.lon=void 0),e.tryToLocalize()):void 0},e.onUseGeopointChanged=function(){e.loading||(e.formPosition.enable?e.tryToLocalize():e.formData.geoPoint&&(e.formData.geoPoint.lat=void 0,e.formData.geoPoint.lon=void 0,e.dirty=!0))},e.onGeopointChanged=function(){e.loading&&(e.formPosition.enable=e.formData.geoPoint&&!!e.formData.geoPoint.lat&&!!e.formData.geoPoint.lon)},e.$watch("formData.geoPoint",e.onGeopointChanged),e.getAddressToSearch=function(){return e.formData.address&&e.formData.city?[e.formData.address.trim(),e.formData.city.trim()].join(", "):e.formData.city||e.formData.address||e.formData.location},e.updateGeoPoint=function(n){if(n&&n.lat&&n.lon&&(e.dirty=!0,e.formData.geoPoint=e.formData.geoPoint||{},e.formData.geoPoint.lat=parseFloat(n.lat),e.formData.geoPoint.lon=parseFloat(n.lon),n.address&&n.address.city)){var t=[n.address.city];n.address.postcode&&t.push(n.address.postcode),n.address.country!=a&&t.push(n.address.country),e.formData.city=t.join(", ")}},e.openSearchLocationModal=function(n){var t={text:(n=n||{}).text||e.getAddressToSearch(),results:n.results,fallbackText:n.fallbackText||e.formData.city,forceFallback:angular.isDefined(n.forceFallback)?n.forceFallback:void 0};return i.show("plugins/es/templates/common/modal_location.html","ESSearchPositionModalCtrl",t,{focusFirstInput:!0}).then(e.updateGeoPoint)}}function C(e,n,t,i,a){var o=t.plugins&&t.plugins.es&&t.plugins.es.defaultCountry,s=!1;e.geoDistanceLabels=[5,10,20,50,100,250,500].reduce((function(e,n){return e[n]={labelKey:"LOCATION.DISTANCE_OPTION",labelParams:{value:n}},e}),{}),e.geoDistances=_.keys(e.geoDistanceLabels),e.searchPosition=function(t){if(s)return n.when();s=!0;var a=t?i.point.searchByAddress(t).then((function(n){return n&&1==n.length?(n[0].exact=!0,n[0]):e.openSearchLocationModal({text:t,results:n||[],forceFallback:!n||!n.length}).then((function(e){if(e&&e.address&&e.address.city){var n=[e.address.city];e.address.postcode&&n.push(e.address.postcode),e.address.country!=o&&n.push(e.address.country),e.shortName=n.join(", ")}return e}))})):i.point.current();return a.then((function(e){if(s=!1,e&&e.lat&&e.lon)return{lat:parseFloat(e.lat),lon:parseFloat(e.lon),name:e.shortName,exact:e.exact}})).catch((function(e){console.error(e),s=!1})),a},e.openSearchLocationModal=function(n){var t={text:(n=n||{}).text||e.getAddressToSearch(),results:n.results,fallbackText:n.fallbackText||e.search.location,forceFallback:angular.isDefined(n.forceFallback)?n.forceFallback:void 0};return a.show("plugins/es/templates/common/modal_location.html","ESSearchPositionModalCtrl",t,{focusFirstInput:!0})}}function D(e,n,t,i,a,o){var s=a.plugins&&a.plugins.es&&a.plugins.es.defaultCountry,r=!1;e.locations=void 0,e.selectLocationIndex=-1,e.onKeydown=function(n){switch(n.keyCode){case 27:e.hideDropdown();break;case 13:e.locations&&e.locations.length&&e.onEnter();break;case 38:e.onArrowUpOrDown(-1),n.preventDefault();break;case 40:e.onArrowUpOrDown(1),n.preventDefault();break;case 8:case 45:case 46:break;case 37:case 39:case 16:case 17:case 35:case 36:break;default:e.showDropdown()}},e.onEnter=function(){e.selectLocationIndex>-1?e.selectLocation(e.locations[e.selectLocationIndex]):e.selectLocation(e.locations[0])},e.onArrowUpOrDown=function(n){e.locations&&(e.selectLocationIndex+=n,e.selectLocationIndex>=e.locations.length&&(e.selectLocationIndex=0),e.selectLocationIndex<0&&(e.selectLocationIndex=e.locations.length-1),_.forEach(e.locations||[],(function(n,t){n.selected=t==e.selectLocationIndex})))},e.onLocationChanged=function(){r||e.search.loading||(e.search.geoPoint=void 0,e.showDropdown())},e.showDropdown=function(){var n=e.search.location&&e.search.location.trim();if(!n||n.length<3)return e.hideDropdown(!0);var t=e.requestId&&e.requestId+1||1;return e.requestId=t,r=!0,o.point.searchByAddress(n).then((function(n){e.requestId==t&&(r=!1,e.locations=n||[],e.license=n&&n.length&&n[0].license)})).catch((function(n){throw e.hideDropdown(),n}))},e.hideDropdown=function(t){return t?(e.locations=void 0,e.selectLocationIndex=-1,e.license=void 0,void(r=!1)):n((function(){r||(e.locations=void 0,e.license=void 0,r=!1)}),500)},e.selectLocation=function(n,t){if(r=!0,n)if(e.search.geoPoint=e.search.geoPoint||{},e.search.geoPoint.lat=parseFloat(n.lat),e.search.geoPoint.lon=parseFloat(n.lon),t)e.search.geoPoint.exact=!0;else if(n&&n.address&&n.address.city){var i=[n.address.city];n.address.postcode&&i.push(n.address.postcode),n.address.country!=s&&i.push(n.address.country),e.search.location=i.join(", ")}e.hideDropdown(!0)},e.openSearchLocationModal=function(n){var t={text:(n=n||{text:e.search.location}).text||e.search.location};return i.show("plugins/es/templates/common/modal_location.html","ESSearchPositionModalCtrl",t,{focusFirstInput:!0}).then(e.selectLocation)},e.showDistancePopover=function(n){t.popover.show(n,{templateUrl:"plugins/es/templates/common/popover_distances.html",scope:e,autoremove:!0,afterShow:function(n){e.actionsPopover=n}})},e.selectDistance=function(n){e.search.geoDistance=n,e.actionsPopover&&e.actionsPopover.hide()}}function y(e,n,t,i,a){e.search={text:a.text||"",fallbackText:a.fallbackText||void 0,forceFallback:!!angular.isDefined(a.forceFallback)&&a.forceFallback,loading:!1,results:a.results||void 0},e.$on("modal.shown",(function(){e.doSearch(!0)})),e.doSearch=function(a){var o=e.search.text&&e.search.text.trim();if(!o)return n.when();e.search.loading=!0;var s=a&&e.search.fallbackText&&e.search.fallbackText.trim();return s=s&&s!=o?s:void 0,(a&&e.search.forceFallback&&e.search.results?n.when(e.search.results):i.point.searchByAddress(o)).then((function(e){return e&&e.length||!s?e:n.all([t("LOCATION.MODAL.ALTERNATIVE_RESULT_DIVIDER",{address:s}),i.point.searchByAddress(s)]).then((function(e){var n=e[0];return(e=e[1])&&e.length?[{name:n}].concat(e):e}))})).then((function(n){e.search.loading=!1,e.search.results=n||[],e.license=n&&n.length&&n[0].license})).catch((function(n){throw e.search.loading=!1,e.search.results=[],e.license=void 0,n}))}}function k(e,n,t,i,a,o,s,r){e.entered=!1,e.abuseData={},e.abuseLevels=[{value:1,label:"LOW"},{value:2,label:"LOW"}],e.staring=!1,e.options=e.options||{},e.options.like=e.options.like||{kinds:r.constants.like.KINDS,index:void 0,type:void 0,id:void 0},e.$on("$recordView.enter",(function(n,t){e.entered?e.id&&e.loadLikes(e.id):e.entered=!1})),e.$on("$recordView.load",(function(n,t){e.id=t||e.id,e.id&&e.loadLikes(e.id)})),e.initLikes=function(){if(!e.likeData)throw Error("Missing 'likeData' in scope. Cannot load likes counter");if(!e.options.like.service){if(!e.options.like.index||!e.options.like.type)throw Error("Missing 'options.like.index' or 'options.like.type' in scope. Cannot load likes counter");e.options.like.service={count:r.like.count(e.options.like.index,e.options.like.type),add:r.like.add(e.options.like.index,e.options.like.type),remove:r.like.remove(e.options.like.index,e.options.like.type),toggle:r.like.toggle(e.options.like.index,e.options.like.type)}}e.options.like.kinds||(e.options.like.kinds=_.filter(r.constants.like.KINDS,(function(n){var t=n.toLowerCase()+"s";return angular.isDefined(e.likeData[t])})))},e.loadLikes=function(t){if(!e.likeData.loading){t=t||e.likeData.id,e.initLikes();var i=e.options.like.kinds||[];if(i.length){e.likeData.loading=!0;var a=Date.now();return console.debug("[ES] Loading counter of {0}... ({1})".format(t.substring(0,8),i)),n.all(_.map(i,(function(n){var i=n.toLowerCase()+"s";return e.options.like.service.count(t,{issuer:s.isLogin()?s.data.pubkey:void 0,kind:n}).then((function(n){e.likeData[i]&&angular.merge(e.likeData[i],n)}))}))).then((function(){e.likeData.id=t,console.debug("[ES] Loading counter of {0} [OK] in {1}ms".format(t.substring(0,8),Date.now()-a)),_.contains(i,"VIEW")&&!e.canEdit&&e.markAsView(),e.$parent&&(console.debug("[ES] [likes] Adding data and functions to parent scope"),e.$parent.toggleLike=e.toggleLike,e.$parent.reportAbuse=e.reportAbuse),e.likeData.loading=!1})).catch((function(n){console.error(n&&n.message||n),e.likeData.loading=!1}))}}},e.markAsView=function(){if(e.likeData&&e.likeData.views&&!e.likeData.views.wasHit&&!(e.canEdit||e.formData&&s.isUserPubkey(e.formData.issuer))){var n=t((function(){s.isLogin()&&e.options.like.service.add(e.likeData.id,{kind:"view"}).then((function(){e.likeData.views.total=(e.likeData.views.total||0)+1})),n=null}),3e3);e.$on("$destroy",(function(){n&&t.cancel(n)}))}},e.toggleLike=function(i,a){if(e.initLikes(),!e.likeData.id)throw Error("Missing 'likeData.id' in scope. Cannot apply toggle");(a=a||{}).kind=a.kind&&a.kind.toUpperCase()||"LIKE";var r=a.kind.toLowerCase()+"s";return e.likeData[r]=e.likeData[r]||{},!0===e.likeData[r].loading||e.likeData.loading?(i.preventDefault(),n.reject()):"LIKE"===a.kind&&e.dislikes&&e.dislikes.wasHit?e.toggleLike(i,{kind:"dislike"}).then((function(){e.toggleLike(i,a)})):"DISLIKE"===a.kind&&e.likes&&e.likes.wasHit?e.toggleLike(i,{kind:"LIKE"}).then((function(){e.toggleLike(i,a)})):(e.likeData[r].loading=!0,(s.isLogin()?n.when():e.loadWallet({minData:!0})).then((function(){return e.options.like.service.toggle(e.likeData.id,a)})).then((function(n){o.loading.hide(),0!==n&&(e.likeData[r].total=(e.likeData[r].total||0)+n,e.likeData[r].wasHit=n>0),t((function(){e.likeData[r].loading=!1}),1e3)})).catch((function(n){console.error(n),e.likeData[r].loading=!1,o.loading.hide(),i.preventDefault()})))},e.setAbuseForm=function(n){e.abuseForm=n},e.showAbuseCommentPopover=function(n){return i(["COMMON.REPORT_ABUSE.TITLE","COMMON.REPORT_ABUSE.SUB_TITLE","COMMON.BTN_SEND","COMMON.BTN_CANCEL"]).then((function(n){return o.loading.hide(),a.show({templateUrl:"plugins/es/templates/common/popup_report_abuse.html",title:n["COMMON.REPORT_ABUSE.TITLE"],subTitle:n["COMMON.REPORT_ABUSE.SUB_TITLE"],cssClass:"popup-report-abuse",scope:e,buttons:[{text:n["COMMON.BTN_CANCEL"],type:"button-stable button-clear gray"},{text:n["COMMON.BTN_SEND"],type:"button button-positive ink",onTap:function(n){if(e.abuseForm.$submitted=!0,e.abuseForm.$valid&&e.abuseData.comment)return e.abuseData;n.preventDefault()}}]})})).then((function(n){if(e.abuseData={},n&&n.comment)return n;o.loading.hide()}))},e.reportAbuse=function(t,i){if(!(e.likeData&&e.likeData.abuses&&e.likeData.abuses.wasHit))return(i=i||{}).comment?(i.kind="ABUSE",e.toggleLike(t,i).then((function(){o.toast.show("COMMON.REPORT_ABUSE.CONFIRM.SENT")}))):(s.isLogin()?n.when():e.loadData({minData:!0})).then((function(){return e.showAbuseCommentPopover(t)})).then((function(n){if(n&&n.comment)return i.comment=n.comment,i.level=n.level||n.delete&&5||void 0,e.reportAbuse(t,i)}))},e.addStar=function(n){if(e.starsPopover)return e.starsPopover.hide().then((function(){e.starsPopover=null,e.addStar(n)}));if(!e.likeData.loading&&e.likeData.stars&&!e.likeData.stars.loading){if(!s.isLogin())return e.loadWallet({minData:!0}).then((function(t){if(t)return o.loading.show(),e.options.like.service.count(e.likeData.id,{issuer:t.pubkey,kind:"STAR"}).then((function(t){angular.merge(e.stars,t),e.addStar(n)}))})).catch((function(e){}));e.likeData.stars.loading=!0;var i=angular.merge({total:0,levelAvg:0,levelSum:0,level:0,wasHit:!1,wasHitId:void 0},e.likeData.stars),a=function(){i.wasHit=!0,i.level=n,i.levelAvg=Math.floor(10*(i.levelSum/i.total+.5))/10-.5,angular.merge(e.likeData.stars,i),o.loading.hide()};return i.wasHitId?(console.debug("[ES] Deleting previous star level... "+i.wasHitId),e.options.like.service.remove(i.wasHitId).catch((function(e){if(!e||404!==e.ucode)throw e})).then((function(){return console.debug("[ES] Deleting previous star level [OK]"),i.levelSum=i.levelSum-i.level+n,a(),t((function(){return console.debug("[ES] Sending new star level..."),e.options.like.service.add(e.likeData.id,{kind:"star",level:n||1})}),2e3)})).then((function(n){return i.wasHitId=n,console.debug("[ES] Star level successfully sent... "+n),o.loading.hide(),t((function(){e.likeData.stars.loading=!1}),1e3)})).catch((function(n){console.error(n&&n.message||n),e.likeData.stars.loading=!1,o.onError("MARKET.WOT.ERROR.FAILED_STAR_PROFILE")(n),e.loadLikes()}))):e.options.like.service.add(e.likeData.id,{kind:"star",level:n||1}).then((function(t){i.levelSum+=n,i.wasHitId=t,i.total+=1,a(),console.debug("[ES] Star level successfully sent... "+t),e.likeData.stars.loading=!1,o.loading.hide()})).catch((function(n){console.error(n&&n.message||n),e.likeData.stars.loading=!1,o.onError("MARKET.WOT.ERROR.FAILED_STAR_PROFILE")(n)}))}},e.removeStar=function(n){e.starsPopover&&e.starsPopover.hide(),e.likeData.loading||(e.likeData.stars.level=void 0,e.toggleLike(n,{kind:"star"}).then((function(){return t((function(){e.loadLikes()}),1e3)})))},e.showStarPopover=function(n){e.initLikes(),e.likeData.stars.loading||(angular.isUndefined(e.likeData.stars.level)&&(e.likeData.stars.level=0),o.popover.show(n,{templateUrl:"plugins/es/templates/common/popover_star.html",scope:e,autoremove:!0,afterShow:function(n){e.starsPopover=n}}))},s.api.data.on.reset(e,(function(){_.forEach(e.options.like.kinds||[],(function(n){var t=n.toLowerCase()+"s";e.likeData[t]&&(e.likeData[t].wasHit=!1,e.likeData[t].wasHitId=void 0,e.likeData[t].level=void 0)}))}),this)}function P(e,n,t){e.extensionPoint=t.extensions.points.current.get(),e.enable=n.isEnable(),n.api.state.on.changed(e,(function(n){e.enable=n,e.$broadcast("$$rebind::state")}))}function M(e,n,t){e.extensionPoint=t.extensions.points.current.get(),e.enable=n.isEnable(),n.api.state.on.changed(e,(function(n){e.enable=n}))}function w(e,n,t,i,a){e.extensionPoint=t.extensions.points.current.get(),e.enable=i.isEnable(),e.showRegistryLookupView=function(){n.go(a.screen.isSmall()?"app.registry_lookup":"app.registry_lookup_lg")},e.showNotificationsPopover=function(n){return a.popover.show(n,{templateUrl:"plugins/es/templates/notification/popover_notification.html",scope:e,autoremove:!1})},e.showMessagesPopover=function(n){return a.popover.show(n,{templateUrl:"plugins/es/templates/message/popover_message.html",scope:e,autoremove:!1})},e.showInvitationsPopover=function(n){return a.popover.show(n,{templateUrl:"plugins/es/templates/invitation/popover_invitation.html",scope:e,autoremove:!1})},i.api.state.on.changed(e,(function(n){e.enable=n}))}function U(e,n,t,i){e.updateView=function(){e.enable=i.isLogin()&&(t.data.plugins&&t.data.plugins.es?t.data.plugins.es.enable:!!t.data.plugins.host)},e.showEditUserProfile=function(){e.closeProfilePopover(),n.go("app.user_edit_profile")},t.api.data.on.changed(e,e.updateView),t.api.data.on.ready(e,e.updateView),i.api.data.on.login(e,(function(n,t){return t=t||$q.defer(),e.updateView(),t.resolve(),t.promise})),i.api.data.on.logout(e,e.updateView),e.updateView()}function x(e,n,t,i,a,o,s,r,l,c,u,d,p){e.hasWindowNotification=!!("Notification"in window),e.formData={},e.popupData={},e.loading=!0,e.enter=function(n,t){e.load()},e.$on("$ionicView.enter",e.enter),e.load=function(n){e.loading=!0;var t=e.formData.enable;e.formData=c.data.plugins&&c.data.plugins.es?angular.copy(c.data.plugins.es):{enable:!1,host:void 0,port:void 0},n&&t&&(e.formData.enable=t),e.isFallbackNode=e.formData.enable&&u.node.isFallback(),e.server=e.getServer(u),e.loading=!1},d.api.state.on.changed(e,(function(n){e.load(!0)})),e.setPopupForm=function(n){e.popupForm=n},e.changeEsNode=function(n){n=n||{host:e.formData.host,port:e.formData.port&&80!=e.formData.port&&443!=e.formData.port?e.formData.port:void 0,useSsl:angular.isDefined(e.formData.useSsl)?e.formData.useSsl:443==e.formData.port},e.showNodePopup(n).then((function(n){if(n.host!=e.formData.host||n.port!=e.formData.port||n.useSsl!=e.formData.useSsl){o.loading.show();var t=u.instance(n.host,n.port,n.useSsl);return t.isAlive().then((function(i){return i?(e.formData.host=t.host,e.formData.port=t.port,e.formData.useSsl=t.useSsl,u.copy(t)):(o.loading.hide(),o.alert.error("ERROR.INVALID_NODE_SUMMARY").then((function(){e.changeEsNode(n)})))})).then((function(){e.server=e.getServer(u),e.isFallbackNode=!1,o.loading.hide()}))}o.loading.hide()}))},e.showNodePopup=function(n){return t((function(t,s){var r=[n.host];n.port&&80!=n.port&&r.push(n.port),e.popupData.newNode=r.join(":"),e.popupData.useSsl=angular.isDefined(n.useSsl)?n.useSsl:443==n.port,e.popupForm&&e.popupForm.$setPristine(),i(["ES_SETTINGS.POPUP_PEER.TITLE","ES_SETTINGS.POPUP_PEER.HELP","COMMON.BTN_OK","COMMON.BTN_CANCEL"]).then((function(n){a.show({templateUrl:"templates/settings/popup_node.html",title:n["ES_SETTINGS.POPUP_PEER.TITLE"],subTitle:n["ES_SETTINGS.POPUP_PEER.HELP"],scope:e,buttons:[{text:n["COMMON.BTN_CANCEL"]},{text:n["COMMON.BTN_OK"],type:"button-positive",onTap:function(n){if(e.popupForm.$submitted=!0,e.popupForm.$valid&&e.popupForm.newNode)return{server:e.popupData.newNode,useSsl:e.popupData.useSsl};n.preventDefault()}}]}).then((function(e){if(e){var n=e.server.split(":");n[1]=n[1]?n[1]:e.useSsl?443:80,t({host:n[0],port:n[1],useSsl:e.useSsl})}else o.loading.hide()}))}))}))},e.showNodeList=function(){var t=!!("true"===l.httpsMode||!0===l.httpsMode||"force"===l.httpsMode||n.location&&"https:"===n.location.protocol);return a._popupStack[0].responseDeferred.promise.close(),p.showNetworkLookup({enableFilter:!0,endpoint:u.constants.ES_GCHANGE_API,ssl:!!t||void 0}).then((function(e){if(e){var n=e.getEndpoints().reduce((function(e,n){var t=u.node.parseEndPoint(n);return t?e.concat(t):e}),[]);if(n.length){var t=n[0];return{host:t.dns?t.dns:e.hasValid4(t)?t.ipv4:t.ipv6,port:t.port||80,useSsl:t.useSsl||443==t.port}}}})).then((function(n){e.changeEsNode(n)}))},e.onFormChanged=function(){e.loading||(e.formData.notifications=e.formData.notifications||{},e.hasWindowNotification&&e.formData.notifications.emitHtml5!==("granted"===window.Notification.permission)?window.Notification.requestPermission((function(n){e.formData.notifications.emitHtml5="granted"===n,e.onFormChanged()})):(e.loading=!0,c.data.plugins=c.data.plugins||{},c.data.plugins.es=c.data.plugins.es?angular.merge(c.data.plugins.es,e.formData):e.formData,delete c.data.plugins.es.newNode,c.store().then((function(){e.loading=!1}))))},e.$watch("formData",e.onFormChanged,!0),e.getServer=function(n){if((n=n||e.formData).host)return r.getServer(n.host,n.port)}}function B(e,n,t,i,a){angular.extend(this,n("ESExtensionCtrl",{$scope:e})),e.showNewPageModal=function(e){return a.showNewPage(e)}}function F(e,n,t,i,a){e.options=e.options||{},e.options.like=e.options.like||{index:"user",type:"profile",service:a.like},e.canEdit=!0,angular.extend(this,n("ESLikesCtrl",{$scope:e})),angular.extend(this,n("ESExtensionCtrl",{$scope:e})),e.$watch("formData.pubkey",(function(n){n&&e.loadLikes(n)}))}function H(e,n,t,i,a,o,s,r){e.options=e.options||{},e.options.like=e.options.like||{kinds:o.constants.like.KINDS,index:"user",type:"profile",service:s.like},e.smallscreen=angular.isDefined(e.smallscreen)?e.smallscreen:i.screen.isSmall(),angular.extend(this,n("ESLikesCtrl",{$scope:e})),angular.extend(this,n("ESExtensionCtrl",{$scope:e})),e.showNewMessageModal=function(n){return e.loadWallet({minData:!0}).then((function(){return i.loading.hide(),!(!n&&!e.formData.profile)||i.alert.confirm("MESSAGE.CONFIRM.USER_HAS_NO_PROFILE").then((function(e){if(e)return!0}))})).then((function(n){return!!n&&r.showMessageCompose({destPub:e.formData.pubkey,destUid:e.formData.name||e.formData.uid}).then((function(e){e&&i.toast.show("MESSAGE.INFO.MESSAGE_SENT")}))}))},e.$watch("formData.pubkey",(function(n){n&&e.loadLikes(n)})),e.showActionsPopover=function(n){i.popover.show(n,{templateUrl:"plugins/es/templates/wot/view_popover_actions.html",scope:e,autoremove:!0,afterShow:function(n){e.actionsPopover=n}})},e.hideActionsPopover=function(){return e.actionsPopover&&(e.actionsPopover.hide(),e.actionsPopover=null),!0},"buttons-top-fab"===e.extensionPoint&&e.$on("$csExtension.motion",(function(n){e.formData.profile&&e.showFab("fab-compose-"+e.formData.pubkey)}))}function W(e,n,t,i,a,o,s,r,l,c,u,d,p,m,E){e.formData={title:null,description:null,socials:[],geoPoint:{}},e.loading=!0,e.dirty=!1,e.walletData=null,e.avatar=null,e.existing=!1,e.socialData={url:null},e.pubkeyPattern=u.regexp.PUBKEY,e.$on("$ionicView.enter",(function(n){e.loadWallet().then((function(n){return e.load(n)})).catch((function(n){if("CANCELLED"==n)return e.close().then(c.loading.hide);c.onError("PROFILE.ERROR.LOAD_PROFILE_FAILED")(n)}))})),e.$on("$stateChangeStart",(function(n,t,i,o){if(e.dirty&&!e.saving&&(n.preventDefault(),!e.loading))return e.loading=!0,c.alert.confirm("CONFIRM.SAVE_BEFORE_LEAVE","CONFIRM.SAVE_BEFORE_LEAVE_TITLE",{cancelText:"COMMON.BTN_NO",okText:"COMMON.BTN_YES_SAVE"}).then((function(n){return e.loading=!1,n?(e.form.$submitted=!0,e.save(!1,!0).then((function(n){return n&&(e.dirty=!1),n}))):(e.dirty=!1,!0)})).then((function(e){e&&(l.nextViewOptions({historyRoot:!0}),a.go(t.name,i))})).catch((function(e){}))})),e.load=function(n){return e.loading=!0,p.get(n.pubkey,{raw:!0}).then((function(t){t?(e.avatar=d.image.fromAttachment(t.source.avatar),e.existing=!0,e.updateView(n,t.source)):(e.avatar=void 0,e.existing=!1,e.updateView(n,{})),o("profile-name")})).catch((function(e){c.loading.hide(10),c.onError("PROFILE.ERROR.LOAD_PROFILE_FAILED")(e)}))},e.setForm=function(n){e.form=n},e.updateView=function(n,t){e.walletData=n,e.formData=t,t.avatar&&(e.avatarStyle={"background-image":'url("'+e.avatar.src+'")'}),e.formData.geoPoint=e.formData.geoPoint||{},e.motion.show(),c.loading.hide(),i((function(){e.loading=!1}),1e3)},e.onFormDataChanged=function(){e.loading||(e.dirty=!0)},e.$watch("formData",e.onFormDataChanged,!0),e.save=function(a,o){if(!e.form.$valid||!n.walletData||e.saving)return t.reject();if(!o)return console.debug("[ES] [profile] Waiting debounce end, before saving..."),i((function(){return e.save(a,!0)}),650);e.saving=!0,console.debug("[ES] [profile] Saving user profile...");var r=function(n){return function(t){e.saving=!1,c.onError(n)(t)}},l=function(n){n&&(e.walletData.name=n.title,e.avatar?e.walletData.avatar=e.avatar:delete e.walletData.avatar,e.walletData.profile=angular.copy(n),e.walletData.profile.description=d.util.parseAsHtml(n.description))},u=function(){if(!a)return s("PROFILE.INFO.PROFILE_SAVED").then((function(e){c.toast.show(e)}))},m=function(t){return t.socials&&t.socials.length&&(t.socials=_.uniq(t.socials,!1,(function(e){return e.url}))),t.position&&delete t.position,t.geoPoint&&t.geoPoint.lat&&t.geoPoint.lon?(t.geoPoint.lat=parseFloat(t.geoPoint.lat),t.geoPoint.lon=parseFloat(t.geoPoint.lon)):t.geoPoint=null,e.existing?p.update(t,{id:n.walletData.pubkey}).then((function(){return console.info("[ES] Profile successfully updated."),e.saving=!1,e.dirty=!1,l(t),u(),!0})).catch(r("PROFILE.ERROR.SAVE_PROFILE_FAILED")):p.add(t).then((function(){return console.info("[ES] [profile] successfully created."),e.existing=!0,e.saving=!1,e.dirty=!1,l(t),u(),!0})).catch(r("PROFILE.ERROR.SAVE_PROFILE_FAILED"))};return e.avatar&&e.avatar.src?c.image.resizeSrc(e.avatar.src,!0).then((function(n){return e.formData.avatar=d.image.toAttachment({src:n}),m(e.formData)})):(delete e.formData.avatar,m(e.formData))},e.saveAndClose=function(){return e.save().then((function(n){n&&e.close()}))},e.submitAndSaveAndClose=function(){e.form.$submitted=!0,e.saveAndClose()},e.cancel=function(){e.dirty=!1,e.close()},e.close=function(){return a.go("app.view_wallet",{refresh:!0})},e.showAvatarModal=function(){return E.camera.enable?E.camera.getPicture().then((function(n){n&&(e.avatar={src:"data:image/png;base64,"+n},e.avatarStyle={"background-image":'url("'+n+'")'},e.dirty=!0)})).catch(c.onError("ERROR.TAKE_PICTURE_FAILED")):m.show("plugins/es/templates/common/modal_edit_avatar.html","ESAvatarModalCtrl",{}).then((function(n){n&&(e.avatar={src:n},e.avatarStyle={"background-image":'url("'+n+'")'},e.dirty=!0)}))},e.rotateAvatar=function(){if(e.avatar&&e.avatar.src&&!e.rotating)return e.rotating=!0,c.image.rotateSrc(e.avatar.src).then((function(n){e.avatar.src=n,e.avatarStyle={"background-image":'url("'+n+'")'},e.dirty=!0,e.rotating=!1})).catch((function(n){console.error(n),e.rotating=!1}))}}function V(e,n,t,i,a,o,s,r,l,c){e.loading=!0,e.messages=[],e.$on("$ionicView.enter",(function(t,a){e.loadWallet({minData:!0}).then((function(){e.entered||(e.entered=!0,e.type=a.stateParams&&a.stateParams.type||"inbox",e.load()),e.showFab("fab-add-message-record")})).catch((function(e){"CANCELLED"===e&&(i.nextViewOptions({historyRoot:!0}),n.go("app.home"))}))})),e.refresh=function(n){return e.load(void 0,void 0,n)},e.load=function(n,t,i){var a={};return a.from=t||0,a.size=n||20,a.type=e.type,e.loading=!i,c.load(a).then((function(n){e.messages=n,r.loading.hide(),e.loading=!1,n.length>0&&e.motion.show({selector:".view-messages .list .item"})})).catch((function(n){r.onError("MESSAGE.ERROR.LOAD_MESSAGES_FAILED")(n),e.messages=[],e.loading=!1}))},e.setType=function(n){e.type=n,e.load()},e.markAllAsRead=function(){e.hideActionsPopover(),e.messages&&e.messages.length&&r.alert.confirm("MESSAGE.CONFIRM.MARK_ALL_AS_READ").then((function(n){n&&c.markAllAsRead().then((function(){_.forEach(e.messages,(function(e){e.read=!0}))})).catch(r.onError("MESSAGE.ERROR.MARK_ALL_AS_READ_FAILED"))}))},e.delete=function(n){var t=e.messages[n];t&&r.alert.confirm("MESSAGE.CONFIRM.REMOVE").then((function(i){i&&c.remove(t.id,e.type).then((function(){e.messages.splice(n,1),r.toast.show("MESSAGE.INFO.MESSAGE_REMOVED")})).catch(r.onError("MESSAGE.ERROR.REMOVE_MESSAGE_FAILED"))}))},e.deleteAll=function(){e.hideActionsPopover(),e.messages&&e.messages.length&&r.alert.confirm("MESSAGE.CONFIRM.REMOVE_ALL").then((function(n){n&&c.removeAll(e.type).then((function(){e.messages.splice(0,e.messages.length),r.toast.show("MESSAGE.INFO.All_MESSAGE_REMOVED")})).catch(r.onError("MESSAGE.ERROR.REMOVE_All_MESSAGES_FAILED"))}))},e.showNewMessageModal=function(n){return e.loadWallet({minData:!0}).then((function(){return r.loading.hide(),s.showMessageCompose(n).then((function(e){e&&r.toast.show("MESSAGE.INFO.MESSAGE_SENT")}))}))},e.showReplyModal=function(n){var i=e.messages[n];i&&t("MESSAGE.REPLY_TITLE_PREFIX").then((function(e){var n=i.content?i.content.replace(/^/g," > "):null;return n=(n=n?n.replace(/\n/g,"\n > "):null)?n+"\n":null,s.showMessageCompose({destPub:i.issuer,destUid:i.name,title:e+i.title,content:n,isReply:!0})})).then((function(e){e&&r.toast.show("MESSAGE.INFO.MESSAGE_SENT")}))},e.showActionsPopover=function(n){e.actionsPopover?e.actionsPopover.show(n):a.fromTemplateUrl("plugins/es/templates/message/lookup_popover_actions.html",{scope:e}).then((function(t){e.actionsPopover=t,e.$on("$destroy",(function(){e.actionsPopover.remove()})),e.actionsPopover.show(n)}))},e.hideActionsPopover=function(){e.actionsPopover&&e.actionsPopover.hide()},e.onMessageDelete=function(n){var t=_.findIndex(e.messages,(function(e){return e.id==n}));t&&e.messages.splice(t,1)},c.api.data.on.delete(e,e.onMessageDelete),e.onNewOutboxMessage=function(n){if("outbox"==e.type)return e.loading=!0,o((function(){return c.get(n,{type:e.type,summary:!0})}),500).then((function(n){e.messages.splice(0,0,n),e.loading=!1,e.motion.show({selector:".view-messages .list .item"})})).catch((function(){e.loading=!1}))},c.api.data.on.sent(e,e.onNewOutboxMessage),e.onNewInboxMessage=function(n){if("inbox"==e.type&&e.entered)return e.loading=!0,c.get(n.id,{type:e.type,summary:!0}).then((function(n){e.messages.splice(0,0,n),e.loading=!1,e.motion.show({selector:".view-messages .list .item"})})).catch((function(){e.loading=!1}))},c.api.data.on.new(e,e.onNewInboxMessage),e.onUnauth=function(){e.messages=void 0,e.loading=!1,e.entered=!1},l.api.data.on.unauth(e,e.onUnauth)}function G(e,n,t){angular.extend(this,n("ESMessageComposeModalCtrl",{$scope:e,parameters:{}})),e.$on("$ionicView.enter",(function(n,i){i.stateParams&&(i.stateParams.pubkey&&(e.formData.destPub=i.stateParams.pubkey,i.stateParams.name?(e.destUid=i.stateParams.name,e.destPub=""):(e.destUid="",e.destPub=e.formData.destPub)),i.stateParams.title&&(e.formData.title=i.stateParams.title),i.stateParams.content&&(e.formData.content=i.stateParams.content)),e.loadWallet({minData:!0}).then((function(){t.loading.hide()})).catch((function(n){"CANCELLED"===n&&e.showHome()}))})),e.cancel=function(){e.showHome()},e.setForm=function(n){e.form=n},e.closeModal=function(){e.showHome()}}function Y(e,n,t,i,a,o,s){e.formData={title:s?s.title:null,content:s?s.content:null,destPub:s?s.destPub:null},e.destUid=s?s.destUid:null,e.destPub=s&&!s.destUid?s.destPub:null,e.isResponse=!!s&&s.isResponse,e.doSend=function(n){if(e.form.$submitted=!0,e.form.$valid){if(!(n||e.formData.content&&e.formData.content.trim().length))return t.alert.confirm("MESSAGE.COMPOSE.CONTENT_CONFIRMATION").then((function(n){n&&e.doSend(!0)}));t.loading.show();var s={issuer:i.data.pubkey,recipient:e.formData.destPub,title:e.formData.title,content:e.formData.content,time:a.date.now()};o.send(s).then((function(n){e.id=n,t.loading.hide(),e.closeModal(n)})).catch(t.onError("MESSAGE.ERROR.SEND_MSG_FAILED"))}},e.showWotLookupModal=function(){n.showWotLookup().then((function(n){n&&(n.name?(e.destUid=n.name,e.destPub=""):(e.destUid="",e.destPub=n.pubkey),e.formData.destPub=n.pubkey)}))},e.cancel=function(){e.closeModal()}}function j(e,n,t,i,a,o,s,r,l){e.formData={},e.id=null,e.loading=!0,e.$on("$ionicView.enter",(function(i,a){a.stateParams&&a.stateParams.id?(e.loading&&(e.type=a.stateParams.type||"inbox",e.load(a.stateParams.id,e.type).then((function(n){e.loading=!1,s.loading.hide(),n&&(e.id=n.id,e.formData=n,e.canDelete=!0,e.motion.show({selector:".view-message .list .item"}),n.read||t((function(){e.id===n.id&&l.markAsRead(n,e.type).then((function(){console.debug("[message] marked as read")})).catch(s.onError("MESSAGE.ERROR.MARK_AS_READ_FAILED"))}),2e3))}))),e.showFab("fab-view-message-reply")):n.go("app.user_message")})),e.load=function(t,i){return i=i||"inbox",e.loadWallet({minData:!0}).then((function(){return l.get(t,{type:i})})).catch(s.onError("MESSAGE.ERROR.LOAD_MESSAGE_FAILED")).then((function(t){return t.valid?t:s.alert.error(e.isUserPubkey(t.recipient)?"MESSAGE.ERROR.NOT_AUTHENTICATED_MESSAGE":"MESSAGE.ERROR.USER_NOT_RECIPIENT","MESSAGE.ERROR.MESSAGE_NOT_READABLE").then((function(){n.go("app.user_message",{type:i})}))}))},e.delete=function(){e.actionsPopover&&e.actionsPopover.hide(),s.alert.confirm("MESSAGE.CONFIRM.REMOVE").then((function(t){if(t)return l.remove(e.id,e.type).then((function(){a.nextViewOptions({historyRoot:!0}),n.go("app.user_message",{type:e.type}),s.toast.show("MESSAGE.INFO.MESSAGE_REMOVED")})).catch(s.onError("MESSAGE.ERROR.REMOVE_MESSAGE_FAILED"))}))},e.showActionsPopover=function(n){e.actionsPopover?e.actionsPopover.show(n):o.fromTemplateUrl("plugins/es/templates/message/view_popover_actions.html",{scope:e}).then((function(t){e.actionsPopover=t,e.$on("$destroy",(function(){e.actionsPopover.remove()})),e.actionsPopover.show(n)}))},e.hideActionsPopover=function(){e.actionsPopover&&e.actionsPopover.hide()},e.showReplyModal=function(){var n="inbox"==e.type?"issuer":"recipient";i("MESSAGE.REPLY_TITLE_PREFIX").then((function(t){var i=e.formData.content?e.formData.content.replace(/^/g," > "):null;return i=(i=i?i.replace(/\n/g,"\n > "):null)?i+"\n":null,r.showMessageCompose({destPub:e.formData[n],destUid:e.formData.name||e.formData.uid,title:t+e.formData.title,content:i,isReply:!0})})).then((function(e){e&&s.toast.show("MESSAGE.INFO.MESSAGE_SENT").then((function(){a.goBack()}))}))}}function $(e,n,t,i,a,o,s,r){e.search={loading:!0,results:null,hasMore:!1,loadingMore:!1,limit:40},e.$on("popover.shown",(function(){e.search.loading&&e.load()})),e.load=function(t,i){var a={};return a.from=t||0,a.size=i||40,s.notifications.load(a).then((function(n){e.search.results=t?e.search.results.concat(n):n,e.search.loading=!1,e.search.hasMore=e.search.results&&e.search.results.length>=e.search.limit,e.updateView()})).catch((function(i){e.search.loading=!1,t||(e.search.results=[]),e.search.hasMore=!1,n.onError("MESSAGE.ERROR.LOAD_NOTIFICATIONS_FAILED")(i)}))},e.updateView=function(){e.motion&&e.search.results&&e.search.results.length&&e.motion.show({selector:".popover-notification .item"})},e.showMore=function(){e.search.limit=e.search.limit||40,e.search.limit=2*e.search.limit,e.search.limit<40&&(e.search.limit=40),e.search.loadingMore=!0,e.load(e.search.results.length,e.search.limit).then((function(){e.search.loadingMore=!1,e.$broadcast("scroll.infiniteScrollComplete")}))},e.onNewMessageNotification=function(n){e.search.loading||e.search.loadingMore||(e.search.results.splice(0,0,n),e.updateView())},e.select=function(n){n.read||(n.read=!0),t.go("app.user_view_message",{id:n.id,type:"inbox"}),e.closePopover(n)},e.resetData=function(){e.search.loading||(console.debug("[ES] [messages] Resetting data (settings or account may have changed)"),e.search.hasMore=!1,e.search.results=[],e.search.loading=!0,delete e.search.limit)},e.showNewMessageModal=function(t){e.closePopover(),i((function(){r.showMessageCompose(t).then((function(e){e&&n.toast.show("MESSAGE.INFO.MESSAGE_SENT")}))}),500)},a.api.data.on.logout(e,e.resetData),o.api.node.on.stop(e,e.resetData),o.api.node.on.start(e,e.load),s.api.data.on.new(e,e.onNewMessageNotification)}function K(e,n,t,i,a,o,s,r,l,c){e.search={loading:!0,results:null,hasMore:!1,loadingMore:!1,limit:40,options:{codes:{excludes:c.constants.EXCLUDED_CODES}}},e.$on("$ionicView.enter",(function(){e.search.loading&&(e.load(),a((function(){e.resetUnreadCount()}),1e3))})),e.load=function(n,t){var i=angular.copy(e.search.options);return i.from=i.from||n||0,i.size=i.size||t||40,e.search.loading=!0,c.load(l.data.pubkey,i).then((function(t){n?t&&(e.search.results=e.search.results.concat(t)):e.search.results=t||[],e.search.loading=!1,e.search.hasMore=e.search.results.length>=e.search.limit,e.updateView()})).catch((function(t){e.search.loading=!1,n||(e.search.results=[]),e.search.hasMore=!1,o.onError("COMMON.NOTIFICATIONS.LOAD_NOTIFICATIONS_FAILED")(t)}))},e.updateView=function(){e.motion&&e.motion.ionListClass&&e.search.results.length&&e.motion.show({selector:".view-notification .item"})},e.markAllAsRead=function(){e.hideActionsPopover(),e.search.results.length&&o.loading.show().then((function(){n.walletData.notifications.unreadCount=0;var t=e.search.results[0];return n.walletData.notifications.readTime=t?t.time:0,_.forEach(e.search.results,(function(e){e.markAsRead&&"function"==typeof e.markAsRead&&e.markAsRead()})),o.loading.hide()}))},e.resetUnreadCount=function(){if(l.data.notifications.unreadCount&&e.search.results&&e.search.results.length){l.data.notifications.unreadCount=0;var n=e.search.results[0],t=n.time?n.time:0;!t||r.data.wallet&&r.data.wallet.notificationReadTime==t||(r.data.wallet=r.data.wallet||{},r.data.wallet.notificationReadTime=t,r.store())}},e.select=function(e){e.markAsRead&&"function"==typeof e.markAsRead&&e.markAsRead(),e.state&&i.go(e.state,e.stateParams)},e.showMore=function(){e.search.limit=e.search.limit||40,e.search.limit+=40,e.search.limit<40&&(e.search.limit=40),e.search.loadingMore=!0,e.load(e.search.results.length,e.search.limit).then((function(){e.search.loadingMore=!1,e.$broadcast("scroll.infiniteScrollComplete")}))},e.onNewNotification=function(n){if(!e.search.loading&&!e.search.loadingMore){var t=_.findIndex(e.search.results,(function(e){return n.time>e.time}));t<0&&(t=0),e.search.results.splice(t,0,n),e.updateView()}},e.resetData=function(){e.search.loading||(console.debug("[ES] [notifications] Resetting data (settings or account may have changed)"),e.search.hasMore=!1,e.search.results=[],e.search.loading=!0,delete e.search.limit)},e.showActionsPopover=function(n){e.actionsPopover?e.actionsPopover.show(n):t.fromTemplateUrl("plugins/es/templates/notification/popover_actions.html",{scope:e}).then((function(t){e.actionsPopover=t,e.$on("$destroy",(function(){e.actionsPopover.remove()})),e.actionsPopover.show(n)}))},e.hideActionsPopover=function(){e.actionsPopover&&e.actionsPopover.hide()},l.api.data.on.logout(e,e.resetData),s.api.node.on.stop(e,e.resetData),s.api.node.on.start(e,e.load),c.api.data.on.new(e,e.onNewNotification)}function q(e,n,t,i,a){angular.extend(this,t("NotificationsCtrl",{$scope:e})),e.motion=null,e.$on("popover.shown",(function(){e.search.loading&&e.load()})),e.updateView=function(){e.search.results.length&&n((function(){i.ink({selector:".popover-notification .item.ink"})}),100)},e.$on("popover.hidden",e.resetUnreadCount),e.select=function(n){n&&(n.markAsRead&&"function"==typeof n.markAsRead&&n.markAsRead(),n.state&&a.go(n.state,n.stateParams),e.closePopover(n))}}function z(e,n,t,i,a,o,s,r){var l;e.loading=!0,e.popupData={},e.search={results:[],loading:!0},e.emailFrequencies=[{id:"daily",label:"daily"},{id:"weekly",label:"weekly"}],e.enter=function(n,i){if(e.loading){if(!(l=i.stateParams&&i.stateParams.id?a.children.get(i.stateParams.id):a))return o.alert.error("ERROR.UNKNOWN_WALLET_ID"),e.showHome();e.loadWallet({wallet:l,auth:!0,minData:!0}).then((function(){return o.loading.hide(),e.load()})).then((function(){e.showFab("fab-add-subscription-record")})).catch((function(n){if("CANCELLED"===n)return o.loading.hide(10),e.loading=!0,void t.goBack();o.onError("SUBSCRIPTION.ERROR.LOAD_SUBSCRIPTIONS_FAILED")(n)}))}},e.$on("$ionicView.enter",e.enter),e.load=function(){return e.loading=!0,r.record.load(l.data.pubkey,l.data.keypair).then((function(e){var n=_.groupBy(e||[],(function(e){return[e.type,e.recipient].join("|")}));return _.keys(n).reduce((function(e,t){var i=t.split("|");return e.concat({type:i[0],recipient:i[1],items:n[t]})}),[])})).then((function(e){return i.extendAll(e,"recipient")})).then(e.updateView).catch((function(n){o.loading.hide(10),n&&404==n.ucode?(e.updateView([]),e.existing=!1):o.onError("PROFILE.ERROR.LOAD_PROFILE_FAILED")(n)}))},e.updateView=function(n){n&&(e.search.results=n),e.search.results&&e.search.results.length&&e.motion.show(),e.search.loading=!1},e.addSubscription=function(){e.showCategoryModal().then((function(n){if(n){if("email"===n.id)return e.showEmailModal();o.alert.notImplemented()}})).then((function(n){n&&(o.loading.show(),r.record.add(n,l).then(e.addToUI).then((function(){l.data.subscriptions=l.data.subscriptions||{count:0},l.data.subscriptions.count++,o.loading.hide(),e.updateView()})).catch(o.onError("SUBSCRIPTION.ERROR.ADD_SUBSCRIPTION_FAILED")))}))},e.editSubscription=function(n){var t,i=angular.copy(n);if("email"===n.type&&(t=e.showEmailModal(n)),t)return t.then((function(t){if(t)return o.loading.show(),n.id=i.id,r.record.update(n,l).then((function(){if(i.type!==n.type||i.recipient!==n.recipient)return e.removeFromUI(i),e.addToUI(n)})).then((function(){o.loading.hide(),e.updateView()})).catch(o.onError("SUBSCRIPTION.ERROR.UPDATE_SUBSCRIPTION_FAILED"))}))},e.deleteSubscription=function(n,t){if(n&&n.id){if(!t)return o.alert.confirm("SUBSCRIPTION.CONFIRM.DELETE_SUBSCRIPTION").then((function(t){if(t)return e.deleteSubscription(n,t)}));o.loading.show(),r.record.remove(n.id,{wallet:l}).then((function(){l.data.subscriptions=l.data.subscriptions||{count:1},l.data.subscriptions.count--,e.removeFromUI(n),o.loading.hide()})).catch(o.onError("SUBSCRIPTION.ERROR.DELETE_SUBSCRIPTION_FAILED"))}},e.removeFromUI=function(n){var t=_.findWhere(e.search.results,{type:n.type,recipient:n.recipient}),i=_.findIndex(t.items,n);i>=0&&t.items.splice(i,1),t.items.length||(i=_.findIndex(e.search.results,t),e.search.results.splice(i,1))},e.addToUI=function(t){e.search.results=e.search.results||[];var a=_.findWhere(e.search.results,{type:t.type,recipient:t.recipient});return a?(a.items.push(t),n.when(t)):(a={type:t.type,recipient:t.recipient,items:[]},i.extendAll([a],"recipient").then((function(){return a.items.push(t),e.search.results.push(a),t})))},e.showCategoryModal=function(){return r.category.all().then((function(e){return s.show("plugins/es/templates/common/modal_category.html","ESCategoryModalCtrl as ctrl",{categories:e},{focusFirstInput:!0})})).then((function(e){if(e&&e.parent)return e}))},e.showEmailModal=function(e){return s.show("plugins/es/templates/subscription/modal_email.html","ModalEmailSubscriptionsCtrl",e,{focusFirstInput:!0})}}function X(e,n,t,i,a,o,s){e.frequencies=[{id:"daily",label:"daily"},{id:"weekly",label:"weekly"}],e.formData=s||{},e.formData.content=e.formData.content||{},e.formData.content.frequency=e.formData.content.frequency||e.frequencies[0].id,e.recipient={},e.$on("modal.shown",(function(){return e.formData.recipient?(e.recipient={pubkey:e.formData.recipient},a.extendAll([e.recipient])):i.network.peering.self().then((function(n){if(n)return e.formData.recipient=n.pubkey,e.recipient={pubkey:e.formData.recipient},a.extendAll([e.recipient])}))})),e.doSubmit=function(){if(e.form.$submitted=!0,e.form.$valid&&e.formData.content.email&&e.formData.content.frequency){var n={type:"email",recipient:e.formData.recipient,content:{email:e.formData.content.email,locale:t.data.locale.id,frequency:e.formData.content.frequency}};e.closeModal(n)}},e.cancel=function(){e.closeModal()},e.subscriptionForm&&e.subscriptionForm.$setPristine(),e.showNetworkLookup=function(){return o.showNetworkLookup({enableFilter:!0,endpointFilter:i.constants.ES_SUBSCRIPTION_API}).then((function(n){n&&(e.recipient=n,e.formData.recipient=n.pubkey)}))}}function Q(e,n,t,i,a,o,s,r,l){e.search=e.search||{loading:!0,hasMore:!1,text:void 0,index:"invitation",type:"certification",results:[],sort:"time",asc:!1,loadingMore:!1},e.entered=!1,e.searchTextId="documentSearchText",e.ionItemClass="item-border-large",e.defaultSizeLimit=e.defaultSizeLimit||(s.screen.isSmall()?50:100),e.helptipPrefix="helptip-document",e.compactMode=!angular.isDefined(e.compactMode)||e.compactMode,e._source=e._source||["issuer","hash","time","creationTime","title","message"],e.enter=function(n,t){e.entered||(e.entered=!0,e.search.index=t.stateParams&&t.stateParams.index||e.search.index,e.search.type=t.stateParams&&t.stateParams.type||e.search.type,e.search.text=t.stateParams&&t.stateParams.q||e.search.text,e.search.last=!e.search.text,e.load()),e.expertMode=angular.isDefined(e.expertMode)?e.expertMode:!s.screen.isSmall()&&a.data.expertMode},e.$on("$ionicView.enter",e.enter),e.computeOptions=function(n,t){var i={index:e.search.index,type:e.search.type,from:n||0,size:t||e.defaultSizeLimit};return e.search.sort?(i.sort={},i.sort[e.search.sort]=e.search.asc?"asc":"desc"):i.sort={time:"desc"},i._source=i._source||e._source,i},e.load=function(n,t,i){if(!e.search.error){var a=e.computeOptions(n,t);return e.search.loading=!i,(e.search.last?l.search(a):l.searchText(e.search.text||"",a)).then((function(t){n?e.search.results=e.search.results.concat(t.hits):(e.search.results=t.hits,e.search.took=t.took),e.search.total=t.total,s.loading.hide(),e.search.loading=!1,e.search.hasMore=t.hits&&t.hits.length>0&&t.total>e.search.results.length,e.updateView()})).catch((function(n){e.search.results=[],e.search.loading=!1,e.search.error=!0,e.search.hasMore=!1,s.onError("DOCUMENT.ERROR.LOAD_DOCUMENTS_FAILED")(n).then((function(){e.search.error=!1}))}))}},e.updateView=function(){e.motion&&e.search.results&&e.search.results.length&&e.motion.show({selector:".list .item.item-document"}),e.$broadcast("$$rebind::rebind")},e.doSearchText=function(){return e.search.last=!e.search.text,e.load().then((function(){t.search({q:e.search.text}).replace()}))},e.doSearchLast=function(){return e.search.last=!0,e.search.text=void 0,e.load()},e.removeAll=function(){if(e.hideActionsPopover(),e.search.results&&e.search.results.length)return s.alert.confirm("DOCUMENT.CONFIRM.REMOVE_ALL").then((function(n){if(n)return s.loading.show(),l.removeAll(e.search.results).then((function(){return e.search.loading=!1,i((function(){return s.toast.show("DOCUMENT.INFO.REMOVED"),e.load()}),1e3)})).catch(s.onError("DOCUMENT.ERROR.REMOVE_ALL_FAILED"))}))},e.remove=function(n,t){var i=e.search.results[t];i&&!n.defaultPrevented&&(n.stopPropagation(),s.alert.confirm("DOCUMENT.CONFIRM.REMOVE").then((function(n){if(n)return l.remove(i).then((function(){e.search.results.splice(t,1),e.$broadcast("$$rebind::rebind"),s.toast.show("DOCUMENT.INFO.REMOVED")})).catch(s.onError("MESSAGE.ERROR.REMOVE_FAILED"))})))},e.selectDocument=function(n,t){console.debug("Selected document: ",t,r);var i=r.getUrl("/{0}/{1}/_search?pretty&q=_id:{2}".format(t.index,t.type,t.id));return e.openLink(n,i)},e.toggleCompactMode=function(){e.compactMode=!e.compactMode,e.updateView(),!e.search.hasMore&&e.search.results.length&&"last"==e.search.type&&i((function(){e.search.hasMore=!0}),500)},e.toggleSort=function(n){e.search.sort!==n||e.search.asc?(e.search.asc=e.search.sort!==n||!e.search.asc,e.search.sort=n):(e.search.asc=void 0,e.search.sort=void 0),e.load()},e.showMore=function(){e.search.loading||(e.search.loadingMore=!0,e.load(e.search.results.length,e.defaultSizeLimit,!0).then((function(){e.search.loadingMore=!1,e.$broadcast("scroll.infiniteScrollComplete")})))},e.startListenChanges=function(){var n=Date.now(),t=e.search.index+"/"+e.search.type,i=r.websocket.changes(t);return i.open().then((function(){console.debug("[ES] [document] Websocket opened in {0} ms".format(Date.now()-n)),i.on((function(n){e.search.last&&n&&l.fromHit(n).then((function(t){"DELETE"===n._operation?e.onDeleteDocument(t):e.onNewDocument(t)}))}))}))},e.onNewDocument=function(n){if(e.search.last&&!e.search.loading){console.debug("[ES] [document] Detected new document: ",n);var t=_.findIndex(e.search.results,{id:n.id,index:n.index,type:n.type});t<0?(e.search.total++,e.search.results.splice(0,0,n)):(n.updated=!0,i((function(){n.updated=!1}),2e3),e.search.results.splice(t,1,n)),e.updateView()}},e.onDeleteDocument=function(n){e.search.last&&!e.search.loading&&i((function(){var t=_.findIndex(e.search.results,{id:n.id,index:n.index,type:n.type});t<0||(console.debug("[ES] [document] Detected document deletion: ",n),e.search.results.splice(t,1),e.search.total--,e.updateView())}),750)},e.showActionsPopover=function(n){s.popover.show(n,{templateUrl:"plugins/es/templates/document/lookup_popover_actions.html",scope:e,autoremove:!0,afterShow:function(n){e.actionsPopover=n}})},e.hideActionsPopover=function(){e.actionsPopover&&(e.actionsPopover.hide(),e.actionsPopover=null)},e.resetData=function(){e.search.loading||(console.debug("[ES] [document] Resetting data (settings or account may have changed)"),e.search.results=[],e.search.loading=!1,e.search.total=void 0,e.search.loadingMore=!1,e.entered=!1,delete e.search.limit)},o.api.data.on.logout(e,e.resetData)}function J(e,n,t,i){e.search={loading:!0,hasMore:!0,text:void 0,index:"user,page,group",type:"profile,record,comment",results:void 0,sort:"time",asc:!1},e.expertMode=!1,e.defaultSizeLimit=20,e._source=["issuer","hash","time","creationTime","title","avatar._content_type","city","message","record"],angular.extend(this,n("ESDocumentLookupCtrl",{$scope:e})),e.$on("$ionicParentView.enter",e.enter),e.selectDocument=function(e,n){if(n&&e&&!e.defaultPrevented)if(e.stopPropagation(),"user"===n.index&&"profile"===n.type)i.go("app.wot_identity",{pubkey:n.pubkey,uid:n.name});else if("page"===n.index&&"record"===n.type)i.go("app.view_page",{title:n.title,id:n.id});else if("page"===n.index&&"comment"===n.type){var t=$filter("formatHash")(n.id);i.go("app.view_page_anchor",{title:n.title,id:n.record,anchor:t})}else"group"===n.index&&"record"===n.type?i.go("app.view_group",{title:n.title,id:n.id}):"group"===n.index&&"comment"===n.type?(t=$filter("formatHash")(n.id),i.go("app.view_group_anchor",{title:n.title,id:n.record,anchor:t})):console.warn("Click on this kind of document not implement yet!",n)};var a=e.computeOptions;e.computeOptions=function(n,t){var i=a(n,t);if(!i.sort||i.sort.time){var o=i.sort&&i.sort.time||o;i.sort=[{time:o}]}return i._source=i._source||e._source,i.getTimeFunction=function(e){return e.time=e.creationTime||e.time,e.time},i},t((function(){e.startListenChanges()}),1e3)}function Z(e,n,t,i,a,o,s,r,l,c,u,d,p){e.networkStarted=!1,e.ionItemClass="",e.expertMode=c.data.expertMode&&!r.screen.isSmall(),e.isHttps="https:"===a.location.protocol,e.search={text:"",loading:!0,online:!0,results:[],endpointFilter:s.constants.GCHANGE_API,sort:void 0,asc:!0},e.listeners=[],e.helptipPrefix="helptip-network",e.enableLocationHref=!0,e.removeListeners=function(){e.listeners.length&&(console.debug("[ES] [network] Closing listeners"),_.forEach(e.listeners,(function(e){e()})),e.listeners=[])},e.enter=function(n,t){e.networkStarted||(e.networkStarted=!0,e.search.loading=!0,u.get().then((function(n){n&&(e.node=s.node.same(n.node.host,n.node.port)?s:s.instance(n.node.host,n.node.port),t&&t.stateParams&&("true"==t.stateParams.online&&(e.search.online=!0),t.stateParams.expert&&(e.expertMode="true"==t.stateParams.expert)),e.load())})).catch((function(n){r.onError("ERROR.GET_CURRENCY_FAILED")(n),e.networkStarted=!1})))},e.$on("$ionicParentView.enter",e.enter),e.leave=function(){e.networkStarted&&(e.removeListeners(),d.close(),e.networkStarted=!1,e.search.loading=!0)},e.$on("$ionicView.beforeLeave",e.leave),e.$on("$ionicParentView.beforeLeave",e.leave),e.$on("$destroy",e.leave),e.computeOptions=function(){return{filter:{member:!e.search.type||"member"===e.search.type,mirror:!e.search.type||"mirror"===e.search.type,endpointFilter:angular.isDefined(e.search.endpointFilter)?e.search.endpointFilter:null,online:e.search.online&&!0},sort:{type:e.search.sort,asc:e.search.asc},expertMode:e.expertMode,timeout:l.timeout&&(e.expertMode?l.timeout/10:l.timeout/100)}},e.load=function(){e.search.loading&&(d.start(e.node,e.computeOptions()),e.refreshing=!1,e.listeners.push(d.api.data.on.changed(e,(function(n){e.refreshing||(e.refreshing=!0,p.extendAll(n.peers).then((function(){e.networkStarted&&e.updateView(n),e.refreshing=!1})))}))))},e.updateView=function(n){console.debug("[peers] Updating UI"),e.search.results=n.peers,e.search.memberPeersCount=n.memberPeersCount,e.search.loading=!e.networkStarted||d.isBusy(),e.motion&&e.search.results&&e.search.results.length>0&&e.motion.show({selector:".item-peer"}),e.loading||e.$broadcast("$$rebind::rebind")},e.refresh=function(){e.search.loading=!0,d.loadPeers()},e.sort=function(){e.search.loading=!0,e.refreshing=!0,d.sort(e.computeOptions()),e.updateView(d.data)},e.toggleOnline=function(n){e.hideActionsPopover(),e.search.online=!1!==n,d.close(),e.search.loading=!0,e.load(),e.enableLocationHref&&t.search({online:e.search.online}).replace()},e.toggleSearchEndpoint=function(n){e.hideActionsPopover(),e.search.endpointFilter===n||null===n?e.search.endpointFilter=null:e.search.endpointFilter=n,e.sort()},e.toggleSort=function(n){e.search.sort!==n||e.search.asc?(e.search.asc=e.search.sort!==n||!e.search.asc,e.search.sort=n):(e.search.asc=void 0,e.search.sort=void 0),e.sort()},e.selectPeer=function(e){if(e.online){var t={server:e.getServer()};e.isSsl()&&(t.ssl=!0),e.isTor()&&(t.tor=!0),n.go("app.view_es_peer",t)}},e.$on("csView.action.refresh",(function(n,t){"peers"===t&&e.refresh()})),e.$on("csView.action.showActionsPopover",(function(n,t){e.showActionsPopover(t)})),e.showActionsPopover=function(n){e.actionsPopover?e.actionsPopover.show(n):i.fromTemplateUrl("templates/network/lookup_popover_actions.html",{scope:e}).then((function(t){e.actionsPopover=t,e.$on("$destroy",(function(){e.actionsPopover.remove()})),e.actionsPopover.show(n)}))},e.hideActionsPopover=function(){e.actionsPopover&&e.actionsPopover.hide()},e.showEndpointsPopover=function(e,n,t){var i=n.getEndpoints(t);(i=(i||[]).reduce((function(e,t){var i=s.node.parseEndPoint(t);return e.concat({label:"NETWORK.VIEW.NODE_ADDRESS",value:n.getServer()+(i.path||"")})}),[])).length&&(r.popover.show(e,{templateUrl:"templates/network/popover_endpoints.html",bindings:{titleKey:"NETWORK.VIEW.ENDPOINTS."+t,items:i}}),e.stopPropagation())},e.showWs2pPopover=function(e,n){return e.stopPropagation(),o("NETWORK.VIEW.PRIVATE_ACCESS").then((function(t){r.popover.show(e,{templateUrl:"templates/network/popover_endpoints.html",bindings:{titleKey:"NETWORK.VIEW.ENDPOINTS.WS2P",valueKey:"NETWORK.VIEW.NODE_ADDRESS",items:[{label:"NETWORK.VIEW.NODE_ADDRESS",value:n.bma.private?t:n.getServer()+(n.bma.path||"")},{label:"NETWORK.VIEW.WS2PID",value:n.bma.ws2pid},{label:"NETWORK.VIEW.POW_PREFIX",value:n.powPrefix}]}})}))}}function ee(e,n,t){angular.extend(this,n("ESNetworkLookupCtrl",{$scope:e})),t=t||{},e.enableFilter=!angular.isDefined(t.enableFilter)||t.enableFilter,e.search.type=angular.isDefined(t.type)?t.type:e.search.type,e.search.endpointFilter=angular.isDefined(t.endpointFilter)?t.endpointFilter:e.search.endpointFilter,e.expertMode=angular.isDefined(t.expertMode)?t.expertMode:e.expertMode,e.ionItemClass=t.ionItemClass||"item-border-large",e.enableLocationHref=!1,e.helptipPrefix="",e.selectPeer=function(n){e.closeModal(n)},e.$on("modal.hidden",(function(){e.leave()})),e.showHelpTip=function(){},e.enter()}function ne(e,n){angular.extend(this,n("NetworkLookupCtrl",{$scope:e}));var t=t||{};e.enableFilter=!angular.isDefined(t.enableFilter)||t.enableFilter,e.search.type=angular.isDefined(t.type)?t.type:e.search.type,e.search.endpointFilter=angular.isDefined(t.endpointFilter)?t.endpointFilter:e.search.endpointFilter,e.expertMode=angular.isDefined(t.expertMode)?t.expertMode:e.expertMode,e.ionItemClass=t.ionItemClass||"item-border-large",e.helptipPrefix="",e.selectPeer=function(n){e.closePopover(n)},e.$on("popover.hidden",(function(){e.leave()})),e.showHelpTip=function(){},e.enter()}function te(e,n,t,i,a,o){e.loading=!0,e.formData={},e.load=function(){return e.loading=!0,e.formData={},n.all([i.blockchain.current().then((function(n){e.formData.number=n.number,e.formData.medianTime=n.medianTime,e.formData.powMin=n.powMin,e.formData.useSsl=o.useSsl})).catch((function(){delete e.formData.number,delete e.formData.medianTime,delete e.formData.powMin,delete e.formData.useSsl})),o.node.summary().then((function(n){e.formData.version=n&&n.duniter&&n.duniter.version,e.formData.software=n&&n.duniter&&n.duniter.software})).catch((function(){delete e.formData.version,delete e.formData.software})),o.version.latest().then((function(n){e.formData.latestRelease=n})).catch((function(){delete e.formData.latestRelease}))]).then((function(){if(e.formData.latestRelease&&"duniter"==e.formData.software){var n=a.version.compare(e.formData.version,e.formData.latestRelease.version);e.formData.isPreRelease=n>0,e.formData.hasNewRelease=n<0}else e.formData.isPreRelease=!1,e.formData.hasNewRelease=!1;e.loading=!1,e.$broadcast("$$rebind::rebind")}))},i.api.data.on.newBlock(e,(function(n){e.loading||(console.debug("[peer info] Received new block. Reload content"),e.load())})),t.api.data.on.changed(e,(function(n){e.loading||(console.debug("[peer info] Peer settings changed. Reload content"),e.load())})),e.load()}function ie(e,n,t,i,a,o,s,r,l){e.node={},e.loading=!0,e.isHttps="https:"===t.location.protocol,e.isReachable=!0,e.options={document:{index:l.data.plugins.es&&l.data.plugins.es.document&&l.data.plugins.es.document.index||"user",type:l.data.plugins.es&&l.data.plugins.es.document&&l.data.plugins.es.document.type||"profile"}},e.$on("$ionicView.beforeEnter",(function(e,n){n.enableBack=!!a.screen.isSmall()||n.enableBack})),e.$on("$ionicView.enter",(function(n,t){var i=!t.stateParams||!t.stateParams.server,a=t.stateParams&&t.stateParams.server||s.server,o=t.stateParams&&"true"==t.stateParams.ssl||!!i&&s.useSsl,r="true"==t.stateParams.tor||!!i&&s.useTor;return e.load(a,o,r).then((function(){return e.$broadcast("$csExtension.enter",n,t)})).then((function(){e.loading=!1}))})),e.load=function(t,i,l){var c={server:t,host:t,useSsl:i,useTor:l},u=t.split(":");return 2==u.length&&(c.host=u[0],c.port=u[1]),c.url=r.getUrl(c.host,c.port,void 0,c.useSsl),angular.merge(e.node,l?s.lightInstance(c.host+".to",443,443,!0,6e4):s.lightInstance(c.host,c.port,c.useSsl),c),e.isReachable=!e.isHttps||i,e.isReachable?n.all([e.node.network.peering.self().then((function(n){e.node.pubkey=n.pubkey,e.node.currency=n.currency})),e.node.record.count(e.options.document.index,e.options.document.type).then((function(n){e.node.docCount=n})),e.node.network.peers().then((function(n){var t=n.peers.reduce((function(e,n){var t=new b(n);return t.hasEndpoint("GCHANGE_API")?(t.online="UP"===n.status,t.blockNumber=t.block.replace(/-.+$/,""),t.ep=s.node.parseEndPoint(t.getEndpoints("GCHANGE_API")[0]),t.dns=t.getDns(),t.id=t.keyID(),t.server=t.getServer(),e.concat(t)):e}),[]);return o.extendAll([e.node].concat(t)).then((function(){e.peers=_.sortBy(t,(function(e){var n=1;return n+=1e4*(e.online?1:0),n+=1e3*(e.hasMainConsensusBlock?1:0),-(n+=100*(e.name?1:0))})),e.motion.show({selector:".item-peer"})}))})),e.node.blockchain.current().then((function(n){e.current=n}))]).catch(a.onError(l?"PEER.VIEW.ERROR.LOADING_TOR_NODE_ERROR":"PEER.VIEW.ERROR.LOADING_NODE_ERROR")):s.network.peers().then((function(n){var t=(n&&n.peers||[]).reduce((function(e,n){var t=new b(n);if(!t.hasEndpoint("GCHANGE_API"))return e;var i=s.node.parseEndPoint(t.getEndpoints("GCHANGE_API")[0]);return i.dns!=c.host&&i.ipv4!=c.host&&i.ipv6!=c.host||i.port!=c.port?e:(t.ep=i,e.concat(t))}),[]),i=t.length&&t[0];if(i)return e.node.pubkey=i.pubkey,e.node.currency=i.currency,o.extend(e.node);console.warn("Could not get peer from /network/peers")}))},e.selectPeer=function(e){if(e.online){var n={server:e.getServer()};e.isSsl()&&(n.ssl=!0),e.isTor()&&(n.tor=!0),i.go("app.view_es_peer",n)}},e.openRawPeering=function(n){return e.openLink(n,e.node.url+"/network/peering?pretty")},e.openRawCurrentBlock=function(n){return e.openLink(n,e.node.url+"/network/peering?pretty")}}function ae(e,n,t,i,a,o,s,r,l,c,u,d,p,m,E,g,h){angular.extend(this,a("ESLookupPositionCtrl",{$scope:e})),e.search={text:"",results:[],loading:!0,lastRecords:!0,type:null,category:null,location:null,advanced:null,issuer:null,geoDistance:isNaN(p.data.plugins.es.geoDistance)?20:p.data.plugins.es.geoDistance},e.searchTextId="registrySearchText",e.enableFilter=!0,e.smallscreen=angular.isDefined(e.smallscreen)?e.smallscreen:c.screen.isSmall(),e.options=angular.merge(e.options||{},{location:{show:!0,help:"REGISTRY.SEARCH.LOCATION_HELP"}}),e.enter=function(t,i){if(!e.entered||!e.search.results||0===e.search.results.length){if(!e.geoUnit)return s("LOCATION.DISTANCE_UNIT").then((function(n){return e.geoUnit=n,e.enter(t,i)}));var a=function(){e.searchTextId&&n(e.searchTextId),e.entered=!0,e.doSearch()};if(i.stateParams&&i.stateParams.q&&"string"==typeof i.stateParams.q&&(e.search.text=i.stateParams.q),i.stateParams&&i.stateParams.hash&&(e.search.text="#"+i.stateParams.hash),i.stateParams&&i.stateParams.location)e.search.location=i.stateParams.location,i.stateParams.lat&&i.stateParams.lon&&(e.search.geoPoint={lat:parseFloat(i.stateParams.lat),lon:parseFloat(i.stateParams.lon)}),i.stateParams.d&&(e.search.geoDistance=i.stateParams.d);else{var o=p.data.plugins.es.registry&&p.data.plugins.es.registry.defaultSearch;if(o&&(o.location?angular.merge(e.search,p.data.plugins.es.registry.defaultSearch):o=void 0),!o&&m.isLogin()&&m.data.profile){if(!m.isDataLoaded())return c.loading.show(),m.loadData().then((function(){return c.loading.hide(),e.enter(t,i)}));e.search.geoPoint=m.data.profile.geoPoint,e.search.location=m.data.profile.city||(m.data.profile.geoPoint?s.instant("LOCATION.PROFILE_POSITION"):void 0)}}i.stateParams&&(i.stateParams.type||i.stateParams.last)?i.stateParams.last||"last"==i.stateParams.type?(e.search.lastRecords=!0,e.search.type=void 0):e.search.type=i.stateParams.type:e.search.lastRecords=!1,i.stateParams&&i.stateParams.issuer&&(e.search.issuer=i.stateParams.issuer),i.stateParams&&i.stateParams.category?g.category.get({id:i.stateParams.category}).then((function(n){e.search.category=n,a()})).catch(c.onError("REGISTRY.ERROR.LOAD_CATEGORY_FAILED")):a()}e.showFab("fab-add-registry-record")},e.$on("$ionicView.enter",(function(n,t){return e.enter(n,t)})),e.leave=function(){var n=!1;p.data.plugins.es.registry=p.data.plugins.es.registry||{},p.data.plugins.es.registry.defaultSearch=p.data.plugins.es.registry.defaultSearch||{};var i=e.search.location&&e.search.location.trim(),a=p.data.plugins.es.registry.defaultSearch.location;a&&a===i||(p.data.plugins.es.registry.defaultSearch={location:i,geoPoint:i&&e.search.geoPoint?angular.copy(e.search.geoPoint):void 0},n=!0);var o=p.data.plugins.es.geoDistance;o&&o===e.search.geoDistance||(p.data.plugins.es.geoDistance=e.search.geoDistance,n=!0),n&&t((function(){p.store()}))},e.$on("$ionicView.leave",(function(){return e.leave()})),e.onGeoPointChanged=function(){e.search.loading||e.search.geoPoint&&e.search.geoPoint.lat&&e.search.geoPoint.lon&&!e.search.geoPoint.exact&&(e.doSearch(),e.updateLocationHref())},e.$watch("search.geoPoint",e.onGeoPointChanged,!0),e.resolveLocationPosition=function(){if(!e.search.loadingPosition)return e.search.loadingPosition=!0,e.searchPosition(e.search.location).then((function(n){if(!n)throw e.search.loading=!1,e.search.results=void 0,e.search.total=0,e.search.loadingPosition=!1,e.search.geoPoint=void 0,"CANCELLED";e.search.geoPoint=n,n.shortName&&!n.exact&&(e.search.location=n.shortName),e.search.loadingPosition=!1}))},e.doGetLastRecords=function(n){return e.hidePopovers(),e.search.text=void 0,e.doSearch(n)},e.doSearchText=function(){e.doSearch()},e.doSearch=function(n){if(e.search.loading=!n,e.search.location&&e.search.location.length>=3&&!e.search.geoPoint)return e.resolveLocationPosition().then((function(){return e.doSearch(n)}));var t=e.search.text&&e.search.text.trim()||"";e.search.lastRecords=!t||!t.length;var i=[],a=[];if(t&&t.length)if(d.regexp.PUBKEY.test(t))a.push({term:{pubkey:t}});else{var o=(t=t.toLowerCase())?h.util.parseTags(t):void 0;i.push({multi_match:{query:t,fields:["title","description","city","address"],type:"phrase_prefix"}}),i.push({match:{title:{query:t,boost:2}}}),i.push({prefix:{title:t}}),i.push({match:{description:t}}),i.push({nested:{path:"category",query:{bool:{filter:{match:{"category.name":t}}}}}}),o&&o.length&&a.push({terms:{tags:o}})}else e.search.issuer&&a.push({term:{issuer:e.search.issuer}});e.search.type&&a.push({term:{type:e.search.type}}),e.search.category&&a.push({nested:{path:"category",query:{bool:{filter:{term:{"category.id":e.search.category.id}}}}}});var s=e.search.location&&e.search.location.trim().toLowerCase();if(e.search.geoPoint&&e.search.geoPoint.lat&&e.search.geoPoint.lon)if(s&&s.length){var r=s.split(",")[0];a.push({or:[{and:[{not:{exists:{field:"geoPoint"}}},{match_phrase:{city:r}}]},{geo_distance:{distance:e.search.geoDistance+e.geoUnit,geoPoint:{lat:e.search.geoPoint.lat,lon:e.search.geoPoint.lon}}}]})}else a.push({geo_distance:{distance:e.search.geoDistance+e.geoUnit,geoPoint:{lat:e.search.geoPoint.lat,lon:e.search.geoPoint.lon}}});var l={highlight:{fields:{title:{},description:{},tags:{}}},from:n};i.length>0&&(l.query=l.query||{bool:{}},l.query.bool.should=i,l.query.bool.minimum_should_match=1),a.length>0&&(l.query=l.query||{bool:{}},l.query.bool.filter=a),e.search.lastRecords&&(l.sort={creationTime:"desc"});var c=e.queryId&&e.queryId+1||0;return e.queryId=c,e.updateLocationHref(),e.doRequest(l,(function(){return e.queryId==c}))},e.doRequest=function(n,t){return(n=n||{}).from=n.from||0,n.size=n.size||10,n.size<10&&(n.size=10),e.search.loading=0===n.from,g.record.search(n).then((function(a){if(!t||t()){if(!a||!a.hits||!a.hits.length)return e.search.results=n.from>0?e.search.results:[],e.search.total=n.from>0?e.search.total:0,e.search.loading=!1,void(e.search.hasMore=!1);var o=i("formatSlug");_.forEach(a.hits,(function(e){e.urlTitle=o(e.title)})),n.from?e.search.results=e.search.results.concat(a.hits):(e.search.results=a.hits,e.search.total=a.total),e.search.hasMore=e.search.results.length0?e.search.results:[],e.search.total=n.from>0?e.search.total:0,e.search.hasMore=!1,c.onError("REGISTRY.ERROR.LOOKUP_RECORDS_FAILED")(t)}))},e.showMore=function(){var n=e.search.results?e.search.results.length:0;return e.search.loadingMore=!0,(e.search.lastRecords?e.doGetLastRecords:e.doSearch)(n).then((function(){e.search.loadingMore=!1,e.$broadcast("scroll.infiniteScrollComplete")})).catch((function(n){console.error(n),e.search.loadingMore=!1,e.search.hasMore=!1,e.$broadcast("scroll.infiniteScrollComplete")}))},e.removeType=function(){e.search.type=null,e.doSearch(),e.updateLocationHref()},e.removeCategory=function(){e.search.category=null,e.category=null,e.doSearch(),e.updateLocationHref()},e.removeLocation=function(){e.search.location=null,e.search.geoPoint=null,e.doSearch(),e.updateLocationHref()},e.updateLocationHref=function(n){n||t((function(){var n=e.search.text&&e.search.text.trim(),t=e.search.location&&e.search.location.trim(),i={location:t&&t.length?t:void 0,category:e.search.category?e.search.category.id:void 0,last:!!e.search.lastRecords||void 0,type:e.search.type?e.search.type:void 0,lat:e.search.geoPoint&&e.search.geoPoint.lat||void 0,lon:e.search.geoPoint&&e.search.geoPoint.lon||void 0,d:e.search.geoPoint&&e.search.geoDistance||void 0};n&&n.match(/^#\w+$/)?i.hash=n.substr(1):n&&n.length&&(i.q=n),o.search(i).replace()}))},e.onToggleAdvanced=function(){e.search.entered&&!e.search.lastRecords&&(e.doSearch(),e.updateLocationHref())},e.$watch("search.advanced",e.onToggleAdvanced,!0),e.toggleAdvanced=function(){e.search.advanced=!e.search.advanced,t(e.hidePopovers,200)},e.showRecordTypeModal=function(n){e.hidePopovers(),t((function(){n.isDefaultPrevented()||u.show("plugins/es/templates/registry/modal_record_type.html").then((function(n){n&&(e.search.type=n,e.doSearch(),e.updateLocationHref())}))}),350)},e.showCategoryModal=function(n){t((function(){n.isDefaultPrevented()||g.category.all().then((function(e){return u.show("plugins/es/templates/common/modal_category.html","ESCategoryModalCtrl as ctrl",{categories:e},{focusFirstInput:!0})})).then((function(n){n&&n.parent&&(e.search.category=n,e.doSearch(),e.updateLocationHref())}))}),350)},e.showNewPageModal=function(){return e.hidePopovers(),e.loadWallet().then((function(e){if(c.loading.hide(),e)return E.showNewPage()}))},e.showActionsPopover=function(n){e.actionsPopover?e.actionsPopover.show(n):r.fromTemplateUrl("plugins/es/templates/registry/lookup_popover_actions.html",{scope:e}).then((function(t){e.actionsPopover=t,e.$on("$destroy",(function(){e.actionsPopover.remove()})),e.actionsPopover.show(n)}))},e.hideActionsPopover=function(){e.actionsPopover&&e.actionsPopover.hide()},e.showFiltersPopover=function(n){e.filtersPopover?e.filtersPopover.show(n):r.fromTemplateUrl("plugins/es/templates/registry/lookup_popover_filters.html",{scope:e}).then((function(t){e.filtersPopover=t,e.$on("$destroy",(function(){e.filtersPopover.remove()})),e.filtersPopover.show(n)}))},e.hideFiltersPopover=function(){e.filtersPopover&&e.filtersPopover.hide()},e.hidePopovers=function(){e.hideActionsPopover(),e.hideFiltersPopover()}}function oe(e,n,t,i,a){angular.extend(this,n("ESRegistryLookupCtrl",{$scope:e})),e.searchTextId=void 0,e.enter=function(n,a){return e.entered?a.stateParams&&a.stateParams.refresh?t(e.doSearch,2e3):void 0:e.loadWallet({minData:!0}).then((function(n){i.loading.hide(),e.search.issuer=n.pubkey,e.search.advanced=!0,t(e.doSearch,100),e.showFab("fab-wallet-add-registry-record")}))},e.doUpdate=function(){if(a.isLogin())return e.search.issuer=a.data.pubkey,e.search.advanced=!0,e.doSearch()}}function se(e,n,t,i,a,o,s,r,l,c,u,d,p,m){e.formData={},e.id=null,e.category={},e.pictures=[],e.canEdit=!1,e.loading=!0,e.motion=p.motion.fadeSlideIn,e.$on("$ionicView.beforeEnter",(function(e,n){n.enableBack=!!p.screen.isSmall()||n.enableBack})),e.$on("$ionicView.enter",(function(n,i){i.stateParams&&i.stateParams.id?((e.loading||i.stateParams.refresh)&&e.load(i.stateParams.id,i.stateParams.anchor),e.$broadcast("$recordView.enter",i)):t.go("app.registry_lookup")})),e.$on("$ionicView.beforeLeave",(function(n,t){e.$broadcast("$recordView.beforeLeave",t)})),e.load=function(n,o){return n=n||e.id,e.loading=!0,i.all([d.record.load(n).then((function(n){e.id=n.id,e.formData=n.record,e.canEdit=u.isUserPubkey(e.formData.issuer),e.issuer=n.issuer,e.avatar=e.formData.avatar,e.avatarStyle=e.formData.avatar&&{"background-image":'url("'+e.avatar.src+'")'},p.loading.hide(),e.loading=!1,e.motion.show({selector:".list > .item, .list > ng-if > .item"})})).catch((function(a){e.secondTry?(e.loading=!1,a&&404===a.ucode?(p.toast.show("REGISTRY.ERROR.RECORD_NOT_EXISTS"),t.go("app.registry_lookup")):p.onError("REGISTRY.ERROR.LOAD_RECORD_FAILED")(a)):(e.secondTry=!0,i((function(){e.load(n)}),100))})),d.record.picture.all({id:n}).then((function(n){e.pictures=n._source.pictures&&n._source.pictures.reduce((function(e,n){return e.concat(m.image.fromAttachment(n.file))}),[]),e.pictures.length>0&&e.motion.show({selector:".lazy-load .item.card-gallery",startVelocity:3e3})})).catch((function(){e.pictures=[]})),a((function(){return e.$broadcast("$recordView.load",n,d.record)}))]).then((function(){e.motion.show({selector:".lazy-load .item",startVelocity:3e3}),o&&a((function(){l(o)}),1e3)}))},e.edit=function(){p.loading.show(),t.go("app.registry_edit_record",{id:e.id})},e.delete=function(){var n;e.hideActionsPopover(),r(["REGISTRY.VIEW.REMOVE_CONFIRMATION","REGISTRY.INFO.RECORD_REMOVED"]).then((function(e){return n=e,p.alert.confirm(e["REGISTRY.VIEW.REMOVE_CONFIRMATION"])})).then((function(i){i&&d.record.remove(e.id).then((function(){u.data.pages&&u.data.pages.count&&u.data.pages.count--,s.nextViewOptions({historyRoot:!0}),t.go("app.wallet_pages",{refresh:!0}),p.toast.show(n["REGISTRY.INFO.RECORD_REMOVED"])})).catch(p.onError("REGISTRY.ERROR.REMOVE_RECORD_FAILED"))}))},e.showActionsPopover=function(n){e.actionsPopover?e.actionsPopover.show(n):o.fromTemplateUrl("plugins/es/templates/registry/view_popover_actions.html",{scope:e}).then((function(t){e.actionsPopover=t,e.$on("$destroy",(function(){e.actionsPopover.remove()})),e.actionsPopover.show(n)}))},e.hideActionsPopover=function(){e.actionsPopover&&e.actionsPopover.hide()},e.showSharePopover=function(n){e.hideActionsPopover();var t=e.formData.title,i=m.getUrl("/page/record/"+e.id+"/_share");p.screen.isSmall()&&(n=angular.element(document.querySelector("#registry-share-anchor-"+e.id))||n),p.popover.share(n,{bindings:{url:i,titleKey:"REGISTRY.VIEW.POPOVER_SHARE_TITLE",titleValues:{title:t},time:e.formData.time,postMessage:t}})}}function re(e,n,t,i,a,o,s,r,l,c,u,d,p,m){angular.extend(this,r("ESPositionEditCtrl",{$scope:e})),e.formData={title:null,description:null,socials:[],geoPoint:null},e.loading=!0,e.dirty=!1,e.walletData=null,e.id=null,e.avatar=null,e.pictures=[],e.setForm=function(n){e.form=n},e.$on("$ionicView.enter",(function(n,t){e.loadWallet({minData:!0}).then((function(n){e.walletData=n,t.stateParams&&t.stateParams.id?e.load(t.stateParams.id):t.stateParams&&t.stateParams.type&&e.updateView({record:{type:t.stateParams.type}}),o("registry-record-title")}))})),e.$on("$stateChangeStart",(function(n,i,o,s){if(e.dirty&&!e.saving&&(n.preventDefault(),!e.loading))return e.loading=!0,c.alert.confirm("CONFIRM.SAVE_BEFORE_LEAVE","CONFIRM.SAVE_BEFORE_LEAVE_TITLE",{cancelText:"COMMON.BTN_NO",okText:"COMMON.BTN_YES_SAVE"}).then((function(n){return e.loading=!1,n?(e.form.$submitted=!0,e.save(!1,!0).then((function(n){return n&&(e.dirty=!1),n}))):(e.dirty=!1,!0)})).then((function(e){e&&(a.nextViewOptions({historyRoot:!0}),t.go(i.name,o))})).catch((function(e){}))})),e.load=function(n){e.loading=!0,m.record.load(n,{raw:!0}).then((function(n){n&&n.record?e.updateView(n):e.updateView({record:{}})})).catch((function(n){c.loading.hide(10),e.loading=!1,c.onError("REGISTRY.ERROR.LOAD_RECORD_FAILED")(n)}))},e.updateView=function(t){e.formData=t.record||{},e.id=t.id,e.avatar=e.formData.avatar,e.avatar?(e.avatarStyle=e.avatar&&{"background-image":'url("'+e.avatar.src+'")'},e.avatarClass={}):(e.avatarStyle=void 0,e.avatarClass={},e.avatarClass["cion-page-"+e.formData.type]=!e.avatar),e.pictures=t.record&&t.record.pictures||[],delete t.record.pictures,e.motion.show({selector:".animate-ripple .item, .card-gallery",startVelocity:3e3}),c.loading.hide(),n((function(){e.loading=!1}),1e3)},e.onFormDataChanged=function(){e.loading||(e.dirty=!0)},e.$watch("formData",e.onFormDataChanged,!0),e.needCategory=function(){return e.formData.type&&("company"==e.formData.type||"shop"==e.formData.type)},e.save=function(o,r){return e.form.$submitted=!0,!e.saving&&e.form.$valid&&("shop"!==e.formData.type&&"company"!==e.formData.type||e.formData.category&&e.formData.category.id)?r?(e.saving=!0,console.debug("[ES] [page] Saving record..."),i.when().then((function(){var n=e.formData;return e.needCategory()||delete n.category,n.time=p.date.now(),n.geoPoint&&n.geoPoint.lat&&n.geoPoint.lon?(n.geoPoint.lat=parseFloat(n.geoPoint.lat),n.geoPoint.lon=parseFloat(n.geoPoint.lon)):n.geoPoint=null,n.socials&&n.socials.length&&(n.socials=_.uniq(n.socials,!1,(function(e){return e.url}))),n.picturesCount=e.pictures.length,n.picturesCount>0?n.pictures=e.pictures.reduce((function(e,n){return e.concat({file:p.image.toAttachment(n)})}),[]):n.pictures=[],e.avatar&&e.avatar.src?c.image.resizeSrc(e.avatar.src,!0).then((function(e){return n.avatar=p.image.toAttachment({src:e}),n})):(n.avatar={_content:"",_content_type:""},n)})).then((function(n){return e.id?m.record.update(n,{id:e.id}):m.record.add(n)})).then((function(n){return console.info("[ES] [page] Record successfully saved."),!e.id&&d.data.pages&&d.data.pages.count&&d.data.pages.count++,e.id=e.id||n,e.saving=!1,e.dirty=!1,o||s("REGISTRY.INFO.RECORD_SAVED").then((function(e){c.toast.show(e)})),a.clearCache(a.currentView().stateId),a.nextViewOptions({historyRoot:!0}),t.go("app.view_page",{id:e.id,refresh:!0})})).catch((function(n){e.saving=!1,c.onError("REGISTRY.ERROR.SAVE_RECORD_FAILED")(n)}))):(console.debug("[ES] [page] Waiting debounce end, before saving..."),n((function(){return e.save(o,!0)}),650)):i.reject()},e.openPicturePopup=function(){l.camera.getPicture().then((function(n){n&&e.pictures.push({src:"data:image/png;base64,"+n})})).catch(c.onError("ERROR.TAKE_PICTURE_FAILED"))},e.rotateAvatar=function(){if(e.avatar&&e.avatar.src&&!e.rotating)return e.rotating=!0,c.image.rotateSrc(e.avatar.src).then((function(n){e.avatar.src=n,e.avatarStyle={"background-image":'url("'+n+'")'},e.dirty=!0,e.rotating=!1})).catch((function(n){console.error(n),e.rotating=!1}))},e.fileChanged=function(n){return c.loading.show(),i((function(t,i){var a=n.target.files[0];c.image.resizeFile(a).then((function(n){e.pictures.push({src:n}),c.loading.hide(),t()}))}))},e.removePicture=function(n){e.pictures.splice(n,1)},e.favoritePicture=function(n){if(n>0){var t=e.pictures[n];e.pictures.splice(n,1),e.pictures.splice(0,0,t)}},e.cancel=function(){a.goBack()},e.showAvatarModal=function(){return l.camera.enable?l.camera.getPicture().then((function(n){n&&(e.avatar={src:"data:image/png;base64,"+n},e.avatarStyle={"background-image":'url("'+n+'")'},e.dirty=!0,e.avatarClass={})})).catch(c.onError("ERROR.TAKE_PICTURE_FAILED")):u.show("plugins/es/templates/common/modal_edit_avatar.html","ESAvatarModalCtrl",{}).then((function(n){n&&(e.avatar={src:n},e.avatarStyle={"background-image":'url("'+n+'")'},e.dirty=!0,e.avatarClass={})}))},e.showRecordTypeModal=function(){u.show("plugins/es/templates/registry/modal_record_type.html").then((function(n){n&&(e.formData.type=n,e.avatar||(e.avatarClass["cion-page-"+n]=!0))}))},e.showCategoryModal=function(n){m.category.all().then((function(e){return u.show("plugins/es/templates/common/modal_category.html","ESCategoryModalCtrl as ctrl",{categories:e},{focusFirstInput:!0})})).then((function(n){n&&n.parent&&(e.formData.category=n)}))}}function le(e,n,t){e.extensionPoint=t.extensions.points.current.get(),e.enable=n.isEnable(),n.api.state.on.changed(e,(function(n){e.enable=n}))}function ce(e,n,t,i,a,o,s,r,l,c,u,d){angular.extend(this,i("ESLookupPositionCtrl",{$scope:e})),e.enable=u.isEnable(),e.search={location:void 0},e.options=e.options||angular.merge({type:{show:!0},location:{show:!0,prefix:void 0}},c.plugins&&c.plugins.market&&c.plugins.market.record||{}),u.api.state.on.changed(e,(function(n){e.enable=n})),e.onGeoPointChanged=function(){e.search.loading||e.search.geoPoint&&e.search.geoPoint.lat&&e.search.geoPoint.lon&&!e.search.geoPoint.exact&&e.doSearch()},e.$watch("search.geoPoint",e.onGeoPointChanged,!0),e.resolveLocationPosition=function(){if(!e.search.loadingPosition)return e.search.loadingPosition=!0,e.searchPosition(e.search.location).then((function(n){if(!n)throw e.search.loadingPosition=!1,e.search.geoPoint=void 0,"CANCELLED";e.search.geoPoint=n,n.shortName&&!n.exact&&(e.search.location=n.shortName),e.search.loadingPosition=!1}))},e.doSearch=function(i){if(!e.search.geoPoint)return e.searchPosition(e.search.location).then((function(n){if(n)return e.search.geoPoint=n,e.search.location?e.doSearch():(e.search.geoPoint.exact=!0,s("MARKET.COMMON.AROUND_ME").then((function(n){return e.doSearch(n)})))})).catch((function(e){return console.error(e),t.go("app.market_lookup")}));var a=i||e.search.location&&e.search.location.split(", ")[0];if(a&&e.search.geoPoint){n.geoPoints=n.geoPoints||{},n.geoPoints[a]=e.search.geoPoint;var o={lat:e.search.geoPoint&&e.search.geoPoint.lat,lon:e.search.geoPoint&&e.search.geoPoint.lon,location:a};return l.screen.isSmall()?t.go("app.market_lookup",o):t.go("app.market_lookup_lg",o)}e.search.geoPoint=void 0},e.showNewRecordModal=function(){return e.loadWallet({minData:!0}).then((function(){return l.loading.hide()})).then((function(){return!e.options.type.show&&e.options.type.default?e.options.type.default:r.show("plugins/market/templates/record/modal_record_type.html")})).then((function(e){e&&t.go("app.market_add_record",{type:e})}))},e.$parent.showJoinModal=d.showJoin,e.$parent.showLoginModal=d.showLogin,e.$parent.showHelpModal=d.showHelp,l.screen.isSmall()||o((function(){a("searchLocationInput")}),500)}function ue(e,n){angular.extend(this,n("LoginModalCtrl",{$scope:e}))}function de(e,n,t,i,a,o){angular.extend(this,n("LoginModalCtrl",{$scope:e}));var s="^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,6}$";e.usernamePattern=s+"|^[0-9]{9,10}$",e.onWalletLogin=function(n,a){a=a||t.defer();var r=i.plugins&&i.plugins.market&&i.plugins.market.defaultAdminPubkeys;if(r&&r.length){console.error("[market] [login] Storing username into user profile socials");var l=new RegExp(s).test(e.formData.username),c={url:e.formData.username,type:l?"email":"phone"},u=[angular.merge({recipient:n.pubkey},c)];u=(r||[]).reduce((function(e,n){return e.concat(angular.merge({recipient:n},c))}),u),o.setDefaultProfile({socials:u})}return a.resolve(n),a.promise},a.api.data.on.login(e,e.onWalletLogin,this)}function pe(e,n,t,i,a,o,s,r,l,c,u,d,p,m,E,g,h){angular.extend(this,s("ESLookupPositionCtrl",{$scope:e})),e.search={text:"",type:null,lastRecords:!0,results:[],loading:!0,category:null,location:null,geoPoint:null,options:null,loadingMore:!1,showClosed:!1,showOld:!1,geoDistance:isNaN(p.data.plugins.es.geoDistance)?20:p.data.plugins.es.geoDistance,sortAttribute:null,sortDirection:"desc"},e.options=e.options||angular.merge({type:{show:!0},category:{show:!0},description:{show:!0},location:{show:!0,prefix:void 0},fees:{show:!0}},d.plugins&&d.plugins.market&&d.plugins.market.record||{}),e.$watch("search.showClosed",(function(){e.options.showClosed=e.search.showClosed}),!0),e.$watch("search.showOld",(function(){e.options.showOld=e.search.showOld}),!0),e.init=function(){return i.all([g.currencies().then((function(n){e.currencies=n})),o("LOCATION.DISTANCE_UNIT").then((function(n){e.geoUnit=n}))]).then((function(){r((function(){l.ink({selector:".item"})}),200)}))},e.toggleAdType=function(n){n===e.search.type?e.search.type=void 0:e.search.type=n,e.search.lastRecords?e.doGetLastRecords():e.doSearch()},e.doSearch=function(n){if(e.search.loading=!n,e.search.lastRecords=!1,e.search.advanced||(e.search.advanced=!1),e.search.location&&!e.search.geoPoint)return e.searchPosition(e.search.location).then((function(t){return t?(e.search.geoPoint=t,e.search.location=t.name&&t.name.split(",")[0]||e.search.location,e.doSearch(n)):(e.search.loading=!1,l.alert.error("MARKET.ERROR.GEO_LOCATION_NOT_FOUND"))}));var t=e.search.text.trim(),i=[],o=[],s=t?c.util.parseTags(t):void 0;if(t.length>1&&(E.regexp.PUBKEY.test(t)?(i=[],o.push({term:{issuer:t}})):(t=t.toLowerCase(),i.push({multi_match:{query:t,fields:["title","description"],type:"phrase_prefix"}}),i.push({match:{title:{query:t,boost:2}}}),i.push({prefix:{title:t}}),i.push({match:{description:t}}),i.push({nested:{path:"category",query:{bool:{filter:{match:{"category.name":t}}}}}}))),e.search.category&&o.push({nested:{path:"category",query:{bool:{filter:{term:{"category.id":e.search.category.id}}}}}}),s&&o.push({terms:{tags:s}}),!i.length&&!o.length)return e.doGetLastRecords();var r={},u=e.search.location&&e.search.location.trim().toLowerCase();if(e.search.geoPoint&&e.search.geoPoint.lat&&e.search.geoPoint.lon){if(u&&u.length){var d=u.split(",")[0];o.push({or:[{and:[{not:{exists:{field:"geoPoint"}}},{multi_match:{query:d,fields:["city^3","location"]}}]},{geo_distance:{distance:e.search.geoDistance+e.geoUnit,geoPoint:{lat:e.search.geoPoint.lat,lon:e.search.geoPoint.lon}}}]}),r.location=e.search.location.trim()}else o.push({geo_distance:{distance:e.search.geoDistance+e.geoUnit,geoPoint:{lat:e.search.geoPoint.lat,lon:e.search.geoPoint.lon}}});r.lat=e.search.geoPoint.lat,r.lon=e.search.geoPoint.lon}if(e.search.showClosed?r.closed=!0:o.push({range:{stock:{gt:0}}}),e.search.showOld)r.old=!0;else{var p=Date.now()/1e3-31536e3;o.push({range:{time:{gt:p}}})}e.search.type&&(o.push({term:{type:e.search.type}}),r.type=e.search.type),e.currencies&&o.push({terms:{currency:e.currencies}}),r.q=e.search.text;var m={bool:{}};i.length>0&&(m.bool.should=i,m.bool.minimum_should_match=1),o.length>0&&(m.bool.filter=o),n||a.search(r).replace();var g={query:m,from:n};return e.search.sortAttribute&&(g.sort=g.sort||{},g.sort[e.search.sortAttribute]="asc"==e.search.sortDirection?"asc":"desc"),e.doRequest(g)},e.doGetLastRecords=function(n){e.hideActionsPopover(),e.search.lastRecords=!0;var t={sort:{creationTime:"desc"},from:n},i=[],o=[];if(e.search.showClosed||i.push({range:{stock:{gt:0}}}),!e.search.showOld){var s=Date.now()/1e3-31536e3;i.push({range:{time:{gt:s}}})}e.search.type&&i.push({term:{type:e.search.type}}),e.currencies&&i.push({terms:{currency:e.currencies}}),e.search.category&&i.push({nested:{path:"category",query:{bool:{filter:{term:{"category.id":e.search.category.id}}}}}});var r=e.search.location&&e.search.location.trim().toLowerCase();if(e.search.geoPoint&&e.search.geoPoint.lat&&e.search.geoPoint.lon)if(r&&r.length){var l=r.split(",")[0];i.push({or:[{and:[{not:{exists:{field:"geoPoint"}}},{multi_match:{query:l,fields:["city^3","location"]}}]},{geo_distance:{distance:e.search.geoDistance+e.geoUnit,geoPoint:{lat:e.search.geoPoint.lat,lon:e.search.geoPoint.lon}}}]})}else i.push({geo_distance:{distance:e.search.geoDistance+e.geoUnit,geoPoint:{lat:e.search.geoPoint.lat,lon:e.search.geoPoint.lon}}});return o.length&&(t.query={bool:{}},t.query.bool.should=o,t.query.bool.minimum_should_match=1),i.length&&(t.query=t.query||{bool:{}},t.query.bool.filter=i),n||a.search({last:!0,category:e.search.category&&e.search.category.id,type:e.search.type,location:e.search.location,lat:e.search.geoPoint&&e.search.geoPoint.lat,lon:e.search.geoPoint&&e.search.geoPoint.lon}).replace(),e.doRequest(t)},e.doRefresh=function(){return(e.search.lastRecords?e.doGetLastRecords:e.doSearch)()},e.showMore=function(){var n=e.search.results?e.search.results.length:0;return e.search.loadingMore=!0,(e.search.lastRecords?e.doGetLastRecords:e.doSearch)(n).then((function(){e.search.loadingMore=!1,e.$broadcast("scroll.infiniteScrollComplete")})).catch((function(n){console.error(n),e.search.loadingMore=!1,e.search.hasMore=!1,e.$broadcast("scroll.infiniteScrollComplete")}))},e.doRequest=function(n){return(n=n||{}).from=n.from||0,n.size=n.size||10,n.size<10&&(n.size=10),e.search.loading=0===n.from,m.record.search(n).then((function(i){if(!i||!i.hits||!i.hits.length)return e.search.results=n.from>0?e.search.results:[],e.search.total=n.from>0?e.search.total:0,e.search.hasMore=!1,void(e.search.loading=!1);var a=t("formatSlug");return _.forEach(i.hits,(function(e){e.urlTitle=a(e.title)})),h.fillAvatars(i.hits,"issuer").then((function(t){n.from?e.search.results=e.search.results.concat(t):(e.search.results=t,e.search.total=i.total),e.search.hasMore=e.search.results.length0?e.search.results:[],e.search.total=n.from>0?e.search.total:0,e.search.hasMore=!1,l.onError("MARKET.ERROR.LOOKUP_RECORDS_FAILED")(t)}))},e.showCategoryModal=function(){return m.category.all().then((function(e){return u.show("plugins/es/templates/common/modal_category.html","ESCategoryModalCtrl as ctrl",{categories:e},{focusFirstInput:!0})})).then((function(n){n&&n.parent&&(e.search.category=n,e.doSearch())}))},e.showNewRecordModal=function(){return e.loadWallet({minData:!0}).then((function(){return l.loading.hide()})).then((function(){return!e.options.type.show&&e.options.type.default?e.options.type.default:u.show("plugins/market/templates/record/modal_record_type.html")})).then((function(e){e&&n.go("app.market_add_record",{type:e})}))},e.showRecord=function(t,i){if(!t.defaultPrevented){var a=e.search.results[i];a&&n.go("app.market_view_record",{id:a.id,title:a.title})}}}function me(e,n,t,i,a,o,s,r){angular.extend(this,t("MkLookupAbstractCtrl",{$scope:e})),e.enter=function(t,i){if(!e.entered||!e.search.results||0===e.search.results.length){var a=!1;if(i.stateParams){if(i.stateParams.q?(e.search.text=i.stateParams.q,e.search.lastRecords=!1):i.stateParams.last&&(e.search.lastRecords=!0),i.stateParams.type&&(e.search.type=i.stateParams.type),i.stateParams.location&&(e.search.location=i.stateParams.location),i.stateParams.lat&&i.stateParams.lon)e.search.geoPoint={lat:parseFloat(i.stateParams.lat),lon:parseFloat(i.stateParams.lon)};else if(i.stateParams.location)e.search.geoPoint=n.geoPoints&&n.geoPoints[i.stateParams.location]||null;else{var o=r.data.plugins.es.market&&r.data.plugins.es.market.defaultSearch;o&&o.location&&angular.merge(e.search,o)}i.stateParams.hash&&(e.search.text?e.search.text="#"+i.stateParams.hash+" "+e.search.text:e.search.text="#"+i.stateParams.hash),angular.isDefined(i.stateParams.closed)&&(e.search.showClosed=!0,a=!0),angular.isDefined(i.stateParams.old)&&(e.search.showOld=!0,a=!0)}i.stateParams&&(i.stateParams.category||i.stateParams.cat)?s.category.get({id:i.stateParams.category||i.stateParams.cat}).then((function(n){return e.search.category=n,e.init()})).then((function(){return e.finishEnter(a)})):e.init().then((function(){return e.finishEnter(a)}))}},e.$on("$ionicView.enter",e.enter),e.finishEnter=function(n){e.search.advanced=!!n||e.search.advanced,e.search.lastRecords?e.doGetLastRecords().then((function(){e.showFab("fab-add-market-record")})):e.doSearch().then((function(){e.showFab("fab-add-market-record")})),i("marketSearchText"),e.entered=!0},e.updateSettings=function(){var n=!1;r.data.plugins.es.market=r.data.plugins.es.market||{},r.data.plugins.es.market.defaultSearch=r.data.plugins.es.market.defaultSearch||{};var t=e.search.location&&e.search.location.trim(),i=r.data.plugins.es.market.defaultSearch.location;i&&i===t||(r.data.plugins.es.market.defaultSearch={location:t,geoPoint:t&&e.search.geoPoint?angular.copy(e.search.geoPoint):void 0},n=!0);var o=r.data.plugins.es.geoDistance;o&&o===e.search.geoDistance||(r.data.plugins.es.geoDistance=e.search.geoDistance,n=!0),n&&a((function(){r.store()}))},e.leave=function(){e.updateSettings()},e.$on("$ionicView.leave",(function(){return e.leave()})),e.onGeoPointChanged=function(){e.search.loading||e.search.geoPoint&&e.search.geoPoint.lat&&e.search.geoPoint.lon&&!e.search.geoPoint.exact&&e.doSearch()},e.$watch("search.geoPoint",e.onGeoPointChanged,!0),e.onLocationChanged=function(){e.search.loading||e.search.location||e.removeLocation()},e.$watch("search.location",e.onLocationChanged,!0),e.onToggleShowClosedAdChanged=function(n){!e.search.loading&&e.entered&&e.doRefresh()},e.$watch("search.showClosed",e.onToggleShowClosedAdChanged,!0),e.onGeoDistanceChanged=function(){!e.search.loading&&e.entered&&e.search.location&&e.doRefresh()},e.$watch("search.geoDistance",e.onGeoDistanceChanged,!0),e.onCategoryClick=function(n){n&&n.parent&&(e.search.category=n,e.options.category.show=!0,e.search.showCategories=!1,e.doSearch())},e.removeCategory=function(){e.search.category=null,e.category=null,e.doSearch()},e.removeLocation=function(){e.search.location=null,e.search.geoPoint=null,e.updateSettings(),e.doSearch()},e.showActionsPopover=function(n){e.actionsPopover?e.actionsPopover.show(n):o.fromTemplateUrl("plugins/market/templates/search/lookup_actions_popover.html",{scope:e}).then((function(t){e.actionsPopover=t,e.$on("$destroy",(function(){e.actionsPopover.remove()})),e.actionsPopover.show(n)}))},e.hideActionsPopover=function(){e.actionsPopover&&e.actionsPopover.hide()},e.toggleShowClosed=function(){e.hideActionsPopover(),e.search.showClosed=!e.search.showClosed}}function Ee(e,n,t,i,a,o,s,r){e.zoomMin=1,e.categories=[],e.pictures=[],e.activeSlide=0,e.activeCategory=null,e.activeCategoryIndex=0,e.started=!1,e.options=e.options||angular.merge({category:{filter:void 0},slideDuration:5e3,showClosed:!1},n.plugins&&n.plugins.market&&n.plugins.market.record||{}),e.slideDurationLabels={3e3:{labelKey:"MARKET.GALLERY.SLIDE_DURATION_OPTION",labelParams:{value:3}},5e3:{labelKey:"MARKET.GALLERY.SLIDE_DURATION_OPTION",labelParams:{value:5}},1e4:{labelKey:"MARKET.GALLERY.SLIDE_DURATION_OPTION",labelParams:{value:10}},15e3:{labelKey:"MARKET.GALLERY.SLIDE_DURATION_OPTION",labelParams:{value:15}},2e4:{labelKey:"MARKET.GALLERY.SLIDE_DURATION_OPTION",labelParams:{value:20}}},e.slideDurations=_.keys(e.slideDurationLabels),e.resetSlideShow=function(){delete e.activeCategory,delete e.activeCategoryIndex,delete e.activeSlide,delete e.categories},e.startSlideShow=function(n){return e.activeCategory&&e.activeCategory.pictures&&e.activeCategory.pictures.length?e.showPicturesModal(e.activeCategoryIndex,e.activeSlide):((n=n||{}).filter=n.filter||e.options&&e.options.category&&e.options.category.filter,n.withStock=!e.options||!e.options.showClosed,n.withOld=e.options&&e.options.showOld,e.stop(),e.loading=!0,delete e.activeCategory,delete e.activeCategoryIndex,delete e.activeSlide,r.category.stats(n).then((function(n){return e.categories=_.filter(n,(function(e){return e.count>0&&e.children&&e.children.length})),e.nextCategory()})).then((function(){e.loading=!1})).catch((function(n){console.error(n),e.loading=!1})).then((function(){if(e.categories&&e.categories.length)return e.showPicturesModal(0,0)})))},e.showPicturesModal=function(n,t,i){return e.activeCategoryIndex=n,e.activeSlide=t,e.activeCategory=e.categories[n],e.modal?(a.slide(t),a.update(),e.modal.show().then((function(){i||e.start()}))):o.fromTemplateUrl("plugins/market/templates/gallery/modal_slideshow.html",{scope:e}).then((function(n){return e.modal=n,e.modal.scope.closeModal=e.hidePictureModal,e.$on("$destroy",(function(){e.modal&&(e.modal.remove(),delete e.modal)})),e.modal.show().then((function(){i||e.start()}))}))},e.hidePictureModal=function(){return e.stop(),e.modal&&e.modal.isShown()?e.modal.hide():t.when()},e.start=function(){e.interval&&s.cancel(e.interval),console.debug("[market] [gallery] Start slideshow"),e.interval=s((function(){e.nextSlide()}),e.options.slideDuration)},e.stop=function(){e.interval&&(console.debug("[market] [gallery] Stop slideshow"),s.cancel(e.interval),delete e.interval)},e.nextCategory=function(n){if(!e.categories||!e.categories.length)return t.when();if((n=n||!!e.interval)&&e.modal.isShown())return e.hidePictureModal().then((function(){return e.nextCategory(n)}));if(e.activeCategoryIndex=e.loading?0:e.activeCategoryIndex+1,e.activeCategoryIndex===e.categories.length)return e.resetSlideShow(),n?e.startSlideShow():t.when();var i=e.categories[e.activeCategoryIndex];return r.record.pictures({categories:_.pluck(i.children,"id"),size:1e3,withStock:!e.options||!e.options.showClosed}).then((function(t){if(i.pictures=t,n)return e.showPicturesModal(e.activeCategoryIndex,0)}))},e.nextSlide=function(){e.activeCategory&&e.activeCategory.pictures&&e.activeCategory.pictures.length&&a.currentIndex()!=e.activeCategory.pictures.length-1?a.next():e.nextCategory()},e.updateSlideStatus=function(n){i.$getByHandle("scrollHandle"+n).getScrollPosition().zoom==e.zoomMin?a.enableSlide(!0):a.enableSlide(!1)},e.isLoadedCategory=function(e){return e.pictures&&e.pictures.length>0},e.slideChanged=function(n){e.activeSlide=n}}function ge(e,n,t,i,a,o,s,r,l,c,u,d,p,m,E,g,h,b,f,_){function T(n,t){return t=t||s.defer(),e.updateButtons(),e.loadLikes(),t.resolve(),t.promise}e.formData={},e.id=null,e.category={},e.pictures=[],e.canEdit=!1,e.maxCommentSize=10,e.loading=!0,e.motion=d.motion.fadeSlideInRight,e.smallscreen=d.screen.isSmall(),e.moreAdMotion=d.motion.default,e.smallpictures=!1,e.options=e.options||angular.merge({type:{show:!0},category:{show:!0},description:{show:!0},location:{show:!0,prefix:void 0},like:{kinds:["VIEW","LIKE","FOLLOW","ABUSE"],index:"market",type:"record",service:_.record.like}},m.plugins&&m.plugins.market&&m.plugins.market.record||{}),e.likeData={views:{},likes:{},follows:{},abuses:{}},e.search={type:null,results:[],total:0,loading:!0},angular.extend(this,r("ESLikesCtrl",{$scope:e})),e.enter=function(n,t){t.stateParams&&t.stateParams.id?(e.loading||t.stateParams.refresh?e.load(t.stateParams.id):(d.loading.hide(),e.updateButtons()),e.$broadcast("$recordView.enter",t)):a.go("app.market_lookup")},e.$on("$ionicView.enter",e.enter),e.$on("$ionicView.beforeLeave",(function(n,t){e.$broadcast("$recordView.beforeLeave",t)})),e.load=function(n){e.loading=!0,e.formData={};var t=_.record.load(n,{fetchPictures:!1,convertPrice:!0,html:!0}).then((function(n){e.formData=n.record,e.formData.feesCurrency=n.record.feesCurrency||n.record.currency,delete e.formData.useRelative,e.id=n.id,e.issuer=n.issuer,e.loadIssuerStars(e.issuer.pubkey),e.smallscreen||e.loadMoreLikeThis(n),e.updateView(),d.loading.hide(),e.loading=!1})).catch((function(t){e.secondTry?(e.loading=!1,d.loading.hide(),t&&404===t.ucode?(d.toast.show("MARKET.ERROR.RECORD_NOT_EXISTS"),a.go("app.market_lookup")):d.onError("MARKET.ERROR.LOAD_RECORD_FAILED")(t)):(e.secondTry=!0,s((function(){e.load(n)}),100))}));return l((function(){e.loadPictures(n),e.$broadcast("$recordView.load",n,_.record)})),t},e.loadPictures=function(n){return n=n||e.id,_.record.picture.all({id:n}).then((function(n){n._source.pictures&&(e.pictures=n._source.pictures.reduce((function(e,n){return e.concat(f.image.fromAttachment(n.file))}),[]),e.pictures.length&&e.motion.show({selector:".lazy-load .item.card-gallery",ink:!1}))})).catch((function(){e.pictures=[]}))},e.loadMoreLikeThis=function(n){return _.record.moreLikeThis(n.id,{category:n.record.category.id,type:n.record.type,city:n.record.city}).then((function(n){n&&n.total&&(e.search.results=n.hits,e.search.total=n.total,e.search.loading=!1,e.motion.show({selector:".list.list-more-record .item",ink:!0}))}))},e.loadIssuerStars=function(n){this.canEdit||g.isLogin()&&g.isUserPubkey(n)||b.like.count(n,{kind:"star",issuer:g.isLogin()?g.data.pubkey:void 0}).then((function(n){e.issuer.stars=n}))},e.updateView=function(){e.updateButtons(),e.motion.show({selector:".list > .item",ink:!0}),e.canEdit||e.showFab("fab-like-market-record-"+e.id)},e.updateButtons=function(){e.canEdit=e.formData&&g.isUserPubkey(e.formData.issuer),e.canSold=e.canEdit&&e.formData.stock>0,e.canReopen=e.canEdit&&0===e.formData.stock,e.canReopen&&(e.canEdit=!1)},e.markAsView=function(){if(e.likeData&&e.likeData.views&&!e.likeData.views.wasHit&&!e.canEdit&&!g.isUserPubkey(e.formData.issuer)){var n=l((function(){g.isLogin()&&e.options.like.service.add(e.id,{kind:"view"}).then((function(){e.likeData.views.total=(e.likeData.views.total||0)+1})),n=null}),3e3);e.$on("$destroy",(function(){n&&l.cancel(n)}))}},e.refreshConvertedPrice=function(){e.loading=!0},e.$watch("$root.settings.useRelative",e.refreshConvertedPrice,!0),e.edit=function(){a.go("app.market_edit_record",{id:e.id,title:c("formatSlug")(e.formData.title)}),e.loading=!0},e.delete=function(){e.hideActionsPopover(),d.alert.confirm("MARKET.VIEW.REMOVE_CONFIRMATION").then((function(n){n&&_.record.remove(e.id).then((function(){o.nextViewOptions({historyRoot:!0}),a.go("app.market_lookup"),d.toast.show("MARKET.INFO.RECORD_REMOVED")})).catch(d.onError("MARKET.ERROR.REMOVE_RECORD_FAILED"))}))},e.sold=function(){e.hideActionsPopover(),d.alert.confirm("MARKET.VIEW.SOLD_CONFIRMATION").then((function(n){if(n)return d.loading.show(),_.record.setStock(e.id,0).then((function(){e.canSold=!1,e.canReopen=!0,e.canEdit=!1})).catch(d.onError("MARKET.ERROR.SOLD_RECORD_FAILED")).then((function(){o.nextViewOptions({disableBack:!0,disableAnimate:!1,historyRoot:!0}),l((function(){d.toast.show("MARKET.INFO.RECORD_SOLD")}),500),a.go("app.market_lookup")}))}))},e.reopen=function(){e.hideActionsPopover(),d.alert.confirm("MARKET.VIEW.REOPEN_CONFIRMATION").then((function(n){if(n)return d.loading.show().then((function(){return _.record.setStock(e.id,1).then((function(){return e.canSold=!0,e.canReopen=!1,e.canEdit=!0,d.loading.hide()})).then((function(){d.toast.show("MARKET.INFO.RECORD_REOPEN")})).catch(d.onError("MARKET.ERROR.REOPEN_RECORD_FAILED"))}))}))},e.showActionsPopover=function(n){d.popover.show(n,{templateUrl:"plugins/market/templates/record/view_popover_actions.html",scope:e,autoremove:!0,afterShow:function(n){e.actionsPopover=n}})},e.hideActionsPopover=function(){return e.actionsPopover&&(e.actionsPopover.hide(),e.actionsPopover=null),!0},e.showSharePopover=function(n){e.hideActionsPopover();var t=e.formData.title,i=f.getUrl("/market/record/"+e.id+"/_share");d.screen.isSmall()&&(n=angular.element(document.querySelector("#record-share-anchor-"+e.id))||n),d.popover.share(n,{bindings:{url:i,titleKey:"MARKET.VIEW.POPOVER_SHARE_TITLE",titleValues:{title:t},time:e.formData.time,postMessage:t,postImage:e.pictures.length>0?e.pictures[0]:null}})},e.showNewMessageModal=function(){return s.all([u("MARKET.VIEW.NEW_MESSAGE_TITLE",e.formData),e.loadWallet({minData:!0})]).then((function(n){var t=n[0];return d.loading.hide(),h.showMessageCompose({title:t,destPub:e.issuer.pubkey,destUid:e.issuer.name||e.issuer.uid})})).then((function(e){e&&d.toast.show("MESSAGE.INFO.MESSAGE_SENT")}))},e.buy=function(){return e.hideActionsPopover(),e.loadWallet().then((function(n){if(d.loading.hide(),n)return p.showTransfer({pubkey:e.issuer.pubkey,uid:e.issuer.name||e.issuer.uid,amount:e.formData.price}).then((function(e){if(e)return d.toast.show("INFO.TRANSFER_SENT")}))}))},e.showRecord=function(n,t){if(!n.defaultPrevented){var i=e.search.results[t];i&&a.go("app.market_view_record",{id:i.id,title:i.title})}},g.api.data.on.login(e,T,this),g.api.data.on.logout(e,T,this)}function he(e,n,t,i,a,o,s,r,l,c,u,d,p,m,E,g,h){e.options=e.options||angular.merge({recordType:{show:!0,canEdit:!0},category:{show:!0,filter:void 0},description:{show:!0},location:{show:!0,required:!0},position:{showCheckbox:!0,required:!0},unit:{canEdit:!0},login:{type:"full"}},p.plugins&&p.plugins.market&&p.plugins.market.record||{}),angular.extend(this,c("ESPositionEditCtrl",{$scope:e})),e.formData={price:null,category:{},geoPoint:null,useRelative:E.data.useRelative},e.id=null,e.pictures=[],e.loading=!0,e.motion=u.motion.ripple,e.setForm=function(n){e.form=n},e.$on("$ionicView.enter",(function(n,i){return t.all([h.currencies(),e.loadWallet({minData:!0})]).then((function(n){e.currencies=n[0],i.stateParams&&i.stateParams.id?e.load(i.stateParams.id):(i.stateParams&&i.stateParams.type&&(e.formData.type=i.stateParams.type),e.formData.type=e.formData.type||e.options.type&&e.options.type.default||"offer",e.formData.currency=e.currencies&&e.currencies[0],e.loading=!1,u.loading.hide(),e.motion.show()),e.options.focus&&!u.screen.isSmall()&&l("market-record-title")})).catch((function(n){"CANCELLED"===n&&(e.motion.hide(),e.showHome())}))})),e.showUnitPopover=function(n){u.popover.show(n,{templateUrl:"templates/wallet/popover_unit.html",scope:e,autoremove:!0}).then((function(n){e.formData.useRelative=n}))},e.cancel=function(){e.closeModal()},e.load=function(n){return u.loading.show(),s.record.load(n,{fetchPictures:!0,convertPrice:!1}).then((function(n){angular.merge(e.formData,n.record),e.formData.useRelative="UD"===n.record.unit,e.formData.useRelative||(e.formData.price=e.formData.price?e.formData.price/100:void 0,e.formData.fees=e.formData.fees?e.formData.fees/100:void 0),e.formData.currency||(e.formData.currency=e.currency),!e.formData.city&&e.formData.location&&(e.formData.city=e.formData.location),e.formData.location&&(e.formData.location=null),e.id=n.id,e.pictures=n.record.pictures||[],delete e.formData.pictures,e.dirty=!1,e.motion.show({selector:".animate-ripple .item, .card-gallery"}),u.loading.hide(),o((function(){e.loading=!1}),1e3)})).catch(u.onError("MARKET.ERROR.LOAD_RECORD_FAILED"))},e.save=function(a,l){return e.form.$submitted=!0,!e.saving&&e.form.$valid&&e.formData.category.id?l?(e.saving=!0,console.debug("[ES] [market] Saving record..."),u.loading.show({delay:0}).then((function(){var n=angular.copy(e.formData);delete n.useRelative;var t=e.formData.useRelative?"UD":"unit";return angular.isDefined(n.price)&&null!=n.price?("string"==typeof n.price&&(n.price=parseFloat(n.price.replace(new RegExp("[.,]"),"."))),n.unit=t,"unit"===t&&(n.price=100*n.price),n.currency||(n.currency=e.currency)):(n.unit=null,n.price=null,n.currency||(n.currency=e.currency)),n.fees?("string"==typeof n.fees&&(n.fees=parseFloat(n.fees.replace(new RegExp("[.,]"),"."))),"unit"===t&&(n.fees=100*n.fees),n.feesCurrency||(n.feesCurrency=n.currency||e.currency),n.unit=n.unit||t):(n.fees=null,n.feesCurrency=null),n.time=m.date.now(),n.geoPoint&&n.geoPoint.lat&&n.geoPoint.lon?(n.geoPoint.lat=parseFloat(n.geoPoint.lat),n.geoPoint.lon=parseFloat(n.geoPoint.lon)):n.geoPoint=null,angular.isDefined(n.location)&&(n.location=null),n.picturesCount=e.pictures.length,n.picturesCount?u.image.resizeSrc(e.pictures[0].src,!0).then((function(t){return n.thumbnail=m.image.toAttachment({src:t}),n.pictures=e.pictures.reduce((function(e,n){return e.concat({file:m.image.toAttachment({src:n.src})})}),[]),n})):(e.formData.thumbnail&&(n.thumbnail={_content:"",_content_type:""}),n.pictures=[],n)})).then((function(n){return e.id?s.record.update(n,{id:e.id}):(n.creationTime=m.date.now(),n.stock=angular.isDefined(n.stock)?n.stock:1,s.record.add(n))})).then((function(t){var a=!e.id;if(e.id=e.id||t,e.saving=!1,e.dirty=!1,r.backView()){var o=n.$on("$stateChangeSuccess",(function(n,t,a,s,r){n.preventDefault(),i.go("app.market_view_record",{id:e.id},{location:"replace",reload:!0}),o()}));r.goBack(a?-1:-2)}else r.nextViewOptions({historyRoot:!0}),i.go("app.market_view_record",{id:e.id})})).catch((function(n){e.saving=!1,n&&"ES_HTTP.ERROR.MAX_UPLOAD_BODY_SIZE"===n.message&&(n.message="MARKET.ERROR.RECORD_EXCEED_UPLOAD_SIZE"),u.onError("MARKET.ERROR.FAILED_SAVE_RECORD")(n)}))):(console.debug("[ES] [market] Waiting debounce end, before saving..."),o((function(){return e.save(a,!0)}),650)):t.reject()},e.openCurrencyLookup=function(){alert("Not implemented yet. Please submit an issue if occur again.")},e.cancel=function(){e.dirty=!1,r.goBack()},e.$on("$stateChangeStart",(function(n,t,a,o){if(e.dirty&&!e.saving&&(n.preventDefault(),!e.loading))return u.alert.confirm("CONFIRM.SAVE_BEFORE_LEAVE","CONFIRM.SAVE_BEFORE_LEAVE_TITLE",{cancelText:"COMMON.BTN_NO",okText:"COMMON.BTN_YES_SAVE"}).then((function(n){if(n)return e.save()})).then((function(){e.dirty=!1,r.nextViewOptions({historyRoot:!0}),i.go(t.name,a),u.loading.hide()}))})),e.onFormDataChanged=function(){e.loading||(e.dirty=!0)},e.$watch("formData",e.onFormDataChanged,!0),e.showRecordTypeModal=function(){d.show("plugins/market/templates/record/modal_record_type.html").then((function(n){n&&(e.formData.type=n)}))},e.showCategoryModal=function(){(e.options&&e.options.category&&e.options.category.filter?s.category.filtered({filter:e.options.category.filter}):s.category.all()).then((function(e){return d.show("plugins/es/templates/common/modal_category.html","ESCategoryModalCtrl as ctrl",{categories:e},{focusFirstInput:!0})})).then((function(n){n&&n.parent&&(e.formData.category=n)}))}}function be(e,n,t){angular.extend(this,n("MkLookupAbstractCtrl",{$scope:e})),e.search.showClosed=!0,e.smallscreen=t.screen.isSmall(),e.enter=function(n,t){e.loadWallet().then((function(n){e.search.text=n.pubkey,e.search.lastRecords=!1,e.search.sortAttribute="creationTime",e.search.sortDirection="desc",e.entered&&e.search.results&&0!==e.search.results.length||e.doSearch().then((function(){e.showFab("fab-wallet-add-market-record")}))})).catch((function(n){if("CANCELLED"==n)return e.showHome();console.error(n)})),e.entered=!0},e.$on("$ionicView.enter",e.enter)}function fe(e,n,t,i){e.loading=!0,e.motion=n.motion.ripple,e.options=e.options||angular.merge({category:{filter:void 0},showClosed:!1},t.plugins&&t.plugins.market&&t.plugins.market.record||{}),e.load=function(n){return e.loading=!0,(n=n||{}).filter=n.filter||e.options&&e.options.category&&e.options.category.filter,n.withStock=!e.options||!e.options.showClosed,i.category.stats(n).then((function(n){e.categories=n,e.totalCount=e.categories.reduce((function(e,n){return e+n.count}),0),e.loading=!1,e.motion.show&&e.motion.show()}))},e.refresh=function(){if(!e.loading)return e.load()},e.$watch("options.showClosed",e.refresh,!0)}function _e(e,n,t){angular.extend(this,n("MkListCategoriesCtrl",{$scope:e})),e.enter=function(n,t){return e.load().then((function(){e.loading=!1,e.entered||e.motion.show(),e.entered=!0}))},e.$on("$ionicView.enter",e.enter),e.onCategoryClick=function(e){return t.go("app.market_lookup",{category:e&&e.id})}}function Te(e,n,t){angular.extend(this,n("MkLookupAbstractCtrl",{$scope:e})),e.smallscreen=t.screen.isSmall(),e.enter=function(n,t){if(e.pubkey=t&&t.stateParams&&t.stateParams.pubkey,!e.pubkey)return e.showHome();e.search.text=e.pubkey,e.search.lastRecords=!1,e.doSearch(),e.entered=!0},e.$on("$ionicView.enter",e.enter)}function ve(e,n,t,i,a){angular.extend(this,n("ESLastDocumentsCtrl",{$scope:e})),e.search.index="user,page,group,market",e.search.type="profile,record,comment",e._source=["issuer","hash","time","creationTime","title","price","unit","currency","picturesCount","thumbnail._content_type","city","message","record"],e.inheritedSelectDocument=e.selectDocument,e.selectDocument=function(n,t){if("market"===t.index){if(t&&n&&!n.defaultPrevented)if(n.stopPropagation(),"market"===t.index&&"record"===t.type)i.go("app.market_view_record",{id:t.id,title:t.title});else if("market"===t.index&&"comment"===t.type){var o=a("formatHash")(t.id);i.go("app.market_view_record_anchor",{id:t.record,anchor:o})}}else e.inheritedSelectDocument(n,t)}}function Oe(e,n,t,i,a,o,s,r){function l(n){return moment.unix(n).utc().startOf(e.formData.rangeDuration).unix()}e.loading=!0,e.formData=e.formData||{useRelative:o.data.useRelative,timePct:100,rangeDuration:"day",firstBlockTime:0,scale:"linear",hide:[],beginAtZero:!0},e.formData.useRelative=!1,e.scale="linear",e.height=void 0,e.width=void 0,e.maintainAspectRatio=!0,e.times=[],e.enter=function(n,t){if(e.loading){if(t&&t.stateParams&&(e.stateName=t&&t.stateName,e.stateParams=angular.copy(t&&t.stateParams||{}),!e.formData.currency&&t&&t.stateParams&&t.stateParams.currency&&(e.formData.currency=t.stateParams.currency),t.stateParams.t?e.formData.timePct=t.stateParams.t:t.stateParams.timePct&&(e.formData.timePct=t.stateParams.timePct),t.stateParams.stepUnit&&(e.formData.rangeDuration=t.stateParams.stepUnit),t.stateParams.scale&&(e.formData.scale=t.stateParams.scale),t.stateParams.hide&&(e.formData.hide=t.stateParams.hide.split(",").reduce((function(e,n){return e.concat(parseInt(n))}),[]))),e.init(n,t),!e.formData.currency)return s.get().then((function(i){return e.formData.currency=i?i.name:null,e.formData.firstBlockTime=i?l(i.firstBlockTime):0,e.formData.firstBlockTime||console.warn("[graph] currency.firstBlockTime not loaded ! Should have been loaded by currrency service!"),e.formData.currencyAge=l(moment().utc().unix())-e.formData.firstBlockTime,e.enter(n,t)}));e.load().then((function(){e.setScale(e.formData.scale),e.updateHiddenDataset(),e.loading=!1}))}},e.$on("$csExtension.enter",e.enter),e.$on("$ionicParentView.enter",e.enter),e.updateLocation=function(){e.stateName&&(i.nextViewOptions({disableAnimate:!0,disableBack:!0,historyRoot:!0}),e.stateParams=e.stateParams||{},e.stateParams.t=e.formData.timePct>=0&&e.formData.timePct<100?e.formData.timePct:void 0,e.stateParams.stepUnit="day"!=e.formData.rangeDuration?e.formData.rangeDuration:void 0,e.stateParams.hide=e.formData.hide&&e.formData.hide.length?e.formData.hide.join(","):void 0,e.stateParams.scale="linear"!=e.formData.scale?e.formData.scale:void 0,a.go(e.stateName,e.stateParams,{reload:!1,inherit:!0,notify:!1}))},e.setSize=function(n,t,i){e.height=n,e.width=t,e.maintainAspectRatio=angular.isDefined(i)?i:e.maintainAspectRatio},e.$on("csView.action.refresh",(function(n,t){if(!t||"currency"==t)return e.load()})),e.init=function(e,n){},e.load=function(){},e.toggleScale=function(){e.setScale("linear"===e.formData.scale?"logarithmic":"linear"),e.updateLocation()},e.setScale=function(t){if(e.hideActionsPopover(),e.formData.scale=t,e.options&&e.options.scales&&e.options.scales.yAxes){var i=n("formatInteger");_.forEach(e.options.scales.yAxes,(function(n,a){n.type=t,n.ticks=n.ticks||{},"linear"==t?(n.ticks.beginAtZero=!angular.isDefined(e.formData.beginAtZero)||e.formData.beginAtZero,delete n.ticks.min,n.ticks.callback=function(e){return i(e)}):(delete n.ticks.beginAtZero,delete n.ticks.callback,n.ticks.callback=function(e,n){if(e)return Math.log10(e)%1==0||Math.log10(e/3)%1==0?i(e):""})}))}},e.setRangeDuration=function(n){e.hideActionsPopover(),e.formData&&n==e.formData.rangeDuration||(e.formData.rangeDuration=n,delete e.formData.startTime,delete e.formData.endTime,delete e.formData.rangeDurationSec,e.load(),e.updateLocation())},e.updateHiddenDataset=function(n){n=n||e.datasetOverride||{},_.forEach(e.formData.hide||[],(function(t){if(n[t]){n[t].hidden=!0;var i=n[t].yAxisID,a=i&&e.options&&e.options.scales&&_.findWhere(e.options.scales.yAxes||[],{id:i});i&&a&&1==_.filter(n,(function(e){return e.yAxisID===i})).length&&(a.display=!1)}}))},e.onLegendClick=function(n,t){var i=t.datasetIndex,a=this.chart,o=a.getDatasetMeta(i);o.hidden=null===o.hidden?!a.data.datasets[i].hidden:null,a.config&&a.config.data&&a.config.data.datasets&&1===_.filter(a.config.data.datasets,(function(e){return e.yAxisID&&e.yAxisID===o.yAxisID})).length&&(a.scales[o.yAxisID].options.display=!(!0===o.hidden)),a.update(),e.formData.hide=e.formData.hide||[],e.formData.hide=o.hidden?_.union(e.formData.hide,[i]):_.difference(e.formData.hide,[i]),e.updateLocation()},e.goPreviousRange=function(){e.loadingRange||(e.loadingRange=!0,e.formData.startTime-=e.times.length*e.formData.rangeDurationSec,e.formData.startTimee.formData.firstBlockTime+e.formData.currencyAge-e.formData.timeWindow&&(e.formData.startTime=e.formData.firstBlockTime+e.formData.currencyAge-e.formData.timeWindow),e.formData.endTime=e.formData.startTime+e.times.length*e.formData.rangeDurationSec,e.load().then((function(){e.updateLocation(),e.loadingRange=!1})))},e.onRangeChanged=function(){e.loadingRange||(e.loadingRange=!0,e.formData.startTime=e.formData.firstBlockTime+parseFloat(e.formData.timePct)/100*(e.formData.currencyAge-e.formData.timeWindow),e.formData.endTime=e.formData.startTime+e.times.length*e.formData.rangeDurationSec,e.load().then((function(){e.updateLocation(),e.loadingRange=!1})))},e.updateRange=function(n,t,i){i=!angular.isDefined(i)||i,e.formData.startTime=n,e.formData.endTime=t,e.formData.timeWindow=e.formData.timeWindow||e.formData.endTime-e.formData.startTime,e.formData.rangeDurationSec=e.formData.rangeDurationSec||e.formData.timeWindow/(e.times.length-1),i&&(e.formData.timePct=Math.ceil(100*(e.formData.startTime-e.formData.firstBlockTime)/(e.formData.currencyAge-e.formData.timeWindow)))},e.showActionsPopover=function(n){r.popover.show(n,{templateUrl:"plugins/graph/templates/common/popover_range_actions.html",scope:e,autoremove:!0,afterShow:function(n){e.actionsPopover=n}})},e.hideActionsPopover=function(){e.actionsPopover&&(e.actionsPopover.hide(),e.actionsPopover=null)}}function Re(e,n,t,i,a,o,s,r){angular.extend(this,t("GpCurrencyAbstractCtrl",{$scope:e})),e.formData.rangeDuration="month",e.displayRightAxis=!0,e.hiddenDatasets=[],e.chartIdPrefix="docstats-chart-",e.charts=[{id:"market",title:"GRAPH.DOC_STATS.MARKET.TITLE",series:[{key:"market_record",label:"GRAPH.DOC_STATS.MARKET.AD",color:o.rgba.royal(),pointHoverBackgroundColor:o.rgba.royal(),clickState:{name:"app.document_search",params:{index:"market",type:"record"}}},{key:"market_comment",label:"GRAPH.DOC_STATS.MARKET.COMMENT",color:o.rgba.gray(.5),pointHoverBackgroundColor:o.rgba.gray(),clickState:{name:"app.document_search",params:{index:"market",type:"comment"}}}]},{id:"user_delta",title:"GRAPH.DOC_STATS.MARKET_DELTA.TITLE",series:[{key:"market_record_delta",label:"GRAPH.DOC_STATS.MARKET_DELTA.AD",type:"line",yAxisID:"y-axis-delta",color:o.rgba.royal(),pointHoverBackgroundColor:o.rgba.royal()},{key:"market_comment_delta",label:"GRAPH.DOC_STATS.MARKET_DELTA.COMMENT",type:"line",yAxisID:"y-axis-delta",color:o.rgba.gray(.5),pointHoverBackgroundColor:o.rgba.gray()}]},{id:"user",title:"GRAPH.DOC_STATS.USER.TITLE",series:[{key:"user_profile",label:"GRAPH.DOC_STATS.USER.USER_PROFILE",color:o.rgba.royal(.7),pointHoverBackgroundColor:o.rgba.royal(),clickState:{name:"app.document_search",params:{index:"user",type:"profile"}}},{key:"user_settings",label:"GRAPH.DOC_STATS.USER.USER_SETTINGS",color:o.rgba.gray(.5),pointHoverBackgroundColor:o.rgba.gray(),clickState:{name:"app.document_search",params:{index:"user",type:"settings"}}}]},{id:"user_delta",title:"GRAPH.DOC_STATS.USER_DELTA.TITLE",series:[{key:"user_profile_delta",label:"GRAPH.DOC_STATS.USER_DELTA.USER_PROFILE",type:"line",yAxisID:"y-axis-delta",color:o.rgba.royal(),pointHoverBackgroundColor:o.rgba.royal()},{key:"user_settings_delta",label:"GRAPH.DOC_STATS.USER_DELTA.USER_SETTINGS",type:"line",yAxisID:"y-axis-delta",color:o.rgba.gray(.5),pointHoverBackgroundColor:o.rgba.gray()}]},{id:"message",title:"GRAPH.DOC_STATS.MESSAGE.TITLE",series:[{key:"message_inbox",label:"GRAPH.DOC_STATS.MESSAGE.MESSAGE_INBOX",color:o.rgba.royal(),pointHoverBackgroundColor:o.rgba.royal(),clickState:{name:"app.document_search",params:{index:"message",type:"inbox"}}},{key:"message_outbox",label:"GRAPH.DOC_STATS.MESSAGE.MESSAGE_OUTBOX",color:o.rgba.calm(),pointHoverBackgroundColor:o.rgba.calm(),clickState:{name:"app.document_search",params:{index:"message",type:"outbox"}}}]},{id:"social",title:"GRAPH.DOC_STATS.SOCIAL.TITLE",series:[{key:"page_record",label:"GRAPH.DOC_STATS.SOCIAL.PAGE_RECORD",color:o.rgba.royal(),pointHoverBackgroundColor:o.rgba.royal(),clickState:{name:"app.document_search",params:{index:"page",type:"record"}}},{key:"group_record",label:"GRAPH.DOC_STATS.SOCIAL.GROUP_RECORD",color:o.rgba.calm(),pointHoverBackgroundColor:o.rgba.calm(),clickState:{name:"app.document_search",params:{index:"group",type:"record"}}},{key:"page_comment",label:"GRAPH.DOC_STATS.SOCIAL.PAGE_COMMENT",color:o.rgba.gray(.5),pointHoverBackgroundColor:o.rgba.gray(),clickState:{name:"app.document_search",params:{index:"page",type:"comment"}}}]},{id:"subscription",title:"GRAPH.DOC_STATS.SUBSCRIPTION.TITLE",series:[{key:"subscription_record",label:"GRAPH.DOC_STATS.SUBSCRIPTION.EMAIL",color:o.rgba.royal(),pointHoverBackgroundColor:o.rgba.royal(),clickState:{name:"app.document_search",params:{index:"subscription",type:"record"}}}]},{id:"other",title:"GRAPH.DOC_STATS.OTHER.TITLE",series:[{key:"history_delete",label:"GRAPH.DOC_STATS.OTHER.HISTORY_DELETE",color:o.rgba.gray(.5),pointHoverBackgroundColor:o.rgba.gray(),clickState:{name:"app.document_search",params:{index:"history",type:"delete"}}}]}];var l=r("formatInteger");e.defaultChartOptions={responsive:!0,maintainAspectRatio:e.maintainAspectRatio,title:{display:!0},legend:{display:!0,onClick:e.onLegendClick},scales:{xAxes:[{stacked:!0}],yAxes:[{id:"y-axis",stacked:!0},{id:"y-axis-delta",stacked:!1},{id:"y-axis-delta-right",stacked:!1,display:e.displayRightAxis,position:"right",gridLines:{drawOnChartArea:!1}}]},tooltips:{enabled:!0,mode:"index",callbacks:{label:function(e,n){return n.datasets[e.datasetIndex].label+": "+l(e.yLabel)}}}},e.init=function(e,n){n&&n.stateParams},e.load=function(n){return i.all([a(e.charts.reduce((function(e,n){return e.concat(n.series.reduce((function(e,n){return e.concat(n.label)}),[n.title]))}),["COMMON.DATE_PATTERN","COMMON.DATE_SHORT_PATTERN","COMMON.DATE_MONTH_YEAR_PATTERN"])),s.docstat.get(e.formData)]).then((function(t){var i=t[0],a={hour:i["COMMON.DATE_PATTERN"],day:i["COMMON.DATE_SHORT_PATTERN"],month:i["COMMON.DATE_MONTH_YEAR_PATTERN"]};if((t=t[1])&&t.times){e.times=t.times;var s=a[e.formData.rangeDuration];e.labels=_.map(t.times,(function(e){return moment.unix(e).local().format(s)})),e.updateRange(t.times[0],t.times[t.times.length-1],n),e.setScale(e.scale),_.forEach(e.charts,(function(n){var a={};n.data=_.map(n.series,(function(e){if(a[e.yAxisID||"y-axis"]=!0,e.key.endsWith("_delta")){var n=e.key.substring(0,e.key.length-"_delta".length);return((i=t[n])?_.map(i,(function(e){var n=void 0!==e&&void 0!==o?e-(o||e):void 0;return o=e,n})):void 0)||[]}var i,o;return t[e.key]||[]})),n.options=angular.copy(e.defaultChartOptions),n.options.title.text=i[n.title],n.options.scales.yAxes=n.options.scales.yAxes.reduce((function(e,n){return a[n.id]?e.concat(n):e}),[]),n.datasetOverride=_.map(n.series,(function(e){return{yAxisID:e.yAxisID||"y-axis",type:e.type||"line",label:i[e.label],fill:"line"!==e.type,borderWidth:2,pointRadius:"line"!==e.type?0:2,pointHitRadius:4,pointHoverRadius:3,borderColor:e.color,backgroundColor:e.color,pointBackgroundColor:e.color,pointBorderColor:e.color,pointHoverBackgroundColor:e.pointHoverBackgroundColor||e.color,pointHoverBorderColor:e.pointHoverBorderColor||o.rgba.white()}}))}))}}))},e.onChartClick=function(t,i,a){if(a){var o=_.find(e.charts,(function(n){return e.chartIdPrefix+n.id==a._chart.canvas.id})).series[a._datasetIndex];if(o&&o.clickState&&o.clickState.name){var s=o.clickState.params?angular.copy(o.clickState.params):{},r=e.times[a._index],l=moment.unix(r).utc().add(1,e.formData.rangeDuration).unix();return s.q="time:>={0} AND time:<{1}".format(r,l),n.go(o.clickState.name,s)}console.debug("Click on item index={0} on range [{1},{2}]".format(a._index,r,l))}}}function Ne(e,n,t,i,a,o,s){angular.extend(this,n("GpCurrencyAbstractCtrl",{$scope:e})),e.formData.rangeDuration="month",e.hiddenDatasets=[],e.charts=[{id:"count",title:"GRAPH.SYNCHRO.COUNT.TITLE",series:[{key:"inserts",type:"bar",label:"GRAPH.SYNCHRO.COUNT.INSERTS",color:a.rgba.royal(),pointHoverBackgroundColor:a.rgba.royal()},{key:"updates",type:"bar",label:"GRAPH.SYNCHRO.COUNT.UPDATES",color:a.rgba.calm(),pointHoverBackgroundColor:a.rgba.calm()},{key:"deletes",type:"bar",label:"GRAPH.SYNCHRO.COUNT.DELETES",color:a.rgba.assertive(.5),pointHoverBackgroundColor:a.rgba.assertive()}]},{id:"peer",title:"GRAPH.SYNCHRO.PEER.TITLE",series:[{key:"ES_USER_API",label:"GRAPH.SYNCHRO.PEER.ES_USER_API",color:a.rgba.royal(),pointHoverBackgroundColor:a.rgba.royal()},{key:"ES_SUBSCRIPTION_API",label:"GRAPH.SYNCHRO.PEER.ES_SUBSCRIPTION_API",color:a.rgba.gray(.5),pointHoverBackgroundColor:a.rgba.gray()}]},{id:"performance",title:"GRAPH.SYNCHRO.PERFORMANCE.TITLE",series:[{key:"duration",type:"bar",label:"GRAPH.SYNCHRO.PERFORMANCE.DURATION",color:a.rgba.gray(.5),pointHoverBackgroundColor:a.rgba.gray()}]}];var r=s("formatInteger");e.defaultChartOptions={responsive:!0,maintainAspectRatio:e.maintainAspectRatio,title:{display:!0},legend:{display:!0,onClick:e.onLegendClick},scales:{xAxes:[{stacked:!0}],yAxes:[{stacked:!0,id:"y-axis"}]},tooltips:{enabled:!0,mode:"index",callbacks:{label:function(e,n){return n.datasets[e.datasetIndex].label+": "+r(e.yLabel)}}}},e.init=function(e,n){n&&n.stateParams},e.load=function(n){return t.all([i(e.charts.reduce((function(e,n){return e.concat(n.series.reduce((function(e,n){return e.concat(n.label)}),[n.title]))}),["COMMON.DATE_PATTERN","COMMON.DATE_SHORT_PATTERN","COMMON.DATE_MONTH_YEAR_PATTERN"])),o.synchro.execution.get(e.formData)]).then((function(t){var i=t[0],o={hour:i["COMMON.DATE_PATTERN"],day:i["COMMON.DATE_SHORT_PATTERN"],month:i["COMMON.DATE_MONTH_YEAR_PATTERN"]};if((t=t[1])&&t.times){e.times=t.times;var s=o[e.formData.rangeDuration];e.labels=t.times.reduce((function(e,n){return e.concat(moment.unix(n).local().format(s))}),[]),e.updateRange(t.times[0],t.times[t.times.length-1],n),e.setScale(e.scale),_.forEach(e.charts,(function(n){n.data=[],_.forEach(n.series,(function(e){n.data.push(t[e.key]||[])})),n.options=angular.copy(e.defaultChartOptions),n.options.title.text=i[n.title],n.datasetOverride=n.series.reduce((function(e,n){return e.concat({yAxisID:"y-axis",type:n.type||"line",label:i[n.label],fill:!0,borderWidth:2,pointRadius:0,pointHitRadius:4,pointHoverRadius:3,borderColor:n.color,backgroundColor:n.color,pointBackgroundColor:n.color,pointBorderColor:n.color,pointHoverBackgroundColor:n.pointHoverBackgroundColor||n.color,pointHoverBorderColor:n.pointHoverBorderColor||a.rgba.white()})}),[])}))}}))}}function Ie(e,n,t){e.extensionPoint=n.extensions.points.current.get(),e.enable=t.isEnable(),t.api.state.on.changed(e,(function(n){e.enable=n}))}function Se(e,n,t,i,a,o){e.extensionPoint=t.extensions.points.current.get(),e.enable=i.isEnable(),e.loading=!0,e.node=e.node||{},i.api.state.on.changed(e,(function(n){e.enable=n})),e.enter=function(t,i){return!e.node.currency&&i&&i.stateParams&&i.stateParams.currency&&(e.node.currency=i.stateParams.currency),e.node.currency?e.node.pubkey?e.load():n((function(){return e.enter(t,i)}),500):a.get().then((function(n){return e.node.currency=n?n.name:null,e.enter(t,i)}))},e.$on("$csExtension.enter",e.enter),e.load=function(){if(e.node.currency||e.node.pubkey)return console.info("[Graph] [peer] Loading blocks count for [{0}]".format(e.node.pubkey.substr(0,8))),o.node.blockCount(e.node.currency,e.node.pubkey).then((function(n){e.blockCount=n,e.loading=!1}))}}if(angular.module("cesium.settings.services",["ngApi","cesium.config"]).factory("csSettings",["$rootScope","$q","$window","Api","localStorage","$translate","csConfig",function(e,n,t,i,a,o,s){var r=[{id:"en",label:"English",country:"us"},{id:"en-GB",label:"English (UK)",country:"gb"},{id:"eo-EO",label:"Esperanto"},{id:"fr-FR",label:"Français",country:"fr"}],l=s.fallbackLanguage?c(s.fallbackLanguage):"en";function c(e){if(!e)return l;if(_.findWhere(r,{id:e}))return e;var n=e.split("-");if(n.length>1)return c(n[0]);var t=_.find(r,(function(n){return String.prototype.startsWith.call(n.id,e)}));return t?t.id:l}var u,d,p,m,E={STORAGE_KEY:"GCHANGE_SETTINGS",KEEP_AUTH_IDLE_SESSION:9999},g={timeout:4e3,cacheTimeMs:6e4,timeWarningExpireMembership:5184e3,timeWarningExpire:7776e3,minVersion:"1.7.0",newIssueUrl:"https://github.com/duniter-gchange/gchange-client/issues/new?labels=bug",userForumUrl:"https://forum.monnaie-libre.fr",latestReleaseUrl:"https://api.github.com/repos/duniter-gchange/gchange-client/releases/latest",httpsMode:!1},h=angular.merge({useRelative:!1,useLocalStorage:!!t.localStorage,useLocalStorageEncryption:!1,walletHistoryTimeSecond:2592e3,walletHistorySliceSecond:432e3,walletHistoryAutoRefresh:!0,rememberMe:!0,keepAuthIdle:600,showUDHistory:!0,showLoginSalt:!1,expertMode:!1,decimalCount:2,uiEffects:!0,blockValidityWindow:6,helptip:{enable:!1,installDocUrl:"https://github.com/duniter-gchange/gchange-client/blob/master/README.md",currency:0,network:0,wotLookup:0,wot:0,wotCerts:0,wallet:0,walletCerts:0,header:0,settings:0},currency:{allRules:!1,allWotRules:!1},wallet:{showPubkey:!0,alertIfUnusedWallet:!0,notificationReadTime:0},locale:{id:(p=s.defaultLanguage||o.use(),m=c(p),p!==m&&console.debug("[settings] Fix locale [{0}] -> [{1}]".format(p,m)),m)}},g,s),b={},f=!1,T=new i(this,"csSettings"),v=function(){if(angular.isUndefined(u)||!angular.equals(u,b))return u=angular.copy(b),T.data.raise.changed(b)},O=function(){return f?(b.useLocalStorage?!0===b.node.temporary?a.getObject(E.STORAGE_KEY).then((function(e){var n=angular.copy(b);return n.node=e&&e.node||{},delete n.temporary,a.setObject(E.STORAGE_KEY,n)})):a.setObject(E.STORAGE_KEY,b):a.setObject(E.STORAGE_KEY,null)).then((function(){return b.useLocalStorage&&console.debug("[setting] Saved locally"),T.data.raisePromise.store(b)})).then(v):(console.debug("[setting] Waiting start finished..."),(d||I()).then(O))},R=function(e){if(e){var n=!1;if(e.locale&&e.locale.id){var t=c(e.locale.id);e.locale=_.findWhere(r,{id:t}),n=!b.locale||e.locale.id!==b.locale.id||e.locale.id!==o.use()}if(_.keys(g).forEach((function(n){e[n]=h[n]})),angular.merge(b,e),(e&&e.node&&!e.node.temporary||!b.node.temporary)&&delete b.node.temporary,b.plugins&&b.plugins.es.host&&b.plugins.es.port&&(!b.node||b.node.host!==b.plugins.es.host)){var i=b.node.host,a=b.plugins.es.host;console.warn("[settings] Replacing duniter node {{0}} with gchange pod {{1}}".format(i,a)),b.node={host:a,port:b.plugins.es.port,useSsl:b.plugins.es.useSsl}}n&&o.use(b.locale.id)}},N=function(){var e=Date.now();return a.getObject(E.STORAGE_KEY).then((function(n){if(!n)return console.debug("[settings] No settings in local storage. Using defaults."),R(h),void v();R(n),console.debug("[settings] Loaded from local storage in "+(Date.now()-e)+"ms"),v()}))},I=function(){return console.debug("[settings] Starting..."),d=a.ready().then(N).then((function(){console.debug("[settings] Started"),f=!0,d=null,T.data.raise.ready(b)}))};return e.$on("$translateChangeSuccess",(function(){var e=o.use();console.debug("[settings] Locale ["+e+"]");try{moment.locale(e.toLowerCase())}catch(n){try{moment.locale(e.substr(0,2))}catch(e){moment.locale("en-gb"),console.warn("[settings] Unknown local for moment lib. Using default [en]")}}try{numeral.language(e.toLowerCase())}catch(n){try{numeral.language(e.substring(0,2))}catch(e){numeral.language("en-gb"),console.warn("[settings] Unknown local for numeral lib. Using default [en]")}}T.locale.raise.changed(e)})),T.registerEvent("data","reset"),T.registerEvent("data","changed"),T.registerEvent("data","store"),T.registerEvent("data","ready"),T.registerEvent("locale","changed"),R(h),{ready:function(){return f?n.when():d||I()},start:I,data:b,apply:R,getByPath:function(e,n){var t=b;return _.each(e.split("."),(function(e){t=t[e],angular.isUndefined(t)&&(t=n)})),t},reset:function(){return _.keys(b).forEach((function(e){delete b[e]})),R(h),T.data.raisePromise.reset(b).then(O)},store:O,restore:N,defaultSettings:h,api:T,locales:r,constants:E}}]),angular.module("cesium.crypto.services",["cesium.utils.services"]).factory("CryptoUtils",["$q","$timeout","ionicReady",function(e,n,t){function i(){this.loaded=!1;var e=this;this.copy=function(n){_.forEach(_.keys(n),(function(t){e[t]=n[t]}))},this.isLoaded=function(){return this.loaded},this.util=this.util||{},this.util.array_to_string=function(e,n){var t=new Blob([new Uint8Array(e)]),i=new FileReader;i.onload=function(e){n(e.target.result)},i.readAsText(t)}}i.prototype.constants={crypto_sign_BYTES:64,crypto_secretbox_NONCEBYTES:24,crypto_box_MACBYTES:16,SEED_LENGTH:32,SCRYPT_PARAMS:{SIMPLE:{N:2048,r:8,p:1,memory:-1},DEFAULT:{N:4096,r:16,p:1,memory:-1}}},i.prototype.async_load_base58=function(e){var t=this;if(null!==Base58)return e(Base58);n((function(){t.async_load_base58(e)}),100)},i.prototype.async_load_scrypt=function(e,t){var i=this;null!==scrypt_module_factory?scrypt_module_factory(e,t):n((function(){i.async_load_scrypt(e,t)}),100)},i.prototype.async_load_nacl_js=function(e,t){var i=this;null!==nacl_factory?nacl_factory.instantiate(e,t):n((function(){i.async_load_nacl_js(e,t)}),100)},i.prototype.async_load_base64=function(e){var t=this;null!==Base64?e(Base64):n((function(){t.async_load_base64(e)}),100)},i.prototype.async_load_sha256=function(e){var t=this;if(null!==sha256)return e(sha256);n((function(){t.async_load_sha256(e)}),100)},i.prototype.seed_from_signSk=function(e){for(var n=new Uint8Array(that.constants.SEED_LENGTH),t=0;t"+(o||a["ERROR.UNKNOWN_ERROR"])+"

",title:a["ERROR.POPUP_TITLE"],subTitle:a[t],buttons:[{text:""+a["COMMON.BTN_OK"]+"",type:"button-assertive",onTap:function(e){i(e)}}]})}))})):o.when()}function v(e,t){return o((function(i){a([e,t,"INFO.POPUP_TITLE","COMMON.BTN_OK"]).then((function(a){n.show({template:"

"+a[e]+"

",title:a["INFO.POPUP_TITLE"],subTitle:a[t],buttons:[{text:a["COMMON.BTN_OK"],type:"button-positive",onTap:function(e){i(e)}}]})}))}))}function O(n){return n?c((function(){return e.hide()}),n):e.hide()}function R(n){return h?((n=n||{}).template=n.template||h,e.show(n)):a("COMMON.LOADING").then((function(e){return h=e,R(n)}))}function N(){return b.smallscreen.active}function I(e,n,t){return function(n){var i,a=n.target.width,o=n.target.height,s=t?200:640,r=t?200:480,l=document.createElement("canvas");if(t){a>o?(a*=r/o,o=r):(o*=s/a,a=s),l.width=s,l.height=r,i=l.getContext("2d");var c=Math.trunc((s-a)/2+.5),u=Math.trunc((r-o)/2+.5);i.drawImage(n.target,c,u,s+-2*c,r+-2*u)}else a>o?a>s&&(o*=s/a,a=s):o>r&&(a*=r/o,o=r),l.width=a,l.height=o,(i=l.getContext("2d")).drawImage(n.target,0,0,l.width,l.height);var d=l.toDataURL();l.remove(),e(d)}}function S(e,n){var t=o.defer();(n=n||{}).templateUrl=n.templateUrl?n.templateUrl:"templates/common/popover_copy.html",n.scope=n.scope||m,n.scope.popovers=n.scope.popovers||{},n.autoselect=n.autoselect||!1,n.autoremove=!angular.isDefined(n.autoremove)||n.autoremove,n.backdropClickToClose=!angular.isDefined(n.backdropClickToClose)||n.backdropClickToClose,n.focusFirstInput=!!angular.isDefined(n.focusFirstInput)&&n.focusFirstInput;var i=function(i){(i=i||n.scope.popovers[n.templateUrl]).isResolved=!1,i.deferred=t,i.options=n,n.bindings&&angular.merge(i.scope,n.bindings),c((function(){i.show(e).then((function(){var e;n.autoselect?(e=document.querySelectorAll(n.autoselect)[0])&&(l.getSelection&&!l.getSelection().toString()?(e.setSelectionRange(0,e.value.length),e.focus()):e.focus()):n.autofocus&&(e=document.querySelectorAll(n.autofocus)[0])&&e.focus(),i.scope.$parent.$emit("popover.shown"),n.afterShow&&n.afterShow(i)}))}))},a=function(e){(e=e||n.scope.popovers[n.templateUrl])&&(delete n.scope.popovers[n.templateUrl],e.remove().then((function(){angular.element(l.document.querySelectorAll("body")[0]).removeClass("popover-open")})))},s=n.scope.popovers[n.templateUrl];return s?i(s):d.fromTemplateUrl(n.templateUrl,{scope:n.scope,backdropClickToClose:n.backdropClickToClose}).then((function(e){e.isResolved=!1,e.scope.closePopover=function(n){var t=e.options&&e.options.autoremove;e.options&&delete e.options.autoremove,e.hide().then((function(){if(t)return a(e)})).then((function(){e.deferred&&e.deferred.resolve(n),delete e.deferred,delete e.options}))},e.scope.$on("popover.hidden",(function(){e.options&&e.options.afterHidden&&e.options.afterHidden(),e.options&&e.options.autoremove&&a(e)})),n.scope.$on("$remove",(function(){e.deferred&&e.deferred.resolve(),a()})),n.scope.popovers[n.templateUrl]=e,i(e)})),t.promise}function A(e,n){var t=N()?100:10,i=".list.{0} .item, .list .{0} .item".format(n,n);return{ionListClass:n,show:function(n){return(n=n||{}).selector=n.selector||i,n.ink=!angular.isDefined(n.ink)||n.ink,n.startVelocity=n.startVelocity||(N()?1100:3e3),c((function(){n.ink&&g.ink(),e(n)}),n.timeout||t)}}}function C(e,n){if("string"==typeof e&&(e={selector:e}),void 0===e.selector||""===e.selector)return console.error("invalid toggleOn selector"),!1;c((function(){var n=document.querySelectorAll(e.selector);n&&_.forEach(n,(function(e){e.classList.toggle("on",!0)}))}),n||100)}function D(e,n){if("string"==typeof e&&(e={selector:e}),void 0===e.selector||""===e.selector)return console.error("invalid toggleOff selector"),!1;c((function(){var n=document.querySelectorAll(e.selector);n&&_.forEach(n,(function(e){e.classList.toggle("on",!1)}))}),n||900)}return f.motion={enable:!0,default:A(r.ripple,"animate-ripple"),blinds:A(r.blinds,"animate-blinds"),fadeSlideIn:A(r.fadeSlideIn,"animate-fade-slide-in"),fadeSlideInRight:A(r.fadeSlideInRight,"animate-fade-slide-in-right"),panInLeft:A(r.panInLeft,"animate-pan-in-left"),pushDown:A(r.pushDown,"push-down"),ripple:A(r.ripple,"animate-ripple"),slideUp:A(r.slideUp,"slide-up"),fadeIn:A((function(e){C(e)}),"fade-in"),toggleOn:C,toggleOff:D},g={alert:{error:T,info:v,confirm:function(e,t,i){return t=t||"CONFIRM.POPUP_TITLE",(i=i||{}).cssClass=i.cssClass||"confirm",i.okText=i.okText||"COMMON.BTN_OK",i.cancelText=i.cancelText||"COMMON.BTN_CANCEL",a([e,t,i.cancelText,i.okText]).then((function(a){return n.confirm({template:a[e],cssClass:i.cssClass,title:a[t],cancelText:a[i.cancelText],cancelType:i.cancelType,okText:a[i.okText],okType:i.okType})}))},notImplemented:function(){return v("INFO.FEATURES_NOT_IMPLEMENTED")}},loading:{show:R,hide:O,update:function(n){return e._getLoader().then((function(e){if(e&&e.isShown)return n&&n.template?a(n&&n.template).then((function(t){return n.template=t,e})):void 0})).then((function(e){if(e&&e.isShown)return R(n)}))}},toast:{show:function(n,t,i){return t=t||"short",i=i||"bottom",a([n]).then((function(i){return"string"==typeof t&&(t="short"==t?2e3:5e3),e.show({template:i[n],noBackdrop:!0,duration:t})}))}},onError:function(e,n){return function(t){var i,a=e;if(t&&t.message?(a=t.message,i=e):e||(a=t),!n)return"CANCELLED"==a?O(10):(O(10),T(a,i));n(a)}},screen:{isSmall:N,fullscreen:u},ink:s.displayEffect,motion:f.motion,setEffects:function(e){if(g.motion.enable!==e){if(console.debug("[UI] [effects] "+(e?"Enable":"Disable")),g.motion.enable=e,e)t.views.transition("platform"),angular.merge(g.motion,f.motion);else{t.views.transition("none");var n={class:void 0,show:function(){}};angular.merge(g.motion,{enable:!1,default:n,fadeSlideIn:n,fadeSlideInRight:n,panInLeft:n,pushDown:n,ripple:n,slideUp:n,fadeIn:n,toggleOn:C,toggleOff:D}),m.motion=n}i.clearCache()}},fab:{show:function(e,n){n||(n=900),c((function(){var n=document.getElementsByClassName("button-fab");_.forEach(n,(function(n){n.id==e&&n.classList.toggle("on",!0)}))}),n)},hide:function(e,n){n||(n=10),c((function(){var n=document.getElementsByClassName("button-fab");_.forEach(n,(function(n){n.id==e&&n.classList.toggle("on",!1)}))}),n)}},popover:{show:S,copy:function(e,n){var t=n&&n.indexOf("\n")>=0?n.split("\n").length:1;return S(e,{templateUrl:"templates/common/popover_copy.html",bindings:{value:n,rows:t},autoselect:".popover-copy "+(t<=1?"input":"textarea")})},share:function(e,n){return(n=n||{}).templateUrl=n.templateUrl?n.templateUrl:"templates/common/popover_share.html",n.autoselect=n.autoselect||".popover-share input",n.bindings=n.bindings||{},n.bindings.value=n.bindings.value||n.bindings.url||p.href(p.current,p.params,{absolute:!0}),n.bindings.postUrl=n.bindings.postUrl||n.bindings.value,n.bindings.postMessage=n.bindings.postMessage||"",n.bindings.titleKey=n.bindings.titleKey||"COMMON.POPOVER_SHARE.TITLE",S(e,n)},helptip:function e(n,t){var i="string"==typeof n&&n?l.document.getElementById(n):n;n||i||!t.selector||(i=l.document.querySelector(t.selector));var a=(t=t||{}).deferred||o.defer();if(i&&!t.timeout)t.preAction&&i[t.preAction](),t.templateUrl=t.templateUrl?t.templateUrl:"templates/common/popover_helptip.html",t.autofocus=t.autofocus||"#helptip-btn-ok",t.bindings=t.bindings||{},t.bindings.icon=t.bindings.icon||{},t.bindings.icon.position=t.bindings.icon.position||!1,t.bindings.icon.glyph=t.bindings.icon.glyph||(t.bindings.icon.position&&t.bindings.icon.position.startsWith("bottom-")?"ion-arrow-down-c":"ion-arrow-up-c"),t.bindings.icon.class=t.bindings.icon.class||"calm icon "+t.bindings.icon.glyph,t.bindings.tour=!!angular.isDefined(t.bindings.tour)&&t.bindings.tour,S(i,t).then((function(e){t.postAction&&i[t.postAction](),a.resolve(e)})).catch((function(e){t.postAction&&i[t.postAction](),a.reject(e)}));else if(t.timeout){var s=t.timeout;t.retryTimeout=t.retryTimeout||s,delete t.timeout,t.deferred=a,c((function(){e(n,t)}),s)}else angular.isDefined(t.retry)&&!t.retry?"continue"===t.onError?c((function(){a.resolve(!0)})):c((function(){a.reject("[helptip] element now found: "+n)})):(t.retry=angular.isUndefined(t.retry)?2:t.retry-1,t.deferred=a,c((function(){e(n,t)}),t.timeout||t.retryTimeout||100));return a.promise}},selection:{select:function e(n){if(n.value||"text"==n.type||"textarea"==n.type)l.getSelection&&!l.getSelection().toString()&&n.setSelectionRange(0,n.value.length);else if(n.childNodes&&n.childNodes.length>0)e(n.childNodes[0]);else{var t=l.document.createRange();t.selectNodeContents(n);var i=l.getSelection();i.removeAllRanges(),i.addRange(t)}},get:function(){var e="";return window.getSelection&&(e=l.getSelection().toString()),e}},image:{resizeFile:function(e,n){var t=document.createElement("img");return o((function(i,a){if(e){var o=new FileReader;o.onload=function(e){t.onload=I(i,0,n),t.src=e.target.result},o.readAsDataURL(e)}else a("no file to resize")})).then((function(e){return t.remove(),e}))},resizeSrc:function(e,n){var t=document.createElement("img");return o((function(i,a){t.onload=I(i,0,n),t.src=e})).then((function(e){return t.remove(),e}))},rotateSrc:function(e,n){var t=document.createElement("img");return o((function(n,i){t.onload=function(e,n){var t=Math.PI/180*90;return function(n){var i=n.target.width,a=n.target.height;i>a?i>640&&(a*=640/i,i=640):a>480&&(i*=480/a,a=480);var o=document.createElement("canvas");o.width=a,o.height=i;var s=o.getContext("2d");s.rotate(t),s.drawImage(n.target,0,-1*o.width);var r=o.toDataURL();o.remove(),e(r)}}(n),t.src=e})).then((function(e){return t.remove(),e}))}},raw:f}}]).factory("$focus",["$timeout","$window",function(e,n){return function(t){e((function(){var e=n.document.getElementById(t);e&&e.focus()}))}}]),angular.module("cesium.cache.services",["ngResource","angular-cache"]).factory("csCache",["$http","csSettings","CacheFactory",function(e,n,t){var i={LONG:36e5,SHORT:n.defaultSettings.cacheTimeMs},a=[];return{get:function(e,n,o){var s=(e=e||"csCache-")+(n=n||i.SHORT);if(o){for(var r=1;t.get(s+r);)r++;return a[s+=r]||(a[s]=!0),t.createCache(s,{maxAge:n,deleteOnExpire:"aggressive",recycleFreq:n,onExpire:o,storageMode:"memory"})}return a[s]||(a[s]=!0),t.get(s)||t.createCache(s,{maxAge:n,deleteOnExpire:"aggressive",recycleFreq:Math.max(n-1e3,3e5),storageMode:"memory"})},clear:function(e){_.forEach(_.keys(a),(function(n){if(n.startsWith(e)){var i=t.get(a);i&&i.removeAll()}}))},clearAll:function(){console.debug("[cache] cleaning all caches"),_.forEach(_.keys(a),(function(e){var n=t.get(e);n&&n.removeAll()}))},constants:{LONG:i.LONG,SHORT:i.SHORT}}}]),angular.module("cesium.modal.services",[]).controller("EmptyModalCtrl",(function(){})).controller("AboutModalCtrl",["$scope","UIUtils","csHttp",function(e,n,t){e.openLink=function(e,i,a){return(a=a||{}).onError=function(){return n.popover.copy(e,i)},t.uri.open(i,a)}}]).factory("ModalUtils",["$ionicModal","$rootScope","$q","$injector","$controller","$timeout",function(e,n,t,i,a,o){function s(e,n,i){e.deferred=n||t.defer(),e.resolved=!1,e.openModal=function(){return e.modal.show()},e.closeModal=function(n){return e.resolved=!0,e.modal.remove().then((function(){return e.deferred.resolve(n),n}))},e.setForm=function(n,t){t?e[t]=n:e.form=n},e.getParameters=function(){return i},e.$on("modal.hidden",(function(){e.resolved||(e.resolved=!0,o((function(){return e.deferred.resolve(),e.modal.remove()}),(e.modal.hideDelay||320)+20))}))}return{show:function(i,o,r,l){var c,u,d,p=t.defer();if((l=l||{}).animation=l.animation||"slide-in-up",o){l.scope=l.scope?l.scope.$new():n.$new(),s.call({},l.scope,p,r);var m={$scope:l.scope,parameters:r},E=(u={isControllerAs:!1,controllerName:"",propName:""},d=((c=o)||"").trim().split(/\s+/),u.isControllerAs=3===d.length&&"as"===(d[1]||"").toLowerCase(),u.isControllerAs?(u.controllerName=d[0],u.propName=d[2]):u.controllerName=c,u),g=a(o,m);E.isControllerAs&&(g.openModal=l.scope.openModal,g.closeModal=l.scope.closeModal)}return e.fromTemplateUrl(i,l).then((function(e){if(o)e.scope.$parent.modal=e;else{var n=e.scope;s.call({},n,p,r),n.modal=e}return e.show()}),(function(e){p.reject(e)})),p.promise}}}]).factory("Modals",["ModalUtils",function(e){return{showTransfer:function(n){return e.show("templates/wallet/modal_transfer.html","TransferModalCtrl",n,{focusFirstInput:!0})},showLogin:function(n){var t=angular.copy(n||{});return delete t.templateUrl,delete t.controller,e.show(n&&n.templateUrl||"templates/login/modal_login.html",n&&n.controller||"LoginModalCtrl",t,{focusFirstInput:!0})},showWotLookup:function(n){return e.show("templates/wot/modal_lookup.html","WotLookupModalCtrl",n||{},{focusFirstInput:!0})},showNetworkLookup:function(n){return e.show("templates/network/modal_network.html","NetworkLookupModalCtrl",n,{focusFirstInput:!0})},showAbout:function(n){return e.show("templates/modal_about.html","AboutModalCtrl",n)},showJoin:function(n){return e.show("templates/join/modal_join.html","JoinModalCtrl",n)},showHelp:function(n){return e.show("templates/help/modal_help.html","HelpModalCtrl",n)},showAccountSecurity:function(n){return e.show("templates/wallet/modal_security.html","WalletSecurityModalCtrl",n)}}}]),angular.module("cesium.http.services",["cesium.cache.services"]).factory("csHttp",["$http","$q","$timeout","$window","csSettings","csCache","Device",function(e,n,t,i,a,o,s){var r=a.data.timeout,l=[];function c(e,n){return e?e+(n&&80!=n&&443!=n?":"+n:""):null}function u(e,n,t,i){return(443==n||i?"https":"http")+"://"+c(e,n)+(t||"")}function d(e,n,t,i){n&&n.message?e(n):e(404==i?{ucode:404,message:"Resource not found"+(t?" ("+t+")":"")}:t?"Error while requesting ["+t+"]":"Unknown error from node")}function p(e,n,t,i){var a=[],o={},s=e;return"object"==typeof n&&(a=_.keys(n)),_.forEach(a,(function(e){s===(s=s.replace(":"+e,n[e]))&&(o[e]=n[e])})),t.params=o,i(s,t)}function m(e){var n;e.startsWith("duniter://")&&(n="duniter",e=e.replace("duniter://","http://"));var t=document.createElement("a");t.href=e;var i=t.pathname;i&&i.startsWith("/")&&(i=i.substring(1));var a={protocol:n||t.protocol,hostname:t.hostname,host:t.host,port:t.port,username:t.username,password:t.password,pathname:i,search:t.search,hash:t.hash};return t.remove(),a}function E(e,n){var t=e.split("."),i=n.split(".");function a(e){for(var n=0;ni[o]?1:-1}return t.length!=i.length?-1:0}r||(r=4e3);var g=angular.copy(o.constants);return g.clear=function(){console.debug("[http] Cleaning cache..."),o.clear("csHttp-")},{get:function(t,i,a,o,s){if(!t)return n.reject("[http] invalid URL from host: "+t);var l=u(t,i,a,o);return function(t){return n((function(n,i){p(l,t,{timeout:s||r,responseType:"json"},(function(t,a){e.get(t,a).success((function(e,t,i,a){n(e)})).error((function(e,n,a,o){d(i,e,t,n)}))}))}))}},getWithCache:function(t,i,a,s,l,c,m,E){var g=u(t,i,a,s);return l=l||o.constants.LONG,function(t){return n((function(n,i){var a={timeout:m||r,responseType:"json"};a.cache=c?o.get(E,l,(function(n,t,i){console.debug("[http] Refreshing cache for ["+n+"] "),e.get(n,a).success((function(e){a.cache.put(n,e),i&&i(n,e)}))})):o.get(E,l),p(g,t,a,(function(t,a){e.get(t,a).success((function(e){n(e)})).error((function(e,n){d(i,e,t,n)}))}))}))}},post:function(t,i,a,o,s){var l=u(t,i,a,o);return function(t,i){return n((function(n,a){p(l,i,{timeout:s||r,headers:{"Content-Type":"application/json;charset=UTF-8"}},(function(i,o){e.post(i,t,o).success((function(e){n(e)})).error((function(e,n){d(a,e,i,n)}))}))}))}},ws:function(e,i,o,s,r){if(!o)throw console.error("calling csHttp.ws without path argument"),"calling csHttp.ws without path argument";var u=function(e,n,t,i){return(443==n||i?"wss":"ws")+"://"+c(e,n)+(t||"")}(e,i,o,s);function d(e){if(!e.delegate)throw new Error("Websocket not opened");return 1==e.delegate.readyState?n.when(e.delegate):3==e.delegate.readyState?n.reject("Unable to connect to websocket ["+e.delegate.url+"]"):(e.waitDuration>=r?(e.waitRetryDelay=e.waitRetryDelay&&Math.min(e.waitRetryDelay+2e3,3e4)||2e3,console.debug("[http] Will retry websocket [{0}] in {1}s...".format(e.path,Math.round(e.waitRetryDelay/1e3)))):Math.round(e.waitDuration/1e3)%10==0&&console.debug("[http] Waiting websocket ["+e.path+"]..."),t((function(){return e.waitDuration+=e.waitRetryDelay,d(e)}),e.waitRetryDelay))}function m(e,n,t){return e.delegate||(e.path=o,e.callbacks=[],e.waitDuration=0,e.waitRetryDelay=200,p(u,t,{},(function(n){e.delegate=new WebSocket(n),e.delegate.onerror=function(n){e.delegate.readyState=3},e.delegate.onmessage=function(n){var t=JSON.parse(n.data);_.forEach(e.callbacks,(function(e){e(t)}))},e.delegate.onopen=function(n){console.debug("[http] Listening on websocket ["+e.path+"]..."),l.push(e),e.delegate.openTime=Date.now()},e.delegate.onclose=function(n){var i=_.findIndex(l,(function(n){return n.path===e.path}));i>=0&&l.splice(i,1),e.delegate.closing?e.delegate=null:e.delegate.openTime?(console.debug("[http] Unexpected close of websocket [{0}] (open {1} ms ago): re-opening...",o,Date.now()-e.delegate.openTime),e.delegate=null,m(e,null,t)):n&&(console.debug("[http] TODO -- Unexpected close of websocket [{0}]: error code: ".format(o),n),e.delegate=null,m(e,null,t))}}))),n&&e.callbacks.push(n),d(e)}function E(e){e.delegate&&(e.delegate.closing=!0,console.debug("[http] Closing websocket ["+e.path+"]..."),e.delegate.close(),e.callbacks=[],e.onclose&&e.onclose())}return r=r||a.data.timeout,{open:function(e){return m(this,null,e)},on:function(e,n){return m(this,e,n)},onListener:function(e,n){var t=this;return m(t,e,n),function(){!function(e,n){e.callbacks=_.reject(e.callbacks,(function(e){return e===n})),e.callbacks.length||E(e)}(t,e)}},send:function(e){var n=this;return d(n).then((function(){n.delegate&&n.delegate.send(e)}))},close:function(){E(this)},isClosed:function(){return!this.delegate||this.delegate.closing}}},closeAllWs:function(){l.length>0&&(console.debug("[http] Closing all websocket..."),_.forEach(l,(function(e){e.close()})),l=[])},getUrl:u,getServer:c,uri:{parse:m,open:function(e,n){if(n=n||{},!e.startsWith("http://")&&!e.startsWith("https://")){var t=m(e);if(!t.protocol&&n.type&&(t.protocol="email"==n.type?"mailto:":"phone"==n.type?"tel:":"",e=t.protocol+e),"mailto:"==t.protocol&&s.isDesktop())try{return void nw.Shell.openExternal(e)}catch(e){console.error("[http] Failed not open 'mailto:' URI into external tool.")}if("mailto:"!=t.protocol&&"tel:"!=t.protocol||!s.enable)return void(n.onError&&"function"==typeof n.onError&&n.onError(e))}var a,o=n.target||(s.enable?"_system":"_blank");if("_blank"===o||"_system"===o&&s.isDesktop())try{return void nw.Shell.openExternal(e)}catch(e){console.error("[http] Failed not open URI into external browser.")}if("_blank"===o&&s.isDesktop()){if(nw&&nw.Shell)return nw.Shell.openExternal(e),!1;a="location=1,titlebar=1,status=1,menubar=1,toolbar=1,resizable=1,scrollbars=1",i.screen&&i.screen.width&&i.screen.height&&(a+=",width={0},height={1}".format(Math.trunc(i.screen.width/2),Math.trunc(i.screen.height/2)))}var r=i.open(e,o,a);a&&i.screen&&i.screen.width&&i.screen.height&&(r.moveTo(i.screen.width/2/2,i.screen.height/2/2),r.focus())}},date:{now:function(){return moment().utc().unix()}},version:{compare:E,isCompatible:function(e,n){return console.debug("[http] Checking actual version [{0}] is compatible with min expected version [{1}]".format(n,e)),E(e,n)<=0}},cache:g}}]),angular.module("cesium.storage.services",["cesium.config"]).factory("sessionStorage",["$window","$q",function(e,n){var t={storage:e.sessionStorage||{},put:function(e,i){return t.storage[e]=i,n.when()},get:function(e,i){return n.when(t.storage[e]||i)},setObject:function(e,i){return t.storage[e]=JSON.stringify(i),n.when()},getObject:function(e){return n.when(JSON.parse(t.storage[e]||"null"))}};return t}]).factory("localStorage",["$window","$q","$log","sessionStorage",function(e,n,t,i){var a,o=!1,s={standard:{storage:null},secure:{storage:null}};function r(){if(a)return a;var t=Date.now();return(e.localStorage?(console.debug("[storage] Starting {local} storage..."),s.standard.storage=e.localStorage,_.forEach(_.keys(s.standard),(function(e){s[e]=s.standard[e]}))):(console.debug("[storage] Starting {session} storage..."),_.forEach(_.keys(i),(function(e){s[e]=i[e]}))),a=n.when()).then((function(){console.debug("[storage] Started in "+(Date.now()-t)+"ms"),o=!0,a=null}))}return s.standard.put=function(e,t){return angular.isDefined(t)&&null!=t?s.standard.storage[e]=t:s.standard.storage.removeItem(e),n.when()},s.standard.get=function(e,t){return n.when(s.standard.storage[e]||t)},s.standard.setObject=function(e,t){return s.standard.storage[e]=JSON.stringify(t),n.when()},s.standard.getObject=function(e){return n.when(JSON.parse(s.standard.storage[e]||"null"))},s.secure.put=function(e,i){return n((function(n,a){null!=i?s.secure.storage.set((function(e){n()}),(function(e){t.error(e),a(e)}),e,i):s.secure.storage.remove((function(){n()}),(function(e){t.error(e),n()}),e)}))},s.secure.get=function(e,i){return n((function(n,a){s.secure.storage.get((function(e){n(!e&&i?i:e)}),(function(e){t.error(e),n()}),e)}))},s.secure.setObject=function(e,i){return t.debug("[storage] Setting object into secure storage, using key="+e),n((function(n,t){s.secure.storage.set(n,t,e,i?JSON.stringify(i):void 0)}))},s.secure.getObject=function(e){return t.debug("[storage] Getting object from secure storage, using key="+e),n((function(n,i){s.secure.storage.get((function(e){n(JSON.parse(e||"null"))}),(function(e){t.error(e),n()}),e)}))},s.isStarted=function(){return o},s.ready=function(){return o?n.when():a||r()},r(),s}]),angular.module("cesium.device.services",["ngResource","cesium.utils.services","cesium.settings.services"]).factory("Device",["$translate","$ionicPopup","$q","ionicReady",function(e,n,t,i){var a,o={enable:!0},s={},r=!1;function l(e){if(!o.enable)return t.reject("Barcode scanner not enable. Please call 'Device.ready()' once before use (e.g in app.js).");var n=t.defer();return cordova.plugins.barcodeScanner.scan((function(e){console.debug("[device] bar code result",e),e.cancelled?n.resolve():n.resolve(e.text)}),(function(e){console.error("[device] Error while using barcode scanner -> "+e),n.reject(e)}),e),n.promise}return o.enable=!1,o.clipboard={copy:function(e,n){if(!o.enable)return t.reject("Device disabled");var i=t.defer();return $cordovaClipboard.copy(e).then((function(){n&&n(),i.resolve()}),(function(){i.reject({message:"ERROR.COPY_CLIPBOARD"})})),i.promise}},o.camera={getPicture:function(i){return o.camera.enable?(i&&"string"==typeof i&&(i={sourceType:i}),i=i||{},angular.isUndefined(i.sourceType)?e(["SYSTEM.PICTURE_CHOOSE_TYPE","SYSTEM.BTN_PICTURE_GALLERY","SYSTEM.BTN_PICTURE_CAMERA"]).then((function(e){return n.show({title:e["SYSTEM.PICTURE_CHOOSE_TYPE"],buttons:[{text:e["SYSTEM.BTN_PICTURE_GALLERY"],type:"button",onTap:function(e){return navigator.camera.PictureSourceType.PHOTOLIBRARY}},{text:e["SYSTEM.BTN_PICTURE_CAMERA"],type:"button button-positive",onTap:function(e){return navigator.camera.PictureSourceType.CAMERA}}]}).then((function(e){return console.info("[camera] User select sourceType:"+e),i.sourceType=e,o.camera.getPicture(i)}))})):(i.quality=i.quality||50,i.destinationType=i.destinationType||navigator.camera.DestinationType.DATA_URL,i.encodingType=i.encodingType||navigator.camera.EncodingType.PNG,i.targetWidth=i.targetWidth||400,i.targetHeight=i.targetHeight||400,$cordovaCamera.getPicture(i))):t.reject("Camera not enable. Please call 'Device.ready()' once before use (e.g in app.js).")},scan:function(e){return console.warn("Deprecated use of Device.camera.scan(). Use Device.barcode.scan() instead"),l(e)}},o.barcode={enable:!1,scan:l},o.keyboard={enable:!1,close:function(){o.keyboard.enable&&cordova.plugins.Keyboard.close()}},o.keyboard.digit={settings:{bindModel:function(e,n,t){t=t||{},e=e||$rootScope;var i=function(){return(n||"").split(".").reduce((function(e,n){return e?e[n]:void 0}),e)},a=function(t){var i=(n||"").split("."),a=i.length&&i[i.length-1];i.reduce((function(e,n){if(n!=a)return e[n];e[a]=t}),e)};return t.action=t.action||function(e){a((i()||"")+e)},t.decimal&&(t.decimalSeparator=t.decimalSeparator||".",t.leftButton=t.leftButton={html:".",action:function(){var e=i()||"";e.indexOf(t.decimalSeparator)>=0||(e.trim().length||(e="0"),a(e+t.decimalSeparator))}}),t.rightButton=t.rightButton||{html:'',action:function(){var e=i();e&&e.length&&(e=e.slice(0,-1),a(e))}},t}}},o.isIOS=function(){return!!navigator.userAgent.match(/iPhone | iPad | iPod/i)||ionic.Platform.isIOS()},o.isDesktop=function(){if(!angular.isDefined(s.isDesktop))try{s.isDesktop=!(o.enable||!process||!nw||!nw.App)}catch(e){s.isDesktop=!1}return s.isDesktop},o.isWeb=function(){return!o.enable&&!o.isDesktop()},o.ready=function(){return r?t.when():a||o.start()},o.start=function(){return a=i().then((function(){o.enable=window.cordova&&cordova&&cordova.plugins,o.enable?(o.camera.enable=!!navigator.camera,o.keyboard.enable=cordova&&cordova.plugins&&!!cordova.plugins.Keyboard,o.barcode.enable=cordova&&cordova.plugins&&!!cordova.plugins.barcodeScanner,o.clipboard.enable=cordova&&cordova.plugins&&!!cordova.plugins.clipboard,o.keyboard.enable&&angular.extend(o.keyboard,cordova.plugins.Keyboard),console.debug("[device] Ionic platform ready, with [camera: {0}] [barcode scanner: {1}] [keyboard: {2}] [clipboard: {3}]".format(o.camera.enable,o.barcode.enable,o.keyboard.enable,o.clipboard.enable))):console.debug("[device] Ionic platform ready - no device detected."),r=!0,a=null}))},o}]),angular.module("cesium.currency.services",["ngApi","cesium.bma.services"]).factory("csCurrency",["$rootScope","$q","$timeout","BMA","Api","csSettings",function(n,t,i,a,o,s){function r(a,r){var l,c,u={WELL_KNOWN_CURRENCIES:{g1:{firstBlockTime:1488987127,medianTimeOffset:3600}}},d={},p=!1,m=new o(this,"csCurrency-"+a);function E(){d.name=null,d.parameters=null,d.firstBlockTime=null,d.membersCount=null,d.cache={},d.node=r,d.currentUD=null,d.medianTimeOffset=0,p=!1,l=void 0,m.data.raise.reset(d)}function g(){return t.all([r.blockchain.parameters().then((function(e){return d.name=e.currency,d.parameters=e,d.medianTimeOffset=e.avgGenTime*e.medianTimeBlocks/2,e})).then((function(e){return n=e.currency,u.WELL_KNOWN_CURRENCIES[n]?(angular.merge(d,u.WELL_KNOWN_CURRENCIES[n]),t.when()):r.blockchain.block({block:0}).then((function(e){d.firstBlockTime=e.medianTime})).catch((function(e){if(e&&e.ucode===r.errorCodes.BLOCK_NOT_FOUND)return d.firstBlockTime=0,d.initPhase=!0,void console.warn("[currency] Blockchain not launched: Enable init phase mode");throw e}));var n})),r.blockchain.stats.ud().then((function(e){return e.result.blocks.length?function e(n,t){if(!n.result.blocks.length||t<0)return d.currentUD=d.parameters?d.parameters.ud0:-1,d.currentUD;var i=n.result.blocks[t];return r.blockchain.block({block:i}).then((function(e){var n,t;return d.currentUD=(n=e.dividend,(t=e.unitbase)<=0?n:n*Math.pow(10,t)),d.currentUD})).catch((function(a){if(console.error("[currency] Unable to load last block with UD, with number {0}".format(i)),t>0)return console.error("[currency] Retrying to load UD from a previous block..."),e(n,t-1);throw d.currentUD=null,a}))}(e,e.result.blocks.length-1):(d.currentUD=d.parameters?d.parameters.ud0:-1,d.currentUD)})).catch((function(e){throw d.currentUD=null,e})),m.data.raisePromise.load(d)]).catch((function(e){throw E(),e}))}function h(){return p?t.when(d):l||O()}function b(e){return function(){return p?t.when(d[e]):l||O().then((function(){return d[e]}))}}function f(n){var t=new e(n);t.cleanData(),console.debug("[currency] Received new block ["+t.number+"-"+t.hash+"]"),d.currentBlock=t,d.currentBlock.receivedAt=moment().utc().unix(),d.medianTime=t.medianTime,d.membersCount=t.membersCount,t.dividend&&(d.currentUD=t.dividend),m.data.raise.newBlock(t)}function T(){console.debug("[currency] Stopping..."),_.forEach(c,(function(e){e()})),c=[],E()}function v(){return T(),i(O,200)}function O(){console.debug("[currency] Starting...");var e=Date.now();return l=r.ready().then(g).then((function(){!function(){c=[r.api.node.on.restart(n,v,this),r.websocket.block().onListener(f)]}(),console.debug("[currency] Started in "+(Date.now()-e)+"ms"),p=!0,l=null,m.data.raise.ready(d)})).then((function(){return d}))}var R=b("currentBlock");function N(e){return R().then((function(n){var t=moment().utc().unix();if(e){if(n&&t-n.receivedAt<60)return n;n||console.warn("[currency] No current block in cache: get it from network. Websocket [/ws/block] may not be started ?")}return r.blockchain.current().catch((function(e){if(e&&e.ucode==r.errorCodes.NO_CURRENT_BLOCK)return{number:0,hash:r.constants.ROOT_BLOCK_HASH,medianTime:moment().utc().unix()};throw e})).then((function(e){return d.currentBlock=e,d.currentBlock.receivedAt=t,e}))}))}return m.registerEvent("data","ready"),m.registerEvent("data","load"),m.registerEvent("data","reset"),m.registerEvent("data","newBlock"),E(),{ready:function(){return p?t.when(d):l||O()},start:O,stop:T,data:d,get:h,name:b("name"),parameters:b("parameters"),currentUD:b("currentUD"),medianTimeOffset:b("medianTimeOffset"),blockchain:{current:N,lastValid:function(){return s.data.blockValidityWindow<=0?N(!0):N(!0).then((function(e){var n=e.number-s.data.blockValidityWindow;return n>0?r.blockchain.block({block:n}):e}))}},date:{now:function(){return moment().utc().unix()-(d.medianTimeOffset||u.WELL_KNOWN_CURRENCIES.g1.medianTimeOffset)}},api:m,default:function(){return console.warn("[currency] 'csCurrency.default()' has been DEPRECATED - Please use 'csCurrency.get()' instead."),h()}}}var l=r("default",a);return l.instance=r,l}]),angular.module("cesium.bma.services",["ngApi","cesium.http.services","cesium.settings.services"]).factory("BMA",["$q","$window","$rootScope","$timeout","Api","Device","csConfig","csSettings","csHttp",function(e,n,t,i,a,o,s,r,l){function c(o,c,u,d){var p,m="[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{43,44}",E="SIG\\(([0-9a-zA-Z]{43,44})\\)",g="OBJ\\(([0-9]+)\\)",h="( ([a-z_][a-z0-9-_.ğĞ]*))?( ([0-9.]+))?( ([0-9a-f:]+))?( ([0-9]+))( (.+))?",b={BMA:"BASIC_MERKLED_API",BMAS:"BMAS",WS2P:"WS2P",BMATOR:"BMATOR",WS2PTOR:"WS2PTOR"},f={USER_ID:"[0-9a-zA-Z-_]+",CURRENCY:"[0-9a-zA-Z-_]+",PUBKEY:m,PUBKEY_WITH_CHECKSUM:"("+m+"):([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{3})",COMMENT:"[ a-zA-Z0-9-_:/;*\\[\\]()?!^\\+=@&~#{}|\\\\<>%.]*",INVALID_COMMENT_CHARS:"[^ a-zA-Z0-9-_:/;*\\[\\]()?!^\\+=@&~#{}|\\\\<>%.]*",URI_WITH_AT:"duniter://(?:([A-Za-z0-9_-]+):)?("+m+"@([a-zA-Z0-9-.]+.[ a-zA-Z0-9-_:/;*?!^\\+=@&~#|<>%.]+)",URI_WITH_PATH:"duniter://([a-zA-Z0-9-.]+.[a-zA-Z0-9-_:.]+)/("+m+")(?:/([A-Za-z0-9_-]+))?",BMA_ENDPOINT:b.BMA+h,BMAS_ENDPOINT:b.BMAS+h,WS2P_ENDPOINT:b.WS2P+" ([a-f0-9]{8})"+h,BMATOR_ENDPOINT:b.BMATOR+" ([a-z0-9-_.]*|[0-9.]+|[0-9a-f:]+.onion)(?: ([0-9]+))?",WS2PTOR_ENDPOINT:b.WS2PTOR+" ([a-f0-9]{8}) ([a-z0-9-_.]*|[0-9.]+|[0-9a-f:]+.onion)(?: ([0-9]+))?(?: (.+))?"},T={PROTOCOL_VERSION:10,ROOT_BLOCK_HASH:"E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855",LIMIT_REQUEST_COUNT:5,LIMIT_REQUEST_DELAY:1e3,regexp:f,api:b},v=this;function O(e,n,t,i){v.started&&v.stop(),v.alive=!1,v.cache={getByPath:{},postByPath:{},wsByPath:{}},r.data&&r.data.node&&(e=e||r.data.node.host,n=n||r.data.node.port,t=angular.isDefined(t)?t:443==n||r.data.node.useSsl||v.forceUseSsl,i=!angular.isDefined(i)||i),e&&(v.host=e,v.port=n||80,v.useSsl=angular.isDefined(t)?t:443==v.port||v.forceUseSsl,v.useCache=!!angular.isDefined(i)&&i,v.server=l.getServer(e,n),v.url=l.getUrl(e,n,"",t))}function R(e){return new RegExp("^"+e+"$")}function N(e){return new RegExp(e)}function I(){v.cache&&(console.warn("[BMA] Closing all websockets..."),_.keys(v.cache.wsByPath||{}).forEach((function(e){v.cache.wsByPath[e].close()})),v.cache.wsByPath={})}function S(e){l.getUrl(e.node.host,e.node.port,"",e.node.useSsl)!=v.url&&(O(e.node.host,e.node.port,e.node.useSsl,v.useCache),v.restart())}v.api=new a(this,"BMA-"+v.server),v.started=!1,v.init=O,v.forceUseSsl=!!("true"===s.httpsMode||!0===s.httpsMode||"force"===s.httpsMode||n.location&&"https:"===n.location.protocol),v.forceUseSsl&&console.debug("[BMA] Enable SSL (forced by config or detected in URL)"),o&&O(o,c,u,d),v.useCache=d,v.cleanCache=function(){console.debug("[BMA] Cleaning requests cache..."),I(),v.cache={getByPath:{},postByPath:{},wsByPath:{}}},get=function(e,n){n=v.useCache&&n;var t=e+(n?"#"+n:""),a=function(o){if(!v.started)return v._startPromise||console.warn("[BMA] Trying to get [{0}] before start(). Waiting...".format(e)),v.ready().then((function(){return a(o)}));var s=v.cache.getByPath[t];s||(s=n?l.getWithCache(v.host,v.port,e,v.useSsl,n):l.get(v.host,v.port,e,v.useSsl),v.cache.getByPath[t]=s);var r=1;return s(o).catch((function(e){if(e&&e.ucode==A.errorCodes.HTTP_LIMITATION&&r<=A.constants.LIMIT_REQUEST_COUNT)return 1===r&&(console.warn("[BMA] Too many HTTP requests: Will wait then retry..."),UIUtils.loading.update({template:"COMMON.LOADING_WAIT"})),i((function(){return r++,s(o)}),A.constants.LIMIT_REQUEST_DELAY);throw e}))};return a},post=function(e){var n=function(t,i){if(!v.started)return v._startPromise||console.error("[BMA] Trying to post [{0}] before start()...".format(e)),v.ready().then((function(){return n(t,i)}));var a=v.cache.postByPath[e];return a||(a=l.post(v.host,v.port,e,v.useSsl),v.cache.postByPath[e]=a),a(t,i)};return n},ws=function(e){return function(){var n=v.cache.wsByPath[e];return n&&!n.isClosed()||((n=l.ws(v.host,v.port,e,v.useSsl)).onclose=function(){delete v.cache.wsByPath[e]},v.cache.wsByPath[e]=n),n}},v.isAlive=function(){return l.get(v.host,v.port,"/node/summary",v.useSsl)().then((function(e){var n=e&&e.duniter&&e.duniter.software,t=!0;return"duniter"===n&&e.duniter.version&&r.data.minVersion?t=l.version.isCompatible(r.data.minVersion,e.duniter.version):"gchange-pod"===n&&e.duniter.version&&r.data.plugins.es.minVersion?t=l.version.isCompatible(r.data.plugins.es.minVersion,e.duniter.version):console.debug("[BMA] Unknown node software [{0} v{1}]: could not check compatibility.".format(n||"?",e.duniter.version||"?")),t||console.error("[BMA] Incompatible node [{0} v{1}]: expected at least v{2}".format(n,e.duniter.version,r.data.minVersion)),t})).catch((function(){return!1}))},v.isStarted=function(){return v.started},v.ready=function(){return v.started?e.when(!0):v._startPromise||v.start()},v.start=function(){if(v._startPromise)return v._startPromise;if(v.started)return e.when(v.alive);if(!v.host)return r.ready().then((function(){return v.init(),v.useCache=!0,v.start()}));v.useSsl?console.debug("[BMA] Starting [{0}] (SSL on)...".format(v.server)):console.debug("[BMA] Starting [{0}]...".format(v.server));var n=Date.now();return v._startPromise=e.all([r.ready,v.isAlive()]).then((function(e){return v.alive=e[1],v.alive?(p&&0!==p.length||function(){p=[r.api.data.on.changed(t,S,this)]}(),console.debug("[BMA] Started in "+(Date.now()-n)+"ms"),v.api.node.raise.start(),v.started=!0,delete v._startPromise,!0):(console.error("[BMA] Could not start [{0}]: node unreachable".format(v.server)),v.started=!0,delete v._startPromise,!1)})),v._startPromise},v.stop=function(){console.debug("[BMA] Stopping..."),_.forEach(p,(function(e){e()})),p=[],l.cache.clear(),v.cleanCache(),v.alive=!1,v.started=!1,delete v._startPromise,v.api.node.raise.stop()},v.restart=function(){return v.stop(),i(v.start,200).then((function(e){return e&&v.api.node.raise.restart(),e}))},v.api.registerEvent("node","start"),v.api.registerEvent("node","stop"),v.api.registerEvent("node","restart");var A={errorCodes:{REVOCATION_ALREADY_REGISTERED:1002,HTTP_LIMITATION:1006,IDENTITY_SANDBOX_FULL:1007,NO_MATCHING_IDENTITY:2001,UID_ALREADY_USED:2003,NO_MATCHING_MEMBER:2004,NO_IDTY_MATCHING_PUB_OR_UID:2021,WRONG_SIGNATURE_MEMBERSHIP:2006,MEMBERSHIP_ALREADY_SEND:2007,NO_CURRENT_BLOCK:2010,BLOCK_NOT_FOUND:2011,SOURCE_ALREADY_CONSUMED:2015,TX_INPUTS_OUTPUTS_NOT_EQUAL:2024,TX_OUTPUT_SUM_NOT_EQUALS_PREV_DELTAS:2025,TX_ALREADY_PROCESSED:2030},constants:T,regexp:{USER_ID:R(f.USER_ID),COMMENT:R(f.COMMENT),PUBKEY:R(f.PUBKEY),PUBKEY_WITH_CHECKSUM:R(f.PUBKEY_WITH_CHECKSUM),CURRENCY:R(f.CURRENCY),URI:R(f.URI),BMA_ENDPOINT:R(f.BMA_ENDPOINT),BMAS_ENDPOINT:R(f.BMAS_ENDPOINT),WS2P_ENDPOINT:R(f.WS2P_ENDPOINT),BMATOR_ENDPOINT:R(f.BMATOR_ENDPOINT),WS2PTOR_ENDPOINT:R(f.WS2PTOR_ENDPOINT),TX_OUTPUT_SIG:R(E),TX_OUTPUT_FUNCTION:N("SIG\\(([0-9a-zA-Z]{43,44})\\)|XHX\\(([A-F0-9]{1,64})\\)|CSV\\(([0-9]{1,8})\\)|CLTV\\(([0-9]{1,10})\\)"),TX_OUTPUT_OBJ_OPERATOR_AND:N(g+"([ ]*&&[ ]*("+g+"))+"),TX_OUTPUT_OBJ_OPERATOR_OR:N(g+"([ ]*\\|\\|[ ]*("+g+"))+"),TX_OUTPUT_OBJ:N(g),TX_OUTPUT_OBJ_OPERATOR:N("OBJ\\(([0-9]+)\\)[ ]*(&&)|(\\|\\|)[ ]*OBJ\\(([0-9]+)\\)"),TX_OUTPUT_OBJ_PARENTHESIS:N("\\(("+g+")\\)"),TX_OUTPUT_FUNCTIONS:N("SIG\\(([0-9a-zA-Z]{43,44})\\)|XHX\\(([A-F0-9]{1,64})\\)|CSV\\(([0-9]{1,8})\\)|CLTV\\(([0-9]{1,10})\\)([ ]*(&&)|(\\|\\|)[ ]*SIG\\(([0-9a-zA-Z]{43,44})\\)|XHX\\(([A-F0-9]{1,64})\\)|CSV\\(([0-9]{1,8})\\)|CLTV\\(([0-9]{1,10})\\))*")},node:{summary:get("/node/summary",l.cache.LONG),same:function(e,n){return e===v.host&&(!v.port&&!n||v.port==n||80)&&v.useSsl==(n&&443===n)},forceUseSsl:v.forceUseSsl},network:{peering:{self:get("/network/peering"),peers:get("/network/peering/peers")},peers:get("/network/peers"),ws2p:{info:get("/network/ws2p/info"),heads:get("/network/ws2p/heads")}},wot:{ lookup:get("/wot/lookup/:search",l.cache.MEDIUM),certifiedBy:get("/wot/certified-by/:pubkey"),certifiersOf:get("/wot/certifiers-of/:pubkey"),member:{all:get("/wot/members",l.cache.LONG),pending:get("/wot/pending",l.cache.SHORT)},requirements:function(e,n){return!0!==n?A.raw.wot.requirements(e):A.raw.wot.requirementsWithCache(e)},add:post("/wot/add"),certify:post("/wot/certify"),revoke:post("/wot/revoke")},blockchain:{parameters:get("/blockchain/parameters",l.cache.VERY_LONG),block:get("/blockchain/block/:block",l.cache.SHORT),blocksSlice:get("/blockchain/blocks/:count/:from"),current:get("/blockchain/current",l.cache.SHORT),membership:post("/blockchain/membership"),stats:{ud:get("/blockchain/with/ud",l.cache.MEDIUM),tx:get("/blockchain/with/tx"),newcomers:get("/blockchain/with/newcomers",l.cache.MEDIUM),hardship:get("/blockchain/hardship/:pubkey"),difficulties:get("/blockchain/difficulties")}},tx:{sources:get("/tx/sources/:pubkey",l.cache.SHORT),process:post("/tx/process"),history:{all:function(e){return A.raw.tx.history.all(e).then((function(e){return e.history=e.history||{},e.history.sending=[],e.history.pendings=[],e}))},times:function(e,n){return(!0!==n?A.raw.tx.history.times(e):A.raw.tx.history.timesWithCache(e)).then((function(e){return e.history=e.history||{},e.history.sending=[],e.history.pendings=[],e}))},blocks:get("/tx/history/:pubkey/blocks/:from/:to",l.cache.LONG),pending:get("/tx/history/:pubkey/pending")}},ud:{history:get("/ud/history/:pubkey")},uri:{},version:{},raw:{wot:{requirementsWithCache:get("/wot/requirements/:pubkey",l.cache.LONG),requirements:get("/wot/requirements/:pubkey")},tx:{history:{timesWithCache:get("/tx/history/:pubkey/times/:from/:to",l.cache.LONG),times:get("/tx/history/:pubkey/times/:from/:to"),all:get("/tx/history/:pubkey")}}}};A.tx.parseUnlockCondition=function(e){for(var n,t,i,a,o=e,s=[],r={},l=A.regexp.TX_OUTPUT_FUNCTION.exec(o);l;)n={},t="OBJ("+s.length+")",n.type=o.substr(l.index,l[0].indexOf("(")),n.value=l[1]||l[2]||l[3]||l[4],s.push(n),r[n.type]=r[n.type]++||1,o=o.replace(l[0],t),l=A.regexp.TX_OUTPUT_FUNCTION.exec(o);for(var c=!0;c;){for(c=!!(l=A.regexp.TX_OUTPUT_OBJ_OPERATOR_AND.exec(o));l;){for(n={},t="OBJ("+s.length+")",n.type="AND",n.children=[],s.push(n),i=l[0],a=A.regexp.TX_OUTPUT_OBJ.exec(i);a;)n.children.push(s[a[1]]),i=i.replace(a[0],""),a=A.regexp.TX_OUTPUT_OBJ.exec(i);o=o.replace(l[0],t),l=A.regexp.TX_OUTPUT_OBJ_OPERATOR_AND.exec(i)}for(l=A.regexp.TX_OUTPUT_OBJ_OPERATOR_OR.exec(o),c=c||!!l;l;){for(n={},t="OBJ("+s.length+")",n.type="OR",n.children=[],s.push(n),i=l[0],a=A.regexp.TX_OUTPUT_OBJ.exec(i);a;)n.children.push(s[a[1]]),i=i.replace(a[0],""),a=A.regexp.TX_OUTPUT_OBJ.exec(i);o=o.replace(l[0],t),l=A.regexp.TX_OUTPUT_OBJ_OPERATOR_AND.exec(o)}for(l=A.regexp.TX_OUTPUT_OBJ_PARENTHESIS.exec(o),c=c||!!l;l;)o=o.replace(l[0],l[1]),l=A.regexp.TX_OUTPUT_OBJ_PARENTHESIS.exec(o)}if(0!==(r=_.keys(r)).length)return console.debug("[BMA] Unlock conditions successfully parsed:",n),{unlockFunctions:r,unlockTree:n};console.error("[BMA] Unparseable unlock condition: ",output)},A.node.parseEndPoint=function(e,n){var t=A.regexp.BMA_ENDPOINT.exec(e);return t?{dns:t[2]||"",ipv4:t[4]||"",ipv6:t[6]||"",port:t[8]||80,useSsl:t[8]&&443==t[8],path:t[10],useBma:!0}:(t=A.regexp.BMAS_ENDPOINT.exec(e))?{dns:t[2]||"",ipv4:t[4]||"",ipv6:t[6]||"",port:t[8]||80,useSsl:!0,path:t[10],useBma:!0}:(t=A.regexp.BMATOR_ENDPOINT.exec(e))?{dns:t[1]||"",port:t[2]||80,useSsl:!1,useTor:!0,useBma:!0}:(t=A.regexp.WS2P_ENDPOINT.exec(e))?{ws2pid:t[1]||"",dns:t[3]||"",ipv4:t[5]||"",ipv6:t[7]||"",port:t[9]||80,useSsl:t[9]&&443==t[9],path:t[11]||"",useWs2p:!0}:(t=A.regexp.WS2PTOR_ENDPOINT.exec(e))?{ws2pid:t[1]||"",dns:t[2]||"",port:t[3]||80,path:t[4]||"",useSsl:!1,useTor:!0,useWs2p:!0}:n&&(t=R(n+h).exec(e))?{dns:t[2]||"",ipv4:t[4]||"",ipv6:t[6]||"",port:t[8]||80,useSsl:t[8]&&443==t[8],path:t[10],useBma:!1}:void 0},A.copy=function(n){var t=v.started;if(l.getUrl(n.host,n.port,"",n.useSsl)!==v.url)return v.init(n.host,n.port,n.useSsl,v.useCache),t?v.restart():e.when()},A.wot.member.uids=function(){return A.wot.member.all().then((function(e){return e.results.reduce((function(e,n){return e[n.pubkey]=n.uid,e}),{})}))},A.wot.member.get=function(e){return A.wot.member.uids().then((function(n){var t=n[e];return{pubkey:e,uid:t||null}}))},A.wot.member.getByUid=function(e){return A.wot.member.all().then((function(n){return _.findWhere(n.results,{uid:e})}))},A.blockchain.blocks=function(e){return A.raw.getHttpRecursive(A.blockchain.block,"block",e)},A.network.peering.peersByLeaves=function(e){return A.raw.getHttpRecursive(A.network.peering.peers,"leaf",e,0,10)},A.raw.getHttpRecursive=function(n,t,a,o,s){return o=angular.isDefined(o)?o:0,s=s||A.constants.LIMIT_REQUEST_COUNT,e((function(r,l){var c=[],u=[];_.each(a.slice(o,o+s),(function(e){var i={};i[t]=e,u.push(n(i).then((function(e){e&&c.push(e)})))})),e.all(u).then((function(){o0?e.dividend*Math.pow(10,e.unitbase):e.dividend}))}))},A.uri.parse=function(n){return e((function(e,t){var i;if(R(f.PUBKEY).test(n))e({pubkey:n});else if(R(f.PUBKEY_WITH_CHECKSUM).test(n)){console.debug("[BMA.parse] Detecting a pubkey with checksum: "+n);var a=A.regexp.PUBKEY_WITH_CHECKSUM.exec(n);i=a[1];var o=a[2];console.debug("[BMA.parse] Detecting a pubkey {"+i+"} with checksum {"+o+"}");var s=csCrypto.util.pkChecksum(i);console.debug("[BMA.parse] Expecting checksum for pubkey is {"+s+"}"),o!=s?t({message:"ERROR.PUBKEY_INVALID_CHECKSUM"}):e({pubkey:i})}else if(n.startsWith("duniter://")){var r,c=l.uri.parse(n),u=-1===c.host.indexOf(".")?c.host:null,d=-1!==c.host.indexOf(".")?c.host:null;if(c.username&&(c.password?(r=c.username,i=c.password):i=c.username),c.pathname){var p=c.pathname.split("/"),m=p?p.length:0,E=0;if(!u&&m>E&&(u=p[E++]),!i&&m>E&&(i=p[E++]),!r&&m>E&&(r=p[E++]),m>E)return void t({message:"Bad Duniter URI format. Invalid path (incomplete or redundant): "+c.pathname})}if(u)return d||e({uid:r,pubkey:i,currency:u}),l.get(d+"/blockchain/parameters")().then((function(n){n.currency===u?e({uid:r,pubkey:i,host:d,currency:u}):t({message:"Node's currency ["+n.currency+"] does not matched URI's currency ["+u+"]."})})).catch((function(e){console.error(e),t({message:"Could not get node parameter. Currency could not be retrieve"})}));if(!d)return void t({message:"Bad Duniter URI format. Missing currency name (or node address)."});l.get(d+"/blockchain/parameters")().then((function(n){e({uid:r,pubkey:i,host:d,currency:n.currency})})).catch((function(e){console.error(e),t({message:"Could not get node parameter. Currency could not be retrieve"})}))}else console.debug("[BMA.parse] Could not parse URI: "+n),t({message:"ERROR.UNKNOWN_URI_FORMAT"})})).then((function(e){if(e){if(e.pubkey&&!R(f.PUBKEY).test(e.pubkey))throw{message:"Invalid pubkey format ["+e.pubkey+"]"};if(e.uid&&!R(f.USER_ID).test(e.uid))throw{message:"Invalid uid format ["+e.uid+"]"};if(e.currency&&!R(f.CURRENCY).test(e.currency))throw{message:"Invalid currency format ["+e.currency+"]"};return e}}))};var C=r.data.duniterLatestReleaseUrl&&l.uri.parse(r.data.duniterLatestReleaseUrl);A.raw.getLatestRelease=C?l.getWithCache(C.host,C.port,"/"+C.pathname,443==+C.port||"https:"===C.protocol||v.forceUseSsl,l.cache.LONG):function(){return e.when()},A.version.latest=function(){return A.raw.getLatestRelease().then((function(e){if(e)return e.name&&e.html_url?{version:e.name,url:e.html_url}:e.tag_name&&e.html_url?{version:e.tag_name.substring(1),url:e.html_url}:void 0})).catch((function(e){console.error("[BMA] Failed to get Duniter latest version",e)}))},A.websocket={block:ws("/ws/block"),peer:ws("/ws/peer"),close:I},angular.merge(v,A)}var u=new c(void 0,void 0,void 0,!0);return u.instance=function(e,n,t,i){return new c(e,n,t,i)},u.lightInstance=function(e,n,t,i){return{host:e,port:n=n||80,useSsl:t=angular.isDefined(t)?t:443==n,url:l.getUrl(e,n,"",t),node:{summary:l.getWithCache(e,n,"/node/summary",t,l.cache.LONG,!1,i)},network:{peering:{self:l.get(e,n,"/network/peering",t,i)},peers:l.get(e,n,"/network/peers",t,i)},blockchain:{current:l.get(e,n,"/blockchain/current",t,i),stats:{hardship:l.get(e,n,"/blockchain/hardship/:pubkey",t,i)}}}},u}]),angular.module("cesium.wot.services",["ngApi","cesium.bma.services","cesium.crypto.services","cesium.utils.services","cesium.settings.services"]).factory("csWot",["$q","$timeout","BMA","Api","CacheFactory","csConfig","csCurrency","csSettings","csCache",function(e,n,t,i,a,o,s,r,l){function c(a){var o=new i(this,"csWot-"+a),c=l.get("csWot-idty-",l.constants.SHORT),u=function(e){var n={};return e.reduce((function(e,t){return t.id=t.id||t.uid+"-"+t.pubkey,n[t.id]?e:(n[t.id]=!0,e.concat(t))}),[])},d=function(e,n,t){return n=n||0,e=u(e),e=_.sortBy(e,(function(e){var n=1;return n+=1e6*e.block,-(n+=10*(900-e.uid.toLowerCase().charCodeAt(0)))})),angular.isDefined(t)&&e.length>t&&(e=e.slice(n,n+t)),e},p=function(e,n){return t.wot.lookup({search:e||n}).then((function(i){if(!i||!i.results||!i.results.length)return{uid:null,pubkey:e,hasSelf:!1};var a=i.results.reduce((function(e,n){return e.concat(n.uids.reduce((function(e,t){var i=t.meta.timestamp.split("-",2);return e.concat({uid:t.uid,pubkey:n.pubkey,timestamp:t.meta.timestamp,number:parseInt(i[0]),hash:i[1],revoked:t.revoked,revocationNumber:t.revoked_on,sig:t.self})}),[]))}),[]);a.length&&(a=_.sortBy(a,(function(e){var t=0;return t+=1e10*(n&&e.uid===n?1:0),t+=1e9*(e.revoked?0:1),-(t+=1*(e.number?e.number:0))})));var o=a[0],r=[o.number];return o.revocationNumber&&r.push(o.revocationNumber),t.blockchain.blocks(r).then((function(e){return o.sigDate=e[0].medianTime,0!==o.number&&o.hash!==e[0].hash&&(o.hasBadSelfBlock=!0),o.revocationNumber&&(o.revocationTime=e[1].medianTime),o})).catch((function(e){if(e&&e.ucode==t.errorCodes.BLOCK_NOT_FOUND&&0===o.number)return o.sigDate=s.date.now(),o;throw e}))})).catch((function(n){if(n&&n.ucode==t.errorCodes.NO_MATCHING_IDENTITY)return{uid:null,pubkey:e,hasSelf:!1};throw n}))},m=function(e,n,i,a,o,l){function c(e,n){return e+"-"+n}var u=!0,d=i?i.reduce((function(e,n){var t=c(n.pubkey,n.cert_time?n.cert_time.block:n.sigDate);return n.cert_time||(u=!1),e[t]=n,e}),{}):{};return e({pubkey:n}).then((function(e){return e.certifications.reduce((function(e,n){var t=!n.written,i=n.cert_time?n.cert_time.medianTime:null,s=i?t?i+a.sigWindow-o:i+a.sigValidity-o:0;s=s<0?0:s;var l=c(n.pubkey,u&&n.cert_time?n.cert_time.block:n.sigDate);return delete d[l],e.concat({pubkey:n.pubkey,uid:n.uid,time:i,isMember:n.isMember,wasMember:n.wasMember,expiresIn:s,willExpire:s&&s<=r.data.timeWarningExpire,pending:t,block:null!==n.written?n.written.number:n.cert_time?n.cert_time.block:null,valid:s>0})}),[])})).catch((function(e){if(e&&e.ucode==t.errorCodes.NO_MATCHING_MEMBER)return[];throw e})).then((function(e){var n=_.values(d);if(!n.length)return e;if(s.data.initPhase)return n.reduce((function(e,n){return e.concat({pubkey:n.pubkey,uid:n.uid,isMember:n.isMember,wasMember:n.wasMember,time:null,expiresIn:a.sigWindow,willExpire:!1,pending:!0,block:0,valid:!0})}),e);var i=n.reduce((function(e,n){var t=u&&n.cert_time?n.cert_time.block:n.sigDate?n.sigDate.split("-")[0]:null;return angular.isDefined(t)&&(e[t]?e[t].push(n):e[t]=[n]),e}),{});return t.blockchain.blocks(_.keys(i)).then((function(n){return e=n.reduce((function(e,n){return e.concat(i[n.number].reduce((function(e,t){var i=n.medianTime,s=Math.max(0,i+a.sigWindow-o),c=!t.cert_time||!t.cert_time.block_hash||t.cert_time.block_hash==n.hash;c||console.debug("[wot] Invalid cert {0}: block hash changed".format(t.pubkey.substring(0,8)));var d=s>0&&(!l||t.isMember)&&c;return e.concat({pubkey:t.pubkey,uid:t.uid,isMember:t.isMember,wasMember:t.wasMember,time:i,expiresIn:s,willExpire:s&&s<=r.data.timeWarningExpire,pending:!0,block:u&&t.cert_time?t.cert_time.block:t.sigDate?t.sigDate.split("-")[0]:null,valid:d})}),[]))}),e)}))})).then((function(e){var n=e.reduce((function(e,n){return!n.pending&&n.valid&&n.expiresIn>=a.sigWindow&&(e[n.pubkey]=!0),e}),{});e=function(e){return _.sortBy(e,(function(e){var n=1;return n+=1e12*(e.expiresIn?e.expiresIn:0),n+=1e7*(e.isMember?1:0),-(n+=10*(e.block?e.block:0))}))}(e);var t=[],i=[];return{valid:e.reduce((function(e,a){return a.pending?(a.valid&&!n[a.pubkey]?t.push(a):a.valid||n[a.pubkey]||i.push(a),e):e.concat(a)}),[]),pending:t,error:i}}))},E=function(n,i,a,r){var l;if(!n&&a&&!r)return t.wot.member.getByUid(a).then((function(e){return e?E(e.pubkey,i,e.uid):E(n,i,a,!0)}));if(n){if((l=i?c.get(n):null)&&(!a||l.uid==a))return console.debug("[wot] Identity "+n.substring(0,8)+" found in cache"),e.when(l);console.debug("[wot] Loading identity "+n.substring(0,8)+"..."),l={pubkey:n}}else console.debug("[wot] Loading identity from uid "+a),l={};var u,d,g=Date.now();return e.all([s.parameters().then((function(e){u=e,l.sigQty=u.sigQty,l.sigStock=u.sigStock})),s.blockchain.current().then((function(e){d=e.medianTime})).catch((function(e){if(!e||e.ucode!=t.errorCodes.NO_CURRENT_BLOCK)throw e;d=Math.trunc((new Date).getTime()/1e3)})),e.when().then((function(){l.requirements={},l.isMember=!1})),p(n,a).then((function(e){angular.merge(l,e)}))]).then((function(){if(l.requirements.uid){var n=l.requirements.uid+"-"+l.requirements.meta.timestamp;return e.all([m(t.wot.certifiersOf,l.pubkey,l.lookup?l.lookup.certifications[n]:null,u,d,!0).then((function(e){l.received_cert=e.valid,l.received_cert_pending=e.pending,l.received_cert_error=e.error})),m(t.wot.certifiedBy,l.pubkey,l.lookup?l.lookup.givenCertifications:null,u,d,!1).then((function(e){l.given_cert=e.valid,l.given_cert_pending=e.pending,l.given_cert_error=e.error}))])}})).then((function(){return function(e){e.requirements.needCertificationCount=!e.requirements.needMembership&&e.requirements.certificationCount0&&(T(e,{type:"error",message:"INFO.IDENTITY_WILL_MISSING_CERTIFICATIONS",messageParams:e.requirements}),console.debug("[wot] Identity {0} will need {1} certification(s)".format(e.uid,e.requirements.willNeedCertificationCount)))}(l),o.data.raisePromise.load(l).catch((function(e){console.debug("Error while loading identity data, on extension point."),console.error(e)}))})).then((function(){if(l.pubkey)return delete l.lookup,c.put(l.pubkey,l),console.debug("[wot] Identity "+l.pubkey.substring(0,8)+" loaded in "+(Date.now()-g)+"ms"),l}))},g=function(n,i){if(!n||n.trim()!==n)return e.when(void 0);var a=n.replace(/(^|\s)#\w+/g,"");return a=(a=a.replace(/[^a-zA-Z0-9_-\s]+/g,"")).replace(/\s+/g," ").trim(),(i=i||{}).addUniqueId=!angular.isDefined(i.addUniqueId)||i.addUniqueId,i.allowExtension=!angular.isDefined(i.allowExtension)||i.allowExtension,i.excludeRevoked=!!angular.isDefined(i.excludeRevoked)&&i.excludeRevoked,(a?e.all(a.split(" ").reduce((function(e,n){return console.debug("[wot] Will search on: '"+n+"'"),e.concat(t.wot.lookup({search:n}))}),[])).then((function(e){return e.reduce((function(e,n){return e.concat(n.results.reduce((function(e,n){return e.concat(n.uids.reduce((function(e,t){var a=t.meta.timestamp.split("-",2),o=!t.revoked&&t.revocation_sig;return i.excludeRevoked&&o?e:e.concat({uid:t.uid,pubkey:n.pubkey,number:a[0],hash:a[1],revoked:o})}),[]))}),[]))}),[])})).catch((function(e){if(e&&e.ucode==t.errorCodes.NO_MATCHING_IDENTITY)return[];throw e})):e.when([])).then((function(e){if(!i.allowExtension)return i.addUniqueId?u(e):e;var a=e.length;return o.data.raisePromise.search(n,e,"pubkey").then((function(){if(e.length>a&&_.filter(e,(function(e){return!e.uid&&e.pubkey})).length)return t.wot.member.uids().then((function(n){_.forEach(e,(function(e){!e.uid&&e.pubkey&&(e.uid=n[e.pubkey])}))}))})).then((function(){return i.addUniqueId?u(e):e}))}))},h=function(i,a,o,s){return e((function(r,l){var c=[],u=[];_.each(i.slice(a,a+o),(function(e){u.push(t.blockchain.block({block:e}).then((function(e){e&&e.joiners&&_.each(e.joiners,(function(n){var t=n.split(":"),i=t[t.length-1]+"-"+t[0];c.push({id:i,uid:t[t.length-1],pubkey:t[0],memberDate:e.medianTime,block:e.number})}))})))})),e.all(u).then((function(){c.lengtht.block)return;l[n.pubkey]=n,r[n.block]?r[n.block].push(n):r[n.block]=[n],t&&(r[t.block]=r[t.block].reduce((function(e,n){return n.pubkey==t.pubkey?e:(e||[]).concat(n)}),null),null===r[t.block]&&delete r[t.block])}}));var c=d(_.values(l),n,i),u=c.reduce((function(e,n){return e.concat(n.block)}),[]);return e.all([t.blockchain.blocks(_.uniq(u)).then((function(e){_.forEach(e,(function(e){_.forEach(r[e.number],(function(n){n.sigDate=e.medianTime,0!==e.number&&n.blockHash!==e.hash&&(T(n,{type:"error",message:"ERROR.WOT_PENDING_INVALID_BLOCK_HASH"}),console.debug("Invalid membership for uid={0}: block hash changed".format(n.uid)))}))}))})),f(c,"pubkey",!0)]).then((function(){return c}))}}))},all:function(){return b(["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","u","v","w","x","y","z"],0,t.constants.LIMIT_REQUEST_COUNT).then((function(e){return f(e,"pubkey",!0).then((function(){return u(e)}))}))},extend:function(e,n,t){return f([e],n,t).then((function(e){return e[0]}))},extendAll:f,api:o}}var u=c("default");return u.instance=c,u}]),angular.module("cesium.tx.services",["ngApi","cesium.bma.services","cesium.settings.services","cesium.wot.services"]).factory("csTx",["$q","$timeout","$filter","$translate","UIUtils","BMA","Api","csConfig","csSettings","csWot","FileSaver",function(e,n,t,i,a,o,s,r,l,c,u){function d(n,o){var r=new s(this,"csTx-"+n),d=function(e,n,t,i,a){n&&0!==n.length&&_.forEach(n,(function(n){if(n.block_number||a){var s,r,l=!1,c=n.issuers.reduce((function(n,t){return l=t===e||l,n+(t!==e?", "+t:"")}),"");c.length>0&&(c=c.substring(2));var u,d=[],p=n.outputs.reduce((function(t,i,a){var p=i.split(":",3);r=parseInt(p[1]);var E=m(parseInt(p[0]),r),g=p[2],h=o.regexp.TX_OUTPUT_SIG.exec(g);if(h){var b=h[1];if(b==e){if(!l)return t+E;null===n.block_number&&d.push({amount:parseInt(p[0]),base:r,type:"T",identifier:n.hash,noffset:a,consumed:!1})}else if(""!==b&&b!=c&&(s=b),l)return t-E}else if(-1!=g.indexOf("SIG("+e+")")){var f=o.tx.parseUnlockCondition(g);if(f)return f.amount=E,(u=u||[]).push(f),console.debug("[tx] has locked output:",f),t+E}return t}),0),E=p>0?c:s,g=n.time||n.blockstampTime,h=p+":"+n.hash+":"+g;if(!i[h]&&0!==p){i[h]=!0;var b={time:g,amount:p,pubkey:E,comment:n.comment,isUD:!1,hash:n.hash,locktime:n.locktime,block_number:n.block_number};l&&null===n.block_number&&(b.inputs=n.inputs,b.sources=d),u&&(b.lockedOutputs=u),t.push(b)}}}))},p=function(n,t,i){return e((function(i,a){var s=[],r=[],c=[],u=Math.trunc((new Date).getTime()/1e3);t=t||u-l.data.walletHistoryTimeSecond;var p={},m={pendings:[]},E=function(e){d(n,e.history.sent,s,p),d(n,e.history.received,s,p),d(n,e.history.sending,s,p),d(n,e.history.pending,c,p,!0)},g=[o.tx.history.pending({pubkey:n}).then(E)];if(-1!==t){for(var h=l.data.walletHistorySliceSecond,b=t-t%h;b-h0?s=!1:(_.forEach(e.inputs,(function(e){var n=e.split(":").slice(2).join(":"),t=a.sourcesIndexByKey[n];if(!angular.isDefined(t))return s=!1,!1;o.push(a.sources[t])})),e.sources&&E(a,e.sources),delete e.sources,delete e.inputs),s?(i+=e.amount,n.push(e),_.forEach(o,(function(e){e.consumed=!0}))):t.push(e)}for(var s=a.tx.pendings,r=!0;s&&s.length>0;)_.forEach(s,o),t.length>0&&n.length>0&&r?(s=t,t=[],r=!1):s=null;return a.tx.pendings=n,a.tx.errors=t,a.balance=i,c.extendAll((a.tx.history||[]).concat(a.tx.pendings||[]),"pubkey")})).then((function(){return console.debug("[tx] TX and sources loaded in "+((new Date).getTime()-i)+"ms"),a}))};return downloadHistoryFile=function(n,s){return(s=s||{}).fromTime=s.fromTime||-1,console.debug("[tx] Exporting TX history for pubkey [{0}]".format(n.substr(0,8))),e.all([i(["ACCOUNT.HEADERS.TIME","COMMON.UID","COMMON.PUBKEY","ACCOUNT.HEADERS.AMOUNT","ACCOUNT.HEADERS.COMMENT"]),o.blockchain.current(),h(n,s.fromTime)]).then((function(e){var o=e[0],s=e[1],r=s&&s.medianTime||moment().utc().unix(),l=s&&s.currency;return(e=e[2])&&e.tx&&e.tx.history?i("ACCOUNT.FILE_NAME",{currency:l,pubkey:n,currentTime:r}).then((function(e){var n=t("formatDecimal"),i=(t("formatPubkey"),t("formatDate")),a=(t("formatDateForFile"),t("currencySymbolNoHtml")),s=[o["ACCOUNT.HEADERS.TIME"],o["COMMON.UID"],o["COMMON.PUBKEY"],o["ACCOUNT.HEADERS.AMOUNT"]+" ("+a(l)+")",o["ACCOUNT.HEADERS.COMMENT"]],r=e.tx.history.reduce((function(e,t){return e.concat([i(t.time),t.uid,t.pubkey,n(t.amount/100),'"'+t.comment+'"'].join(";")+"\n")}),[s.join(";")+"\n"]),c=new Blob(r,{type:"text/plain; charset=utf-8"});u.saveAs(c,e)})):a.toast.show("INFO.EMPTY_TX_HISTORY")}))},{id:n,load:h,downloadHistoryFile:downloadHistoryFile,api:r}}var p=d("default",o);return p.instance=d,p}]),angular.module("cesium.wallet.services",["ngApi","ngFileSaver","cesium.bma.services","cesium.crypto.services","cesium.utils.services","cesium.settings.services"]).factory("csWallet",["$q","$rootScope","$timeout","$translate","$filter","Api","localStorage","CryptoUtils","BMA","csConfig","csSettings","FileSaver","Blob","csWot","csTx","csCurrency",function(e,n,t,i,a,o,s,r,l,c,u,d,p,m,E,g){function h(i,a){var l,m,E,h={},b=new o(this,"csWallet-"+i),f=function(e){h.loaded=!1,h.pubkey=null,h.keypair={signSk:null,signPk:null},h.uid=null,h.isNew=null,h.events=[],T(),m=!1,E=void 0,e?b.data.raise.init(h):(u.data.useLocalStorage||u.reset(),b.data.raise.reset(h))},T=function(){h.keypair={signSk:null,signPk:null}},v=function(){return!!h.pubkey},O=function(n){return m?v()?e.when(h.keypair):e.reject("Not auth"):(E||M()).then((function(){return O(n)}))},R=function(){if(u.data.useLocalStorage)if(v()&&u.data.rememberMe){var e={keypair:h.keypair,pubkey:h.pubkey,version:c.version};s.setObject("GCHANGE_DATA",e)}else s.setObject("GCHANGE_DATA",null);else s.setObject("GCHANGE_DATA",null);s.setObject("CESIUM_DATA",null)},N=function(){return e.all([s.get("GCHANGE_DATA"),s.get("CESIUM_DATA")]).then((function(e){var n=e[0]||e[1];if(n)return y(n,!1).then((function(e){if(e&&e.keypair&&e.pubkey)return h.keypair=e.keypair,h.pubkey=e.pubkey,h.loaded=!1,b.data.raisePromise.login(h)})).then((function(){return h}))}))},I=function(e){return e&&e.minData?A(e):e||h.loaded?C(e):S()},S=function(){return h.loaded=!1,e.all([b.data.raisePromise.load(h,null).catch((function(e){console.error("Error while loading wallet data, on extension point. Try to continue"),console.error(e)}))]).then((function(){return b.data.raisePromise.finishLoad(h).catch((function(e){console.error("Error while finishing wallet data load, on extension point. Try to continue"),console.error(e)}))})).then((function(){return h.loaded=!0,h})).catch((function(e){throw h.loaded=!1,e}))},A=function(e){return C(e=e||{})},C=function(n){n=n||{api:!0};var t=[];return L("requirements"),t.length&&!n.api||t.push(b.data.raisePromise.load(h,n)),e.all(t).then((function(){return b.data.raisePromise.finishLoad(h)})).then((function(){return h}))},D=function(e){var n=Math.round(e.answer.length/2),t=e.answer.substr(0,n),i=e.answer.substr(n);return r.scryptKeypair(t,i).then((function(n){return e.pubkey=r.util.encode_base58(n.signPk),e.keypair=n,e}))},L=function(e){h.events=h.events.reduce((function(n,t){return t.context&&t.context==e?n:n.concat(t)}),[])},y=function(n,t){return t=!!angular.isUndefined(t)||t,e((function(e,i){var a=JSON.parse(n||"{}");if(a&&a.keypair&&a.keypair.signPk&&a.keypair.signSk){var o,s={},r=new Uint8Array(32);for(o=0;o<32;o++)r[o]=a.keypair.signPk[o];s.signPk=r;var l=new Uint8Array(64);for(o=0;o<64;o++)l[o]=a.keypair.signSk[o];if(s.signSk=l,a.version&&a.keypair.boxPk){var c=new Uint8Array(32);for(o=0;o<32;o++)c[o]=a.keypair.boxPk[o];s.boxPk=c}if(a.version&&a.keypair.boxSk){var u=new Uint8Array(32);for(o=0;o<64;o++)u[o]=a.keypair.boxSk[o];s.boxSk=u}e({pubkey:a.pubkey,keypair:s,tx:a.tx})}else t?i("Not a valid Wallet.data object"):e()}))};function k(){console.debug("[wallet] Stopping..."),_.forEach(l,(function(e){e()})),l=[],f()}function P(){return k(),t(M,200)}function M(){console.debug("[wallet] Starting...");var t=(new Date).getTime();return E=e.all([u.ready(),g.ready(),a.ready()]).then(N).then((function(e){if(e&&e.pubkey)return I({minData:!0})})).then((function(){!function(){l=[u.api.data.on.changed(n,R,this),a.api.node.on.restart(n,P,this)]}(),console.debug("[wallet] Started in "+((new Date).getTime()-t)+"ms"),m=!0,E=null,b.data.raise.ready(h)})).then((function(){return h}))}return b.registerEvent("data","ready"),b.registerEvent("data","init"),b.registerEvent("data","loginCheck"),b.registerEvent("data","login"),b.registerEvent("data","load"),b.registerEvent("data","finishLoad"),b.registerEvent("data","logout"),b.registerEvent("data","unauth"),b.registerEvent("data","reset"),b.registerEvent("error","send"),b.registerEvent("action","certify"),f(!0),{id:i,data:h,ready:function(){return m?e.when():E||M()},start:M,stop:k,login:function(e,n){return r.scryptKeypair(e,n).then((function(e){return h.pubkey=r.util.encode_base58(e.signPk),h.keypair=e,b.data.raisePromise.loginCheck(h).catch((function(e){throw f(),e})).then((function(){return b.data.raisePromise.login(h)}))})).then((function(){return u.data.useLocalStorage&&R(),h}))},logout:function(){return e((function(e,n){f(),R(),b.data.raise.logout(),b.data.raise.unauth(),e()}))},isLogin:v,getKeypair:O,isDataLoaded:function(e){return e&&e.minData,h.loaded},isNeverUsed:function(){if(h.loaded)return!h.pubkey||!(h.name||h.profile||h.avatar)},isNew:function(){return!!h.isNew},isUserPubkey:function(e){return v()&&h.pubkey===e},getData:function(){return h},loadData:I,refreshData:C,downloadSaveId:function(e){return function(e){var n="Version: 10 \nType: SaveID\nQuestions: \n"+e.questions+"Issuer: "+h.pubkey+"\nCrypted-Nonce: "+e.nonce+"\nCrypted-Pubkey: "+e.pubkey+"\nCrypted-Salt: "+e.salt+"\nCrypted-Pwd: "+e.pwd+"\n";return r.sign(n,h.keypair).then((function(e){return n+=e+"\n",console.debug("Has generate an SaveID document:\n----\n"+n+"----"),n}))}(e).then((function(e){var n=new p([e],{type:"text/plain; charset=utf-8"});d.saveAs(n,"saveID.txt")}))},getCryptedId:function(e){return D(e).then((function(){return r.util.random_nonce()})).then((function(n){return e.nonce=n,r.box.pack(e.salt,e.nonce,e.keypair.boxPk,e.keypair.boxSk)})).then((function(n){return e.salt=n,r.box.pack(e.pwd,e.nonce,e.keypair.boxPk,e.keypair.boxSk)})).then((function(n){return e.pwd=n,e.nonce=r.util.encode_base58(e.nonce),e}))},recoverId:function(e){var n=r.util.decode_base58(e.cypherNonce);return D(e).then((function(e){return r.box.open(e.cypherSalt,n,e.keypair.boxPk,e.keypair.boxSk)})).then((function(t){return e.salt=t,r.box.open(e.cypherPwd,n,e.keypair.boxPk,e.keypair.boxSk)})).then((function(n){return e.pwd=n,e})).catch((function(e){console.warn("Incorrect answers - Unable to recover passwords")}))},events:{add:function(e,n){(e=e||{}).type=e.type||"info",e.message=e.message||"",e.messageParams=e.messageParams||{},e.context=e.context||"undefined",e.message.trim().length?n?h.events.splice(0,0,e):h.events.push(e):console.debug("Event without message. Skipping this event")},cleanByContext:L},api:b}}var b=h("default",l);return b.instance=h,b}]),angular.module("cesium.plugin.services",[]).provider("PluginService",(function(){var e=[],n={};this.registerEagerLoadingService=function(n){return e.push(n),this},this.extendState=function(e,t){return angular.isDefined(e)&&angular.isDefined(t)&&(n[e]||(n[e]=[]),n[e].push(t)),this},this.extendStates=function(e,n){var t=this;return e.forEach((function(e){t.extendState(e,n)})),this},this.$get=["$injector","$state",function(t,i){var a;return{start:function(){e.length>0&&_.forEach(e,(function(e){t.get(e)}))},extensions:{points:{getActivesByName:function(e){return _.keys(n).reduce((function(e,t){return i.includes(t)?e.concat(n[t]):e}),[]).reduce((function(n,t){return t.points&&t.points[e]?n.concat(t.points[e]):n}),[])},current:{get:function(){return a},set:function(e){a=e}}}}}}]})),angular.module("cesium.services",["cesium.config","cesium.settings.services","cesium.http.services","cesium.bma.services","cesium.crypto.services","cesium.utils.services","cesium.modal.services","cesium.storage.services","cesium.device.services","cesium.currency.services","cesium.wallet.services","cesium.tx.services","cesium.wot.services","cesium.plugin.services"]),e.prototype.isEmpty=function(){"use strict";return!(this.transactionsCount||this.certificationsCount||this.joinersCount||this.dividend||this.activesCount||this.identitiesCount||this.leaversCount||this.excludedCount||this.revokedCount)},e.prototype.parseData=function(){this.identities=this.parseArrayValues(this.identities,["pubkey","signature","buid","uid"]),this.joiners=this.parseArrayValues(this.joiners,["pubkey","signature","mBuid","iBuid","uid"]),this.actives=this.parseArrayValues(this.actives,["pubkey","signature","mBuid","iBuid","uid"]),this.leavers=this.parseArrayValues(this.leavers,["pubkey","signature","mBuid","iBuid","uid"]),this.revoked=this.parseArrayValues(this.revoked,["pubkey","signature"]),this.excluded=this.parseArrayValues(this.excluded,["pubkey"]),this.certifications=this.parseArrayValues(this.certifications,["from","to","block","signature"]),this.transactions=this.parseTransactions(this.transactions),delete this.raw},e.prototype.cleanData=function(){delete this.identities,delete this.joiners,delete this.actives,delete this.leavers,delete this.revoked,delete this.excluded,delete this.certifications,delete this.transactions,delete this.raw},e.prototype.parseArrayValues=function(e,n){return e&&e.length?e.reduce((function(e,t){var i=t.split(":");if(i.length!=n.length)return console.debug("[block] Bad format for '{0}': [{1}]. Expected {1} parts. Skipping".format(arrayProperty,t,n.length)),e;for(var a={},o=0;o\n \x3c!-- HEADER --\x3e\n \n \n \n \n\n \n \n \n \n \x3c!-- Allow extension here --\x3e\n \n\n \x3c!-- profile --\x3e\n \n \n \n \n \n\n \x3c!-- MENU --\x3e\n \n \n

\n COMMON.APP_NAME\n

\n\n \n\n \x3c!-- Fullscreen button --\x3e\n \x3c!-- removeIf(device) --\x3e\n \n \n \n \x3c!-- endRemoveIf(device) --\x3e\n
\n\n \n \n\n \x3c!-- Home --\x3e\n \n \n {{:locale:\'MENU.HOME\'|translate}}\n \n\n \x3c!-- Allow extension here --\x3e\n \n\n \x3c!-- MAIN Section --\x3e\n
\n\n \x3c!-- Allow extension here --\x3e\n \n\n\n \x3c!-- USER Section --\x3e\n
\n\n\n \n \n {{:locale:\'MENU.ACCOUNT\'|translate}}\n \n \n\n \x3c!-- Allow extension here --\x3e\n \n\n \n \n {{:locale:\'MENU.SETTINGS\'|translate}}\n \n \n\n
\n\n
\n\n \x3c!-- removeIf(device) --\x3e\n \n \x3c!-- endRemoveIf(device) --\x3e\n
\n\n\n\n'),e.put("templates/modal_about.html",'\n \n \n

ABOUT.TITLE

\n
\n\n \n\n
\n \n  {{\'COMMON.APP_VERSION\'|translate:$root.config}}\n \n

{{\'COMMON.APP_BUILD\'|translate:$root.config}}

\n ABOUT.LICENSE\n
\n\n \x3c!-- new version --\x3e\n \n \n\n \n \n\n \x3c!-- link to release page --\x3e\n

\n {{::$root.newRelease.url}}\n

\n
\n\n \x3c!-- source code --\x3e\n
\n \n {{\'ABOUT.CODE\' | translate}}\n

https://github.com/duniter-gchange/gchange-client

\n
\n\n \x3c!-- forum --\x3e\n
\n \n {{\'ABOUT.FORUM\' | translate}}\n

{{::$root.settings.userForumUrl}}

\n
\n\n
\n \n {{\'ABOUT.DEVELOPERS\' | translate}}\n

\n Benoit Lavenier\n

\n
\n \n \n

{{\'ABOUT.DEV_WARNING\'|translate}}

\n ABOUT.DEV_WARNING_MESSAGE\n
\n ABOUT.REPORT_ISSUE\n
\n\n \n\n
\n
\n
\n'),e.put("templates/api/locales_popover.html",'\n \n \n \n\n'),e.put("templates/common/form_error_messages.html",'
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n'),e.put("templates/common/popover_copy.html",'\n \n
\n
\n \n
\n
\n
\n
\n'),e.put("templates/common/popover_helptip.html",'\n \n

\n \n\n \x3c!-- close button--\x3e\n \n \n \n\n  \n

\n\n

\n \n \n

\n\n \x3c!-- buttons (if helptip) --\x3e\n
\n \n \n \n
\n\n \x3c!-- buttons (if feature tour) --\x3e\n
\n \n \n
\n\n

\n \n

\n
\n
\n'),e.put("templates/common/popover_profile.html",'\n'),e.put("templates/common/popover_share.html",'\n \n
\n

\n \n
\n \n\n \n
\n
\n'),e.put("templates/join/modal_join.html",'\n\n \n\n \n \n \n\n

ACCOUNT.NEW.TITLE

\n\n \n \n
\n\n\n \n\n \x3c!-- STEP: salt --\x3e\n \n \n
\n\n
\n\n \n\n \x3c!-- salt --\x3e\n
\n LOGIN.SALT\n \n \n
\n
\n
\n \n
\n
\n \n
\n
\n\n \x3c!-- confirm salt --\x3e\n
\n ACCOUNT.NEW.SALT_CONFIRM\n \n \n
\n
\n
\n \n
\n
\n\n \x3c!-- Show values --\x3e\n
\n COMMON.SHOW_VALUES\n \n
\n\n \n
\n
\n
\n
\n\n \x3c!-- STEP: password--\x3e\n \n \n
\n\n \n\n
\n\n \x3c!-- password --\x3e\n
\n LOGIN.PASSWORD\n \n \n
\n
\n
\n \n
\n
\n \n
\n
\n\n \x3c!-- confirm password --\x3e\n
\n ACCOUNT.NEW.PASSWORD_CONFIRM\n \n \n
\n
\n
\n \n
\n
\n\n \x3c!-- Show values --\x3e\n
\n COMMON.SHOW_VALUES\n \n
\n
\n\n \n\n \n
\n
\n
\n\n \x3c!-- STEP 5: pseudo--\x3e\n \n \n
\n\n \n\n
\n\n \x3c!-- pseudo --\x3e\n
\n PROFILE.TITLE\n \n
\n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n\n \n
\n
\n
\n
\n\n \x3c!----\x3e\n\n \x3c!-- STEP 6: last slide --\x3e\n \n \n\n
PROFILE.JOIN.LAST_SLIDE_CONGRATULATION
\n\n
\n\n \n
\n \n
\n COMMON.PUBKEY\n \n ACCOUNT.NEW.COMPUTING_PUBKEY\n \n \n {{formData.pubkey}}\n \n
\n
\n\n \n
\n
\n\n \n
\n'),e.put("templates/help/help.html",'\n \n

HELP.JOIN.SECTION

\n\n \n
\n
LOGIN.SALT
\n
HELP.JOIN.SALT
\n
\n\n \n
\n
LOGIN.PASSWORD
\n
HELP.JOIN.PASSWORD
\n
\n\n \n

HELP.GLOSSARY.SECTION

\n\n \n
\n
COMMON.PUBKEY
\n
HELP.GLOSSARY.PUBKEY_DEF
\n
\n\n \n
\n
COMMON.UNIVERSAL_DIVIDEND
\n
HELP.GLOSSARY.UNIVERSAL_DIVIDEND_DEF
\n
\n\n'),e.put("templates/help/modal_help.html",'\n\n \n \n\n

HELP.TITLE

\n
\n\n \n\n \n\n \n\n \n
\n'),e.put("templates/help/view_help.html",'\n \n HELP.TITLE\n \n\n \n\n

HELP.TITLE

\n\n \n\n
\n
\n'),e.put("templates/home/home.html",'\n \n\n \n\n \n \x3c!-- locales --\x3e\n \n \n\n \n\n \n \n\n
\n\n

\n \n\n \n

\n\n \n\n \n\n
\n
\n

\n \n

\n\n \x3c!-- Retry--\x3e\n \n
\n
\n\n
\n\n\n \x3c!-- Help tour (NOT ready yet for small device)\n --\x3e\n\n \n\n \n\n \n\n
\n \x3c!-- login link --\x3e\n
\n
\n {{\'LOGIN.HAVE_ACCOUNT_QUESTION\'|translate}}\n \n \n \n
\n\n \x3c!-- disconnect link --\x3e\n \n\n \n \n\n
\n\n
\n\n
\n
\n \x3c!-- version --\x3e\n \n |\n \x3c!-- about --\x3e\n HOME.BTN_ABOUT\n
\n
\n\n\n
\n\n
\n'),e.put("templates/login/modal_login.html",'\n \n \n

\n

\n
\n \n \n
\n\n
\n\n \n
\n\n
\n\n \x3c!-- salt (=username, to enable browser login cache) --\x3e\n \n
\n
\n \n
\n
\n\n \x3c!-- Show salt --\x3e\n
\n LOGIN.SHOW_SALT\n \n
\n\n \x3c!-- password--\x3e\n \n
\n
\n \n
\n
\n\n\n \x3c!-- remember me --\x3e\n \n\n\n \x3c!-- Show public key --\x3e\n
\n COMMON.PUBKEY\n \n {{\'COMMON.BTN_SHOW_PUBKEY\' | translate}}\n \n

\n {{pubkey}}\n

\n

\n \n

\n
\n\n
\n\n \n\n \x3c!-- Register ? --\x3e\n
\n {{\'LOGIN.NO_ACCOUNT_QUESTION\'|translate}}\n
\n \n LOGIN.CREATE_ACCOUNT\n \n
\n\n \n\n \x3c!--div class="padding hidden-xs text-right">\n COMMON.NO_ACOUNT_QUESTION\n \n \n \n\n'),e.put("templates/settings/popover_actions.html",'\n \n

COMMON.POPOVER_ACTIONS_TITLE

\n
\n \n \n \n
\n'),e.put("templates/settings/popup_node.html",'\n\n
\n
\n \n \n
\n
\n
\n \n
\n
\n \n
\n
\n\n
\n \n {{\'SETTINGS.POPUP_PEER.USE_SSL\' | translate}}\n \n

\n \n \n

\n \n
\n\n\n \n \n {{\'SETTINGS.POPUP_PEER.BTN_SHOW_LIST\' | translate}}\n \n
\n\n \n
\n\n\n'),e.put("templates/settings/settings.html",'\n SETTINGS.TITLE\n\n \n \n \n\n \n\n \x3c!-- Buttons bar--\x3e\n