16. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 12/4/2017 8:32:29 AM Central Standard Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

16.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\FTPResources\FTPResources_3_35.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Thu Nov 17 16:48:12 2016 UTC
2 VCCM.zip\VCCM\CRM_solutions\FTPResources\FTPResources_3_35.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Thu Nov 30 16:21:55 2017 UTC

16.2 Comparison summary

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

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

16.4 Active regular expressions

No regular expressions were active.

16.5 Comparison detail

  1   //VistACPR SMultiProg ressNoteFo rmScript.j s
  2   //Contains  variables  and funct ions used  by the CRM  Form and  Ribbon
  3   //Requires  jQuery lo aded on th e CRM Form
  4   //The form  where thi s script l ibrary is  applied mu st have th e followin g form par ameters de fined
  5   /*
  6   parameter_ regardingo bjectid  -   Type:Uni queId
  7   parameter_ regardingo bjectidnam e  -  Type :SafeStrin g
  8   parameter_ regardingo bjectidtyp e  -  Type :SafeStrin g
  9   parameter_ triageexpe rt  -  Typ e:SafeStri ng
  10   parameter_ triageminu tes  -  Ty pe:Integer
  11   */
  12  
  13   //Static V ariables
  14   var vcmn_c rmOdataEnd Point = '/ XRMService s/2011/Org anizationD ata.svc';
  15   var vcmn_s erverUrl =  Xrm.Page. context.ge tClientUrl ();
  16  
  17   //var vcmn _NoteWrite Url = 'htt ps://qacrm dac.np.crm .vrm.vba. DNS     /WebParts/ DEV/api/no teswrite';     //OLD MANU AL DEV URL
  18   var vcmn_N oteWriteUr l = '';
  19   //var vcmn _eesummary URLbase =  'https://q acrmdac.np .crm.vrm.v ba. DNS     /WebParts/ api/eesumm ary/1.0/xm l/ftpCRM/'   //OLD MANU AL DEV URL
  20   var vcmn_e esummaryUR Lbase = '' ;
  21   //var vcmn _VistaUser sURLbase =  'https:// qacrmdac.n p.crm.vrm. vba. DNS     /WebParts/ DEV/api/Vi staUsers/1 .0/json/ft pCRM/john/ smith/1234 ?noFilter= true';    //OLD MANU AL DEV URL
  22   var vcmn_V istaUsersU RLbase = ' ';
  23  
  24   function v cmn_getQue ryVariable (vcmn_vari able) {
  25       try {
  26           // Get a Quer y Variable
  27           va r vcmn_que ry = windo w.location .search.su bstring(1) ;
  28           va r vcmn_var s = vcmn_q uery.split ("&");
  29           fo r (var i =  0; i < vc mn_vars.le ngth; i++)  {
  30                var vcmn _pair = vc mn_vars[i] .split("=" );
  31                if (vcmn _pair[0] = = vcmn_var iable) {
  32                    retu rn decodeU RIComponen t(vcmn_pai r[1]);
  33                }
  34           }
  35           re turn "";
  36       }
  37       catch  (err) {
  38           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getQ ueryVariab le): ' + e rr.message );
  39       }
  40   }
  41  
  42   function v cmn_setSim pleLookupV alue(vcmn_ LookupId,  vcmn_Type,  vcmn_Id,  vcmn_Name)  {
  43       try {
  44           // Sets the v alue for l ookup attr ibutes tha t accept o nly a sing le entity  reference.
  45           va r vcmn_loo kupReferen ce = [];
  46           vc mn_lookupR eference[0 ] = {};
  47           vc mn_lookupR eference[0 ].id = vcm n_Id;
  48           vc mn_lookupR eference[0 ].entityTy pe = vcmn_ Type;
  49           vc mn_lookupR eference[0 ].name = v cmn_Name;
  50           Xr m.Page.get Attribute( vcmn_Looku pId).setVa lue(vcmn_l ookupRefer ence);
  51       }
  52       catch  (err) {
  53           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_setS impleLooku pValue): '  + err.mes sage);
  54       }
  55   }
  56  
  57   function v cmn_conver tCrmDateTo VistADate( vcmn_crmDa te) {
  58       try {
  59           va r vcmn_Vis tADate = n ull;
  60           if  (vcmn_crm Date != nu ll) {
  61                var vcmn _crmYear =  (vcmn_crm Date.getFu llYear()). toString() ;
  62                var vcmn _crmMonth  = '00';
  63                if ((vcm n_crmDate. getMonth()  + 1) < 10 ) {
  64                    vcmn _crmMonth  = '0' + (v cmn_crmDat e.getMonth () + 1).to String();
  65                }
  66                else {
  67                    vcmn _crmMonth  = (vcmn_cr mDate.getM onth() + 1 ).toString ();
  68                }
  69                var vcmn _crmDay =  '00';
  70                if ((vcm n_crmDate. getDate())  < 10) {
  71                    vcmn _crmDay =  '0' + (vcm n_crmDate. getDate()) .toString( );
  72                }
  73                else {
  74                    vcmn _crmDay =  (vcmn_crmD ate.getDat e()).toStr ing();
  75                }
  76                var vcmn _crmHours  = '00';
  77                if ((vcm n_crmDate. getHours() ) < 10) {
  78                    vcmn _crmHours  = '0' + (v cmn_crmDat e.getHours ()).toStri ng();
  79                }
  80                else {
  81                    vcmn _crmHours  = (vcmn_cr mDate.getH ours()).to String();
  82                }
  83                var vcmn _crmMinute s = '00';
  84                if ((vcm n_crmDate. getMinutes ()) < 10)  {
  85                    vcmn _crmMinute s = '0' +  (vcmn_crmD ate.getMin utes()).to String();
  86                }
  87                else {
  88                    vcmn _crmMinute s = (vcmn_ crmDate.ge tMinutes() ).toString ();
  89                }
  90                var vcmn _crmSecond s = '00';
  91                if ((vcm n_crmDate. getSeconds ()) < 10)  {
  92                    vcmn _crmSecond s = '0' +  (vcmn_crmD ate.getSec onds()).to String();
  93                }
  94                else {
  95                    vcmn _crmSecond s = (vcmn_ crmDate.ge tSeconds() ).toString ();
  96                }
  97  
  98                //Create  VistA Dat e
  99                vcmn_Vis tADate = v cmn_crmYea r + vcmn_c rmMonth +  vcmn_crmDa y + vcmn_c rmHours +  vcmn_crmMi nutes + vc mn_crmSeco nds;
  100           }
  101           re turn vcmn_ VistADate;
  102       }
  103       catch  (err) {
  104           al ert('Progr ess Note E rror(vcmn_ convertCrm DateToVist ADate): '  + err.mess age);
  105           re turn null;
  106       }
  107   }
  108  
  109   function v cmn_UserHa sTeam(team Name, user Guid) {
  110       try {
  111           va r vcmn_tea mid = null ;
  112           va r vcmn_cur rentUserId  = userGui d;
  113           va r vcmn_con ditionalFi lter = "(N ame eq '"  + teamName  + "')";
  114           va r vcmn_tea mData = vc mn_getMult ipleEntity DataSync(' TeamSet',  'TeamId',  vcmn_condi tionalFilt er, 'Name' , 'asc', 0 );
  115           if  (vcmn_tea mData != n ull) {
  116                for (var  i = 0; i  <= vcmn_te amData.d.r esults.len gth - 1; i ++) {
  117                    //Ge t Info
  118                    if ( vcmn_teamD ata.d.resu lts[i].Tea mId != nul l) { vcmn_ teamid = v cmn_teamDa ta.d.resul ts[i].Team Id; }
  119                    brea k;
  120                }
  121           }
  122           // If Team ex ists, chec k if the c urrent use r is part  of that te am
  123           va r vcmn_tea mMembershi pId = null ;
  124           if  (vcmn_tea mid != nul l && vcmn_ currentUse rId != nul l) {
  125                var vcmn _condition alFilter =  "(TeamId  eq (guid'"  + vcmn_te amid + "')  and Syste mUserId eq  (guid'" +  vcmn_curr entUserId  + "'))";
  126                var vcmn _teamMembe rshipData  = vcmn_get MultipleEn tityDataSy nc('TeamMe mbershipSe t', 'TeamI d, SystemU serId,Team Membership Id', vcmn_ conditiona lFilter, ' TeamId', ' asc', 0);
  127                if (vcmn _teamMembe rshipData  != null) {
  128                    for  (var i = 0 ; i <= vcm n_teamMemb ershipData .d.results .length -  1; i++) {
  129                         //Get Info
  130                         if (vcmn_t eamMembers hipData.d. results[i] .TeamMembe rshipId !=  null) { v cmn_teamMe mbershipId  = vcmn_te amMembersh ipData.d.r esults[i]. TeamMember shipId; }
  131                         break;
  132                    }
  133                }
  134           }
  135           if  (vcmn_tea mMembershi pId != nul l) { retur n true; }
  136  
  137           // otherwise  return fal se                 
  138           re turn false ;
  139       }
  140       catch  (err) {
  141           // Display Er ror
  142           al ert("An er ror occure d in the v cmn_UserHa sTeam func tion.  Err or Detail  Message: "  + err);
  143       }
  144   }
  145  
  146   function v cmn_Settin gsWebServi ceURL_resp onse(vcmn_ settingDat a, vcmn_la stSkip, vc mn_NoteWri teUrl_NA)  {
  147       try {
  148           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  149           va r vcmn_Dac Url = null ;
  150           va r vcmn_Not esWriteApi Url = null ;
  151           va r vcmn_ees ummaryApiU rl = null;
  152           va r vcmn_Vis taUserApiU rl = null;
  153  
  154           fo r (var i =  0; i <= v cmn_settin gData.d.re sults.leng th - 1; i+ +) {
  155                //Get in fo
  156                if (vcmn _settingDa ta.d.resul ts[i].ftp_ DACURL !=  null) { vc mn_DacUrl  = vcmn_set tingData.d .results[i ].ftp_DACU RL; }
  157                if (vcmn _settingDa ta.d.resul ts[i].ftp_ NotesWrite APIURL !=  null) { vc mn_NotesWr iteApiUrl  = vcmn_set tingData.d .results[i ].ftp_Note sWriteAPIU RL; }
  158                if (vcmn _settingDa ta.d.resul ts[i].ftp_ ESRAPIURL  != null) {  vcmn_eesu mmaryApiUr l = vcmn_s ettingData .d.results [i].ftp_ES RAPIURL; }
  159                if (vcmn _settingDa ta.d.resul ts[i].ftp_ VistaUsers APIURL !=  null) { vc mn_VistaUs erApiUrl =  vcmn_sett ingData.d. results[i] .ftp_Vista UsersAPIUR L; }
  160                break;
  161           }
  162           if  (vcmn_Dac Url != nul l && vcmn_ NotesWrite ApiUrl !=  null) {
  163                //Constr uct full w eb service  URL
  164                vcmn_Not eWriteUrl  = vcmn_Dac Url + vcmn _NotesWrit eApiUrl;
  165           }
  166           el se {
  167                Xrm.Page .ui.setFor mNotificat ion("ERROR : THE VIST A NOTES WR ITE SERVIC E URL IS M ISSING, PL EASE CONTA CT TECHNIC AL SUPPORT !", "ERROR ", "VISTAS ERVICE");
  168           }
  169           if  (vcmn_Dac Url != nul l && vcmn_ eesummaryA piUrl != n ull) {
  170                //Constr uct full w eb service  URL
  171                vcmn_ees ummaryURLb ase = vcmn _DacUrl +  vcmn_eesum maryApiUrl ;
  172           }
  173           el se {
  174                Xrm.Page .ui.setFor mNotificat ion("ERROR : THE EESU MMARY SERV ICE URL IS  MISSING,  PLEASE CON TACT TECHN ICAL SUPPO RT!", "ERR OR", "VIST ASERVICE") ;
  175           }
  176           if  (vcmn_Dac Url != nul l && vcmn_ VistaUserA piUrl != n ull) {
  177                //Constr uct full w eb service  URL
  178                vcmn_Vis taUsersURL base = vcm n_DacUrl +  vcmn_Vist aUserApiUr l;
  179           }
  180           el se {
  181                Xrm.Page .ui.setFor mNotificat ion("ERROR : THE VIST A USERS SE RVICE URL  IS MISSING , PLEASE C ONTACT TEC HNICAL SUP PORT!", "E RROR", "VI STASERVICE ");
  182           }
  183  
  184           // Proceed wi th Form Lo ad logic w ith URL
  185           vc mn_newProg ressNoteLo ad_WebURL( );
  186       }
  187       catch  (err) {
  188           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_Sett ingsWebSer viceURL_re sponse): '  + err.mes sage);
  189       }
  190   }
  191  
  192   function v cmn_newPro gressNoteL oad() {
  193       try {
  194           // GET CRM SE TTINGS WEB  SERVICE U RLS
  195           va r vcmn_con ditionalFi lter = "(m cs_name eq  'Active S ettings')" ;
  196           vc mn_getMult ipleEntity DataAsync( 'mcs_setti ngSet', 'f tp_DACURL,  ftp_Notes WriteAPIUR L, ftp_ESR APIURL, ft p_VistaUse rsAPIURL',  vcmn_cond itionalFil ter, 'mcs_ name', 'as c', 0, vcm n_Settings WebService URL_respon se, vcmn_N oteWriteUr l);
  197       }
  198       catch  (err) {
  199           // Display Er ror
  200           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_newP rogressNot eLoad): '  + err.mess age);
  201       }
  202   }
  203  
  204   function v cmn_newPro gressNoteL oad_WebURL () {
  205       try {
  206           // Only handl e forms in  create st ate
  207           if  (Xrm.Page .ui.getFor mType() !=  1) { retu rn false;  }
  208  
  209           // Set defaul t values b ased on th e current  user's USD  Config an d Facility
  210           va r vcmn_cur rentUserId  = Xrm.Pag e.context. getUserId( );
  211           va r vcmn_cur rentUserDa ta = vcmn_ getSingleE ntityDataS ync('Syste mUserSet',  'msdyusd_ USDConfigu rationId,  ftp_Facili tySiteId',  vcmn_curr entUserId) ;
  212           if  (vcmn_cur rentUserDa ta != null ) {
  213                if (vcmn _currentUs erData.d.m sdyusd_USD Configurat ionId != n ull) {
  214                    if ( vcmn_curre ntUserData .d.msdyusd _USDConfig urationId. Id != null ) {
  215                         if (vcmn_c urrentUser Data.d.ftp _FacilityS iteId != n ull) {
  216                             if (vc mn_current UserData.d .ftp_Facil itySiteId. Id != null ) {
  217                                 // Data Requi red to loo kup Facili ty Group D efaults ar e present
  218                                 va r vcmn_con ditionalFi lter = "(f tp_facilit ysiteid/Id  eq guid'"  + vcmn_cu rrentUserD ata.d.ftp_ FacilitySi teId.Id +  "') and (f tp_usdgrou pid/Id eq  guid'" + v cmn_curren tUserData. d.msdyusd_ USDConfigu rationId.I d + "')";
  219                                 vc mn_getMult ipleEntity DataAsync( 'ftp_facil itygroupde faultSet',  'ftp_loca lnotestitl e, ftp_hos pitallocat ion', vcmn _condition alFilter,  'ftp_name' , 'asc', 0 , vcmn_fac ilityGroup Default_re sponse, vc mn_current UserData.d .ftp_Facil itySiteId. Id);
  220                             }
  221                         }
  222                    }
  223                }
  224           }
  225  
  226           // Determine  if regardi ng field i s prefille d (added b y subgrid+ )
  227           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  228           va r vcmn_tri ageexpert  = null;
  229           va r vcmn_tri ageminutes  = null;
  230           if  (vcmn_req uestId ==  null) {
  231                //Get cu stom param eters pass ed to the  form
  232                var vcmn _regarding objectid =  vcmn_getQ ueryVariab le("parame ter_regard ingobjecti d");
  233                var vcmn _regarding objectidna me = vcmn_ getQueryVa riable("pa rameter_re gardingobj ectidname" );
  234                var vcmn _regarding objectidty pe = vcmn_ getQueryVa riable("pa rameter_re gardingobj ectidtype" );
  235                vcmn_tri ageexpert  = vcmn_get QueryVaria ble("param eter_triag eexpert");
  236                vcmn_tri ageminutes  = vcmn_ge tQueryVari able("para meter_tria geminutes" );
  237  
  238                if (vcmn _regarding objectid = = '' || vc mn_regardi ngobjectid  == null | | vcmn_reg ardingobje ctidname = = '' || vc mn_regardi ngobjectid name == nu ll ||
  239                    vcmn _regarding objectidty pe == '' | | vcmn_reg ardingobje ctidtype = = null) {  return fal se; }
  240           }
  241           el se {
  242                var vcmn _regarding objectid =  vcmn_requ estId[0].i d;
  243                var vcmn _regarding objectidna me = vcmn_ requestId[ 0].name;
  244                var vcmn _regarding objectidty pe = vcmn_ requestId[ 0].entityT ype;
  245           }
  246           if  (vcmn_tri ageexpert  == null) {  vcmn_tria geexpert =  'NO'; }
  247           if  (vcmn_tri ageminutes  == null)  { vcmn_tri ageminutes  = 0; }
  248  
  249           // Populate r egarding o bject
  250           vc mn_setSimp leLookupVa lue('regar dingobject id', vcmn_ regardingo bjectidtyp e, vcmn_re gardingobj ectid, vcm n_regardin gobjectidn ame);
  251           Xr m.Page.get Attribute( 'regarding objectid') .setSubmit Mode('alwa ys');
  252  
  253           // Populate s ubject wit h regardin g objects  title
  254           Xr m.Page.get Attribute( 'subject') .setValue( 'Progress  Note: ' +  vcmn_regar dingobject idname);
  255           if  (vcmn_tri ageexpert  == 'YES')  { Xrm.Page .getAttrib ute('subje ct').setVa lue('Triag e Note: '  + vcmn_reg ardingobje ctidname);  }
  256           Xr m.Page.get Attribute( 'subject') .setSubmit Mode('alwa ys');
  257           // Default Sa ve to CPPR S
  258           Xr m.Page.get Attribute( 'ftp_savet ovista').s etValue(10 0000001);  //Yes
  259           Xr m.Page.get Attribute( 'ftp_savet ovista').s etSubmitMo de('always ');
  260  
  261           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  262  
  263           // Populate f orm with r elated CRM  data
  264           va r vcmn_sub ReasonId =  null; //R eference t o the Reas on for Req uest Sub R eason
  265           va r vcmn_min orReasonId  = null;   //Referenc e to the R eason for  Request Mi nor Reason
  266           va r vcmn_sub ReasonTemp lateText =  null;
  267           va r vcmn_min orReasonTe mplateText  = null;
  268           va r vcmn_min orReasonNo teSubText  = null;
  269  
  270           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'ftp_ CallbackNu mber, ftp_ ReasonforR equest, ft p_SubReaso nId, ftp_M inorReason Id, Descri ption, Cus tomerId, f tp_LastFil led, ftp_Q uantityRep ortsTaking , ftp_RxNu mber, ftp_ RxRefillQu antity, ft p_Tracking Number, ft p_OpiodAgr eementOnfi le, ftp_UD Sonfile, f tp_StateDr ugMonitori ngReport,  ftp_spdmps tateonfile , ftp_SPDM PState2, f tp_pickupm ethod, ftp _earlyrefi llcomment,  ftp_quant itytaking,  ftp_vacat ionstart,  ftp_vacati onend', vc mn_regardi ngobjectid );
  271           if  (vcmn_req uestData ! = null) {
  272                if (vcmn _requestDa ta.d.ftp_C allbackNum ber != nul l) {
  273                    Xrm. Page.getAt tribute('f tp_callbac knumber'). setValue(v cmn_reques tData.d.ft p_Callback Number);
  274                    Xrm. Page.getAt tribute('f tp_callbac knumber'). setSubmitM ode('alway s');
  275                }
  276                if (vcmn _requestDa ta.d.ftp_R easonforRe quest != n ull) {
  277                    vcmn _setSimple LookupValu e('ftp_rea sonforrequ est', vcmn _requestDa ta.d.ftp_R easonforRe quest.Logi calName, v cmn_reques tData.d.ft p_Reasonfo rRequest.I d, vcmn_re questData. d.ftp_Reas onforReque st.Name);
  278                    Xrm. Page.getAt tribute('f tp_reasonf orrequest' ).setSubmi tMode('alw ays');
  279                }
  280  
  281                if (vcmn _requestDa ta.d.ftp_S ubReasonId  != null)  {
  282                    vcmn _subReason Id = vcmn_ requestDat a.d.ftp_Su bReasonId. Id;
  283                    if ( vcmn_subRe asonId !=  null) {
  284                         //Get Temp late Text
  285                         var vcmn_s ubreasonDa ta = vcmn_ getSingleE ntityDataS ync('ftp_s ubreasonSe t', 'ftp_n otetext',  vcmn_subRe asonId);
  286                         if (vcmn_s ubreasonDa ta.d.ftp_n otetext !=  null) {
  287                             vcmn_s ubReasonTe mplateText  = vcmn_su breasonDat a.d.ftp_no tetext;
  288                         }
  289                    }
  290                }
  291                if (vcmn _requestDa ta.d.ftp_M inorReason Id != null ) {
  292                    vcmn _minorReas onId = vcm n_requestD ata.d.ftp_ MinorReaso nId.Id;
  293                    if ( vcmn_minor ReasonId ! = null) {
  294                         //Get Temp late Text
  295                         var vcmn_m inorreason Data = vcm n_getSingl eEntityDat aSync('ftp _minorreas onSet', 'f tp_name, f tp_notetex t', vcmn_m inorReason Id);
  296                         if (vcmn_m inorreason Data.d.ftp _name != n ull) {
  297                             vcmn_m inorReason TemplateTe xt = vcmn_ minorreaso nData.d.ft p_name;
  298                         }
  299                         if (vcmn_m inorreason Data.d.ftp _notetext  != null) {
  300                             vcmn_m inorReason NoteSubTex t = vcmn_m inorreason Data.d.ftp _notetext;
  301                         }
  302                    }
  303                }
  304  
  305                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  306                    vcmn _setSimple LookupValu e('ftp_pat ient', vcm n_requestD ata.d.Cust omerId.Log icalName,  vcmn_reque stData.d.C ustomerId. Id, vcmn_r equestData .d.Custome rId.Name);
  307                    Xrm. Page.getAt tribute('f tp_patient ').setSubm itMode('al ways');
  308                    //Se t as veter an id
  309                    vcmn _veteranId  = vcmn_re questData. d.Customer Id.Id
  310                }
  311  
  312                //Constr uct Templa te Note
  313                var vcmn _subReason Name = nul l;
  314                var vcmn _templateN ote = "";
  315                var vcmn _lastFille d = "";
  316                var vcmn _quantityR eportsTaki ng = null;
  317                var vcmn _rxNumber  = null;
  318                var vcmn _rxRefillQ uantity =  null;
  319                var vcmn _trackingN umber = nu ll;
  320                var vcmn _opioidAgr eementOnfi le = null;
  321                var vcmn _UDSonfile  = null;
  322                var vcmn _stateDrug Monitoring Report = n ull;
  323                var vcmn _spdmpstat eonfile =  null;
  324                var vcmn _sPDMPStat e2 = null;
  325                var vcmn _pickupmet hod = null ;
  326  
  327                var vcmn _earlyRefi llComment  = null;
  328                var vcmn _quantityT aking = nu ll;
  329                var vcmn _vacationS tart = nul l;
  330                var vcmn _vacationE nd = null;
  331  
  332                if (vcmn _requestDa ta.d.ftp_L astFilled  != null) {  vcmn_last Filled = n ew Date(pa rseInt(vcm n_requestD ata.d.ftp_ LastFilled .toString( ).replace( "/Date(",  "").replac e(")/", "" ), 10)); }
  333                if (vcmn _requestDa ta.d.ftp_Q uantityRep ortsTaking  != null)  { vcmn_qua ntityRepor tsTaking =  vcmn_requ estData.d. ftp_Quanti tyReportsT aking; }
  334                if (vcmn _requestDa ta.d.ftp_R xNumber !=  null) { v cmn_rxNumb er = vcmn_ requestDat a.d.ftp_Rx Number; }
  335                if (vcmn _requestDa ta.d.ftp_R xRefillQua ntity != n ull) { vcm n_rxRefill Quantity =  vcmn_requ estData.d. ftp_RxRefi llQuantity ; }
  336                if (vcmn _requestDa ta.d.ftp_T rackingNum ber != nul l) { vcmn_ trackingNu mber = vcm n_requestD ata.d.ftp_ TrackingNu mber; }
  337                if (vcmn _requestDa ta.d.ftp_O piodAgreem entOnfile  != null) {  vcmn_opio idAgreemen tOnfile =  vcmn_reque stData.d.f tp_OpiodAg reementOnf ile.Value;  }
  338                if (vcmn _requestDa ta.d.ftp_U DSonfile ! = null) {  vcmn_UDSon file = vcm n_requestD ata.d.ftp_ UDSonfile. Value; }
  339                if (vcmn _requestDa ta.d.ftp_S tateDrugMo nitoringRe port != nu ll) { vcmn _stateDrug Monitoring Report = v cmn_reques tData.d.ft p_StateDru gMonitorin gReport.Va lue; }
  340                if (vcmn _requestDa ta.d.ftp_s pdmpstateo nfile != n ull) { vcm n_spdmpsta teonfile =  vcmn_requ estData.d. ftp_spdmps tateonfile .Value; }
  341                if (vcmn _requestDa ta.d.ftp_S PDMPState2  != null)  { vcmn_sPD MPState2 =  vcmn_requ estData.d. ftp_SPDMPS tate2.Valu e; }
  342                if (vcmn _requestDa ta.d.ftp_p ickupmetho d != null)  { vcmn_pi ckupmethod  = vcmn_re questData. d.ftp_pick upmethod.V alue; }
  343  
  344                if (vcmn _requestDa ta.d.ftp_e arlyrefill comment !=  null) { v cmn_earlyR efillComme nt = vcmn_ requestDat a.d.ftp_ea rlyrefillc omment; }
  345                if (vcmn _requestDa ta.d.ftp_q uantitytak ing != nul l) { vcmn_ quantityTa king = vcm n_requestD ata.d.ftp_ quantityta king; }
  346                if (vcmn _requestDa ta.d.ftp_v acationsta rt != null ) { vcmn_v acationSta rt = new D ate(parseI nt(vcmn_re questData. d.ftp_vaca tionstart. toString() .replace(" /Date(", " ").replace (")/", "") , 10)); }
  347                if (vcmn _requestDa ta.d.ftp_v acationend  != null)  { vcmn_vac ationEnd =  new Date( parseInt(v cmn_reques tData.d.ft p_vacation end.toStri ng().repla ce("/Date( ", "").rep lace(")/",  ""), 10)) ; }
  348                
  349                if (vcmn _requestDa ta.d.ftp_S ubReasonId  != null)  {
  350                    vcmn _subReason Id = vcmn_ requestDat a.d.ftp_Su bReasonId. Id;
  351                    vcmn _subReason Name = vcm n_requestD ata.d.ftp_ SubReasonI d.Name;
  352  
  353                    if ( vcmn_subRe asonName = = 'Regular ') {
  354                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Veteran i s requesti ng a RENEW AL." + "\n \n";
  355                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Last Fill ed: " + vc mn_lastFil led + "\n\ n";
  356                         if (vcmn_m inorReason TemplateTe xt != null ) {
  357                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason TemplateTe xt + "\n\n ";
  358                         }
  359                         if (vcmn_m inorReason NoteSubTex t != null)  {
  360                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason NoteSubTex t + "\n\n" ;
  361                         }
  362                         if (vcmn_s ubReasonTe mplateText  != null)  {
  363                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_s ubReasonTe mplateText  + "\n\n";
  364                         }
  365                    }
  366  
  367                    if ( vcmn_subRe asonName = = 'Early')  {
  368                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Veteran i s requesti ng EARLY F ILL." + "\ n\n";
  369                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Last Fill ed: " + vc mn_lastFil led + "\n\ n";
  370                         if (vcmn_m inorReason TemplateTe xt != null ) {
  371                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason TemplateTe xt + "\n\n ";
  372                         }
  373  
  374                         if (vcmn_q uantityTak ing != nul l) {
  375                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Quant ity Taking : " + vcmn _quantityT aking + "\ n\n";
  376                         }
  377  
  378                         if (vcmn_v acationSta rt != null  && vcmn_v acationEnd  != null)  {
  379                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Veter an Leaving  Town: " +  vcmn_vaca tionStart  + ' - ' +  vcmn_vacat ionEnd + " \n\n";
  380                         }
  381  
  382                         if (vcmn_m inorReason NoteSubTex t != null)  {
  383                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason NoteSubTex t + "\n\n" ;
  384                         }
  385                         if (vcmn_s ubReasonTe mplateText  != null)  {
  386                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_s ubReasonTe mplateText  + "\n\n";
  387                         }
  388                    }
  389  
  390                    if ( vcmn_subRe asonName = = 'Lost')  {
  391                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Veteran c laims pres criptions( s) were LO ST and is  requesting  a new pre scription/ early fill ." + "\n\n ";
  392                         if (vcmn_r xNumber !=  null) {
  393                             vcmn_t emplateNot e = vcmn_t emplateNot e + "RX#:  " + vcmn_r xNumber +  "\n\n";
  394                         }
  395                         if (vcmn_r xRefillQua ntity != n ull) {
  396                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Rx Re fill Quant ity: " + v cmn_rxRefi llQuantity  + "\n\n";
  397                         }
  398                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Last Fill ed: " + vc mn_lastFil led + "\n\ n";
  399                         if (vcmn_m inorReason TemplateTe xt != null ) {
  400                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason TemplateTe xt + "\n\n ";
  401                         }
  402                         if (vcmn_t rackingNum ber != nul l) {
  403                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Track ing Number : " + vcmn _trackingN umber + "\ n\n";
  404                         }
  405                         if (vcmn_m inorReason NoteSubTex t != null)  {
  406                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason NoteSubTex t + "\n\n" ;
  407                         }
  408                         if (vcmn_s ubReasonTe mplateText  != null)  {
  409                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_s ubReasonTe mplateText  + "\n\n";
  410                         }
  411                    }
  412  
  413                    if ( vcmn_subRe asonName = = 'Stolen' ) {
  414                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Veteran c laims pres criptions( s) were ST OLEN and i s requesti ng a new p rescriptio n/early fi ll." + "\n \n";
  415                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Last Fill ed: " + vc mn_lastFil led + "\n\ n";
  416                         if (vcmn_m inorReason TemplateTe xt != null ) {
  417                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason TemplateTe xt + "\n\n ";
  418                         }
  419                         if (vcmn_m inorReason NoteSubTex t != null)  {
  420                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason NoteSubTex t + "\n\n" ;
  421                         }
  422                         if (vcmn_s ubReasonTe mplateText  != null)  {
  423                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_s ubReasonTe mplateText  + "\n\n";
  424                         }
  425                    }
  426  
  427                    //If  Template  Text was p opulated,  fill in ad ditional i nfo...
  428                    if ( vcmn_templ ateNote !=  '') {
  429                         vcmn_templ ateNote =  vcmn_templ ateNote +  "\n_______ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ _\n\n";
  430                         //Is an Op ioid Agree ment curre nt and onf ile?
  431                         if (vcmn_o pioidAgree mentOnfile  != null)  {
  432                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Conse nt for Lon g-Term Opi oid Therap y for Pain :\n";
  433                             if (vc mn_opioidA greementOn file == 10 0000000) {
  434                                 // Yes Option
  435                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] Yes - S ee Posting s\n\n";
  436                             }
  437                             if (vc mn_opioidA greementOn file == 10 0000001) {
  438                                 // No Option
  439                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] No - Ve teran does  not have  a signed C onsent for  Long-Term  Opioid Th erapy for  pain (in P ostings).\ nConsent M UST be rev iewed and  signed as  soon as po ssible.\n\ n";
  440                             }
  441                         }
  442                         //Is valid  Urine Dru g Screen o n-file?
  443                         if (vcmn_U DSonfile ! = null) {
  444                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Is va lid Urine  Drug Scree n on-file? \n";
  445                             if (vc mn_UDSonfi le == 1000 00000) {
  446                                 // Yes Option
  447                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] Yes - S ee Posting s\n\n";
  448                             }
  449                             if (vc mn_UDSonfi le == 1000 00001) {
  450                                 // No Option
  451                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] No - Ve teran does  not have  a valid Ur ine Drug S creen on-f ile.\n\n";
  452                             }
  453                         }
  454                         //State Dr ug Monitor ing Report ?
  455                         if (vcmn_s tateDrugMo nitoringRe port != nu ll) {
  456                             vcmn_t emplateNot e = vcmn_t emplateNot e + "State  Prescript ion Drug M onitoring  Program (S PDMP) repo rt complet ed in last  year:\n";
  457                             if (vc mn_stateDr ugMonitori ngReport = = 10000000 0) {
  458                                 // Positive O ption
  459                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] Positiv e - see SP DMP note.\ n\n";
  460                             }
  461                             if (vc mn_stateDr ugMonitori ngReport = = 10000000 1) {
  462                                 // Negative O ption
  463                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] Negativ e.\n\n";
  464                             }
  465                             if (vc mn_stateDr ugMonitori ngReport = = 10000000 2) {
  466                                 // Not on Fil e Option
  467                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] None on  file, Pha rmacy to r equest.\n\ n";
  468                             }
  469                             //Add  in States  (2), conve rt integer s to state  names fro m form's h idden stat e options
  470                             var vc mn_usState sOptions =  Xrm.Page. getAttribu te("ftp_us statesopti on").getOp tions();
  471                             var vc mn_stateLi st = "";
  472                             if (vc mn_spdmpst ateonfile  != null) {
  473                                 // find text  value for  option
  474                                 $( vcmn_usSta tesOptions ).each(fun ction (i,  e) {
  475                                      var vcmn _optionTex t = $(this )[0].text;
  476                                      var vcmn _optionVal ue = $(thi s)[0].valu e;
  477                                      if (vcmn _spdmpstat eonfile ==  vcmn_opti onValue) {  vcmn_stat eList = vc mn_optionT ext; }
  478                                 }) ;
  479                             }
  480                             if (vc mn_sPDMPSt ate2 != nu ll) {
  481                                 // find text  value for  option
  482                                 $( vcmn_usSta tesOptions ).each(fun ction (i,  e) {
  483                                      var vcmn _optionTex t = $(this )[0].text;
  484                                      var vcmn _optionVal ue = $(thi s)[0].valu e;
  485                                      if (vcmn _sPDMPStat e2 == vcmn _optionVal ue) { vcmn _stateList  = vcmn_st ateList +  ", " +vcmn _optionTex t; }
  486                                 }) ;
  487                             }
  488                             if (vc mn_stateLi st != "")  {
  489                                 // Add states  list to n ote
  490                                 vc mn_templat eNote = vc mn_templat eNote + "S tate Presc ription Dr ug Monitor ing Progra m for the  following  state(s):  " + vcmn_s tateList;
  491                             }
  492                         }
  493  
  494                         //If ftp_p ickupmetho d has a va lue
  495                         if (vcmn_p ickupmetho d != null)  {
  496                             vcmn_t emplateNot e = vcmn_t emplateNot e + "\n___ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ _____\n\n" ;
  497                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Veter an request ed Method  of Pick Up :  ";
  498                             if (vc mn_pickupm ethod == 1 00000000)  {
  499                                 // Mail Optio n
  500                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] Mail. \ n\n";
  501                             }
  502                             if (vc mn_pickupm ethod == 1 00000001)  {
  503                                 // Window Opt ion
  504                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] Window.  \n\n";
  505                             }
  506                             //Get  veteran's  current ad dress
  507                             if (vc mn_veteran Id != null ) {
  508                                 va r vcmn_con tactData =  vcmn_getS ingleEntit yDataSync( 'ContactSe t', 'Addre ss1_Compos ite', vcmn _veteranId );
  509                                 if  (vcmn_con tactData ! = null) {
  510                                      if (vcmn _contactDa ta.d.Addre ss1_Compos ite != nul l && vcmn_ contactDat a.d.Addres s1_Composi te != '')  {
  511                                          vcmn _templateN ote = vcmn _templateN ote + "Add ress confi rmed with  caller: \n ";
  512                                          vcmn _templateN ote = vcmn _templateN ote + vcmn _contactDa ta.d.Addre ss1_Compos ite + "\n" ;
  513                                          if ( Xrm.Page.g etAttribut e('ftp_cal lbacknumbe r').getVal ue() != nu ll) {
  514                                               vcmn_templ ateNote =  vcmn_templ ateNote +  Xrm.Page.g etAttribut e('ftp_cal lbacknumbe r').getVal ue();
  515                                          }
  516                                      }
  517                                 }
  518                             }
  519                         }
  520                    }
  521  
  522                    //Wr ite note t ext if not  Triage:
  523                    if ( vcmn_triag eexpert ==  'NO' || v cmn_triage expert ==  null) {
  524                         Xrm.Page.g etAttribut e('ftp_not edetail'). setValue(v cmn_templa teNote);
  525                         Xrm.Page.g etAttribut e('ftp_not edetail'). setSubmitM ode('alway s');
  526                    }
  527                }
  528  
  529                //Defaul t Diagnosi s code if  TAN user,  based on s ystemuser  lookup
  530                var vcmn _currentUs erId = Xrm .Page.cont ext.getUse rId();
  531                var vcmn _currentUs erData = v cmn_getSin gleEntityD ataSync('S ystemUserS et', 'msdy usd_USDCon figuration Id, ftp_Fa cilitySite Id', vcmn_ currentUse rId);
  532                if (vcmn _currentUs erData !=  null) {
  533                    if ( vcmn_curre ntUserData .d.msdyusd _USDConfig urationId  != null) {
  534                         if (vcmn_c urrentUser Data.d.msd yusd_USDCo nfiguratio nId.Name ! = null) {
  535                             if (vc mn_current UserData.d .msdyusd_U SDConfigur ationId.Na me == 'TAN  Configura tion') {
  536                                 // Get Defaul t Tan Conf iguration  from User' s Facility
  537                                 if  (vcmn_cur rentUserDa ta.d.ftp_F acilitySit eId != nul l) {
  538                                      if (vcmn _currentUs erData.d.f tp_Facilit ySiteId.Id  != null)  {
  539                                          var  vcmn_curre ntUserFaci lityData =  vcmn_getS ingleEntit yDataSync( 'ftp_facil itySet', ' ftp_defaul ttandiagno siscode',  vcmn_curre ntUserData .d.ftp_Fac ilitySiteI d.Id);
  540                                          if ( vcmn_curre ntUserFaci lityData ! = null) {
  541                                               if (vcmn_c urrentUser FacilityDa ta.d.ftp_d efaulttand iagnosisco de != null ) {
  542                                                   if (vc mn_current UserFacili tyData.d.f tp_default tandiagnos iscode.Id  != null) {
  543                                                       // Write Diag nosis code  to Progre ss Note Fo rm if a Tr iage Note
  544                                                       if  (vcmn_tri ageexpert  == 'YES')  {
  545                                                            vcmn_set SimpleLook upValue('f tp_diagnos iscode', v cmn_curren tUserFacil ityData.d. ftp_defaul ttandiagno siscode.Lo gicalName,  vcmn_curr entUserFac ilityData. d.ftp_defa ulttandiag nosiscode. Id, vcmn_c urrentUser FacilityDa ta.d.ftp_d efaulttand iagnosisco de.Name);
  546                                                            Xrm.Page .getAttrib ute('ftp_d iagnosisco de').setSu bmitMode(' always');
  547                                                       }
  548                                                   }
  549                                               }
  550                                          }
  551  
  552                                          //Ma tch up the  VHG Triag e minute c onfigurati on with CP T Code
  553                                          if ( vcmn_triag eminutes >  0) {
  554                                               var vcmn_c onditional Filter = " (ftp_usert ype/Id eq  guid'" + v cmn_curren tUserData. d.msdyusd_ USDConfigu rationId.I d + "') an d (ftp_sta rtminutes  le " + vcm n_triagemi nutes + "  ) and (ftp _endminute s ge " + v cmn_triage minutes +  " )";
  555                                               vcmn_getMu ltipleEnti tyDataAsyn c('ftp_cpt codeSet',  'ftp_cptco deId, ftp_ name, ftp_ startminut es, ftp_en dminutes',  vcmn_cond itionalFil ter, 'ftp_ startminut es', 'asc' , 0, vcmn_ cptCode_re sponse, vc mn_triagem inutes);
  556                                          }
  557                                      }
  558                                 }
  559                             }
  560                         }
  561                    }
  562                }
  563  
  564                if (vcmn _requestDa ta.d.Descr iption !=  null && vc mn_request Data.d.Des cription ! = '' && vc mn_triagee xpert != ' YES' && vc mn_subReas onTemplate Text == nu ll && vcmn _templateN ote == '')  {
  565                    //Pr ompt user  to include  existing  Request No tes if the re is a cu rrent valu e
  566                    Xrm. Utility.co nfirmDialo g(
  567                         "Would you  like to i nclude the  primary n ote descri ption from  the Reque st?, Selec t OK if Ye s, otherwi se CANCEL. ",
  568                         function ( ) {
  569                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setVal ue(vcmn_re questData. d.Descript ion);
  570                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setSub mitMode('a lways');
  571                         }
  572                    );
  573                }
  574           }
  575  
  576           // Get Curren t Facility  based on  veteran/co ntact Use  Current Fa cility (ft p_currentf acilityid)  Text, if  empty use  Home Facil ity (ftp_F acilityId)
  577           if  (vcmn_vet eranId !=  null) {
  578                var vcmn _contactDa ta = vcmn_ getSingleE ntityDataS ync('Conta ctSet', 'f tp_current facilityid , ftp_Faci lityId', v cmn_vetera nId);
  579                if (vcmn _contactDa ta != null ) {
  580                    if ( vcmn_conta ctData.d.f tp_current facilityid  != null)  {
  581                         if (vcmn_c ontactData .d.ftp_cur rentfacili tyid.Id !=  null) {
  582                             vcmn_s etSimpleLo okupValue( 'ftp_patie ntfacility ', vcmn_co ntactData. d.ftp_curr entfacilit yid.Logica lName, vcm n_contactD ata.d.ftp_ currentfac ilityid.Id , vcmn_con tactData.d .ftp_curre ntfacility id.Name);
  583                             Xrm.Pa ge.getAttr ibute('ftp _patientfa cility').s etSubmitMo de('always ');
  584                         }
  585                    else  {
  586                             //Get  Facility f rom Home F acility
  587                             if (vc mn_contact Data.d.ftp _FacilityI d != null)  {
  588                                 vc mn_setSimp leLookupVa lue('ftp_p atientfaci lity', vcm n_contactD ata.d.ftp_ FacilityId .LogicalNa me, vcmn_c ontactData .d.ftp_Fac ilityId.Id , vcmn_con tactData.d .ftp_Facil ityId.Name );
  589                                 Xr m.Page.get Attribute( 'ftp_patie ntfacility ').setSubm itMode('al ways');
  590                             }
  591                         }
  592                    }
  593                    else  {
  594                         //Get Faci lity from  Home Facil ity
  595                         if (vcmn_c ontactData .d.ftp_Fac ilityId !=  null) {
  596                             vcmn_s etSimpleLo okupValue( 'ftp_patie ntfacility ', vcmn_co ntactData. d.ftp_Faci lityId.Log icalName,  vcmn_conta ctData.d.f tp_Facilit yId.Id, vc mn_contact Data.d.ftp _FacilityI d.Name);
  597                             Xrm.Pa ge.getAttr ibute('ftp _patientfa cility').s etSubmitMo de('always ');
  598                         }
  599                    }
  600                }
  601           }
  602  
  603           // Set defaul t patient  admit date
  604           Xr m.Page.get Attribute( 'ftp_patie ntadmitdat e').setVal ue(new Dat e());
  605           Xr m.Page.get Attribute( 'ftp_patie ntadmitdat e').setSub mitMode('a lways');
  606  
  607           // Set other  default fo rm values
  608           Xr m.Page.get Attribute( 'scheduled start').se tValue(new  Date());
  609           Xr m.Page.get Attribute( 'scheduled start').se tSubmitMod e('always' );
  610           Xr m.Page.get Attribute( 'scheduled end').setV alue(new D ate());
  611           Xr m.Page.get Attribute( 'scheduled end').setS ubmitMode( 'always');
  612  
  613           // Append Gen eric Templ ate Data t o top of e xisting no te
  614           va r vcmn_gen ericTempla teData = " Callback N umber: ";
  615           if  (Xrm.Page .getAttrib ute('ftp_c allbacknum ber').getV alue() !=  null && Xr m.Page.get Attribute( 'ftp_callb acknumber' ).getValue () != "")  {
  616                vcmn_gen ericTempla teData = v cmn_generi cTemplateD ata + Xrm. Page.getAt tribute('f tp_callbac knumber'). getValue() ;
  617           }
  618           // Construct  new note w ith existi ng note da ta
  619           va r vcmn_exi stingNoteD ata = "";
  620           if  (Xrm.Page .getAttrib ute("ftp_n otedetail" ).getValue () != null  && Xrm.Pa ge.getAttr ibute("ftp _notedetai l").getVal ue() != "" ) {
  621                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  622           }
  623           vc mn_generic TemplateDa ta = vcmn_ genericTem plateData  + "\n\n" +  vcmn_exis tingNoteDa ta;
  624           // Replace ex isting not e
  625           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_genericT emplateDat a);
  626           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  627  
  628           // Change Foc us to the  Notes fiel d
  629           Xr m.Page.get Control("f tp_notedet ail").setF ocus();      
  630  
  631           // Get ICN vi a web serv ice and ge t Service  Connected  disabiliti es thereaf ter
  632           // Preserved  Variables
  633           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  634           va r vcmn_vet eranFirstN ame = '';
  635           va r vcmn_vet eranLastNa me = '';
  636           va r vcmn_SSN  = '';
  637           va r vcmn_DOB  = '';
  638  
  639           // Get regard ing data
  640           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  641           if  (vcmn_req uestId ==  null) { re turn false ; }
  642           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  643  
  644           if  (vcmn_req uestData ! = null) {
  645                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  646                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  647                    //Ve rify that  the custom erid is of  type cont act
  648                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  649                         return fal se;
  650                    }
  651                }
  652           }
  653           if  (vcmn_vet eranId ==  null) {
  654                return f alse;
  655           }
  656  
  657           va r vcmn_con tactData =  vcmn_getS ingleEntit yDataSync( 'ContactSe t', 'First Name, Last Name, ftp_ DateofBirt h, Governm entId', vc mn_veteran Id.Id);
  658           if  (vcmn_con tactData ! = null) {
  659                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  660                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  661                if (vcmn _contactDa ta.d.ftp_D ateofBirth  != null)  { vcmn_DOB  = vcmn_co ntactData. d.ftp_Date ofBirth; }
  662                if (vcmn _contactDa ta.d.Gover nmentId !=  null) { v cmn_SSN =  vcmn_conta ctData.d.G overnmentI d; }
  663           }
  664  
  665           // Perform MV I Search f or Service  Connected  Disabilit ies
  666           vc mn_unatten dedMviSear chSCD(vcmn _veteranFi rstName, v cmn_vetera nLastName,  vcmn_DOB,  vcmn_SSN) ;
  667       }
  668       catch  (err) {
  669           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_newP rogressNot eLoad_WebU RL): ' + e rr.message );
  670       }
  671   }
  672  
  673   function v cmn_getSer viceConnec tedDisabil ities(vcmn _patientIC N) {
  674       try {
  675           // ******Deve loper Bypa ss for mis sing ICN** ****
  676           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  677                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  678                    aler t("Develop er ICN byp ass applie d!");
  679                    vcmn _patientIC N = "12345 6V123456";
  680                }
  681           }
  682  
  683           // Verify Pat ient ICN
  684           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  685                //No ICN , do not p roceed
  686                return f alse;
  687           }
  688  
  689           // Get the se rvice conn ected disa bilities d ata from t he web ser vice
  690           va r vcmn_dis abilitiesX mlData = v cmn_getDis abilityDat a(vcmn_pat ientICN);
  691  
  692           // Temporary  action: xm l result i s empty, u se sample  data, comm ent out wh en not use d
  693           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********
  694           // if (vcmn_d isabilitie sXmlData = = null ||  vcmn_disab ilitiesXml Data == '' ) { vcmn_d isabilitie sXmlData =  xml_resul ts3; }
  695           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********
  696  
  697           // If no data , do not p roceed.
  698           if  (vcmn_dis abilitiesX mlData ==  null || vc mn_disabil itiesXmlDa ta == '')  { return f alse; }
  699  
  700           // Create bas e Note Str ing
  701           va r vcmn_SCD noteString  = '';
  702           vc mn_SCDnote String = v cmn_SCDnot eString +  "\n------- ---------- ---------- ---------- ---------- ---------- ---------- ------\n";
  703           vc mn_SCDnote String = v cmn_SCDnot eString +  "Special T reatment A uthority a nd Service  Connected  Disabilit ies";
  704           vc mn_SCDnote String = v cmn_SCDnot eString +  "\n------- ---------- ---------- ---------- ---------- ---------- ---------- ------\n";
  705  
  706           // Search XML  values
  707           vc mn_xmlDoc  = $.parseX ML(vcmn_di sabilities XmlData);
  708           $v cmn_xml =  $(vcmn_xml Doc);
  709  
  710           // Data from  parentnode  'enrollme ntDetermin ationInfo'  
  711           va r $vcmn_en rollmentDe terminatio nInfo = nu ll;
  712           va r $vcmn_pr imaryEligi bility = n ull;
  713           va r $vcmn_ty pe = null;
  714           va r vcmn_typ eText = nu ll;
  715           va r $vcmn_en rollmentCa tegoryName  = null;
  716           va r vcmn_enr ollmentCat egoryNameT ext = null ;
  717           va r $vcmn_sp ecialFacto rs = null;
  718           va r $vcmn_en vContamina ntsInd = n ull;
  719           va r vcmn_env Contaminan tsIndText  = null;
  720           va r $vcmn_ra diationExp osureInd =  null;
  721           va r vcmn_rad iationExpo sureIndTex t = null;
  722           va r $vcmn_ag entOrangeI nd = null;
  723           va r vcmn_age ntOrangeIn dText = nu ll;
  724           va r $vcmn_ca mpLejeuneI nd = null;
  725           va r vcmn_cam pLejeuneIn dText = nu ll;
  726           va r $vcmn_se rviceConne ctionAward  = null;
  727           va r $vcmn_se rviceConne ctedPercen tage = nul l;
  728           va r vcmn_ser viceConnec tedPercent ageText =  null;
  729           va r $vcmn_ra tedDisabil ities = nu ll;
  730  
  731           va r $vcmn_ag entOrangeL ocation =  null;
  732           va r vcmn_age ntOrangeLo cationText  = null;
  733           va r $vcmn_ra diationExp osureMetho d = null;
  734           va r vcmn_rad iationExpo sureMethod Text = nul l;
  735  
  736           va r $vcmn_no seThroatRa diumInfo =  null;
  737           va r $vcmn_di agnosedWit hCancer =  null;
  738           va r vcmn_dia gnosedWith CancerText  = null;
  739  
  740           va r $vcmn_mi litarySexu alTraumaIn fo = null;
  741           va r $vcmn_mi lSexTrauma Status = n ull;
  742           va r vcmn_mil SexTraumaS tatusText  = null;
  743  
  744           // Data from  parentnode  'military ServiceInf o' 
  745           va r $vcmn_mi litaryServ iceInfo =  null;
  746           va r $vcmn_co mbatVetera nEligibili tyEndDate  = null;
  747           va r vcmn_com batVeteran Eligibilit yEndDateTe xt = null;
  748           va r $vcmn_sh adIndicato r = null;
  749           va r vcmn_sha dIndicator Text = nul l;
  750  
  751           va r vcmn_rat edDisabili tyPercenta geTotal =  0;
  752  
  753           va r vcmn_det ailrowcoun t = 0;
  754  
  755           $v cmn_enroll mentDeterm inationInf o = $vcmn_ xml.find(' enrollment Determinat ionInfo');
  756           if  ($vcmn_en rollmentDe terminatio nInfo != n ull) {
  757                $vcmn_pr imaryEligi bility = $ vcmn_enrol lmentDeter minationIn fo.find('p rimaryElig ibility');
  758                if ($vcm n_primaryE ligibility  != null)  {
  759                    $vcm n_type = $ vcmn_prima ryEligibil ity.find(' type');
  760                    if ( $vcmn_type  != null)  { vcmn_typ eText = $v cmn_type.t ext(); }
  761                }
  762  
  763                $vcmn_en rollmentCa tegoryName  = $vcmn_e nrollmentD eterminati onInfo.fin d('enrollm entCategor yName');
  764                if ($vcm n_enrollme ntCategory Name != nu ll) { vcmn _enrollmen tCategoryN ameText =  $vcmn_enro llmentCate goryName.t ext(); }
  765  
  766                $vcmn_sp ecialFacto rs = $vcmn _enrollmen tDetermina tionInfo.f ind('speci alFactors' );
  767                if ($vcm n_specialF actors !=  null) {
  768                    $vcm n_envConta minantsInd  = $vcmn_s pecialFact ors.find(' envContami nantsInd') ;
  769                    if ( $vcmn_envC ontaminant sInd != nu ll) { vcmn _envContam inantsIndT ext = $vcm n_envConta minantsInd .text(); }
  770                    $vcm n_radiatio nExposureI nd = $vcmn _specialFa ctors.find ('radiatio nExposureI nd');
  771                    if ( $vcmn_radi ationExpos ureInd !=  null) { vc mn_radiati onExposure IndText =  $vcmn_radi ationExpos ureInd.tex t(); }
  772                    $vcm n_agentOra ngeInd = $ vcmn_speci alFactors. find('agen tOrangeInd ');
  773                    if ( $vcmn_agen tOrangeInd  != null)  { vcmn_age ntOrangeIn dText = $v cmn_agentO rangeInd.t ext(); }
  774                    $vcm n_campLeje uneInd = $ vcmn_speci alFactors. find('camp LejeuneInd ');
  775                    if ( $vcmn_camp LejeuneInd  != null)  { vcmn_cam pLejeuneIn dText = $v cmn_campLe jeuneInd.t ext(); }
  776  
  777                    $vcm n_agentOra ngeLocatio n = $vcmn_ specialFac tors.find( 'agentOran geLocation ');
  778                    if ( $vcmn_agen tOrangeLoc ation != n ull) { vcm n_agentOra ngeLocatio nText = $v cmn_agentO rangeLocat ion.text() ; }
  779                    $vcm n_radiatio nExposureM ethod = $v cmn_specia lFactors.f ind('radia tionExposu reMethod') ;
  780                    if ( $vcmn_radi ationExpos ureMethod  != null) {  vcmn_radi ationExpos ureMethodT ext = $vcm n_radiatio nExposureM ethod.text (); }
  781                }
  782  
  783                $vcmn_se rviceConne ctionAward  = $vcmn_e nrollmentD eterminati onInfo.fin d('service Connection Award');
  784                if ($vcm n_serviceC onnectionA ward != nu ll) {
  785                    $vcm n_serviceC onnectedPe rcentage =  $vcmn_ser viceConnec tionAward. find('serv iceConnect edPercenta ge');
  786                    if ( $vcmn_serv iceConnect edPercenta ge != null ) { vcmn_s erviceConn ectedPerce ntageText  = $vcmn_se rviceConne ctedPercen tage.text( ); }
  787                    $vcm n_ratedDis abilities  = $vcmn_se rviceConne ctionAward .find('rat edDisabili ties');
  788                    //Ge t each dis ability li sted and a dd to note  string
  789                    vcmn _SCDnoteSt ring = vcm n_SCDnoteS tring + "S C Disabili ty: ";
  790                    $vcm n_ratedDis abilities. find('rate dDisabilit y').each(f unction ()  {
  791                         var vcmn_r atedDisabi lityPercen t = 0;
  792                         var vcmn_d isability  = null;
  793                         if (Number ($(this).f ind('perce ntage').te xt()) > 0)  {
  794                             vcmn_r atedDisabi lityPercen tageTotal  = vcmn_rat edDisabili tyPercenta geTotal +  Number($(t his).find( 'percentag e').text() );
  795                             vcmn_r atedDisabi lityPercen t = Number ($(this).f ind('perce ntage').te xt());
  796                         }
  797                         //Add Rate d Disabili ties to th e Note Str ing if Dis ability Pe rcent > 0
  798                         if (vcmn_r atedDisabi lityPercen t > 0) {
  799                             vcmn_S CDnoteStri ng = vcmn_ SCDnoteStr ing + $(th is).find(' disability ').text()  + "\n";
  800                         }
  801                    });
  802                    vcmn _SCDnoteSt ring = vcm n_SCDnoteS tring + "\ n";
  803                }
  804  
  805                $vcmn_no seThroatRa diumInfo =  $vcmn_enr ollmentDet ermination Info.find( 'noseThroa tRadiumInf o');
  806                if ($vcm n_noseThro atRadiumIn fo != null ) {
  807                    $vcm n_diagnose dWithCance r = $vcmn_ noseThroat RadiumInfo .find('dia gnosedWith Cancer');
  808                    if ( $vcmn_diag nosedWithC ancer != n ull) { vcm n_diagnose dWithCance rText = $v cmn_diagno sedWithCan cer.text() ; }
  809                }
  810  
  811                $vcmn_mi litarySexu alTraumaIn fo = $vcmn _enrollmen tDetermina tionInfo.f ind('milit arySexualT raumaInfo' );
  812                if ($vcm n_military SexualTrau maInfo !=  null) {
  813                    $vcm n_milSexTr aumaStatus  = $vcmn_m ilitarySex ualTraumaI nfo.find(' status');
  814                    if ( $vcmn_milS exTraumaSt atus != nu ll) { vcmn _milSexTra umaStatusT ext = $vcm n_milSexTr aumaStatus .text(); }
  815                }
  816           }
  817  
  818           $v cmn_milita ryServiceI nfo = $vcm n_xml.find ('military ServiceInf o');
  819           if  ($vcmn_mi litaryServ iceInfo !=  null) {
  820                $vcmn_co mbatVetera nEligibili tyEndDate  = $vcmn_mi litaryServ iceInfo.fi nd('combat VeteranEli gibilityEn dDate');
  821                if ($vcm n_combatVe teranEligi bilityEndD ate != nul l) {
  822                    vcmn _combatVet eranEligib ilityEndDa teText = v cmn_combat VeteranEli gibilityEn dDateText  = $vcmn_co mbatVetera nEligibili tyEndDate. text();
  823                }
  824                $vcmn_sh adIndicato r = $vcmn_ militarySe rviceInfo. find('shad Indicator' );
  825                if ($vcm n_shadIndi cator != n ull) { vcm n_shadIndi catorText  = $vcmn_sh adIndicato r.text();  }
  826           }
  827  
  828           // If no elig ibility sp ecified, s et to fals e
  829           if  (vcmn_typ eText == n ull || vcm n_typeText  == '') {  vcmn_typeT ext = fals e; }
  830  
  831           // Change boo lean value s to false  if not ma rked true
  832           if  (vcmn_env Contaminan tsIndText  != 'true')  { vcmn_en vContamina ntsIndText  = false;  }
  833           if  (vcmn_rad iationExpo sureIndTex t != 'true ') { vcmn_ radiationE xposureInd Text = fal se; }
  834           if  (vcmn_age ntOrangeIn dText != ' true') { v cmn_agentO rangeIndTe xt = false ; }
  835           if  (vcmn_cam pLejeuneIn dText != ' true') { v cmn_campLe jeuneIndTe xt = false ; }
  836  
  837           if  (vcmn_dia gnosedWith CancerText  != 'true' ) { vcmn_d iagnosedWi thCancerTe xt = false ; }
  838           if  (vcmn_sha dIndicator Text != 't rue') { vc mn_shadInd icatorText  = false;  }
  839  
  840           // Change all  True/Fals e to Yes/N o
  841           if  (vcmn_typ eText == f alse) { vc mn_typeTex t = 'No';  }
  842  
  843           if  (vcmn_env Contaminan tsIndText  == "true")  { vcmn_en vContamina ntsIndText  = "Yes";  } else { v cmn_envCon taminantsI ndText = " No"; }
  844           if  (vcmn_rad iationExpo sureIndTex t == "true ") {
  845                vcmn_rad iationExpo sureIndTex t = "Yes";
  846                if (vcmn _radiation ExposureMe thodText ! = null) {  vcmn_radia tionExposu reIndText  = vcmn_rad iationExpo sureIndTex t + " - "  + vcmn_rad iationExpo sureMethod Text; }
  847           }  else {
  848                vcmn_rad iationExpo sureIndTex t = "No"; 
  849           }
  850           if  (vcmn_age ntOrangeIn dText == " true") {
  851                vcmn_age ntOrangeIn dText = "Y es";
  852                if (vcmn _agentOran geLocation Text != nu ll) { vcmn _agentOran geIndText  = vcmn_age ntOrangeIn dText + "  - " + vcmn _agentOran geLocation Text; }
  853           }
  854           el se {
  855                vcmn_age ntOrangeIn dText = "N o"; 
  856           }
  857           if  (vcmn_cam pLejeuneIn dText == " true") { v cmn_campLe jeuneIndTe xt = "Yes" ; } else {  vcmn_camp LejeuneInd Text = "No "; }
  858  
  859           if  (vcmn_dia gnosedWith CancerText  == "true" ) { vcmn_d iagnosedWi thCancerTe xt = "Yes" ; } else {  vcmn_diag nosedWithC ancerText  = "No"; }
  860  
  861           if  (vcmn_com batVeteran Eligibilit yEndDateTe xt != null  && vcmn_c ombatVeter anEligibil ityEndDate Text != '' ) { vcmn_c ombatVeter anEligibil ityEndDate Text = 'Ye s'; } 
  862  
  863           if  (vcmn_sha dIndicator Text == "t rue") { vc mn_shadInd icatorText  = "Yes";  } else { v cmn_shadIn dicatorTex t = "No";  }
  864           
  865           // Construct  summary no te part
  866           if  (vcmn_env Contaminan tsIndText  != null &&  vcmn_envC ontaminant sIndText ! = '') { vc mn_SCDnote String = v cmn_SCDnot eString +  "Environme ntal Conta minant: "  + vcmn_env Contaminan tsIndText  + "\n"; }
  867           if  (vcmn_com batVeteran Eligibilit yEndDateTe xt != null  && vcmn_c ombatVeter anEligibil ityEndDate Text != '' ) { vcmn_S CDnoteStri ng = vcmn_ SCDnoteStr ing + "Com bat Vetera n: " + vcm n_combatVe teranEligi bilityEndD ateText +  "\n"; }
  868           if  (vcmn_rad iationExpo sureIndTex t != null  && vcmn_ra diationExp osureIndTe xt != '')  { vcmn_SCD noteString  = vcmn_SC DnoteStrin g + "Radia tion Expos ure: " + v cmn_radiat ionExposur eIndText +  "\n"; }
  869           if  (vcmn_age ntOrangeIn dText != n ull && vcm n_agentOra ngeIndText  != '') {  vcmn_SCDno teString =  vcmn_SCDn oteString  + "Agent O range: " +  vcmn_agen tOrangeInd Text + "\n "; }
  870           if  (vcmn_sha dIndicator Text != nu ll && vcmn _shadIndic atorText ! = '') { vc mn_SCDnote String = v cmn_SCDnot eString +  "Shipboard  Hazard &  Defense: "  + vcmn_sh adIndicato rText + "\ n"; }
  871           if  (vcmn_dia gnosedWith CancerText  != null & & vcmn_dia gnosedWith CancerText  != '') {  vcmn_SCDno teString =  vcmn_SCDn oteString  + "Head/Ne ck Cancer:  " + vcmn_ diagnosedW ithCancerT ext + "\n" ; }
  872           if  (vcmn_mil SexTraumaS tatusText  != null &&  vcmn_milS exTraumaSt atusText ! = '') { vc mn_SCDnote String = v cmn_SCDnot eString +  "Military  Sexual Tra uma: " + v cmn_milSex TraumaStat usText + " \n"; }
  873           if  (vcmn_cam pLejeuneIn dText != n ull && vcm n_campLeje uneIndText  != '') {  vcmn_SCDno teString =  vcmn_SCDn oteString  + "Camp Le jeune: " +  vcmn_camp LejeuneInd Text + "\n "; }
  874  
  875           // Update not e with new  SCD note  data
  876           va r vcmn_exi stingNoteD ata = "";
  877           if  (Xrm.Page .getAttrib ute("ftp_n otedetail" ).getValue () != null  && Xrm.Pa ge.getAttr ibute("ftp _notedetai l").getVal ue() != "" ) {
  878                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  879           }
  880           vc mn_extende dTemplateD ata = vcmn _existingN oteData +  vcmn_SCDno teString;
  881           // Replace ex isting not e
  882           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_extended TemplateDa ta);
  883           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  884       }
  885       catch  (err) {
  886           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getS erviceConn ectedDisab ilities):  ' + err.me ssage);
  887       }
  888   }
  889  
  890   function v cmn_getDis abilityDat a(vcmn_nat ionalId) {
  891       try {
  892           va r vcmn_ees ummaryURL  = vcmn_ees ummaryURLb ase + '000 000' + vcm n_national Id + '0000 00';
  893           va r vcmn_xml Data = nul l;
  894  
  895           $. ajax({
  896                type: "G ET",
  897                url: vcm n_eesummar yURL,
  898                contentT ype: "appl ication/xm l; charset =utf-8",
  899                dataType : "text",
  900                success:  function  (xmlTextda ta) {
  901                    vcmn _xmlData =  xmlTextda ta;
  902                },
  903                error: f unction (j qXHR, text Status, er rorThrown)  {
  904                    //Sy stem Error
  905                    vcmn _xmlData =  null;
  906                },
  907                async: f alse,
  908                cache: f alse
  909           }) ;
  910           re turn vcmn_ xmlData;
  911       }
  912       catch  (err) {
  913           al ert("Progr ess Note F orm Load S cript Func tion Error (vcmn_getD isabilityD ata): " +  err.messag e);
  914           re turn null;
  915       }
  916   }
  917  
  918   function v cmn_facili tyByCode_r esponse(vc mn_facilit yData, vcm n_lastSkip , vcmn_fac ilityCode)  {
  919       try {
  920           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  921           // ***REVISED  NOT USED,  KEEP FOR  FUTURE UPD ATE***
  922           /*
  923           va r vcmn_fac ilityid =  null;
  924           va r vcmn_fac ilityname  = null;
  925           fo r (var i =  0; i <= v cmn_facili tyData.d.r esults.len gth - 1; i ++) {
  926                //Get in fo
  927                if (vcmn _facilityD ata.d.resu lts[i].ftp _facilityI d != null)  { vcmn_fa cilityid =  vcmn_faci lityData.d .results[i ].ftp_faci lityId; }
  928                if (vcmn _facilityD ata.d.resu lts[i].ftp _name != n ull) { vcm n_facility name = vcm n_facility Data.d.res ults[i].ft p_name; }
  929                break;
  930           }
  931           if  (vcmn_fac ilityid !=  null) {
  932                vcmn_set SimpleLook upValue('f tp_patient facility',  'ftp_faci lity', vcm n_facility id, vcmn_f acilitynam e);
  933                Xrm.Page .getAttrib ute('ftp_p atientfaci lity').set SubmitMode ('always') ;
  934           }
  935           */
  936       }
  937       catch  (err) {
  938           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_faci lityByCode _response) : ' + err. message);
  939       }
  940   }
  941  
  942   function v cmn_cptCod e_response (vcmn_cptC odeData, v cmn_lastSk ip, vcmn_t riageminut es) {
  943       try {
  944           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  945           fo r (var i =  0; i <= v cmn_cptCod eData.d.re sults.leng th - 1; i+ +) {
  946                //Write  to CRM pro gress note  form
  947                vcmn_set SimpleLook upValue('f tp_cptcode ', 'ftp_cp tcode', vc mn_cptCode Data.d.res ults[i].ft p_cptcodeI d, vcmn_cp tCodeData. d.results[ i].ftp_nam e);
  948                Xrm.Page .getAttrib ute('ftp_c ptcode').s etSubmitMo de('always ');
  949                break;
  950           }
  951       }
  952       catch  (err) {
  953           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_cptC ode_respon se): ' + e rr.message );
  954       }
  955   }
  956  
  957   function v cmn_ribbon ButtonSave () {
  958       try {
  959           // Save the c urrent CRM  data
  960           Xr m.Page.dat a.entity.s ave();
  961       }
  962       catch  (err) {
  963           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa ve): ' + e rr.message );
  964       }
  965   }
  966  
  967   function v cmn_getCoo kie(cname)  {
  968       try {
  969           va r name = c name + "=" ;
  970           va r ca = doc ument.cook ie.split(' ;');
  971           fo r (var i =  0; i < ca .length; i ++) {
  972                var c =  ca[i];
  973                while (c .charAt(0)  == ' ') {
  974                    c =  c.substrin g(1);
  975                }
  976                if (c.in dexOf(name ) == 0) {
  977                    retu rn c.subst ring(name. length, c. length);
  978                }
  979           }
  980           re turn "";
  981       }
  982       catch  (err) {
  983           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getC ookie): '  + err.mess age);
  984       }
  985   }
  986  
  987   function v cmn_ribbon ButtonSave ToVistA()  {
  988       try {
  989           // Check the  value of t he Integra tion Statu s Field, i f = 'OK',  stop and e xit this s cript
  990           va r vcmn_int egrationSt atus = Xrm .Page.getA ttribute(' ftp_integr ationstatu s').getVal ue();
  991           if  (vcmn_int egrationSt atus == 'O K') { retu rn false;  }
  992  
  993           // Prompt use r to sign  the note
  994           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  995           va r vcmn_sig nThisNoteF ailure = f alse;
  996           if  (vcmn_sig nThisNote  == null) {
  997                Xrm.Util ity.confir mDialog(
  998                    "Do  you need t o sign thi s note?, S elect OK i f Yes, oth erwise CAN CEL.",
  999                    func tion () {
  1000                         //Check if  VIA Login  cookie ex ist (not e xpired)
  1001                         var vcmn_V iaLoginCoo kie = vcmn _getCookie ("viasessi onlink");
  1002                         //Prompt u ser to log in to VIA
  1003                         if (vcmn_V iaLoginCoo kie == "")  {
  1004                             alert( "Your VIST A session  has expire d. In orde r to sign  this note,  you must  be logged  into VISTA !");
  1005                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setVisi ble(false) ;
  1006                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setFocu s();
  1007                             vcmn_s ignThisNot eFailure =  true;
  1008                             return ;
  1009                         }
  1010                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000001 );
  1011                    },
  1012                    func tion () {
  1013                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000000 );
  1014                    }
  1015                );
  1016                Xrm.Page .getAttrib ute('ftp_s ignthisnot e').setSub mitMode('a lways');
  1017           }
  1018           if  (vcmn_sig nThisNoteF ailure ==  true) {
  1019                //****** Developer  Bypass for  no VISTA  authentica tion******
  1020                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}" || (X rm.Page.co ntext.getU serId()).t oUpperCase () == "{EB 21BC63-81B F-E511-942 C-0050568D 743D}") {
  1021                    aler t("Develop er VISTA a uthenticat ion bypass  applied!" );
  1022                    Xrm. Page.getAt tribute('f tp_signthi snote').se tValue(100 000001);
  1023                    Xrm. Page.getAt tribute('f tp_signthi snote').se tSubmitMod e('always' );
  1024                }
  1025                else {
  1026                    retu rn false;
  1027                }
  1028           }
  1029  
  1030           // Save the c urrent CRM  data
  1031           Xr m.Page.dat a.entity.s ave();
  1032           // Display YE LLOW Progr ess....
  1033           Xr m.Page.ui. setFormNot ification( "Verifying  progress  note data,  please wa it..", "IN FO", "SAVE VISTA");
  1034  
  1035           va r vcmn_con firmSaveTo Vista = co nfirm('Are  you sure  you want t o save thi s note to  VistA/CPRS ?\nThis ac tion canno t be cance lled!\n\nU pon comple tion of th is process , the prog ress note  will autom atically b e marked a s complete d and you  will be pr ompted to  exit the r ecord!');
  1036           if  (vcmn_con firmSaveTo Vista == f alse) {
  1037                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1038                return f alse;
  1039           }
  1040           // Get regard ing data
  1041           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1042           if  (vcmn_req uestId ==  null) {
  1043                alert('T he current  progress  note does  not have a  related r equest ass igned in t he Regardi ng field,  the note c annot be c reated in  VistA/CPRS !');
  1044                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  1045                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1046                return f alse;
  1047           }
  1048           // Verify tha t the rega rdingid is  of type ' incident'
  1049           if  (vcmn_req uestId[0]. entityType  != 'incid ent') {
  1050                alert('T he current  progress  note has a n invalid  regarding  type, it m ust be of  the type r equest/inc ident, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  1051                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  1052                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1053                return f alse;
  1054           }
  1055  
  1056           // Preserved  Variables
  1057           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1058           va r vcmn_vet eranFirstN ame = '';
  1059           va r vcmn_vet eranLastNa me = '';
  1060           va r vcmn_SSN  = '';
  1061           va r vcmn_DOB  = '';
  1062  
  1063           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1064           if  (vcmn_req uestData ! = null) {
  1065                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1066                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1067                    //Ve rify that  the custom erid is of  type cont act
  1068                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1069                         alert('The  related r equest has  an invali d customer  type, it  must be of  the type  veteran/co ntact, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  1070                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1071                         return fal se;
  1072                    }
  1073                }
  1074           }
  1075           if  (vcmn_vet eranId ==  null) {
  1076                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  1077                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1078                return f alse;
  1079           }
  1080  
  1081           va r vcmn_con tactData =  vcmn_getS ingleEntit yDataSync( 'ContactSe t', 'First Name, Last Name, ftp_ DateofBirt h, Governm entId', vc mn_veteran Id.Id);
  1082           if  (vcmn_con tactData ! = null) {
  1083                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1084                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1085                if (vcmn _contactDa ta.d.ftp_D ateofBirth  != null)  { vcmn_DOB  = vcmn_co ntactData. d.ftp_Date ofBirth; }
  1086                if (vcmn _contactDa ta.d.Gover nmentId !=  null) { v cmn_SSN =  vcmn_conta ctData.d.G overnmentI d; }
  1087           }
  1088  
  1089           // Perform MV I Search
  1090           vc mn_unatten dedMviSear ch(vcmn_ve teranFirst Name, vcmn _veteranLa stName, vc mn_DOB, vc mn_SSN);
  1091       }
  1092       catch  (err) {
  1093           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa veToVistA) : ' + err. message);
  1094           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1095       }
  1096   }
  1097  
  1098   function v cmn_ribbon ButtonSave ToVistA_wi th_ICN(vcm n_patientI CN) {
  1099       try {
  1100           // ******Deve loper Bypa ss for mis sing ICN** ****
  1101           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1102                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  1103                    aler t("Develop er ICN byp ass applie d!");
  1104                    vcmn _patientIC N = "12345 6V123456";
  1105                }
  1106           }
  1107  
  1108           // Verify Pat ient ICN
  1109           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1110                alert('T he assigne d veteran  does not h ave a pati ent ICN, t he note ca nnot be cr eated in V istA/CPRS! ');
  1111                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1112                return f alse;
  1113           }
  1114           
  1115           // Get regard ing data
  1116           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1117  
  1118           // Preserved  Variables
  1119           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1120           va r vcmn_vet eranName =  '';
  1121           va r vcmn_vet eranFirstN ame = '';
  1122           va r vcmn_vet eranLastNa me = '';
  1123           va r vcmn_vet eranMiddle Name = '';
  1124  
  1125           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1126           if  (vcmn_req uestData ! = null) {
  1127                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1128                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1129                    //Ve rify that  the custom erid is of  type cont act
  1130                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1131                         alert('The  related r equest has  an invali d customer  type, it  must be of  the type  veteran/co ntact, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  1132                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1133                         return fal se;
  1134                    }
  1135                }
  1136           }
  1137           if  (vcmn_vet eranId ==  null) {
  1138                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  1139                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1140                return f alse;
  1141           }
  1142  
  1143           va r vcmn_con tactData =  vcmn_getS ingleEntit yDataSync( 'ContactSe t', 'FullN ame, First Name, Last Name, Midd leName', v cmn_vetera nId.Id);
  1144           if  (vcmn_con tactData ! = null) {
  1145                if (vcmn _contactDa ta.d.FullN ame != nul l) { vcmn_ veteranNam e = vcmn_c ontactData .d.FullNam e; }
  1146                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1147                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1148                if (vcmn _contactDa ta.d.Middl eName != n ull) { vcm n_veteranM iddleName  = vcmn_con tactData.d .MiddleNam e; }
  1149           }
  1150  
  1151           // Get user d ata
  1152           va r vcmn_crm UserId = X rm.Page.ge tAttribute ('ownerid' ).getValue ();
  1153           va r vcmn_use rDomainId  = '';
  1154           va r vcmn_use rFirstName  = '';
  1155           va r vcmn_use rLastName  = '';
  1156           va r vcmn_use rMiddleNam e = '';
  1157           va r vcmn_use rSiteId =  '';
  1158  
  1159           if  (vcmn_crm UserId !=  null) {
  1160                //Verify  the owner  type
  1161                if (vcmn _crmUserId [0].entity Type != 's ystemuser' ) {
  1162                    aler t('The pro gress note  owner mus t be an in dividual u ser and no t a team,  the note c annot be c reated in  VistA/CPRS !');
  1163                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1164                    retu rn false;
  1165                }
  1166  
  1167                var vcmn _userData  = vcmn_get SingleEnti tyDataSync ('SystemUs erSet', 'D omainName,  FirstName , LastName , MiddleNa me, ftp_Fa cilitySite Id', vcmn_ crmUserId[ 0].id);
  1168                if (vcmn _userData  != null) {
  1169                    if ( vcmn_userD ata.d.Doma inName !=  null) { vc mn_userDom ainId = vc mn_userDat a.d.Domain Name; }
  1170                    if ( vcmn_userD ata.d.Firs tName != n ull) { vcm n_userFirs tName = vc mn_userDat a.d.FirstN ame; }
  1171                    if ( vcmn_userD ata.d.Last Name != nu ll) { vcmn _userLastN ame = vcmn _userData. d.LastName ; }
  1172                    if ( vcmn_userD ata.d.Midd leName !=  null) { vc mn_userMid dleName =  vcmn_userD ata.d.Midd leName; }
  1173                    if ( vcmn_userD ata.d.ftp_ FacilitySi teId != nu ll) { vcmn _userSiteI d = vcmn_u serData.d. ftp_Facili tySiteId.I d; }
  1174                }
  1175           }
  1176           el se {
  1177                alert('U nable to v erify the  user accou nt for the  current a uthor/owne r assigned  to this n ote, the n ote cannot  be create d in VistA /CPRS!');
  1178                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1179                return f alse;
  1180           }
  1181  
  1182           // Verify tha t the curr ent owner  and the cu rrent user  is the sa me person,  if not do  not proce ed
  1183           if  ((vcmn_cr mUserId[0] .id).toUpp erCase() ! = (Xrm.Pag e.context. getUserId( )).toUpper Case()) {
  1184                alert('T he current  author/ow ner does n ot match t he current  CRM user,  the note  cannot be  created in  VistA/CPR S!');
  1185                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1186                return f alse;
  1187           }
  1188           va r vcmn_Not eUserTeam  = "NONE";
  1189           // Check Team  membershi p
  1190           if  (vcmn_Use rHasTeam(" Pharmacy",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "PHARM ACY"; }
  1191           if  (vcmn_Use rHasTeam(" CCA Team",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "CCA";  }
  1192           if  (vcmn_Use rHasTeam(" TAN", Xrm. Page.conte xt.getUser Id())) { v cmn_NoteUs erTeam = " TAN"; }
  1193           // **TEMP, ve rify these  team valu es that th ey are cor rect **FUT URE NEED**
  1194           if  (vcmn_Use rHasTeam(" PACT User" , Xrm.Page .context.g etUserId() )) { vcmn_ NoteUserTe am = "PACT "; }
  1195           if  (vcmn_Use rHasTeam(" MSA User",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "MSA";  }
  1196  
  1197           // Verify Tea m Value, t hat one ha s been ass igned
  1198           if  (vcmn_Not eUserTeam  == "NONE")  {
  1199                alert('T he current  author/ow ner does n ot belong  to a CRM t eam that c an integra te notes,  the note c annot be c reated in  VistA/CPRS !');
  1200                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1201                return f alse;
  1202           }
  1203  
  1204           // Get reques t form con tent
  1205           va r vcmn_not eDescripti on = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  1206           if  (vcmn_not eDescripti on == null  || vcmn_n oteDescrip tion == '' ) {
  1207                alert('T he note de scription  field is e mpty, the  note canno t be creat ed in Vist A/CPRS!');
  1208                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1209                return f alse;
  1210           }
  1211  
  1212           // Using new  hospital l ocation an d local no tes lookup  fields
  1213           va r vcmn_loc alTitle =  Xrm.Page.g etAttribut e('ftp_loc alnotetitl e').getVal ue();
  1214           if  (vcmn_loc alTitle ==  null) {
  1215                alert('T he local n ote title  field is e mpty, the  note canno t be creat ed in Vist A/CPRS!');
  1216                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1217                return f alse;
  1218           }
  1219           el se { vcmn_ localTitle  = vcmn_lo calTitle[0 ].name; }
  1220  
  1221           vc mn_patient AssignedLo cation = X rm.Page.ge tAttribute ('ftp_note hospitallo cation').g etValue();
  1222           if  (vcmn_pat ientAssign edLocation  == null)  {
  1223                alert('T he hospita l location  field is  empty, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  1224                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1225                return f alse;
  1226           }
  1227           el se { vcmn_ patientAss ignedLocat ion = vcmn _patientAs signedLoca tion[0].na me; }
  1228           
  1229           va r vcmn_cal lbackNumbe r = Xrm.Pa ge.getAttr ibute('ftp _callbackn umber').ge tValue();
  1230           if  (vcmn_cal lbackNumbe r == null  || vcmn_ca llbackNumb er == '')  {
  1231                alert('T he callbac k number f ield is em pty, the n ote cannot  be create d in VistA /CPRS!');
  1232                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1233                return f alse;
  1234           }
  1235           va r vcmn_rea sonForRequ est = Xrm. Page.getAt tribute('f tp_reasonf orrequest' ).getValue ();
  1236           if  (vcmn_rea sonForRequ est == nul l) {
  1237                alert('T he reason  for reques t field is  empty, th e note can not be cre ated in Vi stA/CPRS!' );
  1238                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1239                return f alse;
  1240           }
  1241  
  1242           va r vcmn_enc ounterCode  = 'NEW';
  1243  
  1244           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  1245           if  (vcmn_sig nThisNote  == 1000000 01) { vcmn _signThisN ote = true ; } else {  vcmn_sign ThisNote =  false; }
  1246           va r vcmn_cre atedDateTi me = Xrm.P age.getAtt ribute('sc heduledsta rt').getVa lue();
  1247  
  1248           // Get Progre ss Note Gu id/Id
  1249           va r vcmn_not eId = Xrm. Page.data. entity.get Id();
  1250  
  1251           // Get Create d On Date  & Convert  format
  1252           va r vcmn_cre atedOnDate  = vcmn_co nvertCrmDa teToVistAD ate(Xrm.Pa ge.getAttr ibute('cre atedon').g etValue()) ;
  1253           if  (vcmn_cre atedOnDate  == null)  {
  1254                alert('T he CRM cre atedon fie ld is empt y, the not e cannot b e created  in VistA/C PRS!');
  1255                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1256                return f alse;
  1257           }     
  1258  
  1259           // Get Patien t Admit Da te & Conve rt format
  1260           va r vcmn_pat ientAdmitD ate = vcmn _convertCr mDateToVis tADate(Xrm .Page.getA ttribute(' ftp_patien tadmitdate ').getValu e());
  1261  
  1262           if  (vcmn_pat ientAdmitD ate == nul l) {
  1263                alert('T he CRM pat ient admit  date fiel d is empty , the note  cannot be  created i n VistA/CP RS!');
  1264                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1265                return f alse;
  1266           }
  1267  
  1268           // Get Facili ty and loo kup facili ty number  and HL7 UR L
  1269           va r vcmn_fac ilityCode  = '';
  1270           va r vcmn_sit eHL7Listen erAddress  = '';
  1271           va r vcmn_pat ientFacili ty = Xrm.P age.getAtt ribute('ft p_patientf acility'). getValue() ;
  1272           if  (vcmn_pat ientFacili ty == null ) {
  1273                alert('T he CRM pat ient facil ity field  is empty,  the note c annot be c reated in  VistA/CPRS !');
  1274                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1275                return f alse;
  1276           }
  1277           el se {
  1278                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e, ftp_hl7 listener',  vcmn_pati entFacilit y[0].id);
  1279                if (vcmn _facilityD ata.d.ftp_ facilityco de != null ) {
  1280                    vcmn _facilityC ode = vcmn _facilityD ata.d.ftp_ facilityco de;
  1281                }
  1282                else {
  1283                    aler t('The CRM  patient f acility co de is miss ing in the  Facility  setup, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  1284                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1285                    retu rn false;
  1286                }
  1287  
  1288                if (vcmn _facilityD ata.d.ftp_ hl7listene r != null)  {
  1289                    var  vcmn_siteH L7Listener Address =  vcmn_facil ityData.d. ftp_hl7lis tener;
  1290                }
  1291                else {
  1292                    aler t('The CRM  HL7 liste ner addres s is missi ng in the  Facility s etup, the  note canno t be creat ed in Vist A/CPRS!');
  1293                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1294                    retu rn false;
  1295                }
  1296           }
  1297  
  1298           va r vcmn_ori ginatorID  = '';
  1299           va r vcmn_use rSiteNo =  '';
  1300  
  1301           // Lookup the  Facility/ Site #
  1302           if  (vcmn_use rSiteId !=  null && v cmn_userSi teId != '' ) {
  1303                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e', vcmn_u serSiteId) ;
  1304                if (vcmn _facilityD ata != nul l) {
  1305                    if ( vcmn_facil ityData.d. ftp_facili tycode !=  null) { vc mn_userSit eNo = vcmn _facilityD ata.d.ftp_ facilityco de; }
  1306                }
  1307           }
  1308  
  1309           // Validate r equired Vi sta Lookup  info
  1310           if  (vcmn_use rSiteNo ==  '' || vcm n_userSite No == null  || vcmn_u serFirstNa me == '' | | vcmn_use rFirstName  == null | | vcmn_use rLastName  == '' || v cmn_userLa stName ==  null) {
  1311                //Abort  process, m issing inf o
  1312                alert('O ne of the  following  required C RM user da ta fields  are missin g: Facilty  No, First  Name or L ast Name,  the note c annot be c reated in  VistA/CPRS !');
  1313                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1314                return f alse;
  1315           }
  1316  
  1317           // ***Tempora ry Test Us er Search* *******
  1318           // Provide th e option t o search f or Lori Ni cholls, si te# 613
  1319           va r vcmn_imp ersonatePr omptString  = "**THIS  IS A VIST A USER SEA RCH TEST P ROMPT** \n " +
  1320                "If you  would like  to impers onate the  user: \n"  +
  1321                "Lori Ni cholls (61 3) \n" +
  1322                "Select  OK.  Other wise, sele ct CANCEL. ";
  1323           va r vcmn_con firmImpers onateVista User = con firm(vcmn_ impersonat ePromptStr ing);
  1324           if  (vcmn_con firmImpers onateVista User == tr ue) {
  1325                vcmn_use rFirstName  = "Lori";
  1326                vcmn_use rLastName  = "Nicholl s";
  1327                vcmn_use rSiteNo =  "613";
  1328           }
  1329           // ********** ********** ********** *******
  1330  
  1331           va r vcmn_vis tausersDat a = vcmn_g etVistaUse rsData(vcm n_userFirs tName, vcm n_userLast Name, vcmn _userSiteN o, false);
  1332  
  1333           // ********** ********** ********** *********
  1334           // Temporary  JSON TEST  DATA, comm ent out wh en not nee ded
  1335           /*
  1336           vc mn_vistaus ersData =  {
  1337                "ErrorOc curred": f alse,
  1338                "ErrorMe ssage": nu ll,
  1339                "Status" : null,
  1340                "DebugIn fo": null,
  1341                "Data":  [
  1342                         {
  1343                             "First Name": "LO RI",
  1344                             "Middl eName": "E ",
  1345                             "LastN ame": "NIC HOLLS",
  1346                             "Suffi x": "JR",
  1347                             "Displ ayName": " NICHOLLS,L ORI E JR",
  1348                             "Title ": "HDR Sr . Develope r"
  1349                          },
  1350                          {
  1351                              "Firs tName": "F IVE",
  1352                              "Midd leName": " ",
  1353                              "Last Name": "PR OVIDER",
  1354                              "Titl e": "Schol ar Extraor dinaire"
  1355                          },
  1356                          {
  1357                              "Firs tName": "F IVEHUNDRED ONE",
  1358                              "Midd leName": " ",
  1359                              "Last Name": "PR OVIDER",
  1360                              "Titl e": "Schol ar Extraor dinaire"
  1361                          },
  1362                          {
  1363                              "Firs tName": "F IVEHUNDRED TWO",
  1364                              "Midd leName": " ",
  1365                              "Last Name": "PR OVIDER",
  1366                              "Titl e": "Schol ar Extraor dinaire"
  1367                          }
  1368                ]
  1369           };
  1370           */
  1371           // ********** ********** ********** *********
  1372  
  1373           // Check vist a users da ta content
  1374           if  (vcmn_vis tausersDat a == null  || vcmn_vi stausersDa ta.Data ==  null || v cmn_vistau sersData.D ata.length  == null | | vcmn_vis tausersDat a.Data.len gth == 0)  {
  1375                //Abort  process, m issing inf o
  1376                alert('U nable to o btain Vist a User Dat a, the not e cannot b e created  in VistA/C PRS!');
  1377                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1378                return f alse;
  1379           }
  1380  
  1381           va r vcmn_sel ectedUserF irstName =  '';
  1382           va r vcmn_sel ectedUserM iddleName  = '';
  1383           va r vcmn_sel ectedUserL astName =  '';
  1384           va r vcmn_sel ectedUserS uffix = '' ;
  1385           va r vcmn_sel ectedUserD isplayName  = '';
  1386           va r vcmn_sel ectedUserT itle = '';
  1387           va r vcmn_use rIsSelecte d = false;
  1388  
  1389           if  (vcmn_vis tausersDat a.Data.len gth > 1) {
  1390                alert("T he Vista U ser list,  contains m ore than o ne user, p lease sele ct the Vis ta User yo u want to  use from t he next pr ompt(s), a  total of  " + vcmn_v istausersD ata.Data.l ength + "  users!");
  1391                for (var  i = 0; i  <= vcmn_vi stausersDa ta.Data.le ngth - 1;  i++) {
  1392                    var  vcmn_curre ntUserFirs tName = '' ;
  1393                    var  vcmn_curre ntUserMidd leName = ' ';
  1394                    var  vcmn_curre ntUserLast Name = '';
  1395                    var  vcmn_curre ntUserSuff ix = '';
  1396                    var  vcmn_curre ntUserDisp layName =  '';
  1397                    var  vcmn_curre ntUserTitl e = '';
  1398                    if ( vcmn_vista usersData. Data[i].Fi rstName !=  null) { v cmn_curren tUserFirst Name = vcm n_vistause rsData.Dat a[i].First Name; }
  1399                    if ( vcmn_vista usersData. Data[i].Mi ddleName ! = null) {  vcmn_curre ntUserMidd leName = v cmn_vistau sersData.D ata[i].Mid dleName; }
  1400                    if ( vcmn_vista usersData. Data[i].La stName !=  null) { vc mn_current UserLastNa me = vcmn_ vistausers Data.Data[ i].LastNam e; }
  1401                    if ( vcmn_vista usersData. Data[i].Su ffix != nu ll) { vcmn _currentUs erSuffix =  vcmn_vist ausersData .Data[i].S uffix; }
  1402                    if ( vcmn_vista usersData. Data[i].Di splayName  != null) {  vcmn_curr entUserDis playName =  vcmn_vist ausersData .Data[i].D isplayName ; }
  1403                    if ( vcmn_vista usersData. Data[i].Ti tle != nul l) { vcmn_ currentUse rTitle = v cmn_vistau sersData.D ata[i].Tit le; }
  1404                    //Pr ompt user  about this  vista use r record
  1405                    var  vcmn_userP romptStrin g = "Click  OK, to se lect this  user.  Oth erwise CAN CEL \n" +
  1406                         "\n First  Name: " +  vcmn_curre ntUserFirs tName +
  1407                         "\n Middle  Name: " +  vcmn_curr entUserMid dleName +
  1408                         "\n Last N ame: " + v cmn_curren tUserLastN ame +
  1409                         "\n Suffix : " + vcmn _currentUs erSuffix +
  1410                         "\n Displa y Name: "  + vcmn_cur rentUserDi splayName  +
  1411                         "\n Title:  " + vcmn_ currentUse rTitle;
  1412  
  1413                    var  vcmn_confi rmSelectVi staUser =  confirm(vc mn_userPro mptString) ;
  1414                    if ( vcmn_confi rmSelectVi staUser ==  true) {
  1415                         vcmn_userI sSelected  = true;
  1416                         vcmn_selec tedUserFir stName = v cmn_curren tUserFirst Name;
  1417                         vcmn_selec tedUserMid dleName =  vcmn_curre ntUserMidd leName;
  1418                         vcmn_selec tedUserLas tName = vc mn_current UserLastNa me;
  1419                         vcmn_selec tedUserSuf fix = vcmn _currentUs erSuffix;
  1420                         vcmn_selec tedUserDis playName =  vcmn_curr entUserDis playName;
  1421                         vcmn_selec tedUserTit le = vcmn_ currentUse rTitle;
  1422                         break;
  1423                    }
  1424                }
  1425           }
  1426           el se {
  1427                //Select  data from  the first  record
  1428                vcmn_use rIsSelecte d = true;
  1429                if (vcmn _vistauser sData.Data [0].FirstN ame != nul l) { vcmn_ currentUse rFirstName  = vcmn_vi stausersDa ta.Data[0] .FirstName ; }
  1430                if (vcmn _vistauser sData.Data [0].Middle Name != nu ll) { vcmn _currentUs erMiddleNa me = vcmn_ vistausers Data.Data[ 0].MiddleN ame; }
  1431                if (vcmn _vistauser sData.Data [0].LastNa me != null ) { vcmn_c urrentUser LastName =  vcmn_vist ausersData .Data[0].L astName; }
  1432                if (vcmn _vistauser sData.Data [0].Suffix  != null)  { vcmn_cur rentUserSu ffix = vcm n_vistause rsData.Dat a[0].Suffi x; }
  1433                if (vcmn _vistauser sData.Data [0].Displa yName != n ull) { vcm n_currentU serDisplay Name = vcm n_vistause rsData.Dat a[0].Displ ayName; }
  1434                if (vcmn _vistauser sData.Data [0].Title  != null) {  vcmn_curr entUserTit le = vcmn_ vistausers Data.Data[ 0].Title;  }
  1435           }
  1436  
  1437           // Check if a  user was  selected
  1438           if  (vcmn_use rIsSelecte d == false ) {
  1439                alert('A  user was  not select ed from th e previous  prompts,  the note c annot be c reated in  VistA/CPRS !');
  1440                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1441                return f alse;
  1442           }
  1443  
  1444           // Execute In tegration
  1445           vc mn_execute VistAInteg rationRequ est(vcmn_n oteId, vcm n_noteDesc ription, v cmn_patien tICN, vcmn _userDomai nId, vcmn_ localTitle , vcmn_cal lbackNumbe r, vcmn_re asonForReq uest[0].na me, vcmn_e ncounterCo de, vcmn_s ignThisNot e, vcmn_ve teranFirst Name, vcmn _veteranLa stName, vc mn_created OnDate, vc mn_patient AdmitDate,  vcmn_sele ctedUserFi rstName, v cmn_select edUserMidd leName, vc mn_selecte dUserLastN ame, vcmn_ selectedUs erSuffix,  vcmn_facil ityCode, v cmn_origin atorID, vc mn_siteHL7 ListenerAd dress, vcm n_patientA ssignedLoc ation);
  1446  
  1447       }
  1448       catch  (err) {
  1449           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa veToVistA_ with_ICN):  ' + err.m essage);
  1450           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1451       }
  1452   }
  1453  
  1454   function v cmn_getVis taUsersDat a(vcmn_use rFirstName , vcmn_use rLastName,  vcmn_user SiteNo, vc mn_noFilte r) {
  1455       try {
  1456           va r vcmn_jso nData = nu ll;
  1457           $. ajax({
  1458                type: "G ET",
  1459                url: vcm n_VistaUse rsURLbase  + vcmn_use rFirstName  + "/" + v cmn_userLa stName + " /" + vcmn_ userSiteNo  + "?noFil ter=" + vc mn_noFilte r,
  1460                contentT ype: "appl ication/js on; charse t=utf-8",
  1461                dataType : "json",
  1462                success:  function  (data) {
  1463                    vcmn _jsonData  = data;
  1464                },
  1465                error: f unction (j qXHR, text Status, er rorThrown)  {
  1466                    //Sy stem Error
  1467                    vcmn _jsonData  = null;
  1468                },
  1469                async: f alse,
  1470                cache: f alse
  1471           }) ;
  1472           re turn vcmn_ jsonData;
  1473       }
  1474       catch  (err) {
  1475           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getV istaUsersD ata): ' +  err.messag e);
  1476           re turn null;
  1477       }
  1478   }
  1479  
  1480   function v cmn_execut eVistAInte grationReq uest(vcmn_ noteId, vc mn_noteDes cription,  vcmn_patie ntICN, vcm n_userDoma inId, vcmn _localTitl e, vcmn_ca llbackNumb er, vcmn_r easonForRe quest, vcm n_encounte rCode, vcm n_signThis Note, vcmn _patientFi rstName, v cmn_patien tLastName,  vcmn_acti vityDate,  vcmn_patie ntAdmitDat e, vcmn_or iginatorFi rstName, v cmn_origin atorMiddle Name, vcmn _originato rLastName,  vcmn_orig inatorSuff ix, vcmn_f acilitySit eId, vcmn_ originator ID, vcmn_s iteHL7List enerAddres s, vcmn_pa tientAssig nedLocatio n) {
  1481       try {
  1482           va r vcmn_vis itNumber =  'NEW';
  1483           va r vcmn_cli entName =  "FTPCRM";
  1484           va r vcmn_For mat = "JSO N";
  1485           va r vcmn_pat ientIdenti fierType =  "ICN";
  1486           va r vcmn_doc umentAvail abilitySta tus = "AV" ;  //Histo rical Note  only at t his time
  1487           va r vcmn_ori ginatorCom binedMiddl e = "";
  1488           if  (vcmn_ori ginatorMid dleName !=  '' && vcm n_originat orMiddleNa me != null ) { vcmn_o riginatorC ombinedMid dle = vcmn _originato rMiddleNam e; }
  1489           if  (vcmn_ori ginatorSuf fix != ''  && vcmn_or iginatorSu ffix != nu ll) {
  1490                if (vcmn _originato rCombinedM iddle != ' ') {
  1491                    vcmn _originato rCombinedM iddle = vc mn_origina torCombine dMiddle +  " " + vcmn _originato rSuffix;
  1492                }
  1493                else {
  1494                    vcmn _originato rCombinedM iddle = vc mn_origina torSuffix;
  1495                }
  1496           }
  1497  
  1498           va r vcmn_req uestJSON =  {
  1499                "ClientN ame": vcmn _clientNam e,
  1500                "Format" : vcmn_For mat,
  1501                "Facilit ySiteID":  vcmn_facil itySiteId,
  1502                "SiteHL7 ListenerAd dress": vc mn_siteHL7 ListenerAd dress,
  1503                "VisitNu mber": vcm n_visitNum ber,
  1504                "IsSigne dNote": vc mn_signThi sNote,
  1505                "Patient AdmitDate" : vcmn_pat ientAdmitD ate,
  1506                "Patient LastName":  vcmn_pati entLastNam e,
  1507                "Patient FirstName" : vcmn_pat ientFirstN ame,
  1508                "Patient Identifier ": vcmn_pa tientICN,
  1509                "Patient Identifier Type": vcm n_patientI dentifierT ype,
  1510                "Patient AssignedLo cation": v cmn_patien tAssignedL ocation,
  1511                "NoteTex t": vcmn_n oteDescrip tion,
  1512                "Origina torID": vc mn_origina torID,
  1513                "Origina torFirstNa me": vcmn_ originator FirstName,
  1514                "Origina torMiddleN ame": vcmn _originato rCombinedM iddle,
  1515                "Origina torLastNam e": vcmn_o riginatorL astName,
  1516                "Documen tFileName" : vcmn_loc alTitle,
  1517                "Documen tAvailabil ityStatus" : vcmn_doc umentAvail abilitySta tus,
  1518                "Activit yDate": vc mn_activit yDate
  1519           };
  1520  
  1521           va r vcmn_req uestRespon se = "";
  1522  
  1523           $. ajax({
  1524                type: "P OST",
  1525                url: vcm n_NoteWrit eUrl,
  1526                data: JS ON.stringi fy(vcmn_re questJSON) ,
  1527                contentT ype: "appl ication/js on; charse t=utf-8",
  1528                dataType : "json",
  1529                success:  function  (data) {
  1530                    var  vcmn_newda ta = data;
  1531                    vcmn _requestRe sponse = v cmn_newdat a;
  1532                    vcmn _vistAInte grationReq uest_respo nse(null,  vcmn_reque stResponse );
  1533                },
  1534                error: f unction (j qXHR, text Status, er rorThrown)  {
  1535                    //Sy stem Error
  1536                    vcmn _vistAInte grationReq uest_respo nse(errorT hrown, nul l);
  1537                },
  1538                async: f alse,
  1539                cache: f alse
  1540           }) ;
  1541       }
  1542       catch  (err) {
  1543           al ert('Progr ess Note R ibbon Func tion Error (vcmn_exec uteVistAIn tegrationR equest): '  + err.mes sage);
  1544           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1545       }
  1546   }
  1547  
  1548   function v cmn_vistAI ntegration Request_re sponse(vcm n_errorThr own, vcmn_ requestRes ponse) {
  1549       try {
  1550           // Process In tegration  Request Re sponse
  1551           if  (vcmn_err orThrown ! = null) {
  1552                //Write  Error
  1553                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etValue('E RROR');
  1554                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etSubmitMo de('always ');
  1555                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tValue(Str ing(vcmn_e rrorThrown ));
  1556                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tSubmitMod e('always' );
  1557                Xrm.Page .getAttrib ute('ftp_i ntegration date').set Value(new  Date());
  1558                Xrm.Page .getAttrib ute('ftp_i ntegration date').set SubmitMode ('always') ;
  1559                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etValue('' );
  1560                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etSubmitMo de('always ');
  1561                alert('T he note cr eation in  VistA/CPRS  failed!\n Please see  the integ ration err or field f or details .');
  1562                Xrm.Page .getContro l('ftp_int egrationer ror').setF ocus();
  1563                Xrm.Page .data.enti ty.save();
  1564                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1565                return f alse;
  1566           }
  1567           el se {
  1568                //Write  web servic e response  Success o r Failure
  1569                if (vcmn _requestRe sponse.Err orOccurred  == false)  {
  1570                    //Wr ite Succes s entry
  1571                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setValu e(vcmn_req uestRespon se.Status) ;
  1572                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setSubm itMode('al ways');
  1573                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setValue (null);
  1574                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setSubmi tMode('alw ays');
  1575                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setValue( new Date() );
  1576                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setSubmit Mode('alwa ys');
  1577                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setValu e(vcmn_req uestRespon se.Data);
  1578                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setSubm itMode('al ways');
  1579                    Xrm. Page.getCo ntrol('ftp _integrati onstatus') .setFocus( );
  1580                    aler t('The not e creation  in VistA/ CPRS was s uccessful,  this note  will now  be marked  as complet ed. \n\nPl ease exit  this note  record aft er clickin g OK to th is prompt! ');
  1581                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1582                    Xrm. Page.data. entity.sav e();
  1583                }
  1584                else {
  1585                    //Wr ite Failur e entry
  1586                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setValu e(vcmn_req uestRespon se.Status) ;
  1587                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setSubm itMode('al ways');
  1588                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setValue (vcmn_requ estRespons e.ErrorMes sage + "   DebugInfo: " + vcmn_r equestResp onse.Debug Info);
  1589                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setSubmi tMode('alw ays');
  1590                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setValue( new Date() );
  1591                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setSubmit Mode('alwa ys');
  1592                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setValu e('');
  1593                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setSubm itMode('al ways');
  1594                    aler t('The not e creation  in VistA/ CPRS faile d!\nPlease  see the i ntegration  error fie ld for det ails.');
  1595                    Xrm. Page.getCo ntrol('ftp _integrati onerror'). setFocus() ;
  1596                    Xrm. Page.data. entity.sav e();
  1597                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1598                    retu rn false;
  1599  
  1600                }
  1601           }
  1602       }
  1603       catch  (err) {
  1604           al ert('Progr ess Note R ibbon Func tion Error (vcmn_vist AIntegrati onRequest_ response):  ' + err.m essage);
  1605           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1606       }
  1607   }
  1608  
  1609   function v cmn_initVi aDropdownC ontrols()  {
  1610       //Init ialize VIA  DropDown  Controls
  1611       //Func tion is tr iggered by  The VistA  Login Con trol and o nchange of  Facility  attribute
  1612       try {
  1613           Xr m.Page.get Control("W ebResource _HospitalL ocation"). setSrc(Xrm .Page.getC ontrol("We bResource_ HospitalLo cation").g etSrc());
  1614           Xr m.Page.get Control("W ebResource _LocalNote sTitle").s etSrc(Xrm. Page.getCo ntrol("Web Resource_L ocalNotesT itle").get Src());
  1615       }
  1616       catch  (err) {
  1617           al ert('Progr ess Note V IA Login F unction Er ror(vcmn_i nitViaDrop downContro ls): ' + e rr.message );
  1618       }
  1619   }
  1620  
  1621   function v cmn_facili tyGroupDef ault_respo nse(vcmn_f acilityGro upData, vc mn_lastSki p, vcmn_fa cilitySite Id) {
  1622       try {
  1623           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  1624           fo r (var i =  0; i <= v cmn_facili tyGroupDat a.d.result s.length -  1; i++) {
  1625                //Get Va lues and W rite to Pr ogress Not e
  1626                if (vcmn _facilityG roupData.d .results[i ].ftp_loca lnotestitl e != null)  {
  1627                    Xrm. Page.getAt tribute("f tp_localno testitle") .setValue( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ localnotes title);
  1628                    Xrm. Page.getAt tribute('f tp_localno testitle') .setSubmit Mode('alwa ys');
  1629                }
  1630                if (vcmn _facilityG roupData.d .results[i ].ftp_hosp itallocati on != null ) {
  1631                    Xrm. Page.getAt tribute("f tp_hospita llocation" ).setValue (vcmn_faci lityGroupD ata.d.resu lts[i].ftp _hospitall ocation);
  1632                    Xrm. Page.getAt tribute('f tp_hospita llocation' ).setSubmi tMode('alw ays');
  1633                }
  1634                break;
  1635           }
  1636       }
  1637       catch  (err) {
  1638           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_faci lityGroupD efault_res ponse): '  + err.mess age);
  1639       }
  1640   }
  1641  
  1642  
  1643   function v cmn_buildQ ueryFilter (field, va lue, and)  {
  1644       try {
  1645           if  (value ==  '') {
  1646                if (and)  {
  1647                    retu rn " and "  + field +  " eq null ";
  1648                } else {
  1649                    retu rn field +  " eq null ";
  1650                }
  1651           }
  1652           el se {
  1653                if (and)  {
  1654                    retu rn " and "  + field +  " eq '" +  value + " '";
  1655                } else {
  1656                    retu rn field +  " eq '" +  value + " '";
  1657                }
  1658           }
  1659       }
  1660       catch  (err) {
  1661           al ert('Progr ess Note R ibbon Func tion Error (vcmn_buil dQueryFilt er): ' + e rr.message );
  1662           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1663       }
  1664   }
  1665  
  1666   function v cmn_unatte ndedMviSea rch(firstn ame, lastn ame, dobda te, ssn) {
  1667       try {
  1668           va r filter =  "";
  1669           va r filterPr efix = "$s elect=*&$f ilter=";
  1670           va r edipi =  "";
  1671           va r dobstrin g = "";
  1672           if  (dobdate  != null) {
  1673                dobstrin g = dobdat e;
  1674           }
  1675  
  1676           if  (ssn != " " && ssn ! = null) {
  1677                ssn = ss n.replace( /-/g, "");
  1678           }
  1679  
  1680           // if we have  edipi, se arch using  just it
  1681           if  (edipi !=  "") {
  1682                filter =  vcmn_buil dQueryFilt er("crme_E DIPI", edi pi, false) ;
  1683                filter + = vcmn_bui ldQueryFil ter("crme_ ClassCode" , 'MIL', t rue);
  1684                filter + = vcmn_bui ldQueryFil ter("crme_ SearchType ", 'Search ByIdentifi er', true) ;
  1685  
  1686                //set se arch type  as unatten ded
  1687                filter + = " and cr me_IsAtten ded eq fal se";
  1688           }
  1689           el se {
  1690                //otherw ise search  using las tname, fir stname, ss n, dob
  1691                filter =  vcmn_buil dQueryFilt er("crme_L astName",  lastname,  false); // assuming l astname wi ll never b e blank
  1692  
  1693                if (firs tname != " " && first name != nu ll) {
  1694                    filt er += vcmn _buildQuer yFilter("c rme_FirstN ame", firs tname, tru e);
  1695                }
  1696  
  1697                if (ssn  != "" && s sn != null ) {
  1698                    filt er += vcmn _buildQuer yFilter("c rme_SSN",  ssn, true) ;
  1699                }
  1700  
  1701                if (dobs tring != " ") {
  1702                    filt er += " an d crme_DOB String eq  '" + dobst ring + "'" ;
  1703                }
  1704                filter + = vcmn_bui ldQueryFil ter("crme_ SearchType ", 'Search ByFilter',  true);
  1705  
  1706                //set se arch type  as attende d (for now )
  1707                filter + = " and cr me_IsAtten ded eq tru e";
  1708           }
  1709  
  1710           fi lter = enc odeURIComp onent(filt er);
  1711           fi lter = fil terPrefix  + filter;
  1712           SD K.REST.ret rieveMulti pleRecords ("crme_per son", filt er, vcmn_u nattendedM viSearchCa llback, fu nction (er ror) { ale rt(error.m essage); v cmn_ribbon ButtonSave ToVistA_wi th_ICN("") ; }, vcmn_ unattended MviSearchC omplete);
  1713       }
  1714       catch  (err) {
  1715           al ert('Progr ess Note R ibbon Func tion Error (vcmn_unat tendedMviS earch): '  + err.mess age);
  1716           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1717       }
  1718   }
  1719  
  1720   function v cmn_unatte ndedMviSea rchCallbac k(returnDa ta) {
  1721       try {
  1722           if  (returnDa ta != null  && return Data.lengt h >= 1) {
  1723                // check  for excep tions 1st
  1724                if (retu rnData[0]. crme_Excep tionOccure d || (retu rnData[0]. crme_Retur nMessage ! = null &&  returnData [0].crme_R eturnMessa ge == "An  unexpected  error occ ured durin g the MVI  search. Pl ease try a gain or co ntact your  system ad ministrato r if the p roblem per sists."))  {
  1725                    //do  nothing,  pass empty  ICN
  1726                    vcmn _ribbonBut tonSaveToV istA_with_ ICN("");
  1727                }
  1728                else {
  1729                    var  patientMvi Identifier  = returnD ata[0].crm e_PatientM viIdentifi er == null  ? "" : re turnData[0 ].crme_Pat ientMviIde ntifier;
  1730                    if ( patientMvi Identifier  != "") {
  1731                         var idpart s = patien tMviIdenti fier.split ("^");
  1732  
  1733                         if (idpart s.length >  0) {
  1734                             var na tionalId =  idparts[0 ];
  1735                             _icn =  nationalI d;
  1736                             //Pass  on the IC N and cont inue valid ation
  1737                             vcmn_r ibbonButto nSaveToVis tA_with_IC N(_icn);
  1738                         }
  1739                    }
  1740                }
  1741           }
  1742           el se {
  1743                //Return  empty ICN
  1744                vcmn_rib bonButtonS aveToVistA _with_ICN( "");
  1745           }
  1746       }
  1747       catch  (err) {
  1748           al ert('Progr ess Note R ibbon Func tion Error (vcmn_unat tendedMviS earchCallb ack): ' +  err.messag e);
  1749           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1750       }
  1751   }
  1752  
  1753   function v cmn_unatte ndedMviSea rchComplet e() {
  1754       //do n othing
  1755   }
  1756  
  1757  
  1758   function v cmn_buildQ ueryFilter SCD(field,  value, an d) {
  1759       try {
  1760           if  (value ==  '') {
  1761                if (and)  {
  1762                    retu rn " and "  + field +  " eq null ";
  1763                } else {
  1764                    retu rn field +  " eq null ";
  1765                }
  1766           }
  1767           el se {
  1768                if (and)  {
  1769                    retu rn " and "  + field +  " eq '" +  value + " '";
  1770                } else {
  1771                    retu rn field +  " eq '" +  value + " '";
  1772                }
  1773           }
  1774       }
  1775       catch  (err) {
  1776           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_buil dQueryFilt erSCD): '  + err.mess age);
  1777           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1778       }
  1779   }
  1780  
  1781   function v cmn_unatte ndedMviSea rchSCD(fir stname, la stname, do bdate, ssn ) {
  1782       try {
  1783           va r filter =  "";
  1784           va r filterPr efix = "$s elect=*&$f ilter=";
  1785           va r edipi =  "";
  1786           va r dobstrin g = "";
  1787           if  (dobdate  != null) {
  1788                dobstrin g = dobdat e;
  1789           }
  1790  
  1791           if  (ssn != " " && ssn ! = null) {
  1792                ssn = ss n.replace( /-/g, "");
  1793           }
  1794  
  1795           // if we have  edipi, se arch using  just it
  1796           if  (edipi !=  "") {
  1797                filter =  vcmn_buil dQueryFilt erSCD("crm e_EDIPI",  edipi, fal se);
  1798                filter + = vcmn_bui ldQueryFil terSCD("cr me_ClassCo de", 'MIL' , true);
  1799                filter + = vcmn_bui ldQueryFil terSCD("cr me_SearchT ype", 'Sea rchByIdent ifier', tr ue);
  1800  
  1801                //set se arch type  as unatten ded
  1802                filter + = " and cr me_IsAtten ded eq fal se";
  1803           }
  1804           el se {
  1805                //otherw ise search  using las tname, fir stname, ss n, dob
  1806                filter =  vcmn_buil dQueryFilt erSCD("crm e_LastName ", lastnam e, false);  //assumin g lastname  will neve r be blank
  1807  
  1808                if (firs tname != " " && first name != nu ll) {
  1809                    filt er += vcmn _buildQuer yFilterSCD ("crme_Fir stName", f irstname,  true);
  1810                }
  1811  
  1812                if (ssn  != "" && s sn != null ) {
  1813                    filt er += vcmn _buildQuer yFilterSCD ("crme_SSN ", ssn, tr ue);
  1814                }
  1815  
  1816                if (dobs tring != " ") {
  1817                    filt er += " an d crme_DOB String eq  '" + dobst ring + "'" ;
  1818                }
  1819                filter + = vcmn_bui ldQueryFil terSCD("cr me_SearchT ype", 'Sea rchByFilte r', true);
  1820  
  1821                //set se arch type  as attende d (for now )
  1822                filter + = " and cr me_IsAtten ded eq tru e";
  1823           }
  1824  
  1825           fi lter = enc odeURIComp onent(filt er);
  1826           fi lter = fil terPrefix  + filter;
  1827           SD K.REST.ret rieveMulti pleRecords ("crme_per son", filt er, vcmn_u nattendedM viSearchCa llbackSCD,  function  (error) {  alert(erro r.message) ; vcmn_get ServiceCon nectedDisa bilities(" "); }, vcm n_unattend edMviSearc hComplete) ;
  1828       }
  1829       catch  (err) {
  1830           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_unat tendedMviS earchSCD):  ' + err.m essage);
  1831       }
  1832   }
  1833  
  1834   function v cmn_unatte ndedMviSea rchCallbac kSCD(retur nData) {
  1835       try {
  1836           if  (returnDa ta != null  && return Data.lengt h >= 1) {
  1837                // check  for excep tions 1st
  1838                if (retu rnData[0]. crme_Excep tionOccure d || (retu rnData[0]. crme_Retur nMessage ! = null &&  returnData [0].crme_R eturnMessa ge == "An  unexpected  error occ ured durin g the MVI  search. Pl ease try a gain or co ntact your  system ad ministrato r if the p roblem per sists."))  {
  1839                    //do  nothing,  pass empty  ICN
  1840                    vcmn _getServic eConnected Disabiliti es("");
  1841                }
  1842                else {
  1843                    var  patientMvi Identifier  = returnD ata[0].crm e_PatientM viIdentifi er == null  ? "" : re turnData[0 ].crme_Pat ientMviIde ntifier;
  1844                    if ( patientMvi Identifier  != "") {
  1845                         var idpart s = patien tMviIdenti fier.split ("^");
  1846  
  1847                         if (idpart s.length >  0) {
  1848                             var na tionalId =  idparts[0 ];
  1849                             _icn =  nationalI d;
  1850                             //Pass  on the IC N and cont inue with  SCD
  1851                             vcmn_g etServiceC onnectedDi sabilities (_icn);
  1852                         }
  1853                    }
  1854                }
  1855           }
  1856           el se {
  1857                //Return  empty ICN
  1858                vcmn_get ServiceCon nectedDisa bilities(" ");
  1859           }
  1860       }
  1861       catch  (err) {
  1862           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_unat tendedMviS earchCallb ackSCD): '  + err.mes sage);
  1863       }
  1864   }
  1865  
  1866  
  1867   function v cmn_execut eCrmOdataG etRequest( vcmn_jsonQ uery, vcmn _aSync, vc mn_aSyncCa llback, vc mn_skipCou nt, vcmn_o ptionArray ) {
  1868       //This  function  executes a  CRM Odata  web servi ce call to  retrieve  Crm data
  1869       //*vcm n_jsonQuer y* - a pro perly form atted CRM  Odata Quer y string ( required)
  1870       //*vcm n_aSync* -  specify ' true' to e xecute asy nchronousl y otherwis e 'false'  (required)
  1871       //*vcm n_aSyncCal lback* - s pecify the  name of t he return  function t o call upo n completi on (requir ed if vcmn _aSync = t rue.  Othe rwise '')
  1872       //*vcm n_skipCoun t* - Initi al setting  is always  '0', incr ements by  50 per CRM  SDK Odata  standards  (required )
  1873       //*vcm n_optionAr ray* - is  an optiona l array or  single va lue, that  contains a dditional  task speci fic variab les that c an be pass ed between  functions  (pass 'nu ll' if not  used)
  1874       try {
  1875           va r vcmn_ent ityData =  null;
  1876           $. ajax({
  1877                type: 'G ET',
  1878                contentT ype: 'appl ication/js on; charse t=utf-8',
  1879                datatype : 'json',
  1880                url: vcm n_jsonQuer y,
  1881                beforeSe nd: functi on (XMLHtt pRequest)  {
  1882                    XMLH ttpRequest .setReques tHeader('A ccept', 'a pplication /json');
  1883                },
  1884                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  1885                    vcmn _entityDat a = data;
  1886                    if ( vcmn_aSync  == true)  {
  1887                         vcmn_aSync Callback(v cmn_entity Data, vcmn _skipCount , vcmn_opt ionArray);
  1888                    }
  1889                },
  1890                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  1891                    aler t('Fail: A jax Error  in vcmn_ex ecuteCrmOd ataGetRequ est: ' + e rrorThrown  + " Reque st: " + vc mn_jsonQue ry);
  1892                },
  1893                async: v cmn_aSync,
  1894                cache: f alse
  1895           }) ;
  1896           re turn vcmn_ entityData ;
  1897       }
  1898       catch  (err) {
  1899           al ert('An er ror occure d in the v cmn_execut eCrmOdataG etRequest  function.   Error Det ail Messag e: ' + err );
  1900       }
  1901   }
  1902  
  1903   function v cmn_getMul tipleEntit yDataAsync (vcmn_enti tySetName,  vcmn_attr ibuteSet,  vcmn_condi tionalFilt er, vcmn_s ortAttribu te, vcmn_s ortDirecti on, vcmn_s kipCount,  vcmn_aSync Callback,  vcmn_optio nArray) {
  1904       //This  function  returns a  CRM JSON d ataset for  all entit y records  matching c riteria pr ovided Asy ncronously
  1905       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  1906       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  1907       //*vcm n_conditio nalFilter*  - is the  conditiona l filter v alue place d on the d ata values  retrived  e.g. 'Stat eCode/Valu e eq 0'  t o retrieve  active co ntact reco rds only
  1908       //*vcm n_sortAttr ibute* - i s a string  containin g the name  of the at tribute to  sort the  result set  by e.g. ' LastName'
  1909       //*vcm n_sortDire ction* - i s a string  specifyin g the sort  as Ascend ing or Des cending e. g. 'asc' o r 'desc'
  1910       //*vcm n_skipCoun t* - is th e starting  point in  the result  (use if m ore than 5 0), (Put 0  if not us ed)
  1911       //*vcm n_aSyncCal lback* - i s the name  of the fu nction to  call when  returning  the result
  1912       //*vcm n_optionAr ray* - is  an optiona l array, t hat contai ns additio nal task s pecific va riables th at can be  passed bet ween funct ions
  1913  
  1914       try {
  1915           va r vcmn_jso nQuery = v cmn_server Url + vcmn _crmOdataE ndPoint +  '/' + vcmn _entitySet Name + '?$ select=' +  vcmn_attr ibuteSet +  '&$filter =' + vcmn_ conditiona lFilter +  '&$orderby =' + vcmn_ sortAttrib ute + ' '  + vcmn_sor tDirection  + '&$skip =' + vcmn_ skipCount;
  1916           vc mn_execute CrmOdataGe tRequest(v cmn_jsonQu ery, true,  vcmn_aSyn cCallback,  vcmn_skip Count, vcm n_optionAr ray);
  1917       }
  1918       catch  (err) {
  1919           al ert('An er ror occure d in the v cmn_getMul tipleEntit yDataAsync  function.   Error De tail Messa ge: ' + er r);
  1920       }
  1921   }
  1922  
  1923   function v cmn_getSin gleEntityD ataSync(vc mn_entityS etName, vc mn_attribu teSet, vcm n_entityId ) {
  1924       //This  function  returns a  CRM JSON d ataset for  a single  entity rec ord based  on the ent ity id pro vided Sync ronously
  1925       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  1926       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  1927       //*vcm n_entityId * - is the  Guid for  the entity  record
  1928  
  1929       try {
  1930           va r vcmn_ent ityIdNoBra cket = vcm n_entityId .replace(/ ({|})/g, ' ');
  1931           va r vcmn_sel ectString  = '(guid'  + "'" + vc mn_entityI dNoBracket  + "'" + ' )?$select= ' + vcmn_a ttributeSe t;
  1932           va r vcmn_jso nQuery = v cmn_server Url + vcmn _crmOdataE ndPoint +  '/' + vcmn _entitySet Name + vcm n_selectSt ring;
  1933           va r vcmn_ent ityData =  vcmn_execu teCrmOdata GetRequest (vcmn_json Query, fal se, '', 0,  null);
  1934           re turn vcmn_ entityData ;
  1935       }
  1936       catch  (err) {
  1937           al ert('An er ror occure d in the v cmn_getSin gleEntityD ataSync fu nction.  E rror Detai l Message:  ' + err);
  1938       }
  1939   }
  1940  
  1941   function v cmn_getMul tipleEntit yDataSync( vcmn_entit ySetName,  vcmn_attri buteSet, v cmn_condit ionalFilte r, vcmn_so rtAttribut e, vcmn_so rtDirectio n, vcmn_sk ipCount) {
  1942       //This  function  returns a  CRM JSON d ataset for  all entit y records  matching c riteria pr ovided Syn cronously
  1943       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  1944       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  1945       //*vcm n_conditio nalFilter*  - is the  conditiona l filter v alue place d on the d ata values  retrived  e.g. 'Stat eCode/Valu e eq 0'  t o retrieve  active co ntact reco rds only
  1946       //*vcm n_sortAttr ibute* - i s a string  containin g the name  of the at tribute to  sort the  result set  by e.g. ' LastName'
  1947       //*vcm n_sortDire ction* - i s a string  specifyin g the sort  as Ascend ing or Des cending e. g. 'asc' o r 'desc'
  1948       //*vcm n_skipCoun t* - is th e starting  point in  the result  (use if m ore than 5 0), (Put 0  if not us ed)
  1949  
  1950       try {
  1951           va r vcmn_jso nQuery = v cmn_server Url + vcmn _crmOdataE ndPoint +  '/' + vcmn _entitySet Name + '?$ select=' +  vcmn_attr ibuteSet +  '&$filter =' + vcmn_ conditiona lFilter +  '&$orderby =' + vcmn_ sortAttrib ute + ' '  + vcmn_sor tDirection  + '&$skip =' + vcmn_ skipCount;
  1952           va r vcmn_ent ityData =  vcmn_execu teCrmOdata GetRequest (vcmn_json Query, fal se, '', vc mn_skipCou nt, null);
  1953           re turn vcmn_ entityData ;
  1954       }
  1955       catch  (err) {
  1956           al ert('An er ror occure d in the v cmn_getMul tipleEntit yDataSync  function.   Error Det ail Messag e: ' + err );
  1957       }
  1958   }
  1959