87. EPMO Open Source Coordination Office Redaction File Detail Report

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

87.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_6.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Thu Mar 23 13:44:30 2017 UTC
2 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_6.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Thu Nov 30 17:21:05 2017 UTC

87.2 Comparison summary

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

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

87.4 Active regular expressions

No regular expressions were active.

87.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                //****** FIX DEFECT  481450 ** ****
  600                if (vcmn _requestDa ta.d.Descr iption !=  null && vc mn_request Data.d.Des cription ! = '' && vc mn_triagee xpert == ' YES') {
  601                    //Pr ompt user  to include  existing  Request No tes if the re is a cu rrent valu e
  602                    Xrm. Utility.co nfirmDialo g(
  603                         "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. ",
  604                         function ( ) {
  605                             //Get  the existi ng Triage  Note 
  606                             var vc mn_TriageN ote = Xrm. Page.getAt tribute('f tp_notedet ail').getV alue();
  607                             if (vc mn_TriageN ote != nul l) {
  608                                 Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_requestD ata.d.Desc ription +  "\n\n" + v cmn_Triage Note);
  609                             }
  610                             else {  Xrm.Page. getAttribu te('ftp_no tedetail') .setValue( vcmn_reque stData.d.D escription ); }
  611                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setSub mitMode('a lways');
  612                         }
  613                    );
  614                }
  615                //****** END FIX DE FECT 48145 0 ******
  616  
  617           }
  618  
  619           // 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)
  620           if  (vcmn_vet eranId !=  null) {
  621                var vcmn _contactDa ta = vcmn_ getSingleE ntityDataS ync('Conta ctSet', 'f tp_current facilityid , ftp_Faci lityId', v cmn_vetera nId);
  622                if (vcmn _contactDa ta != null ) {
  623                    if ( vcmn_conta ctData.d.f tp_current facilityid  != null)  {
  624                         if (vcmn_c ontactData .d.ftp_cur rentfacili tyid.Id !=  null) {
  625                             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);
  626                             Xrm.Pa ge.getAttr ibute('ftp _patientfa cility').s etSubmitMo de('always ');
  627                         }
  628                    else  {
  629                             //Get  Facility f rom Home F acility
  630                             if (vc mn_contact Data.d.ftp _FacilityI d != null)  {
  631                                 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 );
  632                                 Xr m.Page.get Attribute( 'ftp_patie ntfacility ').setSubm itMode('al ways');
  633                             }
  634                         }
  635                    }
  636                    else  {
  637                         //Get Faci lity from  Home Facil ity
  638                         if (vcmn_c ontactData .d.ftp_Fac ilityId !=  null) {
  639                             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);
  640                             Xrm.Pa ge.getAttr ibute('ftp _patientfa cility').s etSubmitMo de('always ');
  641                         }
  642                    }
  643                }
  644           }
  645  
  646           // Set other  default fo rm values
  647           Xr m.Page.get Attribute( 'scheduled end').setV alue(new D ate());
  648           Xr m.Page.get Attribute( 'scheduled end').setS ubmitMode( 'always');
  649  
  650           // Append Gen eric Templ ate Data t o top of e xisting no te
  651           va r vcmn_gen ericTempla teData = " Callback N umber: ";
  652           if  (Xrm.Page .getAttrib ute('ftp_c allbacknum ber').getV alue() !=  null && Xr m.Page.get Attribute( 'ftp_callb acknumber' ).getValue () != "")  {
  653                vcmn_gen ericTempla teData = v cmn_generi cTemplateD ata + Xrm. Page.getAt tribute('f tp_callbac knumber'). getValue() ;
  654           }
  655           // Construct  new note w ith existi ng note da ta
  656           va r vcmn_exi stingNoteD ata = "";
  657           if  (Xrm.Page .getAttrib ute("ftp_n otedetail" ).getValue () != null  && Xrm.Pa ge.getAttr ibute("ftp _notedetai l").getVal ue() != "" ) {
  658                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  659           }
  660           vc mn_generic TemplateDa ta = vcmn_ genericTem plateData  + "\n\n" +  vcmn_exis tingNoteDa ta;
  661           // Replace ex isting not e
  662           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_genericT emplateDat a);
  663           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  664  
  665           // Change Foc us to the  Notes fiel d
  666           Xr m.Page.get Control("f tp_notedet ail").setF ocus();      
  667  
  668           // Get ICN vi a web serv ice and ge t Service  Connected  disabiliti es thereaf ter
  669           // Preserved  Variables
  670           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  671           va r vcmn_vet eranFirstN ame = '';
  672           va r vcmn_vet eranLastNa me = '';
  673           va r vcmn_SSN  = '';
  674           va r vcmn_DOB  = '';
  675  
  676           // Get regard ing data
  677           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  678           if  (vcmn_req uestId ==  null) { re turn false ; }
  679           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  680  
  681           if  (vcmn_req uestData ! = null) {
  682                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  683                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  684                    //Ve rify that  the custom erid is of  type cont act
  685                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  686                         return fal se;
  687                    }
  688                }
  689           }
  690           if  (vcmn_vet eranId ==  null) {
  691                return f alse;
  692           }
  693  
  694           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);
  695           if  (vcmn_con tactData ! = null) {
  696                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  697                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  698                if (vcmn _contactDa ta.d.ftp_D ateofBirth  != null)  { vcmn_DOB  = vcmn_co ntactData. d.ftp_Date ofBirth; }
  699                if (vcmn _contactDa ta.d.Gover nmentId !=  null) { v cmn_SSN =  vcmn_conta ctData.d.G overnmentI d; }
  700           }
  701  
  702           // Perform MV I Search f or Service  Connected  Disabilit ies
  703           vc mn_unatten dedMviSear chSCD(vcmn _veteranFi rstName, v cmn_vetera nLastName,  vcmn_DOB,  vcmn_SSN) ;
  704       }
  705       catch  (err) {
  706           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_newP rogressNot eLoad_WebU RL): ' + e rr.message );
  707       }
  708   }
  709  
  710   function v cmn_getSer viceConnec tedDisabil ities(vcmn _patientIC N) {
  711       //**** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ***
  712       //Janu ary 16 201 7 - EXIT T HE FUNCTIO N, NOT USE D SEE BELO W
  713       return  false;
  714       //***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
  715       //**** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ***
  716       try {
  717           // ******Deve loper Bypa ss for mis sing ICN** ****
  718           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  719                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  720                    aler t("Develop er ICN byp ass applie d!");
  721                    vcmn _patientIC N = "12345 6V123456";
  722                }
  723           }
  724  
  725           // Verify Pat ient ICN
  726           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  727                //No ICN , do not p roceed
  728                return f alse;
  729           }
  730  
  731           // Get the se rvice conn ected disa bilities d ata from t he web ser vice
  732           va r vcmn_dis abilitiesX mlData = v cmn_getDis abilityDat a(vcmn_pat ientICN);
  733  
  734           // Temporary  action: xm l result i s empty, u se sample  data, comm ent out wh en not use d
  735           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********
  736           // if (vcmn_d isabilitie sXmlData = = null ||  vcmn_disab ilitiesXml Data == '' ) { vcmn_d isabilitie sXmlData =  xml_resul ts3; }
  737           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********
  738  
  739           // If no data , do not p roceed.
  740           if  (vcmn_dis abilitiesX mlData ==  null || vc mn_disabil itiesXmlDa ta == '')  { return f alse; }
  741  
  742           // Create bas e Note Str ing
  743           va r vcmn_SCD noteString  = '';
  744           vc mn_SCDnote String = v cmn_SCDnot eString +  "\n------- ---------- ---------- ---------- ---------- ---------- ---------- ------\n";
  745           vc mn_SCDnote String = v cmn_SCDnot eString +  "Special T reatment A uthority a nd Service  Connected  Disabilit ies";
  746           vc mn_SCDnote String = v cmn_SCDnot eString +  "\n------- ---------- ---------- ---------- ---------- ---------- ---------- ------\n";
  747  
  748           // Search XML  values
  749           vc mn_xmlDoc  = $.parseX ML(vcmn_di sabilities XmlData);
  750           $v cmn_xml =  $(vcmn_xml Doc);
  751  
  752           // Data from  parentnode  'enrollme ntDetermin ationInfo'  
  753           va r $vcmn_en rollmentDe terminatio nInfo = nu ll;
  754           va r $vcmn_pr imaryEligi bility = n ull;
  755           va r $vcmn_ty pe = null;
  756           va r vcmn_typ eText = nu ll;
  757           va r $vcmn_en rollmentCa tegoryName  = null;
  758           va r vcmn_enr ollmentCat egoryNameT ext = null ;
  759           va r $vcmn_sp ecialFacto rs = null;
  760           va r $vcmn_en vContamina ntsInd = n ull;
  761           va r vcmn_env Contaminan tsIndText  = null;
  762           va r $vcmn_ra diationExp osureInd =  null;
  763           va r vcmn_rad iationExpo sureIndTex t = null;
  764           va r $vcmn_ag entOrangeI nd = null;
  765           va r vcmn_age ntOrangeIn dText = nu ll;
  766           va r $vcmn_ca mpLejeuneI nd = null;
  767           va r vcmn_cam pLejeuneIn dText = nu ll;
  768           va r $vcmn_se rviceConne ctionAward  = null;
  769           va r $vcmn_se rviceConne ctedPercen tage = nul l;
  770           va r vcmn_ser viceConnec tedPercent ageText =  null;
  771           va r $vcmn_ra tedDisabil ities = nu ll;
  772  
  773           va r $vcmn_ag entOrangeL ocation =  null;
  774           va r vcmn_age ntOrangeLo cationText  = null;
  775           va r $vcmn_ra diationExp osureMetho d = null;
  776           va r vcmn_rad iationExpo sureMethod Text = nul l;
  777  
  778           va r $vcmn_no seThroatRa diumInfo =  null;
  779           va r $vcmn_di agnosedWit hCancer =  null;
  780           va r vcmn_dia gnosedWith CancerText  = null;
  781  
  782           va r $vcmn_mi litarySexu alTraumaIn fo = null;
  783           va r $vcmn_mi lSexTrauma Status = n ull;
  784           va r vcmn_mil SexTraumaS tatusText  = null;
  785  
  786           // Data from  parentnode  'military ServiceInf o' 
  787           va r $vcmn_mi litaryServ iceInfo =  null;
  788           va r $vcmn_co mbatVetera nEligibili tyEndDate  = null;
  789           va r vcmn_com batVeteran Eligibilit yEndDateTe xt = null;
  790           va r $vcmn_sh adIndicato r = null;
  791           va r vcmn_sha dIndicator Text = nul l;
  792  
  793           va r vcmn_rat edDisabili tyPercenta geTotal =  0;
  794  
  795           va r vcmn_det ailrowcoun t = 0;
  796  
  797           $v cmn_enroll mentDeterm inationInf o = $vcmn_ xml.find(' enrollment Determinat ionInfo');
  798           if  ($vcmn_en rollmentDe terminatio nInfo != n ull) {
  799                $vcmn_pr imaryEligi bility = $ vcmn_enrol lmentDeter minationIn fo.find('p rimaryElig ibility');
  800                if ($vcm n_primaryE ligibility  != null)  {
  801                    $vcm n_type = $ vcmn_prima ryEligibil ity.find(' type');
  802                    if ( $vcmn_type  != null)  { vcmn_typ eText = $v cmn_type.t ext(); }
  803                }
  804  
  805                $vcmn_en rollmentCa tegoryName  = $vcmn_e nrollmentD eterminati onInfo.fin d('enrollm entCategor yName');
  806                if ($vcm n_enrollme ntCategory Name != nu ll) { vcmn _enrollmen tCategoryN ameText =  $vcmn_enro llmentCate goryName.t ext(); }
  807  
  808                $vcmn_sp ecialFacto rs = $vcmn _enrollmen tDetermina tionInfo.f ind('speci alFactors' );
  809                if ($vcm n_specialF actors !=  null) {
  810                    $vcm n_envConta minantsInd  = $vcmn_s pecialFact ors.find(' envContami nantsInd') ;
  811                    if ( $vcmn_envC ontaminant sInd != nu ll) { vcmn _envContam inantsIndT ext = $vcm n_envConta minantsInd .text(); }
  812                    $vcm n_radiatio nExposureI nd = $vcmn _specialFa ctors.find ('radiatio nExposureI nd');
  813                    if ( $vcmn_radi ationExpos ureInd !=  null) { vc mn_radiati onExposure IndText =  $vcmn_radi ationExpos ureInd.tex t(); }
  814                    $vcm n_agentOra ngeInd = $ vcmn_speci alFactors. find('agen tOrangeInd ');
  815                    if ( $vcmn_agen tOrangeInd  != null)  { vcmn_age ntOrangeIn dText = $v cmn_agentO rangeInd.t ext(); }
  816                    $vcm n_campLeje uneInd = $ vcmn_speci alFactors. find('camp LejeuneInd ');
  817                    if ( $vcmn_camp LejeuneInd  != null)  { vcmn_cam pLejeuneIn dText = $v cmn_campLe jeuneInd.t ext(); }
  818  
  819                    $vcm n_agentOra ngeLocatio n = $vcmn_ specialFac tors.find( 'agentOran geLocation ');
  820                    if ( $vcmn_agen tOrangeLoc ation != n ull) { vcm n_agentOra ngeLocatio nText = $v cmn_agentO rangeLocat ion.text() ; }
  821                    $vcm n_radiatio nExposureM ethod = $v cmn_specia lFactors.f ind('radia tionExposu reMethod') ;
  822                    if ( $vcmn_radi ationExpos ureMethod  != null) {  vcmn_radi ationExpos ureMethodT ext = $vcm n_radiatio nExposureM ethod.text (); }
  823                }
  824  
  825                $vcmn_se rviceConne ctionAward  = $vcmn_e nrollmentD eterminati onInfo.fin d('service Connection Award');
  826                if ($vcm n_serviceC onnectionA ward != nu ll) {
  827                    $vcm n_serviceC onnectedPe rcentage =  $vcmn_ser viceConnec tionAward. find('serv iceConnect edPercenta ge');
  828                    if ( $vcmn_serv iceConnect edPercenta ge != null ) { vcmn_s erviceConn ectedPerce ntageText  = $vcmn_se rviceConne ctedPercen tage.text( ); }
  829                    $vcm n_ratedDis abilities  = $vcmn_se rviceConne ctionAward .find('rat edDisabili ties');
  830                    //Ge t each dis ability li sted and a dd to note  string
  831                    vcmn _SCDnoteSt ring = vcm n_SCDnoteS tring + "S C Disabili ty: ";
  832                    $vcm n_ratedDis abilities. find('rate dDisabilit y').each(f unction ()  {
  833                         var vcmn_r atedDisabi lityPercen t = 0;
  834                         var vcmn_d isability  = null;
  835                         if (Number ($(this).f ind('perce ntage').te xt()) > 0)  {
  836                             vcmn_r atedDisabi lityPercen tageTotal  = vcmn_rat edDisabili tyPercenta geTotal +  Number($(t his).find( 'percentag e').text() );
  837                             vcmn_r atedDisabi lityPercen t = Number ($(this).f ind('perce ntage').te xt());
  838                         }
  839                         //Add Rate d Disabili ties to th e Note Str ing if Dis ability Pe rcent > 0
  840                         if (vcmn_r atedDisabi lityPercen t > 0) {
  841                             vcmn_S CDnoteStri ng = vcmn_ SCDnoteStr ing + $(th is).find(' disability ').text()  + "\n";
  842                         }
  843                    });
  844                    vcmn _SCDnoteSt ring = vcm n_SCDnoteS tring + "\ n";
  845                }
  846  
  847                $vcmn_no seThroatRa diumInfo =  $vcmn_enr ollmentDet ermination Info.find( 'noseThroa tRadiumInf o');
  848                if ($vcm n_noseThro atRadiumIn fo != null ) {
  849                    $vcm n_diagnose dWithCance r = $vcmn_ noseThroat RadiumInfo .find('dia gnosedWith Cancer');
  850                    if ( $vcmn_diag nosedWithC ancer != n ull) { vcm n_diagnose dWithCance rText = $v cmn_diagno sedWithCan cer.text() ; }
  851                }
  852  
  853                $vcmn_mi litarySexu alTraumaIn fo = $vcmn _enrollmen tDetermina tionInfo.f ind('milit arySexualT raumaInfo' );
  854                if ($vcm n_military SexualTrau maInfo !=  null) {
  855                    $vcm n_milSexTr aumaStatus  = $vcmn_m ilitarySex ualTraumaI nfo.find(' status');
  856                    if ( $vcmn_milS exTraumaSt atus != nu ll) { vcmn _milSexTra umaStatusT ext = $vcm n_milSexTr aumaStatus .text(); }
  857                }
  858           }
  859  
  860           $v cmn_milita ryServiceI nfo = $vcm n_xml.find ('military ServiceInf o');
  861           if  ($vcmn_mi litaryServ iceInfo !=  null) {
  862                $vcmn_co mbatVetera nEligibili tyEndDate  = $vcmn_mi litaryServ iceInfo.fi nd('combat VeteranEli gibilityEn dDate');
  863                if ($vcm n_combatVe teranEligi bilityEndD ate != nul l) {
  864                    vcmn _combatVet eranEligib ilityEndDa teText = v cmn_combat VeteranEli gibilityEn dDateText  = $vcmn_co mbatVetera nEligibili tyEndDate. text();
  865                }
  866                $vcmn_sh adIndicato r = $vcmn_ militarySe rviceInfo. find('shad Indicator' );
  867                if ($vcm n_shadIndi cator != n ull) { vcm n_shadIndi catorText  = $vcmn_sh adIndicato r.text();  }
  868           }
  869  
  870           // If no elig ibility sp ecified, s et to fals e
  871           if  (vcmn_typ eText == n ull || vcm n_typeText  == '') {  vcmn_typeT ext = fals e; }
  872  
  873           // Change boo lean value s to false  if not ma rked true
  874           if  (vcmn_env Contaminan tsIndText  != 'true')  { vcmn_en vContamina ntsIndText  = false;  }
  875           if  (vcmn_rad iationExpo sureIndTex t != 'true ') { vcmn_ radiationE xposureInd Text = fal se; }
  876           if  (vcmn_age ntOrangeIn dText != ' true') { v cmn_agentO rangeIndTe xt = false ; }
  877           if  (vcmn_cam pLejeuneIn dText != ' true') { v cmn_campLe jeuneIndTe xt = false ; }
  878  
  879           if  (vcmn_dia gnosedWith CancerText  != 'true' ) { vcmn_d iagnosedWi thCancerTe xt = false ; }
  880           if  (vcmn_sha dIndicator Text != 't rue') { vc mn_shadInd icatorText  = false;  }
  881  
  882           // Change all  True/Fals e to Yes/N o
  883           if  (vcmn_typ eText == f alse) { vc mn_typeTex t = 'No';  }
  884  
  885           if  (vcmn_env Contaminan tsIndText  == "true")  { vcmn_en vContamina ntsIndText  = "Yes";  } else { v cmn_envCon taminantsI ndText = " No"; }
  886           if  (vcmn_rad iationExpo sureIndTex t == "true ") {
  887                vcmn_rad iationExpo sureIndTex t = "Yes";
  888                if (vcmn _radiation ExposureMe thodText ! = null) {  vcmn_radia tionExposu reIndText  = vcmn_rad iationExpo sureIndTex t + " - "  + vcmn_rad iationExpo sureMethod Text; }
  889           }  else {
  890                vcmn_rad iationExpo sureIndTex t = "No"; 
  891           }
  892           if  (vcmn_age ntOrangeIn dText == " true") {
  893                vcmn_age ntOrangeIn dText = "Y es";
  894                if (vcmn _agentOran geLocation Text != nu ll) { vcmn _agentOran geIndText  = vcmn_age ntOrangeIn dText + "  - " + vcmn _agentOran geLocation Text; }
  895           }
  896           el se {
  897                vcmn_age ntOrangeIn dText = "N o"; 
  898           }
  899           if  (vcmn_cam pLejeuneIn dText == " true") { v cmn_campLe jeuneIndTe xt = "Yes" ; } else {  vcmn_camp LejeuneInd Text = "No "; }
  900  
  901           if  (vcmn_dia gnosedWith CancerText  == "true" ) { vcmn_d iagnosedWi thCancerTe xt = "Yes" ; } else {  vcmn_diag nosedWithC ancerText  = "No"; }
  902  
  903           if  (vcmn_com batVeteran Eligibilit yEndDateTe xt != null  && vcmn_c ombatVeter anEligibil ityEndDate Text != '' ) { vcmn_c ombatVeter anEligibil ityEndDate Text = 'Ye s'; } 
  904  
  905           if  (vcmn_sha dIndicator Text == "t rue") { vc mn_shadInd icatorText  = "Yes";  } else { v cmn_shadIn dicatorTex t = "No";  }
  906           
  907           // Construct  summary no te part
  908           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"; }
  909           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"; }
  910           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"; }
  911           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 "; }
  912           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"; }
  913           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" ; }
  914           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"; }
  915           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 "; }
  916  
  917           // Update not e with new  SCD note  data
  918           va r vcmn_exi stingNoteD ata = "";
  919           if  (Xrm.Page .getAttrib ute("ftp_n otedetail" ).getValue () != null  && Xrm.Pa ge.getAttr ibute("ftp _notedetai l").getVal ue() != "" ) {
  920                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  921           }
  922           vc mn_extende dTemplateD ata = vcmn _existingN oteData +  vcmn_SCDno teString;
  923           // Replace ex isting not e
  924           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_extended TemplateDa ta);
  925           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  926       }
  927       catch  (err) {
  928           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getS erviceConn ectedDisab ilities):  ' + err.me ssage);
  929       }
  930   }
  931  
  932   function v cmn_getDis abilityDat a(vcmn_nat ionalId) {
  933       try {
  934           va r vcmn_ees ummaryURL  = vcmn_ees ummaryURLb ase + '000 000' + vcm n_national Id + '0000 00';
  935           va r vcmn_xml Data = nul l;
  936  
  937           $. ajax({
  938                type: "G ET",
  939                url: vcm n_eesummar yURL,
  940                contentT ype: "appl ication/xm l; charset =utf-8",
  941                dataType : "text",
  942                success:  function  (xmlTextda ta) {
  943                    vcmn _xmlData =  xmlTextda ta;
  944                },
  945                error: f unction (j qXHR, text Status, er rorThrown)  {
  946                    //Sy stem Error
  947                    vcmn _xmlData =  null;
  948                },
  949                async: f alse,
  950                cache: f alse
  951           }) ;
  952           re turn vcmn_ xmlData;
  953       }
  954       catch  (err) {
  955           al ert("Progr ess Note F orm Load S cript Func tion Error (vcmn_getD isabilityD ata): " +  err.messag e);
  956           re turn null;
  957       }
  958   }
  959  
  960   function v cmn_facili tyByCode_r esponse(vc mn_facilit yData, vcm n_lastSkip , vcmn_fac ilityCode)  {
  961       try {
  962           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  963           // ***REVISED  NOT USED,  KEEP FOR  FUTURE UPD ATE***
  964           /*
  965           va r vcmn_fac ilityid =  null;
  966           va r vcmn_fac ilityname  = null;
  967           fo r (var i =  0; i <= v cmn_facili tyData.d.r esults.len gth - 1; i ++) {
  968                //Get in fo
  969                if (vcmn _facilityD ata.d.resu lts[i].ftp _facilityI d != null)  { vcmn_fa cilityid =  vcmn_faci lityData.d .results[i ].ftp_faci lityId; }
  970                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; }
  971                break;
  972           }
  973           if  (vcmn_fac ilityid !=  null) {
  974                vcmn_set SimpleLook upValue('f tp_patient facility',  'ftp_faci lity', vcm n_facility id, vcmn_f acilitynam e);
  975                Xrm.Page .getAttrib ute('ftp_p atientfaci lity').set SubmitMode ('always') ;
  976           }
  977           */
  978       }
  979       catch  (err) {
  980           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_faci lityByCode _response) : ' + err. message);
  981       }
  982   }
  983  
  984   function v cmn_cptCod e_response (vcmn_cptC odeData, v cmn_lastSk ip, vcmn_t riageminut es) {
  985       try {
  986           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  987           fo r (var i =  0; i <= v cmn_cptCod eData.d.re sults.leng th - 1; i+ +) {
  988                //Write  to CRM pro gress note  form
  989                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);
  990                Xrm.Page .getAttrib ute('ftp_c ptcode').s etSubmitMo de('always ');
  991                break;
  992           }
  993       }
  994       catch  (err) {
  995           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_cptC ode_respon se): ' + e rr.message );
  996       }
  997   }
  998  
  999   function v cmn_ribbon ButtonSave () {
  1000       try {
  1001           // Save the c urrent CRM  data
  1002           Xr m.Page.dat a.entity.s ave();
  1003       }
  1004       catch  (err) {
  1005           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa ve): ' + e rr.message );
  1006       }
  1007   }
  1008  
  1009   function v cmn_getCoo kie(cname)  {
  1010       try {
  1011           va r name = c name + "=" ;
  1012           va r ca = doc ument.cook ie.split(' ;');
  1013           fo r (var i =  0; i < ca .length; i ++) {
  1014                var c =  ca[i];
  1015                while (c .charAt(0)  == ' ') {
  1016                    c =  c.substrin g(1);
  1017                }
  1018                if (c.in dexOf(name ) == 0) {
  1019                    retu rn c.subst ring(name. length, c. length);
  1020                }
  1021           }
  1022           re turn "";
  1023       }
  1024       catch  (err) {
  1025           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getC ookie): '  + err.mess age);
  1026       }
  1027   }
  1028  
  1029   function v cmn_wordWr ap(str, in tWidth, st rBreak, cu t) {
  1030       try {
  1031           // Takes a st ring that  exceeds a  set length  and inser ts word wr ap
  1032           va r m = ((ar guments.le ngth >= 2)  ? argumen ts[1] : 75 )
  1033           va r b = ((ar guments.le ngth >= 3)  ? argumen ts[2] : '\ n')
  1034           va r c = ((ar guments.le ngth >= 4)  ? argumen ts[3] : fa lse)
  1035  
  1036           va r i, j, l,  s, r
  1037  
  1038           st r += ''
  1039  
  1040           if  (m < 1) {
  1041                return s tr
  1042           }
  1043  
  1044           fo r (i = -1,  l = (r =  str.split( /\r\n|\n|\ r/)).lengt h; ++i < l ; r[i] +=  s) {
  1045                for (s =  r[i], r[i ] = '';
  1046                  s.leng th > m;
  1047                  r[i] + = s.slice( 0, j) + (( s = s.slic e(j)).leng th ? b : ' ')) {
  1048                    j =  c === 2 ||  (j = s.sl ice(0, m +  1).match( /\S*(\s)?$ /))[1]
  1049                      ?  m
  1050                      :  j.input.le ngth - j[0 ].length | | c === tr ue && m ||
  1051                         j.input.le ngth + (j  = s.slice( m).match(/ ^\S*/))[0] .length
  1052                }
  1053           }
  1054  
  1055           re turn r.joi n('\n')
  1056       }
  1057       catch  (err) {
  1058           al ert('Progr ess Note R ibbon Func tion Error (vcmn_word Wrap): ' +  err.messa ge);
  1059       }
  1060   }
  1061  
  1062   function v cmn_ribbon ButtonSave ToVistA()  {
  1063       try {
  1064           // Check the  value of t he Integra tion Statu s Field, i f = 'OK',  stop and e xit this s cript
  1065           va r vcmn_int egrationSt atus = Xrm .Page.getA ttribute(' ftp_integr ationstatu s').getVal ue();
  1066           if  (vcmn_int egrationSt atus == 'O K') { retu rn false;  }
  1067  
  1068           // Prompt use r to sign  the note
  1069           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  1070           va r vcmn_sig nThisNoteF ailure = f alse;
  1071           if  (vcmn_sig nThisNote  == null) {
  1072                Xrm.Util ity.confir mDialog(
  1073                    "Do  you need t o sign thi s note?, S elect OK i f Yes, oth erwise CAN CEL.",
  1074                    func tion () {
  1075                         //Check if  VIA Login  cookie ex ist (not e xpired)
  1076                         var vcmn_V iaLoginCoo kie = vcmn _getCookie ("viasessi onlink");
  1077                         //Prompt u ser to log in to VIA
  1078                         if (vcmn_V iaLoginCoo kie == "")  {
  1079                             alert( "Your VIST A session  has expire d. In orde r to sign  this note,  you must  be logged  into VISTA !");
  1080                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setVisi ble(true);
  1081                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setFocu s();
  1082                             vcmn_s ignThisNot eFailure =  true;
  1083                             return ;
  1084                         }
  1085                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000001 );
  1086                    },
  1087                    func tion () {
  1088                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000000 );
  1089                    }
  1090                );
  1091                Xrm.Page .getAttrib ute('ftp_s ignthisnot e').setSub mitMode('a lways');
  1092           }
  1093  
  1094           // Check for  additional  signers,  if they ex ist, the u ser must b e logged i nto VIA to  continue  process.
  1095           // Additional  Signature s must als o be in sy nc with ma tching Ses sion varia bles
  1096  
  1097           vc mn_AddlSig nersNameAr ray = null ;
  1098           vc mn_AddlSig nersIenArr ay = null;
  1099  
  1100           va r vcmn_sel ectedSigne rs = Xrm.P age.getAtt ribute('ft p_selected signers'). getValue() ;
  1101           if  (vcmn_sel ectedSigne rs != null  && vcmn_s electedSig ners != '' ) {
  1102                //Additi onal Signe rs exist i n CRM, ver ify sessio n variable s
  1103                var vcmn _selectedA rray = vcm n_selected Signers.sp lit('~~~') ;
  1104                var vcmn _selectedA rrayRecord Count = vc mn_selecte dArray.len gth;
  1105                if (vcmn _selectedA rrayRecord Count > 1)  {
  1106                    vcmn _AddlSigne rsNameArra y = vcmn_s electedArr ay;
  1107                }
  1108  
  1109                var vcmn _selectedI ENArray =  '';
  1110                var vcmn _selectedI ENArrayRec ordCount =  0;
  1111                var vcmn _progressN oteId = Xr m.Page.dat a.entity.g etId();
  1112  
  1113                var vcmn _arrayMism atch = fal se;
  1114  
  1115                //Get No te's Brows er Local S torage Val ues
  1116                if (vcmn _progressN oteId != n ull && vcm n_progress NoteId !=  '') {
  1117                    vcmn _localStor ageVarName  = "PN" +  vcmn_progr essNoteId;
  1118                    var  vcmn_local StorageStr ingValue =  localStor age.getIte m(vcmn_loc alStorageV arName);
  1119                    if ( vcmn_local StorageStr ingValue ! = null &&  vcmn_local StorageStr ingValue ! = '') {
  1120                         vcmn_selec tedIENArra y = vcmn_l ocalStorag eStringVal ue.split(' ~~~');
  1121                         vcmn_selec tedIENArra yRecordCou nt = vcmn_ selectedIE NArray.len gth;
  1122                         if (vcmn_s electedIEN ArrayRecor dCount > 1 ) {
  1123                             vcmn_A ddlSigners IenArray =  vcmn_sele ctedIENArr ay;
  1124                         }
  1125                    }
  1126                }
  1127                //Compar e CRM sign er array l ength with  LocalStor age array  length
  1128                if (vcmn _selectedA rrayRecord Count != v cmn_select edIENArray RecordCoun t) { vcmn_ arrayMisma tch = true ; }
  1129  
  1130                if (vcmn _arrayMism atch == tr ue) {
  1131                    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.");
  1132                    vcmn _signThisN oteFailure  = true;
  1133                }
  1134                else {
  1135                    //Ch eck if VIA  Login coo kie exist  (not expir ed)
  1136                    var  vcmn_ViaLo ginCookie  = vcmn_get Cookie("vi asessionli nk");
  1137                    if ( vcmn_ViaLo ginCookie  == "") {
  1138                         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 !");
  1139                         Xrm.Page.u i.tabs.get ('Tab_Vist ALogin').s etVisible( true);
  1140                         Xrm.Page.u i.tabs.get ('Tab_Vist ALogin').s etFocus();
  1141                         vcmn_signT hisNoteFai lure = tru e;
  1142                         return;
  1143                    }
  1144                }             
  1145           }
  1146  
  1147           if  (vcmn_sig nThisNoteF ailure ==  true) {
  1148                //****** Developer  Bypass for  no VISTA  authentica tion******
  1149                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}") {
  1150                    aler t("Develop er VISTA a uthenticat ion bypass  applied!" );
  1151                    Xrm. Page.getAt tribute('f tp_signthi snote').se tValue(100 000001);
  1152                    Xrm. Page.getAt tribute('f tp_signthi snote').se tSubmitMod e('always' );
  1153                }
  1154                else {
  1155                    retu rn false;
  1156                }
  1157           }
  1158  
  1159           // Save the c urrent CRM  data
  1160           Xr m.Page.dat a.entity.s ave();
  1161           // Display YE LLOW Progr ess....
  1162           Xr m.Page.ui. setFormNot ification( "Verifying  progress  note data,  please wa it..", "IN FO", "SAVE VISTA");
  1163  
  1164           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!');
  1165           if  (vcmn_con firmSaveTo Vista == f alse) {
  1166                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1167                return f alse;
  1168           }
  1169           // Get regard ing data
  1170           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1171           if  (vcmn_req uestId ==  null) {
  1172                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 !');
  1173                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  1174                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1175                return f alse;
  1176           }
  1177           // Verify tha t the rega rdingid is  of type ' incident'
  1178           if  (vcmn_req uestId[0]. entityType  != 'incid ent') {
  1179                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!') ;
  1180                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  1181                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1182                return f alse;
  1183           }
  1184  
  1185           // Preserved  Variables
  1186           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1187           va r vcmn_vet eranFirstN ame = '';
  1188           va r vcmn_vet eranLastNa me = '';
  1189           va r vcmn_SSN  = '';
  1190           va r vcmn_DOB  = '';
  1191  
  1192           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1193           if  (vcmn_req uestData ! = null) {
  1194                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1195                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1196                    //Ve rify that  the custom erid is of  type cont act
  1197                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1198                         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!') ;
  1199                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1200                         return fal se;
  1201                    }
  1202                }
  1203           }
  1204           if  (vcmn_vet eranId ==  null) {
  1205                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  1206                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1207                return f alse;
  1208           }
  1209  
  1210           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);
  1211           if  (vcmn_con tactData ! = null) {
  1212                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1213                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1214                if (vcmn _contactDa ta.d.ftp_D ateofBirth  != null)  { vcmn_DOB  = vcmn_co ntactData. d.ftp_Date ofBirth; }
  1215                if (vcmn _contactDa ta.d.Gover nmentId !=  null) { v cmn_SSN =  vcmn_conta ctData.d.G overnmentI d; }
  1216           }
  1217  
  1218           // Perform MV I Search
  1219           vc mn_unatten dedMviSear ch(vcmn_ve teranFirst Name, vcmn _veteranLa stName, vc mn_DOB, vc mn_SSN);
  1220       }
  1221       catch  (err) {
  1222           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa veToVistA) : ' + err. message);
  1223           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1224       }
  1225   }
  1226  
  1227   function v cmn_ribbon ButtonSave ToVistA_wi th_ICN(vcm n_patientI CN) {
  1228       try {
  1229           // ******Deve loper Bypa ss for mis sing ICN** ****
  1230           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1231                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  1232                    aler t("Develop er ICN byp ass applie d!");
  1233                    vcmn _patientIC N = "12345 6V123456";
  1234                }
  1235           }
  1236  
  1237           // Verify Pat ient ICN
  1238           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1239                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! ');
  1240                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1241                return f alse;
  1242           }
  1243           
  1244           // Get regard ing data
  1245           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1246  
  1247           // Preserved  Variables
  1248           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1249           va r vcmn_vet eranName =  '';
  1250           va r vcmn_vet eranFirstN ame = '';
  1251           va r vcmn_vet eranLastNa me = '';
  1252           va r vcmn_vet eranMiddle Name = '';
  1253  
  1254           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1255           if  (vcmn_req uestData ! = null) {
  1256                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1257                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1258                    //Ve rify that  the custom erid is of  type cont act
  1259                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1260                         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!') ;
  1261                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1262                         return fal se;
  1263                    }
  1264                }
  1265           }
  1266           if  (vcmn_vet eranId ==  null) {
  1267                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  1268                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1269                return f alse;
  1270           }
  1271  
  1272           va r vcmn_con tactData =  vcmn_getS ingleEntit yDataSync( 'ContactSe t', 'FullN ame, First Name, Last Name, Midd leName', v cmn_vetera nId.Id);
  1273           if  (vcmn_con tactData ! = null) {
  1274                if (vcmn _contactDa ta.d.FullN ame != nul l) { vcmn_ veteranNam e = vcmn_c ontactData .d.FullNam e; }
  1275                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1276                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1277                if (vcmn _contactDa ta.d.Middl eName != n ull) { vcm n_veteranM iddleName  = vcmn_con tactData.d .MiddleNam e; }
  1278           }
  1279  
  1280           // Get user d ata
  1281           va r vcmn_crm UserId = X rm.Page.ge tAttribute ('ownerid' ).getValue ();
  1282           va r vcmn_use rDomainId  = '';
  1283           va r vcmn_use rFirstName  = '';
  1284           va r vcmn_use rLastName  = '';
  1285           va r vcmn_use rMiddleNam e = '';
  1286           va r vcmn_use rSiteId =  '';
  1287  
  1288           if  (vcmn_crm UserId !=  null) {
  1289                //Verify  the owner  type
  1290                if (vcmn _crmUserId [0].entity Type != 's ystemuser' ) {
  1291                    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 !');
  1292                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1293                    retu rn false;
  1294                }
  1295  
  1296                var vcmn _userData  = vcmn_get SingleEnti tyDataSync ('SystemUs erSet', 'D omainName,  FirstName , LastName , MiddleNa me, ftp_Fa cilitySite Id', vcmn_ crmUserId[ 0].id);
  1297                if (vcmn _userData  != null) {
  1298                    if ( vcmn_userD ata.d.Doma inName !=  null) { vc mn_userDom ainId = vc mn_userDat a.d.Domain Name; }
  1299                    if ( vcmn_userD ata.d.Firs tName != n ull) { vcm n_userFirs tName = vc mn_userDat a.d.FirstN ame; }
  1300                    if ( vcmn_userD ata.d.Last Name != nu ll) { vcmn _userLastN ame = vcmn _userData. d.LastName ; }
  1301                    if ( vcmn_userD ata.d.Midd leName !=  null) { vc mn_userMid dleName =  vcmn_userD ata.d.Midd leName; }
  1302                    if ( vcmn_userD ata.d.ftp_ FacilitySi teId != nu ll) { vcmn _userSiteI d = vcmn_u serData.d. ftp_Facili tySiteId.I d; }
  1303                }
  1304           }
  1305           el se {
  1306                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!');
  1307                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1308                return f alse;
  1309           }
  1310  
  1311           // Verify tha t the curr ent owner  and the cu rrent user  is the sa me person,  if not do  not proce ed
  1312           if  ((vcmn_cr mUserId[0] .id).toUpp erCase() ! = (Xrm.Pag e.context. getUserId( )).toUpper Case()) {
  1313                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!');
  1314                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1315                return f alse;
  1316           }
  1317           va r vcmn_Not eUserTeam  = "NONE";
  1318           // Check Team  membershi p
  1319           if  (vcmn_Use rHasTeam(" Pharmacy",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "PHARM ACY"; }
  1320           if  (vcmn_Use rHasTeam(" CCA Team",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "CCA";  }
  1321           if  (vcmn_Use rHasTeam(" TAN", Xrm. Page.conte xt.getUser Id())) { v cmn_NoteUs erTeam = " TAN"; }
  1322           // **TEMP, ve rify these  team valu es that th ey are cor rect **FUT URE NEED**
  1323           if  (vcmn_Use rHasTeam(" PACT User" , Xrm.Page .context.g etUserId() )) { vcmn_ NoteUserTe am = "PACT "; }
  1324           if  (vcmn_Use rHasTeam(" MSA User",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "MSA";  }
  1325  
  1326           // Verify Tea m Value, t hat one ha s been ass igned
  1327           if  (vcmn_Not eUserTeam  == "NONE")  {
  1328                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 !');
  1329                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1330                return f alse;
  1331           }
  1332  
  1333           // Get reques t form con tent
  1334           va r vcmn_not eDescripti on = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  1335           if  (vcmn_not eDescripti on == null  || vcmn_n oteDescrip tion == '' ) {
  1336                alert('T he note de scription  field is e mpty, the  note canno t be creat ed in Vist A/CPRS!');
  1337                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1338                return f alse;
  1339           }
  1340  
  1341           // Using new  hospital l ocation an d local no tes lookup  fields
  1342           va r vcmn_loc alTitle =  Xrm.Page.g etAttribut e('ftp_loc alnotetitl e').getVal ue();
  1343           if  (vcmn_loc alTitle ==  null) {
  1344                alert('T he local n ote title  field is e mpty, the  note canno t be creat ed in Vist A/CPRS!');
  1345                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1346                return f alse;
  1347           }
  1348           el se { vcmn_ localTitle  = vcmn_lo calTitle[0 ].name; }
  1349  
  1350           vc mn_patient AssignedLo cation = X rm.Page.ge tAttribute ('ftp_note hospitallo cation').g etValue();
  1351           if  (vcmn_pat ientAssign edLocation  == null)  {
  1352                alert('T he hospita l location  field is  empty, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  1353                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1354                return f alse;
  1355           }
  1356           el se { vcmn_ patientAss ignedLocat ion = vcmn _patientAs signedLoca tion[0].na me; }
  1357           
  1358           va r vcmn_cal lbackNumbe r = Xrm.Pa ge.getAttr ibute('ftp _callbackn umber').ge tValue();
  1359           if  (vcmn_cal lbackNumbe r == null  || vcmn_ca llbackNumb er == '')  {
  1360                alert('T he callbac k number f ield is em pty, the n ote cannot  be create d in VistA /CPRS!');
  1361                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1362                return f alse;
  1363           }
  1364           va r vcmn_rea sonForRequ est = Xrm. Page.getAt tribute('f tp_reasonf orrequest' ).getValue ();
  1365           if  (vcmn_rea sonForRequ est == nul l) {
  1366                alert('T he reason  for reques t field is  empty, th e note can not be cre ated in Vi stA/CPRS!' );
  1367                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1368                return f alse;
  1369           }
  1370  
  1371           va r vcmn_enc ounterCode  = 'NEW';
  1372  
  1373           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  1374           if  (vcmn_sig nThisNote  == 1000000 01) { vcmn _signThisN ote = true ; } else {  vcmn_sign ThisNote =  false; }
  1375  
  1376           // Get Progre ss Note Gu id/Id
  1377           va r vcmn_not eId = Xrm. Page.data. entity.get Id();
  1378  
  1379           // Get Create d On Date  & Convert  format
  1380           va r vcmn_cre atedOnDate  = vcmn_co nvertCrmDa teToVistAD ate(Xrm.Pa ge.getAttr ibute('cre atedon').g etValue()) ;
  1381           if  (vcmn_cre atedOnDate  == null)  {
  1382                alert('T he CRM cre atedon fie ld is empt y, the not e cannot b e created  in VistA/C PRS!');
  1383                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1384                return f alse;
  1385           }     
  1386  
  1387           // Get User E ntry Date
  1388           va r vcmn_use rEntryDate  = vcmn_co nvertCrmDa teToVistAD ate(Xrm.Pa ge.getAttr ibute('ftp _userentry date').get Value());
  1389           if  (vcmn_use rEntryDate  == null)  { vcmn_use rEntryDate  = vcmn_cr eatedOnDat e; }
  1390  
  1391           // Get Facili ty and loo kup facili ty number  and HL7 UR L
  1392           va r vcmn_fac ilityCode  = '';
  1393           va r vcmn_sit eHL7Listen erAddress  = '';
  1394           va r vcmn_pat ientFacili ty = Xrm.P age.getAtt ribute('ft p_patientf acility'). getValue() ;
  1395           if  (vcmn_pat ientFacili ty == null ) {
  1396                alert('T he CRM pat ient facil ity field  is empty,  the note c annot be c reated in  VistA/CPRS !');
  1397                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1398                return f alse;
  1399           }
  1400           el se {
  1401                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e, ftp_hl7 listener',  vcmn_pati entFacilit y[0].id);
  1402                if (vcmn _facilityD ata.d.ftp_ facilityco de != null ) {
  1403                    vcmn _facilityC ode = vcmn _facilityD ata.d.ftp_ facilityco de;
  1404                }
  1405                else {
  1406                    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!') ;
  1407                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1408                    retu rn false;
  1409                }
  1410  
  1411                if (vcmn _facilityD ata.d.ftp_ hl7listene r != null)  {
  1412                    var  vcmn_siteH L7Listener Address =  vcmn_facil ityData.d. ftp_hl7lis tener;
  1413                }
  1414                else {
  1415                    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!');
  1416                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1417                    retu rn false;
  1418                }
  1419           }
  1420  
  1421           va r vcmn_ori ginatorID  = '';
  1422           va r vcmn_use rSiteNo =  '';
  1423  
  1424           // Lookup the  Facility/ Site #
  1425           if  (vcmn_use rSiteId !=  null && v cmn_userSi teId != '' ) {
  1426                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e', vcmn_u serSiteId) ;
  1427                if (vcmn _facilityD ata != nul l) {
  1428                    if ( vcmn_facil ityData.d. ftp_facili tycode !=  null) { vc mn_userSit eNo = vcmn _facilityD ata.d.ftp_ facilityco de; }
  1429                }
  1430           }
  1431  
  1432           // Validate r equired Vi sta Lookup  info
  1433           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) {
  1434                //Abort  process, m issing inf o
  1435                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 !');
  1436                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1437                return f alse;
  1438           }
  1439  
  1440           if  (vcmn_IsP roductionE nvironment  == false)  {
  1441                //Provid e the opti on to sear ch for Lor i Nicholls , site# 61 3
  1442                var vcmn _impersona tePromptSt ring = "** THIS IS A  VISTA USER  SEARCH TE ST PROMPT* * \n" +
  1443                    "If  you would  like to im personate  the user:  \n" +
  1444                    "Lor i Nicholls  (613) \n"  +
  1445                    "Sel ect OK.  O therwise,  select CAN CEL.";
  1446                var vcmn _confirmIm personateV istaUser =  confirm(v cmn_impers onatePromp tString);
  1447                if (vcmn _confirmIm personateV istaUser = = true) {
  1448                    vcmn _userFirst Name = "Lo ri";
  1449                    vcmn _userLastN ame = "Nic holls";
  1450                    vcmn _userSiteN o = "613";
  1451                }
  1452           }
  1453  
  1454           va r vcmn_vis tausersDat a = vcmn_g etVistaUse rsData(vcm n_userFirs tName, vcm n_userLast Name, vcmn _userSiteN o, false);
  1455  
  1456           // Check vist a users da ta content
  1457           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)  {
  1458                //Abort  process, m issing inf o
  1459                alert('U nable to o btain Vist a User Dat a, the not e cannot b e created  in VistA/C PRS!');
  1460                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1461                return f alse;
  1462           }
  1463  
  1464           va r vcmn_sel ectedUserF irstName =  '';
  1465           va r vcmn_sel ectedUserM iddleName  = '';
  1466           va r vcmn_sel ectedUserL astName =  '';
  1467           va r vcmn_sel ectedUserS uffix = '' ;
  1468           va r vcmn_sel ectedUserD isplayName  = '';
  1469           va r vcmn_sel ectedUserT itle = '';
  1470           va r vcmn_use rIsSelecte d = false;
  1471  
  1472           if  (vcmn_vis tausersDat a.Data.len gth > 1) {
  1473                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!");
  1474                for (var  i = 0; i  <= vcmn_vi stausersDa ta.Data.le ngth - 1;  i++) {
  1475                    var  vcmn_curre ntUserFirs tName = '' ;
  1476                    var  vcmn_curre ntUserMidd leName = ' ';
  1477                    var  vcmn_curre ntUserLast Name = '';
  1478                    var  vcmn_curre ntUserSuff ix = '';
  1479                    var  vcmn_curre ntUserDisp layName =  '';
  1480                    var  vcmn_curre ntUserTitl e = '';
  1481                    if ( vcmn_vista usersData. Data[i].Fi rstName !=  null) { v cmn_curren tUserFirst Name = vcm n_vistause rsData.Dat a[i].First Name; }
  1482                    if ( vcmn_vista usersData. Data[i].Mi ddleName ! = null) {  vcmn_curre ntUserMidd leName = v cmn_vistau sersData.D ata[i].Mid dleName; }
  1483                    if ( vcmn_vista usersData. Data[i].La stName !=  null) { vc mn_current UserLastNa me = vcmn_ vistausers Data.Data[ i].LastNam e; }
  1484                    if ( vcmn_vista usersData. Data[i].Su ffix != nu ll) { vcmn _currentUs erSuffix =  vcmn_vist ausersData .Data[i].S uffix; }
  1485                    if ( vcmn_vista usersData. Data[i].Di splayName  != null) {  vcmn_curr entUserDis playName =  vcmn_vist ausersData .Data[i].D isplayName ; }
  1486                    if ( vcmn_vista usersData. Data[i].Ti tle != nul l) { vcmn_ currentUse rTitle = v cmn_vistau sersData.D ata[i].Tit le; }
  1487                    //Pr ompt user  about this  vista use r record
  1488                    var  vcmn_userP romptStrin g = "Click  OK, to se lect this  user.  Oth erwise CAN CEL \n" +
  1489                         "\n First  Name: " +  vcmn_curre ntUserFirs tName +
  1490                         "\n Middle  Name: " +  vcmn_curr entUserMid dleName +
  1491                         "\n Last N ame: " + v cmn_curren tUserLastN ame +
  1492                         "\n Suffix : " + vcmn _currentUs erSuffix +
  1493                         "\n Displa y Name: "  + vcmn_cur rentUserDi splayName  +
  1494                         "\n Title:  " + vcmn_ currentUse rTitle;
  1495  
  1496                    var  vcmn_confi rmSelectVi staUser =  confirm(vc mn_userPro mptString) ;
  1497                    if ( vcmn_confi rmSelectVi staUser ==  true) {
  1498                         vcmn_userI sSelected  = true;
  1499                         vcmn_selec tedUserFir stName = v cmn_curren tUserFirst Name;
  1500                         vcmn_selec tedUserMid dleName =  vcmn_curre ntUserMidd leName;
  1501                         vcmn_selec tedUserLas tName = vc mn_current UserLastNa me;
  1502                         vcmn_selec tedUserSuf fix = vcmn _currentUs erSuffix;
  1503                         vcmn_selec tedUserDis playName =  vcmn_curr entUserDis playName;
  1504                         vcmn_selec tedUserTit le = vcmn_ currentUse rTitle;
  1505                         break;
  1506                    }
  1507                }
  1508           }
  1509           el se {
  1510                //Select  data from  the first  record
  1511                vcmn_use rIsSelecte d = true;
  1512                if (vcmn _vistauser sData.Data [0].FirstN ame != nul l) { vcmn_ selectedUs erFirstNam e = vcmn_v istausersD ata.Data[0 ].FirstNam e; }
  1513                if (vcmn _vistauser sData.Data [0].Middle Name != nu ll) { vcmn _selectedU serMiddleN ame = vcmn _vistauser sData.Data [0].Middle Name; }
  1514                if (vcmn _vistauser sData.Data [0].LastNa me != null ) { vcmn_s electedUse rLastName  = vcmn_vis tausersDat a.Data[0]. LastName;  }
  1515                if (vcmn _vistauser sData.Data [0].Suffix  != null)  { vcmn_sel ectedUserS uffix = vc mn_vistaus ersData.Da ta[0].Suff ix; }
  1516                if (vcmn _vistauser sData.Data [0].Displa yName != n ull) { vcm n_selected UserDispla yName = vc mn_vistaus ersData.Da ta[0].Disp layName; }
  1517                if (vcmn _vistauser sData.Data [0].Title  != null) {  vcmn_sele ctedUserTi tle = vcmn _vistauser sData.Data [0].Title;  }
  1518           }
  1519  
  1520           // Check if a  user was  selected
  1521           if  (vcmn_use rIsSelecte d == false ) {
  1522                alert('A  user was  not select ed from th e previous  prompts,  the note c annot be c reated in  VistA/CPRS !');
  1523                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1524                return f alse;
  1525           }
  1526  
  1527           // Execute In tegration
  1528           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_userEnt ryDate, vc mn_created OnDate, vc mn_selecte dUserFirst Name, vcmn _selectedU serMiddleN ame, vcmn_ selectedUs erLastName , vcmn_sel ectedUserS uffix, vcm n_facility Code, vcmn _originato rID, vcmn_ siteHL7Lis tenerAddre ss, vcmn_p atientAssi gnedLocati on);
  1529  
  1530       }
  1531       catch  (err) {
  1532           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa veToVistA_ with_ICN):  ' + err.m essage);
  1533           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1534       }
  1535   }
  1536  
  1537   function v cmn_getVis taUsersDat a(vcmn_use rFirstName , vcmn_use rLastName,  vcmn_user SiteNo, vc mn_noFilte r) {
  1538       try {
  1539           va r vcmn_jso nData = nu ll;
  1540           $. ajax({
  1541                type: "G ET",
  1542                url: vcm n_VistaUse rsURLbase  + vcmn_use rFirstName  + "/" + v cmn_userLa stName + " /" + vcmn_ userSiteNo  + "?noFil ter=" + vc mn_noFilte r,
  1543                contentT ype: "appl ication/js on; charse t=utf-8",
  1544                dataType : "json",
  1545                success:  function  (data) {
  1546                    vcmn _jsonData  = data;
  1547                },
  1548                error: f unction (j qXHR, text Status, er rorThrown)  {
  1549                    //Sy stem Error
  1550                    vcmn _jsonData  = null;
  1551                },
  1552                async: f alse,
  1553                cache: f alse
  1554           }) ;
  1555           re turn vcmn_ jsonData;
  1556       }
  1557       catch  (err) {
  1558           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getV istaUsersD ata): ' +  err.messag e);
  1559           re turn null;
  1560       }
  1561   }
  1562  
  1563   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) {
  1564       try {
  1565           // Reformat N ote Descri ption as n eeded to h andle long  lines of  text (Word Wrap)
  1566           va r vcmn_Not eText = vc mn_noteDes cription;
  1567           va r vcmn_Rev isedNoteTe xt = "";
  1568           // Do Breakdo wn of line s
  1569           va r vcmn_Tex tLines = v cmn_NoteTe xt.split(' \n');
  1570           if  (vcmn_Tex tLines.len gth > 0) {
  1571                //Reform at text
  1572                for (var  i = 0; i  < vcmn_Tex tLines.len gth; i++)  {
  1573                    //Te st for a l ong line
  1574                    if ( vcmn_TextL ines[i].le ngth > vcm n_WordWrap Limit) {
  1575                         //Break do wn line
  1576                         var vcmn_N ewString =  vcmn_word Wrap(vcmn_ TextLines[ i], vcmn_W ordWrapLim it, '\n');
  1577                         //Add revi sed text b ack
  1578                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _NewString  + "\n";   //Add back  the CR/LF  used to s plit on
  1579                    }
  1580                    else  {
  1581                         //Add text  to new no te
  1582                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _TextLines [i] + "\n" ; //Add ba ck the CR/ LF used to  split on
  1583                    }
  1584                }
  1585           }
  1586           if  (vcmn_Rev isedNoteTe xt != "" & & vcmn_Rev isedNoteTe xt != null ) {
  1587                vcmn_not eDescripti on = vcmn_ RevisedNot eText;
  1588           }
  1589  
  1590           // Add list o f addition al signer  names to N ote Text i f they exi sts
  1591           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  1592                //Create  text stri ngs from a dditional  signers ar ray
  1593                var vcmn _SignerNam es = "\nAd ditional N ote Signer s\n"+"---- ---------- ---------- -----\n";
  1594                for (var  i = 0; i  <= vcmn_Ad dlSignersN ameArray.l ength - 1;  i++) {
  1595                    if ( i >= 1) {
  1596                         var vcmn_s ingleSigne rName = vc mn_AddlSig nersNameAr ray[i].spl it("___");
  1597                         vcmn_Signe rNames = v cmn_Signer Names + vc mn_singleS ignerName[ 1] + "\n";
  1598                    }
  1599                }
  1600                //Add to  Note Desc ription
  1601                vcmn_not eDescripti on = vcmn_ noteDescri ption + vc mn_SignerN ames;
  1602           }
  1603  
  1604           va r vcmn_vis itNumber =  'NEW';
  1605           va r vcmn_cli entName =  "FTPCRM";
  1606           va r vcmn_For mat = "JSO N";
  1607           va r vcmn_pat ientIdenti fierType =  "ICN";
  1608           va r vcmn_doc umentAvail abilitySta tus = "AV" ;  //Histo rical Note  only at t his time
  1609           va r vcmn_ori ginatorCom binedMiddl e = "";
  1610           if  (vcmn_ori ginatorMid dleName !=  '' && vcm n_originat orMiddleNa me != null ) { vcmn_o riginatorC ombinedMid dle = vcmn _originato rMiddleNam e; }
  1611           if  (vcmn_ori ginatorSuf fix != ''  && vcmn_or iginatorSu ffix != nu ll) {
  1612                if (vcmn _originato rCombinedM iddle != ' ') {
  1613                    vcmn _originato rCombinedM iddle = vc mn_origina torCombine dMiddle +  " " + vcmn _originato rSuffix;
  1614                }
  1615                else {
  1616                    vcmn _originato rCombinedM iddle = vc mn_origina torSuffix;
  1617                }
  1618           }
  1619  
  1620           va r vcmn_req uestJSON =  {
  1621                "ClientN ame": vcmn _clientNam e,
  1622                "Format" : vcmn_For mat,
  1623                "Facilit ySiteID":  vcmn_facil itySiteId,
  1624                "SiteHL7 ListenerAd dress": vc mn_siteHL7 ListenerAd dress,
  1625                "VisitNu mber": vcm n_visitNum ber,
  1626                "IsSigne dNote": vc mn_signThi sNote,
  1627                "Patient AdmitDate" : vcmn_pat ientAdmitD ate,
  1628                "Patient LastName":  vcmn_pati entLastNam e,
  1629                "Patient FirstName" : vcmn_pat ientFirstN ame,
  1630                "Patient Identifier ": vcmn_pa tientICN,
  1631                "Patient Identifier Type": vcm n_patientI dentifierT ype,
  1632                "Patient AssignedLo cation": v cmn_patien tAssignedL ocation,
  1633                "NoteTex t": vcmn_n oteDescrip tion,
  1634                "Origina torID": vc mn_origina torID,
  1635                "Origina torFirstNa me": vcmn_ originator FirstName,
  1636                "Origina torMiddleN ame": vcmn _originato rCombinedM iddle,
  1637                "Origina torLastNam e": vcmn_o riginatorL astName,
  1638                "Documen tFileName" : vcmn_loc alTitle,
  1639                "Documen tAvailabil ityStatus" : vcmn_doc umentAvail abilitySta tus,
  1640                "Activit yDate": vc mn_activit yDate
  1641           };
  1642  
  1643           va r vcmn_req uestRespon se = "";
  1644  
  1645           $. ajax({
  1646                type: "P OST",
  1647                url: vcm n_NoteWrit eUrl,
  1648                data: JS ON.stringi fy(vcmn_re questJSON) ,
  1649                contentT ype: "appl ication/js on; charse t=utf-8",
  1650                dataType : "json",
  1651                success:  function  (data) {
  1652                    var  vcmn_newda ta = data;
  1653                    vcmn _requestRe sponse = v cmn_newdat a;
  1654                    vcmn _vistAInte grationReq uest_respo nse(null,  vcmn_reque stResponse , vcmn_not eDescripti on);
  1655                },
  1656                error: f unction (j qXHR, text Status, er rorThrown)  {
  1657                    //Sy stem Error
  1658                    vcmn _vistAInte grationReq uest_respo nse(errorT hrown, nul l, vcmn_no teDescript ion);
  1659                },
  1660                async: f alse,
  1661                cache: f alse
  1662           }) ;
  1663       }
  1664       catch  (err) {
  1665           al ert('Progr ess Note R ibbon Func tion Error (vcmn_exec uteVistAIn tegrationR equest): '  + err.mes sage);
  1666           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1667       }
  1668   }
  1669  
  1670   function v cmn_vistAI ntegration Request_re sponse(vcm n_errorThr own, vcmn_ requestRes ponse, vcm n_noteDesc ription) {
  1671       try {
  1672           // Process In tegration  Request Re sponse
  1673           if  (vcmn_err orThrown ! = null) {
  1674                //Write  Error
  1675                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etValue('E RROR');
  1676                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etSubmitMo de('always ');
  1677                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tValue(Str ing(vcmn_e rrorThrown ));
  1678                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tSubmitMod e('always' );
  1679                Xrm.Page .getAttrib ute('ftp_i ntegration date').set Value(new  Date());
  1680                Xrm.Page .getAttrib ute('ftp_i ntegration date').set SubmitMode ('always') ;
  1681                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etValue('' );
  1682                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etSubmitMo de('always ');
  1683                alert('T he note cr eation in  VistA/CPRS  failed!\n Please see  the integ ration err or field f or details .');
  1684                Xrm.Page .getContro l('ftp_int egrationer ror').setF ocus();
  1685                Xrm.Page .data.enti ty.save();
  1686                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1687                return f alse;
  1688           }
  1689           el se {
  1690                //Write  web servic e response  Success o r Failure
  1691                if (vcmn _requestRe sponse.Err orOccurred  == false)  {
  1692                    //Ca ll Additio nal Signer s & Finali ze Note fu nction
  1693                    vcmn _finalizeN oteCreatio n(vcmn_req uestRespon se.Status,  vcmn_requ estRespons e.Data, vc mn_noteDes cription)
  1694                }
  1695                else {
  1696                    //Wr ite Failur e entry
  1697                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setValu e(vcmn_req uestRespon se.Status) ;
  1698                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setSubm itMode('al ways');
  1699                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setValue (vcmn_requ estRespons e.ErrorMes sage + "   DebugInfo: " + vcmn_r equestResp onse.Debug Info);
  1700                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setSubmi tMode('alw ays');
  1701                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setValue( new Date() );
  1702                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setSubmit Mode('alwa ys');
  1703                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setValu e('');
  1704                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setSubm itMode('al ways');
  1705                    aler t('The not e creation  in VistA/ CPRS faile d!\nPlease  see the i ntegration  error fie ld for det ails.');
  1706                    Xrm. Page.getCo ntrol('ftp _integrati onerror'). setFocus() ;
  1707                    Xrm. Page.data. entity.sav e();
  1708                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1709                    retu rn false;
  1710                }
  1711           }
  1712       }
  1713       catch  (err) {
  1714           al ert('Progr ess Note R ibbon Func tion Error (vcmn_vist AIntegrati onRequest_ response):  ' + err.m essage);
  1715           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1716       }
  1717   }
  1718  
  1719   function v cmn_finali zeNoteCrea tion(vcmn_ integratio nStatus, v cmn_integr ationNoteI d, vcmn_no teDescript ion) {
  1720       //The  Note was s ucessfully  created i n Vista/CP RS, add ad ditional s igners if  needed
  1721       try {
  1722           // Determine  if additio nal signer s exists
  1723           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  1724                //Get th e current  CRM User's  assigned  site/facil ity
  1725                var vcmn _userSiteI d = "";
  1726                var vcmn _UserSiteN o = "";
  1727                var vcmn _duz = "";
  1728                var vcmn _providern ame = "";
  1729  
  1730                var vcmn _userData  = vcmn_get SingleEnti tyDataSync ('SystemUs erSet', 'f tp_Facilit ySiteId',  Xrm.Page.c ontext.get UserId());
  1731                if (vcmn _userData  != null) {
  1732                    if ( vcmn_userD ata.d.ftp_ FacilitySi teId != nu ll) {
  1733                         vcmn_userS iteId = vc mn_userDat a.d.ftp_Fa cilitySite Id.Id;
  1734                    }
  1735                }
  1736  
  1737                //Lookup  the Facil ity/Site #
  1738                if (vcmn _userSiteI d != null  && vcmn_us erSiteId ! = '') {
  1739                    var  vcmn_facil ityData =  vcmn_getSi ngleEntity DataSync(' ftp_facili tySet', 'f tp_facilit ycode', vc mn_userSit eId);
  1740                    if ( vcmn_facil ityData !=  null) {
  1741                         if (vcmn_f acilityDat a.d.ftp_fa cilitycode  != null)  { vcmn_Use rSiteNo =  vcmn_facil ityData.d. ftp_facili tycode; }
  1742                    }
  1743                }
  1744  
  1745                //Check  if VIA Log in cookie  exist (not  expired)
  1746                var vcmn _ViaLoginC ookie = vc mn_getCook ie("viases sionlink") ;
  1747                if (vcmn _ViaLoginC ookie != n ull && vcm n_ViaLogin Cookie !=  '') {
  1748                    var  vcmn_cooki earray = v cmn_ViaLog inCookie.s plit("~~~~ ", 2);
  1749                    vcmn _duz = vcm n_cookiear ray[0];
  1750                    vcmn _providern ame = vcmn _cookiearr ay[1];
  1751                }
  1752  
  1753                //Create  text stri ngs from a dditional  signers ar ray
  1754                var vcmn _SignerIEN  = "";
  1755                for (var  i = 0; i  <= vcmn_Ad dlSignersI enArray.le ngth - 1;  i++) {
  1756                    if ( i == 1) {  vcmn_Signe rIEN = vcm n_AddlSign ersIenArra y[i]; }
  1757                    if ( i > 1) { v cmn_Signer IEN = vcmn _SignerIEN  + " " + v cmn_AddlSi gnersIenAr ray[i]; }
  1758                }
  1759  
  1760                //Create  the Addit ional Sign ers
  1761                var vcmn _viaSigner s = new Ob ject();
  1762                vcmn_via Signers.Pr oviderName  = vcmn_pr ovidername ;
  1763                vcmn_via Signers.Du z = vcmn_d uz;
  1764                vcmn_via Signers.Lo ginSiteCod e = vcmn_U serSiteNo;
  1765                vcmn_via Signers.Ta rget = vcm n_integrat ionNoteId;
  1766                vcmn_via Signers.Su pplemental Parameters  = vcmn_Si gnerIEN;
  1767  
  1768                $.ajax({
  1769                    type : "POST",
  1770                    url:  vcmn_AddS ignersUrl,
  1771                    data : JSON.str ingify(vcm n_viaSigne rs),
  1772                    cont entType: " applicatio n/json; ch arset=utf- 8",
  1773                    data Type: "jso n",
  1774                    succ ess: funct ion (data)  {
  1775                         vcmn_viaSi gnersRespo nse = JSON .stringify (data.Data );
  1776                         //Test for  Failure
  1777                         if (vcmn_v iaSignersR esponse.Er rorOccurre d == true)  {
  1778                             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!");
  1779                         }
  1780                    },
  1781                    erro r: functio n (jqXHR,  textStatus , errorThr own) {
  1782                         //System E rror
  1783                         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!");
  1784                    },
  1785                    asyn c: false,
  1786                    cach e: false
  1787                });
  1788  
  1789                if (vcmn _localStor ageVarName  != "" &&  vcmn_local StorageVar Name != nu ll) {
  1790                    //Cl ear existi ng session  storage v ariable.
  1791                    loca lStorage.r emoveItem( vcmn_local StorageVar Name);  
  1792                }
  1793           }
  1794  
  1795           // Perform st andard for m updates  to signify  completio n
  1796           // Write Succ ess entry
  1797           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_noteDesc ription);
  1798           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  1799           Xr m.Page.get Attribute( 'ftp_integ rationstat us').setVa lue(vcmn_i ntegration Status);
  1800           Xr m.Page.get Attribute( 'ftp_integ rationstat us').setSu bmitMode(' always');
  1801           Xr m.Page.get Attribute( 'ftp_integ rationerro r').setVal ue(null);
  1802           Xr m.Page.get Attribute( 'ftp_integ rationerro r').setSub mitMode('a lways');
  1803           Xr m.Page.get Attribute( 'ftp_integ rationdate ').setValu e(new Date ());
  1804           Xr m.Page.get Attribute( 'ftp_integ rationdate ').setSubm itMode('al ways');
  1805           Xr m.Page.get Attribute( 'ftp_integ rationnote id').setVa lue(vcmn_i ntegration NoteId);
  1806           Xr m.Page.get Attribute( 'ftp_integ rationnote id').setSu bmitMode(' always');
  1807           Xr m.Page.get Control('f tp_integra tionstatus ').setFocu s();
  1808           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!');
  1809           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1810           Xr m.Page.dat a.entity.s ave();
  1811       }
  1812       catch  (err) {
  1813           al ert('Progr ess Note R ibbon Func tion Error (vcmn_fina lizeNoteCr eation): '  + err.mes sage);
  1814           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1815       }
  1816   }
  1817  
  1818   function v cmn_getCoo kie(cname)  {
  1819       try {
  1820           va r name = c name + "=" ;
  1821           va r ca = doc ument.cook ie.split(' ;');
  1822           fo r (var i =  0; i < ca .length; i ++) {
  1823                var c =  ca[i];
  1824                while (c .charAt(0)  == ' ') {
  1825                    c =  c.substrin g(1);
  1826                }
  1827                if (c.in dexOf(name ) == 0) {
  1828                    retu rn c.subst ring(name. length, c. length);
  1829                }
  1830           }
  1831           re turn "";
  1832       }
  1833       catch  (err) {
  1834           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getC ookie): '  + err.mess age);
  1835       }
  1836   }
  1837  
  1838   function v cmn_initVi aDropdownC ontrols()  {
  1839       //Init ialize VIA  DropDown  Controls
  1840       //Func tion is tr iggered by  The VistA  Login Con trol and o nchange of  Facility  attribute
  1841       try {
  1842           Xr m.Page.get Control("W ebResource _HospitalL ocation"). setSrc(Xrm .Page.getC ontrol("We bResource_ HospitalLo cation").g etSrc());
  1843           Xr m.Page.get Control("W ebResource _LocalNote sTitle").s etSrc(Xrm. Page.getCo ntrol("Web Resource_L ocalNotesT itle").get Src());
  1844       }
  1845       catch  (err) {
  1846           al ert('Progr ess Note V IA Login F unction Er ror(vcmn_i nitViaDrop downContro ls): ' + e rr.message );
  1847       }
  1848   }
  1849  
  1850   function v cmn_facili tyGroupDef ault_respo nse(vcmn_f acilityGro upData, vc mn_lastSki p, vcmn_fa cilitySite Id) {
  1851       try {
  1852           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  1853           fo r (var i =  0; i <= v cmn_facili tyGroupDat a.d.result s.length -  1; i++) {
  1854                //Get Va lues and W rite to Pr ogress Not e
  1855                if (vcmn _facilityG roupData.d .results[i ].ftp_loca lnotestitl e != null)  {
  1856                    Xrm. Page.getAt tribute("f tp_localno testitle") .setValue( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ localnotes title);
  1857                    Xrm. Page.getAt tribute('f tp_localno testitle') .setSubmit Mode('alwa ys');
  1858                }
  1859                if (vcmn _facilityG roupData.d .results[i ].ftp_hosp itallocati on != null ) {
  1860                    Xrm. Page.getAt tribute("f tp_hospita llocation" ).setValue (vcmn_faci lityGroupD ata.d.resu lts[i].ftp _hospitall ocation);
  1861                    Xrm. Page.getAt tribute('f tp_hospita llocation' ).setSubmi tMode('alw ays');
  1862                }
  1863                break;
  1864           }
  1865       }
  1866       catch  (err) {
  1867           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_faci lityGroupD efault_res ponse): '  + err.mess age);
  1868       }
  1869   }
  1870  
  1871   function v cmn_buildQ ueryFilter (field, va lue, and)  {
  1872       try {
  1873           if  (value ==  '') {
  1874                if (and)  {
  1875                    retu rn " and "  + field +  " eq null ";
  1876                } else {
  1877                    retu rn field +  " eq null ";
  1878                }
  1879           }
  1880           el se {
  1881                if (and)  {
  1882                    retu rn " and "  + field +  " eq '" +  value + " '";
  1883                } else {
  1884                    retu rn field +  " eq '" +  value + " '";
  1885                }
  1886           }
  1887       }
  1888       catch  (err) {
  1889           al ert('Progr ess Note R ibbon Func tion Error (vcmn_buil dQueryFilt er): ' + e rr.message );
  1890           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1891       }
  1892   }
  1893  
  1894   function v cmn_unatte ndedMviSea rch(firstn ame, lastn ame, dobda te, ssn) {
  1895       try {
  1896           va r filter =  "";
  1897           va r filterPr efix = "$s elect=*&$f ilter=";
  1898           va r edipi =  "";
  1899           va r dobstrin g = "";
  1900           if  (dobdate  != null) {
  1901                dobstrin g = dobdat e;
  1902           }
  1903  
  1904           if  (ssn != " " && ssn ! = null) {
  1905                ssn = ss n.replace( /-/g, "");
  1906           }
  1907  
  1908           // if we have  edipi, se arch using  just it
  1909           if  (edipi !=  "") {
  1910                filter =  vcmn_buil dQueryFilt er("crme_E DIPI", edi pi, false) ;
  1911                filter + = vcmn_bui ldQueryFil ter("crme_ ClassCode" , 'MIL', t rue);
  1912                filter + = vcmn_bui ldQueryFil ter("crme_ SearchType ", 'Search ByIdentifi er', true) ;
  1913  
  1914                //set se arch type  as unatten ded
  1915                filter + = " and cr me_IsAtten ded eq fal se";
  1916           }
  1917           el se {
  1918                //otherw ise search  using las tname, fir stname, ss n, dob
  1919                filter =  vcmn_buil dQueryFilt er("crme_L astName",  lastname,  false); // assuming l astname wi ll never b e blank
  1920  
  1921                if (firs tname != " " && first name != nu ll) {
  1922                    filt er += vcmn _buildQuer yFilter("c rme_FirstN ame", firs tname, tru e);
  1923                }
  1924  
  1925                if (ssn  != "" && s sn != null ) {
  1926                    filt er += vcmn _buildQuer yFilter("c rme_SSN",  ssn, true) ;
  1927                }
  1928  
  1929                if (dobs tring != " ") {
  1930                    filt er += " an d crme_DOB String eq  '" + dobst ring + "'" ;
  1931                }
  1932                filter + = vcmn_bui ldQueryFil ter("crme_ SearchType ", 'Search ByFilter',  true);
  1933  
  1934                //set se arch type  as attende d (for now )
  1935                filter + = " and cr me_IsAtten ded eq tru e";
  1936           }
  1937  
  1938           fi lter = enc odeURIComp onent(filt er);
  1939           fi lter = fil terPrefix  + filter;
  1940           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);
  1941       }
  1942       catch  (err) {
  1943           al ert('Progr ess Note R ibbon Func tion Error (vcmn_unat tendedMviS earch): '  + err.mess age);
  1944           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1945       }
  1946   }
  1947  
  1948   function v cmn_unatte ndedMviSea rchCallbac k(returnDa ta) {
  1949       try {
  1950           if  (returnDa ta != null  && return Data.lengt h >= 1) {
  1951                // check  for excep tions 1st
  1952                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."))  {
  1953                    //do  nothing,  pass empty  ICN
  1954                    vcmn _ribbonBut tonSaveToV istA_with_ ICN("");
  1955                }
  1956                else {
  1957                    var  patientMvi Identifier  = returnD ata[0].crm e_PatientM viIdentifi er == null  ? "" : re turnData[0 ].crme_Pat ientMviIde ntifier;
  1958                    if ( patientMvi Identifier  != "") {
  1959                         var idpart s = patien tMviIdenti fier.split ("^");
  1960  
  1961                         if (idpart s.length >  0) {
  1962                             var na tionalId =  idparts[0 ];
  1963                             _icn =  nationalI d;
  1964                             //Pass  on the IC N and cont inue valid ation
  1965                             vcmn_r ibbonButto nSaveToVis tA_with_IC N(_icn);
  1966                         }
  1967                    }
  1968                }
  1969           }
  1970           el se {
  1971                //Return  empty ICN
  1972                vcmn_rib bonButtonS aveToVistA _with_ICN( "");
  1973           }
  1974       }
  1975       catch  (err) {
  1976           al ert('Progr ess Note R ibbon Func tion Error (vcmn_unat tendedMviS earchCallb ack): ' +  err.messag e);
  1977           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1978       }
  1979   }
  1980  
  1981   function v cmn_unatte ndedMviSea rchComplet e() {
  1982       //do n othing
  1983   }
  1984  
  1985   function v cmn_buildQ ueryFilter SCD(field,  value, an d) {
  1986       try {
  1987           if  (value ==  '') {
  1988                if (and)  {
  1989                    retu rn " and "  + field +  " eq null ";
  1990                } else {
  1991                    retu rn field +  " eq null ";
  1992                }
  1993           }
  1994           el se {
  1995                if (and)  {
  1996                    retu rn " and "  + field +  " eq '" +  value + " '";
  1997                } else {
  1998                    retu rn field +  " eq '" +  value + " '";
  1999                }
  2000           }
  2001       }
  2002       catch  (err) {
  2003           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_buil dQueryFilt erSCD): '  + err.mess age);
  2004           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2005       }
  2006   }
  2007  
  2008   function v cmn_unatte ndedMviSea rchSCD(fir stname, la stname, do bdate, ssn ) {
  2009       try {
  2010           va r filter =  "";
  2011           va r filterPr efix = "$s elect=*&$f ilter=";
  2012           va r edipi =  "";
  2013           va r dobstrin g = "";
  2014           if  (dobdate  != null) {
  2015                dobstrin g = dobdat e;
  2016           }
  2017  
  2018           if  (ssn != " " && ssn ! = null) {
  2019                ssn = ss n.replace( /-/g, "");
  2020           }
  2021  
  2022           // if we have  edipi, se arch using  just it
  2023           if  (edipi !=  "") {
  2024                filter =  vcmn_buil dQueryFilt erSCD("crm e_EDIPI",  edipi, fal se);
  2025                filter + = vcmn_bui ldQueryFil terSCD("cr me_ClassCo de", 'MIL' , true);
  2026                filter + = vcmn_bui ldQueryFil terSCD("cr me_SearchT ype", 'Sea rchByIdent ifier', tr ue);
  2027  
  2028                //set se arch type  as unatten ded
  2029                filter + = " and cr me_IsAtten ded eq fal se";
  2030           }
  2031           el se {
  2032                //otherw ise search  using las tname, fir stname, ss n, dob
  2033                filter =  vcmn_buil dQueryFilt erSCD("crm e_LastName ", lastnam e, false);  //assumin g lastname  will neve r be blank
  2034  
  2035                if (firs tname != " " && first name != nu ll) {
  2036                    filt er += vcmn _buildQuer yFilterSCD ("crme_Fir stName", f irstname,  true);
  2037                }
  2038  
  2039                if (ssn  != "" && s sn != null ) {
  2040                    filt er += vcmn _buildQuer yFilterSCD ("crme_SSN ", ssn, tr ue);
  2041                }
  2042  
  2043                if (dobs tring != " ") {
  2044                    filt er += " an d crme_DOB String eq  '" + dobst ring + "'" ;
  2045                }
  2046                filter + = vcmn_bui ldQueryFil terSCD("cr me_SearchT ype", 'Sea rchByFilte r', true);
  2047  
  2048                //set se arch type  as attende d (for now )
  2049                filter + = " and cr me_IsAtten ded eq tru e";
  2050           }
  2051  
  2052           fi lter = enc odeURIComp onent(filt er);
  2053           fi lter = fil terPrefix  + filter;
  2054           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) ;
  2055       }
  2056       catch  (err) {
  2057           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_unat tendedMviS earchSCD):  ' + err.m essage);
  2058       }
  2059   }
  2060  
  2061   function v cmn_unatte ndedMviSea rchCallbac kSCD(retur nData) {
  2062       try {
  2063           if  (returnDa ta != null  && return Data.lengt h >= 1) {
  2064                // check  for excep tions 1st
  2065                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."))  {
  2066                    //do  nothing,  pass empty  ICN
  2067                    vcmn _getServic eConnected Disabiliti es("");
  2068                }
  2069                else {
  2070                    var  patientMvi Identifier  = returnD ata[0].crm e_PatientM viIdentifi er == null  ? "" : re turnData[0 ].crme_Pat ientMviIde ntifier;
  2071                    if ( patientMvi Identifier  != "") {
  2072                         var idpart s = patien tMviIdenti fier.split ("^");
  2073  
  2074                         if (idpart s.length >  0) {
  2075                             var na tionalId =  idparts[0 ];
  2076                             _icn =  nationalI d;
  2077                             //Pass  on the IC N and cont inue with  SCD
  2078                             vcmn_g etServiceC onnectedDi sabilities (_icn);
  2079                         }
  2080                    }
  2081                }
  2082           }
  2083           el se {
  2084                //Return  empty ICN
  2085                vcmn_get ServiceCon nectedDisa bilities(" ");
  2086           }
  2087       }
  2088       catch  (err) {
  2089           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_unat tendedMviS earchCallb ackSCD): '  + err.mes sage);
  2090       }
  2091   }
  2092  
  2093   //Standalo ne form lo ad functio ns
  2094   function v cmn_secure ProgressNo te() {
  2095       try {
  2096           // Disable al l form att ributes if  form is o pened by a  user who  does not o wn the pro gress note
  2097           // Only handl e forms in  create st ate
  2098           if  (Xrm.Page .ui.getFor mType() !=  2) { retu rn false;  } //2 = CR M Update S tatus
  2099           // Get the cu rrent owne r of the r ecord and  compare to  the curre nt user
  2100           va r vcmn_rec ordOwnerId  = Xrm.Pag e.getAttri bute('owne rid').getV alue();
  2101           // 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
  2102           if  ((vcmn_re cordOwnerI d[0].id).t oUpperCase () != (Xrm .Page.cont ext.getUse rId()).toU pperCase() ) {
  2103                Xrm.Page .data.enti ty.attribu tes.forEac h(function  (attribut e, index)  {
  2104                    var  control =  Xrm.Page.g etControl( attribute. getName()) ;
  2105                    if ( control) {
  2106                         control.se tDisabled( true)
  2107                    }
  2108                });
  2109           }
  2110       }
  2111       catch  (err) {
  2112           al ert('Progr ess Note F orm Load F unction Er ror(vcmn_s ecureProgr essNote):  ' + err.me ssage);
  2113       }
  2114   }
  2115  
  2116   function v cmn_initFi nancialDis claimer()  {
  2117       //This  function  is used to  initialze  the Finan cial Discl aimer tab  on the pro gress note  form
  2118       try {
  2119           va r vcmn_isR eadDisclai mer = Xrm. Page.getAt tribute("f tp_isreadd isclaimer" ).getValue ();
  2120           va r vcmn_res ponseToDis claimer =  Xrm.Page.g etAttribut e("ftp_isd isclaimerr ead").getV alue();
  2121           Xr m.Page.get Attribute( "ftp_patie ntcallersr easonfordi sagreeing" ).setSubmi tMode("alw ays");
  2122           if  (vcmn_isR eadDisclai mer == tru e && vcmn_ responseTo Disclaimer  == true)  {
  2123                Xrm.Page .ui.tabs.g et("Tab_Fi nancialDis claimer"). setVisible (true);
  2124                Xrm.Page .getAttrib ute("ftp_i spatientag ree").setR equiredLev el("requir ed");
  2125                var vcmn _isPatient Agree = Xr m.Page.get Attribute( "ftp_ispat ientagree" ).getValue ();
  2126                if (vcmn _isPatient Agree == f alse) {
  2127                    Xrm. Page.getAt tribute("f tp_patient callersrea sonfordisa greeing"). setRequire dLevel("re quired");
  2128                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tVisible(t rue);
  2129                }
  2130                else { X rm.Page.ge tControl(" ftp_patien tcallersre asonfordis agreeing") .setVisibl e(false);  }
  2131           }
  2132       }
  2133       catch  (err) {
  2134           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ initFinanc ialDisclai mer): ' +  err.messag e);
  2135       }
  2136   }
  2137  
  2138   //Standalo ne form at tribute on  change ev ent functi ons
  2139   function v cmn_needTo ReadDiscla imer_OnCha nge() {
  2140       //This  function  is used to  display t he Financi al Disclai mer prompt
  2141       try {
  2142           va r vcmn_isR eadDisclai mer = Xrm. Page.getAt tribute("f tp_isreadd isclaimer" ).getValue ();
  2143           if  (vcmn_isR eadDisclai mer == tru e) {
  2144                //Financ ial Discla imer is ne eded
  2145                var vcmn _responseT oDisclaime r = confir m("FINANCI AL DISCLAI MER\n\n'Th is is not  an authori zation for  VA Paymen t'\nand al so\n'To ha ve hospita l contact  the neares t VA\nFaci lity for t ransfer up on stabili zation.'\n \nSelect O K if you r ead the di sclaimer t o the pati ent / vete ran and Ca ncel if yo u did not  read it.") ;
  2146                if (vcmn _responseT oDisclaime r == true)  {
  2147                    Xrm. Page.ui.ta bs.get("Ta b_Financia lDisclaime r").setVis ible(true) ;
  2148                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setValue (true);
  2149                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setSubmi tMode("alw ays");
  2150                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setRequire dLevel("re quired");
  2151                    //Se t Default  Value to N ot Agreein g and Requ ire Reason  for disag reeing
  2152                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setValue(f alse);
  2153                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setSubmitM ode("alway s");
  2154                    Xrm. Page.getAt tribute("f tp_patient callersrea sonfordisa greeing"). setRequire dLevel("re quired");
  2155                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tVisible(t rue);
  2156                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tFocus();
  2157                }
  2158                else {
  2159                    Xrm. Page.ui.ta bs.get("Ta b_Financia lDisclaime r").setVis ible(false );
  2160                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setValue (false);
  2161                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setSubmi tMode("alw ays");
  2162                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setRequire dLevel("no ne");
  2163                    Xrm. Page.getAt tribute("f tp_patient callersrea sonfordisa greeing"). setRequire dLevel("no ne");
  2164                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tVisible(f alse);
  2165                }
  2166           }
  2167           el se {
  2168                //No Fin ancial Dis claimer ne eded  (Hid e Financia l Disclaim er section )
  2169                Xrm.Page .ui.tabs.g et("Tab_Fi nancialDis claimer"). setVisible (false);
  2170                Xrm.Page .getAttrib ute("ftp_i spatientag ree").setR equiredLev el("none") ;
  2171                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setR equiredLev el("none") ;
  2172                Xrm.Page .getContro l("ftp_pat ientcaller sreasonfor disagreein g").setVis ible(false );
  2173           }
  2174       }
  2175       catch  (err) {
  2176           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ needToRead Disclaimer _OnChange) : ' + err. message);
  2177       }
  2178   }
  2179  
  2180   function v cmn_isPati entInAgree ment_OnCha nge() {
  2181       try {
  2182           va r vcmn_isP atientAgre e = Xrm.Pa ge.getAttr ibute("ftp _ispatient agree").ge tValue();
  2183           if  (vcmn_isP atientAgre e == false ) {
  2184                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setR equiredLev el("requir ed");
  2185                Xrm.Page .getContro l("ftp_pat ientcaller sreasonfor disagreein g").setVis ible(true) ;
  2186           }
  2187           el se {
  2188                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setR equiredLev el("none") ;
  2189                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setV alue(null) ;
  2190                Xrm.Page .getContro l("ftp_pat ientcaller sreasonfor disagreein g").setVis ible(false );
  2191                //Update  Note
  2192                vcmn_app endNoteFin ancialDisc laimer_OnC hange();
  2193           }
  2194       }
  2195       catch  (err) {
  2196           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ isPatientI nAgreement _OnChange) : ' + err. message);
  2197       }
  2198   }
  2199  
  2200   function v cmn_append NoteFinanc ialDisclai mer_OnChan ge() {
  2201       //This  function  adds Finan cial Discl aimer text  to the en d of the N ote
  2202       try {
  2203           // Get Curren t Note Tex t
  2204           va r vcmn_cur rentNoteTe xt = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  2205           if  (vcmn_cur rentNoteTe xt == null ) { vcmn_c urrentNote Text = "";  }
  2206           // Create new  Financial  Disclaime r Text
  2207           va r vcmn_fin ancialDisc laimerText  = "";
  2208  
  2209           va r vcmn_sta ndardText  = "\n\nFIN ANCIAL DIS CLAIMER\n"  +
  2210                "------- ---------- ---------- ---------- ---------- ---------- ---------- ---\n" +
  2211                "The fol lowing dis claimer wa s read to  the caller :\n" +
  2212                "Patient  was instr ucted, 'Th is is not  an authori zation for  VA\n" +
  2213                "Payment  and also  'To have h ospital co ntact the  nearest VA \n" +
  2214                "Facilit y for tran sfer upon  stabilizat ion.\n";
  2215           va r vcmn_ter minationTe xt = "\n-- ---------- ---------- ---------- ---------- ---------- ---------- --------\n ";
  2216  
  2217           va r vcmn_isR eadDisclai mer = Xrm. Page.getAt tribute("f tp_isreadd isclaimer" ).getValue ();
  2218           va r vcmn_res ponseToDis claimer =  Xrm.Page.g etAttribut e("ftp_isd isclaimerr ead").getV alue();
  2219           if  (vcmn_isR eadDisclai mer == tru e && vcmn_ responseTo Disclaimer  == true)  {
  2220                var vcmn _isPatient Agree = Xr m.Page.get Attribute( "ftp_ispat ientagree" ).getValue ();
  2221                if (vcmn _isPatient Agree == t rue) {
  2222                    vcmn _financial Disclaimer Text = vcm n_standard Text +
  2223                         "\nPatient /Caller ag rees with  plan." + v cmn_termin ationText;
  2224                }
  2225                else {
  2226                    var  vcmn_reaso nForDisagr eeing = Xr m.Page.get Attribute( "ftp_patie ntcallersr easonfordi sagreeing" ).getValue ();
  2227                    if ( vcmn_reaso nForDisagr eeing == n ull) { vcm n_reasonFo rDisagreei ng = ""; }
  2228                    vcmn _financial Disclaimer Text = vcm n_standard Text +
  2229                         "\nPatient /Caller do es not agr ee with th e plan bec ause:\n" +
  2230                         vcmn_reaso nForDisagr eeing + vc mn_termina tionText;
  2231                }
  2232           }
  2233  
  2234           // Append to  existing N ote
  2235           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_currentN oteText +  vcmn_finan cialDiscla imerText);
  2236           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  2237       }
  2238       catch  (err) {
  2239           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ appendNote FinancialD isclaimer_ OnChange):  ' + err.m essage);
  2240       }
  2241   }
  2242  
  2243   function v cmn_execut eCrmOdataG etRequest( vcmn_jsonQ uery, vcmn _aSync, vc mn_aSyncCa llback, vc mn_skipCou nt, vcmn_o ptionArray ) {
  2244       //This  function  executes a  CRM Odata  web servi ce call to  retrieve  Crm data
  2245       //*vcm n_jsonQuer y* - a pro perly form atted CRM  Odata Quer y string ( required)
  2246       //*vcm n_aSync* -  specify ' true' to e xecute asy nchronousl y otherwis e 'false'  (required)
  2247       //*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 '')
  2248       //*vcm n_skipCoun t* - Initi al setting  is always  '0', incr ements by  50 per CRM  SDK Odata  standards  (required )
  2249       //*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)
  2250       try {
  2251           va r vcmn_ent ityData =  null;
  2252           $. ajax({
  2253                type: 'G ET',
  2254                contentT ype: 'appl ication/js on; charse t=utf-8',
  2255                datatype : 'json',
  2256                url: vcm n_jsonQuer y,
  2257                beforeSe nd: functi on (XMLHtt pRequest)  {
  2258                    XMLH ttpRequest .setReques tHeader('A ccept', 'a pplication /json');
  2259                },
  2260                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  2261                    vcmn _entityDat a = data;
  2262                    if ( vcmn_aSync  == true)  {
  2263                         vcmn_aSync Callback(v cmn_entity Data, vcmn _skipCount , vcmn_opt ionArray);
  2264                    }
  2265                },
  2266                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  2267                    aler t('Fail: A jax Error  in vcmn_ex ecuteCrmOd ataGetRequ est: ' + e rrorThrown  + " Reque st: " + vc mn_jsonQue ry);
  2268                },
  2269                async: v cmn_aSync,
  2270                cache: f alse
  2271           }) ;
  2272           re turn vcmn_ entityData ;
  2273       }
  2274       catch  (err) {
  2275           al ert('An er ror occure d in the v cmn_execut eCrmOdataG etRequest  function.   Error Det ail Messag e: ' + err );
  2276       }
  2277   }
  2278  
  2279   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) {
  2280       //This  function  returns a  CRM JSON d ataset for  all entit y records  matching c riteria pr ovided Asy ncronously
  2281       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  2282       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  2283       //*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
  2284       //*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'
  2285       //*vcm n_sortDire ction* - i s a string  specifyin g the sort  as Ascend ing or Des cending e. g. 'asc' o r 'desc'
  2286       //*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)
  2287       //*vcm n_aSyncCal lback* - i s the name  of the fu nction to  call when  returning  the result
  2288       //*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
  2289  
  2290       try {
  2291           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;
  2292           vc mn_execute CrmOdataGe tRequest(v cmn_jsonQu ery, true,  vcmn_aSyn cCallback,  vcmn_skip Count, vcm n_optionAr ray);
  2293       }
  2294       catch  (err) {
  2295           al ert('An er ror occure d in the v cmn_getMul tipleEntit yDataAsync  function.   Error De tail Messa ge: ' + er r);
  2296       }
  2297   }
  2298  
  2299   function v cmn_getSin gleEntityD ataSync(vc mn_entityS etName, vc mn_attribu teSet, vcm n_entityId ) {
  2300       //This  function  returns a  CRM JSON d ataset for  a single  entity rec ord based  on the ent ity id pro vided Sync ronously
  2301       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  2302       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  2303       //*vcm n_entityId * - is the  Guid for  the entity  record
  2304  
  2305       try {
  2306           va r vcmn_ent ityIdNoBra cket = vcm n_entityId .replace(/ ({|})/g, ' ');
  2307           va r vcmn_sel ectString  = '(guid'  + "'" + vc mn_entityI dNoBracket  + "'" + ' )?$select= ' + vcmn_a ttributeSe t;
  2308           va r vcmn_jso nQuery = v cmn_server Url + vcmn _crmOdataE ndPoint +  '/' + vcmn _entitySet Name + vcm n_selectSt ring;
  2309           va r vcmn_ent ityData =  vcmn_execu teCrmOdata GetRequest (vcmn_json Query, fal se, '', 0,  null);
  2310           re turn vcmn_ entityData ;
  2311       }
  2312       catch  (err) {
  2313           al ert('An er ror occure d in the v cmn_getSin gleEntityD ataSync fu nction.  E rror Detai l Message:  ' + err);
  2314       }
  2315   }
  2316  
  2317   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) {
  2318       //This  function  returns a  CRM JSON d ataset for  all entit y records  matching c riteria pr ovided Syn cronously
  2319       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  2320       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  2321       //*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
  2322       //*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'
  2323       //*vcm n_sortDire ction* - i s a string  specifyin g the sort  as Ascend ing or Des cending e. g. 'asc' o r 'desc'
  2324       //*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)
  2325  
  2326       try {
  2327           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;
  2328           va r vcmn_ent ityData =  vcmn_execu teCrmOdata GetRequest (vcmn_json Query, fal se, '', vc mn_skipCou nt, null);
  2329           re turn vcmn_ entityData ;
  2330       }
  2331       catch  (err) {
  2332           al ert('An er ror occure d in the v cmn_getMul tipleEntit yDataSync  function.   Error Det ail Messag e: ' + err );
  2333       }
  2334   }
  2335