119. EPMO Open Source Coordination Office Redaction File Detail Report

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

119.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\VCCMResources\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Tue Nov 7 11:34:40 2017 UTC
2 VCCM.zip\VCCM\CRM_solutions\VCCMResources\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Mon Dec 4 13:07:13 2017 UTC

119.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 7 9022
Changed 6 12
Inserted 0 0
Removed 0 0

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

119.4 Active regular expressions

No regular expressions were active.

119.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:// se r
v e r
/WebParts/ DEV/api/no teswrite';     //OLD MANU AL DEV URL
  18   var vcmn_N oteWriteUr l = '';
  19   //var vcmn _Enrollmen tEligibili tySummaryU RLbase = ' https:// se r
v e r
/WebParts/ DEV/api/es r/Enrollme ntEligibil itySummary /2.0/json/ ';    //OLD MANU AL DEV URL
  20   var vcmn_e esummaryUR Lbase = '' ;
  21   var vcmn_E nrollmentE ligibility SummaryURL base = '';
  22   //var vcmn _VistaUser sURLbase =  'https:// se r
v e r
/WebParts/ DEV/api/Vi staUsers/1 .0/json/ft pCRM/john/ smith/1234 ?noFilter= true';    //OLD MANU AL DEV URL
  23   var vcmn_V istaUsersU RLbase = ' ';
  24   //var vcmn _AddSigner sUrl = 'ht tps:// se r
v e r
/WebParts/ DEV/api/VI A/AddSigne rs/1.0/jso n';    //OLD MANU AL DEV URL
  25   var vcmn_A ddSignersU rl = '';
  26   //var vcmn _Appointme ntsUrl = ' https:// se r
v e r
/WebParts/ DEV/api/Ap pointments /1.0/json/ FtPCRM/';    //OLD MANU AL DEV URL
  27   var vcmn_A ppointment sUrl = '';
  28   //var vcmn _Medicatio nsUrl = 'h ttps:// se r
v e r
/WebParts/ DEV/api/Me dications/ 1.0/json/F tPCRM/';    //OLD MANU AL DEV URL
  29   var vcmn_M edications Url = '';
  30  
  31   var vcmn_E nrollmentE ligibility SummaryDat a = null;
  32   var vcmn_S ecurePatie ntICN = nu ll;
  33  
  34   //Producti on Environ ment Indic ator
  35   var vcmn_I sProductio nEnvironme nt = false ;
  36  
  37   //Word Wra p Line Lim it
  38   var vcmn_W ordWrapLim it = 75;
  39  
  40   //Addition al Signers  Data
  41   var vcmn_A ddlSigners NameArray  = null;
  42   var vcmn_A ddlSigners IenArray =  null;
  43   var vcmn_l ocalStorag eVarName =  "";
  44  
  45   //Workload  Encounter  data
  46   var vcmn_P rogressNot eSubject =  'Progress  Note: ';
  47   var vcmn_T riageNoteS ubject = ' Triage Not e: ';
  48   var vcmn_W orkloadEnc ounterSubj ect = 'Wor kload Enco unter Note : ';
  49   var vcmn_i sWorkloadE ncounter =  false;
  50   var vcmn_m atchLookup Id = '';
  51  
  52   var vcmn_V iaLoginNam e = null;
  53   var vcmn_V iaLoginTok en = null;
  54   var vcmn_e signatureC ode = null ;
  55   var vcmn_V iaLoginFac ility = nu ll;
  56   var vcmn_V iaPatientI d = null;
  57   var vcmn_V iaInPatien t = null;
  58   var vcmn_V iaCptCode  = null;
  59   var vcmn_V iaCptDescr iption = n ull;
  60   var vcmn_V iaDiagnosi sCode = nu ll;
  61   var vcmn_V iaDiagnosi sDescripti on = null;
  62  
  63   var vcmn_b aseService EndpointUr l = null;
  64   var vcmn_r equestingA pp = null;
  65   var vcmn_c onsumingAp pToken = n ull;
  66   var vcmn_c onsumingAp pPassword  = null;
  67  
  68   var vcmn_f acilityGro upDefaultI d = null;
  69  
  70   var vcmn_n onNarcotic Template =  false;
  71   var vcmn_n onNarcotic RequestNam e = "Medic ation - Re newal Non- Narcotic";
  72  
  73   function v cmn_getQue ryVariable (vcmn_vari able) {
  74       try {
  75           // Get a Quer y Variable
  76           va r vcmn_que ry = windo w.location .search.su bstring(1) ;
  77           va r vcmn_var s = vcmn_q uery.split ("&");
  78           fo r (var i =  0; i < vc mn_vars.le ngth; i++)  {
  79                var vcmn _pair = vc mn_vars[i] .split("=" );
  80                if (vcmn _pair[0] = = vcmn_var iable) {
  81                    retu rn decodeU RIComponen t(vcmn_pai r[1]);
  82                }
  83           }
  84           re turn "";
  85       }
  86       catch  (err) {
  87           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getQ ueryVariab le): ' + e rr.message );
  88       }
  89   }
  90  
  91   function v cmn_setSim pleLookupV alue(vcmn_ LookupId,  vcmn_Type,  vcmn_Id,  vcmn_Name)  {
  92       try {
  93           // Sets the v alue for l ookup attr ibutes tha t accept o nly a sing le entity  reference.
  94           va r vcmn_loo kupReferen ce = [];
  95           vc mn_lookupR eference[0 ] = {};
  96           vc mn_lookupR eference[0 ].id = vcm n_Id;
  97           vc mn_lookupR eference[0 ].entityTy pe = vcmn_ Type;
  98           vc mn_lookupR eference[0 ].name = v cmn_Name;
  99           Xr m.Page.get Attribute( vcmn_Looku pId).setVa lue(vcmn_l ookupRefer ence);
  100       }
  101       catch  (err) {
  102           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_setS impleLooku pValue): '  + err.mes sage);
  103       }
  104   }
  105  
  106   function v cmn_conver tCrmDateTo VistADate( vcmn_crmDa te) {
  107       try {
  108           va r vcmn_Vis tADate = n ull;
  109           if  (vcmn_crm Date != nu ll) {
  110                var vcmn _crmYear =  (vcmn_crm Date.getFu llYear()). toString() ;
  111                var vcmn _crmMonth  = '00';
  112                if ((vcm n_crmDate. getMonth()  + 1) < 10 ) {
  113                    vcmn _crmMonth  = '0' + (v cmn_crmDat e.getMonth () + 1).to String();
  114                }
  115                else {
  116                    vcmn _crmMonth  = (vcmn_cr mDate.getM onth() + 1 ).toString ();
  117                }
  118                var vcmn _crmDay =  '00';
  119                if ((vcm n_crmDate. getDate())  < 10) {
  120                    vcmn _crmDay =  '0' + (vcm n_crmDate. getDate()) .toString( );
  121                }
  122                else {
  123                    vcmn _crmDay =  (vcmn_crmD ate.getDat e()).toStr ing();
  124                }
  125                var vcmn _crmHours  = '00';
  126                if ((vcm n_crmDate. getHours() ) < 10) {
  127                    vcmn _crmHours  = '0' + (v cmn_crmDat e.getHours ()).toStri ng();
  128                }
  129                else {
  130                    vcmn _crmHours  = (vcmn_cr mDate.getH ours()).to String();
  131                }
  132                var vcmn _crmMinute s = '00';
  133                if ((vcm n_crmDate. getMinutes ()) < 10)  {
  134                    vcmn _crmMinute s = '0' +  (vcmn_crmD ate.getMin utes()).to String();
  135                }
  136                else {
  137                    vcmn _crmMinute s = (vcmn_ crmDate.ge tMinutes() ).toString ();
  138                }
  139                var vcmn _crmSecond s = '00';
  140                if ((vcm n_crmDate. getSeconds ()) < 10)  {
  141                    vcmn _crmSecond s = '0' +  (vcmn_crmD ate.getSec onds()).to String();
  142                }
  143                else {
  144                    vcmn _crmSecond s = (vcmn_ crmDate.ge tSeconds() ).toString ();
  145                }
  146  
  147                //Create  VistA Dat e
  148                vcmn_Vis tADate = v cmn_crmYea r + vcmn_c rmMonth +  vcmn_crmDa y + vcmn_c rmHours +  vcmn_crmMi nutes + vc mn_crmSeco nds;
  149           }
  150           re turn vcmn_ VistADate;
  151       }
  152       catch  (err) {
  153           al ert('Progr ess Note E rror(vcmn_ convertCrm DateToVist ADate): '  + err.mess age);
  154           re turn null;
  155       }
  156   }
  157  
  158   function v cmn_decryp tServiceCo nnector(vc mn_connect orArray, v cmn_connec torValue)  {
  159       var vc mn_decrypt edString =  "";
  160       if (vc mn_connect orArray !=  null && v cmn_connec torArray ! = "") {
  161           va r vcmn_new Array = vc mn_connect orArray.to String().s plit(',');
  162           vc mn_newArra y.reverse( );
  163           fo r (i = 0;  i < vcmn_n ewArray.le ngth; i++)  {
  164                var vcmn _curChar =  "";
  165                if (i ==  0) {
  166                    vcmn _curChar =  vcmn_newA rray[i] -  vcmn_conne ctorValue;
  167                }
  168                else {
  169                    vcmn _curChar =  vcmn_newA rray[i] -  (i + vcmn_ connectorV alue);
  170                }
  171                vcmn_dec ryptedStri ng = vcmn_ decryptedS tring + St ring.fromC harCode(vc mn_curChar );
  172           }
  173       }
  174       return  vcmn_decr yptedStrin g;
  175   }
  176  
  177   function v cmn_UserHa sTeam(team Name, user Guid) {
  178       try {
  179           va r vcmn_tea mid = null ;
  180           va r vcmn_cur rentUserId  = userGui d;
  181           va r vcmn_con ditionalFi lter = "(N ame eq '"  + teamName  + "')";
  182           va r vcmn_tea mData = vc mn_getMult ipleEntity DataSync(' TeamSet',  'TeamId',  vcmn_condi tionalFilt er, 'Name' , 'asc', 0 );
  183           if  (vcmn_tea mData != n ull) {
  184                for (var  i = 0; i  <= vcmn_te amData.d.r esults.len gth - 1; i ++) {
  185                    //Ge t Info
  186                    if ( vcmn_teamD ata.d.resu lts[i].Tea mId != nul l) { vcmn_ teamid = v cmn_teamDa ta.d.resul ts[i].Team Id; }
  187                    brea k;
  188                }
  189           }
  190           // If Team ex ists, chec k if the c urrent use r is part  of that te am
  191           va r vcmn_tea mMembershi pId = null ;
  192           if  (vcmn_tea mid != nul l && vcmn_ currentUse rId != nul l) {
  193                var vcmn _condition alFilter =  "(TeamId  eq (guid'"  + vcmn_te amid + "')  and Syste mUserId eq  (guid'" +  vcmn_curr entUserId  + "'))";
  194                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);
  195                if (vcmn _teamMembe rshipData  != null) {
  196                    for  (var i = 0 ; i <= vcm n_teamMemb ershipData .d.results .length -  1; i++) {
  197                         //Get Info
  198                         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; }
  199                         break;
  200                    }
  201                }
  202           }
  203           if  (vcmn_tea mMembershi pId != nul l) { retur n true; }
  204  
  205           // otherwise  return fal se                 
  206           re turn false ;
  207       }
  208       catch  (err) {
  209           // Display Er ror
  210           al ert("An er ror occure d in the v cmn_UserHa sTeam func tion.  Err or Detail  Message: "  + err);
  211       }
  212   }
  213  
  214   function v cmn_Settin gsWebServi ceURL_resp onse(vcmn_ settingDat a, vcmn_la stSkip, vc mn_NoteWri teUrl_NA)  {
  215       try {
  216           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  217           va r vcmn_Dac Url = null ;
  218           va r vcmn_Not esWriteApi Url = null ;
  219           va r vcmn_Enr ollmentEli gibilitySu mmaryApiUr l = null;
  220           va r vcmn_Vis taUserApiU rl = null;
  221           va r vcmn_Via AddlSigner sApiUrl =  null;
  222           va r vcmn_App ointmentAp iUrl = nul l;
  223           va r vcmn_Med icationApi Url = null ;
  224  
  225           fo r (var i =  0; i <= v cmn_settin gData.d.re sults.leng th - 1; i+ +) {
  226                //Get in fo
  227                if (vcmn _settingDa ta.d.resul ts[i].ftp_ DACURL !=  null) { vc mn_DacUrl  = vcmn_set tingData.d .results[i ].ftp_DACU RL; }
  228                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; }
  229                if (vcmn _settingDa ta.d.resul ts[i].ftp_ ESREnrollm entEligibi litySummar yAPIURL !=  null) { v cmn_Enroll mentEligib ilitySumma ryApiUrl =  vcmn_sett ingData.d. results[i] .ftp_ESREn rollmentEl igibilityS ummaryAPIU RL; }
  230                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; }
  231                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; }
  232                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 ; }
  233                if (vcmn _settingDa ta.d.resul ts[i].ftp_ VIAService BaseURL !=  null) { v cmn_baseSe rviceEndpo intUrl = v cmn_settin gData.d.re sults[i].f tp_VIAServ iceBaseURL ; }
  234                if (vcmn _settingDa ta.d.resul ts[i].ftp_ VIARequest ingApplica tionCode ! = null) {  vcmn_reque stingApp =  vcmn_sett ingData.d. results[i] .ftp_VIARe questingAp plicationC ode; }
  235                if (vcmn _settingDa ta.d.resul ts[i].ftp_ VIAConsumi ngApplicat ionToken ! = null) {  vcmn_consu mingAppTok en = vcmn_ settingDat a.d.result s[i].ftp_V IAConsumin gApplicati onToken; }
  236                if (vcmn _settingDa ta.d.resul ts[i].ftp_ VIAConsumi ngApplicat ionPasswor d != null)  { vcmn_co nsumingApp Password =  vcmn_sett ingData.d. results[i] .ftp_VIACo nsumingApp licationPa ssword; }
  237                if (vcmn _settingDa ta.d.resul ts[i].ftp_ Appointmen tAPIURL !=  null) { v cmn_Appoin tmentApiUr l = vcmn_s ettingData .d.results [i].ftp_Ap pointmentA PIURL; }
  238                if (vcmn _settingDa ta.d.resul ts[i].ftp_ Medication APIURL !=  null) { vc mn_Medicat ionApiUrl  = vcmn_set tingData.d .results[i ].ftp_Medi cationAPIU RL; }
  239                break;
  240           }
  241  
  242           if  (vcmn_Dac Url != nul l && vcmn_ NotesWrite ApiUrl !=  null) {
  243                //Constr uct full w eb service  URL
  244                vcmn_Not eWriteUrl  = vcmn_Dac Url + vcmn _NotesWrit eApiUrl;
  245           }
  246           el se {
  247                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 ", "APISER VICE");
  248           }
  249  
  250           if  (vcmn_Dac Url != nul l && vcmn_ Enrollment Eligibilit ySummaryAp iUrl != nu ll) {
  251                //Constr uct full w eb service  URL
  252                vcmn_Enr ollmentEli gibilitySu mmaryURLba se = vcmn_ DacUrl + v cmn_Enroll mentEligib ilitySumma ryApiUrl;
  253           }
  254           el se {
  255                Xrm.Page .ui.setFor mNotificat ion("ERROR : THE ENRO LLMENT ELI GIBILITY S UMMARY WEB  SERVICE U RL IS MISS ING, PLEAS E CONTACT  TECHNICAL  SUPPORT!",  "ERROR",  "APISERVIC E");
  256           }
  257  
  258           if  (vcmn_Dac Url != nul l && vcmn_ VistaUserA piUrl != n ull) {
  259                //Constr uct full w eb service  URL
  260                vcmn_Vis taUsersURL base = vcm n_DacUrl +  vcmn_Vist aUserApiUr l;
  261           }
  262           el se {
  263                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 ");
  264           }
  265           if  (vcmn_Dac Url != nul l && vcmn_ ViaAddlSig nersApiUrl  != null)  {
  266                //Constr uct full w eb service  URL
  267                vcmn_Add SignersUrl  = vcmn_Da cUrl + vcm n_ViaAddlS ignersApiU rl;
  268           }
  269           el se {
  270                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");
  271           }
  272           if  (vcmn_Dac Url != nul l && vcmn_ Appointmen tApiUrl !=  null) {
  273                //Constr uct full w eb service  URL
  274                vcmn_App ointmentsU rl = vcmn_ DacUrl + v cmn_Appoin tmentApiUr l;
  275           }
  276           el se {
  277                Xrm.Page .ui.setFor mNotificat ion("ERROR : THE APPO INTMENT AP I WEB SERV ICE URL IS  MISSING,  PLEASE CON TACT TECHN ICAL SUPPO RT!", "ERR OR", "APIS ERVICE");
  278           }
  279           if  (vcmn_Dac Url != nul l && vcmn_ Medication ApiUrl !=  null) {
  280                //Constr uct full w eb service  URL
  281                vcmn_Med icationsUr l = vcmn_D acUrl + vc mn_Medicat ionApiUrl;
  282           }
  283           el se {
  284                Xrm.Page .ui.setFor mNotificat ion("ERROR : THE MEDI CATION API  WEB SERVI CE URL IS  MISSING, P LEASE CONT ACT TECHNI CAL SUPPOR T!", "ERRO R", "APISE RVICE");
  285           }
  286  
  287           if  (vcmn_bas eServiceEn dpointUrl  == null ||  vcmn_requ estingApp  == null ||  vcmn_cons umingAppTo ken == nul l || vcmn_ consumingA ppPassword  == null)  {
  288                Xrm.Page .ui.setFor mNotificat ion("ERROR : THE 'VIA  Service C onnector'  CONFIGURAT ION IS MIS SING DATA  IN THE 'Se ttings Ent ity', PLEA SE CONTACT  TECHNICAL  SUPPORT!" , "ERROR",  "VISTASER VICE");
  289           }
  290           // Decrypt VI A Service  Connector  Items
  291           vc mn_request ingApp = v cmn_decryp tServiceCo nnector(vc mn_request ingApp, 4) ;
  292           vc mn_consumi ngAppToken  = vcmn_de cryptServi ceConnecto r(vcmn_con sumingAppT oken, 6);
  293           vc mn_consumi ngAppPassw ord = vcmn _decryptSe rviceConne ctor(vcmn_ consumingA ppPassword , 8);
  294  
  295           // Proceed wi th Form Lo ad logic w ith URL
  296           vc mn_newProg ressNoteLo ad_WebURL( );
  297       }
  298       catch  (err) {
  299           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_Sett ingsWebSer viceURL_re sponse): '  + err.mes sage);
  300       }
  301   }
  302  
  303   function v cmn_newPro gressNoteL oad() {
  304       try {
  305           // GET CRM SE TTINGS WEB  SERVICE U RLS
  306           va r vcmn_con ditionalFi lter = "(m cs_name eq  'Active S ettings')" ;
  307           vc mn_getMult ipleEntity DataAsync( 'mcs_setti ngSet', 'f tp_DACURL,  ftp_Notes WriteAPIUR L, ftp_ESR Enrollment Eligibilit ySummaryAP IURL, ftp_ VistaUsers APIURL, ft p_IsProduc tionEnviro nment, ftp _VIAAdditi onalSigner sURL, ftp_ VIAService BaseURL, f tp_VIARequ estingAppl icationCod e, ftp_VIA ConsumingA pplication Token, ftp _VIAConsum ingApplica tionPasswo rd, ftp_Ap pointmentA PIURL, ftp _Medicatio nAPIURL',  vcmn_condi tionalFilt er, 'mcs_n ame', 'asc ', 0, vcmn _SettingsW ebServiceU RL_respons e, vcmn_No teWriteUrl );
  308       }
  309       catch  (err) {
  310           // Display Er ror
  311           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_newP rogressNot eLoad): '  + err.mess age);
  312       }
  313   }
  314  
  315   function v cmn_newPro gressNoteL oad_WebURL () {
  316       try {
  317           // Check if m arked as a  workload  encounter
  318           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) == true)  {
  319                vcmn_isW orkloadEnc ounter = t rue;
  320                Xrm.Page .ui.tabs.g et('Tab_Wo rkloadEnco unter').se tVisible(t rue);
  321                Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itletext") .setRequir edLevel("r equired");
  322                Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat iontext"). setRequire dLevel("re quired");
  323                Xrm.Page .getAttrib ute("ftp_w orkloadinp atient").s etRequired Level("req uired");
  324                Xrm.Page .getAttrib ute("ftp_c ptcode").s etRequired Level("req uired");
  325                Xrm.Page .getAttrib ute("ftp_d iagnosisco de").setRe quiredLeve l("require d");
  326                //Set Si gn this no te to Yes
  327                Xrm.Page .getAttrib ute('ftp_s ignthisnot e').setVal ue(1000000 01);
  328                Xrm.Page .getAttrib ute('ftp_s ignthisnot e').setSub mitMode('a lways');
  329                //Histor ical Note  Settings
  330                Xrm.Page .ui.tabs.g et('Tab_Hi storicalNo te').setVi sible(fals e);
  331                Xrm.Page .getAttrib ute("ftp_n otehospita llocation" ).setRequi redLevel(" none");
  332                Xrm.Page .getAttrib ute("ftp_l ocalnoteti tle").setR equiredLev el("none") ;
  333           }
  334           el se {
  335                vcmn_isW orkloadEnc ounter = f alse;
  336                Xrm.Page .ui.tabs.g et('Tab_Wo rkloadEnco unter').se tVisible(f alse);
  337                Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itletext") .setRequir edLevel("n one");
  338                Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat iontext"). setRequire dLevel("no ne");
  339                Xrm.Page .getAttrib ute("ftp_w orkloadinp atient").s etRequired Level("non e");
  340                Xrm.Page .getAttrib ute("ftp_c ptcode").s etRequired Level("non e");
  341                Xrm.Page .getAttrib ute("ftp_d iagnosisco de").setRe quiredLeve l("none");
  342                //Histor ical Note  Settings
  343                Xrm.Page .ui.tabs.g et('Tab_Hi storicalNo te').setVi sible(true );
  344                Xrm.Page .getAttrib ute("ftp_n otehospita llocation" ).setRequi redLevel(" required") ;
  345                Xrm.Page .getAttrib ute("ftp_l ocalnoteti tle").setR equiredLev el("requir ed");
  346           }
  347  
  348           // Set defaul t values b ased on th e current  user's USD  Config an d Facility
  349           va r vcmn_cur rentUserId  = Xrm.Pag e.context. getUserId( );
  350           va r vcmn_cur rentUserDa ta = vcmn_ getSingleE ntityDataS ync('Syste mUserSet',  'msdyusd_ USDConfigu rationId,  ftp_Facili tySiteId',  vcmn_curr entUserId) ;
  351           if  (vcmn_cur rentUserDa ta != null ) {
  352                if (vcmn _currentUs erData.d.m sdyusd_USD Configurat ionId != n ull) {
  353                    if ( vcmn_curre ntUserData .d.msdyusd _USDConfig urationId. Id != null ) {
  354                         if (vcmn_c urrentUser Data.d.msd yusd_USDCo nfiguratio nId.Name ! = null &&  vcmn_curre ntUserData .d.msdyusd _USDConfig urationId. Name != '' ) {
  355                             if (vc mn_current UserData.d .msdyusd_U SDConfigur ationId.Na me == "Pha rmacy Conf iguration" ) {
  356                                 // Set Local  Title View  to Pharma cy
  357                                 Xr m.Page.get Control("f tp_localno tetitle"). setDefault View("{AF5 A2EBB-A22A -E711-944E -0050568D7 43D}");
  358                                 // Dev Test
  359                                 // Xrm.Page.g etControl( "ftp_local notetitle" ).setDefau ltView("{D CEC6C83-B5 34-E711-82 43-000C29F F8C5B}");
  360                             }
  361                         }
  362                         //Retrieve  Facillity  Group Def ault info
  363                         if (vcmn_c urrentUser Data.d.ftp _FacilityS iteId != n ull) {
  364                             if (vc mn_current UserData.d .ftp_Facil itySiteId. Id != null ) {
  365                                 // Data Requi red to loo kup Facili ty Group D efaults ar e present
  366                                 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 + "')";
  367                                 vc mn_getMult ipleEntity DataAsync( 'ftp_facil itygroupde faultSet',  'ftp_loca lnotestitl e, ftp_hos pitallocat ion, ftp_f acilitygro updefaultI d, ftp_via workloaden counterloc ationdefau lt, ftp_vi aworkloade ncounterno tetitledef ault, ftp_ historical locationde fault, ftp _historica lnotetitle default',  vcmn_condi tionalFilt er, 'ftp_n ame', 'asc ', 0, vcmn _facilityG roupDefaul t_response , vcmn_cur rentUserDa ta.d.ftp_F acilitySit eId.Id);
  368                             }
  369                         }
  370                    }
  371                }
  372           }
  373  
  374           // Only handl e forms in  create st ate
  375           if  (Xrm.Page .ui.getFor mType() !=  1) { retu rn false;  }
  376  
  377           // Determine  if regardi ng field i s prefille d (added b y subgrid+ )
  378           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  379           va r vcmn_tri ageexpert  = null;
  380           va r vcmn_tri ageminutes  = null;
  381           if  (vcmn_req uestId ==  null) {
  382                //Get cu stom param eters pass ed to the  form
  383                var vcmn _regarding objectid =  vcmn_getQ ueryVariab le("parame ter_regard ingobjecti d");
  384                var vcmn _regarding objectidna me = vcmn_ getQueryVa riable("pa rameter_re gardingobj ectidname" );
  385                var vcmn _regarding objectidty pe = vcmn_ getQueryVa riable("pa rameter_re gardingobj ectidtype" );
  386                vcmn_tri ageexpert  = vcmn_get QueryVaria ble("param eter_triag eexpert");
  387                vcmn_tri ageminutes  = vcmn_ge tQueryVari able("para meter_tria geminutes" );
  388  
  389                if (vcmn _regarding objectid = = '' || vc mn_regardi ngobjectid  == null | | vcmn_reg ardingobje ctidname = = '' || vc mn_regardi ngobjectid name == nu ll ||
  390                    vcmn _regarding objectidty pe == '' | | vcmn_reg ardingobje ctidtype = = null) {  return fal se; }
  391           }
  392           el se {
  393                var vcmn _regarding objectid =  vcmn_requ estId[0].i d;
  394                var vcmn _regarding objectidna me = vcmn_ requestId[ 0].name;
  395                var vcmn _regarding objectidty pe = vcmn_ requestId[ 0].entityT ype;
  396           }
  397           if  (vcmn_tri ageexpert  == null) {  vcmn_tria geexpert =  'NO'; }
  398           if  (vcmn_tri ageminutes  == null)  { vcmn_tri ageminutes  = 0; }
  399  
  400           // Populate r egarding o bject
  401           vc mn_setSimp leLookupVa lue('regar dingobject id', vcmn_ regardingo bjectidtyp e, vcmn_re gardingobj ectid, vcm n_regardin gobjectidn ame);
  402           Xr m.Page.get Attribute( 'regarding objectid') .setSubmit Mode('alwa ys');
  403  
  404           // Refresh th e Request  Notes Cont rol, since  it's poss ible that  the regard ingobjecti d was miss ing during  initial l oad
  405           Xr m.Page.get Control("W ebResource _RequestNo tesControl ").setSrc( Xrm.Page.g etControl( "WebResour ce_Request NotesContr ol").getSr c());
  406  
  407           // Prompt use r if progr ess note i s a worklo ad encount er except  when a Tri age Note
  408           if  (vcmn_tri ageexpert  == 'NO') {
  409                Xrm.Util ity.confir mDialog(
  410                    "Is  this note  a Workload  Encounter ?, Select  OK if Yes,  otherwise  CANCEL.",
  411                    func tion () {
  412                         Xrm.Page.g etAttribut e('ftp_isw orkloadenc ounter').s etValue(tr ue);
  413                         Xrm.Page.g etAttribut e('ftp_isw orkloadenc ounter').s etSubmitMo de('always ');
  414                         //Display  workload e ncounter t ab and oth er info ac cordingly. ..
  415                         Xrm.Page.u i.tabs.get ('Tab_Work loadEncoun ter').setV isible(tru e);
  416                         vcmn_isWor kloadEncou nter = tru e;
  417                         Xrm.Page.g etAttribut e("ftp_sel ectedworkl oadnotetit letext").s etRequired Level("req uired");
  418                         Xrm.Page.g etAttribut e("ftp_sel ectedworkl oadlocatio ntext").se tRequiredL evel("requ ired");
  419                         Xrm.Page.g etAttribut e("ftp_wor kloadinpat ient").set RequiredLe vel("requi red");
  420                         Xrm.Page.g etAttribut e("ftp_cpt code").set RequiredLe vel("requi red");
  421                         Xrm.Page.g etAttribut e("ftp_dia gnosiscode ").setRequ iredLevel( "required" );
  422                         //Historic al Note Se ttings
  423                         Xrm.Page.u i.tabs.get ('Tab_Hist oricalNote ').setVisi ble(false) ;
  424                         Xrm.Page.g etAttribut e("ftp_not ehospitall ocation"). setRequire dLevel("no ne");
  425                         Xrm.Page.g etAttribut e("ftp_loc alnotetitl e").setReq uiredLevel ("none");
  426                    }
  427                );
  428           }
  429           el se {
  430                Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .setValue( true);
  431                Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .setSubmit Mode('alwa ys');
  432                //Displa y workload  encounter  tab and o ther info  accordingl y...
  433                Xrm.Page .ui.tabs.g et('Tab_Wo rkloadEnco unter').se tVisible(t rue);
  434                vcmn_isW orkloadEnc ounter = t rue;
  435                Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itletext") .setRequir edLevel("r equired");
  436                Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat iontext"). setRequire dLevel("re quired");
  437                Xrm.Page .getAttrib ute("ftp_w orkloadinp atient").s etRequired Level("req uired");
  438                Xrm.Page .getAttrib ute("ftp_c ptcode").s etRequired Level("req uired");
  439                Xrm.Page .getAttrib ute("ftp_d iagnosisco de").setRe quiredLeve l("require d");
  440                //Histor ical Note  Settings
  441                Xrm.Page .ui.tabs.g et('Tab_Hi storicalNo te').setVi sible(fals e);
  442                Xrm.Page .getAttrib ute("ftp_n otehospita llocation" ).setRequi redLevel(" none");
  443                Xrm.Page .getAttrib ute("ftp_l ocalnoteti tle").setR equiredLev el("none") ;
  444           }
  445  
  446           // If Histori cal Encoun ter
  447           if  (vcmn_isW orkloadEnc ounter ==  false) {
  448                Xrm.Page .ui.tabs.g et('Tab_Hi storicalNo te').setVi sible(true );
  449                Xrm.Page .getAttrib ute("ftp_n otehospita llocation" ).setRequi redLevel(" required") ;
  450                Xrm.Page .getAttrib ute("ftp_l ocalnoteti tle").setR equiredLev el("requir ed");
  451           }
  452  
  453           // Populate s ubject wit h regardin g objects  title
  454           Xr m.Page.get Attribute( 'subject') .setValue( vcmn_Progr essNoteSub ject + vcm n_regardin gobjectidn ame);
  455           if  (vcmn_tri ageexpert  == 'YES')  { Xrm.Page .getAttrib ute('subje ct').setVa lue(vcmn_T riageNoteS ubject + v cmn_regard ingobjecti dname); }
  456           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) == true)  { Xrm.Pag e.getAttri bute('subj ect').setV alue(vcmn_ WorkloadEn counterSub ject + vcm n_regardin gobjectidn ame); }
  457           Xr m.Page.get Attribute( 'subject') .setSubmit Mode('alwa ys');
  458           // Default Sa ve to CPRS
  459           Xr m.Page.get Attribute( 'ftp_savet ovista').s etValue(10 0000001);  //Yes
  460           Xr m.Page.get Attribute( 'ftp_savet ovista').s etSubmitMo de('always ');
  461  
  462           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  463  
  464           // Populate f orm with r elated CRM  data
  465           va r vcmn_sub ReasonId =  null; //R eference t o the Reas on for Req uest Sub R eason
  466           va r vcmn_min orReasonId  = null;   //Referenc e to the R eason for  Request Mi nor Reason
  467           va r vcmn_sub ReasonTemp lateText =  null;
  468           va r vcmn_min orReasonTe mplateText  = null;
  469           va r vcmn_min orReasonNo teSubText  = null;
  470  
  471           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, ftp _rxtype, f tp_methodo frequest,  ftp_age, f tp_pcp, ft p_calccrcl , ftp_Late steGFRResu lt, ftp_la stdirectio nsonfile,  ftp_patien tstatesdir ections, f tp_directi onsby, ftp _veteranch angeddose,  ftp_other text, ftp_ lostorstol en, ftp_Tr ackingNumb er, ftp_Rx RefillQuan tity, ftp_ othercopay reversal,  ftp_reason forstoppin g, ftp_Qua ntityRepor tsTaking',  vcmn_rega rdingobjec tid);
  472           if  (vcmn_req uestData ! = null) {
  473                if (vcmn _requestDa ta.d.ftp_C allbackNum ber != nul l) {
  474                    Xrm. Page.getAt tribute('f tp_callbac knumber'). setValue(v cmn_reques tData.d.ft p_Callback Number);
  475                    Xrm. Page.getAt tribute('f tp_callbac knumber'). setSubmitM ode('alway s');
  476                }
  477                if (vcmn _requestDa ta.d.ftp_R easonforRe quest != n ull) {
  478                    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);
  479                    Xrm. Page.getAt tribute('f tp_reasonf orrequest' ).setSubmi tMode('alw ays');
  480                }
  481  
  482                if (vcmn _requestDa ta.d.ftp_R easonforRe quest.Name  == "Pharm acy Outbou nd Call")  {
  483                    if ( typeof out boundTempl ate_buildN oteText ==  "function ") {
  484                         outboundTe mplate_bui ldNoteText ();
  485                    }
  486                }
  487                    //** ***NON NAR COTIC*****
  488                else if  (vcmn_requ estData.d. ftp_Reason forRequest .Name == v cmn_nonNar coticReque stName ||  vcmn_regar dingobject idname.ind exOf(vcmn_ nonNarcoti cRequestNa me) > -1)  {
  489                    //De fine as No n Narcotic  Template
  490                    vcmn _nonNarcot icTemplate  = true;
  491                    //Co nstruct No n-Narcotic  Template  Text
  492                    var  vcmn_nonNa rcoticTemp lateText =  ""; // '- ---------- ----Medica tions Sele cted------ ---------- ---\n\n\n- ---------- ---------- ---------- ---------- ---------- ------';
  493                    //Do  Middle Se ction
  494                    if ( vcmn_reque stData.d.f tp_rxtype  != null) {
  495                         var vcmn_r xType = ""
  496                         if (vcmn_r equestData .d.ftp_rxt ype.Value  == 1000000 00) { vcmn _rxType =  "Refill";  }
  497                         if (vcmn_r equestData .d.ftp_rxt ype.Value  == 1000000 01) { vcmn _rxType =  "Renewal";  }
  498                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nVeter an is requ esting a "  + vcmn_rx Type;
  499                    }
  500                    if ( vcmn_reque stData.d.f tp_SubReas onId != nu ll) {
  501                         vcmn_subRe asonId = v cmn_reques tData.d.ft p_SubReaso nId.Id;
  502                         if (vcmn_s ubReasonId  != null)  {
  503                             //Get  Template T ext
  504                             var vc mn_subreas onData = v cmn_getSin gleEntityD ataSync('f tp_subreas onSet', 'f tp_notetex t', vcmn_s ubReasonId );
  505                             if (vc mn_subreas onData.d.f tp_notetex t != null)  {
  506                                 vc mn_subReas onTemplate Text = vcm n_subreaso nData.d.ft p_notetext ;
  507                             }
  508                         }
  509                    }
  510                    if ( vcmn_reque stData.d.f tp_MinorRe asonId !=  null) {
  511                         vcmn_minor ReasonId =  vcmn_requ estData.d. ftp_MinorR easonId.Id ;
  512                         if (vcmn_m inorReason Id != null ) {
  513                             //Get  Template T ext
  514                             var vc mn_minorre asonData =  vcmn_getS ingleEntit yDataSync( 'ftp_minor reasonSet' , 'ftp_nam e, ftp_not etext', vc mn_minorRe asonId);
  515                             if (vc mn_minorre asonData.d .ftp_name  != null) {
  516                                 vc mn_minorRe asonTempla teText = v cmn_minorr easonData. d.ftp_name ;
  517                             }
  518                             if (vc mn_minorre asonData.d .ftp_notet ext != nul l) {
  519                                 vc mn_minorRe asonNoteSu bText = vc mn_minorre asonData.d .ftp_notet ext;
  520                             }
  521                         }
  522                    }
  523                    if ( vcmn_reque stData.d.C ustomerId  != null) {
  524                         vcmn_setSi mpleLookup Value('ftp _patient',  vcmn_requ estData.d. CustomerId .LogicalNa me, vcmn_r equestData .d.Custome rId.Id, vc mn_request Data.d.Cus tomerId.Na me);
  525                         Xrm.Page.g etAttribut e('ftp_pat ient').set SubmitMode ('always') ;
  526                         //Set as v eteran id
  527                         vcmn_veter anId = vcm n_requestD ata.d.Cust omerId.Id
  528                    }
  529  
  530                    //Di splay sub- reason not e text
  531                    if ( vcmn_subRe asonTempla teText !=  null && vc mn_subReas onTemplate Text != "" ) {
  532                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\n" + v cmn_subRea sonTemplat eText;
  533                         if (vcmn_m inorReason NoteSubTex t != null  && vcmn_mi norReasonN oteSubText  != "") {
  534                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\n"  + vcmn_mi norReasonN oteSubText ;
  535                             if (vc mn_minorRe asonNoteSu bText == " Medication  used to t reat servi ce connect ed conditi ons") {
  536                                 // Add Servic e Connecte d Disabili ties TAG f or later u pdate from  function
  537                                 vc mn_nonNarc oticTempla teText = v cmn_nonNar coticTempl ateText +  "\n" +
  538                                      "~~~~SCD TAG~~~~";
  539                             }
  540                         }
  541                    }
  542  
  543                    //In cluded req uired fiel ds in temp late based  on sub an d minor re asons
  544                    if ( (vcmn_subR easonTempl ateText ==  "Veteran  is request ing a rene wal of a m edication  no longer  on their m edication  profile" & &
  545                         vcmn_minor ReasonNote SubText ==  "Medicati on dose ch ange or wa s taking d ifferently  than pres cribed. Pa tient stat ed they ha ve been ta king regul arly")
  546                         || (vcmn_s ubReasonTe mplateText  == "Medic ation dose  change or  taken dif ferently t han prescr ibed")) {
  547  
  548                         if (vcmn_r equestData .d.ftp_las tdirection sonfile !=  null) {
  549                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nL ast Direct ions On Fi le: " + vc mn_request Data.d.ftp _lastdirec tionsonfil e;
  550                         }
  551                         if (vcmn_r equestData .d.ftp_pat ientstates directions  != null)  {
  552                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nP atient Sta tes Direct ions: " +  vcmn_reque stData.d.f tp_patient statesdire ctions;
  553                         }
  554                         if (vcmn_r equestData .d.ftp_dir ectionsby  != null) {
  555                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nD irections  by: " + vc mn_request Data.d.ftp _direction sby;
  556                         }
  557                         if (vcmn_r equestData .d.ftp_vet eranchange ddose != n ull) {
  558                             var vc mn_veteran ChangedDos e = null;
  559                             if (vc mn_request Data.d.ftp _veteranch angeddose  == false)  { vcmn_vet eranChange dDose = "N o"; }
  560                             if (vc mn_request Data.d.ftp _veteranch angeddose  == true) {  vcmn_vete ranChanged Dose = "Ye s"; }
  561                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nV eteran Cha nged Dose:  " + vcmn_ veteranCha ngedDose;
  562                         }
  563                    }
  564                    if ( vcmn_subRe asonTempla teText ==  "Other:")  {
  565                         if (vcmn_r equestData .d.ftp_oth ertext !=  null) {
  566                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nO ther Text:  " + vcmn_ requestDat a.d.ftp_ot hertext;
  567                         }
  568                    }
  569                    if ( vcmn_subRe asonTempla teText ==  "Veteran i s requesti ng medicat ion replac ement" &&  vcmn_minor ReasonNote SubText ==  "Medicati on lost or  stolen")  {
  570                         if (vcmn_r equestData .d.ftp_los torstolen  != null) {
  571                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nL ost or Sto len: " + v cmn_reques tData.d.ft p_lostorst olen;
  572                         }
  573                    }
  574                    if ( vcmn_subRe asonTempla teText ==  "Veteran i s requesti ng medicat ion replac ement" &&  vcmn_minor ReasonNote SubText ==  "Medicati on never a rrived in  mail. Trac king #:")  {
  575                         if (vcmn_r equestData .d.ftp_Tra ckingNumbe r != null)  {
  576                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nT racking Nu mber: " +  vcmn_reque stData.d.f tp_Trackin gNumber;
  577                         }
  578                    }
  579                    if ( vcmn_subRe asonTempla teText ==  "Veteran r equesting  refill qua ntity to b e changed  to a _____  day suppl y") {
  580                         if (vcmn_r equestData .d.ftp_RxR efillQuant ity != nul l) {
  581                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nR x Refill Q uantity: "  + vcmn_re questData. d.ftp_RxRe fillQuanti ty;
  582                         }
  583                    }
  584                    if ( vcmn_subRe asonTempla teText ==  "Veteran r equests me dication c opay rever sal" && vc mn_minorRe asonNoteSu bText == " Other:") {
  585                         if (vcmn_r equestData .d.ftp_oth ercopayrev ersal != n ull) {
  586                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nO ther (copa y reversal ): " + vcm n_requestD ata.d.ftp_ othercopay reversal;
  587                         }
  588                    }
  589                    if ( vcmn_subRe asonTempla teText ==  "Veteran h as stopped  taking th e medicati on") {
  590                         if (vcmn_r equestData .d.ftp_rea sonforstop ping != nu ll) {
  591                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nR eason for  Stopping:  " + vcmn_r equestData .d.ftp_rea sonforstop ping;
  592                         }
  593                    }
  594                    if ( (vcmn_subR easonTempl ateText ==  "Medicati on request ing early  refill:" & &
  595                         vcmn_minor ReasonNote SubText ==  "Veteran  has been r equiring e xtra medic ation and  is taking  more than  prescribed  (reports  taking ___ _____ tabl ets / caps ules per d ay):")
  596                         || (vcmn_s ubReasonTe mplateText  == "Veter an is requ esting a p artial fil l" &&
  597                         vcmn_minor ReasonNote SubText ==  "Veteran  has been r equiring e xtra medic ation and  is taking  more than  prescribed  (reports  taking ___ _____ tabl ets / caps ules per d ay)")) {
  598                         if (vcmn_r equestData .d.ftp_Qua ntityRepor tsTaking ! = null) {
  599                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nQ uantity Re ports Taki ng: " + vc mn_request Data.d.ftp _QuantityR eportsTaki ng;
  600                         }
  601                    }
  602  
  603                    //Al ways inclu de last fi lled
  604                    if ( vcmn_reque stData.d.f tp_LastFil led != nul l) {
  605                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nLast  Filled: "  + new Date (parseInt( vcmn_reque stData.d.f tp_LastFil led.toStri ng().repla ce("/Date( ", "").rep lace(")/",  ""), 10)) ;
  606                    }
  607  
  608                    //Do  Bottom Se ction
  609                    vcmn _nonNarcot icTemplate Text = vcm n_nonNarco ticTemplat eText + "\ n";
  610                    if ( vcmn_reque stData.d.f tp_methodo frequest ! = null) {
  611                         var vcmn_m ethodOfReq uest = "";
  612                         if (vcmn_r equestData .d.ftp_met hodofreque st.Value = = 10000000 0) { vcmn_ methodOfRe quest = "P hone"; }
  613                         if (vcmn_r equestData .d.ftp_met hodofreque st.Value = = 10000000 1) { vcmn_ methodOfRe quest = "I n Person";  }
  614                         if (vcmn_r equestData .d.ftp_met hodofreque st.Value = = 10000000 2) { vcmn_ methodOfRe quest = "M ail"; }
  615                         if (vcmn_r equestData .d.ftp_met hodofreque st.Value = = 10000000 3) { vcmn_ methodOfRe quest = "I nternet";  }
  616                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nMetho d of Reque st: " + vc mn_methodO fRequest;
  617                    }
  618                    if ( vcmn_reque stData.d.f tp_pickupm ethod != n ull) {
  619                         var vcmn_p ickupmetho d = vcmn_r equestData .d.ftp_pic kupmethod. Value;
  620                         if (vcmn_p ickupmetho d == 10000 0000) {
  621                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nP ick-Up Met hod: " + " Mail";
  622                         }
  623                         if (vcmn_p ickupmetho d == 10000 0001) {
  624                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nP ick-Up Met hod: " + " Window *** **";
  625                         }
  626                    }
  627                    //Ge t veteran' s current  address
  628                    if ( vcmn_veter anId != nu ll) {
  629                         var vcmn_c ontactData  = vcmn_ge tSingleEnt ityDataSyn c('Contact Set', 'Add ress1_Comp osite', vc mn_veteran Id);
  630                         if (vcmn_c ontactData  != null)  {
  631                             if (vc mn_contact Data.d.Add ress1_Comp osite != n ull && vcm n_contactD ata.d.Addr ess1_Compo site != '' ) {
  632                                 vc mn_nonNarc oticTempla teText = v cmn_nonNar coticTempl ateText +  "\n\nAddre ss confirm ed:";
  633                                 vc mn_nonNarc oticTempla teText = v cmn_nonNar coticTempl ateText +  "\n" + vcm n_contactD ata.d.Addr ess1_Compo site;
  634                             }
  635                         }
  636                    }
  637                    if ( Xrm.Page.g etAttribut e('ftp_cal lbacknumbe r').getVal ue() != nu ll) {
  638                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nCallb ack Number : " + Xrm. Page.getAt tribute('f tp_callbac knumber'). getValue()  + "\n";
  639                    }
  640                    if ( vcmn_reque stData.d.f tp_age !=  null) {
  641                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nAge:  " + vcmn_r equestData .d.ftp_age ;
  642                    }
  643                    if ( vcmn_reque stData.d.f tp_pcp !=  null) {
  644                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nPCP:  " + vcmn_r equestData .d.ftp_pcp ;
  645                    }
  646                    if ( vcmn_reque stData.d.f tp_calccrc l != null)  {
  647                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nCalc  CrCl: " +  vcmn_reque stData.d.f tp_calccrc l;
  648                    }
  649                    if ( vcmn_reque stData.d.f tp_Lateste GFRResult  != null) {
  650                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nLates t eGFR: "  + vcmn_req uestData.d .ftp_Lates teGFRResul t;
  651                    }
  652  
  653                    //Wr ite Non Na rcotic Tem plate Text  as long a s it is no t a Triage
  654                    if ( vcmn_triag eexpert ==  'NO' || v cmn_triage expert ==  null) {
  655                         Xrm.Page.g etAttribut e("ftp_not edetail"). setValue(v cmn_nonNar coticTempl ateText);
  656                         Xrm.Page.g etAttribut e("ftp_not edetail"). setSubmitM ode("alway s");
  657                    }
  658                }
  659                    //** ***NON NAR COTIC END* ****
  660  
  661                    //** ***STANDAR D TEMPLATE  START**** *
  662                else {
  663                    if ( vcmn_reque stData.d.f tp_SubReas onId != nu ll) {
  664                         vcmn_subRe asonId = v cmn_reques tData.d.ft p_SubReaso nId.Id;
  665                         if (vcmn_s ubReasonId  != null)  {
  666                             //Get  Template T ext
  667                             var vc mn_subreas onData = v cmn_getSin gleEntityD ataSync('f tp_subreas onSet', 'f tp_notetex t', vcmn_s ubReasonId );
  668                             if (vc mn_subreas onData.d.f tp_notetex t != null)  {
  669                                 vc mn_subReas onTemplate Text = vcm n_subreaso nData.d.ft p_notetext ;
  670                             }
  671                         }
  672                    }
  673                    if ( vcmn_reque stData.d.f tp_MinorRe asonId !=  null) {
  674                         vcmn_minor ReasonId =  vcmn_requ estData.d. ftp_MinorR easonId.Id ;
  675                         if (vcmn_m inorReason Id != null ) {
  676                             //Get  Template T ext
  677                             var vc mn_minorre asonData =  vcmn_getS ingleEntit yDataSync( 'ftp_minor reasonSet' , 'ftp_nam e, ftp_not etext', vc mn_minorRe asonId);
  678                             if (vc mn_minorre asonData.d .ftp_name  != null) {
  679                                 vc mn_minorRe asonTempla teText = v cmn_minorr easonData. d.ftp_name ;
  680                             }
  681                             if (vc mn_minorre asonData.d .ftp_notet ext != nul l) {
  682                                 vc mn_minorRe asonNoteSu bText = vc mn_minorre asonData.d .ftp_notet ext;
  683                             }
  684                         }
  685                    }
  686  
  687                    if ( vcmn_reque stData.d.C ustomerId  != null) {
  688                         vcmn_setSi mpleLookup Value('ftp _patient',  vcmn_requ estData.d. CustomerId .LogicalNa me, vcmn_r equestData .d.Custome rId.Id, vc mn_request Data.d.Cus tomerId.Na me);
  689                         Xrm.Page.g etAttribut e('ftp_pat ient').set SubmitMode ('always') ;
  690                         //Set as v eteran id
  691                         vcmn_veter anId = vcm n_requestD ata.d.Cust omerId.Id
  692                    }
  693  
  694                    //Co nstruct Te mplate Not e
  695                    var  vcmn_subRe asonName =  null;
  696                    var  vcmn_templ ateNote =  "";
  697                    var  vcmn_lastF illed = "" ;
  698                    var  vcmn_quant ityReports Taking = n ull;
  699                    var  vcmn_rxNum ber = null ;
  700                    var  vcmn_rxRef illQuantit y = null;
  701                    var  vcmn_track ingNumber  = null;
  702                    var  vcmn_opioi dAgreement Onfile = n ull;
  703                    var  vcmn_UDSon file = nul l;
  704                    var  vcmn_state DrugMonito ringReport  = null;
  705                    var  vcmn_spdmp stateonfil e = null;
  706                    var  vcmn_sPDMP State2 = n ull;
  707                    var  vcmn_picku pmethod =  null;
  708  
  709                    var  vcmn_early RefillComm ent = null ;
  710                    var  vcmn_quant ityTaking  = null;
  711                    var  vcmn_vacat ionStart =  null;
  712                    var  vcmn_vacat ionEnd = n ull;
  713  
  714                    if ( vcmn_reque stData.d.f tp_LastFil led != nul l) { vcmn_ lastFilled  = new Dat e(parseInt (vcmn_requ estData.d. ftp_LastFi lled.toStr ing().repl ace("/Date (", "").re place(")/" , ""), 10) ); }
  715                    if ( vcmn_reque stData.d.f tp_Quantit yReportsTa king != nu ll) { vcmn _quantityR eportsTaki ng = vcmn_ requestDat a.d.ftp_Qu antityRepo rtsTaking;  }
  716                    if ( vcmn_reque stData.d.f tp_RxNumbe r != null)  { vcmn_rx Number = v cmn_reques tData.d.ft p_RxNumber ; }
  717                    if ( vcmn_reque stData.d.f tp_RxRefil lQuantity  != null) {  vcmn_rxRe fillQuanti ty = vcmn_ requestDat a.d.ftp_Rx RefillQuan tity; }
  718                    if ( vcmn_reque stData.d.f tp_Trackin gNumber !=  null) { v cmn_tracki ngNumber =  vcmn_requ estData.d. ftp_Tracki ngNumber;  }
  719                    if ( vcmn_reque stData.d.f tp_OpiodAg reementOnf ile != nul l) { vcmn_ opioidAgre ementOnfil e = vcmn_r equestData .d.ftp_Opi odAgreemen tOnfile.Va lue; }
  720                    if ( vcmn_reque stData.d.f tp_UDSonfi le != null ) { vcmn_U DSonfile =  vcmn_requ estData.d. ftp_UDSonf ile.Value;  }
  721                    if ( vcmn_reque stData.d.f tp_StateDr ugMonitori ngReport ! = null) {  vcmn_state DrugMonito ringReport  = vcmn_re questData. d.ftp_Stat eDrugMonit oringRepor t.Value; }
  722                    if ( vcmn_reque stData.d.f tp_spdmpst ateonfile  != null) {  vcmn_spdm pstateonfi le = vcmn_ requestDat a.d.ftp_sp dmpstateon file.Value ; }
  723                    if ( vcmn_reque stData.d.f tp_SPDMPSt ate2 != nu ll) { vcmn _sPDMPStat e2 = vcmn_ requestDat a.d.ftp_SP DMPState2. Value; }
  724                    if ( vcmn_reque stData.d.f tp_pickupm ethod != n ull) { vcm n_pickupme thod = vcm n_requestD ata.d.ftp_ pickupmeth od.Value;  }
  725  
  726                    if ( vcmn_reque stData.d.f tp_earlyre fillcommen t != null)  { vcmn_ea rlyRefillC omment = v cmn_reques tData.d.ft p_earlyref illcomment ; }
  727                    if ( vcmn_reque stData.d.f tp_quantit ytaking !=  null) { v cmn_quanti tyTaking =  vcmn_requ estData.d. ftp_quanti tytaking;  }
  728                    if ( vcmn_reque stData.d.f tp_vacatio nstart !=  null) { vc mn_vacatio nStart = n ew Date(pa rseInt(vcm n_requestD ata.d.ftp_ vacationst art.toStri ng().repla ce("/Date( ", "").rep lace(")/",  ""), 10)) ; }
  729                    if ( vcmn_reque stData.d.f tp_vacatio nend != nu ll) { vcmn _vacationE nd = new D ate(parseI nt(vcmn_re questData. d.ftp_vaca tionend.to String().r eplace("/D ate(", "") .replace(" )/", ""),  10)); }
  730  
  731                    if ( vcmn_reque stData.d.f tp_SubReas onId != nu ll) {
  732                         vcmn_subRe asonId = v cmn_reques tData.d.ft p_SubReaso nId.Id;
  733                         vcmn_subRe asonName =  vcmn_requ estData.d. ftp_SubRea sonId.Name ;
  734  
  735                         if (vcmn_s ubReasonNa me == 'Reg ular') {
  736                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Veter an is requ esting a R ENEWAL." +  "\n\n";
  737                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Last  Filled: "  + vcmn_las tFilled +  "\n\n";
  738                             if (vc mn_pickupm ethod != n ull) {
  739                                 if  (vcmn_pic kupmethod  == 1000000 00) {
  740                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "\nPick- Up Method:  " + "Mail ";
  741                                 }
  742                                 if  (vcmn_pic kupmethod  == 1000000 01) {
  743                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "\nPick- Up Method:  " + "Wind ow *****";
  744                                 }
  745                             }
  746                             if (vc mn_minorRe asonTempla teText !=  null) {
  747                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  748                             }
  749                             if (vc mn_minorRe asonNoteSu bText != n ull) {
  750                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonNoteSu bText + "\ n\n";
  751                             }
  752                             if (vc mn_subReas onTemplate Text != nu ll) {
  753                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_subReas onTemplate Text + "\n \n";
  754                             }
  755                         }
  756  
  757                         if (vcmn_s ubReasonNa me == 'Ear ly') {
  758                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Veter an is requ esting EAR LY FILL."  + "\n\n";
  759                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Last  Filled: "  + vcmn_las tFilled +  "\n\n";
  760                             if (vc mn_minorRe asonTempla teText !=  null) {
  761                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  762                             }
  763  
  764                             if (vc mn_quantit yTaking !=  null) {
  765                                 vc mn_templat eNote = vc mn_templat eNote + "Q uantity Ta king: " +  vcmn_quant ityTaking  + "\n\n";
  766                             }
  767  
  768                             if (vc mn_vacatio nStart !=  null && vc mn_vacatio nEnd != nu ll) {
  769                                 vc mn_templat eNote = vc mn_templat eNote + "V eteran Lea ving Town:  " + vcmn_ vacationSt art + ' -  ' + vcmn_v acationEnd  + "\n\n";
  770                             }
  771  
  772                             if (vc mn_minorRe asonNoteSu bText != n ull) {
  773                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonNoteSu bText + "\ n\n";
  774                             }
  775                             if (vc mn_subReas onTemplate Text != nu ll) {
  776                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_subReas onTemplate Text + "\n \n";
  777                             }
  778                         }
  779  
  780                         if (vcmn_s ubReasonNa me == 'Los t') {
  781                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Veter an claims  prescripti ons(s) wer e LOST and  is reques ting a new  prescript ion/early  fill." + " \n\n";
  782                             if (vc mn_rxNumbe r != null)  {
  783                                 vc mn_templat eNote = vc mn_templat eNote + "R X#: " + vc mn_rxNumbe r + "\n\n" ;
  784                             }
  785                             if (vc mn_rxRefil lQuantity  != null) {
  786                                 vc mn_templat eNote = vc mn_templat eNote + "R x Refill Q uantity: "  + vcmn_rx RefillQuan tity + "\n \n";
  787                             }
  788                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Last  Filled: "  + vcmn_las tFilled +  "\n\n";
  789                             if (vc mn_minorRe asonTempla teText !=  null) {
  790                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  791                             }
  792                             if (vc mn_trackin gNumber !=  null) {
  793                                 vc mn_templat eNote = vc mn_templat eNote + "T racking Nu mber: " +  vcmn_track ingNumber  + "\n\n";
  794                             }
  795                             if (vc mn_minorRe asonNoteSu bText != n ull) {
  796                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonNoteSu bText + "\ n\n";
  797                             }
  798                             if (vc mn_subReas onTemplate Text != nu ll) {
  799                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_subReas onTemplate Text + "\n \n";
  800                             }
  801                         }
  802  
  803                         if (vcmn_s ubReasonNa me == 'Sto len') {
  804                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Veter an claims  prescripti ons(s) wer e STOLEN a nd is requ esting a n ew prescri ption/earl y fill." +  "\n\n";
  805                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Last  Filled: "  + vcmn_las tFilled +  "\n\n";
  806                             if (vc mn_minorRe asonTempla teText !=  null) {
  807                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  808                             }
  809                             if (vc mn_minorRe asonNoteSu bText != n ull) {
  810                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonNoteSu bText + "\ n\n";
  811                             }
  812                             if (vc mn_subReas onTemplate Text != nu ll) {
  813                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_subReas onTemplate Text + "\n \n";
  814                             }
  815                         }
  816  
  817                         if (vcmn_s ubReasonNa me == 'Req uesting Ho ld / Unhol d') {
  818                             if (vc mn_subReas onTemplate Text != nu ll) {
  819                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_subReas onTemplate Text + "\n \n";
  820                             }
  821                             if (vc mn_minorRe asonTempla teText !=  null) {
  822                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  823                             }
  824                             if (vc mn_request Data.d.ftp _rxtype !=  null) {
  825                                 va r vcmn_rxT ype = ""
  826                                 if  (vcmn_req uestData.d .ftp_rxtyp e.Value ==  100000000 ) { vcmn_r xType = "R efill"; }
  827                                 if  (vcmn_req uestData.d .ftp_rxtyp e.Value ==  100000001 ) { vcmn_r xType = "R enewal"; }
  828                                 vc mn_templat eNote = vc mn_templat eNote + "\ nRx Type:  " + vcmn_r xType;
  829                             }
  830                             vcmn_t emplateNot e = vcmn_t emplateNot e + "\nLas t Filled:  " + vcmn_l astFilled  + "\n\n";
  831                             if (vc mn_pickupm ethod != n ull) {
  832                                 if  (vcmn_pic kupmethod  == 1000000 00) {
  833                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "\nPick- Up Method:  " + "Mail ";
  834                                 }
  835                                 if  (vcmn_pic kupmethod  == 1000000 01) {
  836                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "\nPick- Up Method:  " + "Wind ow *****";
  837                                 }
  838                             }
  839                             if (vc mn_request Data.d.ftp _othertext  != null)  {
  840                                 vc mn_templat eNote = vc mn_templat eNote + "\ nOther Tex t: " + vcm n_requestD ata.d.ftp_ othertext;
  841                             }
  842                             if (vc mn_request Data.d.ftp _methodofr equest !=  null) {
  843                                 va r vcmn_met hodOfReque st = "";
  844                                 if  (vcmn_req uestData.d .ftp_metho dofrequest .Value ==  100000000)  { vcmn_me thodOfRequ est = "Pho ne"; }
  845                                 if  (vcmn_req uestData.d .ftp_metho dofrequest .Value ==  100000001)  { vcmn_me thodOfRequ est = "In  Person"; }
  846                                 if  (vcmn_req uestData.d .ftp_metho dofrequest .Value ==  100000002)  { vcmn_me thodOfRequ est = "Mai l"; }
  847                                 if  (vcmn_req uestData.d .ftp_metho dofrequest .Value ==  100000003)  { vcmn_me thodOfRequ est = "Int ernet"; }
  848                                 vc mn_templat eNote = vc mn_templat eNote + "\ nMethod of  Request:  " + vcmn_m ethodOfReq uest;
  849                             }
  850                             if (vc mn_request Data.d.ftp _age != nu ll) {
  851                                 vc mn_templat eNote = vc mn_templat eNote + "\ nAge: " +  vcmn_reque stData.d.f tp_age;
  852                             }
  853                             if (vc mn_request Data.d.ftp _pcp != nu ll) {
  854                                 vc mn_templat eNote = vc mn_templat eNote + "\ nPCP: " +  vcmn_reque stData.d.f tp_pcp;
  855                             }
  856                             if (vc mn_request Data.d.ftp _calccrcl  != null) {
  857                                 vc mn_templat eNote = vc mn_templat eNote + "\ nCalc CrCl : " + vcmn _requestDa ta.d.ftp_c alccrcl;
  858                             }
  859                             if (vc mn_request Data.d.ftp _LatesteGF RResult !=  null) {
  860                                 vc mn_templat eNote = vc mn_templat eNote + "\ nLatest eG FR: " + vc mn_request Data.d.ftp _LatesteGF RResult;
  861                             }
  862                         }
  863  
  864                         //If Templ ate Text w as populat ed, fill i n addition al info...
  865                         if (vcmn_t emplateNot e != '') {
  866                             vcmn_t emplateNot e = vcmn_t emplateNot e + "\n___ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ _____\n\n" ;
  867                             //Is a n Opioid A greement c urrent and  onfile?
  868                             if (vc mn_opioidA greementOn file != nu ll) {
  869                                 vc mn_templat eNote = vc mn_templat eNote + "C onsent for  Long-Term  Opioid Th erapy for  Pain:\n";
  870                                 if  (vcmn_opi oidAgreeme ntOnfile = = 10000000 0) {
  871                                      //Yes Op tion
  872                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Yes  - See Pos tings\n\n" ;
  873                                 }
  874                                 if  (vcmn_opi oidAgreeme ntOnfile = = 10000000 1) {
  875                                      //No Opt ion
  876                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] No  - Veteran  does not h ave a sign ed Consent  for Long- Term Opioi d Therapy  for pain ( in Posting s).\nConse nt MUST be  reviewed  and signed  as soon a s possible .\n\n";
  877                                 }
  878                             }
  879                             //Is v alid Urine  Drug Scre en on-file ?
  880                             if (vc mn_UDSonfi le != null ) {
  881                                 vc mn_templat eNote = vc mn_templat eNote + "I s valid Ur ine Drug S creen on-f ile?\n";
  882                                 if  (vcmn_UDS onfile ==  100000000)  {
  883                                      //Yes Op tion
  884                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Yes  - See Pos tings\n\n" ;
  885                                 }
  886                                 if  (vcmn_UDS onfile ==  100000001)  {
  887                                      //No Opt ion
  888                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] No  - Veteran  does not h ave a vali d Urine Dr ug Screen  on-file.\n \n";
  889                                 }
  890                             }
  891                             //Stat e Drug Mon itoring Re port?
  892                             if (vc mn_stateDr ugMonitori ngReport ! = null) {
  893                                 vc mn_templat eNote = vc mn_templat eNote + "S tate Presc ription Dr ug Monitor ing Progra m (SPDMP)  report com pleted in  last year: \n";
  894                                 if  (vcmn_sta teDrugMoni toringRepo rt == 1000 00000) {
  895                                      //Positi ve Option
  896                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Pos itive - se e SPDMP no te.\n\n";
  897                                 }
  898                                 if  (vcmn_sta teDrugMoni toringRepo rt == 1000 00001) {
  899                                      //Negati ve Option
  900                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Neg ative.\n\n ";
  901                                 }
  902                                 if  (vcmn_sta teDrugMoni toringRepo rt == 1000 00002) {
  903                                      //Not on  File Opti on
  904                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Non e on file,  Pharmacy  to request .\n\n";
  905                                 }
  906                                 // Add in Sta tes (2), c onvert int egers to s tate names  from form 's hidden  state opti ons
  907                                 va r vcmn_usS tatesOptio ns = Xrm.P age.getAtt ribute("ft p_usstates option").g etOptions( );
  908                                 va r vcmn_sta teList = " ";
  909                                 if  (vcmn_spd mpstateonf ile != nul l) {
  910                                      //find t ext value  for option
  911                                      $(vcmn_u sStatesOpt ions).each (function  (i, e) {
  912                                          var  vcmn_optio nText = $( this)[0].t ext;
  913                                          var  vcmn_optio nValue = $ (this)[0]. value;
  914                                          if ( vcmn_spdmp stateonfil e == vcmn_ optionValu e) { vcmn_ stateList  = vcmn_opt ionText; }
  915                                      });
  916                                 }
  917                                 if  (vcmn_sPD MPState2 ! = null) {
  918                                      //find t ext value  for option
  919                                      $(vcmn_u sStatesOpt ions).each (function  (i, e) {
  920                                          var  vcmn_optio nText = $( this)[0].t ext;
  921                                          var  vcmn_optio nValue = $ (this)[0]. value;
  922                                          if ( vcmn_sPDMP State2 ==  vcmn_optio nValue) {  vcmn_state List = vcm n_stateLis t + ", " +  vcmn_opti onText; }
  923                                      });
  924                                 }
  925                                 if  (vcmn_sta teList !=  "") {
  926                                      //Add st ates list  to note
  927                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "State P rescriptio n Drug Mon itoring Pr ogram for  the follow ing state( s): " + vc mn_stateLi st;
  928                                 }
  929                             }
  930  
  931                             //If f tp_pickupm ethod has  a value
  932                             if (vc mn_pickupm ethod != n ull && vcm n_subReaso nName != ' Regular' & & vcmn_sub ReasonName  != 'Reque sting Hold  / Unhold' ) {
  933                                 vc mn_templat eNote = vc mn_templat eNote + "\ n_________ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ _________\ n\n";
  934                                 vc mn_templat eNote = vc mn_templat eNote + "V eteran req uested Met hod of Pic k Up:  ";
  935                                 if  (vcmn_pic kupmethod  == 1000000 00) {
  936                                      //Mail O ption
  937                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Mai l. \n\n";
  938                                 }
  939                                 if  (vcmn_pic kupmethod  == 1000000 01) {
  940                                      //Window  Option
  941                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Win dow. \n\n" ;
  942                                 }
  943                                 // Get vetera n's curren t address
  944                                 if  (vcmn_vet eranId !=  null) {
  945                                      var vcmn _contactDa ta = vcmn_ getSingleE ntityDataS ync('Conta ctSet', 'A ddress1_Co mposite',  vcmn_veter anId);
  946                                      if (vcmn _contactDa ta != null ) {
  947                                          if ( vcmn_conta ctData.d.A ddress1_Co mposite !=  null && v cmn_contac tData.d.Ad dress1_Com posite !=  '') {
  948                                               vcmn_templ ateNote =  vcmn_templ ateNote +  "Address c onfirmed w ith caller : \n";
  949                                               vcmn_templ ateNote =  vcmn_templ ateNote +  vcmn_conta ctData.d.A ddress1_Co mposite +  "\n";
  950                                               if (Xrm.Pa ge.getAttr ibute('ftp _callbackn umber').ge tValue() ! = null) {
  951                                                   vcmn_t emplateNot e = vcmn_t emplateNot e + Xrm.Pa ge.getAttr ibute('ftp _callbackn umber').ge tValue();
  952                                               }
  953                                          }
  954                                      }
  955                                 }
  956                             }
  957                         }
  958  
  959                         //Write no te text if  not Triag e:
  960                         if (vcmn_t riageexper t == 'NO'  || vcmn_tr iageexpert  == null)  {
  961                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setVal ue(vcmn_te mplateNote );
  962                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setSub mitMode('a lways');
  963                         }
  964                    }
  965                }
  966                //*****S TANDARD TE MPLATE END *****
  967  
  968                //Defaul t Diagnosi s code if  TAN or PHA RMACY user , based on  systemuse r lookup
  969                var vcmn _currentUs erId = Xrm .Page.cont ext.getUse rId();
  970                var vcmn _currentUs erData = v cmn_getSin gleEntityD ataSync('S ystemUserS et', 'msdy usd_USDCon figuration Id, ftp_Fa cilitySite Id', vcmn_ currentUse rId);
  971                if (vcmn _currentUs erData !=  null) {
  972                    if ( vcmn_curre ntUserData .d.msdyusd _USDConfig urationId  != null) {
  973                         if (vcmn_c urrentUser Data.d.msd yusd_USDCo nfiguratio nId.Name ! = null) {
  974                             //TAN  logic
  975                             if (vc mn_current UserData.d .msdyusd_U SDConfigur ationId.Na me == 'TAN  Configura tion') {
  976                                 // Get Defaul t Tan Conf iguration  from User' s Facility
  977                                 if  (vcmn_cur rentUserDa ta.d.ftp_F acilitySit eId != nul l) {
  978                                      if (vcmn _currentUs erData.d.f tp_Facilit ySiteId.Id  != null)  {
  979                                          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);
  980                                          if ( vcmn_curre ntUserFaci lityData ! = null) {
  981                                               if (vcmn_c urrentUser FacilityDa ta.d.ftp_d efaulttand iagnosisco de != null ) {
  982                                                   if (vc mn_current UserFacili tyData.d.f tp_default tandiagnos iscode.Id  != null) {
  983                                                       // Write Diag nosis code  to Progre ss Note Fo rm if a Tr iage Note  (revised 5 /9-17 for  workload e ncounter a lso)
  984                                                       // *if (vcmn_ triageexpe rt == 'YES ') {
  985                                                       vc mn_setSimp leLookupVa lue('ftp_d iagnosisco de', vcmn_ currentUse rFacilityD ata.d.ftp_ defaulttan diagnosisc ode.Logica lName, vcm n_currentU serFacilit yData.d.ft p_defaultt andiagnosi scode.Id,  vcmn_curre ntUserFaci lityData.d .ftp_defau lttandiagn osiscode.N ame);
  986                                                       Xr m.Page.get Attribute( 'ftp_diagn osiscode') .setSubmit Mode('alwa ys');
  987                                                       // *}
  988                                                   }
  989                                               }
  990                                          }
  991  
  992                                          //Ma tch up the  VHG Triag e minute c onfigurati on with CP T Code
  993                                          if ( vcmn_triag eminutes >  0) {
  994                                               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 +  " )";
  995                                               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);
  996                                          }
  997                                      }
  998                                 }
  999                             }
  1000                             //Phar macy logic
  1001                             if (vc mn_current UserData.d .msdyusd_U SDConfigur ationId.Na me == 'Pha rmacy Conf iguration' ) {
  1002                                 // Get Defaul t Pharmacy  Configura tion from  User's Fac ility
  1003                                 if  (vcmn_cur rentUserDa ta.d.ftp_F acilitySit eId != nul l) {
  1004                                      if (vcmn _currentUs erData.d.f tp_Facilit ySiteId.Id  != null)  {
  1005                                          var  vcmn_curre ntUserFaci lityData =  vcmn_getS ingleEntit yDataSync( 'ftp_facil itySet', ' ftp_defaul tpharmacyp rimarydiag nosiscode' , vcmn_cur rentUserDa ta.d.ftp_F acilitySit eId.Id);
  1006                                          if ( vcmn_curre ntUserFaci lityData ! = null) {
  1007                                               if (vcmn_c urrentUser FacilityDa ta.d.ftp_d efaultphar macyprimar ydiagnosis code != nu ll) {
  1008                                                   if (vc mn_current UserFacili tyData.d.f tp_default pharmacypr imarydiagn osiscode.I d != null)  {
  1009                                                       // Write Diag nosis code  to Progre ss Note Fo rm if a Tr iage Note  (revised 5 /9-17 for  workload e ncounter a lso)
  1010                                                       // *if (vcmn_ triageexpe rt == 'YES ') {
  1011                                                       vc mn_setSimp leLookupVa lue('ftp_d iagnosisco de', vcmn_ currentUse rFacilityD ata.d.ftp_ defaultpha rmacyprima rydiagnosi scode.Logi calName, v cmn_curren tUserFacil ityData.d. ftp_defaul tpharmacyp rimarydiag nosiscode. Id, vcmn_c urrentUser FacilityDa ta.d.ftp_d efaultphar macyprimar ydiagnosis code.Name) ;
  1012                                                       Xr m.Page.get Attribute( 'ftp_diagn osiscode') .setSubmit Mode('alwa ys');
  1013                                                       // *}
  1014                                                   }
  1015                                               }
  1016                                          }
  1017                                      }
  1018                                 }
  1019                             }
  1020                         }
  1021                    }
  1022                }
  1023  
  1024                //*****  SECTION BE LOW HAS BE EN DISABLE D.  The Pr imary Requ est Note ' Descriptio n' attribu te is no l onger used  as of 07/ 10/2017*** *
  1025                /*
  1026                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 == '')  {
  1027                    //Pr ompt user  to include  existing  Request No tes if the re is a cu rrent valu e
  1028                    Xrm. Utility.co nfirmDialo g(
  1029                         "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. ",
  1030                         function ( ) {
  1031                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setVal ue(vcmn_re questData. d.Descript ion);
  1032                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setSub mitMode('a lways');
  1033                         }
  1034                    );
  1035                }
  1036  
  1037                //****** FIX DEFECT  481450 ** ****
  1038                if (vcmn _requestDa ta.d.Descr iption !=  null && vc mn_request Data.d.Des cription ! = '' && vc mn_triagee xpert == ' YES') {
  1039                    //Pr ompt user  to include  existing  Request No tes if the re is a cu rrent valu e
  1040                    Xrm. Utility.co nfirmDialo g(
  1041                         "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. ",
  1042                         function ( ) {
  1043                             //Get  the existi ng Triage  Note 
  1044                             var vc mn_TriageN ote = Xrm. Page.getAt tribute('f tp_notedet ail').getV alue();
  1045                             if (vc mn_TriageN ote != nul l) {
  1046                                 Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_requestD ata.d.Desc ription +  "\n\n" + v cmn_Triage Note);
  1047                             }
  1048                             else {  Xrm.Page. getAttribu te('ftp_no tedetail') .setValue( vcmn_reque stData.d.D escription ); }
  1049                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setSub mitMode('a lways');
  1050                         }
  1051                    );
  1052                }
  1053                //****** END FIX DE FECT 48145 0 ******
  1054                */
  1055                //*****E ND DISABLE D SECTION* ******
  1056           }
  1057  
  1058           // 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)
  1059           if  (vcmn_vet eranId !=  null) {
  1060                var vcmn _contactDa ta = vcmn_ getSingleE ntityDataS ync('Conta ctSet', 'f tp_current facilityid , ftp_Faci lityId', v cmn_vetera nId);
  1061                if (vcmn _contactDa ta != null ) {
  1062                    if ( vcmn_conta ctData.d.f tp_current facilityid  != null)  {
  1063                         if (vcmn_c ontactData .d.ftp_cur rentfacili tyid.Id !=  null) {
  1064                             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);
  1065                             Xrm.Pa ge.getAttr ibute('ftp _patientfa cility').s etSubmitMo de('always ');
  1066                         }
  1067                         else {
  1068                             //Get  Facility f rom Home F acility
  1069                             if (vc mn_contact Data.d.ftp _FacilityI d != null)  {
  1070                                 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 );
  1071                                 Xr m.Page.get Attribute( 'ftp_patie ntfacility ').setSubm itMode('al ways');
  1072                             }
  1073                         }
  1074                    }
  1075                    else  {
  1076                         //Get Faci lity from  Home Facil ity
  1077                         if (vcmn_c ontactData .d.ftp_Fac ilityId !=  null) {
  1078                             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);
  1079                             Xrm.Pa ge.getAttr ibute('ftp _patientfa cility').s etSubmitMo de('always ');
  1080                         }
  1081                    }
  1082                }
  1083           }
  1084  
  1085           // Set other  default fo rm values
  1086           Xr m.Page.get Attribute( 'scheduled end').setV alue(new D ate());
  1087           Xr m.Page.get Attribute( 'scheduled end').setS ubmitMode( 'always');
  1088  
  1089           // Append Gen eric Templ ate Data t o top of e xisting no te
  1090           va r vcmn_gen ericTempla teData = " Callback N umber: ";
  1091           if  (Xrm.Page .getAttrib ute('ftp_c allbacknum ber').getV alue() !=  null && Xr m.Page.get Attribute( 'ftp_callb acknumber' ).getValue () != "")  {
  1092                vcmn_gen ericTempla teData = v cmn_generi cTemplateD ata + Xrm. Page.getAt tribute('f tp_callbac knumber'). getValue() ;
  1093           }
  1094           // Construct  new note w ith existi ng note da ta
  1095           va r vcmn_exi stingNoteD ata = "";
  1096           if  (Xrm.Page .getAttrib ute("ftp_n otedetail" ).getValue () != null  && Xrm.Pa ge.getAttr ibute("ftp _notedetai l").getVal ue() != "" ) {
  1097                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  1098           }
  1099           vc mn_generic TemplateDa ta = vcmn_ genericTem plateData  + "\n\n" +  vcmn_exis tingNoteDa ta;
  1100           // Replace ex isting not e if it is  not a Non -Narcotic  Note
  1101           if  (vcmn_non NarcoticTe mplate ==  false) {
  1102                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setValue (vcmn_gene ricTemplat eData);
  1103                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setSubmi tMode('alw ays');
  1104           }
  1105  
  1106           // Change Foc us to the  Notes fiel d
  1107           // Xrm.Page.g etControl( "ftp_noted etail").se tFocus();
  1108  
  1109           // Get ICN vi a web serv ice and ge t Service  Connected  disabiliti es, Appoin tments and  Medicatio ns thereaf ter
  1110           // Preserved  Variables
  1111           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1112           va r vcmn_vet eranFirstN ame = '';
  1113           va r vcmn_vet eranLastNa me = '';
  1114           va r vcmn_SSN  = '';
  1115           va r vcmn_DOB  = '';
  1116  
  1117           // Get regard ing data
  1118           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1119           if  (vcmn_req uestId ==  null) { re turn false ; }
  1120           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1121  
  1122           if  (vcmn_req uestData ! = null) {
  1123                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1124                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1125                    //Ve rify that  the custom erid is of  type cont act
  1126                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1127                         return fal se;
  1128                    }
  1129                }
  1130           }
  1131           if  (vcmn_vet eranId ==  null) {
  1132                return f alse;
  1133           }
  1134  
  1135           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);
  1136           if  (vcmn_con tactData ! = null) {
  1137                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1138                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1139                if (vcmn _contactDa ta.d.ftp_D ateofBirth  != null)  { vcmn_DOB  = vcmn_co ntactData. d.ftp_Date ofBirth; }
  1140                if (vcmn _contactDa ta.d.Gover nmentId !=  null) { v cmn_SSN =  vcmn_conta ctData.d.G overnmentI d; }
  1141           }
  1142  
  1143           // Perform MV I Search f or Service  Connected  Disabilit ies
  1144           vc mn_unatten dedMviSear chSCD(vcmn _veteranFi rstName, v cmn_vetera nLastName,  vcmn_DOB,  vcmn_SSN) ;
  1145       }
  1146       catch  (err) {
  1147           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_newP rogressNot eLoad_WebU RL): ' + e rr.message );
  1148       }
  1149   }
  1150  
  1151   function v cmn_getSer viceConnec tedDisabil ities(vcmn _patientIC N) {
  1152       try {
  1153           // ******Deve loper Bypa ss for mis sing ICN** ****
  1154           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1155                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  1156                    aler t("Develop er ICN byp ass applie d!");
  1157                    vcmn _patientIC N = "12345 6V123456";
  1158                }
  1159           }
  1160  
  1161           // Verify Pat ient ICN
  1162           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1163                //No ICN , do not p roceed
  1164                return f alse;
  1165           }
  1166  
  1167           // Keep ICN i n memory f or reuse
  1168           vc mn_SecureP atientICN  = vcmn_pat ientICN;
  1169  
  1170           // Construct  Service Pa rameters
  1171           va r vcmn_ido bject = {} ;
  1172           vc mn_idobjec t.National Id = '0000 00' + vcmn _SecurePat ientICN +  '000000';
  1173           va r vcmn_ser viceParams  = [{
  1174                key: "id entifier",
  1175                type: "c :string",
  1176                value: J SON.string ify(vcmn_i dobject)
  1177           }] ;
  1178           // Call the w eb service  security  function
  1179           Cr mSecurityT okenEncryp tion(vcmn_ Enrollment Eligibilit ySummaryUR Lbase, vcm n_serviceP arams, vcm n_serverUr l, vcmn_ge tEsrEnroll mentJSON_r esponse)
  1180  
  1181       }
  1182       catch  (err) {
  1183           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getS erviceConn ectedDisab ilities):  ' + err.me ssage);
  1184       }
  1185   }
  1186  
  1187   function v cmn_getEsr Enrollment JSON_respo nse(vcmn_e rror, vcmn _getesrres ponse) {
  1188       try {
  1189           // NOTE:Expec ting JSON  result, if  changed t o XML modi fy code ac cordingly.
  1190  
  1191           // Set JSON D ata to Nul l;
  1192           vc mn_Enrollm entEligibi litySummar yData = nu ll;
  1193  
  1194           // Check for  non ESR se rvice erro r
  1195           if  (vcmn_err or != null ) {
  1196                alert("A n ESR Secu re Service  error occ ured:\n "  + vcmn_err or + " \nD ebugInfo:  " + vcmn_g etesrrespo nse);
  1197           }
  1198           el se {
  1199                //Test f or ESR ser vice error
  1200                if (vcmn _getesrres ponse.Erro rOccurred  == true) {
  1201                    aler t("An ESR  Secure Ser vice error  occurred: \n " + vcm n_getesrre sponse.Err orMessage  + " \nDebu gInfo: " +  vcmn_gete srresponse .DebugInfo );
  1202                }
  1203                else {
  1204                    //Se t Data Ret urned
  1205                    vcmn _Enrollmen tEligibili tySummaryD ata = vcmn _getesrres ponse;
  1206                }
  1207           }
  1208  
  1209           va r vcmn_SCD noteString  = '';
  1210           if  (vcmn_Enr ollmentEli gibilitySu mmaryData  == null) {
  1211                vcmn_SCD noteString  = "\nNo S ervice Con nected Dis abilities  Found";
  1212           }
  1213           el se {
  1214                //Create  base Note  String
  1215                vcmn_SCD noteString  = vcmn_SC DnoteStrin g + "\n--- ---------- ---------- ---------- ---------- ---------- ---------- ---------- \n";
  1216                vcmn_SCD noteString  = vcmn_SC DnoteStrin g + "Speci al Treatme nt Authori ty and Ser vice Conne cted Disab ilities";
  1217                vcmn_SCD noteString  = vcmn_SC DnoteStrin g + "\n--- ---------- ---------- ---------- ---------- ---------- ---------- ---------- \n";
  1218  
  1219                //Data f rom parent node 'enro llmentDete rminationI nfo' 
  1220                var $vcm n_enrollme ntDetermin ationInfo  = null;
  1221                var $vcm n_primaryE ligibility  = null;
  1222                var $vcm n_type = n ull;
  1223                var vcmn _typeText  = null;
  1224                var $vcm n_enrollme ntCategory Name = nul l;
  1225                var vcmn _enrollmen tCategoryN ameText =  null;
  1226                var $vcm n_specialF actors = n ull;
  1227                var $vcm n_envConta minantsInd  = null;
  1228                var vcmn _envContam inantsIndT ext = null ;
  1229                var $vcm n_radiatio nExposureI nd = null;
  1230                var vcmn _radiation ExposureIn dText = nu ll;
  1231                var $vcm n_agentOra ngeInd = n ull;
  1232                var vcmn _agentOran geIndText  = null;
  1233                var $vcm n_campLeje uneInd = n ull;
  1234                var vcmn _campLejeu neIndText  = null;
  1235                var $vcm n_serviceC onnectionA ward = nul l;
  1236                var $vcm n_serviceC onnectedPe rcentage =  null;
  1237                var vcmn _serviceCo nnectedPer centageTex t = null;
  1238                var $vcm n_ratedDis abilities  = null;
  1239  
  1240                var $vcm n_agentOra ngeLocatio n = null;
  1241                var vcmn _agentOran geLocation Text = nul l;
  1242                var $vcm n_radiatio nExposureM ethod = nu ll;
  1243                var vcmn _radiation ExposureMe thodText =  null;
  1244  
  1245                var $vcm n_noseThro atRadiumIn fo = null;
  1246                var $vcm n_diagnose dWithCance r = null;
  1247                var vcmn _diagnosed WithCancer Text = nul l;
  1248  
  1249                var $vcm n_military SexualTrau maInfo = n ull;
  1250                var $vcm n_milSexTr aumaStatus  = null;
  1251                var vcmn _milSexTra umaStatusT ext = null ;
  1252  
  1253                //Data f rom parent node 'mili taryServic eInfo' 
  1254                var $vcm n_military ServiceInf o = null;
  1255                var $vcm n_combatVe teranEligi bilityEndD ate = null ;
  1256                var vcmn _combatVet eranEligib ilityEndDa teText = n ull;
  1257                var $vcm n_shadIndi cator = nu ll;
  1258                var vcmn _shadIndic atorText =  null;
  1259  
  1260                var vcmn _ratedDisa bilityPerc entageTota l = 0;
  1261  
  1262                var vcmn _detailrow count = 0;
  1263  
  1264                if (vcmn _Enrollmen tEligibili tySummaryD ata != nul l) {
  1265                    $vcm n_enrollme ntDetermin ationInfo  = vcmn_Enr ollmentEli gibilitySu mmaryData. Data.Enrol lmentDeter minationIn fo;
  1266                }
  1267  
  1268                if ($vcm n_enrollme ntDetermin ationInfo  != null) {
  1269                    $vcm n_primaryE ligibility  = $vcmn_e nrollmentD eterminati onInfo.Pri maryEligib ility;
  1270  
  1271                    if ( $vcmn_prim aryEligibi lity != nu ll) {
  1272                         $vcmn_type  = $vcmn_p rimaryElig ibility.Ty pe;
  1273                         if ($vcmn_ type != nu ll) { vcmn _typeText  = $vcmn_ty pe; }
  1274                    }
  1275  
  1276                    $vcm n_enrollme ntCategory Name = $vc mn_enrollm entDetermi nationInfo .Enrollmen tCategoryN ame;
  1277                    if ( $vcmn_enro llmentCate goryName ! = null) {  vcmn_enrol lmentCateg oryNameTex t = $vcmn_ enrollment CategoryNa me; }
  1278  
  1279                    $vcm n_specialF actors = $ vcmn_enrol lmentDeter minationIn fo.Special Factors;
  1280                    if ( $vcmn_spec ialFactors  != null)  {
  1281                         $vcmn_envC ontaminant sInd = $vc mn_special Factors.En vContamina ntsInd;
  1282                         if ($vcmn_ envContami nantsInd ! = null) {  vcmn_envCo ntaminants IndText =  $vcmn_envC ontaminant sInd; }
  1283                         $vcmn_radi ationExpos ureInd = $ vcmn_speci alFactors. RadiationE xposureInd ;
  1284                         if ($vcmn_ radiationE xposureInd  != null)  { vcmn_rad iationExpo sureIndTex t = $vcmn_ radiationE xposureInd ; }
  1285                         $vcmn_agen tOrangeInd  = $vcmn_s pecialFact ors.AgentO rangeInd;
  1286                         if ($vcmn_ agentOrang eInd != nu ll) { vcmn _agentOran geIndText  = $vcmn_ag entOrangeI nd; }
  1287                         $vcmn_camp LejeuneInd  = $vcmn_s pecialFact ors.CampLe jeuneInd;
  1288                         if ($vcmn_ campLejeun eInd != nu ll) { vcmn _campLejeu neIndText  = $vcmn_ca mpLejeuneI nd; }
  1289                         $vcmn_agen tOrangeLoc ation = $v cmn_specia lFactors.A gentOrange Location;
  1290                         if ($vcmn_ agentOrang eLocation  != null) {  vcmn_agen tOrangeLoc ationText  = $vcmn_ag entOrangeL ocation; }
  1291                         $vcmn_radi ationExpos ureMethod  = $vcmn_sp ecialFacto rs.Radiati onExposure Method;
  1292                         if ($vcmn_ radiationE xposureMet hod != nul l) { vcmn_ radiationE xposureMet hodText =  $vcmn_radi ationExpos ureMethod;  }
  1293                    }
  1294  
  1295                    $vcm n_serviceC onnectionA ward = $vc mn_enrollm entDetermi nationInfo .ServiceCo nnectionAw ard;
  1296  
  1297                    if ( $vcmn_serv iceConnect ionAward ! = null) {
  1298                         $vcmn_serv iceConnect edPercenta ge = $vcmn _serviceCo nnectionAw ard.Servic eConnected Percentage ;
  1299                         if ($vcmn_ serviceCon nectedPerc entage !=  null) { vc mn_service ConnectedP ercentageT ext = $vcm n_serviceC onnectedPe rcentage;  }
  1300                         $vcmn_rate dDisabilit ies = $vcm n_serviceC onnectionA ward.Rated Disabiliti es;
  1301  
  1302                         //Get each  disabilit y listed a nd add to  note strin g
  1303                         vcmn_SCDno teString =  vcmn_SCDn oteString  + "SC Disa bility: ";
  1304  
  1305                         for (var i  = 0; i <=  $vcmn_rat edDisabili ties.Rated Disability .length -  1; i++) {
  1306                             var vc mn_ratedDi sabilityPe rcent = 0;
  1307                             var vc mn_disabil ity = null ;
  1308                             if (Nu mber($vcmn _ratedDisa bilities.R atedDisabi lity[i].Pe rcentage)  > 0) {
  1309                                 vc mn_ratedDi sabilityPe rcentageTo tal = vcmn _ratedDisa bilityPerc entageTota l + Number ($vcmn_rat edDisabili ties.Rated Disability [i].Percen tage);
  1310                                 vc mn_ratedDi sabilityPe rcent = Nu mber($vcmn _ratedDisa bilities.R atedDisabi lity[i].Pe rcentage);
  1311                             }
  1312                             //Add  Rated Disa bilities t o the Note  String if  Disabilit y Percent  > 0
  1313                             if (vc mn_ratedDi sabilityPe rcent > 0)  {
  1314                                 vc mn_SCDnote String = v cmn_SCDnot eString +  $vcmn_rate dDisabilit ies.RatedD isability[ i].Disabil ity + "\n" ;
  1315                             }
  1316                         };
  1317                         vcmn_SCDno teString =  vcmn_SCDn oteString  + "\n";
  1318                    }
  1319  
  1320                    $vcm n_noseThro atRadiumIn fo = $vcmn _enrollmen tDetermina tionInfo.N oseThroatR adiumInfo;
  1321                    if ( $vcmn_nose ThroatRadi umInfo !=  null) {
  1322                         $vcmn_diag nosedWithC ancer = $v cmn_noseTh roatRadium Info.Diagn osedWithCa ncer;
  1323                         if ($vcmn_ diagnosedW ithCancer  != null) {  vcmn_diag nosedWithC ancerText  = $vcmn_di agnosedWit hCancer; }
  1324                    }
  1325  
  1326                    $vcm n_military SexualTrau maInfo = $ vcmn_enrol lmentDeter minationIn fo.Militar ySexualTra umaInfo;
  1327                    if ( $vcmn_mili tarySexual TraumaInfo  != null)  {
  1328                         $vcmn_milS exTraumaSt atus = $vc mn_militar ySexualTra umaInfo.St atus;
  1329                         if ($vcmn_ milSexTrau maStatus ! = null) {  vcmn_milSe xTraumaSta tusText =  $vcmn_milS exTraumaSt atus; }
  1330                    }
  1331                }
  1332  
  1333                if (vcmn _Enrollmen tEligibili tySummaryD ata != nul l) {
  1334                    $vcm n_military ServiceInf o = vcmn_E nrollmentE ligibility SummaryDat a.Data.Mil itaryServi ceInfo;
  1335                }
  1336                if ($vcm n_military ServiceInf o != null)  {
  1337                    $vcm n_combatVe teranEligi bilityEndD ate = $vcm n_military ServiceInf o.CombatVe teranEligi bilityEndD ate;
  1338                    if ( $vcmn_comb atVeteranE ligibility EndDate !=  null) {
  1339                         vcmn_comba tVeteranEl igibilityE ndDateText  = vcmn_co mbatVetera nEligibili tyEndDateT ext = $vcm n_combatVe teranEligi bilityEndD ate;
  1340                    }
  1341                    $vcm n_shadIndi cator = $v cmn_milita ryServiceI nfo.ShadIn dicator;
  1342                    if ( $vcmn_shad Indicator  != null) {  vcmn_shad IndicatorT ext = $vcm n_shadIndi cator; }
  1343                }
  1344  
  1345                //If no  eligibilit y specifie d, set to  false
  1346                if (vcmn _typeText  == null ||  vcmn_type Text == '' ) { vcmn_t ypeText =  false; }
  1347  
  1348                //Change  boolean v alues to f alse if no t marked t rue
  1349                if (vcmn _envContam inantsIndT ext != 'tr ue') { vcm n_envConta minantsInd Text = fal se; }
  1350                if (vcmn _radiation ExposureIn dText != ' true') { v cmn_radiat ionExposur eIndText =  false; }
  1351                if (vcmn _agentOran geIndText  != 'true')  { vcmn_ag entOrangeI ndText = f alse; }
  1352                if (vcmn _campLejeu neIndText  != 'true')  { vcmn_ca mpLejeuneI ndText = f alse; }
  1353  
  1354                if (vcmn _diagnosed WithCancer Text != 't rue') { vc mn_diagnos edWithCanc erText = f alse; }
  1355                if (vcmn _shadIndic atorText ! = 'true')  { vcmn_sha dIndicator Text = fal se; }
  1356  
  1357                //Change  all True/ False to Y es/No
  1358                if (vcmn _typeText  == false)  { vcmn_typ eText = 'N o'; }
  1359  
  1360                if (vcmn _envContam inantsIndT ext == "tr ue") { vcm n_envConta minantsInd Text = "Ye s"; } else  { vcmn_en vContamina ntsIndText  = "No"; }
  1361                if (vcmn _radiation ExposureIn dText == " true") {
  1362                    vcmn _radiation ExposureIn dText = "Y es";
  1363                    if ( vcmn_radia tionExposu reMethodTe xt != null ) { vcmn_r adiationEx posureIndT ext = vcmn _radiation ExposureIn dText + "  - " + vcmn _radiation ExposureMe thodText;  }
  1364                } else {
  1365                    vcmn _radiation ExposureIn dText = "N o";
  1366                }
  1367                if (vcmn _agentOran geIndText  == "true")  {
  1368                    vcmn _agentOran geIndText  = "Yes";
  1369                    if ( vcmn_agent OrangeLoca tionText ! = null) {  vcmn_agent OrangeIndT ext = vcmn _agentOran geIndText  + " - " +  vcmn_agent OrangeLoca tionText;  }
  1370                }
  1371                else {
  1372                    vcmn _agentOran geIndText  = "No";
  1373                }
  1374                if (vcmn _campLejeu neIndText  == "true")  { vcmn_ca mpLejeuneI ndText = " Yes"; } el se { vcmn_ campLejeun eIndText =  "No"; }
  1375  
  1376                if (vcmn _diagnosed WithCancer Text == "t rue") { vc mn_diagnos edWithCanc erText = " Yes"; } el se { vcmn_ diagnosedW ithCancerT ext = "No" ; }
  1377  
  1378                if (vcmn _combatVet eranEligib ilityEndDa teText !=  null && vc mn_combatV eteranElig ibilityEnd DateText ! = '') { vc mn_combatV eteranElig ibilityEnd DateText =  'Yes'; }
  1379  
  1380                if (vcmn _shadIndic atorText = = "true")  { vcmn_sha dIndicator Text = "Ye s"; } else  { vcmn_sh adIndicato rText = "N o"; }
  1381  
  1382                //Constr uct summar y note par t
  1383                if (vcmn _envContam inantsIndT ext != nul l && vcmn_ envContami nantsIndTe xt != '')  { vcmn_SCD noteString  = vcmn_SC DnoteStrin g + "Envir onmental C ontaminant : " + vcmn _envContam inantsIndT ext + "\n" ; }
  1384                if (vcmn _combatVet eranEligib ilityEndDa teText !=  null && vc mn_combatV eteranElig ibilityEnd DateText ! = '') { vc mn_SCDnote String = v cmn_SCDnot eString +  "Combat Ve teran: " +  vcmn_comb atVeteranE ligibility EndDateTex t + "\n";  }
  1385                if (vcmn _radiation ExposureIn dText != n ull && vcm n_radiatio nExposureI ndText !=  '') { vcmn _SCDnoteSt ring = vcm n_SCDnoteS tring + "R adiation E xposure: "  + vcmn_ra diationExp osureIndTe xt + "\n";  }
  1386                if (vcmn _agentOran geIndText  != null &&  vcmn_agen tOrangeInd Text != '' ) { vcmn_S CDnoteStri ng = vcmn_ SCDnoteStr ing + "Age nt Orange:  " + vcmn_ agentOrang eIndText +  "\n"; }
  1387                if (vcmn _shadIndic atorText ! = null &&  vcmn_shadI ndicatorTe xt != '')  { vcmn_SCD noteString  = vcmn_SC DnoteStrin g + "Shipb oard Hazar d & Defens e: " + vcm n_shadIndi catorText  + "\n"; }
  1388                if (vcmn _diagnosed WithCancer Text != nu ll && vcmn _diagnosed WithCancer Text != '' ) { vcmn_S CDnoteStri ng = vcmn_ SCDnoteStr ing + "Hea d/Neck Can cer: " + v cmn_diagno sedWithCan cerText +  "\n"; }
  1389                if (vcmn _milSexTra umaStatusT ext != nul l && vcmn_ milSexTrau maStatusTe xt != '')  { vcmn_SCD noteString  = vcmn_SC DnoteStrin g + "Milit ary Sexual  Trauma: "  + vcmn_mi lSexTrauma StatusText  + "\n"; }
  1390                if (vcmn _campLejeu neIndText  != null &&  vcmn_camp LejeuneInd Text != '' ) { vcmn_S CDnoteStri ng = vcmn_ SCDnoteStr ing + "Cam p Lejeune:  " + vcmn_ campLejeun eIndText +  "\n"; }
  1391           }
  1392  
  1393           // Update not e with new  SCD note  data
  1394           va r vcmn_exi stingNoteD ata = "";
  1395           if  (Xrm.Page .getAttrib ute("ftp_n otedetail" ).getValue () != null  && Xrm.Pa ge.getAttr ibute("ftp _notedetai l").getVal ue() != "" ) {
  1396                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  1397           }
  1398  
  1399           if  (vcmn_exi stingNoteD ata.indexO f("~~~~SCD TAG~~~~")  > -1) {
  1400                var vcmn _extendedT emplateDat a = vcmn_e xistingNot eData.repl ace("~~~~S CDTAG~~~~" , vcmn_SCD noteString );
  1401                //Replac e existing  note
  1402                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setValue (vcmn_exte ndedTempla teData);
  1403                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setSubmi tMode('alw ays');
  1404           }
  1405  
  1406           // Move on to  Appointme nts
  1407           // *vcmn_getP atientAppo intments(v cmn_patien tICN);
  1408           vc mn_getPati entAppoint ments(vcmn _SecurePat ientICN);
  1409       }
  1410       catch  (err) {
  1411           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getE srEnrollme ntJSON_res ponse): '  + err.mess age);
  1412       }
  1413   }
  1414  
  1415   function v cmn_getApp ointmentDa ta(vcmn_na tionalId)  {
  1416       try {
  1417           va r vcmn_app ointmentUR L = vcmn_A ppointment sUrl + '00 0000' + vc mn_nationa lId + '000 000';
  1418           va r vcmn_jso nAppointme ntData = n ull;
  1419  
  1420           $. ajax({
  1421                type: "G ET",
  1422                url: vcm n_appointm entURL,
  1423                contentT ype: "appl ication/js on; charse t=utf-8",
  1424                dataType : "json",
  1425                success:  function  (data) {
  1426                    vcmn _jsonAppoi ntmentData  = data;
  1427                },
  1428                error: f unction (j qXHR, text Status, er rorThrown)  {
  1429                    //Sy stem Error
  1430                    vcmn _jsonAppoi ntmentData  = null;
  1431                },
  1432                async: f alse,
  1433                cache: f alse
  1434           }) ;
  1435           re turn vcmn_ jsonAppoin tmentData;
  1436       }
  1437       catch  (err) {
  1438           al ert("Progr ess Note F orm Load S cript Func tion Error (vcmn_getA ppointment Data): " +  err.messa ge);
  1439           re turn null;
  1440       }
  1441   }
  1442  
  1443   function v cmn_getPat ientAppoin tments(vcm n_patientI CN) {
  1444       try {
  1445           // ******Deve loper Bypa ss for mis sing ICN** ****
  1446           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1447                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  1448                    aler t("Develop er ICN byp ass applie d!");
  1449                    vcmn _patientIC N = "12345 6V123456";
  1450                }
  1451           }
  1452  
  1453           // Verify Pat ient ICN
  1454           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1455                //No ICN , do not p roceed
  1456                return f alse;
  1457           }
  1458  
  1459           // Get appoin tment data  from the  web servic e
  1460           va r vcmn_app ointmentDa ta = vcmn_ getAppoint mentData(v cmn_patien tICN);
  1461  
  1462           // Temporary  action jso n result i s empty, u se sample  data, comm ent out wh en not use d
  1463           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** *******
  1464           // if (vcmn_a ppointment Data == nu ll || vcmn _appointme ntData ==  '') { vcmn _appointme ntData = j sonApptDat a; }
  1465           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** *******
  1466  
  1467           va r vcmn_APP noteString  = '';
  1468           if  (vcmn_app ointmentDa ta == null  || vcmn_a ppointment Data == '' ) {
  1469                vcmn_APP noteString  = "\nNo A ppointment s Found";
  1470           }
  1471           el se {
  1472                //Got da ta, check  for errors
  1473                if (vcmn _appointme ntData.Err orOccurred  == false)  {
  1474                    var  vcmn_curre ntDateTime  = new Dat e();
  1475                    if ( vcmn_appoi ntmentData .Data != n ull) {
  1476                         for (var i  = 0; i <=  vcmn_appo intmentDat a.Data.len gth - 1; i ++) {
  1477                             var vc mn_jsonDat eTimeDate  = null;
  1478                             if (vc mn_appoint mentData.D ata[i].Dat eTimeDate  != null) {  vcmn_json DateTimeDa te = vcmn_ appointmen tData.Data [i].DateTi meDate; }
  1479                             if (vc mn_current DateTime >  new Date( vcmn_jsonD ateTimeDat e)) {
  1480                                 // Do Nothing , skip ove r the reco rd
  1481                             }
  1482                             else {
  1483                                 // Include ap pointment  in appoint ment list:
  1484                                 vc mn_APPnote String = v cmn_APPnot eString +  "\n" + (ne w Date(vcm n_jsonDate TimeDate)) .toString( )
  1485                                 if  (vcmn_app ointmentDa ta.Data[i] .ClinicNam e != null)  { vcmn_AP PnoteStrin g = vcmn_A PPnoteStri ng + " - "  + vcmn_ap pointmentD ata.Data[i ].ClinicNa me; }
  1486                                 if  (vcmn_app ointmentDa ta.Data[i] .FacilityN ame != nul l) { vcmn_ APPnoteStr ing = vcmn _APPnoteSt ring + " -  " + vcmn_ appointmen tData.Data [i].Facili tyName; }
  1487                                 if  (vcmn_app ointmentDa ta.Data[i] .StatusNam e != null)  { vcmn_AP PnoteStrin g = vcmn_A PPnoteStri ng + " - "  + vcmn_ap pointmentD ata.Data[i ].StatusNa me; }
  1488                             }
  1489                         }
  1490                    }
  1491                    if ( vcmn_APPno teString = = '') { vc mn_APPnote String = " \nNo Appoi ntments Fo und"; }
  1492                }
  1493                else {
  1494                    vcmn _APPnoteSt ring = "\n No Appoint ments Foun d";
  1495                }
  1496           }
  1497           // If there a re appoint ments then  add to th e note if  a Non-Narc otic Templ ate Note
  1498           if  (vcmn_APP noteString  != '' &&  vcmn_nonNa rcoticTemp late == tr ue) {
  1499                vcmn_APP noteString  = "\n\nNe xt Appoint ment(s) Sc heduled: "  + vcmn_AP PnoteStrin g;
  1500                //Add to  bottom of  existing  Note text
  1501                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  1502                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setValue (vcmn_exis tingNoteDa ta + vcmn_ APPnoteStr ing);
  1503                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setSubmi tMode('alw ays');
  1504           }
  1505  
  1506           // Move on to  Medicatio ns
  1507           // *vcmn_getP atientMedi cations(vc mn_patient ICN);
  1508  
  1509           // The above  medication s call is  being repl aced by a  new CRM en tity 'ftp_ pickedmedi cation'
  1510           vc mn_getPick edMedicati ons(0, '') ;
  1511  
  1512       }
  1513       catch  (err) {
  1514           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getP atientAppo intments):  ' + err.m essage);
  1515       }
  1516   }
  1517  
  1518   function v cmn_getMed icationDat a(vcmn_nat ionalId) {
  1519       try {
  1520           va r vcmn_med icationURL  = vcmn_Me dicationsU rl + '0000 00' + vcmn _nationalI d + '00000 0';
  1521           va r vcmn_jso nMedicatio nData = nu ll;
  1522  
  1523           $. ajax({
  1524                type: "G ET",
  1525                url: vcm n_medicati onURL,
  1526                contentT ype: "appl ication/js on; charse t=utf-8",
  1527                dataType : "json",
  1528                success:  function  (data) {
  1529                    vcmn _jsonMedic ationData  = data;
  1530                },
  1531                error: f unction (j qXHR, text Status, er rorThrown)  {
  1532                    //Sy stem Error
  1533                    vcmn _jsonMedic ationData  = null;
  1534                },
  1535                async: f alse,
  1536                cache: f alse
  1537           }) ;
  1538           re turn vcmn_ jsonMedica tionData;
  1539       }
  1540       catch  (err) {
  1541           al ert("Progr ess Note F orm Load S cript Func tion Error (vcmn_getM edicationD ata): " +  err.messag e);
  1542           re turn null;
  1543       }
  1544   }
  1545  
  1546   function v cmn_getPat ientMedica tions(vcmn _patientIC N) {
  1547       try {
  1548           // ******Deve loper Bypa ss for mis sing ICN** ****
  1549           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1550                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  1551                    aler t("Develop er ICN byp ass applie d!");
  1552                    vcmn _patientIC N = "12345 6V123456";
  1553                }
  1554           }
  1555  
  1556           // Verify Pat ient ICN
  1557           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1558                //No ICN , do not p roceed
  1559                return f alse;
  1560           }
  1561  
  1562           // Get medica tion data  from the w eb service
  1563           va r vcmn_med icationDat a = vcmn_g etMedicati onData(vcm n_patientI CN);
  1564  
  1565           // Temporary  action jso n result i s empty, u se sample  data, comm ent out wh en not use d
  1566           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** *******
  1567           // if (vcmn_m edicationD ata == nul l || vcmn_ medication Data == '' ) { vcmn_m edicationD ata = json MedData; }
  1568           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** *******
  1569  
  1570           va r vcmn_MED noteString  = '';
  1571           if  (vcmn_med icationDat a == null  || vcmn_me dicationDa ta == '')  {
  1572                vcmn_MED noteString  = "\nNo M edications  Found";
  1573           }
  1574           el se {
  1575                //Got da ta, check  for errors
  1576                if (vcmn _medicatio nData.Erro rOccurred  == false)  {
  1577                    if ( vcmn_medic ationData. Data != nu ll) {
  1578                         for (var i  = 0; i <=  vcmn_medi cationData .Data.leng th - 1; i+ +) {
  1579                             if (vc mn_medicat ionData.Da ta[i].Name  != null)  { vcmn_MED noteString  = vcmn_ME DnoteStrin g + "\n" +  vcmn_medi cationData .Data[i].N ame; }
  1580                             if (vc mn_medicat ionData.Da ta[i].VaSt atus != nu ll) { vcmn _MEDnoteSt ring = vcm n_MEDnoteS tring + "  - " + vcmn _medicatio nData.Data [i].VaStat us; }
  1581                             if (vc mn_medicat ionData.Da ta[i].Orde rs[0].Fill sRemaining  != null)  { vcmn_MED noteString  = vcmn_ME DnoteStrin g + " - "  + vcmn_med icationDat a.Data[i]. Orders[0]. FillsRemai ning; }
  1582                             if (vc mn_medicat ionData.Da ta[i].Over allStart ! = null) {  vcmn_MEDno teString =  vcmn_MEDn oteString  + " - " +  vcmn_medic ationData. Data[i].Ov erallStart ; }
  1583                             if (vc mn_medicat ionData.Da ta[i].Last Filled !=  null) { vc mn_MEDnote String = v cmn_MEDnot eString +  " - " + vc mn_medicat ionData.Da ta[i].Last Filled; }
  1584                             if (vc mn_medicat ionData.Da ta[i].Over allStop !=  null) { v cmn_MEDnot eString =  vcmn_MEDno teString +  " - " + v cmn_medica tionData.D ata[i].Ove rallStop;  }
  1585                         }
  1586                    }
  1587                    if ( vcmn_MEDno teString = = '') { vc mn_MEDnote String = " \nNo Medic ations Fou nd"; }
  1588                }
  1589                else {
  1590                    vcmn _MEDnoteSt ring = "\n No Medicat ions Found ";
  1591                }
  1592           }
  1593           // If there a re medicat ions then  add to the  note if a  Non-Narco tic Templa te Note
  1594           if  (vcmn_MED noteString  != '' &&  vcmn_nonNa rcoticTemp late == tr ue) {
  1595                vcmn_MED noteString  = "\n\nMe dications:  (Name, St atus, Refi lls Remain ing, Issue  Date, Las t Refill,  Expiration ) " + vcmn _MEDnoteSt ring;
  1596                //Add to  bottom of  existing  Note text
  1597                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  1598                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setValue (vcmn_exis tingNoteDa ta + vcmn_ MEDnoteStr ing);
  1599                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setSubmi tMode('alw ays');
  1600           }
  1601       }
  1602       catch  (err) {
  1603           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getP atientMedi cations):  ' + err.me ssage);
  1604       }
  1605   }
  1606  
  1607   function v cmn_getPic kedMedicat ions(vcmn_ skipCount,  vcmn_MEDn oteString)  {
  1608       try {
  1609           // Stop Proce ssing if m ore than 1 000 Record s have bee en retriev ed
  1610           if  (vcmn_ski pCount >=  1000) { re turn false ; }
  1611  
  1612           // Retrieve P icked Medi cations ba sed on par ent reques t/incident
  1613           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1614           if  (vcmn_req uestId ==  null) { re turn false ; }
  1615           va r vcmn_con ditionalFi lter = "(f tp_Request Id/Id eq g uid'" + vc mn_request Id[0].id +  "')";
  1616           vc mn_getMult ipleEntity DataAsync( 'ftp_picke dmedicatio nSet', 'ft p_name, ft p_VAStatus , ftp_Refi llsRemaini ng_text, f tp_IssueDa te_text, f tp_LastRef ill_text,  ftp_Expira tionDate_t ext', vcmn _condition alFilter,  'ftp_name' , 'asc', v cmn_skipCo unt, vcmn_ getPickedM edications _response,  vcmn_MEDn oteString) ;
  1617       }
  1618       catch  (err) {
  1619           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getP ickedMedic ations): '  + err.mes sage);
  1620       }
  1621   }
  1622  
  1623   function v cmn_getPic kedMedicat ions_respo nse(vcmn_p ickedMedic ationData,  vcmn_last Skip, vcmn _MEDnoteSt ring) {
  1624       try {
  1625           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)
  1626           fo r (var i =  0; i <= v cmn_picked Medication Data.d.res ults.lengt h - 1; i++ ) {
  1627                if (vcmn _pickedMed icationDat a.d.result s[i].ftp_n ame != nul l) { vcmn_ MEDnoteStr ing = vcmn _MEDnoteSt ring + "\n " + vcmn_p ickedMedic ationData. d.results[ i].ftp_nam e; }
  1628                if (vcmn _pickedMed icationDat a.d.result s[i].ftp_V AStatus !=  null) { v cmn_MEDnot eString =  vcmn_MEDno teString +  " - " + v cmn_picked Medication Data.d.res ults[i].ft p_VAStatus ; }
  1629                if (vcmn _pickedMed icationDat a.d.result s[i].ftp_R efillsRema ining_text  != null)  { vcmn_MED noteString  = vcmn_ME DnoteStrin g + " - "  + vcmn_pic kedMedicat ionData.d. results[i] .ftp_Refil lsRemainin g_text; }
  1630                if (vcmn _pickedMed icationDat a.d.result s[i].ftp_I ssueDate_t ext != nul l) { vcmn_ MEDnoteStr ing = vcmn _MEDnoteSt ring + " -  " + vcmn_ pickedMedi cationData .d.results [i].ftp_Is sueDate_te xt; }
  1631                if (vcmn _pickedMed icationDat a.d.result s[i].ftp_L astRefill_ text != nu ll) { vcmn _MEDnoteSt ring = vcm n_MEDnoteS tring + "  - " + vcmn _pickedMed icationDat a.d.result s[i].ftp_L astRefill_ text; }
  1632                if (vcmn _pickedMed icationDat a.d.result s[i].ftp_E xpirationD ate_text ! = null) {  vcmn_MEDno teString =  vcmn_MEDn oteString  + " - " +  vcmn_picke dMedicatio nData.d.re sults[i].f tp_Expirat ionDate_te xt; }
  1633           }
  1634           if  (vcmn_pic kedMedicat ionData.d. __next !=  null) {
  1635                vcmn_get PickedMedi cations(vc mn_lastSki p + 50, vc mn_MEDnote String);
  1636           }
  1637  
  1638           if  (vcmn_MED noteString  == '') {  vcmn_MEDno teString =  "\nNo Med ications S elected";  }
  1639           // If there a re medicat ions selec ted on the  request,  then add t hem to the  note
  1640           vc mn_MEDnote String = " ---------- -----Medic ations Sel ected----- ---------- ----\nMedi cations: ( Name, Stat us, Refill s Remainin g, Issue D ate, Last  Refill, Ex piration)  " + vcmn_M EDnoteStri ng + "\n-- ---------- ---------- ---------- ---------- ---------- -----\n";
  1641           // Add to top  of existi ng Note te xt
  1642           vc mn_existin gNoteData  = Xrm.Page .getAttrib ute("ftp_n otedetail" ).getValue ();
  1643           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_MEDnoteS tring + vc mn_existin gNoteData) ;
  1644           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  1645       }
  1646       catch  (err) {
  1647           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getP ickedMedic ations_res ponse): '  + err.mess age);
  1648       }
  1649   }
  1650  
  1651   function v cmn_facili tyByCode_r esponse(vc mn_facilit yData, vcm n_lastSkip , vcmn_fac ilityCode)  {
  1652       try {
  1653           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  1654           // ***REVISED  NOT USED,  KEEP FOR  FUTURE UPD ATE***
  1655           /*
  1656           va r vcmn_fac ilityid =  null;
  1657           va r vcmn_fac ilityname  = null;
  1658           fo r (var i =  0; i <= v cmn_facili tyData.d.r esults.len gth - 1; i ++) {
  1659                //Get in fo
  1660                if (vcmn _facilityD ata.d.resu lts[i].ftp _facilityI d != null)  { vcmn_fa cilityid =  vcmn_faci lityData.d .results[i ].ftp_faci lityId; }
  1661                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; }
  1662                break;
  1663           }
  1664           if  (vcmn_fac ilityid !=  null) {
  1665                vcmn_set SimpleLook upValue('f tp_patient facility',  'ftp_faci lity', vcm n_facility id, vcmn_f acilitynam e);
  1666                Xrm.Page .getAttrib ute('ftp_p atientfaci lity').set SubmitMode ('always') ;
  1667           }
  1668           */
  1669       }
  1670       catch  (err) {
  1671           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_faci lityByCode _response) : ' + err. message);
  1672       }
  1673   }
  1674  
  1675   function v cmn_cptCod e_response (vcmn_cptC odeData, v cmn_lastSk ip, vcmn_t riageminut es) {
  1676       try {
  1677           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  1678           fo r (var i =  0; i <= v cmn_cptCod eData.d.re sults.leng th - 1; i+ +) {
  1679                //Write  to CRM pro gress note  form
  1680                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);
  1681                Xrm.Page .getAttrib ute('ftp_c ptcode').s etSubmitMo de('always ');
  1682                break;
  1683           }
  1684       }
  1685       catch  (err) {
  1686           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_cptC ode_respon se): ' + e rr.message );
  1687       }
  1688   }
  1689  
  1690   function v cmn_ribbon ButtonSave () {
  1691       try {
  1692           // Save the c urrent CRM  data
  1693           Xr m.Page.dat a.entity.s ave();
  1694       }
  1695       catch  (err) {
  1696           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa ve): ' + e rr.message );
  1697       }
  1698   }
  1699  
  1700   function v cmn_wordWr ap(str, in tWidth, st rBreak, cu t) {
  1701       try {
  1702           // Takes a st ring that  exceeds a  set length  and inser ts word wr ap
  1703           va r m = ((ar guments.le ngth >= 2)  ? argumen ts[1] : 75 )
  1704           va r b = ((ar guments.le ngth >= 3)  ? argumen ts[2] : '\ n')
  1705           va r c = ((ar guments.le ngth >= 4)  ? argumen ts[3] : fa lse)
  1706  
  1707           va r i, j, l,  s, r
  1708  
  1709           st r += ''
  1710  
  1711           if  (m < 1) {
  1712                return s tr
  1713           }
  1714  
  1715           fo r (i = -1,  l = (r =  str.split( /\r\n|\n|\ r/)).lengt h; ++i < l ; r[i] +=  s) {
  1716                for (s =  r[i], r[i ] = '';
  1717                  s.leng th > m;
  1718                  r[i] + = s.slice( 0, j) + (( s = s.slic e(j)).leng th ? b : ' ')) {
  1719                    j =  c === 2 ||  (j = s.sl ice(0, m +  1).match( /\S*(\s)?$ /))[1]
  1720                      ?  m
  1721                      :  j.input.le ngth - j[0 ].length | | c === tr ue && m ||
  1722                         j.input.le ngth + (j  = s.slice( m).match(/ ^\S*/))[0] .length
  1723                }
  1724           }
  1725  
  1726           re turn r.joi n('\n')
  1727       }
  1728       catch  (err) {
  1729           al ert('Progr ess Note R ibbon Func tion Error (vcmn_word Wrap): ' +  err.messa ge);
  1730       }
  1731   }
  1732  
  1733   function v cmn_ribbon ButtonSave ToVistA()  {
  1734       try {
  1735           // Check the  value of t he Integra tion Statu s Field, i f = 'OK',  stop and e xit this s cript
  1736           va r vcmn_int egrationSt atus = Xrm .Page.getA ttribute(' ftp_integr ationstatu s').getVal ue();
  1737           if  (vcmn_int egrationSt atus == 'O K') { retu rn false;  }
  1738  
  1739           // Prompt use r to sign  the note
  1740           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  1741           va r vcmn_sig nThisNoteF ailure = f alse;
  1742           if  (vcmn_sig nThisNote  == null) {
  1743                Xrm.Util ity.confir mDialog(
  1744                    "Do  you need t o sign thi s note?, S elect OK i f Yes, oth erwise CAN CEL.",
  1745                    func tion () {
  1746                         //Check if  VIA Login  cookie ex ist (not e xpired)
  1747                         var vcmn_V iaLoginCoo kie = vcmn _getCookie ("viasessi onlink");
  1748                         //Prompt u ser to log in to VIA
  1749                         if (vcmn_V iaLoginCoo kie == "")  {
  1750                             alert( "Your VIST A session  has expire d. In orde r to sign  this note,  you must  be logged  into VISTA !");
  1751                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setVisi ble(true);
  1752                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setFocu s();
  1753                             vcmn_s ignThisNot eFailure =  true;
  1754                             return ;
  1755                         }
  1756                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000001 );
  1757                    },
  1758                    func tion () {
  1759                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000000 );
  1760                    }
  1761                );
  1762                Xrm.Page .getAttrib ute('ftp_s ignthisnot e').setSub mitMode('a lways');
  1763           }
  1764  
  1765           // Check for  additional  signers,  if they ex ist, the u ser must b e logged i nto VIA to  continue  process.
  1766           // Additional  Signature s must als o be in sy nc with ma tching Ses sion varia bles
  1767  
  1768           vc mn_AddlSig nersNameAr ray = null ;
  1769           vc mn_AddlSig nersIenArr ay = null;
  1770  
  1771           va r vcmn_sel ectedSigne rs = Xrm.P age.getAtt ribute('ft p_selected signers'). getValue() ;
  1772           if  (vcmn_sel ectedSigne rs != null  && vcmn_s electedSig ners != '' ) {
  1773                //Additi onal Signe rs exist i n CRM, ver ify sessio n variable s
  1774                var vcmn _selectedA rray = vcm n_selected Signers.sp lit('~~~') ;
  1775                var vcmn _selectedA rrayRecord Count = vc mn_selecte dArray.len gth;
  1776                if (vcmn _selectedA rrayRecord Count > 1)  {
  1777                    vcmn _AddlSigne rsNameArra y = vcmn_s electedArr ay;
  1778                }
  1779  
  1780                var vcmn _selectedI ENArray =  '';
  1781                var vcmn _selectedI ENArrayRec ordCount =  0;
  1782                var vcmn _progressN oteId = Xr m.Page.dat a.entity.g etId();
  1783  
  1784                var vcmn _arrayMism atch = fal se;
  1785  
  1786                //Get No te's Brows er Local S torage Val ues
  1787                if (vcmn _progressN oteId != n ull && vcm n_progress NoteId !=  '') {
  1788                    vcmn _localStor ageVarName  = "PN" +  vcmn_progr essNoteId;
  1789                    var  vcmn_local StorageStr ingValue =  localStor age.getIte m(vcmn_loc alStorageV arName);
  1790                    if ( vcmn_local StorageStr ingValue ! = null &&  vcmn_local StorageStr ingValue ! = '') {
  1791                         vcmn_selec tedIENArra y = vcmn_l ocalStorag eStringVal ue.split(' ~~~');
  1792                         vcmn_selec tedIENArra yRecordCou nt = vcmn_ selectedIE NArray.len gth;
  1793                         if (vcmn_s electedIEN ArrayRecor dCount > 1 ) {
  1794                             vcmn_A ddlSigners IenArray =  vcmn_sele ctedIENArr ay;
  1795                         }
  1796                    }
  1797                }
  1798                //Compar e CRM sign er array l ength with  LocalStor age array  length
  1799                if (vcmn _selectedA rrayRecord Count != v cmn_select edIENArray RecordCoun t) { vcmn_ arrayMisma tch = true ; }
  1800  
  1801                if (vcmn _arrayMism atch == tr ue) {
  1802                    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.");
  1803                    vcmn _signThisN oteFailure  = true;
  1804                }
  1805                else {
  1806                    //Ch eck if VIA  Login coo kie exist  (not expir ed)
  1807                    var  vcmn_ViaLo ginCookie  = vcmn_get Cookie("vi asessionli nk");
  1808                    if ( vcmn_ViaLo ginCookie  == "") {
  1809                         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 !");
  1810                         Xrm.Page.u i.tabs.get ('Tab_Vist ALogin').s etVisible( true);
  1811                         Xrm.Page.u i.tabs.get ('Tab_Vist ALogin').s etFocus();
  1812                         vcmn_signT hisNoteFai lure = tru e;
  1813                         return;
  1814                    }
  1815                }
  1816           }
  1817  
  1818           // Check if m arked as a  workload  encounter  and if so  enforce VI A Login
  1819           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) == true)  {
  1820                //Check  if VIA Log in cookie  exist (not  expired)
  1821                var vcmn _ViaLoginC ookie = vc mn_getCook ie("viases sionlink") ;
  1822                if (vcmn _ViaLoginC ookie == " ") {
  1823                    aler t("Your VI STA sessio n has expi red. In or der to pro cess a wor kload enco unter note , you must  be logged  into VIST A!");
  1824                    Xrm. Page.ui.ta bs.get('Ta b_VistALog in').setVi sible(true );
  1825                    Xrm. Page.ui.ta bs.get('Ta b_VistALog in').setFo cus();
  1826                    vcmn _signThisN oteFailure  = true;
  1827                    retu rn;
  1828                }
  1829           }
  1830  
  1831           if  (vcmn_sig nThisNoteF ailure ==  true) {
  1832                //****** Developer  Bypass for  no VISTA  authentica tion******
  1833                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}") {
  1834                    aler t("Develop er VISTA a uthenticat ion bypass  applied!" );
  1835                    Xrm. Page.getAt tribute('f tp_signthi snote').se tValue(100 000001);
  1836                    Xrm. Page.getAt tribute('f tp_signthi snote').se tSubmitMod e('always' );
  1837                }
  1838                else {
  1839                    retu rn false;
  1840                }
  1841           }
  1842  
  1843           // Save the c urrent CRM  data
  1844           Xr m.Page.dat a.entity.s ave();
  1845           // Display YE LLOW Progr ess....
  1846           Xr m.Page.ui. setFormNot ification( "Verifying  progress  note data,  please wa it..", "IN FO", "SAVE VISTA");
  1847  
  1848           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!');
  1849           if  (vcmn_con firmSaveTo Vista == f alse) {
  1850                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1851                return f alse;
  1852           }
  1853           // Get regard ing data
  1854           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1855           if  (vcmn_req uestId ==  null) {
  1856                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 !');
  1857                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  1858                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1859                return f alse;
  1860           }
  1861           // Verify tha t the rega rdingid is  of type ' incident'
  1862           if  (vcmn_req uestId[0]. entityType  != 'incid ent') {
  1863                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!') ;
  1864                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  1865                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1866                return f alse;
  1867           }
  1868  
  1869           // Preserved  Variables
  1870           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1871           va r vcmn_vet eranFirstN ame = '';
  1872           va r vcmn_vet eranLastNa me = '';
  1873           va r vcmn_SSN  = '';
  1874           va r vcmn_DOB  = '';
  1875  
  1876           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1877           if  (vcmn_req uestData ! = null) {
  1878                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1879                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1880                    //Ve rify that  the custom erid is of  type cont act
  1881                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1882                         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!') ;
  1883                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1884                         return fal se;
  1885                    }
  1886                }
  1887           }
  1888           if  (vcmn_vet eranId ==  null) {
  1889                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  1890                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1891                return f alse;
  1892           }
  1893  
  1894           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);
  1895           if  (vcmn_con tactData ! = null) {
  1896                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1897                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1898                if (vcmn _contactDa ta.d.ftp_D ateofBirth  != null)  { vcmn_DOB  = vcmn_co ntactData. d.ftp_Date ofBirth; }
  1899                if (vcmn _contactDa ta.d.Gover nmentId !=  null) { v cmn_SSN =  vcmn_conta ctData.d.G overnmentI d; }
  1900           }
  1901  
  1902           // **WORKLOAD  ENCOUNTER **
  1903           vc mn_matchLo okupId = v cmn_SSN;
  1904           // ********** ********** ***
  1905  
  1906           // Perform MV I Search
  1907           vc mn_unatten dedMviSear ch(vcmn_ve teranFirst Name, vcmn _veteranLa stName, vc mn_DOB, vc mn_SSN);
  1908       }
  1909       catch  (err) {
  1910           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa veToVistA) : ' + err. message);
  1911           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1912       }
  1913   }
  1914  
  1915   function v cmn_ribbon ButtonSave ToVistA_wi th_ICN(vcm n_patientI CN) {
  1916       try {
  1917           // ******Deve loper Bypa ss for mis sing ICN** ****
  1918           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1919                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  1920                    aler t("Develop er ICN byp ass applie d!");
  1921                    vcmn _patientIC N = "12345 6V123456";
  1922                }
  1923           }
  1924  
  1925           // Verify Pat ient ICN
  1926           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1927                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! ');
  1928                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1929                return f alse;
  1930           }
  1931  
  1932           // Get regard ing data
  1933           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1934  
  1935           // Preserved  Variables
  1936           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1937           va r vcmn_vet eranName =  '';
  1938           va r vcmn_vet eranFirstN ame = '';
  1939           va r vcmn_vet eranLastNa me = '';
  1940           va r vcmn_vet eranMiddle Name = '';
  1941  
  1942           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1943           if  (vcmn_req uestData ! = null) {
  1944                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1945                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1946                    //Ve rify that  the custom erid is of  type cont act
  1947                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1948                         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!') ;
  1949                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1950                         return fal se;
  1951                    }
  1952                }
  1953           }
  1954           if  (vcmn_vet eranId ==  null) {
  1955                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  1956                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1957                return f alse;
  1958           }
  1959  
  1960           va r vcmn_con tactData =  vcmn_getS ingleEntit yDataSync( 'ContactSe t', 'FullN ame, First Name, Last Name, Midd leName', v cmn_vetera nId.Id);
  1961           if  (vcmn_con tactData ! = null) {
  1962                if (vcmn _contactDa ta.d.FullN ame != nul l) { vcmn_ veteranNam e = vcmn_c ontactData .d.FullNam e; }
  1963                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1964                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1965                if (vcmn _contactDa ta.d.Middl eName != n ull) { vcm n_veteranM iddleName  = vcmn_con tactData.d .MiddleNam e; }
  1966           }
  1967  
  1968           // Get user d ata
  1969           va r vcmn_crm UserId = X rm.Page.ge tAttribute ('ownerid' ).getValue ();
  1970           va r vcmn_use rDomainId  = '';
  1971           va r vcmn_use rFirstName  = '';
  1972           va r vcmn_use rLastName  = '';
  1973           va r vcmn_use rMiddleNam e = '';
  1974           va r vcmn_use rSiteId =  '';
  1975  
  1976           if  (vcmn_crm UserId !=  null) {
  1977                //Verify  the owner  type
  1978                if (vcmn _crmUserId [0].entity Type != 's ystemuser' ) {
  1979                    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 !');
  1980                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1981                    retu rn false;
  1982                }
  1983  
  1984                var vcmn _userData  = vcmn_get SingleEnti tyDataSync ('SystemUs erSet', 'D omainName,  FirstName , LastName , MiddleNa me, ftp_Fa cilitySite Id', vcmn_ crmUserId[ 0].id);
  1985                if (vcmn _userData  != null) {
  1986                    if ( vcmn_userD ata.d.Doma inName !=  null) { vc mn_userDom ainId = vc mn_userDat a.d.Domain Name; }
  1987                    if ( vcmn_userD ata.d.Firs tName != n ull) { vcm n_userFirs tName = vc mn_userDat a.d.FirstN ame; }
  1988                    if ( vcmn_userD ata.d.Last Name != nu ll) { vcmn _userLastN ame = vcmn _userData. d.LastName ; }
  1989                    if ( vcmn_userD ata.d.Midd leName !=  null) { vc mn_userMid dleName =  vcmn_userD ata.d.Midd leName; }
  1990                    if ( vcmn_userD ata.d.ftp_ FacilitySi teId != nu ll) { vcmn _userSiteI d = vcmn_u serData.d. ftp_Facili tySiteId.I d; }
  1991                }
  1992           }
  1993           el se {
  1994                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!');
  1995                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1996                return f alse;
  1997           }
  1998  
  1999           // Verify tha t the curr ent owner  and the cu rrent user  is the sa me person,  if not do  not proce ed
  2000           if  ((vcmn_cr mUserId[0] .id).toUpp erCase() ! = (Xrm.Pag e.context. getUserId( )).toUpper Case()) {
  2001                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!');
  2002                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2003                return f alse;
  2004           }
  2005           va r vcmn_Not eUserTeam  = "NONE";
  2006           // Check Team  membershi p
  2007           if  (vcmn_Use rHasTeam(" Pharmacy",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "PHARM ACY"; }
  2008           if  (vcmn_Use rHasTeam(" CCA Team",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "CCA";  }
  2009           if  (vcmn_Use rHasTeam(" TAN", Xrm. Page.conte xt.getUser Id())) { v cmn_NoteUs erTeam = " TAN"; }
  2010           // **TEMP, ve rify these  team valu es that th ey are cor rect **FUT URE NEED**
  2011           if  (vcmn_Use rHasTeam(" PACT User" , Xrm.Page .context.g etUserId() )) { vcmn_ NoteUserTe am = "PACT "; }
  2012           if  (vcmn_Use rHasTeam(" MSA User",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "MSA";  }
  2013  
  2014           // Verify Tea m Value, t hat one ha s been ass igned
  2015           if  (vcmn_Not eUserTeam  == "NONE")  {
  2016                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 !');
  2017                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2018                return f alse;
  2019           }
  2020  
  2021           // Get reques t form con tent
  2022           va r vcmn_not eDescripti on = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  2023           if  (vcmn_not eDescripti on == null  || vcmn_n oteDescrip tion == '' ) {
  2024                alert('T he note de scription  field is e mpty, the  note canno t be creat ed in Vist A/CPRS!');
  2025                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2026                return f alse;
  2027           }
  2028  
  2029           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) != true)  {
  2030                //Using  new hospit al locatio n and loca l notes lo okup field s
  2031                var vcmn _localTitl e = Xrm.Pa ge.getAttr ibute('ftp _localnote title').ge tValue();
  2032                if (vcmn _localTitl e == null)  {
  2033                    aler t('The loc al note ti tle field  is empty,  the note c annot be c reated in  VistA/CPRS !');
  2034                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2035                    retu rn false;
  2036                }
  2037                else { v cmn_localT itle = vcm n_localTit le[0].name ; }
  2038  
  2039                vcmn_pat ientAssign edLocation  = Xrm.Pag e.getAttri bute('ftp_ notehospit allocation ').getValu e();
  2040                if (vcmn _patientAs signedLoca tion == nu ll) {
  2041                    aler t('The hos pital loca tion field  is empty,  the note  cannot be  created in  VistA/CPR S!');
  2042                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2043                    retu rn false;
  2044                }
  2045                else { v cmn_patien tAssignedL ocation =  vcmn_patie ntAssigned Location[0 ].name; }
  2046           }
  2047  
  2048           va r vcmn_cal lbackNumbe r = Xrm.Pa ge.getAttr ibute('ftp _callbackn umber').ge tValue();
  2049           if  (vcmn_cal lbackNumbe r == null  || vcmn_ca llbackNumb er == '')  {
  2050                alert('T he callbac k number f ield is em pty, the n ote cannot  be create d in VistA /CPRS!');
  2051                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2052                return f alse;
  2053           }
  2054           va r vcmn_rea sonForRequ est = Xrm. Page.getAt tribute('f tp_reasonf orrequest' ).getValue ();
  2055           if  (vcmn_rea sonForRequ est == nul l) {
  2056                alert('T he reason  for reques t field is  empty, th e note can not be cre ated in Vi stA/CPRS!' );
  2057                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2058                return f alse;
  2059           }
  2060  
  2061           va r vcmn_enc ounterCode  = 'NEW';
  2062           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  2063           if  (vcmn_sig nThisNote  == 1000000 01) { vcmn _signThisN ote = true ; } else {  vcmn_sign ThisNote =  false; }
  2064  
  2065           // Get Progre ss Note Gu id/Id
  2066           va r vcmn_not eId = Xrm. Page.data. entity.get Id();
  2067  
  2068           // Get Create d On Date  & Convert  format
  2069           va r vcmn_cre atedOnDate  = vcmn_co nvertCrmDa teToVistAD ate(Xrm.Pa ge.getAttr ibute('cre atedon').g etValue()) ;
  2070           if  (vcmn_cre atedOnDate  == null)  {
  2071                alert('T he CRM cre atedon fie ld is empt y, the not e cannot b e created  in VistA/C PRS!');
  2072                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2073                return f alse;
  2074           }
  2075  
  2076           // Get User E ntry Date
  2077           va r vcmn_use rEntryDate  = vcmn_co nvertCrmDa teToVistAD ate(Xrm.Pa ge.getAttr ibute('ftp _userentry date').get Value());
  2078           if  (vcmn_use rEntryDate  == null)  { vcmn_use rEntryDate  = vcmn_cr eatedOnDat e; }
  2079  
  2080           // Get Facili ty and loo kup facili ty number  and HL7 UR L
  2081           va r vcmn_fac ilityCode  = '';
  2082           va r vcmn_sit eHL7Listen erAddress  = '';
  2083           va r vcmn_pat ientFacili ty = Xrm.P age.getAtt ribute('ft p_patientf acility'). getValue() ;
  2084           if  (vcmn_pat ientFacili ty == null ) {
  2085                alert('T he CRM pat ient facil ity field  is empty,  the note c annot be c reated in  VistA/CPRS !');
  2086                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2087                return f alse;
  2088           }
  2089           el se {
  2090                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e, ftp_hl7 listener',  vcmn_pati entFacilit y[0].id);
  2091                if (vcmn _facilityD ata.d.ftp_ facilityco de != null ) {
  2092                    vcmn _facilityC ode = vcmn _facilityD ata.d.ftp_ facilityco de;
  2093                }
  2094                else {
  2095                    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!') ;
  2096                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2097                    retu rn false;
  2098                }
  2099  
  2100                if (vcmn _facilityD ata.d.ftp_ hl7listene r != null)  {
  2101                    var  vcmn_siteH L7Listener Address =  vcmn_facil ityData.d. ftp_hl7lis tener;
  2102                }
  2103                else {
  2104                    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!');
  2105                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2106                    retu rn false;
  2107                }
  2108           }
  2109  
  2110           va r vcmn_ori ginatorID  = '';
  2111           va r vcmn_use rSiteNo =  '';
  2112  
  2113           // Lookup the  Facility/ Site #
  2114           if  (vcmn_use rSiteId !=  null && v cmn_userSi teId != '' ) {
  2115                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e', vcmn_u serSiteId) ;
  2116                if (vcmn _facilityD ata != nul l) {
  2117                    if ( vcmn_facil ityData.d. ftp_facili tycode !=  null) { vc mn_userSit eNo = vcmn _facilityD ata.d.ftp_ facilityco de; }
  2118                }
  2119           }
  2120  
  2121           // Validate r equired Vi sta Lookup  info
  2122           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) {
  2123                //Abort  process, m issing inf o
  2124                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 !');
  2125                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2126                return f alse;
  2127           }
  2128  
  2129           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) != true)  {
  2130                //Obtain  the Vista Duz from t he cross r eference t able if av ailable
  2131                if (vcmn _crmUserId  != null)  {
  2132                    var  vcmn_condi tionalFilt er = "ftp_ crmuser/Id  eq (guid' " + vcmn_c rmUserId[0 ].id + "') ";
  2133                    var  vcmn_cross ReferenceD ata = vcmn _getMultip leEntityDa taSync('ft p_useridSe t', 'ftp_u seridId, f tp_vistadu z', vcmn_c onditional Filter, 'f tp_name',  'asc', 0);
  2134                    if ( vcmn_cross ReferenceD ata != nul l) {
  2135                         for (var i  = 0; i <=  vcmn_cros sReference Data.d.res ults.lengt h - 1; i++ ) {
  2136                             //Get  Info
  2137                             if (vc mn_crossRe ferenceDat a.d.result s[i].ftp_v istaduz !=  null) { v cmn_origin atorID = v cmn_crossR eferenceDa ta.d.resul ts[i].ftp_ vistaduz;  }
  2138                             break;
  2139                         }
  2140                    }
  2141                }
  2142  
  2143                //**NOTE : The code  below to  impersonat e Lori Nic holls has  been disab led per ta sk 562307
  2144                /*
  2145                if (vcmn _IsProduct ionEnviron ment == fa lse) {
  2146                    //Pr ovide the  option to  search for  Lori Nich olls, site # 613
  2147                    var  vcmn_imper sonateProm ptString =  "**THIS I S A VISTA  USER SEARC H TEST PRO MPT** \n"  +
  2148                         "If you wo uld like t o imperson ate the us er: \n" +
  2149                         "Lori Nich olls (613)  \n" +
  2150                         "Select OK .  Otherwi se, select  CANCEL.";
  2151                    var  vcmn_confi rmImperson ateVistaUs er = confi rm(vcmn_im personateP romptStrin g);
  2152                    if ( vcmn_confi rmImperson ateVistaUs er == true ) {
  2153                         vcmn_userF irstName =  "Lori";
  2154                         vcmn_userL astName =  "Nicholls" ;
  2155                         vcmn_userS iteNo = "6 13";
  2156                    }
  2157                }
  2158                */
  2159  
  2160                var vcmn _vistauser sData = vc mn_getVist aUsersData (vcmn_user FirstName,  vcmn_user LastName,  vcmn_userS iteNo, fal se);
  2161  
  2162                //Check  vista user s data con tent
  2163                if (vcmn _vistauser sData == n ull || vcm n_vistause rsData.Dat a == null  || vcmn_vi stausersDa ta.Data.le ngth == nu ll || vcmn _vistauser sData.Data .length ==  0) {
  2164                    //Ab ort proces s, missing  info
  2165                    aler t('Unable  to obtain  Vista User  Data, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  2166                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2167                    retu rn false;
  2168                }
  2169  
  2170                var vcmn _selectedU serFirstNa me = '';
  2171                var vcmn _selectedU serMiddleN ame = '';
  2172                var vcmn _selectedU serLastNam e = '';
  2173                var vcmn _selectedU serSuffix  = '';
  2174                var vcmn _selectedU serDisplay Name = '';
  2175                var vcmn _selectedU serTitle =  '';
  2176                var vcmn _userIsSel ected = fa lse;
  2177  
  2178                if (vcmn _vistauser sData.Data .length >  1) {
  2179                    aler t("The Vis ta User li st, contai ns more th an one use r, please  select the  Vista Use r you want  to use fr om the nex t prompt(s ), a total  of " + vc mn_vistaus ersData.Da ta.length  + " users! ");
  2180                    for  (var i = 0 ; i <= vcm n_vistause rsData.Dat a.length -  1; i++) {
  2181                         var vcmn_c urrentUser FirstName  = '';
  2182                         var vcmn_c urrentUser MiddleName  = '';
  2183                         var vcmn_c urrentUser LastName =  '';
  2184                         var vcmn_c urrentUser Suffix = ' ';
  2185                         var vcmn_c urrentUser DisplayNam e = '';
  2186                         var vcmn_c urrentUser Title = '' ;
  2187                         if (vcmn_v istausersD ata.Data[i ].FirstNam e != null)  { vcmn_cu rrentUserF irstName =  vcmn_vist ausersData .Data[i].F irstName;  }
  2188                         if (vcmn_v istausersD ata.Data[i ].MiddleNa me != null ) { vcmn_c urrentUser MiddleName  = vcmn_vi stausersDa ta.Data[i] .MiddleNam e; }
  2189                         if (vcmn_v istausersD ata.Data[i ].LastName  != null)  { vcmn_cur rentUserLa stName = v cmn_vistau sersData.D ata[i].Las tName; }
  2190                         if (vcmn_v istausersD ata.Data[i ].Suffix ! = null) {  vcmn_curre ntUserSuff ix = vcmn_ vistausers Data.Data[ i].Suffix;  }
  2191                         if (vcmn_v istausersD ata.Data[i ].DisplayN ame != nul l) { vcmn_ currentUse rDisplayNa me = vcmn_ vistausers Data.Data[ i].Display Name; }
  2192                         if (vcmn_v istausersD ata.Data[i ].Title !=  null) { v cmn_curren tUserTitle  = vcmn_vi stausersDa ta.Data[i] .Title; }
  2193                         //Prompt u ser about  this vista  user reco rd
  2194                         var vcmn_u serPromptS tring = "C lick OK, t o select t his user.   Otherwise  CANCEL \n " +
  2195                             "\n Fi rst Name:  " + vcmn_c urrentUser FirstName  +
  2196                             "\n Mi ddle Name:  " + vcmn_ currentUse rMiddleNam e +
  2197                             "\n La st Name: "  + vcmn_cu rrentUserL astName +
  2198                             "\n Su ffix: " +  vcmn_curre ntUserSuff ix +
  2199                             "\n Di splay Name : " + vcmn _currentUs erDisplayN ame +
  2200                             "\n Ti tle: " + v cmn_curren tUserTitle ;
  2201  
  2202                         var vcmn_c onfirmSele ctVistaUse r = confir m(vcmn_use rPromptStr ing);
  2203                         if (vcmn_c onfirmSele ctVistaUse r == true)  {
  2204                             vcmn_u serIsSelec ted = true ;
  2205                             vcmn_s electedUse rFirstName  = vcmn_cu rrentUserF irstName;
  2206                             vcmn_s electedUse rMiddleNam e = vcmn_c urrentUser MiddleName ;
  2207                             vcmn_s electedUse rLastName  = vcmn_cur rentUserLa stName;
  2208                             vcmn_s electedUse rSuffix =  vcmn_curre ntUserSuff ix;
  2209                             vcmn_s electedUse rDisplayNa me = vcmn_ currentUse rDisplayNa me;
  2210                             vcmn_s electedUse rTitle = v cmn_curren tUserTitle ;
  2211                             break;
  2212                         }
  2213                    }
  2214                }
  2215                else {
  2216                    //Se lect data  from the f irst recor d
  2217                    vcmn _userIsSel ected = tr ue;
  2218                    if ( vcmn_vista usersData. Data[0].Fi rstName !=  null) { v cmn_select edUserFirs tName = vc mn_vistaus ersData.Da ta[0].Firs tName; }
  2219                    if ( vcmn_vista usersData. Data[0].Mi ddleName ! = null) {  vcmn_selec tedUserMid dleName =  vcmn_vista usersData. Data[0].Mi ddleName;  }
  2220                    if ( vcmn_vista usersData. Data[0].La stName !=  null) { vc mn_selecte dUserLastN ame = vcmn _vistauser sData.Data [0].LastNa me; }
  2221                    if ( vcmn_vista usersData. Data[0].Su ffix != nu ll) { vcmn _selectedU serSuffix  = vcmn_vis tausersDat a.Data[0]. Suffix; }
  2222                    if ( vcmn_vista usersData. Data[0].Di splayName  != null) {  vcmn_sele ctedUserDi splayName  = vcmn_vis tausersDat a.Data[0]. DisplayNam e; }
  2223                    if ( vcmn_vista usersData. Data[0].Ti tle != nul l) { vcmn_ selectedUs erTitle =  vcmn_vista usersData. Data[0].Ti tle; }
  2224                }
  2225  
  2226                //Check  if a user  was select ed
  2227                if (vcmn _userIsSel ected == f alse) {
  2228                    aler t('A user  was not se lected fro m the prev ious promp ts, the no te cannot  be created  in VistA/ CPRS!');
  2229                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2230                    retu rn false;
  2231                }
  2232  
  2233                //Execut e Integrat ion
  2234                vcmn_exe cuteVistAI ntegration Request(vc mn_noteId,  vcmn_note Descriptio n, vcmn_pa tientICN,  vcmn_userD omainId, v cmn_localT itle, vcmn _callbackN umber, vcm n_reasonFo rRequest[0 ].name, vc mn_encount erCode, vc mn_signThi sNote, vcm n_veteranF irstName,  vcmn_veter anLastName , vcmn_cre atedOnDate , vcmn_use rEntryDate , vcmn_sel ectedUserF irstName,  vcmn_selec tedUserMid dleName, v cmn_select edUserLast Name, vcmn _selectedU serSuffix,  vcmn_faci lityCode,  vcmn_origi natorID, v cmn_siteHL 7ListenerA ddress, vc mn_patient AssignedLo cation);
  2235  
  2236           }
  2237           el se {
  2238                //Execut e workload  encounter  note inte gration st eps
  2239                vcmn_pre pWorkloadE ncounterIn tegrationS tep01();
  2240           }
  2241       }
  2242       catch  (err) {
  2243           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa veToVistA_ with_ICN):  ' + err.m essage);
  2244           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2245       }
  2246   }
  2247  
  2248   function v cmn_prepWo rkloadEnco unterInteg rationStep 01() {
  2249       try {
  2250           // Verify Not e Title
  2251           va r vcmn_Not eTitleIEN  = Xrm.Page .getAttrib ute('ftp_s electedwor kloadnotet itleid').g etValue();
  2252           if  (vcmn_Not eTitleIEN  == null ||  vcmn_Note TitleIEN = = '') {
  2253                alert('T he selecte d note tit le field i s empty, t he note ca nnot be cr eated in V istA/CPRS! ');
  2254                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2255                return f alse;
  2256           }
  2257           // Verify Loc ation
  2258           va r vcmn_Loc ationIEN =  Xrm.Page. getAttribu te('ftp_se lectedwork loadlocati onid').get Value();
  2259           if  (vcmn_Loc ationIEN = = null ||  vcmn_Locat ionIEN ==  '') {
  2260                alert('T he selecte d location  field is  empty, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  2261                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2262                return f alse;
  2263           }
  2264           // Verify pat ient id
  2265           if  (vcmn_mat chLookupId  == null | | vcmn_mat chLookupId  == '') {
  2266                alert('T he veteran /patient d oes not ha ve a SSN,  the note c annot be c reated in  VistA/CPRS !');
  2267                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2268                return f alse;
  2269           }
  2270  
  2271           // Get the cu rrent CRM  User's ass igned site /facility
  2272           va r vcmn_use rSiteId =  "";
  2273  
  2274           va r vcmn_use rData = vc mn_getSing leEntityDa taSync('Sy stemUserSe t', 'ftp_F acilitySit eId', Xrm. Page.conte xt.getUser Id());
  2275           if  (vcmn_use rData != n ull) {
  2276                if (vcmn _userData. d.ftp_Faci litySiteId  != null)  {
  2277                    vcmn _userSiteI d = vcmn_u serData.d. ftp_Facili tySiteId.I d;
  2278                }
  2279           }
  2280  
  2281           // Lookup the  Facility/ Site #
  2282           if  (vcmn_use rSiteId !=  null && v cmn_userSi teId != '' ) {
  2283                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e', vcmn_u serSiteId) ;
  2284                if (vcmn _facilityD ata != nul l) {
  2285                    if ( vcmn_facil ityData.d. ftp_facili tycode !=  null) { vc mn_ViaLogi nFacility  = vcmn_fac ilityData. d.ftp_faci litycode;  }
  2286                }
  2287           }
  2288  
  2289           // Check if V IA Login c ookie exis t (not exp ired)
  2290           va r vcmn_Via LoginCooki e = vcmn_g etCookie(" viasession link");
  2291           if  (vcmn_Via LoginCooki e != null  && vcmn_Vi aLoginCook ie != '')  {
  2292                var vcmn _cookiearr ay = vcmn_ ViaLoginCo okie.split ("~~~~", 3 );
  2293                vcmn_Via LoginToken  = vcmn_co okiearray[ 0];
  2294                vcmn_Via LoginName  = vcmn_coo kiearray[1 ];
  2295                vcmn_esi gnatureCod e = vcmn_c ookiearray [2];
  2296           }
  2297           el se {
  2298                alert("Y our VISTA  session ha s expired.  In order  to process  a workloa d encounte r note, yo u must be  logged int o VISTA!") ;
  2299                Xrm.Page .ui.tabs.g et('Tab_Vi stALogin') .setVisibl e(true);
  2300                Xrm.Page .ui.tabs.g et('Tab_Vi stALogin') .setFocus( );
  2301                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2302                return;
  2303           }
  2304  
  2305           // Lookup Pat ient Id us ing VIA 'm atch' serv ice
  2306           vi alib_match (vcmn_requ estingApp,  vcmn_cons umingAppTo ken, vcmn_ consumingA ppPassword , vcmn_bas eServiceEn dpointUrl,  vcmn_ViaL oginName,  vcmn_ViaLo ginToken,  vcmn_ViaLo ginFacilit y, vcmn_ma tchLookupI d, vcmn_pr epWorkload EncounterI ntegration Step01_res ponse);
  2307       }
  2308       catch  (err) {
  2309           al ert('Progr ess Note R ibbon Func tion Error (vcmn_prep WorkloadEn counterInt egrationSt ep01): ' +  err.messa ge);
  2310           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2311       }
  2312   }
  2313  
  2314   function v cmn_prepWo rkloadEnco unterInteg rationStep 01_respons e(vcmn_err or, vcmn_m atchrespon se) {
  2315       try {
  2316           // Check for  non VIA se rvice erro r
  2317           if  (vcmn_err or != null ) {
  2318                alert("U nable to m atch the C RM Veteran /Patient w ith a reco rd in Vist A/CPRS. Th e process  failed wit h error: "  + vcmn_ma tchrespons e + ", the  note cann ot be crea ted in Vis tA/CPRS!") ;
  2319                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2320                return f alse;
  2321           }
  2322           el se {
  2323                //Test f or VIA Ser vice Error
  2324                if (vcmn _matchresp onse.getEl ementsByTa gName("fau lt").lengt h > 0) {
  2325                    aler t("Unable  to match t he CRM Vet eran/Patie nt with a  record in  Vista/CPRS . Service  Error: " +  vcmn_matc hresponse. getElement sByTagName ("fault")[ 0].textCon tent + ",  the note c annot be c reated in  VistA/CPRS !");
  2326                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2327                    retu rn false;
  2328                }
  2329                //Get VI A service  Response
  2330                if (vcmn _matchresp onse.getEl ementsByTa gName("pat ients")[0] ) {
  2331                    var  vcmn_match Array = vc mn_matchre sponse.get ElementsBy TagName("p atients")[ 0].childNo des;
  2332                    //ch ildNodes[4 ] holds th e localPid /IEN value
  2333                    vcmn _ViaPatien tId = vcmn _matchArra y[0].child Nodes[4].t extContent ;
  2334                }
  2335                else {
  2336                    aler t("Unable  to match t he CRM Vet eran/Patie nt with a  record in  Vista/CPRS . No data  returned,  the note c annot be c reated in  VistA/CPRS !");
  2337                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2338                    retu rn false;
  2339                }
  2340           }
  2341  
  2342           // Verify Inp atient
  2343           if  (Xrm.Page .getAttrib ute('ftp_w orkloadinp atient').g etValue()  == true) {
  2344                vcmn_Via InPatient  = "1";
  2345           }
  2346           el se {
  2347                vcmn_Via InPatient  = "0";
  2348           }
  2349  
  2350           // Verify CPT  Code & De scription
  2351           va r vcmn_Crm CptCode =  Xrm.Page.g etAttribut e('ftp_cpt code').get Value();
  2352           if  (vcmn_Crm CptCode ==  null) {
  2353                alert('T he CPT Cod e field is  empty, th e note can not be cre ated in Vi stA/CPRS!' );
  2354                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2355                return f alse;
  2356           }
  2357           el se {
  2358                var vcmn _cptData =  vcmn_getS ingleEntit yDataSync( 'ftp_cptco deSet', 'f tp_amadesc ription',  vcmn_CrmCp tCode[0].i d);
  2359                if (vcmn _cptData.d .ftp_amade scription  != null) {
  2360                    vcmn _ViaCptDes cription =  (vcmn_cpt Data.d.ftp _amadescri ption).rep lace(";",  "\;");
  2361                    vcmn _ViaCptCod e = vcmn_C rmCptCode[ 0].name;
  2362                }
  2363                else {
  2364                    aler t('The CPT  Code is m issing the  AMA Descr iption, th e note can not be cre ated in Vi stA/CPRS!' );
  2365                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2366                    retu rn false;
  2367                }
  2368           }
  2369  
  2370           // Combine CP T Code and  Descripti on
  2371           va r vcmn_Cpt Combined =  '';
  2372           if  (vcmn_Via CptCode.le ngth > 0 & & vcmn_Via CptDescrip tion.lengt h > 0) {
  2373                vcmn_Cpt Combined =  vcmn_ViaC ptCode + " ^" + vcmn_ ViaCptDesc ription;
  2374           }
  2375  
  2376           // Verify Dia gnosis Cod e & Descri ption
  2377           va r vcmn_Crm DiagnosisC ode = Xrm. Page.getAt tribute('f tp_diagnos iscode').g etValue();
  2378           if  (vcmn_Crm DiagnosisC ode == nul l) {
  2379                alert('T he Primary  Diagnosis  Code fiel d is empty , the note  cannot be  created i n VistA/CP RS!');
  2380                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2381                return f alse;
  2382           }
  2383  
  2384           if  (vcmn_Crm DiagnosisC ode != nul l && vcmn_ CrmDiagnos isCode !=  '') {
  2385                var vcmn _diagnosis Data = vcm n_getSingl eEntityDat aSync('ftp _diagnosis codeSet',  'ftp_descr iption', v cmn_CrmDia gnosisCode [0].id);
  2386                if (vcmn _diagnosis Data.d.ftp _descripti on != null ) {
  2387                    vcmn _ViaDiagno sisDescrip tion = (vc mn_diagnos isData.d.f tp_descrip tion).repl ace(";", " \;");
  2388                    vcmn _ViaDiagno sisCode =  vcmn_CrmDi agnosisCod e[0].name;
  2389                }
  2390           }
  2391  
  2392           // Combine Di agnosis Co de and Des cription a nd mark as  PRIMARY ( ^1)
  2393           va r vcmn_Dia gnosisComb ined = '';
  2394           if  (vcmn_Via DiagnosisC ode != nul l && vcmn_ ViaDiagnos isDescript ion != nul l) {
  2395                if (vcmn _ViaDiagno sisCode.le ngth > 0 & & vcmn_Via DiagnosisD escription .length >  0) {
  2396                    vcmn _Diagnosis Combined =  vcmn_ViaD iagnosisCo de + "^" +  vcmn_ViaD iagnosisDe scription  + "^1";
  2397                }
  2398           }
  2399  
  2400           // Get Second ary Diagno sis Codes
  2401           va r vcmn_Crm SecondaryD iagnosis =  Xrm.Page. getAttribu te('ftp_se lectedseco ndarydiagn osiscodes' ).getValue ();
  2402           if  (vcmn_Crm SecondaryD iagnosis ! = null &&  vcmn_CrmSe condaryDia gnosis !=  '') {
  2403                if (vcmn _Diagnosis Combined ! = '') {
  2404                    vcmn _Diagnosis Combined =  vcmn_Diag nosisCombi ned + ";"  + vcmn_Crm SecondaryD iagnosis;
  2405                }
  2406                else { v cmn_Diagno sisCombine d = vcmn_C rmSecondar yDiagnosis ; }
  2407           }
  2408  
  2409           // Get eSigna ture code
  2410           // This secti on is no l onger used , replaced  by via lo gin contro l esignatu re
  2411           /*
  2412           va r vcmn_eSi gnatureCod e = prompt ("Please e nter your  eSignature  Code belo w.\nThis i s required  to comple te the Wor kload Enco unter Note !");
  2413           if  (vcmn_eSi gnatureCod e == null  || vcmn_eS ignatureCo de == "" | | vcmn_eSi gnatureCod e == "unde fined") {
  2414                alert('T he eSignat ure Code e ntered is  invalid, t he note ca nnot be cr eated in V istA/CPRS! ');
  2415                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2416                return f alse;
  2417           }
  2418           */
  2419  
  2420           // Get User E ntry Date
  2421           va r vcmn_cre atedOnDate  = vialib_ convertToS tringDateT ime(Xrm.Pa ge.getAttr ibute('cre atedon').g etValue()) ;
  2422           va r vcmn_use rEntryDate  = null;
  2423           if  (Xrm.Page .getAttrib ute('ftp_u serentryda te').getVa lue() != n ull) {
  2424                vcmn_use rEntryDate  = vialib_ convertToS tringDateT ime(Xrm.Pa ge.getAttr ibute('ftp _userentry date').get Value());
  2425           }
  2426           if  (vcmn_use rEntryDate  == null)  { vcmn_use rEntryDate  = vcmn_cr eatedOnDat e; }
  2427  
  2428           // Reformat N ote Descri ption as n eeded to h andle long  lines of  text (Word Wrap)
  2429           va r vcmn_not eDescripti on = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  2430           va r vcmn_Not eText = vc mn_noteDes cription;
  2431           va r vcmn_Rev isedNoteTe xt = "";
  2432           // Do Breakdo wn of line s
  2433           va r vcmn_Tex tLines = v cmn_NoteTe xt.split(' \n');
  2434           if  (vcmn_Tex tLines.len gth > 0) {
  2435                //Reform at text
  2436                for (var  i = 0; i  < vcmn_Tex tLines.len gth; i++)  {
  2437                    //Te st for a l ong line
  2438                    if ( vcmn_TextL ines[i].le ngth > vcm n_WordWrap Limit) {
  2439                         //Break do wn line
  2440                         var vcmn_N ewString =  vcmn_word Wrap(vcmn_ TextLines[ i], vcmn_W ordWrapLim it, '\n');
  2441                         //Add revi sed text b ack
  2442                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _NewString  + "\n";   //Add back  the CR/LF  used to s plit on
  2443                    }
  2444                    else  {
  2445                         //Add text  to new no te
  2446                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _TextLines [i] + "\n" ; //Add ba ck the CR/ LF used to  split on
  2447                    }
  2448                }
  2449           }
  2450           if  (vcmn_Rev isedNoteTe xt != "" & & vcmn_Rev isedNoteTe xt != null ) {
  2451                vcmn_not eDescripti on = vcmn_ RevisedNot eText;
  2452           }
  2453  
  2454           // Add list o f addition al signer  names to N ote Text i f they exi sts
  2455           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  2456                //Create  text stri ngs from a dditional  signers ar ray
  2457                var vcmn _SignerNam es = "\nAd ditional N ote Signer s\n" + "-- ---------- ---------- -------\n" ;
  2458                for (var  i = 0; i  <= vcmn_Ad dlSignersN ameArray.l ength - 1;  i++) {
  2459                    if ( i >= 1) {
  2460                         var vcmn_s ingleSigne rName = vc mn_AddlSig nersNameAr ray[i].spl it("___");
  2461                         vcmn_Signe rNames = v cmn_Signer Names + vc mn_singleS ignerName[ 1] + "\n";
  2462                    }
  2463                }
  2464                //Add to  Note Desc ription
  2465                vcmn_not eDescripti on = vcmn_ noteDescri ption + vc mn_SignerN ames;
  2466           }
  2467           va r vcmn_Not eTitleIEN  = Xrm.Page .getAttrib ute('ftp_s electedwor kloadnotet itleid').g etValue();
  2468           va r vcmn_Loc ationIEN =  Xrm.Page. getAttribu te('ftp_se lectedwork loadlocati onid').get Value();
  2469  
  2470           // Create tex t strings  from addit ional sign ers array
  2471           va r vcmn_Sig nerIEN = " ";
  2472           if  (vcmn_Add lSignersIe nArray !=  null) {
  2473                for (var  i = 0; i  <= vcmn_Ad dlSignersI enArray.le ngth - 1;  i++) {
  2474                    if ( i == 1) {  vcmn_Signe rIEN = vcm n_AddlSign ersIenArra y[i]; }
  2475                    if ( i > 1) { v cmn_Signer IEN = vcmn _SignerIEN  + "," + v cmn_AddlSi gnersIenAr ray[i]; }
  2476                }
  2477           }
  2478  
  2479           // Reformat N ote Descri ption for  VIA Note a nd Encount er web ser vice to ha ndle line  feed and c arriage re turn
  2480           // Replace al l \n and \ r occurren ces with |
  2481           vc mn_noteDes cription =  vcmn_note Descriptio n.replace( /\n/g, "|" );
  2482           vc mn_noteDes cription =  vcmn_note Descriptio n.replace( /\r/g, "|" );
  2483  
  2484           // Execute VI A saveNote AndEncount er Service
  2485           vi alib_saveN oteAndEnco unter(vcmn _requestin gApp, vcmn _consuming AppToken,  vcmn_consu mingAppPas sword, vcm n_baseServ iceEndpoin tUrl, vcmn _ViaLoginN ame, vcmn_ ViaLoginTo ken, vcmn_ ViaLoginFa cility, vc mn_NoteTit leIEN, vcm n_Location IEN, vcmn_ ViaPatient Id, vcmn_n oteDescrip tion, vcmn _userEntry Date, vcmn _ViaLoginF acility, v cmn_ViaInP atient, vc mn_CptComb ined, vcmn _Diagnosis Combined,  vcmn_esign atureCode,  vcmn_Sign erIEN, 'E' , vcmn_sav eNoteAndEn counter_re sponse)
  2486       }
  2487       catch  (err) {
  2488           al ert('Progr ess Note R ibbon Func tion Error (vcmn_prep WorkloadEn counterInt egrationSt ep01_respo nse): ' +  err.messag e);
  2489           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2490       }
  2491   }
  2492  
  2493   function v cmn_saveNo teAndEncou nter_respo nse(vcmn_e rrorThrown , vcmn_req uestRespon se, vcmn_n oteText) {
  2494       //Proc ess Note a nd Encount er Respons e
  2495       try {
  2496           if  (vcmn_err orThrown ! = null) {
  2497                //Write  Error
  2498                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etValue('E RROR');
  2499                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etSubmitMo de('always ');
  2500                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tValue(Str ing(vcmn_e rrorThrown ));
  2501                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tSubmitMod e('always' );
  2502                Xrm.Page .getAttrib ute('ftp_i ntegration date').set Value(new  Date());
  2503                Xrm.Page .getAttrib ute('ftp_i ntegration date').set SubmitMode ('always') ;
  2504                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etValue('' );
  2505                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etSubmitMo de('always ');
  2506                alert('T he workloa d encounte r note cre ation in V istA/CPRS  failed!\nP lease see  the integr ation erro r field fo r details. ');
  2507                Xrm.Page .getContro l('ftp_int egrationer ror').setF ocus();
  2508                Xrm.Page .data.enti ty.save();
  2509                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2510                return f alse;
  2511           }
  2512           el se {
  2513                //Write  web servic e response  Success o r Failure
  2514                if (vcmn _requestRe sponse.get ElementsBy TagName("f ault").len gth > 0) {
  2515                    //Wr ite Failur e entry
  2516                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setValu e('ERROR') ;
  2517                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setSubm itMode('al ways');
  2518                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setValue ("Service  Error: " +  vcmn_requ estRespons e.getEleme ntsByTagNa me("fault" )[0].textC ontent);
  2519                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setSubmi tMode('alw ays');
  2520                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setValue( new Date() );
  2521                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setSubmit Mode('alwa ys');
  2522                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setValu e('');
  2523                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setSubm itMode('al ways');
  2524                    aler t('The wor kload enco unter note  creation  in VistA/C PRS failed !\nPlease  see the in tegration  error fiel d for deta ils.');
  2525                    Xrm. Page.getCo ntrol('ftp _integrati onerror'). setFocus() ;
  2526                    Xrm. Page.data. entity.sav e();
  2527                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2528                    retu rn false;
  2529                }
  2530                else {
  2531                    //Te st for dat a
  2532                    if ( vcmn_reque stResponse .getElemen tsByTagNam e("ns2:sav eNoteAndEn counterRes ponse")[0] ) {
  2533                         //Sucessfu ll creatio n of workl oad encoun ter note
  2534                         Xrm.Page.g etAttribut e('ftp_not edetail'). setValue(v cmn_noteTe xt);
  2535                         Xrm.Page.g etAttribut e('ftp_not edetail'). setSubmitM ode('alway s');
  2536                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set Value('OK' );
  2537                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set SubmitMode ('always') ;
  2538                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setV alue(null) ;
  2539                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setS ubmitMode( 'always');
  2540                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setVa lue(new Da te());
  2541                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setSu bmitMode(' always');
  2542                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set Value(vcmn _requestRe sponse.get ElementsBy TagName("n s2:saveNot eAndEncoun terRespons e")[0].tex tContent);
  2543                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set SubmitMode ('always') ;
  2544                         //****UPDA TE e-Sign  attributes
  2545                         Xrm.Page.g etAttribut e('ftp_iss igned').se tValue(tru e);
  2546                         Xrm.Page.g etAttribut e('ftp_iss igned').se tSubmitMod e('always' );
  2547                         Xrm.Page.g etAttribut e('ftp_sig neddate'). setValue(n ew Date()) ;
  2548                         Xrm.Page.g etAttribut e('ftp_sig neddate'). setSubmitM ode('alway s');
  2549                         //******** ********** **********
  2550                         Xrm.Page.g etControl( 'ftp_integ rationstat us').setFo cus();
  2551                         alert('The  workload  encounter  note creat ion in Vis tA/CPRS wa s successf ul, this w orkload en counter 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!');
  2552                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  2553                         Xrm.Page.d ata.entity .save();
  2554  
  2555                         if (vcmn_l ocalStorag eVarName ! = "" && vc mn_localSt orageVarNa me != null ) {
  2556                             //Clea r existing  session s torage var iable.
  2557                             localS torage.rem oveItem(vc mn_localSt orageVarNa me);
  2558                         }
  2559                    }
  2560                    else  {
  2561                         //Write No  Data Fail ure
  2562                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set Value('ERR OR');
  2563                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set SubmitMode ('always') ;
  2564                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setV alue("Serv ice Error:  NO DATA R ETURNED FR OM VIA/VIS TA REGARDI NG WORKLOA D WITH ENC OUNTER NOT E CREATION !");
  2565                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setS ubmitMode( 'always');
  2566                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setVa lue(new Da te());
  2567                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setSu bmitMode(' always');
  2568                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set Value('');
  2569                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set SubmitMode ('always') ;
  2570                         alert('The  workload  encounter  note creat ion in Vis tA/CPRS fa iled!\nPle ase see th e integrat ion error  field for  details.') ;
  2571                         Xrm.Page.g etControl( 'ftp_integ rationerro r').setFoc us();
  2572                         Xrm.Page.d ata.entity .save();
  2573                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  2574                         return fal se;
  2575                    }
  2576                }
  2577           }
  2578       }
  2579       catch  (err) {
  2580           al ert('Progr ess Note R ibbon Func tion Error (vcmn_save NoteAndEnc ounter_res ponse): '  + err.mess age);
  2581           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2582       }
  2583   }
  2584  
  2585   function v cmn_getVis taUsersDat a(vcmn_use rFirstName , vcmn_use rLastName,  vcmn_user SiteNo, vc mn_noFilte r) {
  2586       try {
  2587           va r vcmn_jso nData = nu ll;
  2588           $. ajax({
  2589                type: "G ET",
  2590                url: vcm n_VistaUse rsURLbase  + vcmn_use rFirstName  + "/" + v cmn_userLa stName + " /" + vcmn_ userSiteNo  + "?noFil ter=" + vc mn_noFilte r,
  2591                contentT ype: "appl ication/js on; charse t=utf-8",
  2592                dataType : "json",
  2593                success:  function  (data) {
  2594                    vcmn _jsonData  = data;
  2595                },
  2596                error: f unction (j qXHR, text Status, er rorThrown)  {
  2597                    //Sy stem Error
  2598                    vcmn _jsonData  = null;
  2599                },
  2600                async: f alse,
  2601                cache: f alse
  2602           }) ;
  2603           re turn vcmn_ jsonData;
  2604       }
  2605       catch  (err) {
  2606           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getV istaUsersD ata): ' +  err.messag e);
  2607           re turn null;
  2608       }
  2609   }
  2610  
  2611   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) {
  2612       try {
  2613           // Reformat N ote Descri ption as n eeded to h andle long  lines of  text (Word Wrap)
  2614           va r vcmn_Not eText = vc mn_noteDes cription;
  2615           va r vcmn_Rev isedNoteTe xt = "";
  2616           // Do Breakdo wn of line s
  2617           va r vcmn_Tex tLines = v cmn_NoteTe xt.split(' \n');
  2618           if  (vcmn_Tex tLines.len gth > 0) {
  2619                //Reform at text
  2620                for (var  i = 0; i  < vcmn_Tex tLines.len gth; i++)  {
  2621                    //Te st for a l ong line
  2622                    if ( vcmn_TextL ines[i].le ngth > vcm n_WordWrap Limit) {
  2623                         //Break do wn line
  2624                         var vcmn_N ewString =  vcmn_word Wrap(vcmn_ TextLines[ i], vcmn_W ordWrapLim it, '\n');
  2625                         //Add revi sed text b ack
  2626                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _NewString  + "\n";   //Add back  the CR/LF  used to s plit on
  2627                    }
  2628                    else  {
  2629                         //Add text  to new no te
  2630                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _TextLines [i] + "\n" ; //Add ba ck the CR/ LF used to  split on
  2631                    }
  2632                }
  2633           }
  2634           if  (vcmn_Rev isedNoteTe xt != "" & & vcmn_Rev isedNoteTe xt != null ) {
  2635                vcmn_not eDescripti on = vcmn_ RevisedNot eText;
  2636           }
  2637  
  2638           // Add list o f addition al signer  names to N ote Text i f they exi sts
  2639           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  2640                //Create  text stri ngs from a dditional  signers ar ray
  2641                var vcmn _SignerNam es = "\nAd ditional N ote Signer s\n" + "-- ---------- ---------- -------\n" ;
  2642                for (var  i = 0; i  <= vcmn_Ad dlSignersN ameArray.l ength - 1;  i++) {
  2643                    if ( i >= 1) {
  2644                         var vcmn_s ingleSigne rName = vc mn_AddlSig nersNameAr ray[i].spl it("___");
  2645                         vcmn_Signe rNames = v cmn_Signer Names + vc mn_singleS ignerName[ 1] + "\n";
  2646                    }
  2647                }
  2648                //Add to  Note Desc ription
  2649                vcmn_not eDescripti on = vcmn_ noteDescri ption + vc mn_SignerN ames;
  2650           }
  2651  
  2652           va r vcmn_vis itNumber =  'NEW';
  2653           va r vcmn_cli entName =  "FTPCRM";
  2654           va r vcmn_For mat = "JSO N";
  2655           va r vcmn_pat ientIdenti fierType =  "ICN";
  2656           va r vcmn_doc umentAvail abilitySta tus = "AV" ;  //Histo rical Note  only at t his time
  2657           va r vcmn_ori ginatorCom binedMiddl e = "";
  2658           if  (vcmn_ori ginatorMid dleName !=  '' && vcm n_originat orMiddleNa me != null ) { vcmn_o riginatorC ombinedMid dle = vcmn _originato rMiddleNam e; }
  2659           if  (vcmn_ori ginatorSuf fix != ''  && vcmn_or iginatorSu ffix != nu ll) {
  2660                if (vcmn _originato rCombinedM iddle != ' ') {
  2661                    vcmn _originato rCombinedM iddle = vc mn_origina torCombine dMiddle +  " " + vcmn _originato rSuffix;
  2662                }
  2663                else {
  2664                    vcmn _originato rCombinedM iddle = vc mn_origina torSuffix;
  2665                }
  2666           }
  2667  
  2668           va r vcmn_req uestJSON =  {
  2669                "ClientN ame": vcmn _clientNam e,
  2670                "Format" : vcmn_For mat,
  2671                "Facilit ySiteID":  vcmn_facil itySiteId,
  2672                "SiteHL7 ListenerAd dress": vc mn_siteHL7 ListenerAd dress,
  2673                "VisitNu mber": vcm n_visitNum ber,
  2674                "IsSigne dNote": vc mn_signThi sNote,
  2675                "Patient AdmitDate" : vcmn_pat ientAdmitD ate,
  2676                "Patient LastName":  vcmn_pati entLastNam e,
  2677                "Patient FirstName" : vcmn_pat ientFirstN ame,
  2678                "Patient Identifier ": vcmn_pa tientICN,
  2679                "Patient Identifier Type": vcm n_patientI dentifierT ype,
  2680                "Patient AssignedLo cation": v cmn_patien tAssignedL ocation,
  2681                "NoteTex t": vcmn_n oteDescrip tion,
  2682                "Origina torID": vc mn_origina torID,
  2683                "Origina torFirstNa me": vcmn_ originator FirstName,
  2684                "Origina torMiddleN ame": vcmn _originato rCombinedM iddle,
  2685                "Origina torLastNam e": vcmn_o riginatorL astName,
  2686                "Documen tFileName" : vcmn_loc alTitle,
  2687                "Documen tAvailabil ityStatus" : vcmn_doc umentAvail abilitySta tus,
  2688                "Activit yDate": vc mn_activit yDate
  2689           };
  2690  
  2691           va r vcmn_req uestRespon se = "";
  2692  
  2693           $. ajax({
  2694                type: "P OST",
  2695                url: vcm n_NoteWrit eUrl,
  2696                data: JS ON.stringi fy(vcmn_re questJSON) ,
  2697                contentT ype: "appl ication/js on; charse t=utf-8",
  2698                dataType : "json",
  2699                success:  function  (data) {
  2700                    var  vcmn_newda ta = data;
  2701                    vcmn _requestRe sponse = v cmn_newdat a;
  2702                    vcmn _vistAInte grationReq uest_respo nse(null,  vcmn_reque stResponse , vcmn_not eDescripti on);
  2703                },
  2704                error: f unction (j qXHR, text Status, er rorThrown)  {
  2705                    //Sy stem Error
  2706                    vcmn _vistAInte grationReq uest_respo nse(errorT hrown, nul l, vcmn_no teDescript ion);
  2707                },
  2708                async: f alse,
  2709                cache: f alse
  2710           }) ;
  2711       }
  2712       catch  (err) {
  2713           al ert('Progr ess Note R ibbon Func tion Error (vcmn_exec uteVistAIn tegrationR equest): '  + err.mes sage);
  2714           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2715       }
  2716   }
  2717  
  2718   function v cmn_vistAI ntegration Request_re sponse(vcm n_errorThr own, vcmn_ requestRes ponse, vcm n_noteDesc ription) {
  2719       try {
  2720           // Process In tegration  Request Re sponse
  2721           if  (vcmn_err orThrown ! = null) {
  2722                //Write  Error
  2723                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etValue('E RROR');
  2724                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etSubmitMo de('always ');
  2725                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tValue(Str ing(vcmn_e rrorThrown ));
  2726                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tSubmitMod e('always' );
  2727                Xrm.Page .getAttrib ute('ftp_i ntegration date').set Value(new  Date());
  2728                Xrm.Page .getAttrib ute('ftp_i ntegration date').set SubmitMode ('always') ;
  2729                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etValue('' );
  2730                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etSubmitMo de('always ');
  2731                alert('T he note cr eation in  VistA/CPRS  failed!\n Please see  the integ ration err or field f or details .');
  2732                Xrm.Page .getContro l('ftp_int egrationer ror').setF ocus();
  2733                Xrm.Page .data.enti ty.save();
  2734                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2735                return f alse;
  2736           }
  2737           el se {
  2738                //Write  web servic e response  Success o r Failure
  2739                if (vcmn _requestRe sponse.Err orOccurred  == false)  {
  2740                    //Ca ll Additio nal Signer s & Finali ze Note fu nction
  2741                    vcmn _finalizeN oteCreatio n(vcmn_req uestRespon se.Status,  vcmn_requ estRespons e.Data, vc mn_noteDes cription)
  2742                }
  2743                else {
  2744                    //Wr ite Failur e entry
  2745                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setValu e(vcmn_req uestRespon se.Status) ;
  2746                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setSubm itMode('al ways');
  2747                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setValue (vcmn_requ estRespons e.ErrorMes sage + "   DebugInfo: " + vcmn_r equestResp onse.Debug Info);
  2748                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setSubmi tMode('alw ays');
  2749                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setValue( new Date() );
  2750                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setSubmit Mode('alwa ys');
  2751                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setValu e('');
  2752                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setSubm itMode('al ways');
  2753                    aler t('The not e creation  in VistA/ CPRS faile d!\nPlease  see the i ntegration  error fie ld for det ails.');
  2754                    Xrm. Page.getCo ntrol('ftp _integrati onerror'). setFocus() ;
  2755                    Xrm. Page.data. entity.sav e();
  2756                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2757                    retu rn false;
  2758                }
  2759           }
  2760       }
  2761       catch  (err) {
  2762           al ert('Progr ess Note R ibbon Func tion Error (vcmn_vist AIntegrati onRequest_ response):  ' + err.m essage);
  2763           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2764       }
  2765   }
  2766  
  2767   function v cmn_finali zeNoteCrea tion(vcmn_ integratio nStatus, v cmn_integr ationNoteI d, vcmn_no teDescript ion) {
  2768       //The  Note was s ucessfully  created i n Vista/CP RS, add ad ditional s igners if  needed
  2769       try {
  2770           // Determine  if additio nal signer s exists
  2771           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  2772                //Get th e current  CRM User's  assigned  site/facil ity
  2773                var vcmn _userSiteI d = "";
  2774                var vcmn _UserSiteN o = "";
  2775                var vcmn _duz = "";
  2776                var vcmn _providern ame = "";
  2777  
  2778                var vcmn _userData  = vcmn_get SingleEnti tyDataSync ('SystemUs erSet', 'f tp_Facilit ySiteId',  Xrm.Page.c ontext.get UserId());
  2779                if (vcmn _userData  != null) {
  2780                    if ( vcmn_userD ata.d.ftp_ FacilitySi teId != nu ll) {
  2781                         vcmn_userS iteId = vc mn_userDat a.d.ftp_Fa cilitySite Id.Id;
  2782                    }
  2783                }
  2784  
  2785                //Lookup  the Facil ity/Site #
  2786                if (vcmn _userSiteI d != null  && vcmn_us erSiteId ! = '') {
  2787                    var  vcmn_facil ityData =  vcmn_getSi ngleEntity DataSync(' ftp_facili tySet', 'f tp_facilit ycode', vc mn_userSit eId);
  2788                    if ( vcmn_facil ityData !=  null) {
  2789                         if (vcmn_f acilityDat a.d.ftp_fa cilitycode  != null)  { vcmn_Use rSiteNo =  vcmn_facil ityData.d. ftp_facili tycode; }
  2790                    }
  2791                }
  2792  
  2793                //Check  if VIA Log in cookie  exist (not  expired)
  2794                var vcmn _ViaLoginC ookie = vc mn_getCook ie("viases sionlink") ;
  2795                if (vcmn _ViaLoginC ookie != n ull && vcm n_ViaLogin Cookie !=  '') {
  2796                    var  vcmn_cooki earray = v cmn_ViaLog inCookie.s plit("~~~~ ", 3);
  2797                    vcmn _duz = vcm n_cookiear ray[0];
  2798                    vcmn _providern ame = vcmn _cookiearr ay[1];
  2799                    vcmn _esignatur eCode = vc mn_cookiea rray[2];
  2800                }
  2801  
  2802                //Create  text stri ngs from a dditional  signers ar ray
  2803                var vcmn _SignerIEN  = "";
  2804                for (var  i = 0; i  <= vcmn_Ad dlSignersI enArray.le ngth - 1;  i++) {
  2805                    if ( i == 1) {  vcmn_Signe rIEN = vcm n_AddlSign ersIenArra y[i]; }
  2806                    if ( i > 1) { v cmn_Signer IEN = vcmn _SignerIEN  + " " + v cmn_AddlSi gnersIenAr ray[i]; }
  2807                }
  2808  
  2809                //Create  the Addit ional Sign ers
  2810                var vcmn _viaSigner s = new Ob ject();
  2811                vcmn_via Signers.Pr oviderName  = vcmn_pr ovidername ;
  2812                vcmn_via Signers.Du z = vcmn_d uz;
  2813                vcmn_via Signers.Lo ginSiteCod e = vcmn_U serSiteNo;
  2814                vcmn_via Signers.Ta rget = vcm n_integrat ionNoteId;
  2815                vcmn_via Signers.Su pplemental Parameters  = vcmn_Si gnerIEN;
  2816  
  2817                $.ajax({
  2818                    type : "POST",
  2819                    url:  vcmn_AddS ignersUrl,
  2820                    data : JSON.str ingify(vcm n_viaSigne rs),
  2821                    cont entType: " applicatio n/json; ch arset=utf- 8",
  2822                    data Type: "jso n",
  2823                    succ ess: funct ion (data)  {
  2824                         vcmn_viaSi gnersRespo nse = JSON .stringify (data.Data );
  2825                         //Test for  Failure
  2826                         if (vcmn_v iaSignersR esponse.Er rorOccurre d == true)  {
  2827                             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!");
  2828                         }
  2829                    },
  2830                    erro r: functio n (jqXHR,  textStatus , errorThr own) {
  2831                         //System E rror
  2832                         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!");
  2833                    },
  2834                    asyn c: false,
  2835                    cach e: false
  2836                });
  2837  
  2838                if (vcmn _localStor ageVarName  != "" &&  vcmn_local StorageVar Name != nu ll) {
  2839                    //Cl ear existi ng session  storage v ariable.
  2840                    loca lStorage.r emoveItem( vcmn_local StorageVar Name);
  2841                }
  2842           }
  2843  
  2844           // Perform st andard for m updates  to signify  completio n
  2845           // Write Succ ess entry
  2846           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_noteDesc ription);
  2847           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  2848           Xr m.Page.get Attribute( 'ftp_integ rationstat us').setVa lue(vcmn_i ntegration Status);
  2849           Xr m.Page.get Attribute( 'ftp_integ rationstat us').setSu bmitMode(' always');
  2850           Xr m.Page.get Attribute( 'ftp_integ rationerro r').setVal ue(null);
  2851           Xr m.Page.get Attribute( 'ftp_integ rationerro r').setSub mitMode('a lways');
  2852           Xr m.Page.get Attribute( 'ftp_integ rationdate ').setValu e(new Date ());
  2853           Xr m.Page.get Attribute( 'ftp_integ rationdate ').setSubm itMode('al ways');
  2854           Xr m.Page.get Attribute( 'ftp_integ rationnote id').setVa lue(vcmn_i ntegration NoteId);
  2855           Xr m.Page.get Attribute( 'ftp_integ rationnote id').setSu bmitMode(' always');
  2856           Xr m.Page.get Control('f tp_integra tionstatus ').setFocu s();
  2857           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!');
  2858           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2859           Xr m.Page.dat a.entity.s ave();
  2860       }
  2861       catch  (err) {
  2862           al ert('Progr ess Note R ibbon Func tion Error (vcmn_fina lizeNoteCr eation): '  + err.mes sage);
  2863           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2864       }
  2865   }
  2866  
  2867   function v cmn_getCoo kie(cname)  {
  2868       try {
  2869           va r name = c name + "=" ;
  2870           va r ca = doc ument.cook ie.split(' ;');
  2871           fo r (var i =  0; i < ca .length; i ++) {
  2872                var c =  ca[i];
  2873                while (c .charAt(0)  == ' ') {
  2874                    c =  c.substrin g(1);
  2875                }
  2876                if (c.in dexOf(name ) == 0) {
  2877                    retu rn c.subst ring(name. length, c. length);
  2878                }
  2879           }
  2880           re turn "";
  2881       }
  2882       catch  (err) {
  2883           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getC ookie): '  + err.mess age);
  2884       }
  2885   }
  2886  
  2887   function v cmn_initVi aDropdownC ontrols()  {
  2888       //Init ialize VIA  DropDown  Controls
  2889       //Func tion is tr iggered by  The VistA  Login Con trol and o nchange of  Facility  attribute
  2890       try {
  2891           Xr m.Page.get Control("W ebResource _ViaWorklo adLookup") .setSrc(Xr m.Page.get Control("W ebResource _ViaWorklo adLookup") .getSrc()) ;
  2892           Xr m.Page.get Control("W ebResource _ProgressN oteSignerS earch").se tSrc(Xrm.P age.getCon trol("WebR esource_Pr ogressNote SignerSear ch").getSr c());
  2893       }
  2894       catch  (err) {
  2895           al ert('Progr ess Note V IA Login F unction Er ror(vcmn_i nitViaDrop downContro ls): ' + e rr.message );
  2896       }
  2897   }
  2898  
  2899   function v cmn_facili tyGroupDef ault_respo nse(vcmn_f acilityGro upData, vc mn_lastSki p, vcmn_fa cilitySite Id) {
  2900       try {
  2901           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  2902           fo r (var i =  0; i <= v cmn_facili tyGroupDat a.d.result s.length -  1; i++) {
  2903                //Get Va lues and W rite to Pr ogress Not e if a new  Note
  2904                if (Xrm. Page.ui.ge tFormType( ) == 1) {
  2905                    if ( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ localnotes title != n ull) {
  2906                         Xrm.Page.g etAttribut e("ftp_loc alnotestit le").setVa lue(vcmn_f acilityGro upData.d.r esults[i]. ftp_localn otestitle) ;
  2907                         Xrm.Page.g etAttribut e('ftp_loc alnotestit le').setSu bmitMode(' always');
  2908                    }
  2909                    if ( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ hospitallo cation !=  null) {
  2910                         Xrm.Page.g etAttribut e("ftp_hos pitallocat ion").setV alue(vcmn_ facilityGr oupData.d. results[i] .ftp_hospi tallocatio n);
  2911                         Xrm.Page.g etAttribut e('ftp_hos pitallocat ion').setS ubmitMode( 'always');
  2912                    }
  2913                    if ( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ viaworkloa dencounter locationde fault != n ull) {
  2914                         //Verify t hat the te xt contain s the doub le tilde ~ ~
  2915                         if (vcmn_f acilityGro upData.d.r esults[i]. ftp_viawor kloadencou nterlocati ondefault. indexOf("~ ~") >= 0)  {
  2916                             //Spli t on ~~
  2917                             var vc mn_encount erLocation Array = vc mn_facilit yGroupData .d.results [i].ftp_vi aworkloade ncounterlo cationdefa ult.split( "~~", 2);
  2918                             if (vc mn_encount erLocation Array.leng th > 1) {
  2919                                 if  (vcmn_enc ounterLoca tionArray[ 0] != null  && vcmn_e ncounterLo cationArra y[0] != ''  && vcmn_e ncounterLo cationArra y[1] != nu ll && vcmn _encounter LocationAr ray[1] !=  '') {
  2920                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat ionid").se tValue(vcm n_encounte rLocationA rray[0]);
  2921                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat ionid").se tSubmitMod e('always' );
  2922                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat iontext"). setValue(v cmn_encoun terLocatio nArray[1]) ;
  2923                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat iontext"). setSubmitM ode('alway s');
  2924                                 }
  2925                             }
  2926                         }
  2927                    }
  2928                    if ( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ viaworkloa dencounter notetitled efault !=  null) {
  2929                         //Verify t hat the te xt contain s the doub le tilde ~ ~
  2930                         if (vcmn_f acilityGro upData.d.r esults[i]. ftp_viawor kloadencou nternoteti tledefault .indexOf(" ~~") >= 0)  {
  2931                             //Spli t on ~~
  2932                             var vc mn_encount erNoteTitl eArray = v cmn_facili tyGroupDat a.d.result s[i].ftp_v iaworkload encountern otetitlede fault.spli t("~~", 2) ;
  2933                             if (vc mn_encount erNoteTitl eArray.len gth > 1) {
  2934                                 if  (vcmn_enc ounterNote TitleArray [0] != nul l && vcmn_ encounterN oteTitleAr ray[0] !=  '' && vcmn _encounter NoteTitleA rray[1] !=  null && v cmn_encoun terNoteTit leArray[1]  != '') {
  2935                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itleid").s etValue(vc mn_encount erNoteTitl eArray[0]) ;
  2936                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itleid").s etSubmitMo de('always ');
  2937                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itletext") .setValue( vcmn_encou nterNoteTi tleArray[1 ]);
  2938                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itletext") .setSubmit Mode('alwa ys');
  2939                                 }
  2940                             }
  2941                         }
  2942                    }
  2943                    if ( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ historical notetitled efault !=  null) {
  2944                         vcmn_setSi mpleLookup Value('ftp _localnote title', vc mn_facilit yGroupData .d.results [i].ftp_hi storicalno tetitledef ault.Logic alName, vc mn_facilit yGroupData .d.results [i].ftp_hi storicalno tetitledef ault.Id, v cmn_facili tyGroupDat a.d.result s[i].ftp_h istoricaln otetitlede fault.Name );
  2945                         Xrm.Page.g etAttribut e('ftp_loc alnotetitl e').setSub mitMode('a lways');
  2946                    }
  2947                    if ( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ historical locationde fault != n ull) {
  2948                         vcmn_setSi mpleLookup Value('ftp _notehospi tallocatio n', vcmn_f acilityGro upData.d.r esults[i]. ftp_histor icallocati ondefault. LogicalNam e, vcmn_fa cilityGrou pData.d.re sults[i].f tp_histori callocatio ndefault.I d, vcmn_fa cilityGrou pData.d.re sults[i].f tp_histori callocatio ndefault.N ame);
  2949                         Xrm.Page.g etAttribut e('ftp_not ehospitall ocation'). setSubmitM ode('alway s');
  2950                    }
  2951                }
  2952                //Store  the Id for  the match ing Facili ty Group D efault, us ed later t o update f requently  used value s.
  2953                if (vcmn _facilityG roupData.d .results[i ].ftp_faci litygroupd efaultId ! = null) {
  2954                    vcmn _facilityG roupDefaul tId = vcmn _facilityG roupData.d .results[i ].ftp_faci litygroupd efaultId;
  2955                }
  2956                break;
  2957           }
  2958       }
  2959       catch  (err) {
  2960           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_faci lityGroupD efault_res ponse): '  + err.mess age);
  2961       }
  2962   }
  2963  
  2964   function v cmn_buildQ ueryFilter (field, va lue, and)  {
  2965       try {
  2966           if  (value ==  '') {
  2967                if (and)  {
  2968                    retu rn " and "  + field +  " eq null ";
  2969                } else {
  2970                    retu rn field +  " eq null ";
  2971                }
  2972           }
  2973           el se {
  2974                if (and)  {
  2975                    retu rn " and "  + field +  " eq '" +  value + " '";
  2976                } else {
  2977                    retu rn field +  " eq '" +  value + " '";
  2978                }
  2979           }
  2980       }
  2981       catch  (err) {
  2982           al ert('Progr ess Note R ibbon Func tion Error (vcmn_buil dQueryFilt er): ' + e rr.message );
  2983           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2984       }
  2985   }
  2986  
  2987   function v cmn_unatte ndedMviSea rch(firstn ame, lastn ame, dobda te, ssn) {
  2988       try {
  2989           va r filter =  "";
  2990           va r filterPr efix = "$s elect=*&$f ilter=";
  2991           va r edipi =  "";
  2992           va r dobstrin g = "";
  2993           if  (dobdate  != null) {
  2994                dobstrin g = dobdat e;
  2995           }
  2996  
  2997           if  (ssn != " " && ssn ! = null) {
  2998                ssn = ss n.replace( /-/g, "");
  2999           }
  3000  
  3001           // if we have  edipi, se arch using  just it
  3002           if  (edipi !=  "") {
  3003                filter =  vcmn_buil dQueryFilt er("crme_E DIPI", edi pi, false) ;
  3004                filter + = vcmn_bui ldQueryFil ter("crme_ ClassCode" , 'MIL', t rue);
  3005                filter + = vcmn_bui ldQueryFil ter("crme_ SearchType ", 'Search ByIdentifi er', true) ;
  3006  
  3007                //set se arch type  as unatten ded
  3008                filter + = " and cr me_IsAtten ded eq fal se";
  3009           }
  3010           el se {
  3011                //otherw ise search  using las tname, fir stname, ss n, dob
  3012                filter =  vcmn_buil dQueryFilt er("crme_L astName",  lastname,  false); // assuming l astname wi ll never b e blank
  3013  
  3014                if (firs tname != " " && first name != nu ll) {
  3015                    filt er += vcmn _buildQuer yFilter("c rme_FirstN ame", firs tname, tru e);
  3016                }
  3017  
  3018                if (ssn  != "" && s sn != null ) {
  3019                    filt er += vcmn _buildQuer yFilter("c rme_SSN",  ssn, true) ;
  3020                }
  3021  
  3022                if (dobs tring != " ") {
  3023                    filt er += " an d crme_DOB String eq  '" + dobst ring + "'" ;
  3024                }
  3025                filter + = vcmn_bui ldQueryFil ter("crme_ SearchType ", 'Search ByFilter',  true);
  3026  
  3027                //set se arch type  as attende d (for now )
  3028                filter + = " and cr me_IsAtten ded eq tru e";
  3029           }
  3030  
  3031           fi lter = enc odeURIComp onent(filt er);
  3032           fi lter = fil terPrefix  + filter;
  3033           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);
  3034       }
  3035       catch  (err) {
  3036           al ert('Progr ess Note R ibbon Func tion Error (vcmn_unat tendedMviS earch): '  + err.mess age);
  3037           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  3038       }
  3039   }
  3040  
  3041   function v cmn_unatte ndedMviSea rchCallbac k(returnDa ta) {
  3042       try {
  3043           if  (returnDa ta != null  && return Data.lengt h >= 1) {
  3044                // check  for excep tions 1st
  3045                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."))  {
  3046                    //do  nothing,  pass empty  ICN
  3047                    vcmn _ribbonBut tonSaveToV istA_with_ ICN("");
  3048                }
  3049                else {
  3050                    var  patientMvi Identifier  = returnD ata[0].crm e_PatientM viIdentifi er == null  ? "" : re turnData[0 ].crme_Pat ientMviIde ntifier;
  3051                    if ( patientMvi Identifier  != "") {
  3052                         var idpart s = patien tMviIdenti fier.split ("^");
  3053  
  3054                         if (idpart s.length >  0) {
  3055                             var na tionalId =  idparts[0 ];
  3056                             _icn =  nationalI d;
  3057                             //Pass  on the IC N and cont inue valid ation
  3058                             vcmn_r ibbonButto nSaveToVis tA_with_IC N(_icn);
  3059                         }
  3060                    }
  3061                }
  3062           }
  3063           el se {
  3064                //Return  empty ICN
  3065                vcmn_rib bonButtonS aveToVistA _with_ICN( "");
  3066           }
  3067       }
  3068       catch  (err) {
  3069           al ert('Progr ess Note R ibbon Func tion Error (vcmn_unat tendedMviS earchCallb ack): ' +  err.messag e);
  3070           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  3071       }
  3072   }
  3073  
  3074   function v cmn_unatte ndedMviSea rchComplet e() {
  3075       //do n othing
  3076   }
  3077  
  3078   function v cmn_buildQ ueryFilter SCD(field,  value, an d) {
  3079       try {
  3080           if  (value ==  '') {
  3081                if (and)  {
  3082                    retu rn " and "  + field +  " eq null ";
  3083                } else {
  3084                    retu rn field +  " eq null ";
  3085                }
  3086           }
  3087           el se {
  3088                if (and)  {
  3089                    retu rn " and "  + field +  " eq '" +  value + " '";
  3090                } else {
  3091                    retu rn field +  " eq '" +  value + " '";
  3092                }
  3093           }
  3094       }
  3095       catch  (err) {
  3096           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_buil dQueryFilt erSCD): '  + err.mess age);
  3097           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  3098       }
  3099   }
  3100  
  3101   function v cmn_unatte ndedMviSea rchSCD(fir stname, la stname, do bdate, ssn ) {
  3102       try {
  3103           va r filter =  "";
  3104           va r filterPr efix = "$s elect=*&$f ilter=";
  3105           va r edipi =  "";
  3106           va r dobstrin g = "";
  3107           if  (dobdate  != null) {
  3108                dobstrin g = dobdat e;
  3109           }
  3110  
  3111           if  (ssn != " " && ssn ! = null) {
  3112                ssn = ss n.replace( /-/g, "");
  3113           }
  3114  
  3115           // if we have  edipi, se arch using  just it
  3116           if  (edipi !=  "") {
  3117                filter =  vcmn_buil dQueryFilt erSCD("crm e_EDIPI",  edipi, fal se);
  3118                filter + = vcmn_bui ldQueryFil terSCD("cr me_ClassCo de", 'MIL' , true);
  3119                filter + = vcmn_bui ldQueryFil terSCD("cr me_SearchT ype", 'Sea rchByIdent ifier', tr ue);
  3120  
  3121                //set se arch type  as unatten ded
  3122                filter + = " and cr me_IsAtten ded eq fal se";
  3123           }
  3124           el se {
  3125                //otherw ise search  using las tname, fir stname, ss n, dob
  3126                filter =  vcmn_buil dQueryFilt erSCD("crm e_LastName ", lastnam e, false);  //assumin g lastname  will neve r be blank
  3127  
  3128                if (firs tname != " " && first name != nu ll) {
  3129                    filt er += vcmn _buildQuer yFilterSCD ("crme_Fir stName", f irstname,  true);
  3130                }
  3131  
  3132                if (ssn  != "" && s sn != null ) {
  3133                    filt er += vcmn _buildQuer yFilterSCD ("crme_SSN ", ssn, tr ue);
  3134                }
  3135  
  3136                if (dobs tring != " ") {
  3137                    filt er += " an d crme_DOB String eq  '" + dobst ring + "'" ;
  3138                }
  3139                filter + = vcmn_bui ldQueryFil terSCD("cr me_SearchT ype", 'Sea rchByFilte r', true);
  3140  
  3141                //set se arch type  as attende d (for now )
  3142                filter + = " and cr me_IsAtten ded eq tru e";
  3143           }
  3144  
  3145           fi lter = enc odeURIComp onent(filt er);
  3146           fi lter = fil terPrefix  + filter;
  3147           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) ;
  3148       }
  3149       catch  (err) {
  3150           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_unat tendedMviS earchSCD):  ' + err.m essage);
  3151       }
  3152   }
  3153  
  3154   function v cmn_unatte ndedMviSea rchCallbac kSCD(retur nData) {
  3155       try {
  3156           if  (returnDa ta != null  && return Data.lengt h >= 1) {
  3157                // check  for excep tions 1st
  3158                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."))  {
  3159                    //do  nothing,  pass empty  ICN
  3160                    vcmn _getServic eConnected Disabiliti es("");
  3161                }
  3162                else {
  3163                    var  patientMvi Identifier  = returnD ata[0].crm e_PatientM viIdentifi er == null  ? "" : re turnData[0 ].crme_Pat ientMviIde ntifier;
  3164                    if ( patientMvi Identifier  != "") {
  3165                         var idpart s = patien tMviIdenti fier.split ("^");
  3166  
  3167                         if (idpart s.length >  0) {
  3168                             var na tionalId =  idparts[0 ];
  3169                             _icn =  nationalI d;
  3170                             //Pass  on the IC N and cont inue with  SCD
  3171                             vcmn_g etServiceC onnectedDi sabilities (_icn);
  3172                         }
  3173                    }
  3174                }
  3175           }
  3176           el se {
  3177                //Return  empty ICN
  3178                vcmn_get ServiceCon nectedDisa bilities(" ");
  3179           }
  3180       }
  3181       catch  (err) {
  3182           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_unat tendedMviS earchCallb ackSCD): '  + err.mes sage);
  3183       }
  3184   }
  3185  
  3186   //Standalo ne form lo ad functio ns
  3187   function v cmn_secure ProgressNo te() {
  3188       try {
  3189           // Disable al l form att ributes if  form is o pened by a  user who  does not o wn the pro gress note
  3190           // Only handl e forms in  create st ate
  3191           if  (Xrm.Page .ui.getFor mType() !=  2) { retu rn false;  } //2 = CR M Update S tatus
  3192           // Get the cu rrent owne r of the r ecord and  compare to  the curre nt user
  3193           va r vcmn_rec ordOwnerId  = Xrm.Pag e.getAttri bute('owne rid').getV alue();
  3194           // 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
  3195           if  ((vcmn_re cordOwnerI d[0].id).t oUpperCase () != (Xrm .Page.cont ext.getUse rId()).toU pperCase() ) {
  3196                Xrm.Page .data.enti ty.attribu tes.forEac h(function  (attribut e, index)  {
  3197                    var  control =  Xrm.Page.g etControl( attribute. getName()) ;
  3198                    if ( control) {
  3199                         control.se tDisabled( true)
  3200                    }
  3201                });
  3202           }
  3203       }
  3204       catch  (err) {
  3205           al ert('Progr ess Note F orm Load F unction Er ror(vcmn_s ecureProgr essNote):  ' + err.me ssage);
  3206       }
  3207   }
  3208  
  3209   function v cmn_initFi nancialDis claimer()  {
  3210       //This  function  is used to  initialze  the Finan cial Discl aimer tab  on the pro gress note  form
  3211       try {
  3212           va r vcmn_isR eadDisclai mer = Xrm. Page.getAt tribute("f tp_isreadd isclaimer" ).getValue ();
  3213           va r vcmn_res ponseToDis claimer =  Xrm.Page.g etAttribut e("ftp_isd isclaimerr ead").getV alue();
  3214           Xr m.Page.get Attribute( "ftp_patie ntcallersr easonfordi sagreeing" ).setSubmi tMode("alw ays");
  3215           if  (vcmn_isR eadDisclai mer == tru e && vcmn_ responseTo Disclaimer  == true)  {
  3216                Xrm.Page .ui.tabs.g et("Tab_Fi nancialDis claimer"). setVisible (true);
  3217                Xrm.Page .getAttrib ute("ftp_i spatientag ree").setR equiredLev el("requir ed");
  3218                var vcmn _isPatient Agree = Xr m.Page.get Attribute( "ftp_ispat ientagree" ).getValue ();
  3219                if (vcmn _isPatient Agree == f alse) {
  3220                    Xrm. Page.getAt tribute("f tp_patient callersrea sonfordisa greeing"). setRequire dLevel("re quired");
  3221                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tVisible(t rue);
  3222                }
  3223                else { X rm.Page.ge tControl(" ftp_patien tcallersre asonfordis agreeing") .setVisibl e(false);  }
  3224           }
  3225       }
  3226       catch  (err) {
  3227           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ initFinanc ialDisclai mer): ' +  err.messag e);
  3228       }
  3229   }
  3230  
  3231   //Standalo ne form at tribute on  change ev ent functi ons
  3232   function v cmn_needTo ReadDiscla imer_OnCha nge() {
  3233       //This  function  is used to  display t he Financi al Disclai mer prompt
  3234       try {
  3235           va r vcmn_isR eadDisclai mer = Xrm. Page.getAt tribute("f tp_isreadd isclaimer" ).getValue ();
  3236           if  (vcmn_isR eadDisclai mer == tru e) {
  3237                //Financ ial Discla imer is ne eded
  3238                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.") ;
  3239                if (vcmn _responseT oDisclaime r == true)  {
  3240                    Xrm. Page.ui.ta bs.get("Ta b_Financia lDisclaime r").setVis ible(true) ;
  3241                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setValue (true);
  3242                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setSubmi tMode("alw ays");
  3243                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setRequire dLevel("re quired");
  3244                    //Se t Default  Value to N ot Agreein g and Requ ire Reason  for disag reeing
  3245                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setValue(f alse);
  3246                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setSubmitM ode("alway s");
  3247                    Xrm. Page.getAt tribute("f tp_patient callersrea sonfordisa greeing"). setRequire dLevel("re quired");
  3248                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tVisible(t rue);
  3249                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tFocus();
  3250                }
  3251                else {
  3252                    Xrm. Page.ui.ta bs.get("Ta b_Financia lDisclaime r").setVis ible(false );
  3253                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setValue (false);
  3254                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setSubmi tMode("alw ays");
  3255                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setRequire dLevel("no ne");
  3256                    Xrm. Page.getAt tribute("f tp_patient callersrea sonfordisa greeing"). setRequire dLevel("no ne");
  3257                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tVisible(f alse);
  3258                }
  3259           }
  3260           el se {
  3261                //No Fin ancial Dis claimer ne eded  (Hid e Financia l Disclaim er section )
  3262                Xrm.Page .ui.tabs.g et("Tab_Fi nancialDis claimer"). setVisible (false);
  3263                Xrm.Page .getAttrib ute("ftp_i spatientag ree").setR equiredLev el("none") ;
  3264                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setR equiredLev el("none") ;
  3265                Xrm.Page .getContro l("ftp_pat ientcaller sreasonfor disagreein g").setVis ible(false );
  3266           }
  3267       }
  3268       catch  (err) {
  3269           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ needToRead Disclaimer _OnChange) : ' + err. message);
  3270       }
  3271   }
  3272  
  3273   function v cmn_isPati entInAgree ment_OnCha nge() {
  3274       try {
  3275           va r vcmn_isP atientAgre e = Xrm.Pa ge.getAttr ibute("ftp _ispatient agree").ge tValue();
  3276           if  (vcmn_isP atientAgre e == false ) {
  3277                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setR equiredLev el("requir ed");
  3278                Xrm.Page .getContro l("ftp_pat ientcaller sreasonfor disagreein g").setVis ible(true) ;
  3279           }
  3280           el se {
  3281                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setR equiredLev el("none") ;
  3282                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setV alue(null) ;
  3283                Xrm.Page .getContro l("ftp_pat ientcaller sreasonfor disagreein g").setVis ible(false );
  3284                //Update  Note
  3285                vcmn_app endNoteFin ancialDisc laimer_OnC hange();
  3286           }
  3287       }
  3288       catch  (err) {
  3289           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ isPatientI nAgreement _OnChange) : ' + err. message);
  3290       }
  3291   }
  3292  
  3293   function v cmn_append NoteFinanc ialDisclai mer_OnChan ge() {
  3294       //This  function  adds Finan cial Discl aimer text  to the en d of the N ote
  3295       try {
  3296           // Get Curren t Note Tex t
  3297           va r vcmn_cur rentNoteTe xt = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  3298           if  (vcmn_cur rentNoteTe xt == null ) { vcmn_c urrentNote Text = "";  }
  3299           // Create new  Financial  Disclaime r Text
  3300           va r vcmn_fin ancialDisc laimerText  = "";
  3301  
  3302           va r vcmn_sta ndardText  = "\n\nFIN ANCIAL DIS CLAIMER\n"  +
  3303                "------- ---------- ---------- ---------- ---------- ---------- ---------- ---\n" +
  3304                "The fol lowing dis claimer wa s read to  the caller :\n" +
  3305                "Patient  was instr ucted, 'Th is is not  an authori zation for  VA\n" +
  3306                "Payment  and also  'To have h ospital co ntact the  nearest VA \n" +
  3307                "Facilit y for tran sfer upon  stabilizat ion.\n";
  3308           va r vcmn_ter minationTe xt = "\n-- ---------- ---------- ---------- ---------- ---------- ---------- --------\n ";
  3309  
  3310           va r vcmn_isR eadDisclai mer = Xrm. Page.getAt tribute("f tp_isreadd isclaimer" ).getValue ();
  3311           va r vcmn_res ponseToDis claimer =  Xrm.Page.g etAttribut e("ftp_isd isclaimerr ead").getV alue();
  3312           if  (vcmn_isR eadDisclai mer == tru e && vcmn_ responseTo Disclaimer  == true)  {
  3313                var vcmn _isPatient Agree = Xr m.Page.get Attribute( "ftp_ispat ientagree" ).getValue ();
  3314                if (vcmn _isPatient Agree == t rue) {
  3315                    vcmn _financial Disclaimer Text = vcm n_standard Text +
  3316                         "\nPatient /Caller ag rees with  plan." + v cmn_termin ationText;
  3317                }
  3318                else {
  3319                    var  vcmn_reaso nForDisagr eeing = Xr m.Page.get Attribute( "ftp_patie ntcallersr easonfordi sagreeing" ).getValue ();
  3320                    if ( vcmn_reaso nForDisagr eeing == n ull) { vcm n_reasonFo rDisagreei ng = ""; }
  3321                    vcmn _financial Disclaimer Text = vcm n_standard Text +
  3322                         "\nPatient /Caller do es not agr ee with th e plan bec ause:\n" +
  3323                         vcmn_reaso nForDisagr eeing + vc mn_termina tionText;
  3324                }
  3325           }
  3326  
  3327           // Append to  existing N ote
  3328           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_currentN oteText +  vcmn_finan cialDiscla imerText);
  3329           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  3330       }
  3331       catch  (err) {
  3332           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ appendNote FinancialD isclaimer_ OnChange):  ' + err.m essage);
  3333       }
  3334   }
  3335  
  3336   function f req_button Action(fre q_buttonNa me) {
  3337       try {
  3338           // Frequently  Used butt on pressed , validate  Facility  Group Defa ults
  3339           if  (vcmn_fac ilityGroup DefaultId  == null) {
  3340                alert("C rm Facilit y Group De fault has  not been c onfigured.  Please de fine for y our Group  and Facili ty to util ize this f unctionali ty!");
  3341                return f alse;
  3342           }
  3343           if  (freq_but tonName !=  null && f req_button Name != un defined &&  freq_butt onName !=  "") {
  3344                //Verify  button na me and tak e action a ccordingly
  3345                if (freq _buttonNam e == "Freq UsedNoteTi tleButton" ) {
  3346                    //No te Title b utton clic ked
  3347                    var  freq_ViaNo teTitleIEN  = Xrm.Pag e.getAttri bute("ftp_ selectedwo rkloadnote titleid"). getValue() ;
  3348                    var  freq_ViaNo teTitleDes cription =  Xrm.Page. getAttribu te("ftp_se lectedwork loadnoteti tletext"). getValue() ;
  3349                    if ( freq_ViaNo teTitleIEN  == null | | freq_Via NoteTitleI EN == "" | | freq_Via NoteTitleD escription  == null | | freq_Via NoteTitleD escription  == "") {
  3350                         alert("The  selected  Note Title  is not va lid, it ca n not be a dded to th e Frequent ly Used Li st!");
  3351                         return fal se;
  3352                    }
  3353                    //Pr ompt User  to add Not e Title
  3354                    var  freq_AddCo nfirm = fa lse;
  3355                    Xrm. Utility.co nfirmDialo g("Are you  sure you  want to ad d " + freq _ViaNoteTi tleDescrip tion + "   (" + freq_ ViaNoteTit leIEN + ")   to the F requently  Used Note  Title List ?",
  3356                         function ( ) { freq_A ddConfirm  = true; },
  3357                         function ( ) { freq_A ddConfirm  = false; }
  3358                    );
  3359                    if ( freq_AddCo nfirm == f alse) { re turn false ; }
  3360  
  3361                    //Ge t Existing  Frequentl y Used Not e Title Li st
  3362                    var  freq_frequ entlyUsedN oteTitles  = null;
  3363                    var  freq_facil ityGroupDe faultData  = vcmn_get SingleEnti tyDataSync ('ftp_faci litygroupd efaultSet' , 'ftp_fre quentlyuse dnotetitle s', vcmn_f acilityGro upDefaultI d);
  3364                    if ( freq_facil ityGroupDe faultData  != null) {
  3365                         if (freq_f acilityGro upDefaultD ata.d.ftp_ frequently usednoteti tles != nu ll) {
  3366                             freq_f requentlyU sedNoteTit les = freq _facilityG roupDefaul tData.d.ft p_frequent lyusednote titles;
  3367                         }
  3368                    }
  3369                    var  freq_newNo teTitle =  freq_ViaNo teTitleIEN  + "~~" +  freq_ViaNo teTitleDes cription;
  3370                    if ( freq_frequ entlyUsedN oteTitles  != null &&  freq_freq uentlyUsed NoteTitles  != "") {
  3371                         //Test for  duplicate s
  3372                         var freq_n oteTitleEx ist = freq _frequentl yUsedNoteT itles.inde xOf(freq_n ewNoteTitl e);
  3373                         if (freq_n oteTitleEx ist != -1)  {
  3374                             alert( "The selec ted Note T itle alrea dy exist o n the Freq uently Use d List");
  3375                             return  false;
  3376                         }
  3377                    }
  3378  
  3379                    //Up date exist ing CRM Fa cility Gro up Default  entity re cord
  3380                    //Cr eate the F acility Gr oup Defaul t object
  3381                    var  freq_facil ityGroupDe faultItem  = new Obje ct();
  3382                    if ( freq_frequ entlyUsedN oteTitles  == null ||  freq_freq uentlyUsed NoteTitles  == "") {
  3383                         //Add as f irst item
  3384                         freq_facil ityGroupDe faultItem. ftp_freque ntlyusedno tetitles =  freq_newN oteTitle;
  3385                    }
  3386                    else  {
  3387                         //Combine  with exist ing item
  3388                         freq_facil ityGroupDe faultItem. ftp_freque ntlyusedno tetitles =  freq_freq uentlyUsed NoteTitles  + "^^" +  freq_newNo teTitle;
  3389                    }
  3390                    //ma ke it a js on object
  3391                    var  jsonEntity  = JSON.st ringify(fr eq_facilit yGroupDefa ultItem);
  3392  
  3393                    $.aj ax({
  3394                         type: "POS T",
  3395                         contentTyp e: "applic ation/json ; charset= utf-8",
  3396                         datatype:  "json",
  3397                         url: vcmn_ serverUrl  + vcmn_crm OdataEndPo int + "/"  + 'ftp_fac ilitygroup defaultSet ' + "(guid '" + vcmn_ facilityGr oupDefault Id + "')",
  3398                         data: json Entity,
  3399                         beforeSend : function  (XMLHttpR equest) {
  3400                             XMLHtt pRequest.s etRequestH eader("X-H TTP-Method ", "MERGE" );
  3401                         },
  3402                         success: f unction (t extStatus,  XmlHttpRe quest) {
  3403                             alert( "The Selec ted Note T itle was a dded succe ssfully to  the Frequ ently Used  List.");
  3404                         },
  3405                         error: fun ction (Xml HttpReques t, textSta tus, error Thrown) {
  3406                             alert( 'Ajax Erro r in Updat e of Crm F acility Gr oup Defaul t entity:  ' + errorT hrown);
  3407                         }
  3408                    });
  3409                }
  3410                else if  (freq_butt onName ==  "FreqUsedL ocationBut ton") {
  3411                    //Lo cation but ton clicke d
  3412                    var  freq_ViaLo cationIEN  = Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat ionid").ge tValue();
  3413                    var  freq_ViaLo cationDesc ription =  Xrm.Page.g etAttribut e("ftp_sel ectedworkl oadlocatio ntext").ge tValue();
  3414                    if ( freq_ViaLo cationIEN  == null ||  freq_ViaL ocationIEN  == "" ||  freq_ViaLo cationDesc ription ==  null || f req_ViaLoc ationDescr iption ==  "") {
  3415                         alert("The  selected  Location i s not vali d, it can  not be add ed to the  Frequently  Used List !");
  3416                         return fal se;
  3417                    }
  3418                    //Pr ompt User  to add Loc ation
  3419                    var  freq_AddCo nfirm = fa lse;
  3420                    Xrm. Utility.co nfirmDialo g("Are you  sure you  want to ad d " + freq _ViaLocati onDescript ion + "  ( " + freq_V iaLocation IEN + ")   to the Fre quently Us ed Locatio n List?",
  3421                         function ( ) { freq_A ddConfirm  = true; },
  3422                         function ( ) { freq_A ddConfirm  = false; }
  3423                    );
  3424                    if ( freq_AddCo nfirm == f alse) { re turn false ; }
  3425  
  3426                    //Ge t Existing  Frequentl y Used Loc ation List
  3427                    var  freq_frequ entlyUsedL ocations =  null;
  3428                    var  freq_facil ityGroupDe faultData  = vcmn_get SingleEnti tyDataSync ('ftp_faci litygroupd efaultSet' , 'ftp_fre quentlyuse dlocations ', vcmn_fa cilityGrou pDefaultId );
  3429                    if ( freq_facil ityGroupDe faultData  != null) {
  3430                         if (freq_f acilityGro upDefaultD ata.d.ftp_ frequently usedlocati ons != nul l) {
  3431                             freq_f requentlyU sedLocatio ns = freq_ facilityGr oupDefault Data.d.ftp _frequentl yusedlocat ions;
  3432                         }
  3433                    }
  3434                    var  freq_newLo cation = f req_ViaLoc ationIEN +  "~~" + fr eq_ViaLoca tionDescri ption;
  3435                    if ( freq_frequ entlyUsedL ocations ! = null &&  freq_frequ entlyUsedL ocations ! = "") {
  3436                         //Test for  duplicate s
  3437                         var freq_l ocationExi st = freq_ frequently UsedLocati ons.indexO f(freq_new Location);
  3438                         if (freq_l ocationExi st != -1)  {
  3439                             alert( "The selec ted Locati on already  exist on  the Freque ntly Used  List");
  3440                             return  false;
  3441                         }
  3442                    }
  3443  
  3444                    //Up date exist ing CRM Fa cility Gro up Default  entity re cord
  3445                    //Cr eate the F acility Gr oup Defaul t object
  3446                    var  freq_facil ityGroupDe faultItem  = new Obje ct();
  3447                    if ( freq_frequ entlyUsedL ocations = = null ||  freq_frequ entlyUsedL ocations = = "") {
  3448                         //Add as f irst item
  3449                         freq_facil ityGroupDe faultItem. ftp_freque ntlyusedlo cations =  freq_newLo cation;
  3450                    }
  3451                    else  {
  3452                         //Combine  with exist ing item
  3453                         freq_facil ityGroupDe faultItem. ftp_freque ntlyusedlo cations =  freq_frequ entlyUsedL ocations +  "^^" + fr eq_newLoca tion;
  3454                    }
  3455                    //ma ke it a js on object
  3456                    var  jsonEntity  = JSON.st ringify(fr eq_facilit yGroupDefa ultItem);
  3457  
  3458                    $.aj ax({
  3459                         type: "POS T",
  3460                         contentTyp e: "applic ation/json ; charset= utf-8",
  3461                         datatype:  "json",
  3462                         url: vcmn_ serverUrl  + vcmn_crm OdataEndPo int + "/"  + 'ftp_fac ilitygroup defaultSet ' + "(guid '" + vcmn_ facilityGr oupDefault Id + "')",
  3463                         data: json Entity,
  3464                         beforeSend : function  (XMLHttpR equest) {
  3465                             XMLHtt pRequest.s etRequestH eader("X-H TTP-Method ", "MERGE" );
  3466                         },
  3467                         success: f unction (t extStatus,  XmlHttpRe quest) {
  3468                             alert( "The Selec ted Locati on was add ed success fully to t he Frequen tly Used L ist.");
  3469                         },
  3470                         error: fun ction (Xml HttpReques t, textSta tus, error Thrown) {
  3471                             alert( 'Ajax Erro r in Updat e of Crm F acility Gr oup Defaul t entity:  ' + errorT hrown);
  3472                         }
  3473                    });
  3474                }
  3475  
  3476                //****** ********** ********** ***
  3477                else if  (freq_butt onName ==  "TestHisto ricalNoteB utton") {
  3478                    //Te stHistoric alNoteButt on clicked
  3479                    vcmn _ribbonBut tonSaveToV istA_Histo ricalTest( );
  3480                }
  3481                //****** ********** ********** ***
  3482  
  3483                else {
  3484                    aler t("The Fre quently Us ed button  named '" +  freq_butt onName + " ' has not  been defin ed in this  applicati on, please  contact y our system  administr ator!");
  3485                    retu rn false;
  3486                }
  3487           }
  3488           el se {
  3489                alert("T he Frequen tly Used b utton in u se has bee n defined  incorrectl y, please  contact yo ur system  administra tor!");
  3490                return f alse;
  3491           }
  3492       }
  3493       catch  (err) {
  3494           al ert('Progr ess Note F requently  Used Butto n Script F unction Er ror(freq_b uttonActio n): ' + er r.message) ;
  3495       }
  3496   }
  3497  
  3498  
  3499  
  3500   //******Te st Section  for VIA H istorical  Note Creat ion******* ********** ******
  3501   function v cmn_ribbon ButtonSave ToVistA_Hi storicalTe st() {
  3502       try {
  3503           // Check the  value of t he Integra tion Statu s Field, i f = 'OK',  stop and e xit this s cript
  3504           va r vcmn_int egrationSt atus = Xrm .Page.getA ttribute(' ftp_integr ationstatu s').getVal ue();
  3505           if  (vcmn_int egrationSt atus == 'O K') { retu rn false;  }
  3506  
  3507           // Prompt use r to sign  the note
  3508           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  3509           va r vcmn_sig nThisNoteF ailure = f alse;
  3510           if  (vcmn_sig nThisNote  == null) {
  3511                Xrm.Util ity.confir mDialog(
  3512                    "Do  you need t o sign thi s note?, S elect OK i f Yes, oth erwise CAN CEL.",
  3513                    func tion () {
  3514                         //Check if  VIA Login  cookie ex ist (not e xpired)
  3515                         var vcmn_V iaLoginCoo kie = vcmn _getCookie ("viasessi onlink");
  3516                         //Prompt u ser to log in to VIA
  3517                         if (vcmn_V iaLoginCoo kie == "")  {
  3518                             alert( "Your VIST A session  has expire d. In orde r to sign  this note,  you must  be logged  into VISTA !");
  3519                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setVisi ble(true);
  3520                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setFocu s();
  3521                             vcmn_s ignThisNot eFailure =  true;
  3522                             return ;
  3523                         }
  3524                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000001 );
  3525                    },
  3526                    func tion () {
  3527                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000000 );
  3528                    }
  3529                );
  3530                Xrm.Page .getAttrib ute('ftp_s ignthisnot e').setSub mitMode('a lways');
  3531           }
  3532  
  3533           if  (vcmn_sig nThisNoteF ailure ==  true) { re turn false ; }
  3534  
  3535           // Check for  additional  signers,  if they ex ist, the u ser must b e logged i nto VIA to  continue  process.
  3536           // Additional  Signature s must als o be in sy nc with ma tching Ses sion varia bles
  3537  
  3538           vc mn_AddlSig nersNameAr ray = null ;
  3539           vc mn_AddlSig nersIenArr ay = null;
  3540  
  3541           va r vcmn_sel ectedSigne rs = Xrm.P age.getAtt ribute('ft p_selected signers'). getValue() ;
  3542           if  (vcmn_sel ectedSigne rs != null  && vcmn_s electedSig ners != '' ) {
  3543                //Additi onal Signe rs exist i n CRM, ver ify sessio n variable s
  3544                var vcmn _selectedA rray = vcm n_selected Signers.sp lit('~~~') ;
  3545                var vcmn _selectedA rrayRecord Count = vc mn_selecte dArray.len gth;
  3546                if (vcmn _selectedA rrayRecord Count > 1)  {
  3547                    vcmn _AddlSigne rsNameArra y = vcmn_s electedArr ay;
  3548                }
  3549  
  3550                var vcmn _selectedI ENArray =  '';
  3551                var vcmn _selectedI ENArrayRec ordCount =  0;
  3552                var vcmn _progressN oteId = Xr m.Page.dat a.entity.g etId();
  3553  
  3554                var vcmn _arrayMism atch = fal se;
  3555  
  3556                //Get No te's Brows er Local S torage Val ues
  3557                if (vcmn _progressN oteId != n ull && vcm n_progress NoteId !=  '') {
  3558                    vcmn _localStor ageVarName  = "PN" +  vcmn_progr essNoteId;
  3559                    var  vcmn_local StorageStr ingValue =  localStor age.getIte m(vcmn_loc alStorageV arName);
  3560                    if ( vcmn_local StorageStr ingValue ! = null &&  vcmn_local StorageStr ingValue ! = '') {
  3561                         vcmn_selec tedIENArra y = vcmn_l ocalStorag eStringVal ue.split(' ~~~');
  3562                         vcmn_selec tedIENArra yRecordCou nt = vcmn_ selectedIE NArray.len gth;
  3563                         if (vcmn_s electedIEN ArrayRecor dCount > 1 ) {
  3564                             vcmn_A ddlSigners IenArray =  vcmn_sele ctedIENArr ay;
  3565                         }
  3566                    }
  3567                }
  3568                //Compar e CRM sign er array l ength with  LocalStor age array  length
  3569                if (vcmn _selectedA rrayRecord Count != v cmn_select edIENArray RecordCoun t) { vcmn_ arrayMisma tch = true ; }
  3570  
  3571                if (vcmn _arrayMism atch == tr ue) {
  3572                    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.");
  3573                    vcmn _signThisN oteFailure  = true;
  3574                }
  3575                else {
  3576                    //Ch eck if VIA  Login coo kie exist  (not expir ed)
  3577                    var  vcmn_ViaLo ginCookie  = vcmn_get Cookie("vi asessionli nk");
  3578                    if ( vcmn_ViaLo ginCookie  == "") {
  3579                         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 !");
  3580                         Xrm.Page.u i.tabs.get ('Tab_Vist ALogin').s etVisible( true);
  3581                         Xrm.Page.u i.tabs.get ('Tab_Vist ALogin').s etFocus();
  3582                         vcmn_signT hisNoteFai lure = tru e;
  3583                         return;
  3584                    }
  3585                }
  3586           }
  3587  
  3588           // Enforce VI A Login
  3589           // Check if V IA Login c ookie exis t (not exp ired)
  3590           va r vcmn_Via LoginCooki e = vcmn_g etCookie(" viasession link");
  3591           if  (vcmn_Via LoginCooki e == "") {
  3592                alert("Y our VISTA  session ha s expired.  In order  to process  a note, y ou must be  logged in to VISTA!" );
  3593                Xrm.Page .ui.tabs.g et('Tab_Vi stALogin') .setVisibl e(true);
  3594                Xrm.Page .ui.tabs.g et('Tab_Vi stALogin') .setFocus( );
  3595                vcmn_sig nThisNoteF ailure = t rue;
  3596                return f alse;
  3597           }
  3598  
  3599           if  (vcmn_sig nThisNoteF ailure ==  true) {
  3600                //****** Developer  Bypass for  no VISTA  authentica tion******
  3601                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}") {
  3602                    aler t("Develop er VISTA a uthenticat ion bypass  applied!" );
  3603                    Xrm. Page.getAt tribute('f tp_signthi snote').se tValue(100 000001);
  3604                    Xrm. Page.getAt tribute('f tp_signthi snote').se tSubmitMod e('always' );
  3605                }
  3606                else {
  3607                    retu rn false;
  3608                }
  3609           }
  3610  
  3611           // Save the c urrent CRM  data
  3612           Xr m.Page.dat a.entity.s ave();
  3613           // Display YE LLOW Progr ess....
  3614           Xr m.Page.ui. setFormNot ification( "Verifying  progress  note data,  please wa it..", "IN FO", "SAVE VISTA");
  3615  
  3616           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!');
  3617           if  (vcmn_con firmSaveTo Vista == f alse) {
  3618                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3619                return f alse;
  3620           }
  3621           // Get regard ing data
  3622           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  3623           if  (vcmn_req uestId ==  null) {
  3624                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 !');
  3625                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  3626                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3627                return f alse;
  3628           }
  3629           // Verify tha t the rega rdingid is  of type ' incident'
  3630           if  (vcmn_req uestId[0]. entityType  != 'incid ent') {
  3631                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!') ;
  3632                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  3633                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3634                return f alse;
  3635           }
  3636  
  3637           // Preserved  Variables
  3638           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  3639           va r vcmn_vet eranFirstN ame = '';
  3640           va r vcmn_vet eranLastNa me = '';
  3641           va r vcmn_SSN  = '';
  3642           va r vcmn_DOB  = '';
  3643  
  3644           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  3645           if  (vcmn_req uestData ! = null) {
  3646                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  3647                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  3648                    //Ve rify that  the custom erid is of  type cont act
  3649                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  3650                         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!') ;
  3651                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  3652                         return fal se;
  3653                    }
  3654                }
  3655           }
  3656           if  (vcmn_vet eranId ==  null) {
  3657                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  3658                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3659                return f alse;
  3660           }
  3661  
  3662           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);
  3663           if  (vcmn_con tactData ! = null) {
  3664                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  3665                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  3666                if (vcmn _contactDa ta.d.ftp_D ateofBirth  != null)  { vcmn_DOB  = vcmn_co ntactData. d.ftp_Date ofBirth; }
  3667                if (vcmn _contactDa ta.d.Gover nmentId !=  null) { v cmn_SSN =  vcmn_conta ctData.d.G overnmentI d; }
  3668           }
  3669  
  3670           // **WORKLOAD  ENCOUNTER **
  3671           vc mn_matchLo okupId = v cmn_SSN;
  3672           // ********** ********** ***
  3673  
  3674           // Perform MV I Search
  3675           // *vcmn_unat tendedMviS earch(vcmn _veteranFi rstName, v cmn_vetera nLastName,  vcmn_DOB,  vcmn_SSN) ;
  3676  
  3677           // Skipping U nattended  MVI******* *******
  3678           // ******Deve loper Bypa ss for mis sing ICN** ****
  3679  
  3680           // Get regard ing data
  3681           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  3682  
  3683           // Preserved  Variables
  3684           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  3685           va r vcmn_vet eranName =  '';
  3686           va r vcmn_vet eranFirstN ame = '';
  3687           va r vcmn_vet eranLastNa me = '';
  3688           va r vcmn_vet eranMiddle Name = '';
  3689  
  3690           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  3691           if  (vcmn_req uestData ! = null) {
  3692                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  3693                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  3694                    //Ve rify that  the custom erid is of  type cont act
  3695                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  3696                         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!') ;
  3697                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  3698                         return fal se;
  3699                    }
  3700                }
  3701           }
  3702           if  (vcmn_vet eranId ==  null) {
  3703                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  3704                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3705                return f alse;
  3706           }
  3707  
  3708           va r vcmn_con tactData =  vcmn_getS ingleEntit yDataSync( 'ContactSe t', 'FullN ame, First Name, Last Name, Midd leName', v cmn_vetera nId.Id);
  3709           if  (vcmn_con tactData ! = null) {
  3710                if (vcmn _contactDa ta.d.FullN ame != nul l) { vcmn_ veteranNam e = vcmn_c ontactData .d.FullNam e; }
  3711                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  3712                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  3713                if (vcmn _contactDa ta.d.Middl eName != n ull) { vcm n_veteranM iddleName  = vcmn_con tactData.d .MiddleNam e; }
  3714           }
  3715  
  3716           // Get user d ata
  3717           va r vcmn_crm UserId = X rm.Page.ge tAttribute ('ownerid' ).getValue ();
  3718           va r vcmn_use rDomainId  = '';
  3719           va r vcmn_use rFirstName  = '';
  3720           va r vcmn_use rLastName  = '';
  3721           va r vcmn_use rMiddleNam e = '';
  3722           va r vcmn_use rSiteId =  '';
  3723  
  3724           if  (vcmn_crm UserId !=  null) {
  3725                //Verify  the owner  type
  3726                if (vcmn _crmUserId [0].entity Type != 's ystemuser' ) {
  3727                    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 !');
  3728                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  3729                    retu rn false;
  3730                }
  3731  
  3732                var vcmn _userData  = vcmn_get SingleEnti tyDataSync ('SystemUs erSet', 'D omainName,  FirstName , LastName , MiddleNa me, ftp_Fa cilitySite Id', vcmn_ crmUserId[ 0].id);
  3733                if (vcmn _userData  != null) {
  3734                    if ( vcmn_userD ata.d.Doma inName !=  null) { vc mn_userDom ainId = vc mn_userDat a.d.Domain Name; }
  3735                    if ( vcmn_userD ata.d.Firs tName != n ull) { vcm n_userFirs tName = vc mn_userDat a.d.FirstN ame; }
  3736                    if ( vcmn_userD ata.d.Last Name != nu ll) { vcmn _userLastN ame = vcmn _userData. d.LastName ; }
  3737                    if ( vcmn_userD ata.d.Midd leName !=  null) { vc mn_userMid dleName =  vcmn_userD ata.d.Midd leName; }
  3738                    if ( vcmn_userD ata.d.ftp_ FacilitySi teId != nu ll) { vcmn _userSiteI d = vcmn_u serData.d. ftp_Facili tySiteId.I d; }
  3739                }
  3740           }
  3741           el se {
  3742                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!');
  3743                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3744                return f alse;
  3745           }
  3746  
  3747           // Verify tha t the curr ent owner  and the cu rrent user  is the sa me person,  if not do  not proce ed
  3748           if  ((vcmn_cr mUserId[0] .id).toUpp erCase() ! = (Xrm.Pag e.context. getUserId( )).toUpper Case()) {
  3749                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!');
  3750                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3751                return f alse;
  3752           }
  3753           va r vcmn_Not eUserTeam  = "NONE";
  3754           // Check Team  membershi p
  3755           if  (vcmn_Use rHasTeam(" Pharmacy",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "PHARM ACY"; }
  3756           if  (vcmn_Use rHasTeam(" CCA Team",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "CCA";  }
  3757           if  (vcmn_Use rHasTeam(" TAN", Xrm. Page.conte xt.getUser Id())) { v cmn_NoteUs erTeam = " TAN"; }
  3758           // **TEMP, ve rify these  team valu es that th ey are cor rect **FUT URE NEED**
  3759           if  (vcmn_Use rHasTeam(" PACT User" , Xrm.Page .context.g etUserId() )) { vcmn_ NoteUserTe am = "PACT "; }
  3760           if  (vcmn_Use rHasTeam(" MSA User",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "MSA";  }
  3761  
  3762           // Verify Tea m Value, t hat one ha s been ass igned
  3763           if  (vcmn_Not eUserTeam  == "NONE")  {
  3764                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 !');
  3765                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3766                return f alse;
  3767           }
  3768  
  3769           // Get reques t form con tent
  3770           va r vcmn_not eDescripti on = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  3771           if  (vcmn_not eDescripti on == null  || vcmn_n oteDescrip tion == '' ) {
  3772                alert('T he note de scription  field is e mpty, the  note canno t be creat ed in Vist A/CPRS!');
  3773                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3774                return f alse;
  3775           }
  3776  
  3777           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) != true)  {
  3778                //Using  new hospit al locatio n and loca l notes lo okup field s
  3779                var vcmn _localTitl e = Xrm.Pa ge.getAttr ibute('ftp _localnote title').ge tValue();
  3780                if (vcmn _localTitl e == null)  {
  3781                    aler t('The loc al note ti tle field  is empty,  the note c annot be c reated in  VistA/CPRS !');
  3782                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  3783                    retu rn false;
  3784                }
  3785                else { v cmn_localT itle = vcm n_localTit le[0].name ; }
  3786  
  3787                vcmn_pat ientAssign edLocation  = Xrm.Pag e.getAttri bute('ftp_ notehospit allocation ').getValu e();
  3788                if (vcmn _patientAs signedLoca tion == nu ll) {
  3789                    aler t('The hos pital loca tion field  is empty,  the note  cannot be  created in  VistA/CPR S!');
  3790                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  3791                    retu rn false;
  3792                }
  3793                else { v cmn_patien tAssignedL ocation =  vcmn_patie ntAssigned Location[0 ].name; }
  3794           }
  3795  
  3796           va r vcmn_cal lbackNumbe r = Xrm.Pa ge.getAttr ibute('ftp _callbackn umber').ge tValue();
  3797           if  (vcmn_cal lbackNumbe r == null  || vcmn_ca llbackNumb er == '')  {
  3798                alert('T he callbac k number f ield is em pty, the n ote cannot  be create d in VistA /CPRS!');
  3799                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3800                return f alse;
  3801           }
  3802           va r vcmn_rea sonForRequ est = Xrm. Page.getAt tribute('f tp_reasonf orrequest' ).getValue ();
  3803           if  (vcmn_rea sonForRequ est == nul l) {
  3804                alert('T he reason  for reques t field is  empty, th e note can not be cre ated in Vi stA/CPRS!' );
  3805                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3806                return f alse;
  3807           }
  3808  
  3809           va r vcmn_enc ounterCode  = 'NEW';
  3810           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  3811           if  (vcmn_sig nThisNote  == 1000000 01) { vcmn _signThisN ote = true ; } else {  vcmn_sign ThisNote =  false; }
  3812  
  3813           // Get Progre ss Note Gu id/Id
  3814           va r vcmn_not eId = Xrm. Page.data. entity.get Id();
  3815  
  3816           // Get Create d On Date  & Convert  format
  3817           va r vcmn_cre atedOnDate  = vcmn_co nvertCrmDa teToVistAD ate(Xrm.Pa ge.getAttr ibute('cre atedon').g etValue()) ;
  3818           if  (vcmn_cre atedOnDate  == null)  {
  3819                alert('T he CRM cre atedon fie ld is empt y, the not e cannot b e created  in VistA/C PRS!');
  3820                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3821                return f alse;
  3822           }
  3823  
  3824           // Get User E ntry Date
  3825           va r vcmn_use rEntryDate  = vcmn_co nvertCrmDa teToVistAD ate(Xrm.Pa ge.getAttr ibute('ftp _userentry date').get Value());
  3826           if  (vcmn_use rEntryDate  == null)  { vcmn_use rEntryDate  = vcmn_cr eatedOnDat e; }
  3827  
  3828           // Get Facili ty and loo kup facili ty number  and HL7 UR L
  3829           va r vcmn_fac ilityCode  = '';
  3830           va r vcmn_sit eHL7Listen erAddress  = '';
  3831           va r vcmn_pat ientFacili ty = Xrm.P age.getAtt ribute('ft p_patientf acility'). getValue() ;
  3832           if  (vcmn_pat ientFacili ty == null ) {
  3833                alert('T he CRM pat ient facil ity field  is empty,  the note c annot be c reated in  VistA/CPRS !');
  3834                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3835                return f alse;
  3836           }
  3837           el se {
  3838                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e, ftp_hl7 listener',  vcmn_pati entFacilit y[0].id);
  3839                if (vcmn _facilityD ata.d.ftp_ facilityco de != null ) {
  3840                    vcmn _facilityC ode = vcmn _facilityD ata.d.ftp_ facilityco de;
  3841                }
  3842                else {
  3843                    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!') ;
  3844                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  3845                    retu rn false;
  3846                }
  3847  
  3848                if (vcmn _facilityD ata.d.ftp_ hl7listene r != null)  {
  3849                    var  vcmn_siteH L7Listener Address =  vcmn_facil ityData.d. ftp_hl7lis tener;
  3850                }
  3851                else {
  3852                    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!');
  3853                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  3854                    retu rn false;
  3855                }
  3856           }
  3857  
  3858           va r vcmn_ori ginatorID  = '';
  3859           va r vcmn_use rSiteNo =  '';
  3860  
  3861           // Lookup the  Facility/ Site #
  3862           if  (vcmn_use rSiteId !=  null && v cmn_userSi teId != '' ) {
  3863                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e', vcmn_u serSiteId) ;
  3864                if (vcmn _facilityD ata != nul l) {
  3865                    if ( vcmn_facil ityData.d. ftp_facili tycode !=  null) { vc mn_userSit eNo = vcmn _facilityD ata.d.ftp_ facilityco de; }
  3866                }
  3867           }
  3868  
  3869           // Validate r equired Vi sta Lookup  info
  3870           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) {
  3871                //Abort  process, m issing inf o
  3872                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 !');
  3873                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  3874                return f alse;
  3875           }
  3876  
  3877           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) != true)  {
  3878  
  3879                //**TEMP  DISABLED
  3880                /*
  3881                //Obtain  the Vista Duz from t he cross r eference t able if av ailable
  3882                if (vcmn _crmUserId  != null)  {
  3883                    var  vcmn_condi tionalFilt er = "ftp_ crmuser/Id  eq (guid' " + vcmn_c rmUserId[0 ].id + "') ";
  3884                    var  vcmn_cross ReferenceD ata = vcmn _getMultip leEntityDa taSync('ft p_useridSe t', 'ftp_u seridId, f tp_vistadu z', vcmn_c onditional Filter, 'f tp_name',  'asc', 0);
  3885                    if ( vcmn_cross ReferenceD ata != nul l) {
  3886                         for (var i  = 0; i <=  vcmn_cros sReference Data.d.res ults.lengt h - 1; i++ ) {
  3887                             //Get  Info
  3888                             if (vc mn_crossRe ferenceDat a.d.result s[i].ftp_v istaduz !=  null) { v cmn_origin atorID = v cmn_crossR eferenceDa ta.d.resul ts[i].ftp_ vistaduz;  }
  3889                             break;
  3890                         }
  3891                    }
  3892                }
  3893                */
  3894                //**END  TEMP DISAB LED
  3895  
  3896                //**NOTE : The code  below to  impersonat e Lori Nic holls has  been disab led per ta sk 562307
  3897                /*
  3898                if (vcmn _IsProduct ionEnviron ment == fa lse) {
  3899                    //Pr ovide the  option to  search for  Lori Nich olls, site # 613
  3900                    var  vcmn_imper sonateProm ptString =  "**THIS I S A VISTA  USER SEARC H TEST PRO MPT** \n"  +
  3901                         "If you wo uld like t o imperson ate the us er: \n" +
  3902                         "Lori Nich olls (613)  \n" +
  3903                         "Select OK .  Otherwi se, select  CANCEL.";
  3904                    var  vcmn_confi rmImperson ateVistaUs er = confi rm(vcmn_im personateP romptStrin g);
  3905                    if ( vcmn_confi rmImperson ateVistaUs er == true ) {
  3906                         vcmn_userF irstName =  "Lori";
  3907                         vcmn_userL astName =  "Nicholls" ;
  3908                         vcmn_userS iteNo = "6 13";
  3909                    }
  3910                }
  3911                */
  3912  
  3913                //**TEMP  DISABLED
  3914                /*
  3915                var vcmn _vistauser sData = vc mn_getVist aUsersData (vcmn_user FirstName,  vcmn_user LastName,  vcmn_userS iteNo, fal se);
  3916  
  3917                //Check  vista user s data con tent
  3918                if (vcmn _vistauser sData == n ull || vcm n_vistause rsData.Dat a == null  || vcmn_vi stausersDa ta.Data.le ngth == nu ll || vcmn _vistauser sData.Data .length ==  0) {
  3919                    //Ab ort proces s, missing  info
  3920                    aler t('Unable  to obtain  Vista User  Data, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  3921                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  3922                    retu rn false;
  3923                }
  3924  
  3925                var vcmn _selectedU serFirstNa me = '';
  3926                var vcmn _selectedU serMiddleN ame = '';
  3927                var vcmn _selectedU serLastNam e = '';
  3928                var vcmn _selectedU serSuffix  = '';
  3929                var vcmn _selectedU serDisplay Name = '';
  3930                var vcmn _selectedU serTitle =  '';
  3931                var vcmn _userIsSel ected = fa lse;
  3932  
  3933                if (vcmn _vistauser sData.Data .length >  1) {
  3934                    aler t("The Vis ta User li st, contai ns more th an one use r, please  select the  Vista Use r you want  to use fr om the nex t prompt(s ), a total  of " + vc mn_vistaus ersData.Da ta.length  + " users! ");
  3935                    for  (var i = 0 ; i <= vcm n_vistause rsData.Dat a.length -  1; i++) {
  3936                         var vcmn_c urrentUser FirstName  = '';
  3937                         var vcmn_c urrentUser MiddleName  = '';
  3938                         var vcmn_c urrentUser LastName =  '';
  3939                         var vcmn_c urrentUser Suffix = ' ';
  3940                         var vcmn_c urrentUser DisplayNam e = '';
  3941                         var vcmn_c urrentUser Title = '' ;
  3942                         if (vcmn_v istausersD ata.Data[i ].FirstNam e != null)  { vcmn_cu rrentUserF irstName =  vcmn_vist ausersData .Data[i].F irstName;  }
  3943                         if (vcmn_v istausersD ata.Data[i ].MiddleNa me != null ) { vcmn_c urrentUser MiddleName  = vcmn_vi stausersDa ta.Data[i] .MiddleNam e; }
  3944                         if (vcmn_v istausersD ata.Data[i ].LastName  != null)  { vcmn_cur rentUserLa stName = v cmn_vistau sersData.D ata[i].Las tName; }
  3945                         if (vcmn_v istausersD ata.Data[i ].Suffix ! = null) {  vcmn_curre ntUserSuff ix = vcmn_ vistausers Data.Data[ i].Suffix;  }
  3946                         if (vcmn_v istausersD ata.Data[i ].DisplayN ame != nul l) { vcmn_ currentUse rDisplayNa me = vcmn_ vistausers Data.Data[ i].Display Name; }
  3947                         if (vcmn_v istausersD ata.Data[i ].Title !=  null) { v cmn_curren tUserTitle  = vcmn_vi stausersDa ta.Data[i] .Title; }
  3948                         //Prompt u ser about  this vista  user reco rd
  3949                         var vcmn_u serPromptS tring = "C lick OK, t o select t his user.   Otherwise  CANCEL \n " +
  3950                             "\n Fi rst Name:  " + vcmn_c urrentUser FirstName  +
  3951                             "\n Mi ddle Name:  " + vcmn_ currentUse rMiddleNam e +
  3952                             "\n La st Name: "  + vcmn_cu rrentUserL astName +
  3953                             "\n Su ffix: " +  vcmn_curre ntUserSuff ix +
  3954                             "\n Di splay Name : " + vcmn _currentUs erDisplayN ame +
  3955                             "\n Ti tle: " + v cmn_curren tUserTitle ;
  3956  
  3957                         var vcmn_c onfirmSele ctVistaUse r = confir m(vcmn_use rPromptStr ing);
  3958                         if (vcmn_c onfirmSele ctVistaUse r == true)  {
  3959                             vcmn_u serIsSelec ted = true ;
  3960                             vcmn_s electedUse rFirstName  = vcmn_cu rrentUserF irstName;
  3961                             vcmn_s electedUse rMiddleNam e = vcmn_c urrentUser MiddleName ;
  3962                             vcmn_s electedUse rLastName  = vcmn_cur rentUserLa stName;
  3963                             vcmn_s electedUse rSuffix =  vcmn_curre ntUserSuff ix;
  3964                             vcmn_s electedUse rDisplayNa me = vcmn_ currentUse rDisplayNa me;
  3965                             vcmn_s electedUse rTitle = v cmn_curren tUserTitle ;
  3966                             break;
  3967                         }
  3968                    }
  3969                }
  3970                else {
  3971                    //Se lect data  from the f irst recor d
  3972                    vcmn _userIsSel ected = tr ue;
  3973                    if ( vcmn_vista usersData. Data[0].Fi rstName !=  null) { v cmn_select edUserFirs tName = vc mn_vistaus ersData.Da ta[0].Firs tName; }
  3974                    if ( vcmn_vista usersData. Data[0].Mi ddleName ! = null) {  vcmn_selec tedUserMid dleName =  vcmn_vista usersData. Data[0].Mi ddleName;  }
  3975                    if ( vcmn_vista usersData. Data[0].La stName !=  null) { vc mn_selecte dUserLastN ame = vcmn _vistauser sData.Data [0].LastNa me; }
  3976                    if ( vcmn_vista usersData. Data[0].Su ffix != nu ll) { vcmn _selectedU serSuffix  = vcmn_vis tausersDat a.Data[0]. Suffix; }
  3977                    if ( vcmn_vista usersData. Data[0].Di splayName  != null) {  vcmn_sele ctedUserDi splayName  = vcmn_vis tausersDat a.Data[0]. DisplayNam e; }
  3978                    if ( vcmn_vista usersData. Data[0].Ti tle != nul l) { vcmn_ selectedUs erTitle =  vcmn_vista usersData. Data[0].Ti tle; }
  3979                }
  3980  
  3981                //Check  if a user  was select ed
  3982                if (vcmn _userIsSel ected == f alse) {
  3983                    aler t('A user  was not se lected fro m the prev ious promp ts, the no te cannot  be created  in VistA/ CPRS!');
  3984                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  3985                    retu rn false;
  3986                }
  3987  
  3988                //Execut e Integrat ion
  3989                vcmn_exe cuteVistAI ntegration Request(vc mn_noteId,  vcmn_note Descriptio n, vcmn_pa tientICN,  vcmn_userD omainId, v cmn_localT itle, vcmn _callbackN umber, vcm n_reasonFo rRequest[0 ].name, vc mn_encount erCode, vc mn_signThi sNote, vcm n_veteranF irstName,  vcmn_veter anLastName , vcmn_cre atedOnDate , vcmn_use rEntryDate , vcmn_sel ectedUserF irstName,  vcmn_selec tedUserMid dleName, v cmn_select edUserLast Name, vcmn _selectedU serSuffix,  vcmn_faci lityCode,  vcmn_origi natorID, v cmn_siteHL 7ListenerA ddress, vc mn_patient AssignedLo cation);
  3990  
  3991                */
  3992                //**END  TEMP DISAB LED
  3993                
  3994           }
  3995           el se {
  3996                //Execut e workload  encounter  note inte gration st eps
  3997                //*vcmn_ prepWorklo adEncounte rIntegrati onStep01() ;
  3998  
  3999                //Change d to handl e Historic al Note in stead
  4000                vcmn_pre pHistorica lIntegrati onStep01() ;
  4001           }
  4002  
  4003           // ********** ********** ********** *******
  4004  
  4005  
  4006       }
  4007       catch  (err) {
  4008           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa veToVistA_ Historical Test): ' +  err.messa ge);
  4009           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  4010       }
  4011   }
  4012  
  4013   function v cmn_prepHi storicalIn tegrationS tep01() {
  4014       try {
  4015           // Verify Not e Title
  4016           va r vcmn_Not eTitleIEN  = Xrm.Page .getAttrib ute('ftp_s electedwor kloadnotet itleid').g etValue();
  4017           if  (vcmn_Not eTitleIEN  == null ||  vcmn_Note TitleIEN = = '') {
  4018                alert('T he selecte d note tit le field i s empty, t he note ca nnot be cr eated in V istA/CPRS! ');
  4019                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  4020                return f alse;
  4021           }
  4022           // Verify Loc ation
  4023           va r vcmn_Loc ationIEN =  Xrm.Page. getAttribu te('ftp_se lectedwork loadlocati onid').get Value();
  4024           if  (vcmn_Loc ationIEN = = null ||  vcmn_Locat ionIEN ==  '') {
  4025                alert('T he selecte d location  field is  empty, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  4026                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  4027                return f alse;
  4028           }
  4029           // Verify pat ient id
  4030           if  (vcmn_mat chLookupId  == null | | vcmn_mat chLookupId  == '') {
  4031                alert('T he veteran /patient d oes not ha ve a SSN,  the note c annot be c reated in  VistA/CPRS !');
  4032                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  4033                return f alse;
  4034           }
  4035  
  4036           // Get the cu rrent CRM  User's ass igned site /facility
  4037           va r vcmn_use rSiteId =  "";
  4038  
  4039           va r vcmn_use rData = vc mn_getSing leEntityDa taSync('Sy stemUserSe t', 'ftp_F acilitySit eId', Xrm. Page.conte xt.getUser Id());
  4040           if  (vcmn_use rData != n ull) {
  4041                if (vcmn _userData. d.ftp_Faci litySiteId  != null)  {
  4042                    vcmn _userSiteI d = vcmn_u serData.d. ftp_Facili tySiteId.I d;
  4043                }
  4044           }
  4045  
  4046           // Lookup the  Facility/ Site #
  4047           if  (vcmn_use rSiteId !=  null && v cmn_userSi teId != '' ) {
  4048                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e', vcmn_u serSiteId) ;
  4049                if (vcmn _facilityD ata != nul l) {
  4050                    if ( vcmn_facil ityData.d. ftp_facili tycode !=  null) { vc mn_ViaLogi nFacility  = vcmn_fac ilityData. d.ftp_faci litycode;  }
  4051                }
  4052           }
  4053  
  4054           // Check if V IA Login c ookie exis t (not exp ired)
  4055           va r vcmn_Via LoginCooki e = vcmn_g etCookie(" viasession link");
  4056           if  (vcmn_Via LoginCooki e != null  && vcmn_Vi aLoginCook ie != '')  {
  4057                var vcmn _cookiearr ay = vcmn_ ViaLoginCo okie.split ("~~~~", 3 );
  4058                vcmn_Via LoginToken  = vcmn_co okiearray[ 0];
  4059                vcmn_Via LoginName  = vcmn_coo kiearray[1 ];
  4060                vcmn_esi gnatureCod e = vcmn_c ookiearray [2];
  4061           }
  4062           el se {
  4063                alert("Y our VISTA  session ha s expired.  In order  to process  a note, y ou must be  logged in to VISTA!" );
  4064                Xrm.Page .ui.tabs.g et('Tab_Vi stALogin') .setVisibl e(true);
  4065                Xrm.Page .ui.tabs.g et('Tab_Vi stALogin') .setFocus( );
  4066                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  4067                return;
  4068           }
  4069  
  4070           // Lookup Pat ient Id us ing VIA 'm atch' serv ice
  4071           vi alib_match (vcmn_requ estingApp,  vcmn_cons umingAppTo ken, vcmn_ consumingA ppPassword , vcmn_bas eServiceEn dpointUrl,  vcmn_ViaL oginName,  vcmn_ViaLo ginToken,  vcmn_ViaLo ginFacilit y, vcmn_ma tchLookupI d, vcmn_pr epHistoric alIntegrat ionStep01_ response);
  4072       }
  4073       catch  (err) {
  4074           al ert('Progr ess Note R ibbon Func tion Error (vcmn_prep Historical Integratio nStep01):  ' + err.me ssage);
  4075           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  4076       }
  4077   }
  4078  
  4079   function v cmn_prepHi storicalIn tegrationS tep01_resp onse(vcmn_ error, vcm n_matchres ponse) {
  4080       try {
  4081           // Check for  non VIA se rvice erro r
  4082           if  (vcmn_err or != null ) {
  4083                alert("U nable to m atch the C RM Veteran /Patient w ith a reco rd in Vist A/CPRS. Th e process  failed wit h error: "  + vcmn_ma tchrespons e + ", the  note cann ot be crea ted in Vis tA/CPRS!") ;
  4084                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  4085                return f alse;
  4086           }
  4087           el se {
  4088                //Test f or VIA Ser vice Error
  4089                if (vcmn _matchresp onse.getEl ementsByTa gName("fau lt").lengt h > 0) {
  4090                    aler t("Unable  to match t he CRM Vet eran/Patie nt with a  record in  Vista/CPRS . Service  Error: " +  vcmn_matc hresponse. getElement sByTagName ("fault")[ 0].textCon tent + ",  the note c annot be c reated in  VistA/CPRS !");
  4091                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  4092                    retu rn false;
  4093                }
  4094                //Get VI A service  Response
  4095                if (vcmn _matchresp onse.getEl ementsByTa gName("pat ients")[0] ) {
  4096                    var  vcmn_match Array = vc mn_matchre sponse.get ElementsBy TagName("p atients")[ 0].childNo des;
  4097                    //ch ildNodes[4 ] holds th e localPid /IEN value
  4098                    vcmn _ViaPatien tId = vcmn _matchArra y[0].child Nodes[4].t extContent ;
  4099                }
  4100                else {
  4101                    aler t("Unable  to match t he CRM Vet eran/Patie nt with a  record in  Vista/CPRS . No data  returned,  the note c annot be c reated in  VistA/CPRS !");
  4102                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  4103                    retu rn false;
  4104                }
  4105           }
  4106  
  4107           // **DISABLED  FOR HISTO RICAL
  4108           /*
  4109  
  4110           // Verify Inp atient
  4111           if  (Xrm.Page .getAttrib ute('ftp_w orkloadinp atient').g etValue()  == true) {
  4112                vcmn_Via InPatient  = "1";
  4113           }
  4114           el se {
  4115                vcmn_Via InPatient  = "0";
  4116           }
  4117  
  4118           // Verify CPT  Code & De scription
  4119           va r vcmn_Crm CptCode =  Xrm.Page.g etAttribut e('ftp_cpt code').get Value();
  4120           if  (vcmn_Crm CptCode ==  null) {
  4121                alert('T he CPT Cod e field is  empty, th e note can not be cre ated in Vi stA/CPRS!' );
  4122                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  4123                return f alse;
  4124           }
  4125           el se {
  4126                var vcmn _cptData =  vcmn_getS ingleEntit yDataSync( 'ftp_cptco deSet', 'f tp_amadesc ription',  vcmn_CrmCp tCode[0].i d);
  4127                if (vcmn _cptData.d .ftp_amade scription  != null) {
  4128                    vcmn _ViaCptDes cription =  (vcmn_cpt Data.d.ftp _amadescri ption).rep lace(";",  "\;");
  4129                    vcmn _ViaCptCod e = vcmn_C rmCptCode[ 0].name;
  4130                }
  4131                else {
  4132                    aler t('The CPT  Code is m issing the  AMA Descr iption, th e note can not be cre ated in Vi stA/CPRS!' );
  4133                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  4134                    retu rn false;
  4135                }
  4136           }
  4137  
  4138           // Combine CP T Code and  Descripti on
  4139           va r vcmn_Cpt Combined =  '';
  4140           if  (vcmn_Via CptCode.le ngth > 0 & & vcmn_Via CptDescrip tion.lengt h > 0) {
  4141                vcmn_Cpt Combined =  vcmn_ViaC ptCode + " ^" + vcmn_ ViaCptDesc ription;
  4142           }
  4143  
  4144           // Verify Dia gnosis Cod e & Descri ption
  4145           va r vcmn_Crm DiagnosisC ode = Xrm. Page.getAt tribute('f tp_diagnos iscode').g etValue();
  4146           if  (vcmn_Crm DiagnosisC ode == nul l) {
  4147                alert('T he Primary  Diagnosis  Code fiel d is empty , the note  cannot be  created i n VistA/CP RS!');
  4148                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  4149                return f alse;
  4150           }
  4151  
  4152           if  (vcmn_Crm DiagnosisC ode != nul l && vcmn_ CrmDiagnos isCode !=  '') {
  4153                var vcmn _diagnosis Data = vcm n_getSingl eEntityDat aSync('ftp _diagnosis codeSet',  'ftp_descr iption', v cmn_CrmDia gnosisCode [0].id);
  4154                if (vcmn _diagnosis Data.d.ftp _descripti on != null ) {
  4155                    vcmn _ViaDiagno sisDescrip tion = (vc mn_diagnos isData.d.f tp_descrip tion).repl ace(";", " \;");
  4156                    vcmn _ViaDiagno sisCode =  vcmn_CrmDi agnosisCod e[0].name;
  4157                }
  4158           }
  4159  
  4160           // Combine Di agnosis Co de and Des cription a nd mark as  PRIMARY ( ^1)
  4161           va r vcmn_Dia gnosisComb ined = '';
  4162           if  (vcmn_Via DiagnosisC ode != nul l && vcmn_ ViaDiagnos isDescript ion != nul l) {
  4163                if (vcmn _ViaDiagno sisCode.le ngth > 0 & & vcmn_Via DiagnosisD escription .length >  0) {
  4164                    vcmn _Diagnosis Combined =  vcmn_ViaD iagnosisCo de + "^" +  vcmn_ViaD iagnosisDe scription  + "^1";
  4165                }
  4166           }
  4167  
  4168           // Get Second ary Diagno sis Codes
  4169           va r vcmn_Crm SecondaryD iagnosis =  Xrm.Page. getAttribu te('ftp_se lectedseco ndarydiagn osiscodes' ).getValue ();
  4170           if  (vcmn_Crm SecondaryD iagnosis ! = null &&  vcmn_CrmSe condaryDia gnosis !=  '') {
  4171                if (vcmn _Diagnosis Combined ! = '') {
  4172                    vcmn _Diagnosis Combined =  vcmn_Diag nosisCombi ned + ";"  + vcmn_Crm SecondaryD iagnosis;
  4173                }
  4174                else { v cmn_Diagno sisCombine d = vcmn_C rmSecondar yDiagnosis ; }
  4175           }
  4176  
  4177           */
  4178           // **END DISA BLED FOR H ISTORICAL
  4179  
  4180           // Get eSigna ture code
  4181           // This secti on is no l onger used , replaced  by via lo gin contro l esignatu re
  4182           /*
  4183           va r vcmn_eSi gnatureCod e = prompt ("Please e nter your  eSignature  Code belo w.\nThis i s required  to comple te the Wor kload Enco unter Note !");
  4184           if  (vcmn_eSi gnatureCod e == null  || vcmn_eS ignatureCo de == "" | | vcmn_eSi gnatureCod e == "unde fined") {
  4185                alert('T he eSignat ure Code e ntered is  invalid, t he note ca nnot be cr eated in V istA/CPRS! ');
  4186                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  4187                return f alse;
  4188           }
  4189           */
  4190  
  4191           // Get User E ntry Date
  4192           va r vcmn_cre atedOnDate  = vialib_ convertToV istaDateTi me(Xrm.Pag e.getAttri bute('crea tedon').ge tValue());
  4193           va r vcmn_use rEntryDate  = null;
  4194           if  (Xrm.Page .getAttrib ute('ftp_u serentryda te').getVa lue() != n ull) {
  4195                vcmn_use rEntryDate  = vialib_ convertToV istaDateTi me(Xrm.Pag e.getAttri bute('ftp_ userentryd ate').getV alue());
  4196           }
  4197           if  (vcmn_use rEntryDate  == null)  { vcmn_use rEntryDate  = vcmn_cr eatedOnDat e; }
  4198  
  4199           // Reformat N ote Descri ption as n eeded to h andle long  lines of  text (Word Wrap)
  4200           va r vcmn_not eDescripti on = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  4201           va r vcmn_Not eText = vc mn_noteDes cription;
  4202           va r vcmn_Rev isedNoteTe xt = "";
  4203           // Do Breakdo wn of line s
  4204           va r vcmn_Tex tLines = v cmn_NoteTe xt.split(' \n');
  4205           if  (vcmn_Tex tLines.len gth > 0) {
  4206                //Reform at text
  4207                for (var  i = 0; i  < vcmn_Tex tLines.len gth; i++)  {
  4208                    //Te st for a l ong line
  4209                    if ( vcmn_TextL ines[i].le ngth > vcm n_WordWrap Limit) {
  4210                         //Break do wn line
  4211                         var vcmn_N ewString =  vcmn_word Wrap(vcmn_ TextLines[ i], vcmn_W ordWrapLim it, '\n');
  4212                         //Add revi sed text b ack
  4213                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _NewString  + "\n";   //Add back  the CR/LF  used to s plit on
  4214                    }
  4215                    else  {
  4216                         //Add text  to new no te
  4217                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _TextLines [i] + "\n" ; //Add ba ck the CR/ LF used to  split on
  4218                    }
  4219                }
  4220           }
  4221           if  (vcmn_Rev isedNoteTe xt != "" & & vcmn_Rev isedNoteTe xt != null ) {
  4222                vcmn_not eDescripti on = vcmn_ RevisedNot eText;
  4223           }
  4224  
  4225           // Add list o f addition al signer  names to N ote Text i f they exi sts
  4226           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  4227                //Create  text stri ngs from a dditional  signers ar ray
  4228                var vcmn _SignerNam es = "\nAd ditional N ote Signer s\n" + "-- ---------- ---------- -------\n" ;
  4229                for (var  i = 0; i  <= vcmn_Ad dlSignersN ameArray.l ength - 1;  i++) {
  4230                    if ( i >= 1) {
  4231                         var vcmn_s ingleSigne rName = vc mn_AddlSig nersNameAr ray[i].spl it("___");
  4232                         vcmn_Signe rNames = v cmn_Signer Names + vc mn_singleS ignerName[ 1] + "\n";
  4233                    }
  4234                }
  4235                //Add to  Note Desc ription
  4236                vcmn_not eDescripti on = vcmn_ noteDescri ption + vc mn_SignerN ames;
  4237           }
  4238           va r vcmn_Not eTitleIEN  = Xrm.Page .getAttrib ute('ftp_s electedwor kloadnotet itleid').g etValue();
  4239           va r vcmn_Loc ationIEN =  Xrm.Page. getAttribu te('ftp_se lectedwork loadlocati onid').get Value();
  4240  
  4241           // Create tex t strings  from addit ional sign ers array
  4242           // **NOT USED  ON HISTOR ICAL***
  4243           /*
  4244           va r vcmn_Sig nerIEN = " ";
  4245           if  (vcmn_Add lSignersIe nArray !=  null) {
  4246                for (var  i = 0; i  <= vcmn_Ad dlSignersI enArray.le ngth - 1;  i++) {
  4247                    if ( i == 1) {  vcmn_Signe rIEN = vcm n_AddlSign ersIenArra y[i]; }
  4248                    if ( i > 1) { v cmn_Signer IEN = vcmn _SignerIEN  + "," + v cmn_AddlSi gnersIenAr ray[i]; }
  4249                }
  4250           }
  4251           */
  4252           // **END NOT  USED ON HI STORICAL** *
  4253  
  4254           // Reformat N ote Descri ption for  VIA Note a nd Encount er web ser vice to ha ndle line  feed and c arriage re turn
  4255           // Replace al l \n and \ r occurren ces with |
  4256           vc mn_noteDes cription =  vcmn_note Descriptio n.replace( /\n/g, "|" );
  4257           vc mn_noteDes cription =  vcmn_note Descriptio n.replace( /\r/g, "|" );
  4258  
  4259           // Execute VI A saveNote AndEncount er Service
  4260           // *vialib_sa veNoteAndE ncounter(v cmn_reques tingApp, v cmn_consum ingAppToke n, vcmn_co nsumingApp Password,  vcmn_baseS erviceEndp ointUrl, v cmn_ViaLog inName, vc mn_ViaLogi nToken, vc mn_ViaLogi nFacility,  vcmn_Note TitleIEN,  vcmn_Locat ionIEN, vc mn_ViaPati entId, vcm n_noteDesc ription, v cmn_userEn tryDate, v cmn_ViaLog inFacility , vcmn_Via InPatient,  vcmn_CptC ombined, v cmn_Diagno sisCombine d, vcmn_es ignatureCo de, vcmn_S ignerIEN,  'E', vcmn_ saveNoteAn dEncounter _response)
  4261           // Replace wi th Historc al Note cr eation
  4262           vi alib_write Note(vcmn_ requesting App, vcmn_ consumingA ppToken, v cmn_consum ingAppPass word, vcmn _baseServi ceEndpoint Url, vcmn_ ViaLoginNa me, vcmn_V iaLoginTok en, vcmn_V iaLoginFac ility, vcm n_NoteTitl eIEN, vcmn _LocationI EN, vcmn_u serEntryDa te, 'E', v cmn_ViaPat ientId, vc mn_noteDes cription,  vcmn_write Note_respo nse)
  4263  
  4264  
  4265       }
  4266       catch  (err) {
  4267           al ert('Progr ess Note R ibbon Func tion Error (vcmn_prep Historical Integratio nStep01_re sponse): '  + err.mes sage);
  4268           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  4269       }
  4270   }
  4271  
  4272   function v cmn_writeN ote_respon se(vcmn_er rorThrown,  vcmn_requ estRespons e) {
  4273       //Proc ess Note R esponse
  4274       try {
  4275           if  (vcmn_err orThrown ! = null) {
  4276                //Write  Error
  4277                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etValue('E RROR');
  4278                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etSubmitMo de('always ');
  4279                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tValue(Str ing(vcmn_e rrorThrown ));
  4280                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tSubmitMod e('always' );
  4281                Xrm.Page .getAttrib ute('ftp_i ntegration date').set Value(new  Date());
  4282                Xrm.Page .getAttrib ute('ftp_i ntegration date').set SubmitMode ('always') ;
  4283                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etValue('' );
  4284                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etSubmitMo de('always ');
  4285                alert('T he histori cal note c reation in  VistA/CPR S failed!\ nPlease se e the inte gration er ror field  for detail s.');
  4286                Xrm.Page .getContro l('ftp_int egrationer ror').setF ocus();
  4287                Xrm.Page .data.enti ty.save();
  4288                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  4289                return f alse;
  4290           }
  4291           el se {
  4292                //Write  web servic e response  Success o r Failure
  4293                if (vcmn _requestRe sponse.get ElementsBy TagName("f ault").len gth > 0) {
  4294                    //Wr ite Failur e entry
  4295                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setValu e('ERROR') ;
  4296                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setSubm itMode('al ways');
  4297                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setValue ("Service  Error: " +  vcmn_requ estRespons e.getEleme ntsByTagNa me("fault" )[0].textC ontent);
  4298                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setSubmi tMode('alw ays');
  4299                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setValue( new Date() );
  4300                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setSubmit Mode('alwa ys');
  4301                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setValu e('');
  4302                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setSubm itMode('al ways');
  4303                    aler t('The his torical no te creatio n in VistA /CPRS fail ed!\nPleas e see the  integratio n error fi eld for de tails.');
  4304                    Xrm. Page.getCo ntrol('ftp _integrati onerror'). setFocus() ;
  4305                    Xrm. Page.data. entity.sav e();
  4306                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  4307                    retu rn false;
  4308                }
  4309                else {
  4310                    //Te st for dat a
  4311                    if ( vcmn_reque stResponse .getElemen tsByTagNam e("ns2:Not eResultTO" )[0]) {
  4312                         //Sucessfu ll creatio n of histo rical note
  4313                         //Xrm.Page .getAttrib ute('ftp_n otedetail' ).setValue (vcmn_note Text);
  4314                         //Xrm.Page .getAttrib ute('ftp_n otedetail' ).setSubmi tMode('alw ays');
  4315                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set Value('OK' );
  4316                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set SubmitMode ('always') ;
  4317                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setV alue(null) ;
  4318                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setS ubmitMode( 'always');
  4319                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setVa lue(new Da te());
  4320                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setSu bmitMode(' always');
  4321                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set Value(vcmn _requestRe sponse.get ElementsBy TagName("n s2:NoteRes ultTO")[0] .childNode s[0].textC ontent);
  4322                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set SubmitMode ('always') ;
  4323  
  4324  
  4325                         //alert("H istorical  Note Id cr eated: " +  vcmn_requ estRespons e.getEleme ntsByTagNa me("ns2:No teResultTO ")[0].chil dNodes[0]. textConten t);
  4326  
  4327                         //***FIX S TUFF below  so not to  double up ...
  4328                         //Need to  sign, then  add addit ional sign ers next.. .
  4329  
  4330                         var vcmn_s ignThisNot e = Xrm.Pa ge.getAttr ibute('ftp _signthisn ote').getV alue();
  4331                         if (vcmn_s ignThisNot e == 10000 0001) { vc mn_signThi sNote = tr ue; } else  { vcmn_si gnThisNote  = false;  }
  4332  
  4333                        
  4334                         if (vcmn_s ignThisNot e == true)  {
  4335                             //Use  VIA and si gn the not e
  4336                             //aler t("The not e should b e signed.. ..");
  4337  
  4338                             //Exec ute signNo te Service
  4339                             vialib _signNote( vcmn_reque stingApp,  vcmn_consu mingAppTok en, vcmn_c onsumingAp pPassword,  vcmn_base ServiceEnd pointUrl,  vcmn_ViaLo ginName, v cmn_ViaLog inToken, v cmn_ViaLog inFacility , Xrm.Page .getAttrib ute('ftp_i ntegration noteid').g etValue(),  vcmn_esig natureCode , vcmn_sig nNote_resp onse);
  4340                         }
  4341                         else {
  4342                             //Comp lete Note
  4343                             Xrm.Pa ge.getCont rol('ftp_i ntegration status').s etFocus();
  4344                             alert( 'The histo rical note  creation  in VistA/C PRS was su ccessful,  this note  will now b e marked a s complete d. \n\nPle ase exit t his note r ecord afte r clicking  OK to thi s prompt!' );
  4345                             Xrm.Pa ge.ui.clea rFormNotif ication("S AVEVISTA") ;
  4346                             Xrm.Pa ge.data.en tity.save( );
  4347                         }
  4348                         /*
  4349                         if (vcmn_l ocalStorag eVarName ! = "" && vc mn_localSt orageVarNa me != null ) {
  4350                             //Clea r existing  session s torage var iable.
  4351                             localS torage.rem oveItem(vc mn_localSt orageVarNa me);
  4352                         }
  4353                         */
  4354  
  4355                    }
  4356                    else  {
  4357                         //Write No  Data Fail ure
  4358                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set Value('ERR OR');
  4359                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set SubmitMode ('always') ;
  4360                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setV alue("Serv ice Error:  NO DATA R ETURNED FR OM VIA/VIS TA REGARDI NG HISTORI CAL NOTE C REATION!") ;
  4361                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setS ubmitMode( 'always');
  4362                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setVa lue(new Da te());
  4363                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setSu bmitMode(' always');
  4364                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set Value('');
  4365                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set SubmitMode ('always') ;
  4366                         alert('The  historica l note cre ation in V istA/CPRS  failed!\nP lease see  the integr ation erro r field fo r details. ');
  4367                         Xrm.Page.g etControl( 'ftp_integ rationerro r').setFoc us();
  4368                         Xrm.Page.d ata.entity .save();
  4369                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  4370                         return fal se;
  4371                    }
  4372                }
  4373           }
  4374       }
  4375       catch  (err) {
  4376           al ert('Progr ess Note R ibbon Func tion Error (vcmn_writ eNote_resp onse): ' +  err.messa ge);
  4377           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  4378       }
  4379   }
  4380  
  4381   function v cmn_signNo te_respons e(vcmn_err orThrown,  vcmn_reque stResponse ) {
  4382       //Proc ess Sign N ote Respon se
  4383       try {
  4384           if  (vcmn_err orThrown ! = null) {
  4385                //Write  Error
  4386                alert("T he VIA sig nNote fail ed with er ror: " + v cmn_reques tResponse) ;
  4387                return f alse;
  4388           }
  4389           // Write web  service re sponse Suc cess or Fa ilure
  4390           if  (vcmn_req uestRespon se.getElem entsByTagN ame("fault ").length  > 0) {
  4391                //Write  Failure en try
  4392                alert("S ervice Err or: " + vc mn_request Response.g etElements ByTagName( "fault")[0 ].textCont ent);
  4393                return f alse;
  4394           }
  4395           el se {
  4396                //Test f or data
  4397                if (vcmn _requestRe sponse.get ElementsBy TagName("n s2:signNot eResponse" )[0]) {
  4398                    //Su cessful si gn of note
  4399                    aler t("Note si gned suces sfully wit h status o f " + vcmn _requestRe sponse.get ElementsBy TagName("n s2:signNot eResponse" )[0].textC ontent);
  4400                    
  4401                    //Co mplete Not e
  4402                    Xrm. Page.getCo ntrol('ftp _integrati onstatus') .setFocus( );
  4403                    aler t('The his torical no te creatio n in VistA /CPRS was  successful , this not e will now  be marked  as comple ted. \n\nP lease exit  this note  record af ter clicki ng OK to t his prompt !');
  4404                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  4405                    Xrm. Page.data. entity.sav e();
  4406                }
  4407                else {
  4408                    //Wr ite No Dat a Failure
  4409                    aler t("Service  Error: NO  RESPONSE  RETURNED F ROM VIA si gnNote ser vice");
  4410                    retu rn false;
  4411                }
  4412           }
  4413  
  4414           // *****NOTE,  NEED TO F ILL IN THE  SIGNED NO TE VARIABL ES ON FORM , SEE orig inal non-v ia histori cal note
  4415       }
  4416       catch  (err) {
  4417           al ert('Progr ess Note R ibbon Func tion Error (vcmn_sign Note_respo nse): ' +  err.messag e);
  4418           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  4419       }
  4420   }
  4421  
  4422   //******En d Test Sec tion for V IA Histori cal Note C reation*** ********** ******
  4423  
  4424  
  4425  
  4426   function v cmn_execut eCrmOdataG etRequest( vcmn_jsonQ uery, vcmn _aSync, vc mn_aSyncCa llback, vc mn_skipCou nt, vcmn_o ptionArray ) {
  4427       //This  function  executes a  CRM Odata  web servi ce call to  retrieve  Crm data
  4428       //*vcm n_jsonQuer y* - a pro perly form atted CRM  Odata Quer y string ( required)
  4429       //*vcm n_aSync* -  specify ' true' to e xecute asy nchronousl y otherwis e 'false'  (required)
  4430       //*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 '')
  4431       //*vcm n_skipCoun t* - Initi al setting  is always  '0', incr ements by  50 per CRM  SDK Odata  standards  (required )
  4432       //*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)
  4433       try {
  4434           va r vcmn_ent ityData =  null;
  4435           $. ajax({
  4436                type: 'G ET',
  4437                contentT ype: 'appl ication/js on; charse t=utf-8',
  4438                datatype : 'json',
  4439                url: vcm n_jsonQuer y,
  4440                beforeSe nd: functi on (XMLHtt pRequest)  {
  4441                    XMLH ttpRequest .setReques tHeader('A ccept', 'a pplication /json');
  4442                },
  4443                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  4444                    vcmn _entityDat a = data;
  4445                    if ( vcmn_aSync  == true)  {
  4446                         vcmn_aSync Callback(v cmn_entity Data, vcmn _skipCount , vcmn_opt ionArray);
  4447                    }
  4448                },
  4449                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  4450                    aler t('Fail: A jax Error  in vcmn_ex ecuteCrmOd ataGetRequ est: ' + e rrorThrown  + " Reque st: " + vc mn_jsonQue ry);
  4451                },
  4452                async: v cmn_aSync,
  4453                cache: f alse
  4454           }) ;
  4455           re turn vcmn_ entityData ;
  4456       }
  4457       catch  (err) {
  4458           al ert('An er ror occure d in the v cmn_execut eCrmOdataG etRequest  function.   Error Det ail Messag e: ' + err );
  4459       }
  4460   }
  4461  
  4462   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) {
  4463       //This  function  returns a  CRM JSON d ataset for  all entit y records  matching c riteria pr ovided Asy ncronously
  4464       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  4465       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  4466       //*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
  4467       //*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'
  4468       //*vcm n_sortDire ction* - i s a string  specifyin g the sort  as Ascend ing or Des cending e. g. 'asc' o r 'desc'
  4469       //*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)
  4470       //*vcm n_aSyncCal lback* - i s the name  of the fu nction to  call when  returning  the result
  4471       //*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
  4472  
  4473       try {
  4474           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;
  4475           vc mn_execute CrmOdataGe tRequest(v cmn_jsonQu ery, true,  vcmn_aSyn cCallback,  vcmn_skip Count, vcm n_optionAr ray);
  4476       }
  4477       catch  (err) {
  4478           al ert('An er ror occure d in the v cmn_getMul tipleEntit yDataAsync  function.   Error De tail Messa ge: ' + er r);
  4479       }
  4480   }
  4481  
  4482   function v cmn_getSin gleEntityD ataSync(vc mn_entityS etName, vc mn_attribu teSet, vcm n_entityId ) {
  4483       //This  function  returns a  CRM JSON d ataset for  a single  entity rec ord based  on the ent ity id pro vided Sync ronously
  4484       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  4485       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  4486       //*vcm n_entityId * - is the  Guid for  the entity  record
  4487  
  4488       try {
  4489           va r vcmn_ent ityIdNoBra cket = vcm n_entityId .replace(/ ({|})/g, ' ');
  4490           va r vcmn_sel ectString  = '(guid'  + "'" + vc mn_entityI dNoBracket  + "'" + ' )?$select= ' + vcmn_a ttributeSe t;
  4491           va r vcmn_jso nQuery = v cmn_server Url + vcmn _crmOdataE ndPoint +  '/' + vcmn _entitySet Name + vcm n_selectSt ring;
  4492           va r vcmn_ent ityData =  vcmn_execu teCrmOdata GetRequest (vcmn_json Query, fal se, '', 0,  null);
  4493           re turn vcmn_ entityData ;
  4494       }
  4495       catch  (err) {
  4496           al ert('An er ror occure d in the v cmn_getSin gleEntityD ataSync fu nction.  E rror Detai l Message:  ' + err);
  4497       }
  4498   }
  4499  
  4500   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) {
  4501       //This  function  returns a  CRM JSON d ataset for  all entit y records  matching c riteria pr ovided Syn cronously
  4502       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  4503       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  4504       //*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
  4505       //*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'
  4506       //*vcm n_sortDire ction* - i s a string  specifyin g the sort  as Ascend ing or Des cending e. g. 'asc' o r 'desc'
  4507       //*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)
  4508  
  4509       try {
  4510           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;
  4511           va r vcmn_ent ityData =  vcmn_execu teCrmOdata GetRequest (vcmn_json Query, fal se, '', vc mn_skipCou nt, null);
  4512           re turn vcmn_ entityData ;
  4513       }
  4514       catch  (err) {
  4515           al ert('An er ror occure d in the v cmn_getMul tipleEntit yDataSync  function.   Error Det ail Messag e: ' + err );
  4516       }
  4517   }