384. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 6/22/2018 1:29:28 PM Central Daylight 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.

384.1 Files compared

# Location File Last Modified
1 v1603_release_60.zip\CRM_solutions\VCCMResources.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Tue May 22 14:39:24 2018 UTC
2 v1603_release_60.zip\CRM_solutions\VCCMResources.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Wed Jun 20 16:38:27 2018 UTC

384.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 6 9918
Changed 5 10
Inserted 0 0
Removed 0 0

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

384.4 Active regular expressions

No regular expressions were active.

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