73. EPMO Open Source Coordination Office Redaction File Detail Report

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

73.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_2.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Wed Feb 15 14:53:00 2017 UTC
2 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_2.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Thu Nov 30 17:20:20 2017 UTC

73.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 5 4484
Changed 4 8
Inserted 0 0
Removed 0 0

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

73.4 Active regular expressions

No regular expressions were active.

73.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/ QA/api/ees ummary/1.0 /xml/ftpCR M/';    //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   //var vcmn _AddSigner sUrl = 'ht tps://qacr mdac.np.cr m.vrm.vba. DNS     /WebParts/ DEV/api/VI A/AddSigne rs/1.0/jso n';    //OLD MANU AL DEV URL
  24   var vcmn_A ddSignersU rl = '';
  25  
  26   //Producti on Environ ment Indic ator
  27   var vcmn_I sProductio nEnvironme nt = false ;
  28  
  29   //Word Wra p Line Lim it
  30   var vcmn_W ordWrapLim it = 75;
  31  
  32   //Addition al Signers  Data
  33   var vcmn_A ddlSigners NameArray  = null;
  34   var vcmn_A ddlSigners IenArray =  null;
  35   var vcmn_l ocalStorag eVarName =  "";
  36  
  37   function v cmn_getQue ryVariable (vcmn_vari able) {
  38       try {
  39           // Get a Quer y Variable
  40           va r vcmn_que ry = windo w.location .search.su bstring(1) ;
  41           va r vcmn_var s = vcmn_q uery.split ("&");
  42           fo r (var i =  0; i < vc mn_vars.le ngth; i++)  {
  43                var vcmn _pair = vc mn_vars[i] .split("=" );
  44                if (vcmn _pair[0] = = vcmn_var iable) {
  45                    retu rn decodeU RIComponen t(vcmn_pai r[1]);
  46                }
  47           }
  48           re turn "";
  49       }
  50       catch  (err) {
  51           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getQ ueryVariab le): ' + e rr.message );
  52       }
  53   }
  54  
  55   function v cmn_setSim pleLookupV alue(vcmn_ LookupId,  vcmn_Type,  vcmn_Id,  vcmn_Name)  {
  56       try {
  57           // Sets the v alue for l ookup attr ibutes tha t accept o nly a sing le entity  reference.
  58           va r vcmn_loo kupReferen ce = [];
  59           vc mn_lookupR eference[0 ] = {};
  60           vc mn_lookupR eference[0 ].id = vcm n_Id;
  61           vc mn_lookupR eference[0 ].entityTy pe = vcmn_ Type;
  62           vc mn_lookupR eference[0 ].name = v cmn_Name;
  63           Xr m.Page.get Attribute( vcmn_Looku pId).setVa lue(vcmn_l ookupRefer ence);
  64       }
  65       catch  (err) {
  66           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_setS impleLooku pValue): '  + err.mes sage);
  67       }
  68   }
  69  
  70   function v cmn_conver tCrmDateTo VistADate( vcmn_crmDa te) {
  71       try {
  72           va r vcmn_Vis tADate = n ull;
  73           if  (vcmn_crm Date != nu ll) {
  74                var vcmn _crmYear =  (vcmn_crm Date.getFu llYear()). toString() ;
  75                var vcmn _crmMonth  = '00';
  76                if ((vcm n_crmDate. getMonth()  + 1) < 10 ) {
  77                    vcmn _crmMonth  = '0' + (v cmn_crmDat e.getMonth () + 1).to String();
  78                }
  79                else {
  80                    vcmn _crmMonth  = (vcmn_cr mDate.getM onth() + 1 ).toString ();
  81                }
  82                var vcmn _crmDay =  '00';
  83                if ((vcm n_crmDate. getDate())  < 10) {
  84                    vcmn _crmDay =  '0' + (vcm n_crmDate. getDate()) .toString( );
  85                }
  86                else {
  87                    vcmn _crmDay =  (vcmn_crmD ate.getDat e()).toStr ing();
  88                }
  89                var vcmn _crmHours  = '00';
  90                if ((vcm n_crmDate. getHours() ) < 10) {
  91                    vcmn _crmHours  = '0' + (v cmn_crmDat e.getHours ()).toStri ng();
  92                }
  93                else {
  94                    vcmn _crmHours  = (vcmn_cr mDate.getH ours()).to String();
  95                }
  96                var vcmn _crmMinute s = '00';
  97                if ((vcm n_crmDate. getMinutes ()) < 10)  {
  98                    vcmn _crmMinute s = '0' +  (vcmn_crmD ate.getMin utes()).to String();
  99                }
  100                else {
  101                    vcmn _crmMinute s = (vcmn_ crmDate.ge tMinutes() ).toString ();
  102                }
  103                var vcmn _crmSecond s = '00';
  104                if ((vcm n_crmDate. getSeconds ()) < 10)  {
  105                    vcmn _crmSecond s = '0' +  (vcmn_crmD ate.getSec onds()).to String();
  106                }
  107                else {
  108                    vcmn _crmSecond s = (vcmn_ crmDate.ge tSeconds() ).toString ();
  109                }
  110  
  111                //Create  VistA Dat e
  112                vcmn_Vis tADate = v cmn_crmYea r + vcmn_c rmMonth +  vcmn_crmDa y + vcmn_c rmHours +  vcmn_crmMi nutes + vc mn_crmSeco nds;
  113           }
  114           re turn vcmn_ VistADate;
  115       }
  116       catch  (err) {
  117           al ert('Progr ess Note E rror(vcmn_ convertCrm DateToVist ADate): '  + err.mess age);
  118           re turn null;
  119       }
  120   }
  121  
  122   function v cmn_UserHa sTeam(team Name, user Guid) {
  123       try {
  124           va r vcmn_tea mid = null ;
  125           va r vcmn_cur rentUserId  = userGui d;
  126           va r vcmn_con ditionalFi lter = "(N ame eq '"  + teamName  + "')";
  127           va r vcmn_tea mData = vc mn_getMult ipleEntity DataSync(' TeamSet',  'TeamId',  vcmn_condi tionalFilt er, 'Name' , 'asc', 0 );
  128           if  (vcmn_tea mData != n ull) {
  129                for (var  i = 0; i  <= vcmn_te amData.d.r esults.len gth - 1; i ++) {
  130                    //Ge t Info
  131                    if ( vcmn_teamD ata.d.resu lts[i].Tea mId != nul l) { vcmn_ teamid = v cmn_teamDa ta.d.resul ts[i].Team Id; }
  132                    brea k;
  133                }
  134           }
  135           // If Team ex ists, chec k if the c urrent use r is part  of that te am
  136           va r vcmn_tea mMembershi pId = null ;
  137           if  (vcmn_tea mid != nul l && vcmn_ currentUse rId != nul l) {
  138                var vcmn _condition alFilter =  "(TeamId  eq (guid'"  + vcmn_te amid + "')  and Syste mUserId eq  (guid'" +  vcmn_curr entUserId  + "'))";
  139                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);
  140                if (vcmn _teamMembe rshipData  != null) {
  141                    for  (var i = 0 ; i <= vcm n_teamMemb ershipData .d.results .length -  1; i++) {
  142                         //Get Info
  143                         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; }
  144                         break;
  145                    }
  146                }
  147           }
  148           if  (vcmn_tea mMembershi pId != nul l) { retur n true; }
  149  
  150           // otherwise  return fal se                 
  151           re turn false ;
  152       }
  153       catch  (err) {
  154           // Display Er ror
  155           al ert("An er ror occure d in the v cmn_UserHa sTeam func tion.  Err or Detail  Message: "  + err);
  156       }
  157   }
  158  
  159   function v cmn_Settin gsWebServi ceURL_resp onse(vcmn_ settingDat a, vcmn_la stSkip, vc mn_NoteWri teUrl_NA)  {
  160       try {
  161           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  162           va r vcmn_Dac Url = null ;
  163           va r vcmn_Not esWriteApi Url = null ;
  164           va r vcmn_ees ummaryApiU rl = null;
  165           va r vcmn_Vis taUserApiU rl = null;
  166           va r vcmn_Via AddlSigner sApiUrl =  null;
  167  
  168           fo r (var i =  0; i <= v cmn_settin gData.d.re sults.leng th - 1; i+ +) {
  169                //Get in fo
  170                if (vcmn _settingDa ta.d.resul ts[i].ftp_ DACURL !=  null) { vc mn_DacUrl  = vcmn_set tingData.d .results[i ].ftp_DACU RL; }
  171                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; }
  172                if (vcmn _settingDa ta.d.resul ts[i].ftp_ ESRAPIURL  != null) {  vcmn_eesu mmaryApiUr l = vcmn_s ettingData .d.results [i].ftp_ES RAPIURL; }
  173                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; }
  174                if (vcmn _settingDa ta.d.resul ts[i].ftp_ IsProducti onEnvironm ent != nul l) { vcmn_ IsProducti onEnvironm ent = vcmn _settingDa ta.d.resul ts[i].ftp_ IsProducti onEnvironm ent; }
  175                if (vcmn _settingDa ta.d.resul ts[i].ftp_ VIAAdditio nalSigners URL != nul l) { vcmn_ ViaAddlSig nersApiUrl  = vcmn_se ttingData. d.results[ i].ftp_VIA Additional SignersURL ; }
  176                break;
  177           }
  178  
  179           if  (vcmn_Dac Url != nul l && vcmn_ NotesWrite ApiUrl !=  null) {
  180                //Constr uct full w eb service  URL
  181                vcmn_Not eWriteUrl  = vcmn_Dac Url + vcmn _NotesWrit eApiUrl;
  182           }
  183           el se {
  184                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");
  185           }
  186           if  (vcmn_Dac Url != nul l && vcmn_ eesummaryA piUrl != n ull) {
  187                //Constr uct full w eb service  URL
  188                vcmn_ees ummaryURLb ase = vcmn _DacUrl +  vcmn_eesum maryApiUrl ;
  189           }
  190           el se {
  191                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") ;
  192           }
  193           if  (vcmn_Dac Url != nul l && vcmn_ VistaUserA piUrl != n ull) {
  194                //Constr uct full w eb service  URL
  195                vcmn_Vis taUsersURL base = vcm n_DacUrl +  vcmn_Vist aUserApiUr l;
  196           }
  197           el se {
  198                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 ");
  199           }
  200           if  (vcmn_Dac Url != nul l && vcmn_ ViaAddlSig nersApiUrl  != null)  {
  201                //Constr uct full w eb service  URL
  202                vcmn_Add SignersUrl  = vcmn_Da cUrl + vcm n_ViaAddlS ignersApiU rl;
  203           }
  204           el se {
  205                Xrm.Page .ui.setFor mNotificat ion("ERROR : THE VIA  ADDITIONAL  SIGNERS S ERVICE URL  IS MISSIN G, PLEASE  CONTACT TE CHNICAL SU PPORT!", " ERROR", "V ISTASERVIC E");
  206           }
  207  
  208           // Proceed wi th Form Lo ad logic w ith URL
  209           vc mn_newProg ressNoteLo ad_WebURL( );
  210       }
  211       catch  (err) {
  212           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_Sett ingsWebSer viceURL_re sponse): '  + err.mes sage);
  213       }
  214   }
  215  
  216   function v cmn_newPro gressNoteL oad() {
  217       try {
  218           // GET CRM SE TTINGS WEB  SERVICE U RLS
  219           va r vcmn_con ditionalFi lter = "(m cs_name eq  'Active S ettings')" ;
  220           vc mn_getMult ipleEntity DataAsync( 'mcs_setti ngSet', 'f tp_DACURL,  ftp_Notes WriteAPIUR L, ftp_ESR APIURL, ft p_VistaUse rsAPIURL,  ftp_IsProd uctionEnvi ronment, f tp_VIAAddi tionalSign ersURL', v cmn_condit ionalFilte r, 'mcs_na me', 'asc' , 0, vcmn_ SettingsWe bServiceUR L_response , vcmn_Not eWriteUrl) ;
  221       }
  222       catch  (err) {
  223           // Display Er ror
  224           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_newP rogressNot eLoad): '  + err.mess age);
  225       }
  226   }
  227  
  228   function v cmn_newPro gressNoteL oad_WebURL () {
  229       try {
  230           // Only handl e forms in  create st ate
  231           if  (Xrm.Page .ui.getFor mType() !=  1) { retu rn false;  }
  232  
  233           // Set defaul t values b ased on th e current  user's USD  Config an d Facility
  234           va r vcmn_cur rentUserId  = Xrm.Pag e.context. getUserId( );
  235           va r vcmn_cur rentUserDa ta = vcmn_ getSingleE ntityDataS ync('Syste mUserSet',  'msdyusd_ USDConfigu rationId,  ftp_Facili tySiteId',  vcmn_curr entUserId) ;
  236           if  (vcmn_cur rentUserDa ta != null ) {
  237                if (vcmn _currentUs erData.d.m sdyusd_USD Configurat ionId != n ull) {
  238                    if ( vcmn_curre ntUserData .d.msdyusd _USDConfig urationId. Id != null ) {
  239                         if (vcmn_c urrentUser Data.d.ftp _FacilityS iteId != n ull) {
  240                             if (vc mn_current UserData.d .ftp_Facil itySiteId. Id != null ) {
  241                                 // Data Requi red to loo kup Facili ty Group D efaults ar e present
  242                                 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 + "')";
  243                                 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);
  244                             }
  245                         }
  246                    }
  247                }
  248           }
  249  
  250           // Determine  if regardi ng field i s prefille d (added b y subgrid+ )
  251           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  252           va r vcmn_tri ageexpert  = null;
  253           va r vcmn_tri ageminutes  = null;
  254           if  (vcmn_req uestId ==  null) {
  255                //Get cu stom param eters pass ed to the  form
  256                var vcmn _regarding objectid =  vcmn_getQ ueryVariab le("parame ter_regard ingobjecti d");
  257                var vcmn _regarding objectidna me = vcmn_ getQueryVa riable("pa rameter_re gardingobj ectidname" );
  258                var vcmn _regarding objectidty pe = vcmn_ getQueryVa riable("pa rameter_re gardingobj ectidtype" );
  259                vcmn_tri ageexpert  = vcmn_get QueryVaria ble("param eter_triag eexpert");
  260                vcmn_tri ageminutes  = vcmn_ge tQueryVari able("para meter_tria geminutes" );
  261  
  262                if (vcmn _regarding objectid = = '' || vc mn_regardi ngobjectid  == null | | vcmn_reg ardingobje ctidname = = '' || vc mn_regardi ngobjectid name == nu ll ||
  263                    vcmn _regarding objectidty pe == '' | | vcmn_reg ardingobje ctidtype = = null) {  return fal se; }
  264           }
  265           el se {
  266                var vcmn _regarding objectid =  vcmn_requ estId[0].i d;
  267                var vcmn _regarding objectidna me = vcmn_ requestId[ 0].name;
  268                var vcmn _regarding objectidty pe = vcmn_ requestId[ 0].entityT ype;
  269           }
  270           if  (vcmn_tri ageexpert  == null) {  vcmn_tria geexpert =  'NO'; }
  271           if  (vcmn_tri ageminutes  == null)  { vcmn_tri ageminutes  = 0; }
  272  
  273           // Populate r egarding o bject
  274           vc mn_setSimp leLookupVa lue('regar dingobject id', vcmn_ regardingo bjectidtyp e, vcmn_re gardingobj ectid, vcm n_regardin gobjectidn ame);
  275           Xr m.Page.get Attribute( 'regarding objectid') .setSubmit Mode('alwa ys');
  276  
  277           // Populate s ubject wit h regardin g objects  title
  278           Xr m.Page.get Attribute( 'subject') .setValue( 'Progress  Note: ' +  vcmn_regar dingobject idname);
  279           if  (vcmn_tri ageexpert  == 'YES')  { Xrm.Page .getAttrib ute('subje ct').setVa lue('Triag e Note: '  + vcmn_reg ardingobje ctidname);  }
  280           Xr m.Page.get Attribute( 'subject') .setSubmit Mode('alwa ys');
  281           // Default Sa ve to CPPR S
  282           Xr m.Page.get Attribute( 'ftp_savet ovista').s etValue(10 0000001);  //Yes
  283           Xr m.Page.get Attribute( 'ftp_savet ovista').s etSubmitMo de('always ');
  284  
  285           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  286  
  287           // Populate f orm with r elated CRM  data
  288           va r vcmn_sub ReasonId =  null; //R eference t o the Reas on for Req uest Sub R eason
  289           va r vcmn_min orReasonId  = null;   //Referenc e to the R eason for  Request Mi nor Reason
  290           va r vcmn_sub ReasonTemp lateText =  null;
  291           va r vcmn_min orReasonTe mplateText  = null;
  292           va r vcmn_min orReasonNo teSubText  = null;
  293  
  294           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 );
  295           if  (vcmn_req uestData ! = null) {
  296                if (vcmn _requestDa ta.d.ftp_C allbackNum ber != nul l) {
  297                    Xrm. Page.getAt tribute('f tp_callbac knumber'). setValue(v cmn_reques tData.d.ft p_Callback Number);
  298                    Xrm. Page.getAt tribute('f tp_callbac knumber'). setSubmitM ode('alway s');
  299                }
  300                if (vcmn _requestDa ta.d.ftp_R easonforRe quest != n ull) {
  301                    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);
  302                    Xrm. Page.getAt tribute('f tp_reasonf orrequest' ).setSubmi tMode('alw ays');
  303                }
  304  
  305                if (vcmn _requestDa ta.d.ftp_S ubReasonId  != null)  {
  306                    vcmn _subReason Id = vcmn_ requestDat a.d.ftp_Su bReasonId. Id;
  307                    if ( vcmn_subRe asonId !=  null) {
  308                         //Get Temp late Text
  309                         var vcmn_s ubreasonDa ta = vcmn_ getSingleE ntityDataS ync('ftp_s ubreasonSe t', 'ftp_n otetext',  vcmn_subRe asonId);
  310                         if (vcmn_s ubreasonDa ta.d.ftp_n otetext !=  null) {
  311                             vcmn_s ubReasonTe mplateText  = vcmn_su breasonDat a.d.ftp_no tetext;
  312                         }
  313                    }
  314                }
  315                if (vcmn _requestDa ta.d.ftp_M inorReason Id != null ) {
  316                    vcmn _minorReas onId = vcm n_requestD ata.d.ftp_ MinorReaso nId.Id;
  317                    if ( vcmn_minor ReasonId ! = null) {
  318                         //Get Temp late Text
  319                         var vcmn_m inorreason Data = vcm n_getSingl eEntityDat aSync('ftp _minorreas onSet', 'f tp_name, f tp_notetex t', vcmn_m inorReason Id);
  320                         if (vcmn_m inorreason Data.d.ftp _name != n ull) {
  321                             vcmn_m inorReason TemplateTe xt = vcmn_ minorreaso nData.d.ft p_name;
  322                         }
  323                         if (vcmn_m inorreason Data.d.ftp _notetext  != null) {
  324                             vcmn_m inorReason NoteSubTex t = vcmn_m inorreason Data.d.ftp _notetext;
  325                         }
  326                    }
  327                }
  328  
  329                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  330                    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);
  331                    Xrm. Page.getAt tribute('f tp_patient ').setSubm itMode('al ways');
  332                    //Se t as veter an id
  333                    vcmn _veteranId  = vcmn_re questData. d.Customer Id.Id
  334                }
  335  
  336                //Constr uct Templa te Note
  337                var vcmn _subReason Name = nul l;
  338                var vcmn _templateN ote = "";
  339                var vcmn _lastFille d = "";
  340                var vcmn _quantityR eportsTaki ng = null;
  341                var vcmn _rxNumber  = null;
  342                var vcmn _rxRefillQ uantity =  null;
  343                var vcmn _trackingN umber = nu ll;
  344                var vcmn _opioidAgr eementOnfi le = null;
  345                var vcmn _UDSonfile  = null;
  346                var vcmn _stateDrug Monitoring Report = n ull;
  347                var vcmn _spdmpstat eonfile =  null;
  348                var vcmn _sPDMPStat e2 = null;
  349                var vcmn _pickupmet hod = null ;
  350  
  351                var vcmn _earlyRefi llComment  = null;
  352                var vcmn _quantityT aking = nu ll;
  353                var vcmn _vacationS tart = nul l;
  354                var vcmn _vacationE nd = null;
  355  
  356                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)); }
  357                if (vcmn _requestDa ta.d.ftp_Q uantityRep ortsTaking  != null)  { vcmn_qua ntityRepor tsTaking =  vcmn_requ estData.d. ftp_Quanti tyReportsT aking; }
  358                if (vcmn _requestDa ta.d.ftp_R xNumber !=  null) { v cmn_rxNumb er = vcmn_ requestDat a.d.ftp_Rx Number; }
  359                if (vcmn _requestDa ta.d.ftp_R xRefillQua ntity != n ull) { vcm n_rxRefill Quantity =  vcmn_requ estData.d. ftp_RxRefi llQuantity ; }
  360                if (vcmn _requestDa ta.d.ftp_T rackingNum ber != nul l) { vcmn_ trackingNu mber = vcm n_requestD ata.d.ftp_ TrackingNu mber; }
  361                if (vcmn _requestDa ta.d.ftp_O piodAgreem entOnfile  != null) {  vcmn_opio idAgreemen tOnfile =  vcmn_reque stData.d.f tp_OpiodAg reementOnf ile.Value;  }
  362                if (vcmn _requestDa ta.d.ftp_U DSonfile ! = null) {  vcmn_UDSon file = vcm n_requestD ata.d.ftp_ UDSonfile. Value; }
  363                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; }
  364                if (vcmn _requestDa ta.d.ftp_s pdmpstateo nfile != n ull) { vcm n_spdmpsta teonfile =  vcmn_requ estData.d. ftp_spdmps tateonfile .Value; }
  365                if (vcmn _requestDa ta.d.ftp_S PDMPState2  != null)  { vcmn_sPD MPState2 =  vcmn_requ estData.d. ftp_SPDMPS tate2.Valu e; }
  366                if (vcmn _requestDa ta.d.ftp_p ickupmetho d != null)  { vcmn_pi ckupmethod  = vcmn_re questData. d.ftp_pick upmethod.V alue; }
  367  
  368                if (vcmn _requestDa ta.d.ftp_e arlyrefill comment !=  null) { v cmn_earlyR efillComme nt = vcmn_ requestDat a.d.ftp_ea rlyrefillc omment; }
  369                if (vcmn _requestDa ta.d.ftp_q uantitytak ing != nul l) { vcmn_ quantityTa king = vcm n_requestD ata.d.ftp_ quantityta king; }
  370                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)); }
  371                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)) ; }
  372                
  373                if (vcmn _requestDa ta.d.ftp_S ubReasonId  != null)  {
  374                    vcmn _subReason Id = vcmn_ requestDat a.d.ftp_Su bReasonId. Id;
  375                    vcmn _subReason Name = vcm n_requestD ata.d.ftp_ SubReasonI d.Name;
  376  
  377                    if ( vcmn_subRe asonName = = 'Regular ') {
  378                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Veteran i s requesti ng a RENEW AL." + "\n \n";
  379                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Last Fill ed: " + vc mn_lastFil led + "\n\ n";
  380                         if (vcmn_m inorReason TemplateTe xt != null ) {
  381                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason TemplateTe xt + "\n\n ";
  382                         }
  383                         if (vcmn_m inorReason NoteSubTex t != null)  {
  384                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason NoteSubTex t + "\n\n" ;
  385                         }
  386                         if (vcmn_s ubReasonTe mplateText  != null)  {
  387                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_s ubReasonTe mplateText  + "\n\n";
  388                         }
  389                    }
  390  
  391                    if ( vcmn_subRe asonName = = 'Early')  {
  392                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Veteran i s requesti ng EARLY F ILL." + "\ n\n";
  393                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Last Fill ed: " + vc mn_lastFil led + "\n\ n";
  394                         if (vcmn_m inorReason TemplateTe xt != null ) {
  395                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason TemplateTe xt + "\n\n ";
  396                         }
  397  
  398                         if (vcmn_q uantityTak ing != nul l) {
  399                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Quant ity Taking : " + vcmn _quantityT aking + "\ n\n";
  400                         }
  401  
  402                         if (vcmn_v acationSta rt != null  && vcmn_v acationEnd  != null)  {
  403                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Veter an Leaving  Town: " +  vcmn_vaca tionStart  + ' - ' +  vcmn_vacat ionEnd + " \n\n";
  404                         }
  405  
  406                         if (vcmn_m inorReason NoteSubTex t != null)  {
  407                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason NoteSubTex t + "\n\n" ;
  408                         }
  409                         if (vcmn_s ubReasonTe mplateText  != null)  {
  410                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_s ubReasonTe mplateText  + "\n\n";
  411                         }
  412                    }
  413  
  414                    if ( vcmn_subRe asonName = = 'Lost')  {
  415                         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 ";
  416                         if (vcmn_r xNumber !=  null) {
  417                             vcmn_t emplateNot e = vcmn_t emplateNot e + "RX#:  " + vcmn_r xNumber +  "\n\n";
  418                         }
  419                         if (vcmn_r xRefillQua ntity != n ull) {
  420                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Rx Re fill Quant ity: " + v cmn_rxRefi llQuantity  + "\n\n";
  421                         }
  422                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Last Fill ed: " + vc mn_lastFil led + "\n\ n";
  423                         if (vcmn_m inorReason TemplateTe xt != null ) {
  424                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason TemplateTe xt + "\n\n ";
  425                         }
  426                         if (vcmn_t rackingNum ber != nul l) {
  427                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Track ing Number : " + vcmn _trackingN umber + "\ n\n";
  428                         }
  429                         if (vcmn_m inorReason NoteSubTex t != null)  {
  430                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason NoteSubTex t + "\n\n" ;
  431                         }
  432                         if (vcmn_s ubReasonTe mplateText  != null)  {
  433                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_s ubReasonTe mplateText  + "\n\n";
  434                         }
  435                    }
  436  
  437                    if ( vcmn_subRe asonName = = 'Stolen' ) {
  438                         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";
  439                         vcmn_templ ateNote =  vcmn_templ ateNote +  "Last Fill ed: " + vc mn_lastFil led + "\n\ n";
  440                         if (vcmn_m inorReason TemplateTe xt != null ) {
  441                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason TemplateTe xt + "\n\n ";
  442                         }
  443                         if (vcmn_m inorReason NoteSubTex t != null)  {
  444                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_m inorReason NoteSubTex t + "\n\n" ;
  445                         }
  446                         if (vcmn_s ubReasonTe mplateText  != null)  {
  447                             vcmn_t emplateNot e = vcmn_t emplateNot e + vcmn_s ubReasonTe mplateText  + "\n\n";
  448                         }
  449                    }
  450  
  451                    //If  Template  Text was p opulated,  fill in ad ditional i nfo...
  452                    if ( vcmn_templ ateNote !=  '') {
  453                         vcmn_templ ateNote =  vcmn_templ ateNote +  "\n_______ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ _\n\n";
  454                         //Is an Op ioid Agree ment curre nt and onf ile?
  455                         if (vcmn_o pioidAgree mentOnfile  != null)  {
  456                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Conse nt for Lon g-Term Opi oid Therap y for Pain :\n";
  457                             if (vc mn_opioidA greementOn file == 10 0000000) {
  458                                 // Yes Option
  459                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] Yes - S ee Posting s\n\n";
  460                             }
  461                             if (vc mn_opioidA greementOn file == 10 0000001) {
  462                                 // No Option
  463                                 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";
  464                             }
  465                         }
  466                         //Is valid  Urine Dru g Screen o n-file?
  467                         if (vcmn_U DSonfile ! = null) {
  468                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Is va lid Urine  Drug Scree n on-file? \n";
  469                             if (vc mn_UDSonfi le == 1000 00000) {
  470                                 // Yes Option
  471                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] Yes - S ee Posting s\n\n";
  472                             }
  473                             if (vc mn_UDSonfi le == 1000 00001) {
  474                                 // No Option
  475                                 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";
  476                             }
  477                         }
  478                         //State Dr ug Monitor ing Report ?
  479                         if (vcmn_s tateDrugMo nitoringRe port != nu ll) {
  480                             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";
  481                             if (vc mn_stateDr ugMonitori ngReport = = 10000000 0) {
  482                                 // Positive O ption
  483                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] Positiv e - see SP DMP note.\ n\n";
  484                             }
  485                             if (vc mn_stateDr ugMonitori ngReport = = 10000000 1) {
  486                                 // Negative O ption
  487                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] Negativ e.\n\n";
  488                             }
  489                             if (vc mn_stateDr ugMonitori ngReport = = 10000000 2) {
  490                                 // Not on Fil e Option
  491                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] None on  file, Pha rmacy to r equest.\n\ n";
  492                             }
  493                             //Add  in States  (2), conve rt integer s to state  names fro m form's h idden stat e options
  494                             var vc mn_usState sOptions =  Xrm.Page. getAttribu te("ftp_us statesopti on").getOp tions();
  495                             var vc mn_stateLi st = "";
  496                             if (vc mn_spdmpst ateonfile  != null) {
  497                                 // find text  value for  option
  498                                 $( vcmn_usSta tesOptions ).each(fun ction (i,  e) {
  499                                      var vcmn _optionTex t = $(this )[0].text;
  500                                      var vcmn _optionVal ue = $(thi s)[0].valu e;
  501                                      if (vcmn _spdmpstat eonfile ==  vcmn_opti onValue) {  vcmn_stat eList = vc mn_optionT ext; }
  502                                 }) ;
  503                             }
  504                             if (vc mn_sPDMPSt ate2 != nu ll) {
  505                                 // find text  value for  option
  506                                 $( vcmn_usSta tesOptions ).each(fun ction (i,  e) {
  507                                      var vcmn _optionTex t = $(this )[0].text;
  508                                      var vcmn _optionVal ue = $(thi s)[0].valu e;
  509                                      if (vcmn _sPDMPStat e2 == vcmn _optionVal ue) { vcmn _stateList  = vcmn_st ateList +  ", " +vcmn _optionTex t; }
  510                                 }) ;
  511                             }
  512                             if (vc mn_stateLi st != "")  {
  513                                 // Add states  list to n ote
  514                                 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;
  515                             }
  516                         }
  517  
  518                         //If ftp_p ickupmetho d has a va lue
  519                         if (vcmn_p ickupmetho d != null)  {
  520                             vcmn_t emplateNot e = vcmn_t emplateNot e + "\n___ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ _____\n\n" ;
  521                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Veter an request ed Method  of Pick Up :  ";
  522                             if (vc mn_pickupm ethod == 1 00000000)  {
  523                                 // Mail Optio n
  524                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] Mail. \ n\n";
  525                             }
  526                             if (vc mn_pickupm ethod == 1 00000001)  {
  527                                 // Window Opt ion
  528                                 vc mn_templat eNote = vc mn_templat eNote + "[ X] Window.  \n\n";
  529                             }
  530                             //Get  veteran's  current ad dress
  531                             if (vc mn_veteran Id != null ) {
  532                                 va r vcmn_con tactData =  vcmn_getS ingleEntit yDataSync( 'ContactSe t', 'Addre ss1_Compos ite', vcmn _veteranId );
  533                                 if  (vcmn_con tactData ! = null) {
  534                                      if (vcmn _contactDa ta.d.Addre ss1_Compos ite != nul l && vcmn_ contactDat a.d.Addres s1_Composi te != '')  {
  535                                          vcmn _templateN ote = vcmn _templateN ote + "Add ress confi rmed with  caller: \n ";
  536                                          vcmn _templateN ote = vcmn _templateN ote + vcmn _contactDa ta.d.Addre ss1_Compos ite + "\n" ;
  537                                          if ( Xrm.Page.g etAttribut e('ftp_cal lbacknumbe r').getVal ue() != nu ll) {
  538                                               vcmn_templ ateNote =  vcmn_templ ateNote +  Xrm.Page.g etAttribut e('ftp_cal lbacknumbe r').getVal ue();
  539                                          }
  540                                      }
  541                                 }
  542                             }
  543                         }
  544                    }
  545  
  546                    //Wr ite note t ext if not  Triage:
  547                    if ( vcmn_triag eexpert ==  'NO' || v cmn_triage expert ==  null) {
  548                         Xrm.Page.g etAttribut e('ftp_not edetail'). setValue(v cmn_templa teNote);
  549                         Xrm.Page.g etAttribut e('ftp_not edetail'). setSubmitM ode('alway s');
  550                    }
  551                }
  552  
  553                //Defaul t Diagnosi s code if  TAN user,  based on s ystemuser  lookup
  554                var vcmn _currentUs erId = Xrm .Page.cont ext.getUse rId();
  555                var vcmn _currentUs erData = v cmn_getSin gleEntityD ataSync('S ystemUserS et', 'msdy usd_USDCon figuration Id, ftp_Fa cilitySite Id', vcmn_ currentUse rId);
  556                if (vcmn _currentUs erData !=  null) {
  557                    if ( vcmn_curre ntUserData .d.msdyusd _USDConfig urationId  != null) {
  558                         if (vcmn_c urrentUser Data.d.msd yusd_USDCo nfiguratio nId.Name ! = null) {
  559                             if (vc mn_current UserData.d .msdyusd_U SDConfigur ationId.Na me == 'TAN  Configura tion') {
  560                                 // Get Defaul t Tan Conf iguration  from User' s Facility
  561                                 if  (vcmn_cur rentUserDa ta.d.ftp_F acilitySit eId != nul l) {
  562                                      if (vcmn _currentUs erData.d.f tp_Facilit ySiteId.Id  != null)  {
  563                                          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);
  564                                          if ( vcmn_curre ntUserFaci lityData ! = null) {
  565                                               if (vcmn_c urrentUser FacilityDa ta.d.ftp_d efaulttand iagnosisco de != null ) {
  566                                                   if (vc mn_current UserFacili tyData.d.f tp_default tandiagnos iscode.Id  != null) {
  567                                                       // Write Diag nosis code  to Progre ss Note Fo rm if a Tr iage Note
  568                                                       if  (vcmn_tri ageexpert  == 'YES')  {
  569                                                            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);
  570                                                            Xrm.Page .getAttrib ute('ftp_d iagnosisco de').setSu bmitMode(' always');
  571                                                       }
  572                                                   }
  573                                               }
  574                                          }
  575  
  576                                          //Ma tch up the  VHG Triag e minute c onfigurati on with CP T Code
  577                                          if ( vcmn_triag eminutes >  0) {
  578                                               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 +  " )";
  579                                               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);
  580                                          }
  581                                      }
  582                                 }
  583                             }
  584                         }
  585                    }
  586                }
  587  
  588                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 == '')  {
  589                    //Pr ompt user  to include  existing  Request No tes if the re is a cu rrent valu e
  590                    Xrm. Utility.co nfirmDialo g(
  591                         "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. ",
  592                         function ( ) {
  593                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setVal ue(vcmn_re questData. d.Descript ion);
  594                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setSub mitMode('a lways');
  595                         }
  596                    );
  597                }
  598           }
  599  
  600           // 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)
  601           if  (vcmn_vet eranId !=  null) {
  602                var vcmn _contactDa ta = vcmn_ getSingleE ntityDataS ync('Conta ctSet', 'f tp_current facilityid , ftp_Faci lityId', v cmn_vetera nId);
  603                if (vcmn _contactDa ta != null ) {
  604                    if ( vcmn_conta ctData.d.f tp_current facilityid  != null)  {
  605                         if (vcmn_c ontactData .d.ftp_cur rentfacili tyid.Id !=  null) {
  606                             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);
  607                             Xrm.Pa ge.getAttr ibute('ftp _patientfa cility').s etSubmitMo de('always ');
  608                         }
  609                    else  {
  610                             //Get  Facility f rom Home F acility
  611                             if (vc mn_contact Data.d.ftp _FacilityI d != null)  {
  612                                 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 );
  613                                 Xr m.Page.get Attribute( 'ftp_patie ntfacility ').setSubm itMode('al ways');
  614                             }
  615                         }
  616                    }
  617                    else  {
  618                         //Get Faci lity from  Home Facil ity
  619                         if (vcmn_c ontactData .d.ftp_Fac ilityId !=  null) {
  620                             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);
  621                             Xrm.Pa ge.getAttr ibute('ftp _patientfa cility').s etSubmitMo de('always ');
  622                         }
  623                    }
  624                }
  625           }
  626  
  627           // Set defaul t patient  admit date
  628           Xr m.Page.get Attribute( 'ftp_patie ntadmitdat e').setVal ue(new Dat e());
  629           Xr m.Page.get Attribute( 'ftp_patie ntadmitdat e').setSub mitMode('a lways');
  630  
  631           // Set other  default fo rm values
  632           Xr m.Page.get Attribute( 'scheduled start').se tValue(new  Date());
  633           Xr m.Page.get Attribute( 'scheduled start').se tSubmitMod e('always' );
  634           Xr m.Page.get Attribute( 'scheduled end').setV alue(new D ate());
  635           Xr m.Page.get Attribute( 'scheduled end').setS ubmitMode( 'always');
  636  
  637           // Append Gen eric Templ ate Data t o top of e xisting no te
  638           va r vcmn_gen ericTempla teData = " Callback N umber: ";
  639           if  (Xrm.Page .getAttrib ute('ftp_c allbacknum ber').getV alue() !=  null && Xr m.Page.get Attribute( 'ftp_callb acknumber' ).getValue () != "")  {
  640                vcmn_gen ericTempla teData = v cmn_generi cTemplateD ata + Xrm. Page.getAt tribute('f tp_callbac knumber'). getValue() ;
  641           }
  642           // Construct  new note w ith existi ng note da ta
  643           va r vcmn_exi stingNoteD ata = "";
  644           if  (Xrm.Page .getAttrib ute("ftp_n otedetail" ).getValue () != null  && Xrm.Pa ge.getAttr ibute("ftp _notedetai l").getVal ue() != "" ) {
  645                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  646           }
  647           vc mn_generic TemplateDa ta = vcmn_ genericTem plateData  + "\n\n" +  vcmn_exis tingNoteDa ta;
  648           // Replace ex isting not e
  649           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_genericT emplateDat a);
  650           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  651  
  652           // Change Foc us to the  Notes fiel d
  653           Xr m.Page.get Control("f tp_notedet ail").setF ocus();      
  654  
  655           // Get ICN vi a web serv ice and ge t Service  Connected  disabiliti es thereaf ter
  656           // Preserved  Variables
  657           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  658           va r vcmn_vet eranFirstN ame = '';
  659           va r vcmn_vet eranLastNa me = '';
  660           va r vcmn_SSN  = '';
  661           va r vcmn_DOB  = '';
  662  
  663           // Get regard ing data
  664           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  665           if  (vcmn_req uestId ==  null) { re turn false ; }
  666           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  667  
  668           if  (vcmn_req uestData ! = null) {
  669                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  670                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  671                    //Ve rify that  the custom erid is of  type cont act
  672                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  673                         return fal se;
  674                    }
  675                }
  676           }
  677           if  (vcmn_vet eranId ==  null) {
  678                return f alse;
  679           }
  680  
  681           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);
  682           if  (vcmn_con tactData ! = null) {
  683                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  684                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  685                if (vcmn _contactDa ta.d.ftp_D ateofBirth  != null)  { vcmn_DOB  = vcmn_co ntactData. d.ftp_Date ofBirth; }
  686                if (vcmn _contactDa ta.d.Gover nmentId !=  null) { v cmn_SSN =  vcmn_conta ctData.d.G overnmentI d; }
  687           }
  688  
  689           // Perform MV I Search f or Service  Connected  Disabilit ies
  690           vc mn_unatten dedMviSear chSCD(vcmn _veteranFi rstName, v cmn_vetera nLastName,  vcmn_DOB,  vcmn_SSN) ;
  691       }
  692       catch  (err) {
  693           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_newP rogressNot eLoad_WebU RL): ' + e rr.message );
  694       }
  695   }
  696  
  697   function v cmn_getSer viceConnec tedDisabil ities(vcmn _patientIC N) {
  698       //**** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ***
  699       //Janu ary 16 201 7 - EXIT T HE FUNCTIO N, NOT USE D SEE BELO W
  700       return  false;
  701       //***T HE CODE BE LOW HAS BE EN TEMPORA RILY DISAB LED TO NOT  INCLUDE S ERVICE CON NECTED DIS ABILITIES  IN THE NOT E
  702       //**** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ***
  703       try {
  704           // ******Deve loper Bypa ss for mis sing ICN** ****
  705           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  706                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  707                    aler t("Develop er ICN byp ass applie d!");
  708                    vcmn _patientIC N = "12345 6V123456";
  709                }
  710           }
  711  
  712           // Verify Pat ient ICN
  713           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  714                //No ICN , do not p roceed
  715                return f alse;
  716           }
  717  
  718           // Get the se rvice conn ected disa bilities d ata from t he web ser vice
  719           va r vcmn_dis abilitiesX mlData = v cmn_getDis abilityDat a(vcmn_pat ientICN);
  720  
  721           // Temporary  action: xm l result i s empty, u se sample  data, comm ent out wh en not use d
  722           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********
  723           // if (vcmn_d isabilitie sXmlData = = null ||  vcmn_disab ilitiesXml Data == '' ) { vcmn_d isabilitie sXmlData =  xml_resul ts3; }
  724           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********
  725  
  726           // If no data , do not p roceed.
  727           if  (vcmn_dis abilitiesX mlData ==  null || vc mn_disabil itiesXmlDa ta == '')  { return f alse; }
  728  
  729           // Create bas e Note Str ing
  730           va r vcmn_SCD noteString  = '';
  731           vc mn_SCDnote String = v cmn_SCDnot eString +  "\n------- ---------- ---------- ---------- ---------- ---------- ---------- ------\n";
  732           vc mn_SCDnote String = v cmn_SCDnot eString +  "Special T reatment A uthority a nd Service  Connected  Disabilit ies";
  733           vc mn_SCDnote String = v cmn_SCDnot eString +  "\n------- ---------- ---------- ---------- ---------- ---------- ---------- ------\n";
  734  
  735           // Search XML  values
  736           vc mn_xmlDoc  = $.parseX ML(vcmn_di sabilities XmlData);
  737           $v cmn_xml =  $(vcmn_xml Doc);
  738  
  739           // Data from  parentnode  'enrollme ntDetermin ationInfo'  
  740           va r $vcmn_en rollmentDe terminatio nInfo = nu ll;
  741           va r $vcmn_pr imaryEligi bility = n ull;
  742           va r $vcmn_ty pe = null;
  743           va r vcmn_typ eText = nu ll;
  744           va r $vcmn_en rollmentCa tegoryName  = null;
  745           va r vcmn_enr ollmentCat egoryNameT ext = null ;
  746           va r $vcmn_sp ecialFacto rs = null;
  747           va r $vcmn_en vContamina ntsInd = n ull;
  748           va r vcmn_env Contaminan tsIndText  = null;
  749           va r $vcmn_ra diationExp osureInd =  null;
  750           va r vcmn_rad iationExpo sureIndTex t = null;
  751           va r $vcmn_ag entOrangeI nd = null;
  752           va r vcmn_age ntOrangeIn dText = nu ll;
  753           va r $vcmn_ca mpLejeuneI nd = null;
  754           va r vcmn_cam pLejeuneIn dText = nu ll;
  755           va r $vcmn_se rviceConne ctionAward  = null;
  756           va r $vcmn_se rviceConne ctedPercen tage = nul l;
  757           va r vcmn_ser viceConnec tedPercent ageText =  null;
  758           va r $vcmn_ra tedDisabil ities = nu ll;
  759  
  760           va r $vcmn_ag entOrangeL ocation =  null;
  761           va r vcmn_age ntOrangeLo cationText  = null;
  762           va r $vcmn_ra diationExp osureMetho d = null;
  763           va r vcmn_rad iationExpo sureMethod Text = nul l;
  764  
  765           va r $vcmn_no seThroatRa diumInfo =  null;
  766           va r $vcmn_di agnosedWit hCancer =  null;
  767           va r vcmn_dia gnosedWith CancerText  = null;
  768  
  769           va r $vcmn_mi litarySexu alTraumaIn fo = null;
  770           va r $vcmn_mi lSexTrauma Status = n ull;
  771           va r vcmn_mil SexTraumaS tatusText  = null;
  772  
  773           // Data from  parentnode  'military ServiceInf o' 
  774           va r $vcmn_mi litaryServ iceInfo =  null;
  775           va r $vcmn_co mbatVetera nEligibili tyEndDate  = null;
  776           va r vcmn_com batVeteran Eligibilit yEndDateTe xt = null;
  777           va r $vcmn_sh adIndicato r = null;
  778           va r vcmn_sha dIndicator Text = nul l;
  779  
  780           va r vcmn_rat edDisabili tyPercenta geTotal =  0;
  781  
  782           va r vcmn_det ailrowcoun t = 0;
  783  
  784           $v cmn_enroll mentDeterm inationInf o = $vcmn_ xml.find(' enrollment Determinat ionInfo');
  785           if  ($vcmn_en rollmentDe terminatio nInfo != n ull) {
  786                $vcmn_pr imaryEligi bility = $ vcmn_enrol lmentDeter minationIn fo.find('p rimaryElig ibility');
  787                if ($vcm n_primaryE ligibility  != null)  {
  788                    $vcm n_type = $ vcmn_prima ryEligibil ity.find(' type');
  789                    if ( $vcmn_type  != null)  { vcmn_typ eText = $v cmn_type.t ext(); }
  790                }
  791  
  792                $vcmn_en rollmentCa tegoryName  = $vcmn_e nrollmentD eterminati onInfo.fin d('enrollm entCategor yName');
  793                if ($vcm n_enrollme ntCategory Name != nu ll) { vcmn _enrollmen tCategoryN ameText =  $vcmn_enro llmentCate goryName.t ext(); }
  794  
  795                $vcmn_sp ecialFacto rs = $vcmn _enrollmen tDetermina tionInfo.f ind('speci alFactors' );
  796                if ($vcm n_specialF actors !=  null) {
  797                    $vcm n_envConta minantsInd  = $vcmn_s pecialFact ors.find(' envContami nantsInd') ;
  798                    if ( $vcmn_envC ontaminant sInd != nu ll) { vcmn _envContam inantsIndT ext = $vcm n_envConta minantsInd .text(); }
  799                    $vcm n_radiatio nExposureI nd = $vcmn _specialFa ctors.find ('radiatio nExposureI nd');
  800                    if ( $vcmn_radi ationExpos ureInd !=  null) { vc mn_radiati onExposure IndText =  $vcmn_radi ationExpos ureInd.tex t(); }
  801                    $vcm n_agentOra ngeInd = $ vcmn_speci alFactors. find('agen tOrangeInd ');
  802                    if ( $vcmn_agen tOrangeInd  != null)  { vcmn_age ntOrangeIn dText = $v cmn_agentO rangeInd.t ext(); }
  803                    $vcm n_campLeje uneInd = $ vcmn_speci alFactors. find('camp LejeuneInd ');
  804                    if ( $vcmn_camp LejeuneInd  != null)  { vcmn_cam pLejeuneIn dText = $v cmn_campLe jeuneInd.t ext(); }
  805  
  806                    $vcm n_agentOra ngeLocatio n = $vcmn_ specialFac tors.find( 'agentOran geLocation ');
  807                    if ( $vcmn_agen tOrangeLoc ation != n ull) { vcm n_agentOra ngeLocatio nText = $v cmn_agentO rangeLocat ion.text() ; }
  808                    $vcm n_radiatio nExposureM ethod = $v cmn_specia lFactors.f ind('radia tionExposu reMethod') ;
  809                    if ( $vcmn_radi ationExpos ureMethod  != null) {  vcmn_radi ationExpos ureMethodT ext = $vcm n_radiatio nExposureM ethod.text (); }
  810                }
  811  
  812                $vcmn_se rviceConne ctionAward  = $vcmn_e nrollmentD eterminati onInfo.fin d('service Connection Award');
  813                if ($vcm n_serviceC onnectionA ward != nu ll) {
  814                    $vcm n_serviceC onnectedPe rcentage =  $vcmn_ser viceConnec tionAward. find('serv iceConnect edPercenta ge');
  815                    if ( $vcmn_serv iceConnect edPercenta ge != null ) { vcmn_s erviceConn ectedPerce ntageText  = $vcmn_se rviceConne ctedPercen tage.text( ); }
  816                    $vcm n_ratedDis abilities  = $vcmn_se rviceConne ctionAward .find('rat edDisabili ties');
  817                    //Ge t each dis ability li sted and a dd to note  string
  818                    vcmn _SCDnoteSt ring = vcm n_SCDnoteS tring + "S C Disabili ty: ";
  819                    $vcm n_ratedDis abilities. find('rate dDisabilit y').each(f unction ()  {
  820                         var vcmn_r atedDisabi lityPercen t = 0;
  821                         var vcmn_d isability  = null;
  822                         if (Number ($(this).f ind('perce ntage').te xt()) > 0)  {
  823                             vcmn_r atedDisabi lityPercen tageTotal  = vcmn_rat edDisabili tyPercenta geTotal +  Number($(t his).find( 'percentag e').text() );
  824                             vcmn_r atedDisabi lityPercen t = Number ($(this).f ind('perce ntage').te xt());
  825                         }
  826                         //Add Rate d Disabili ties to th e Note Str ing if Dis ability Pe rcent > 0
  827                         if (vcmn_r atedDisabi lityPercen t > 0) {
  828                             vcmn_S CDnoteStri ng = vcmn_ SCDnoteStr ing + $(th is).find(' disability ').text()  + "\n";
  829                         }
  830                    });
  831                    vcmn _SCDnoteSt ring = vcm n_SCDnoteS tring + "\ n";
  832                }
  833  
  834                $vcmn_no seThroatRa diumInfo =  $vcmn_enr ollmentDet ermination Info.find( 'noseThroa tRadiumInf o');
  835                if ($vcm n_noseThro atRadiumIn fo != null ) {
  836                    $vcm n_diagnose dWithCance r = $vcmn_ noseThroat RadiumInfo .find('dia gnosedWith Cancer');
  837                    if ( $vcmn_diag nosedWithC ancer != n ull) { vcm n_diagnose dWithCance rText = $v cmn_diagno sedWithCan cer.text() ; }
  838                }
  839  
  840                $vcmn_mi litarySexu alTraumaIn fo = $vcmn _enrollmen tDetermina tionInfo.f ind('milit arySexualT raumaInfo' );
  841                if ($vcm n_military SexualTrau maInfo !=  null) {
  842                    $vcm n_milSexTr aumaStatus  = $vcmn_m ilitarySex ualTraumaI nfo.find(' status');
  843                    if ( $vcmn_milS exTraumaSt atus != nu ll) { vcmn _milSexTra umaStatusT ext = $vcm n_milSexTr aumaStatus .text(); }
  844                }
  845           }
  846  
  847           $v cmn_milita ryServiceI nfo = $vcm n_xml.find ('military ServiceInf o');
  848           if  ($vcmn_mi litaryServ iceInfo !=  null) {
  849                $vcmn_co mbatVetera nEligibili tyEndDate  = $vcmn_mi litaryServ iceInfo.fi nd('combat VeteranEli gibilityEn dDate');
  850                if ($vcm n_combatVe teranEligi bilityEndD ate != nul l) {
  851                    vcmn _combatVet eranEligib ilityEndDa teText = v cmn_combat VeteranEli gibilityEn dDateText  = $vcmn_co mbatVetera nEligibili tyEndDate. text();
  852                }
  853                $vcmn_sh adIndicato r = $vcmn_ militarySe rviceInfo. find('shad Indicator' );
  854                if ($vcm n_shadIndi cator != n ull) { vcm n_shadIndi catorText  = $vcmn_sh adIndicato r.text();  }
  855           }
  856  
  857           // If no elig ibility sp ecified, s et to fals e
  858           if  (vcmn_typ eText == n ull || vcm n_typeText  == '') {  vcmn_typeT ext = fals e; }
  859  
  860           // Change boo lean value s to false  if not ma rked true
  861           if  (vcmn_env Contaminan tsIndText  != 'true')  { vcmn_en vContamina ntsIndText  = false;  }
  862           if  (vcmn_rad iationExpo sureIndTex t != 'true ') { vcmn_ radiationE xposureInd Text = fal se; }
  863           if  (vcmn_age ntOrangeIn dText != ' true') { v cmn_agentO rangeIndTe xt = false ; }
  864           if  (vcmn_cam pLejeuneIn dText != ' true') { v cmn_campLe jeuneIndTe xt = false ; }
  865  
  866           if  (vcmn_dia gnosedWith CancerText  != 'true' ) { vcmn_d iagnosedWi thCancerTe xt = false ; }
  867           if  (vcmn_sha dIndicator Text != 't rue') { vc mn_shadInd icatorText  = false;  }
  868  
  869           // Change all  True/Fals e to Yes/N o
  870           if  (vcmn_typ eText == f alse) { vc mn_typeTex t = 'No';  }
  871  
  872           if  (vcmn_env Contaminan tsIndText  == "true")  { vcmn_en vContamina ntsIndText  = "Yes";  } else { v cmn_envCon taminantsI ndText = " No"; }
  873           if  (vcmn_rad iationExpo sureIndTex t == "true ") {
  874                vcmn_rad iationExpo sureIndTex t = "Yes";
  875                if (vcmn _radiation ExposureMe thodText ! = null) {  vcmn_radia tionExposu reIndText  = vcmn_rad iationExpo sureIndTex t + " - "  + vcmn_rad iationExpo sureMethod Text; }
  876           }  else {
  877                vcmn_rad iationExpo sureIndTex t = "No"; 
  878           }
  879           if  (vcmn_age ntOrangeIn dText == " true") {
  880                vcmn_age ntOrangeIn dText = "Y es";
  881                if (vcmn _agentOran geLocation Text != nu ll) { vcmn _agentOran geIndText  = vcmn_age ntOrangeIn dText + "  - " + vcmn _agentOran geLocation Text; }
  882           }
  883           el se {
  884                vcmn_age ntOrangeIn dText = "N o"; 
  885           }
  886           if  (vcmn_cam pLejeuneIn dText == " true") { v cmn_campLe jeuneIndTe xt = "Yes" ; } else {  vcmn_camp LejeuneInd Text = "No "; }
  887  
  888           if  (vcmn_dia gnosedWith CancerText  == "true" ) { vcmn_d iagnosedWi thCancerTe xt = "Yes" ; } else {  vcmn_diag nosedWithC ancerText  = "No"; }
  889  
  890           if  (vcmn_com batVeteran Eligibilit yEndDateTe xt != null  && vcmn_c ombatVeter anEligibil ityEndDate Text != '' ) { vcmn_c ombatVeter anEligibil ityEndDate Text = 'Ye s'; } 
  891  
  892           if  (vcmn_sha dIndicator Text == "t rue") { vc mn_shadInd icatorText  = "Yes";  } else { v cmn_shadIn dicatorTex t = "No";  }
  893           
  894           // Construct  summary no te part
  895           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"; }
  896           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"; }
  897           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"; }
  898           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 "; }
  899           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"; }
  900           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" ; }
  901           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"; }
  902           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 "; }
  903  
  904           // Update not e with new  SCD note  data
  905           va r vcmn_exi stingNoteD ata = "";
  906           if  (Xrm.Page .getAttrib ute("ftp_n otedetail" ).getValue () != null  && Xrm.Pa ge.getAttr ibute("ftp _notedetai l").getVal ue() != "" ) {
  907                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  908           }
  909           vc mn_extende dTemplateD ata = vcmn _existingN oteData +  vcmn_SCDno teString;
  910           // Replace ex isting not e
  911           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_extended TemplateDa ta);
  912           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  913       }
  914       catch  (err) {
  915           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getS erviceConn ectedDisab ilities):  ' + err.me ssage);
  916       }
  917   }
  918  
  919   function v cmn_getDis abilityDat a(vcmn_nat ionalId) {
  920       try {
  921           va r vcmn_ees ummaryURL  = vcmn_ees ummaryURLb ase + '000 000' + vcm n_national Id + '0000 00';
  922           va r vcmn_xml Data = nul l;
  923  
  924           $. ajax({
  925                type: "G ET",
  926                url: vcm n_eesummar yURL,
  927                contentT ype: "appl ication/xm l; charset =utf-8",
  928                dataType : "text",
  929                success:  function  (xmlTextda ta) {
  930                    vcmn _xmlData =  xmlTextda ta;
  931                },
  932                error: f unction (j qXHR, text Status, er rorThrown)  {
  933                    //Sy stem Error
  934                    vcmn _xmlData =  null;
  935                },
  936                async: f alse,
  937                cache: f alse
  938           }) ;
  939           re turn vcmn_ xmlData;
  940       }
  941       catch  (err) {
  942           al ert("Progr ess Note F orm Load S cript Func tion Error (vcmn_getD isabilityD ata): " +  err.messag e);
  943           re turn null;
  944       }
  945   }
  946  
  947   function v cmn_facili tyByCode_r esponse(vc mn_facilit yData, vcm n_lastSkip , vcmn_fac ilityCode)  {
  948       try {
  949           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  950           // ***REVISED  NOT USED,  KEEP FOR  FUTURE UPD ATE***
  951           /*
  952           va r vcmn_fac ilityid =  null;
  953           va r vcmn_fac ilityname  = null;
  954           fo r (var i =  0; i <= v cmn_facili tyData.d.r esults.len gth - 1; i ++) {
  955                //Get in fo
  956                if (vcmn _facilityD ata.d.resu lts[i].ftp _facilityI d != null)  { vcmn_fa cilityid =  vcmn_faci lityData.d .results[i ].ftp_faci lityId; }
  957                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; }
  958                break;
  959           }
  960           if  (vcmn_fac ilityid !=  null) {
  961                vcmn_set SimpleLook upValue('f tp_patient facility',  'ftp_faci lity', vcm n_facility id, vcmn_f acilitynam e);
  962                Xrm.Page .getAttrib ute('ftp_p atientfaci lity').set SubmitMode ('always') ;
  963           }
  964           */
  965       }
  966       catch  (err) {
  967           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_faci lityByCode _response) : ' + err. message);
  968       }
  969   }
  970  
  971   function v cmn_cptCod e_response (vcmn_cptC odeData, v cmn_lastSk ip, vcmn_t riageminut es) {
  972       try {
  973           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  974           fo r (var i =  0; i <= v cmn_cptCod eData.d.re sults.leng th - 1; i+ +) {
  975                //Write  to CRM pro gress note  form
  976                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);
  977                Xrm.Page .getAttrib ute('ftp_c ptcode').s etSubmitMo de('always ');
  978                break;
  979           }
  980       }
  981       catch  (err) {
  982           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_cptC ode_respon se): ' + e rr.message );
  983       }
  984   }
  985  
  986   function v cmn_ribbon ButtonSave () {
  987       try {
  988           // Save the c urrent CRM  data
  989           Xr m.Page.dat a.entity.s ave();
  990       }
  991       catch  (err) {
  992           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa ve): ' + e rr.message );
  993       }
  994   }
  995  
  996   function v cmn_getCoo kie(cname)  {
  997       try {
  998           va r name = c name + "=" ;
  999           va r ca = doc ument.cook ie.split(' ;');
  1000           fo r (var i =  0; i < ca .length; i ++) {
  1001                var c =  ca[i];
  1002                while (c .charAt(0)  == ' ') {
  1003                    c =  c.substrin g(1);
  1004                }
  1005                if (c.in dexOf(name ) == 0) {
  1006                    retu rn c.subst ring(name. length, c. length);
  1007                }
  1008           }
  1009           re turn "";
  1010       }
  1011       catch  (err) {
  1012           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getC ookie): '  + err.mess age);
  1013       }
  1014   }
  1015  
  1016   function v cmn_wordWr ap(str, in tWidth, st rBreak, cu t) {
  1017       try {
  1018           // Takes a st ring that  exceeds a  set length  and inser ts word wr ap
  1019           va r m = ((ar guments.le ngth >= 2)  ? argumen ts[1] : 75 )
  1020           va r b = ((ar guments.le ngth >= 3)  ? argumen ts[2] : '\ n')
  1021           va r c = ((ar guments.le ngth >= 4)  ? argumen ts[3] : fa lse)
  1022  
  1023           va r i, j, l,  s, r
  1024  
  1025           st r += ''
  1026  
  1027           if  (m < 1) {
  1028                return s tr
  1029           }
  1030  
  1031           fo r (i = -1,  l = (r =  str.split( /\r\n|\n|\ r/)).lengt h; ++i < l ; r[i] +=  s) {
  1032                for (s =  r[i], r[i ] = '';
  1033                  s.leng th > m;
  1034                  r[i] + = s.slice( 0, j) + (( s = s.slic e(j)).leng th ? b : ' ')) {
  1035                    j =  c === 2 ||  (j = s.sl ice(0, m +  1).match( /\S*(\s)?$ /))[1]
  1036                      ?  m
  1037                      :  j.input.le ngth - j[0 ].length | | c === tr ue && m ||
  1038                         j.input.le ngth + (j  = s.slice( m).match(/ ^\S*/))[0] .length
  1039                }
  1040           }
  1041  
  1042           re turn r.joi n('\n')
  1043       }
  1044       catch  (err) {
  1045           al ert('Progr ess Note R ibbon Func tion Error (vcmn_word Wrap): ' +  err.messa ge);
  1046       }
  1047   }
  1048  
  1049   function v cmn_ribbon ButtonSave ToVistA()  {
  1050       try {
  1051           // Check the  value of t he Integra tion Statu s Field, i f = 'OK',  stop and e xit this s cript
  1052           va r vcmn_int egrationSt atus = Xrm .Page.getA ttribute(' ftp_integr ationstatu s').getVal ue();
  1053           if  (vcmn_int egrationSt atus == 'O K') { retu rn false;  }
  1054  
  1055           // Prompt use r to sign  the note
  1056           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  1057           va r vcmn_sig nThisNoteF ailure = f alse;
  1058           if  (vcmn_sig nThisNote  == null) {
  1059                Xrm.Util ity.confir mDialog(
  1060                    "Do  you need t o sign thi s note?, S elect OK i f Yes, oth erwise CAN CEL.",
  1061                    func tion () {
  1062                         //Check if  VIA Login  cookie ex ist (not e xpired)
  1063                         var vcmn_V iaLoginCoo kie = vcmn _getCookie ("viasessi onlink");
  1064                         //Prompt u ser to log in to VIA
  1065                         if (vcmn_V iaLoginCoo kie == "")  {
  1066                             alert( "Your VIST A session  has expire d. In orde r to sign  this note,  you must  be logged  into VISTA !");
  1067                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setVisi ble(false) ;
  1068                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setFocu s();
  1069                             vcmn_s ignThisNot eFailure =  true;
  1070                             return ;
  1071                         }
  1072                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000001 );
  1073                    },
  1074                    func tion () {
  1075                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000000 );
  1076                    }
  1077                );
  1078                Xrm.Page .getAttrib ute('ftp_s ignthisnot e').setSub mitMode('a lways');
  1079           }
  1080  
  1081           // Check for  additional  signers,  if they ex ist, the u ser must b e logged i nto VIA to  continue  process.
  1082           // Additional  Signature s must als o be in sy nc with ma tching Ses sion varia bles
  1083  
  1084           vc mn_AddlSig nersNameAr ray = null ;
  1085           vc mn_AddlSig nersIenArr ay = null;
  1086  
  1087           va r vcmn_sel ectedSigne rs = Xrm.P age.getAtt ribute('ft p_selected signers'). getValue() ;
  1088           if  (vcmn_sel ectedSigne rs != null  && vcmn_s electedSig ners != '' ) {
  1089                //Additi onal Signe rs exist i n CRM, ver ify sessio n variable s
  1090                var vcmn _selectedA rray = vcm n_selected Signers.sp lit('~~~') ;
  1091                var vcmn _selectedA rrayRecord Count = vc mn_selecte dArray.len gth;
  1092                if (vcmn _selectedA rrayRecord Count > 1)  {
  1093                    vcmn _AddlSigne rsNameArra y = vcmn_s electedArr ay;
  1094                }
  1095  
  1096                var vcmn _selectedI ENArray =  '';
  1097                var vcmn _selectedI ENArrayRec ordCount =  0;
  1098                var vcmn _progressN oteId = Xr m.Page.dat a.entity.g etId();
  1099  
  1100                var vcmn _arrayMism atch = fal se;
  1101  
  1102                //Get No te's Brows er Local S torage Val ues
  1103                if (vcmn _progressN oteId != n ull && vcm n_progress NoteId !=  '') {
  1104                    vcmn _localStor ageVarName  = "PN" +  vcmn_progr essNoteId;
  1105                    var  vcmn_local StorageStr ingValue =  localStor age.getIte m(vcmn_loc alStorageV arName);
  1106                    if ( vcmn_local StorageStr ingValue ! = null &&  vcmn_local StorageStr ingValue ! = '') {
  1107                         vcmn_selec tedIENArra y = vcmn_l ocalStorag eStringVal ue.split(' ~~~');
  1108                         vcmn_selec tedIENArra yRecordCou nt = vcmn_ selectedIE NArray.len gth;
  1109                         if (vcmn_s electedIEN ArrayRecor dCount > 1 ) {
  1110                             vcmn_A ddlSigners IenArray =  vcmn_sele ctedIENArr ay;
  1111                         }
  1112                    }
  1113                }
  1114                //Compar e CRM sign er array l ength with  LocalStor age array  length
  1115                if (vcmn _selectedA rrayRecord Count != v cmn_select edIENArray RecordCoun t) { vcmn_ arrayMisma tch = true ; }
  1116  
  1117                if (vcmn _arrayMism atch == tr ue) {
  1118                    aler t("The cou nt of Addi tional Sig ners selec ted in CRM , does not  match the  count of  Additional  Signers i n VISTA!\n \nPlease r emove all  the additi onal signe rs on this  Progress  Note and p erform the  selection  process a gain!\n\nT his note c annot be i ntegrated  with VISTA /CPRS unti l this has  been reso lved.");
  1119                    vcmn _signThisN oteFailure  = true;
  1120                }
  1121                else {
  1122                    //Ch eck if VIA  Login coo kie exist  (not expir ed)
  1123                    var  vcmn_ViaLo ginCookie  = vcmn_get Cookie("vi asessionli nk");
  1124                    if ( vcmn_ViaLo ginCookie  == "") {
  1125                         alert("You r VISTA se ssion has  expired. I n order to  process a  note with  additiona l signers,  you must  be logged  into VISTA !");
  1126                         Xrm.Page.u i.tabs.get ('Tab_Vist ALogin').s etVisible( false);
  1127                         Xrm.Page.u i.tabs.get ('Tab_Vist ALogin').s etFocus();
  1128                         vcmn_signT hisNoteFai lure = tru e;
  1129                         return;
  1130                    }
  1131                }             
  1132           }
  1133  
  1134           if  (vcmn_sig nThisNoteF ailure ==  true) {
  1135                //****** Developer  Bypass for  no VISTA  authentica tion******
  1136                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}") {
  1137                    aler t("Develop er VISTA a uthenticat ion bypass  applied!" );
  1138                    Xrm. Page.getAt tribute('f tp_signthi snote').se tValue(100 000001);
  1139                    Xrm. Page.getAt tribute('f tp_signthi snote').se tSubmitMod e('always' );
  1140                }
  1141                else {
  1142                    retu rn false;
  1143                }
  1144           }
  1145  
  1146           // Save the c urrent CRM  data
  1147           Xr m.Page.dat a.entity.s ave();
  1148           // Display YE LLOW Progr ess....
  1149           Xr m.Page.ui. setFormNot ification( "Verifying  progress  note data,  please wa it..", "IN FO", "SAVE VISTA");
  1150  
  1151           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!');
  1152           if  (vcmn_con firmSaveTo Vista == f alse) {
  1153                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1154                return f alse;
  1155           }
  1156           // Get regard ing data
  1157           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1158           if  (vcmn_req uestId ==  null) {
  1159                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 !');
  1160                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  1161                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1162                return f alse;
  1163           }
  1164           // Verify tha t the rega rdingid is  of type ' incident'
  1165           if  (vcmn_req uestId[0]. entityType  != 'incid ent') {
  1166                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!') ;
  1167                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  1168                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1169                return f alse;
  1170           }
  1171  
  1172           // Preserved  Variables
  1173           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1174           va r vcmn_vet eranFirstN ame = '';
  1175           va r vcmn_vet eranLastNa me = '';
  1176           va r vcmn_SSN  = '';
  1177           va r vcmn_DOB  = '';
  1178  
  1179           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1180           if  (vcmn_req uestData ! = null) {
  1181                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1182                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1183                    //Ve rify that  the custom erid is of  type cont act
  1184                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1185                         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!') ;
  1186                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1187                         return fal se;
  1188                    }
  1189                }
  1190           }
  1191           if  (vcmn_vet eranId ==  null) {
  1192                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  1193                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1194                return f alse;
  1195           }
  1196  
  1197           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);
  1198           if  (vcmn_con tactData ! = null) {
  1199                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1200                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1201                if (vcmn _contactDa ta.d.ftp_D ateofBirth  != null)  { vcmn_DOB  = vcmn_co ntactData. d.ftp_Date ofBirth; }
  1202                if (vcmn _contactDa ta.d.Gover nmentId !=  null) { v cmn_SSN =  vcmn_conta ctData.d.G overnmentI d; }
  1203           }
  1204  
  1205           // Perform MV I Search
  1206           vc mn_unatten dedMviSear ch(vcmn_ve teranFirst Name, vcmn _veteranLa stName, vc mn_DOB, vc mn_SSN);
  1207       }
  1208       catch  (err) {
  1209           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa veToVistA) : ' + err. message);
  1210           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1211       }
  1212   }
  1213  
  1214   function v cmn_ribbon ButtonSave ToVistA_wi th_ICN(vcm n_patientI CN) {
  1215       try {
  1216           // ******Deve loper Bypa ss for mis sing ICN** ****
  1217           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1218                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  1219                    aler t("Develop er ICN byp ass applie d!");
  1220                    vcmn _patientIC N = "12345 6V123456";
  1221                }
  1222           }
  1223  
  1224           // Verify Pat ient ICN
  1225           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1226                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! ');
  1227                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1228                return f alse;
  1229           }
  1230           
  1231           // Get regard ing data
  1232           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1233  
  1234           // Preserved  Variables
  1235           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1236           va r vcmn_vet eranName =  '';
  1237           va r vcmn_vet eranFirstN ame = '';
  1238           va r vcmn_vet eranLastNa me = '';
  1239           va r vcmn_vet eranMiddle Name = '';
  1240  
  1241           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1242           if  (vcmn_req uestData ! = null) {
  1243                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1244                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1245                    //Ve rify that  the custom erid is of  type cont act
  1246                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1247                         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!') ;
  1248                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1249                         return fal se;
  1250                    }
  1251                }
  1252           }
  1253           if  (vcmn_vet eranId ==  null) {
  1254                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  1255                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1256                return f alse;
  1257           }
  1258  
  1259           va r vcmn_con tactData =  vcmn_getS ingleEntit yDataSync( 'ContactSe t', 'FullN ame, First Name, Last Name, Midd leName', v cmn_vetera nId.Id);
  1260           if  (vcmn_con tactData ! = null) {
  1261                if (vcmn _contactDa ta.d.FullN ame != nul l) { vcmn_ veteranNam e = vcmn_c ontactData .d.FullNam e; }
  1262                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1263                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1264                if (vcmn _contactDa ta.d.Middl eName != n ull) { vcm n_veteranM iddleName  = vcmn_con tactData.d .MiddleNam e; }
  1265           }
  1266  
  1267           // Get user d ata
  1268           va r vcmn_crm UserId = X rm.Page.ge tAttribute ('ownerid' ).getValue ();
  1269           va r vcmn_use rDomainId  = '';
  1270           va r vcmn_use rFirstName  = '';
  1271           va r vcmn_use rLastName  = '';
  1272           va r vcmn_use rMiddleNam e = '';
  1273           va r vcmn_use rSiteId =  '';
  1274  
  1275           if  (vcmn_crm UserId !=  null) {
  1276                //Verify  the owner  type
  1277                if (vcmn _crmUserId [0].entity Type != 's ystemuser' ) {
  1278                    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 !');
  1279                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1280                    retu rn false;
  1281                }
  1282  
  1283                var vcmn _userData  = vcmn_get SingleEnti tyDataSync ('SystemUs erSet', 'D omainName,  FirstName , LastName , MiddleNa me, ftp_Fa cilitySite Id', vcmn_ crmUserId[ 0].id);
  1284                if (vcmn _userData  != null) {
  1285                    if ( vcmn_userD ata.d.Doma inName !=  null) { vc mn_userDom ainId = vc mn_userDat a.d.Domain Name; }
  1286                    if ( vcmn_userD ata.d.Firs tName != n ull) { vcm n_userFirs tName = vc mn_userDat a.d.FirstN ame; }
  1287                    if ( vcmn_userD ata.d.Last Name != nu ll) { vcmn _userLastN ame = vcmn _userData. d.LastName ; }
  1288                    if ( vcmn_userD ata.d.Midd leName !=  null) { vc mn_userMid dleName =  vcmn_userD ata.d.Midd leName; }
  1289                    if ( vcmn_userD ata.d.ftp_ FacilitySi teId != nu ll) { vcmn _userSiteI d = vcmn_u serData.d. ftp_Facili tySiteId.I d; }
  1290                }
  1291           }
  1292           el se {
  1293                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!');
  1294                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1295                return f alse;
  1296           }
  1297  
  1298           // Verify tha t the curr ent owner  and the cu rrent user  is the sa me person,  if not do  not proce ed
  1299           if  ((vcmn_cr mUserId[0] .id).toUpp erCase() ! = (Xrm.Pag e.context. getUserId( )).toUpper Case()) {
  1300                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!');
  1301                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1302                return f alse;
  1303           }
  1304           va r vcmn_Not eUserTeam  = "NONE";
  1305           // Check Team  membershi p
  1306           if  (vcmn_Use rHasTeam(" Pharmacy",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "PHARM ACY"; }
  1307           if  (vcmn_Use rHasTeam(" CCA Team",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "CCA";  }
  1308           if  (vcmn_Use rHasTeam(" TAN", Xrm. Page.conte xt.getUser Id())) { v cmn_NoteUs erTeam = " TAN"; }
  1309           // **TEMP, ve rify these  team valu es that th ey are cor rect **FUT URE NEED**
  1310           if  (vcmn_Use rHasTeam(" PACT User" , Xrm.Page .context.g etUserId() )) { vcmn_ NoteUserTe am = "PACT "; }
  1311           if  (vcmn_Use rHasTeam(" MSA User",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "MSA";  }
  1312  
  1313           // Verify Tea m Value, t hat one ha s been ass igned
  1314           if  (vcmn_Not eUserTeam  == "NONE")  {
  1315                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 !');
  1316                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1317                return f alse;
  1318           }
  1319  
  1320           // Get reques t form con tent
  1321           va r vcmn_not eDescripti on = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  1322           if  (vcmn_not eDescripti on == null  || vcmn_n oteDescrip tion == '' ) {
  1323                alert('T he note de scription  field is e mpty, the  note canno t be creat ed in Vist A/CPRS!');
  1324                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1325                return f alse;
  1326           }
  1327  
  1328           // Using new  hospital l ocation an d local no tes lookup  fields
  1329           va r vcmn_loc alTitle =  Xrm.Page.g etAttribut e('ftp_loc alnotetitl e').getVal ue();
  1330           if  (vcmn_loc alTitle ==  null) {
  1331                alert('T he local n ote title  field is e mpty, the  note canno t be creat ed in Vist A/CPRS!');
  1332                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1333                return f alse;
  1334           }
  1335           el se { vcmn_ localTitle  = vcmn_lo calTitle[0 ].name; }
  1336  
  1337           vc mn_patient AssignedLo cation = X rm.Page.ge tAttribute ('ftp_note hospitallo cation').g etValue();
  1338           if  (vcmn_pat ientAssign edLocation  == null)  {
  1339                alert('T he hospita l location  field is  empty, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  1340                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1341                return f alse;
  1342           }
  1343           el se { vcmn_ patientAss ignedLocat ion = vcmn _patientAs signedLoca tion[0].na me; }
  1344           
  1345           va r vcmn_cal lbackNumbe r = Xrm.Pa ge.getAttr ibute('ftp _callbackn umber').ge tValue();
  1346           if  (vcmn_cal lbackNumbe r == null  || vcmn_ca llbackNumb er == '')  {
  1347                alert('T he callbac k number f ield is em pty, the n ote cannot  be create d in VistA /CPRS!');
  1348                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1349                return f alse;
  1350           }
  1351           va r vcmn_rea sonForRequ est = Xrm. Page.getAt tribute('f tp_reasonf orrequest' ).getValue ();
  1352           if  (vcmn_rea sonForRequ est == nul l) {
  1353                alert('T he reason  for reques t field is  empty, th e note can not be cre ated in Vi stA/CPRS!' );
  1354                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1355                return f alse;
  1356           }
  1357  
  1358           va r vcmn_enc ounterCode  = 'NEW';
  1359  
  1360           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  1361           if  (vcmn_sig nThisNote  == 1000000 01) { vcmn _signThisN ote = true ; } else {  vcmn_sign ThisNote =  false; }
  1362           va r vcmn_cre atedDateTi me = Xrm.P age.getAtt ribute('sc heduledsta rt').getVa lue();
  1363  
  1364           // Get Progre ss Note Gu id/Id
  1365           va r vcmn_not eId = Xrm. Page.data. entity.get Id();
  1366  
  1367           // Get Create d On Date  & Convert  format
  1368           va r vcmn_cre atedOnDate  = vcmn_co nvertCrmDa teToVistAD ate(Xrm.Pa ge.getAttr ibute('cre atedon').g etValue()) ;
  1369           if  (vcmn_cre atedOnDate  == null)  {
  1370                alert('T he CRM cre atedon fie ld is empt y, the not e cannot b e created  in VistA/C PRS!');
  1371                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1372                return f alse;
  1373           }     
  1374  
  1375           // Get Patien t Admit Da te & Conve rt format
  1376           va r vcmn_pat ientAdmitD ate = vcmn _convertCr mDateToVis tADate(Xrm .Page.getA ttribute(' ftp_patien tadmitdate ').getValu e());
  1377  
  1378           if  (vcmn_pat ientAdmitD ate == nul l) {
  1379                alert('T he CRM pat ient admit  date fiel d is empty , the note  cannot be  created i n VistA/CP RS!');
  1380                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1381                return f alse;
  1382           }
  1383  
  1384           // Get Facili ty and loo kup facili ty number  and HL7 UR L
  1385           va r vcmn_fac ilityCode  = '';
  1386           va r vcmn_sit eHL7Listen erAddress  = '';
  1387           va r vcmn_pat ientFacili ty = Xrm.P age.getAtt ribute('ft p_patientf acility'). getValue() ;
  1388           if  (vcmn_pat ientFacili ty == null ) {
  1389                alert('T he CRM pat ient facil ity field  is empty,  the note c annot be c reated in  VistA/CPRS !');
  1390                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1391                return f alse;
  1392           }
  1393           el se {
  1394                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e, ftp_hl7 listener',  vcmn_pati entFacilit y[0].id);
  1395                if (vcmn _facilityD ata.d.ftp_ facilityco de != null ) {
  1396                    vcmn _facilityC ode = vcmn _facilityD ata.d.ftp_ facilityco de;
  1397                }
  1398                else {
  1399                    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!') ;
  1400                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1401                    retu rn false;
  1402                }
  1403  
  1404                if (vcmn _facilityD ata.d.ftp_ hl7listene r != null)  {
  1405                    var  vcmn_siteH L7Listener Address =  vcmn_facil ityData.d. ftp_hl7lis tener;
  1406                }
  1407                else {
  1408                    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!');
  1409                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1410                    retu rn false;
  1411                }
  1412           }
  1413  
  1414           va r vcmn_ori ginatorID  = '';
  1415           va r vcmn_use rSiteNo =  '';
  1416  
  1417           // Lookup the  Facility/ Site #
  1418           if  (vcmn_use rSiteId !=  null && v cmn_userSi teId != '' ) {
  1419                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e', vcmn_u serSiteId) ;
  1420                if (vcmn _facilityD ata != nul l) {
  1421                    if ( vcmn_facil ityData.d. ftp_facili tycode !=  null) { vc mn_userSit eNo = vcmn _facilityD ata.d.ftp_ facilityco de; }
  1422                }
  1423           }
  1424  
  1425           // Validate r equired Vi sta Lookup  info
  1426           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) {
  1427                //Abort  process, m issing inf o
  1428                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 !');
  1429                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1430                return f alse;
  1431           }
  1432  
  1433           // ***Tempora ry Test Us er Search* *******
  1434           if  (vcmn_IsP roductionE nvironment  == false)  {
  1435                //Provid e the opti on to sear ch for Lor i Nicholls , site# 61 3
  1436                var vcmn _impersona tePromptSt ring = "** THIS IS A  VISTA USER  SEARCH TE ST PROMPT* * \n" +
  1437                    "If  you would  like to im personate  the user:  \n" +
  1438                    "Lor i Nicholls  (613) \n"  +
  1439                    "Sel ect OK.  O therwise,  select CAN CEL.";
  1440                var vcmn _confirmIm personateV istaUser =  confirm(v cmn_impers onatePromp tString);
  1441                if (vcmn _confirmIm personateV istaUser = = true) {
  1442                    vcmn _userFirst Name = "Lo ri";
  1443                    vcmn _userLastN ame = "Nic holls";
  1444                    vcmn _userSiteN o = "613";
  1445                }
  1446           }
  1447           // ********** ********** ********** *******
  1448  
  1449           va r vcmn_vis tausersDat a = vcmn_g etVistaUse rsData(vcm n_userFirs tName, vcm n_userLast Name, vcmn _userSiteN o, false);
  1450  
  1451           // ********** ********** ********** *********
  1452           // Temporary  JSON TEST  DATA, comm ent out wh en not nee ded
  1453           /*
  1454           vc mn_vistaus ersData =  {
  1455                "ErrorOc curred": f alse,
  1456                "ErrorMe ssage": nu ll,
  1457                "Status" : null,
  1458                "DebugIn fo": null,
  1459                "Data":  [
  1460                         {
  1461                             "First Name": "LO RI",
  1462                             "Middl eName": "E ",
  1463                             "LastN ame": "NIC HOLLS",
  1464                             "Suffi x": "JR",
  1465                             "Displ ayName": " NICHOLLS,L ORI E JR",
  1466                             "Title ": "HDR Sr . Develope r"
  1467                          },
  1468                          {
  1469                              "Firs tName": "F IVE",
  1470                              "Midd leName": " ",
  1471                              "Last Name": "PR OVIDER",
  1472                              "Titl e": "Schol ar Extraor dinaire"
  1473                          },
  1474                          {
  1475                              "Firs tName": "F IVEHUNDRED ONE",
  1476                              "Midd leName": " ",
  1477                              "Last Name": "PR OVIDER",
  1478                              "Titl e": "Schol ar Extraor dinaire"
  1479                          },
  1480                          {
  1481                              "Firs tName": "F IVEHUNDRED TWO",
  1482                              "Midd leName": " ",
  1483                              "Last Name": "PR OVIDER",
  1484                              "Titl e": "Schol ar Extraor dinaire"
  1485                          }
  1486                ]
  1487           };
  1488           */
  1489           // ********** ********** ********** *********
  1490  
  1491           // Check vist a users da ta content
  1492           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)  {
  1493                //Abort  process, m issing inf o
  1494                alert('U nable to o btain Vist a User Dat a, the not e cannot b e created  in VistA/C PRS!');
  1495                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1496                return f alse;
  1497           }
  1498  
  1499           va r vcmn_sel ectedUserF irstName =  '';
  1500           va r vcmn_sel ectedUserM iddleName  = '';
  1501           va r vcmn_sel ectedUserL astName =  '';
  1502           va r vcmn_sel ectedUserS uffix = '' ;
  1503           va r vcmn_sel ectedUserD isplayName  = '';
  1504           va r vcmn_sel ectedUserT itle = '';
  1505           va r vcmn_use rIsSelecte d = false;
  1506  
  1507           if  (vcmn_vis tausersDat a.Data.len gth > 1) {
  1508                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!");
  1509                for (var  i = 0; i  <= vcmn_vi stausersDa ta.Data.le ngth - 1;  i++) {
  1510                    var  vcmn_curre ntUserFirs tName = '' ;
  1511                    var  vcmn_curre ntUserMidd leName = ' ';
  1512                    var  vcmn_curre ntUserLast Name = '';
  1513                    var  vcmn_curre ntUserSuff ix = '';
  1514                    var  vcmn_curre ntUserDisp layName =  '';
  1515                    var  vcmn_curre ntUserTitl e = '';
  1516                    if ( vcmn_vista usersData. Data[i].Fi rstName !=  null) { v cmn_curren tUserFirst Name = vcm n_vistause rsData.Dat a[i].First Name; }
  1517                    if ( vcmn_vista usersData. Data[i].Mi ddleName ! = null) {  vcmn_curre ntUserMidd leName = v cmn_vistau sersData.D ata[i].Mid dleName; }
  1518                    if ( vcmn_vista usersData. Data[i].La stName !=  null) { vc mn_current UserLastNa me = vcmn_ vistausers Data.Data[ i].LastNam e; }
  1519                    if ( vcmn_vista usersData. Data[i].Su ffix != nu ll) { vcmn _currentUs erSuffix =  vcmn_vist ausersData .Data[i].S uffix; }
  1520                    if ( vcmn_vista usersData. Data[i].Di splayName  != null) {  vcmn_curr entUserDis playName =  vcmn_vist ausersData .Data[i].D isplayName ; }
  1521                    if ( vcmn_vista usersData. Data[i].Ti tle != nul l) { vcmn_ currentUse rTitle = v cmn_vistau sersData.D ata[i].Tit le; }
  1522                    //Pr ompt user  about this  vista use r record
  1523                    var  vcmn_userP romptStrin g = "Click  OK, to se lect this  user.  Oth erwise CAN CEL \n" +
  1524                         "\n First  Name: " +  vcmn_curre ntUserFirs tName +
  1525                         "\n Middle  Name: " +  vcmn_curr entUserMid dleName +
  1526                         "\n Last N ame: " + v cmn_curren tUserLastN ame +
  1527                         "\n Suffix : " + vcmn _currentUs erSuffix +
  1528                         "\n Displa y Name: "  + vcmn_cur rentUserDi splayName  +
  1529                         "\n Title:  " + vcmn_ currentUse rTitle;
  1530  
  1531                    var  vcmn_confi rmSelectVi staUser =  confirm(vc mn_userPro mptString) ;
  1532                    if ( vcmn_confi rmSelectVi staUser ==  true) {
  1533                         vcmn_userI sSelected  = true;
  1534                         vcmn_selec tedUserFir stName = v cmn_curren tUserFirst Name;
  1535                         vcmn_selec tedUserMid dleName =  vcmn_curre ntUserMidd leName;
  1536                         vcmn_selec tedUserLas tName = vc mn_current UserLastNa me;
  1537                         vcmn_selec tedUserSuf fix = vcmn _currentUs erSuffix;
  1538                         vcmn_selec tedUserDis playName =  vcmn_curr entUserDis playName;
  1539                         vcmn_selec tedUserTit le = vcmn_ currentUse rTitle;
  1540                         break;
  1541                    }
  1542                }
  1543           }
  1544           el se {
  1545                //Select  data from  the first  record
  1546                vcmn_use rIsSelecte d = true;
  1547                if (vcmn _vistauser sData.Data [0].FirstN ame != nul l) { vcmn_ selectedUs erFirstNam e = vcmn_v istausersD ata.Data[0 ].FirstNam e; }
  1548                if (vcmn _vistauser sData.Data [0].Middle Name != nu ll) { vcmn _selectedU serMiddleN ame = vcmn _vistauser sData.Data [0].Middle Name; }
  1549                if (vcmn _vistauser sData.Data [0].LastNa me != null ) { vcmn_s electedUse rLastName  = vcmn_vis tausersDat a.Data[0]. LastName;  }
  1550                if (vcmn _vistauser sData.Data [0].Suffix  != null)  { vcmn_sel ectedUserS uffix = vc mn_vistaus ersData.Da ta[0].Suff ix; }
  1551                if (vcmn _vistauser sData.Data [0].Displa yName != n ull) { vcm n_selected UserDispla yName = vc mn_vistaus ersData.Da ta[0].Disp layName; }
  1552                if (vcmn _vistauser sData.Data [0].Title  != null) {  vcmn_sele ctedUserTi tle = vcmn _vistauser sData.Data [0].Title;  }
  1553           }
  1554  
  1555           // Check if a  user was  selected
  1556           if  (vcmn_use rIsSelecte d == false ) {
  1557                alert('A  user was  not select ed from th e previous  prompts,  the note c annot be c reated in  VistA/CPRS !');
  1558                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1559                return f alse;
  1560           }
  1561  
  1562           // Execute In tegration
  1563           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);
  1564  
  1565       }
  1566       catch  (err) {
  1567           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa veToVistA_ with_ICN):  ' + err.m essage);
  1568           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1569       }
  1570   }
  1571  
  1572   function v cmn_getVis taUsersDat a(vcmn_use rFirstName , vcmn_use rLastName,  vcmn_user SiteNo, vc mn_noFilte r) {
  1573       try {
  1574           va r vcmn_jso nData = nu ll;
  1575           $. ajax({
  1576                type: "G ET",
  1577                url: vcm n_VistaUse rsURLbase  + vcmn_use rFirstName  + "/" + v cmn_userLa stName + " /" + vcmn_ userSiteNo  + "?noFil ter=" + vc mn_noFilte r,
  1578                contentT ype: "appl ication/js on; charse t=utf-8",
  1579                dataType : "json",
  1580                success:  function  (data) {
  1581                    vcmn _jsonData  = data;
  1582                },
  1583                error: f unction (j qXHR, text Status, er rorThrown)  {
  1584                    //Sy stem Error
  1585                    vcmn _jsonData  = null;
  1586                },
  1587                async: f alse,
  1588                cache: f alse
  1589           }) ;
  1590           re turn vcmn_ jsonData;
  1591       }
  1592       catch  (err) {
  1593           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getV istaUsersD ata): ' +  err.messag e);
  1594           re turn null;
  1595       }
  1596   }
  1597  
  1598   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) {
  1599       try {
  1600           // Reformat N ote Descri ption as n eeded to h andle long  lines of  text (Word Wrap)
  1601           va r vcmn_Not eText = vc mn_noteDes cription;
  1602           va r vcmn_Rev isedNoteTe xt = "";
  1603           // Do Breakdo wn of line s
  1604           va r vcmn_Tex tLines = v cmn_NoteTe xt.split(' \n');
  1605           if  (vcmn_Tex tLines.len gth > 0) {
  1606                //Reform at text
  1607                for (var  i = 0; i  < vcmn_Tex tLines.len gth; i++)  {
  1608                    //Te st for a l ong line
  1609                    if ( vcmn_TextL ines[i].le ngth > vcm n_WordWrap Limit) {
  1610                         //Break do wn line
  1611                         var vcmn_N ewString =  vcmn_word Wrap(vcmn_ TextLines[ i], vcmn_W ordWrapLim it, '\n');
  1612                         //Add revi sed text b ack
  1613                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _NewString  + "\n";   //Add back  the CR/LF  used to s plit on
  1614                    }
  1615                    else  {
  1616                         //Add text  to new no te
  1617                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _TextLines [i] + "\n" ; //Add ba ck the CR/ LF used to  split on
  1618                    }
  1619                }
  1620           }
  1621           if  (vcmn_Rev isedNoteTe xt != "" & & vcmn_Rev isedNoteTe xt != null ) {
  1622                vcmn_not eDescripti on = vcmn_ RevisedNot eText;
  1623           }
  1624  
  1625           // Add list o f addition al signer  names to N ote Text i f they exi sts
  1626           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  1627                //Create  text stri ngs from a dditional  signers ar ray
  1628                var vcmn _SignerNam es = "\nAd ditional N ote Signer s\n"+"---- ---------- ---------- -----\n";
  1629                for (var  i = 0; i  <= vcmn_Ad dlSignersN ameArray.l ength - 1;  i++) {
  1630                    if ( i >= 1) {
  1631                         var vcmn_s ingleSigne rName = vc mn_AddlSig nersNameAr ray[i].spl it("___");
  1632                         vcmn_Signe rNames = v cmn_Signer Names + vc mn_singleS ignerName[ 1] + "\n";
  1633                    }
  1634                }
  1635                //Add to  Note Desc ription
  1636                vcmn_not eDescripti on = vcmn_ noteDescri ption + vc mn_SignerN ames;
  1637           }
  1638  
  1639           va r vcmn_vis itNumber =  'NEW';
  1640           va r vcmn_cli entName =  "FTPCRM";
  1641           va r vcmn_For mat = "JSO N";
  1642           va r vcmn_pat ientIdenti fierType =  "ICN";
  1643           va r vcmn_doc umentAvail abilitySta tus = "AV" ;  //Histo rical Note  only at t his time
  1644           va r vcmn_ori ginatorCom binedMiddl e = "";
  1645           if  (vcmn_ori ginatorMid dleName !=  '' && vcm n_originat orMiddleNa me != null ) { vcmn_o riginatorC ombinedMid dle = vcmn _originato rMiddleNam e; }
  1646           if  (vcmn_ori ginatorSuf fix != ''  && vcmn_or iginatorSu ffix != nu ll) {
  1647                if (vcmn _originato rCombinedM iddle != ' ') {
  1648                    vcmn _originato rCombinedM iddle = vc mn_origina torCombine dMiddle +  " " + vcmn _originato rSuffix;
  1649                }
  1650                else {
  1651                    vcmn _originato rCombinedM iddle = vc mn_origina torSuffix;
  1652                }
  1653           }
  1654  
  1655           va r vcmn_req uestJSON =  {
  1656                "ClientN ame": vcmn _clientNam e,
  1657                "Format" : vcmn_For mat,
  1658                "Facilit ySiteID":  vcmn_facil itySiteId,
  1659                "SiteHL7 ListenerAd dress": vc mn_siteHL7 ListenerAd dress,
  1660                "VisitNu mber": vcm n_visitNum ber,
  1661                "IsSigne dNote": vc mn_signThi sNote,
  1662                "Patient AdmitDate" : vcmn_pat ientAdmitD ate,
  1663                "Patient LastName":  vcmn_pati entLastNam e,
  1664                "Patient FirstName" : vcmn_pat ientFirstN ame,
  1665                "Patient Identifier ": vcmn_pa tientICN,
  1666                "Patient Identifier Type": vcm n_patientI dentifierT ype,
  1667                "Patient AssignedLo cation": v cmn_patien tAssignedL ocation,
  1668                "NoteTex t": vcmn_n oteDescrip tion,
  1669                "Origina torID": vc mn_origina torID,
  1670                "Origina torFirstNa me": vcmn_ originator FirstName,
  1671                "Origina torMiddleN ame": vcmn _originato rCombinedM iddle,
  1672                "Origina torLastNam e": vcmn_o riginatorL astName,
  1673                "Documen tFileName" : vcmn_loc alTitle,
  1674                "Documen tAvailabil ityStatus" : vcmn_doc umentAvail abilitySta tus,
  1675                "Activit yDate": vc mn_activit yDate
  1676           };
  1677  
  1678           va r vcmn_req uestRespon se = "";
  1679  
  1680           $. ajax({
  1681                type: "P OST",
  1682                url: vcm n_NoteWrit eUrl,
  1683                data: JS ON.stringi fy(vcmn_re questJSON) ,
  1684                contentT ype: "appl ication/js on; charse t=utf-8",
  1685                dataType : "json",
  1686                success:  function  (data) {
  1687                    var  vcmn_newda ta = data;
  1688                    vcmn _requestRe sponse = v cmn_newdat a;
  1689                    vcmn _vistAInte grationReq uest_respo nse(null,  vcmn_reque stResponse , vcmn_not eDescripti on);
  1690                },
  1691                error: f unction (j qXHR, text Status, er rorThrown)  {
  1692                    //Sy stem Error
  1693                    vcmn _vistAInte grationReq uest_respo nse(errorT hrown, nul l, vcmn_no teDescript ion);
  1694                },
  1695                async: f alse,
  1696                cache: f alse
  1697           }) ;
  1698       }
  1699       catch  (err) {
  1700           al ert('Progr ess Note R ibbon Func tion Error (vcmn_exec uteVistAIn tegrationR equest): '  + err.mes sage);
  1701           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1702       }
  1703   }
  1704  
  1705   function v cmn_vistAI ntegration Request_re sponse(vcm n_errorThr own, vcmn_ requestRes ponse, vcm n_noteDesc ription) {
  1706       try {
  1707           // Process In tegration  Request Re sponse
  1708           if  (vcmn_err orThrown ! = null) {
  1709                //Write  Error
  1710                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etValue('E RROR');
  1711                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etSubmitMo de('always ');
  1712                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tValue(Str ing(vcmn_e rrorThrown ));
  1713                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tSubmitMod e('always' );
  1714                Xrm.Page .getAttrib ute('ftp_i ntegration date').set Value(new  Date());
  1715                Xrm.Page .getAttrib ute('ftp_i ntegration date').set SubmitMode ('always') ;
  1716                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etValue('' );
  1717                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etSubmitMo de('always ');
  1718                alert('T he note cr eation in  VistA/CPRS  failed!\n Please see  the integ ration err or field f or details .');
  1719                Xrm.Page .getContro l('ftp_int egrationer ror').setF ocus();
  1720                Xrm.Page .data.enti ty.save();
  1721                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1722                return f alse;
  1723           }
  1724           el se {
  1725                //Write  web servic e response  Success o r Failure
  1726                if (vcmn _requestRe sponse.Err orOccurred  == false)  {
  1727                    //Ca ll Additio nal Signer s & Finali ze Note fu nction
  1728                    vcmn _finalizeN oteCreatio n(vcmn_req uestRespon se.Status,  vcmn_requ estRespons e.Data, vc mn_noteDes cription)
  1729                }
  1730                else {
  1731                    //Wr ite Failur e entry
  1732                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setValu e(vcmn_req uestRespon se.Status) ;
  1733                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setSubm itMode('al ways');
  1734                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setValue (vcmn_requ estRespons e.ErrorMes sage + "   DebugInfo: " + vcmn_r equestResp onse.Debug Info);
  1735                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setSubmi tMode('alw ays');
  1736                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setValue( new Date() );
  1737                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setSubmit Mode('alwa ys');
  1738                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setValu e('');
  1739                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setSubm itMode('al ways');
  1740                    aler t('The not e creation  in VistA/ CPRS faile d!\nPlease  see the i ntegration  error fie ld for det ails.');
  1741                    Xrm. Page.getCo ntrol('ftp _integrati onerror'). setFocus() ;
  1742                    Xrm. Page.data. entity.sav e();
  1743                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1744                    retu rn false;
  1745                }
  1746           }
  1747       }
  1748       catch  (err) {
  1749           al ert('Progr ess Note R ibbon Func tion Error (vcmn_vist AIntegrati onRequest_ response):  ' + err.m essage);
  1750           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1751       }
  1752   }
  1753  
  1754   function v cmn_finali zeNoteCrea tion(vcmn_ integratio nStatus, v cmn_integr ationNoteI d, vcmn_no teDescript ion) {
  1755       //The  Note was s ucessfully  created i n Vista/CP RS, add ad ditional s igners if  needed
  1756       try {
  1757           // Determine  if additio nal signer s exists
  1758           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  1759                //Get th e current  CRM User's  assigned  site/facil ity
  1760                var vcmn _userSiteI d = "";
  1761                var vcmn _UserSiteN o = "";
  1762                var vcmn _duz = "";
  1763                var vcmn _providern ame = "";
  1764  
  1765                var vcmn _userData  = vcmn_get SingleEnti tyDataSync ('SystemUs erSet', 'f tp_Facilit ySiteId',  Xrm.Page.c ontext.get UserId());
  1766                if (vcmn _userData  != null) {
  1767                    if ( vcmn_userD ata.d.ftp_ FacilitySi teId != nu ll) {
  1768                         vcmn_userS iteId = vc mn_userDat a.d.ftp_Fa cilitySite Id.Id;
  1769                    }
  1770                }
  1771  
  1772                //Lookup  the Facil ity/Site #
  1773                if (vcmn _userSiteI d != null  && vcmn_us erSiteId ! = '') {
  1774                    var  vcmn_facil ityData =  vcmn_getSi ngleEntity DataSync(' ftp_facili tySet', 'f tp_facilit ycode', vc mn_userSit eId);
  1775                    if ( vcmn_facil ityData !=  null) {
  1776                         if (vcmn_f acilityDat a.d.ftp_fa cilitycode  != null)  { vcmn_Use rSiteNo =  vcmn_facil ityData.d. ftp_facili tycode; }
  1777                    }
  1778                }
  1779  
  1780                //Check  if VIA Log in cookie  exist (not  expired)
  1781                var vcmn _ViaLoginC ookie = vc mn_getCook ie("viases sionlink") ;
  1782                if (vcmn _ViaLoginC ookie != n ull && vcm n_ViaLogin Cookie !=  '') {
  1783                    var  vcmn_cooki earray = v cmn_ViaLog inCookie.s plit("~~~~ ", 2);
  1784                    vcmn _duz = vcm n_cookiear ray[0];
  1785                    vcmn _providern ame = vcmn _cookiearr ay[1];
  1786                }
  1787  
  1788                //Create  text stri ngs from a dditional  signers ar ray
  1789                var vcmn _SignerIEN  = "";
  1790                for (var  i = 0; i  <= vcmn_Ad dlSignersI enArray.le ngth - 1;  i++) {
  1791                    if ( i == 1) {  vcmn_Signe rIEN = vcm n_AddlSign ersIenArra y[i]; }
  1792                    if ( i > 1) { v cmn_Signer IEN = vcmn _SignerIEN  + " " + v cmn_AddlSi gnersIenAr ray[i]; }
  1793                }
  1794  
  1795                //Create  the Addit ional Sign ers
  1796                var vcmn _viaSigner s = new Ob ject();
  1797                vcmn_via Signers.Pr oviderName  = vcmn_pr ovidername ;
  1798                vcmn_via Signers.Du z = vcmn_d uz;
  1799                vcmn_via Signers.Lo ginSiteCod e = vcmn_U serSiteNo;
  1800                vcmn_via Signers.Ta rget = vcm n_integrat ionNoteId;
  1801                vcmn_via Signers.Su pplemental Parameters  = vcmn_Si gnerIEN;
  1802  
  1803                $.ajax({
  1804                    type : "POST",
  1805                    url:  vcmn_AddS ignersUrl,
  1806                    data : JSON.str ingify(vcm n_viaSigne rs),
  1807                    cont entType: " applicatio n/json; ch arset=utf- 8",
  1808                    data Type: "jso n",
  1809                    succ ess: funct ion (data)  {
  1810                         vcmn_viaSi gnersRespo nse = JSON .stringify (data.Data );
  1811                         //Test for  Failure
  1812                         if (vcmn_v iaSignersR esponse.Er rorOccurre d == true)  {
  1813                             alert( "Error: Un able to ad d the addi tional sig ners selec ted to thi s note.\n\ nPlease re view the n ote and si gners in y our Vista/ CPRS appli cation!");
  1814                         }
  1815                    },
  1816                    erro r: functio n (jqXHR,  textStatus , errorThr own) {
  1817                         //System E rror
  1818                         alert("Err or: Unable  to add th e addition al signers  selected  to this no te.\n\nPle ase review  the note  and signer s in your  Vista/CPRS  applicati on!");
  1819                    },
  1820                    asyn c: false,
  1821                    cach e: false
  1822                });
  1823  
  1824                if (vcmn _localStor ageVarName  != "" &&  vcmn_local StorageVar Name != nu ll) {
  1825                    //Cl ear existi ng session  storage v ariable.
  1826                    loca lStorage.r emoveItem( vcmn_local StorageVar Name);  
  1827                }
  1828           }
  1829  
  1830           // Perform st andard for m updates  to signify  completio n
  1831           // Write Succ ess entry
  1832           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_noteDesc ription);
  1833           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  1834           Xr m.Page.get Attribute( 'ftp_integ rationstat us').setVa lue(vcmn_i ntegration Status);
  1835           Xr m.Page.get Attribute( 'ftp_integ rationstat us').setSu bmitMode(' always');
  1836           Xr m.Page.get Attribute( 'ftp_integ rationerro r').setVal ue(null);
  1837           Xr m.Page.get Attribute( 'ftp_integ rationerro r').setSub mitMode('a lways');
  1838           Xr m.Page.get Attribute( 'ftp_integ rationdate ').setValu e(new Date ());
  1839           Xr m.Page.get Attribute( 'ftp_integ rationdate ').setSubm itMode('al ways');
  1840           Xr m.Page.get Attribute( 'ftp_integ rationnote id').setVa lue(vcmn_i ntegration NoteId);
  1841           Xr m.Page.get Attribute( 'ftp_integ rationnote id').setSu bmitMode(' always');
  1842           Xr m.Page.get Control('f tp_integra tionstatus ').setFocu s();
  1843           al ert('The n ote creati on in Vist A/CPRS was  successfu l, this no te will no w be marke d as compl eted. \n\n Please exi t this not e record a fter click ing OK to  this promp t!');
  1844           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1845           Xr m.Page.dat a.entity.s ave();
  1846       }
  1847       catch  (err) {
  1848           al ert('Progr ess Note R ibbon Func tion Error (vcmn_fina lizeNoteCr eation): '  + err.mes sage);
  1849           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1850       }
  1851   }
  1852  
  1853   function v cmn_getCoo kie(cname)  {
  1854       try {
  1855           va r name = c name + "=" ;
  1856           va r ca = doc ument.cook ie.split(' ;');
  1857           fo r (var i =  0; i < ca .length; i ++) {
  1858                var c =  ca[i];
  1859                while (c .charAt(0)  == ' ') {
  1860                    c =  c.substrin g(1);
  1861                }
  1862                if (c.in dexOf(name ) == 0) {
  1863                    retu rn c.subst ring(name. length, c. length);
  1864                }
  1865           }
  1866           re turn "";
  1867       }
  1868       catch  (err) {
  1869           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getC ookie): '  + err.mess age);
  1870       }
  1871   }
  1872  
  1873   function v cmn_initVi aDropdownC ontrols()  {
  1874       //Init ialize VIA  DropDown  Controls
  1875       //Func tion is tr iggered by  The VistA  Login Con trol and o nchange of  Facility  attribute
  1876       try {
  1877           Xr m.Page.get Control("W ebResource _HospitalL ocation"). setSrc(Xrm .Page.getC ontrol("We bResource_ HospitalLo cation").g etSrc());
  1878           Xr m.Page.get Control("W ebResource _LocalNote sTitle").s etSrc(Xrm. Page.getCo ntrol("Web Resource_L ocalNotesT itle").get Src());
  1879       }
  1880       catch  (err) {
  1881           al ert('Progr ess Note V IA Login F unction Er ror(vcmn_i nitViaDrop downContro ls): ' + e rr.message );
  1882       }
  1883   }
  1884  
  1885   function v cmn_facili tyGroupDef ault_respo nse(vcmn_f acilityGro upData, vc mn_lastSki p, vcmn_fa cilitySite Id) {
  1886       try {
  1887           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  1888           fo r (var i =  0; i <= v cmn_facili tyGroupDat a.d.result s.length -  1; i++) {
  1889                //Get Va lues and W rite to Pr ogress Not e
  1890                if (vcmn _facilityG roupData.d .results[i ].ftp_loca lnotestitl e != null)  {
  1891                    Xrm. Page.getAt tribute("f tp_localno testitle") .setValue( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ localnotes title);
  1892                    Xrm. Page.getAt tribute('f tp_localno testitle') .setSubmit Mode('alwa ys');
  1893                }
  1894                if (vcmn _facilityG roupData.d .results[i ].ftp_hosp itallocati on != null ) {
  1895                    Xrm. Page.getAt tribute("f tp_hospita llocation" ).setValue (vcmn_faci lityGroupD ata.d.resu lts[i].ftp _hospitall ocation);
  1896                    Xrm. Page.getAt tribute('f tp_hospita llocation' ).setSubmi tMode('alw ays');
  1897                }
  1898                break;
  1899           }
  1900       }
  1901       catch  (err) {
  1902           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_faci lityGroupD efault_res ponse): '  + err.mess age);
  1903       }
  1904   }
  1905  
  1906  
  1907   function v cmn_buildQ ueryFilter (field, va lue, and)  {
  1908       try {
  1909           if  (value ==  '') {
  1910                if (and)  {
  1911                    retu rn " and "  + field +  " eq null ";
  1912                } else {
  1913                    retu rn field +  " eq null ";
  1914                }
  1915           }
  1916           el se {
  1917                if (and)  {
  1918                    retu rn " and "  + field +  " eq '" +  value + " '";
  1919                } else {
  1920                    retu rn field +  " eq '" +  value + " '";
  1921                }
  1922           }
  1923       }
  1924       catch  (err) {
  1925           al ert('Progr ess Note R ibbon Func tion Error (vcmn_buil dQueryFilt er): ' + e rr.message );
  1926           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1927       }
  1928   }
  1929  
  1930   function v cmn_unatte ndedMviSea rch(firstn ame, lastn ame, dobda te, ssn) {
  1931       try {
  1932           va r filter =  "";
  1933           va r filterPr efix = "$s elect=*&$f ilter=";
  1934           va r edipi =  "";
  1935           va r dobstrin g = "";
  1936           if  (dobdate  != null) {
  1937                dobstrin g = dobdat e;
  1938           }
  1939  
  1940           if  (ssn != " " && ssn ! = null) {
  1941                ssn = ss n.replace( /-/g, "");
  1942           }
  1943  
  1944           // if we have  edipi, se arch using  just it
  1945           if  (edipi !=  "") {
  1946                filter =  vcmn_buil dQueryFilt er("crme_E DIPI", edi pi, false) ;
  1947                filter + = vcmn_bui ldQueryFil ter("crme_ ClassCode" , 'MIL', t rue);
  1948                filter + = vcmn_bui ldQueryFil ter("crme_ SearchType ", 'Search ByIdentifi er', true) ;
  1949  
  1950                //set se arch type  as unatten ded
  1951                filter + = " and cr me_IsAtten ded eq fal se";
  1952           }
  1953           el se {
  1954                //otherw ise search  using las tname, fir stname, ss n, dob
  1955                filter =  vcmn_buil dQueryFilt er("crme_L astName",  lastname,  false); // assuming l astname wi ll never b e blank
  1956  
  1957                if (firs tname != " " && first name != nu ll) {
  1958                    filt er += vcmn _buildQuer yFilter("c rme_FirstN ame", firs tname, tru e);
  1959                }
  1960  
  1961                if (ssn  != "" && s sn != null ) {
  1962                    filt er += vcmn _buildQuer yFilter("c rme_SSN",  ssn, true) ;
  1963                }
  1964  
  1965                if (dobs tring != " ") {
  1966                    filt er += " an d crme_DOB String eq  '" + dobst ring + "'" ;
  1967                }
  1968                filter + = vcmn_bui ldQueryFil ter("crme_ SearchType ", 'Search ByFilter',  true);
  1969  
  1970                //set se arch type  as attende d (for now )
  1971                filter + = " and cr me_IsAtten ded eq tru e";
  1972           }
  1973  
  1974           fi lter = enc odeURIComp onent(filt er);
  1975           fi lter = fil terPrefix  + filter;
  1976           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);
  1977       }
  1978       catch  (err) {
  1979           al ert('Progr ess Note R ibbon Func tion Error (vcmn_unat tendedMviS earch): '  + err.mess age);
  1980           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1981       }
  1982   }
  1983  
  1984   function v cmn_unatte ndedMviSea rchCallbac k(returnDa ta) {
  1985       try {
  1986           if  (returnDa ta != null  && return Data.lengt h >= 1) {
  1987                // check  for excep tions 1st
  1988                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."))  {
  1989                    //do  nothing,  pass empty  ICN
  1990                    vcmn _ribbonBut tonSaveToV istA_with_ ICN("");
  1991                }
  1992                else {
  1993                    var  patientMvi Identifier  = returnD ata[0].crm e_PatientM viIdentifi er == null  ? "" : re turnData[0 ].crme_Pat ientMviIde ntifier;
  1994                    if ( patientMvi Identifier  != "") {
  1995                         var idpart s = patien tMviIdenti fier.split ("^");
  1996  
  1997                         if (idpart s.length >  0) {
  1998                             var na tionalId =  idparts[0 ];
  1999                             _icn =  nationalI d;
  2000                             //Pass  on the IC N and cont inue valid ation
  2001                             vcmn_r ibbonButto nSaveToVis tA_with_IC N(_icn);
  2002                         }
  2003                    }
  2004                }
  2005           }
  2006           el se {
  2007                //Return  empty ICN
  2008                vcmn_rib bonButtonS aveToVistA _with_ICN( "");
  2009           }
  2010       }
  2011       catch  (err) {
  2012           al ert('Progr ess Note R ibbon Func tion Error (vcmn_unat tendedMviS earchCallb ack): ' +  err.messag e);
  2013           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2014       }
  2015   }
  2016  
  2017   function v cmn_unatte ndedMviSea rchComplet e() {
  2018       //do n othing
  2019   }
  2020  
  2021  
  2022   function v cmn_buildQ ueryFilter SCD(field,  value, an d) {
  2023       try {
  2024           if  (value ==  '') {
  2025                if (and)  {
  2026                    retu rn " and "  + field +  " eq null ";
  2027                } else {
  2028                    retu rn field +  " eq null ";
  2029                }
  2030           }
  2031           el se {
  2032                if (and)  {
  2033                    retu rn " and "  + field +  " eq '" +  value + " '";
  2034                } else {
  2035                    retu rn field +  " eq '" +  value + " '";
  2036                }
  2037           }
  2038       }
  2039       catch  (err) {
  2040           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_buil dQueryFilt erSCD): '  + err.mess age);
  2041           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2042       }
  2043   }
  2044  
  2045   function v cmn_unatte ndedMviSea rchSCD(fir stname, la stname, do bdate, ssn ) {
  2046       try {
  2047           va r filter =  "";
  2048           va r filterPr efix = "$s elect=*&$f ilter=";
  2049           va r edipi =  "";
  2050           va r dobstrin g = "";
  2051           if  (dobdate  != null) {
  2052                dobstrin g = dobdat e;
  2053           }
  2054  
  2055           if  (ssn != " " && ssn ! = null) {
  2056                ssn = ss n.replace( /-/g, "");
  2057           }
  2058  
  2059           // if we have  edipi, se arch using  just it
  2060           if  (edipi !=  "") {
  2061                filter =  vcmn_buil dQueryFilt erSCD("crm e_EDIPI",  edipi, fal se);
  2062                filter + = vcmn_bui ldQueryFil terSCD("cr me_ClassCo de", 'MIL' , true);
  2063                filter + = vcmn_bui ldQueryFil terSCD("cr me_SearchT ype", 'Sea rchByIdent ifier', tr ue);
  2064  
  2065                //set se arch type  as unatten ded
  2066                filter + = " and cr me_IsAtten ded eq fal se";
  2067           }
  2068           el se {
  2069                //otherw ise search  using las tname, fir stname, ss n, dob
  2070                filter =  vcmn_buil dQueryFilt erSCD("crm e_LastName ", lastnam e, false);  //assumin g lastname  will neve r be blank
  2071  
  2072                if (firs tname != " " && first name != nu ll) {
  2073                    filt er += vcmn _buildQuer yFilterSCD ("crme_Fir stName", f irstname,  true);
  2074                }
  2075  
  2076                if (ssn  != "" && s sn != null ) {
  2077                    filt er += vcmn _buildQuer yFilterSCD ("crme_SSN ", ssn, tr ue);
  2078                }
  2079  
  2080                if (dobs tring != " ") {
  2081                    filt er += " an d crme_DOB String eq  '" + dobst ring + "'" ;
  2082                }
  2083                filter + = vcmn_bui ldQueryFil terSCD("cr me_SearchT ype", 'Sea rchByFilte r', true);
  2084  
  2085                //set se arch type  as attende d (for now )
  2086                filter + = " and cr me_IsAtten ded eq tru e";
  2087           }
  2088  
  2089           fi lter = enc odeURIComp onent(filt er);
  2090           fi lter = fil terPrefix  + filter;
  2091           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) ;
  2092       }
  2093       catch  (err) {
  2094           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_unat tendedMviS earchSCD):  ' + err.m essage);
  2095       }
  2096   }
  2097  
  2098   function v cmn_unatte ndedMviSea rchCallbac kSCD(retur nData) {
  2099       try {
  2100           if  (returnDa ta != null  && return Data.lengt h >= 1) {
  2101                // check  for excep tions 1st
  2102                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."))  {
  2103                    //do  nothing,  pass empty  ICN
  2104                    vcmn _getServic eConnected Disabiliti es("");
  2105                }
  2106                else {
  2107                    var  patientMvi Identifier  = returnD ata[0].crm e_PatientM viIdentifi er == null  ? "" : re turnData[0 ].crme_Pat ientMviIde ntifier;
  2108                    if ( patientMvi Identifier  != "") {
  2109                         var idpart s = patien tMviIdenti fier.split ("^");
  2110  
  2111                         if (idpart s.length >  0) {
  2112                             var na tionalId =  idparts[0 ];
  2113                             _icn =  nationalI d;
  2114                             //Pass  on the IC N and cont inue with  SCD
  2115                             vcmn_g etServiceC onnectedDi sabilities (_icn);
  2116                         }
  2117                    }
  2118                }
  2119           }
  2120           el se {
  2121                //Return  empty ICN
  2122                vcmn_get ServiceCon nectedDisa bilities(" ");
  2123           }
  2124       }
  2125       catch  (err) {
  2126           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_unat tendedMviS earchCallb ackSCD): '  + err.mes sage);
  2127       }
  2128   }
  2129  
  2130   //Standalo ne form lo ad functio n
  2131   function v cmn_secure ProgressNo te() {
  2132       try {
  2133           // Disable al l form att ributes if  form is o pened by a  user who  does not o wn the pro gress note
  2134           // Only handl e forms in  create st ate
  2135           if  (Xrm.Page .ui.getFor mType() !=  2) { retu rn false;  } //2 = CR M Update S tatus
  2136           // Get the cu rrent owne r of the r ecord and  compare to  the curre nt user
  2137           va r vcmn_rec ordOwnerId  = Xrm.Pag e.getAttri bute('owne rid').getV alue();
  2138           // Verify tha t the curr ent owner  and the cu rrent user  is the sa me person,  if not lo ck down th e form
  2139           if  ((vcmn_re cordOwnerI d[0].id).t oUpperCase () != (Xrm .Page.cont ext.getUse rId()).toU pperCase() ) {
  2140                Xrm.Page .data.enti ty.attribu tes.forEac h(function  (attribut e, index)  {
  2141                    var  control =  Xrm.Page.g etControl( attribute. getName()) ;
  2142                    if ( control) {
  2143                         control.se tDisabled( true)
  2144                    }
  2145                });
  2146           }
  2147       }
  2148       catch  (err) {
  2149           al ert('Progr ess Note F orm Load F unction Er ror(vcmn_s ecureProgr essNote):  ' + err.me ssage);
  2150       }
  2151   }
  2152  
  2153  
  2154   function v cmn_execut eCrmOdataG etRequest( vcmn_jsonQ uery, vcmn _aSync, vc mn_aSyncCa llback, vc mn_skipCou nt, vcmn_o ptionArray ) {
  2155       //This  function  executes a  CRM Odata  web servi ce call to  retrieve  Crm data
  2156       //*vcm n_jsonQuer y* - a pro perly form atted CRM  Odata Quer y string ( required)
  2157       //*vcm n_aSync* -  specify ' true' to e xecute asy nchronousl y otherwis e 'false'  (required)
  2158       //*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 '')
  2159       //*vcm n_skipCoun t* - Initi al setting  is always  '0', incr ements by  50 per CRM  SDK Odata  standards  (required )
  2160       //*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)
  2161       try {
  2162           va r vcmn_ent ityData =  null;
  2163           $. ajax({
  2164                type: 'G ET',
  2165                contentT ype: 'appl ication/js on; charse t=utf-8',
  2166                datatype : 'json',
  2167                url: vcm n_jsonQuer y,
  2168                beforeSe nd: functi on (XMLHtt pRequest)  {
  2169                    XMLH ttpRequest .setReques tHeader('A ccept', 'a pplication /json');
  2170                },
  2171                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  2172                    vcmn _entityDat a = data;
  2173                    if ( vcmn_aSync  == true)  {
  2174                         vcmn_aSync Callback(v cmn_entity Data, vcmn _skipCount , vcmn_opt ionArray);
  2175                    }
  2176                },
  2177                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  2178                    aler t('Fail: A jax Error  in vcmn_ex ecuteCrmOd ataGetRequ est: ' + e rrorThrown  + " Reque st: " + vc mn_jsonQue ry);
  2179                },
  2180                async: v cmn_aSync,
  2181                cache: f alse
  2182           }) ;
  2183           re turn vcmn_ entityData ;
  2184       }
  2185       catch  (err) {
  2186           al ert('An er ror occure d in the v cmn_execut eCrmOdataG etRequest  function.   Error Det ail Messag e: ' + err );
  2187       }
  2188   }
  2189  
  2190   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) {
  2191       //This  function  returns a  CRM JSON d ataset for  all entit y records  matching c riteria pr ovided Asy ncronously
  2192       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  2193       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  2194       //*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
  2195       //*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'
  2196       //*vcm n_sortDire ction* - i s a string  specifyin g the sort  as Ascend ing or Des cending e. g. 'asc' o r 'desc'
  2197       //*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)
  2198       //*vcm n_aSyncCal lback* - i s the name  of the fu nction to  call when  returning  the result
  2199       //*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
  2200  
  2201       try {
  2202           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;
  2203           vc mn_execute CrmOdataGe tRequest(v cmn_jsonQu ery, true,  vcmn_aSyn cCallback,  vcmn_skip Count, vcm n_optionAr ray);
  2204       }
  2205       catch  (err) {
  2206           al ert('An er ror occure d in the v cmn_getMul tipleEntit yDataAsync  function.   Error De tail Messa ge: ' + er r);
  2207       }
  2208   }
  2209  
  2210   function v cmn_getSin gleEntityD ataSync(vc mn_entityS etName, vc mn_attribu teSet, vcm n_entityId ) {
  2211       //This  function  returns a  CRM JSON d ataset for  a single  entity rec ord based  on the ent ity id pro vided Sync ronously
  2212       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  2213       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  2214       //*vcm n_entityId * - is the  Guid for  the entity  record
  2215  
  2216       try {
  2217           va r vcmn_ent ityIdNoBra cket = vcm n_entityId .replace(/ ({|})/g, ' ');
  2218           va r vcmn_sel ectString  = '(guid'  + "'" + vc mn_entityI dNoBracket  + "'" + ' )?$select= ' + vcmn_a ttributeSe t;
  2219           va r vcmn_jso nQuery = v cmn_server Url + vcmn _crmOdataE ndPoint +  '/' + vcmn _entitySet Name + vcm n_selectSt ring;
  2220           va r vcmn_ent ityData =  vcmn_execu teCrmOdata GetRequest (vcmn_json Query, fal se, '', 0,  null);
  2221           re turn vcmn_ entityData ;
  2222       }
  2223       catch  (err) {
  2224           al ert('An er ror occure d in the v cmn_getSin gleEntityD ataSync fu nction.  E rror Detai l Message:  ' + err);
  2225       }
  2226   }
  2227  
  2228   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) {
  2229       //This  function  returns a  CRM JSON d ataset for  all entit y records  matching c riteria pr ovided Syn cronously
  2230       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  2231       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  2232       //*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
  2233       //*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'
  2234       //*vcm n_sortDire ction* - i s a string  specifyin g the sort  as Ascend ing or Des cending e. g. 'asc' o r 'desc'
  2235       //*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)
  2236  
  2237       try {
  2238           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;
  2239           va r vcmn_ent ityData =  vcmn_execu teCrmOdata GetRequest (vcmn_json Query, fal se, '', vc mn_skipCou nt, null);
  2240           re turn vcmn_ entityData ;
  2241       }
  2242       catch  (err) {
  2243           al ert('An er ror occure d in the v cmn_getMul tipleEntit yDataSync  function.   Error Det ail Messag e: ' + err );
  2244       }
  2245   }
  2246