text: "use strict";angular.module("medleyDashboardAngularApp",["ngCookies","ngResource","ngSanitize","ngRoute","ui.bootstrap","ui.select2","ui.checkbox","ngProgressLite","googlechart","ui.utils","angulartics","angulartics.google.analytics","config","angularSpinner"]).config(["$routeProvider","$compileProvider",function(a,b){b.aHrefSanitizationWhitelist(/^\s*(https?|blob):/),a.when("/login",{templateUrl:"views/login.html",controller:"LoginCtrl"}).when("/alerts-centre",{templateUrl:"views/users/list/alerts-centre.html",userType:"patient"}).when("/clinics",{templateUrl:"views/users/list/clinic-list.html",controller:"ClinicListCtrl",userType:"clinic"}).when("/clinics/:id",{templateUrl:"views/clinic.html",controller:"UserCtrl",userType:"clinic",resolve:{userPromise:["APIResources","$route",function(a,b){return a.userResource(b.current.userType,b.current.params.id).get().$promise}]}}).when("/patient",{templateUrl:"views/users/list/patient-list.html",controller:"UserListCtrl",userType:"patient"}).when("/patient/:id",{templateUrl:"views/patient.html",controller:"UserCtrl",userType:"patient",resolve:{userPromise:["APIResources","$route",function(a,b){return a.userResource(b.current.userType,b.current.params.id).get().$promise}]}}).when("/patient/:id/:activeTab",{templateUrl:"views/patient.html",controller:"UserCtrl",userType:"patient",resolve:{userPromise:["APIResources","$route",function(a,b){return a.userResource(b.current.userType,b.current.params.id).get().$promise}]}}).when("/admin/:id",{templateUrl:"views/admin.html",controller:"UserCtrl",userType:"admin",resolve:{userPromise:["APIResources","$route",function(a,b){return a.userResource(b.current.userType,b.current.params.id).get().$promise}]}}).when("/adminlist",{templateUrl:"views/users/list/admin-list.html",controller:"UserListCtrl",userType:"admin"}).when("/clinician/:id",{templateUrl:"views/caregiver.html",controller:"UserCtrl",userType:"caregiver",resolve:{userPromise:["APIResources","$route",function(a,b){return a.userResource(b.current.userType,b.current.params.id).get().$promise}]}}).when("/clinicianlist",{templateUrl:"views/users/list/caregiver-list.html",controller:"UserListCtrl",userType:"caregiver"}).when("/information-centre",{templateUrl:"views/information-centre.html"}).when("/about",{templateUrl:"views/about.html"}).otherwise({redirectTo:"/login"}),a.when("/privacypolicy",{templateUrl:"views/privacy-policy.html"})}]).config(["$httpProvider",function(a){a.interceptors.push("SecurityInterceptor")}]),angular.module("config",[]).constant("ENV",{version:"2.0.10",revision:"2.0.10-9-ga22bde0\n",name:"staging"}),angular.module("medleyDashboardAngularApp").constant("DISEASES",{CHF:"CHF",COPD:"COPD",CKD:"CKD",DIABETES:"DIABETES",HTN:"HTN"}),angular.module("medleyDashboardAngularApp").constant("MEASUREMENT","measurement"),angular.module("medleyDashboardAngularApp").controller("LoginCtrl",["$scope","$log","$location","ngProgressLite","LoginService","SecurityInterceptor",function(a,b,c,d,e,f){a.formData={},a.processLoginSubmit=function(){a.requestPending=!0,d.start(),e.login(a.formData.username,a.formData.password,function(e){d.done(),a.user_display_name=e.email,f.restoreOriginalPathIfSet()||("admin"==e.userable_type?c.path("/alerts-centre"):"caregiver"==e.userable_type?c.path("/alerts-centre"):"superadmin"==e.userable_type?c.path("/alerts-centre"):"patient"==e.userable_type?c.path("/patient/profile"):(c.path("/patient/profile/profile"),b.info("assuming we are a patient because we are not an admin or clinician.")))},function(b){a.requestPending=!1,d.done(),a.errorLogin=b.data.error})}}]),angular.module("medleyDashboardAngularApp").factory("APIBaseURL",["$window","$location","$log",function(a,b,c){var d="";return a.localStorage&&a.localStorage.getItem("medly.backend.url")?(d=a.localStorage.getItem("medly.backend.url"),c.log("using custom backend",d)):("localhost"==b.host()||"127.0.0.1"==b.host())&&"3000"!=b.port()&&(d="http://localhost:3000"),d}]),angular.module("medleyDashboardAngularApp").factory("APILoginResource",["$resource","APIBaseURL",function(a,b){return a(b+"/sign_in",null,{})}]),angular.module("medleyDashboardAngularApp").factory("APICaregiversQuery",["APIResources",function(a){return a.userListResourceForType("caregiver").query}]),angular.module("medleyDashboardAngularApp").factory("APICaregiverRolesQuery",["APIResources",function(a){return a.caregiverRoleResource().query}]),angular.module("medleyDashboardAngularApp").factory("APIResources",["$resource","UserSession","$log","APIBaseURL","$http",function(a,b,c,d,e){function f(a){var b=_.first(_.keys(a));if(b){var c=a[b];return c.meta=a.meta,c}return a}function g(){return b.user()&&b.user().links||{}}function h(){return b.user()&&b.user().userable_type}function i(a){var b=g()[a+"s"];return d+b}function j(a){return i(a)+"/:id"}function k(b,c){c=c||b;var d=a(i(b),{},{query:o(),save:p(c,{method:"POST"})});return d.prototype.meta=function(){},d}function l(){return d+g()._self}function m(a){return"profile"===a?l():j("patient")}var n,o,p,q=e.defaults.transformResponse.concat(f);return n={method:"GET",transformResponse:q},o=function(a){var b={method:"GET",isArray:!0,params:a,transformResponse:q,interceptor:{response:function(a){return a.resource.meta=a.data.meta,a.resource}}};return b},p=function(a,b){var c=b||{method:"POST"};return c.transformRequest=[].concat(function(b){var c={};return c[a]=b,c},e.defaults.transformRequest),c},{userResource:function(b,c){var d,e;return"profile"==c?(d=l(),e={}):(d=j(b),e={id:c}),a(d,e,{get:n,update:p(b,{method:"PUT"}),"delete":p(b,{method:"DELETE"}),restore:p(b,{method:"RESTORE"})})},userListResourceForType:k,alertsResource:function(b){var c=d+"/"+h()+"/alerts";return a(c,{alertId:b},{query:o(),update:p("alert",{method:"PUT",url:c+"/:alertId"})})},patientMeasurementResource:function(b,c){var d=m(b);return a(d+"/:readingName",{id:b,readingName:c+"_readings"},{query:o({sort:"measured_at DESC"})})},singleMeasurementResource:function(b,c,d){var e=m(b);return a(e+"/:readingName/:readingId",{id:b,readingName:c+"_readings",readingId:d},{query:{method:"GET",isArray:!1}})},patientPrescriptionListResource:function(b,c,d){var e="profile"==b?l():j("patient"),f="prescription",g=e+"/"+(c?c+"_":"")+"prescriptions";return a(g,{id:b,prescriptionId:d},{query:o(),save:p(f),update:p(f,{method:"PUT",url:g+"/:prescriptionId"}),"delete":p(f,{method:"DELETE",url:g+"/:prescriptionId"})})},copdMedicationResource:function(b){var c=d+"/"+h()+"/copd_medications";return a(c,{option:b.option,"selected[direction]":b.direction?b.direction:"","selected[brand]":b.brand,"selected[intake_method]":b.intake_method,"selected[formulation]":b.formulation,"selected[dose]":b.dose,"selected[frequency]":b.frequency})},caregiverRoleResource:function(b){var c=d+"/admin/caregiver_roles";return a(c,{},{query:o()})},patientHistoryListResource:function(b){var c="profile"==b?l():j("patient");return a(c+"/versions",{id:b},{query:o()})},patientDatesResource:function(b){var c="profile"==b?l():j("patient");return a(c+"/dates",{id:b},{get:n,save:p("date")})},pdfSummaryResource:function(b){var c="profile"==b?l():j("patient");return a(c+"/pdf_summary",{id:b},{get:{method:"GET",headers:{accept:"application/pdf"},responseType:"arraybuffer",cache:!0,transformResponse:function(a){var b;return a&&(b=new Blob([a],{type:"application/pdf"})),{response:b}}}})},patientAlertsListResource:function(b){var c="profile"==b?l():j("patient");return a(c+"/alerts",{id:b},{query:o({sort:"created_at DESC"})})},patientLabResultResource:function(b,c){var d=m(b),e=d+"/lab_results",f="lab_result";return a(e,{id:b,labEntryId:c},{query:o({sort:"collected_at DESC"}),save:p(f),update:p(f,{method:"PUT",url:e+"/:labEntryId"}),"delete":p(f,{method:"DELETE",url:e+"/:labEntryId"})})}}}]),angular.module("medleyDashboardAngularApp").factory("LoginService",["APILoginResource","UserSession",function(a,b){return{login:function(c,d,e,f){var g={user:{email:c,password:d}};return a.save({},g,function(a){b.setUser(a.user),e(a.user);var c=a.user.username;ga("set","dimension1",c)},function(a){b.setUser(null),f(a)})}}}]),angular.module("medleyDashboardAngularApp").factory("ReadingGraphService",["$routeParams","APIResources",function(a,b){var c="transparent",d="#8ccbe0",e="#00FFFF",f="#FFFFFF",g={0:{type:"area",color:c,lineWidth:0,opacity:1,pointSize:0},1:{type:"area",color:e,lineWidth:0,opacity:1,pointSize:0},2:{type:"line",color:c,lineWidth:0,pointSize:0},3:{type:"area",color:d,lineWidth:0,opacity:1,pointSize:0},4:{type:"line",color:c,lineWidth:0,pointSize:0},5:{type:"area",color:e,lineWidth:0,opacity:1,pointSize:0},6:{type:"line",color:c,lineWidth:0,pointSize:0},7:{type:"line",color:f,lineWidth:2,opacity:1,pointSize:0},8:{type:"line",color:f,lineWidth:0,opacity:1,pointSize:8}},h={0:{type:"line",color:f,lineWidth:2,pointSize:8,opacity:1}},i={0:{type:"area",color:c,lineWidth:0,opacity:1,pointSize:0},1:{type:"area",color:d,lineWidth:0,opacity:1,pointSize:0},2:{color:c,lineWidth:0,pointSize:0},3:{type:"line",color:f,lineWidth:2,opacity:1,pointSize:0},4:{type:"line",color:f,lineWidth:0,opacity:1,pointSize:8}},j="#0099AC",k="#498AA3",l="#357087",m={0:{type:"line",color:f,pointSize:8},1:{type:"area",color:k,lineWidth:0,enableInteractivity:!1},2:{type:"area",color:j,lineWidth:0,enableInteractivity:!1},3:{type:"area",color:k,lineWidth:0,enableInteractivity:!1},4:{type:"area",color:l,lineWidth:0,enableInteractivity:!1}},n={vAxis:{title:"Weight (lbs)",gridlines:{color:"transparent"},viewWindow:{min:90}},series:i},o={vAxis:{title:"Pulse (bpm)",gridlines:{color:"transparent"},viewWindow:{min:0}},series:i},p={vAxis:{title:"Systolic (mmHg)",gridlines:{color:"transparent"},viewWindow:{min:0}},series:i},q={vAxis:{title:"Diastolic (mmHg)",gridlines:{color:"transparent"},viewWindow:{min:0}},series:i},r={vAxis:{title:"Potassium (mmol/L)",gridlines:{color:"transparent"},viewWindow:{min:0}},series:g},s={vAxis:{title:"Phosphate (mmol/L)",gridlines:{color:"transparent"},viewWindow:{min:0}},series:g},t={vAxis:{title:"Hemoglobin (g/L)",gridlines:{color:"transparent"},viewWindow:{min:0}},series:g},u={vAxis:{title:"Kidney function (%)",gridlines:{color:"transparent"},viewWindow:{min:0}},series:h},v={vAxis:{title:"Creatinine (umol/L)",gridlines:{color:"transparent"},viewWindow:{min:0}},series:h},w={seriesType:"line",height:350,areaOpacity:1,series:m,legend:{position:"none"},chartArea:{backgroundColor:{fill:"#357087"},width:"85%",height:"80%"},vAxis:{title:"Blood Glucose (mmol/L)",gridlines:{color:"transparent"},maxValue:35,minValue:0,ticks:[0,5,10,15,20,25,30,35],viewWindow:{max:35,min:0}},hAxis:{gridlines:{color:"transparent"},format:"d MMM y"}},x={chartArea:{backgroundColor:{fill:"#357087"},width:"80%",height:"70%"},hAxis:{direction:-1},isStacked:!0,seriesType:"line",legend:{position:"none"}};return angular.extend(r,x),angular.extend(s,x),angular.extend(t,x),angular.extend(u,x),angular.extend(v,x),angular.extend(n,x),angular.extend(o,x),angular.extend(p,x),angular.extend(q,x),{graph:function(a,c,d,e,f,g){var h=b.patientMeasurementResource(a,d).query(e);h.$promise.then(function(a){a.length>0&&(c[d]=a,f(),void 0!==g&&g())})},weightOptions:n,pulseOptions:o,systolicOptions:p,diastolicOptions:q,potassiumOptions:r,phosphateOptions:s,hemoglobinOptions:t,kidneyOptions:u,creatinineOptions:v,bgOptions:w}}]),angular.module("medleyDashboardAngularApp").factory("UserListService",["APIResources",function(a){var b=function(b){return a.userListResourceForType(b)};return{get:function(a,c,d){var e=b(a);return e?e.query(c,d):[]},save:function(a,c,d,e){var f=b(a);return f?f.save(c,d,e):{error:"The api "+a+" does not exist"}}}}]),angular.module("medleyDashboardAngularApp").factory("ClinicListService",["APIResources",function(a){var b=function(b){return a.userListResourceForType(b)};return{get:function(a,c,d,e){var f=b(a);return f?f.query(c,d):[]},save:function(a,c,d,e){var f=b(a);return f?f.save(c,d,e):{error:"The api "+a+" does not exist"}}}}]),angular.module("medleyDashboardAngularApp").service("MedicationService",["$q","APIResources",function(a,b){var c=[{name:"direction",child:"brand",childLabel:"Brand"},{name:"generic"},{name:"brand",child:"intake_method",childLabel:"Method"},{name:"intake_method",child:"formulation",childLabel:"Formulation"},{name:"formulation",child:"dose",childLabel:"Dose"},{name:"dose",child:"frequency",childLabel:"Frequency"},{name:"frequency"},{name:"duration"},{name:"additional_information"},{name:"tapered"}],d=function(a,b){for(var c,d={option:a},e=a;e&&(c=_(b).findWhere({child:e}));)e=c.name,c.value&&c.value.id===parseInt(c.value.id)&&(d[e]=c.value.text);return d},e=function(a){var b={prescribable_id:a.id};for(var c in a.prescription)b[c]=a.prescription[c].value&&a.prescription[c].value.text||a.prescription[c].value;return b};return{filter:function(c,e){var f=a.defer();return b.copdMedicationResource(d(c,e)).get().$promise.then(function(a){f.resolve(a.copd_medications)}),f.promise},forEachMedicationKey:function(a){c.forEach(a)},makeEditablePrescription:function(a){var b={type:a.prescribable_type,id:a.prescribable_id,prescription:{}};return c.forEach(function(c){b.prescription[c.name]={name:c.name,value:a[c.name],child:c.child,childLabel:c.childLabel}}),b},saveEditablePrescription:function(a,c){var d=c.id?b.patientPrescriptionListResource(a,c.type,c.id).update:b.patientPrescriptionListResource(a,c.type).save;return d(e(c)).$promise},deleteEditablePrescription:function(a,c){return b.patientPrescriptionListResource(a,c.type,c.id)["delete"]().$promise}}}]),angular.module("medleyDashboardAngularApp").factory("PagePrinter",["$rootScope","$compile","$http","$timeout",function(a,b,c,d){var e=function(a){var b=$('<iframe style="display: none"></iframe>').appendTo("body")[0],c='<!doctype html><html><body onload="window.print();">'+a+"</body></html>",d=b.contentWindow.document.open("text/html","replace");d.write(c),d.close()},f=function(f,g){c.get(f).success(function(f){var h=a.$new();angular.extend(h,g);var i=b($("<div>"+f+"</div>"))(h),j=function(){h.$$phase||c.pendingRequests.length?d(j):(e(i.html()),h.$destroy())};j()})};return{print:f}}]),angular.module("medleyDashboardAngularApp").factory("CkdSummaryPrinter",["$q","PagePrinter","PatientLabResultService","APIResources",function(a,b,c,d){var e=function(b,c){var e=a.defer(),f=d.userResource("patient",b).get(c,function(){e.resolve(f)});return e.promise},f=function(b,c){var e=a.defer(),f=d.patientMeasurementResource(b,"bp").query(c,function(){e.resolve(f)});return e.promise},g=function(b,c,e){var f=a.defer(),g=d.singleMeasurementResource(b,"bp",c).query(e,function(){f.resolve(g)});return f.promise},h=function(a,b){var d=c.getLabResults(a,b);return d},i=function(b,c){var e=a.defer(),f=d.patientMeasurementResource(b,"symptom").query(c,function(){e.resolve(f)});return e.promise};return{print:function(c){var d=new Date,j={today:d,patient:{},bps:[],labs:[],symptoms:[],medications:[],notAvailable:"n/a"};a.all([f(c,{limit:1,sort:"measured_at DESC"})]).then(function(d){var f={latest:null,twoMonthsAgo:null};f.latest=d[0][0].readable_id;var k=d[0][0]&&new Date(d[0][0].measured_at),l=2;k&&k.setMonth(k.getMonth()-l);var m=_.find(d[0],function(a){return new Date(a.measured_at)<k});f.twoMonthsAgo=m.readable_id,a.all([e(c),g(c,f.latest,{with_ckd_bp_data:!0}),h(c),i(c,{limit:1,sort:"measured_at DESC",version:"ckd_1"}),i(c,{limit:1,sort:"measured_at DESC",version:"ckd_med_1"})]).then(function(d){j.patient=d[0],j.bps[0]=d[1].reading,j.labs[0]=d[2]&&d[2][0],j.symptoms[0]=d[3]&&d[3][0],j.medications[0]=d[4]&&d[4][0];var e=2,k=j.labs[0]&&new Date(j.labs[0].date);k&&k.setMonth(k.getMonth()-e);var l=j.symptoms[0]&&new Date(j.symptoms[0].measured_at);l&&l.setMonth(l.getMonth()-e);var m=j.medications[0]&&new Date(j.medications[0].measured_at);m&&m.setMonth(m.getMonth()-e),a.all([g(c,f.twoMonthsAgo,{with_ckd_bp_data:!0}),h(c,{collected_before:k&&k.toISOString()}),i(c,{limit:1,sort:"measured_at DESC",version:"ckd_1",measured_before:l&&l.toISOString()}),i(c,{limit:1,sort:"measured_at DESC",version:"ckd_med_1",measured_before:m&&m.toISOString()})]).then(function(a){j.bps[1]=a[0].reading,j.labs[1]=a[1]&&a[1][0],j.symptoms[1]=a[2]&&a[2][0],j.medications[1]=a[3]&&a[3][0],b.print("/views/ckd-one-pager.html",j)})})})}}}]),angular.module("medleyDashboardAngularApp").config(["$provide",function(a){a.decorator("$exceptionHandler",["$delegate","ENV",function(a,b){return function(c,d){Bugsnag.releaseStage=b.name||"production",Bugsnag.notifyReleaseStages=["development","staging","production"],"local"!==Bugsnag.releaseStage&&Bugsnag.notifyException(c,{diagnostics:{cause:d}}),a(c,d)}}])}]),angular.module("medleyDashboardAngularApp").constant("EmailAlerts",{BLOOD_PRESSURE:"Blood Pressure",SYMPTOMS:"Symptoms",MEDICATIONS:"Medications",LAB_RESULTS:"Lab Results"}),angular.module("medleyDashboardAngularApp").run(["$locale",function(a){a.DATETIME_FORMATS.medlyDate="dd MMM yyyy",a.DATETIME_FORMATS.medlyTime="HH:mm"}]),angular.module("medleyDashboardAngularApp").run(["$rootScope",function(a){a.$on("$routeChangeSuccess",function(){window.scrollTo(0,0)})}]),angular.module("medleyDashboardAngularApp").run(["$rootScope",function(a){var b=!1;a.$on("medly.modal.opened",function(){b=!0}),a.$on("medly.modal.closed",function(){b=!1}),a.$on("$routeChangeSuccess",function(){b&&a.modalInstance.dismiss()})}]),angular.module("medleyDashboardAngularApp").factory("UserSession",["$window","$http",function(a,b){function c(a){i=a,e(a),f(a)}function d(){g&&g.getItem(h)&&c(JSON.parse(g.getItem(h)))}function e(a){g&&(a?g.setItem(h,JSON.stringify(a)):g.removeItem(h))}function f(a){a&&a.session?b.defaults.headers.common.Authorization='Token token="'+a.session.token+'"':delete b.defaults.headers.common.Authorization}var g,h,i=null,j={editPrescription:["superadmin","admin","caregiver"],editCareTeam:["superadmin","admin"],viewHistory:["superadmin","admin"],addPatient:["superadmin","admin"],addLabResults:["superadmin","admin","caregiver"],editLabResults:["superadmin","admin","caregiver"],editPatientInfo:["superadmin","admin","caregiver"],editPatientContact:["superadmin","admin","caregiver"],editPatientStudy:["superadmin","admin"],editPatientGoals:["superadmin","admin","caregiver"],editCaregiverContact:["superadmin","admin"],editCaregiverRole:["superadmin","admin"],resetPatientAlgorithm:["superadmin","admin","caregiver"],updateNextClinicDate:["superadmin","admin","caregiver"]};return g=a.sessionStorage,h="medleyDashboardUser",d(),{setUser:c,isLoggedIn:function(){return null!=i},user:function(){return i},role:function(){return this.isLoggedIn()?i.superadmin?"superadmin":i.userable_type:"anonymous"},can:function(a){return j[a]&&j[a].indexOf(this.role())>=0}}}]),angular.module("medleyDashboardAngularApp").factory("SecurityInterceptor",["$location","$log","$q",function(a,b,c){var d;return{responseError:function(e){b.log("SecurityInterceptor: in responseError");var f;if(401==e.status||404==e.status||0==e.status){f=a.path(),b.log("responseError: in error on ",f);var g=f.indexOf("/login")>=0;g||(d=f,b.log("responseError: saving path",d)),a.path("/login")}return c.reject(e)},restoreOriginalPathIfSet:function(){return d?(b.log("responseError: restoring path",d),a.path(d),d=null,!0):!1}}}]),angular.module("medleyDashboardAngularApp").run(["$rootScope","$location","UserSession",function(a,b,c){a.$on("$routeChangeStart",function(a,d,e){!c.isLoggedIn()&&b.path().indexOf("/login")>=0&&b.path("/login")})}]),angular.module("medleyDashboardAngularApp").config(["$modalProvider",function(a){a.options.backdrop="static"}]).run(["$locale","datepickerConfig",function(a,b){b.showWeeks=!1}]).run(["$locale","datepickerPopupConfig",function(a,b){b.showButtonBar=!1,b.dateFormat=a.DATETIME_FORMATS.medlyDate}]),angular.module("medleyDashboardAngularApp").factory("PatientAlerts",["APIResources","$rootScope","$routeParams",function(a,b,c){var d={alerts:[],headerAlerts:null,refresh:function(b,e){"patient"===e?(d.all=a.patientAlertsListResource(c.id).query({}),d.all.$promise.then(function(){d.headerAlerts=d.all})):d.all=[]},dismissHeaderAlert:function(){delete d.headerAlerts}};return b.$on("medly.user.loaded",function(a,b,c){d.refresh(b,c)}),d}]),angular.module("medleyDashboardAngularApp").controller("UserCtrl",["$scope","$route","userPromise","$rootScope","APICaregiverRolesQuery","UserSession","APIResources",function(a,b,c,d,e,f,g){a.user=c,a.canEditCaregiverRole=f.can("editCaregiverRole");var h=b.current.userType;a["is"+h.charAt(0).toUpperCase()+h.slice(1)]=!0;var i=function(){if(a.canEditCaregiverRole&&"caregiver"===h){e().$promise.then(function(b){a.availableRoles=b})}};a.userRefresh=function(){g.userResource(b.current.userType,b.current.params.id).get().$promise.then(function(b){a.user=b,window.setTimeout(function(){d.$broadcast("medly.user.loaded",b,h)},2e3)},function(a){console.log("Data failed to load.")})};var j=function(){a.userRefresh(),i()};j()}]),angular.module("medleyDashboardAngularApp").service("PatientLabResultService",["$q","APIResources",function(a,b){function c(a){this.isNew=!a,this.results=[],this.imported=a&&a.imported,a&&(this.date=a.collected_at,this.results.push(a))}var d,e={Potassium:"mmol/L",Phosphate:"mmol/L",Hemoglobin:"g/L","Kidney Function":"%",Creatinine:"umol/L",Sodium:"mmol/L",BNP:"pg/mL",FEV1:"L","FEV1 Predicted":"%",FVC:"L","FVC Predicted":"%","FEV1/FVC":"n/a"};return c.prototype.add=function(a){this.results.push(a)},c.prototype.get=function(a){var b=_.findWhere(this.results,{name:a});if(b)return b;var c={name:a,unit:e[a]};return this.results.push(c),c},c.prototype.update=function(){var c=this,e=[],f=new Date;return angular.forEach(this.results,function(a){a.value&&(a.id?(a.collected_at=c.date,e.push(b.patientLabResultResource(d,a.id).update(a).$promise)):(c.isNew&&(c.date.setHours(f.getHours()),c.date.setMinutes(f.getMinutes()),c.date.setSeconds(f.getSeconds())),a.collected_at=c.date,e.push(b.patientLabResultResource(d).save(a).$promise)))}),a.all(e)},c.prototype["delete"]=function(){var c=[];return angular.forEach(this.results,function(a){a.value&&a.id&&c.push(b.patientLabResultResource(d,a.id)["delete"]().$promise)}),a.all(c)},{getLabResults:function(e,f){d=e;var g=a.defer();return b.patientLabResultResource(d).query(f).$promise.then(function(a){var b=[];angular.forEach(a,function(a){var d=_.findWhere(b,{date:a.collected_at});d?d.add(a):b.push(new c(a))}),b.meta=a.meta,g.resolve(b)}),g.promise},createNew:function(){return new c}}}]),angular.module("medleyDashboardAngularApp").service("AlertMessageService",["DISEASES",function(a){var b=5,c=6,d=7,e=8,f=function(a){var f="";switch(a){case b:f+="Low";break;case c:f+="High";break;case d:f+="Critical Low";break;case e:f+="Critical High";break;default:f+="No status"}return f},g=function(a){var b="";return b+="<b>Measurements</b>: ",a.additional_info.hasOwnProperty("weight_tag")&&null!==a.additional_info.weight_tag&&(b+=a.additional_info.triggering_weight+"lbs",(-1===a.additional_info.weight_tag.indexOf("normal")||"abnormal delta"===a.additional_info.weight_tag)&&(b+=" ("+a.additional_info.weight_tag+")"),b+=", "),a.additional_info.hasOwnProperty("bp_tag")&&null!==a.additional_info.bp_tag&&(b+=a.additional_info.triggering_sbp+"/"+a.additional_info.triggering_dbp+"mmHg",-1===a.additional_info.bp_tag.indexOf("normal")&&(b+=" ("+a.additional_info.bp_tag+")"),b+=", "),a.additional_info.hasOwnProperty("pulse_tag")&&null!==a.additional_info.pulse_tag&&(b+=a.additional_info.triggering_pulse+"bpm",-1===a.additional_info.pulse_tag.indexOf("normal")&&(b+=" ("+a.additional_info.pulse_tag+")"),b+=", "),a.additional_info.hasOwnProperty("triggering_symptoms")&&null!==a.additional_info.triggering_symptoms&&(b+="<b>Symptoms</b>: ",b+=a.additional_info.triggering_symptoms.join(", ")+", "),a.additional_info.hasOwnProperty("message")&&null!==a.additional_info.message?(b+="<b>Message</b>: ",b+='"'+a.additional_info.message+'"'):void 0};this.alertMessage=function(b,c){var d="";switch(b.alertable_type){case"BpReading":b.disease_type===a.CKD?(d="Blood Pressure - ",b.severity&&(d+=b.severity+" -"),d+=" Last: <b>"+b.alertable.sbp+"/"+b.alertable.dbp+"</b>",b.additional_info.overall_sbp&&(d+=" Overall reading: "+b.additional_info.overall_sbp+"/"+b.additional_info.overall_dbp),d+=' - <a href="#/patient/'+c+'/summary">More Info</a>'):b.disease_type===a.CHF?d+=g(b):d="Blood Pressure";break;case"SymptomReading":if("ckd_1"===b.alertable.version){d="Symptoms - ";var e=[];b.alertable.responses.forEach(function(a,c){a>0&&e.push("<b>"+b.alertable.questions[c]+"</b> ("+b.alertable.possible_responses[a]+")")}),d+=e.join(", "),d+=' - <a href="#/patient/'+c+'/summary">More Info</a>'}else if("ckd_med_1"===b.alertable.version){d="Medications - ";var h=[];1===b.alertable.responses[0]&&h.push("<b>New medications</b>"),1===b.alertable.responses[1]&&h.push("<b>Changed medications</b>: "+(b.alertable.additional_info.changed_names?b.alertable.additional_info.changed_names.join(", "):b.alertable.additional_info.changed.join(", "))),1===b.alertable.responses[2]&&h.push("<b>Medication issues</b>: "+(b.alertable.additional_info.issues_names?b.alertable.additional_info.issues_names.join(", "):b.alertable.additional_info.issues.join(", "))),0===h.length&&h.push("Nothing reported"),d+=h.join(" - "),d+=' - <a href="#/patient/'+c+'/medication">More Info</a>'}else if("copd_1"===b.alertable.version){var i=2,j=3,k=4,l=5;switch(b.patient_state){case i:d+="<b>Exacerbation</b>: ";break;case j:d+="<b>Exacerbation</b> (<i>continues</i>): ";break;case k:d+="<b>Exacerbation</b> (<i>2 or more over last 6 weeks</i>): ";break;case l:d+="<b>Exacerbation</b>: ";break;default:d+=""}var e=[];b.alertable.responses.forEach(function(a,c){c>=0&&3>=c&&a>0&&e.push(b.alertable.questions[c]+" ("+b.alertable.possible_responses[a]+")")}),d+=e.join(", ")}else"chf_1"===b.alertable.version?d+=g(b):d="Symptoms";break;case"PulseReading":b.disease_type===a.CHF?d+=g(b):d="Pulse";break;case"WeightReading":b.disease_type===a.CHF?d+=g(b):d="Weight";break;case"BgReading":var m=function(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")};if(d+="<b>Blood Glucose: </b>",d+=b.alertable.measurement_context.substr(0,1).toUpperCase()+b.alertable.measurement_context.substr(1)+" ",b.additional_info&&b.additional_info.causes&&b.additional_info.fixes){d+="Trend ",d+="("+f(b.patient_state)+")",d+=", ",d+=b.reading_ids.length+" readings, ",d+="<b>Entry: </b>";var m=function(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")},n="Causes ("+(b.additional_info.causes&&b.additional_info.causes.join(", "))+"), ",o="Fixes ("+(b.additional_info.fixes&&b.additional_info.fixes.join(", "))+")";d+=m(n),d+=m(o)}else d+=b.alertable.measurement.toFixed(2),d+=" mmol/L ",d+="("+f(b.patient_state)+")";break;case"LabResult":d="Labs -  <b>"+b.alertable.name+": "+b.alertable.value+" "+b.alertable.unit+"</b>",d+=" ("+b.additional_info.patient_state_note+")",d+=' - <a href="#/patient/'+c+'/labs">More Info</a>'}return d}}]),angular.module("medleyDashboardAngularApp").service("AnalyticsService",["$timeout",function(a){this.displayedReadings=function(a,b,c,d){var e=_.filter(a,function(a){var d=new Date(a.measured_at);return d>=new Date(b)&&d<=new Date(c)}),f=_.pluck(e,d.toString());return f},this.labReadings=function(a,b,c,d){var e=_.filter(a,function(a){var d=new Date(a.date);return d>=new Date(b)&&d<=new Date(c)}),f=_.map(e,function(a){return a.get(d).value});return f},this.totalNumReadings=function(a){return a?a.length:0},this.numOutsideRange=function(a,b,c){var d=_.filter(c,function(c){return a>c||c>b});return d.length},this.average=function(a,b){if(0!==a.length){var c=_.reduce(a,function(a,b){return a+b},0),d=c/b;return d}}}]),angular.module("medleyDashboardAngularApp").filter("formatPhone",function(){return function(a){return a&&10===a.length?"("+a.slice(0,3)+") "+a.slice(3,6)+"-"+a.slice(6):a}}),angular.module("medleyDashboardAngularApp").filter("percentage",["$filter",function(a){return function(b,c){return a("number")(100*b,c)+"%"}}]),angular.module("medleyDashboardAngularApp").controller("UserListCtrl",["$scope","$route","$modal","UserListService","$rootScope","UserSession","APIResources","CkdSummaryPrinter",function(a,b,c,d,e,f,g,h){a.canAddPatient=f.can("addPatient"),a.showSpinner=!0;var i={firstname:"LOWER(first_name) ASC, LOWER(last_name) ASC",lastname:"LOWER(last_name) ASC, LOWER(first_name) ASC",id:"id DESC",mrn:"mrn DESC"};a.filterForm={searchText:"",sort:i.lastname,currentPage:1,totalPages:0,itemsPerPage:10},a.userType=b.current.userType,a.sortBy=function(b){b&&i[b]&&(a.filterForm.sort=i[b],a.filter())},a.onSuccessQuery=function(b){a.users=b,a.filterForm.totalPages=b.meta.total_pages*a.filterForm.itemsPerPage,a.showSpinner=!1},a.filter=function(){d.get(a.userType,{search:a.filterForm.searchText,sort:a.filterForm.sort,page:a.filterForm.currentPage},a.onSuccessQuery)},a.pageChanged=function(b){a.filter()};var j=function(){e.modalInstance.opened.then(function(){e.$broadcast("medly.modal.opened")}),e.modalInstance.result.then(function(){},function(a){e.$broadcast("medly.modal.closed")})};a.openAddModal=function(){e.modalInstance=c.open({controller:"AddUserCtrl",templateUrl:"views/users/add/modal-"+a.userType+"-add.html"}),j()},a.openPrintModal=function(a){e.modalInstance=c.open({controller:"MohPatientPrintSummaryCtrl",templateUrl:"views/modal-patient-print-summary.html",resolve:{patient:function(){return a}}}),j()},a.filter(),e.$on("medly.event.user.added",a.filter)}]),angular.module("medleyDashboardAngularApp").controller("ClinicalAlertsCtrl",["$scope","$sce","$route","$modal","$rootScope","APIResources","AlertMessageService","$location",function(a,b,c,d,e,f,g,h){a.sortOptions={patientAscending:"LOWER(common_patients.last_name) ASC",patientDescending:"LOWER(common_patients.last_name) DESC",timeAscending:"created_at ASC",timeDescending:"created_at DESC"},a.filterForm={sort:a.sortOptions.timeDescending,currentPage:1,totalPages:0,itemsPerPage:10},a.sortBy=function(b){b&&a.sortOptions[b]&&(a.filterForm.sort=a.sortOptions[b],a.filter())},a.filter=function(){a.showSpinner=!0,f.alertsResource().query({sort:a.filterForm.sort,page:a.filterForm.currentPage}).$promise.then(function(b){0===b.length&&(a.showSpinner=!1);var c=new Date;c.setHours(0,0,0,0);var d=_.filter(b,function(b){var d="unresolved"===b.status,e="resolved"===b.status&&Date.parse(b.status_updated_at)>c,f=d||e;return a.showSpinner=!1,f}),e=_.sortBy(d,function(a){return a.alertable.measured_at}).reverse();a.alerts=e,a.filterForm.totalPages=b.meta.total_pages*a.filterForm.itemsPerPage})},a.pageChanged=function(){a.filter()},a.alertMessage=function(a,c){var a=g.alertMessage(a,c);return b.trustAsHtml(a)},a.alertTime=function(a){return null!==a.start_date?a.start_date:a.alertable.measured_at},a.go=function(a){h.path("/patient/"+a.patient.id)},a.stopPropagation=function(a){a.stopPropagation()},a.statusChange=function(a){f.alertsResource(a.id).update(a).$promise},a.alertResolved=function(a){return"resolved"===a.status},e.$on("medly.event.user.added",a.filter);var i=function(){a.filter()};i()}]),angular.module("medleyDashboardAngularApp").controller("NonCompliantAlertsCtrl",["$scope","$route","$modal","$rootScope","$location","UserListService",function(a,b,c,d,e,f){a.sortOptions={lastCallAscending:function(a){return a.last_called_at},lastCallDescending:function(a){return a.last_called_at},consecutiveCallAscending:function(a){return a.consecutive_calls},consecutiveCallDescending:function(a){return a.consecutive_calls}},a.filterForm={sort:a.sortOptions.lastCallDescending,currentPage:1,totalPages:0,itemsPerPage:10},a.sortBy=function(b){if(a.filterForm.sort=a.sortOptions[b],a.inadherentPatients){var c=a.inadherentPatients,d=_.sortBy(c,a.filterForm.sort);b&&b.indexOf("Descending")>-1&&(d=d.reverse()),a.inadherentPatients=d}},a.filter=function(){f.get("patient",{inadherent:!0}).$promise.then(function(b){var c=_.filter(b,function(a){return a.consecutive_calls});a.inadherentPatients=c,a.sortBy("lastCallDescending");
  })},a.pageChanged=function(b){a.filterForm.currentPage=b,a.filter()},a.go=function(a){e.path("/patient/"+a.patient.id)},d.$on("medly.event.user.added",a.filter);var g=function(){a.filter()};g()}]),angular.module("medleyDashboardAngularApp").controller("AddUserCtrl",["$rootScope","$scope","$route","$location","$modal","$filter","UserListService","APICaregiverRolesQuery","DISEASES","ClinicListService",function(a,b,c,d,e,f,g,h,i,j){b.userForm={user_attributes:{disease_names:[],email_alerts:[]},determinant_set_attributes:{},thresholds_attributes:[{}]};var k=c.current.userType;if(b.userType=k,"caregiver"===k){h().$promise.then(function(a){b.availableRoles=a})}b.patientDiseases=b.userForm.user_attributes.disease_names,b.weightThreshold=b.userForm.thresholds_attributes[0],b.weightThreshold.upper=b.userForm.thresholds_attributes[0].upper,b.weightThreshold.lower=b.userForm.thresholds_attributes[0].lower,b.weightThreshold.delta=b.userForm.thresholds_attributes[0].delta,b.weightMinMaxValidity=function(){var a=parseFloat(b.weightThreshold.lower)<parseFloat(b.weightThreshold.upper);return 0==a&&b.patientDiseases.includes("CHF")?(b.requestPending=!0,a):(b.requestPending=!1,a)},b.weightPattern=/^[0-9]+(\.[0-9]{1})?$/,b.birthday={},b.months=["January","February","March","April","May","June","July","August","September","October","November","December"],b.days=function(){for(var a=[],b=1;31>=b;b++)a.push(b);return a},b.userForm.determinant_set_attributes.bp_email=!0,b.userForm.determinant_set_attributes.symptoms_email=!0,b.userForm.determinant_set_attributes.meds_email=!0,b.userForm.determinant_set_attributes.lab_email=!0,b.emailAlerts=[{id:"blood-pressure",label:"Blood Pressure",value:"Blood Pressure",attr:"bp_email"},{id:"symptoms",label:"Symptoms",value:"Symptoms",attr:"symptoms_email"},{id:"medications",label:"Medications",value:"Medications",attr:"meds_email"},{id:"lab-results",label:"Lab Results",value:"Lab Results",attr:"lab_email"}],b.diseaseNames=[{id:0,label:i.CHF,value:i.CHF},{id:1,label:i.CKD,value:i.CKD},{id:2,label:i.COPD,value:i.COPD},{id:3,label:"Diabetes",value:i.DIABETES},{id:4,label:i.HTN,value:i.HTN}],b.updateQuestionValue=function(a){b.patientDiseases=b.patientDiseases||[],a.checked?(b.patientDiseases.push(a.value),b.patientDiseases=_.uniq(b.patientDiseases)):b.patientDiseases=_.without(b.patientDiseases,a.value)},b.requestPending=!1,b.onError=function(a){b.requestPending=!1,b.errorMessage=a.error},b.onSaved=function(){b.requestPending=!1,a.$broadcast("medly.event.user.added"),b.$dismiss("")},b.done=function(){b.requestPending=!0;var a=new Date(b.birthday.year,b.birthday.month,b.birthday.day);b.userForm.birthdate=a,"patient"===k&&(b.userForm.contact_information_attributes.home_phone=f("formatPhone")(b.userForm.contact_information_attributes.home_phone),b.patientDiseases.includes("CHF")?(b.weightThreshold.measurement_type="weight",b.weightThreshold.field="measurement"):b.userForm.thresholds_attributes=void 0),"admin"===!k&&(b.userForm.first_name=b.userForm.first_name.replace(/\s{2,}/g," ").replace(/(\s)?\-(\s)?/g,"-"),b.userForm.last_name=b.userForm.last_name.replace(/\s{2,}/g," ").replace(/(\s)?\-(\s)?/g,"-")),g.save(b.userType,b.userForm,b.onSaved,b.onError)},b.cancel=function(){b.$dismiss()},b.onClinicSuccessQuery=function(a){b.clinics=a},b.getClinics=function(){j.get("clinic",{search:"",sort:"name ASC"},b.onClinicSuccessQuery)};var l=function(){b.getClinics()};l()}]),angular.module("medleyDashboardAngularApp").controller("AddClinicCtrl",["$rootScope","$scope","$route","$location","$modal","$filter","ClinicListService",function(a,b,c,d,e,f,g){b.clinicForm={};var h=c.current.userType;b.userType=h,b.requestPending=!1,b.onError=function(a){b.requestPending=!1,b.errorMessage=a.error},b.onSaved=function(){b.requestPending=!1,a.$broadcast("medly.event.clinic.added"),b.$dismiss("")},b.done=function(){b.requestPending=!0,b.clinicForm.phone_number=f("formatPhone")(b.clinicForm.phone_number),g.save(b.userType,b.clinicForm,b.onSaved,b.onError)},b.cancel=function(){b.$dismiss()}}]),angular.module("medleyDashboardAngularApp").controller("EditCareTeamCtrl",["$scope","APICaregiversQuery","APIResources","$route",function(a,b,c,d){function e(a){return a.map(function(a){return a.caregiver.id})}var f={addItem:null,availableCaregivers:[],allCaregivers:[],relationships:[]};a.edit=f,f.relationships=a.user.medical_relationships.map(function(a){return a}),f.refreshAvailableList=function(){var a=e(f.relationships);f.availableCaregivers=f.allCaregivers.filter(function(b){return!_.contains(a,b.id)}),f.addItem=_.first(f.availableCaregivers)},f.allCaregivers=b({all:!0}),f.allCaregivers.$promise.then(f.refreshAvailableList),f.deleteCaregiverAtIndex=function(a){f.relationships.splice(a,1),f.refreshAvailableList()},f.addCaregiver=function(){var a=f.addItem;a&&(f.relationships.push({caregiver:a}),f.refreshAvailableList())},f.makeUpdateObject=function(){var b,c,d=e(f.relationships),g=e(a.user.medical_relationships),h=_.difference(g,d),i=_.difference(d,g);return b=a.user.medical_relationships.filter(function(a){return _.contains(h,a.caregiver.id)}).map(function(a){return{id:a.id,_destroy:!0}}),c=i.map(function(a){return{caregiver_id:a}}),{medical_relationships_attributes:b.concat(c)}},a.save=function(){a.requestPending=!0,c.userResource(d.current.userType,d.current.params.id).update(f.makeUpdateObject()).$promise.then(function(b){a.userRefresh(),a.requestPending=!1}),a.$dismiss()}}]),angular.module("medleyDashboardAngularApp").controller("EditUserCtrl",["$scope","$rootScope","$filter","APIResources","$route","DISEASES","ClinicListService",function(a,b,c,d,e,f,g){a.birthday={},a.pwdValidity=!1,a.minMaxValidity=[0],a.fieldname="",a.goalsPattern=/^[0-9]+(\.[0-9]{1,2})?$/,a.weightPattern=/^[0-9]+(\.[0-9]{1})?$/,a.minPattern=[0],a.maxPattern=[0],a.months=["January","February","March","April","May","June","July","August","September","October","November","December"],a.hemoRangeMax=function(){return a.diseases.CHF?null:a.goals.hemoglobin.caution_lower-.01},a.hemoRangeMin=function(){return a.diseases.CHF?null:a.goals.hemoglobin.caution_upper+.01},a.potRangeMax=function(){return a.diseases.CHF?a.goals.potassium.caution_lower+.01:a.goals.potassium.caution_lower-.01},a.potRangeMin=function(){return a.diseases.CHF?a.goals.potassium.caution_upper-.01:a.goals.potassium.caution_upper+.01},a.days=function(){for(var a=[],b=1;31>=b;b++)a.push(b);return a};var h=new Date(a.user.birthdate);a.birthday.year=h.getFullYear(),a.birthday.month=h.getMonth(),a.birthday.day=h.getUTCDate(),a.emails=[{id:"blood-pressure",label:"Blood Pressure",value:"Blood Pressure",attr:"bp_email"},{id:"symptoms",label:"Symptoms",value:"Symptoms",attr:"symptoms_email"},{id:"medications",label:"Medications",value:"Medications",attr:"meds_email"},{id:"lab-results",label:"Lab Results",value:"Lab Results",attr:"lab_email"}],a.setPwdValidity=function(b,c){c===b?a.pwdValidity=!0:a.pwdValidity=!1},a.weightMinMaxValidity=function(){var b=parseFloat(a.goals.weight.lower)<parseFloat(a.goals.weight.upper);return 0==b&&a.user.diseases.includes("CHF")?(a.requestPending=!0,b):(a.requestPending=!1,b)},a.setMinMaxValidity=function(b,c,d){if(null==b&&null!=c&&a.goalsPattern.test(b),null==c&&null!=b&&a.goalsPattern.test(c),a.goalsPattern.test(b)||-1!==a.minPattern.indexOf(d)){if(a.goalsPattern.test(b)){var e=a.minPattern.indexOf(d);-1!==e&&a.minPattern.splice(e,1)}}else a.minPattern.push(d);if(a.goalsPattern.test(c)||-1!==a.maxPattern.indexOf(d)){if(a.goalsPattern.test(c)){var e=a.maxPattern.indexOf(d);-1!==e&&a.maxPattern.splice(e,1)}}else a.maxPattern.push(d);if(parseFloat(b)>=parseFloat(c)&&-1===a.minMaxValidity.indexOf(d))a.minMaxValidity.push(d);else if(parseFloat(b)<parseFloat(c)){var e=a.minMaxValidity.indexOf(d);-1!==e&&a.minMaxValidity.splice(e,1)}},a.bgMaxLowRange=function(a,b,c){return a>b&&c>=a?Number(a)+1:b},a.emailAlerts=[],a.diseaseNames=[{id:0,label:f.CHF,value:f.CHF,checked:a.user.diseases&&a.user.diseases.indexOf(f.CHF)>-1},{id:1,label:f.CKD,value:f.CKD,checked:a.user.diseases&&a.user.diseases.indexOf(f.CKD)>-1},{id:2,label:f.COPD,value:f.COPD,checked:a.user.diseases&&a.user.diseases.indexOf(f.COPD)>-1},{id:3,label:"Diabetes",value:f.DIABETES,checked:a.user.diseases&&a.user.diseases.indexOf(f.DIABETES)>-1},{id:4,label:f.HTN,value:f.HTN,checked:a.user.diseases&&a.user.diseases.indexOf(f.HTN)>-1}],a.updateQuestionValue=function(b){b.checked?(a.user.diseases.push(b.value),a.user.diseases=_.uniq(a.user.diseases)):a.user.diseases=_.without(a.user.diseases,b.value)};var i=function(){if("goals"===a.editSection)return{thresholds_attributes:a.user.thresholds,med_info:a.user.med_info};if("contact"===a.editSection||"patient-contact"===a.editSection)return a.user.contact_information.cell_phone=c("formatPhone")(a.user.contact_information.cell_phone),a.user.contact_information.home_phone=c("formatPhone")(a.user.contact_information.home_phone),a.user.contact_information.work_phone=c("formatPhone")(a.user.contact_information.work_phone),{contact_information_attributes:a.user.contact_information};if("login"===a.editSection||"patient-login"===a.editSection)return{user_attributes:a.user.user};if("study"===a.editSection){var b;return b=a.isCaregiver?{alerts_enabled:a.user.alerts_enabled,caregiver_role_id:a.user.caregiver_role_id}:{determinant_set_attributes:a.user.determinant_set,user_attributes:{disease_names:a.user.diseases}}}if("information"===a.editSection){var d=new Date;return d.setFullYear(a.birthday.year,a.birthday.month,a.birthday.day),a.user.birthdate=d,a.user.first_name=a.user.first_name.replace(/\s{2,}/g," ").replace(/(\s)?\-(\s)?/g,"-"),a.user.last_name=a.user.last_name.replace(/\s{2,}/g," ").replace(/(\s)?\-(\s)?/g,"-"),{mrn:a.user.mrn,title:a.user.title,first_name:a.user.first_name,last_name:a.user.last_name,middle_initial:a.user.middle_initial,maiden_name:a.user.maiden_name,birthdate:a.user.birthdate,age:a.user.age,sex:a.user.sex,user_clinic_attributes:{clinic_id:a.user.clinic.id}}}return{unexpectedSection:a.editSection}};a.user_pristine=angular.copy(a.user),a.goals_pristine=angular.copy(a.goals),a.onClinicSuccessQuery=function(b){a.clinics=b},a.getClinics=function(){g.get("clinic",{search:"",sort:"name ASC"},a.onClinicSuccessQuery)},a.checkUser=function(){d.userResource(e.current.userType,e.current.params.id).get().$promise.then(function(b){a.userNow=b,a.noChangeInUser=a.user.updated_at===a.userNow.updated_at},function(a){console.log("Data failed to load.")})},a.save=function(){a.requestPending=!0,a.noChangeInUser?d.userResource(e.current.userType,e.current.params.id).update(i()).$promise.then(function(c){a.requestPending=!1,a.userRefresh(),b.$broadcast("medly.event.user.updated"),a.$dismiss()},function(a){console.log("Error saving",a),alert("There was an error saving your changes. Please try again.")}):(alert("Patient information is out of date. Please try again."),a.requestPending=!1,angular.copy(a.user_pristine,a.user),angular.copy(a.goals_pristine,a.goals),a.userRefresh(),a.$dismiss())},a.cancel=function(){angular.copy(a.user_pristine,a.user),angular.copy(a.goals_pristine,a.goals),a.$dismiss()};var j=function(){a.getClinics(),a.checkUser()};j()}]),angular.module("medleyDashboardAngularApp").controller("EditClinicCtrl",["$scope","$rootScope","$filter","APIResources","$route",function(a,b,c,d,e){var f=function(){return a.clinic.phone_number=c("formatPhone")(a.clinic.phone_number),{name:a.clinic.name,address:a.clinic.address,city:a.clinic.city,postal_code:a.clinic.postal_code,phone_number:a.clinic.phone_number}};a.save=function(){a.requestPending=!0,d.userResource(e.current.userType,e.current.params.id).update(f()).$promise.then(function(b){a.userRefresh(),a.requestPending=!1}),b.$broadcast("medly.event.user.updated"),a.$dismiss()},a.clinic_pristine=angular.copy(a.clinic),a.cancel=function(){angular.copy(a.clinic_pristine,a.clinic),a.$dismiss()}}]),angular.module("medleyDashboardAngularApp").controller("PatientCtrl",["$scope","$sce","$routeParams","UserSession","$cookieStore","AlertMessageService","$rootScope","$modal","APIResources","DISEASES",function(a,b,c,d,e,f,g,h,i,j){a.canViewHistory=d.can("viewHistory"),a.canResetPatientAlgorithm=d.can("resetPatientAlgorithm"),a.canUpdateNextClinicDate=d.can("updateNextClinicDate");var k=function(b){return a.user&&a.user.diseases&&a.user.diseases.indexOf(b)>-1},l=function(){a.diseases={CHF:k(j.CHF),CKD:k(j.CKD),COPD:k(j.COPD),DIABETES:k(j.DIABETES)},_.keys(a.tabState).forEach(function(b){a.$watch(function(){return a.tabState[b]},function(a){a&&(console.log(b+" tab activated"),e.put("activeTab",b))})})};a.$on("$destroy",function(){e.remove("activeTab")}),a.$on("medly.user.loaded",l),a.tabState=function(b){_.keys(a.tabState).forEach(function(b){a.tabState[b]=!1}),a.tabState[b]=!0},a.tabState(c.activeTab||e.get("activeTab")||"summary");var m=function(){a.showSpinner=!0,i.patientAlertsListResource(c.id).query({sort:"created_at DESC"}).$promise.then(function(b){a.allAlerts=_.sortBy(b,function(a){return a.alertable.measured_at}).reverse();var c=new Date;c.setHours(0,0,0,0);var d=_.filter(a.allAlerts,function(a){var b="unresolved"===a.status,d="resolved"===a.status&&Date.parse(a.status_updated_at)>c,e=b||d;return e});a.headerAlerts=d})};a.alertMessage=function(c){var c=f.alertMessage(c,a.user.id);return b.trustAsHtml(c)},a.alertTime=function(a){return null!==a.start_date?a.start_date:a.alertable.measured_at},a.refreshClinicDates=function(){i.patientDatesResource(c.id).get({only:"ckd_next_clinic_date"}).$promise.then(function(b){a.nextClinicDate=b}),i.patientDatesResource(c.id).get({only:"ckd_last_clinic_date"}).$promise.then(function(b){a.lastClinicDate=b})},a.resetCOPDAlgorithm=function(){a.disableResetButton=!0;var b=new Date,c={date_type:1,date:b},d=i.patientDatesResource(a.user.id).save(c);d.$promise.then(function(){a.refreshCopdResetDate(),a.disableResetButton=!1})},a.refreshCopdResetDate=function(){i.patientDatesResource(c.id).get({only:"copd_algorithm_last_reset_date"}).$promise.then(function(b){a.copdResetDate=b})},a.openClinicDateModal=function(){g.modalInstance=h.open({controller:"PatientClinicDateEditCtrl",templateUrl:"views/users/edit/modal-clinic-date-edit.html",scope:a}),g.modalInstance.opened.then(function(){g.$broadcast("medly.modal.opened")}),g.modalInstance.result.then(function(){},function(a){g.$broadcast("medly.modal.closed")})},a.stopPropagation=function(a){a.stopPropagation()},a.statusChange=function(a){i.alertsResource(a.id).update(a).$promise},a.alertResolved=function(a){return"resolved"===a.status};var n=function(){a.refreshClinicDates(),a.disableResetButton=!1,a.refreshCopdResetDate(),m()};n()}]),angular.module("medleyDashboardAngularApp").controller("ClinicCtrl",["$scope","$sce","$route","UserSession","$cookieStore","$rootScope","$modal","APIResources",function(a,b,c,d,e,f,g,h){c.current.userType;a.clinicRefresh=function(){h.userResource(c.current.userType,c.current.params.id).get().$promise.then(function(b){a.clinic=b})},a.openEditModal=function(){f.modalInstance=g.open({controller:"EditClinicCtrl",scope:a,templateUrl:"views/users/edit/modal-clinic-edit.html"}),f.modalInstance.opened.then(function(){f.$broadcast("medly.modal.opened")}),f.modalInstance.result.then(function(){},function(a){f.$broadcast("medly.modal.closed")})};var i=function(){a.clinicRefresh()};i()}]),angular.module("medleyDashboardAngularApp").controller("PatientCareTeamCtrl",["$scope","$rootScope","$modal","UserSession",function(a,b,c,d){a.editableCareTeam=d.can("editCareTeam"),a.$on("medly.user.loaded",function(){a.caregivers=a.user.medical_relationships.map(function(a){var b=a.caregiver.contact_information,c=[{label:"Phone",value:b.home_phone},{label:"Work Phone",value:b.work_phone},{label:"Fax",value:b.fax},{label:"Address",value:b.address?b.address+", "+b.city:null}].filter(function(a){return a.value});return $.extend({},a,{displayItems:c})})}),a.$on("medly.user.loaded",function(){a.contacts=a.user.contacts,a.contacts.forEach(function(a){var b={phone:"Phone",email:"Email",address:"Address",fax:"Fax"};a.formattedItems=Object.keys(b).map(function(c){return{label:b[c],value:a[c]}}).filter(function(a){return a.value})})}),a.openCaregiverEditModal=function(){a.editSection="careTeam",b.modalInstance=c.open({controller:"EditCareTeamCtrl",scope:a.$new(),templateUrl:"views/users/edit/modal-careTeam-edit.html"}),b.modalInstance.opened.then(function(){b.$broadcast("medly.modal.opened")}),b.modalInstance.result.then(function(){},function(a){b.$broadcast("medly.modal.closed")})}}]),angular.module("medleyDashboardAngularApp").controller("PatientPrescriptionCtrl",["$scope","$rootScope","$routeParams","$modal","APIResources","UserSession",function(a,b,c,d,e,f){a.medReviewButtonTitle="View More ",a.canEditPrescription=f.can("editPrescription"),a.displayMedReviewResults=0,a.selectedPrescriptionEntries=[],a.supplementalO2View=[],a.changeTitle=function(){"View More "===a.medReviewButtonTitle?(a.medReviewButtonTitle="View Less ",a.displayMedReviewResults=1):(a.medReviewButtonTitle="View More ",a.displayMedReviewResults=0)},a.refreshPrescriptionList=function(){var b=e.patientPrescriptionListResource(c.id).query();b.$promise.then(function(b){a.prescriptions=b,a.supplementalO2View=[],angular.forEach(a.prescriptions,function(b,c){angular.forEach(b,function(a,c){"Maintenance"===a&&(b.duration=null)}),"Supplemental Oxygen"===b.generic&&a.supplementalO2View.push(b)}),a.updateDate=b.meta.last_updated});var d=e.patientMeasurementResource(c.id,"symptom").query({});d.$promise.then(function(b){a.medReviews=b.filter(function(a){return"ckd_med_1"===a.version}),a.questions=a.medReviews[0]&&a.medReviews[0].questions,a.possible_responses=a.medReviews[0]&&a.medReviews[0].possible_responses})},a.openPrescriptionEntryModal=function(c,e){a.selectedPrescriptionEntry=e?e:{prescribable_type:c.toLowerCase()},b.modalInstance=d.open({controller:"PatientPrescriptionEditCtrl",templateUrl:"views/users/add/modal-"+c+"-prescription-add.html",scope:a}),b.modalInstance.opened.then(function(){b.$broadcast("medly.modal.opened")}),b.modalInstance.result.then(function(){},function(a){b.$broadcast("medly.modal.closed")})},a.pullCKDMeds=function(){},a.openSupplementalO2Modal=function(c){a.selectedPrescriptionEntries=[],angular.forEach(c,function(b,c){a.selectedPrescriptionEntries.push(b?b:{prescribable_type:"copd"})}),b.modalInstance=d.open({controller:"PatientSupplementalO2Ctrl",templateUrl:"views/users/add/modal-supplemental-O2.html",scope:a}),b.modalInstance.opened.then(function(){b.$broadcast("medly.modal.opened")}),b.modalInstance.result.then(function(){},function(a){b.$broadcast("medly.modal.closed")})},a.isPrescriptionType=function(a,b){return a.prescribable_type===b},a.editablePrescription=function(b){return a.isPrescriptionType(b,"chf")|a.isPrescriptionType(b,"copd")},a.refreshPrescriptionList()}]),angular.module("medleyDashboardAngularApp").controller("PatientPrescriptionEditCtrl",["$scope","$routeParams","APIResources","MedicationService",function(a,b,c,d){a.showTapered=!1,a.requestPending=!1,a.hasVerification=!0,a.editablePrescription=d.makeEditablePrescription(a.selectedPrescriptionEntry),a.availableMedications={};var e={},f=0;"Maintenance"===a.editablePrescription.prescription.direction.value?f=0:"Exacerbation 1"===a.editablePrescription.prescription.direction.value?f=1:"Exacerbation 2"===a.editablePrescription.prescription.direction.value&&(f=2),"copd"===a.editablePrescription.prescribable_type&&void 0===a.editablePrescription.prescription.tapered.value&&(a.editablePrescription.prescription.tapered.value=!1);var g=function(b,c){return{multiple:!1,containerCss:{display:"block"},placeholder:"Select "+b.childLabel+" or enter your own",formatNoMatches:"Enter your own "+b.childLabel,data:function(){return{results:c[b.child]}},createSearchChoice:function(a,b){return 0===$(b).filter(function(){return 0===this.text.localeCompare(a)}).length?{id:a,text:a}:void 0},initSelection:function(c,d){var e={id:0,text:a.editablePrescription.prescription[b.child].value};a.editablePrescription.prescription[b.name].value&&d(e)}}};a.availableMedications.direction={multiple:!1,containerCss:{display:"block"},formatNoMatches:"Please select direction",placeholder:"Select direction",data:function(){return{results:e.direction}},initSelection:function(b,c){var d={id:f,text:a.editablePrescription.prescription.direction.value};a.editablePrescription.prescription.direction.value&&c(d)}},a.availableMedications.additional_information={multiple:!1,containerCss:{display:"block"},formatNoMatches:"Please select additional information",placeholder:"Select additional information",data:[{id:0,text:"in the morning"},{id:1,text:"in the evening"},{id:2,text:"every 12 hours"},{id:3,text:"approximately at the same time every day"},{id:4,text:"every 4 hours"},{id:5,text:"every 6 hours"}],initSelection:function(b,c){var d={id:0,text:a.editablePrescription.prescription.additional_information.value};a.editablePrescription.prescription.additional_information.value&&c(d)}};var h=function(b,c){"direction"!==b&&a.editablePrescription.prescription[b].value&&a.editablePrescription.prescription[b].value.text&&(a.editablePrescription.prescription[b].value=null),d.filter(b,c).then(function(a){e[b]=[],a.forEach(function(a,c){var d={id:c,text:a};e[b].push(d)})}),a.editablePrescription.prescription.direction.value&&a.editablePrescription.prescription.direction.value.text&&(a.editablePrescription.prescription.direction.value.text.indexOf("Exacerbation")>-1?a.showTapered=!0:a.editablePrescription.prescription.direction.value.text.indexOf("Maintenance")>-1&&(a.showTapered=!1,a.editablePrescription.prescription.tapered.value=!1))};a["delete"]=function(){a.requestPending=!0,d.deleteEditablePrescription(b.id,a.editablePrescription).then(a.dismissAndRefresh)},a.save=function(){a.requestPending=!0,d.saveEditablePrescription(b.id,a.editablePrescription).then(function(){a.requestPending=!1,a.dismissAndRefresh()})},a.dismissAndRefresh=function(){a.$dismiss(),a.refreshPrescriptionList()},a.isEditablePrescriptionType=function(b){return a.editablePrescription.type===b},a.isEditablePrescriptionType("copd")&&(d.forEachMedicationKey(function(b){var c=a.editablePrescription.prescription[b.name];c.child&&(a.$watch("editablePrescription.prescription."+c.name+".value",function(){h(c.child,a.editablePrescription.prescription)}),a.availableMedications[c.child]=g(c,e))}),h("direction"))}]),angular.module("medleyDashboardAngularApp").controller("PatientSupplementalO2Ctrl",["$q","$scope","$routeParams","$rootScope","$modal","APIResources",function(a,b,c,d,e,f){b.supplementalPattern=/^[0-9]+(\.[0-9]*)?$/,b.supplementalOptions=["L/min","% (FiO2)"],b.supplementalO2Rest={generic:"Supplemental Oxygen",dose:"",units:"",additional_information:"at rest",type:"copd"},b.supplementalO2Exertion={generic:"Supplemental Oxygen",dose:"",units:"",additional_information:"with exertion",type:"copd"},b.supplementalO2Sleep={generic:"Supplemental Oxygen",dose:"",units:"",additional_information:"during sleep",type:"copd"},b.supplementalO2Rest.units=b.supplementalOptions[0],b.supplementalO2Exertion.units=b.supplementalOptions[0],b.supplementalO2Sleep.units=b.supplementalOptions[0],b.requestPending=!1,b.hasVerification=!0,b.optionsUpdated=function(a){"rest"===a?b.supplementalO2Rest.dose="":"exertion"===a?b.supplementalO2Exertion.dose="":"sleep"===a&&(b.supplementalO2Sleep.dose="")},angular.forEach(b.selectedPrescriptionEntries,function(a,c){"at rest"===a.additional_information&&(b.supplementalO2Rest=a),"with exertion"===a.additional_information&&(b.supplementalO2Exertion=a),"during sleep"===a.additional_information&&(b.supplementalO2Sleep=a)});var g=function(a,b){var c=b.id?f.patientPrescriptionListResource(a,b.prescribable_type,b.prescribable_id).update:f.patientPrescriptionListResource(a,b.type).save;return c(b).$promise},h=function(a,b){return f.patientPrescriptionListResource(a,b.prescribable_type,b.prescribable_id)["delete"]().$promise};b.save=function(){b.requestPending=!0,a.all([g(c.id,b.supplementalO2Rest),g(c.id,b.supplementalO2Exertion),g(c.id,b.supplementalO2Sleep)]).then(function(a){b.requestPending=!1,b.dismissAndRefresh()})},b["delete"]=function(){b.requestPending=!0,a.all([h(c.id,b.supplementalO2Rest),h(c.id,b.supplementalO2Exertion),h(c.id,b.supplementalO2Sleep)]).then(function(a){b.requestPending=!1,b.dismissAndRefresh()})},b.dismissAndRefresh=function(){b.$dismiss(),b.refreshPrescriptionList()}}]),angular.module("medleyDashboardAngularApp").controller("PatientClinicDateEditCtrl",["$scope","$rootScope","APIResources","$routeParams",function(a,b,c,d){a.newNextClinicDate={},a.newNextClinicDate.date=new Date,a.newNextClinicDate.date.setHours(12),a.newNextClinicDate.date.setMinutes(0),a.requestPending=!1;var e=0;a.newNextClinicDate.date_type=e,a.save=function(){a.requestPending=!0;var b=c.patientDatesResource(a.user.id).save(a.newNextClinicDate);b.$promise.then(function(){a.requestPending=!1,a.dismissAndRefresh()})},a.dismissAndRefresh=function(){a.refreshClinicDates(),a.cancel()},a.cancel=function(){a.$dismiss()}}]),angular.module("medleyDashboardAngularApp").controller("MohPatientPrintSummaryCtrl",["$scope","$modal","patient","APIResources","CkdSummaryPrinter",function(a,b,c,d,e){var f=["January","February","March","April","May","June","July","August","September","October","November","December"];a.patientId=c.id,a.hasCKD=!0;var g=c.diseases;_.indexOf(g,"CKD")<0&&(a.hasCKD=!1),a.loadPdfSummary=function(b){a.requestPending=!0;var e=new Date(b.getFullYear(),b.getMonth()+1,0);d.pdfSummaryResource(c.id).get({start_date:b,end_date:e}).$promise.then(function(c){a.downloadFileName=f[b.getMonth()]+" "+b.getFullYear()+" Summary Report.pdf",a.url=(window.URL||window.webkitURL).createObjectURL(c.response)})};var h=function(a,b){var c=b.getMonth()+12*b.getFullYear()-(a.getMonth()+12*a.getFullYear());return c},i=function(a){var b=[];if(a.earliest_reading_date){var c=new Date(a.earliest_reading_date);c.setDate(1);var d=new Date;d.setDate(1),d.setMonth(d.getMonth()-1);var e=h(c,d);if(e>=0)for(var g=0;e>=g;g++){var i=new Date;i.setDate(d.getDate()),i.setMonth(d.getMonth()-g),b.push({id:g,label:f[i.getMonth()]+" "+i.getFullYear(),value:i})}}return b};a.printCKDOnePager=function(){e.print(a.patientId)};var j=function(){a.requestPending=!1,a.availableMonths=i(c)};j()}]),angular.module("medleyDashboardAngularApp").controller("PatientReadingsCtrl",["$rootScope","$scope","$filter","$routeParams","$timeout","APIResources","ReadingGraphService","googleChartApiPromise","PatientLabResultService","AnalyticsService",function(a,b,c,d,e,f,g,h,i,j){b.readings={};b.min={},b.max={},b.components={},b.cautionLower={},b.cautionUpper={},b.chart={},b.displayedReadings=function(a){var c=_.filter(b.labResults,function(b){return void 0!==b.get(a).value});return j.labReadings(c,b.min[a],b.max[a],a)},b.numReadings=function(a){return j.totalNumReadings(b.displayedReadings(a))},b.numOutRange=function(a){return j.numOutsideRange(b.cautionLower[a],b.cautionUpper[a],b.displayedReadings(a))},b.avg=function(a){return j.average(b.displayedReadings(a),b.numReadings(a))},b.highlightReading=function(a,c){var d=a.get(c).value;return b.isOutsideRange=d<b.cautionLower[c]||d>b.cautionUpper[c],d},b.chfSymptoms={version:"chf_1"},b.ckdSymptoms={version:"ckd_1"},b.copdSymptoms={version:"copd_1"};var k=function(a){var b=f.patientMeasurementResource(d.id,"symptom").query({version:a.version});b.$promise.then(function(b){a.readings=b,a.questions=a.readings[0]&&a.readings[0].questions,a.possible_responses=a.readings[0]&&a.readings[0].possible_responses})},l=function(){b.allSymptoms={};var a=f.patientMeasurementResource(d.id,"symptom").query();a.$promise.then(function(a){b.allSymptoms.readings=a.reverse()})};$("#summaryTab").click(function(){b.$on("medly.user.loaded",function(a){b.scrollSymptoms()})}),b.scrollSymptoms=function(){if($(".symptoms-inner").is(":visible")&&b.tabState.summary){var a=$(".symptoms-inner"),c=$("#symptom-body");b.maxScrollLeft=0;var d=function(){b.maxScrollLeft=c.width()-a.width()};if(d(),b.maxScrollLeft>0)a.scrollLeft(b.maxScrollLeft);else for(;b.maxScrollLeft<20;)d(),$("#symptoms-table tr").each(function(a){0==a?$(this).append($('<td class="active"></td>')):$(this).append($("<td>"))})}};var m;b.refreshTestResults=function(a){b.user.thresholds&&(m=b.user.thresholds),m&&i.getLabResults(d.id).then(function(a){b.labResults=a,b.potassium=[],b.phosphate=[],b.kidney=[],b.hemoglobin=[],b.creatinine=[],b.sodium=[],b.bnp=[],b.testsWithValues=[];for(var d=function(a,c,d,f,g,h){b.chart[h]=new OMHWebVisualizations.Chart(a,c,d,f);var i=function(){void 0!==b.components[h]&&e(function(){b.min[h]=b.components[h].xScales[h].domainMin(),b.max[h]=b.components[h].xScales[h].domainMax()})};b.components[h]=b.chart[h].getComponents(),b.chart[h].onXScaleUpdate(i),b.chart[h].renderTo(c.find(g)[0])},f="#4a90e2",g="#FFFFFF",h="#4a90e2",i="#FFFFFF",j="#e8ac4e",k=function(){var a=b.potassium;b.maxPotassiumReading=_.max(b.potassium,function(a){return a.value}).value,b.minPotassiumReading=_.min(b.potassium,function(a){return a.value}).value;var c=_.findWhere(m,{measurement_type:"blood",field:"potassium"});b.cautionLower.Potassium=c?c.lower:b.minPotassiumReading,b.cautionUpper.Potassium=c?c.upper:b.maxPotassiumReading,b.potassiumRangeMax=c.upper>b.maxPotassiumReading?1.1*c.upper:1.1*b.maxPotassiumReading,b.potassiumRangeMin=c.lower<b.minPotassiumReading?.5*c.lower:.4*b.minPotassiumReading;var e="mmol/L";b.normalPotassium=b.cautionLower.Potassium+"-"+b.cautionUpper.Potassium+" "+e;var k=$(".omh-potassium-chart-container"),l="svg.omh-potassium-chart",n="Potassium",o={measures:{Potassium:{valueKeyPath:"value",units:"mmol/L",range:{min:b.potassiumRangeMin,max:b.potassiumRangeMax},seriesName:"Potassium",thresholds:{min:b.cautionLower.Potassium,max:b.cautionUpper.Potassium},chart:{type:"line",pointSize:10.5,lineColor:f,pointFillColor:g,pointStrokeColor:h,aboveThresholdPointFillColor:i,aboveThresholdPointStrokeColor:j,barColor:h,daysShownOnTimeline:{min:3,max:366}}}}};d(a,k,n,o,l,"Potassium")},l=function(){var a=b.phosphate;b.maxPhosphateReading=_.max(b.phosphate,function(a){return a.value}).value,b.minPhosphateReading=_.min(b.phosphate,function(a){return a.value}).value;var c=_.findWhere(m,{measurement_type:"blood",field:"phosphate"});b.cautionLower.Phosphate=c?c.lower:b.minPhosphateReading,b.cautionUpper.Phosphate=c?c.upper:b.maxPhosphateReading,b.phosphateRangeMax=c.upper>b.maxPhosphateReading?1.1*c.upper:1.1*b.maxPhosphateReading,b.phosphateRangeMin=c.lower<b.minPhosphateReading?.5*c.lower:.4*b.minPhosphateReading;var e="mmol/L";b.normalPhosphate=b.cautionLower.Phosphate+"-"+b.cautionUpper.Phosphate+" "+e;var k=$(".omh-phosphate-chart-container"),l="svg.omh-phosphate-chart",n="Phosphate",o={measures:{Phosphate:{valueKeyPath:"value",units:"mmol/L",range:{min:b.phosphateRangeMin,max:b.phosphateRangeMax},seriesName:"Phosphate",thresholds:{min:b.cautionLower.Phosphate,max:b.cautionUpper.Phosphate},chart:{type:"line",pointSize:10.5,lineColor:f,pointFillColor:g,pointStrokeColor:h,aboveThresholdPointFillColor:i,aboveThresholdPointStrokeColor:j,barColor:h,daysShownOnTimeline:{min:3,max:366}}}}};d(a,k,n,o,l,"Phosphate")},n=function(){var a=b.creatinine;b.maxCreatinineReading=_.max(b.creatinine,function(a){return a.value}).value,b.minCreatinineReading=_.min(b.creatinine,function(a){return a.value}).value;var c=_.findWhere(m,{measurement_type:"blood",field:"creatinine"});b.creatinineExists=null!=c.lower&&null!=c.upper,b.cautionUpper.Creatinine=b.creatinineExists?c.upper:1.1*b.maxCreatinineReading,b.cautionLower.Creatinine=b.creatinineExists?c.lower:.5*b.minCreatinineReading,b.creatinineRangeMax=b.creatinineExists&&c.upper>b.maxCreatinineReading?1.1*c.upper:1.1*b.maxCreatinineReading,b.creatinineRangeMin=b.creatinineExists&&c.lower<b.minCreatinineReading?.5*c.lower:.5*b.minCreatinineReading;var e="µmol/L";b.normalCreatinine=b.cautionLower.Creatinine+"-"+b.cautionUpper.Creatinine+" "+e;
  var k=$(".omh-creatinine-chart-container"),l="svg.omh-creatinine-chart",n="Creatinine",o={measures:{Creatinine:{valueKeyPath:"value",units:"umol/L",range:{min:b.creatinineRangeMin,max:b.creatinineRangeMax},seriesName:"Creatinine",thresholds:{min:b.cautionLower.Creatinine,max:b.cautionUpper.Creatinine},chart:{type:"line",pointSize:10.5,lineColor:f,pointFillColor:g,pointStrokeColor:h,aboveThresholdPointFillColor:i,aboveThresholdPointStrokeColor:j,barColor:h,daysShownOnTimeline:{min:3,max:366}}}}};d(a,k,n,o,l,"Creatinine")},o=function(){var a=b.kidney,c=$(".omh-kidney-chart-container"),e="svg.omh-kidney-chart",f="Kidney Function",g={measures:{"Kidney Function":{valueKeyPath:"value",units:"%",range:{min:0,max:100},seriesName:"Kidney",thresholds:{min:0,max:100},chart:{type:"line",pointSize:10.5,lineColor:"#4a90e2",pointFillColor:"#FFFFFF",pointStrokeColor:"#4a90e2",aboveThresholdPointFillColor:"#FFFFFF",aboveThresholdPointStrokeColor:"#e8ac4e",barColor:"#4a90e2",daysShownOnTimeline:{min:3,max:366}}}}};d(a,c,f,g,e,"Kidney Function")},p=function(){var a=b.hemoglobin;b.maxHemoglobinReading=_.max(b.hemoglobin,function(a){return a.value}).value,b.minHemoglobinReading=_.min(b.hemoglobin,function(a){return a.value}).value;var c=_.findWhere(m,{measurement_type:"blood",field:"hemoglobin"});b.cautionLower.Hemoglobin=c?c.lower:b.minHemoglobinReading,b.cautionUpper.Hemoglobin=c?c.upper:b.maxHemoglobinReading;var e="g/L";b.hemoglobinRangeMax=c.upper>b.maxHemoglobinReading?1.1*c.upper:1.1*b.maxHemoglobinReading,b.hemoglobinRangeMin=c.lower<b.minHemoglobinReading?.5*c.lower:.8*b.minHemoglobinReading,b.normalHemoglobin=b.cautionLower.Hemoglobin+"-"+b.cautionUpper.Hemoglobin+" "+e;var f=$(".omh-hemo-chart-container"),g="svg.omh-hemo-chart",h="Hemoglobin",i={measures:{Hemoglobin:{valueKeyPath:"value",units:"g/L",range:{min:b.hemoglobinRangeMin,max:b.hemoglobinRangeMax},seriesName:"Hemoglobin",thresholds:{min:b.cautionLower.Hemoglobin,max:b.cautionUpper.Hemoglobin},chart:{type:"line",pointSize:10.5,lineColor:"#4a90e2",pointFillColor:"#FFFFFF",pointStrokeColor:"#4a90e2",aboveThresholdPointFillColor:"#FFFFFF",aboveThresholdPointStrokeColor:"#e8ac4e",barColor:"#4a90e2",daysShownOnTimeline:{min:3,max:366}}}}};d(a,f,h,i,g,"Hemoglobin")},q=function(){var a=b.sodium;b.maxSodiumReading=_.max(b.sodium,function(a){return a.value}).value,b.minSodiumReading=_.min(b.sodium,function(a){return a.value}).value;var c=_.findWhere(m,{measurement_type:"blood",field:"sodium"});b.sodiumExists=null!=c.lower&&null!=c.upper,b.cautionUpper.Sodium=b.sodiumExists?c.upper:1.1*b.maxSodiumReading,b.cautionLower.Sodium=b.sodiumExists?c.lower:.5*b.minSodiumReading,b.sodiumRangeMax=b.sodiumExists&&c.upper>b.maxSodiumReading?1.1*c.upper:1.1*b.maxSodiumReading,b.sodiumRangeMin=b.sodiumExists&&c.lower<b.minSodiumReading?.5*c.lower:.5*b.minSodiumReading;var e="mmol/L";b.normalSodium=b.cautionLower.Sodium+"-"+b.cautionUpper.Sodium+" "+e;var f=$(".omh-sodium-chart-container"),g="svg.omh-sodium-chart",h="Sodium",i={measures:{Sodium:{valueKeyPath:"value",units:"mmol/L",range:{min:b.sodiumRangeMin,max:b.sodiumRangeMax},seriesName:"Sodium",thresholds:{min:b.cautionLower.Sodium,max:b.cautionUpper.Sodium},chart:{type:"line",pointSize:10.5,lineColor:"#4a90e2",pointFillColor:"#FFFFFF",pointStrokeColor:"#4a90e2",aboveThresholdPointFillColor:"#FFFFFF",aboveThresholdPointStrokeColor:"#e8ac4e",barColor:"#4a90e2",daysShownOnTimeline:{min:3,max:366}}}}};d(a,f,h,i,g,"Sodium")},r=function(){var a=b.bnp;b.maxBnpReading=_.max(b.bnp,function(a){return a.value}).value,b.minBnpReading=_.min(b.bnp,function(a){return a.value}).value;var c=_.findWhere(m,{measurement_type:"blood",field:"bnp"});b.bnpExists=null!=c.lower&&null!=c.upper,b.cautionUpper.BNP=b.bnpExists?c.upper:1.1*b.maxBnpReading,b.cautionLower.BNP=b.bnpExists?c.lower:.4*b.minBnpReading,b.bnpRangeMax=b.bnpExists&&c.upper>b.maxBnpReading?1.1*c.upper:1.1*b.maxBnpReading,b.bnpRangeMin=b.bnpExists&&c.lower<b.minBnpReading?.5*c.lower:.4*b.minBnpReading;var e="pg/mL";b.normalBnp=b.cautionLower.BNP+"-"+b.cautionUpper.BNP+" "+e;var f=$(".omh-bnp-chart-container"),g="svg.omh-bnp-chart",h="BNP",i={measures:{BNP:{valueKeyPath:"value",units:"pg/mL",range:{min:b.bnpRangeMin,max:b.bnpRangeMax},seriesName:"BNP",thresholds:{min:b.cautionLower.BNP,max:b.cautionUpper.BNP},chart:{type:"line",pointSize:10.5,lineColor:"#4a90e2",pointFillColor:"#FFFFFF",pointStrokeColor:"#4a90e2",aboveThresholdPointFillColor:"#FFFFFF",aboveThresholdPointStrokeColor:"#e8ac4e",barColor:"#4a90e2",daysShownOnTimeline:{min:3,max:366}}}}};d(a,f,h,i,g,"BNP")},s=0;s<b.labResults.length;s++)for(var t=0;t<b.labResults[s].results.length;t++){c("date")(b.labResults[s].date,"medlyDate");switch(b.labResults[s].results[t].name){case"Potassium":b.potassium.push(b.labResults[s].results[t]);break;case"Phosphate":b.phosphate.push(b.labResults[s].results[t]);break;case"Hemoglobin":b.hemoglobin.push(b.labResults[s].results[t]);break;case"Kidney Function":b.kidney.push(b.labResults[s].results[t]);break;case"Creatinine":b.creatinine.push(b.labResults[s].results[t]);break;case"Sodium":b.sodium.push(b.labResults[s].results[t]);break;case"BNP":b.bnp.push(b.labResults[s].results[t])}b.labResults[s].results[t]&&-1==b.testsWithValues.indexOf(b.labResults[s].results[t].name)&&b.testsWithValues.push(b.labResults[s].results[t].name),t==b.labResults[s].results.length-1&&s==b.labResults.length-1&&(console.log("all lab results data loaded"),b.potassium&&b.potassium.length>0&&(b.potassiumPresent=!0,k()),b.phosphate&&b.phosphate.length>0&&(b.phosphatePresent=!0,l()),b.hemoglobin&&b.hemoglobin.length>0&&(b.hemoglobinPresent=!0,p()),b.kidney&&b.kidney.length>0&&(b.kidneyPresent=!0,o()),b.creatinine&&b.creatinine.length>0&&(b.creatininePresent=!0,n()),b.sodium&&b.sodium.length>0&&(b.sodiumPresent=!0,q()),b.bnp&&b.bnp.length>0&&(b.bnpPresent=!0,r()))}})},b.$on("medly.user.loaded",function(){if(b.chart)for(var a in b.chart)b.chart[a].destroy()}),b.$on("medly.event.user.updated",function(){if(b.chart)for(var a in b.chart)b.chart[a].destroy()}),b.$on("$destroy",function(){if(b.chart)for(var a in b.chart)b.chart[a].destroy()}),b.$on("medly.user.loaded",function(a){m=a.thresholds,b.refreshTestResults(),l()});var n=function(){k(b.ckdSymptoms),k(b.copdSymptoms),k(b.chfSymptoms)};n()}]),angular.module("medleyDashboardAngularApp").controller("PatientBpReadingsCtrl",["$rootScope","$scope","$routeParams","$filter","$timeout","ReadingGraphService","APIResources","AnalyticsService",function(a,b,c,d,e,f,g,h){var i;b.setDateDomain=function(){void 0!==b.components&&e(function(){b.min=b.components.xScales.systolic_blood_pressure.domainMin(),b.max=b.components.xScales.systolic_blood_pressure.domainMax()})},b.$on("bpLoaded",function(a,b){b||$(".bp-container").remove()}),b.bpChartData=function(a){b.user.thresholds&&(i=b.user.thresholds);var c="mmHg";_.contains(b.user.diseases,"CKD")?(b.systolicLower=115,b.systolicUpper=134,b.diastolicLower=55,b.diastolicUpper=84):(b.systolicLower=_.findWhere(i,{field:"systolic"}).lower,b.systolicUpper=_.findWhere(i,{field:"systolic"}).upper,b.diastolicLower=_.findWhere(i,{field:"diastolic"}).lower,b.diastolicUpper=_.findWhere(i,{field:"diastolic"}).upper),b.normalSystolic=b.systolicLower+"-"+b.systolicUpper+" "+c,b.normalDiastolic=b.diastolicLower+"-"+b.diastolicUpper+" "+c,b.sysHighlight=function(a){return b.isOutsideRange=a<b.systolicLower||a>b.systolicUpper,a},b.diaHighlight=function(a){return b.isOutsideRange=a<b.diastolicLower||a>b.diastolicUpper,a};var d=function(){return h.displayedReadings(b.readings.bp,b.min,b.max,"sbp")};b.sbpNumReadings=function(){return h.totalNumReadings(d())},b.sbpNumOutRange=function(){return h.numOutsideRange(b.systolicLower,b.systolicUpper,d())},b.sbpAvg=function(){return h.average(d(),b.sbpNumReadings())};var e=function(){return h.displayedReadings(b.readings.bp,b.min,b.max,"dbp")};b.dbpNumReadings=function(){return h.totalNumReadings(e())},b.dbpNumOutRange=function(){return h.numOutsideRange(b.diastolicLower,b.diastolicUpper,e())},b.dbpAvg=function(){return h.average(e(),b.dbpNumReadings())};var f=_.max(b.readings.bp,function(a){return a.sbp}).sbp+10,g=_.max([f,b.systolicUpper+10]),j=a,k=$(".omh-bp-chart-container"),l="BpReading",m={measures:{systolic_blood_pressure:{valueKeyPath:"sbp",range:{min:b.diastolicLower-40,max:g},units:"mmHg",seriesName:"Systolic/Diastolic",thresholds:{min:b.systolicLower,max:b.systolicUpper},chart:{type:"line",pointSize:10.5,lineColor:"#4a90e2",pointFillColor:"#FFFFFF",pointStrokeColor:"#4a90e2",aboveThresholdPointFillColor:"#FFFFFF",aboveThresholdPointStrokeColor:"#e8ac4e",barColor:"#4a90e2",daysShownOnTimeline:{min:1,max:366}}},diastolic_blood_pressure:{valueKeyPath:"dbp",range:{min:b.diastolicLower-40,max:b.diastolicUpper},units:"mmHg",seriesName:"Systolic/Diastolic",thresholds:{min:b.diastolicLower,max:b.diastolicUpper},chart:{type:"line",pointSize:10.5,lineColor:"#4a90e2",pointFillColor:"#FFFFFF",pointStrokeColor:"#4a90e2",aboveThresholdPointFillColor:"#FFFFFF",aboveThresholdPointStrokeColor:"#e8ac4e",barColor:"#4a90e2",daysShownOnTimeline:{min:1,max:366}}}}};b.drawOmhChart(j,k,l,m)},b.drawOmhChart=function(a,c,d,e){b.bpChart=new OMHWebVisualizations.Chart(a,c,d,e),b.components=b.bpChart.getComponents(),b.bpChart.onXScaleUpdate(b.setDateDomain),b.bpChart.renderTo(c.find("svg.omh-bp-chart")[0])},b.$on("medly.user.loaded",function(){b.bpChart&&b.bpChart.destroy()}),b.$on("medly.event.user.updated",function(){b.bpChart&&b.bpChart.destroy()}),b.$on("$destroy",function(){b.bpChart&&b.bpChart.destroy()}),b.$on("medly.user.loaded",function(d){i=d.thresholds;var e=g.patientMeasurementResource(c.id,"bp").query();e.$promise.then(function(c){c.length>0?(b.readings.bp=c,b.bpChartData(c),a.$broadcast("bpLoaded",!0)):a.$broadcast("bpLoaded",!1)})})}]),angular.module("medleyDashboardAngularApp").controller("PatientBgReadingsCtrl",["$scope","$routeParams","$filter","$timeout","APIResources","ReadingGraphService","AnalyticsService","MEASUREMENT",function(a,b,c,d,e,f,g,h){a.min={},a.max={},a.components={};var i="overall",j=function(b,c){return void 0===c&&(c=i),g.displayedReadings(b,a.min[c],a.max[c],h)};a.bgNumReadings=function(a,b){return g.totalNumReadings(j(a,b))},a.bgNumOutRange=function(b,c){return g.numOutsideRange(a.bgGoal.lower,a.bgGoal.upper,j(b,c))},a.bgAvg=function(b,c){return g.average(j(b,c),a.bgNumReadings(b,c))},a.outRangeHighlight=function(b){return a.isOutsideRange=b<a.bgGoal.lower||b>a.bgGoal.upper,b};var k=function(a){var b=_.groupBy(a,function(a){return a.measured_at.substring(0,10)}),c=_.reduce(b,function(a,b){return a+b.length},0),d=c/Object.keys(b).length;return d};a.totalNumReadings=function(a){return a?a.length:0},a.averageBloodGlucose=function(b){var c=_.reduce(b,function(a,b){return a+b.measurement},0),d=c/a.totalNumReadings(b);return d},a.belowRange=function(b){var c=_.pluck(b,h),d=_.select(c,function(b){return a.bgGoal&&b<a.bgGoal.caution_lower});return c.length>0?d.length/c.length:null},a.withinRange=function(b){var c=_.pluck(b,h),d=_.select(c,function(b){return a.bgGoal&&b>a.bgGoal.caution_lower&&b<a.bgGoal.caution_upper});return c.length>0?d.length/c.length:null},a.aboveRange=function(b){var c=_.pluck(b,h),d=_.select(c,function(b){return a.bgGoal&&b>a.bgGoal.caution_upper});return c.length>0?d.length/c.length:null},a.criticalHigh=function(b){var c=_.pluck(b,h),d=_.select(c,function(b){return a.bgGoal&&b>=a.bgGoal.upper});return d.length},a.criticalLow=function(b){var c=_.pluck(b,h),d=_.select(c,function(b){return a.bgGoal&&b<a.bgGoal.lower});return d.length},a.loadReadings=function(){var c=e.patientMeasurementResource(b.id,"bg").query();c.$promise.then(function(b){if(b.length>0){a.readings.bg={};var c=_.reject(b,function(b){var c=_.contains(a.defaultContexts,b.measurement_context);return c});if(c.length>1){_.pluck(c,"measurement_context");_.each(c,function(c){a.readings.bg[c.measurement_context]=_.where(b,{measurement_context:c.measurement_context}),a.firstRenders[c.measurement_context]=!0})}a.bgGoal=_.findWhere(a.user.thresholds,{measurement_type:"blood_glucose",field:h}),a.readings.bg.overnight=_.where(b,{measurement_context:"overnight"}),a.readings.bg.breakfast=_.where(b,{measurement_context:"breakfast"}),a.readings.bg.lunch=_.where(b,{measurement_context:"lunch"}),a.readings.bg.dinner=_.where(b,{measurement_context:"dinner"}),a.readings.bg.bedtime=_.where(b,{measurement_context:"bedtime"}),a.readings.bg.overall=b,a.chartObject={},a.filterReadings()}})},a.filterReadings=function(){a.readings.bg.overall&&(a.overallBgReadings=a.readings.bg.overall,a.averageReadingsPerDay=k(a.overallBgReadings),a.contexts=_.groupBy(a.overallBgReadings,"measurement_context"),a.customContexts=_.reduce(a.contexts,function(b,c,d){return _.contains(a.defaultContexts,d)===!1&&(b[d]=c),b},{}),a.customContextKeys=Object.keys(a.customContexts),a.allContexts=a.defaultContexts.concat(a.customContextKeys),a.allContexts.forEach(function(b){a.loadChartForContext(b)}),a.loadChartForContext(i))},a.contextHasReadings=function(a){return a.length>0};var l=function(a){return a===i},m=function(b,c,e,f,g,h){if(a.bgChart=new OMHWebVisualizations.Chart(b,c,e,f),l(h)){var j=function(){void 0!==a.components[i]&&d(function(){a.min[i]=a.components[i].xScales.BgReading.domainMin(),a.max[i]=a.components[i].xScales.BgReading.domainMax()})};a.components[i]=a.bgChart.getComponents(),a.bgChart.onXScaleUpdate(j)}else{var j=function(){void 0!==a.components[h]&&d(function(){a.min[h]=a.components[h].xScales.BgReading.domainMin(),a.max[h]=a.components[h].xScales.BgReading.domainMax()})};a.components[h]=a.bgChart.getComponents(),a.bgChart.onXScaleUpdate(j)}a.bgChart.renderTo(c.find(g)[0])};a.$on("$destroy",function(){a.bgChart&&a.bgChart.destroy()}),a.loadChartForContext=function(b){a.chartObject[b]={};var c=l(b)?a.overallBgReadings:a.contexts[b];if(a.normalBg=a.bgGoal.lower+"-"+a.bgGoal.upper,l(b)&&c.length>0&&a.bgGoal){var d=a.readings.bg.overall,e=$(".omh-bg-chart-container"),f="svg.omh-bg-chart",g="BgReading",i={measures:{BgReading:{valueKeyPath:h,units:"mmol/L",range:{min:0,max:35},seriesName:"Blood Glucose",thresholds:{min:a.bgGoal.lower,max:a.bgGoal.upper},chart:{type:"line",pointSize:10.5,lineColor:"#4a90e2",pointFillColor:"#FFFFFF",pointStrokeColor:"#4a90e2",aboveThresholdPointFillColor:"#FFFFFF",aboveThresholdPointStrokeColor:"#e8ac4e",barColor:"#4a90e2",daysShownOnTimeline:{min:3,max:366}}}}};a.firstRenders.overall&&e.length>0&&(m(d,e,g,i,f,b),a.firstRenders.overall=!1)}if(!l(b)&&void 0!==c&&c.length>0&&a.bgGoal){var d=a.readings.bg[b],e=$(".omh-bg-"+b+"-chart-container"),f="svg.omh-bg-"+b+"-chart",g="BgReading",i={measures:{BgReading:{valueKeyPath:h,units:"mmol/L",range:{min:0,max:35},seriesName:"Blood Glucose",thresholds:{min:a.bgGoal.lower,max:a.bgGoal.upper},chart:{type:"line",pointSize:10.5,lineColor:"#4a90e2",pointFillColor:"#FFFFFF",pointStrokeColor:"#4a90e2",aboveThresholdPointFillColor:"#FFFFFF",aboveThresholdPointStrokeColor:"#e8ac4e",barColor:"#4a90e2",daysShownOnTimeline:{min:3,max:366}}}}};a.firstRenders[b]&&e.length>0&&(m(d,e,g,i,f,b),a.firstRenders[b]=!1)}};var n=function(){a.averageReadingsPerDay=null,a.bgGoal=null,a.defaultContexts=["overnight","breakfast","lunch","dinner","bedtime"],a.firstRenders={},a.firstRenders.overall=!0;for(var b=0;b<a.defaultContexts.length;b++)a.firstRenders[a.defaultContexts[b]]=!0;a.contexts=[],a.allContexts=[],a.loadReadings()};a.$on("medly.user.loaded",function(){n()})}]),angular.module("medleyDashboardAngularApp").controller("PatientWeightReadingsCtrl",["$rootScope","$scope","$filter","$routeParams","ReadingGraphService","APIResources","AnalyticsService","$timeout","MEASUREMENT",function(a,b,c,d,e,f,g,h,i){var j;b.setDateDomain=function(){void 0!==b.components&&h(function(){b.min=b.components.xScales.WeightReading.domainMin(),b.max=b.components.xScales.WeightReading.domainMax()})},b.$on("weightLoaded",function(a,b){b||$(".weight-container").remove()}),b.weightChartData=function(a){b.user.thresholds&&(j=b.user.thresholds);var c=_.map(a,function(a){return"kg"===a.units?(a.measurement=Math.round(2.2*a.measurement),a):a}),d=_.findWhere(j,{measurement_type:"weight",field:i}),e=d?d.lower:null,f=d?d.upper:null,h=(d?d.upper-d.lower:null,"lbs");b.normalWeight=e+"-"+f+" "+h,b.highlight=function(a){return b.isOutsideRange=e>a||a>f,a};var k=function(){return g.displayedReadings(b.readings.weight,b.min,b.max,i)};b.numReadings=function(){return g.totalNumReadings(k())},b.numOutRange=function(){return g.numOutsideRange(e,f,k())},b.average=function(){return g.average(k(),b.numReadings())};var l=c,m=$(".omh-weight-chart-container"),n="WeightReading",o={measures:{WeightReading:{valueKeyPath:i,units:"lbs",range:{min:e-20,max:f+20},seriesName:"Weight",thresholds:{min:e,max:f},chart:{type:"line",pointSize:10.5,lineColor:"#4a90e2",pointFillColor:"#FFFFFF",pointStrokeColor:"#4a90e2",aboveThresholdPointFillColor:"#FFFFFF",aboveThresholdPointStrokeColor:"#e8ac4e",barColor:"#4a90e2",daysShownOnTimeline:{min:3,max:366}}}}};b.drawOmhChart(l,m,n,o)},b.drawOmhChart=function(a,c,d,e){b.weightChart=new OMHWebVisualizations.Chart(a,c,d,e),b.components=b.weightChart.getComponents(),b.weightChart.onXScaleUpdate(b.setDateDomain),b.weightChart.renderTo(c.find("svg.omh-weight-chart")[0])},b.$on("medly.user.loaded",function(){b.weightChart&&b.weightChart.destroy()}),b.$on("medly.event.user.updated",function(){b.weightChart&&b.weightChart.destroy()}),b.$on("$destroy",function(){b.weightChart&&b.weightChart.destroy()}),b.$on("medly.user.loaded",function(c){j=c.thresholds;var e=f.patientMeasurementResource(d.id,"weight").query();e.$promise.then(function(c){c.length>0?(b.readings.weight=c,b.weightChartData(c),a.$broadcast("weightLoaded",!0)):a.$broadcast("weightLoaded",!1)})})}]),angular.module("medleyDashboardAngularApp").controller("PatientPulseReadingsCtrl",["$rootScope","$scope","$routeParams","$filter","ReadingGraphService","APIResources","$timeout","AnalyticsService","MEASUREMENT",function(a,b,c,d,e,f,g,h,i){var j;b.setDateDomain=function(){void 0!==b.components&&g(function(){b.min=b.components.xScales.PulseReading.domainMin(),b.max=b.components.xScales.PulseReading.domainMax()})},b.$on("pulseLoaded",function(a,b){b||$(".pulse-container").remove()}),b.pulseChartData=function(a){b.user.thresholds&&(j=b.user.thresholds);var c=_.findWhere(j,{measurement_type:"pulse",field:i}),d=c?c.lower:null,e=c?c.upper:null,f=(c?c.upper-c.lower:null,"bpm");b.normalPulse=d+"-"+e+" "+f,b.outRangeHighlight=function(a){return b.isOutsideRange=d>a||a>e,a};var g=function(){return h.displayedReadings(b.readings.pulse,b.min,b.max,i)};b.numReadings=function(){return h.totalNumReadings(g())},b.numOutRange=function(){return h.numOutsideRange(d,e,g())},b.average=function(){return h.average(g(),b.numReadings())};var k=b.readings.pulse,l=$(".omh-pulse-chart-container"),m="PulseReading",n={measures:{PulseReading:{valueKeyPath:i,units:"bpm",range:{min:d-40,max:e+40},seriesName:"Pulse",thresholds:{min:d,max:e},chart:{type:"line",pointSize:10.5,lineColor:"#4a90e2",pointFillColor:"#FFFFFF",pointStrokeColor:"#4a90e2",aboveThresholdPointFillColor:"#FFFFFF",aboveThresholdPointStrokeColor:"#e8ac4e",barColor:"#4a90e2",daysShownOnTimeline:{min:2,max:365}}}}};b.drawOmhChart(k,l,m,n)},b.drawOmhChart=function(a,c,d,e){b.pulseChart=new OMHWebVisualizations.Chart(a,c,d,e),b.components=b.pulseChart.getComponents(),b.pulseChart.onXScaleUpdate(b.setDateDomain),b.pulseChart.renderTo(c.find("svg.omh-pulse-chart")[0])},b.$on("medly.user.loaded",function(){b.pulseChart&&b.pulseChart.destroy()}),b.$on("medly.event.user.updated",function(){b.pulseChart&&b.pulseChart.destroy()}),b.$on("$destroy",function(){b.pulseChart&&b.pulseChart.destroy()}),b.$on("medly.user.loaded",function(d){j=d.thresholds;var e=f.patientMeasurementResource(c.id,"pulse").query();e.$promise.then(function(c){c.length>0?(b.readings.pulse=c,b.pulseChartData(c),a.$broadcast("pulseLoaded",!0)):a.$broadcast("pulseLoaded",!1)})})}]),angular.module("medleyDashboardAngularApp").controller("PatientLabResultCtrl",["$scope","$rootScope","$routeParams","$modal","PatientLabResultService","UserSession",function(a,b,c,d,e,f){a.canAddLabResults=f.can("addLabResults"),a.canEditLabResults=f.can("editLabResults"),a.labsPattern=/^[0-9]+(\.[0-9]{1,2})?$/,a.requestPending=!1,a.maxDate=new Date,a.filterForm={searchText:"",currentPage:1,totalPages:0,itemsPerPage:10},a.pageChanged=function(b){a.refresh()},a.refresh=function(){e.getLabResults(c.id,{page:a.filterForm.currentPage,limit:48}).then(function(b){a.labResults=b,a.updateDate=b.meta.last_updated_at,a.filterForm.totalPages=b.meta.total_pages*a.filterForm.itemsPerPage})},a["delete"]=function(b){a.requestPending=!0,a.selectedLabEntry=b,a.selectedLabEntry["delete"]().then(function(){a.requestPending=!1,a.refresh()})},a.openLabEntryModal=function(c){a.selectedLabEntry=c?c:e.createNew(),b.modalInstance=d.open({controller:"PatientLabResultEditCtrl",templateUrl:"views/users/add/modal-lab-add.html",scope:a}),b.modalInstance.opened.then(function(){b.$broadcast("medly.modal.opened")}),b.modalInstance.result.then(function(){},function(a){b.$broadcast("medly.modal.closed")})},a.refresh()}]),angular.module("medleyDashboardAngularApp").controller("PatientLabResultEditCtrl",["$scope","$rootScope",function(a,b){a.hasVerification=!0,a.calculateEgfr=function(){var b="M"===a.user.sex?1:.742,c=a.selectedLabEntry.get("Creatinine").value,d=a.user.age,e=a.user.diseases.includes("CKD");if(e&&c&&b&&d>1){var f=175*Math.pow(.0113*c,-1.154)*Math.pow(d,-.203)*b;a.selectedLabEntry.get("Kidney Function").value=Math.round(f)}},a["delete"]=function(){a.selectedLabEntry["delete"]().then(function(){a.refresh(),a.$dismiss()})},a.save=function(){a.requestPending=!0,a.selectedLabEntry.update().then(function(){a.refresh(),a.$dismiss()})},a.cancel=function(){a.refresh(),a.$dismiss()}}]),angular.module("medleyDashboardAngularApp").controller("PatientProfileCtrl",["$scope","$filter","$modal","$route","$rootScope","UserSession","APIResources","$routeParams","EmailAlerts","MEASUREMENT",function(a,b,c,d,e,f,g,h,i,j){a.canEditPatientInfo=f.can("editPatientInfo"),a.canEditPatientContact=f.can("editPatientContact"),a.canEditPatientStudy=f.can("editPatientStudy"),a.canEditPatientGoals=f.can("editPatientGoals"),a.canAddPatient=f.can("addPatient");var k=[],l=function(){a.isPatient&&(k=[],a.user.determinant_set.bp_email&&k.push(i.BLOOD_PRESSURE),a.user.determinant_set.symptoms_email&&k.push(i.SYMPTOMS),a.user.determinant_set.meds_email&&k.push(i.MEDICATIONS),a.user.determinant_set.lab_email&&k.push(i.LAB_RESULTS),a.patientEmailAlerts=k)};a.$on("medly.event.user.updated",l);var m=function(b,c){if(a.user.thresholds){var d=_.findWhere(a.user.thresholds,{measurement_type:b,field:c});if(d)return d;var e={measurement_type:b,field:c};return a.user.thresholds.push(e),e}},n=function(){a.goals={weight:m("weight",j),systolic:m("blood_pressure","systolic"),diastolic:m("blood_pressure","diastolic"),systolic_overall:m("blood_pressure","systolic_overall"),diastolic_overall:m("blood_pressure","diastolic_overall"),pulse:m("pulse",j),phosphate:m("blood","phosphate"),potassium:m("blood","potassium"),hemoglobin:m("blood","hemoglobin"),bnp:m("blood","bnp"),sodium:m("blood","sodium"),creatinine:m("blood","creatinine"),blood_glucose:m("blood_glucose",j)}};a.openEditModal=function(b){a.editSection=b,e.modalInstance=c.open({controller:"EditUserCtrl",scope:a,templateUrl:"views/users/edit/modal-"+b+"-edit.html"}),e.modalInstance.opened.then(function(){e.$broadcast("medly.modal.opened")}),e.modalInstance.result.then(function(){},function(a){e.$broadcast("medly.modal.closed")})},a.toggleState=function(){a.requestPending=!0,g.userResource(d.current.userType,d.current.params.id)["delete"]().$promise.then(function(b){a.userRefresh(),a.requestPending=!1})};var o=function(){a.isPatient&&(n(),a.$on("medly.user.loaded",n)),l()};o()}]),angular.module("medleyDashboardAngularApp").controller("PatientHistoriesCtrl",["$scope","$routeParams","APIResources",function(a,b,c){a.showSpinner=!0,a.filterForm={currentPage:1,totalPages:0,itemsPerPage:10},a.loadHistories=function(){if(a.canViewHistory){var d=c.patientHistoryListResource(b.id).query({page:a.filterForm.currentPage});d.$promise.then(function(b){a.showSpinner=!1,a.histories=b,a.filterForm.totalPages=b.meta.total_pages*a.filterForm.itemsPerPage},function(b){console.log("Error",b),a.showSpinner=!1})}},a.pageChanged=function(){a.loadHistories()},a.histories=[],a.loadHistories(),a.$on("medly.event.user.updated",function(){a.loadHistories()}),a.$on("medly.user.loaded",function(){a.loadHistories()})}]),angular.module("medleyDashboardAngularApp").controller("SubNavCtrl",["$scope","UserSession","$location",function(a,b,c){function d(a){return a.href.indexOf(c.path().substring(0,8))>=0}function e(){var a={superadmin:"admin",admin:"admin",caregiver:"clinician",patient:"patient"}[b.role()],c="#/"+a+"/profile";return"patient"===b.role()&&(c+="/profile"),c}var f=[{title:"Alerts",href:"#/alerts-centre",allowed:["superadmin","admin","caregiver"]},{title:"Administrators",href:"#/adminlist",allowed:["superadmin"]},{title:"Caregivers",href:"#/clinicianlist",allowed:["superadmin","admin"]},{title:"Patients",href:"#/patient",allowed:["superadmin","admin","caregiver"]},{title:"Clinics",href:"#/clinics",allowed:["superadmin","admin"]}];this.updateLinks=function(){a.navLinks=f.filter(function(a){return!a.allowed||a.allowed.indexOf(b.role())>=0}).map(function(a){var b=a;return d(b)&&(b=Object.create(a),b.active=!0),b})},this.updateLinks(),a.logOut=function(){b.setUser(null),c.path("/login")};var g=function(){a.username=b.user().username,a.profileLink=e()};g()}]),angular.module("medleyDashboardAngularApp").controller("AboutCtrl",["$scope","ENV",function(a,b){a.version=b.version,a.revision=b.revision,a.environment=b.name,console.log(a.environment+" environment")}]),angular.module("medleyDashboardAngularApp").controller("ClinicListCtrl",["$scope","$route","$modal","ClinicListService","$rootScope","UserSession","APIResources",function(a,b,c,d,e,f,g){a.userType=b.current.userType,a.showSpinner=!0;var h={name:"name ASC"};a.filterForm={searchText:"",sort:h.name,currentPage:1,totalPages:0,itemsPerPage:10},a.onSuccessQuery=function(b){a.clinics=b,a.filterForm.totalPages=b.meta.total_pages*a.filterForm.itemsPerPage,a.showSpinner=!1},a.onError=function(b){a.errorMessage=b.error},a.filter=function(){d.get(a.userType,{search:a.filterForm.searchText,sort:a.filterForm.sort,page:a.filterForm.currentPage},a.onSuccessQuery,a.onError)},a.pageChanged=function(b){a.filter()};var i=function(){e.modalInstance.opened.then(function(){e.$broadcast("medly.modal.opened")}),e.modalInstance.result.then(function(){},function(a){e.$broadcast("medly.modal.closed")})};a.openAddModal=function(){e.modalInstance=c.open({controller:"AddClinicCtrl",templateUrl:"views/users/add/modal-"+a.userType+"-add.html"}),i()};var j=function(){a.disableResetButton=!1,a.filter()};j(),e.$on("medly.event.clinic.added",a.filter)}]),angular.module("medleyDashboardAngularApp").directive("wizardModal",function(){return{restrict:"E",transclude:!0,scope:{wizardTitle:"@",wizardClass:"@",wizardError:"=",wizardSubmitDisabled:"=",wizardSubmit:"&",wizardCancel:"&",wizardDelete:"&",wizardHasDelete:"=",wizardId:"=",wizardHasVerification:"=",form:"="},templateUrl:"views/directives/wizard-modal-template.html",link:function(a,b,c){var d=b.find(".wizard-steps"),e=(b.find(".modal-footer > .wizard-next"),b.find(".modal-footer > .wizard-verify"),b.find(".modal-footer > .wizard-modify"),b.find(".modal-footer > .wizard-previous"),b.find(".modal-footer > .wizard-done"),b.find("wizard-modal-step"));e.each(function(a,b){var c=$(b);d.append('<div class="wstep"><span class="txt">'+c.attr("wizard-step-title")+'</span><div class="donut"><i class="glyphicon glyphicon-ok"></i><span>'+(a+1)+"</span></div></div>"),c.prepend("<h4>"+c.attr("wizard-form-title")+"</h4>")}),a.currentStep=0,a.maxStep=e.size()-1,a.$watch("currentStep",function(a){$("wizard-modal-step").each(function(b,c){b===a?$(c).show():$(c).hide()}),$(".wstep").each(function(b,c){a>b?($(c).addClass("done"),$(c).removeClass("current")):b===a?($(c).addClass("current"),$(c).removeClass("done")):($(c).removeClass("current"),$(c).removeClass("done"))})})}}}),angular.module("medleyDashboardAngularApp").directive("scrollOnClick",function(){return{restrict:"A",link:function(a,b,c){var d=c.href;b.on("click",function(a){var c;a.preventDefault(),c=d?$(d):b,$("body").animate({scrollTop:c.offset().top},"slow")})}}}),angular.module("medleyDashboardAngularApp").directive("rangeValidate",function(){return{restrict:"A",require:"ngModel",scope:{rangeMin:"@",rangeMax:"@"},link:function(a,b,c,d){$(b).on("keyup",function(){a.$apply(function(){var a=d.$viewValue;d.$setValidity("outOfRange",!a||!(isNaN(a)||c.rangeMin&&parseFloat(a)<parseFloat(c.rangeMin)||c.rangeMax&&parseFloat(a)>parseFloat(c.rangeMax)))})})}}}),angular.module("medleyDashboardAngularApp").directive("selectWithFreeTextOption",function(){return{restrict:"E",scope:{title:"@",optionsArray:"=",valueModel:"=",otherModel:"=",required:"="},templateUrl:"views/directives/select-with-free-text-option-template.html"}}),angular.module("medleyDashboardAngularApp").directive("joinValues",function(){return{restrict:"E",scope:{ngModel:"=",properties:"="},link:function(a,b){if(a.properties){var c=[];a.properties.forEach(function(b){a.ngModel[b]&&("duration"===b?c.push(_.isBoolean(a.ngModel[b])?b:a.ngModel[b]+" day(s)"):"tapered"===b?c.push(" - Starting dose, tapered as prescribed."):c.push(_.isBoolean(a.ngModel[b])?b:a.ngModel[b]))}),b.append(c.join(" "))}}}}),angular.module("medleyDashboardAngularApp").directive("ngReallyClick",[function(){return{restrict:"A",link:function(a,b,c){b.bind("click",function(){var b=c.ngReallyMessage;b&&confirm(b)&&a.$apply(c.ngReallyClick)})}}}]);