13. EPMO Open Source Coordination Office Redaction File Detail Report

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

13.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\FTPResources\FTPResources_3_35.zip\WebResources ftp_VeteranJScriptmainjs59ECC3B8-0DCC-E411-80CB-00155DD08303 Thu Nov 17 16:48:12 2016 UTC
2 VCCM.zip\VCCM\CRM_solutions\FTPResources\FTPResources_3_35.zip\WebResources ftp_VeteranJScriptmainjs59ECC3B8-0DCC-E411-80CB-00155DD08303 Thu Nov 30 16:21:48 2017 UTC

13.2 Comparison summary

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

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

13.4 Active regular expressions

No regular expressions were active.

13.5 Comparison detail

  1   //global v ariable.
  2   var _notPr od = true;
  3   var _ICN =  "";
  4   var PCMMGr idMembers  = [];
  5   var finish edGettingP rimaryCare Providers  = false;
  6   var finish edGettingM HTC = fals e;
  7   //******** ********** ********** ********** **
  8   //Set new  PCMM Enabl ed flag to  True as d efault, th en read fr om 'Active  Settings'
  9   var pcmm_E nabled = t rue;
  10   //******** ********** ********** ********** **
  11  
  12   function f orm_onLoad () {
  13       //**** ********** ********** ********** ******
  14       //Get  PCMM Setti ng value f rom Active  Settings
  15       var pc mm_actives ettings =  pcmm_retri evePCMMSet ting();
  16       for (i  = 0; i <  pcmm_activ esettings. d.results. length; i+ +) {
  17           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;  }
  18           br eak;
  19       }
  20       if (pc mm_Enabled  == false)  {
  21           Xr m.Page.get Control("W ebResource _VeteranPA CTTeam").s etVisible( false);
  22           Xr m.Page.get Control("f tp_pactid" ).setVisib le(false);
  23           Xr m.Page.get Attribute( "ftp_pacti d").setSub mitMode("a lways");
  24           Xr m.Page.get Control("f tp_primary careprovid er").setVi sible(fals e);
  25           Xr m.Page.get Attribute( "ftp_prima rycareprov ider").set SubmitMode ("always") ;
  26       }
  27       //**** ********** ********** ********** ******
  28  
  29       //**** ********** *
  30       if (pc mm_Enabled  == false)  {
  31           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.";
  32           Xr m.Page.ui. setFormNot ification( pcmm_alert Text, "INF O", "noPCM M");
  33       }
  34       //**** ********** *
  35  
  36       var qu eryStringP arameters  = Xrm.Page .context.g etQueryStr ingParamet ers();
  37       _ICN =  (queryStr ingParamet ers.hasOwn Property(" ICN_0")) ?  queryStri ngParamete rs.ICN_0 :  "";
  38       var sk ipWebServi ceCalls =  (queryStri ngParamete rs.hasOwnP roperty("s kipWebServ iceCalls_0 ")) ? quer yStringPar ameters.sk ipWebServi ceCalls_0  : false;
  39  
  40       if (sk ipWebServi ceCalls) {
  41           op enSensitiv eVeteranWR (
  42                             "NEWVE TERAN",
  43                             false,  //assume  not sensit ive, so th at we can  continue w ith intera ction in U SD
  44                             Xrm.Pa ge.getAttr ibute("ftp _homephone ").getValu e(),
  45                             Xrm.Pa ge.getAttr ibute("ftp _workphone ").getValu e(),
  46                             Xrm.Pa ge.getAttr ibute("ftp _mobilepho ne").getVa lue()
  47                    );
  48           re turn;
  49       }
  50  
  51       SetVis n();
  52       unempl oyableVisi bility();
  53       maskPh ones();
  54       setSub mitModeOnS omeAttribu tes();
  55       unatte ndedMVISea rchFromVet eran(_ICN) ;
  56  
  57       var th isOrgUrl =  Xrm.Page. context.ge tClientUrl ();
  58       _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;
  59   }
  60  
  61   function h ideBusines sProcessFl ow() {
  62       var fl ow = Xrm.P age.ui.pro cess;
  63       if (!! flow && fl ow.getVisi ble())
  64           fl ow.setVisi ble(false) ;
  65   }
  66  
  67   function m askPhones( ) {
  68       var ph oneFields  = [
  69                    "ftp _mobilepho ne",
  70                    "ftp _mobilepho ne",
  71                    "ftp _workphone "
  72       ];
  73  
  74       for (v ar i = 0,  l = phoneF ields.leng th; i < l;  i++) {
  75           va r attr = X rm.Page.ge tAttribute (phoneFiel ds[i]);
  76           if  (!!attr)  attr.fireO nChange();
  77       }
  78   }
  79  
  80   function M ask(field,  format) {
  81       //depc recated in  favor of  formatTele phoneNumbe r
  82       return ;
  83       var oC trl = Xrm. Page.getCo ntrol(fiel d);
  84       if (!! oCtrl && o Ctrl.getCo ntrolType( ) == 'stan dard') {
  85           oC trl.setFoc us();
  86           $( "#" + fiel d + "_i"). mask(forma t);
  87           oC trl.blur() ;
  88       }
  89   }
  90  
  91   function f ormatTelep honeNumber (pContext)  {
  92       if (!! pContext)  {
  93           va r changedA ttribute =  pContext. getEventSo urce();
  94           if  (!!change dAttribute ) {
  95                var valu e = change dAttribute .getValue( );
  96                if (!!va lue) {
  97                    var  tempValue  = value.to String().r eplace(/[^ 0-9A-Za-z] /g, "").to UpperCase( );
  98                    if ( tempValue. substr(0,  1) == "1")  tempValue  = tempVal ue.substr( 1, 99);
  99                    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 );
  100                    chan gedAttribu te.setValu e(formatte dValue);
  101                }
  102           }
  103       }
  104   }
  105  
  106   function u nemployabl eVisibilit y() {
  107       Xrm.Pa ge.getCont rol("ftp_u nemployabl e").setVis ible(Xrm.P age.getAtt ribute("ft p_scpercen t").getVal ue() !== n ull);
  108   }
  109  
  110   function s etSubmitMo deOnSomeAt tributes()  {
  111       var fi eldsToSave  = [
  112           "f irstname",
  113           "m iddlename" ,
  114           "l astname",
  115           "f tp_edipi",
  116           "g overnmenti d",
  117           "f tp_dateofb irth",
  118           "f tp_nextofk in",
  119           "f tp_remarks ",
  120           "f tp_primary eligibilit ycode",
  121           "f tp_patient type",
  122           "f tp_service connected" ,
  123           "f tp_scperce nt",
  124           "f tp_unemplo yable",
  125           "f tp_dentali nj",
  126           "f tp_medicat ioncopayme ntexemptio nstatus",
  127           "f tp_copayme ntexemptio nstatus",
  128           "f tp_isinsur ance",
  129           "f tp_mobilep hone",
  130           "f tp_homepho ne",
  131           "f tp_workpho ne"
  132       ];
  133       for (v ar i = 0,  l = fields ToSave.len gth; i < l ; i++) {
  134           va r field =  Xrm.Page.g etAttribut e(fieldsTo Save[i]);
  135           if  (!!field)  field.set SubmitMode ("always") ;
  136       }
  137   }
  138  
  139   function S etVisn() {
  140       ////de bugger;
  141       var fa cilityLook upValue =  Xrm.Page.g etAttribut e("ftp_fac ilityid"). getValue() ;
  142       if (!! facilityLo okupValue)  {
  143           va r columnse t = "ftp_v isnid";
  144           SD K.REST.ret rieveRecor d(
  145                facility LookupValu e[0].id,
  146                "ftp_fac ility",
  147                columnse t,
  148                null,
  149                function  (retrieve dRecord) {
  150                    if ( !!retrieve dRecord &&  !!retriev edRecord.f tp_visnid)  {
  151                         Xrm.Page.g etAttribut e("ftp_vis n").setVal ue(retriev edRecord.f tp_visnid. Name);
  152                         Xrm.Page.g etAttribut e("ftp_vis n").setSub mitMode("a lways");
  153                    }
  154                },
  155                errorHan dler
  156           );
  157       }
  158   }
  159  
  160   function u nattendedM VISearchFr omVeteran( pICN) {
  161       if (!! pICN) {
  162           pe rformExter nalWebServ iceCalls(p ICN);
  163           // *******Cal l function  in Popula tePreferre dFacility  script**** ***
  164           Ge tFacilityF romService (pICN);
  165           // ********** ********** ********** ********** ********** ********** ***
  166       } else  {
  167           // perform MV I search t o get ICN,  then call  performEx ternalWebS erviceCall s() with r etrieved I CN.
  168           va r queryStr ing = "$se lect=*&$fi lter=";
  169           va r firstnam e = Xrm.Pa ge.getAttr ibute("fir stname").g etValue();
  170           va r lastname  = Xrm.Pag e.getAttri bute("last name").get Value();
  171  
  172           va r dobdate  = Xrm.Page .getAttrib ute("ftp_d ateofbirth ").getValu e();
  173           va r dobstrin g = !!dobd ate ? dobd ate : "";
  174  
  175           va r ssn = Xr m.Page.get Attribute( "governmen tid").getV alue();
  176           if  (!!ssn) s sn = ssn.r eplace(/-/ g, "");
  177  
  178           qu eryString  += buildQu eryFilter( "crme_Last Name", las tname, fal se); //ass uming last name will  never be b lank
  179           if  (!!firstn ame)
  180                queryStr ing += bui ldQueryFil ter("crme_ FirstName" , firstnam e, true);
  181           if  (!!ssn)
  182                queryStr ing += bui ldQueryFil ter("crme_ SSN", ssn,  true);
  183           if  (!!dobstr ing)
  184                queryStr ing += " a nd crme_DO BString eq  '" + dobs tring + "' ";
  185           qu eryString  += buildQu eryFilter( "crme_Sear chType", ' SearchByFi lter', tru e);
  186           // set search  type as a ttended (f or now)
  187           qu eryString  += " and c rme_IsAtte nded eq tr ue";
  188  
  189  
  190           // queryStrin g = encode URICompone nt(querySt ring);
  191           va r retrieve dPerson =  null;
  192           va r MVIBadRe sultsText  = "Invalid  results f rom MVI";
  193           SD K.REST.ret rieveMulti pleRecords (
  194                             "crme_ person",
  195                             queryS tring,
  196                             functi on (retrie vedRecords ) {
  197                                 // debugger;
  198                                 if  (!!retrie vedRecords  && retrie vedRecords .length ==  1) {
  199                                      retrieve dPerson =  retrievedR ecords[0];
  200                                 }
  201                                 el se {
  202                                      MVIBadRe sultsText  = "Could n ot determi ne veteran  ICN from  " + retrie vedRecords .length +  " MVI sear ch results .";
  203                                 }
  204                             },
  205                             errorH andler,
  206                             functi on () {
  207                                 // debugger;
  208                                 if  (!!retrie vedPerson)  {
  209                                      // check  for excep tions 1st
  210                                      if ((ret rievedPers on.crme_Ex ceptionOcc ured || !! retrievedP erson.crme _Exception Message)
  211                                                       ||  (!!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. ")
  212                                                       ||  (!!retrie vedPerson. crme_Retur nMessage & & retrieve dPerson.cr me_ReturnM essage ==  "Unknown K ey Identif ier| Unkno wn Key Ide ntifier")
  213                                                       ||  (!!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.")) {
  214                                          var  messageToS how =
  215                                                                !!re trievedPer son.crme_E xceptionMe ssage ? re trievedPer son.crme_E xceptionMe ssage :
  216                                                                !!re trievedPer son.crme_R eturnMessa ge ? retri evedPerson .crme_Retu rnMessage  :
  217                                                                "Unk nown error ";
  218                                          Xrm. Utility.al ertDialog(
  219                                                                "Err or perform ing MVI se arch: \n\n " + messag eToShow +  "\n\nCould  not deter mine veter an sensiti vity.\nThi s session  will now c lose.",
  220                                                                func tion () {
  221                                                                     finishedGe ttingPrima ryCareProv iders = tr ue;
  222                                                                     finishedGe ttingMHTC  = true;
  223                                                                     window.ope n("http:// event/?eve ntname=End SessionOnB adESRCall" );
  224                                                                }
  225                                                       );
  226                                      }
  227                                      else {
  228                                          var  patientMvi Identifier  = retriev edPerson.c rme_Patien tMviIdenti fier == nu ll ? "" :  retrievedP erson.crme _PatientMv iIdentifie r;
  229                                          if ( patientMvi Identifier  != "") {
  230                                               var idpart s = patien tMviIdenti fier.split ("^");
  231  
  232                                               if (idpart s.length >  0) {
  233                                                   var IC N = idpart s[0];
  234                                                   _ICN =  ICN;
  235  
  236                                                   //DO W HATEVER YO U ARE GOIN G TO DO WI TH THE ICN  HERE
  237                                                   perfor mExternalW ebServiceC alls(ICN);
  238                                                   //**** ******Call  function  in Populat ePreferred Facility s cript***** **
  239                                                   GetFac ilityFromS ervice(ICN );
  240                                                   //**** ********** ********** ********** ********** ********** ********** **
  241                                               }
  242                                          }
  243                                      }
  244                                 }
  245                                 el se {
  246                                      Xrm.Util ity.alertD ialog(
  247                                                       MV IBadResult sText + "\ n\nCould n ot determi ne veteran  sensitivi ty.\nThis  session wi ll now clo se.",
  248                                                       fu nction ()  {
  249                                                            Xrm.Page .ui.setFor mNotificat ion(MVIBad ResultsTex t, "INFO",  "MVIBadRe sultsMessa ge");
  250                                                            finished GettingPri maryCarePr oviders =  true;
  251                                                            finished GettingMHT C = true;
  252                                                            window.o pen("http: //event/?e ventname=E ndSessionO nBadESRCal l");
  253                                                       }
  254                                               );
  255                                 }
  256                             }
  257                    );
  258       }
  259   }
  260  
  261   function p erformExte rnalWebSer viceCalls( pICN) {
  262       try {
  263           va r fType =  Xrm.Page.u i.getFormT ype();
  264           if  (!!pICN & & !!fType  && fType >  1) {
  265                //retrie ve Active  Settings r ecord to g et URLs, T HEN perfor m external  web servi ce calls
  266                var quer yString =  "$select=* &$filter=m cs_name eq  'Active S ettings'";
  267                var retr ievedSetti ngs = null ;
  268                SDK.REST .retrieveM ultipleRec ords(
  269                    "mcs _setting",
  270                    quer yString,
  271                    func tion (retr ievedRecor ds) {
  272                         if (!!retr ievedRecor ds && retr ievedRecor ds.length  == 1) retr ievedSetti ngs = retr ievedRecor ds[0];
  273                         writeToCon sole("insi de page ca llback");
  274                    },
  275                    erro rHandler,
  276                    func tion () {
  277  
  278                         if (!!retr ievedSetti ngs) {
  279                             //perf orm ESR we b service  call for d emographic s and sens itivity fl ag
  280                             //perf orm Patien t Summary  web servic e call for  PCMM
  281  
  282                             if (!( retrievedS ettings.ha sOwnProper ty("ftp_DA CURL")) ||  !retrieve dSettings. ftp_DACURL ) {
  283                                 al ert("Could  not find  DAC URL");
  284                                 re turn;
  285                             }
  286                             //ESR
  287                             if (re trievedSet tings.hasO wnProperty ("ftp_ESRA PIURL") &&  !!retriev edSettings .ftp_ESRAP IURL) {
  288                                 va r request  = retrieve dSettings. ftp_DACURL  + retriev edSettings .ftp_ESRAP IURL + "00 0000" + pI CN + "0000 00";
  289                                 va r query =  new XMLHtt pRequest() ;
  290                                 qu ery.open(' GET', requ est, true) ;
  291                                 qu ery.onread ystatechan ge = funct ion () {
  292                                      if (quer y.readySta te == 4 &&  query.sta tus == 200 ) {
  293                                          if ( !query.res ponseXML)  return;
  294                                          var  xml = quer y.response XML;
  295                                          //If  no result s found- c onsider th e vet to b e SENSITIV E
  296                                          if ( xml.childN odes.lengt h > 0 && x ml.childNo des[0].chi ldNodes.le ngth === 0 ) {
  297                                               openSensit iveVeteran WR(pICN, t rue);
  298                                               return;
  299                                          }
  300                                          //Ph ones Drill  down demo graphics>p hones>phon e
  301                                          var  dem = $(xm l).find('d emographic s');
  302                                          var  home = "",
  303                                          work  = "",
  304                                          mobi le = "";
  305                                          if ( !!dem && d em.length  > 0) {
  306                                               telephones  = $(dem). find('phon es');
  307                                               if (teleph ones.lengt h > 0) {
  308                                                   phones  = $(telep hones).fin d('phone') ;
  309                                                   if (ph ones.lengt h > 0) {
  310                                                       $. each(phone s, functio n () {
  311                                                            t = $(th is).find(' type')[0]. textConten t;
  312                                                            num = $( this).find ('phoneNum ber')[0].t extContent ;
  313                                                            if (t ==  'Home') {
  314                                                                home  = num;
  315                                                            }
  316                                                            if (t ==  'Business ') {
  317                                                                work  = num;
  318                                                            }
  319                                                            if (t ==  'Mobile')  {
  320                                                                mobi le = num;
  321                                                            }
  322                                                       }) ;
  323                                                   }
  324                                               }
  325                                          }
  326                                          Xrm. Page.getAt tribute("f tp_homepho ne").setVa lue(home);
  327                                          Xrm. Page.getAt tribute("f tp_homepho ne").setSu bmitMode(' always');
  328                                          Xrm. Page.getAt tribute("f tp_workpho ne").setVa lue(work);
  329                                          Xrm. Page.getAt tribute("f tp_workpho ne").setSu bmitMode(' always');
  330                                          Xrm. Page.getAt tribute("f tp_mobilep hone").set Value(mobi le);
  331                                          Xrm. Page.getAt tribute("f tp_mobilep hone").set SubmitMode ('always') ;
  332  
  333                                          //If  they are  a veteran-  pull that  return
  334                                          var  veteran =  ($(xml).fi nd('vetera n').length  > 0 && $( xml).find( 'veteran') [0].textCo ntent ===  "true");
  335                                          Xrm. Page.getAt tribute("f tp_patient type").set Value(vete ran ? "vet eran" : "N on-Veteran ");
  336                                          Xrm. Page.getAt tribute("f tp_patient type").set SubmitMode ('always') ;
  337  
  338                                          var  disability  = $(xml). find('rate dDisabilit y');
  339                                          var  rDisabilit y = (disab ility.leng th > 0) ?  $(xml).fin d('ratedDi sability') [0].textCo ntent : nu ll;
  340  
  341                                          var  eligibilit yNode = $( xml).find( 'primaryEl igibility' );
  342                                          var  eligibilit y = (eligi bilityNode .length >  0) ? $(eli gibilityNo de).find(' type')[0]. textConten t : null;
  343                                          Xrm. Page.getAt tribute("f tp_primary eligibilit ycode").se tValue(eli gibility);
  344                                          Xrm. Page.getAt tribute("f tp_primary eligibilit ycode").se tSubmitMod e('always' );
  345  
  346                                          var  unemployab leNode = $ (xml).find ('unemploy able');
  347                                          var  unemployab le = (unem ployableNo de.length  > 0) ? une mployableN ode[0].tex tContent :  null;
  348  
  349                                          if ( unemployab le == "tru e") { unem ployable =  "Yes"; }  else { une mployable  = "No"; }
  350                                          Xrm. Page.getAt tribute("f tp_unemplo yable").se tValue(une mployable) ;
  351                                          Xrm. Page.getAt tribute("f tp_unemplo yable").se tSubmitMod e('always' );
  352  
  353  
  354                                          var  svcCINode  = $(xml).f ind('servi ceConnecte dIndicator ');
  355                                          var  svcCI = sv cCINode.le ngth > 0 ?  $(xml).fi nd('servic eConnected Indicator' )[0].textC ontent : " ";
  356                                          Xrm. Page.getAt tribute("f tp_service connected" ).setValue (svcCI ==  "true");
  357                                          Xrm. Page.getAt tribute("f tp_service connected" ).setSubmi tMode('alw ays');
  358  
  359                                          var  percentage  = (svcCI  == "true"  && $(xml). find('serv iceConnect edPercenta ge').lengt h > 0) ? $ (xml).find ('serviceC onnectedPe rcentage') [0].textCo ntent : nu ll;
  360                                          if ( !!percenta ge) {
  361                                               Xrm.Page.g etAttribut e("ftp_scp ercent").s etValue(pe rcentage);
  362                                               Xrm.Page.g etAttribut e("ftp_scp ercent").s etSubmitMo de('always ');
  363                                          }
  364                                          var  sensitivit yFlag = ($ (xml).find ('sensityF lag').leng th > 0) ?  $(xml).fin d('sensity Flag')[0]. textConten t : null;
  365                                          Xrm. Page.getAt tribute("f tp_sensiti veveteran" ).setValue (sensitivi tyFlag ==  "true");
  366                                          Xrm. Page.getAt tribute("f tp_sensiti veveteran" ).setSubmi tMode('alw ays');
  367  
  368                                          var  hasInsuran ce = $(xml ).find('in suranceLis t').length  > 0;
  369                                          Xrm. Page.getAt tribute("f tp_isinsur ance").set Value(hasI nsurance);
  370                                          Xrm. Page.getAt tribute("f tp_isinsur ance").set SubmitMode ('always') ;
  371  
  372                                          //ne xt of kin
  373                                          var  assoc = $( xml).find( 'associati on');
  374                                          if ( assoc.leng th > 0) {
  375                                               $.each(
  376                                                                                                   as soc,
  377                                                                                                   fu nction ()  {
  378                                                                                                        var cTyp e = ($(thi s).find('c ontactType ').length  > 0) ? $(t his).find( 'contactTy pe')[0].te xtContent  : "";
  379                                                                                                        if (cTyp e === "Pri mary Next  of Kin") {
  380                                                                                                            var  nok = ($(t his).find( 'givenName ').length  > 0) ? $(t his).find( 'givenName ')[0].text Content :  "";
  381                                                                                                            nok  = ($(this) .find('mid dleName'). length > 0 ) ? nok.tr im() + " "  + $(this) .find('mid dleName')[ 0].textCon tent : nok .trim();
  382                                                                                                            nok  = ($(this) .find('fam ilyName'). length > 0 ) ? nok.tr im() + " "  + $(this) .find('fam ilyName')[ 0].textCon tent : nok .trim();
  383                                                                                                            nok  = ($(this) .find('rel ationship' ).length >  0) ? nok. trim() + " , " + $(th is).find(' relationsh ip')[0].te xtContent  : nok.trim ();
  384                                                                                                            if ( !!nok) {
  385                                                                                                                 Xrm.Page.g etAttribut e("ftp_nex tofkin").s etValue(no k);
  386                                                                                                                 Xrm.Page.g etAttribut e("ftp_nex tofkin").s etSubmitMo de('always ');
  387                                                                                                            }
  388                                                                                                        }
  389                                                                                                   }
  390                                                                                           );
  391                                          }
  392                                          //ad dresses
  393                                          var  adds = $(x ml).find(' addresses' );
  394                                          if ( adds.lengt h > 0) {
  395                                               add = $(ad ds).find(' address');
  396                                               if (add.le ngth > 0)  {
  397                                                   $.each (
  398                                                       ad d,
  399                                                       fu nction ()  {
  400                                                            var aTyp e = $(this ).find('ad dressTypeC ode').leng th > 0 ? $ (this).fin d('address TypeCode') [0].textCo ntent : "" ;
  401                                                            switch ( aType) {
  402                                                                case  "Permanen t":
  403                                                                     var add1 =  ($(this). find('line 1').length  > 0) ? $( this).find ('line1')[ 0].textCon tent : nul l;
  404                                                                     if (!!add1 )
  405                                                                         Xrm.Pa ge.getAttr ibute("add ress1_line 1").setVal ue(add1);
  406                                                                     Xrm.Page.g etAttribut e("address 1_line1"). setSubmitM ode('alway s');
  407                                                                     var add2 =  ($(this). find('line 2').length  > 0) ? $( this).find ('line2')[ 0].textCon tent : nul l;
  408                                                                     if (!!add2 )
  409                                                                         Xrm.Pa ge.getAttr ibute("add ress1_line 2").setVal ue(add2);
  410                                                                     Xrm.Page.g etAttribut e("address 1_line2"). setSubmitM ode('alway s');
  411                                                                     var add3 =  ($(this). find('line 3').length  > 0) ? $( this).find ('line3')[ 0].textCon tent : nul l;
  412                                                                     if (!!add3 )
  413                                                                         Xrm.Pa ge.getAttr ibute("add ress1_line 3").setVal ue(add3);
  414                                                                     Xrm.Page.g etAttribut e("address 1_line3"). setSubmitM ode('alway s');
  415                                                                     var zip =  ($(this).f ind('zipCo de').lengt h > 0) ? $ (this).fin d('zipCode ')[0].text Content :  null;
  416                                                                     if (!!zip)
  417                                                                         Xrm.Pa ge.getAttr ibute("add ress1_post alcode").s etValue(zi p);
  418                                                                     Xrm.Page.g etAttribut e("address 1_postalco de").setSu bmitMode(' always');
  419                                                                     var state  = ($(this) .find('sta te').lengt h > 0) ? $ (this).fin d('state') [0].textCo ntent : nu ll;
  420                                                                     if (!!stat e)
  421                                                                         Xrm.Pa ge.getAttr ibute("add ress1_stat eorprovinc e").setVal ue(state);
  422                                                                     Xrm.Page.g etAttribut e("address 1_stateorp rovince"). setSubmitM ode('alway s');
  423                                                                     var city =  ($(this). find('city ').length  > 0) ? $(t his).find( 'city')[0] .textConte nt : null;
  424                                                                     if (!!city )
  425                                                                         Xrm.Pa ge.getAttr ibute("add ress1_city ").setValu e(city);
  426                                                                     Xrm.Page.g etAttribut e("address 1_city").s etSubmitMo de('always ');
  427                                                                     var countr y = ($(thi s).find('c ountry').l ength > 0)  ? $(this) .find('cou ntry')[0]. textConten t : null;
  428                                                                     if (!!coun try)
  429                                                                         Xrm.Pa ge.getAttr ibute("add ress1_coun try").setV alue(count ry);
  430                                                                     Xrm.Page.g etAttribut e("address 1_country" ).setSubmi tMode('alw ays');
  431                                                                     break;
  432                                                                case  "Temporar y":
  433                                                                     var addt1  = ($(this) .find('lin e1').lengt h > 0) ? $ (this).fin d('line1') [0].textCo ntent : nu ll;
  434                                                                     if (!!addt 1)
  435                                                                         Xrm.Pa ge.getAttr ibute("add ress2_line 1").setVal ue(addt1);
  436                                                                     Xrm.Page.g etAttribut e("address 2_line1"). setSubmitM ode('alway s');
  437                                                                     var addt2  = ($(this) .find('lin e2').lengt h > 0) ? $ (this).fin d('line2') [0].textCo ntent : nu ll;
  438                                                                     if (!!addt 2)
  439                                                                         Xrm.Pa ge.getAttr ibute("add ress2_line 2").setVal ue(addt2);
  440                                                                     Xrm.Page.g etAttribut e("address 2_line2"). setSubmitM ode('alway s');
  441                                                                     var addt3  = ($(this) .find('lin e3').lengt h > 0) ? $ (this).fin d('line3') [0].textCo ntent : nu ll;
  442                                                                     if (!!addt 3)
  443                                                                         Xrm.Pa ge.getAttr ibute("add ress2_line 3").setVal ue(addt3);
  444                                                                     Xrm.Page.g etAttribut e("address 2_line3"). setSubmitM ode('alway s');
  445                                                                     var tzip =  ($(this). find('zipC ode').leng th > 0) ?  $(this).fi nd('zipCod e')[0].tex tContent :  null;
  446                                                                     if (!!tzip )
  447                                                                         Xrm.Pa ge.getAttr ibute("add ress2_post alcode").s etValue(tz ip);
  448                                                                     Xrm.Page.g etAttribut e("address 2_postalco de").setSu bmitMode(' always');
  449                                                                     var tstate  = ($(this ).find('st ate').leng th > 0) ?  $(this).fi nd('state' )[0].textC ontent : n ull;
  450                                                                     if (!!tsta te)
  451                                                                         Xrm.Pa ge.getAttr ibute("add ress2_stat eorprovinc e").setVal ue(tstate) ;
  452                                                                     Xrm.Page.g etAttribut e("address 2_stateorp rovince"). setSubmitM ode('alway s');
  453                                                                     var tcity  = ($(this) .find('cit y').length  > 0) ? $( this).find ('city')[0 ].textCont ent : null ;
  454                                                                     if (!!tcit y)
  455                                                                         Xrm.Pa ge.getAttr ibute("add ress2_city ").setValu e(tcity);
  456                                                                     Xrm.Page.g etAttribut e("address 2_city").s etSubmitMo de('always ');
  457                                                                     var tcount ry = ($(th is).find(' country'). length > 0 ) ? $(this ).find('co untry')[0] .textConte nt : null;
  458                                                                     if (!!tcou ntry)
  459                                                                         Xrm.Pa ge.getAttr ibute("add ress2_coun try").setV alue(tcoun try);
  460                                                                     Xrm.Page.g etAttribut e("address 2_country" ).setSubmi tMode('alw ays');
  461                                                                     break;
  462                                                                defa ult:
  463                                                            }
  464                                                       }
  465                                                   );
  466                                               }
  467                                          } // end addres ses
  468                                          open SensitiveV eteranWR(p ICN, sensi tivityFlag , home, mo bile, work );
  469                                      } //end  if ESR cal l (query.r eadyState  == 4 && qu ery.status  == 200)
  470                                      else if  (query.rea dyState ==  4 && quer y.status = = 500) {
  471                                          Xrm. Utility.al ertDialog(
  472                                               //"Enrollm ent Servic es is not  responding  at this t ime and ve teran sens itivity ca nnot be de termined.\ n\nYour qu ery: " + r equest + " \n\nThis s ession wil l now clos e.",
  473                                                                                           "Enrollmen t Services  is not re sponding a t this tim e and vete ran sensit ivity cann ot be dete rmined.\n\ nThis sess ion will n ow close." ,
  474                                               function ( ) {
  475                                                   window .open("htt p://event/ ?eventname =EndSessio nOnBadESRC all");
  476                                               }
  477                                          );
  478                                      }
  479                                 };  //end onr eadystatec hange func tion
  480                                 qu ery.send(r equest);
  481                             } //en d if !!ftp _ESRAPIURL
  482                             else {
  483                                 Xr m.Utility. alertDialo g(
  484                                      "Could n ot find ES R API URL. \n\nThis s ession wil l now clos e.",
  485                                      function  () {
  486                                          wind ow.open("h ttp://even t/?eventna me=EndSess ionOnBadES RCall");
  487                                      }
  488                                 );
  489                             }
  490  
  491                             //PCMM  aka Patie nt Summary
  492                             if (re trievedSet tings.hasO wnProperty ("ftp_Pati entSummary APIURL") & & !!retrie vedSetting s.ftp_Pati entSummary APIURL) {
  493                                 if  (_notProd ) {
  494                                      var test FacilityCo de = "987" ;
  495                                      var pcmm Url = retr ievedSetti ngs.ftp_DA CURL + ret rievedSett ings.ftp_P atientSumm aryAPIURL  + testFaci lityCode +  "/" + pIC N + "?idTy pe=ICN";
  496                                      //then,  use facili tyCode and  pICN to g et patient  summary d ata
  497                                      $.get(
  498                                          pcmm Url,
  499                                          func tion (retu rnData, st atus) {
  500                                               if (!!retu rnData) {
  501                                                   if (re turnData.E rrorOccurr ed == true  || return Data.Error Message !=  null || r eturnData. DebugInfo  != null) {
  502                                                       Xr m.Page.ui. setFormNot ification( "Error occ urred retr ieving pat ient summa ry: " + re turnData.D ebugInfo,  "WARNING",  "ESRCallE rror");
  503                                                       // alert("Err or occurre d retrievi ng patient  summary:\ n\n" + ret urnData.Er rorMessage  + "\n\n"  + returnDa ta.DebugIn fo + "\n\n Your query :\n" + pcm mUrl);
  504                                                       fi llFtp_pact IdWithPact Teamlet12( );
  505                                                   } else  {
  506                                                       if  (returnDa ta.hasOwnP roperty("D ata")) {
  507                                                            var data  = returnD ata.Data;
  508                                                            var resu ltsAsText  = data.Pat ientSummar yText;
  509                                                            if (resu ltsAsText. trim() ==  "No PACT a ssigned at  any VA lo cation.")  {
  510                                                                PCMM GridMember s.push({ N ame: resul tsAsText.t rim(), Tea mRoleName:  "" });
  511                                                                fill Ftp_pactId WithPactTe amlet12();  //do this  here, too ?
  512  
  513                                                            } else i f (data.ha sOwnProper ty("patien tAssignmen ts") && da ta.patient Assignment s.length >  0) {
  514                                                                var  patientAss ignment =  data.patie ntAssignme nts[0];
  515                                                                proc essPCHBAss ignment(pa tientAssig nment);
  516                                                                proc essMentalH ealthProvi der(patien tAssignmen t);
  517                                                            } else {
  518                                                                //if  we don't  find ANY p atientAssi gnments an d also don 't have a  "no result s message" , just ass ign defaul t Pact Tea mlet 12, s o some kin d of assig nment can  happen
  519                                                                fill Ftp_pactId WithPactTe amlet12();
  520                                                            }
  521                                                       }
  522                                                   }
  523                                               } else {
  524                                                   fillFt p_pactIdWi thPactTeam let12();
  525                                               }
  526                                          }
  527                                      );
  528                                 }
  529                                 el se {
  530                                      //get fa cility cod e first
  531                                      var faci lityAttr =  Xrm.Page. getAttribu te("ftp_fa cilityid") ;
  532                                      var faci lityValue  = !!facili tyAttr ? f acilityAtt r.getValue () : null;
  533                                      if (!!fa cilityValu e) {
  534                                          var  columnset  = "ftp_fac ilitycode" ;
  535                                          SDK. REST.retri eveRecord(
  536                                               facilityVa lue[0].id,
  537                                               "ftp_facil ity",
  538                                               columnset,
  539                                               null,
  540                                               function ( retrievedR ecord) {
  541                                                   //if ( !!retrieve dRecord &&  !!retriev edRecord.f tp_facilit ycode) {
  542                                                   var fa cilityCode  = retriev edRecord.f tp_facilit ycode;
  543                                                   var pc mmUrl = re trievedSet tings.ftp_ DACURL + r etrievedSe ttings.ftp _PatientSu mmaryAPIUR L + facili tyCode + " /" + pICN  + "?idType =ICN";
  544  
  545                                                   //then , use faci lityCode a nd pICN to  get patie nt summary  data
  546                                                   $.get(
  547                                                       pc mmUrl,
  548                                                       fu nction (re turnData,  status) {
  549                                                            if (!!re turnData)  {
  550                                                                if ( returnData .ErrorOccu rred == tr ue || retu rnData.Err orMessage  != null ||  returnDat a.DebugInf o != null)  {
  551                                                                     Xrm.Page.u i.setFormN otificatio n("Error o ccurred re trieving p atient sum mary: " +  returnData .DebugInfo , "WARNING ", "ESRCal lError");
  552                                                                     //alert("E rror occur red retrie ving patie nt summary :\n\n" + r eturnData. ErrorMessa ge + "\n\n " + return Data.Debug Info + "\n \nYour que ry:\n" + p cmmUrl);
  553                                                                     fillFtp_pa ctIdWithPa ctTeamlet1 2();
  554                                                                } el se {
  555                                                                     if (return Data.hasOw nProperty( "Data")) {
  556                                                                         var da ta = retur nData.Data ;
  557                                                                         if (da ta.hasOwnP roperty("p atientAssi gnments")  && data.pa tientAssig nments.len gth > 0) {
  558                                                                             va r patientA ssignment  = data.pat ientAssign ments[0];
  559                                                                             pr ocessPCHBA ssignment( patientAss ignment);
  560                                                                             pr ocessMenta lHealthPro vider(pati entAssignm ent);
  561                                                                         }
  562                                                                         else {
  563                                                                             // if we don' t find ANY  patientAs signments,  just assi gn default  Pact Team let 12, so  some kind  of assign ment can h appen
  564                                                                             fi llFtp_pact IdWithPact Teamlet12( );
  565                                                                         }
  566                                                                     }
  567                                                                }
  568                                                            } else {
  569                                                                fill Ftp_pactId WithPactTe amlet12();
  570                                                            }
  571                                                       }
  572                                                   );
  573                                                   //}//e nd if !!fa cilityCode
  574                                               },
  575                                               errorHandl er
  576                                          );
  577                                      } //end  if !!facil ityValue
  578                                 }
  579                             } //en d if !!ftp _PatientSu mmaryAPIUR L
  580                             else {
  581                                 // alert("Cou ld not fin d Patient  Summary AP I URL");
  582                             }
  583                         } //end if  !!retriev edSettings
  584                         else {
  585                             Xrm.Ut ility.aler tDialog(
  586                                                                "Cou ld not fin d Active S ettings fo r this org ; contact  your syste m administ rator.\n\n This sessi on will no w close.",
  587                                                                func tion () {
  588                                                                     window.ope n("http:// event/?eve ntname=End SessionOnB adESRCall" );
  589                                                                }
  590                                                       );
  591                         }
  592                    } // end active  settings  retrieval  complete c allback
  593                );//end  active set tings quer y
  594           }  //end if ( !!pICN &&  !!fType &&  fType > 1 )
  595           el se if (!pI CN && !!fT ype && fTy pe > 1) {  //without  an id, ass ume sensit ivity=true
  596                openSens itiveVeter anWR(pICN,  true);
  597                return;
  598           }
  599           el se {
  600                //if (wi ndow.IsUSD ) {
  601                if (loca tion.href. indexOf("O utlook15Wh ite") != - 1) {
  602                    //US D Session
  603                    wind ow.open("h ttp://even t/?eventna me=New Vet &lastname= " + Xrm.Pa ge.getAttr ibute("las tname").ge tValue());
  604                }
  605                return;
  606           }
  607       }
  608       catch  (e) {
  609           al ert(e);
  610       }
  611   }
  612  
  613   function o penSensiti veVeteranW R(pICN, pS ensitivity , pHomepho ne, pMobil ephone, pW orkphone)  {
  614       if (!! pICN && pS ensitivity  != null)  {
  615           // fire USD e vent to co py some fi elds to co ntext
  616           // if(window. IsUSD){
  617           if  (location .href.inde xOf("Outlo ok15White" ) != -1) {
  618                var even tUrl = "ht tp://event /?eventnam e=Shared S et Veteran  Fields";
  619                eventUrl  += "&vete ranid=" +  pICN;
  620                eventUrl  += "&nati onalid=" +  pICN.slic e(0, 10);  //this is  the ID use d to query  the Patie nt Flags A PI
  621                eventUrl  += "&sens itivity="  + pSensiti vity.toStr ing(); //b oolean
  622                eventUrl  += !!pHom ephone ? " &homephone =" + pHome phone : "" ;
  623                eventUrl  += !!pMob ilephone ?  "&mobilep hone=" + p Mobilephon e : "";
  624                eventUrl  += !!pWor kphone ? " &workfphon e=" + pWor kphone : " ";
  625                window.o pen(eventU rl);
  626           }
  627  
  628           // a USD wind ow navigat ion rule w ill route  this to th e Shared S ensitive V eteran hos ted contro l
  629           // the PageLo adComplete  event of  that hoste d control  will deter mine wheth er or not  to SHOW th e tab in U SD
  630           // the parame ters we're  passing t o it are r equired fo r logging  the user's  Yes/No de cision to  continue w hen it is  a sensitiv e veteran
  631           va r paramete rs = "cont actid=" +  Xrm.Page.d ata.entity .getId()
  632                             + "&fu llname=" +  Xrm.Page. data.entit y.getPrima ryAttribut eValue()
  633                             + "&se nsitivity= " + pSensi tivity.toS tring()
  634                             + "&IC N=" + pICN
  635                             //+ "& IsUSD=" +  (window.Is USD ? "tru e" : "fals e");
  636                             + "&Is USD=" + (l ocation.hr ef.indexOf ("Outlook1 5White") ! = -1 ? "tr ue" : "fal se");
  637           pa rameters + = !!pHomep hone ? "&h omephone="  + pHomeph one : "";
  638           pa rameters + = !!pMobil ephone ? " &mobilepho ne=" + pMo bilephone  : "";
  639           pa rameters + = !!pWorkp hone ? "&w orkfphone= " + pWorkp hone : "";
  640           Xr m.Utility. openWebRes ource("ftp _/Veteran/ SensitiveV eteran.htm l", encode URICompone nt(paramet ers));
  641       }
  642   }
  643  
  644   function p erformPCMM WebService Call(pActi veSettings ) {
  645       //not  yet implem ented
  646   }
  647  
  648   function p rocessPCHB Assignment (pPatientA ssignment)  {
  649       if (!p PatientAss ignment) {
  650           fi nishedGett ingPrimary CareProvid ers = true ;
  651           re turn;
  652       }
  653       var te amName = " ";
  654       var te amMembersF romEESumma ry = []; / /empty arr ay intende d to hold  objects of  schema {  Name, Team RoleName }
  655       if (pP atientAssi gnment.has OwnPropert y("primary CareAssign ments") &&  pPatientA ssignment. primaryCar eAssignmen ts.length  > 0) {
  656           va r pcAssign ment = pPa tientAssig nment.prim aryCareAss ignments[0 ];
  657           te amName = p cAssignmen t.teamName ;
  658           if  (pcAssign ment.hasOw nProperty( "teamletMe mbers") &&  pcAssignm ent.teamle tMembers.l ength > 0)  {
  659                for (var  i = 0, l  = pcAssign ment.teaml etMembers. length; i  < l; i++)  {
  660                    var  thisTeamle tMember =  pcAssignme nt.teamlet Members[i] ;
  661                    if ( thisTeamle tMember.ha sOwnProper ty("StaffC ontact") & & !!thisTe amletMembe r.StaffCon tact) {
  662                         var sc = t hisTeamlet Member.Sta ffContact;
  663                         if (sc.has OwnPropert y("Name")  && !!sc.Na me) {
  664                             var pe rson = { N ame: sc.Na me, TeamRo leName: sc .TeamRoleN ame };
  665                             teamMe mbersFromE ESummary.p ush(person );
  666                             PCMMGr idMembers. push(perso n);
  667                         }
  668                    }
  669                }
  670                finished GettingPri maryCarePr oviders =  true;
  671           }  else {
  672                finished GettingPri maryCarePr oviders =  true;
  673           }
  674       } else  if (pPati entAssignm ent.hasOwn Property(" primaryCar eHBPCAssig nments") & & pPatient Assignment .primaryCa reHBPCAssi gnments.le ngth > 0)  {
  675           va r homeboun dPCAssignm ent = pPat ientAssign ment.prima ryCareHBPC Assignment s[0];
  676           te amName = h omeboundPC Assignment .teamName;
  677           if  (homeboun dPCAssignm ent.hasOwn Property(" teamMember s") && hom eboundPCAs signment.t eamMembers .length >  0) {
  678                for (var  i = 0, l  = homeboun dPCAssignm ent.teamMe mbers.leng th; i < l;  i++) {
  679                    var  thisTeamMe mber = hom eboundPCAs signment.t eamMembers [i];
  680                    if ( thisTeamMe mber.hasOw nProperty( "Name") &&  !!thisTea mMember.Na me) {
  681                         var person  = { Name:  thisTeamM ember.Name , TeamRole Name: this TeamMember .TeamRoleN ame };
  682                         teamMember sFromEESum mary.push( person);
  683                         PCMMGridMe mbers.push (person);
  684                    }
  685                }
  686                finished GettingPri maryCarePr oviders =  true;
  687           }  else {
  688                finished GettingPri maryCarePr oviders =  true;
  689           }
  690       } else  {
  691           fi nishedGett ingPrimary CareProvid ers = true ;
  692       }
  693       //can  add more e lse if sta tements he re for oth er care as signment t ypes
  694  
  695       if (!! teamName)  {
  696           // find or cr eate a PAC T team rec ord called  named <te amName>
  697           va r retrieve dPACTTeams  = [];
  698           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" ;
  699           SD K.REST.ret rieveMulti pleRecords (
  700                "ftp_pac t",
  701                queryStr ing,
  702                function  (retrieve dRecords)  {
  703                    if ( !!retrieve dRecords)  retrievedP ACTTeams =  retrieved PACTTeams. concat(ret rievedReco rds);
  704                },
  705                errorHan dler,
  706                function  () {
  707                    if ( retrievedP ACTTeams.l ength > 0)  {
  708                         matchPCTea mMembersTo PACTTeam(r etrievedPA CTTeams[0] , teamMemb ersFromEES ummary);
  709                    } el se {
  710                         var newPac t = {
  711                             ftp_na me: teamNa me
  712                         };
  713                         SDK.REST.c reateRecor d(
  714                             newPac t,
  715                             "ftp_p act",
  716                             functi on (create dPACTTeam)  {
  717                                 ma tchPCTeamM embersToPA CTTeam(cre atedPACTTe am, teamMe mbersFromE ESummary);
  718                             },
  719                             errorH andler
  720                         );
  721                    }
  722                });
  723       } else  {
  724           // 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
  725           fi llFtp_pact IdWithPact Teamlet12( );
  726       }
  727   }
  728  
  729   function p rocessMent alHealthPr ovider(pPa tientAssig nment) {
  730       if (!p PatientAss ignment) {
  731           fi nishedGett ingMHTC =  true;
  732           re turn;
  733       }
  734       if (pP atientAssi gnment.has OwnPropert y("mentalH ealthAssig nments") & & !!pPatie ntAssignme nt.mentalH ealthAssig nment && A rray.isArr ay(pPatien tAssignmen t.mentalHe althAssign ments) &&  pPatientAs signment.m entalHealt hAssignmen ts.length  > 0) {
  735           va r mentalHe althAssign ment = pPa tientAssig nment.ment alHealthAs signments[ 0];
  736           if  (mentalHe althAssign ment.hasOw nProperty( "teamName" ) && !!men talHealthA ssignment. teamName)  {
  737                var team Name = men talHealthA ssignment. teamName;
  738                if (ment alHealthAs signment.h asOwnPrope rty("menta lHealthTre atmentCoor d") && !!m entalHealt hAssignmen t.mentalHe althTreatm entCoord)  {
  739                    var  MHTC = men talHealthA ssignment. mentalHeal thTreatmen tCoord;
  740                    PCMM GridMember s.push(MHT C);
  741                    fini shedGettin gMHTC = tr ue;
  742  
  743                    //fi nd or crea te the PAC T Team rec ord matchi ng teamNam e
  744                    //ac cording to  Jeff, thi s should h appen
  745                    if ( !!teamName ) {
  746                         //find or  create a P ACT team r ecord call ed named < teamName>
  747                         var retrie vedPACTTea ms = [];
  748                         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_ftp_pa ct_systemu ser/System UserId";
  749                         SDK.REST.r etrieveMul tipleRecor ds(
  750                             "ftp_p act",
  751                             queryS tring,
  752                             functi on (retrie vedRecords ) {
  753                                 if  (!!retrie vedRecord)
  754                                      retrieve dPACTTeams  = retriev edPACTTeam s.concat(r etrievedRe cords);
  755                             },
  756                             errorH andler,
  757                             functi on () {
  758                                 if  (retrieve dPACTTeams .length >  0) {
  759                                      matchMHT CToPACTTea m(retrieve dPACTTeams [0], MHTC) ;
  760                                 }  else {
  761                                      var newP act = {
  762                                          ftp_ name: team Name
  763                                      };
  764                                      SDK.REST .createRec ord(
  765                                          newP act,
  766                                          "ftp _pact",
  767                                          func tion (crea tedPACTTea m) {
  768                                               matchMHTCT oPACTTeam( createdPAC TTeam, MHT C);
  769                                          },
  770                                          erro rHandler
  771                                      );
  772                                 }
  773                             }
  774                         );
  775                    }
  776                } else {
  777                    fini shedGettin gMHTC = tr ue;
  778                }
  779           }  else {
  780                finished GettingMHT C = true;
  781           }
  782       }
  783       else {
  784           fi nishedGett ingMHTC =  true;
  785       }
  786   }
  787  
  788   function m atchPCTeam MembersToP ACTTeam(pP ACTTeam, p PACTTeamMe mbersToAdd ) {
  789       if (!p PACTTeam)
  790           re turn;
  791       //firs t fill the  ftp_pacti d lookup f ield on th e vet form
  792       Xrm.Pa ge.getAttr ibute("ftp _pactid"). setValue([ {
  793           id : pPACTTea m.ftp_pact Id,
  794           na me: pPACTT eam.ftp_na me,
  795           en tityType:  "ftp_pact"
  796       }
  797       ]);
  798  
  799       Xrm.Pa ge.getAttr ibute("ftp _pactid"). addOnChang e(ftp_pact id_onChang e);
  800  
  801       //save  to an arr ay the cur rent list  of users w ho current ly referen ce pPACTTe am
  802       var us ersToUpdat e = [];
  803       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)  {
  804           fo r (var i =  0, l = pP ACTTeam.ft p_ftp_pact _systemuse r.results. length; i  < l; i++)  {
  805                usersToU pdate.push (pPACTTeam .ftp_ftp_p act_system user.resul ts[i]);
  806           }
  807       }
  808  
  809       if (pP ACTTeamMem bersToAdd. length > 0 ) {
  810           // get "PACT  User" team  GUID, the n process  pPACTTeamM embersToAd d, creatin g new user s where ne cessary
  811           va r queryStr ing = "$se lect=Name, TeamId,Bus inessUnitI d&$filter= Name eq 'P ACT User'  and TeamTy pe/Value e q 0";
  812           va r retrieve dCRMTeams  = [];
  813           SD K.REST.ret rieveMulti pleRecords (
  814           "T eam",
  815           qu eryString,
  816           fu nction (re trievedRec ords) {
  817                if (!!re trievedRec ords)
  818                    retr ievedCRMTe ams = retr ievedCRMTe ams.concat (retrieved Records);
  819           },
  820           er rorHandler ,
  821           fu nction ()  {
  822                if (retr ievedCRMTe ams.length  > 0) {
  823                    var  PACTUserCR MTeam = re trievedCRM Teams[0];
  824  
  825                    //cy cle throug h pPACTTea mMembersTo Add: find/ create eac h systemus er and
  826                    //se t its ftp_ pactid loo kup field  to pPACTTe am and ftp _PACTTeamR ole to thi sMember.Te amRoleName
  827                    //ad d it to th e 'PACT Us er' CRM te am, so it  will inher it securit y roles
  828                    //if  we find a  matching  systemuser  from pPAC TTeamMembe rsToAdd an d their ft p_PACTId a nd ftp_PAC TTeamRole  are fine
  829                    //re move that  person fro m usersToU pdate arra y
  830                    //af ter the la st member  of pPACTTe amMembersT oAdd, proc ess usersT oUpdate, c learing ea ch record' s ftp_PACT Id field
  831  
  832                    var  alreadySet PrimaryCar eProviderF ield = fal se;
  833                    for  (var i = 0 , l = pPAC TTeamMembe rsToAdd.le ngth; i <  l; i++) {
  834                         var thisMe mber = pPA CTTeamMemb ersToAdd[i ];
  835                         var splitN ame = this Member.Nam e.split(", ");
  836                         var lastNa me = split Name[0];
  837                         var splitF irstMiddle Names = sp litName.le ngth > 1 ?  splitName [1].split( " ") : "";
  838                         var firstN ame = !!sp litFirstMi ddleNames  ? splitFir stMiddleNa mes[0] : " ";
  839                         var middle Name = !!s plitFirstM iddleNames  && splitF irstMiddle Names.leng th > 1 ? s plitFirstM iddleNames [1] : "";
  840                         var fakeFu llName = l astName +  ", " + fir stName + "  " + middl eName;
  841                         var queryS tring = "$ select=Fir stName,Las tName,Syst emUserId,f tp_PACTId, ftp_PACTTe amRole&$fi lter=First Name eq '"  + firstNa me + "' an d LastName  eq '" + l astName +  "' and IsD isabled eq  false";
  842                         var retrie vedUsers =  [];
  843                         SDK.REST.r etrieveMul tipleRecor ds(
  844                         "SystemUse r",
  845                         queryStrin g,
  846                         function ( retrievedR ecords) {
  847                             if (!! retrievedR ecords)
  848                                 re trievedUse rs = retri evedUsers. concat(ret rievedReco rds);
  849                         },
  850                         errorHandl er,
  851                         function ( ) {
  852                             if (re trievedUse rs.length  > 0) {
  853                                 va r foundUse r = retrie vedUsers[0 ];
  854                                 if  (foundUse r.hasOwnPr operty("ft p_PACTId")  && !!foun dUser.ftp_ PACTId &&  foundUser. ftp_PACTId .Id == pPA CTTeam.ftp _pactId &&
  855                                                   foundU ser.hasOwn Property(" ftp_PACTTe amRole") & & foundUse r.ftp_PACT TeamRole = = thisMemb er.TeamRol eName) {
  856                                      //remove  this pers on from th e usersToU pdate arra y, because  their ftp _PACTId an d ftp_PACT TeamRole a re already  fine
  857                                      usersToU pdate.spli ce(i, 1);
  858                                      if (!alr eadySetPri maryCarePr oviderFiel d)
  859                                          alre adySetPrim aryCarePro viderField  = setPrim aryCarePro viderField (foundUser );
  860                                      if (i ==  l - 1)
  861                                          unli nkOldPACTT eamMembers (usersToUp date);
  862                                 }  else {
  863                                      foundUse r.ftp_PACT Id = {
  864                                          Id:  pPACTTeam. ftp_pactId ,
  865                                          Logi calName: " ftp_pact",
  866                                          Name : pPACTTea m.ftp_name
  867                                      };
  868                                      foundUse r.ftp_PACT TeamRole =  thisMembe r.TeamRole Name;
  869                                      SDK.REST .updateRec ord(
  870                                          foun dUser.Syst emUserId,
  871                                          foun dUser,
  872                                          "Sys temUser",
  873                                          func tion () {
  874                                               if (!alrea dySetPrima ryCareProv iderField)
  875                                                   alread ySetPrimar yCareProvi derField =  setPrimar yCareProvi derField(f oundUser);
  876                                               if (i == l  - 1)
  877                                                   unlink OldPACTTea mMembers(u sersToUpda te);
  878                                          },
  879                                          erro rHandler
  880                                      );
  881                                 }
  882                             } else  {
  883                                 // build user  object
  884                                 va r newUser  = {
  885                                      FirstNam e: firstNa me,
  886                                      LastName : lastName ,
  887                                      MiddleNa me: middle Name,
  888                                      ftp_PACT TeamRole:  thisMember .TeamRoleN ame,
  889                                      IsIntegr ationUser:  false,
  890                                      UserLice nseType: 3 ,
  891                                      AccessMo de: {
  892                                          Valu e: 0
  893                                      },
  894                                        DomainName : firstNam e + "." +  lastName +  "@nodomai naccount. DNS     ",
  895                                      Business UnitId: {
  896                                          Id:  PACTUserCR MTeam.Busi nessUnitId .Id,
  897                                          Logi calName: P ACTUserCRM Team.Busin essUnitId. LogicalNam e,
  898                                          Name : PACTUser CRMTeam.Bu sinessUnit Id.Name
  899                                      },
  900                                      ftp_PACT Id: {
  901                                          Id:  pPACTTeam. ftp_pactId ,
  902                                          Logi calName: " ftp_pact",
  903                                          Name : pPACTTea m.ftp_name
  904                                      }
  905                                 };
  906                                 // create it
  907                                 SD K.REST.cre ateRecord(
  908                                      newUser,
  909                                      "SystemU ser",
  910                                      function  (createdU ser) {
  911                                          crea tedUser.Fu llName = f akeFullNam e;
  912                                          if ( !alreadySe tPrimaryCa reProvider Field)
  913                                               alreadySet PrimaryCar eProviderF ield = set PrimaryCar eProviderF ield(creat edUser);
  914                                          addU sersToTeam (createdUs er.SystemU serId, PAC TUserCRMTe am.TeamId) ;
  915                                          if ( i == l - 1 )
  916                                               unlinkOldP ACTTeamMem bers(users ToUpdate);
  917                                      },
  918                                      errorHan dler
  919                                 );
  920                             }
  921                         });
  922                    } // end for-lo op through  pPACTTeam MembersToA dd
  923                }
  924           }) ;
  925       } //en d if pPACT TeamMember sToAdd.len gth > 0
  926       else {
  927           // even if we  don't lin k any user s to pPACT Team for t he first t ime, still  need to u nlink "old " members  of pPACTTe am
  928           un linkOldPAC TTeamMembe rs(usersTo Update);
  929       }
  930   }
  931  
  932   function s etPrimaryC areProvide rField(pUs er) {
  933       if (!p User || !p User.ftp_P ACTTeamRol e || !pUse r.FullName ) return f alse;
  934       if (!( pUser.ftp_ PACTTeamRo le == "Pri mary Care  Provider"  || pUser.f tp_PACTTea mRole == " Associate  Provider") ) return f alse;
  935  
  936       Xrm.Pa ge.getAttr ibute("ftp _primaryca reprovider ").setValu e(pUser.Fu llName);
  937       Xrm.Pa ge.getAttr ibute("ftp _primaryca reprovider ").setSubm itMode("al ways");
  938       return  true;
  939   }
  940  
  941   function m atchMHTCTo PACTTeam(p PACTTeam,  pMHTC) {
  942       if (!p PACTTeam)
  943           re turn;
  944       //don' t set the  ftp_pactid  lookup fi eld on the  vet form
  945  
  946       //save  to an arr ay the cur rent list  of users w ho current ly referen ce pPACTTe am (for a  mental hea lth PACT t eam...it s hould just  be one us er)
  947       var us ersToUpdat e = [];
  948       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)  {
  949           fo r (var i =  0, l = pP ACTTeam.ft p_ftp_pact _systemuse r.results. length; i  < l; i++)  {
  950                usersToU pdate.push (pPACTTeam .ftp_ftp_p act_system user.resul ts[i]);
  951           }
  952       }
  953  
  954       if (!! pMHTC) {
  955           va r queryStr ing = "$se lect=Name, TeamId,Bus inessUnitI d&$filter= Name eq 'P ACT User'  and TeamTy pe/Value e q 0";
  956           va r retrieve dCRMTeams  = [];
  957           SD K.REST.ret rieveMulti pleRecords (
  958           "T eam",
  959           qu eryString,
  960           fu nction (re trievedRec ords) {
  961                if (!!re trievedRec ords)
  962                    retr ievedCRMTe ams = retr ievedCRMTe ams.concat (retrieved Records);
  963           },
  964           er rorHandler ,
  965           fu nction ()  {
  966                if (retr ievedCRMTe ams.length  > 0) {
  967                    var  PACTUserCR MTeam = re trievedCRM Teams[0];
  968  
  969                    //fi nd or crea te a syste muser for  pMHTC
  970                    //se t its ftp_ pactid loo kup field  to pPACTTe am
  971                    //ad d it to th e 'PACT Us er' CRM te am, so it  will inher it securit y roles
  972                    //if  their ftp _PACTId an d ftp_PACT TeamRole a re fine
  973                    //re move that  person fro m usersToU pdate arra y
  974  
  975                    //pM HTC schema : { Name,  TeamRoleNa me, TeamRo leCode, Ph one, Page,  Ien }
  976  
  977                    var  splitName  = pMHTC.Na me.split(" ,");
  978                    var  lastName =  splitName [0];
  979                    var  splitFirst MiddleName s = splitN ame.length  > 1 ? spl itName[1]. split(" ")  : "";
  980                    var  firstName  = !!splitF irstMiddle Names ? sp litFirstMi ddleNames[ 0] : "";
  981                    var  middleName  = !!split FirstMiddl eNames &&  splitFirst MiddleName s.length >  1 ? split FirstMiddl eNames[1]  : "";
  982                    var  queryStrin g = "$sele ct=FirstNa me,LastNam e,SystemUs erId,ftp_P ACTId,ftp_ PACTTeamRo le&$filter =FirstName  eq '" + f istName +  "' and Las tName eq ' " + lastNa me + "' an d IsDisabl ed eq fals e";
  983                    var  retrievedU sers = [];
  984                    SDK. REST.retri eveMultipl eRecords(
  985                         "SystemUse r",
  986                         queryStrin g,
  987                         function ( retrievedR ecords) {
  988                             if (!! retrievedR ecords)
  989                                 re trievedUse rs = retri evedUsers. concat(ret rievedReco rds);
  990                         },
  991                         errorHandl er,
  992                         function ( ) {
  993                             if (re trievedUse rs.length  > 0) {
  994                                 va r foundUse r = retrie vedUsers[0 ];
  995                                 if  (foundUse r.hasOwnPr operty("ft p_PACTId")  && !!foun dUser.ftp_ PACTId &&  foundUser. ftp_PACTId .Id == pPA CTTeam.ftp _pactId &&
  996                                                   foundU ser.hasOwn Property(" ftp_PACTTe amRole") & & foundUse r.ftp_PACT TeamRole = = pMHTC.Te amRoleName ) {
  997                                      //remove  this pers on from th e usersToU pdate arra y, because  their ftp _PACTId an d ftp_PACT TeamRole a re already  fine
  998                                      usersToU pdate.spli ce(i, 1);
  999                                      setMenta lHealthTea mField(fou ndUser);
  1000                                 }  else {
  1001                                      foundUse r.ftp_PACT Id = {
  1002                                          Id:  pPACTTeam. ftp_pactId ,
  1003                                          Logi calName: " ftp_pact",
  1004                                          Name : pPACTTea m.ftp_name
  1005                                      };
  1006                                      foundUse r.ftp_PACT TeamRole =  pMHTC.Tea mRoleName;
  1007                                      SDK.REST .updateRec ord(
  1008                                          foun dUser.Syst emUserId,
  1009                                          foun dUser,
  1010                                          "Sys temUser",
  1011                                          func tion () {
  1012                                               setMentalH ealthTeamF ield(found User);
  1013                                          },
  1014                                          erro rHandler
  1015                                      );
  1016                                 }
  1017                             } else  {
  1018                                 // build user  object
  1019                                 va r newUser  = {
  1020                                      FirstNam e: firstNa me,
  1021                                      LastName : lastName ,
  1022                                      MiddleNa me: middle Name,
  1023                                      ftp_PACT TeamRole:  pMHTC.Team RoleName,
  1024                                      IsIntegr ationUser:  false,
  1025                                      UserLice nseType: 3 ,
  1026                                      AccessMo de: {
  1027                                          Valu e: 0
  1028                                      },
  1029                                        DomainName : firstNam e + "." +  lastName +  "@nodomai naccount. DNS     ",
  1030                                      Business UnitId: {
  1031                                          Id:  PACTUserCR MTeam.Busi nessUnitId .Id,
  1032                                          Logi calName: P ACTUserCRM Team.Busin essUnitId. LogicalNam e,
  1033                                          Name : PACTUser CRMTeam.Bu sinessUnit Id.Name
  1034                                      },
  1035                                      ftp_PACT Id: {
  1036                                          Id:  pPACTTeam. ftp_pactId ,
  1037                                          Logi calName: " ftp_pact",
  1038                                          Name : pPACTTea m.ftp_name
  1039                                      }
  1040                                 };
  1041                                 // create it
  1042                                 SD K.REST.cre ateRecord(
  1043                                      newUser,
  1044                                      "SystemU ser",
  1045                                      function  (createdU ser) {
  1046                                          setM entalHealt hTeamField (createdUs er);
  1047                                          addU sersToTeam (createdUs er.SystemU serId, PAC TUserCRMTe am.TeamId) ;
  1048                                      },
  1049                                      errorHan dler
  1050                                 );
  1051                             }
  1052                         }
  1053                    );
  1054                }
  1055           }) ;
  1056       } else  {
  1057           // 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
  1058           un linkOldPAC TTeamMembe rs(usersTo Update);
  1059       }
  1060   }
  1061  
  1062   function s etMentalHe althTeamFi eld(pUser)  {
  1063       if (!! pUser && ! !pUser.ftp _PACTTeamR ole && !!p User.FullN ame) {
  1064           if  (pUser.ft p_PACTTeam Role == "( mhtc) Addi ction Ther apist") {
  1065                Xrm.Page .getAttrib ute("ftp_m entalhealt hteam").se tValue(pUs er.FullNam e);
  1066                Xrm.Page .getAttrib ute("ftp_m entalhealt hteam").se tSubmitMod e("always" );
  1067           }
  1068       }
  1069   }
  1070  
  1071   function a ddUsersToT eam(pUserI ds, pTeamI d) {
  1072       var se rviceURL =  Xrm.Page. context.ge tClientUrl () + "/XRM Services/2 011/Organi zation.svc /web";
  1073       var re questMain  = "";
  1074       reques tMain += " <s:Envelop e xmlns:s= \"http://s chemas.xml soap.org/s oap/envelo pe/\">";
  1075       reques tMain += "   <s:Body> ";
  1076       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\">";
  1077       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\"> ";
  1078       reques tMain += "         <a :Parameter s xmlns:c= \"http://s chemas.dat acontract. org/2004/0 7/System.C ollections .Generic\" >";
  1079       reques tMain += "            <a:KeyValu ePairOfstr inganyType >";
  1080       reques tMain += "              <c:key>T eamId</c:k ey>";
  1081       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>";
  1082       reques tMain += "            </a:KeyVal uePairOfst ringanyTyp e>";
  1083       reques tMain += "            <a:KeyValu ePairOfstr inganyType >";
  1084       reques tMain += "              <c:key>M emberIds</ c:key>";
  1085       reques tMain += "              <c:value  i:type=\" d:ArrayOfg uid\" xmln s:d=\"http ://schemas .microsoft .com/2003/ 10/Seriali zation/Arr ays\">";
  1086       if (Ar ray.isArra y(pUserIds )) {
  1087           fo r (var i =  0, l = pU serIds.len gth; i < l ; i++) {
  1088                requestM ain += "                <d:guid> " + pUserI ds[i] + "< /d:guid>";
  1089           }
  1090       } else  {
  1091           re questMain  += "               <d :guid>" +  pUserIds +  "</d:guid >";
  1092       }
  1093       reques tMain += "              </c:valu e>";
  1094       reques tMain += "            </a:KeyVal uePairOfst ringanyTyp e>";
  1095       reques tMain += "         </ a:Paramete rs>";
  1096       reques tMain += "         <a :RequestId  i:nil=\"t rue\" />";
  1097       reques tMain += "         <a :RequestNa me>AddMemb ersTeam</a :RequestNa me>";
  1098       reques tMain += "       </re quest>";
  1099       reques tMain += "     </Exec ute>";
  1100       reques tMain += "   </s:Body >";
  1101       reques tMain += " </s:Envelo pe>";
  1102       var re q = new XM LHttpReque st();
  1103       req.op en("POST",  serviceUR L, true);
  1104       // Res ponses wil l return X ML. It isn 't possibl e to retur n JSON.
  1105       req.se tRequestHe ader("Acce pt", "appl ication/xm l, text/xm l, */*");
  1106       req.se tRequestHe ader("Cont ent-Type",  "text/xml ; charset= utf-8");
  1107       req.se tRequestHe ader("SOAP Action", " http://sch emas.micro soft.com/x rm/2011/Co ntracts/Se rvices/IOr ganization Service/Ex ecute");
  1108       var su ccessCallb ack = null ;
  1109       var er rorCallbac k = null;
  1110       req.on readystate change = f unction ()  { };
  1111       req.se nd(request Main);
  1112   }
  1113  
  1114   function u nlinkOldPA CTTeamMemb ers(pUsers ) {
  1115       if (!! pUsers &&  Array.isAr ray(pUsers ) && pUser s.length >  0) {
  1116           fo r (var i =  0, l = pU sers.lengt h; i < l;  i++) {
  1117                var this User = pUs ers[i];
  1118                if (this User.hasOw nProperty( "SystemUse rId") && ! !thisUser. SystemUser Id) {
  1119                    this User.ftp_P ACTId = {
  1120                         Id: null,
  1121                         LogicalNam e: null,
  1122                         Name: null
  1123                    };
  1124                    SDK. REST.updat eRecord(
  1125                         thisUser.S ystemUserI d,
  1126                         thisUser,
  1127                         "SystemUse r",
  1128                         function ( ) {
  1129                             //do n othing els e with thi s user
  1130                         },
  1131                         errorHandl er
  1132                    );
  1133                }
  1134           }
  1135       }
  1136   }
  1137  
  1138   function f tp_pactid_ onChange()  {
  1139       //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
  1140       var pa ctTeamValu e = Xrm.Pa ge.getAttr ibute("ftp _pactid"). getValue() ;
  1141       if (!p actTeamVal ue) return ;
  1142       var qu eryString  = "$select =FullName, ftp_PACTId &$filter=f tp_PACTId/ Id eq guid '" + pactT eamValue[0 ].id + "'  and ftp_PA CTTeamRole  ne null";
  1143       var re trievedUse rs = [];
  1144       SDK.RE ST.retriev eMultipleR ecords(
  1145           "S ystemUser" ,
  1146           qu eryString,
  1147           fu nction (re trievedRec ords) {
  1148                if (!!re trievedRec ords) retr ievedUsers  = retriev edUsers.co ncat(retri evedRecord s);
  1149           },
  1150           er rorHandler ,
  1151           fu nction ()  {
  1152                if (retr ievedUsers .length >  0) {
  1153                    var  alreadySet PrimaryCar eProviderF ield = fal se;
  1154                    var  alreadySet MentalHeal thTeamFiel d = false;
  1155                    for  (var i = 0 , l = retr ievedUsers .length; i  < l && (! alreadySet PrimaryCar eProviderF ield || !a lreadySetM entalHealt hTeamField ) ; i++) {
  1156                         var thisUs er = retri evedUsers[ i];
  1157                         if (!alrea dySetPrima ryCareProv iderField  && (thisUs er.ftp_PAC TTeamRole  == "Primar y Care Pro vider" ||  thisUser.f tp_PACTTea mRole == " Associate  Provider") ) {
  1158                             alread ySetPrimar yCareProvi derField =  setPrimar yCareProvi derField(t hisUser);
  1159                         }
  1160                         if (!alrea dySetMenta lHealthTea mField &&  thisUser.f tp_PACTTea mRole == " (mhtc) Add iction The rapist") {
  1161                             alread ySetMental HealthTeam Field = se tMentalHea lthTeamFie ld(thisUse r);
  1162                         }
  1163                    }
  1164                }
  1165           }
  1166       );
  1167   }
  1168  
  1169   function f illFtp_pac tIdWithPac tTeamlet12 () {
  1170       var re trievedPAC TTeams = [ ];
  1171       var qu eryString  = "$filter =ftp_name  eq 'PACT T eamlet 12' &$select=f tp_name,ft p_pactId";
  1172       SDK.RE ST.retriev eMultipleR ecords(
  1173           "f tp_pact",
  1174           qu eryString,
  1175           fu nction (re trievedRec ords) {
  1176                if (!!re trievedRec ords) retr ievedPACTT eams = ret rievedPACT Teams.conc at(retriev edRecords) ;
  1177           },
  1178           er rorHandler ,
  1179           fu nction ()  {
  1180                if (retr ievedPACTT eams.lengt h > 0) {
  1181                    var  PACTTeamle t12 = retr ievedPACTT eams[0];
  1182                    Xrm. Page.getAt tribute("f tp_pactid" ).setValue ([{
  1183                         id: PACTTe amlet12.ft p_pactId,
  1184                         name: PACT Teamlet12. ftp_name,
  1185                         entityType : "ftp_pac t"
  1186                    }
  1187                    ]);
  1188  
  1189                    Xrm. Page.getAt tribute("f tp_pactid" ).setSubmi tMode("alw ays");
  1190  
  1191                    //** ********** ***
  1192                    if ( pcmm_Enabl ed == true ) {
  1193                         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.";
  1194                         Xrm.Page.u i.setFormN otificatio n(alertTex t, "INFO",  "noPACTFr omPCMM");
  1195                    }
  1196                    //** ********** ***
  1197  
  1198                    fini shedGettin gPrimaryCa reProvider s = true;
  1199                    fini shedGettin gMHTC = tr ue;
  1200                }
  1201           }
  1202       );
  1203   }
  1204  
  1205   function b uildQueryF ilter(fiel d, value,  and) {
  1206       return  !!field ?  ((and ? "  and " : " ") + field  + " eq "  + (value = = '' ? "nu ll" : "'"  + value +  "'")) : "" ;
  1207   }
  1208  
  1209   function e rrorHandle r(error) {
  1210       alert( error.mess age);
  1211   }
  1212   function w riteToCons ole(messag e) {
  1213       if (ty peof conso le != 'und efined') c onsole.log (message);
  1214   }
  1215  
  1216   //******** ********** ********** **
  1217   function p cmm_retrie vePCMMSett ing() {
  1218       try {
  1219           va r context  = Xrm.Page .context.g etClientUr l();
  1220           va r ODATA_EN DPOINT = " /XRMServic es/2011/Or ganization Data.svc";
  1221           // Construct  the JSON Q uery
  1222           va r EntitySe tName = "m cs_setting Set";
  1223           va r selectSt ring = "?$ select=ftp _IsPCMMEna bled&$filt er=mcs_nam e eq 'Acti ve Setting s'";
  1224           va r jsonQuer y = contex t + ODATA_ ENDPOINT +  "/" + Ent itySetName  + selectS tring;
  1225           // Initialize  the retur n value
  1226           va r EntityDa ta = null;
  1227           $. ajax({
  1228                type: "G ET",
  1229                contentT ype: "appl ication/js on; charse t=utf-8",
  1230                datatype : "json",
  1231                url: jso nQuery,
  1232                beforeSe nd: functi on (XMLHtt pRequest)  {
  1233                    //Sp ecifying t his header  ensures t hat the re sults will  be return ed as JSON .
  1234                    XMLH ttpRequest .setReques tHeader("A ccept", "a pplication /json");
  1235                },
  1236                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  1237                    //Ge t the data  values
  1238                    Enti tyData = d ata;
  1239  
  1240                },
  1241                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  1242                    aler t('Fail: A jax Error  in Veteran  OnLoad Sc ript - pcm m_retrieve PCMMSettin g Function . Error: '  + errorTh rown);
  1243                },
  1244                async: f alse,
  1245                cache: f alse
  1246           }) ;
  1247           re turn Entit yData;
  1248       }
  1249       catch  (e) {
  1250           al ert("Error  occurred  in Veteran  OnLoad Sc ript - pcm m_retrieve PCMMSettin g function . Error da ta:" + e);
  1251       }
  1252   }
  1253   //******** ********** ********** **