72. EPMO Open Source Coordination Office Redaction File Detail Report

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

72.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_2.zip\WebResources ftp_VeteranJScriptmainjs59ECC3B8-0DCC-E411-80CB-00155DD08303 Wed Feb 15 14:53:00 2017 UTC
2 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_2.zip\WebResources ftp_VeteranJScriptmainjs59ECC3B8-0DCC-E411-80CB-00155DD08303 Thu Nov 30 17:20:17 2017 UTC

72.2 Comparison summary

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

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

72.4 Active regular expressions

No regular expressions were active.

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