31. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 12/4/2017 8:32:30 AM Central Standard Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

31.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_0.zip\WebResources ftp_VeteranJScriptmainjs59ECC3B8-0DCC-E411-80CB-00155DD08303 Sat Jan 21 18:28:48 2017 UTC
2 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_0.zip\WebResources ftp_VeteranJScriptmainjs59ECC3B8-0DCC-E411-80CB-00155DD08303 Thu Nov 30 17:17:59 2017 UTC

31.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 3 2806
Changed 2 4
Inserted 0 0
Removed 0 0

31.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

31.4 Active regular expressions

No regular expressions were active.

31.5 Comparison detail

  1   //global v ariable.
  2   var _notPr od = true;
  3   var _ICN =  "";
  4   var _retri evedSettin gs = null;
  5   var PCMMGr idMembers  = [];
  6   var finish edGettingP rimaryCare Providers  = false;
  7   var finish edGettingM HTC = fals e;
  8   //******** ********** ********** ********** **
  9   //Set new  PCMM Enabl ed flag to  True as d efault, th en read fr om 'Active  Settings'
  10   var pcmm_E nabled = t rue;
  11   //******** ********** ********** ********** **
  12  
  13   function f orm_onLoad () {
  14           va r thisOrgU rl = Xrm.P age.contex t.getClien tUrl();
  15       _notPr od = thisO rgUrl.inde xOf("ftp.d ev") > 1 | | thisOrgU rl.indexOf ("INTFTP")  > 1 || th isOrgUrl.i ndexOf("QA FTP") > 1  || thisOrg Url.indexO f("PREFTP" ) > 1;
  16           /*  
  17       //**** ********** ********** ********** ******
  18       //Get  PCMM Setti ng value f rom Active  Settings
  19       var pc mm_actives ettings =  pcmm_retri evePCMMSet ting();
  20       for (i  = 0; i <  pcmm_activ esettings. d.results. length; i+ +) {
  21           if  (pcmm_act ivesetting s.d.result s[i].ftp_I sPCMMEnabl ed != null ) { pcmm_E nabled = p cmm_active settings.d .results[i ].ftp_IsPC MMEnabled;  }
  22           br eak;
  23       }
  24       if (pc mm_Enabled  == false)  {
  25           Xr m.Page.get Control("W ebResource _VeteranPA CTTeam").s etVisible( false);
  26           Xr m.Page.get Control("f tp_pactid" ).setVisib le(false);
  27           Xr m.Page.get Attribute( "ftp_pacti d").setSub mitMode("a lways");
  28           Xr m.Page.get Control("f tp_primary careprovid er").setVi sible(fals e);
  29           Xr m.Page.get Attribute( "ftp_prima rycareprov ider").set SubmitMode ("always") ;
  30       }
  31       //**** ********** ********** ********** ******
  32  
  33       //**** ********** *
  34       if (pc mm_Enabled  == false)  {
  35           va r pcmm_ale rtText = " The Patien t Care Man agement Mo dule (PCMM ) is down  at this ti me so PACT  Team data  is not av ailable.";
  36           Xr m.Page.ui. setFormNot ification( pcmm_alert Text, "INF O", "noPCM M");
  37       }
  38       //**** ********** * */
  39  
  40       var qu eryStringP arameters  = Xrm.Page .context.g etQueryStr ingParamet ers();
  41       _ICN =  (queryStr ingParamet ers.hasOwn Property(" ICN_0")) ?  queryStri ngParamete rs.ICN_0 :  "";
  42       
  43           va r skipWebS erviceCall s = (query StringPara meters.has OwnPropert y("skipWeb ServiceCal ls_0")) ?  queryStrin gParameter s.skipWebS erviceCall s_0 : fals e;
  44       if (sk ipWebServi ceCalls) {
  45           op enSensitiv eVeteranWR (
  46                             "NEWVE TERAN",
  47                             false,  //assume  not sensit ive, so th at we can  continue w ith intera ction in U SD
  48                             Xrm.Pa ge.getAttr ibute("ftp _homephone ").getValu e(),
  49                             Xrm.Pa ge.getAttr ibute("ftp _workphone ").getValu e(),
  50                             Xrm.Pa ge.getAttr ibute("ftp _mobilepho ne").getVa lue()
  51                    );
  52           re turn;
  53       }
  54  
  55       SetVis n();
  56       unempl oyableVisi bility();
  57       maskPh ones();
  58       setSub mitModeOnS omeAttribu tes();
  59       unatte ndedMVISea rchFromVet eran(_ICN) ;
  60   }
  61  
  62   function h ideBusines sProcessFl ow() {
  63       var fl ow = Xrm.P age.ui.pro cess;
  64       if (!! flow && fl ow.getVisi ble())
  65           fl ow.setVisi ble(false) ;
  66   }
  67  
  68   function m askPhones( ) {
  69       var ph oneFields  = [
  70                    "ftp _mobilepho ne",
  71                    "ftp _mobilepho ne",
  72                    "ftp _workphone "
  73       ];
  74  
  75       for (v ar i = 0,  l = phoneF ields.leng th; i < l;  i++) {
  76           va r attr = X rm.Page.ge tAttribute (phoneFiel ds[i]);
  77           if  (!!attr)  attr.fireO nChange();
  78       }
  79   }
  80  
  81   function M ask(field,  format) {
  82       //depc recated in  favor of  formatTele phoneNumbe r
  83       return ;
  84       var oC trl = Xrm. Page.getCo ntrol(fiel d);
  85       if (!! oCtrl && o Ctrl.getCo ntrolType( ) == 'stan dard') {
  86           oC trl.setFoc us();
  87           $( "#" + fiel d + "_i"). mask(forma t);
  88           oC trl.blur() ;
  89       }
  90   }
  91  
  92   function f ormatTelep honeNumber (pContext)  {
  93       if (!! pContext)  {
  94           va r changedA ttribute =  pContext. getEventSo urce();
  95           if  (!!change dAttribute ) {
  96                var valu e = change dAttribute .getValue( );
  97                if (!!va lue) {
  98                    var  tempValue  = value.to String().r eplace(/[^ 0-9A-Za-z] /g, "").to UpperCase( );
  99                    if ( tempValue. substr(0,  1) == "1")  tempValue  = tempVal ue.substr( 1, 99);
  100                    var  formattedV alue = (te mpValue.le ngth >= 10 ) ? "(" +  tempValue. substr(0,  3) + ") "  + tempValu e.substr(3 , 3) + "-"  + tempVal ue.substr( 6, 4) : te mpValue.su bstr(0, 3)  + "-" + t empValue.s ubstr(3, 4 );
  101                    chan gedAttribu te.setValu e(formatte dValue);
  102                }
  103           }
  104       }
  105   }
  106  
  107   function u nemployabl eVisibilit y() {
  108       Xrm.Pa ge.getCont rol("ftp_u nemployabl e").setVis ible(Xrm.P age.getAtt ribute("ft p_scpercen t").getVal ue() !== n ull);
  109   }
  110  
  111   function s etSubmitMo deOnSomeAt tributes()  {
  112       var fi eldsToSave  = [
  113           "f irstname",
  114           "m iddlename" ,
  115           "l astname",
  116           "f tp_edipi",
  117           "g overnmenti d",
  118           "f tp_dateofb irth",
  119           "f tp_nextofk in",
  120           "f tp_remarks ",
  121           "f tp_primary eligibilit ycode",
  122           "f tp_patient type",
  123           "f tp_service connected" ,
  124           "f tp_scperce nt",
  125           "f tp_unemplo yable",
  126           "f tp_dentali nj",
  127           "f tp_medicat ioncopayme ntexemptio nstatus",
  128           "f tp_copayme ntexemptio nstatus",
  129           "f tp_isinsur ance",
  130           "f tp_mobilep hone",
  131           "f tp_homepho ne",
  132           "f tp_workpho ne"
  133       ];
  134       for (v ar i = 0,  l = fields ToSave.len gth; i < l ; i++) {
  135           va r field =  Xrm.Page.g etAttribut e(fieldsTo Save[i]);
  136           if  (!!field)  field.set SubmitMode ("always") ;
  137       }
  138   }
  139  
  140   function S etVisn() {
  141       ////de bugger;
  142       var fa cilityLook upValue =  Xrm.Page.g etAttribut e("ftp_fac ilityid"). getValue() ;
  143       if (!! facilityLo okupValue)  {
  144           va r columnse t = "ftp_v isnid";
  145           SD K.REST.ret rieveRecor d(
  146                facility LookupValu e[0].id,
  147                "ftp_fac ility",
  148                columnse t,
  149                null,
  150                function  (retrieve dRecord) {
  151                    if ( !!retrieve dRecord &&  !!retriev edRecord.f tp_visnid)  {
  152                         Xrm.Page.g etAttribut e("ftp_vis n").setVal ue(retriev edRecord.f tp_visnid. Name);
  153                         Xrm.Page.g etAttribut e("ftp_vis n").setSub mitMode("a lways");
  154                    }
  155                },
  156                errorHan dler
  157           );
  158       }
  159   }
  160  
  161   function u nattendedM VISearchFr omVeteran( pICN) {
  162       if (!! pICN) {
  163                    //** *****Call  function i n Populate PreferredF acility sc ript****** *
  164                    /*Mo ve inside  performExt ernalWebSe rviceCalls () after r etrieving  Active Set tings*/
  165                    //Ge tFacilityF romService (pICN);
  166                    //** ********** ********** ********** ********** ********** ********** *
  167           pe rformExter nalWebServ iceCalls(p ICN);         
  168       } else  {
  169           // perform MV I search t o get ICN,  then call  performEx ternalWebS erviceCall s() with r etrieved I CN.
  170           va r queryStr ing = "$se lect=*&$fi lter=";
  171           va r firstnam e = Xrm.Pa ge.getAttr ibute("fir stname").g etValue();
  172           va r lastname  = Xrm.Pag e.getAttri bute("last name").get Value();
  173  
  174           va r dobdate  = Xrm.Page .getAttrib ute("ftp_d ateofbirth ").getValu e();
  175           va r dobstrin g = !!dobd ate ? dobd ate : "";
  176  
  177           va r ssn = Xr m.Page.get Attribute( "governmen tid").getV alue();
  178           if  (!!ssn) s sn = ssn.r eplace(/-/ g, "");
  179  
  180           qu eryString  += buildQu eryFilter( "crme_Last Name", las tname, fal se); //ass uming last name will  never be b lank
  181           if  (!!firstn ame)
  182                queryStr ing += bui ldQueryFil ter("crme_ FirstName" , firstnam e, true);
  183           if  (!!ssn)
  184                queryStr ing += bui ldQueryFil ter("crme_ SSN", ssn,  true);
  185           if  (!!dobstr ing)
  186                queryStr ing += " a nd crme_DO BString eq  '" + dobs tring + "' ";
  187           qu eryString  += buildQu eryFilter( "crme_Sear chType", ' SearchByFi lter', tru e);
  188           // set search  type as a ttended (f or now)
  189           qu eryString  += " and c rme_IsAtte nded eq tr ue";
  190  
  191  
  192           // queryStrin g = encode URICompone nt(querySt ring);
  193           va r retrieve dPerson =  null;
  194           va r MVIBadRe sultsText  = "Invalid  results f rom MVI";
  195           SD K.REST.ret rieveMulti pleRecords (
  196                             "crme_ person",
  197                             queryS tring,
  198                             functi on (retrie vedRecords ) {
  199                                 // debugger;
  200                                 if  (typeof r etrievedRe cords != " undefined"  && !!retr ievedRecor ds && retr ievedRecor ds.length  == 1) {
  201                                      retrieve dPerson =  retrievedR ecords[0];
  202                                 }
  203                                 el se {
  204                                      MVIBadRe sultsText  = "Could n ot determi ne veteran  ICN from  " + retrie vedRecords .length +  " MVI sear ch results .";
  205                                 }
  206                             },
  207                             errorH andler,
  208                             functi on () {
  209                                 // debugger;
  210                                 if  (!!retrie vedPerson)  {
  211                                      // check  for excep tions 1st
  212                                      if ((ret rievedPers on.crme_Ex ceptionOcc ured || !! retrievedP erson.crme _Exception Message)
  213                                                       ||  (!!retrie vedPerson. crme_Retur nMessage & & retrieve dPerson.cr me_ReturnM essage ==  "An unexpe cted error  occured d uring the  MVI search . Please t ry again o r contact  your syste m administ rator if t he problem  persists. ")
  214                                                       ||  (!!retrie vedPerson. crme_Retur nMessage & & retrieve dPerson.cr me_ReturnM essage ==  "Unknown K ey Identif ier| Unkno wn Key Ide ntifier")
  215                                                       ||  (!!retrie vedPerson. crme_Retur nMessage & & retrieve dPerson.cr me_ReturnM essage ==  "Your sear ch in MVI  did not fi nd any rec ords match ing the se arch crite ria.")) {
  216                                          var  messageToS how =
  217                                                                !!re trievedPer son.crme_E xceptionMe ssage ? re trievedPer son.crme_E xceptionMe ssage :
  218                                                                !!re trievedPer son.crme_R eturnMessa ge ? retri evedPerson .crme_Retu rnMessage  :
  219                                                                "Unk nown error ";
  220                                          Xrm. Utility.al ertDialog(
  221                                                                "Err or perform ing MVI se arch: \n\n " + messag eToShow +  "\n\nCould  not deter mine veter an sensiti vity.\nThi s session  will now c lose.",
  222                                                                func tion () {
  223                                                                     finishedGe ttingPrima ryCareProv iders = tr ue;
  224                                                                     finishedGe ttingMHTC  = true;
  225                                                                     window.ope n("http:// event/?eve ntname=End SessionOnB adESRCall" );
  226                                                                }
  227                                                       );
  228                                      }
  229                                      else {
  230                                          var  patientMvi Identifier  = retriev edPerson.c rme_Patien tMviIdenti fier == nu ll ? "" :  retrievedP erson.crme _PatientMv iIdentifie r;
  231                                          if ( patientMvi Identifier  != "") {
  232                                               var idpart s = patien tMviIdenti fier.split ("^");
  233  
  234                                               if (idpart s.length >  0) {
  235                                                   var IC N = idpart s[0];
  236                                                   _ICN =  ICN;
  237  
  238                                                   //DO W HATEVER YO U ARE GOIN G TO DO WI TH THE ICN  HERE
  239                                                                         //**** ******Call  function  in Populat ePreferred Facility s cript***** **
  240                                                   /*Move  inside pe rformExter nalWebServ iceCalls()  after ret rieving Ac tive Setti ngs*/
  241                                                                         //GetF acilityFro mService(p ICN);
  242                                                   //**** ********** ********** ********** ********** ********** ********** **
  243                                                   perfor mExternalW ebServiceC alls(ICN);                                                 
  244                                               }
  245                                          }
  246                                      }
  247                                 }
  248                                 el se {
  249                                      Xrm.Util ity.alertD ialog(
  250                                                       MV IBadResult sText + "\ n\nCould n ot determi ne veteran  sensitivi ty.\nThis  session wi ll now clo se.",
  251                                                       fu nction ()  {
  252                                                            Xrm.Page .ui.setFor mNotificat ion(MVIBad ResultsTex t, "INFO",  "MVIBadRe sultsMessa ge");
  253                                                            finished GettingPri maryCarePr oviders =  true;
  254                                                            finished GettingMHT C = true;
  255                                                            window.o pen("http: //event/?e ventname=E ndSessionO nBadESRCal l");
  256                                                       }
  257                                               );
  258                                 }
  259                             }
  260                    );
  261       }
  262   }
  263  
  264   function p erformExte rnalWebSer viceCalls( pICN) {
  265       try {
  266           va r fType =  Xrm.Page.u i.getFormT ype();
  267           if  (!!pICN & & !!fType  && fType >  1) {
  268                //retrie ve Active  Settings r ecord to g et URLs, T HEN perfor m external  web servi ce calls
  269                var quer yString =  "$select=* &$filter=m cs_name eq  'Active S ettings'";
  270                var retr ievedSetti ngs = null ;
  271                SDK.REST .retrieveM ultipleRec ords(
  272                    "mcs _setting",
  273                    quer yString,
  274                    func tion (retr ievedRecor ds) {
  275                         if (typeof  retrieved Records !=  "undefine d" && !!re trievedRec ords && re trievedRec ords.lengt h == 1) re trievedSet tings = re trievedRec ords[0];
  276                    },
  277                    erro rHandler,
  278                    func tion () {
  279                         if (!!retr ievedSetti ngs) {
  280                                                       _r etrievedSe ttings = r etrievedSe ttings;
  281                             //perf orm ESR we b service  call for d emographic s and sens itivity fl ag
  282                             //perf orm Patien t Summary  web servic e call for  PCMM
  283  
  284                             if (!( retrievedS ettings.ha sOwnProper ty("ftp_DA CURL")) ||  !retrieve dSettings. ftp_DACURL ) {
  285                                 al ert("Could  not find  DAC URL");
  286                                 re turn;
  287                             }
  288                                                       
  289                                                       wr iteToConso le("got Ac tive Setti ngs record .");
  290                             //ESR
  291                             if (re trievedSet tings.hasO wnProperty ("ftp_ESRA PIURL") &&  !!retriev edSettings .ftp_ESRAP IURL) {
  292                                                                var  baseESRUrl  = retriev edSettings .ftp_DACUR L + retrie vedSetting s.ftp_ESRA PIURL;
  293                                                                //** *****Call  function i n Populate PreferredF acility sc ript****** *
  294                                                                GetF acilityFro mService(p ICN, baseE SRUrl);
  295                                                                //** ********** ********** ********** ********** ********** ********** *
  296                                                                
  297                                 va r request  = baseESRU rl + "0000 00" + pICN  + "000000 ";
  298                                 va r query =  new XMLHtt pRequest() ;
  299                                 qu ery.open(' GET', requ est, true) ;
  300                                 qu ery.onread ystatechan ge = funct ion () {
  301                                      if (quer y.readySta te == 4 &&  query.sta tus == 200 ) {
  302                                          if ( !query.res ponseXML)  return;
  303                                          var  xml = quer y.response XML;
  304                                          //If  no result s found- c onsider th e vet to b e SENSITIV E
  305                                          if ( xml.childN odes.lengt h > 0 && x ml.childNo des[0].chi ldNodes.le ngth === 0 ) {
  306                                               //openSens itiveVeter anWR(pICN,  true);
  307                                                                                           openESRweb resource(p ICN, true,  false);
  308                                               return;
  309                                          }
  310                                          var  dem = $(xm l).find('d emographic s');
  311                                                                                  writeToC onsole("re trieved de mographics  informati on from ES R");
  312                                          var  home = "",
  313                                          work  = "",
  314                                          mobi le = "";
  315                                          if ( !!dem && d em.length  > 0) {
  316                                                                                           //Phones D rill down  demographi cs>phones> phone
  317                                               telephones  = $(dem). find('phon es');
  318                                               if (teleph ones.lengt h > 0) {
  319                                                   phones  = $(telep hones).fin d('phone') ;
  320                                                   if (ph ones.lengt h > 0) {
  321                                                       $. each(phone s, functio n () {
  322                                                            t = $(th is).find(' type')[0]. textConten t;
  323                                                            num = $( this).find ('phoneNum ber')[0].t extContent ;
  324                                                            if (t ==  'Home') {
  325                                                                home  = num;
  326                                                            }
  327                                                            if (t ==  'Business ') {
  328                                                                work  = num;
  329                                                            }
  330                                                            if (t ==  'Mobile')  {
  331                                                                mobi le = num;
  332                                                            }
  333                                                       }) ;
  334                                                   }
  335                                               }
  336                                          }
  337                                          Xrm. Page.getAt tribute("f tp_homepho ne").setVa lue(home);
  338                                          Xrm. Page.getAt tribute("f tp_homepho ne").setSu bmitMode(' always');
  339                                          Xrm. Page.getAt tribute("f tp_workpho ne").setVa lue(work);
  340                                          Xrm. Page.getAt tribute("f tp_workpho ne").setSu bmitMode(' always');
  341                                          Xrm. Page.getAt tribute("f tp_mobilep hone").set Value(mobi le);
  342                                          Xrm. Page.getAt tribute("f tp_mobilep hone").set SubmitMode ('always') ;
  343  
  344                                          //If  they are  a veteran-  pull that  return
  345                                          var  veteran =  ($(xml).fi nd('vetera n').length  > 0 && $( xml).find( 'veteran') [0].textCo ntent ===  "true");
  346                                          Xrm. Page.getAt tribute("f tp_patient type").set Value(vete ran ? "vet eran" : "N on-Veteran ");
  347                                          Xrm. Page.getAt tribute("f tp_patient type").set SubmitMode ('always') ;
  348  
  349                                          var  disability  = $(xml). find('rate dDisabilit y');
  350                                          var  rDisabilit y = (disab ility.leng th > 0) ?  $(xml).fin d('ratedDi sability') [0].textCo ntent : nu ll;
  351  
  352                                          var  eligibilit yNode = $( xml).find( 'primaryEl igibility' );
  353                                          var  eligibilit y = (eligi bilityNode .length >  0) ? $(eli gibilityNo de).find(' type')[0]. textConten t : null;
  354                                          Xrm. Page.getAt tribute("f tp_primary eligibilit ycode").se tValue(eli gibility);
  355                                          Xrm. Page.getAt tribute("f tp_primary eligibilit ycode").se tSubmitMod e('always' );
  356  
  357                                          var  unemployab leNode = $ (xml).find ('unemploy able');
  358                                          var  unemployab le = (unem ployableNo de.length  > 0) ? une mployableN ode[0].tex tContent :  null;
  359  
  360                                          if ( unemployab le == "tru e") { unem ployable =  "Yes"; }  else { une mployable  = "No"; }
  361                                          Xrm. Page.getAt tribute("f tp_unemplo yable").se tValue(une mployable) ;
  362                                          Xrm. Page.getAt tribute("f tp_unemplo yable").se tSubmitMod e('always' );
  363  
  364  
  365                                          var  svcCINode  = $(xml).f ind('servi ceConnecte dIndicator ');
  366                                          var  svcCI = sv cCINode.le ngth > 0 ?  $(xml).fi nd('servic eConnected Indicator' )[0].textC ontent : " ";
  367                                          Xrm. Page.getAt tribute("f tp_service connected" ).setValue (svcCI ==  "true");
  368                                          Xrm. Page.getAt tribute("f tp_service connected" ).setSubmi tMode('alw ays');
  369  
  370                                          var  percentage  = (svcCI  == "true"  && $(xml). find('serv iceConnect edPercenta ge').lengt h > 0) ? $ (xml).find ('serviceC onnectedPe rcentage') [0].textCo ntent : nu ll;
  371                                          if ( !!percenta ge) {
  372                                               Xrm.Page.g etAttribut e("ftp_scp ercent").s etValue(pe rcentage);
  373                                               Xrm.Page.g etAttribut e("ftp_scp ercent").s etSubmitMo de('always ');
  374                                          }
  375                                          var  sensitivit yFlag = ($ (xml).find ('sensityF lag').leng th > 0) ?  $(xml).fin d('sensity Flag')[0]. textConten t : null;
  376                                                                                  writeToC onsole("ve teran sens itivity: "  + sensiti vityFlag);
  377                                          Xrm. Page.getAt tribute("f tp_sensiti veveteran" ).setValue (sensitivi tyFlag ==  "true");
  378                                          Xrm. Page.getAt tribute("f tp_sensiti veveteran" ).setSubmi tMode('alw ays');
  379                                                                                  
  380                                                                                  //determ ine if vet eran is al ive
  381                                                                                  var deat hInfoNode  = $(xml).f ind("death Recond");  //the deat hRecond no de contain s data suc h as death Date, data Source, fa cilityRece ived, deat hLastModif ied, death ReportDate
  382                                                                                  var isDe ceased = d eathInfoNo de.length  > 0;
  383                                                                                  var deat hReportDat eString =  ($(xml).fi nd("deathR eportDate" ).length >  0) ? $(xm l).find("d eathReport Date")[0]. text : nul l;
  384                                                                                  var deat hReportDat e = null;
  385                                                                                  if(!!dea thReportDa teString){
  386                                                                                           var dateTi meSplit =  deathRepor tDateStrin g.split("T ");
  387                                                                                           var datePa rts = date TimeSplit[ 0].split(" -");
  388                                                                                           var timeZo neOffset =  dateTimeS plit[1].sp lit("-")[1 ]; //e.g.  05:00
  389                                                                                           var timeZo neOffsetPa rts = time ZoneOffset .split(":" );
  390                                                                                           var timePa rts = date TimeSplit[ 1].split(" -")[0].spl it(".")[0] .split(":" );
  391                                                                                           var utcDea thDate = n ew Date(Da te.UTC(par seInt(date Parts[0],  10), parse Int(datePa rts[1], 10 )-1, parse Int(datePa rts[2], 10 ), parseIn t(timePart s[0], 10)  + parseInt (timeZoneO ffsetParts [0], 10),  parseInt(t imeParts[1 ], 10) + p arseInt(ti meZoneOffs etParts[1] , 10), par seInt(time Parts[2],  10)));
  392                                                                                           deathRepor tDate = ut cDeathDate ;                                                                                
  393                                                                                  }
  394  
  395                                          var  hasInsuran ce = $(xml ).find('in suranceLis t').length  > 0;
  396                                          Xrm. Page.getAt tribute("f tp_isinsur ance").set Value(hasI nsurance);
  397                                          Xrm. Page.getAt tribute("f tp_isinsur ance").set SubmitMode ('always') ;
  398  
  399                                          //ne xt of kin
  400                                          var  assoc = $( xml).find( 'associati on');
  401                                          if ( assoc.leng th > 0) {
  402                                               $.each(
  403                                                                                                   as soc,
  404                                                                                                   fu nction ()  {
  405                                                                                                        var cTyp e = ($(thi s).find('c ontactType ').length  > 0) ? $(t his).find( 'contactTy pe')[0].te xtContent  : "";
  406                                                                                                        if (cTyp e === "Pri mary Next  of Kin") {
  407                                                                                                            var  nok = ($(t his).find( 'givenName ').length  > 0) ? $(t his).find( 'givenName ')[0].text Content :  "";
  408                                                                                                            nok  = ($(this) .find('mid dleName'). length > 0 ) ? nok.tr im() + " "  + $(this) .find('mid dleName')[ 0].textCon tent : nok .trim();
  409                                                                                                            nok  = ($(this) .find('fam ilyName'). length > 0 ) ? nok.tr im() + " "  + $(this) .find('fam ilyName')[ 0].textCon tent : nok .trim();
  410                                                                                                            nok  = ($(this) .find('rel ationship' ).length >  0) ? nok. trim() + " , " + $(th is).find(' relationsh ip')[0].te xtContent  : nok.trim ();
  411                                                                                                            if ( !!nok) {
  412                                                                                                                 Xrm.Page.g etAttribut e("ftp_nex tofkin").s etValue(no k);
  413                                                                                                                 Xrm.Page.g etAttribut e("ftp_nex tofkin").s etSubmitMo de('always ');
  414                                                                                                            }
  415                                                                                                        }
  416                                                                                                   }
  417                                                                                           );
  418                                          }
  419                                          
  420                                                                                  //addres ses
  421                                          var  adds = $(x ml).find(' addresses' );
  422                                          if ( adds.lengt h > 0) {
  423                                               add = $(ad ds).find(' address');
  424                                               if (add.le ngth > 0)  {
  425                                                   $.each (
  426                                                       ad d,
  427                                                       fu nction ()  {
  428                                                            var aTyp e = $(this ).find('ad dressTypeC ode').leng th > 0 ? $ (this).fin d('address TypeCode') [0].textCo ntent : "" ;
  429                                                            switch ( aType) {
  430                                                                case  "Permanen t":
  431                                                                     var add1 =  ($(this). find('line 1').length  > 0) ? $( this).find ('line1')[ 0].textCon tent : nul l;
  432                                                                     if (!!add1 )
  433                                                                         Xrm.Pa ge.getAttr ibute("add ress1_line 1").setVal ue(add1);
  434                                                                     Xrm.Page.g etAttribut e("address 1_line1"). setSubmitM ode('alway s');
  435                                                                     var add2 =  ($(this). find('line 2').length  > 0) ? $( this).find ('line2')[ 0].textCon tent : nul l;
  436                                                                     if (!!add2 )
  437                                                                         Xrm.Pa ge.getAttr ibute("add ress1_line 2").setVal ue(add2);
  438                                                                     Xrm.Page.g etAttribut e("address 1_line2"). setSubmitM ode('alway s');
  439                                                                     var add3 =  ($(this). find('line 3').length  > 0) ? $( this).find ('line3')[ 0].textCon tent : nul l;
  440                                                                     if (!!add3 )
  441                                                                         Xrm.Pa ge.getAttr ibute("add ress1_line 3").setVal ue(add3);
  442                                                                     Xrm.Page.g etAttribut e("address 1_line3"). setSubmitM ode('alway s');
  443                                                                     var zip =  ($(this).f ind('zipCo de').lengt h > 0) ? $ (this).fin d('zipCode ')[0].text Content :  null;
  444                                                                     if (!!zip)
  445                                                                         Xrm.Pa ge.getAttr ibute("add ress1_post alcode").s etValue(zi p);
  446                                                                     Xrm.Page.g etAttribut e("address 1_postalco de").setSu bmitMode(' always');
  447                                                                     var state  = ($(this) .find('sta te').lengt h > 0) ? $ (this).fin d('state') [0].textCo ntent : nu ll;
  448                                                                     if (!!stat e)
  449                                                                         Xrm.Pa ge.getAttr ibute("add ress1_stat eorprovinc e").setVal ue(state);
  450                                                                     Xrm.Page.g etAttribut e("address 1_stateorp rovince"). setSubmitM ode('alway s');
  451                                                                     var city =  ($(this). find('city ').length  > 0) ? $(t his).find( 'city')[0] .textConte nt : null;
  452                                                                     if (!!city )
  453                                                                         Xrm.Pa ge.getAttr ibute("add ress1_city ").setValu e(city);
  454                                                                     Xrm.Page.g etAttribut e("address 1_city").s etSubmitMo de('always ');
  455                                                                     var countr y = ($(thi s).find('c ountry').l ength > 0)  ? $(this) .find('cou ntry')[0]. textConten t : null;
  456                                                                     if (!!coun try)
  457                                                                         Xrm.Pa ge.getAttr ibute("add ress1_coun try").setV alue(count ry);
  458                                                                     Xrm.Page.g etAttribut e("address 1_country" ).setSubmi tMode('alw ays');
  459                                                                     break;
  460                                                                case  "Temporar y":
  461                                                                     var addt1  = ($(this) .find('lin e1').lengt h > 0) ? $ (this).fin d('line1') [0].textCo ntent : nu ll;
  462                                                                     if (!!addt 1)
  463                                                                         Xrm.Pa ge.getAttr ibute("add ress2_line 1").setVal ue(addt1);
  464                                                                     Xrm.Page.g etAttribut e("address 2_line1"). setSubmitM ode('alway s');
  465                                                                     var addt2  = ($(this) .find('lin e2').lengt h > 0) ? $ (this).fin d('line2') [0].textCo ntent : nu ll;
  466                                                                     if (!!addt 2)
  467                                                                         Xrm.Pa ge.getAttr ibute("add ress2_line 2").setVal ue(addt2);
  468                                                                     Xrm.Page.g etAttribut e("address 2_line2"). setSubmitM ode('alway s');
  469                                                                     var addt3  = ($(this) .find('lin e3').lengt h > 0) ? $ (this).fin d('line3') [0].textCo ntent : nu ll;
  470                                                                     if (!!addt 3)
  471                                                                         Xrm.Pa ge.getAttr ibute("add ress2_line 3").setVal ue(addt3);
  472                                                                     Xrm.Page.g etAttribut e("address 2_line3"). setSubmitM ode('alway s');
  473                                                                     var tzip =  ($(this). find('zipC ode').leng th > 0) ?  $(this).fi nd('zipCod e')[0].tex tContent :  null;
  474                                                                     if (!!tzip )
  475                                                                         Xrm.Pa ge.getAttr ibute("add ress2_post alcode").s etValue(tz ip);
  476                                                                     Xrm.Page.g etAttribut e("address 2_postalco de").setSu bmitMode(' always');
  477                                                                     var tstate  = ($(this ).find('st ate').leng th > 0) ?  $(this).fi nd('state' )[0].textC ontent : n ull;
  478                                                                     if (!!tsta te)
  479                                                                         Xrm.Pa ge.getAttr ibute("add ress2_stat eorprovinc e").setVal ue(tstate) ;
  480                                                                     Xrm.Page.g etAttribut e("address 2_stateorp rovince"). setSubmitM ode('alway s');
  481                                                                     var tcity  = ($(this) .find('cit y').length  > 0) ? $( this).find ('city')[0 ].textCont ent : null ;
  482                                                                     if (!!tcit y)
  483                                                                         Xrm.Pa ge.getAttr ibute("add ress2_city ").setValu e(tcity);
  484                                                                     Xrm.Page.g etAttribut e("address 2_city").s etSubmitMo de('always ');
  485                                                                     var tcount ry = ($(th is).find(' country'). length > 0 ) ? $(this ).find('co untry')[0] .textConte nt : null;
  486                                                                     if (!!tcou ntry)
  487                                                                         Xrm.Pa ge.getAttr ibute("add ress2_coun try").setV alue(tcoun try);
  488                                                                     Xrm.Page.g etAttribut e("address 2_country" ).setSubmi tMode('alw ays');
  489                                                                     break;
  490                                                                defa ult:
  491                                                            }
  492                                                       }
  493                                                   );
  494                                               }
  495                                          } // end addres ses
  496                                                                                  
  497                                                                                  
  498                                          //op enSensitiv eVeteranWR (pICN, sen sitivityFl ag, home,  mobile, wo rk);
  499                                                                                  openESRw ebresource (pICN, sen sitivityFl ag, isDece ased, deat hReportDat e, home, m obile, wor k);
  500                                      } //end  if ESR cal l (query.r eadyState  == 4 && qu ery.status  == 200)
  501                                      else if  (query.rea dyState ==  4 && quer y.status = = 500) {
  502                                          Xrm. Utility.al ertDialog(
  503                                               //"Enrollm ent Servic es is not  responding  at this t ime and ve teran sens itivity ca nnot be de termined.\ n\nYour qu ery: " + r equest + " \n\nThis s ession wil l now clos e.",
  504                                                                                           "Enrollmen t Services  is not re sponding a t this tim e and vete ran sensit ivity cann ot be dete rmined.\n\ nThis sess ion will n ow close." ,
  505                                               function ( ) {
  506                                                   window .open("htt p://event/ ?eventname =EndSessio nOnBadESRC all");
  507                                               }
  508                                          );
  509                                      }
  510                                 };  //end onr eadystatec hange func tion
  511                                 qu ery.send(r equest);
  512                             } //en d if !!ftp _ESRAPIURL
  513                             else {
  514                                 Xr m.Utility. alertDialo g(
  515                                      "Could n ot find ES R API URL. \n\nThis s ession wil l now clos e.",
  516                                      function  () {
  517                                          wind ow.open("h ttp://even t/?eventna me=EndSess ionOnBadES RCall");
  518                                      }
  519                                 );
  520                             }
  521  
  522                             //PCMM  aka Patie nt Summary
  523                                                       // the pcmm q uery happe ns AFTER o ur other E SR query ( which gets  the vet's  preferred  facility  code), in  the GetFac ilityFromS ervice.OnS uccess fun ction, in  the Popula tePreferre dFacility  library
  524                         } //end if  !!retriev edSettings
  525                         else {
  526                             Xrm.Ut ility.aler tDialog(
  527                                                                "Cou ld not fin d Active S ettings fo r this org ; contact  your syste m administ rator.\n\n This sessi on will no w close.",
  528                                                                func tion () {
  529                                                                     window.ope n("http:// event/?eve ntname=End SessionOnB adESRCall" );
  530                                                                }
  531                                                       );
  532                         }
  533                    } // end active  settings  retrieval  complete c allback
  534                );//end  active set tings quer y
  535           }  //end if ( !!pICN &&  !!fType &&  fType > 1 )
  536           el se if (!pI CN && !!fT ype && fTy pe > 1) {  //without  an id, ass ume sensit ivity=true
  537                //openSe nsitiveVet eranWR(pIC N, true);
  538                             openES Rwebresour ce(pICN, t rue, false );
  539                return;
  540           }
  541           el se {
  542                //if (wi ndow.IsUSD ) {
  543                if (loca tion.href. indexOf("O utlook15Wh ite") != - 1) {
  544                    //US D Session
  545                    wind ow.open("h ttp://even t/?eventna me=New Vet &lastname= " + Xrm.Pa ge.getAttr ibute("las tname").ge tValue());
  546                }
  547                return;
  548           }
  549       }
  550       catch  (e) {
  551           al ert(e);
  552       }
  553   }
  554  
  555   function o penESRwebr esource(pI CN, pSensi tivity, pD eceased, p DeathDate,  pHomephon e, pMobile phone, pWo rkphone){
  556           wr iteToConso le("begin  openESRweb resource(p ICN: " + p ICN + ", p Sensitivit y: " + pSe nsitivity. toString()  + ", pDec eased: " +  pDeceased .toString( ) + ")");
  557           if (!!pICN &&  pSensitiv ity != nul l && pDece ased != nu ll){
  558                    //fi re USD eve nt to copy  some fiel ds to cont ext
  559                    var  eventUrl =  "http://e vent/?even tname=Shar ed Set Vet eran Field s";
  560                    even tUrl += "& veteranid= " + pICN;
  561                    even tUrl += "& nationalid =" + pICN. substring( 0, 10); // this is th e ID used  to query t he Patient  Flags API
  562                    even tUrl += "& sensitivit y=" + pSen sitivity.t oString();  //ESR tab  will move  to MainPa nel if thi s == true
  563                    even tUrl += "& isDeceased =" + pDece ased.toStr ing(); //E SR tab wil l move to  MainPanel  if this ==  true
  564                    even tUrl += "& ESRTabLabe l=" + (pDe ceased ==  true || pD eceased ==  "true" ?  "Deceased  Veteran Wa rning" : " Sensitive  Veteran Wa rning");
  565                    even tUrl += !! pHomephone  ? "&homep hone=" + p Homephone  : "";
  566                    even tUrl += !! pMobilepho ne ? "&mob ilephone="  + pMobile phone : "" ;
  567                    even tUrl += !! pWorkphone  ? "&workp hone=" + p Workphone  : "";
  568                    wind ow.open(ev entUrl);
  569                    writ eToConsole ("fired Sh ared Set V eteran Fie lds event. ");
  570                    
  571                    if(p Sensitivit y == true  || pSensit ivity == " true" || p Deceased = = true ||  pDeceased  == "true") {
  572                             //a US D window n avigation  rule will  route this  to the ES R hosted c ontrol
  573                             //the  PageLoadCo mplete eve nt of that  hosted co ntrol will  determine  whether o r not to S HOW the ta b in USD
  574                             //the  parameters  we're pas sing to it  are requi red for co llecting t he user's  Yes/No dec ision to c ontinue wh en it is a  dead and/ or sensiti ve veteran  and for c ontinuing  on to Pati entFlags.h tml
  575                             var pa rameters =  "contacti d=" + Xrm. Page.data. entity.get Id()
  576                                      + "&full name=" + X rm.Page.da ta.entity. getPrimary AttributeV alue()
  577                                      + "&isDe ceased=" +  pDeceased .toString( )
  578                                      + "&isSe nsitive="  + pSensiti vity.toStr ing()
  579                                      + "&ICN= " + pICN
  580                                      + "&nati onalid=" +  pICN.subs tring(0,10 )
  581                                      //+ "&Is USD=" + (w indow.IsUS D ? "true"  : "false" );
  582                                      + "&IsUS D=" + (loc ation.href .indexOf(" Outlook15W hite") !=  -1 ? "true " : "false ");
  583                             parame ters += !! pDeathDate  ? "&death Date=" + p DeathDate. toLocaleSt ring("en-U S") : "";
  584                             parame ters += !! pHomephone  ? "&homep hone=" + p Homephone  : "";
  585                             parame ters += !! pMobilepho ne ? "&mob ilephone="  + pMobile phone : "" ;
  586                             parame ters += !! pWorkphone  ? "&workf phone=" +  pWorkphone  : "";
  587                             Xrm.Ut ility.open WebResourc e("ftp_/Ve teran/ESR. html", enc odeURIComp onent(para meters));
  588                             writeT oConsole(" opened ESR .html");
  589                    }
  590                    else {
  591                             //skip  ESR.html  and go str aight to P atientFlag s.html
  592                             //a US D window n avigation  rule will  route this  to the Sh ared Patie nt Flags c ontrol
  593                             var da ta = pICN. substring( 0,10); //n ationalid
  594                             Xrm.Ut ility.open WebResourc e("ftp_/Ve teran/Pati entFlags.h tml", data );
  595                             writeT oConsole(" opened Pat ientFlags. html");
  596                    }
  597           }
  598   }
  599  
  600   function o penSensiti veVeteranW R(pICN, pS ensitivity , pHomepho ne, pMobil ephone, pW orkphone)  {
  601           wr iteToConso le("begin  openSensit iveVeteran WR(pICN: "  + pICN +  ", pSensit ivity: " +  pSensitiv ity.toStri ng() + ")" );
  602       if (!! pICN && pS ensitivity  != null)  {
  603           // fire USD e vent to co py some fi elds to co ntext
  604                    var  eventUrl =  "http://e vent/?even tname=Shar ed Set Vet eran Field s";
  605                    even tUrl += "& veteranid= " + pICN;
  606                    even tUrl += "& nationalid =" + pICN. substring( 0, 10); // this is th e ID used  to query t he Patient  Flags API
  607                    even tUrl += "& sensitivit y=" + pSen sitivity.t oString();  //boolean
  608                    even tUrl += !! pHomephone  ? "&homep hone=" + p Homephone  : "";
  609                    even tUrl += !! pMobilepho ne ? "&mob ilephone="  + pMobile phone : "" ;
  610                    even tUrl += !! pWorkphone  ? "&workp hone=" + p Workphone  : "";
  611                    wind ow.open(ev entUrl);
  612                    writ eToConsole ("fired Sh ared Set V eteran Fie lds event. ");
  613                    
  614                    if(p Sensitivit y == true  || pSensit ivity == " true"){
  615                             //a US D window n avigation  rule will  route this  to the Sh ared Sensi tive Veter an hosted  control
  616                             //the  PageLoadCo mplete eve nt of that  hosted co ntrol will  determine  whether o r not to S HOW the ta b in USD
  617                             //the  parameters  we're pas sing to it  are requi red for lo gging the  user's Yes /No decisi on to cont inue when  it is a se nsitive ve teran and  for contin uing on to  PatientFl ags.html
  618                             var pa rameters =  "contacti d=" + Xrm. Page.data. entity.get Id()
  619                                      + "&full name=" + X rm.Page.da ta.entity. getPrimary AttributeV alue()
  620                                      + "&sens itivity="  + pSensiti vity.toStr ing()
  621                                      + "&ICN= " + pICN
  622                                      + "&nati onalid=" +  pICN.subs tring(0,10 )
  623                                      //+ "&Is USD=" + (w indow.IsUS D ? "true"  : "false" );
  624                                      + "&IsUS D=" + (loc ation.href .indexOf(" Outlook15W hite") !=  -1 ? "true " : "false ");
  625                             parame ters += !! pHomephone  ? "&homep hone=" + p Homephone  : "";
  626                             parame ters += !! pMobilepho ne ? "&mob ilephone="  + pMobile phone : "" ;
  627                             parame ters += !! pWorkphone  ? "&workf phone=" +  pWorkphone  : "";
  628                             Xrm.Ut ility.open WebResourc e("ftp_/Ve teran/Sens itiveVeter an.html",  encodeURIC omponent(p arameters) );
  629                             writeT oConsole(" opened Sen sitiveVete ran.html") ;
  630                    }
  631                    else { //skip S ensitiveVe teran.html  and go st raight to  PatientFla gs.html
  632                             //a US D window n avigation  rule will  route this  to the Sh ared Patie nt Flags c ontrol
  633                             var da ta = pICN. substring( 0,10); //n ationalid
  634                             Xrm.Ut ility.open WebResourc e("ftp_/Ve teran/Pati entFlags.h tml", data );
  635                             writeT oConsole(" opened Pat ientFlags. html");
  636                    }
  637       }
  638   }
  639  
  640   function p erformPCMM WebService Call(pFaci lityCode,  pICN) {
  641           wr iteToConso le("begin  performPCM MWebServic eCall()");
  642           Xr m.Page.ui. clearFormN otificatio n("noPCMM" );
  643           pc mm_Enabled  = (_retri evedSettin gs.hasOwnP roperty("f tp_IsPCMME nabled") & & _retriev edSettings .ftp_IsPCM MEnabled ! = null) ?  _retrieved Settings.f tp_IsPCMME nabled : t rue;
  644           wr iteToConso le("pcmm_E nabled: "  + pcmm_Ena bled);
  645           if (pcmm_Enab led && _re trievedSet tings.hasO wnProperty ("ftp_Pati entSummary APIURL") & & !!_retri evedSettin gs.ftp_Pat ientSummar yAPIURL){
  646                    var  facilityCo de = _notP rod ? "987 " : pFacil ityCode;
  647                    writ eToConsole ("_notProd : " + _not Prod);
  648                    writ eToConsole ("facility Code: " +  facilityCo de);
  649                    var  ICN = !!pI CN ? pICN  : !!_ICN ?  _ICN : nu ll;
  650                    if(! !facilityC ode && !!I CN){
  651                             var pc mmUrl = _r etrievedSe ttings.ftp _DACURL +  _retrieved Settings.f tp_Patient SummaryAPI URL + faci lityCode +  "/" + ICN  + "?idTyp e=ICN";
  652                    
  653                             writeT oConsole(" firing $.g et() again st PCMM ur l: " + pcm mUrl);
  654                             $.get(
  655                                      pcmmUrl,
  656                                      function  (returnDa ta, status ) {
  657                                               if (!!retu rnData) {
  658                                                       if  (returnDa ta.ErrorOc curred ==  true || re turnData.E rrorMessag e != null  || returnD ata.DebugI nfo != nul l) {
  659                                                                Xrm. Page.ui.se tFormNotif ication("E rror occur red retrie ving patie nt summary : " + retu rnData.Deb ugInfo, "W ARNING", " ESRCallErr or");
  660                                                                //al ert("Error  occurred  retrieving  patient s ummary:\n\ n" + retur nData.Erro rMessage +  "\n\n" +  returnData .DebugInfo  + "\n\nYo ur query:\ n" + pcmmU rl);
  661                                                                writ eToConsole ("error re trieving P CMM data." );
  662                                                                fill Ftp_pactId WithPactTe amlet12();
  663                                                       }
  664                                                       el se {
  665                                                                if ( returnData .hasOwnPro perty("Dat a")) {
  666                                                                         var da ta = retur nData.Data ;
  667                                                                         writeT oConsole(" got data o bject from  PCMM: ");
  668                                                                         writeT oConsole(d ata);
  669                                                                         var re sultsAsTex t = data.P atientSumm aryText;
  670                                                                         if (re sultsAsTex t.trim() = = "No PACT  assigned  at any VA  location." ) {
  671                                                                                  PCMMGrid Members.pu sh({ Name:  resultsAs Text.trim( ), TeamRol eName: ""  });
  672                                                                                  fillFtp_ pactIdWith PactTeamle t12(); //d o this her e, too?
  673  
  674                                                                         } else  if (data. hasOwnProp erty("pati entAssignm ents") &&  data.patie ntAssignme nts.length  > 0) {
  675                                                                                  var pati entAssignm ent = data .patientAs signments[ 0];
  676                                                                                  writeToC onsole("go t patientA ssignment  from data. ");
  677                                                                                  processP CHBAssignm ent(patien tAssignmen t);
  678                                                                                  processM entalHealt hProvider( patientAss ignment);
  679                                                                         } else  {
  680                                                                                  //if we  don't find  ANY patie ntAssignme nts and al so don't h ave a "no  results me ssage", ju st assign  default Pa ct Teamlet  12, so so me kind of  assignmen t can happ en
  681                                                                                  fillFtp_ pactIdWith PactTeamle t12();
  682                                                                         }
  683                                                                }
  684                                                       }
  685                                               } else {
  686                                                       fi llFtp_pact IdWithPact Teamlet12( );
  687                                               }
  688                                      }
  689                             );
  690                    }//e nd if (!!f acilityCod e && !!ICN )
  691           }/ /end if pc mm_Enabled  == true
  692           el se{
  693                    writ eToConsole ("PCMM is  disabled o r we are m issing ftp _PatientSu mmaryAPIUR L from Act ive Settin gs.");
  694                    
  695                    Xrm. Page.getCo ntrol("Web Resource_V eteranPACT Team").set Visible(fa lse);
  696                    Xrm. Page.getCo ntrol("ftp _pactid"). setVisible (false);
  697                    Xrm. Page.getAt tribute("f tp_pactid" ).setSubmi tMode("alw ays");
  698                    Xrm. Page.getCo ntrol("ftp _primaryca reprovider ").setVisi ble(false) ;
  699                    Xrm. Page.getAt tribute("f tp_primary careprovid er").setSu bmitMode(" always");
  700                    
  701                    Xrm. Page.ui.se tFormNotif ication("T he Patient  Care Mana gement Mod ule (PCMM)  is down a t this tim e so PACT  Team data  is not ava ilable.",  "INFO", "n oPCMM");
  702                    fill Ftp_pactId WithPactTe amlet12();
  703           }
  704   }
  705  
  706   function p rocessPCHB Assignment (pPatientA ssignment)  {
  707           wr iteToConso le("begin  processPCH BAssignmen t");
  708       if (!p PatientAss ignment) {
  709                    writ eToConsole ("patient  assingment  object is  empty.");
  710           fi nishedGett ingPrimary CareProvid ers = true ;
  711           re turn;
  712       }
  713           
  714           /*  Summary
  715                    Data .patientAs signments  will have  either 'pr imaryCareA ssignments ' or 'prim aryCareHBP CAssignmen ts' (home  bound assi gnments).
  716                    Cycl e through  the one wi th data an d store th em in the  teamMember sFromPCMM  array and  the PCMMGr idMembers  array.
  717           */
  718           
  719           va r teamName  = "";
  720       var te amMembersF romPCMM =  []; //empt y array in tended to  hold objec ts of sche ma { Name,  TeamRoleN ame }
  721           
  722           // primaryCar eAssignmen ts array
  723       if (pP atientAssi gnment.has OwnPropert y("primary CareAssign ments") &&  pPatientA ssignment. primaryCar eAssignmen ts.length  > 0) {
  724                    writ eToConsole ("found pr imaryCareA ssignments ");
  725           va r pcAssign ment = pPa tientAssig nment.prim aryCareAss ignments[0 ];
  726           te amName = p cAssignmen t.teamName ;
  727           if  (pcAssign ment.hasOw nProperty( "teamletMe mbers") &&  pcAssignm ent.teamle tMembers.l ength > 0)  {
  728                for (var  i = 0, l  = pcAssign ment.teaml etMembers. length; i  < l; i++)  {
  729                    var  thisTeamle tMember =  pcAssignme nt.teamlet Members[i] ;
  730                    if ( thisTeamle tMember.ha sOwnProper ty("StaffC ontact") & & !!thisTe amletMembe r.StaffCon tact) {
  731                         var sc = t hisTeamlet Member.Sta ffContact;
  732                         if (sc.has OwnPropert y("Name")  && !!sc.Na me) {
  733                             var pe rson = { N ame: sc.Na me, TeamRo leName: sc .TeamRoleN ame };
  734                             teamMe mbersFromP CMM.push(p erson);
  735                             PCMMGr idMembers. push(perso n);
  736                         }
  737                    }
  738                }
  739                finished GettingPri maryCarePr oviders =  true;
  740           }
  741                    else  {
  742                finished GettingPri maryCarePr oviders =  true;
  743           }
  744       }
  745           
  746           // primaryCar eHBPCAssig nments arr ay
  747           el se if (pPa tientAssig nment.hasO wnProperty ("primaryC areHBPCAss ignments")  && pPatie ntAssignme nt.primary CareHBPCAs signments. length > 0 ) {
  748                    writ eToConsole ("found pr imaryCareH BPCAssignm ents");
  749           va r homeboun dPCAssignm ent = pPat ientAssign ment.prima ryCareHBPC Assignment s[0];
  750           te amName = h omeboundPC Assignment .teamName;
  751           if  (homeboun dPCAssignm ent.hasOwn Property(" teamMember s") && hom eboundPCAs signment.t eamMembers .length >  0) {
  752                for (var  i = 0, l  = homeboun dPCAssignm ent.teamMe mbers.leng th; i < l;  i++) {
  753                    var  thisTeamMe mber = hom eboundPCAs signment.t eamMembers [i];
  754                    if ( thisTeamMe mber.hasOw nProperty( "Name") &&  !!thisTea mMember.Na me) {
  755                         var person  = { Name:  thisTeamM ember.Name , TeamRole Name: this TeamMember .TeamRoleN ame };
  756                         teamMember sFromPCMM. push(perso n);
  757                         PCMMGridMe mbers.push (person);
  758                    }
  759                }
  760                finished GettingPri maryCarePr oviders =  true;
  761           }
  762                    else  {
  763                finished GettingPri maryCarePr oviders =  true;
  764           }
  765       }
  766           
  767           // all care a ssignment  arrays are  empty
  768           el se {
  769           fi nishedGett ingPrimary CareProvid ers = true ;
  770       }
  771  
  772       if (!! teamName)  {
  773                    writ eToConsole ("retrievi ng ftp_pac t record:  " + teamNa me);
  774           // find or cr eate a PAC T team rec ord called  named <te amName>
  775           va r retrieve dPACTTeams  = [];
  776           va r queryStr ing = "$fi lter=ftp_n ame eq '"  + teamName  + "'&$exp and=ftp_ft p_pact_sys temuser&$s elect=ftp_ name,ftp_p actId,ftp_ ftp_pact_s ystemuser/ FirstName, ftp_ftp_pa ct_systemu ser/LastNa me,ftp_ftp _pact_syst emuser/Sys temUserId, ftp_ftp_pa ct_systemu ser/FullNa me,ftp_ftp _pact_syst emuser/Dom ainName";
  777           SD K.REST.ret rieveMulti pleRecords (
  778                "ftp_pac t",
  779                queryStr ing,
  780                function  (retrieve dRecords)  {
  781                    if ( typeof ret rievedReco rds != "un defined" & & !!retrie vedRecords ) retrieve dPACTTeams  = retriev edPACTTeam s.concat(r etrievedRe cords);
  782                },
  783                errorHan dler,
  784                function  () {
  785                    if ( retrievedP ACTTeams.l ength > 0)  {
  786                                               writeToCon sole("foun d " + team Name + " p act team i n CRM");
  787                                               setftp_pac tid(retrie vedPACTTea ms[0]);
  788                         matchPCTea mMembersTo PACTTeam(r etrievedPA CTTeams[0] , teamMemb ersFromPCM M, false,  null); //a fter calli ng it here , this met hod calls  itself for  the rest  of the PAC T team mem bers from  PCMM
  789                    }
  790                                      else {
  791                                               writeToCon sole("did  not find "  + teamNam e + " pact  team, cre ating.");
  792                         var newPac t = {
  793                             ftp_na me: teamNa me
  794                         };
  795                         SDK.REST.c reateRecor d(
  796                             newPac t,
  797                             "ftp_p act",
  798                             functi on (create dPACTTeam)  {
  799                                                                setf tp_pactid( createdPAC TTeam);
  800                                 ma tchPCTeamM embersToPA CTTeam(cre atedPACTTe am, teamMe mbersFromP CMM, false , null); / /after cal ling it he re, this m ethod call s itself f or the res t of the P ACT team m embers fro m PCMM
  801                             },
  802                             errorH andler
  803                         );
  804                    }
  805                });
  806       }
  807           el se {
  808           // if we didn 't find a  teamName f rom the pr imaryCareA ssignments  or primar yCareHBPCA ssignments  nodes, se t ftp_pact Id on the  veteran to  PACT Team let 12
  809           fi llFtp_pact IdWithPact Teamlet12( );
  810       }
  811   }
  812  
  813   function p rocessMent alHealthPr ovider(pPa tientAssig nment) {
  814           wr iteToConso le("begin  processMen talHealthP rovider()" );
  815       if (!p PatientAss ignment) {
  816                    writ eToConsole ("patient  assingment  object is  empty.");
  817           fi nishedGett ingMHTC =  true;
  818           re turn;
  819       }
  820           
  821           /*  Summary
  822                    Data .patientAs signments  will have  a mentalHe althAssign ments prop erty that  is an arra y.
  823                    Cycl e through  the array  store its  members in  the teamM embersFrom PCMM array  and the P CMMGridMem bers array .
  824           */
  825       if (pP atientAssi gnment.has OwnPropert y("mentalH ealthAssig nments") & & !!pPatie ntAssignme nt.mentalH ealthAssig nments &&  Array.isAr ray(pPatie ntAssignme nt.mentalH ealthAssig nments) &&  pPatientA ssignment. mentalHeal thAssignme nts.length  > 0) {
  826           va r mentalHe althAssign ment = pPa tientAssig nment.ment alHealthAs signments[ 0];
  827           if  (mentalHe althAssign ment.hasOw nProperty( "teamName" ) && !!men talHealthA ssignment. teamName)  {
  828                var team Name = men talHealthA ssignment. teamName;
  829                if (ment alHealthAs signment.h asOwnPrope rty("menta lHealthTre atmentCoor d") && !!m entalHealt hAssignmen t.mentalHe althTreatm entCoord)  {
  830                    var  MHTC = men talHealthA ssignment. mentalHeal thTreatmen tCoord;
  831                                      writeToC onsole("go t mentalHe althAssign ment.menta lHealthTre atmentCoor d object." );
  832                    PCMM GridMember s.push(MHT C);
  833                    fini shedGettin gMHTC = tr ue;
  834  
  835                    //fi nd or crea te the PAC T Team rec ord matchi ng teamNam e
  836                    //ac cording to  Jeff, thi s should h appen
  837                    if ( !!teamName ) {
  838                         //find or  create a P ACT team r ecord call ed named < teamName>
  839                         var retrie vedPACTTea ms = [];
  840                         var queryS tring = "$ filter=ftp _name eq ' " + teamNa me + "' an d statecod e/Value eq  0&$expand =ftp_ftp_p act_system user&$sele ct=ftp_nam e,ftp_pact Id,ftp_ftp _pact_syst emuser/Fir stName,ftp _ftp_pact_ systemuser /LastName, ftp_pactId ,ftp_ftp_p act_system user/FullN ame,ftp_ft p_pact_sys temuser/Sy stemUserId ";
  841                         SDK.REST.r etrieveMul tipleRecor ds(
  842                             "ftp_p act",
  843                             queryS tring,
  844                             functi on (retrie vedRecords ) {
  845                                 if  (typeof r etrievedRe cords != " undefined" ) retrieve dPACTTeams  = retriev edPACTTeam s.concat(r etrievedRe cords);
  846                             },
  847                             errorH andler,
  848                             functi on () {
  849                                 if  (retrieve dPACTTeams .length >  0) {
  850                                      matchMHT CToPACTTea m(retrieve dPACTTeams [0], MHTC) ;
  851                                 } 
  852                                                                else  {
  853                                      var newP act = {
  854                                          ftp_ name: team Name
  855                                      };
  856                                      SDK.REST .createRec ord(
  857                                          newP act,
  858                                          "ftp _pact",
  859                                          func tion (crea tedPACTTea m) {
  860                                               matchMHTCT oPACTTeam( createdPAC TTeam, MHT C);
  861                                          },
  862                                          erro rHandler
  863                                      );
  864                                 }
  865                             }
  866                         );
  867                    }
  868                } else {
  869                    fini shedGettin gMHTC = tr ue;
  870                }
  871           }  else {
  872                finished GettingMHT C = true;
  873           }
  874       }
  875       else {
  876           fi nishedGett ingMHTC =  true;
  877       }
  878   }
  879  
  880   function s etftp_pact id(pPACTTe am){
  881           wr iteToConso le("begin  setftp_pac tid()");
  882           if (!pPACTTea m) return;
  883           Xr m.Page.get Attribute( "ftp_pacti d").setVal ue([{
  884           id : pPACTTea m.ftp_pact Id,
  885           na me: pPACTT eam.ftp_na me,
  886           en tityType:  "ftp_pact"
  887       }]);
  888           Xr m.Page.get Attribute( "ftp_pacti d").addOnC hange(ftp_ pactid_onC hange);
  889   }
  890  
  891   function m atchPCTeam MembersToP ACTTeam(pP ACTTeam, p PACTTeamMe mbersFromP CMM, pAlre adySetPrim aryCarePro viderField , pUsersTo UnlinkFrom PACTTeam){
  892           wr iteToConso le("");
  893           wr iteToConso le("begin  matchPCTea mMembersTo PACTTeam() ... pPACTT eamMembers FromPCMM.l ength = "  + pPACTTea mMembersFr omPCMM.len gth);
  894           
  895           // usersToUnl ink is an  array that  will end  up holding  a list of  users to  update, se tting thei r ftp_PACT id field n ull
  896           va r usersToU nlink = pU sersToUnli nkFromPACT Team; 
  897           // populate u sersToUnli nk from pP ACTTeam on ly if we h aven't pas sed in an  array of u sers alrea dy (pUsers ToUnlinkFr omPACTTeam )
  898           if (usersToUn link == nu ll){
  899                    user sToUnlink  = [];
  900                    if ( pPACTTeam. hasOwnProp erty("ftp_ ftp_pact_s ystemuser" ) && pPACT Team.ftp_f tp_pact_sy stemuser.h asOwnPrope rty("resul ts") && pP ACTTeam.ft p_ftp_pact _systemuse r.results. length > 0 ) {
  901                             writeT oConsole(p PACTTeam.f tp_ftp_pac t_systemus er.results .length +  " CRM user s already  connected  to the " +  pPACTTeam .ftp_name  + " PACT t eam, befor e we add/r emove anyb ody");
  902                             for (v ar i = 0,  l = pPACTT eam.ftp_ft p_pact_sys temuser.re sults.leng th; i < l;  i++) {
  903                                      usersToU nlink.push (pPACTTeam .ftp_ftp_p act_system user.resul ts[i]);
  904                             }
  905                    }
  906                    else {
  907                             writeT oConsole(" no CRM use rs are cur rently con nected to  the " + pP ACTTeam.ft p_name + "  PACT team , before w e add/remo ve anybody ");
  908                    }
  909           }
  910           
  911           if (pPACTTeam MembersFro mPCMM.leng th > 0){
  912                    var  alreadySet PrimaryCar eProviderF ield = pAl readySetPr imaryCareP roviderFie ld != null  ? pAlread ySetPrimar yCareProvi derField :  false;
  913                    var  thisTeamMe mber = pPA CTTeamMemb ersFromPCM M.shift();  //cut the  length of  pPACTTeam MembersFro mPCMM down  one at a  time
  914                    var  splitName  = thisTeam Member.Nam e.split(", ");
  915                    var  lastName =  splitName [0].trim() ;
  916                    var  splitFirst MiddleName s = splitN ame.length  > 1 ? spl itName[1]. trim().spl it(" ") :  "";
  917                    var  firstName  = !!splitF irstMiddle Names ? sp litFirstMi ddleNames[ 0] : "";
  918                    var  middleName  = !!split FirstMiddl eNames &&  splitFirst MiddleName s.length >  1 ? split FirstMiddl eNames[1]  : "";
  919                    var  fakeFullNa me = lastN ame + ", "  + firstNa me + " " +  middleNam e;
  920                     var domain Name = fir stName + " ." + lastN ame + "@no domainacco unt. DNS     ";
  921                    var  userQuery  = "$select =FirstName ,LastName, SystemUser Id,ftp_PAC TId,ftp_PA CTTeamRole ,IsDisable d,DomainNa me,FullNam e&$filter= DomainName  eq '" + d omainName  + "'";
  922                    writ eToConsole ("thisTeam Member: "  + fakeFull Name + " ( " + domain Name + ")" );
  923                    var  retrievedU sers = [];
  924                    SDK. REST.retri eveMultipl eRecords(
  925                             "Syste mUser",
  926                             userQu ery,
  927                             functi on (retrie vedRecords ) {
  928                                      if (type of retriev edRecords  != "undefi ned" && !! retrievedR ecords) re trievedUse rs = retri evedUsers. concat(ret rievedReco rds);
  929                             },
  930                             errorH andler,
  931                             functi on () {
  932                                      if (retr ievedUsers .length >  0) {
  933                                               var foundU ser = retr ievedUsers [0];
  934                                               if(!foundU ser.IsDisa bled){
  935                                                       wr iteToConso le("found  systemuser  " + found User.Domai nName + "  in CRM");
  936                                                       if  (foundUse r.hasOwnPr operty("ft p_PACTId")  && !!foun dUser.ftp_ PACTId &&  foundUser. ftp_PACTId .Id == pPA CTTeam.ftp _pactId &&
  937                                                                foun dUser.hasO wnProperty ("ftp_PACT TeamRole")  && foundU ser.ftp_PA CTTeamRole  == thisTe amMember.T eamRoleNam e) {
  938                                                                writ eToConsole (foundUser .FullName  + " is alr eady linke d to the "  + pPACTTe am.ftp_nam e + " and  has the co rrect PACT  Team Role ; skipping  update.") ;
  939                                                                user sToUnlink  = removeUs erFromUser sToUnlink( foundUser,  usersToUn link);
  940                                                                if ( !alreadySe tPrimaryCa reProvider Field) alr eadySetPri maryCarePr oviderFiel d = setPri maryCarePr oviderFiel d(foundUse r);
  941                                                                matc hPCTeamMem bersToPACT Team(pPACT Team, pPAC TTeamMembe rsFromPCMM , alreadyS etPrimaryC areProvide rField, us ersToUnlin k);//run t his method  again
  942                                                       }
  943                                                       el se {
  944                                                                foun dUser.ftp_ PACTId = {
  945                                                                         Id: pP ACTTeam.ft p_pactId,
  946                                                                         Logica lName: "ft p_pact",
  947                                                                         Name:  pPACTTeam. ftp_name
  948                                                                };
  949                                                                foun dUser.ftp_ PACTTeamRo le = thisT eamMember. TeamRoleNa me;
  950                                                                SDK. REST.updat eRecord(
  951                                                                         foundU ser.System UserId,
  952                                                                         foundU ser,
  953                                                                         "Syste mUser",
  954                                                                         functi on () {
  955                                                                                  writeToC onsole("up dated " +  foundUser. DomainName  + " with  PACT team  (" + pPACT Team.ftp_n ame + ") a nd PACT te am role ("  + thisTea mMember.Te amRoleName  + ")");
  956                                                                                  usersToU nlink = re moveUserFr omUsersToU nlink(foun dUser, use rsToUnlink );
  957                                                                                  if (!alr eadySetPri maryCarePr oviderFiel d) already SetPrimary CareProvid erField =  setPrimary CareProvid erField(fo undUser);
  958                                                                                  matchPCT eamMembers ToPACTTeam (pPACTTeam , pPACTTea mMembersFr omPCMM, al readySetPr imaryCareP roviderFie ld, usersT oUnlink);/ /run this  method aga in
  959                                                                         },
  960                                                                         errorH andler
  961                                                                );
  962                                                       }
  963                                               }
  964                                               else{
  965                                                       wr iteToConso le("found  systemuser " + foundU ser.Domain Name + ",  but this u ser is dis abled.  Sk ipping use r update." );
  966                                               }
  967                                      }
  968                                      //If we  didn't fin d thisMemb er in CRM  as a user,  then retr ieve the ' PACT USER'  CRM team,  and creat e the new  user, and  make the u ser a memb er of the  team
  969                                      else { 
  970                                               writeToCon sole("did  not find "  + domainN ame + ", c reating sy stemuser." );
  971                                               var PACTUs erCRMTeam  = null;
  972                                               var teamQu ery = "$se lect=Name, TeamId,Bus inessUnitI d&$filter= Name eq 'P ACT User'  and TeamTy pe/Value e q 0";
  973                                               var retrie vedCRMTeam s = [];
  974                                               SDK.REST.r etrieveMul tipleRecor ds(
  975                                                       "T eam",
  976                                                       te amQuery,
  977                                                       fu nction (re trievedRec ords) {
  978                                                                if ( typeof ret rievedReco rds != "un defined" & & !!retrie vedRecords ) retrieve dCRMTeams  = retrieve dCRMTeams. concat(ret rievedReco rds);
  979                                                       },
  980                                                       er rorHandler ,
  981                                                       fu nction ()  {
  982                                                                if ( retrievedC RMTeams.le ngth > 0)  {
  983                                                                         PACTUs erCRMTeam  = retrieve dCRMTeams[ 0];
  984                                                                         
  985                                                                         //buil d newUser  object
  986                                                                         var ne wUser = {
  987                                                                                  FirstNam e: firstNa me,
  988                                                                                  LastName : lastName ,
  989                                                                                  MiddleNa me: middle Name,
  990                                                                                  ftp_PACT TeamRole:  thisTeamMe mber.TeamR oleName,
  991                                                                                  IsIntegr ationUser:  false,
  992                                                                                  UserLice nseType: 3 ,
  993                                                                                  AccessMo de: {
  994                                                                                           Value: 0
  995                                                                                  },
  996                                                                                  DomainNa me: domain Name,
  997                                                                                  Business UnitId: {
  998                                                                                           Id: PACTUs erCRMTeam. BusinessUn itId.Id,
  999                                                                                           LogicalNam e: PACTUse rCRMTeam.B usinessUni tId.Logica lName,
  1000                                                                                           Name: PACT UserCRMTea m.Business UnitId.Nam e
  1001                                                                                  },
  1002                                                                                  ftp_PACT Id: {
  1003                                                                                           Id: pPACTT eam.ftp_pa ctId,
  1004                                                                                           LogicalNam e: "ftp_pa ct",
  1005                                                                                           Name: pPAC TTeam.ftp_ name
  1006                                                                                  }
  1007                                                                         };
  1008                                                                         SDK.RE ST.createR ecord(
  1009                                                                                  newUser,
  1010                                                                                  "SystemU ser",
  1011                                                                                  function  (createdU ser) {
  1012                                                                                           writeToCon sole("crea ted system user: " +  fakeFullNa me + " ("  + domainNa me + "). G UID: " + c reatedUser .SystemUse rId);
  1013                                                                                           addUsersTo Team(creat edUser.Sys temUserId,  PACTUserC RMTeam.Tea mId);
  1014                                                                                           if (!alrea dySetPrima ryCareProv iderField)  alreadySe tPrimaryCa reProvider Field = se tPrimaryCa reProvider Field(crea tedUser);
  1015                                                                                           matchPCTea mMembersTo PACTTeam(p PACTTeam,  pPACTTeamM embersFrom PCMM, alre adySetPrim aryCarePro viderField , usersToU nlink); // run this m ethod agai n
  1016                                                                                  },
  1017                                                                                  errorHan dler
  1018                                                                         );
  1019                                                                }
  1020                                                       }
  1021                                               );
  1022                                      }
  1023                             }
  1024                    );
  1025           }
  1026           el se{
  1027                    //if  all prima ry care te am members  PCMM are  now in CRM  as system users, lin ked to the  PACT team , we can n ow update  any remain ing system users that  should be  be linked  to this P ACT team
  1028                    unli nkUsersFro mPACTTeam( usersToUnl ink);
  1029           }
  1030   }
  1031  
  1032   function r emoveUserF romUsersTo Unlink(pUs er, pUsers ToUnlink){
  1033           fo r(var i =  0, l = pUs ersToUnlin k.length;  i < l; i++ ){
  1034                    if(p UsersToUnl ink[i].Sys temUserId  == pUser.S ystemUserI d){
  1035                             pUsers ToUnlink.s plice(i,1) ;
  1036                             break;
  1037                    }
  1038           }
  1039           re turn pUser sToUnlink;
  1040   }
  1041  
  1042   function u nlinkUsers FromPACTTe am(pUsers) {
  1043           wr iteToConso le("begin  unlinkUser sFromPACTT eam()");
  1044       if (!! pUsers &&  Array.isAr ray(pUsers ) && pUser s.length >  0) {
  1045                    writ eToConsole ("pUsers.l ength: " +  pUsers.le ngth);
  1046                    var  thisUser =  pUsers.sh ift();
  1047                    if ( thisUser.h asOwnPrope rty("Syste mUserId")  && !!thisU ser.System UserId) {
  1048                             thisUs er.ftp_PAC TId = {
  1049                                      Id: null ,
  1050                                      LogicalN ame: null,
  1051                                      Name: nu ll
  1052                             };
  1053                             SDK.RE ST.updateR ecord(
  1054                                      thisUser .SystemUse rId,
  1055                                      thisUser ,
  1056                                      "SystemU ser",
  1057                                      function  () {
  1058                                               //do nothi ng else wi th this us er
  1059                                               writeToCon sole("clea red ftp_PA CTId field  on system user:" + t hisUser.Fu llName + "  {" + this User.Syste mUserId +  "}");
  1060                                              
  1061                                               //re-enter  this func tion until  pUsers is  empty
  1062                                               unlinkUser sFromPACTT eam(pUsers );
  1063                                      },
  1064                                      errorHan dler
  1065                             );
  1066                    }
  1067           }
  1068           el se{
  1069                    writ eToConsole ("no users  to unlink .");
  1070           }
  1071   }
  1072  
  1073   function s etPrimaryC areProvide rField(pUs er) {
  1074       if (!p User || !p User.ftp_P ACTTeamRol e || !pUse r.FullName ) return f alse;
  1075       if (!( pUser.ftp_ PACTTeamRo le == "Pri mary Care  Provider"  || pUser.f tp_PACTTea mRole == " Associate  Provider") ) return f alse;
  1076       Xrm.Pa ge.getAttr ibute("ftp _primaryca reprovider ").setValu e(pUser.Fu llName);
  1077       Xrm.Pa ge.getAttr ibute("ftp _primaryca reprovider ").setSubm itMode("al ways");
  1078           wr iteToConso le("set Ve teran's ft p_primaryc areprovide r with sys temuser.Fu llName: "  + pUser.Fu llName);
  1079       return  true;
  1080   }
  1081  
  1082   function m atchMHTCTo PACTTeam(p PACTTeam,  pMHTC) {
  1083           wr iteToConso le("begin  matchMHTCT oPACTTeam( )");
  1084       if (!p PACTTeam)  return;
  1085       //don' t set the  ftp_pactid  lookup fi eld on the  vet form
  1086  
  1087       //save  to an arr ay the cur rent list  of users w ho current ly referen ce pPACTTe am, so tha t we can r emove that  reference  if they N O LONGER a re a membe r of pPACT Team accor ding to PC MM
  1088           // for a ment al health  PACT team. ..it shoul d just be  one user
  1089           // for a newl y-created  ftp_pact r ecord, thi s list of  users will  be empty
  1090       var us ersToUpdat e = [];
  1091       if (pP ACTTeam.ha sOwnProper ty("ftp_ft p_pact_sys temuser")  && pPACTTe am.ftp_ftp _pact_syst emuser.has OwnPropert y("results ") && pPAC TTeam.ftp_ ftp_pact_s ystemuser. results.le ngth > 0)  {
  1092                    writ eToConsole (pPACTTeam .ftp_ftp_p act_system user.resul ts.length  + " CRM us ers curren tly connec ted to the  " + pPACT Team.ftp_n ame + " PA CT team");
  1093           fo r (var i =  0, l = pP ACTTeam.ft p_ftp_pact _systemuse r.results. length; i  < l; i++)  {
  1094                usersToU pdate.push (pPACTTeam .ftp_ftp_p act_system user.resul ts[i]);
  1095           }
  1096       }
  1097  
  1098       if (!! pMHTC) {
  1099           va r teamQuer y = "$sele ct=Name,Te amId,Busin essUnitId& $filter=Na me eq 'PAC T User' an d TeamType /Value eq  0";
  1100           va r retrieve dCRMTeams  = [];
  1101           SD K.REST.ret rieveMulti pleRecords (
  1102                             "Team" ,
  1103                             teamQu ery,
  1104                             functi on (retrie vedRecords ) {
  1105                                      if (type of retriev edRecords  != "undefi ned" && !! retrievedR ecords) re trievedCRM Teams = re trievedCRM Teams.conc at(retriev edRecords) ;
  1106                             },
  1107                             errorH andler,
  1108                             functi on () {
  1109                                      if (retr ievedCRMTe ams.length  > 0) {
  1110                                               var PACTUs erCRMTeam  = retrieve dCRMTeams[ 0];
  1111  
  1112                                               //find or  create a s ystemuser  for the Me ntal Healt h Treatmen t Coordina tor (pMHTC )
  1113                                               //set thei r ftp_PACT Id lookup  field to p PACTTeam
  1114                                               //add the  user to th e 'PACT Us er' CRM te am, so it  will inher it the tea m's securi ty roles
  1115                                               //if their  ftp_PACTI d and ftp_ PACTTeamRo le are fin e, remove  that perso n from use rsToUpdate  array
  1116  
  1117                                               //pMHTC sc hema: { Na me, TeamRo leName, Te amRoleCode , Phone, P age, Ien }
  1118                                               writeToCon sole("sear ching for  " + pMHTC. Name + " t o connect  their CRM  user recor d to the "  + pPACTTe am.ftp_nam e + " PACT  team in C RM");
  1119                                               var splitN ame = pMHT C.Name.spl it(",");
  1120                                               var lastNa me = split Name[0];
  1121                                               var splitF irstMiddle Names = sp litName.le ngth > 1 ?  splitName [1].trim() .split(" " ) : "";
  1122                                               var firstN ame = !!sp litFirstMi ddleNames  ? splitFir stMiddleNa mes[0] : " ";
  1123                                               var middle Name = !!s plitFirstM iddleNames  && splitF irstMiddle Names.leng th > 1 ? s plitFirstM iddleNames [1] : "";
  1124                                               var fakeFu llName = l astName +  ", " + fir stName + "  " + middl eName;
  1125                                                var domain Name = fir stName + " ." + lastN ame + "@no domainacco unt. DNS     ";
  1126                                               var userQu ery = "$se lect=First Name,LastN ame,System UserId,ftp _PACTId,ft p_PACTTeam Role,IsDis abled,Doma inName,Ful lName&$fil ter=Domain Name eq '"  + domainN ame + "'";
  1127                                               var retrie vedUsers =  [];
  1128                                               SDK.REST.r etrieveMul tipleRecor ds(
  1129                                                       "S ystemUser" ,
  1130                                                       us erQuery,
  1131                                                       fu nction (re trievedRec ords) {
  1132                                                                if ( typeof ret rievedReco rds != "un defined" & & !!retrie vedRecords ) retrieve dUsers = r etrievedUs ers.concat (retrieved Records);
  1133                                                       },
  1134                                                       er rorHandler ,
  1135                                                       fu nction ()  {
  1136                                                                if ( retrievedU sers.lengt h > 0) {
  1137                                                                         writeT oConsole(" found syst emuser: "  + domainNa me + ", up dating sys temuser.") ;
  1138                                                                         var fo undUser =  retrievedU sers[0];
  1139                                                                         if(!fo undUser.Is Disabled){
  1140                                                                                  if (foun dUser.hasO wnProperty ("ftp_PACT Id") && !! foundUser. ftp_PACTId  && foundU ser.ftp_PA CTId.Id ==  pPACTTeam .ftp_pactI d &&
  1141                                                                                           foundUser. hasOwnProp erty("ftp_ PACTTeamRo le") && fo undUser.ft p_PACTTeam Role == pM HTC.TeamRo leName) {
  1142                                                                                           writeToCon sole(found User.FullN ame + " is  already l inked to t he " + pPA CTTeam.ftp _name + "  and has th e correct  PACT Team  Role; skip ping updat e.");
  1143                                                                                           //remove t his person  from the  usersToUpd ate array,  because t heir ftp_P ACTId and  ftp_PACTTe amRole are  already f ine
  1144                                                                                           usersToUpd ate.splice (i, 1);
  1145                                                                                           setMentalH ealthTeamF ield(found User);
  1146                                                                                  } 
  1147                                                                                  else {
  1148                                                                                           foundUser. ftp_PACTId  = {
  1149                                                                                                   Id : pPACTTea m.ftp_pact Id,
  1150                                                                                                   Lo gicalName:  "ftp_pact ",
  1151                                                                                                   Na me: pPACTT eam.ftp_na me
  1152                                                                                           };
  1153                                                                                           foundUser. ftp_PACTTe amRole = p MHTC.TeamR oleName;
  1154                                                                                           SDK.REST.u pdateRecor d(
  1155                                                                                                   fo undUser.Sy stemUserId ,
  1156                                                                                                   fo undUser,
  1157                                                                                                   "S ystemUser" ,
  1158                                                                                                   fu nction ()  {
  1159                                                                                                            writ eToConsole ("updated  " + foundU ser.Domain Name + " w ith PACT t eam (" + p PACTTeam.f tp_name +  ") and PAC T team rol e (" + pMH TC.TeamRol eName + ") ");
  1160                                                                                                            setM entalHealt hTeamField (foundUser );
  1161                                                                                                   },
  1162                                                                                                   er rorHandler
  1163                                                                                           );
  1164                                                                                  }
  1165                                                                         }
  1166                                                                         else{
  1167                                                                                  writeToC onsole("fo und system user" + fo undUser.Do mainName +  ", but th is user is  disabled.   Skipping  user upda te.");
  1168                                                                         }
  1169                                                                }
  1170                                                                else  {
  1171                                                                         writeT oConsole(" did not fi nd systemu ser: " + d omainName  + ", creat ing system user.");
  1172                                                                         //buil d user obj ect
  1173                                                                         var ne wUser = {
  1174                                                                                  FirstNam e: firstNa me,
  1175                                                                                  LastName : lastName ,
  1176                                                                                  MiddleNa me: middle Name,
  1177                                                                                  ftp_PACT TeamRole:  pMHTC.Team RoleName,
  1178                                                                                  IsIntegr ationUser:  false,
  1179                                                                                  UserLice nseType: 3 ,
  1180                                                                                  AccessMo de: {
  1181                                                                                           Value: 0
  1182                                                                                  },
  1183                                                                                  DomainNa me: domain Name,
  1184                                                                                  Business UnitId: {
  1185                                                                                           Id: PACTUs erCRMTeam. BusinessUn itId.Id,
  1186                                                                                           LogicalNam e: PACTUse rCRMTeam.B usinessUni tId.Logica lName,
  1187                                                                                           Name: PACT UserCRMTea m.Business UnitId.Nam e
  1188                                                                                  },
  1189                                                                                  ftp_PACT Id: {
  1190                                                                                           Id: pPACTT eam.ftp_pa ctId,
  1191                                                                                           LogicalNam e: "ftp_pa ct",
  1192                                                                                           Name: pPAC TTeam.ftp_ name
  1193                                                                                  }
  1194                                                                         };
  1195                                                                         //crea te it
  1196                                                                         SDK.RE ST.createR ecord(
  1197                                                                                  newUser,
  1198                                                                                  "SystemU ser",
  1199                                                                                  function  (createdU ser) {
  1200                                                                                           writeToCon sole("crea ted system user: " +  fakeFullNa me + " ("  + domainNa me + "). G UID: " + c reatedUser .SystemUse rId);
  1201                                                                                           setMentalH ealthTeamF ield(creat edUser);
  1202                                                                                           addUsersTo Team(creat edUser.Sys temUserId,  PACTUserC RMTeam.Tea mId);
  1203                                                                                  },
  1204                                                                                  errorHan dler
  1205                                                                         );
  1206                                                                }
  1207                                                       }
  1208                                               );
  1209                                      }
  1210                             }
  1211                    );
  1212       }
  1213           el se {
  1214           // even if we  don't lin k a new MH TC user to  pPACTTeam  for the f irst time,  still nee d to unlin k "old" me mbers of p PACTTeam
  1215           un linkUsersF romPACTTea m(usersToU pdate);
  1216       }
  1217   }
  1218  
  1219   function s etMentalHe althTeamFi eld(pUser)  {
  1220           wr iteToConso le("begin  setMentalH ealthTeamF ield()");
  1221       if (!! pUser && ! !pUser.ftp _PACTTeamR ole && !!p User.FullN ame) {
  1222           if  (pUser.ft p_PACTTeam Role == "( mhtc) Addi ction Ther apist") {
  1223                             var MH TCAttr = X rm.Page.ge tAttribute ("ftp_ment alhealthte am");
  1224                             if(!!M HTCAttr){
  1225                                      Xrm.Page .getAttrib ute("ftp_m entalhealt hteam").se tValue(pUs er.FullNam e);
  1226                                      Xrm.Page .getAttrib ute("ftp_m entalhealt hteam").se tSubmitMod e("always" );
  1227                                      writeToC onsole("se t ftp_ment alhealthte am to " +  pUser.Full Name);
  1228                             }
  1229                             else{
  1230                                      writeToC onsole("di d not set  ftp_mental healthteam  to becaus e attribut e is not o n form.");
  1231                             }
  1232           }
  1233       }
  1234   }
  1235  
  1236   function a ddUsersToT eam(pUserI ds, pTeamI d) {
  1237           wr iteToConso le("begin  addUsersTo Team.  pTe amId: " +  pTeamId);
  1238       var se rviceURL =  Xrm.Page. context.ge tClientUrl () + "/XRM Services/2 011/Organi zation.svc /web";
  1239       var re questMain  = "";
  1240       reques tMain += " <s:Envelop e xmlns:s= \"http://s chemas.xml soap.org/s oap/envelo pe/\">";
  1241       reques tMain += "   <s:Body> ";
  1242       reques tMain += "     <Execu te xmlns=\ "http://sc hemas.micr osoft.com/ xrm/2011/C ontracts/S ervices\"  xmlns:i=\" http://www .w3.org/20 01/XMLSche ma-instanc e\">";
  1243       reques tMain += "       <req uest i:typ e=\"b:AddM embersTeam Request\"  xmlns:a=\" http://sch emas.micro soft.com/x rm/2011/Co ntracts\"  xmlns:b=\" http://sch emas.micro soft.com/c rm/2011/Co ntracts\"> ";
  1244       reques tMain += "         <a :Parameter s xmlns:c= \"http://s chemas.dat acontract. org/2004/0 7/System.C ollections .Generic\" >";
  1245       reques tMain += "            <a:KeyValu ePairOfstr inganyType >";
  1246       reques tMain += "              <c:key>T eamId</c:k ey>";
  1247       reques tMain += "              <c:value  i:type=\" d:guid\" x mlns:d=\"h ttp://sche mas.micros oft.com/20 03/10/Seri alization/ \">" + pTe amId + "</ c:value>";
  1248       reques tMain += "            </a:KeyVal uePairOfst ringanyTyp e>";
  1249       reques tMain += "            <a:KeyValu ePairOfstr inganyType >";
  1250       reques tMain += "              <c:key>M emberIds</ c:key>";
  1251       reques tMain += "              <c:value  i:type=\" d:ArrayOfg uid\" xmln s:d=\"http ://schemas .microsoft .com/2003/ 10/Seriali zation/Arr ays\">";
  1252       if (Ar ray.isArra y(pUserIds )) {
  1253           fo r (var i =  0, l = pU serIds.len gth; i < l ; i++) {
  1254                             writeT oConsole(" adding sys temuser {"  + pUserId s[i] + "}  to team {"  + pTeamId  + "}");
  1255                requestM ain += "                <d:guid> " + pUserI ds[i] + "< /d:guid>";
  1256           }
  1257       } else  {
  1258                    writ eToConsole ("adding s ystemuser  {" + pUser Ids + "} t o team {"  + pTeamId  + "}");
  1259           re questMain  += "               <d :guid>" +  pUserIds +  "</d:guid >";
  1260       }
  1261       reques tMain += "              </c:valu e>";
  1262       reques tMain += "            </a:KeyVal uePairOfst ringanyTyp e>";
  1263       reques tMain += "         </ a:Paramete rs>";
  1264       reques tMain += "         <a :RequestId  i:nil=\"t rue\" />";
  1265       reques tMain += "         <a :RequestNa me>AddMemb ersTeam</a :RequestNa me>";
  1266       reques tMain += "       </re quest>";
  1267       reques tMain += "     </Exec ute>";
  1268       reques tMain += "   </s:Body >";
  1269       reques tMain += " </s:Envelo pe>";
  1270       var re q = new XM LHttpReque st();
  1271       req.op en("POST",  serviceUR L, true);
  1272       // Res ponses wil l return X ML. It isn 't possibl e to retur n JSON.
  1273       req.se tRequestHe ader("Acce pt", "appl ication/xm l, text/xm l, */*");
  1274       req.se tRequestHe ader("Cont ent-Type",  "text/xml ; charset= utf-8");
  1275       req.se tRequestHe ader("SOAP Action", " http://sch emas.micro soft.com/x rm/2011/Co ntracts/Se rvices/IOr ganization Service/Ex ecute");
  1276       var su ccessCallb ack = null ;
  1277       var er rorCallbac k = null;
  1278       req.on readystate change = f unction ()  { };
  1279       req.se nd(request Main);
  1280           wr iteToConso le("sent r equest to  add user t o team.");
  1281   }
  1282  
  1283   function f tp_pactid_ onChange()  {
  1284           wr iteToConso le("begin  ftp_pactid _onChange( )");
  1285       //cycl e through  users unde r selected  PACT who  have a rol e, and upd ate some f ields on t he form wi th their n ames
  1286       var pa ctTeamValu e = Xrm.Pa ge.getAttr ibute("ftp _pactid"). getValue() ;
  1287       if (!p actTeamVal ue) return ;
  1288           wr iteToConso le("PACT t eam: " + p actTeamVal ue[0].name );
  1289       var qu eryString  = "$select =FullName, ftp_PACTId &$filter=f tp_PACTId/ Id eq guid '" + pactT eamValue[0 ].id + "'  and ftp_PA CTTeamRole  ne null";
  1290       var re trievedUse rs = [];
  1291       SDK.RE ST.retriev eMultipleR ecords(
  1292           "S ystemUser" ,
  1293           qu eryString,
  1294           fu nction (re trievedRec ords) {
  1295                if (type of retriev edRecords  != "undefi ned" && !! retrievedR ecords) re trievedUse rs = retri evedUsers. concat(ret rievedReco rds);
  1296           },
  1297           er rorHandler ,
  1298           fu nction ()  {
  1299                if (retr ievedUsers .length >  0) {
  1300                                      writeToC onsole("fo und " + re trievedUse rs.length  + " users  on this PA CT team.") ;
  1301                    var  alreadySet PrimaryCar eProviderF ield = fal se;
  1302                    var  alreadySet MentalHeal thTeamFiel d = false;
  1303                                      writeToC onsole("cy cling thro ugh users  to find Pr imary Care  Provider  (or Associ ate Provid er), and ( mhtc) Addi ction Ther apist.");
  1304                    for  (var i = 0 , l = retr ievedUsers .length; i  < l && (! alreadySet PrimaryCar eProviderF ield || !a lreadySetM entalHealt hTeamField ) ; i++) {
  1305                         var thisUs er = retri evedUsers[ i];
  1306                         if (!alrea dySetPrima ryCareProv iderField  && (thisUs er.ftp_PAC TTeamRole  == "Primar y Care Pro vider" ||  thisUser.f tp_PACTTea mRole == " Associate  Provider") ) {
  1307                             alread ySetPrimar yCareProvi derField =  setPrimar yCareProvi derField(t hisUser);
  1308                         }
  1309                         if (!alrea dySetMenta lHealthTea mField &&  thisUser.f tp_PACTTea mRole == " (mhtc) Add iction The rapist") {
  1310                             alread ySetMental HealthTeam Field = se tMentalHea lthTeamFie ld(thisUse r);
  1311                         }
  1312                    }
  1313                }
  1314           }
  1315       );
  1316   }
  1317  
  1318   function f illFtp_pac tIdWithPac tTeamlet12 () {
  1319           wr iteToConso le("begin  fillFtp_pa ctIdWithPa ctTeamlet1 2()");
  1320       var re trievedPAC TTeams = [ ];
  1321       var qu eryString  = "$filter =ftp_name  eq 'PACT T eamlet 12' &$select=f tp_name,ft p_pactId";
  1322       SDK.RE ST.retriev eMultipleR ecords(
  1323           "f tp_pact",
  1324           qu eryString,
  1325           fu nction (re trievedRec ords) {
  1326                if (type of retriev edRecords  != "undefi ned" && !! retrievedR ecords) re trievedPAC TTeams = r etrievedPA CTTeams.co ncat(retri evedRecord s);
  1327           },
  1328           er rorHandler ,
  1329           fu nction ()  {
  1330                if (retr ievedPACTT eams.lengt h > 0) {
  1331                    var  PACTTeamle t12 = retr ievedPACTT eams[0];
  1332                                      writeToC onsole("go t PACTTeam let12");
  1333                    Xrm. Page.getAt tribute("f tp_pactid" ).setValue ([{
  1334                         id: PACTTe amlet12.ft p_pactId,
  1335                         name: PACT Teamlet12. ftp_name,
  1336                         entityType : "ftp_pac t"
  1337                    }
  1338                    ]);
  1339                                      writeToC onsole("se t Veteran' s ftp_pact id field") ;
  1340                                      Xrm.Page .getAttrib ute("ftp_p actid").se tSubmitMod e("always" );
  1341  
  1342                    //** ********** ***
  1343                    if ( pcmm_Enabl ed == true ) {
  1344                         var alertT ext = "Not ify your P CMM Admini strator to  set up th is veteran 's Care Te am Assignm ent in PCM M. You can not assign  Requests  until this  is comple te.";
  1345                         Xrm.Page.u i.setFormN otificatio n(alertTex t, "INFO",  "noPACTFr omPCMM");
  1346                    }
  1347                    //** ********** ***
  1348  
  1349                    fini shedGettin gPrimaryCa reProvider s = true;
  1350                    fini shedGettin gMHTC = tr ue;
  1351                }
  1352           }
  1353       );
  1354   }
  1355  
  1356   function b uildQueryF ilter(fiel d, value,  and) {
  1357       return  !!field ?  ((and ? "  and " : " ") + field  + " eq "  + (value = = '' ? "nu ll" : "'"  + value +  "'")) : "" ;
  1358   }
  1359  
  1360   function e rrorHandle r(error) {
  1361           wr iteToConso le(error.m essage);
  1362       alert( error.mess age);
  1363   }
  1364   function w riteToCons ole(messag e) {
  1365       if (ty peof conso le != 'und efined') c onsole.log (message);
  1366   }
  1367  
  1368   //******** ********** ********** **
  1369   function p cmm_retrie vePCMMSett ing() {
  1370       try {
  1371           va r context  = Xrm.Page .context.g etClientUr l();
  1372           va r ODATA_EN DPOINT = " /XRMServic es/2011/Or ganization Data.svc";
  1373           // Construct  the JSON Q uery
  1374           va r EntitySe tName = "m cs_setting Set";
  1375           va r selectSt ring = "?$ select=ftp _IsPCMMEna bled&$filt er=mcs_nam e eq 'Acti ve Setting s'";
  1376           va r jsonQuer y = contex t + ODATA_ ENDPOINT +  "/" + Ent itySetName  + selectS tring;
  1377           // Initialize  the retur n value
  1378           va r EntityDa ta = null;
  1379           $. ajax({
  1380                type: "G ET",
  1381                contentT ype: "appl ication/js on; charse t=utf-8",
  1382                datatype : "json",
  1383                url: jso nQuery,
  1384                beforeSe nd: functi on (XMLHtt pRequest)  {
  1385                    //Sp ecifying t his header  ensures t hat the re sults will  be return ed as JSON .
  1386                    XMLH ttpRequest .setReques tHeader("A ccept", "a pplication /json");
  1387                },
  1388                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  1389                    //Ge t the data  values
  1390                    Enti tyData = d ata;
  1391  
  1392                },
  1393                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  1394                    aler t('Fail: A jax Error  in Veteran  OnLoad Sc ript - pcm m_retrieve PCMMSettin g Function . Error: '  + errorTh rown);
  1395                },
  1396                async: f alse,
  1397                cache: f alse
  1398           }) ;
  1399           re turn Entit yData;
  1400       }
  1401       catch  (e) {
  1402           al ert("Error  occurred  in Veteran  OnLoad Sc ript - pcm m_retrieve PCMMSettin g function . Error da ta:" + e);
  1403       }
  1404   }
  1405   //******** ********** ********** **