59. EPMO Open Source Coordination Office Redaction File Detail Report

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

59.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_18.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Fri Jul 28 04:36:30 2017 UTC
2 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_18.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Thu Nov 30 17:19:34 2017 UTC

59.2 Comparison summary

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

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

59.4 Active regular expressions

No regular expressions were active.

59.5 Comparison detail

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