35. EPMO Open Source Coordination Office Redaction File Detail Report

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

35.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_10.zip\WebResources ftp_VeteranJScriptmainjs59ECC3B8-0DCC-E411-80CB-00155DD08303 Fri May 5 04:06:48 2017 UTC
2 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_10.zip\WebResources ftp_VeteranJScriptmainjs59ECC3B8-0DCC-E411-80CB-00155DD08303 Thu Nov 30 17:18:16 2017 UTC

35.2 Comparison summary

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

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

35.4 Active regular expressions

No regular expressions were active.

35.5 Comparison detail

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