41. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 12/4/2017 8:32:32 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.

41.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_14.zip\WebResources ftp_VeteranJScriptmainjs59ECC3B8-0DCC-E411-80CB-00155DD08303 Fri May 12 22:15:46 2017 UTC
2 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_14.zip\WebResources ftp_VeteranJScriptmainjs59ECC3B8-0DCC-E411-80CB-00155DD08303 Thu Nov 30 17:18:37 2017 UTC

41.2 Comparison summary

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

41.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

41.4 Active regular expressions

No regular expressions were active.

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