85. EPMO Open Source Coordination Office Redaction File Detail Report

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

85.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_6.zip\WebResources ftp_VeteranJScriptmainjs59ECC3B8-0DCC-E411-80CB-00155DD08303 Thu Mar 23 13:44:30 2017 UTC
2 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_6.zip\WebResources ftp_VeteranJScriptmainjs59ECC3B8-0DCC-E411-80CB-00155DD08303 Thu Nov 30 17:21:02 2017 UTC

85.2 Comparison summary

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

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

85.4 Active regular expressions

No regular expressions were active.

85.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                                                                
  547                                                                quer y.send(req uest);
  548                                                                **** ********** /
  549                             } //en d if !!ftp _ESRAPIURL
  550                             else {
  551                                 Xr m.Utility. alertDialo g(
  552                                      "Could n ot find ES R API URL. \n\nThis s ession wil l now clos e.",
  553                                      function  () {
  554                                          wind ow.open("h ttp://even t/?eventna me=EndSess ionOnBadES RCall");
  555                                      }
  556                                 );
  557                             }
  558                         } //end if  !!retriev edSettings
  559                         else {
  560                             Xrm.Ut ility.aler tDialog(
  561                                                                "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.",
  562                                                                func tion () {
  563                                                                     window.ope n("http:// event/?eve ntname=End SessionOnB adESRCall" );
  564                                                                }
  565                                                       );
  566                         }
  567                    } // end active  settings  retrieval  complete c allback
  568                );//end  active set tings quer y
  569           }  //end if ( !!pICN &&  !!fType &&  fType > 1 )
  570           el se if (!pI CN && !!fT ype && fTy pe > 1) {  //without  an id, ass ume sensit ivity=true
  571                             openES Rwebresour ce(pICN, t rue, false );
  572                return;
  573           }
  574           el se {
  575                //if (wi ndow.IsUSD ) {
  576                if (loca tion.href. indexOf("O utlook15Wh ite") != - 1) {
  577                    //US D Session
  578                    wind ow.open("h ttp://even t/?eventna me=New Vet &lastname= " + Xrm.Pa ge.getAttr ibute("las tname").ge tValue());
  579                }
  580                return;
  581           }
  582       }
  583       catch  (e) {
  584           al ert(e);
  585       }
  586   }
  587  
  588   /*Deprecat ed by Vete ranAlerts. html web r esource*/
  589   function o penESRwebr esource(pI CN, pSensi tivity, pD eceased, p DeathDate,  pHomephon e, pMobile phone, pWo rkphone){
  590           re turn;
  591           wr iteToConso le("begin  openESRweb resource(p ICN: " + p ICN + ", p Sensitivit y: " + pSe nsitivity. toString()  + ", pDec eased: " +  pDeceased .toString( ) + ")");
  592           if (!!pICN &&  pSensitiv ity != nul l && pDece ased != nu ll){
  593                    //fi re USD eve nt to copy  some fiel ds to cont ext
  594                    var  eventUrl =  "http://e vent/?even tname=Shar ed Set Vet eran Field s";
  595                    even tUrl += "& veteranid= " + pICN;
  596                    even tUrl += "& nationalid =" + pICN. substring( 0, 10); // this is th e ID used  to query t he Patient  Flags API
  597                    even tUrl += "& sensitivit y=" + pSen sitivity.t oString();  //ESR tab  will move  to MainPa nel if thi s == true
  598                    even tUrl += "& isDeceased =" + pDece ased.toStr ing(); //E SR tab wil l move to  MainPanel  if this ==  true
  599                    even tUrl += "& ESRTabLabe l=" + (pDe ceased ==  true || pD eceased ==  "true" ?  "Deceased  Veteran Wa rning" : " Sensitive  Veteran Wa rning");
  600                    even tUrl += !! pHomephone  ? "&homep hone=" + p Homephone  : "";
  601                    even tUrl += !! pMobilepho ne ? "&mob ilephone="  + pMobile phone : "" ;
  602                    even tUrl += !! pWorkphone  ? "&workp hone=" + p Workphone  : "";
  603                    wind ow.open(ev entUrl);
  604                    writ eToConsole ("fired Sh ared Set V eteran Fie lds event. ");
  605                    
  606                    if(p Sensitivit y == true  || pSensit ivity == " true" || p Deceased = = true ||  pDeceased  == "true") {
  607                             //a US D window n avigation  rule will  route this  to the ES R hosted c ontrol
  608                             //the  PageLoadCo mplete eve nt of that  hosted co ntrol will  determine  whether o r not to S HOW the ta b in USD
  609                             //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
  610                             var pa rameters =  "contacti d=" + Xrm. Page.data. entity.get Id()
  611                                      + "&full name=" + X rm.Page.da ta.entity. getPrimary AttributeV alue()
  612                                      + "&isDe ceased=" +  pDeceased .toString( )
  613                                      + "&isSe nsitive="  + pSensiti vity.toStr ing()
  614                                      + "&ICN= " + pICN
  615                                      + "&nati onalid=" +  pICN.subs tring(0,10 )
  616                                      + "&IsUS D=" + (loc ation.href .indexOf(" Outlook15W hite") !=  -1 ? "true " : "false ")
  617                                      + (_DFN  != "" ? "& DFN=" + _D FN : "")
  618                                      + (_faci lityCode ! = "" ? "&f acilityCod e=" + _fac ilityCode  : "");
  619                             parame ters += !! pDeathDate  ? "&death Date=" + p DeathDate. toLocaleSt ring("en-U S") : "";
  620                             parame ters += !! pHomephone  ? "&homep hone=" + p Homephone  : "";
  621                             parame ters += !! pMobilepho ne ? "&mob ilephone="  + pMobile phone : "" ;
  622                             parame ters += !! pWorkphone  ? "&workf phone=" +  pWorkphone  : "";
  623                             
  624                             /*
  625                             //comm ented out  2/7/17 by  kknab
  626                             setTim eout(funct ion(){wind ow.open("h ttp://even t/?eventna me=ReadyTo CloseMVI") ;}, 1000);
  627                             Xrm.Ut ility.open WebResourc e("ftp_/Ve teran/ESR. html", enc odeURIComp onent(para meters));
  628                             writeT oConsole(" opened ESR .html");
  629                             
  630                             */
  631                    }
  632                    else {
  633                             //skip  ESR.html  and go str aight to P atientFlag s.html
  634                             //a US D window n avigation  rule will  route this  to the Sh ared Patie nt Flags c ontrol
  635                             var da ta = pICN. substring( 0,10); //n ationalid
  636                             
  637                             /*
  638                             //comm ented out  2/7/17 by  kknab
  639                             setTim eout(funct ion(){wind ow.open("h ttp://even t/?eventna me=ReadyTo CloseMVI") ;}, 1000);
  640                             Xrm.Ut ility.open WebResourc e("ftp_/Ve teran/Pati entFlags.h tml", data );
  641                             writeT oConsole(" opened Pat ientFlags. html");
  642                             */
  643                    }
  644           }
  645   }
  646  
  647   /*Deprecat ed by open ESRwebreso urce, whic h has in t urn been d eprecated  by Veteran Alerts.htm l web reso urce*/
  648   function o penSensiti veVeteranW R(pICN, pS ensitivity , pHomepho ne, pMobil ephone, pW orkphone)  {
  649           re turn;
  650           wr iteToConso le("begin  openSensit iveVeteran WR(pICN: "  + pICN +  ", pSensit ivity: " +  pSensitiv ity.toStri ng() + ")" );
  651       if (!! pICN && pS ensitivity  != null)  {
  652           // fire USD e vent to co py some fi elds to co ntext
  653                    var  eventUrl =  "http://e vent/?even tname=Shar ed Set Vet eran Field s";
  654                    even tUrl += "& veteranid= " + pICN;
  655                    even tUrl += "& nationalid =" + pICN. substring( 0, 10); // this is th e ID used  to query t he Patient  Flags API
  656                    even tUrl += "& sensitivit y=" + pSen sitivity.t oString();  //boolean
  657                    even tUrl += !! pHomephone  ? "&homep hone=" + p Homephone  : "";
  658                    even tUrl += !! pMobilepho ne ? "&mob ilephone="  + pMobile phone : "" ;
  659                    even tUrl += !! pWorkphone  ? "&workp hone=" + p Workphone  : "";
  660                    wind ow.open(ev entUrl);
  661                    writ eToConsole ("fired Sh ared Set V eteran Fie lds event. ");
  662                    
  663                    if(p Sensitivit y == true  || pSensit ivity == " true"){
  664                             //a US D window n avigation  rule will  route this  to the Sh ared Sensi tive Veter an hosted  control
  665                             //the  PageLoadCo mplete eve nt of that  hosted co ntrol will  determine  whether o r not to S HOW the ta b in USD
  666                             //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
  667                             var pa rameters =  "contacti d=" + Xrm. Page.data. entity.get Id()
  668                                      + "&full name=" + X rm.Page.da ta.entity. getPrimary AttributeV alue()
  669                                      + "&sens itivity="  + pSensiti vity.toStr ing()
  670                                      + "&ICN= " + pICN
  671                                      + "&nati onalid=" +  pICN.subs tring(0,10 )
  672                                      //+ "&Is USD=" + (w indow.IsUS D ? "true"  : "false" );
  673                                      + "&IsUS D=" + (loc ation.href .indexOf(" Outlook15W hite") !=  -1 ? "true " : "false ");
  674                             parame ters += !! pHomephone  ? "&homep hone=" + p Homephone  : "";
  675                             parame ters += !! pMobilepho ne ? "&mob ilephone="  + pMobile phone : "" ;
  676                             parame ters += !! pWorkphone  ? "&workf phone=" +  pWorkphone  : "";
  677                             Xrm.Ut ility.open WebResourc e("ftp_/Ve teran/Sens itiveVeter an.html",  encodeURIC omponent(p arameters) );
  678                             writeT oConsole(" opened Sen sitiveVete ran.html") ;
  679                    }
  680                    else { //skip S ensitiveVe teran.html  and go st raight to  PatientFla gs.html
  681                             //a US D window n avigation  rule will  route this  to the Sh ared Patie nt Flags c ontrol
  682                             var da ta = pICN. substring( 0,10); //n ationalid
  683                             Xrm.Ut ility.open WebResourc e("ftp_/Ve teran/Pati entFlags.h tml", data );
  684                             writeT oConsole(" opened Pat ientFlags. html");
  685                    }
  686       }
  687   }
  688  
  689   function p erformPCMM WebService Call(pFaci lityCode,  pICN) {
  690           wr iteToConso le("begin  performPCM MWebServic eCall()");
  691           Xr m.Page.ui. clearFormN otificatio n("noPCMM" );
  692           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;
  693           wr iteToConso le("pcmm_E nabled: "  + pcmm_Ena bled);
  694           if (pcmm_Enab led && _re trievedSet tings.hasO wnProperty ("ftp_Pati entSummary APIURL") & & !!_retri evedSettin gs.ftp_Pat ientSummar yAPIURL){
  695                    var  facilityCo de = _notP rod ? "987 " : pFacil ityCode;
  696                    writ eToConsole ("_notProd : " + _not Prod);
  697                    writ eToConsole ("facility Code: " +  facilityCo de);
  698                    var  ICN = !!pI CN ? pICN  : !!_ICN ?  _ICN : nu ll;
  699                    if(! !facilityC ode && !!I CN){
  700                             var pc mmUrl = _r etrievedSe ttings.ftp _DACURL +  _retrieved Settings.f tp_Patient SummaryAPI URL + faci lityCode +  "/" + ICN  + "?idTyp e=ICN";
  701                    
  702                             //TODO : replace  $.get with  $.ajax, f or better  error hand ling - PCM M sometime s returns  404 errors  and we ha ve to catc h them.
  703                             writeT oConsole(" firing $.g et() again st PCMM ur l: " + pcm mUrl);
  704                             $.get(
  705                                      pcmmUrl,
  706                                      function  (returnDa ta, status ) {
  707                                               if (!!retu rnData) {
  708                                                       if  (returnDa ta.ErrorOc curred ==  true || re turnData.E rrorMessag e != null  || returnD ata.DebugI nfo != nul l) {
  709                                                                Xrm. Page.ui.se tFormNotif ication("E rror occur red retrie ving patie nt summary : " + retu rnData.Deb ugInfo, "W ARNING", " ESRCallErr or");
  710                                                                //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);
  711                                                                writ eToConsole ("error re trieving P CMM data." );
  712                                                                fill Ftp_pactId WithPactTe amlet12();
  713                                                       }
  714                                                       el se {
  715                                                                if ( returnData .hasOwnPro perty("Dat a")) {
  716                                                                         var da ta = retur nData.Data ;
  717                                                                         writeT oConsole(" got data o bject from  PCMM: ");
  718                                                                         writeT oConsole(d ata);
  719                                                                         var re sultsAsTex t = data.P atientSumm aryText;
  720                                                                         if (re sultsAsTex t.trim() = = "No PACT  assigned  at any VA  location." ) {
  721                                                                                  PCMMGrid Members.pu sh({ Name:  resultsAs Text.trim( ), TeamRol eName: ""  });
  722                                                                                  fillFtp_ pactIdWith PactTeamle t12(); //d o this her e, too?
  723  
  724                                                                         } else  if (data. hasOwnProp erty("pati entAssignm ents") &&  data.patie ntAssignme nts.length  > 0) {
  725                                                                                  var pati entAssignm ent = data .patientAs signments[ 0];
  726                                                                                  writeToC onsole("go t patientA ssignment  from data. ");
  727                                                                                  processP CHBAssignm ent(patien tAssignmen t);
  728                                                                                  processM entalHealt hProvider( patientAss ignment);
  729                                                                         } else  {
  730                                                                                  //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
  731                                                                                  fillFtp_ pactIdWith PactTeamle t12();
  732                                                                         }
  733                                                                }
  734                                                       }
  735                                               } else {
  736                                                       fi llFtp_pact IdWithPact Teamlet12( );
  737                                               }
  738                                      }
  739                             );
  740                    }//e nd if (!!f acilityCod e && !!ICN )
  741           }/ /end if pc mm_Enabled  == true
  742           el se{
  743                    writ eToConsole ("PCMM is  disabled o r we are m issing ftp _PatientSu mmaryAPIUR L from Act ive Settin gs.");
  744                    
  745                    Xrm. Page.getCo ntrol("Web Resource_V eteranPACT Team").set Visible(fa lse);
  746                    Xrm. Page.getCo ntrol("ftp _pactid"). setVisible (false);
  747                    Xrm. Page.getAt tribute("f tp_pactid" ).setSubmi tMode("alw ays");
  748                    Xrm. Page.getCo ntrol("ftp _primaryca reprovider ").setVisi ble(false) ;
  749                    Xrm. Page.getAt tribute("f tp_primary careprovid er").setSu bmitMode(" always");
  750                    
  751                    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");
  752                    fill Ftp_pactId WithPactTe amlet12();
  753           }
  754   }
  755  
  756   function p rocessPCHB Assignment (pPatientA ssignment)  {
  757           wr iteToConso le("begin  processPCH BAssignmen t");
  758       if (!p PatientAss ignment) {
  759                    writ eToConsole ("patient  assingment  object is  empty.");
  760           fi nishedGett ingPrimary CareProvid ers = true ;
  761           re turn;
  762       }
  763           
  764           /*  Summary
  765                    Data .patientAs signments  will have  either 'pr imaryCareA ssignments ' or 'prim aryCareHBP CAssignmen ts' (home  bound assi gnments).
  766                    Cycl e through  the one wi th data an d store th em in the  teamMember sFromPCMM  array and  the PCMMGr idMembers  array.
  767           */
  768           
  769           va r teamName  = "";
  770       var te amMembersF romPCMM =  []; //empt y array in tended to  hold objec ts of sche ma { Name,  TeamRoleN ame }
  771           
  772           // primaryCar eAssignmen ts array
  773       if (pP atientAssi gnment.has OwnPropert y("primary CareAssign ments") &&  pPatientA ssignment. primaryCar eAssignmen ts.length  > 0) {
  774                    writ eToConsole ("found pr imaryCareA ssignments ");
  775           va r pcAssign ment = pPa tientAssig nment.prim aryCareAss ignments[0 ];
  776           te amName = p cAssignmen t.teamName ;
  777           if  (pcAssign ment.hasOw nProperty( "teamletMe mbers") &&  pcAssignm ent.teamle tMembers.l ength > 0)  {
  778                for (var  i = 0, l  = pcAssign ment.teaml etMembers. length; i  < l; i++)  {
  779                    var  thisTeamle tMember =  pcAssignme nt.teamlet Members[i] ;
  780                    if ( thisTeamle tMember.ha sOwnProper ty("StaffC ontact") & & !!thisTe amletMembe r.StaffCon tact) {
  781                         var sc = t hisTeamlet Member.Sta ffContact;
  782                         if (sc.has OwnPropert y("Name")  && !!sc.Na me) {
  783                             var pe rson = { N ame: sc.Na me, TeamRo leName: sc .TeamRoleN ame };
  784                             teamMe mbersFromP CMM.push(p erson);
  785                             PCMMGr idMembers. push(perso n);
  786                         }
  787                    }
  788                }
  789                finished GettingPri maryCarePr oviders =  true;
  790           }
  791                    else  {
  792                finished GettingPri maryCarePr oviders =  true;
  793           }
  794       }
  795           
  796           // primaryCar eHBPCAssig nments arr ay
  797           el se if (pPa tientAssig nment.hasO wnProperty ("primaryC areHBPCAss ignments")  && pPatie ntAssignme nt.primary CareHBPCAs signments. length > 0 ) {
  798                    writ eToConsole ("found pr imaryCareH BPCAssignm ents");
  799           va r homeboun dPCAssignm ent = pPat ientAssign ment.prima ryCareHBPC Assignment s[0];
  800           te amName = h omeboundPC Assignment .teamName;
  801           if  (homeboun dPCAssignm ent.hasOwn Property(" teamMember s") && hom eboundPCAs signment.t eamMembers .length >  0) {
  802                for (var  i = 0, l  = homeboun dPCAssignm ent.teamMe mbers.leng th; i < l;  i++) {
  803                    var  thisTeamMe mber = hom eboundPCAs signment.t eamMembers [i];
  804                    if ( thisTeamMe mber.hasOw nProperty( "Name") &&  !!thisTea mMember.Na me) {
  805                         var person  = { Name:  thisTeamM ember.Name , TeamRole Name: this TeamMember .TeamRoleN ame };
  806                         teamMember sFromPCMM. push(perso n);
  807                         PCMMGridMe mbers.push (person);
  808                    }
  809                }
  810                finished GettingPri maryCarePr oviders =  true;
  811           }
  812                    else  {
  813                finished GettingPri maryCarePr oviders =  true;
  814           }
  815       }
  816           
  817           // all care a ssignment  arrays are  empty
  818           el se {
  819           fi nishedGett ingPrimary CareProvid ers = true ;
  820       }
  821  
  822       if (!! teamName)  {
  823                    writ eToConsole ("retrievi ng ftp_pac t record:  " + teamNa me);
  824           // find or cr eate a PAC T team rec ord called  named <te amName>
  825           va r retrieve dPACTTeams  = [];
  826           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";
  827           SD K.REST.ret rieveMulti pleRecords (
  828                "ftp_pac t",
  829                queryStr ing,
  830                function  (retrieve dRecords)  {
  831                    if ( typeof ret rievedReco rds != "un defined" & & !!retrie vedRecords ) retrieve dPACTTeams  = retriev edPACTTeam s.concat(r etrievedRe cords);
  832                },
  833                errorHan dler,
  834                function  () {
  835                    if ( retrievedP ACTTeams.l ength > 0)  {
  836                                               writeToCon sole("foun d " + team Name + " p act team i n CRM");
  837                                               setftp_pac tid(retrie vedPACTTea ms[0]);
  838                         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
  839                    }
  840                                      else {
  841                                               writeToCon sole("did  not find "  + teamNam e + " pact  team, cre ating.");
  842                         var newPac t = {
  843                             ftp_na me: teamNa me
  844                         };
  845                         SDK.REST.c reateRecor d(
  846                             newPac t,
  847                             "ftp_p act",
  848                             functi on (create dPACTTeam)  {
  849                                                                setf tp_pactid( createdPAC TTeam);
  850                                 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
  851                             },
  852                             errorH andler
  853                         );
  854                    }
  855                });
  856       }
  857           el se {
  858           // 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
  859           fi llFtp_pact IdWithPact Teamlet12( );
  860       }
  861   }
  862  
  863   function p rocessMent alHealthPr ovider(pPa tientAssig nment) {
  864           wr iteToConso le("begin  processMen talHealthP rovider()" );
  865       if (!p PatientAss ignment) {
  866                    writ eToConsole ("patient  assingment  object is  empty.");
  867           fi nishedGett ingMHTC =  true;
  868           re turn;
  869       }
  870           
  871           /*  Summary
  872                    Data .patientAs signments  will have  a mentalHe althAssign ments prop erty that  is an arra y.
  873                    Cycl e through  the array  store its  members in  the teamM embersFrom PCMM array  and the P CMMGridMem bers array .
  874           */
  875       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) {
  876           va r mentalHe althAssign ment = pPa tientAssig nment.ment alHealthAs signments[ 0];
  877           if  (mentalHe althAssign ment.hasOw nProperty( "teamName" ) && !!men talHealthA ssignment. teamName)  {
  878                var team Name = men talHealthA ssignment. teamName;
  879                if (ment alHealthAs signment.h asOwnPrope rty("menta lHealthTre atmentCoor d") && !!m entalHealt hAssignmen t.mentalHe althTreatm entCoord)  {
  880                    var  MHTC = men talHealthA ssignment. mentalHeal thTreatmen tCoord;
  881                                      writeToC onsole("go t mentalHe althAssign ment.menta lHealthTre atmentCoor d object." );
  882                    PCMM GridMember s.push(MHT C);
  883                    fini shedGettin gMHTC = tr ue;
  884  
  885                    //fi nd or crea te the PAC T Team rec ord matchi ng teamNam e
  886                    //ac cording to  Jeff, thi s should h appen
  887                    if ( !!teamName ) {
  888                         //find or  create a P ACT team r ecord call ed named < teamName>
  889                         var retrie vedPACTTea ms = [];
  890                         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 ";
  891                         SDK.REST.r etrieveMul tipleRecor ds(
  892                             "ftp_p act",
  893                             queryS tring,
  894                             functi on (retrie vedRecords ) {
  895                                 if  (typeof r etrievedRe cords != " undefined" ) retrieve dPACTTeams  = retriev edPACTTeam s.concat(r etrievedRe cords);
  896                             },
  897                             errorH andler,
  898                             functi on () {
  899                                 if  (retrieve dPACTTeams .length >  0) {
  900                                      matchMHT CToPACTTea m(retrieve dPACTTeams [0], MHTC) ;
  901                                 } 
  902                                                                else  {
  903                                      var newP act = {
  904                                          ftp_ name: team Name
  905                                      };
  906                                      SDK.REST .createRec ord(
  907                                          newP act,
  908                                          "ftp _pact",
  909                                          func tion (crea tedPACTTea m) {
  910                                               matchMHTCT oPACTTeam( createdPAC TTeam, MHT C);
  911                                          },
  912                                          erro rHandler
  913                                      );
  914                                 }
  915                             }
  916                         );
  917                    }
  918                } else {
  919                    fini shedGettin gMHTC = tr ue;
  920                }
  921           }  else {
  922                finished GettingMHT C = true;
  923           }
  924       }
  925       else {
  926           fi nishedGett ingMHTC =  true;
  927       }
  928   }
  929  
  930   function s etftp_pact id(pPACTTe am){
  931           wr iteToConso le("begin  setftp_pac tid()");
  932           if (!pPACTTea m) return;
  933           Xr m.Page.get Attribute( "ftp_pacti d").setVal ue([{
  934           id : pPACTTea m.ftp_pact Id,
  935           na me: pPACTT eam.ftp_na me,
  936           en tityType:  "ftp_pact"
  937       }]);
  938           Xr m.Page.get Attribute( "ftp_pacti d").addOnC hange(ftp_ pactid_onC hange);
  939   }
  940  
  941   function m atchPCTeam MembersToP ACTTeam(pP ACTTeam, p PACTTeamMe mbersFromP CMM, pAlre adySetPrim aryCarePro viderField , pUsersTo UnlinkFrom PACTTeam){
  942           wr iteToConso le("");
  943           wr iteToConso le("begin  matchPCTea mMembersTo PACTTeam() ... pPACTT eamMembers FromPCMM.l ength = "  + pPACTTea mMembersFr omPCMM.len gth);
  944           
  945           // 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
  946           va r usersToU nlink = pU sersToUnli nkFromPACT Team; 
  947           // 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 )
  948           if (usersToUn link == nu ll){
  949                    user sToUnlink  = [];
  950                    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 ) {
  951                             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");
  952                             for (v ar i = 0,  l = pPACTT eam.ftp_ft p_pact_sys temuser.re sults.leng th; i < l;  i++) {
  953                                      usersToU nlink.push (pPACTTeam .ftp_ftp_p act_system user.resul ts[i]);
  954                             }
  955                    }
  956                    else {
  957                             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 ");
  958                    }
  959           }
  960           
  961           if (pPACTTeam MembersFro mPCMM.leng th > 0){
  962                    var  alreadySet PrimaryCar eProviderF ield = pAl readySetPr imaryCareP roviderFie ld != null  ? pAlread ySetPrimar yCareProvi derField :  false;
  963                    var  thisTeamMe mber = pPA CTTeamMemb ersFromPCM M.shift();  //cut the  length of  pPACTTeam MembersFro mPCMM down  one at a  time
  964                    var  splitName  = thisTeam Member.Nam e.split(", ");
  965                    var  lastName =  splitName [0].trim() ;
  966                    var  splitFirst MiddleName s = splitN ame.length  > 1 ? spl itName[1]. trim().spl it(" ") :  "";
  967                    var  firstName  = !!splitF irstMiddle Names ? sp litFirstMi ddleNames[ 0] : "";
  968                    var  middleName  = !!split FirstMiddl eNames &&  splitFirst MiddleName s.length >  1 ? split FirstMiddl eNames[1]  : "";
  969                    var  fakeFullNa me = lastN ame + ", "  + firstNa me + " " +  middleNam e;
  970                     var domain Name = fir stName + " ." + lastN ame + "@no domainacco unt. DNS     ";
  971                    var  userQuery  = "$select =FirstName ,LastName, SystemUser Id,ftp_PAC TId,ftp_PA CTTeamRole ,IsDisable d,DomainNa me,FullNam e&$filter= DomainName  eq '" + d omainName  + "'";
  972                    writ eToConsole ("thisTeam Member: "  + fakeFull Name + " ( " + domain Name + ")" );
  973                    var  retrievedU sers = [];
  974                    SDK. REST.retri eveMultipl eRecords(
  975                             "Syste mUser",
  976                             userQu ery,
  977                             functi on (retrie vedRecords ) {
  978                                      if (type of retriev edRecords  != "undefi ned" && !! retrievedR ecords) re trievedUse rs = retri evedUsers. concat(ret rievedReco rds);
  979                             },
  980                             errorH andler,
  981                             functi on () {
  982                                      if (retr ievedUsers .length >  0) {
  983                                               var foundU ser = retr ievedUsers [0];
  984                                               if(!foundU ser.IsDisa bled){
  985                                                       wr iteToConso le("found  systemuser  " + found User.Domai nName + "  in CRM");
  986                                                       if  (foundUse r.hasOwnPr operty("ft p_PACTId")  && !!foun dUser.ftp_ PACTId &&  foundUser. ftp_PACTId .Id == pPA CTTeam.ftp _pactId &&
  987                                                                foun dUser.hasO wnProperty ("ftp_PACT TeamRole")  && foundU ser.ftp_PA CTTeamRole  == thisTe amMember.T eamRoleNam e) {
  988                                                                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.") ;
  989                                                                user sToUnlink  = removeUs erFromUser sToUnlink( foundUser,  usersToUn link);
  990                                                                if ( !alreadySe tPrimaryCa reProvider Field) alr eadySetPri maryCarePr oviderFiel d = setPri maryCarePr oviderFiel d(foundUse r);
  991                                                                matc hPCTeamMem bersToPACT Team(pPACT Team, pPAC TTeamMembe rsFromPCMM , alreadyS etPrimaryC areProvide rField, us ersToUnlin k);//run t his method  again
  992                                                       }
  993                                                       el se {
  994                                                                foun dUser.ftp_ PACTId = {
  995                                                                         Id: pP ACTTeam.ft p_pactId,
  996                                                                         Logica lName: "ft p_pact",
  997                                                                         Name:  pPACTTeam. ftp_name
  998                                                                };
  999                                                                foun dUser.ftp_ PACTTeamRo le = thisT eamMember. TeamRoleNa me;
  1000                                                                SDK. REST.updat eRecord(
  1001                                                                         foundU ser.System UserId,
  1002                                                                         foundU ser,
  1003                                                                         "Syste mUser",
  1004                                                                         functi on () {
  1005                                                                                  writeToC onsole("up dated " +  foundUser. DomainName  + " with  PACT team  (" + pPACT Team.ftp_n ame + ") a nd PACT te am role ("  + thisTea mMember.Te amRoleName  + ")");
  1006                                                                                  usersToU nlink = re moveUserFr omUsersToU nlink(foun dUser, use rsToUnlink );
  1007                                                                                  if (!alr eadySetPri maryCarePr oviderFiel d) already SetPrimary CareProvid erField =  setPrimary CareProvid erField(fo undUser);
  1008                                                                                  matchPCT eamMembers ToPACTTeam (pPACTTeam , pPACTTea mMembersFr omPCMM, al readySetPr imaryCareP roviderFie ld, usersT oUnlink);/ /run this  method aga in
  1009                                                                         },
  1010                                                                         errorH andler
  1011                                                                );
  1012                                                       }
  1013                                               }
  1014                                               else{
  1015                                                       wr iteToConso le("found  systemuser " + foundU ser.Domain Name + ",  but this u ser is dis abled.  Sk ipping use r update." );
  1016                                               }
  1017                                      }
  1018                                      //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
  1019                                      else { 
  1020                                               writeToCon sole("did  not find "  + domainN ame + ", c reating sy stemuser." );
  1021                                               var PACTUs erCRMTeam  = null;
  1022                                               var teamQu ery = "$se lect=Name, TeamId,Bus inessUnitI d&$filter= Name eq 'P ACT User'  and TeamTy pe/Value e q 0";
  1023                                               var retrie vedCRMTeam s = [];
  1024                                               SDK.REST.r etrieveMul tipleRecor ds(
  1025                                                       "T eam",
  1026                                                       te amQuery,
  1027                                                       fu nction (re trievedRec ords) {
  1028                                                                if ( typeof ret rievedReco rds != "un defined" & & !!retrie vedRecords ) retrieve dCRMTeams  = retrieve dCRMTeams. concat(ret rievedReco rds);
  1029                                                       },
  1030                                                       er rorHandler ,
  1031                                                       fu nction ()  {
  1032                                                                if ( retrievedC RMTeams.le ngth > 0)  {
  1033                                                                         PACTUs erCRMTeam  = retrieve dCRMTeams[ 0];
  1034                                                                         
  1035                                                                         //buil d newUser  object
  1036                                                                         var ne wUser = {
  1037                                                                                  FirstNam e: firstNa me,
  1038                                                                                  LastName : lastName ,
  1039                                                                                  MiddleNa me: middle Name,
  1040                                                                                  ftp_PACT TeamRole:  thisTeamMe mber.TeamR oleName,
  1041                                                                                  IsIntegr ationUser:  false,
  1042                                                                                  UserLice nseType: 3 ,
  1043                                                                                  AccessMo de: {
  1044                                                                                           Value: 0
  1045                                                                                  },
  1046                                                                                  DomainNa me: domain Name,
  1047                                                                                  Business UnitId: {
  1048                                                                                           Id: PACTUs erCRMTeam. BusinessUn itId.Id,
  1049                                                                                           LogicalNam e: PACTUse rCRMTeam.B usinessUni tId.Logica lName,
  1050                                                                                           Name: PACT UserCRMTea m.Business UnitId.Nam e
  1051                                                                                  },
  1052                                                                                  ftp_PACT Id: {
  1053                                                                                           Id: pPACTT eam.ftp_pa ctId,
  1054                                                                                           LogicalNam e: "ftp_pa ct",
  1055                                                                                           Name: pPAC TTeam.ftp_ name
  1056                                                                                  }
  1057                                                                         };
  1058                                                                         SDK.RE ST.createR ecord(
  1059                                                                                  newUser,
  1060                                                                                  "SystemU ser",
  1061                                                                                  function  (createdU ser) {
  1062                                                                                           writeToCon sole("crea ted system user: " +  fakeFullNa me + " ("  + domainNa me + "). G UID: " + c reatedUser .SystemUse rId);
  1063                                                                                           addUsersTo Team(creat edUser.Sys temUserId,  PACTUserC RMTeam.Tea mId);
  1064                                                                                           if (!alrea dySetPrima ryCareProv iderField)  alreadySe tPrimaryCa reProvider Field = se tPrimaryCa reProvider Field(crea tedUser);
  1065                                                                                           matchPCTea mMembersTo PACTTeam(p PACTTeam,  pPACTTeamM embersFrom PCMM, alre adySetPrim aryCarePro viderField , usersToU nlink); // run this m ethod agai n
  1066                                                                                  },
  1067                                                                                  errorHan dler
  1068                                                                         );
  1069                                                                }
  1070                                                       }
  1071                                               );
  1072                                      }
  1073                             }
  1074                    );
  1075           }
  1076           el se{
  1077                    //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
  1078                    unli nkUsersFro mPACTTeam( usersToUnl ink);
  1079           }
  1080   }
  1081  
  1082   function r emoveUserF romUsersTo Unlink(pUs er, pUsers ToUnlink){
  1083           fo r(var i =  0, l = pUs ersToUnlin k.length;  i < l; i++ ){
  1084                    if(p UsersToUnl ink[i].Sys temUserId  == pUser.S ystemUserI d){
  1085                             pUsers ToUnlink.s plice(i,1) ;
  1086                             break;
  1087                    }
  1088           }
  1089           re turn pUser sToUnlink;
  1090   }
  1091  
  1092   function u nlinkUsers FromPACTTe am(pUsers) {
  1093           wr iteToConso le("begin  unlinkUser sFromPACTT eam()");
  1094       if (!! pUsers &&  Array.isAr ray(pUsers ) && pUser s.length >  0) {
  1095                    writ eToConsole ("pUsers.l ength: " +  pUsers.le ngth);
  1096                    var  thisUser =  pUsers.sh ift();
  1097                    if ( thisUser.h asOwnPrope rty("Syste mUserId")  && !!thisU ser.System UserId) {
  1098                             thisUs er.ftp_PAC TId = {
  1099                                      Id: null ,
  1100                                      LogicalN ame: null,
  1101                                      Name: nu ll
  1102                             };
  1103                             SDK.RE ST.updateR ecord(
  1104                                      thisUser .SystemUse rId,
  1105                                      thisUser ,
  1106                                      "SystemU ser",
  1107                                      function  () {
  1108                                               //do nothi ng else wi th this us er
  1109                                               writeToCon sole("clea red ftp_PA CTId field  on system user:" + t hisUser.Fu llName + "  {" + this User.Syste mUserId +  "}");
  1110                                              
  1111                                               //re-enter  this func tion until  pUsers is  empty
  1112                                               unlinkUser sFromPACTT eam(pUsers );
  1113                                      },
  1114                                      errorHan dler
  1115                             );
  1116                    }
  1117           }
  1118           el se{
  1119                    writ eToConsole ("no users  to unlink .");
  1120           }
  1121   }
  1122  
  1123   function s etPrimaryC areProvide rField(pUs er) {
  1124       if (!p User || !p User.ftp_P ACTTeamRol e || !pUse r.FullName ) return f alse;
  1125       if (!( pUser.ftp_ PACTTeamRo le == "Pri mary Care  Provider"  || pUser.f tp_PACTTea mRole == " Associate  Provider") ) return f alse;
  1126       Xrm.Pa ge.getAttr ibute("ftp _primaryca reprovider ").setValu e(pUser.Fu llName);
  1127       Xrm.Pa ge.getAttr ibute("ftp _primaryca reprovider ").setSubm itMode("al ways");
  1128           wr iteToConso le("set Ve teran's ft p_primaryc areprovide r with sys temuser.Fu llName: "  + pUser.Fu llName);
  1129       return  true;
  1130   }
  1131  
  1132   function m atchMHTCTo PACTTeam(p PACTTeam,  pMHTC) {
  1133           wr iteToConso le("begin  matchMHTCT oPACTTeam( )");
  1134       if (!p PACTTeam)  return;
  1135       //don' t set the  ftp_pactid  lookup fi eld on the  vet form
  1136  
  1137       //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
  1138           // for a ment al health  PACT team. ..it shoul d just be  one user
  1139           // for a newl y-created  ftp_pact r ecord, thi s list of  users will  be empty
  1140       var us ersToUpdat e = [];
  1141       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)  {
  1142                    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");
  1143           fo r (var i =  0, l = pP ACTTeam.ft p_ftp_pact _systemuse r.results. length; i  < l; i++)  {
  1144                usersToU pdate.push (pPACTTeam .ftp_ftp_p act_system user.resul ts[i]);
  1145           }
  1146       }
  1147  
  1148       if (!! pMHTC) {
  1149           va r teamQuer y = "$sele ct=Name,Te amId,Busin essUnitId& $filter=Na me eq 'PAC T User' an d TeamType /Value eq  0";
  1150           va r retrieve dCRMTeams  = [];
  1151           SD K.REST.ret rieveMulti pleRecords (
  1152                             "Team" ,
  1153                             teamQu ery,
  1154                             functi on (retrie vedRecords ) {
  1155                                      if (type of retriev edRecords  != "undefi ned" && !! retrievedR ecords) re trievedCRM Teams = re trievedCRM Teams.conc at(retriev edRecords) ;
  1156                             },
  1157                             errorH andler,
  1158                             functi on () {
  1159                                      if (retr ievedCRMTe ams.length  > 0) {
  1160                                               var PACTUs erCRMTeam  = retrieve dCRMTeams[ 0];
  1161  
  1162                                               //find or  create a s ystemuser  for the Me ntal Healt h Treatmen t Coordina tor (pMHTC )
  1163                                               //set thei r ftp_PACT Id lookup  field to p PACTTeam
  1164                                               //add the  user to th e 'PACT Us er' CRM te am, so it  will inher it the tea m's securi ty roles
  1165                                               //if their  ftp_PACTI d and ftp_ PACTTeamRo le are fin e, remove  that perso n from use rsToUpdate  array
  1166  
  1167                                               //pMHTC sc hema: { Na me, TeamRo leName, Te amRoleCode , Phone, P age, Ien }
  1168                                               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");
  1169                                               var splitN ame = pMHT C.Name.spl it(",");
  1170                                               var lastNa me = split Name[0];
  1171                                               var splitF irstMiddle Names = sp litName.le ngth > 1 ?  splitName [1].trim() .split(" " ) : "";
  1172                                               var firstN ame = !!sp litFirstMi ddleNames  ? splitFir stMiddleNa mes[0] : " ";
  1173                                               var middle Name = !!s plitFirstM iddleNames  && splitF irstMiddle Names.leng th > 1 ? s plitFirstM iddleNames [1] : "";
  1174                                               var fakeFu llName = l astName +  ", " + fir stName + "  " + middl eName;
  1175                                                var domain Name = fir stName + " ." + lastN ame + "@no domainacco unt. DNS     ";
  1176                                               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 + "'";
  1177                                               var retrie vedUsers =  [];
  1178                                               SDK.REST.r etrieveMul tipleRecor ds(
  1179                                                       "S ystemUser" ,
  1180                                                       us erQuery,
  1181                                                       fu nction (re trievedRec ords) {
  1182                                                                if ( typeof ret rievedReco rds != "un defined" & & !!retrie vedRecords ) retrieve dUsers = r etrievedUs ers.concat (retrieved Records);
  1183                                                       },
  1184                                                       er rorHandler ,
  1185                                                       fu nction ()  {
  1186                                                                if ( retrievedU sers.lengt h > 0) {
  1187                                                                         writeT oConsole(" found syst emuser: "  + domainNa me + ", up dating sys temuser.") ;
  1188                                                                         var fo undUser =  retrievedU sers[0];
  1189                                                                         if(!fo undUser.Is Disabled){
  1190                                                                                  if (foun dUser.hasO wnProperty ("ftp_PACT Id") && !! foundUser. ftp_PACTId  && foundU ser.ftp_PA CTId.Id ==  pPACTTeam .ftp_pactI d &&
  1191                                                                                           foundUser. hasOwnProp erty("ftp_ PACTTeamRo le") && fo undUser.ft p_PACTTeam Role == pM HTC.TeamRo leName) {
  1192                                                                                           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.");
  1193                                                                                           //remove t his person  from the  usersToUpd ate array,  because t heir ftp_P ACTId and  ftp_PACTTe amRole are  already f ine
  1194                                                                                           usersToUpd ate.splice (i, 1);
  1195                                                                                           setMentalH ealthTeamF ield(found User);
  1196                                                                                  } 
  1197                                                                                  else {
  1198                                                                                           foundUser. ftp_PACTId  = {
  1199                                                                                                   Id : pPACTTea m.ftp_pact Id,
  1200                                                                                                   Lo gicalName:  "ftp_pact ",
  1201                                                                                                   Na me: pPACTT eam.ftp_na me
  1202                                                                                           };
  1203                                                                                           foundUser. ftp_PACTTe amRole = p MHTC.TeamR oleName;
  1204                                                                                           SDK.REST.u pdateRecor d(
  1205                                                                                                   fo undUser.Sy stemUserId ,
  1206                                                                                                   fo undUser,
  1207                                                                                                   "S ystemUser" ,
  1208                                                                                                   fu nction ()  {
  1209                                                                                                            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 + ") ");
  1210                                                                                                            setM entalHealt hTeamField (foundUser );
  1211                                                                                                   },
  1212                                                                                                   er rorHandler
  1213                                                                                           );
  1214                                                                                  }
  1215                                                                         }
  1216                                                                         else{
  1217                                                                                  writeToC onsole("fo und system user" + fo undUser.Do mainName +  ", but th is user is  disabled.   Skipping  user upda te.");
  1218                                                                         }
  1219                                                                }
  1220                                                                else  {
  1221                                                                         writeT oConsole(" did not fi nd systemu ser: " + d omainName  + ", creat ing system user.");
  1222                                                                         //buil d user obj ect
  1223                                                                         var ne wUser = {
  1224                                                                                  FirstNam e: firstNa me,
  1225                                                                                  LastName : lastName ,
  1226                                                                                  MiddleNa me: middle Name,
  1227                                                                                  ftp_PACT TeamRole:  pMHTC.Team RoleName,
  1228                                                                                  IsIntegr ationUser:  false,
  1229                                                                                  UserLice nseType: 3 ,
  1230                                                                                  AccessMo de: {
  1231                                                                                           Value: 0
  1232                                                                                  },
  1233                                                                                  DomainNa me: domain Name,
  1234                                                                                  Business UnitId: {
  1235                                                                                           Id: PACTUs erCRMTeam. BusinessUn itId.Id,
  1236                                                                                           LogicalNam e: PACTUse rCRMTeam.B usinessUni tId.Logica lName,
  1237                                                                                           Name: PACT UserCRMTea m.Business UnitId.Nam e
  1238                                                                                  },
  1239                                                                                  ftp_PACT Id: {
  1240                                                                                           Id: pPACTT eam.ftp_pa ctId,
  1241                                                                                           LogicalNam e: "ftp_pa ct",
  1242                                                                                           Name: pPAC TTeam.ftp_ name
  1243                                                                                  }
  1244                                                                         };
  1245                                                                         //crea te it
  1246                                                                         SDK.RE ST.createR ecord(
  1247                                                                                  newUser,
  1248                                                                                  "SystemU ser",
  1249                                                                                  function  (createdU ser) {
  1250                                                                                           writeToCon sole("crea ted system user: " +  fakeFullNa me + " ("  + domainNa me + "). G UID: " + c reatedUser .SystemUse rId);
  1251                                                                                           setMentalH ealthTeamF ield(creat edUser);
  1252                                                                                           addUsersTo Team(creat edUser.Sys temUserId,  PACTUserC RMTeam.Tea mId);
  1253                                                                                  },
  1254                                                                                  errorHan dler
  1255                                                                         );
  1256                                                                }
  1257                                                       }
  1258                                               );
  1259                                      }
  1260                             }
  1261                    );
  1262       }
  1263           el se {
  1264           // 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
  1265           un linkUsersF romPACTTea m(usersToU pdate);
  1266       }
  1267   }
  1268  
  1269   function s etMentalHe althTeamFi eld(pUser)  {
  1270           wr iteToConso le("begin  setMentalH ealthTeamF ield()");
  1271       if (!! pUser && ! !pUser.ftp _PACTTeamR ole && !!p User.FullN ame) {
  1272           if  (pUser.ft p_PACTTeam Role == "( mhtc) Addi ction Ther apist") {
  1273                             var MH TCAttr = X rm.Page.ge tAttribute ("ftp_ment alhealthte am");
  1274                             if(!!M HTCAttr){
  1275                                      Xrm.Page .getAttrib ute("ftp_m entalhealt hteam").se tValue(pUs er.FullNam e);
  1276                                      Xrm.Page .getAttrib ute("ftp_m entalhealt hteam").se tSubmitMod e("always" );
  1277                                      writeToC onsole("se t ftp_ment alhealthte am to " +  pUser.Full Name);
  1278                             }
  1279                             else{
  1280                                      writeToC onsole("di d not set  ftp_mental healthteam  to becaus e attribut e is not o n form.");
  1281                             }
  1282           }
  1283       }
  1284   }
  1285  
  1286   function a ddUsersToT eam(pUserI ds, pTeamI d) {
  1287           wr iteToConso le("begin  addUsersTo Team.  pTe amId: " +  pTeamId);
  1288       var se rviceURL =  Xrm.Page. context.ge tClientUrl () + "/XRM Services/2 011/Organi zation.svc /web";
  1289       var re questMain  = "";
  1290       reques tMain += " <s:Envelop e xmlns:s= \"http://s chemas.xml soap.org/s oap/envelo pe/\">";
  1291       reques tMain += "   <s:Body> ";
  1292       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\">";
  1293       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\"> ";
  1294       reques tMain += "         <a :Parameter s xmlns:c= \"http://s chemas.dat acontract. org/2004/0 7/System.C ollections .Generic\" >";
  1295       reques tMain += "            <a:KeyValu ePairOfstr inganyType >";
  1296       reques tMain += "              <c:key>T eamId</c:k ey>";
  1297       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>";
  1298       reques tMain += "            </a:KeyVal uePairOfst ringanyTyp e>";
  1299       reques tMain += "            <a:KeyValu ePairOfstr inganyType >";
  1300       reques tMain += "              <c:key>M emberIds</ c:key>";
  1301       reques tMain += "              <c:value  i:type=\" d:ArrayOfg uid\" xmln s:d=\"http ://schemas .microsoft .com/2003/ 10/Seriali zation/Arr ays\">";
  1302       if (Ar ray.isArra y(pUserIds )) {
  1303           fo r (var i =  0, l = pU serIds.len gth; i < l ; i++) {
  1304                             writeT oConsole(" adding sys temuser {"  + pUserId s[i] + "}  to team {"  + pTeamId  + "}");
  1305                requestM ain += "                <d:guid> " + pUserI ds[i] + "< /d:guid>";
  1306           }
  1307       } else  {
  1308                    writ eToConsole ("adding s ystemuser  {" + pUser Ids + "} t o team {"  + pTeamId  + "}");
  1309           re questMain  += "               <d :guid>" +  pUserIds +  "</d:guid >";
  1310       }
  1311       reques tMain += "              </c:valu e>";
  1312       reques tMain += "            </a:KeyVal uePairOfst ringanyTyp e>";
  1313       reques tMain += "         </ a:Paramete rs>";
  1314       reques tMain += "         <a :RequestId  i:nil=\"t rue\" />";
  1315       reques tMain += "         <a :RequestNa me>AddMemb ersTeam</a :RequestNa me>";
  1316       reques tMain += "       </re quest>";
  1317       reques tMain += "     </Exec ute>";
  1318       reques tMain += "   </s:Body >";
  1319       reques tMain += " </s:Envelo pe>";
  1320       var re q = new XM LHttpReque st();
  1321       req.op en("POST",  serviceUR L, true);
  1322       // Res ponses wil l return X ML. It isn 't possibl e to retur n JSON.
  1323       req.se tRequestHe ader("Acce pt", "appl ication/xm l, text/xm l, */*");
  1324       req.se tRequestHe ader("Cont ent-Type",  "text/xml ; charset= utf-8");
  1325       req.se tRequestHe ader("SOAP Action", " http://sch emas.micro soft.com/x rm/2011/Co ntracts/Se rvices/IOr ganization Service/Ex ecute");
  1326       var su ccessCallb ack = null ;
  1327       var er rorCallbac k = null;
  1328       req.on readystate change = f unction ()  { };
  1329       req.se nd(request Main);
  1330           wr iteToConso le("sent r equest to  add user t o team.");
  1331   }
  1332  
  1333   function f tp_pactid_ onChange()  {
  1334           wr iteToConso le("begin  ftp_pactid _onChange( )");
  1335       //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
  1336       var pa ctTeamValu e = Xrm.Pa ge.getAttr ibute("ftp _pactid"). getValue() ;
  1337       if (!p actTeamVal ue) return ;
  1338           wr iteToConso le("PACT t eam: " + p actTeamVal ue[0].name );
  1339       var qu eryString  = "$select =FullName, ftp_PACTId &$filter=f tp_PACTId/ Id eq guid '" + pactT eamValue[0 ].id + "'  and ftp_PA CTTeamRole  ne null";
  1340       var re trievedUse rs = [];
  1341       SDK.RE ST.retriev eMultipleR ecords(
  1342           "S ystemUser" ,
  1343           qu eryString,
  1344           fu nction (re trievedRec ords) {
  1345                if (type of retriev edRecords  != "undefi ned" && !! retrievedR ecords) re trievedUse rs = retri evedUsers. concat(ret rievedReco rds);
  1346           },
  1347           er rorHandler ,
  1348           fu nction ()  {
  1349                if (retr ievedUsers .length >  0) {
  1350                                      writeToC onsole("fo und " + re trievedUse rs.length  + " users  on this PA CT team.") ;
  1351                    var  alreadySet PrimaryCar eProviderF ield = fal se;
  1352                    var  alreadySet MentalHeal thTeamFiel d = false;
  1353                                      writeToC onsole("cy cling thro ugh users  to find Pr imary Care  Provider  (or Associ ate Provid er), and ( mhtc) Addi ction Ther apist.");
  1354                    for  (var i = 0 , l = retr ievedUsers .length; i  < l && (! alreadySet PrimaryCar eProviderF ield || !a lreadySetM entalHealt hTeamField ) ; i++) {
  1355                         var thisUs er = retri evedUsers[ i];
  1356                         if (!alrea dySetPrima ryCareProv iderField  && (thisUs er.ftp_PAC TTeamRole  == "Primar y Care Pro vider" ||  thisUser.f tp_PACTTea mRole == " Associate  Provider") ) {
  1357                             alread ySetPrimar yCareProvi derField =  setPrimar yCareProvi derField(t hisUser);
  1358                         }
  1359                         if (!alrea dySetMenta lHealthTea mField &&  thisUser.f tp_PACTTea mRole == " (mhtc) Add iction The rapist") {
  1360                             alread ySetMental HealthTeam Field = se tMentalHea lthTeamFie ld(thisUse r);
  1361                         }
  1362                    }
  1363                }
  1364           }
  1365       );
  1366   }
  1367  
  1368   function f illFtp_pac tIdWithPac tTeamlet12 () {
  1369           wr iteToConso le("begin  fillFtp_pa ctIdWithPa ctTeamlet1 2()");
  1370       var re trievedPAC TTeams = [ ];
  1371       var qu eryString  = "$filter =ftp_name  eq 'PACT T eamlet 12' &$select=f tp_name,ft p_pactId";
  1372       SDK.RE ST.retriev eMultipleR ecords(
  1373           "f tp_pact",
  1374           qu eryString,
  1375           fu nction (re trievedRec ords) {
  1376                if (type of retriev edRecords  != "undefi ned" && !! retrievedR ecords) re trievedPAC TTeams = r etrievedPA CTTeams.co ncat(retri evedRecord s);
  1377           },
  1378           er rorHandler ,
  1379           fu nction ()  {
  1380                if (retr ievedPACTT eams.lengt h > 0) {
  1381                    var  PACTTeamle t12 = retr ievedPACTT eams[0];
  1382                                      writeToC onsole("go t PACTTeam let12");
  1383                    Xrm. Page.getAt tribute("f tp_pactid" ).setValue ([{
  1384                         id: PACTTe amlet12.ft p_pactId,
  1385                         name: PACT Teamlet12. ftp_name,
  1386                         entityType : "ftp_pac t"
  1387                    }
  1388                    ]);
  1389                                      writeToC onsole("se t Veteran' s ftp_pact id field") ;
  1390                                      Xrm.Page .getAttrib ute("ftp_p actid").se tSubmitMod e("always" );
  1391  
  1392                    //** ********** ***
  1393                    if ( pcmm_Enabl ed == true ) {
  1394                         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.";
  1395                         Xrm.Page.u i.setFormN otificatio n(alertTex t, "INFO",  "noPACTFr omPCMM");
  1396                    }
  1397                    //** ********** ***
  1398  
  1399                    fini shedGettin gPrimaryCa reProvider s = true;
  1400                    fini shedGettin gMHTC = tr ue;
  1401                }
  1402           }
  1403       );
  1404   }
  1405  
  1406   function b uildQueryF ilter(fiel d, value,  and) {
  1407       return  !!field ?  ((and ? "  and " : " ") + field  + " eq "  + (value = = '' ? "nu ll" : "'"  + value +  "'")) : "" ;
  1408   }
  1409  
  1410   function e rrorHandle r(error) {
  1411           wr iteToConso le(error.m essage);
  1412       alert( error.mess age);
  1413   }
  1414   function w riteToCons ole(messag e) {
  1415       if (ty peof conso le != 'und efined') c onsole.log (message);
  1416   }
  1417  
  1418   //******** ********** ********** **
  1419   function p cmm_retrie vePCMMSett ing() {
  1420       try {
  1421           va r context  = Xrm.Page .context.g etClientUr l();
  1422           va r ODATA_EN DPOINT = " /XRMServic es/2011/Or ganization Data.svc";
  1423           // Construct  the JSON Q uery
  1424           va r EntitySe tName = "m cs_setting Set";
  1425           va r selectSt ring = "?$ select=ftp _IsPCMMEna bled&$filt er=mcs_nam e eq 'Acti ve Setting s'";
  1426           va r jsonQuer y = contex t + ODATA_ ENDPOINT +  "/" + Ent itySetName  + selectS tring;
  1427           // Initialize  the retur n value
  1428           va r EntityDa ta = null;
  1429           $. ajax({
  1430                type: "G ET",
  1431                //conten tType: "ap plication/ json; char set=utf-8" ,
  1432                datatype : "json",
  1433                url: jso nQuery,
  1434                beforeSe nd: functi on (XMLHtt pRequest)  {
  1435                    //Sp ecifying t his header  ensures t hat the re sults will  be return ed as JSON .
  1436                    XMLH ttpRequest .setReques tHeader("A ccept", "a pplication /json");
  1437                },
  1438                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  1439                    //Ge t the data  values
  1440                    Enti tyData = d ata;
  1441  
  1442                },
  1443                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  1444                    aler t('Fail: A jax Error  in Veteran  OnLoad Sc ript - pcm m_retrieve PCMMSettin g Function . Error: '  + errorTh rown);
  1445                },
  1446                async: f alse,
  1447                cache: f alse
  1448           }) ;
  1449           re turn Entit yData;
  1450       }
  1451       catch  (e) {
  1452           al ert("Error  occurred  in Veteran  OnLoad Sc ript - pcm m_retrieve PCMMSettin g function . Error da ta:" + e);
  1453       }
  1454   }
  1455   //******** ********** ********** **