109. EPMO Open Source Coordination Office Redaction File Detail Report

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

109.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_3_0_0_12.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Mon Sep 18 10:55:52 2017 UTC
2 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_3_0_0_12.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Thu Nov 30 17:22:23 2017 UTC

109.2 Comparison summary

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

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

109.4 Active regular expressions

No regular expressions were active.

109.5 Comparison detail

  1   //VistACPR SMultiProg ressNoteFo rmScript.j s
  2   //Contains  variables  and funct ions used  by the CRM  Form and  Ribbon
  3   //Requires  jQuery lo aded on th e CRM Form
  4   //The form  where thi s script l ibrary is  applied mu st have th e followin g form par ameters de fined
  5   /*
  6   parameter_ regardingo bjectid  -   Type:Uni queId
  7   parameter_ regardingo bjectidnam e  -  Type :SafeStrin g
  8   parameter_ regardingo bjectidtyp e  -  Type :SafeStrin g
  9   parameter_ triageexpe rt  -  Typ e:SafeStri ng
  10   parameter_ triageminu tes  -  Ty pe:Integer
  11   */
  12  
  13   //Static V ariables
  14   var vcmn_c rmOdataEnd Point = '/ XRMService s/2011/Org anizationD ata.svc';
  15   var vcmn_s erverUrl =  Xrm.Page. context.ge tClientUrl ();
  16  
  17   //var vcmn _NoteWrite Url = 'htt ps://qacrm dac.np.crm .vrm.vba. DNS     /WebParts/ DEV/api/no teswrite';     //OLD MANU AL DEV URL
  18   var vcmn_N oteWriteUr l = '';
  19   //var vcmn _eesummary URLbase =  'https://q acrmdac.np .crm.vrm.v ba. DNS     /WebParts/ QA/api/ees ummary/1.0 /xml/ftpCR M/';    //OLD MANU AL DEV URL
  20   var vcmn_e esummaryUR Lbase = '' ;
  21   //var vcmn _VistaUser sURLbase =  'https:// qacrmdac.n p.crm.vrm. vba. DNS     /WebParts/ DEV/api/Vi staUsers/1 .0/json/ft pCRM/john/ smith/1234 ?noFilter= true';    //OLD MANU AL DEV URL
  22   var vcmn_V istaUsersU RLbase = ' ';
  23   //var vcmn _AddSigner sUrl = 'ht tps://qacr mdac.np.cr m.vrm.vba. DNS     /WebParts/ DEV/api/VI A/AddSigne rs/1.0/jso n';    //OLD MANU AL DEV URL
  24   var vcmn_A ddSignersU rl = '';
  25   //var vcmn _Appointme ntsUrl = ' https://qa crmdac.np. crm.vrm.vb a. DNS     /WebParts/ DEV/api/Ap pointments /1.0/json/ FtPCRM/';    //OLD MANU AL DEV URL
  26   var vcmn_A ppointment sUrl = '';
  27   //var vcmn _Medicatio nsUrl = 'h ttps://qac rmdac.np.c rm.vrm.vba . DNS     /WebParts/ DEV/api/Me dications/ 1.0/json/F tPCRM/';    //OLD MANU AL DEV URL
  28   var vcmn_M edications Url = '';
  29  
  30   //Producti on Environ ment Indic ator
  31   var vcmn_I sProductio nEnvironme nt = false ;
  32  
  33   //Word Wra p Line Lim it
  34   var vcmn_W ordWrapLim it = 75;
  35  
  36   //Addition al Signers  Data
  37   var vcmn_A ddlSigners NameArray  = null;
  38   var vcmn_A ddlSigners IenArray =  null;
  39   var vcmn_l ocalStorag eVarName =  "";
  40  
  41   //Workload  Encounter  data
  42   var vcmn_P rogressNot eSubject =  'Progress  Note: ';
  43   var vcmn_T riageNoteS ubject = ' Triage Not e: ';
  44   var vcmn_W orkloadEnc ounterSubj ect = 'Wor kload Enco unter Note : ';
  45   var vcmn_i sWorkloadE ncounter =  false;
  46   var vcmn_m atchLookup Id = '';
  47  
  48   var vcmn_V iaLoginNam e = null;
  49   var vcmn_V iaLoginTok en = null;
  50   var vcmn_e signatureC ode = null ;
  51   var vcmn_V iaLoginFac ility = nu ll;
  52   var vcmn_V iaPatientI d = null;
  53   var vcmn_V iaInPatien t = null;
  54   var vcmn_V iaCptCode  = null;
  55   var vcmn_V iaCptDescr iption = n ull;
  56   var vcmn_V iaDiagnosi sCode = nu ll;
  57   var vcmn_V iaDiagnosi sDescripti on = null;
  58  
  59   var vcmn_b aseService EndpointUr l = null;
  60   var vcmn_r equestingA pp = null;
  61   var vcmn_c onsumingAp pToken = n ull;
  62   var vcmn_c onsumingAp pPassword  = null;
  63  
  64   var vcmn_f acilityGro upDefaultI d = null;
  65  
  66   var vcmn_n onNarcotic Template =  false;
  67   var vcmn_n onNarcotic RequestNam e = "Medic ation - Re newal Non- Narcotic";
  68  
  69   function v cmn_getQue ryVariable (vcmn_vari able) {
  70       try {
  71           // Get a Quer y Variable
  72           va r vcmn_que ry = windo w.location .search.su bstring(1) ;
  73           va r vcmn_var s = vcmn_q uery.split ("&");
  74           fo r (var i =  0; i < vc mn_vars.le ngth; i++)  {
  75                var vcmn _pair = vc mn_vars[i] .split("=" );
  76                if (vcmn _pair[0] = = vcmn_var iable) {
  77                    retu rn decodeU RIComponen t(vcmn_pai r[1]);
  78                }
  79           }
  80           re turn "";
  81       }
  82       catch  (err) {
  83           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getQ ueryVariab le): ' + e rr.message );
  84       }
  85   }
  86  
  87   function v cmn_setSim pleLookupV alue(vcmn_ LookupId,  vcmn_Type,  vcmn_Id,  vcmn_Name)  {
  88       try {
  89           // Sets the v alue for l ookup attr ibutes tha t accept o nly a sing le entity  reference.
  90           va r vcmn_loo kupReferen ce = [];
  91           vc mn_lookupR eference[0 ] = {};
  92           vc mn_lookupR eference[0 ].id = vcm n_Id;
  93           vc mn_lookupR eference[0 ].entityTy pe = vcmn_ Type;
  94           vc mn_lookupR eference[0 ].name = v cmn_Name;
  95           Xr m.Page.get Attribute( vcmn_Looku pId).setVa lue(vcmn_l ookupRefer ence);
  96       }
  97       catch  (err) {
  98           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_setS impleLooku pValue): '  + err.mes sage);
  99       }
  100   }
  101  
  102   function v cmn_conver tCrmDateTo VistADate( vcmn_crmDa te) {
  103       try {
  104           va r vcmn_Vis tADate = n ull;
  105           if  (vcmn_crm Date != nu ll) {
  106                var vcmn _crmYear =  (vcmn_crm Date.getFu llYear()). toString() ;
  107                var vcmn _crmMonth  = '00';
  108                if ((vcm n_crmDate. getMonth()  + 1) < 10 ) {
  109                    vcmn _crmMonth  = '0' + (v cmn_crmDat e.getMonth () + 1).to String();
  110                }
  111                else {
  112                    vcmn _crmMonth  = (vcmn_cr mDate.getM onth() + 1 ).toString ();
  113                }
  114                var vcmn _crmDay =  '00';
  115                if ((vcm n_crmDate. getDate())  < 10) {
  116                    vcmn _crmDay =  '0' + (vcm n_crmDate. getDate()) .toString( );
  117                }
  118                else {
  119                    vcmn _crmDay =  (vcmn_crmD ate.getDat e()).toStr ing();
  120                }
  121                var vcmn _crmHours  = '00';
  122                if ((vcm n_crmDate. getHours() ) < 10) {
  123                    vcmn _crmHours  = '0' + (v cmn_crmDat e.getHours ()).toStri ng();
  124                }
  125                else {
  126                    vcmn _crmHours  = (vcmn_cr mDate.getH ours()).to String();
  127                }
  128                var vcmn _crmMinute s = '00';
  129                if ((vcm n_crmDate. getMinutes ()) < 10)  {
  130                    vcmn _crmMinute s = '0' +  (vcmn_crmD ate.getMin utes()).to String();
  131                }
  132                else {
  133                    vcmn _crmMinute s = (vcmn_ crmDate.ge tMinutes() ).toString ();
  134                }
  135                var vcmn _crmSecond s = '00';
  136                if ((vcm n_crmDate. getSeconds ()) < 10)  {
  137                    vcmn _crmSecond s = '0' +  (vcmn_crmD ate.getSec onds()).to String();
  138                }
  139                else {
  140                    vcmn _crmSecond s = (vcmn_ crmDate.ge tSeconds() ).toString ();
  141                }
  142  
  143                //Create  VistA Dat e
  144                vcmn_Vis tADate = v cmn_crmYea r + vcmn_c rmMonth +  vcmn_crmDa y + vcmn_c rmHours +  vcmn_crmMi nutes + vc mn_crmSeco nds;
  145           }
  146           re turn vcmn_ VistADate;
  147       }
  148       catch  (err) {
  149           al ert('Progr ess Note E rror(vcmn_ convertCrm DateToVist ADate): '  + err.mess age);
  150           re turn null;
  151       }
  152   }
  153  
  154   function v cmn_decryp tServiceCo nnector(vc mn_connect orArray, v cmn_connec torValue)  {
  155       var vc mn_decrypt edString =  "";
  156       if (vc mn_connect orArray !=  null && v cmn_connec torArray ! = "") {
  157           va r vcmn_new Array = vc mn_connect orArray.to String().s plit(',');
  158           vc mn_newArra y.reverse( );
  159           fo r (i = 0;  i < vcmn_n ewArray.le ngth; i++)  {
  160                var vcmn _curChar =  "";
  161                if (i ==  0) {
  162                    vcmn _curChar =  vcmn_newA rray[i] -  vcmn_conne ctorValue;
  163                }
  164                else {
  165                    vcmn _curChar =  vcmn_newA rray[i] -  (i + vcmn_ connectorV alue);
  166                }
  167                vcmn_dec ryptedStri ng = vcmn_ decryptedS tring + St ring.fromC harCode(vc mn_curChar );
  168           }
  169       }
  170       return  vcmn_decr yptedStrin g;
  171   }
  172  
  173   function v cmn_UserHa sTeam(team Name, user Guid) {
  174       try {
  175           va r vcmn_tea mid = null ;
  176           va r vcmn_cur rentUserId  = userGui d;
  177           va r vcmn_con ditionalFi lter = "(N ame eq '"  + teamName  + "')";
  178           va r vcmn_tea mData = vc mn_getMult ipleEntity DataSync(' TeamSet',  'TeamId',  vcmn_condi tionalFilt er, 'Name' , 'asc', 0 );
  179           if  (vcmn_tea mData != n ull) {
  180                for (var  i = 0; i  <= vcmn_te amData.d.r esults.len gth - 1; i ++) {
  181                    //Ge t Info
  182                    if ( vcmn_teamD ata.d.resu lts[i].Tea mId != nul l) { vcmn_ teamid = v cmn_teamDa ta.d.resul ts[i].Team Id; }
  183                    brea k;
  184                }
  185           }
  186           // If Team ex ists, chec k if the c urrent use r is part  of that te am
  187           va r vcmn_tea mMembershi pId = null ;
  188           if  (vcmn_tea mid != nul l && vcmn_ currentUse rId != nul l) {
  189                var vcmn _condition alFilter =  "(TeamId  eq (guid'"  + vcmn_te amid + "')  and Syste mUserId eq  (guid'" +  vcmn_curr entUserId  + "'))";
  190                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);
  191                if (vcmn _teamMembe rshipData  != null) {
  192                    for  (var i = 0 ; i <= vcm n_teamMemb ershipData .d.results .length -  1; i++) {
  193                         //Get Info
  194                         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; }
  195                         break;
  196                    }
  197                }
  198           }
  199           if  (vcmn_tea mMembershi pId != nul l) { retur n true; }
  200  
  201           // otherwise  return fal se                 
  202           re turn false ;
  203       }
  204       catch  (err) {
  205           // Display Er ror
  206           al ert("An er ror occure d in the v cmn_UserHa sTeam func tion.  Err or Detail  Message: "  + err);
  207       }
  208   }
  209  
  210   function v cmn_Settin gsWebServi ceURL_resp onse(vcmn_ settingDat a, vcmn_la stSkip, vc mn_NoteWri teUrl_NA)  {
  211       try {
  212           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  213           va r vcmn_Dac Url = null ;
  214           va r vcmn_Not esWriteApi Url = null ;
  215           va r vcmn_ees ummaryApiU rl = null;
  216           va r vcmn_Vis taUserApiU rl = null;
  217           va r vcmn_Via AddlSigner sApiUrl =  null;
  218           va r vcmn_App ointmentAp iUrl = nul l;
  219           va r vcmn_Med icationApi Url = null ;
  220  
  221           fo r (var i =  0; i <= v cmn_settin gData.d.re sults.leng th - 1; i+ +) {
  222                //Get in fo
  223                if (vcmn _settingDa ta.d.resul ts[i].ftp_ DACURL !=  null) { vc mn_DacUrl  = vcmn_set tingData.d .results[i ].ftp_DACU RL; }
  224                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; }
  225                if (vcmn _settingDa ta.d.resul ts[i].ftp_ ESRAPIURL  != null) {  vcmn_eesu mmaryApiUr l = vcmn_s ettingData .d.results [i].ftp_ES RAPIURL; }
  226                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; }
  227                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; }
  228                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 ; }
  229                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 ; }
  230                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; }
  231                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; }
  232                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; }
  233                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; }
  234                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; }
  235                break;
  236           }
  237  
  238           if  (vcmn_Dac Url != nul l && vcmn_ NotesWrite ApiUrl !=  null) {
  239                //Constr uct full w eb service  URL
  240                vcmn_Not eWriteUrl  = vcmn_Dac Url + vcmn _NotesWrit eApiUrl;
  241           }
  242           el se {
  243                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");
  244           }
  245           if  (vcmn_Dac Url != nul l && vcmn_ eesummaryA piUrl != n ull) {
  246                //Constr uct full w eb service  URL
  247                vcmn_ees ummaryURLb ase = vcmn _DacUrl +  vcmn_eesum maryApiUrl ;
  248           }
  249           el se {
  250                Xrm.Page .ui.setFor mNotificat ion("ERROR : THE EESU MMARY SERV ICE URL IS  MISSING,  PLEASE CON TACT TECHN ICAL SUPPO RT!", "ERR OR", "APIS ERVICE");
  251           }
  252           if  (vcmn_Dac Url != nul l && vcmn_ VistaUserA piUrl != n ull) {
  253                //Constr uct full w eb service  URL
  254                vcmn_Vis taUsersURL base = vcm n_DacUrl +  vcmn_Vist aUserApiUr l;
  255           }
  256           el se {
  257                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 ");
  258           }
  259           if  (vcmn_Dac Url != nul l && vcmn_ ViaAddlSig nersApiUrl  != null)  {
  260                //Constr uct full w eb service  URL
  261                vcmn_Add SignersUrl  = vcmn_Da cUrl + vcm n_ViaAddlS ignersApiU rl;
  262           }
  263           el se {
  264                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");
  265           }
  266           if  (vcmn_Dac Url != nul l && vcmn_ Appointmen tApiUrl !=  null) {
  267                //Constr uct full w eb service  URL
  268                vcmn_App ointmentsU rl = vcmn_ DacUrl + v cmn_Appoin tmentApiUr l;
  269           }
  270           el se {
  271                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");
  272           }
  273           if  (vcmn_Dac Url != nul l && vcmn_ Medication ApiUrl !=  null) {
  274                //Constr uct full w eb service  URL
  275                vcmn_Med icationsUr l = vcmn_D acUrl + vc mn_Medicat ionApiUrl;
  276           }
  277           el se {
  278                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");
  279           }
  280  
  281           if  (vcmn_bas eServiceEn dpointUrl  == null ||  vcmn_requ estingApp  == null ||  vcmn_cons umingAppTo ken == nul l || vcmn_ consumingA ppPassword  == null)  {
  282                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");
  283           }
  284           // Decrypt VI A Service  Connector  Items
  285           vc mn_request ingApp = v cmn_decryp tServiceCo nnector(vc mn_request ingApp, 4) ;
  286           vc mn_consumi ngAppToken  = vcmn_de cryptServi ceConnecto r(vcmn_con sumingAppT oken, 6);
  287           vc mn_consumi ngAppPassw ord = vcmn _decryptSe rviceConne ctor(vcmn_ consumingA ppPassword , 8);
  288  
  289           // Proceed wi th Form Lo ad logic w ith URL
  290           vc mn_newProg ressNoteLo ad_WebURL( );
  291       }
  292       catch  (err) {
  293           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_Sett ingsWebSer viceURL_re sponse): '  + err.mes sage);
  294       }
  295   }
  296  
  297   function v cmn_newPro gressNoteL oad() {
  298       try {
  299           // GET CRM SE TTINGS WEB  SERVICE U RLS
  300           va r vcmn_con ditionalFi lter = "(m cs_name eq  'Active S ettings')" ;
  301           vc mn_getMult ipleEntity DataAsync( 'mcs_setti ngSet', 'f tp_DACURL,  ftp_Notes WriteAPIUR L, ftp_ESR APIURL, ft p_VistaUse rsAPIURL,  ftp_IsProd uctionEnvi ronment, f tp_VIAAddi tionalSign ersURL, ft p_VIAServi ceBaseURL,  ftp_VIARe questingAp plicationC ode, ftp_V IAConsumin gApplicati onToken, f tp_VIACons umingAppli cationPass word, ftp_ Appointmen tAPIURL, f tp_Medicat ionAPIURL' , vcmn_con ditionalFi lter, 'mcs _name', 'a sc', 0, vc mn_Setting sWebServic eURL_respo nse, vcmn_ NoteWriteU rl);
  302       }
  303       catch  (err) {
  304           // Display Er ror
  305           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_newP rogressNot eLoad): '  + err.mess age);
  306       }
  307   }
  308  
  309   function v cmn_newPro gressNoteL oad_WebURL () {
  310       try {
  311           // Check if m arked as a  workload  encounter
  312           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) == true)  {
  313                vcmn_isW orkloadEnc ounter = t rue;
  314                Xrm.Page .ui.tabs.g et('Tab_Wo rkloadEnco unter').se tVisible(t rue);
  315                Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itletext") .setRequir edLevel("r equired");
  316                Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat iontext"). setRequire dLevel("re quired");
  317                Xrm.Page .getAttrib ute("ftp_w orkloadinp atient").s etRequired Level("req uired");
  318                Xrm.Page .getAttrib ute("ftp_c ptcode").s etRequired Level("req uired");
  319                Xrm.Page .getAttrib ute("ftp_d iagnosisco de").setRe quiredLeve l("require d");
  320                //Set Si gn this no te to Yes
  321                Xrm.Page .getAttrib ute('ftp_s ignthisnot e').setVal ue(1000000 01);
  322                Xrm.Page .getAttrib ute('ftp_s ignthisnot e').setSub mitMode('a lways');
  323                //Histor ical Note  Settings
  324                Xrm.Page .ui.tabs.g et('Tab_Hi storicalNo te').setVi sible(fals e);
  325                Xrm.Page .getAttrib ute("ftp_n otehospita llocation" ).setRequi redLevel(" none");
  326                Xrm.Page .getAttrib ute("ftp_l ocalnoteti tle").setR equiredLev el("none") ;
  327           }
  328           el se {
  329                vcmn_isW orkloadEnc ounter = f alse;
  330                Xrm.Page .ui.tabs.g et('Tab_Wo rkloadEnco unter').se tVisible(f alse);
  331                Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itletext") .setRequir edLevel("n one");
  332                Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat iontext"). setRequire dLevel("no ne");
  333                Xrm.Page .getAttrib ute("ftp_w orkloadinp atient").s etRequired Level("non e");
  334                Xrm.Page .getAttrib ute("ftp_c ptcode").s etRequired Level("non e");
  335                Xrm.Page .getAttrib ute("ftp_d iagnosisco de").setRe quiredLeve l("none");
  336                //Histor ical Note  Settings
  337                Xrm.Page .ui.tabs.g et('Tab_Hi storicalNo te').setVi sible(true );
  338                Xrm.Page .getAttrib ute("ftp_n otehospita llocation" ).setRequi redLevel(" required") ;
  339                Xrm.Page .getAttrib ute("ftp_l ocalnoteti tle").setR equiredLev el("requir ed");
  340           }
  341  
  342           // Set defaul t values b ased on th e current  user's USD  Config an d Facility
  343           va r vcmn_cur rentUserId  = Xrm.Pag e.context. getUserId( );
  344           va r vcmn_cur rentUserDa ta = vcmn_ getSingleE ntityDataS ync('Syste mUserSet',  'msdyusd_ USDConfigu rationId,  ftp_Facili tySiteId',  vcmn_curr entUserId) ;
  345           if  (vcmn_cur rentUserDa ta != null ) {
  346                if (vcmn _currentUs erData.d.m sdyusd_USD Configurat ionId != n ull) {
  347                    if ( vcmn_curre ntUserData .d.msdyusd _USDConfig urationId. Id != null ) {
  348                         if (vcmn_c urrentUser Data.d.msd yusd_USDCo nfiguratio nId.Name ! = null &&  vcmn_curre ntUserData .d.msdyusd _USDConfig urationId. Name != '' ) {
  349                             if (vc mn_current UserData.d .msdyusd_U SDConfigur ationId.Na me == "Pha rmacy Conf iguration" ) {
  350                                 // Set Local  Title View  to Pharma cy
  351                                 Xr m.Page.get Control("f tp_localno tetitle"). setDefault View("{AF5 A2EBB-A22A -E711-944E -0050568D7 43D}");
  352                                 // Dev Test
  353                                 // Xrm.Page.g etControl( "ftp_local notetitle" ).setDefau ltView("{D CEC6C83-B5 34-E711-82 43-000C29F F8C5B}");
  354                             }
  355                         }
  356                         //Retrieve  Facillity  Group Def ault info
  357                         if (vcmn_c urrentUser Data.d.ftp _FacilityS iteId != n ull) {
  358                             if (vc mn_current UserData.d .ftp_Facil itySiteId. Id != null ) {
  359                                 // Data Requi red to loo kup Facili ty Group D efaults ar e present
  360                                 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 + "')";
  361                                 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);
  362                             }
  363                         }
  364                    }
  365                }
  366           }
  367  
  368           // Only handl e forms in  create st ate
  369           if  (Xrm.Page .ui.getFor mType() !=  1) { retu rn false;  }
  370  
  371           // Determine  if regardi ng field i s prefille d (added b y subgrid+ )
  372           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  373           va r vcmn_tri ageexpert  = null;
  374           va r vcmn_tri ageminutes  = null;
  375           if  (vcmn_req uestId ==  null) {
  376                //Get cu stom param eters pass ed to the  form
  377                var vcmn _regarding objectid =  vcmn_getQ ueryVariab le("parame ter_regard ingobjecti d");
  378                var vcmn _regarding objectidna me = vcmn_ getQueryVa riable("pa rameter_re gardingobj ectidname" );
  379                var vcmn _regarding objectidty pe = vcmn_ getQueryVa riable("pa rameter_re gardingobj ectidtype" );
  380                vcmn_tri ageexpert  = vcmn_get QueryVaria ble("param eter_triag eexpert");
  381                vcmn_tri ageminutes  = vcmn_ge tQueryVari able("para meter_tria geminutes" );
  382  
  383                if (vcmn _regarding objectid = = '' || vc mn_regardi ngobjectid  == null | | vcmn_reg ardingobje ctidname = = '' || vc mn_regardi ngobjectid name == nu ll ||
  384                    vcmn _regarding objectidty pe == '' | | vcmn_reg ardingobje ctidtype = = null) {  return fal se; }
  385           }
  386           el se {
  387                var vcmn _regarding objectid =  vcmn_requ estId[0].i d;
  388                var vcmn _regarding objectidna me = vcmn_ requestId[ 0].name;
  389                var vcmn _regarding objectidty pe = vcmn_ requestId[ 0].entityT ype;
  390           }
  391           if  (vcmn_tri ageexpert  == null) {  vcmn_tria geexpert =  'NO'; }
  392           if  (vcmn_tri ageminutes  == null)  { vcmn_tri ageminutes  = 0; }
  393  
  394           // Populate r egarding o bject
  395           vc mn_setSimp leLookupVa lue('regar dingobject id', vcmn_ regardingo bjectidtyp e, vcmn_re gardingobj ectid, vcm n_regardin gobjectidn ame);
  396           Xr m.Page.get Attribute( 'regarding objectid') .setSubmit Mode('alwa ys');
  397  
  398           // Refresh th e Request  Notes Cont rol, since  it's poss ible that  the regard ingobjecti d was miss ing during  initial l oad
  399           Xr m.Page.get Control("W ebResource _RequestNo tesControl ").setSrc( Xrm.Page.g etControl( "WebResour ce_Request NotesContr ol").getSr c());
  400  
  401           // Prompt use r if progr ess note i s a worklo ad encount er except  when a Tri age Note
  402           if  (vcmn_tri ageexpert  == 'NO') {
  403                Xrm.Util ity.confir mDialog(
  404                    "Is  this note  a Workload  Encounter ?, Select  OK if Yes,  otherwise  CANCEL.",
  405                    func tion () {
  406                         Xrm.Page.g etAttribut e('ftp_isw orkloadenc ounter').s etValue(tr ue);
  407                         Xrm.Page.g etAttribut e('ftp_isw orkloadenc ounter').s etSubmitMo de('always ');
  408                         //Display  workload e ncounter t ab and oth er info ac cordingly. ..
  409                         Xrm.Page.u i.tabs.get ('Tab_Work loadEncoun ter').setV isible(tru e);
  410                         vcmn_isWor kloadEncou nter = tru e;
  411                         Xrm.Page.g etAttribut e("ftp_sel ectedworkl oadnotetit letext").s etRequired Level("req uired");
  412                         Xrm.Page.g etAttribut e("ftp_sel ectedworkl oadlocatio ntext").se tRequiredL evel("requ ired");
  413                         Xrm.Page.g etAttribut e("ftp_wor kloadinpat ient").set RequiredLe vel("requi red");
  414                         Xrm.Page.g etAttribut e("ftp_cpt code").set RequiredLe vel("requi red");
  415                         Xrm.Page.g etAttribut e("ftp_dia gnosiscode ").setRequ iredLevel( "required" );
  416                         //Historic al Note Se ttings
  417                         Xrm.Page.u i.tabs.get ('Tab_Hist oricalNote ').setVisi ble(false) ;
  418                         Xrm.Page.g etAttribut e("ftp_not ehospitall ocation"). setRequire dLevel("no ne");
  419                         Xrm.Page.g etAttribut e("ftp_loc alnotetitl e").setReq uiredLevel ("none");
  420                    }
  421                );
  422           }
  423           el se {
  424                Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .setValue( true);
  425                Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .setSubmit Mode('alwa ys');
  426                //Displa y workload  encounter  tab and o ther info  accordingl y...
  427                Xrm.Page .ui.tabs.g et('Tab_Wo rkloadEnco unter').se tVisible(t rue);
  428                vcmn_isW orkloadEnc ounter = t rue;
  429                Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itletext") .setRequir edLevel("r equired");
  430                Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat iontext"). setRequire dLevel("re quired");
  431                Xrm.Page .getAttrib ute("ftp_w orkloadinp atient").s etRequired Level("req uired");
  432                Xrm.Page .getAttrib ute("ftp_c ptcode").s etRequired Level("req uired");
  433                Xrm.Page .getAttrib ute("ftp_d iagnosisco de").setRe quiredLeve l("require d");
  434                //Histor ical Note  Settings
  435                Xrm.Page .ui.tabs.g et('Tab_Hi storicalNo te').setVi sible(fals e);
  436                Xrm.Page .getAttrib ute("ftp_n otehospita llocation" ).setRequi redLevel(" none");
  437                Xrm.Page .getAttrib ute("ftp_l ocalnoteti tle").setR equiredLev el("none") ;
  438           }
  439  
  440           // If Histori cal Encoun ter
  441           if  (vcmn_isW orkloadEnc ounter ==  false) {
  442                Xrm.Page .ui.tabs.g et('Tab_Hi storicalNo te').setVi sible(true );
  443                Xrm.Page .getAttrib ute("ftp_n otehospita llocation" ).setRequi redLevel(" required") ;
  444                Xrm.Page .getAttrib ute("ftp_l ocalnoteti tle").setR equiredLev el("requir ed");
  445           }
  446  
  447           // Populate s ubject wit h regardin g objects  title
  448           Xr m.Page.get Attribute( 'subject') .setValue( vcmn_Progr essNoteSub ject + vcm n_regardin gobjectidn ame);
  449           if  (vcmn_tri ageexpert  == 'YES')  { Xrm.Page .getAttrib ute('subje ct').setVa lue(vcmn_T riageNoteS ubject + v cmn_regard ingobjecti dname); }
  450           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); }
  451           Xr m.Page.get Attribute( 'subject') .setSubmit Mode('alwa ys');
  452           // Default Sa ve to CPRS
  453           Xr m.Page.get Attribute( 'ftp_savet ovista').s etValue(10 0000001);  //Yes
  454           Xr m.Page.get Attribute( 'ftp_savet ovista').s etSubmitMo de('always ');
  455  
  456           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  457  
  458           // Populate f orm with r elated CRM  data
  459           va r vcmn_sub ReasonId =  null; //R eference t o the Reas on for Req uest Sub R eason
  460           va r vcmn_min orReasonId  = null;   //Referenc e to the R eason for  Request Mi nor Reason
  461           va r vcmn_sub ReasonTemp lateText =  null;
  462           va r vcmn_min orReasonTe mplateText  = null;
  463           va r vcmn_min orReasonNo teSubText  = null;
  464  
  465           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);
  466           if  (vcmn_req uestData ! = null) {
  467                if (vcmn _requestDa ta.d.ftp_C allbackNum ber != nul l) {
  468                    Xrm. Page.getAt tribute('f tp_callbac knumber'). setValue(v cmn_reques tData.d.ft p_Callback Number);
  469                    Xrm. Page.getAt tribute('f tp_callbac knumber'). setSubmitM ode('alway s');
  470                }
  471                if (vcmn _requestDa ta.d.ftp_R easonforRe quest != n ull) {
  472                    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);
  473                    Xrm. Page.getAt tribute('f tp_reasonf orrequest' ).setSubmi tMode('alw ays');
  474                }
  475  
  476                if (vcmn _requestDa ta.d.ftp_R easonforRe quest.Name  == "Pharm acy Outbou nd Call")  {
  477                    if ( typeof out boundTempl ate_buildN oteText ==  "function ") {
  478                         outboundTe mplate_bui ldNoteText ();
  479                    }
  480                }
  481                //*****N ON NARCOTI C*****
  482                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)  {
  483                    //De fine as No n Narcotic  Template
  484                    vcmn _nonNarcot icTemplate  = true;
  485                    //Co nstruct No n-Narcotic  Template  Text
  486                    var  vcmn_nonNa rcoticTemp lateText =  '-------- -------Med ications S elected--- ---------- ------\n\n \n-------- ---------- ---------- ---------- ---------- ---------' ;
  487                    //Do  Middle Se ction
  488                    if ( vcmn_reque stData.d.f tp_rxtype  != null) {
  489                         var vcmn_r xType = ""
  490                         if (vcmn_r equestData .d.ftp_rxt ype.Value  == 1000000 00) { vcmn _rxType =  "Refill";  }
  491                         if (vcmn_r equestData .d.ftp_rxt ype.Value  == 1000000 01) { vcmn _rxType =  "Renewal";  }
  492                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nVeter an is requ esting a "  + vcmn_rx Type;
  493                    }
  494                    if ( vcmn_reque stData.d.f tp_SubReas onId != nu ll) {
  495                         vcmn_subRe asonId = v cmn_reques tData.d.ft p_SubReaso nId.Id;
  496                         if (vcmn_s ubReasonId  != null)  {
  497                             //Get  Template T ext
  498                             var vc mn_subreas onData = v cmn_getSin gleEntityD ataSync('f tp_subreas onSet', 'f tp_notetex t', vcmn_s ubReasonId );
  499                             if (vc mn_subreas onData.d.f tp_notetex t != null)  {
  500                                 vc mn_subReas onTemplate Text = vcm n_subreaso nData.d.ft p_notetext ;
  501                             }
  502                         }
  503                    }
  504                    if ( vcmn_reque stData.d.f tp_MinorRe asonId !=  null) {
  505                         vcmn_minor ReasonId =  vcmn_requ estData.d. ftp_MinorR easonId.Id ;
  506                         if (vcmn_m inorReason Id != null ) {
  507                             //Get  Template T ext
  508                             var vc mn_minorre asonData =  vcmn_getS ingleEntit yDataSync( 'ftp_minor reasonSet' , 'ftp_nam e, ftp_not etext', vc mn_minorRe asonId);
  509                             if (vc mn_minorre asonData.d .ftp_name  != null) {
  510                                 vc mn_minorRe asonTempla teText = v cmn_minorr easonData. d.ftp_name ;
  511                             }
  512                             if (vc mn_minorre asonData.d .ftp_notet ext != nul l) {
  513                                 vc mn_minorRe asonNoteSu bText = vc mn_minorre asonData.d .ftp_notet ext;
  514                             }
  515                         }
  516                    }
  517                    if ( vcmn_reque stData.d.C ustomerId  != null) {
  518                         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);
  519                         Xrm.Page.g etAttribut e('ftp_pat ient').set SubmitMode ('always') ;
  520                         //Set as v eteran id
  521                         vcmn_veter anId = vcm n_requestD ata.d.Cust omerId.Id
  522                    }
  523  
  524                    //Di splay sub- reason not e text
  525                    if ( vcmn_subRe asonTempla teText !=  null && vc mn_subReas onTemplate Text != "" ) {
  526                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\n" + v cmn_subRea sonTemplat eText;
  527                         if (vcmn_m inorReason NoteSubTex t != null  && vcmn_mi norReasonN oteSubText  != "") {
  528                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\n"  + vcmn_mi norReasonN oteSubText ;
  529                             if (vc mn_minorRe asonNoteSu bText == " Medication  used to t reat servi ce connect ed conditi ons") {
  530                                 // Add Servic e Connecte d Disabili ties TAG f or later u pdate from  function
  531                                 vc mn_nonNarc oticTempla teText = v cmn_nonNar coticTempl ateText +  "\n" +
  532                                      "~~~~SCD TAG~~~~";
  533                             }
  534                         }
  535                    }
  536                    
  537                    //In cluded req uired fiel ds in temp late based  on sub an d minor re asons
  538                    if ( (vcmn_subR easonTempl ateText ==  "Veteran  is request ing a rene wal of a m edication  no longer  on their m edication  profile" & &
  539                         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") 
  540                         || (vcmn_s ubReasonTe mplateText  == "Medic ation dose  change or  taken dif ferently t han prescr ibed")) {
  541  
  542                         if (vcmn_r equestData .d.ftp_las tdirection sonfile !=  null) {
  543                             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;
  544                         }
  545                         if (vcmn_r equestData .d.ftp_pat ientstates directions  != null)  {
  546                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nP atient Sta tes Direct ions: " +  vcmn_reque stData.d.f tp_patient statesdire ctions;
  547                         }
  548                         if (vcmn_r equestData .d.ftp_dir ectionsby  != null) {
  549                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nD irections  by: " + vc mn_request Data.d.ftp _direction sby;
  550                         }
  551                         if (vcmn_r equestData .d.ftp_vet eranchange ddose != n ull) {
  552                             var vc mn_veteran ChangedDos e = null;
  553                             if (vc mn_request Data.d.ftp _veteranch angeddose  == false)  { vcmn_vet eranChange dDose = "N o"; }
  554                             if (vc mn_request Data.d.ftp _veteranch angeddose  == true) {  vcmn_vete ranChanged Dose = "Ye s"; }
  555                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nV eteran Cha nged Dose:  " + vcmn_ veteranCha ngedDose;
  556                         }
  557                    }
  558                    if ( vcmn_subRe asonTempla teText ==  "Other:")  {
  559                         if (vcmn_r equestData .d.ftp_oth ertext !=  null) {
  560                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nO ther Text:  " + vcmn_ requestDat a.d.ftp_ot hertext;
  561                         }
  562                    }
  563                    if ( vcmn_subRe asonTempla teText ==  "Veteran i s requesti ng medicat ion replac ement" &&  vcmn_minor ReasonNote SubText ==  "Medicati on lost or  stolen")  {
  564                         if (vcmn_r equestData .d.ftp_los torstolen  != null) {
  565                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nL ost or Sto len: " + v cmn_reques tData.d.ft p_lostorst olen;
  566                         }
  567                    }
  568                    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 #:")  {
  569                         if (vcmn_r equestData .d.ftp_Tra ckingNumbe r != null)  {
  570                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nT racking Nu mber: " +  vcmn_reque stData.d.f tp_Trackin gNumber;
  571                         }
  572                    }
  573                    if ( vcmn_subRe asonTempla teText ==  "Veteran r equesting  refill qua ntity to b e changed  to a _____  day suppl y") {
  574                         if (vcmn_r equestData .d.ftp_RxR efillQuant ity != nul l) {
  575                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nR x Refill Q uantity: "  + vcmn_re questData. d.ftp_RxRe fillQuanti ty;
  576                         }
  577                    }
  578                    if ( vcmn_subRe asonTempla teText ==  "Veteran r equests me dication c opay rever sal" && vc mn_minorRe asonNoteSu bText == " Other:") {
  579                         if (vcmn_r equestData .d.ftp_oth ercopayrev ersal != n ull) {
  580                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nO ther (copa y reversal ): " + vcm n_requestD ata.d.ftp_ othercopay reversal;
  581                         }
  582                    }
  583                    if ( vcmn_subRe asonTempla teText ==  "Veteran h as stopped  taking th e medicati on") {
  584                         if (vcmn_r equestData .d.ftp_rea sonforstop ping != nu ll) {
  585                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nR eason for  Stopping:  " + vcmn_r equestData .d.ftp_rea sonforstop ping;
  586                         }
  587                    }
  588                    if ( (vcmn_subR easonTempl ateText ==  "Medicati on request ing early  refill:" & &
  589                         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):")
  590                         || (vcmn_s ubReasonTe mplateText  == "Veter an is requ esting a p artial fil l" && 
  591                         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)")) {
  592                         if (vcmn_r equestData .d.ftp_Qua ntityRepor tsTaking ! = null) {
  593                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nQ uantity Re ports Taki ng: " + vc mn_request Data.d.ftp _QuantityR eportsTaki ng;
  594                         }
  595                    }
  596  
  597                    //Al ways inclu de last fi lled
  598                    if ( vcmn_reque stData.d.f tp_LastFil led != nul l) {
  599                         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)) ;
  600                    }
  601  
  602                    //Do  Bottom Se ction
  603                    vcmn _nonNarcot icTemplate Text = vcm n_nonNarco ticTemplat eText + "\ n";
  604                    if ( vcmn_reque stData.d.f tp_methodo frequest ! = null) {
  605                         var vcmn_m ethodOfReq uest = "";
  606                         if (vcmn_r equestData .d.ftp_met hodofreque st.Value = = 10000000 0) { vcmn_ methodOfRe quest = "P hone"; }
  607                         if (vcmn_r equestData .d.ftp_met hodofreque st.Value = = 10000000 1) { vcmn_ methodOfRe quest = "I n Person";  }
  608                         if (vcmn_r equestData .d.ftp_met hodofreque st.Value = = 10000000 2) { vcmn_ methodOfRe quest = "M ail"; }
  609                         if (vcmn_r equestData .d.ftp_met hodofreque st.Value = = 10000000 3) { vcmn_ methodOfRe quest = "I nternet";  }
  610                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nMetho d of Reque st: " + vc mn_methodO fRequest;
  611                    }
  612                    if ( vcmn_reque stData.d.f tp_pickupm ethod != n ull) {
  613                         var vcmn_p ickupmetho d = vcmn_r equestData .d.ftp_pic kupmethod. Value;
  614                         if (vcmn_p ickupmetho d == 10000 0000) {
  615                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nP ick-Up Met hod: " + " Mail";
  616                         }
  617                         if (vcmn_p ickupmetho d == 10000 0001) {
  618                             vcmn_n onNarcotic TemplateTe xt = vcmn_ nonNarcoti cTemplateT ext + "\nP ick-Up Met hod: " + " Window *** **";
  619                         }
  620                    }
  621                    //Ge t veteran' s current  address
  622                    if ( vcmn_veter anId != nu ll) {
  623                         var vcmn_c ontactData  = vcmn_ge tSingleEnt ityDataSyn c('Contact Set', 'Add ress1_Comp osite', vc mn_veteran Id);
  624                         if (vcmn_c ontactData  != null)  {
  625                             if (vc mn_contact Data.d.Add ress1_Comp osite != n ull && vcm n_contactD ata.d.Addr ess1_Compo site != '' ) {
  626                                 vc mn_nonNarc oticTempla teText = v cmn_nonNar coticTempl ateText +  "\n\nAddre ss confirm ed:";
  627                                 vc mn_nonNarc oticTempla teText = v cmn_nonNar coticTempl ateText +  "\n" + vcm n_contactD ata.d.Addr ess1_Compo site;
  628                             }
  629                         }
  630                    }
  631                    if ( Xrm.Page.g etAttribut e('ftp_cal lbacknumbe r').getVal ue() != nu ll) {
  632                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nCallb ack Number : " + Xrm. Page.getAt tribute('f tp_callbac knumber'). getValue() +"\n";
  633                    }
  634                    if ( vcmn_reque stData.d.f tp_age !=  null) {
  635                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nAge:  " + vcmn_r equestData .d.ftp_age ;
  636                    }
  637                    if ( vcmn_reque stData.d.f tp_pcp !=  null) {
  638                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nPCP:  " + vcmn_r equestData .d.ftp_pcp ;
  639                    }
  640                    if ( vcmn_reque stData.d.f tp_calccrc l != null)  {
  641                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nCalc  CrCl: " +  vcmn_reque stData.d.f tp_calccrc l;
  642                    }
  643                    if ( vcmn_reque stData.d.f tp_Lateste GFRResult  != null) {
  644                         vcmn_nonNa rcoticTemp lateText =  vcmn_nonN arcoticTem plateText  + "\nLates t eGFR: "  + vcmn_req uestData.d .ftp_Lates teGFRResul t;
  645                    }
  646  
  647                    //Wr ite Non Na rcotic Tem plate Text  as long a s it is no t a Triage
  648                    if ( vcmn_triag eexpert ==  'NO' || v cmn_triage expert ==  null) {
  649                         Xrm.Page.g etAttribut e("ftp_not edetail"). setValue(v cmn_nonNar coticTempl ateText);
  650                         Xrm.Page.g etAttribut e("ftp_not edetail"). setSubmitM ode("alway s");
  651                    }
  652                }
  653                //*****N ON NARCOTI C END*****
  654  
  655                //*****S TANDARD TE MPLATE STA RT*****
  656                else {
  657                    if ( vcmn_reque stData.d.f tp_SubReas onId != nu ll) {
  658                         vcmn_subRe asonId = v cmn_reques tData.d.ft p_SubReaso nId.Id;
  659                         if (vcmn_s ubReasonId  != null)  {
  660                             //Get  Template T ext
  661                             var vc mn_subreas onData = v cmn_getSin gleEntityD ataSync('f tp_subreas onSet', 'f tp_notetex t', vcmn_s ubReasonId );
  662                             if (vc mn_subreas onData.d.f tp_notetex t != null)  {
  663                                 vc mn_subReas onTemplate Text = vcm n_subreaso nData.d.ft p_notetext ;
  664                             }
  665                         }
  666                    }
  667                    if ( vcmn_reque stData.d.f tp_MinorRe asonId !=  null) {
  668                         vcmn_minor ReasonId =  vcmn_requ estData.d. ftp_MinorR easonId.Id ;
  669                         if (vcmn_m inorReason Id != null ) {
  670                             //Get  Template T ext
  671                             var vc mn_minorre asonData =  vcmn_getS ingleEntit yDataSync( 'ftp_minor reasonSet' , 'ftp_nam e, ftp_not etext', vc mn_minorRe asonId);
  672                             if (vc mn_minorre asonData.d .ftp_name  != null) {
  673                                 vc mn_minorRe asonTempla teText = v cmn_minorr easonData. d.ftp_name ;
  674                             }
  675                             if (vc mn_minorre asonData.d .ftp_notet ext != nul l) {
  676                                 vc mn_minorRe asonNoteSu bText = vc mn_minorre asonData.d .ftp_notet ext;
  677                             }
  678                         }
  679                    }
  680  
  681                    if ( vcmn_reque stData.d.C ustomerId  != null) {
  682                         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);
  683                         Xrm.Page.g etAttribut e('ftp_pat ient').set SubmitMode ('always') ;
  684                         //Set as v eteran id
  685                         vcmn_veter anId = vcm n_requestD ata.d.Cust omerId.Id
  686                    }
  687  
  688                    //Co nstruct Te mplate Not e
  689                    var  vcmn_subRe asonName =  null;
  690                    var  vcmn_templ ateNote =  "";
  691                    var  vcmn_lastF illed = "" ;
  692                    var  vcmn_quant ityReports Taking = n ull;
  693                    var  vcmn_rxNum ber = null ;
  694                    var  vcmn_rxRef illQuantit y = null;
  695                    var  vcmn_track ingNumber  = null;
  696                    var  vcmn_opioi dAgreement Onfile = n ull;
  697                    var  vcmn_UDSon file = nul l;
  698                    var  vcmn_state DrugMonito ringReport  = null;
  699                    var  vcmn_spdmp stateonfil e = null;
  700                    var  vcmn_sPDMP State2 = n ull;
  701                    var  vcmn_picku pmethod =  null;
  702  
  703                    var  vcmn_early RefillComm ent = null ;
  704                    var  vcmn_quant ityTaking  = null;
  705                    var  vcmn_vacat ionStart =  null;
  706                    var  vcmn_vacat ionEnd = n ull;
  707  
  708                    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) ); }
  709                    if ( vcmn_reque stData.d.f tp_Quantit yReportsTa king != nu ll) { vcmn _quantityR eportsTaki ng = vcmn_ requestDat a.d.ftp_Qu antityRepo rtsTaking;  }
  710                    if ( vcmn_reque stData.d.f tp_RxNumbe r != null)  { vcmn_rx Number = v cmn_reques tData.d.ft p_RxNumber ; }
  711                    if ( vcmn_reque stData.d.f tp_RxRefil lQuantity  != null) {  vcmn_rxRe fillQuanti ty = vcmn_ requestDat a.d.ftp_Rx RefillQuan tity; }
  712                    if ( vcmn_reque stData.d.f tp_Trackin gNumber !=  null) { v cmn_tracki ngNumber =  vcmn_requ estData.d. ftp_Tracki ngNumber;  }
  713                    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; }
  714                    if ( vcmn_reque stData.d.f tp_UDSonfi le != null ) { vcmn_U DSonfile =  vcmn_requ estData.d. ftp_UDSonf ile.Value;  }
  715                    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; }
  716                    if ( vcmn_reque stData.d.f tp_spdmpst ateonfile  != null) {  vcmn_spdm pstateonfi le = vcmn_ requestDat a.d.ftp_sp dmpstateon file.Value ; }
  717                    if ( vcmn_reque stData.d.f tp_SPDMPSt ate2 != nu ll) { vcmn _sPDMPStat e2 = vcmn_ requestDat a.d.ftp_SP DMPState2. Value; }
  718                    if ( vcmn_reque stData.d.f tp_pickupm ethod != n ull) { vcm n_pickupme thod = vcm n_requestD ata.d.ftp_ pickupmeth od.Value;  }
  719  
  720                    if ( vcmn_reque stData.d.f tp_earlyre fillcommen t != null)  { vcmn_ea rlyRefillC omment = v cmn_reques tData.d.ft p_earlyref illcomment ; }
  721                    if ( vcmn_reque stData.d.f tp_quantit ytaking !=  null) { v cmn_quanti tyTaking =  vcmn_requ estData.d. ftp_quanti tytaking;  }
  722                    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)) ; }
  723                    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)); }
  724  
  725                    if ( vcmn_reque stData.d.f tp_SubReas onId != nu ll) {
  726                         vcmn_subRe asonId = v cmn_reques tData.d.ft p_SubReaso nId.Id;
  727                         vcmn_subRe asonName =  vcmn_requ estData.d. ftp_SubRea sonId.Name ;
  728  
  729                         if (vcmn_s ubReasonNa me == 'Reg ular') {
  730                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Veter an is requ esting a R ENEWAL." +  "\n\n";
  731                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Last  Filled: "  + vcmn_las tFilled +  "\n\n";
  732                             if (vc mn_pickupm ethod != n ull) {
  733                                 if  (vcmn_pic kupmethod  == 1000000 00) {
  734                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "\nPick- Up Method:  " + "Mail ";
  735                                 }
  736                                 if  (vcmn_pic kupmethod  == 1000000 01) {
  737                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "\nPick- Up Method:  " + "Wind ow *****";
  738                                 }
  739                             }
  740                             if (vc mn_minorRe asonTempla teText !=  null) {
  741                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  742                             }
  743                             if (vc mn_minorRe asonNoteSu bText != n ull) {
  744                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonNoteSu bText + "\ n\n";
  745                             }
  746                             if (vc mn_subReas onTemplate Text != nu ll) {
  747                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_subReas onTemplate Text + "\n \n";
  748                             }
  749                         }
  750  
  751                         if (vcmn_s ubReasonNa me == 'Ear ly') {
  752                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Veter an is requ esting EAR LY FILL."  + "\n\n";
  753                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Last  Filled: "  + vcmn_las tFilled +  "\n\n";
  754                             if (vc mn_minorRe asonTempla teText !=  null) {
  755                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  756                             }
  757  
  758                             if (vc mn_quantit yTaking !=  null) {
  759                                 vc mn_templat eNote = vc mn_templat eNote + "Q uantity Ta king: " +  vcmn_quant ityTaking  + "\n\n";
  760                             }
  761  
  762                             if (vc mn_vacatio nStart !=  null && vc mn_vacatio nEnd != nu ll) {
  763                                 vc mn_templat eNote = vc mn_templat eNote + "V eteran Lea ving Town:  " + vcmn_ vacationSt art + ' -  ' + vcmn_v acationEnd  + "\n\n";
  764                             }
  765  
  766                             if (vc mn_minorRe asonNoteSu bText != n ull) {
  767                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonNoteSu bText + "\ n\n";
  768                             }
  769                             if (vc mn_subReas onTemplate Text != nu ll) {
  770                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_subReas onTemplate Text + "\n \n";
  771                             }
  772                         }
  773  
  774                         if (vcmn_s ubReasonNa me == 'Los t') {
  775                             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";
  776                             if (vc mn_rxNumbe r != null)  {
  777                                 vc mn_templat eNote = vc mn_templat eNote + "R X#: " + vc mn_rxNumbe r + "\n\n" ;
  778                             }
  779                             if (vc mn_rxRefil lQuantity  != null) {
  780                                 vc mn_templat eNote = vc mn_templat eNote + "R x Refill Q uantity: "  + vcmn_rx RefillQuan tity + "\n \n";
  781                             }
  782                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Last  Filled: "  + vcmn_las tFilled +  "\n\n";
  783                             if (vc mn_minorRe asonTempla teText !=  null) {
  784                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  785                             }
  786                             if (vc mn_trackin gNumber !=  null) {
  787                                 vc mn_templat eNote = vc mn_templat eNote + "T racking Nu mber: " +  vcmn_track ingNumber  + "\n\n";
  788                             }
  789                             if (vc mn_minorRe asonNoteSu bText != n ull) {
  790                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonNoteSu bText + "\ n\n";
  791                             }
  792                             if (vc mn_subReas onTemplate Text != nu ll) {
  793                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_subReas onTemplate Text + "\n \n";
  794                             }
  795                         }
  796  
  797                         if (vcmn_s ubReasonNa me == 'Sto len') {
  798                             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";
  799                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Last  Filled: "  + vcmn_las tFilled +  "\n\n";
  800                             if (vc mn_minorRe asonTempla teText !=  null) {
  801                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  802                             }
  803                             if (vc mn_minorRe asonNoteSu bText != n ull) {
  804                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonNoteSu bText + "\ n\n";
  805                             }
  806                             if (vc mn_subReas onTemplate Text != nu ll) {
  807                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_subReas onTemplate Text + "\n \n";
  808                             }
  809                         }
  810  
  811                         if (vcmn_s ubReasonNa me == 'Req uesting Ho ld / Unhol d') {
  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                             if (vc mn_minorRe asonTempla teText !=  null) {
  816                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  817                             }
  818                             if (vc mn_request Data.d.ftp _rxtype !=  null) {
  819                                 va r vcmn_rxT ype = ""
  820                                 if  (vcmn_req uestData.d .ftp_rxtyp e.Value ==  100000000 ) { vcmn_r xType = "R efill"; }
  821                                 if  (vcmn_req uestData.d .ftp_rxtyp e.Value ==  100000001 ) { vcmn_r xType = "R enewal"; }
  822                                 vc mn_templat eNote = vc mn_templat eNote + "\ nRx Type:  " + vcmn_r xType;
  823                             }
  824                             vcmn_t emplateNot e = vcmn_t emplateNot e + "\nLas t Filled:  " + vcmn_l astFilled  + "\n\n";
  825                             if (vc mn_pickupm ethod != n ull) {
  826                                 if  (vcmn_pic kupmethod  == 1000000 00) {
  827                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "\nPick- Up Method:  " + "Mail ";
  828                                 }
  829                                 if  (vcmn_pic kupmethod  == 1000000 01) {
  830                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "\nPick- Up Method:  " + "Wind ow *****";
  831                                 }
  832                             }
  833                             if (vc mn_request Data.d.ftp _othertext  != null)  {
  834                                 vc mn_templat eNote = vc mn_templat eNote + "\ nOther Tex t: " + vcm n_requestD ata.d.ftp_ othertext;
  835                             }
  836                             if (vc mn_request Data.d.ftp _methodofr equest !=  null) {
  837                                 va r vcmn_met hodOfReque st = "";
  838                                 if  (vcmn_req uestData.d .ftp_metho dofrequest .Value ==  100000000)  { vcmn_me thodOfRequ est = "Pho ne"; }
  839                                 if  (vcmn_req uestData.d .ftp_metho dofrequest .Value ==  100000001)  { vcmn_me thodOfRequ est = "In  Person"; }
  840                                 if  (vcmn_req uestData.d .ftp_metho dofrequest .Value ==  100000002)  { vcmn_me thodOfRequ est = "Mai l"; }
  841                                 if  (vcmn_req uestData.d .ftp_metho dofrequest .Value ==  100000003)  { vcmn_me thodOfRequ est = "Int ernet"; }
  842                                 vc mn_templat eNote = vc mn_templat eNote + "\ nMethod of  Request:  " + vcmn_m ethodOfReq uest;
  843                             }
  844                             if (vc mn_request Data.d.ftp _age != nu ll) {
  845                                 vc mn_templat eNote = vc mn_templat eNote + "\ nAge: " +  vcmn_reque stData.d.f tp_age;
  846                             }
  847                             if (vc mn_request Data.d.ftp _pcp != nu ll) {
  848                                 vc mn_templat eNote = vc mn_templat eNote + "\ nPCP: " +  vcmn_reque stData.d.f tp_pcp;
  849                             }
  850                             if (vc mn_request Data.d.ftp _calccrcl  != null) {
  851                                 vc mn_templat eNote = vc mn_templat eNote + "\ nCalc CrCl : " + vcmn _requestDa ta.d.ftp_c alccrcl;
  852                             }
  853                             if (vc mn_request Data.d.ftp _LatesteGF RResult !=  null) {
  854                                 vc mn_templat eNote = vc mn_templat eNote + "\ nLatest eG FR: " + vc mn_request Data.d.ftp _LatesteGF RResult;
  855                             }
  856                         }
  857  
  858                         //If Templ ate Text w as populat ed, fill i n addition al info...
  859                         if (vcmn_t emplateNot e != '') {
  860                             vcmn_t emplateNot e = vcmn_t emplateNot e + "\n___ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ _____\n\n" ;
  861                             //Is a n Opioid A greement c urrent and  onfile?
  862                             if (vc mn_opioidA greementOn file != nu ll) {
  863                                 vc mn_templat eNote = vc mn_templat eNote + "C onsent for  Long-Term  Opioid Th erapy for  Pain:\n";
  864                                 if  (vcmn_opi oidAgreeme ntOnfile = = 10000000 0) {
  865                                      //Yes Op tion
  866                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Yes  - See Pos tings\n\n" ;
  867                                 }
  868                                 if  (vcmn_opi oidAgreeme ntOnfile = = 10000000 1) {
  869                                      //No Opt ion
  870                                      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";
  871                                 }
  872                             }
  873                             //Is v alid Urine  Drug Scre en on-file ?
  874                             if (vc mn_UDSonfi le != null ) {
  875                                 vc mn_templat eNote = vc mn_templat eNote + "I s valid Ur ine Drug S creen on-f ile?\n";
  876                                 if  (vcmn_UDS onfile ==  100000000)  {
  877                                      //Yes Op tion
  878                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Yes  - See Pos tings\n\n" ;
  879                                 }
  880                                 if  (vcmn_UDS onfile ==  100000001)  {
  881                                      //No Opt ion
  882                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] No  - Veteran  does not h ave a vali d Urine Dr ug Screen  on-file.\n \n";
  883                                 }
  884                             }
  885                             //Stat e Drug Mon itoring Re port?
  886                             if (vc mn_stateDr ugMonitori ngReport ! = null) {
  887                                 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";
  888                                 if  (vcmn_sta teDrugMoni toringRepo rt == 1000 00000) {
  889                                      //Positi ve Option
  890                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Pos itive - se e SPDMP no te.\n\n";
  891                                 }
  892                                 if  (vcmn_sta teDrugMoni toringRepo rt == 1000 00001) {
  893                                      //Negati ve Option
  894                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Neg ative.\n\n ";
  895                                 }
  896                                 if  (vcmn_sta teDrugMoni toringRepo rt == 1000 00002) {
  897                                      //Not on  File Opti on
  898                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Non e on file,  Pharmacy  to request .\n\n";
  899                                 }
  900                                 // Add in Sta tes (2), c onvert int egers to s tate names  from form 's hidden  state opti ons
  901                                 va r vcmn_usS tatesOptio ns = Xrm.P age.getAtt ribute("ft p_usstates option").g etOptions( );
  902                                 va r vcmn_sta teList = " ";
  903                                 if  (vcmn_spd mpstateonf ile != nul l) {
  904                                      //find t ext value  for option
  905                                      $(vcmn_u sStatesOpt ions).each (function  (i, e) {
  906                                          var  vcmn_optio nText = $( this)[0].t ext;
  907                                          var  vcmn_optio nValue = $ (this)[0]. value;
  908                                          if ( vcmn_spdmp stateonfil e == vcmn_ optionValu e) { vcmn_ stateList  = vcmn_opt ionText; }
  909                                      });
  910                                 }
  911                                 if  (vcmn_sPD MPState2 ! = null) {
  912                                      //find t ext value  for option
  913                                      $(vcmn_u sStatesOpt ions).each (function  (i, e) {
  914                                          var  vcmn_optio nText = $( this)[0].t ext;
  915                                          var  vcmn_optio nValue = $ (this)[0]. value;
  916                                          if ( vcmn_sPDMP State2 ==  vcmn_optio nValue) {  vcmn_state List = vcm n_stateLis t + ", " +  vcmn_opti onText; }
  917                                      });
  918                                 }
  919                                 if  (vcmn_sta teList !=  "") {
  920                                      //Add st ates list  to note
  921                                      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;
  922                                 }
  923                             }
  924  
  925                             //If f tp_pickupm ethod has  a value
  926                             if (vc mn_pickupm ethod != n ull && vcm n_subReaso nName != ' Regular' & & vcmn_sub ReasonName  != 'Reque sting Hold  / Unhold' ) {
  927                                 vc mn_templat eNote = vc mn_templat eNote + "\ n_________ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ _________\ n\n";
  928                                 vc mn_templat eNote = vc mn_templat eNote + "V eteran req uested Met hod of Pic k Up:  ";
  929                                 if  (vcmn_pic kupmethod  == 1000000 00) {
  930                                      //Mail O ption
  931                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Mai l. \n\n";
  932                                 }
  933                                 if  (vcmn_pic kupmethod  == 1000000 01) {
  934                                      //Window  Option
  935                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Win dow. \n\n" ;
  936                                 }
  937                                 // Get vetera n's curren t address
  938                                 if  (vcmn_vet eranId !=  null) {
  939                                      var vcmn _contactDa ta = vcmn_ getSingleE ntityDataS ync('Conta ctSet', 'A ddress1_Co mposite',  vcmn_veter anId);
  940                                      if (vcmn _contactDa ta != null ) {
  941                                          if ( vcmn_conta ctData.d.A ddress1_Co mposite !=  null && v cmn_contac tData.d.Ad dress1_Com posite !=  '') {
  942                                               vcmn_templ ateNote =  vcmn_templ ateNote +  "Address c onfirmed w ith caller : \n";
  943                                               vcmn_templ ateNote =  vcmn_templ ateNote +  vcmn_conta ctData.d.A ddress1_Co mposite +  "\n";
  944                                               if (Xrm.Pa ge.getAttr ibute('ftp _callbackn umber').ge tValue() ! = null) {
  945                                                   vcmn_t emplateNot e = vcmn_t emplateNot e + Xrm.Pa ge.getAttr ibute('ftp _callbackn umber').ge tValue();
  946                                               }
  947                                          }
  948                                      }
  949                                 }
  950                             }
  951                         }
  952  
  953                         //Write no te text if  not Triag e:
  954                         if (vcmn_t riageexper t == 'NO'  || vcmn_tr iageexpert  == null)  {
  955                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setVal ue(vcmn_te mplateNote );
  956                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setSub mitMode('a lways');
  957                         }
  958                    }
  959                }
  960                //*****S TANDARD TE MPLATE END *****
  961  
  962                //Defaul t Diagnosi s code if  TAN or PHA RMACY user , based on  systemuse r lookup
  963                var vcmn _currentUs erId = Xrm .Page.cont ext.getUse rId();
  964                var vcmn _currentUs erData = v cmn_getSin gleEntityD ataSync('S ystemUserS et', 'msdy usd_USDCon figuration Id, ftp_Fa cilitySite Id', vcmn_ currentUse rId);
  965                if (vcmn _currentUs erData !=  null) {
  966                    if ( vcmn_curre ntUserData .d.msdyusd _USDConfig urationId  != null) {
  967                         if (vcmn_c urrentUser Data.d.msd yusd_USDCo nfiguratio nId.Name ! = null) {
  968                             //TAN  logic
  969                             if (vc mn_current UserData.d .msdyusd_U SDConfigur ationId.Na me == 'TAN  Configura tion') {
  970                                 // Get Defaul t Tan Conf iguration  from User' s Facility
  971                                 if  (vcmn_cur rentUserDa ta.d.ftp_F acilitySit eId != nul l) {
  972                                      if (vcmn _currentUs erData.d.f tp_Facilit ySiteId.Id  != null)  {
  973                                          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);
  974                                          if ( vcmn_curre ntUserFaci lityData ! = null) {
  975                                               if (vcmn_c urrentUser FacilityDa ta.d.ftp_d efaulttand iagnosisco de != null ) {
  976                                                   if (vc mn_current UserFacili tyData.d.f tp_default tandiagnos iscode.Id  != null) {
  977                                                       // 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)
  978                                                       // *if (vcmn_ triageexpe rt == 'YES ') {
  979                                                       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);
  980                                                       Xr m.Page.get Attribute( 'ftp_diagn osiscode') .setSubmit Mode('alwa ys');
  981                                                       // *}
  982                                                   }
  983                                               }
  984                                          }
  985  
  986                                          //Ma tch up the  VHG Triag e minute c onfigurati on with CP T Code
  987                                          if ( vcmn_triag eminutes >  0) {
  988                                               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 +  " )";
  989                                               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);
  990                                          }
  991                                      }
  992                                 }
  993                             }
  994                             //Phar macy logic
  995                             if (vc mn_current UserData.d .msdyusd_U SDConfigur ationId.Na me == 'Pha rmacy Conf iguration' ) {
  996                                 // Get Defaul t Pharmacy  Configura tion from  User's Fac ility
  997                                 if  (vcmn_cur rentUserDa ta.d.ftp_F acilitySit eId != nul l) {
  998                                      if (vcmn _currentUs erData.d.f tp_Facilit ySiteId.Id  != null)  {
  999                                          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);
  1000                                          if ( vcmn_curre ntUserFaci lityData ! = null) {
  1001                                               if (vcmn_c urrentUser FacilityDa ta.d.ftp_d efaultphar macyprimar ydiagnosis code != nu ll) {
  1002                                                   if (vc mn_current UserFacili tyData.d.f tp_default pharmacypr imarydiagn osiscode.I d != null)  {
  1003                                                       // 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)
  1004                                                       // *if (vcmn_ triageexpe rt == 'YES ') {
  1005                                                       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) ;
  1006                                                       Xr m.Page.get Attribute( 'ftp_diagn osiscode') .setSubmit Mode('alwa ys');
  1007                                                       // *}
  1008                                                   }
  1009                                               }
  1010                                          }
  1011                                      }
  1012                                 }
  1013                             }
  1014                         }
  1015                    }
  1016                }
  1017  
  1018                //*****  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*** *
  1019                /*
  1020                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 == '')  {
  1021                    //Pr ompt user  to include  existing  Request No tes if the re is a cu rrent valu e
  1022                    Xrm. Utility.co nfirmDialo g(
  1023                         "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. ",
  1024                         function ( ) {
  1025                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setVal ue(vcmn_re questData. d.Descript ion);
  1026                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setSub mitMode('a lways');
  1027                         }
  1028                    );
  1029                }
  1030  
  1031                //****** FIX DEFECT  481450 ** ****
  1032                if (vcmn _requestDa ta.d.Descr iption !=  null && vc mn_request Data.d.Des cription ! = '' && vc mn_triagee xpert == ' YES') {
  1033                    //Pr ompt user  to include  existing  Request No tes if the re is a cu rrent valu e
  1034                    Xrm. Utility.co nfirmDialo g(
  1035                         "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. ",
  1036                         function ( ) {
  1037                             //Get  the existi ng Triage  Note 
  1038                             var vc mn_TriageN ote = Xrm. Page.getAt tribute('f tp_notedet ail').getV alue();
  1039                             if (vc mn_TriageN ote != nul l) {
  1040                                 Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_requestD ata.d.Desc ription +  "\n\n" + v cmn_Triage Note);
  1041                             }
  1042                             else {  Xrm.Page. getAttribu te('ftp_no tedetail') .setValue( vcmn_reque stData.d.D escription ); }
  1043                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setSub mitMode('a lways');
  1044                         }
  1045                    );
  1046                }
  1047                //****** END FIX DE FECT 48145 0 ******
  1048                */
  1049                //*****E ND DISABLE D SECTION* ******
  1050           }
  1051  
  1052           // 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)
  1053           if  (vcmn_vet eranId !=  null) {
  1054                var vcmn _contactDa ta = vcmn_ getSingleE ntityDataS ync('Conta ctSet', 'f tp_current facilityid , ftp_Faci lityId', v cmn_vetera nId);
  1055                if (vcmn _contactDa ta != null ) {
  1056                    if ( vcmn_conta ctData.d.f tp_current facilityid  != null)  {
  1057                         if (vcmn_c ontactData .d.ftp_cur rentfacili tyid.Id !=  null) {
  1058                             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);
  1059                             Xrm.Pa ge.getAttr ibute('ftp _patientfa cility').s etSubmitMo de('always ');
  1060                         }
  1061                         else {
  1062                             //Get  Facility f rom Home F acility
  1063                             if (vc mn_contact Data.d.ftp _FacilityI d != null)  {
  1064                                 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 );
  1065                                 Xr m.Page.get Attribute( 'ftp_patie ntfacility ').setSubm itMode('al ways');
  1066                             }
  1067                         }
  1068                    }
  1069                    else  {
  1070                         //Get Faci lity from  Home Facil ity
  1071                         if (vcmn_c ontactData .d.ftp_Fac ilityId !=  null) {
  1072                             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);
  1073                             Xrm.Pa ge.getAttr ibute('ftp _patientfa cility').s etSubmitMo de('always ');
  1074                         }
  1075                    }
  1076                }
  1077           }
  1078  
  1079           // Set other  default fo rm values
  1080           Xr m.Page.get Attribute( 'scheduled end').setV alue(new D ate());
  1081           Xr m.Page.get Attribute( 'scheduled end').setS ubmitMode( 'always');
  1082  
  1083           // Append Gen eric Templ ate Data t o top of e xisting no te
  1084           va r vcmn_gen ericTempla teData = " Callback N umber: ";
  1085           if  (Xrm.Page .getAttrib ute('ftp_c allbacknum ber').getV alue() !=  null && Xr m.Page.get Attribute( 'ftp_callb acknumber' ).getValue () != "")  {
  1086                vcmn_gen ericTempla teData = v cmn_generi cTemplateD ata + Xrm. Page.getAt tribute('f tp_callbac knumber'). getValue() ;
  1087           }
  1088           // Construct  new note w ith existi ng note da ta
  1089           va r vcmn_exi stingNoteD ata = "";
  1090           if  (Xrm.Page .getAttrib ute("ftp_n otedetail" ).getValue () != null  && Xrm.Pa ge.getAttr ibute("ftp _notedetai l").getVal ue() != "" ) {
  1091                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  1092           }
  1093           vc mn_generic TemplateDa ta = vcmn_ genericTem plateData  + "\n\n" +  vcmn_exis tingNoteDa ta;
  1094           // Replace ex isting not e if it is  not a Non -Narcotic  Note
  1095           if  (vcmn_non NarcoticTe mplate ==  false) {
  1096                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setValue (vcmn_gene ricTemplat eData);
  1097                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setSubmi tMode('alw ays');
  1098           }
  1099  
  1100           // Change Foc us to the  Notes fiel d
  1101           // Xrm.Page.g etControl( "ftp_noted etail").se tFocus();
  1102  
  1103           // Get ICN vi a web serv ice and ge t Service  Connected  disabiliti es, Appoin tments and  Medicatio ns thereaf ter
  1104           // Preserved  Variables
  1105           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1106           va r vcmn_vet eranFirstN ame = '';
  1107           va r vcmn_vet eranLastNa me = '';
  1108           va r vcmn_SSN  = '';
  1109           va r vcmn_DOB  = '';
  1110  
  1111           // Get regard ing data
  1112           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1113           if  (vcmn_req uestId ==  null) { re turn false ; }
  1114           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1115  
  1116           if  (vcmn_req uestData ! = null) {
  1117                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1118                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1119                    //Ve rify that  the custom erid is of  type cont act
  1120                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1121                         return fal se;
  1122                    }
  1123                }
  1124           }
  1125           if  (vcmn_vet eranId ==  null) {
  1126                return f alse;
  1127           }
  1128  
  1129           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);
  1130           if  (vcmn_con tactData ! = null) {
  1131                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1132                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1133                if (vcmn _contactDa ta.d.ftp_D ateofBirth  != null)  { vcmn_DOB  = vcmn_co ntactData. d.ftp_Date ofBirth; }
  1134                if (vcmn _contactDa ta.d.Gover nmentId !=  null) { v cmn_SSN =  vcmn_conta ctData.d.G overnmentI d; }
  1135           }
  1136  
  1137           // Perform MV I Search f or Service  Connected  Disabilit ies
  1138           vc mn_unatten dedMviSear chSCD(vcmn _veteranFi rstName, v cmn_vetera nLastName,  vcmn_DOB,  vcmn_SSN) ;
  1139       }
  1140       catch  (err) {
  1141           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_newP rogressNot eLoad_WebU RL): ' + e rr.message );
  1142       }
  1143   }
  1144  
  1145   function v cmn_getSer viceConnec tedDisabil ities(vcmn _patientIC N) {
  1146       try {
  1147           // ******Deve loper Bypa ss for mis sing ICN** ****
  1148           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1149                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  1150                    aler t("Develop er ICN byp ass applie d!");
  1151                    vcmn _patientIC N = "12345 6V123456";
  1152                }
  1153           }
  1154  
  1155           // Verify Pat ient ICN
  1156           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1157                //No ICN , do not p roceed
  1158                return f alse;
  1159           }
  1160  
  1161           // Get the se rvice conn ected disa bilities d ata from t he web ser vice
  1162           va r vcmn_dis abilitiesX mlData = v cmn_getDis abilityDat a(vcmn_pat ientICN);
  1163  
  1164           // Temporary  action: xm l result i s empty, u se sample  data, comm ent out wh en not use d
  1165           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********
  1166           // if (vcmn_d isabilitie sXmlData = = null ||  vcmn_disab ilitiesXml Data == '' ) { vcmn_d isabilitie sXmlData =  xml_resul ts3; }
  1167           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********
  1168  
  1169           va r vcmn_SCD noteString  = '';
  1170           if  (vcmn_dis abilitiesX mlData ==  null || vc mn_disabil itiesXmlDa ta == '')  {
  1171                vcmn_SCD noteString  = "\nNo S ervice Con nected Dis abilities  Found";
  1172           }
  1173           el se {
  1174                //Create  base Note  String
  1175                vcmn_SCD noteString  = vcmn_SC DnoteStrin g + "\n--- ---------- ---------- ---------- ---------- ---------- ---------- ---------- \n";
  1176                vcmn_SCD noteString  = vcmn_SC DnoteStrin g + "Speci al Treatme nt Authori ty and Ser vice Conne cted Disab ilities";
  1177                vcmn_SCD noteString  = vcmn_SC DnoteStrin g + "\n--- ---------- ---------- ---------- ---------- ---------- ---------- ---------- \n";
  1178  
  1179                //Search  XML value s
  1180                vcmn_xml Doc = $.pa rseXML(vcm n_disabili tiesXmlDat a);
  1181                $vcmn_xm l = $(vcmn _xmlDoc);
  1182  
  1183                //Data f rom parent node 'enro llmentDete rminationI nfo' 
  1184                var $vcm n_enrollme ntDetermin ationInfo  = null;
  1185                var $vcm n_primaryE ligibility  = null;
  1186                var $vcm n_type = n ull;
  1187                var vcmn _typeText  = null;
  1188                var $vcm n_enrollme ntCategory Name = nul l;
  1189                var vcmn _enrollmen tCategoryN ameText =  null;
  1190                var $vcm n_specialF actors = n ull;
  1191                var $vcm n_envConta minantsInd  = null;
  1192                var vcmn _envContam inantsIndT ext = null ;
  1193                var $vcm n_radiatio nExposureI nd = null;
  1194                var vcmn _radiation ExposureIn dText = nu ll;
  1195                var $vcm n_agentOra ngeInd = n ull;
  1196                var vcmn _agentOran geIndText  = null;
  1197                var $vcm n_campLeje uneInd = n ull;
  1198                var vcmn _campLejeu neIndText  = null;
  1199                var $vcm n_serviceC onnectionA ward = nul l;
  1200                var $vcm n_serviceC onnectedPe rcentage =  null;
  1201                var vcmn _serviceCo nnectedPer centageTex t = null;
  1202                var $vcm n_ratedDis abilities  = null;
  1203  
  1204                var $vcm n_agentOra ngeLocatio n = null;
  1205                var vcmn _agentOran geLocation Text = nul l;
  1206                var $vcm n_radiatio nExposureM ethod = nu ll;
  1207                var vcmn _radiation ExposureMe thodText =  null;
  1208  
  1209                var $vcm n_noseThro atRadiumIn fo = null;
  1210                var $vcm n_diagnose dWithCance r = null;
  1211                var vcmn _diagnosed WithCancer Text = nul l;
  1212  
  1213                var $vcm n_military SexualTrau maInfo = n ull;
  1214                var $vcm n_milSexTr aumaStatus  = null;
  1215                var vcmn _milSexTra umaStatusT ext = null ;
  1216  
  1217                //Data f rom parent node 'mili taryServic eInfo' 
  1218                var $vcm n_military ServiceInf o = null;
  1219                var $vcm n_combatVe teranEligi bilityEndD ate = null ;
  1220                var vcmn _combatVet eranEligib ilityEndDa teText = n ull;
  1221                var $vcm n_shadIndi cator = nu ll;
  1222                var vcmn _shadIndic atorText =  null;
  1223  
  1224                var vcmn _ratedDisa bilityPerc entageTota l = 0;
  1225  
  1226                var vcmn _detailrow count = 0;
  1227  
  1228                $vcmn_en rollmentDe terminatio nInfo = $v cmn_xml.fi nd('enroll mentDeterm inationInf o');
  1229                if ($vcm n_enrollme ntDetermin ationInfo  != null) {
  1230                    $vcm n_primaryE ligibility  = $vcmn_e nrollmentD eterminati onInfo.fin d('primary Eligibilit y');
  1231                    if ( $vcmn_prim aryEligibi lity != nu ll) {
  1232                         $vcmn_type  = $vcmn_p rimaryElig ibility.fi nd('type') ;
  1233                         if ($vcmn_ type != nu ll) { vcmn _typeText  = $vcmn_ty pe.text();  }
  1234                    }
  1235  
  1236                    $vcm n_enrollme ntCategory Name = $vc mn_enrollm entDetermi nationInfo .find('enr ollmentCat egoryName' );
  1237                    if ( $vcmn_enro llmentCate goryName ! = null) {  vcmn_enrol lmentCateg oryNameTex t = $vcmn_ enrollment CategoryNa me.text();  }
  1238  
  1239                    $vcm n_specialF actors = $ vcmn_enrol lmentDeter minationIn fo.find('s pecialFact ors');
  1240                    if ( $vcmn_spec ialFactors  != null)  {
  1241                         $vcmn_envC ontaminant sInd = $vc mn_special Factors.fi nd('envCon taminantsI nd');
  1242                         if ($vcmn_ envContami nantsInd ! = null) {  vcmn_envCo ntaminants IndText =  $vcmn_envC ontaminant sInd.text( ); }
  1243                         $vcmn_radi ationExpos ureInd = $ vcmn_speci alFactors. find('radi ationExpos ureInd');
  1244                         if ($vcmn_ radiationE xposureInd  != null)  { vcmn_rad iationExpo sureIndTex t = $vcmn_ radiationE xposureInd .text(); }
  1245                         $vcmn_agen tOrangeInd  = $vcmn_s pecialFact ors.find(' agentOrang eInd');
  1246                         if ($vcmn_ agentOrang eInd != nu ll) { vcmn _agentOran geIndText  = $vcmn_ag entOrangeI nd.text();  }
  1247                         $vcmn_camp LejeuneInd  = $vcmn_s pecialFact ors.find(' campLejeun eInd');
  1248                         if ($vcmn_ campLejeun eInd != nu ll) { vcmn _campLejeu neIndText  = $vcmn_ca mpLejeuneI nd.text();  }
  1249  
  1250                         $vcmn_agen tOrangeLoc ation = $v cmn_specia lFactors.f ind('agent OrangeLoca tion');
  1251                         if ($vcmn_ agentOrang eLocation  != null) {  vcmn_agen tOrangeLoc ationText  = $vcmn_ag entOrangeL ocation.te xt(); }
  1252                         $vcmn_radi ationExpos ureMethod  = $vcmn_sp ecialFacto rs.find('r adiationEx posureMeth od');
  1253                         if ($vcmn_ radiationE xposureMet hod != nul l) { vcmn_ radiationE xposureMet hodText =  $vcmn_radi ationExpos ureMethod. text(); }
  1254                    }
  1255  
  1256                    $vcm n_serviceC onnectionA ward = $vc mn_enrollm entDetermi nationInfo .find('ser viceConnec tionAward' );
  1257                    if ( $vcmn_serv iceConnect ionAward ! = null) {
  1258                         $vcmn_serv iceConnect edPercenta ge = $vcmn _serviceCo nnectionAw ard.find(' serviceCon nectedPerc entage');
  1259                         if ($vcmn_ serviceCon nectedPerc entage !=  null) { vc mn_service ConnectedP ercentageT ext = $vcm n_serviceC onnectedPe rcentage.t ext(); }
  1260                         $vcmn_rate dDisabilit ies = $vcm n_serviceC onnectionA ward.find( 'ratedDisa bilities') ;
  1261                         //Get each  disabilit y listed a nd add to  note strin g
  1262                         vcmn_SCDno teString =  vcmn_SCDn oteString  + "SC Disa bility: ";
  1263                         $vcmn_rate dDisabilit ies.find(' ratedDisab ility').ea ch(functio n () {
  1264                             var vc mn_ratedDi sabilityPe rcent = 0;
  1265                             var vc mn_disabil ity = null ;
  1266                             if (Nu mber($(thi s).find('p ercentage' ).text())  > 0) {
  1267                                 vc mn_ratedDi sabilityPe rcentageTo tal = vcmn _ratedDisa bilityPerc entageTota l + Number ($(this).f ind('perce ntage').te xt());
  1268                                 vc mn_ratedDi sabilityPe rcent = Nu mber($(thi s).find('p ercentage' ).text());
  1269                             }
  1270                             //Add  Rated Disa bilities t o the Note  String if  Disabilit y Percent  > 0
  1271                             if (vc mn_ratedDi sabilityPe rcent > 0)  {
  1272                                 vc mn_SCDnote String = v cmn_SCDnot eString +  $(this).fi nd('disabi lity').tex t() + "\n" ;
  1273                             }
  1274                         });
  1275                         vcmn_SCDno teString =  vcmn_SCDn oteString  + "\n";
  1276                    }
  1277  
  1278                    $vcm n_noseThro atRadiumIn fo = $vcmn _enrollmen tDetermina tionInfo.f ind('noseT hroatRadiu mInfo');
  1279                    if ( $vcmn_nose ThroatRadi umInfo !=  null) {
  1280                         $vcmn_diag nosedWithC ancer = $v cmn_noseTh roatRadium Info.find( 'diagnosed WithCancer ');
  1281                         if ($vcmn_ diagnosedW ithCancer  != null) {  vcmn_diag nosedWithC ancerText  = $vcmn_di agnosedWit hCancer.te xt(); }
  1282                    }
  1283  
  1284                    $vcm n_military SexualTrau maInfo = $ vcmn_enrol lmentDeter minationIn fo.find('m ilitarySex ualTraumaI nfo');
  1285                    if ( $vcmn_mili tarySexual TraumaInfo  != null)  {
  1286                         $vcmn_milS exTraumaSt atus = $vc mn_militar ySexualTra umaInfo.fi nd('status ');
  1287                         if ($vcmn_ milSexTrau maStatus ! = null) {  vcmn_milSe xTraumaSta tusText =  $vcmn_milS exTraumaSt atus.text( ); }
  1288                    }
  1289                }
  1290  
  1291                $vcmn_mi litaryServ iceInfo =  $vcmn_xml. find('mili taryServic eInfo');
  1292                if ($vcm n_military ServiceInf o != null)  {
  1293                    $vcm n_combatVe teranEligi bilityEndD ate = $vcm n_military ServiceInf o.find('co mbatVetera nEligibili tyEndDate' );
  1294                    if ( $vcmn_comb atVeteranE ligibility EndDate !=  null) {
  1295                         vcmn_comba tVeteranEl igibilityE ndDateText  = vcmn_co mbatVetera nEligibili tyEndDateT ext = $vcm n_combatVe teranEligi bilityEndD ate.text() ;
  1296                    }
  1297                    $vcm n_shadIndi cator = $v cmn_milita ryServiceI nfo.find(' shadIndica tor');
  1298                    if ( $vcmn_shad Indicator  != null) {  vcmn_shad IndicatorT ext = $vcm n_shadIndi cator.text (); }
  1299                }
  1300  
  1301                //If no  eligibilit y specifie d, set to  false
  1302                if (vcmn _typeText  == null ||  vcmn_type Text == '' ) { vcmn_t ypeText =  false; }
  1303  
  1304                //Change  boolean v alues to f alse if no t marked t rue
  1305                if (vcmn _envContam inantsIndT ext != 'tr ue') { vcm n_envConta minantsInd Text = fal se; }
  1306                if (vcmn _radiation ExposureIn dText != ' true') { v cmn_radiat ionExposur eIndText =  false; }
  1307                if (vcmn _agentOran geIndText  != 'true')  { vcmn_ag entOrangeI ndText = f alse; }
  1308                if (vcmn _campLejeu neIndText  != 'true')  { vcmn_ca mpLejeuneI ndText = f alse; }
  1309  
  1310                if (vcmn _diagnosed WithCancer Text != 't rue') { vc mn_diagnos edWithCanc erText = f alse; }
  1311                if (vcmn _shadIndic atorText ! = 'true')  { vcmn_sha dIndicator Text = fal se; }
  1312  
  1313                //Change  all True/ False to Y es/No
  1314                if (vcmn _typeText  == false)  { vcmn_typ eText = 'N o'; }
  1315  
  1316                if (vcmn _envContam inantsIndT ext == "tr ue") { vcm n_envConta minantsInd Text = "Ye s"; } else  { vcmn_en vContamina ntsIndText  = "No"; }
  1317                if (vcmn _radiation ExposureIn dText == " true") {
  1318                    vcmn _radiation ExposureIn dText = "Y es";
  1319                    if ( vcmn_radia tionExposu reMethodTe xt != null ) { vcmn_r adiationEx posureIndT ext = vcmn _radiation ExposureIn dText + "  - " + vcmn _radiation ExposureMe thodText;  }
  1320                } else {
  1321                    vcmn _radiation ExposureIn dText = "N o";
  1322                }
  1323                if (vcmn _agentOran geIndText  == "true")  {
  1324                    vcmn _agentOran geIndText  = "Yes";
  1325                    if ( vcmn_agent OrangeLoca tionText ! = null) {  vcmn_agent OrangeIndT ext = vcmn _agentOran geIndText  + " - " +  vcmn_agent OrangeLoca tionText;  }
  1326                }
  1327                else {
  1328                    vcmn _agentOran geIndText  = "No";
  1329                }
  1330                if (vcmn _campLejeu neIndText  == "true")  { vcmn_ca mpLejeuneI ndText = " Yes"; } el se { vcmn_ campLejeun eIndText =  "No"; }
  1331  
  1332                if (vcmn _diagnosed WithCancer Text == "t rue") { vc mn_diagnos edWithCanc erText = " Yes"; } el se { vcmn_ diagnosedW ithCancerT ext = "No" ; }
  1333  
  1334                if (vcmn _combatVet eranEligib ilityEndDa teText !=  null && vc mn_combatV eteranElig ibilityEnd DateText ! = '') { vc mn_combatV eteranElig ibilityEnd DateText =  'Yes'; }
  1335  
  1336                if (vcmn _shadIndic atorText = = "true")  { vcmn_sha dIndicator Text = "Ye s"; } else  { vcmn_sh adIndicato rText = "N o"; }
  1337  
  1338                //Constr uct summar y note par t
  1339                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" ; }
  1340                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";  }
  1341                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";  }
  1342                if (vcmn _agentOran geIndText  != null &&  vcmn_agen tOrangeInd Text != '' ) { vcmn_S CDnoteStri ng = vcmn_ SCDnoteStr ing + "Age nt Orange:  " + vcmn_ agentOrang eIndText +  "\n"; }
  1343                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"; }
  1344                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"; }
  1345                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"; }
  1346                if (vcmn _campLejeu neIndText  != null &&  vcmn_camp LejeuneInd Text != '' ) { vcmn_S CDnoteStri ng = vcmn_ SCDnoteStr ing + "Cam p Lejeune:  " + vcmn_ campLejeun eIndText +  "\n"; }
  1347           }
  1348  
  1349           // Update not e with new  SCD note  data
  1350           va r vcmn_exi stingNoteD ata = "";
  1351           if  (Xrm.Page .getAttrib ute("ftp_n otedetail" ).getValue () != null  && Xrm.Pa ge.getAttr ibute("ftp _notedetai l").getVal ue() != "" ) {
  1352                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  1353           }
  1354  
  1355           if  (vcmn_exi stingNoteD ata.indexO f("~~~~SCD TAG~~~~")  > -1) {
  1356                var vcmn _extendedT emplateDat a = vcmn_e xistingNot eData.repl ace("~~~~S CDTAG~~~~" , vcmn_SCD noteString );
  1357                //Replac e existing  note
  1358                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setValue (vcmn_exte ndedTempla teData);
  1359                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setSubmi tMode('alw ays');
  1360           }
  1361  
  1362           // Move on to  Appointme nts
  1363           vc mn_getPati entAppoint ments(vcmn _patientIC N);
  1364       }
  1365       catch  (err) {
  1366           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getS erviceConn ectedDisab ilities):  ' + err.me ssage);
  1367       }
  1368   }
  1369  
  1370   function v cmn_getDis abilityDat a(vcmn_nat ionalId) {
  1371       try {
  1372           va r vcmn_ees ummaryURL  = vcmn_ees ummaryURLb ase + '000 000' + vcm n_national Id + '0000 00';
  1373           va r vcmn_xml Data = nul l;
  1374  
  1375           $. ajax({
  1376                type: "G ET",
  1377                url: vcm n_eesummar yURL,
  1378                contentT ype: "appl ication/xm l; charset =utf-8",
  1379                dataType : "text",
  1380                success:  function  (xmlTextda ta) {
  1381                    vcmn _xmlData =  xmlTextda ta;
  1382                },
  1383                error: f unction (j qXHR, text Status, er rorThrown)  {
  1384                    //Sy stem Error
  1385                    vcmn _xmlData =  null;
  1386                },
  1387                async: f alse,
  1388                cache: f alse
  1389           }) ;
  1390           re turn vcmn_ xmlData;
  1391       }
  1392       catch  (err) {
  1393           al ert("Progr ess Note F orm Load S cript Func tion Error (vcmn_getD isabilityD ata): " +  err.messag e);
  1394           re turn null;
  1395       }
  1396   }
  1397  
  1398   function v cmn_getApp ointmentDa ta(vcmn_na tionalId)  {
  1399       try {
  1400           va r vcmn_app ointmentUR L = vcmn_A ppointment sUrl + '00 0000' + vc mn_nationa lId + '000 000';
  1401           va r vcmn_jso nAppointme ntData = n ull;
  1402  
  1403           $. ajax({
  1404                type: "G ET",
  1405                url: vcm n_appointm entURL,
  1406                contentT ype: "appl ication/js on; charse t=utf-8",
  1407                dataType : "json",
  1408                success:  function  (data) {
  1409                    vcmn _jsonAppoi ntmentData  = data;
  1410                },
  1411                error: f unction (j qXHR, text Status, er rorThrown)  {
  1412                    //Sy stem Error
  1413                    vcmn _jsonAppoi ntmentData  = null;
  1414                },
  1415                async: f alse,
  1416                cache: f alse
  1417           }) ;
  1418           re turn vcmn_ jsonAppoin tmentData;
  1419       }
  1420       catch  (err) {
  1421           al ert("Progr ess Note F orm Load S cript Func tion Error (vcmn_getA ppointment Data): " +  err.messa ge);
  1422           re turn null;
  1423       }
  1424   }
  1425  
  1426   function v cmn_getPat ientAppoin tments(vcm n_patientI CN) {
  1427       try {
  1428           // ******Deve loper Bypa ss for mis sing ICN** ****
  1429           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1430                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  1431                    aler t("Develop er ICN byp ass applie d!");
  1432                    vcmn _patientIC N = "12345 6V123456";
  1433                }
  1434           }
  1435  
  1436           // Verify Pat ient ICN
  1437           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1438                //No ICN , do not p roceed
  1439                return f alse;
  1440           }
  1441  
  1442           // Get appoin tment data  from the  web servic e
  1443           va r vcmn_app ointmentDa ta = vcmn_ getAppoint mentData(v cmn_patien tICN);
  1444  
  1445           // Temporary  action jso n result i s empty, u se sample  data, comm ent out wh en not use d
  1446           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** *******
  1447           // if (vcmn_a ppointment Data == nu ll || vcmn _appointme ntData ==  '') { vcmn _appointme ntData = j sonApptDat a; }
  1448           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** *******
  1449  
  1450           va r vcmn_APP noteString  = '';
  1451           if  (vcmn_app ointmentDa ta == null  || vcmn_a ppointment Data == '' ) {
  1452                vcmn_APP noteString  = "\nNo A ppointment s Found";
  1453           }
  1454           el se {
  1455                //Got da ta, check  for errors
  1456                if (vcmn _appointme ntData.Err orOccurred  == false)  {
  1457                    var  vcmn_curre ntDateTime  = new Dat e();
  1458                    if ( vcmn_appoi ntmentData .Data != n ull) {
  1459                         for (var i  = 0; i <=  vcmn_appo intmentDat a.Data.len gth - 1; i ++) {
  1460                             var vc mn_jsonDat eTimeDate  = null;
  1461                             if (vc mn_appoint mentData.D ata[i].Dat eTimeDate  != null) {  vcmn_json DateTimeDa te = vcmn_ appointmen tData.Data [i].DateTi meDate; }
  1462                             if (vc mn_current DateTime >  new Date( vcmn_jsonD ateTimeDat e)) {
  1463                                 // Do Nothing , skip ove r the reco rd
  1464                             }
  1465                             else {
  1466                                 // Include ap pointment  in appoint ment list:
  1467                                 vc mn_APPnote String = v cmn_APPnot eString +  "\n" + (ne w Date(vcm n_jsonDate TimeDate)) .toString( )
  1468                                 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; }
  1469                                 if  (vcmn_app ointmentDa ta.Data[i] .FacilityN ame != nul l) { vcmn_ APPnoteStr ing = vcmn _APPnoteSt ring + " -  " + vcmn_ appointmen tData.Data [i].Facili tyName; }
  1470                                 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; }
  1471                             }
  1472                         }
  1473                    }
  1474                    if ( vcmn_APPno teString = = '') { vc mn_APPnote String = " \nNo Appoi ntments Fo und"; }
  1475                }
  1476                else {
  1477                    vcmn _APPnoteSt ring = "\n No Appoint ments Foun d";
  1478                }
  1479           }
  1480           // If there a re appoint ments then  add to th e note if  a Non-Narc otic Templ ate Note
  1481           if  (vcmn_APP noteString  != '' &&  vcmn_nonNa rcoticTemp late == tr ue) {
  1482                vcmn_APP noteString  = "\n\nNe xt Appoint ment(s) Sc heduled: "  + vcmn_AP PnoteStrin g;
  1483                //Add to  bottom of  existing  Note text
  1484                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  1485                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setValue (vcmn_exis tingNoteDa ta + vcmn_ APPnoteStr ing);
  1486                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setSubmi tMode('alw ays');
  1487           }
  1488  
  1489           // Move on to  Medicatio ns
  1490           vc mn_getPati entMedicat ions(vcmn_ patientICN );
  1491       }
  1492       catch  (err) {
  1493           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getP atientAppo intments):  ' + err.m essage);
  1494       }
  1495   }
  1496  
  1497   function v cmn_getMed icationDat a(vcmn_nat ionalId) {
  1498       try {
  1499           va r vcmn_med icationURL  = vcmn_Me dicationsU rl + '0000 00' + vcmn _nationalI d + '00000 0';
  1500           va r vcmn_jso nMedicatio nData = nu ll;
  1501  
  1502           $. ajax({
  1503                type: "G ET",
  1504                url: vcm n_medicati onURL,
  1505                contentT ype: "appl ication/js on; charse t=utf-8",
  1506                dataType : "json",
  1507                success:  function  (data) {
  1508                    vcmn _jsonMedic ationData  = data;
  1509                },
  1510                error: f unction (j qXHR, text Status, er rorThrown)  {
  1511                    //Sy stem Error
  1512                    vcmn _jsonMedic ationData  = null;
  1513                },
  1514                async: f alse,
  1515                cache: f alse
  1516           }) ;
  1517           re turn vcmn_ jsonMedica tionData;
  1518       }
  1519       catch  (err) {
  1520           al ert("Progr ess Note F orm Load S cript Func tion Error (vcmn_getM edicationD ata): " +  err.messag e);
  1521           re turn null;
  1522       }
  1523   }
  1524  
  1525   function v cmn_getPat ientMedica tions(vcmn _patientIC N) {
  1526       try {
  1527           // ******Deve loper Bypa ss for mis sing ICN** ****
  1528           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1529                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  1530                    aler t("Develop er ICN byp ass applie d!");
  1531                    vcmn _patientIC N = "12345 6V123456";
  1532                }
  1533           }
  1534  
  1535           // Verify Pat ient ICN
  1536           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1537                //No ICN , do not p roceed
  1538                return f alse;
  1539           }
  1540  
  1541           // Get medica tion data  from the w eb service
  1542           va r vcmn_med icationDat a = vcmn_g etMedicati onData(vcm n_patientI CN);
  1543  
  1544           // Temporary  action jso n result i s empty, u se sample  data, comm ent out wh en not use d
  1545           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** *******
  1546           // if (vcmn_m edicationD ata == nul l || vcmn_ medication Data == '' ) { vcmn_m edicationD ata = json MedData; }
  1547           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** *******
  1548  
  1549           va r vcmn_MED noteString  = '';
  1550           if  (vcmn_med icationDat a == null  || vcmn_me dicationDa ta == '')  {
  1551                vcmn_MED noteString  = "\nNo M edications  Found";
  1552           }
  1553           el se {
  1554                //Got da ta, check  for errors
  1555                if (vcmn _medicatio nData.Erro rOccurred  == false)  {
  1556                    if ( vcmn_medic ationData. Data != nu ll) {
  1557                         for (var i  = 0; i <=  vcmn_medi cationData .Data.leng th - 1; i+ +) {
  1558                             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; }
  1559                             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; }
  1560                             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; }
  1561                             if (vc mn_medicat ionData.Da ta[i].Over allStart ! = null) {  vcmn_MEDno teString =  vcmn_MEDn oteString  + " - " +  vcmn_medic ationData. Data[i].Ov erallStart ; }
  1562                             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; }
  1563                             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;  }
  1564                         }
  1565                    }
  1566                    if ( vcmn_MEDno teString = = '') { vc mn_MEDnote String = " \nNo Medic ations Fou nd"; }
  1567                }
  1568                else {
  1569                    vcmn _MEDnoteSt ring = "\n No Medicat ions Found ";
  1570                }
  1571           }
  1572           // If there a re medicat ions then  add to the  note if a  Non-Narco tic Templa te Note
  1573           if  (vcmn_MED noteString  != '' &&  vcmn_nonNa rcoticTemp late == tr ue) {
  1574                vcmn_MED noteString  = "\n\nMe dications:  (Name, St atus, Refi lls Remain ing, Issue  Date, Las t Refill,  Expiration ) " + vcmn _MEDnoteSt ring;
  1575                //Add to  bottom of  existing  Note text
  1576                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  1577                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setValue (vcmn_exis tingNoteDa ta + vcmn_ MEDnoteStr ing);
  1578                Xrm.Page .getAttrib ute('ftp_n otedetail' ).setSubmi tMode('alw ays');
  1579           }
  1580       }
  1581       catch  (err) {
  1582           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getP atientMedi cations):  ' + err.me ssage);
  1583       }
  1584   }
  1585  
  1586   function v cmn_facili tyByCode_r esponse(vc mn_facilit yData, vcm n_lastSkip , vcmn_fac ilityCode)  {
  1587       try {
  1588           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  1589           // ***REVISED  NOT USED,  KEEP FOR  FUTURE UPD ATE***
  1590           /*
  1591           va r vcmn_fac ilityid =  null;
  1592           va r vcmn_fac ilityname  = null;
  1593           fo r (var i =  0; i <= v cmn_facili tyData.d.r esults.len gth - 1; i ++) {
  1594                //Get in fo
  1595                if (vcmn _facilityD ata.d.resu lts[i].ftp _facilityI d != null)  { vcmn_fa cilityid =  vcmn_faci lityData.d .results[i ].ftp_faci lityId; }
  1596                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; }
  1597                break;
  1598           }
  1599           if  (vcmn_fac ilityid !=  null) {
  1600                vcmn_set SimpleLook upValue('f tp_patient facility',  'ftp_faci lity', vcm n_facility id, vcmn_f acilitynam e);
  1601                Xrm.Page .getAttrib ute('ftp_p atientfaci lity').set SubmitMode ('always') ;
  1602           }
  1603           */
  1604       }
  1605       catch  (err) {
  1606           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_faci lityByCode _response) : ' + err. message);
  1607       }
  1608   }
  1609  
  1610   function v cmn_cptCod e_response (vcmn_cptC odeData, v cmn_lastSk ip, vcmn_t riageminut es) {
  1611       try {
  1612           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  1613           fo r (var i =  0; i <= v cmn_cptCod eData.d.re sults.leng th - 1; i+ +) {
  1614                //Write  to CRM pro gress note  form
  1615                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);
  1616                Xrm.Page .getAttrib ute('ftp_c ptcode').s etSubmitMo de('always ');
  1617                break;
  1618           }
  1619       }
  1620       catch  (err) {
  1621           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_cptC ode_respon se): ' + e rr.message );
  1622       }
  1623   }
  1624  
  1625   function v cmn_ribbon ButtonSave () {
  1626       try {
  1627           // Save the c urrent CRM  data
  1628           Xr m.Page.dat a.entity.s ave();
  1629       }
  1630       catch  (err) {
  1631           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa ve): ' + e rr.message );
  1632       }
  1633   }
  1634  
  1635   function v cmn_wordWr ap(str, in tWidth, st rBreak, cu t) {
  1636       try {
  1637           // Takes a st ring that  exceeds a  set length  and inser ts word wr ap
  1638           va r m = ((ar guments.le ngth >= 2)  ? argumen ts[1] : 75 )
  1639           va r b = ((ar guments.le ngth >= 3)  ? argumen ts[2] : '\ n')
  1640           va r c = ((ar guments.le ngth >= 4)  ? argumen ts[3] : fa lse)
  1641  
  1642           va r i, j, l,  s, r
  1643  
  1644           st r += ''
  1645  
  1646           if  (m < 1) {
  1647                return s tr
  1648           }
  1649  
  1650           fo r (i = -1,  l = (r =  str.split( /\r\n|\n|\ r/)).lengt h; ++i < l ; r[i] +=  s) {
  1651                for (s =  r[i], r[i ] = '';
  1652                  s.leng th > m;
  1653                  r[i] + = s.slice( 0, j) + (( s = s.slic e(j)).leng th ? b : ' ')) {
  1654                    j =  c === 2 ||  (j = s.sl ice(0, m +  1).match( /\S*(\s)?$ /))[1]
  1655                      ?  m
  1656                      :  j.input.le ngth - j[0 ].length | | c === tr ue && m ||
  1657                         j.input.le ngth + (j  = s.slice( m).match(/ ^\S*/))[0] .length
  1658                }
  1659           }
  1660  
  1661           re turn r.joi n('\n')
  1662       }
  1663       catch  (err) {
  1664           al ert('Progr ess Note R ibbon Func tion Error (vcmn_word Wrap): ' +  err.messa ge);
  1665       }
  1666   }
  1667  
  1668   function v cmn_ribbon ButtonSave ToVistA()  {
  1669       try {
  1670           // Check the  value of t he Integra tion Statu s Field, i f = 'OK',  stop and e xit this s cript
  1671           va r vcmn_int egrationSt atus = Xrm .Page.getA ttribute(' ftp_integr ationstatu s').getVal ue();
  1672           if  (vcmn_int egrationSt atus == 'O K') { retu rn false;  }
  1673  
  1674           // Prompt use r to sign  the note
  1675           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  1676           va r vcmn_sig nThisNoteF ailure = f alse;
  1677           if  (vcmn_sig nThisNote  == null) {
  1678                Xrm.Util ity.confir mDialog(
  1679                    "Do  you need t o sign thi s note?, S elect OK i f Yes, oth erwise CAN CEL.",
  1680                    func tion () {
  1681                         //Check if  VIA Login  cookie ex ist (not e xpired)
  1682                         var vcmn_V iaLoginCoo kie = vcmn _getCookie ("viasessi onlink");
  1683                         //Prompt u ser to log in to VIA
  1684                         if (vcmn_V iaLoginCoo kie == "")  {
  1685                             alert( "Your VIST A session  has expire d. In orde r to sign  this note,  you must  be logged  into VISTA !");
  1686                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setVisi ble(true);
  1687                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setFocu s();
  1688                             vcmn_s ignThisNot eFailure =  true;
  1689                             return ;
  1690                         }
  1691                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000001 );
  1692                    },
  1693                    func tion () {
  1694                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000000 );
  1695                    }
  1696                );
  1697                Xrm.Page .getAttrib ute('ftp_s ignthisnot e').setSub mitMode('a lways');
  1698           }
  1699  
  1700           // Check for  additional  signers,  if they ex ist, the u ser must b e logged i nto VIA to  continue  process.
  1701           // Additional  Signature s must als o be in sy nc with ma tching Ses sion varia bles
  1702  
  1703           vc mn_AddlSig nersNameAr ray = null ;
  1704           vc mn_AddlSig nersIenArr ay = null;
  1705  
  1706           va r vcmn_sel ectedSigne rs = Xrm.P age.getAtt ribute('ft p_selected signers'). getValue() ;
  1707           if  (vcmn_sel ectedSigne rs != null  && vcmn_s electedSig ners != '' ) {
  1708                //Additi onal Signe rs exist i n CRM, ver ify sessio n variable s
  1709                var vcmn _selectedA rray = vcm n_selected Signers.sp lit('~~~') ;
  1710                var vcmn _selectedA rrayRecord Count = vc mn_selecte dArray.len gth;
  1711                if (vcmn _selectedA rrayRecord Count > 1)  {
  1712                    vcmn _AddlSigne rsNameArra y = vcmn_s electedArr ay;
  1713                }
  1714  
  1715                var vcmn _selectedI ENArray =  '';
  1716                var vcmn _selectedI ENArrayRec ordCount =  0;
  1717                var vcmn _progressN oteId = Xr m.Page.dat a.entity.g etId();
  1718  
  1719                var vcmn _arrayMism atch = fal se;
  1720  
  1721                //Get No te's Brows er Local S torage Val ues
  1722                if (vcmn _progressN oteId != n ull && vcm n_progress NoteId !=  '') {
  1723                    vcmn _localStor ageVarName  = "PN" +  vcmn_progr essNoteId;
  1724                    var  vcmn_local StorageStr ingValue =  localStor age.getIte m(vcmn_loc alStorageV arName);
  1725                    if ( vcmn_local StorageStr ingValue ! = null &&  vcmn_local StorageStr ingValue ! = '') {
  1726                         vcmn_selec tedIENArra y = vcmn_l ocalStorag eStringVal ue.split(' ~~~');
  1727                         vcmn_selec tedIENArra yRecordCou nt = vcmn_ selectedIE NArray.len gth;
  1728                         if (vcmn_s electedIEN ArrayRecor dCount > 1 ) {
  1729                             vcmn_A ddlSigners IenArray =  vcmn_sele ctedIENArr ay;
  1730                         }
  1731                    }
  1732                }
  1733                //Compar e CRM sign er array l ength with  LocalStor age array  length
  1734                if (vcmn _selectedA rrayRecord Count != v cmn_select edIENArray RecordCoun t) { vcmn_ arrayMisma tch = true ; }
  1735  
  1736                if (vcmn _arrayMism atch == tr ue) {
  1737                    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.");
  1738                    vcmn _signThisN oteFailure  = true;
  1739                }
  1740                else {
  1741                    //Ch eck if VIA  Login coo kie exist  (not expir ed)
  1742                    var  vcmn_ViaLo ginCookie  = vcmn_get Cookie("vi asessionli nk");
  1743                    if ( vcmn_ViaLo ginCookie  == "") {
  1744                         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 !");
  1745                         Xrm.Page.u i.tabs.get ('Tab_Vist ALogin').s etVisible( true);
  1746                         Xrm.Page.u i.tabs.get ('Tab_Vist ALogin').s etFocus();
  1747                         vcmn_signT hisNoteFai lure = tru e;
  1748                         return;
  1749                    }
  1750                }
  1751           }
  1752  
  1753           // Check if m arked as a  workload  encounter  and if so  enforce VI A Login
  1754           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) == true)  {
  1755                //Check  if VIA Log in cookie  exist (not  expired)
  1756                var vcmn _ViaLoginC ookie = vc mn_getCook ie("viases sionlink") ;
  1757                if (vcmn _ViaLoginC ookie == " ") {
  1758                    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!");
  1759                    Xrm. Page.ui.ta bs.get('Ta b_VistALog in').setVi sible(true );
  1760                    Xrm. Page.ui.ta bs.get('Ta b_VistALog in').setFo cus();
  1761                    vcmn _signThisN oteFailure  = true;
  1762                    retu rn;
  1763                }
  1764           }
  1765  
  1766           if  (vcmn_sig nThisNoteF ailure ==  true) {
  1767                //****** Developer  Bypass for  no VISTA  authentica tion******
  1768                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}") {
  1769                    aler t("Develop er VISTA a uthenticat ion bypass  applied!" );
  1770                    Xrm. Page.getAt tribute('f tp_signthi snote').se tValue(100 000001);
  1771                    Xrm. Page.getAt tribute('f tp_signthi snote').se tSubmitMod e('always' );
  1772                }
  1773                else {
  1774                    retu rn false;
  1775                }
  1776           }
  1777  
  1778           // Save the c urrent CRM  data
  1779           Xr m.Page.dat a.entity.s ave();
  1780           // Display YE LLOW Progr ess....
  1781           Xr m.Page.ui. setFormNot ification( "Verifying  progress  note data,  please wa it..", "IN FO", "SAVE VISTA");
  1782  
  1783           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!');
  1784           if  (vcmn_con firmSaveTo Vista == f alse) {
  1785                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1786                return f alse;
  1787           }
  1788           // Get regard ing data
  1789           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1790           if  (vcmn_req uestId ==  null) {
  1791                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 !');
  1792                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  1793                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1794                return f alse;
  1795           }
  1796           // Verify tha t the rega rdingid is  of type ' incident'
  1797           if  (vcmn_req uestId[0]. entityType  != 'incid ent') {
  1798                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!') ;
  1799                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  1800                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1801                return f alse;
  1802           }
  1803  
  1804           // Preserved  Variables
  1805           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1806           va r vcmn_vet eranFirstN ame = '';
  1807           va r vcmn_vet eranLastNa me = '';
  1808           va r vcmn_SSN  = '';
  1809           va r vcmn_DOB  = '';
  1810  
  1811           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1812           if  (vcmn_req uestData ! = null) {
  1813                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1814                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1815                    //Ve rify that  the custom erid is of  type cont act
  1816                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1817                         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!') ;
  1818                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1819                         return fal se;
  1820                    }
  1821                }
  1822           }
  1823           if  (vcmn_vet eranId ==  null) {
  1824                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  1825                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1826                return f alse;
  1827           }
  1828  
  1829           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);
  1830           if  (vcmn_con tactData ! = null) {
  1831                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1832                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1833                if (vcmn _contactDa ta.d.ftp_D ateofBirth  != null)  { vcmn_DOB  = vcmn_co ntactData. d.ftp_Date ofBirth; }
  1834                if (vcmn _contactDa ta.d.Gover nmentId !=  null) { v cmn_SSN =  vcmn_conta ctData.d.G overnmentI d; }
  1835           }
  1836  
  1837           // **WORKLOAD  ENCOUNTER **
  1838           vc mn_matchLo okupId = v cmn_SSN;
  1839           // ********** ********** ***
  1840  
  1841           // Perform MV I Search
  1842           vc mn_unatten dedMviSear ch(vcmn_ve teranFirst Name, vcmn _veteranLa stName, vc mn_DOB, vc mn_SSN);
  1843       }
  1844       catch  (err) {
  1845           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa veToVistA) : ' + err. message);
  1846           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1847       }
  1848   }
  1849  
  1850   function v cmn_ribbon ButtonSave ToVistA_wi th_ICN(vcm n_patientI CN) {
  1851       try {
  1852           // ******Deve loper Bypa ss for mis sing ICN** ****
  1853           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1854                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  1855                    aler t("Develop er ICN byp ass applie d!");
  1856                    vcmn _patientIC N = "12345 6V123456";
  1857                }
  1858           }
  1859  
  1860           // Verify Pat ient ICN
  1861           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1862                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! ');
  1863                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1864                return f alse;
  1865           }
  1866  
  1867           // Get regard ing data
  1868           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1869  
  1870           // Preserved  Variables
  1871           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1872           va r vcmn_vet eranName =  '';
  1873           va r vcmn_vet eranFirstN ame = '';
  1874           va r vcmn_vet eranLastNa me = '';
  1875           va r vcmn_vet eranMiddle Name = '';
  1876  
  1877           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1878           if  (vcmn_req uestData ! = null) {
  1879                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1880                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1881                    //Ve rify that  the custom erid is of  type cont act
  1882                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1883                         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!') ;
  1884                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1885                         return fal se;
  1886                    }
  1887                }
  1888           }
  1889           if  (vcmn_vet eranId ==  null) {
  1890                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  1891                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1892                return f alse;
  1893           }
  1894  
  1895           va r vcmn_con tactData =  vcmn_getS ingleEntit yDataSync( 'ContactSe t', 'FullN ame, First Name, Last Name, Midd leName', v cmn_vetera nId.Id);
  1896           if  (vcmn_con tactData ! = null) {
  1897                if (vcmn _contactDa ta.d.FullN ame != nul l) { vcmn_ veteranNam e = vcmn_c ontactData .d.FullNam e; }
  1898                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1899                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1900                if (vcmn _contactDa ta.d.Middl eName != n ull) { vcm n_veteranM iddleName  = vcmn_con tactData.d .MiddleNam e; }
  1901           }
  1902  
  1903           // Get user d ata
  1904           va r vcmn_crm UserId = X rm.Page.ge tAttribute ('ownerid' ).getValue ();
  1905           va r vcmn_use rDomainId  = '';
  1906           va r vcmn_use rFirstName  = '';
  1907           va r vcmn_use rLastName  = '';
  1908           va r vcmn_use rMiddleNam e = '';
  1909           va r vcmn_use rSiteId =  '';
  1910  
  1911           if  (vcmn_crm UserId !=  null) {
  1912                //Verify  the owner  type
  1913                if (vcmn _crmUserId [0].entity Type != 's ystemuser' ) {
  1914                    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 !');
  1915                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1916                    retu rn false;
  1917                }
  1918  
  1919                var vcmn _userData  = vcmn_get SingleEnti tyDataSync ('SystemUs erSet', 'D omainName,  FirstName , LastName , MiddleNa me, ftp_Fa cilitySite Id', vcmn_ crmUserId[ 0].id);
  1920                if (vcmn _userData  != null) {
  1921                    if ( vcmn_userD ata.d.Doma inName !=  null) { vc mn_userDom ainId = vc mn_userDat a.d.Domain Name; }
  1922                    if ( vcmn_userD ata.d.Firs tName != n ull) { vcm n_userFirs tName = vc mn_userDat a.d.FirstN ame; }
  1923                    if ( vcmn_userD ata.d.Last Name != nu ll) { vcmn _userLastN ame = vcmn _userData. d.LastName ; }
  1924                    if ( vcmn_userD ata.d.Midd leName !=  null) { vc mn_userMid dleName =  vcmn_userD ata.d.Midd leName; }
  1925                    if ( vcmn_userD ata.d.ftp_ FacilitySi teId != nu ll) { vcmn _userSiteI d = vcmn_u serData.d. ftp_Facili tySiteId.I d; }
  1926                }
  1927           }
  1928           el se {
  1929                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!');
  1930                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1931                return f alse;
  1932           }
  1933  
  1934           // Verify tha t the curr ent owner  and the cu rrent user  is the sa me person,  if not do  not proce ed
  1935           if  ((vcmn_cr mUserId[0] .id).toUpp erCase() ! = (Xrm.Pag e.context. getUserId( )).toUpper Case()) {
  1936                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!');
  1937                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1938                return f alse;
  1939           }
  1940           va r vcmn_Not eUserTeam  = "NONE";
  1941           // Check Team  membershi p
  1942           if  (vcmn_Use rHasTeam(" Pharmacy",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "PHARM ACY"; }
  1943           if  (vcmn_Use rHasTeam(" CCA Team",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "CCA";  }
  1944           if  (vcmn_Use rHasTeam(" TAN", Xrm. Page.conte xt.getUser Id())) { v cmn_NoteUs erTeam = " TAN"; }
  1945           // **TEMP, ve rify these  team valu es that th ey are cor rect **FUT URE NEED**
  1946           if  (vcmn_Use rHasTeam(" PACT User" , Xrm.Page .context.g etUserId() )) { vcmn_ NoteUserTe am = "PACT "; }
  1947           if  (vcmn_Use rHasTeam(" MSA User",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "MSA";  }
  1948  
  1949           // Verify Tea m Value, t hat one ha s been ass igned
  1950           if  (vcmn_Not eUserTeam  == "NONE")  {
  1951                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 !');
  1952                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1953                return f alse;
  1954           }
  1955  
  1956           // Get reques t form con tent
  1957           va r vcmn_not eDescripti on = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  1958           if  (vcmn_not eDescripti on == null  || vcmn_n oteDescrip tion == '' ) {
  1959                alert('T he note de scription  field is e mpty, the  note canno t be creat ed in Vist A/CPRS!');
  1960                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1961                return f alse;
  1962           }
  1963  
  1964           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) != true)  {
  1965                //Using  new hospit al locatio n and loca l notes lo okup field s
  1966                var vcmn _localTitl e = Xrm.Pa ge.getAttr ibute('ftp _localnote title').ge tValue();
  1967                if (vcmn _localTitl e == null)  {
  1968                    aler t('The loc al note ti tle field  is empty,  the note c annot be c reated in  VistA/CPRS !');
  1969                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1970                    retu rn false;
  1971                }
  1972                else { v cmn_localT itle = vcm n_localTit le[0].name ; }
  1973  
  1974                vcmn_pat ientAssign edLocation  = Xrm.Pag e.getAttri bute('ftp_ notehospit allocation ').getValu e();
  1975                if (vcmn _patientAs signedLoca tion == nu ll) {
  1976                    aler t('The hos pital loca tion field  is empty,  the note  cannot be  created in  VistA/CPR S!');
  1977                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1978                    retu rn false;
  1979                }
  1980                else { v cmn_patien tAssignedL ocation =  vcmn_patie ntAssigned Location[0 ].name; }
  1981           }
  1982  
  1983           va r vcmn_cal lbackNumbe r = Xrm.Pa ge.getAttr ibute('ftp _callbackn umber').ge tValue();
  1984           if  (vcmn_cal lbackNumbe r == null  || vcmn_ca llbackNumb er == '')  {
  1985                alert('T he callbac k number f ield is em pty, the n ote cannot  be create d in VistA /CPRS!');
  1986                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1987                return f alse;
  1988           }
  1989           va r vcmn_rea sonForRequ est = Xrm. Page.getAt tribute('f tp_reasonf orrequest' ).getValue ();
  1990           if  (vcmn_rea sonForRequ est == nul l) {
  1991                alert('T he reason  for reques t field is  empty, th e note can not be cre ated in Vi stA/CPRS!' );
  1992                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1993                return f alse;
  1994           }
  1995  
  1996           va r vcmn_enc ounterCode  = 'NEW';
  1997           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  1998           if  (vcmn_sig nThisNote  == 1000000 01) { vcmn _signThisN ote = true ; } else {  vcmn_sign ThisNote =  false; }
  1999  
  2000           // Get Progre ss Note Gu id/Id
  2001           va r vcmn_not eId = Xrm. Page.data. entity.get Id();
  2002  
  2003           // Get Create d On Date  & Convert  format
  2004           va r vcmn_cre atedOnDate  = vcmn_co nvertCrmDa teToVistAD ate(Xrm.Pa ge.getAttr ibute('cre atedon').g etValue()) ;
  2005           if  (vcmn_cre atedOnDate  == null)  {
  2006                alert('T he CRM cre atedon fie ld is empt y, the not e cannot b e created  in VistA/C PRS!');
  2007                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2008                return f alse;
  2009           }
  2010  
  2011           // Get User E ntry Date
  2012           va r vcmn_use rEntryDate  = vcmn_co nvertCrmDa teToVistAD ate(Xrm.Pa ge.getAttr ibute('ftp _userentry date').get Value());
  2013           if  (vcmn_use rEntryDate  == null)  { vcmn_use rEntryDate  = vcmn_cr eatedOnDat e; }
  2014  
  2015           // Get Facili ty and loo kup facili ty number  and HL7 UR L
  2016           va r vcmn_fac ilityCode  = '';
  2017           va r vcmn_sit eHL7Listen erAddress  = '';
  2018           va r vcmn_pat ientFacili ty = Xrm.P age.getAtt ribute('ft p_patientf acility'). getValue() ;
  2019           if  (vcmn_pat ientFacili ty == null ) {
  2020                alert('T he CRM pat ient facil ity field  is empty,  the note c annot be c reated in  VistA/CPRS !');
  2021                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2022                return f alse;
  2023           }
  2024           el se {
  2025                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e, ftp_hl7 listener',  vcmn_pati entFacilit y[0].id);
  2026                if (vcmn _facilityD ata.d.ftp_ facilityco de != null ) {
  2027                    vcmn _facilityC ode = vcmn _facilityD ata.d.ftp_ facilityco de;
  2028                }
  2029                else {
  2030                    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!') ;
  2031                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2032                    retu rn false;
  2033                }
  2034  
  2035                if (vcmn _facilityD ata.d.ftp_ hl7listene r != null)  {
  2036                    var  vcmn_siteH L7Listener Address =  vcmn_facil ityData.d. ftp_hl7lis tener;
  2037                }
  2038                else {
  2039                    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!');
  2040                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2041                    retu rn false;
  2042                }
  2043           }
  2044  
  2045           va r vcmn_ori ginatorID  = '';
  2046           va r vcmn_use rSiteNo =  '';
  2047  
  2048           // Lookup the  Facility/ Site #
  2049           if  (vcmn_use rSiteId !=  null && v cmn_userSi teId != '' ) {
  2050                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e', vcmn_u serSiteId) ;
  2051                if (vcmn _facilityD ata != nul l) {
  2052                    if ( vcmn_facil ityData.d. ftp_facili tycode !=  null) { vc mn_userSit eNo = vcmn _facilityD ata.d.ftp_ facilityco de; }
  2053                }
  2054           }
  2055  
  2056           // Validate r equired Vi sta Lookup  info
  2057           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) {
  2058                //Abort  process, m issing inf o
  2059                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 !');
  2060                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2061                return f alse;
  2062           }
  2063  
  2064           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) != true)  {
  2065                //Obtain  the Vista Duz from t he cross r eference t able if av ailable
  2066                if (vcmn _crmUserId  != null)  {
  2067                    var  vcmn_condi tionalFilt er = "ftp_ crmuser/Id  eq (guid' " + vcmn_c rmUserId[0 ].id + "') ";
  2068                    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);
  2069                    if ( vcmn_cross ReferenceD ata != nul l) {
  2070                         for (var i  = 0; i <=  vcmn_cros sReference Data.d.res ults.lengt h - 1; i++ ) {
  2071                             //Get  Info
  2072                             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;  }
  2073                             break;
  2074                         }
  2075                    }
  2076                }
  2077  
  2078                //**NOTE : The code  below to  impersonat e Lori Nic holls has  been disab led per ta sk 562307
  2079                /*
  2080                if (vcmn _IsProduct ionEnviron ment == fa lse) {
  2081                    //Pr ovide the  option to  search for  Lori Nich olls, site # 613
  2082                    var  vcmn_imper sonateProm ptString =  "**THIS I S A VISTA  USER SEARC H TEST PRO MPT** \n"  +
  2083                         "If you wo uld like t o imperson ate the us er: \n" +
  2084                         "Lori Nich olls (613)  \n" +
  2085                         "Select OK .  Otherwi se, select  CANCEL.";
  2086                    var  vcmn_confi rmImperson ateVistaUs er = confi rm(vcmn_im personateP romptStrin g);
  2087                    if ( vcmn_confi rmImperson ateVistaUs er == true ) {
  2088                         vcmn_userF irstName =  "Lori";
  2089                         vcmn_userL astName =  "Nicholls" ;
  2090                         vcmn_userS iteNo = "6 13";
  2091                    }
  2092                }
  2093                */
  2094  
  2095                var vcmn _vistauser sData = vc mn_getVist aUsersData (vcmn_user FirstName,  vcmn_user LastName,  vcmn_userS iteNo, fal se);
  2096  
  2097                //Check  vista user s data con tent
  2098                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) {
  2099                    //Ab ort proces s, missing  info
  2100                    aler t('Unable  to obtain  Vista User  Data, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  2101                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2102                    retu rn false;
  2103                }
  2104  
  2105                var vcmn _selectedU serFirstNa me = '';
  2106                var vcmn _selectedU serMiddleN ame = '';
  2107                var vcmn _selectedU serLastNam e = '';
  2108                var vcmn _selectedU serSuffix  = '';
  2109                var vcmn _selectedU serDisplay Name = '';
  2110                var vcmn _selectedU serTitle =  '';
  2111                var vcmn _userIsSel ected = fa lse;
  2112  
  2113                if (vcmn _vistauser sData.Data .length >  1) {
  2114                    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! ");
  2115                    for  (var i = 0 ; i <= vcm n_vistause rsData.Dat a.length -  1; i++) {
  2116                         var vcmn_c urrentUser FirstName  = '';
  2117                         var vcmn_c urrentUser MiddleName  = '';
  2118                         var vcmn_c urrentUser LastName =  '';
  2119                         var vcmn_c urrentUser Suffix = ' ';
  2120                         var vcmn_c urrentUser DisplayNam e = '';
  2121                         var vcmn_c urrentUser Title = '' ;
  2122                         if (vcmn_v istausersD ata.Data[i ].FirstNam e != null)  { vcmn_cu rrentUserF irstName =  vcmn_vist ausersData .Data[i].F irstName;  }
  2123                         if (vcmn_v istausersD ata.Data[i ].MiddleNa me != null ) { vcmn_c urrentUser MiddleName  = vcmn_vi stausersDa ta.Data[i] .MiddleNam e; }
  2124                         if (vcmn_v istausersD ata.Data[i ].LastName  != null)  { vcmn_cur rentUserLa stName = v cmn_vistau sersData.D ata[i].Las tName; }
  2125                         if (vcmn_v istausersD ata.Data[i ].Suffix ! = null) {  vcmn_curre ntUserSuff ix = vcmn_ vistausers Data.Data[ i].Suffix;  }
  2126                         if (vcmn_v istausersD ata.Data[i ].DisplayN ame != nul l) { vcmn_ currentUse rDisplayNa me = vcmn_ vistausers Data.Data[ i].Display Name; }
  2127                         if (vcmn_v istausersD ata.Data[i ].Title !=  null) { v cmn_curren tUserTitle  = vcmn_vi stausersDa ta.Data[i] .Title; }
  2128                         //Prompt u ser about  this vista  user reco rd
  2129                         var vcmn_u serPromptS tring = "C lick OK, t o select t his user.   Otherwise  CANCEL \n " +
  2130                             "\n Fi rst Name:  " + vcmn_c urrentUser FirstName  +
  2131                             "\n Mi ddle Name:  " + vcmn_ currentUse rMiddleNam e +
  2132                             "\n La st Name: "  + vcmn_cu rrentUserL astName +
  2133                             "\n Su ffix: " +  vcmn_curre ntUserSuff ix +
  2134                             "\n Di splay Name : " + vcmn _currentUs erDisplayN ame +
  2135                             "\n Ti tle: " + v cmn_curren tUserTitle ;
  2136  
  2137                         var vcmn_c onfirmSele ctVistaUse r = confir m(vcmn_use rPromptStr ing);
  2138                         if (vcmn_c onfirmSele ctVistaUse r == true)  {
  2139                             vcmn_u serIsSelec ted = true ;
  2140                             vcmn_s electedUse rFirstName  = vcmn_cu rrentUserF irstName;
  2141                             vcmn_s electedUse rMiddleNam e = vcmn_c urrentUser MiddleName ;
  2142                             vcmn_s electedUse rLastName  = vcmn_cur rentUserLa stName;
  2143                             vcmn_s electedUse rSuffix =  vcmn_curre ntUserSuff ix;
  2144                             vcmn_s electedUse rDisplayNa me = vcmn_ currentUse rDisplayNa me;
  2145                             vcmn_s electedUse rTitle = v cmn_curren tUserTitle ;
  2146                             break;
  2147                         }
  2148                    }
  2149                }
  2150                else {
  2151                    //Se lect data  from the f irst recor d
  2152                    vcmn _userIsSel ected = tr ue;
  2153                    if ( vcmn_vista usersData. Data[0].Fi rstName !=  null) { v cmn_select edUserFirs tName = vc mn_vistaus ersData.Da ta[0].Firs tName; }
  2154                    if ( vcmn_vista usersData. Data[0].Mi ddleName ! = null) {  vcmn_selec tedUserMid dleName =  vcmn_vista usersData. Data[0].Mi ddleName;  }
  2155                    if ( vcmn_vista usersData. Data[0].La stName !=  null) { vc mn_selecte dUserLastN ame = vcmn _vistauser sData.Data [0].LastNa me; }
  2156                    if ( vcmn_vista usersData. Data[0].Su ffix != nu ll) { vcmn _selectedU serSuffix  = vcmn_vis tausersDat a.Data[0]. Suffix; }
  2157                    if ( vcmn_vista usersData. Data[0].Di splayName  != null) {  vcmn_sele ctedUserDi splayName  = vcmn_vis tausersDat a.Data[0]. DisplayNam e; }
  2158                    if ( vcmn_vista usersData. Data[0].Ti tle != nul l) { vcmn_ selectedUs erTitle =  vcmn_vista usersData. Data[0].Ti tle; }
  2159                }
  2160  
  2161                //Check  if a user  was select ed
  2162                if (vcmn _userIsSel ected == f alse) {
  2163                    aler t('A user  was not se lected fro m the prev ious promp ts, the no te cannot  be created  in VistA/ CPRS!');
  2164                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2165                    retu rn false;
  2166                }
  2167  
  2168                //Execut e Integrat ion
  2169                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);
  2170  
  2171           }
  2172           el se {
  2173                //Execut e workload  encounter  note inte gration st eps
  2174                vcmn_pre pWorkloadE ncounterIn tegrationS tep01();
  2175           }
  2176       }
  2177       catch  (err) {
  2178           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa veToVistA_ with_ICN):  ' + err.m essage);
  2179           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2180       }
  2181   }
  2182  
  2183   function v cmn_prepWo rkloadEnco unterInteg rationStep 01() {
  2184       try {
  2185           // Verify Not e Title
  2186           va r vcmn_Not eTitleIEN  = Xrm.Page .getAttrib ute('ftp_s electedwor kloadnotet itleid').g etValue();
  2187           if  (vcmn_Not eTitleIEN  == null ||  vcmn_Note TitleIEN = = '') {
  2188                alert('T he selecte d note tit le field i s empty, t he note ca nnot be cr eated in V istA/CPRS! ');
  2189                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2190                return f alse;
  2191           }
  2192           // Verify Loc ation
  2193           va r vcmn_Loc ationIEN =  Xrm.Page. getAttribu te('ftp_se lectedwork loadlocati onid').get Value();
  2194           if  (vcmn_Loc ationIEN = = null ||  vcmn_Locat ionIEN ==  '') {
  2195                alert('T he selecte d location  field is  empty, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  2196                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2197                return f alse;
  2198           }
  2199           // Verify pat ient id
  2200           if  (vcmn_mat chLookupId  == null | | vcmn_mat chLookupId  == '') {
  2201                alert('T he veteran /patient d oes not ha ve a SSN,  the note c annot be c reated in  VistA/CPRS !');
  2202                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2203                return f alse;
  2204           }
  2205  
  2206           // Get the cu rrent CRM  User's ass igned site /facility
  2207           va r vcmn_use rSiteId =  "";
  2208  
  2209           va r vcmn_use rData = vc mn_getSing leEntityDa taSync('Sy stemUserSe t', 'ftp_F acilitySit eId', Xrm. Page.conte xt.getUser Id());
  2210           if  (vcmn_use rData != n ull) {
  2211                if (vcmn _userData. d.ftp_Faci litySiteId  != null)  {
  2212                    vcmn _userSiteI d = vcmn_u serData.d. ftp_Facili tySiteId.I d;
  2213                }
  2214           }
  2215  
  2216           // Lookup the  Facility/ Site #
  2217           if  (vcmn_use rSiteId !=  null && v cmn_userSi teId != '' ) {
  2218                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e', vcmn_u serSiteId) ;
  2219                if (vcmn _facilityD ata != nul l) {
  2220                    if ( vcmn_facil ityData.d. ftp_facili tycode !=  null) { vc mn_ViaLogi nFacility  = vcmn_fac ilityData. d.ftp_faci litycode;  }
  2221                }
  2222           }
  2223  
  2224           // Check if V IA Login c ookie exis t (not exp ired)
  2225           va r vcmn_Via LoginCooki e = vcmn_g etCookie(" viasession link");
  2226           if  (vcmn_Via LoginCooki e != null  && vcmn_Vi aLoginCook ie != '')  {
  2227                var vcmn _cookiearr ay = vcmn_ ViaLoginCo okie.split ("~~~~", 3 );
  2228                vcmn_Via LoginToken  = vcmn_co okiearray[ 0];
  2229                vcmn_Via LoginName  = vcmn_coo kiearray[1 ];
  2230                vcmn_esi gnatureCod e = vcmn_c ookiearray [2];
  2231           }
  2232           el se {
  2233                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!") ;
  2234                Xrm.Page .ui.tabs.g et('Tab_Vi stALogin') .setVisibl e(true);
  2235                Xrm.Page .ui.tabs.g et('Tab_Vi stALogin') .setFocus( );
  2236                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2237                return;
  2238           }
  2239  
  2240           // Lookup Pat ient Id us ing VIA 'm atch' serv ice
  2241           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);
  2242       }
  2243       catch  (err) {
  2244           al ert('Progr ess Note R ibbon Func tion Error (vcmn_prep WorkloadEn counterInt egrationSt ep01): ' +  err.messa ge);
  2245           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2246       }
  2247   }
  2248  
  2249   function v cmn_prepWo rkloadEnco unterInteg rationStep 01_respons e(vcmn_err or, vcmn_m atchrespon se) {
  2250       try {
  2251           // Check for  non VIA se rvice erro r
  2252           if  (vcmn_err or != null ) {
  2253                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!") ;
  2254                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2255                return f alse;
  2256           }
  2257           el se {
  2258                //Test f or VIA Ser vice Error
  2259                if (vcmn _matchresp onse.getEl ementsByTa gName("fau lt").lengt h > 0) {
  2260                    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 !");
  2261                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2262                    retu rn false;
  2263                }
  2264                //Get VI A service  Response
  2265                if (vcmn _matchresp onse.getEl ementsByTa gName("pat ients")[0] ) {
  2266                    var  vcmn_match Array = vc mn_matchre sponse.get ElementsBy TagName("p atients")[ 0].childNo des;
  2267                    //ch ildNodes[4 ] holds th e localPid /IEN value
  2268                    vcmn _ViaPatien tId = vcmn _matchArra y[0].child Nodes[4].t extContent ;
  2269                }
  2270                else {
  2271                    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 !");
  2272                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2273                    retu rn false;
  2274                }
  2275           }
  2276  
  2277           // Verify Inp atient
  2278           if  (Xrm.Page .getAttrib ute('ftp_w orkloadinp atient').g etValue()  == true) {
  2279                vcmn_Via InPatient  = "1";
  2280           }
  2281           el se {
  2282                vcmn_Via InPatient  = "0";
  2283           }
  2284  
  2285           // Verify CPT  Code & De scription
  2286           va r vcmn_Crm CptCode =  Xrm.Page.g etAttribut e('ftp_cpt code').get Value();
  2287           if  (vcmn_Crm CptCode ==  null) {
  2288                alert('T he CPT Cod e field is  empty, th e note can not be cre ated in Vi stA/CPRS!' );
  2289                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2290                return f alse;
  2291           }
  2292           el se {
  2293                var vcmn _cptData =  vcmn_getS ingleEntit yDataSync( 'ftp_cptco deSet', 'f tp_amadesc ription',  vcmn_CrmCp tCode[0].i d);
  2294                if (vcmn _cptData.d .ftp_amade scription  != null) {
  2295                    vcmn _ViaCptDes cription =  (vcmn_cpt Data.d.ftp _amadescri ption).rep lace(";",  "\;");
  2296                    vcmn _ViaCptCod e = vcmn_C rmCptCode[ 0].name;
  2297                }
  2298                else {
  2299                    aler t('The CPT  Code is m issing the  AMA Descr iption, th e note can not be cre ated in Vi stA/CPRS!' );
  2300                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2301                    retu rn false;
  2302                }
  2303           }
  2304  
  2305           // Combine CP T Code and  Descripti on
  2306           va r vcmn_Cpt Combined =  '';
  2307           if  (vcmn_Via CptCode.le ngth > 0 & & vcmn_Via CptDescrip tion.lengt h > 0) {
  2308                vcmn_Cpt Combined =  vcmn_ViaC ptCode + " ^" + vcmn_ ViaCptDesc ription;
  2309           }
  2310  
  2311           // Verify Dia gnosis Cod e & Descri ption
  2312           va r vcmn_Crm DiagnosisC ode = Xrm. Page.getAt tribute('f tp_diagnos iscode').g etValue();
  2313           if  (vcmn_Crm DiagnosisC ode == nul l) {
  2314                alert('T he Primary  Diagnosis  Code fiel d is empty , the note  cannot be  created i n VistA/CP RS!');
  2315                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2316                return f alse;
  2317           }
  2318  
  2319           if  (vcmn_Crm DiagnosisC ode != nul l && vcmn_ CrmDiagnos isCode !=  '') {
  2320                var vcmn _diagnosis Data = vcm n_getSingl eEntityDat aSync('ftp _diagnosis codeSet',  'ftp_descr iption', v cmn_CrmDia gnosisCode [0].id);
  2321                if (vcmn _diagnosis Data.d.ftp _descripti on != null ) {
  2322                    vcmn _ViaDiagno sisDescrip tion = (vc mn_diagnos isData.d.f tp_descrip tion).repl ace(";", " \;");
  2323                    vcmn _ViaDiagno sisCode =  vcmn_CrmDi agnosisCod e[0].name;
  2324                }
  2325           }
  2326  
  2327           // Combine Di agnosis Co de and Des cription a nd mark as  PRIMARY ( ^1)
  2328           va r vcmn_Dia gnosisComb ined = '';
  2329           if  (vcmn_Via DiagnosisC ode != nul l && vcmn_ ViaDiagnos isDescript ion != nul l) {
  2330                if (vcmn _ViaDiagno sisCode.le ngth > 0 & & vcmn_Via DiagnosisD escription .length >  0) {
  2331                    vcmn _Diagnosis Combined =  vcmn_ViaD iagnosisCo de + "^" +  vcmn_ViaD iagnosisDe scription  + "^1";
  2332                }
  2333           }
  2334  
  2335           // Get Second ary Diagno sis Codes
  2336           va r vcmn_Crm SecondaryD iagnosis =  Xrm.Page. getAttribu te('ftp_se lectedseco ndarydiagn osiscodes' ).getValue ();
  2337           if  (vcmn_Crm SecondaryD iagnosis ! = null &&  vcmn_CrmSe condaryDia gnosis !=  '') {
  2338                if (vcmn _Diagnosis Combined ! = '') {
  2339                    vcmn _Diagnosis Combined =  vcmn_Diag nosisCombi ned + ";"  + vcmn_Crm SecondaryD iagnosis;
  2340                }
  2341                else { v cmn_Diagno sisCombine d = vcmn_C rmSecondar yDiagnosis ; }
  2342           }
  2343  
  2344           // Get eSigna ture code
  2345           // This secti on is no l onger used , replaced  by via lo gin contro l esignatu re
  2346           /*
  2347           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 !");
  2348           if  (vcmn_eSi gnatureCod e == null  || vcmn_eS ignatureCo de == "" | | vcmn_eSi gnatureCod e == "unde fined") {
  2349                alert('T he eSignat ure Code e ntered is  invalid, t he note ca nnot be cr eated in V istA/CPRS! ');
  2350                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2351                return f alse;
  2352           }
  2353           */
  2354  
  2355           // Get User E ntry Date
  2356           va r vcmn_cre atedOnDate  = vialib_ convertToS tringDateT ime(Xrm.Pa ge.getAttr ibute('cre atedon').g etValue()) ;
  2357           va r vcmn_use rEntryDate  = null;
  2358           if  (Xrm.Page .getAttrib ute('ftp_u serentryda te').getVa lue() != n ull) {
  2359                vcmn_use rEntryDate  = vialib_ convertToS tringDateT ime(Xrm.Pa ge.getAttr ibute('ftp _userentry date').get Value());
  2360           }
  2361           if  (vcmn_use rEntryDate  == null)  { vcmn_use rEntryDate  = vcmn_cr eatedOnDat e; }
  2362  
  2363           // Reformat N ote Descri ption as n eeded to h andle long  lines of  text (Word Wrap)
  2364           va r vcmn_not eDescripti on = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  2365           va r vcmn_Not eText = vc mn_noteDes cription;
  2366           va r vcmn_Rev isedNoteTe xt = "";
  2367           // Do Breakdo wn of line s
  2368           va r vcmn_Tex tLines = v cmn_NoteTe xt.split(' \n');
  2369           if  (vcmn_Tex tLines.len gth > 0) {
  2370                //Reform at text
  2371                for (var  i = 0; i  < vcmn_Tex tLines.len gth; i++)  {
  2372                    //Te st for a l ong line
  2373                    if ( vcmn_TextL ines[i].le ngth > vcm n_WordWrap Limit) {
  2374                         //Break do wn line
  2375                         var vcmn_N ewString =  vcmn_word Wrap(vcmn_ TextLines[ i], vcmn_W ordWrapLim it, '\n');
  2376                         //Add revi sed text b ack
  2377                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _NewString  + "\n";   //Add back  the CR/LF  used to s plit on
  2378                    }
  2379                    else  {
  2380                         //Add text  to new no te
  2381                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _TextLines [i] + "\n" ; //Add ba ck the CR/ LF used to  split on
  2382                    }
  2383                }
  2384           }
  2385           if  (vcmn_Rev isedNoteTe xt != "" & & vcmn_Rev isedNoteTe xt != null ) {
  2386                vcmn_not eDescripti on = vcmn_ RevisedNot eText;
  2387           }
  2388  
  2389           // Add list o f addition al signer  names to N ote Text i f they exi sts
  2390           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  2391                //Create  text stri ngs from a dditional  signers ar ray
  2392                var vcmn _SignerNam es = "\nAd ditional N ote Signer s\n" + "-- ---------- ---------- -------\n" ;
  2393                for (var  i = 0; i  <= vcmn_Ad dlSignersN ameArray.l ength - 1;  i++) {
  2394                    if ( i >= 1) {
  2395                         var vcmn_s ingleSigne rName = vc mn_AddlSig nersNameAr ray[i].spl it("___");
  2396                         vcmn_Signe rNames = v cmn_Signer Names + vc mn_singleS ignerName[ 1] + "\n";
  2397                    }
  2398                }
  2399                //Add to  Note Desc ription
  2400                vcmn_not eDescripti on = vcmn_ noteDescri ption + vc mn_SignerN ames;
  2401           }
  2402           va r vcmn_Not eTitleIEN  = Xrm.Page .getAttrib ute('ftp_s electedwor kloadnotet itleid').g etValue();
  2403           va r vcmn_Loc ationIEN =  Xrm.Page. getAttribu te('ftp_se lectedwork loadlocati onid').get Value();
  2404  
  2405           // Create tex t strings  from addit ional sign ers array
  2406           va r vcmn_Sig nerIEN = " ";
  2407           if  (vcmn_Add lSignersIe nArray !=  null) {
  2408                for (var  i = 0; i  <= vcmn_Ad dlSignersI enArray.le ngth - 1;  i++) {
  2409                    if ( i == 1) {  vcmn_Signe rIEN = vcm n_AddlSign ersIenArra y[i]; }
  2410                    if ( i > 1) { v cmn_Signer IEN = vcmn _SignerIEN  + "," + v cmn_AddlSi gnersIenAr ray[i]; }
  2411                }
  2412           }
  2413  
  2414           // 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
  2415           // Replace al l \n and \ r occurren ces with |
  2416           vc mn_noteDes cription =  vcmn_note Descriptio n.replace( /\n/g, "|" );
  2417           vc mn_noteDes cription =  vcmn_note Descriptio n.replace( /\r/g, "|" );
  2418  
  2419           // Execute VI A saveNote AndEncount er Service
  2420           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)
  2421       }
  2422       catch  (err) {
  2423           al ert('Progr ess Note R ibbon Func tion Error (vcmn_prep WorkloadEn counterInt egrationSt ep01_respo nse): ' +  err.messag e);
  2424           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2425       }
  2426   }
  2427  
  2428   function v cmn_saveNo teAndEncou nter_respo nse(vcmn_e rrorThrown , vcmn_req uestRespon se, vcmn_n oteText) {
  2429       //Proc ess Note a nd Encount er Respons e
  2430       try {
  2431           if  (vcmn_err orThrown ! = null) {
  2432                //Write  Error
  2433                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etValue('E RROR');
  2434                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etSubmitMo de('always ');
  2435                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tValue(Str ing(vcmn_e rrorThrown ));
  2436                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tSubmitMod e('always' );
  2437                Xrm.Page .getAttrib ute('ftp_i ntegration date').set Value(new  Date());
  2438                Xrm.Page .getAttrib ute('ftp_i ntegration date').set SubmitMode ('always') ;
  2439                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etValue('' );
  2440                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etSubmitMo de('always ');
  2441                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. ');
  2442                Xrm.Page .getContro l('ftp_int egrationer ror').setF ocus();
  2443                Xrm.Page .data.enti ty.save();
  2444                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2445                return f alse;
  2446           }
  2447           el se {
  2448                //Write  web servic e response  Success o r Failure
  2449                if (vcmn _requestRe sponse.get ElementsBy TagName("f ault").len gth > 0) {
  2450                    //Wr ite Failur e entry
  2451                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setValu e('ERROR') ;
  2452                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setSubm itMode('al ways');
  2453                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setValue ("Service  Error: " +  vcmn_requ estRespons e.getEleme ntsByTagNa me("fault" )[0].textC ontent);
  2454                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setSubmi tMode('alw ays');
  2455                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setValue( new Date() );
  2456                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setSubmit Mode('alwa ys');
  2457                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setValu e('');
  2458                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setSubm itMode('al ways');
  2459                    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.');
  2460                    Xrm. Page.getCo ntrol('ftp _integrati onerror'). setFocus() ;
  2461                    Xrm. Page.data. entity.sav e();
  2462                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2463                    retu rn false;
  2464                }
  2465                else {
  2466                    //Te st for dat a
  2467                    if ( vcmn_reque stResponse .getElemen tsByTagNam e("ns2:sav eNoteAndEn counterRes ponse")[0] ) {
  2468                         //Sucessfu ll creatio n of workl oad encoun ter note
  2469                         Xrm.Page.g etAttribut e('ftp_not edetail'). setValue(v cmn_noteTe xt);
  2470                         Xrm.Page.g etAttribut e('ftp_not edetail'). setSubmitM ode('alway s');
  2471                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set Value('OK' );
  2472                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set SubmitMode ('always') ;
  2473                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setV alue(null) ;
  2474                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setS ubmitMode( 'always');
  2475                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setVa lue(new Da te());
  2476                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setSu bmitMode(' always');
  2477                         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);
  2478                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set SubmitMode ('always') ;
  2479                         //****UPDA TE e-Sign  attributes
  2480                         Xrm.Page.g etAttribut e('ftp_iss igned').se tValue(tru e);
  2481                         Xrm.Page.g etAttribut e('ftp_iss igned').se tSubmitMod e('always' );
  2482                         Xrm.Page.g etAttribut e('ftp_sig neddate'). setValue(n ew Date()) ;
  2483                         Xrm.Page.g etAttribut e('ftp_sig neddate'). setSubmitM ode('alway s');
  2484                         //******** ********** **********
  2485                         Xrm.Page.g etControl( 'ftp_integ rationstat us').setFo cus();
  2486                         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!');
  2487                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  2488                         Xrm.Page.d ata.entity .save();
  2489  
  2490                         if (vcmn_l ocalStorag eVarName ! = "" && vc mn_localSt orageVarNa me != null ) {
  2491                             //Clea r existing  session s torage var iable.
  2492                             localS torage.rem oveItem(vc mn_localSt orageVarNa me);
  2493                         }
  2494                    }
  2495                    else  {
  2496                         //Write No  Data Fail ure
  2497                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set Value('ERR OR');
  2498                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set SubmitMode ('always') ;
  2499                         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 !");
  2500                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setS ubmitMode( 'always');
  2501                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setVa lue(new Da te());
  2502                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setSu bmitMode(' always');
  2503                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set Value('');
  2504                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set SubmitMode ('always') ;
  2505                         alert('The  workload  encounter  note creat ion in Vis tA/CPRS fa iled!\nPle ase see th e integrat ion error  field for  details.') ;
  2506                         Xrm.Page.g etControl( 'ftp_integ rationerro r').setFoc us();
  2507                         Xrm.Page.d ata.entity .save();
  2508                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  2509                         return fal se;
  2510                    }
  2511                }
  2512           }
  2513       }
  2514       catch  (err) {
  2515           al ert('Progr ess Note R ibbon Func tion Error (vcmn_save NoteAndEnc ounter_res ponse): '  + err.mess age);
  2516           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2517       }
  2518   }
  2519  
  2520   function v cmn_getVis taUsersDat a(vcmn_use rFirstName , vcmn_use rLastName,  vcmn_user SiteNo, vc mn_noFilte r) {
  2521       try {
  2522           va r vcmn_jso nData = nu ll;
  2523           $. ajax({
  2524                type: "G ET",
  2525                url: vcm n_VistaUse rsURLbase  + vcmn_use rFirstName  + "/" + v cmn_userLa stName + " /" + vcmn_ userSiteNo  + "?noFil ter=" + vc mn_noFilte r,
  2526                contentT ype: "appl ication/js on; charse t=utf-8",
  2527                dataType : "json",
  2528                success:  function  (data) {
  2529                    vcmn _jsonData  = data;
  2530                },
  2531                error: f unction (j qXHR, text Status, er rorThrown)  {
  2532                    //Sy stem Error
  2533                    vcmn _jsonData  = null;
  2534                },
  2535                async: f alse,
  2536                cache: f alse
  2537           }) ;
  2538           re turn vcmn_ jsonData;
  2539       }
  2540       catch  (err) {
  2541           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getV istaUsersD ata): ' +  err.messag e);
  2542           re turn null;
  2543       }
  2544   }
  2545  
  2546   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) {
  2547       try {
  2548           // Reformat N ote Descri ption as n eeded to h andle long  lines of  text (Word Wrap)
  2549           va r vcmn_Not eText = vc mn_noteDes cription;
  2550           va r vcmn_Rev isedNoteTe xt = "";
  2551           // Do Breakdo wn of line s
  2552           va r vcmn_Tex tLines = v cmn_NoteTe xt.split(' \n');
  2553           if  (vcmn_Tex tLines.len gth > 0) {
  2554                //Reform at text
  2555                for (var  i = 0; i  < vcmn_Tex tLines.len gth; i++)  {
  2556                    //Te st for a l ong line
  2557                    if ( vcmn_TextL ines[i].le ngth > vcm n_WordWrap Limit) {
  2558                         //Break do wn line
  2559                         var vcmn_N ewString =  vcmn_word Wrap(vcmn_ TextLines[ i], vcmn_W ordWrapLim it, '\n');
  2560                         //Add revi sed text b ack
  2561                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _NewString  + "\n";   //Add back  the CR/LF  used to s plit on
  2562                    }
  2563                    else  {
  2564                         //Add text  to new no te
  2565                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _TextLines [i] + "\n" ; //Add ba ck the CR/ LF used to  split on
  2566                    }
  2567                }
  2568           }
  2569           if  (vcmn_Rev isedNoteTe xt != "" & & vcmn_Rev isedNoteTe xt != null ) {
  2570                vcmn_not eDescripti on = vcmn_ RevisedNot eText;
  2571           }
  2572  
  2573           // Add list o f addition al signer  names to N ote Text i f they exi sts
  2574           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  2575                //Create  text stri ngs from a dditional  signers ar ray
  2576                var vcmn _SignerNam es = "\nAd ditional N ote Signer s\n" + "-- ---------- ---------- -------\n" ;
  2577                for (var  i = 0; i  <= vcmn_Ad dlSignersN ameArray.l ength - 1;  i++) {
  2578                    if ( i >= 1) {
  2579                         var vcmn_s ingleSigne rName = vc mn_AddlSig nersNameAr ray[i].spl it("___");
  2580                         vcmn_Signe rNames = v cmn_Signer Names + vc mn_singleS ignerName[ 1] + "\n";
  2581                    }
  2582                }
  2583                //Add to  Note Desc ription
  2584                vcmn_not eDescripti on = vcmn_ noteDescri ption + vc mn_SignerN ames;
  2585           }
  2586  
  2587           va r vcmn_vis itNumber =  'NEW';
  2588           va r vcmn_cli entName =  "FTPCRM";
  2589           va r vcmn_For mat = "JSO N";
  2590           va r vcmn_pat ientIdenti fierType =  "ICN";
  2591           va r vcmn_doc umentAvail abilitySta tus = "AV" ;  //Histo rical Note  only at t his time
  2592           va r vcmn_ori ginatorCom binedMiddl e = "";
  2593           if  (vcmn_ori ginatorMid dleName !=  '' && vcm n_originat orMiddleNa me != null ) { vcmn_o riginatorC ombinedMid dle = vcmn _originato rMiddleNam e; }
  2594           if  (vcmn_ori ginatorSuf fix != ''  && vcmn_or iginatorSu ffix != nu ll) {
  2595                if (vcmn _originato rCombinedM iddle != ' ') {
  2596                    vcmn _originato rCombinedM iddle = vc mn_origina torCombine dMiddle +  " " + vcmn _originato rSuffix;
  2597                }
  2598                else {
  2599                    vcmn _originato rCombinedM iddle = vc mn_origina torSuffix;
  2600                }
  2601           }
  2602  
  2603           va r vcmn_req uestJSON =  {
  2604                "ClientN ame": vcmn _clientNam e,
  2605                "Format" : vcmn_For mat,
  2606                "Facilit ySiteID":  vcmn_facil itySiteId,
  2607                "SiteHL7 ListenerAd dress": vc mn_siteHL7 ListenerAd dress,
  2608                "VisitNu mber": vcm n_visitNum ber,
  2609                "IsSigne dNote": vc mn_signThi sNote,
  2610                "Patient AdmitDate" : vcmn_pat ientAdmitD ate,
  2611                "Patient LastName":  vcmn_pati entLastNam e,
  2612                "Patient FirstName" : vcmn_pat ientFirstN ame,
  2613                "Patient Identifier ": vcmn_pa tientICN,
  2614                "Patient Identifier Type": vcm n_patientI dentifierT ype,
  2615                "Patient AssignedLo cation": v cmn_patien tAssignedL ocation,
  2616                "NoteTex t": vcmn_n oteDescrip tion,
  2617                "Origina torID": vc mn_origina torID,
  2618                "Origina torFirstNa me": vcmn_ originator FirstName,
  2619                "Origina torMiddleN ame": vcmn _originato rCombinedM iddle,
  2620                "Origina torLastNam e": vcmn_o riginatorL astName,
  2621                "Documen tFileName" : vcmn_loc alTitle,
  2622                "Documen tAvailabil ityStatus" : vcmn_doc umentAvail abilitySta tus,
  2623                "Activit yDate": vc mn_activit yDate
  2624           };
  2625  
  2626           va r vcmn_req uestRespon se = "";
  2627  
  2628           $. ajax({
  2629                type: "P OST",
  2630                url: vcm n_NoteWrit eUrl,
  2631                data: JS ON.stringi fy(vcmn_re questJSON) ,
  2632                contentT ype: "appl ication/js on; charse t=utf-8",
  2633                dataType : "json",
  2634                success:  function  (data) {
  2635                    var  vcmn_newda ta = data;
  2636                    vcmn _requestRe sponse = v cmn_newdat a;
  2637                    vcmn _vistAInte grationReq uest_respo nse(null,  vcmn_reque stResponse , vcmn_not eDescripti on);
  2638                },
  2639                error: f unction (j qXHR, text Status, er rorThrown)  {
  2640                    //Sy stem Error
  2641                    vcmn _vistAInte grationReq uest_respo nse(errorT hrown, nul l, vcmn_no teDescript ion);
  2642                },
  2643                async: f alse,
  2644                cache: f alse
  2645           }) ;
  2646       }
  2647       catch  (err) {
  2648           al ert('Progr ess Note R ibbon Func tion Error (vcmn_exec uteVistAIn tegrationR equest): '  + err.mes sage);
  2649           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2650       }
  2651   }
  2652  
  2653   function v cmn_vistAI ntegration Request_re sponse(vcm n_errorThr own, vcmn_ requestRes ponse, vcm n_noteDesc ription) {
  2654       try {
  2655           // Process In tegration  Request Re sponse
  2656           if  (vcmn_err orThrown ! = null) {
  2657                //Write  Error
  2658                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etValue('E RROR');
  2659                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etSubmitMo de('always ');
  2660                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tValue(Str ing(vcmn_e rrorThrown ));
  2661                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tSubmitMod e('always' );
  2662                Xrm.Page .getAttrib ute('ftp_i ntegration date').set Value(new  Date());
  2663                Xrm.Page .getAttrib ute('ftp_i ntegration date').set SubmitMode ('always') ;
  2664                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etValue('' );
  2665                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etSubmitMo de('always ');
  2666                alert('T he note cr eation in  VistA/CPRS  failed!\n Please see  the integ ration err or field f or details .');
  2667                Xrm.Page .getContro l('ftp_int egrationer ror').setF ocus();
  2668                Xrm.Page .data.enti ty.save();
  2669                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2670                return f alse;
  2671           }
  2672           el se {
  2673                //Write  web servic e response  Success o r Failure
  2674                if (vcmn _requestRe sponse.Err orOccurred  == false)  {
  2675                    //Ca ll Additio nal Signer s & Finali ze Note fu nction
  2676                    vcmn _finalizeN oteCreatio n(vcmn_req uestRespon se.Status,  vcmn_requ estRespons e.Data, vc mn_noteDes cription)
  2677                }
  2678                else {
  2679                    //Wr ite Failur e entry
  2680                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setValu e(vcmn_req uestRespon se.Status) ;
  2681                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setSubm itMode('al ways');
  2682                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setValue (vcmn_requ estRespons e.ErrorMes sage + "   DebugInfo: " + vcmn_r equestResp onse.Debug Info);
  2683                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setSubmi tMode('alw ays');
  2684                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setValue( new Date() );
  2685                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setSubmit Mode('alwa ys');
  2686                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setValu e('');
  2687                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setSubm itMode('al ways');
  2688                    aler t('The not e creation  in VistA/ CPRS faile d!\nPlease  see the i ntegration  error fie ld for det ails.');
  2689                    Xrm. Page.getCo ntrol('ftp _integrati onerror'). setFocus() ;
  2690                    Xrm. Page.data. entity.sav e();
  2691                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2692                    retu rn false;
  2693                }
  2694           }
  2695       }
  2696       catch  (err) {
  2697           al ert('Progr ess Note R ibbon Func tion Error (vcmn_vist AIntegrati onRequest_ response):  ' + err.m essage);
  2698           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2699       }
  2700   }
  2701  
  2702   function v cmn_finali zeNoteCrea tion(vcmn_ integratio nStatus, v cmn_integr ationNoteI d, vcmn_no teDescript ion) {
  2703       //The  Note was s ucessfully  created i n Vista/CP RS, add ad ditional s igners if  needed
  2704       try {
  2705           // Determine  if additio nal signer s exists
  2706           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  2707                //Get th e current  CRM User's  assigned  site/facil ity
  2708                var vcmn _userSiteI d = "";
  2709                var vcmn _UserSiteN o = "";
  2710                var vcmn _duz = "";
  2711                var vcmn _providern ame = "";
  2712  
  2713                var vcmn _userData  = vcmn_get SingleEnti tyDataSync ('SystemUs erSet', 'f tp_Facilit ySiteId',  Xrm.Page.c ontext.get UserId());
  2714                if (vcmn _userData  != null) {
  2715                    if ( vcmn_userD ata.d.ftp_ FacilitySi teId != nu ll) {
  2716                         vcmn_userS iteId = vc mn_userDat a.d.ftp_Fa cilitySite Id.Id;
  2717                    }
  2718                }
  2719  
  2720                //Lookup  the Facil ity/Site #
  2721                if (vcmn _userSiteI d != null  && vcmn_us erSiteId ! = '') {
  2722                    var  vcmn_facil ityData =  vcmn_getSi ngleEntity DataSync(' ftp_facili tySet', 'f tp_facilit ycode', vc mn_userSit eId);
  2723                    if ( vcmn_facil ityData !=  null) {
  2724                         if (vcmn_f acilityDat a.d.ftp_fa cilitycode  != null)  { vcmn_Use rSiteNo =  vcmn_facil ityData.d. ftp_facili tycode; }
  2725                    }
  2726                }
  2727  
  2728                //Check  if VIA Log in cookie  exist (not  expired)
  2729                var vcmn _ViaLoginC ookie = vc mn_getCook ie("viases sionlink") ;
  2730                if (vcmn _ViaLoginC ookie != n ull && vcm n_ViaLogin Cookie !=  '') {
  2731                    var  vcmn_cooki earray = v cmn_ViaLog inCookie.s plit("~~~~ ", 3);
  2732                    vcmn _duz = vcm n_cookiear ray[0];
  2733                    vcmn _providern ame = vcmn _cookiearr ay[1];
  2734                    vcmn _esignatur eCode = vc mn_cookiea rray[2];
  2735                }
  2736  
  2737                //Create  text stri ngs from a dditional  signers ar ray
  2738                var vcmn _SignerIEN  = "";
  2739                for (var  i = 0; i  <= vcmn_Ad dlSignersI enArray.le ngth - 1;  i++) {
  2740                    if ( i == 1) {  vcmn_Signe rIEN = vcm n_AddlSign ersIenArra y[i]; }
  2741                    if ( i > 1) { v cmn_Signer IEN = vcmn _SignerIEN  + " " + v cmn_AddlSi gnersIenAr ray[i]; }
  2742                }
  2743  
  2744                //Create  the Addit ional Sign ers
  2745                var vcmn _viaSigner s = new Ob ject();
  2746                vcmn_via Signers.Pr oviderName  = vcmn_pr ovidername ;
  2747                vcmn_via Signers.Du z = vcmn_d uz;
  2748                vcmn_via Signers.Lo ginSiteCod e = vcmn_U serSiteNo;
  2749                vcmn_via Signers.Ta rget = vcm n_integrat ionNoteId;
  2750                vcmn_via Signers.Su pplemental Parameters  = vcmn_Si gnerIEN;
  2751  
  2752                $.ajax({
  2753                    type : "POST",
  2754                    url:  vcmn_AddS ignersUrl,
  2755                    data : JSON.str ingify(vcm n_viaSigne rs),
  2756                    cont entType: " applicatio n/json; ch arset=utf- 8",
  2757                    data Type: "jso n",
  2758                    succ ess: funct ion (data)  {
  2759                         vcmn_viaSi gnersRespo nse = JSON .stringify (data.Data );
  2760                         //Test for  Failure
  2761                         if (vcmn_v iaSignersR esponse.Er rorOccurre d == true)  {
  2762                             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!");
  2763                         }
  2764                    },
  2765                    erro r: functio n (jqXHR,  textStatus , errorThr own) {
  2766                         //System E rror
  2767                         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!");
  2768                    },
  2769                    asyn c: false,
  2770                    cach e: false
  2771                });
  2772  
  2773                if (vcmn _localStor ageVarName  != "" &&  vcmn_local StorageVar Name != nu ll) {
  2774                    //Cl ear existi ng session  storage v ariable.
  2775                    loca lStorage.r emoveItem( vcmn_local StorageVar Name);
  2776                }
  2777           }
  2778  
  2779           // Perform st andard for m updates  to signify  completio n
  2780           // Write Succ ess entry
  2781           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_noteDesc ription);
  2782           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  2783           Xr m.Page.get Attribute( 'ftp_integ rationstat us').setVa lue(vcmn_i ntegration Status);
  2784           Xr m.Page.get Attribute( 'ftp_integ rationstat us').setSu bmitMode(' always');
  2785           Xr m.Page.get Attribute( 'ftp_integ rationerro r').setVal ue(null);
  2786           Xr m.Page.get Attribute( 'ftp_integ rationerro r').setSub mitMode('a lways');
  2787           Xr m.Page.get Attribute( 'ftp_integ rationdate ').setValu e(new Date ());
  2788           Xr m.Page.get Attribute( 'ftp_integ rationdate ').setSubm itMode('al ways');
  2789           Xr m.Page.get Attribute( 'ftp_integ rationnote id').setVa lue(vcmn_i ntegration NoteId);
  2790           Xr m.Page.get Attribute( 'ftp_integ rationnote id').setSu bmitMode(' always');
  2791           Xr m.Page.get Control('f tp_integra tionstatus ').setFocu s();
  2792           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!');
  2793           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2794           Xr m.Page.dat a.entity.s ave();
  2795       }
  2796       catch  (err) {
  2797           al ert('Progr ess Note R ibbon Func tion Error (vcmn_fina lizeNoteCr eation): '  + err.mes sage);
  2798           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2799       }
  2800   }
  2801  
  2802   function v cmn_getCoo kie(cname)  {
  2803       try {
  2804           va r name = c name + "=" ;
  2805           va r ca = doc ument.cook ie.split(' ;');
  2806           fo r (var i =  0; i < ca .length; i ++) {
  2807                var c =  ca[i];
  2808                while (c .charAt(0)  == ' ') {
  2809                    c =  c.substrin g(1);
  2810                }
  2811                if (c.in dexOf(name ) == 0) {
  2812                    retu rn c.subst ring(name. length, c. length);
  2813                }
  2814           }
  2815           re turn "";
  2816       }
  2817       catch  (err) {
  2818           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getC ookie): '  + err.mess age);
  2819       }
  2820   }
  2821  
  2822   function v cmn_initVi aDropdownC ontrols()  {
  2823       //Init ialize VIA  DropDown  Controls
  2824       //Func tion is tr iggered by  The VistA  Login Con trol and o nchange of  Facility  attribute
  2825       try {
  2826           Xr m.Page.get Control("W ebResource _ViaWorklo adLookup") .setSrc(Xr m.Page.get Control("W ebResource _ViaWorklo adLookup") .getSrc()) ;
  2827           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());
  2828       }
  2829       catch  (err) {
  2830           al ert('Progr ess Note V IA Login F unction Er ror(vcmn_i nitViaDrop downContro ls): ' + e rr.message );
  2831       }
  2832   }
  2833  
  2834   function v cmn_facili tyGroupDef ault_respo nse(vcmn_f acilityGro upData, vc mn_lastSki p, vcmn_fa cilitySite Id) {
  2835       try {
  2836           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  2837           fo r (var i =  0; i <= v cmn_facili tyGroupDat a.d.result s.length -  1; i++) {
  2838                //Get Va lues and W rite to Pr ogress Not e if a new  Note
  2839                if (Xrm. Page.ui.ge tFormType( ) == 1) {
  2840                    if ( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ localnotes title != n ull) {
  2841                         Xrm.Page.g etAttribut e("ftp_loc alnotestit le").setVa lue(vcmn_f acilityGro upData.d.r esults[i]. ftp_localn otestitle) ;
  2842                         Xrm.Page.g etAttribut e('ftp_loc alnotestit le').setSu bmitMode(' always');
  2843                    }
  2844                    if ( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ hospitallo cation !=  null) {
  2845                         Xrm.Page.g etAttribut e("ftp_hos pitallocat ion").setV alue(vcmn_ facilityGr oupData.d. results[i] .ftp_hospi tallocatio n);
  2846                         Xrm.Page.g etAttribut e('ftp_hos pitallocat ion').setS ubmitMode( 'always');
  2847                    }
  2848                    if ( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ viaworkloa dencounter locationde fault != n ull) {
  2849                         //Verify t hat the te xt contain s the doub le tilde ~ ~
  2850                         if (vcmn_f acilityGro upData.d.r esults[i]. ftp_viawor kloadencou nterlocati ondefault. indexOf("~ ~") >= 0)  {
  2851                             //Spli t on ~~
  2852                             var vc mn_encount erLocation Array = vc mn_facilit yGroupData .d.results [i].ftp_vi aworkloade ncounterlo cationdefa ult.split( "~~", 2);
  2853                             if (vc mn_encount erLocation Array.leng th > 1) {
  2854                                 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] !=  '') {
  2855                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat ionid").se tValue(vcm n_encounte rLocationA rray[0]);
  2856                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat ionid").se tSubmitMod e('always' );
  2857                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat iontext"). setValue(v cmn_encoun terLocatio nArray[1]) ;
  2858                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat iontext"). setSubmitM ode('alway s');
  2859                                 }
  2860                             }
  2861                         }
  2862                    }
  2863                    if ( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ viaworkloa dencounter notetitled efault !=  null) {
  2864                         //Verify t hat the te xt contain s the doub le tilde ~ ~
  2865                         if (vcmn_f acilityGro upData.d.r esults[i]. ftp_viawor kloadencou nternoteti tledefault .indexOf(" ~~") >= 0)  {
  2866                             //Spli t on ~~
  2867                             var vc mn_encount erNoteTitl eArray = v cmn_facili tyGroupDat a.d.result s[i].ftp_v iaworkload encountern otetitlede fault.spli t("~~", 2) ;
  2868                             if (vc mn_encount erNoteTitl eArray.len gth > 1) {
  2869                                 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]  != '') {
  2870                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itleid").s etValue(vc mn_encount erNoteTitl eArray[0]) ;
  2871                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itleid").s etSubmitMo de('always ');
  2872                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itletext") .setValue( vcmn_encou nterNoteTi tleArray[1 ]);
  2873                                      Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itletext") .setSubmit Mode('alwa ys');
  2874                                 }
  2875                             }
  2876                         }
  2877                    }
  2878                    if ( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ historical notetitled efault !=  null) {
  2879                         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 );
  2880                         Xrm.Page.g etAttribut e('ftp_loc alnotetitl e').setSub mitMode('a lways');
  2881                    }
  2882                    if ( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ historical locationde fault != n ull) {
  2883                         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);
  2884                         Xrm.Page.g etAttribut e('ftp_not ehospitall ocation'). setSubmitM ode('alway s');
  2885                    }
  2886                }
  2887                //Store  the Id for  the match ing Facili ty Group D efault, us ed later t o update f requently  used value s.
  2888                if (vcmn _facilityG roupData.d .results[i ].ftp_faci litygroupd efaultId ! = null) {
  2889                    vcmn _facilityG roupDefaul tId = vcmn _facilityG roupData.d .results[i ].ftp_faci litygroupd efaultId;
  2890                }
  2891                break;
  2892           }
  2893       }
  2894       catch  (err) {
  2895           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_faci lityGroupD efault_res ponse): '  + err.mess age);
  2896       }
  2897   }
  2898  
  2899   function v cmn_buildQ ueryFilter (field, va lue, and)  {
  2900       try {
  2901           if  (value ==  '') {
  2902                if (and)  {
  2903                    retu rn " and "  + field +  " eq null ";
  2904                } else {
  2905                    retu rn field +  " eq null ";
  2906                }
  2907           }
  2908           el se {
  2909                if (and)  {
  2910                    retu rn " and "  + field +  " eq '" +  value + " '";
  2911                } else {
  2912                    retu rn field +  " eq '" +  value + " '";
  2913                }
  2914           }
  2915       }
  2916       catch  (err) {
  2917           al ert('Progr ess Note R ibbon Func tion Error (vcmn_buil dQueryFilt er): ' + e rr.message );
  2918           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2919       }
  2920   }
  2921  
  2922   function v cmn_unatte ndedMviSea rch(firstn ame, lastn ame, dobda te, ssn) {
  2923       try {
  2924           va r filter =  "";
  2925           va r filterPr efix = "$s elect=*&$f ilter=";
  2926           va r edipi =  "";
  2927           va r dobstrin g = "";
  2928           if  (dobdate  != null) {
  2929                dobstrin g = dobdat e;
  2930           }
  2931  
  2932           if  (ssn != " " && ssn ! = null) {
  2933                ssn = ss n.replace( /-/g, "");
  2934           }
  2935  
  2936           // if we have  edipi, se arch using  just it
  2937           if  (edipi !=  "") {
  2938                filter =  vcmn_buil dQueryFilt er("crme_E DIPI", edi pi, false) ;
  2939                filter + = vcmn_bui ldQueryFil ter("crme_ ClassCode" , 'MIL', t rue);
  2940                filter + = vcmn_bui ldQueryFil ter("crme_ SearchType ", 'Search ByIdentifi er', true) ;
  2941  
  2942                //set se arch type  as unatten ded
  2943                filter + = " and cr me_IsAtten ded eq fal se";
  2944           }
  2945           el se {
  2946                //otherw ise search  using las tname, fir stname, ss n, dob
  2947                filter =  vcmn_buil dQueryFilt er("crme_L astName",  lastname,  false); // assuming l astname wi ll never b e blank
  2948  
  2949                if (firs tname != " " && first name != nu ll) {
  2950                    filt er += vcmn _buildQuer yFilter("c rme_FirstN ame", firs tname, tru e);
  2951                }
  2952  
  2953                if (ssn  != "" && s sn != null ) {
  2954                    filt er += vcmn _buildQuer yFilter("c rme_SSN",  ssn, true) ;
  2955                }
  2956  
  2957                if (dobs tring != " ") {
  2958                    filt er += " an d crme_DOB String eq  '" + dobst ring + "'" ;
  2959                }
  2960                filter + = vcmn_bui ldQueryFil ter("crme_ SearchType ", 'Search ByFilter',  true);
  2961  
  2962                //set se arch type  as attende d (for now )
  2963                filter + = " and cr me_IsAtten ded eq tru e";
  2964           }
  2965  
  2966           fi lter = enc odeURIComp onent(filt er);
  2967           fi lter = fil terPrefix  + filter;
  2968           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);
  2969       }
  2970       catch  (err) {
  2971           al ert('Progr ess Note R ibbon Func tion Error (vcmn_unat tendedMviS earch): '  + err.mess age);
  2972           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2973       }
  2974   }
  2975  
  2976   function v cmn_unatte ndedMviSea rchCallbac k(returnDa ta) {
  2977       try {
  2978           if  (returnDa ta != null  && return Data.lengt h >= 1) {
  2979                // check  for excep tions 1st
  2980                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."))  {
  2981                    //do  nothing,  pass empty  ICN
  2982                    vcmn _ribbonBut tonSaveToV istA_with_ ICN("");
  2983                }
  2984                else {
  2985                    var  patientMvi Identifier  = returnD ata[0].crm e_PatientM viIdentifi er == null  ? "" : re turnData[0 ].crme_Pat ientMviIde ntifier;
  2986                    if ( patientMvi Identifier  != "") {
  2987                         var idpart s = patien tMviIdenti fier.split ("^");
  2988  
  2989                         if (idpart s.length >  0) {
  2990                             var na tionalId =  idparts[0 ];
  2991                             _icn =  nationalI d;
  2992                             //Pass  on the IC N and cont inue valid ation
  2993                             vcmn_r ibbonButto nSaveToVis tA_with_IC N(_icn);
  2994                         }
  2995                    }
  2996                }
  2997           }
  2998           el se {
  2999                //Return  empty ICN
  3000                vcmn_rib bonButtonS aveToVistA _with_ICN( "");
  3001           }
  3002       }
  3003       catch  (err) {
  3004           al ert('Progr ess Note R ibbon Func tion Error (vcmn_unat tendedMviS earchCallb ack): ' +  err.messag e);
  3005           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  3006       }
  3007   }
  3008  
  3009   function v cmn_unatte ndedMviSea rchComplet e() {
  3010       //do n othing
  3011   }
  3012  
  3013   function v cmn_buildQ ueryFilter SCD(field,  value, an d) {
  3014       try {
  3015           if  (value ==  '') {
  3016                if (and)  {
  3017                    retu rn " and "  + field +  " eq null ";
  3018                } else {
  3019                    retu rn field +  " eq null ";
  3020                }
  3021           }
  3022           el se {
  3023                if (and)  {
  3024                    retu rn " and "  + field +  " eq '" +  value + " '";
  3025                } else {
  3026                    retu rn field +  " eq '" +  value + " '";
  3027                }
  3028           }
  3029       }
  3030       catch  (err) {
  3031           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_buil dQueryFilt erSCD): '  + err.mess age);
  3032           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  3033       }
  3034   }
  3035  
  3036   function v cmn_unatte ndedMviSea rchSCD(fir stname, la stname, do bdate, ssn ) {
  3037       try {
  3038           va r filter =  "";
  3039           va r filterPr efix = "$s elect=*&$f ilter=";
  3040           va r edipi =  "";
  3041           va r dobstrin g = "";
  3042           if  (dobdate  != null) {
  3043                dobstrin g = dobdat e;
  3044           }
  3045  
  3046           if  (ssn != " " && ssn ! = null) {
  3047                ssn = ss n.replace( /-/g, "");
  3048           }
  3049  
  3050           // if we have  edipi, se arch using  just it
  3051           if  (edipi !=  "") {
  3052                filter =  vcmn_buil dQueryFilt erSCD("crm e_EDIPI",  edipi, fal se);
  3053                filter + = vcmn_bui ldQueryFil terSCD("cr me_ClassCo de", 'MIL' , true);
  3054                filter + = vcmn_bui ldQueryFil terSCD("cr me_SearchT ype", 'Sea rchByIdent ifier', tr ue);
  3055  
  3056                //set se arch type  as unatten ded
  3057                filter + = " and cr me_IsAtten ded eq fal se";
  3058           }
  3059           el se {
  3060                //otherw ise search  using las tname, fir stname, ss n, dob
  3061                filter =  vcmn_buil dQueryFilt erSCD("crm e_LastName ", lastnam e, false);  //assumin g lastname  will neve r be blank
  3062  
  3063                if (firs tname != " " && first name != nu ll) {
  3064                    filt er += vcmn _buildQuer yFilterSCD ("crme_Fir stName", f irstname,  true);
  3065                }
  3066  
  3067                if (ssn  != "" && s sn != null ) {
  3068                    filt er += vcmn _buildQuer yFilterSCD ("crme_SSN ", ssn, tr ue);
  3069                }
  3070  
  3071                if (dobs tring != " ") {
  3072                    filt er += " an d crme_DOB String eq  '" + dobst ring + "'" ;
  3073                }
  3074                filter + = vcmn_bui ldQueryFil terSCD("cr me_SearchT ype", 'Sea rchByFilte r', true);
  3075  
  3076                //set se arch type  as attende d (for now )
  3077                filter + = " and cr me_IsAtten ded eq tru e";
  3078           }
  3079  
  3080           fi lter = enc odeURIComp onent(filt er);
  3081           fi lter = fil terPrefix  + filter;
  3082           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) ;
  3083       }
  3084       catch  (err) {
  3085           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_unat tendedMviS earchSCD):  ' + err.m essage);
  3086       }
  3087   }
  3088  
  3089   function v cmn_unatte ndedMviSea rchCallbac kSCD(retur nData) {
  3090       try {
  3091           if  (returnDa ta != null  && return Data.lengt h >= 1) {
  3092                // check  for excep tions 1st
  3093                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."))  {
  3094                    //do  nothing,  pass empty  ICN
  3095                    vcmn _getServic eConnected Disabiliti es("");
  3096                }
  3097                else {
  3098                    var  patientMvi Identifier  = returnD ata[0].crm e_PatientM viIdentifi er == null  ? "" : re turnData[0 ].crme_Pat ientMviIde ntifier;
  3099                    if ( patientMvi Identifier  != "") {
  3100                         var idpart s = patien tMviIdenti fier.split ("^");
  3101  
  3102                         if (idpart s.length >  0) {
  3103                             var na tionalId =  idparts[0 ];
  3104                             _icn =  nationalI d;
  3105                             //Pass  on the IC N and cont inue with  SCD
  3106                             vcmn_g etServiceC onnectedDi sabilities (_icn);
  3107                         }
  3108                    }
  3109                }
  3110           }
  3111           el se {
  3112                //Return  empty ICN
  3113                vcmn_get ServiceCon nectedDisa bilities(" ");
  3114           }
  3115       }
  3116       catch  (err) {
  3117           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_unat tendedMviS earchCallb ackSCD): '  + err.mes sage);
  3118       }
  3119   }
  3120  
  3121   //Standalo ne form lo ad functio ns
  3122   function v cmn_secure ProgressNo te() {
  3123       try {
  3124           // Disable al l form att ributes if  form is o pened by a  user who  does not o wn the pro gress note
  3125           // Only handl e forms in  create st ate
  3126           if  (Xrm.Page .ui.getFor mType() !=  2) { retu rn false;  } //2 = CR M Update S tatus
  3127           // Get the cu rrent owne r of the r ecord and  compare to  the curre nt user
  3128           va r vcmn_rec ordOwnerId  = Xrm.Pag e.getAttri bute('owne rid').getV alue();
  3129           // 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
  3130           if  ((vcmn_re cordOwnerI d[0].id).t oUpperCase () != (Xrm .Page.cont ext.getUse rId()).toU pperCase() ) {
  3131                Xrm.Page .data.enti ty.attribu tes.forEac h(function  (attribut e, index)  {
  3132                    var  control =  Xrm.Page.g etControl( attribute. getName()) ;
  3133                    if ( control) {
  3134                         control.se tDisabled( true)
  3135                    }
  3136                });
  3137           }
  3138       }
  3139       catch  (err) {
  3140           al ert('Progr ess Note F orm Load F unction Er ror(vcmn_s ecureProgr essNote):  ' + err.me ssage);
  3141       }
  3142   }
  3143  
  3144   function v cmn_initFi nancialDis claimer()  {
  3145       //This  function  is used to  initialze  the Finan cial Discl aimer tab  on the pro gress note  form
  3146       try {
  3147           va r vcmn_isR eadDisclai mer = Xrm. Page.getAt tribute("f tp_isreadd isclaimer" ).getValue ();
  3148           va r vcmn_res ponseToDis claimer =  Xrm.Page.g etAttribut e("ftp_isd isclaimerr ead").getV alue();
  3149           Xr m.Page.get Attribute( "ftp_patie ntcallersr easonfordi sagreeing" ).setSubmi tMode("alw ays");
  3150           if  (vcmn_isR eadDisclai mer == tru e && vcmn_ responseTo Disclaimer  == true)  {
  3151                Xrm.Page .ui.tabs.g et("Tab_Fi nancialDis claimer"). setVisible (true);
  3152                Xrm.Page .getAttrib ute("ftp_i spatientag ree").setR equiredLev el("requir ed");
  3153                var vcmn _isPatient Agree = Xr m.Page.get Attribute( "ftp_ispat ientagree" ).getValue ();
  3154                if (vcmn _isPatient Agree == f alse) {
  3155                    Xrm. Page.getAt tribute("f tp_patient callersrea sonfordisa greeing"). setRequire dLevel("re quired");
  3156                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tVisible(t rue);
  3157                }
  3158                else { X rm.Page.ge tControl(" ftp_patien tcallersre asonfordis agreeing") .setVisibl e(false);  }
  3159           }
  3160       }
  3161       catch  (err) {
  3162           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ initFinanc ialDisclai mer): ' +  err.messag e);
  3163       }
  3164   }
  3165  
  3166   //Standalo ne form at tribute on  change ev ent functi ons
  3167   function v cmn_needTo ReadDiscla imer_OnCha nge() {
  3168       //This  function  is used to  display t he Financi al Disclai mer prompt
  3169       try {
  3170           va r vcmn_isR eadDisclai mer = Xrm. Page.getAt tribute("f tp_isreadd isclaimer" ).getValue ();
  3171           if  (vcmn_isR eadDisclai mer == tru e) {
  3172                //Financ ial Discla imer is ne eded
  3173                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.") ;
  3174                if (vcmn _responseT oDisclaime r == true)  {
  3175                    Xrm. Page.ui.ta bs.get("Ta b_Financia lDisclaime r").setVis ible(true) ;
  3176                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setValue (true);
  3177                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setSubmi tMode("alw ays");
  3178                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setRequire dLevel("re quired");
  3179                    //Se t Default  Value to N ot Agreein g and Requ ire Reason  for disag reeing
  3180                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setValue(f alse);
  3181                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setSubmitM ode("alway s");
  3182                    Xrm. Page.getAt tribute("f tp_patient callersrea sonfordisa greeing"). setRequire dLevel("re quired");
  3183                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tVisible(t rue);
  3184                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tFocus();
  3185                }
  3186                else {
  3187                    Xrm. Page.ui.ta bs.get("Ta b_Financia lDisclaime r").setVis ible(false );
  3188                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setValue (false);
  3189                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setSubmi tMode("alw ays");
  3190                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setRequire dLevel("no ne");
  3191                    Xrm. Page.getAt tribute("f tp_patient callersrea sonfordisa greeing"). setRequire dLevel("no ne");
  3192                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tVisible(f alse);
  3193                }
  3194           }
  3195           el se {
  3196                //No Fin ancial Dis claimer ne eded  (Hid e Financia l Disclaim er section )
  3197                Xrm.Page .ui.tabs.g et("Tab_Fi nancialDis claimer"). setVisible (false);
  3198                Xrm.Page .getAttrib ute("ftp_i spatientag ree").setR equiredLev el("none") ;
  3199                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setR equiredLev el("none") ;
  3200                Xrm.Page .getContro l("ftp_pat ientcaller sreasonfor disagreein g").setVis ible(false );
  3201           }
  3202       }
  3203       catch  (err) {
  3204           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ needToRead Disclaimer _OnChange) : ' + err. message);
  3205       }
  3206   }
  3207  
  3208   function v cmn_isPati entInAgree ment_OnCha nge() {
  3209       try {
  3210           va r vcmn_isP atientAgre e = Xrm.Pa ge.getAttr ibute("ftp _ispatient agree").ge tValue();
  3211           if  (vcmn_isP atientAgre e == false ) {
  3212                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setR equiredLev el("requir ed");
  3213                Xrm.Page .getContro l("ftp_pat ientcaller sreasonfor disagreein g").setVis ible(true) ;
  3214           }
  3215           el se {
  3216                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setR equiredLev el("none") ;
  3217                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setV alue(null) ;
  3218                Xrm.Page .getContro l("ftp_pat ientcaller sreasonfor disagreein g").setVis ible(false );
  3219                //Update  Note
  3220                vcmn_app endNoteFin ancialDisc laimer_OnC hange();
  3221           }
  3222       }
  3223       catch  (err) {
  3224           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ isPatientI nAgreement _OnChange) : ' + err. message);
  3225       }
  3226   }
  3227  
  3228   function v cmn_append NoteFinanc ialDisclai mer_OnChan ge() {
  3229       //This  function  adds Finan cial Discl aimer text  to the en d of the N ote
  3230       try {
  3231           // Get Curren t Note Tex t
  3232           va r vcmn_cur rentNoteTe xt = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  3233           if  (vcmn_cur rentNoteTe xt == null ) { vcmn_c urrentNote Text = "";  }
  3234           // Create new  Financial  Disclaime r Text
  3235           va r vcmn_fin ancialDisc laimerText  = "";
  3236  
  3237           va r vcmn_sta ndardText  = "\n\nFIN ANCIAL DIS CLAIMER\n"  +
  3238                "------- ---------- ---------- ---------- ---------- ---------- ---------- ---\n" +
  3239                "The fol lowing dis claimer wa s read to  the caller :\n" +
  3240                "Patient  was instr ucted, 'Th is is not  an authori zation for  VA\n" +
  3241                "Payment  and also  'To have h ospital co ntact the  nearest VA \n" +
  3242                "Facilit y for tran sfer upon  stabilizat ion.\n";
  3243           va r vcmn_ter minationTe xt = "\n-- ---------- ---------- ---------- ---------- ---------- ---------- --------\n ";
  3244  
  3245           va r vcmn_isR eadDisclai mer = Xrm. Page.getAt tribute("f tp_isreadd isclaimer" ).getValue ();
  3246           va r vcmn_res ponseToDis claimer =  Xrm.Page.g etAttribut e("ftp_isd isclaimerr ead").getV alue();
  3247           if  (vcmn_isR eadDisclai mer == tru e && vcmn_ responseTo Disclaimer  == true)  {
  3248                var vcmn _isPatient Agree = Xr m.Page.get Attribute( "ftp_ispat ientagree" ).getValue ();
  3249                if (vcmn _isPatient Agree == t rue) {
  3250                    vcmn _financial Disclaimer Text = vcm n_standard Text +
  3251                         "\nPatient /Caller ag rees with  plan." + v cmn_termin ationText;
  3252                }
  3253                else {
  3254                    var  vcmn_reaso nForDisagr eeing = Xr m.Page.get Attribute( "ftp_patie ntcallersr easonfordi sagreeing" ).getValue ();
  3255                    if ( vcmn_reaso nForDisagr eeing == n ull) { vcm n_reasonFo rDisagreei ng = ""; }
  3256                    vcmn _financial Disclaimer Text = vcm n_standard Text +
  3257                         "\nPatient /Caller do es not agr ee with th e plan bec ause:\n" +
  3258                         vcmn_reaso nForDisagr eeing + vc mn_termina tionText;
  3259                }
  3260           }
  3261  
  3262           // Append to  existing N ote
  3263           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_currentN oteText +  vcmn_finan cialDiscla imerText);
  3264           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  3265       }
  3266       catch  (err) {
  3267           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ appendNote FinancialD isclaimer_ OnChange):  ' + err.m essage);
  3268       }
  3269   }
  3270  
  3271   function f req_button Action(fre q_buttonNa me) {
  3272       try {
  3273           // Frequently  Used butt on pressed , validate  Facility  Group Defa ults
  3274           if  (vcmn_fac ilityGroup DefaultId  == null) {
  3275                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!");
  3276                return f alse;
  3277           }
  3278           if  (freq_but tonName !=  null && f req_button Name != un defined &&  freq_butt onName !=  "") {
  3279                //Verify  button na me and tak e action a ccordingly
  3280                if (freq _buttonNam e == "Freq UsedNoteTi tleButton" ) {
  3281                    //No te Title b utton clic ked
  3282                    var  freq_ViaNo teTitleIEN  = Xrm.Pag e.getAttri bute("ftp_ selectedwo rkloadnote titleid"). getValue() ;
  3283                    var  freq_ViaNo teTitleDes cription =  Xrm.Page. getAttribu te("ftp_se lectedwork loadnoteti tletext"). getValue() ;
  3284                    if ( freq_ViaNo teTitleIEN  == null | | freq_Via NoteTitleI EN == "" | | freq_Via NoteTitleD escription  == null | | freq_Via NoteTitleD escription  == "") {
  3285                         alert("The  selected  Note Title  is not va lid, it ca n not be a dded to th e Frequent ly Used Li st!");
  3286                         return fal se;
  3287                    }
  3288                    //Pr ompt User  to add Not e Title
  3289                    var  freq_AddCo nfirm = fa lse;
  3290                    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 ?",
  3291                         function ( ) { freq_A ddConfirm  = true; },
  3292                         function ( ) { freq_A ddConfirm  = false; }
  3293                    );
  3294                    if ( freq_AddCo nfirm == f alse) { re turn false ; }
  3295  
  3296                    //Ge t Existing  Frequentl y Used Not e Title Li st
  3297                    var  freq_frequ entlyUsedN oteTitles  = null;
  3298                    var  freq_facil ityGroupDe faultData  = vcmn_get SingleEnti tyDataSync ('ftp_faci litygroupd efaultSet' , 'ftp_fre quentlyuse dnotetitle s', vcmn_f acilityGro upDefaultI d);
  3299                    if ( freq_facil ityGroupDe faultData  != null) {
  3300                         if (freq_f acilityGro upDefaultD ata.d.ftp_ frequently usednoteti tles != nu ll) {
  3301                             freq_f requentlyU sedNoteTit les = freq _facilityG roupDefaul tData.d.ft p_frequent lyusednote titles;
  3302                         }
  3303                    }
  3304                    var  freq_newNo teTitle =  freq_ViaNo teTitleIEN  + "~~" +  freq_ViaNo teTitleDes cription;
  3305                    if ( freq_frequ entlyUsedN oteTitles  != null &&  freq_freq uentlyUsed NoteTitles  != "") {
  3306                         //Test for  duplicate s
  3307                         var freq_n oteTitleEx ist = freq _frequentl yUsedNoteT itles.inde xOf(freq_n ewNoteTitl e);
  3308                         if (freq_n oteTitleEx ist != -1)  {
  3309                             alert( "The selec ted Note T itle alrea dy exist o n the Freq uently Use d List");
  3310                             return  false;
  3311                         }
  3312                    }
  3313  
  3314                    //Up date exist ing CRM Fa cility Gro up Default  entity re cord
  3315                    //Cr eate the F acility Gr oup Defaul t object
  3316                    var  freq_facil ityGroupDe faultItem  = new Obje ct();
  3317                    if ( freq_frequ entlyUsedN oteTitles  == null ||  freq_freq uentlyUsed NoteTitles  == "") {
  3318                         //Add as f irst item
  3319                         freq_facil ityGroupDe faultItem. ftp_freque ntlyusedno tetitles =  freq_newN oteTitle;
  3320                    }
  3321                    else  {
  3322                         //Combine  with exist ing item
  3323                         freq_facil ityGroupDe faultItem. ftp_freque ntlyusedno tetitles =  freq_freq uentlyUsed NoteTitles  + "^^" +  freq_newNo teTitle;
  3324                    }
  3325                    //ma ke it a js on object
  3326                    var  jsonEntity  = JSON.st ringify(fr eq_facilit yGroupDefa ultItem);
  3327  
  3328                    $.aj ax({
  3329                         type: "POS T",
  3330                         contentTyp e: "applic ation/json ; charset= utf-8",
  3331                         datatype:  "json",
  3332                         url: vcmn_ serverUrl  + vcmn_crm OdataEndPo int + "/"  + 'ftp_fac ilitygroup defaultSet ' + "(guid '" + vcmn_ facilityGr oupDefault Id + "')",
  3333                         data: json Entity,
  3334                         beforeSend : function  (XMLHttpR equest) {
  3335                             XMLHtt pRequest.s etRequestH eader("X-H TTP-Method ", "MERGE" );
  3336                         },
  3337                         success: f unction (t extStatus,  XmlHttpRe quest) {
  3338                             alert( "The Selec ted Note T itle was a dded succe ssfully to  the Frequ ently Used  List.");
  3339                         },
  3340                         error: fun ction (Xml HttpReques t, textSta tus, error Thrown) {
  3341                             alert( 'Ajax Erro r in Updat e of Crm F acility Gr oup Defaul t entity:  ' + errorT hrown);
  3342                         }
  3343                    });
  3344                }
  3345                else if  (freq_butt onName ==  "FreqUsedL ocationBut ton") {
  3346                    //Lo cation but ton clicke d
  3347                    var  freq_ViaLo cationIEN  = Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat ionid").ge tValue();
  3348                    var  freq_ViaLo cationDesc ription =  Xrm.Page.g etAttribut e("ftp_sel ectedworkl oadlocatio ntext").ge tValue();
  3349                    if ( freq_ViaLo cationIEN  == null ||  freq_ViaL ocationIEN  == "" ||  freq_ViaLo cationDesc ription ==  null || f req_ViaLoc ationDescr iption ==  "") {
  3350                         alert("The  selected  Location i s not vali d, it can  not be add ed to the  Frequently  Used List !");
  3351                         return fal se;
  3352                    }
  3353                    //Pr ompt User  to add Loc ation
  3354                    var  freq_AddCo nfirm = fa lse;
  3355                    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?",
  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 Loc ation List
  3362                    var  freq_frequ entlyUsedL ocations =  null;
  3363                    var  freq_facil ityGroupDe faultData  = vcmn_get SingleEnti tyDataSync ('ftp_faci litygroupd efaultSet' , 'ftp_fre quentlyuse dlocations ', vcmn_fa cilityGrou pDefaultId );
  3364                    if ( freq_facil ityGroupDe faultData  != null) {
  3365                         if (freq_f acilityGro upDefaultD ata.d.ftp_ frequently usedlocati ons != nul l) {
  3366                             freq_f requentlyU sedLocatio ns = freq_ facilityGr oupDefault Data.d.ftp _frequentl yusedlocat ions;
  3367                         }
  3368                    }
  3369                    var  freq_newLo cation = f req_ViaLoc ationIEN +  "~~" + fr eq_ViaLoca tionDescri ption;
  3370                    if ( freq_frequ entlyUsedL ocations ! = null &&  freq_frequ entlyUsedL ocations ! = "") {
  3371                         //Test for  duplicate s
  3372                         var freq_l ocationExi st = freq_ frequently UsedLocati ons.indexO f(freq_new Location);
  3373                         if (freq_l ocationExi st != -1)  {
  3374                             alert( "The selec ted Locati on already  exist on  the Freque ntly Used  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 entlyUsedL ocations = = null ||  freq_frequ entlyUsedL ocations = = "") {
  3383                         //Add as f irst item
  3384                         freq_facil ityGroupDe faultItem. ftp_freque ntlyusedlo cations =  freq_newLo cation;
  3385                    }
  3386                    else  {
  3387                         //Combine  with exist ing item
  3388                         freq_facil ityGroupDe faultItem. ftp_freque ntlyusedlo cations =  freq_frequ entlyUsedL ocations +  "^^" + fr eq_newLoca tion;
  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 Locati on was add ed success fully to t he Frequen tly Used L ist.");
  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 {
  3411                    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!");
  3412                    retu rn false;
  3413                }
  3414           }
  3415           el se {
  3416                alert("T he Frequen tly Used b utton in u se has bee n defined  incorrectl y, please  contact yo ur system  administra tor!");
  3417                return f alse;
  3418           }
  3419       }
  3420       catch  (err) {
  3421           al ert('Progr ess Note F requently  Used Butto n Script F unction Er ror(freq_b uttonActio n): ' + er r.message) ;
  3422       }
  3423   }
  3424  
  3425  
  3426   function v cmn_execut eCrmOdataG etRequest( vcmn_jsonQ uery, vcmn _aSync, vc mn_aSyncCa llback, vc mn_skipCou nt, vcmn_o ptionArray ) {
  3427       //This  function  executes a  CRM Odata  web servi ce call to  retrieve  Crm data
  3428       //*vcm n_jsonQuer y* - a pro perly form atted CRM  Odata Quer y string ( required)
  3429       //*vcm n_aSync* -  specify ' true' to e xecute asy nchronousl y otherwis e 'false'  (required)
  3430       //*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 '')
  3431       //*vcm n_skipCoun t* - Initi al setting  is always  '0', incr ements by  50 per CRM  SDK Odata  standards  (required )
  3432       //*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)
  3433       try {
  3434           va r vcmn_ent ityData =  null;
  3435           $. ajax({
  3436                type: 'G ET',
  3437                contentT ype: 'appl ication/js on; charse t=utf-8',
  3438                datatype : 'json',
  3439                url: vcm n_jsonQuer y,
  3440                beforeSe nd: functi on (XMLHtt pRequest)  {
  3441                    XMLH ttpRequest .setReques tHeader('A ccept', 'a pplication /json');
  3442                },
  3443                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  3444                    vcmn _entityDat a = data;
  3445                    if ( vcmn_aSync  == true)  {
  3446                         vcmn_aSync Callback(v cmn_entity Data, vcmn _skipCount , vcmn_opt ionArray);
  3447                    }
  3448                },
  3449                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  3450                    aler t('Fail: A jax Error  in vcmn_ex ecuteCrmOd ataGetRequ est: ' + e rrorThrown  + " Reque st: " + vc mn_jsonQue ry);
  3451                },
  3452                async: v cmn_aSync,
  3453                cache: f alse
  3454           }) ;
  3455           re turn vcmn_ entityData ;
  3456       }
  3457       catch  (err) {
  3458           al ert('An er ror occure d in the v cmn_execut eCrmOdataG etRequest  function.   Error Det ail Messag e: ' + err );
  3459       }
  3460   }
  3461  
  3462   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) {
  3463       //This  function  returns a  CRM JSON d ataset for  all entit y records  matching c riteria pr ovided Asy ncronously
  3464       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  3465       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  3466       //*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
  3467       //*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'
  3468       //*vcm n_sortDire ction* - i s a string  specifyin g the sort  as Ascend ing or Des cending e. g. 'asc' o r 'desc'
  3469       //*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)
  3470       //*vcm n_aSyncCal lback* - i s the name  of the fu nction to  call when  returning  the result
  3471       //*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
  3472  
  3473       try {
  3474           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;
  3475           vc mn_execute CrmOdataGe tRequest(v cmn_jsonQu ery, true,  vcmn_aSyn cCallback,  vcmn_skip Count, vcm n_optionAr ray);
  3476       }
  3477       catch  (err) {
  3478           al ert('An er ror occure d in the v cmn_getMul tipleEntit yDataAsync  function.   Error De tail Messa ge: ' + er r);
  3479       }
  3480   }
  3481  
  3482   function v cmn_getSin gleEntityD ataSync(vc mn_entityS etName, vc mn_attribu teSet, vcm n_entityId ) {
  3483       //This  function  returns a  CRM JSON d ataset for  a single  entity rec ord based  on the ent ity id pro vided Sync ronously
  3484       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  3485       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  3486       //*vcm n_entityId * - is the  Guid for  the entity  record
  3487  
  3488       try {
  3489           va r vcmn_ent ityIdNoBra cket = vcm n_entityId .replace(/ ({|})/g, ' ');
  3490           va r vcmn_sel ectString  = '(guid'  + "'" + vc mn_entityI dNoBracket  + "'" + ' )?$select= ' + vcmn_a ttributeSe t;
  3491           va r vcmn_jso nQuery = v cmn_server Url + vcmn _crmOdataE ndPoint +  '/' + vcmn _entitySet Name + vcm n_selectSt ring;
  3492           va r vcmn_ent ityData =  vcmn_execu teCrmOdata GetRequest (vcmn_json Query, fal se, '', 0,  null);
  3493           re turn vcmn_ entityData ;
  3494       }
  3495       catch  (err) {
  3496           al ert('An er ror occure d in the v cmn_getSin gleEntityD ataSync fu nction.  E rror Detai l Message:  ' + err);
  3497       }
  3498   }
  3499  
  3500   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) {
  3501       //This  function  returns a  CRM JSON d ataset for  all entit y records  matching c riteria pr ovided Syn cronously
  3502       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  3503       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  3504       //*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
  3505       //*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'
  3506       //*vcm n_sortDire ction* - i s a string  specifyin g the sort  as Ascend ing or Des cending e. g. 'asc' o r 'desc'
  3507       //*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)
  3508  
  3509       try {
  3510           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;
  3511           va r vcmn_ent ityData =  vcmn_execu teCrmOdata GetRequest (vcmn_json Query, fal se, '', vc mn_skipCou nt, null);
  3512           re turn vcmn_ entityData ;
  3513       }
  3514       catch  (err) {
  3515           al ert('An er ror occure d in the v cmn_getMul tipleEntit yDataSync  function.   Error Det ail Messag e: ' + err );
  3516       }
  3517   }