38. EPMO Open Source Coordination Office Redaction File Detail Report

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

38.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_10.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Fri May 5 04:06:48 2017 UTC
2 VCCM.zip\VCCM\CRM_solutions\VCCMResources\VCCMResources_1_0_0_10.zip\WebResources ftp_VistAMultiNoteFormScriptVistACPRSMultiProgressD9489705-E7FC-E511-9433-0050568D743D Thu Nov 30 17:18:22 2017 UTC

38.2 Comparison summary

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

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

38.4 Active regular expressions

No regular expressions were active.

38.5 Comparison detail

  1   //VistACPR SMultiProg ressNoteFo rmScript.j s
  2   //Contains  variables  and funct ions used  by the CRM  Form and  Ribbon
  3   //Requires  jQuery lo aded on th e CRM Form
  4   //The form  where thi s script l ibrary is  applied mu st have th e followin g form par ameters de fined
  5   /*
  6   parameter_ regardingo bjectid  -   Type:Uni queId
  7   parameter_ regardingo bjectidnam e  -  Type :SafeStrin g
  8   parameter_ regardingo bjectidtyp e  -  Type :SafeStrin g
  9   parameter_ triageexpe rt  -  Typ e:SafeStri ng
  10   parameter_ triageminu tes  -  Ty pe:Integer
  11   */
  12  
  13   //Static V ariables
  14   var vcmn_c rmOdataEnd Point = '/ XRMService s/2011/Org anizationD ata.svc';
  15   var vcmn_s erverUrl =  Xrm.Page. context.ge tClientUrl ();
  16  
  17   //var vcmn _NoteWrite Url = 'htt ps://qacrm dac.np.crm .vrm.vba. DNS     /WebParts/ DEV/api/no teswrite';     //OLD MANU AL DEV URL
  18   var vcmn_N oteWriteUr l = '';
  19   //var vcmn _eesummary URLbase =  'https://q acrmdac.np .crm.vrm.v ba. DNS     /WebParts/ QA/api/ees ummary/1.0 /xml/ftpCR M/';    //OLD MANU AL DEV URL
  20   var vcmn_e esummaryUR Lbase = '' ;
  21   //var vcmn _VistaUser sURLbase =  'https:// qacrmdac.n p.crm.vrm. vba. DNS     /WebParts/ DEV/api/Vi staUsers/1 .0/json/ft pCRM/john/ smith/1234 ?noFilter= true';    //OLD MANU AL DEV URL
  22   var vcmn_V istaUsersU RLbase = ' ';
  23   //var vcmn _AddSigner sUrl = 'ht tps://qacr mdac.np.cr m.vrm.vba. DNS     /WebParts/ DEV/api/VI A/AddSigne rs/1.0/jso n';    //OLD MANU AL DEV URL
  24   var vcmn_A ddSignersU rl = '';
  25  
  26   //Producti on Environ ment Indic ator
  27   var vcmn_I sProductio nEnvironme nt = false ;
  28  
  29   //Word Wra p Line Lim it
  30   var vcmn_W ordWrapLim it = 75;
  31  
  32   //Addition al Signers  Data
  33   var vcmn_A ddlSigners NameArray  = null;
  34   var vcmn_A ddlSigners IenArray =  null;
  35   var vcmn_l ocalStorag eVarName =  "";
  36  
  37   //Workload  Encounter  data
  38   var vcmn_P rogressNot eSubject =  'Progress  Note: ';
  39   var vcmn_T riageNoteS ubject = ' Triage Not e: ';
  40   var vcmn_W orkloadEnc ounterSubj ect = 'Wor kload Enco unter Note : ';
  41   var vcmn_i sWorkloadE ncounter =  false;
  42   var vcmn_m atchLookup Id = '';
  43  
  44   var vcmn_V iaLoginNam e = null;
  45   var vcmn_V iaLoginTok en = null;
  46   var vcmn_V iaLoginFac ility = nu ll;
  47   var vcmn_V iaPatientI d = null;
  48   var vcmn_V iaInPatien t = null;
  49   var vcmn_V iaCptCode  = null;
  50   var vcmn_V iaCptDescr iption = n ull;
  51   var vcmn_V iaDiagnosi sCode = nu ll;
  52   var vcmn_V iaDiagnosi sDescripti on = null;
  53  
  54   var vcmn_b aseService EndpointUr l = null;
  55   var vcmn_r equestingA pp = null;
  56   var vcmn_c onsumingAp pToken = n ull;
  57   var vcmn_c onsumingAp pPassword  = null;
  58  
  59   function v cmn_getQue ryVariable (vcmn_vari able) {
  60       try {
  61           // Get a Quer y Variable
  62           va r vcmn_que ry = windo w.location .search.su bstring(1) ;
  63           va r vcmn_var s = vcmn_q uery.split ("&");
  64           fo r (var i =  0; i < vc mn_vars.le ngth; i++)  {
  65                var vcmn _pair = vc mn_vars[i] .split("=" );
  66                if (vcmn _pair[0] = = vcmn_var iable) {
  67                    retu rn decodeU RIComponen t(vcmn_pai r[1]);
  68                }
  69           }
  70           re turn "";
  71       }
  72       catch  (err) {
  73           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getQ ueryVariab le): ' + e rr.message );
  74       }
  75   }
  76  
  77   function v cmn_setSim pleLookupV alue(vcmn_ LookupId,  vcmn_Type,  vcmn_Id,  vcmn_Name)  {
  78       try {
  79           // Sets the v alue for l ookup attr ibutes tha t accept o nly a sing le entity  reference.
  80           va r vcmn_loo kupReferen ce = [];
  81           vc mn_lookupR eference[0 ] = {};
  82           vc mn_lookupR eference[0 ].id = vcm n_Id;
  83           vc mn_lookupR eference[0 ].entityTy pe = vcmn_ Type;
  84           vc mn_lookupR eference[0 ].name = v cmn_Name;
  85           Xr m.Page.get Attribute( vcmn_Looku pId).setVa lue(vcmn_l ookupRefer ence);
  86       }
  87       catch  (err) {
  88           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_setS impleLooku pValue): '  + err.mes sage);
  89       }
  90   }
  91  
  92   function v cmn_conver tCrmDateTo VistADate( vcmn_crmDa te) {
  93       try {
  94           va r vcmn_Vis tADate = n ull;
  95           if  (vcmn_crm Date != nu ll) {
  96                var vcmn _crmYear =  (vcmn_crm Date.getFu llYear()). toString() ;
  97                var vcmn _crmMonth  = '00';
  98                if ((vcm n_crmDate. getMonth()  + 1) < 10 ) {
  99                    vcmn _crmMonth  = '0' + (v cmn_crmDat e.getMonth () + 1).to String();
  100                }
  101                else {
  102                    vcmn _crmMonth  = (vcmn_cr mDate.getM onth() + 1 ).toString ();
  103                }
  104                var vcmn _crmDay =  '00';
  105                if ((vcm n_crmDate. getDate())  < 10) {
  106                    vcmn _crmDay =  '0' + (vcm n_crmDate. getDate()) .toString( );
  107                }
  108                else {
  109                    vcmn _crmDay =  (vcmn_crmD ate.getDat e()).toStr ing();
  110                }
  111                var vcmn _crmHours  = '00';
  112                if ((vcm n_crmDate. getHours() ) < 10) {
  113                    vcmn _crmHours  = '0' + (v cmn_crmDat e.getHours ()).toStri ng();
  114                }
  115                else {
  116                    vcmn _crmHours  = (vcmn_cr mDate.getH ours()).to String();
  117                }
  118                var vcmn _crmMinute s = '00';
  119                if ((vcm n_crmDate. getMinutes ()) < 10)  {
  120                    vcmn _crmMinute s = '0' +  (vcmn_crmD ate.getMin utes()).to String();
  121                }
  122                else {
  123                    vcmn _crmMinute s = (vcmn_ crmDate.ge tMinutes() ).toString ();
  124                }
  125                var vcmn _crmSecond s = '00';
  126                if ((vcm n_crmDate. getSeconds ()) < 10)  {
  127                    vcmn _crmSecond s = '0' +  (vcmn_crmD ate.getSec onds()).to String();
  128                }
  129                else {
  130                    vcmn _crmSecond s = (vcmn_ crmDate.ge tSeconds() ).toString ();
  131                }
  132  
  133                //Create  VistA Dat e
  134                vcmn_Vis tADate = v cmn_crmYea r + vcmn_c rmMonth +  vcmn_crmDa y + vcmn_c rmHours +  vcmn_crmMi nutes + vc mn_crmSeco nds;
  135           }
  136           re turn vcmn_ VistADate;
  137       }
  138       catch  (err) {
  139           al ert('Progr ess Note E rror(vcmn_ convertCrm DateToVist ADate): '  + err.mess age);
  140           re turn null;
  141       }
  142   }
  143  
  144   function v cmn_decryp tServiceCo nnector(vc mn_connect orArray, v cmn_connec torValue)  {
  145       var vc mn_decrypt edString =  "";
  146       if (vc mn_connect orArray !=  null && v cmn_connec torArray ! = "") {
  147           va r vcmn_new Array = vc mn_connect orArray.to String().s plit(',');
  148           vc mn_newArra y.reverse( );
  149           fo r (i = 0;  i < vcmn_n ewArray.le ngth; i++)  {
  150                var vcmn _curChar =  "";
  151                if (i ==  0) {
  152                    vcmn _curChar =  vcmn_newA rray[i] -  vcmn_conne ctorValue;
  153                }
  154                else {
  155                    vcmn _curChar =  vcmn_newA rray[i] -  (i + vcmn_ connectorV alue);
  156                }
  157                vcmn_dec ryptedStri ng = vcmn_ decryptedS tring + St ring.fromC harCode(vc mn_curChar );
  158           }
  159       }
  160       return  vcmn_decr yptedStrin g;
  161   }
  162  
  163   function v cmn_UserHa sTeam(team Name, user Guid) {
  164       try {
  165           va r vcmn_tea mid = null ;
  166           va r vcmn_cur rentUserId  = userGui d;
  167           va r vcmn_con ditionalFi lter = "(N ame eq '"  + teamName  + "')";
  168           va r vcmn_tea mData = vc mn_getMult ipleEntity DataSync(' TeamSet',  'TeamId',  vcmn_condi tionalFilt er, 'Name' , 'asc', 0 );
  169           if  (vcmn_tea mData != n ull) {
  170                for (var  i = 0; i  <= vcmn_te amData.d.r esults.len gth - 1; i ++) {
  171                    //Ge t Info
  172                    if ( vcmn_teamD ata.d.resu lts[i].Tea mId != nul l) { vcmn_ teamid = v cmn_teamDa ta.d.resul ts[i].Team Id; }
  173                    brea k;
  174                }
  175           }
  176           // If Team ex ists, chec k if the c urrent use r is part  of that te am
  177           va r vcmn_tea mMembershi pId = null ;
  178           if  (vcmn_tea mid != nul l && vcmn_ currentUse rId != nul l) {
  179                var vcmn _condition alFilter =  "(TeamId  eq (guid'"  + vcmn_te amid + "')  and Syste mUserId eq  (guid'" +  vcmn_curr entUserId  + "'))";
  180                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);
  181                if (vcmn _teamMembe rshipData  != null) {
  182                    for  (var i = 0 ; i <= vcm n_teamMemb ershipData .d.results .length -  1; i++) {
  183                         //Get Info
  184                         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; }
  185                         break;
  186                    }
  187                }
  188           }
  189           if  (vcmn_tea mMembershi pId != nul l) { retur n true; }
  190  
  191           // otherwise  return fal se                 
  192           re turn false ;
  193       }
  194       catch  (err) {
  195           // Display Er ror
  196           al ert("An er ror occure d in the v cmn_UserHa sTeam func tion.  Err or Detail  Message: "  + err);
  197       }
  198   }
  199  
  200   function v cmn_Settin gsWebServi ceURL_resp onse(vcmn_ settingDat a, vcmn_la stSkip, vc mn_NoteWri teUrl_NA)  {
  201       try {
  202           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  203           va r vcmn_Dac Url = null ;
  204           va r vcmn_Not esWriteApi Url = null ;
  205           va r vcmn_ees ummaryApiU rl = null;
  206           va r vcmn_Vis taUserApiU rl = null;
  207           va r vcmn_Via AddlSigner sApiUrl =  null;
  208  
  209           fo r (var i =  0; i <= v cmn_settin gData.d.re sults.leng th - 1; i+ +) {
  210                //Get in fo
  211                if (vcmn _settingDa ta.d.resul ts[i].ftp_ DACURL !=  null) { vc mn_DacUrl  = vcmn_set tingData.d .results[i ].ftp_DACU RL; }
  212                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; }
  213                if (vcmn _settingDa ta.d.resul ts[i].ftp_ ESRAPIURL  != null) {  vcmn_eesu mmaryApiUr l = vcmn_s ettingData .d.results [i].ftp_ES RAPIURL; }
  214                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; }
  215                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; }
  216                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 ; }
  217                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 ; }
  218                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; }
  219                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; }
  220                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; }
  221                break;
  222           }
  223  
  224           if  (vcmn_Dac Url != nul l && vcmn_ NotesWrite ApiUrl !=  null) {
  225                //Constr uct full w eb service  URL
  226                vcmn_Not eWriteUrl  = vcmn_Dac Url + vcmn _NotesWrit eApiUrl;
  227           }
  228           el se {
  229                Xrm.Page .ui.setFor mNotificat ion("ERROR : THE VIST A NOTES WR ITE SERVIC E URL IS M ISSING, PL EASE CONTA CT TECHNIC AL SUPPORT !", "ERROR ", "VISTAS ERVICE");
  230           }
  231           if  (vcmn_Dac Url != nul l && vcmn_ eesummaryA piUrl != n ull) {
  232                //Constr uct full w eb service  URL
  233                vcmn_ees ummaryURLb ase = vcmn _DacUrl +  vcmn_eesum maryApiUrl ;
  234           }
  235           el se {
  236                Xrm.Page .ui.setFor mNotificat ion("ERROR : THE EESU MMARY SERV ICE URL IS  MISSING,  PLEASE CON TACT TECHN ICAL SUPPO RT!", "ERR OR", "VIST ASERVICE") ;
  237           }
  238           if  (vcmn_Dac Url != nul l && vcmn_ VistaUserA piUrl != n ull) {
  239                //Constr uct full w eb service  URL
  240                vcmn_Vis taUsersURL base = vcm n_DacUrl +  vcmn_Vist aUserApiUr l;
  241           }
  242           el se {
  243                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 ");
  244           }
  245           if  (vcmn_Dac Url != nul l && vcmn_ ViaAddlSig nersApiUrl  != null)  {
  246                //Constr uct full w eb service  URL
  247                vcmn_Add SignersUrl  = vcmn_Da cUrl + vcm n_ViaAddlS ignersApiU rl;
  248           }
  249           el se {
  250                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");
  251           }
  252  
  253           if  (vcmn_bas eServiceEn dpointUrl  == null ||  vcmn_requ estingApp  == null ||  vcmn_cons umingAppTo ken == nul l || vcmn_ consumingA ppPassword  == null)  {
  254                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");
  255           }
  256           // Decrypt VI A Service  Connector  Items
  257           vc mn_request ingApp = v cmn_decryp tServiceCo nnector(vc mn_request ingApp, 4) ;
  258           vc mn_consumi ngAppToken  = vcmn_de cryptServi ceConnecto r(vcmn_con sumingAppT oken, 6);
  259           vc mn_consumi ngAppPassw ord = vcmn _decryptSe rviceConne ctor(vcmn_ consumingA ppPassword , 8);
  260  
  261           // Proceed wi th Form Lo ad logic w ith URL
  262           vc mn_newProg ressNoteLo ad_WebURL( );
  263       }
  264       catch  (err) {
  265           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_Sett ingsWebSer viceURL_re sponse): '  + err.mes sage);
  266       }
  267   }
  268  
  269   function v cmn_newPro gressNoteL oad() {
  270       try {
  271           // GET CRM SE TTINGS WEB  SERVICE U RLS
  272           va r vcmn_con ditionalFi lter = "(m cs_name eq  'Active S ettings')" ;
  273           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', vcm n_conditio nalFilter,  'mcs_name ', 'asc',  0, vcmn_Se ttingsWebS erviceURL_ response,  vcmn_NoteW riteUrl);
  274       }
  275       catch  (err) {
  276           // Display Er ror
  277           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_newP rogressNot eLoad): '  + err.mess age);
  278       }
  279   }
  280  
  281   function v cmn_newPro gressNoteL oad_WebURL () {
  282       try {
  283           // Check if m arked as a  workload  encounter
  284           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) == true)  {
  285                vcmn_isW orkloadEnc ounter = t rue;
  286                Xrm.Page .ui.tabs.g et('Tab_Wo rkloadEnco unter').se tVisible(t rue);
  287                Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itletext") .setRequir edLevel("r equired");
  288                Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat iontext"). setRequire dLevel("re quired");
  289                Xrm.Page .getAttrib ute("ftp_w orkloadinp atient").s etRequired Level("req uired");
  290                //Set Si gn this no te to Yes
  291                Xrm.Page .getAttrib ute('ftp_s ignthisnot e').setVal ue(1000000 01);
  292                Xrm.Page .getAttrib ute('ftp_s ignthisnot e').setSub mitMode('a lways');
  293           }
  294           el se {
  295                vcmn_isW orkloadEnc ounter = f alse;
  296                Xrm.Page .ui.tabs.g et('Tab_Wo rkloadEnco unter').se tVisible(f alse);
  297                Xrm.Page .getAttrib ute("ftp_s electedwor kloadnotet itletext") .setRequir edLevel("n one");
  298                Xrm.Page .getAttrib ute("ftp_s electedwor kloadlocat iontext"). setRequire dLevel("no ne");
  299                Xrm.Page .getAttrib ute("ftp_w orkloadinp atient").s etRequired Level("non e");
  300           }
  301  
  302           // Only handl e forms in  create st ate
  303           if  (Xrm.Page .ui.getFor mType() !=  1) { retu rn false;  }
  304  
  305           // Set defaul t values b ased on th e current  user's USD  Config an d Facility
  306           va r vcmn_cur rentUserId  = Xrm.Pag e.context. getUserId( );
  307           va r vcmn_cur rentUserDa ta = vcmn_ getSingleE ntityDataS ync('Syste mUserSet',  'msdyusd_ USDConfigu rationId,  ftp_Facili tySiteId',  vcmn_curr entUserId) ;
  308           if  (vcmn_cur rentUserDa ta != null ) {
  309                if (vcmn _currentUs erData.d.m sdyusd_USD Configurat ionId != n ull) {
  310                    if ( vcmn_curre ntUserData .d.msdyusd _USDConfig urationId. Id != null ) {
  311                         if (vcmn_c urrentUser Data.d.ftp _FacilityS iteId != n ull) {
  312                             if (vc mn_current UserData.d .ftp_Facil itySiteId. Id != null ) {
  313                                 // Data Requi red to loo kup Facili ty Group D efaults ar e present
  314                                 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 + "')";
  315                                 vc mn_getMult ipleEntity DataAsync( 'ftp_facil itygroupde faultSet',  'ftp_loca lnotestitl e, ftp_hos pitallocat ion', vcmn _condition alFilter,  'ftp_name' , 'asc', 0 , vcmn_fac ilityGroup Default_re sponse, vc mn_current UserData.d .ftp_Facil itySiteId. Id);
  316                             }
  317                         }
  318                    }
  319                }
  320           }
  321  
  322           // Determine  if regardi ng field i s prefille d (added b y subgrid+ )
  323           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  324           va r vcmn_tri ageexpert  = null;
  325           va r vcmn_tri ageminutes  = null;
  326           if  (vcmn_req uestId ==  null) {
  327                //Get cu stom param eters pass ed to the  form
  328                var vcmn _regarding objectid =  vcmn_getQ ueryVariab le("parame ter_regard ingobjecti d");
  329                var vcmn _regarding objectidna me = vcmn_ getQueryVa riable("pa rameter_re gardingobj ectidname" );
  330                var vcmn _regarding objectidty pe = vcmn_ getQueryVa riable("pa rameter_re gardingobj ectidtype" );
  331                vcmn_tri ageexpert  = vcmn_get QueryVaria ble("param eter_triag eexpert");
  332                vcmn_tri ageminutes  = vcmn_ge tQueryVari able("para meter_tria geminutes" );
  333  
  334                if (vcmn _regarding objectid = = '' || vc mn_regardi ngobjectid  == null | | vcmn_reg ardingobje ctidname = = '' || vc mn_regardi ngobjectid name == nu ll ||
  335                    vcmn _regarding objectidty pe == '' | | vcmn_reg ardingobje ctidtype = = null) {  return fal se; }
  336           }
  337           el se {
  338                var vcmn _regarding objectid =  vcmn_requ estId[0].i d;
  339                var vcmn _regarding objectidna me = vcmn_ requestId[ 0].name;
  340                var vcmn _regarding objectidty pe = vcmn_ requestId[ 0].entityT ype;
  341           }
  342           if  (vcmn_tri ageexpert  == null) {  vcmn_tria geexpert =  'NO'; }
  343           if  (vcmn_tri ageminutes  == null)  { vcmn_tri ageminutes  = 0; }
  344  
  345           // Populate r egarding o bject
  346           vc mn_setSimp leLookupVa lue('regar dingobject id', vcmn_ regardingo bjectidtyp e, vcmn_re gardingobj ectid, vcm n_regardin gobjectidn ame);
  347           Xr m.Page.get Attribute( 'regarding objectid') .setSubmit Mode('alwa ys');
  348  
  349           // Prompt use r if progr ess note i s a worklo ad encount er
  350           Xr m.Utility. confirmDia log(
  351                "Is this  note a Wo rkload Enc ounter?, S elect OK i f Yes, oth erwise CAN CEL.",
  352                function  () {
  353                    Xrm. Page.getAt tribute('f tp_isworkl oadencount er').setVa lue(true);
  354                    Xrm. Page.getAt tribute('f tp_isworkl oadencount er').setSu bmitMode(' always');
  355                    //Di splay work load encou nter tab a nd other i nfo accord ingly...
  356                    Xrm. Page.ui.ta bs.get('Ta b_Workload Encounter' ).setVisib le(true);
  357                    vcmn _isWorkloa dEncounter  = true;
  358                    Xrm. Page.getAt tribute("f tp_selecte dworkloadn otetitlete xt").setRe quiredLeve l("require d");
  359                    Xrm. Page.getAt tribute("f tp_selecte dworkloadl ocationtex t").setReq uiredLevel ("required ");
  360                    Xrm. Page.getAt tribute("f tp_workloa dinpatient ").setRequ iredLevel( "required" );
  361                }
  362           );
  363  
  364           // Populate s ubject wit h regardin g objects  title
  365           Xr m.Page.get Attribute( 'subject') .setValue( vcmn_Progr essNoteSub ject + vcm n_regardin gobjectidn ame);
  366           if  (vcmn_tri ageexpert  == 'YES')  { Xrm.Page .getAttrib ute('subje ct').setVa lue(vcmn_T riageNoteS ubject + v cmn_regard ingobjecti dname); }
  367           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); }
  368           Xr m.Page.get Attribute( 'subject') .setSubmit Mode('alwa ys');
  369           // Default Sa ve to CPPR S
  370           Xr m.Page.get Attribute( 'ftp_savet ovista').s etValue(10 0000001);  //Yes
  371           Xr m.Page.get Attribute( 'ftp_savet ovista').s etSubmitMo de('always ');
  372  
  373           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  374  
  375           // Populate f orm with r elated CRM  data
  376           va r vcmn_sub ReasonId =  null; //R eference t o the Reas on for Req uest Sub R eason
  377           va r vcmn_min orReasonId  = null;   //Referenc e to the R eason for  Request Mi nor Reason
  378           va r vcmn_sub ReasonTemp lateText =  null;
  379           va r vcmn_min orReasonTe mplateText  = null;
  380           va r vcmn_min orReasonNo teSubText  = null;
  381  
  382           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'ftp_ CallbackNu mber, ftp_ ReasonforR equest, ft p_SubReaso nId, ftp_M inorReason Id, Descri ption, Cus tomerId, f tp_LastFil led, ftp_Q uantityRep ortsTaking , ftp_RxNu mber, ftp_ RxRefillQu antity, ft p_Tracking Number, ft p_OpiodAgr eementOnfi le, ftp_UD Sonfile, f tp_StateDr ugMonitori ngReport,  ftp_spdmps tateonfile , ftp_SPDM PState2, f tp_pickupm ethod, ftp _earlyrefi llcomment,  ftp_quant itytaking,  ftp_vacat ionstart,  ftp_vacati onend', vc mn_regardi ngobjectid );
  383           if  (vcmn_req uestData ! = null) {
  384                if (vcmn _requestDa ta.d.ftp_C allbackNum ber != nul l) {
  385                    Xrm. Page.getAt tribute('f tp_callbac knumber'). setValue(v cmn_reques tData.d.ft p_Callback Number);
  386                    Xrm. Page.getAt tribute('f tp_callbac knumber'). setSubmitM ode('alway s');
  387                }
  388                if (vcmn _requestDa ta.d.ftp_R easonforRe quest != n ull) {
  389                    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);
  390                    Xrm. Page.getAt tribute('f tp_reasonf orrequest' ).setSubmi tMode('alw ays');
  391                }
  392  
  393                if (vcmn _requestDa ta.d.ftp_R easonforRe quest.Name  == "Pharm acy Outbou nd Call")  {
  394                    if ( typeof out boundTempl ate_buildN oteText ==  "function ") {
  395                         outboundTe mplate_bui ldNoteText ();
  396                    }
  397                }
  398                else {
  399                    if ( vcmn_reque stData.d.f tp_SubReas onId != nu ll) {
  400                         vcmn_subRe asonId = v cmn_reques tData.d.ft p_SubReaso nId.Id;
  401                         if (vcmn_s ubReasonId  != null)  {
  402                             //Get  Template T ext
  403                             var vc mn_subreas onData = v cmn_getSin gleEntityD ataSync('f tp_subreas onSet', 'f tp_notetex t', vcmn_s ubReasonId );
  404                             if (vc mn_subreas onData.d.f tp_notetex t != null)  {
  405                                 vc mn_subReas onTemplate Text = vcm n_subreaso nData.d.ft p_notetext ;
  406                             }
  407                         }
  408                    }
  409                    if ( vcmn_reque stData.d.f tp_MinorRe asonId !=  null) {
  410                         vcmn_minor ReasonId =  vcmn_requ estData.d. ftp_MinorR easonId.Id ;
  411                         if (vcmn_m inorReason Id != null ) {
  412                             //Get  Template T ext
  413                             var vc mn_minorre asonData =  vcmn_getS ingleEntit yDataSync( 'ftp_minor reasonSet' , 'ftp_nam e, ftp_not etext', vc mn_minorRe asonId);
  414                             if (vc mn_minorre asonData.d .ftp_name  != null) {
  415                                 vc mn_minorRe asonTempla teText = v cmn_minorr easonData. d.ftp_name ;
  416                             }
  417                             if (vc mn_minorre asonData.d .ftp_notet ext != nul l) {
  418                                 vc mn_minorRe asonNoteSu bText = vc mn_minorre asonData.d .ftp_notet ext;
  419                             }
  420                         }
  421                    }
  422  
  423                    if ( vcmn_reque stData.d.C ustomerId  != null) {
  424                         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);
  425                         Xrm.Page.g etAttribut e('ftp_pat ient').set SubmitMode ('always') ;
  426                         //Set as v eteran id
  427                         vcmn_veter anId = vcm n_requestD ata.d.Cust omerId.Id
  428                    }
  429  
  430                    //Co nstruct Te mplate Not e
  431                    var  vcmn_subRe asonName =  null;
  432                    var  vcmn_templ ateNote =  "";
  433                    var  vcmn_lastF illed = "" ;
  434                    var  vcmn_quant ityReports Taking = n ull;
  435                    var  vcmn_rxNum ber = null ;
  436                    var  vcmn_rxRef illQuantit y = null;
  437                    var  vcmn_track ingNumber  = null;
  438                    var  vcmn_opioi dAgreement Onfile = n ull;
  439                    var  vcmn_UDSon file = nul l;
  440                    var  vcmn_state DrugMonito ringReport  = null;
  441                    var  vcmn_spdmp stateonfil e = null;
  442                    var  vcmn_sPDMP State2 = n ull;
  443                    var  vcmn_picku pmethod =  null;
  444  
  445                    var  vcmn_early RefillComm ent = null ;
  446                    var  vcmn_quant ityTaking  = null;
  447                    var  vcmn_vacat ionStart =  null;
  448                    var  vcmn_vacat ionEnd = n ull;
  449  
  450                    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) ); }
  451                    if ( vcmn_reque stData.d.f tp_Quantit yReportsTa king != nu ll) { vcmn _quantityR eportsTaki ng = vcmn_ requestDat a.d.ftp_Qu antityRepo rtsTaking;  }
  452                    if ( vcmn_reque stData.d.f tp_RxNumbe r != null)  { vcmn_rx Number = v cmn_reques tData.d.ft p_RxNumber ; }
  453                    if ( vcmn_reque stData.d.f tp_RxRefil lQuantity  != null) {  vcmn_rxRe fillQuanti ty = vcmn_ requestDat a.d.ftp_Rx RefillQuan tity; }
  454                    if ( vcmn_reque stData.d.f tp_Trackin gNumber !=  null) { v cmn_tracki ngNumber =  vcmn_requ estData.d. ftp_Tracki ngNumber;  }
  455                    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; }
  456                    if ( vcmn_reque stData.d.f tp_UDSonfi le != null ) { vcmn_U DSonfile =  vcmn_requ estData.d. ftp_UDSonf ile.Value;  }
  457                    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; }
  458                    if ( vcmn_reque stData.d.f tp_spdmpst ateonfile  != null) {  vcmn_spdm pstateonfi le = vcmn_ requestDat a.d.ftp_sp dmpstateon file.Value ; }
  459                    if ( vcmn_reque stData.d.f tp_SPDMPSt ate2 != nu ll) { vcmn _sPDMPStat e2 = vcmn_ requestDat a.d.ftp_SP DMPState2. Value; }
  460                    if ( vcmn_reque stData.d.f tp_pickupm ethod != n ull) { vcm n_pickupme thod = vcm n_requestD ata.d.ftp_ pickupmeth od.Value;  }
  461  
  462                    if ( vcmn_reque stData.d.f tp_earlyre fillcommen t != null)  { vcmn_ea rlyRefillC omment = v cmn_reques tData.d.ft p_earlyref illcomment ; }
  463                    if ( vcmn_reque stData.d.f tp_quantit ytaking !=  null) { v cmn_quanti tyTaking =  vcmn_requ estData.d. ftp_quanti tytaking;  }
  464                    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)) ; }
  465                    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)); }
  466  
  467                    if ( vcmn_reque stData.d.f tp_SubReas onId != nu ll) {
  468                         vcmn_subRe asonId = v cmn_reques tData.d.ft p_SubReaso nId.Id;
  469                         vcmn_subRe asonName =  vcmn_requ estData.d. ftp_SubRea sonId.Name ;
  470  
  471                         if (vcmn_s ubReasonNa me == 'Reg ular') {
  472                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Veter an is requ esting a R ENEWAL." +  "\n\n";
  473                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Last  Filled: "  + vcmn_las tFilled +  "\n\n";
  474                             if (vc mn_minorRe asonTempla teText !=  null) {
  475                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  476                             }
  477                             if (vc mn_minorRe asonNoteSu bText != n ull) {
  478                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonNoteSu bText + "\ n\n";
  479                             }
  480                             if (vc mn_subReas onTemplate Text != nu ll) {
  481                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_subReas onTemplate Text + "\n \n";
  482                             }
  483                         }
  484  
  485                         if (vcmn_s ubReasonNa me == 'Ear ly') {
  486                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Veter an is requ esting EAR LY FILL."  + "\n\n";
  487                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Last  Filled: "  + vcmn_las tFilled +  "\n\n";
  488                             if (vc mn_minorRe asonTempla teText !=  null) {
  489                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  490                             }
  491  
  492                             if (vc mn_quantit yTaking !=  null) {
  493                                 vc mn_templat eNote = vc mn_templat eNote + "Q uantity Ta king: " +  vcmn_quant ityTaking  + "\n\n";
  494                             }
  495  
  496                             if (vc mn_vacatio nStart !=  null && vc mn_vacatio nEnd != nu ll) {
  497                                 vc mn_templat eNote = vc mn_templat eNote + "V eteran Lea ving Town:  " + vcmn_ vacationSt art + ' -  ' + vcmn_v acationEnd  + "\n\n";
  498                             }
  499  
  500                             if (vc mn_minorRe asonNoteSu bText != n ull) {
  501                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonNoteSu bText + "\ n\n";
  502                             }
  503                             if (vc mn_subReas onTemplate Text != nu ll) {
  504                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_subReas onTemplate Text + "\n \n";
  505                             }
  506                         }
  507  
  508                         if (vcmn_s ubReasonNa me == 'Los t') {
  509                             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";
  510                             if (vc mn_rxNumbe r != null)  {
  511                                 vc mn_templat eNote = vc mn_templat eNote + "R X#: " + vc mn_rxNumbe r + "\n\n" ;
  512                             }
  513                             if (vc mn_rxRefil lQuantity  != null) {
  514                                 vc mn_templat eNote = vc mn_templat eNote + "R x Refill Q uantity: "  + vcmn_rx RefillQuan tity + "\n \n";
  515                             }
  516                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Last  Filled: "  + vcmn_las tFilled +  "\n\n";
  517                             if (vc mn_minorRe asonTempla teText !=  null) {
  518                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  519                             }
  520                             if (vc mn_trackin gNumber !=  null) {
  521                                 vc mn_templat eNote = vc mn_templat eNote + "T racking Nu mber: " +  vcmn_track ingNumber  + "\n\n";
  522                             }
  523                             if (vc mn_minorRe asonNoteSu bText != n ull) {
  524                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonNoteSu bText + "\ n\n";
  525                             }
  526                             if (vc mn_subReas onTemplate Text != nu ll) {
  527                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_subReas onTemplate Text + "\n \n";
  528                             }
  529                         }
  530  
  531                         if (vcmn_s ubReasonNa me == 'Sto len') {
  532                             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";
  533                             vcmn_t emplateNot e = vcmn_t emplateNot e + "Last  Filled: "  + vcmn_las tFilled +  "\n\n";
  534                             if (vc mn_minorRe asonTempla teText !=  null) {
  535                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonTempla teText + " \n\n";
  536                             }
  537                             if (vc mn_minorRe asonNoteSu bText != n ull) {
  538                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_minorRe asonNoteSu bText + "\ n\n";
  539                             }
  540                             if (vc mn_subReas onTemplate Text != nu ll) {
  541                                 vc mn_templat eNote = vc mn_templat eNote + vc mn_subReas onTemplate Text + "\n \n";
  542                             }
  543                         }
  544  
  545                         //If Templ ate Text w as populat ed, fill i n addition al info...
  546                         if (vcmn_t emplateNot e != '') {
  547                             vcmn_t emplateNot e = vcmn_t emplateNot e + "\n___ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ _____\n\n" ;
  548                             //Is a n Opioid A greement c urrent and  onfile?
  549                             if (vc mn_opioidA greementOn file != nu ll) {
  550                                 vc mn_templat eNote = vc mn_templat eNote + "C onsent for  Long-Term  Opioid Th erapy for  Pain:\n";
  551                                 if  (vcmn_opi oidAgreeme ntOnfile = = 10000000 0) {
  552                                      //Yes Op tion
  553                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Yes  - See Pos tings\n\n" ;
  554                                 }
  555                                 if  (vcmn_opi oidAgreeme ntOnfile = = 10000000 1) {
  556                                      //No Opt ion
  557                                      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";
  558                                 }
  559                             }
  560                             //Is v alid Urine  Drug Scre en on-file ?
  561                             if (vc mn_UDSonfi le != null ) {
  562                                 vc mn_templat eNote = vc mn_templat eNote + "I s valid Ur ine Drug S creen on-f ile?\n";
  563                                 if  (vcmn_UDS onfile ==  100000000)  {
  564                                      //Yes Op tion
  565                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Yes  - See Pos tings\n\n" ;
  566                                 }
  567                                 if  (vcmn_UDS onfile ==  100000001)  {
  568                                      //No Opt ion
  569                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] No  - Veteran  does not h ave a vali d Urine Dr ug Screen  on-file.\n \n";
  570                                 }
  571                             }
  572                             //Stat e Drug Mon itoring Re port?
  573                             if (vc mn_stateDr ugMonitori ngReport ! = null) {
  574                                 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";
  575                                 if  (vcmn_sta teDrugMoni toringRepo rt == 1000 00000) {
  576                                      //Positi ve Option
  577                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Pos itive - se e SPDMP no te.\n\n";
  578                                 }
  579                                 if  (vcmn_sta teDrugMoni toringRepo rt == 1000 00001) {
  580                                      //Negati ve Option
  581                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Neg ative.\n\n ";
  582                                 }
  583                                 if  (vcmn_sta teDrugMoni toringRepo rt == 1000 00002) {
  584                                      //Not on  File Opti on
  585                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Non e on file,  Pharmacy  to request .\n\n";
  586                                 }
  587                                 // Add in Sta tes (2), c onvert int egers to s tate names  from form 's hidden  state opti ons
  588                                 va r vcmn_usS tatesOptio ns = Xrm.P age.getAtt ribute("ft p_usstates option").g etOptions( );
  589                                 va r vcmn_sta teList = " ";
  590                                 if  (vcmn_spd mpstateonf ile != nul l) {
  591                                      //find t ext value  for option
  592                                      $(vcmn_u sStatesOpt ions).each (function  (i, e) {
  593                                          var  vcmn_optio nText = $( this)[0].t ext;
  594                                          var  vcmn_optio nValue = $ (this)[0]. value;
  595                                          if ( vcmn_spdmp stateonfil e == vcmn_ optionValu e) { vcmn_ stateList  = vcmn_opt ionText; }
  596                                      });
  597                                 }
  598                                 if  (vcmn_sPD MPState2 ! = null) {
  599                                      //find t ext value  for option
  600                                      $(vcmn_u sStatesOpt ions).each (function  (i, e) {
  601                                          var  vcmn_optio nText = $( this)[0].t ext;
  602                                          var  vcmn_optio nValue = $ (this)[0]. value;
  603                                          if ( vcmn_sPDMP State2 ==  vcmn_optio nValue) {  vcmn_state List = vcm n_stateLis t + ", " +  vcmn_opti onText; }
  604                                      });
  605                                 }
  606                                 if  (vcmn_sta teList !=  "") {
  607                                      //Add st ates list  to note
  608                                      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;
  609                                 }
  610                             }
  611  
  612                             //If f tp_pickupm ethod has  a value
  613                             if (vc mn_pickupm ethod != n ull) {
  614                                 vc mn_templat eNote = vc mn_templat eNote + "\ n_________ __________ __________ __________ __________ __________ __________ __________ __________ __________ __________ _________\ n\n";
  615                                 vc mn_templat eNote = vc mn_templat eNote + "V eteran req uested Met hod of Pic k Up:  ";
  616                                 if  (vcmn_pic kupmethod  == 1000000 00) {
  617                                      //Mail O ption
  618                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Mai l. \n\n";
  619                                 }
  620                                 if  (vcmn_pic kupmethod  == 1000000 01) {
  621                                      //Window  Option
  622                                      vcmn_tem plateNote  = vcmn_tem plateNote  + "[X] Win dow. \n\n" ;
  623                                 }
  624                                 // Get vetera n's curren t address
  625                                 if  (vcmn_vet eranId !=  null) {
  626                                      var vcmn _contactDa ta = vcmn_ getSingleE ntityDataS ync('Conta ctSet', 'A ddress1_Co mposite',  vcmn_veter anId);
  627                                      if (vcmn _contactDa ta != null ) {
  628                                          if ( vcmn_conta ctData.d.A ddress1_Co mposite !=  null && v cmn_contac tData.d.Ad dress1_Com posite !=  '') {
  629                                               vcmn_templ ateNote =  vcmn_templ ateNote +  "Address c onfirmed w ith caller : \n";
  630                                               vcmn_templ ateNote =  vcmn_templ ateNote +  vcmn_conta ctData.d.A ddress1_Co mposite +  "\n";
  631                                               if (Xrm.Pa ge.getAttr ibute('ftp _callbackn umber').ge tValue() ! = null) {
  632                                                   vcmn_t emplateNot e = vcmn_t emplateNot e + Xrm.Pa ge.getAttr ibute('ftp _callbackn umber').ge tValue();
  633                                               }
  634                                          }
  635                                      }
  636                                 }
  637                             }
  638                         }
  639  
  640                         //Write no te text if  not Triag e:
  641                         if (vcmn_t riageexper t == 'NO'  || vcmn_tr iageexpert  == null)  {
  642                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setVal ue(vcmn_te mplateNote );
  643                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setSub mitMode('a lways');
  644                         }
  645                    }
  646                }
  647  
  648                //Defaul t Diagnosi s code if  TAN user,  based on s ystemuser  lookup
  649                var vcmn _currentUs erId = Xrm .Page.cont ext.getUse rId();
  650                var vcmn _currentUs erData = v cmn_getSin gleEntityD ataSync('S ystemUserS et', 'msdy usd_USDCon figuration Id, ftp_Fa cilitySite Id', vcmn_ currentUse rId);
  651                if (vcmn _currentUs erData !=  null) {
  652                    if ( vcmn_curre ntUserData .d.msdyusd _USDConfig urationId  != null) {
  653                         if (vcmn_c urrentUser Data.d.msd yusd_USDCo nfiguratio nId.Name ! = null) {
  654                             if (vc mn_current UserData.d .msdyusd_U SDConfigur ationId.Na me == 'TAN  Configura tion') {
  655                                 // Get Defaul t Tan Conf iguration  from User' s Facility
  656                                 if  (vcmn_cur rentUserDa ta.d.ftp_F acilitySit eId != nul l) {
  657                                      if (vcmn _currentUs erData.d.f tp_Facilit ySiteId.Id  != null)  {
  658                                          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);
  659                                          if ( vcmn_curre ntUserFaci lityData ! = null) {
  660                                               if (vcmn_c urrentUser FacilityDa ta.d.ftp_d efaulttand iagnosisco de != null ) {
  661                                                   if (vc mn_current UserFacili tyData.d.f tp_default tandiagnos iscode.Id  != null) {
  662                                                       // Write Diag nosis code  to Progre ss Note Fo rm if a Tr iage Note
  663                                                       if  (vcmn_tri ageexpert  == 'YES')  {
  664                                                            vcmn_set SimpleLook upValue('f tp_diagnos iscode', v cmn_curren tUserFacil ityData.d. ftp_defaul ttandiagno siscode.Lo gicalName,  vcmn_curr entUserFac ilityData. d.ftp_defa ulttandiag nosiscode. Id, vcmn_c urrentUser FacilityDa ta.d.ftp_d efaulttand iagnosisco de.Name);
  665                                                            Xrm.Page .getAttrib ute('ftp_d iagnosisco de').setSu bmitMode(' always');
  666                                                       }
  667                                                   }
  668                                               }
  669                                          }
  670  
  671                                          //Ma tch up the  VHG Triag e minute c onfigurati on with CP T Code
  672                                          if ( vcmn_triag eminutes >  0) {
  673                                               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 +  " )";
  674                                               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);
  675                                          }
  676                                      }
  677                                 }
  678                             }
  679                         }
  680                    }
  681                }
  682  
  683                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 == '')  {
  684                    //Pr ompt user  to include  existing  Request No tes if the re is a cu rrent valu e
  685                    Xrm. Utility.co nfirmDialo g(
  686                         "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. ",
  687                         function ( ) {
  688                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setVal ue(vcmn_re questData. d.Descript ion);
  689                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setSub mitMode('a lways');
  690                         }
  691                    );
  692                }
  693  
  694                //****** FIX DEFECT  481450 ** ****
  695                if (vcmn _requestDa ta.d.Descr iption !=  null && vc mn_request Data.d.Des cription ! = '' && vc mn_triagee xpert == ' YES') {
  696                    //Pr ompt user  to include  existing  Request No tes if the re is a cu rrent valu e
  697                    Xrm. Utility.co nfirmDialo g(
  698                         "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. ",
  699                         function ( ) {
  700                             //Get  the existi ng Triage  Note 
  701                             var vc mn_TriageN ote = Xrm. Page.getAt tribute('f tp_notedet ail').getV alue();
  702                             if (vc mn_TriageN ote != nul l) {
  703                                 Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_requestD ata.d.Desc ription +  "\n\n" + v cmn_Triage Note);
  704                             }
  705                             else {  Xrm.Page. getAttribu te('ftp_no tedetail') .setValue( vcmn_reque stData.d.D escription ); }
  706                             Xrm.Pa ge.getAttr ibute('ftp _notedetai l').setSub mitMode('a lways');
  707                         }
  708                    );
  709                }
  710                //****** END FIX DE FECT 48145 0 ******
  711           }
  712  
  713           // 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)
  714           if  (vcmn_vet eranId !=  null) {
  715                var vcmn _contactDa ta = vcmn_ getSingleE ntityDataS ync('Conta ctSet', 'f tp_current facilityid , ftp_Faci lityId', v cmn_vetera nId);
  716                if (vcmn _contactDa ta != null ) {
  717                    if ( vcmn_conta ctData.d.f tp_current facilityid  != null)  {
  718                         if (vcmn_c ontactData .d.ftp_cur rentfacili tyid.Id !=  null) {
  719                             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);
  720                             Xrm.Pa ge.getAttr ibute('ftp _patientfa cility').s etSubmitMo de('always ');
  721                         }
  722                         else {
  723                             //Get  Facility f rom Home F acility
  724                             if (vc mn_contact Data.d.ftp _FacilityI d != null)  {
  725                                 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 );
  726                                 Xr m.Page.get Attribute( 'ftp_patie ntfacility ').setSubm itMode('al ways');
  727                             }
  728                         }
  729                    }
  730                    else  {
  731                         //Get Faci lity from  Home Facil ity
  732                         if (vcmn_c ontactData .d.ftp_Fac ilityId !=  null) {
  733                             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);
  734                             Xrm.Pa ge.getAttr ibute('ftp _patientfa cility').s etSubmitMo de('always ');
  735                         }
  736                    }
  737                }
  738           }
  739  
  740           // Set other  default fo rm values
  741           Xr m.Page.get Attribute( 'scheduled end').setV alue(new D ate());
  742           Xr m.Page.get Attribute( 'scheduled end').setS ubmitMode( 'always');
  743  
  744           // Append Gen eric Templ ate Data t o top of e xisting no te
  745           va r vcmn_gen ericTempla teData = " Callback N umber: ";
  746           if  (Xrm.Page .getAttrib ute('ftp_c allbacknum ber').getV alue() !=  null && Xr m.Page.get Attribute( 'ftp_callb acknumber' ).getValue () != "")  {
  747                vcmn_gen ericTempla teData = v cmn_generi cTemplateD ata + Xrm. Page.getAt tribute('f tp_callbac knumber'). getValue() ;
  748           }
  749           // Construct  new note w ith existi ng note da ta
  750           va r vcmn_exi stingNoteD ata = "";
  751           if  (Xrm.Page .getAttrib ute("ftp_n otedetail" ).getValue () != null  && Xrm.Pa ge.getAttr ibute("ftp _notedetai l").getVal ue() != "" ) {
  752                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  753           }
  754           vc mn_generic TemplateDa ta = vcmn_ genericTem plateData  + "\n\n" +  vcmn_exis tingNoteDa ta;
  755           // Replace ex isting not e
  756           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_genericT emplateDat a);
  757           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  758  
  759           // Change Foc us to the  Notes fiel d
  760           Xr m.Page.get Control("f tp_notedet ail").setF ocus();
  761  
  762           // Get ICN vi a web serv ice and ge t Service  Connected  disabiliti es thereaf ter
  763           // Preserved  Variables
  764           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  765           va r vcmn_vet eranFirstN ame = '';
  766           va r vcmn_vet eranLastNa me = '';
  767           va r vcmn_SSN  = '';
  768           va r vcmn_DOB  = '';
  769  
  770           // Get regard ing data
  771           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  772           if  (vcmn_req uestId ==  null) { re turn false ; }
  773           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  774  
  775           if  (vcmn_req uestData ! = null) {
  776                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  777                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  778                    //Ve rify that  the custom erid is of  type cont act
  779                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  780                         return fal se;
  781                    }
  782                }
  783           }
  784           if  (vcmn_vet eranId ==  null) {
  785                return f alse;
  786           }
  787  
  788           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);
  789           if  (vcmn_con tactData ! = null) {
  790                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  791                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  792                if (vcmn _contactDa ta.d.ftp_D ateofBirth  != null)  { vcmn_DOB  = vcmn_co ntactData. d.ftp_Date ofBirth; }
  793                if (vcmn _contactDa ta.d.Gover nmentId !=  null) { v cmn_SSN =  vcmn_conta ctData.d.G overnmentI d; }
  794           }
  795  
  796           // Perform MV I Search f or Service  Connected  Disabilit ies
  797           vc mn_unatten dedMviSear chSCD(vcmn _veteranFi rstName, v cmn_vetera nLastName,  vcmn_DOB,  vcmn_SSN) ;
  798       }
  799       catch  (err) {
  800           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_newP rogressNot eLoad_WebU RL): ' + e rr.message );
  801       }
  802   }
  803  
  804   function v cmn_getSer viceConnec tedDisabil ities(vcmn _patientIC N) {
  805       //**** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ***
  806       //Janu ary 16 201 7 - EXIT T HE FUNCTIO N, NOT USE D SEE BELO W
  807       return  false;
  808       //***T HE CODE BE LOW HAS BE EN TEMPORA RILY DISAB LED TO NOT  INCLUDE S ERVICE CON NECTED DIS ABILITIES  IN THE NOT E
  809       //**** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ***
  810       try {
  811           // ******Deve loper Bypa ss for mis sing ICN** ****
  812           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  813                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  814                    aler t("Develop er ICN byp ass applie d!");
  815                    vcmn _patientIC N = "12345 6V123456";
  816                }
  817           }
  818  
  819           // Verify Pat ient ICN
  820           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  821                //No ICN , do not p roceed
  822                return f alse;
  823           }
  824  
  825           // Get the se rvice conn ected disa bilities d ata from t he web ser vice
  826           va r vcmn_dis abilitiesX mlData = v cmn_getDis abilityDat a(vcmn_pat ientICN);
  827  
  828           // Temporary  action: xm l result i s empty, u se sample  data, comm ent out wh en not use d
  829           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********
  830           // if (vcmn_d isabilitie sXmlData = = null ||  vcmn_disab ilitiesXml Data == '' ) { vcmn_d isabilitie sXmlData =  xml_resul ts3; }
  831           // ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********
  832  
  833           // If no data , do not p roceed.
  834           if  (vcmn_dis abilitiesX mlData ==  null || vc mn_disabil itiesXmlDa ta == '')  { return f alse; }
  835  
  836           // Create bas e Note Str ing
  837           va r vcmn_SCD noteString  = '';
  838           vc mn_SCDnote String = v cmn_SCDnot eString +  "\n------- ---------- ---------- ---------- ---------- ---------- ---------- ------\n";
  839           vc mn_SCDnote String = v cmn_SCDnot eString +  "Special T reatment A uthority a nd Service  Connected  Disabilit ies";
  840           vc mn_SCDnote String = v cmn_SCDnot eString +  "\n------- ---------- ---------- ---------- ---------- ---------- ---------- ------\n";
  841  
  842           // Search XML  values
  843           vc mn_xmlDoc  = $.parseX ML(vcmn_di sabilities XmlData);
  844           $v cmn_xml =  $(vcmn_xml Doc);
  845  
  846           // Data from  parentnode  'enrollme ntDetermin ationInfo'  
  847           va r $vcmn_en rollmentDe terminatio nInfo = nu ll;
  848           va r $vcmn_pr imaryEligi bility = n ull;
  849           va r $vcmn_ty pe = null;
  850           va r vcmn_typ eText = nu ll;
  851           va r $vcmn_en rollmentCa tegoryName  = null;
  852           va r vcmn_enr ollmentCat egoryNameT ext = null ;
  853           va r $vcmn_sp ecialFacto rs = null;
  854           va r $vcmn_en vContamina ntsInd = n ull;
  855           va r vcmn_env Contaminan tsIndText  = null;
  856           va r $vcmn_ra diationExp osureInd =  null;
  857           va r vcmn_rad iationExpo sureIndTex t = null;
  858           va r $vcmn_ag entOrangeI nd = null;
  859           va r vcmn_age ntOrangeIn dText = nu ll;
  860           va r $vcmn_ca mpLejeuneI nd = null;
  861           va r vcmn_cam pLejeuneIn dText = nu ll;
  862           va r $vcmn_se rviceConne ctionAward  = null;
  863           va r $vcmn_se rviceConne ctedPercen tage = nul l;
  864           va r vcmn_ser viceConnec tedPercent ageText =  null;
  865           va r $vcmn_ra tedDisabil ities = nu ll;
  866  
  867           va r $vcmn_ag entOrangeL ocation =  null;
  868           va r vcmn_age ntOrangeLo cationText  = null;
  869           va r $vcmn_ra diationExp osureMetho d = null;
  870           va r vcmn_rad iationExpo sureMethod Text = nul l;
  871  
  872           va r $vcmn_no seThroatRa diumInfo =  null;
  873           va r $vcmn_di agnosedWit hCancer =  null;
  874           va r vcmn_dia gnosedWith CancerText  = null;
  875  
  876           va r $vcmn_mi litarySexu alTraumaIn fo = null;
  877           va r $vcmn_mi lSexTrauma Status = n ull;
  878           va r vcmn_mil SexTraumaS tatusText  = null;
  879  
  880           // Data from  parentnode  'military ServiceInf o' 
  881           va r $vcmn_mi litaryServ iceInfo =  null;
  882           va r $vcmn_co mbatVetera nEligibili tyEndDate  = null;
  883           va r vcmn_com batVeteran Eligibilit yEndDateTe xt = null;
  884           va r $vcmn_sh adIndicato r = null;
  885           va r vcmn_sha dIndicator Text = nul l;
  886  
  887           va r vcmn_rat edDisabili tyPercenta geTotal =  0;
  888  
  889           va r vcmn_det ailrowcoun t = 0;
  890  
  891           $v cmn_enroll mentDeterm inationInf o = $vcmn_ xml.find(' enrollment Determinat ionInfo');
  892           if  ($vcmn_en rollmentDe terminatio nInfo != n ull) {
  893                $vcmn_pr imaryEligi bility = $ vcmn_enrol lmentDeter minationIn fo.find('p rimaryElig ibility');
  894                if ($vcm n_primaryE ligibility  != null)  {
  895                    $vcm n_type = $ vcmn_prima ryEligibil ity.find(' type');
  896                    if ( $vcmn_type  != null)  { vcmn_typ eText = $v cmn_type.t ext(); }
  897                }
  898  
  899                $vcmn_en rollmentCa tegoryName  = $vcmn_e nrollmentD eterminati onInfo.fin d('enrollm entCategor yName');
  900                if ($vcm n_enrollme ntCategory Name != nu ll) { vcmn _enrollmen tCategoryN ameText =  $vcmn_enro llmentCate goryName.t ext(); }
  901  
  902                $vcmn_sp ecialFacto rs = $vcmn _enrollmen tDetermina tionInfo.f ind('speci alFactors' );
  903                if ($vcm n_specialF actors !=  null) {
  904                    $vcm n_envConta minantsInd  = $vcmn_s pecialFact ors.find(' envContami nantsInd') ;
  905                    if ( $vcmn_envC ontaminant sInd != nu ll) { vcmn _envContam inantsIndT ext = $vcm n_envConta minantsInd .text(); }
  906                    $vcm n_radiatio nExposureI nd = $vcmn _specialFa ctors.find ('radiatio nExposureI nd');
  907                    if ( $vcmn_radi ationExpos ureInd !=  null) { vc mn_radiati onExposure IndText =  $vcmn_radi ationExpos ureInd.tex t(); }
  908                    $vcm n_agentOra ngeInd = $ vcmn_speci alFactors. find('agen tOrangeInd ');
  909                    if ( $vcmn_agen tOrangeInd  != null)  { vcmn_age ntOrangeIn dText = $v cmn_agentO rangeInd.t ext(); }
  910                    $vcm n_campLeje uneInd = $ vcmn_speci alFactors. find('camp LejeuneInd ');
  911                    if ( $vcmn_camp LejeuneInd  != null)  { vcmn_cam pLejeuneIn dText = $v cmn_campLe jeuneInd.t ext(); }
  912  
  913                    $vcm n_agentOra ngeLocatio n = $vcmn_ specialFac tors.find( 'agentOran geLocation ');
  914                    if ( $vcmn_agen tOrangeLoc ation != n ull) { vcm n_agentOra ngeLocatio nText = $v cmn_agentO rangeLocat ion.text() ; }
  915                    $vcm n_radiatio nExposureM ethod = $v cmn_specia lFactors.f ind('radia tionExposu reMethod') ;
  916                    if ( $vcmn_radi ationExpos ureMethod  != null) {  vcmn_radi ationExpos ureMethodT ext = $vcm n_radiatio nExposureM ethod.text (); }
  917                }
  918  
  919                $vcmn_se rviceConne ctionAward  = $vcmn_e nrollmentD eterminati onInfo.fin d('service Connection Award');
  920                if ($vcm n_serviceC onnectionA ward != nu ll) {
  921                    $vcm n_serviceC onnectedPe rcentage =  $vcmn_ser viceConnec tionAward. find('serv iceConnect edPercenta ge');
  922                    if ( $vcmn_serv iceConnect edPercenta ge != null ) { vcmn_s erviceConn ectedPerce ntageText  = $vcmn_se rviceConne ctedPercen tage.text( ); }
  923                    $vcm n_ratedDis abilities  = $vcmn_se rviceConne ctionAward .find('rat edDisabili ties');
  924                    //Ge t each dis ability li sted and a dd to note  string
  925                    vcmn _SCDnoteSt ring = vcm n_SCDnoteS tring + "S C Disabili ty: ";
  926                    $vcm n_ratedDis abilities. find('rate dDisabilit y').each(f unction ()  {
  927                         var vcmn_r atedDisabi lityPercen t = 0;
  928                         var vcmn_d isability  = null;
  929                         if (Number ($(this).f ind('perce ntage').te xt()) > 0)  {
  930                             vcmn_r atedDisabi lityPercen tageTotal  = vcmn_rat edDisabili tyPercenta geTotal +  Number($(t his).find( 'percentag e').text() );
  931                             vcmn_r atedDisabi lityPercen t = Number ($(this).f ind('perce ntage').te xt());
  932                         }
  933                         //Add Rate d Disabili ties to th e Note Str ing if Dis ability Pe rcent > 0
  934                         if (vcmn_r atedDisabi lityPercen t > 0) {
  935                             vcmn_S CDnoteStri ng = vcmn_ SCDnoteStr ing + $(th is).find(' disability ').text()  + "\n";
  936                         }
  937                    });
  938                    vcmn _SCDnoteSt ring = vcm n_SCDnoteS tring + "\ n";
  939                }
  940  
  941                $vcmn_no seThroatRa diumInfo =  $vcmn_enr ollmentDet ermination Info.find( 'noseThroa tRadiumInf o');
  942                if ($vcm n_noseThro atRadiumIn fo != null ) {
  943                    $vcm n_diagnose dWithCance r = $vcmn_ noseThroat RadiumInfo .find('dia gnosedWith Cancer');
  944                    if ( $vcmn_diag nosedWithC ancer != n ull) { vcm n_diagnose dWithCance rText = $v cmn_diagno sedWithCan cer.text() ; }
  945                }
  946  
  947                $vcmn_mi litarySexu alTraumaIn fo = $vcmn _enrollmen tDetermina tionInfo.f ind('milit arySexualT raumaInfo' );
  948                if ($vcm n_military SexualTrau maInfo !=  null) {
  949                    $vcm n_milSexTr aumaStatus  = $vcmn_m ilitarySex ualTraumaI nfo.find(' status');
  950                    if ( $vcmn_milS exTraumaSt atus != nu ll) { vcmn _milSexTra umaStatusT ext = $vcm n_milSexTr aumaStatus .text(); }
  951                }
  952           }
  953  
  954           $v cmn_milita ryServiceI nfo = $vcm n_xml.find ('military ServiceInf o');
  955           if  ($vcmn_mi litaryServ iceInfo !=  null) {
  956                $vcmn_co mbatVetera nEligibili tyEndDate  = $vcmn_mi litaryServ iceInfo.fi nd('combat VeteranEli gibilityEn dDate');
  957                if ($vcm n_combatVe teranEligi bilityEndD ate != nul l) {
  958                    vcmn _combatVet eranEligib ilityEndDa teText = v cmn_combat VeteranEli gibilityEn dDateText  = $vcmn_co mbatVetera nEligibili tyEndDate. text();
  959                }
  960                $vcmn_sh adIndicato r = $vcmn_ militarySe rviceInfo. find('shad Indicator' );
  961                if ($vcm n_shadIndi cator != n ull) { vcm n_shadIndi catorText  = $vcmn_sh adIndicato r.text();  }
  962           }
  963  
  964           // If no elig ibility sp ecified, s et to fals e
  965           if  (vcmn_typ eText == n ull || vcm n_typeText  == '') {  vcmn_typeT ext = fals e; }
  966  
  967           // Change boo lean value s to false  if not ma rked true
  968           if  (vcmn_env Contaminan tsIndText  != 'true')  { vcmn_en vContamina ntsIndText  = false;  }
  969           if  (vcmn_rad iationExpo sureIndTex t != 'true ') { vcmn_ radiationE xposureInd Text = fal se; }
  970           if  (vcmn_age ntOrangeIn dText != ' true') { v cmn_agentO rangeIndTe xt = false ; }
  971           if  (vcmn_cam pLejeuneIn dText != ' true') { v cmn_campLe jeuneIndTe xt = false ; }
  972  
  973           if  (vcmn_dia gnosedWith CancerText  != 'true' ) { vcmn_d iagnosedWi thCancerTe xt = false ; }
  974           if  (vcmn_sha dIndicator Text != 't rue') { vc mn_shadInd icatorText  = false;  }
  975  
  976           // Change all  True/Fals e to Yes/N o
  977           if  (vcmn_typ eText == f alse) { vc mn_typeTex t = 'No';  }
  978  
  979           if  (vcmn_env Contaminan tsIndText  == "true")  { vcmn_en vContamina ntsIndText  = "Yes";  } else { v cmn_envCon taminantsI ndText = " No"; }
  980           if  (vcmn_rad iationExpo sureIndTex t == "true ") {
  981                vcmn_rad iationExpo sureIndTex t = "Yes";
  982                if (vcmn _radiation ExposureMe thodText ! = null) {  vcmn_radia tionExposu reIndText  = vcmn_rad iationExpo sureIndTex t + " - "  + vcmn_rad iationExpo sureMethod Text; }
  983           }  else {
  984                vcmn_rad iationExpo sureIndTex t = "No";
  985           }
  986           if  (vcmn_age ntOrangeIn dText == " true") {
  987                vcmn_age ntOrangeIn dText = "Y es";
  988                if (vcmn _agentOran geLocation Text != nu ll) { vcmn _agentOran geIndText  = vcmn_age ntOrangeIn dText + "  - " + vcmn _agentOran geLocation Text; }
  989           }
  990           el se {
  991                vcmn_age ntOrangeIn dText = "N o";
  992           }
  993           if  (vcmn_cam pLejeuneIn dText == " true") { v cmn_campLe jeuneIndTe xt = "Yes" ; } else {  vcmn_camp LejeuneInd Text = "No "; }
  994  
  995           if  (vcmn_dia gnosedWith CancerText  == "true" ) { vcmn_d iagnosedWi thCancerTe xt = "Yes" ; } else {  vcmn_diag nosedWithC ancerText  = "No"; }
  996  
  997           if  (vcmn_com batVeteran Eligibilit yEndDateTe xt != null  && vcmn_c ombatVeter anEligibil ityEndDate Text != '' ) { vcmn_c ombatVeter anEligibil ityEndDate Text = 'Ye s'; }
  998  
  999           if  (vcmn_sha dIndicator Text == "t rue") { vc mn_shadInd icatorText  = "Yes";  } else { v cmn_shadIn dicatorTex t = "No";  }
  1000  
  1001           // Construct  summary no te part
  1002           if  (vcmn_env Contaminan tsIndText  != null &&  vcmn_envC ontaminant sIndText ! = '') { vc mn_SCDnote String = v cmn_SCDnot eString +  "Environme ntal Conta minant: "  + vcmn_env Contaminan tsIndText  + "\n"; }
  1003           if  (vcmn_com batVeteran Eligibilit yEndDateTe xt != null  && vcmn_c ombatVeter anEligibil ityEndDate Text != '' ) { vcmn_S CDnoteStri ng = vcmn_ SCDnoteStr ing + "Com bat Vetera n: " + vcm n_combatVe teranEligi bilityEndD ateText +  "\n"; }
  1004           if  (vcmn_rad iationExpo sureIndTex t != null  && vcmn_ra diationExp osureIndTe xt != '')  { vcmn_SCD noteString  = vcmn_SC DnoteStrin g + "Radia tion Expos ure: " + v cmn_radiat ionExposur eIndText +  "\n"; }
  1005           if  (vcmn_age ntOrangeIn dText != n ull && vcm n_agentOra ngeIndText  != '') {  vcmn_SCDno teString =  vcmn_SCDn oteString  + "Agent O range: " +  vcmn_agen tOrangeInd Text + "\n "; }
  1006           if  (vcmn_sha dIndicator Text != nu ll && vcmn _shadIndic atorText ! = '') { vc mn_SCDnote String = v cmn_SCDnot eString +  "Shipboard  Hazard &  Defense: "  + vcmn_sh adIndicato rText + "\ n"; }
  1007           if  (vcmn_dia gnosedWith CancerText  != null & & vcmn_dia gnosedWith CancerText  != '') {  vcmn_SCDno teString =  vcmn_SCDn oteString  + "Head/Ne ck Cancer:  " + vcmn_ diagnosedW ithCancerT ext + "\n" ; }
  1008           if  (vcmn_mil SexTraumaS tatusText  != null &&  vcmn_milS exTraumaSt atusText ! = '') { vc mn_SCDnote String = v cmn_SCDnot eString +  "Military  Sexual Tra uma: " + v cmn_milSex TraumaStat usText + " \n"; }
  1009           if  (vcmn_cam pLejeuneIn dText != n ull && vcm n_campLeje uneIndText  != '') {  vcmn_SCDno teString =  vcmn_SCDn oteString  + "Camp Le jeune: " +  vcmn_camp LejeuneInd Text + "\n "; }
  1010  
  1011           // Update not e with new  SCD note  data
  1012           va r vcmn_exi stingNoteD ata = "";
  1013           if  (Xrm.Page .getAttrib ute("ftp_n otedetail" ).getValue () != null  && Xrm.Pa ge.getAttr ibute("ftp _notedetai l").getVal ue() != "" ) {
  1014                vcmn_exi stingNoteD ata = Xrm. Page.getAt tribute("f tp_notedet ail").getV alue();
  1015           }
  1016           vc mn_extende dTemplateD ata = vcmn _existingN oteData +  vcmn_SCDno teString;
  1017           // Replace ex isting not e
  1018           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_extended TemplateDa ta);
  1019           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  1020       }
  1021       catch  (err) {
  1022           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_getS erviceConn ectedDisab ilities):  ' + err.me ssage);
  1023       }
  1024   }
  1025  
  1026   function v cmn_getDis abilityDat a(vcmn_nat ionalId) {
  1027       try {
  1028           va r vcmn_ees ummaryURL  = vcmn_ees ummaryURLb ase + '000 000' + vcm n_national Id + '0000 00';
  1029           va r vcmn_xml Data = nul l;
  1030  
  1031           $. ajax({
  1032                type: "G ET",
  1033                url: vcm n_eesummar yURL,
  1034                contentT ype: "appl ication/xm l; charset =utf-8",
  1035                dataType : "text",
  1036                success:  function  (xmlTextda ta) {
  1037                    vcmn _xmlData =  xmlTextda ta;
  1038                },
  1039                error: f unction (j qXHR, text Status, er rorThrown)  {
  1040                    //Sy stem Error
  1041                    vcmn _xmlData =  null;
  1042                },
  1043                async: f alse,
  1044                cache: f alse
  1045           }) ;
  1046           re turn vcmn_ xmlData;
  1047       }
  1048       catch  (err) {
  1049           al ert("Progr ess Note F orm Load S cript Func tion Error (vcmn_getD isabilityD ata): " +  err.messag e);
  1050           re turn null;
  1051       }
  1052   }
  1053  
  1054   function v cmn_facili tyByCode_r esponse(vc mn_facilit yData, vcm n_lastSkip , vcmn_fac ilityCode)  {
  1055       try {
  1056           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  1057           // ***REVISED  NOT USED,  KEEP FOR  FUTURE UPD ATE***
  1058           /*
  1059           va r vcmn_fac ilityid =  null;
  1060           va r vcmn_fac ilityname  = null;
  1061           fo r (var i =  0; i <= v cmn_facili tyData.d.r esults.len gth - 1; i ++) {
  1062                //Get in fo
  1063                if (vcmn _facilityD ata.d.resu lts[i].ftp _facilityI d != null)  { vcmn_fa cilityid =  vcmn_faci lityData.d .results[i ].ftp_faci lityId; }
  1064                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; }
  1065                break;
  1066           }
  1067           if  (vcmn_fac ilityid !=  null) {
  1068                vcmn_set SimpleLook upValue('f tp_patient facility',  'ftp_faci lity', vcm n_facility id, vcmn_f acilitynam e);
  1069                Xrm.Page .getAttrib ute('ftp_p atientfaci lity').set SubmitMode ('always') ;
  1070           }
  1071           */
  1072       }
  1073       catch  (err) {
  1074           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_faci lityByCode _response) : ' + err. message);
  1075       }
  1076   }
  1077  
  1078   function v cmn_cptCod e_response (vcmn_cptC odeData, v cmn_lastSk ip, vcmn_t riageminut es) {
  1079       try {
  1080           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  1081           fo r (var i =  0; i <= v cmn_cptCod eData.d.re sults.leng th - 1; i+ +) {
  1082                //Write  to CRM pro gress note  form
  1083                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);
  1084                Xrm.Page .getAttrib ute('ftp_c ptcode').s etSubmitMo de('always ');
  1085                break;
  1086           }
  1087       }
  1088       catch  (err) {
  1089           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_cptC ode_respon se): ' + e rr.message );
  1090       }
  1091   }
  1092  
  1093   function v cmn_ribbon ButtonSave () {
  1094       try {
  1095           // Save the c urrent CRM  data
  1096           Xr m.Page.dat a.entity.s ave();
  1097       }
  1098       catch  (err) {
  1099           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa ve): ' + e rr.message );
  1100       }
  1101   }
  1102  
  1103   function v cmn_wordWr ap(str, in tWidth, st rBreak, cu t) {
  1104       try {
  1105           // Takes a st ring that  exceeds a  set length  and inser ts word wr ap
  1106           va r m = ((ar guments.le ngth >= 2)  ? argumen ts[1] : 75 )
  1107           va r b = ((ar guments.le ngth >= 3)  ? argumen ts[2] : '\ n')
  1108           va r c = ((ar guments.le ngth >= 4)  ? argumen ts[3] : fa lse)
  1109  
  1110           va r i, j, l,  s, r
  1111  
  1112           st r += ''
  1113  
  1114           if  (m < 1) {
  1115                return s tr
  1116           }
  1117  
  1118           fo r (i = -1,  l = (r =  str.split( /\r\n|\n|\ r/)).lengt h; ++i < l ; r[i] +=  s) {
  1119                for (s =  r[i], r[i ] = '';
  1120                  s.leng th > m;
  1121                  r[i] + = s.slice( 0, j) + (( s = s.slic e(j)).leng th ? b : ' ')) {
  1122                    j =  c === 2 ||  (j = s.sl ice(0, m +  1).match( /\S*(\s)?$ /))[1]
  1123                      ?  m
  1124                      :  j.input.le ngth - j[0 ].length | | c === tr ue && m ||
  1125                         j.input.le ngth + (j  = s.slice( m).match(/ ^\S*/))[0] .length
  1126                }
  1127           }
  1128  
  1129           re turn r.joi n('\n')
  1130       }
  1131       catch  (err) {
  1132           al ert('Progr ess Note R ibbon Func tion Error (vcmn_word Wrap): ' +  err.messa ge);
  1133       }
  1134   }
  1135  
  1136   function v cmn_ribbon ButtonSave ToVistA()  {
  1137       try {
  1138           // Check the  value of t he Integra tion Statu s Field, i f = 'OK',  stop and e xit this s cript
  1139           va r vcmn_int egrationSt atus = Xrm .Page.getA ttribute(' ftp_integr ationstatu s').getVal ue();
  1140           if  (vcmn_int egrationSt atus == 'O K') { retu rn false;  }
  1141  
  1142           // Prompt use r to sign  the note
  1143           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  1144           va r vcmn_sig nThisNoteF ailure = f alse;
  1145           if  (vcmn_sig nThisNote  == null) {
  1146                Xrm.Util ity.confir mDialog(
  1147                    "Do  you need t o sign thi s note?, S elect OK i f Yes, oth erwise CAN CEL.",
  1148                    func tion () {
  1149                         //Check if  VIA Login  cookie ex ist (not e xpired)
  1150                         var vcmn_V iaLoginCoo kie = vcmn _getCookie ("viasessi onlink");
  1151                         //Prompt u ser to log in to VIA
  1152                         if (vcmn_V iaLoginCoo kie == "")  {
  1153                             alert( "Your VIST A session  has expire d. In orde r to sign  this note,  you must  be logged  into VISTA !");
  1154                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setVisi ble(true);
  1155                             Xrm.Pa ge.ui.tabs .get('Tab_ VistALogin ').setFocu s();
  1156                             vcmn_s ignThisNot eFailure =  true;
  1157                             return ;
  1158                         }
  1159                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000001 );
  1160                    },
  1161                    func tion () {
  1162                         Xrm.Page.g etAttribut e('ftp_sig nthisnote' ).setValue (100000000 );
  1163                    }
  1164                );
  1165                Xrm.Page .getAttrib ute('ftp_s ignthisnot e').setSub mitMode('a lways');
  1166           }
  1167  
  1168           // Check for  additional  signers,  if they ex ist, the u ser must b e logged i nto VIA to  continue  process.
  1169           // Additional  Signature s must als o be in sy nc with ma tching Ses sion varia bles
  1170  
  1171           vc mn_AddlSig nersNameAr ray = null ;
  1172           vc mn_AddlSig nersIenArr ay = null;
  1173  
  1174           va r vcmn_sel ectedSigne rs = Xrm.P age.getAtt ribute('ft p_selected signers'). getValue() ;
  1175           if  (vcmn_sel ectedSigne rs != null  && vcmn_s electedSig ners != '' ) {
  1176                //Additi onal Signe rs exist i n CRM, ver ify sessio n variable s
  1177                var vcmn _selectedA rray = vcm n_selected Signers.sp lit('~~~') ;
  1178                var vcmn _selectedA rrayRecord Count = vc mn_selecte dArray.len gth;
  1179                if (vcmn _selectedA rrayRecord Count > 1)  {
  1180                    vcmn _AddlSigne rsNameArra y = vcmn_s electedArr ay;
  1181                }
  1182  
  1183                var vcmn _selectedI ENArray =  '';
  1184                var vcmn _selectedI ENArrayRec ordCount =  0;
  1185                var vcmn _progressN oteId = Xr m.Page.dat a.entity.g etId();
  1186  
  1187                var vcmn _arrayMism atch = fal se;
  1188  
  1189                //Get No te's Brows er Local S torage Val ues
  1190                if (vcmn _progressN oteId != n ull && vcm n_progress NoteId !=  '') {
  1191                    vcmn _localStor ageVarName  = "PN" +  vcmn_progr essNoteId;
  1192                    var  vcmn_local StorageStr ingValue =  localStor age.getIte m(vcmn_loc alStorageV arName);
  1193                    if ( vcmn_local StorageStr ingValue ! = null &&  vcmn_local StorageStr ingValue ! = '') {
  1194                         vcmn_selec tedIENArra y = vcmn_l ocalStorag eStringVal ue.split(' ~~~');
  1195                         vcmn_selec tedIENArra yRecordCou nt = vcmn_ selectedIE NArray.len gth;
  1196                         if (vcmn_s electedIEN ArrayRecor dCount > 1 ) {
  1197                             vcmn_A ddlSigners IenArray =  vcmn_sele ctedIENArr ay;
  1198                         }
  1199                    }
  1200                }
  1201                //Compar e CRM sign er array l ength with  LocalStor age array  length
  1202                if (vcmn _selectedA rrayRecord Count != v cmn_select edIENArray RecordCoun t) { vcmn_ arrayMisma tch = true ; }
  1203  
  1204                if (vcmn _arrayMism atch == tr ue) {
  1205                    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.");
  1206                    vcmn _signThisN oteFailure  = true;
  1207                }
  1208                else {
  1209                    //Ch eck if VIA  Login coo kie exist  (not expir ed)
  1210                    var  vcmn_ViaLo ginCookie  = vcmn_get Cookie("vi asessionli nk");
  1211                    if ( vcmn_ViaLo ginCookie  == "") {
  1212                         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 !");
  1213                         Xrm.Page.u i.tabs.get ('Tab_Vist ALogin').s etVisible( true);
  1214                         Xrm.Page.u i.tabs.get ('Tab_Vist ALogin').s etFocus();
  1215                         vcmn_signT hisNoteFai lure = tru e;
  1216                         return;
  1217                    }
  1218                }
  1219           }
  1220  
  1221           // Check if m arked as a  workload  encounter  and if so  enforce VI A Login
  1222           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) == true)  {
  1223                //Check  if VIA Log in cookie  exist (not  expired)
  1224                var vcmn _ViaLoginC ookie = vc mn_getCook ie("viases sionlink") ;
  1225                if (vcmn _ViaLoginC ookie == " ") {
  1226                    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!");
  1227                    Xrm. Page.ui.ta bs.get('Ta b_VistALog in').setVi sible(true );
  1228                    Xrm. Page.ui.ta bs.get('Ta b_VistALog in').setFo cus();
  1229                    vcmn _signThisN oteFailure  = true;
  1230                    retu rn;
  1231                }
  1232           }
  1233  
  1234           if  (vcmn_sig nThisNoteF ailure ==  true) {
  1235                //****** Developer  Bypass for  no VISTA  authentica tion******
  1236                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}") {
  1237                    aler t("Develop er VISTA a uthenticat ion bypass  applied!" );
  1238                    Xrm. Page.getAt tribute('f tp_signthi snote').se tValue(100 000001);
  1239                    Xrm. Page.getAt tribute('f tp_signthi snote').se tSubmitMod e('always' );
  1240                }
  1241                else {
  1242                    retu rn false;
  1243                }
  1244           }
  1245  
  1246           // Save the c urrent CRM  data
  1247           Xr m.Page.dat a.entity.s ave();
  1248           // Display YE LLOW Progr ess....
  1249           Xr m.Page.ui. setFormNot ification( "Verifying  progress  note data,  please wa it..", "IN FO", "SAVE VISTA");
  1250  
  1251           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!');
  1252           if  (vcmn_con firmSaveTo Vista == f alse) {
  1253                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1254                return f alse;
  1255           }
  1256           // Get regard ing data
  1257           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1258           if  (vcmn_req uestId ==  null) {
  1259                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 !');
  1260                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  1261                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1262                return f alse;
  1263           }
  1264           // Verify tha t the rega rdingid is  of type ' incident'
  1265           if  (vcmn_req uestId[0]. entityType  != 'incid ent') {
  1266                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!') ;
  1267                Xrm.Page .getContro l('regardi ngobjectid ').setFocu s();
  1268                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1269                return f alse;
  1270           }
  1271  
  1272           // Preserved  Variables
  1273           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1274           va r vcmn_vet eranFirstN ame = '';
  1275           va r vcmn_vet eranLastNa me = '';
  1276           va r vcmn_SSN  = '';
  1277           va r vcmn_DOB  = '';
  1278  
  1279           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1280           if  (vcmn_req uestData ! = null) {
  1281                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1282                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1283                    //Ve rify that  the custom erid is of  type cont act
  1284                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1285                         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!') ;
  1286                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1287                         return fal se;
  1288                    }
  1289                }
  1290           }
  1291           if  (vcmn_vet eranId ==  null) {
  1292                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  1293                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1294                return f alse;
  1295           }
  1296  
  1297           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);
  1298           if  (vcmn_con tactData ! = null) {
  1299                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1300                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1301                if (vcmn _contactDa ta.d.ftp_D ateofBirth  != null)  { vcmn_DOB  = vcmn_co ntactData. d.ftp_Date ofBirth; }
  1302                if (vcmn _contactDa ta.d.Gover nmentId !=  null) { v cmn_SSN =  vcmn_conta ctData.d.G overnmentI d; }
  1303           }
  1304  
  1305           // **WORKLOAD  ENCOUNTER **
  1306           vc mn_matchLo okupId = v cmn_SSN;
  1307           // ********** ********** ***
  1308  
  1309           // Perform MV I Search
  1310           vc mn_unatten dedMviSear ch(vcmn_ve teranFirst Name, vcmn _veteranLa stName, vc mn_DOB, vc mn_SSN);
  1311       }
  1312       catch  (err) {
  1313           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa veToVistA) : ' + err. message);
  1314           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1315       }
  1316   }
  1317  
  1318   function v cmn_ribbon ButtonSave ToVistA_wi th_ICN(vcm n_patientI CN) {
  1319       try {
  1320           // ******Deve loper Bypa ss for mis sing ICN** ****
  1321           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1322                if ((Xrm .Page.cont ext.getUse rId()).toU pperCase()  == "{CA50 0504-CBC5- E511-8173- 000C2941CE 19}") {
  1323                    aler t("Develop er ICN byp ass applie d!");
  1324                    vcmn _patientIC N = "12345 6V123456";
  1325                }
  1326           }
  1327  
  1328           // Verify Pat ient ICN
  1329           if  (vcmn_pat ientICN ==  '' || vcm n_patientI CN == null ) {
  1330                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! ');
  1331                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1332                return f alse;
  1333           }
  1334  
  1335           // Get regard ing data
  1336           va r vcmn_req uestId = X rm.Page.ge tAttribute ('regardin gobjectid' ).getValue ();
  1337  
  1338           // Preserved  Variables
  1339           va r vcmn_vet eranId = n ull;  //Fr om request  customeri d
  1340           va r vcmn_vet eranName =  '';
  1341           va r vcmn_vet eranFirstN ame = '';
  1342           va r vcmn_vet eranLastNa me = '';
  1343           va r vcmn_vet eranMiddle Name = '';
  1344  
  1345           va r vcmn_req uestData =  vcmn_getS ingleEntit yDataSync( 'IncidentS et', 'Cust omerId', v cmn_reques tId[0].id) ;
  1346           if  (vcmn_req uestData ! = null) {
  1347                if (vcmn _requestDa ta.d.Custo merId != n ull) {
  1348                    vcmn _veteranId  = vcmn_re questData. d.Customer Id;
  1349                    //Ve rify that  the custom erid is of  type cont act
  1350                    if ( vcmn_veter anId.Logic alName !=  'contact')  {
  1351                         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!') ;
  1352                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1353                         return fal se;
  1354                    }
  1355                }
  1356           }
  1357           if  (vcmn_vet eranId ==  null) {
  1358                alert('T he related  request d oes not ha ve a veter an/contact  assigned,  the note  cannot be  created in  VistA/CPR S!');
  1359                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1360                return f alse;
  1361           }
  1362  
  1363           va r vcmn_con tactData =  vcmn_getS ingleEntit yDataSync( 'ContactSe t', 'FullN ame, First Name, Last Name, Midd leName', v cmn_vetera nId.Id);
  1364           if  (vcmn_con tactData ! = null) {
  1365                if (vcmn _contactDa ta.d.FullN ame != nul l) { vcmn_ veteranNam e = vcmn_c ontactData .d.FullNam e; }
  1366                if (vcmn _contactDa ta.d.First Name != nu ll) { vcmn _veteranFi rstName =  vcmn_conta ctData.d.F irstName;  }
  1367                if (vcmn _contactDa ta.d.LastN ame != nul l) { vcmn_ veteranLas tName = vc mn_contact Data.d.Las tName; }
  1368                if (vcmn _contactDa ta.d.Middl eName != n ull) { vcm n_veteranM iddleName  = vcmn_con tactData.d .MiddleNam e; }
  1369           }
  1370  
  1371           // Get user d ata
  1372           va r vcmn_crm UserId = X rm.Page.ge tAttribute ('ownerid' ).getValue ();
  1373           va r vcmn_use rDomainId  = '';
  1374           va r vcmn_use rFirstName  = '';
  1375           va r vcmn_use rLastName  = '';
  1376           va r vcmn_use rMiddleNam e = '';
  1377           va r vcmn_use rSiteId =  '';
  1378  
  1379           if  (vcmn_crm UserId !=  null) {
  1380                //Verify  the owner  type
  1381                if (vcmn _crmUserId [0].entity Type != 's ystemuser' ) {
  1382                    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 !');
  1383                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1384                    retu rn false;
  1385                }
  1386  
  1387                var vcmn _userData  = vcmn_get SingleEnti tyDataSync ('SystemUs erSet', 'D omainName,  FirstName , LastName , MiddleNa me, ftp_Fa cilitySite Id', vcmn_ crmUserId[ 0].id);
  1388                if (vcmn _userData  != null) {
  1389                    if ( vcmn_userD ata.d.Doma inName !=  null) { vc mn_userDom ainId = vc mn_userDat a.d.Domain Name; }
  1390                    if ( vcmn_userD ata.d.Firs tName != n ull) { vcm n_userFirs tName = vc mn_userDat a.d.FirstN ame; }
  1391                    if ( vcmn_userD ata.d.Last Name != nu ll) { vcmn _userLastN ame = vcmn _userData. d.LastName ; }
  1392                    if ( vcmn_userD ata.d.Midd leName !=  null) { vc mn_userMid dleName =  vcmn_userD ata.d.Midd leName; }
  1393                    if ( vcmn_userD ata.d.ftp_ FacilitySi teId != nu ll) { vcmn _userSiteI d = vcmn_u serData.d. ftp_Facili tySiteId.I d; }
  1394                }
  1395           }
  1396           el se {
  1397                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!');
  1398                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1399                return f alse;
  1400           }
  1401  
  1402           // Verify tha t the curr ent owner  and the cu rrent user  is the sa me person,  if not do  not proce ed
  1403           if  ((vcmn_cr mUserId[0] .id).toUpp erCase() ! = (Xrm.Pag e.context. getUserId( )).toUpper Case()) {
  1404                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!');
  1405                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1406                return f alse;
  1407           }
  1408           va r vcmn_Not eUserTeam  = "NONE";
  1409           // Check Team  membershi p
  1410           if  (vcmn_Use rHasTeam(" Pharmacy",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "PHARM ACY"; }
  1411           if  (vcmn_Use rHasTeam(" CCA Team",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "CCA";  }
  1412           if  (vcmn_Use rHasTeam(" TAN", Xrm. Page.conte xt.getUser Id())) { v cmn_NoteUs erTeam = " TAN"; }
  1413           // **TEMP, ve rify these  team valu es that th ey are cor rect **FUT URE NEED**
  1414           if  (vcmn_Use rHasTeam(" PACT User" , Xrm.Page .context.g etUserId() )) { vcmn_ NoteUserTe am = "PACT "; }
  1415           if  (vcmn_Use rHasTeam(" MSA User",  Xrm.Page. context.ge tUserId()) ) { vcmn_N oteUserTea m = "MSA";  }
  1416  
  1417           // Verify Tea m Value, t hat one ha s been ass igned
  1418           if  (vcmn_Not eUserTeam  == "NONE")  {
  1419                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 !');
  1420                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1421                return f alse;
  1422           }
  1423  
  1424           // Get reques t form con tent
  1425           va r vcmn_not eDescripti on = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  1426           if  (vcmn_not eDescripti on == null  || vcmn_n oteDescrip tion == '' ) {
  1427                alert('T he note de scription  field is e mpty, the  note canno t be creat ed in Vist A/CPRS!');
  1428                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1429                return f alse;
  1430           }
  1431  
  1432           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) != true)  {
  1433                //Using  new hospit al locatio n and loca l notes lo okup field s
  1434                var vcmn _localTitl e = Xrm.Pa ge.getAttr ibute('ftp _localnote title').ge tValue();
  1435                if (vcmn _localTitl e == null)  {
  1436                    aler t('The loc al note ti tle field  is empty,  the note c annot be c reated in  VistA/CPRS !');
  1437                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1438                    retu rn false;
  1439                }
  1440                else { v cmn_localT itle = vcm n_localTit le[0].name ; }
  1441  
  1442                vcmn_pat ientAssign edLocation  = Xrm.Pag e.getAttri bute('ftp_ notehospit allocation ').getValu e();
  1443                if (vcmn _patientAs signedLoca tion == nu ll) {
  1444                    aler t('The hos pital loca tion field  is empty,  the note  cannot be  created in  VistA/CPR S!');
  1445                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1446                    retu rn false;
  1447                }
  1448                else { v cmn_patien tAssignedL ocation =  vcmn_patie ntAssigned Location[0 ].name; }
  1449           }
  1450  
  1451           va r vcmn_cal lbackNumbe r = Xrm.Pa ge.getAttr ibute('ftp _callbackn umber').ge tValue();
  1452           if  (vcmn_cal lbackNumbe r == null  || vcmn_ca llbackNumb er == '')  {
  1453                alert('T he callbac k number f ield is em pty, the n ote cannot  be create d in VistA /CPRS!');
  1454                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1455                return f alse;
  1456           }
  1457           va r vcmn_rea sonForRequ est = Xrm. Page.getAt tribute('f tp_reasonf orrequest' ).getValue ();
  1458           if  (vcmn_rea sonForRequ est == nul l) {
  1459                alert('T he reason  for reques t field is  empty, th e note can not be cre ated in Vi stA/CPRS!' );
  1460                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1461                return f alse;
  1462           }
  1463  
  1464           va r vcmn_enc ounterCode  = 'NEW';
  1465  
  1466           va r vcmn_sig nThisNote  = Xrm.Page .getAttrib ute('ftp_s ignthisnot e').getVal ue();
  1467           if  (vcmn_sig nThisNote  == 1000000 01) { vcmn _signThisN ote = true ; } else {  vcmn_sign ThisNote =  false; }
  1468  
  1469           // Get Progre ss Note Gu id/Id
  1470           va r vcmn_not eId = Xrm. Page.data. entity.get Id();
  1471  
  1472           // Get Create d On Date  & Convert  format
  1473           va r vcmn_cre atedOnDate  = vcmn_co nvertCrmDa teToVistAD ate(Xrm.Pa ge.getAttr ibute('cre atedon').g etValue()) ;
  1474           if  (vcmn_cre atedOnDate  == null)  {
  1475                alert('T he CRM cre atedon fie ld is empt y, the not e cannot b e created  in VistA/C PRS!');
  1476                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1477                return f alse;
  1478           }
  1479  
  1480           // Get User E ntry Date
  1481           va r vcmn_use rEntryDate  = vcmn_co nvertCrmDa teToVistAD ate(Xrm.Pa ge.getAttr ibute('ftp _userentry date').get Value());
  1482           if  (vcmn_use rEntryDate  == null)  { vcmn_use rEntryDate  = vcmn_cr eatedOnDat e; }
  1483  
  1484           // Get Facili ty and loo kup facili ty number  and HL7 UR L
  1485           va r vcmn_fac ilityCode  = '';
  1486           va r vcmn_sit eHL7Listen erAddress  = '';
  1487           va r vcmn_pat ientFacili ty = Xrm.P age.getAtt ribute('ft p_patientf acility'). getValue() ;
  1488           if  (vcmn_pat ientFacili ty == null ) {
  1489                alert('T he CRM pat ient facil ity field  is empty,  the note c annot be c reated in  VistA/CPRS !');
  1490                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1491                return f alse;
  1492           }
  1493           el se {
  1494                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e, ftp_hl7 listener',  vcmn_pati entFacilit y[0].id);
  1495                if (vcmn _facilityD ata.d.ftp_ facilityco de != null ) {
  1496                    vcmn _facilityC ode = vcmn _facilityD ata.d.ftp_ facilityco de;
  1497                }
  1498                else {
  1499                    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!') ;
  1500                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1501                    retu rn false;
  1502                }
  1503  
  1504                if (vcmn _facilityD ata.d.ftp_ hl7listene r != null)  {
  1505                    var  vcmn_siteH L7Listener Address =  vcmn_facil ityData.d. ftp_hl7lis tener;
  1506                }
  1507                else {
  1508                    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!');
  1509                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1510                    retu rn false;
  1511                }
  1512           }
  1513  
  1514           va r vcmn_ori ginatorID  = '';
  1515           va r vcmn_use rSiteNo =  '';
  1516  
  1517           // Lookup the  Facility/ Site #
  1518           if  (vcmn_use rSiteId !=  null && v cmn_userSi teId != '' ) {
  1519                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e', vcmn_u serSiteId) ;
  1520                if (vcmn _facilityD ata != nul l) {
  1521                    if ( vcmn_facil ityData.d. ftp_facili tycode !=  null) { vc mn_userSit eNo = vcmn _facilityD ata.d.ftp_ facilityco de; }
  1522                }
  1523           }
  1524  
  1525           // Validate r equired Vi sta Lookup  info
  1526           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) {
  1527                //Abort  process, m issing inf o
  1528                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 !');
  1529                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1530                return f alse;
  1531           }
  1532  
  1533           if  (Xrm.Page .getAttrib ute('ftp_i sworkloade ncounter') .getValue( ) != true)  {
  1534                if (vcmn _IsProduct ionEnviron ment == fa lse) {
  1535                    //Pr ovide the  option to  search for  Lori Nich olls, site # 613
  1536                    var  vcmn_imper sonateProm ptString =  "**THIS I S A VISTA  USER SEARC H TEST PRO MPT** \n"  +
  1537                         "If you wo uld like t o imperson ate the us er: \n" +
  1538                         "Lori Nich olls (613)  \n" +
  1539                         "Select OK .  Otherwi se, select  CANCEL.";
  1540                    var  vcmn_confi rmImperson ateVistaUs er = confi rm(vcmn_im personateP romptStrin g);
  1541                    if ( vcmn_confi rmImperson ateVistaUs er == true ) {
  1542                         vcmn_userF irstName =  "Lori";
  1543                         vcmn_userL astName =  "Nicholls" ;
  1544                         vcmn_userS iteNo = "6 13";
  1545                    }
  1546                }
  1547  
  1548                var vcmn _vistauser sData = vc mn_getVist aUsersData (vcmn_user FirstName,  vcmn_user LastName,  vcmn_userS iteNo, fal se);
  1549  
  1550                //Check  vista user s data con tent
  1551                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) {
  1552                    //Ab ort proces s, missing  info
  1553                    aler t('Unable  to obtain  Vista User  Data, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  1554                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1555                    retu rn false;
  1556                }
  1557  
  1558                var vcmn _selectedU serFirstNa me = '';
  1559                var vcmn _selectedU serMiddleN ame = '';
  1560                var vcmn _selectedU serLastNam e = '';
  1561                var vcmn _selectedU serSuffix  = '';
  1562                var vcmn _selectedU serDisplay Name = '';
  1563                var vcmn _selectedU serTitle =  '';
  1564                var vcmn _userIsSel ected = fa lse;
  1565  
  1566                if (vcmn _vistauser sData.Data .length >  1) {
  1567                    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! ");
  1568                    for  (var i = 0 ; i <= vcm n_vistause rsData.Dat a.length -  1; i++) {
  1569                         var vcmn_c urrentUser FirstName  = '';
  1570                         var vcmn_c urrentUser MiddleName  = '';
  1571                         var vcmn_c urrentUser LastName =  '';
  1572                         var vcmn_c urrentUser Suffix = ' ';
  1573                         var vcmn_c urrentUser DisplayNam e = '';
  1574                         var vcmn_c urrentUser Title = '' ;
  1575                         if (vcmn_v istausersD ata.Data[i ].FirstNam e != null)  { vcmn_cu rrentUserF irstName =  vcmn_vist ausersData .Data[i].F irstName;  }
  1576                         if (vcmn_v istausersD ata.Data[i ].MiddleNa me != null ) { vcmn_c urrentUser MiddleName  = vcmn_vi stausersDa ta.Data[i] .MiddleNam e; }
  1577                         if (vcmn_v istausersD ata.Data[i ].LastName  != null)  { vcmn_cur rentUserLa stName = v cmn_vistau sersData.D ata[i].Las tName; }
  1578                         if (vcmn_v istausersD ata.Data[i ].Suffix ! = null) {  vcmn_curre ntUserSuff ix = vcmn_ vistausers Data.Data[ i].Suffix;  }
  1579                         if (vcmn_v istausersD ata.Data[i ].DisplayN ame != nul l) { vcmn_ currentUse rDisplayNa me = vcmn_ vistausers Data.Data[ i].Display Name; }
  1580                         if (vcmn_v istausersD ata.Data[i ].Title !=  null) { v cmn_curren tUserTitle  = vcmn_vi stausersDa ta.Data[i] .Title; }
  1581                         //Prompt u ser about  this vista  user reco rd
  1582                         var vcmn_u serPromptS tring = "C lick OK, t o select t his user.   Otherwise  CANCEL \n " +
  1583                             "\n Fi rst Name:  " + vcmn_c urrentUser FirstName  +
  1584                             "\n Mi ddle Name:  " + vcmn_ currentUse rMiddleNam e +
  1585                             "\n La st Name: "  + vcmn_cu rrentUserL astName +
  1586                             "\n Su ffix: " +  vcmn_curre ntUserSuff ix +
  1587                             "\n Di splay Name : " + vcmn _currentUs erDisplayN ame +
  1588                             "\n Ti tle: " + v cmn_curren tUserTitle ;
  1589  
  1590                         var vcmn_c onfirmSele ctVistaUse r = confir m(vcmn_use rPromptStr ing);
  1591                         if (vcmn_c onfirmSele ctVistaUse r == true)  {
  1592                             vcmn_u serIsSelec ted = true ;
  1593                             vcmn_s electedUse rFirstName  = vcmn_cu rrentUserF irstName;
  1594                             vcmn_s electedUse rMiddleNam e = vcmn_c urrentUser MiddleName ;
  1595                             vcmn_s electedUse rLastName  = vcmn_cur rentUserLa stName;
  1596                             vcmn_s electedUse rSuffix =  vcmn_curre ntUserSuff ix;
  1597                             vcmn_s electedUse rDisplayNa me = vcmn_ currentUse rDisplayNa me;
  1598                             vcmn_s electedUse rTitle = v cmn_curren tUserTitle ;
  1599                             break;
  1600                         }
  1601                    }
  1602                }
  1603                else {
  1604                    //Se lect data  from the f irst recor d
  1605                    vcmn _userIsSel ected = tr ue;
  1606                    if ( vcmn_vista usersData. Data[0].Fi rstName !=  null) { v cmn_select edUserFirs tName = vc mn_vistaus ersData.Da ta[0].Firs tName; }
  1607                    if ( vcmn_vista usersData. Data[0].Mi ddleName ! = null) {  vcmn_selec tedUserMid dleName =  vcmn_vista usersData. Data[0].Mi ddleName;  }
  1608                    if ( vcmn_vista usersData. Data[0].La stName !=  null) { vc mn_selecte dUserLastN ame = vcmn _vistauser sData.Data [0].LastNa me; }
  1609                    if ( vcmn_vista usersData. Data[0].Su ffix != nu ll) { vcmn _selectedU serSuffix  = vcmn_vis tausersDat a.Data[0]. Suffix; }
  1610                    if ( vcmn_vista usersData. Data[0].Di splayName  != null) {  vcmn_sele ctedUserDi splayName  = vcmn_vis tausersDat a.Data[0]. DisplayNam e; }
  1611                    if ( vcmn_vista usersData. Data[0].Ti tle != nul l) { vcmn_ selectedUs erTitle =  vcmn_vista usersData. Data[0].Ti tle; }
  1612                }
  1613  
  1614                //Check  if a user  was select ed
  1615                if (vcmn _userIsSel ected == f alse) {
  1616                    aler t('A user  was not se lected fro m the prev ious promp ts, the no te cannot  be created  in VistA/ CPRS!');
  1617                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1618                    retu rn false;
  1619                }
  1620  
  1621                //Execut e Integrat ion
  1622                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);
  1623  
  1624           }
  1625           el se {
  1626                //Execut e workload  encounter  note inte gration st eps
  1627                vcmn_pre pWorkloadE ncounterIn tegrationS tep01();
  1628           }
  1629       }
  1630       catch  (err) {
  1631           al ert('Progr ess Note R ibbon Func tion Error (vcmn_ribb onButtonSa veToVistA_ with_ICN):  ' + err.m essage);
  1632           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1633       }
  1634   }
  1635  
  1636   function v cmn_prepWo rkloadEnco unterInteg rationStep 01() {
  1637       try {
  1638           // Verify Not e Title
  1639           va r vcmn_Not eTitleIEN  = Xrm.Page .getAttrib ute('ftp_s electedwor kloadnotet itleid').g etValue();
  1640           if  (vcmn_Not eTitleIEN  == null ||  vcmn_Note TitleIEN = = '') {
  1641                alert('T he selecte d note tit le field i s empty, t he note ca nnot be cr eated in V istA/CPRS! ');
  1642                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1643                return f alse;
  1644           }
  1645           // Verify Loc ation
  1646           va r vcmn_Loc ationIEN =  Xrm.Page. getAttribu te('ftp_se lectedwork loadlocati onid').get Value();
  1647           if  (vcmn_Loc ationIEN = = null ||  vcmn_Locat ionIEN ==  '') {
  1648                alert('T he selecte d location  field is  empty, the  note cann ot be crea ted in Vis tA/CPRS!') ;
  1649                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1650                return f alse;
  1651           }
  1652           // Verify pat ient id
  1653           if  (vcmn_mat chLookupId  == null | | vcmn_mat chLookupId  == '') {
  1654                alert('T he veteran /patient d oes not ha ve a SSN,  the note c annot be c reated in  VistA/CPRS !');
  1655                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1656                return f alse;
  1657           }
  1658  
  1659           // Get the cu rrent CRM  User's ass igned site /facility
  1660           va r vcmn_use rSiteId =  "";
  1661  
  1662           va r vcmn_use rData = vc mn_getSing leEntityDa taSync('Sy stemUserSe t', 'ftp_F acilitySit eId', Xrm. Page.conte xt.getUser Id());
  1663           if  (vcmn_use rData != n ull) {
  1664                if (vcmn _userData. d.ftp_Faci litySiteId  != null)  {
  1665                    vcmn _userSiteI d = vcmn_u serData.d. ftp_Facili tySiteId.I d;
  1666                }
  1667           }
  1668  
  1669           // Lookup the  Facility/ Site #
  1670           if  (vcmn_use rSiteId !=  null && v cmn_userSi teId != '' ) {
  1671                var vcmn _facilityD ata = vcmn _getSingle EntityData Sync('ftp_ facilitySe t', 'ftp_f acilitycod e', vcmn_u serSiteId) ;
  1672                if (vcmn _facilityD ata != nul l) {
  1673                    if ( vcmn_facil ityData.d. ftp_facili tycode !=  null) { vc mn_ViaLogi nFacility  = vcmn_fac ilityData. d.ftp_faci litycode;  }
  1674                }
  1675           }
  1676  
  1677           // Check if V IA Login c ookie exis t (not exp ired)
  1678           va r vcmn_Via LoginCooki e = vcmn_g etCookie(" viasession link");
  1679           if  (vcmn_Via LoginCooki e != null  && vcmn_Vi aLoginCook ie != '')  {
  1680                var vcmn _cookiearr ay = vcmn_ ViaLoginCo okie.split ("~~~~", 2 );
  1681                vcmn_Via LoginToken  = vcmn_co okiearray[ 0];
  1682                vcmn_Via LoginName  = vcmn_coo kiearray[1 ];
  1683           }
  1684           el se {
  1685                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!") ;
  1686                Xrm.Page .ui.tabs.g et('Tab_Vi stALogin') .setVisibl e(true);
  1687                Xrm.Page .ui.tabs.g et('Tab_Vi stALogin') .setFocus( );
  1688                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1689                return;
  1690           }
  1691  
  1692           // Lookup Pat ient Id us ing VIA 'm atch' serv ice
  1693           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);
  1694       }
  1695       catch  (err) {
  1696           al ert('Progr ess Note R ibbon Func tion Error (vcmn_prep WorkloadEn counterInt egrationSt ep01): ' +  err.messa ge);
  1697           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1698       }
  1699   }
  1700  
  1701   function v cmn_prepWo rkloadEnco unterInteg rationStep 01_respons e(vcmn_err or, vcmn_m atchrespon se) {
  1702       try {
  1703           // Check for  non VIA se rvice erro r
  1704           if  (vcmn_err or != null ) {
  1705                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!") ;
  1706                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1707                return f alse;
  1708           }
  1709           el se {
  1710                //Test f or VIA Ser vice Error
  1711                if (vcmn _matchresp onse.getEl ementsByTa gName("fau lt").lengt h > 0) {
  1712                    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 !");
  1713                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1714                    retu rn false;
  1715                }
  1716                //Get VI A service  Response
  1717                if (vcmn _matchresp onse.getEl ementsByTa gName("pat ients")[0] ) {
  1718                    var  vcmn_match Array = vc mn_matchre sponse.get ElementsBy TagName("p atients")[ 0].childNo des;
  1719                    //ch ildNodes[4 ] holds th e localPid /IEN value
  1720                    vcmn _ViaPatien tId = vcmn _matchArra y[0].child Nodes[4].t extContent ;
  1721                }
  1722                else {
  1723                    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 !");
  1724                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1725                    retu rn false;
  1726                }
  1727           }
  1728  
  1729           // Verify Inp atient
  1730           if  (Xrm.Page .getAttrib ute('ftp_w orkloadinp atient').g etValue()  == true) {
  1731                vcmn_Via InPatient  = "1";
  1732           }
  1733           el se {
  1734                vcmn_Via InPatient  = "0";
  1735           }
  1736  
  1737           // Verify CPT  Code & De scription
  1738           va r vcmn_Crm CptCode =  Xrm.Page.g etAttribut e('ftp_cpt code').get Value();
  1739           if  (vcmn_Crm CptCode ==  null) {
  1740                alert('T he CPT Cod e field is  empty, th e note can not be cre ated in Vi stA/CPRS!' );
  1741                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1742                return f alse;
  1743           }
  1744           el se {
  1745                var vcmn _cptData =  vcmn_getS ingleEntit yDataSync( 'ftp_cptco deSet', 'f tp_amadesc ription',  vcmn_CrmCp tCode[0].i d);
  1746                if (vcmn _cptData.d .ftp_amade scription  != null) {
  1747                    vcmn _ViaCptDes cription =  (vcmn_cpt Data.d.ftp _amadescri ption).rep lace(";",  "\;");
  1748                    vcmn _ViaCptCod e = vcmn_C rmCptCode[ 0].name;
  1749                }
  1750                else {
  1751                    aler t('The CPT  Code is m issing the  AMA Descr iption, th e note can not be cre ated in Vi stA/CPRS!' );
  1752                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1753                    retu rn false;
  1754                }
  1755           }
  1756  
  1757           // Combine CP T Code and  Descripti on
  1758           va r vcmn_Cpt Combined =  '';
  1759           if  (vcmn_Via CptCode.le ngth > 0 & & vcmn_Via CptDescrip tion.lengt h > 0) {
  1760                vcmn_Cpt Combined =  vcmn_ViaC ptCode + " ^" + vcmn_ ViaCptDesc ription;
  1761           }
  1762  
  1763           // Verify Dia gnosis Cod e & Descri ption
  1764           va r vcmn_Crm DiagnosisC ode = Xrm. Page.getAt tribute('f tp_diagnos iscode').g etValue();
  1765           if  (vcmn_Crm DiagnosisC ode != nul l && vcmn_ CrmDiagnos isCode !=  '') {
  1766                var vcmn _diagnosis Data = vcm n_getSingl eEntityDat aSync('ftp _diagnosis codeSet',  'ftp_descr iption', v cmn_CrmDia gnosisCode [0].id);
  1767                if (vcmn _diagnosis Data.d.ftp _descripti on != null ) {
  1768                    vcmn _ViaDiagno sisDescrip tion = (vc mn_diagnos isData.d.f tp_descrip tion).repl ace(";", " \;");
  1769                    vcmn _ViaDiagno sisCode =  vcmn_CrmDi agnosisCod e[0].name;
  1770                }
  1771           }
  1772  
  1773           // Combine Di agnosis Co de and Des cription a nd mark as  PRIMARY ( ^1)
  1774           va r vcmn_Dia gnosisComb ined = '';
  1775           if  (vcmn_Via DiagnosisC ode != nul l && vcmn_ ViaDiagnos isDescript ion != nul l) {
  1776                if (vcmn _ViaDiagno sisCode.le ngth > 0 & & vcmn_Via DiagnosisD escription .length >  0) {
  1777                    vcmn _Diagnosis Combined =  vcmn_ViaD iagnosisCo de + "^" +  vcmn_ViaD iagnosisDe scription  + "^1";
  1778                }
  1779           }
  1780  
  1781           // Get Second ary Diagno sis Codes
  1782           va r vcmn_Crm SecondaryD iagnosis =  Xrm.Page. getAttribu te('ftp_se lectedseco ndarydiagn osiscodes' ).getValue ();
  1783           if  (vcmn_Crm SecondaryD iagnosis ! = null &&  vcmn_CrmSe condaryDia gnosis !=  '') {
  1784                if (vcmn _Diagnosis Combined ! = '') {
  1785                    vcmn _Diagnosis Combined =  vcmn_Diag nosisCombi ned + ";"  + vcmn_Crm SecondaryD iagnosis;
  1786                }
  1787                else { v cmn_Diagno sisCombine d = vcmn_C rmSecondar yDiagnosis ; }
  1788           }
  1789  
  1790           // Get eSigna ture code
  1791           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 !");
  1792           if  (vcmn_eSi gnatureCod e == null  || vcmn_eS ignatureCo de == "" | | vcmn_eSi gnatureCod e == "unde fined") {
  1793                alert('T he eSignat ure Code e ntered is  invalid, t he note ca nnot be cr eated in V istA/CPRS! ');
  1794                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1795                return f alse;
  1796           }
  1797  
  1798           // Get User E ntry Date
  1799           va r vcmn_cre atedOnDate  = vialib_ convertToS tringDateT ime(Xrm.Pa ge.getAttr ibute('cre atedon').g etValue()) ;
  1800           va r vcmn_use rEntryDate  = null;
  1801           if  (Xrm.Page .getAttrib ute('ftp_u serentryda te').getVa lue() != n ull) {
  1802                vcmn_use rEntryDate  = vialib_ convertToS tringDateT ime(Xrm.Pa ge.getAttr ibute('ftp _userentry date').get Value());
  1803           }
  1804           if  (vcmn_use rEntryDate  == null)  { vcmn_use rEntryDate  = vcmn_cr eatedOnDat e; }
  1805  
  1806           // Reformat N ote Descri ption as n eeded to h andle long  lines of  text (Word Wrap)
  1807           va r vcmn_not eDescripti on = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  1808           va r vcmn_Not eText = vc mn_noteDes cription;
  1809           va r vcmn_Rev isedNoteTe xt = "";
  1810           // Do Breakdo wn of line s
  1811           va r vcmn_Tex tLines = v cmn_NoteTe xt.split(' \n');
  1812           if  (vcmn_Tex tLines.len gth > 0) {
  1813                //Reform at text
  1814                for (var  i = 0; i  < vcmn_Tex tLines.len gth; i++)  {
  1815                    //Te st for a l ong line
  1816                    if ( vcmn_TextL ines[i].le ngth > vcm n_WordWrap Limit) {
  1817                         //Break do wn line
  1818                         var vcmn_N ewString =  vcmn_word Wrap(vcmn_ TextLines[ i], vcmn_W ordWrapLim it, '\n');
  1819                         //Add revi sed text b ack
  1820                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _NewString  + "\n";   //Add back  the CR/LF  used to s plit on
  1821                    }
  1822                    else  {
  1823                         //Add text  to new no te
  1824                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _TextLines [i] + "\n" ; //Add ba ck the CR/ LF used to  split on
  1825                    }
  1826                }
  1827           }
  1828           if  (vcmn_Rev isedNoteTe xt != "" & & vcmn_Rev isedNoteTe xt != null ) {
  1829                vcmn_not eDescripti on = vcmn_ RevisedNot eText;
  1830           }
  1831  
  1832           // Add list o f addition al signer  names to N ote Text i f they exi sts
  1833           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  1834                //Create  text stri ngs from a dditional  signers ar ray
  1835                var vcmn _SignerNam es = "\nAd ditional N ote Signer s\n" + "-- ---------- ---------- -------\n" ;
  1836                for (var  i = 0; i  <= vcmn_Ad dlSignersN ameArray.l ength - 1;  i++) {
  1837                    if ( i >= 1) {
  1838                         var vcmn_s ingleSigne rName = vc mn_AddlSig nersNameAr ray[i].spl it("___");
  1839                         vcmn_Signe rNames = v cmn_Signer Names + vc mn_singleS ignerName[ 1] + "\n";
  1840                    }
  1841                }
  1842                //Add to  Note Desc ription
  1843                vcmn_not eDescripti on = vcmn_ noteDescri ption + vc mn_SignerN ames;
  1844           }
  1845           va r vcmn_Not eTitleIEN  = Xrm.Page .getAttrib ute('ftp_s electedwor kloadnotet itleid').g etValue();
  1846           va r vcmn_Loc ationIEN =  Xrm.Page. getAttribu te('ftp_se lectedwork loadlocati onid').get Value();
  1847  
  1848           // Create tex t strings  from addit ional sign ers array
  1849           va r vcmn_Sig nerIEN = " ";
  1850           if  (vcmn_Add lSignersIe nArray !=  null) {
  1851                for (var  i = 0; i  <= vcmn_Ad dlSignersI enArray.le ngth - 1;  i++) {
  1852                    if ( i == 1) {  vcmn_Signe rIEN = vcm n_AddlSign ersIenArra y[i]; }
  1853                    if ( i > 1) { v cmn_Signer IEN = vcmn _SignerIEN  + "," + v cmn_AddlSi gnersIenAr ray[i]; }
  1854                }
  1855           }
  1856  
  1857           // Execute VI A saveNote AndEncount er Service
  1858           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)
  1859       }
  1860       catch  (err) {
  1861           al ert('Progr ess Note R ibbon Func tion Error (vcmn_prep WorkloadEn counterInt egrationSt ep01_respo nse): ' +  err.messag e);
  1862           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1863       }
  1864   }
  1865  
  1866   function v cmn_saveNo teAndEncou nter_respo nse(vcmn_e rrorThrown , vcmn_req uestRespon se, vcmn_n oteText) {
  1867       //Proc ess Note a nd Encount er Respons e
  1868       try {
  1869           if  (vcmn_err orThrown ! = null) {
  1870                //Write  Error
  1871                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etValue('E RROR');
  1872                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etSubmitMo de('always ');
  1873                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tValue(Str ing(vcmn_e rrorThrown ));
  1874                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tSubmitMod e('always' );
  1875                Xrm.Page .getAttrib ute('ftp_i ntegration date').set Value(new  Date());
  1876                Xrm.Page .getAttrib ute('ftp_i ntegration date').set SubmitMode ('always') ;
  1877                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etValue('' );
  1878                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etSubmitMo de('always ');
  1879                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. ');
  1880                Xrm.Page .getContro l('ftp_int egrationer ror').setF ocus();
  1881                Xrm.Page .data.enti ty.save();
  1882                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  1883                return f alse;
  1884           }
  1885           el se {
  1886                //Write  web servic e response  Success o r Failure
  1887                if (vcmn _requestRe sponse.get ElementsBy TagName("f ault").len gth > 0) {
  1888                    //Wr ite Failur e entry
  1889                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setValu e('ERROR') ;
  1890                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setSubm itMode('al ways');
  1891                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setValue ("Service  Error: " +  vcmn_requ estRespons e.getEleme ntsByTagNa me("fault" )[0].textC ontent);
  1892                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setSubmi tMode('alw ays');
  1893                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setValue( new Date() );
  1894                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setSubmit Mode('alwa ys');
  1895                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setValu e('');
  1896                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setSubm itMode('al ways');
  1897                    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.');
  1898                    Xrm. Page.getCo ntrol('ftp _integrati onerror'). setFocus() ;
  1899                    Xrm. Page.data. entity.sav e();
  1900                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  1901                    retu rn false;
  1902                }
  1903                else {
  1904                    //Te st for dat a
  1905                    if ( vcmn_reque stResponse .getElemen tsByTagNam e("ns2:sav eNoteAndEn counterRes ponse")[0] ) {
  1906                         //Sucessfu ll creatio n of workl oad encoun ter note
  1907                         Xrm.Page.g etAttribut e('ftp_not edetail'). setValue(v cmn_noteTe xt);
  1908                         Xrm.Page.g etAttribut e('ftp_not edetail'). setSubmitM ode('alway s');
  1909                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set Value('OK' );
  1910                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set SubmitMode ('always') ;
  1911                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setV alue(null) ;
  1912                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setS ubmitMode( 'always');
  1913                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setVa lue(new Da te());
  1914                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setSu bmitMode(' always');
  1915                         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);
  1916                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set SubmitMode ('always') ;
  1917                         //****UPDA TE e-Sign  attributes
  1918                         Xrm.Page.g etAttribut e('ftp_iss igned').se tValue(tru e);
  1919                         Xrm.Page.g etAttribut e('ftp_iss igned').se tSubmitMod e('always' );
  1920                         Xrm.Page.g etAttribut e('ftp_sig neddate'). setValue(n ew Date()) ;
  1921                         Xrm.Page.g etAttribut e('ftp_sig neddate'). setSubmitM ode('alway s');
  1922                         //******** ********** **********
  1923                         Xrm.Page.g etControl( 'ftp_integ rationstat us').setFo cus();
  1924                         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!');
  1925                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1926                         Xrm.Page.d ata.entity .save();
  1927  
  1928                         if (vcmn_l ocalStorag eVarName ! = "" && vc mn_localSt orageVarNa me != null ) {
  1929                             //Clea r existing  session s torage var iable.
  1930                             localS torage.rem oveItem(vc mn_localSt orageVarNa me);
  1931                         }
  1932                    }
  1933                    else  {
  1934                         //Write No  Data Fail ure
  1935                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set Value('ERR OR');
  1936                         Xrm.Page.g etAttribut e('ftp_int egrationst atus').set SubmitMode ('always') ;
  1937                         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 !");
  1938                         Xrm.Page.g etAttribut e('ftp_int egrationer ror').setS ubmitMode( 'always');
  1939                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setVa lue(new Da te());
  1940                         Xrm.Page.g etAttribut e('ftp_int egrationda te').setSu bmitMode(' always');
  1941                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set Value('');
  1942                         Xrm.Page.g etAttribut e('ftp_int egrationno teid').set SubmitMode ('always') ;
  1943                         alert('The  workload  encounter  note creat ion in Vis tA/CPRS fa iled!\nPle ase see th e integrat ion error  field for  details.') ;
  1944                         Xrm.Page.g etControl( 'ftp_integ rationerro r').setFoc us();
  1945                         Xrm.Page.d ata.entity .save();
  1946                         Xrm.Page.u i.clearFor mNotificat ion("SAVEV ISTA");
  1947                         return fal se;
  1948                    }
  1949                }
  1950           }
  1951       }
  1952       catch  (err) {
  1953           al ert('Progr ess Note R ibbon Func tion Error (vcmn_save NoteAndEnc ounter_res ponse): '  + err.mess age);
  1954           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  1955       }
  1956   }
  1957  
  1958   function v cmn_getVis taUsersDat a(vcmn_use rFirstName , vcmn_use rLastName,  vcmn_user SiteNo, vc mn_noFilte r) {
  1959       try {
  1960           va r vcmn_jso nData = nu ll;
  1961           $. ajax({
  1962                type: "G ET",
  1963                url: vcm n_VistaUse rsURLbase  + vcmn_use rFirstName  + "/" + v cmn_userLa stName + " /" + vcmn_ userSiteNo  + "?noFil ter=" + vc mn_noFilte r,
  1964                contentT ype: "appl ication/js on; charse t=utf-8",
  1965                dataType : "json",
  1966                success:  function  (data) {
  1967                    vcmn _jsonData  = data;
  1968                },
  1969                error: f unction (j qXHR, text Status, er rorThrown)  {
  1970                    //Sy stem Error
  1971                    vcmn _jsonData  = null;
  1972                },
  1973                async: f alse,
  1974                cache: f alse
  1975           }) ;
  1976           re turn vcmn_ jsonData;
  1977       }
  1978       catch  (err) {
  1979           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getV istaUsersD ata): ' +  err.messag e);
  1980           re turn null;
  1981       }
  1982   }
  1983  
  1984   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) {
  1985       try {
  1986           // Reformat N ote Descri ption as n eeded to h andle long  lines of  text (Word Wrap)
  1987           va r vcmn_Not eText = vc mn_noteDes cription;
  1988           va r vcmn_Rev isedNoteTe xt = "";
  1989           // Do Breakdo wn of line s
  1990           va r vcmn_Tex tLines = v cmn_NoteTe xt.split(' \n');
  1991           if  (vcmn_Tex tLines.len gth > 0) {
  1992                //Reform at text
  1993                for (var  i = 0; i  < vcmn_Tex tLines.len gth; i++)  {
  1994                    //Te st for a l ong line
  1995                    if ( vcmn_TextL ines[i].le ngth > vcm n_WordWrap Limit) {
  1996                         //Break do wn line
  1997                         var vcmn_N ewString =  vcmn_word Wrap(vcmn_ TextLines[ i], vcmn_W ordWrapLim it, '\n');
  1998                         //Add revi sed text b ack
  1999                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _NewString  + "\n";   //Add back  the CR/LF  used to s plit on
  2000                    }
  2001                    else  {
  2002                         //Add text  to new no te
  2003                         vcmn_Revis edNoteText  = vcmn_Re visedNoteT ext + vcmn _TextLines [i] + "\n" ; //Add ba ck the CR/ LF used to  split on
  2004                    }
  2005                }
  2006           }
  2007           if  (vcmn_Rev isedNoteTe xt != "" & & vcmn_Rev isedNoteTe xt != null ) {
  2008                vcmn_not eDescripti on = vcmn_ RevisedNot eText;
  2009           }
  2010  
  2011           // Add list o f addition al signer  names to N ote Text i f they exi sts
  2012           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  2013                //Create  text stri ngs from a dditional  signers ar ray
  2014                var vcmn _SignerNam es = "\nAd ditional N ote Signer s\n" + "-- ---------- ---------- -------\n" ;
  2015                for (var  i = 0; i  <= vcmn_Ad dlSignersN ameArray.l ength - 1;  i++) {
  2016                    if ( i >= 1) {
  2017                         var vcmn_s ingleSigne rName = vc mn_AddlSig nersNameAr ray[i].spl it("___");
  2018                         vcmn_Signe rNames = v cmn_Signer Names + vc mn_singleS ignerName[ 1] + "\n";
  2019                    }
  2020                }
  2021                //Add to  Note Desc ription
  2022                vcmn_not eDescripti on = vcmn_ noteDescri ption + vc mn_SignerN ames;
  2023           }
  2024  
  2025           va r vcmn_vis itNumber =  'NEW';
  2026           va r vcmn_cli entName =  "FTPCRM";
  2027           va r vcmn_For mat = "JSO N";
  2028           va r vcmn_pat ientIdenti fierType =  "ICN";
  2029           va r vcmn_doc umentAvail abilitySta tus = "AV" ;  //Histo rical Note  only at t his time
  2030           va r vcmn_ori ginatorCom binedMiddl e = "";
  2031           if  (vcmn_ori ginatorMid dleName !=  '' && vcm n_originat orMiddleNa me != null ) { vcmn_o riginatorC ombinedMid dle = vcmn _originato rMiddleNam e; }
  2032           if  (vcmn_ori ginatorSuf fix != ''  && vcmn_or iginatorSu ffix != nu ll) {
  2033                if (vcmn _originato rCombinedM iddle != ' ') {
  2034                    vcmn _originato rCombinedM iddle = vc mn_origina torCombine dMiddle +  " " + vcmn _originato rSuffix;
  2035                }
  2036                else {
  2037                    vcmn _originato rCombinedM iddle = vc mn_origina torSuffix;
  2038                }
  2039           }
  2040  
  2041           va r vcmn_req uestJSON =  {
  2042                "ClientN ame": vcmn _clientNam e,
  2043                "Format" : vcmn_For mat,
  2044                "Facilit ySiteID":  vcmn_facil itySiteId,
  2045                "SiteHL7 ListenerAd dress": vc mn_siteHL7 ListenerAd dress,
  2046                "VisitNu mber": vcm n_visitNum ber,
  2047                "IsSigne dNote": vc mn_signThi sNote,
  2048                "Patient AdmitDate" : vcmn_pat ientAdmitD ate,
  2049                "Patient LastName":  vcmn_pati entLastNam e,
  2050                "Patient FirstName" : vcmn_pat ientFirstN ame,
  2051                "Patient Identifier ": vcmn_pa tientICN,
  2052                "Patient Identifier Type": vcm n_patientI dentifierT ype,
  2053                "Patient AssignedLo cation": v cmn_patien tAssignedL ocation,
  2054                "NoteTex t": vcmn_n oteDescrip tion,
  2055                "Origina torID": vc mn_origina torID,
  2056                "Origina torFirstNa me": vcmn_ originator FirstName,
  2057                "Origina torMiddleN ame": vcmn _originato rCombinedM iddle,
  2058                "Origina torLastNam e": vcmn_o riginatorL astName,
  2059                "Documen tFileName" : vcmn_loc alTitle,
  2060                "Documen tAvailabil ityStatus" : vcmn_doc umentAvail abilitySta tus,
  2061                "Activit yDate": vc mn_activit yDate
  2062           };
  2063  
  2064           va r vcmn_req uestRespon se = "";
  2065  
  2066           $. ajax({
  2067                type: "P OST",
  2068                url: vcm n_NoteWrit eUrl,
  2069                data: JS ON.stringi fy(vcmn_re questJSON) ,
  2070                contentT ype: "appl ication/js on; charse t=utf-8",
  2071                dataType : "json",
  2072                success:  function  (data) {
  2073                    var  vcmn_newda ta = data;
  2074                    vcmn _requestRe sponse = v cmn_newdat a;
  2075                    vcmn _vistAInte grationReq uest_respo nse(null,  vcmn_reque stResponse , vcmn_not eDescripti on);
  2076                },
  2077                error: f unction (j qXHR, text Status, er rorThrown)  {
  2078                    //Sy stem Error
  2079                    vcmn _vistAInte grationReq uest_respo nse(errorT hrown, nul l, vcmn_no teDescript ion);
  2080                },
  2081                async: f alse,
  2082                cache: f alse
  2083           }) ;
  2084       }
  2085       catch  (err) {
  2086           al ert('Progr ess Note R ibbon Func tion Error (vcmn_exec uteVistAIn tegrationR equest): '  + err.mes sage);
  2087           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2088       }
  2089   }
  2090  
  2091   function v cmn_vistAI ntegration Request_re sponse(vcm n_errorThr own, vcmn_ requestRes ponse, vcm n_noteDesc ription) {
  2092       try {
  2093           // Process In tegration  Request Re sponse
  2094           if  (vcmn_err orThrown ! = null) {
  2095                //Write  Error
  2096                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etValue('E RROR');
  2097                Xrm.Page .getAttrib ute('ftp_i ntegration status').s etSubmitMo de('always ');
  2098                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tValue(Str ing(vcmn_e rrorThrown ));
  2099                Xrm.Page .getAttrib ute('ftp_i ntegration error').se tSubmitMod e('always' );
  2100                Xrm.Page .getAttrib ute('ftp_i ntegration date').set Value(new  Date());
  2101                Xrm.Page .getAttrib ute('ftp_i ntegration date').set SubmitMode ('always') ;
  2102                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etValue('' );
  2103                Xrm.Page .getAttrib ute('ftp_i ntegration noteid').s etSubmitMo de('always ');
  2104                alert('T he note cr eation in  VistA/CPRS  failed!\n Please see  the integ ration err or field f or details .');
  2105                Xrm.Page .getContro l('ftp_int egrationer ror').setF ocus();
  2106                Xrm.Page .data.enti ty.save();
  2107                Xrm.Page .ui.clearF ormNotific ation("SAV EVISTA");
  2108                return f alse;
  2109           }
  2110           el se {
  2111                //Write  web servic e response  Success o r Failure
  2112                if (vcmn _requestRe sponse.Err orOccurred  == false)  {
  2113                    //Ca ll Additio nal Signer s & Finali ze Note fu nction
  2114                    vcmn _finalizeN oteCreatio n(vcmn_req uestRespon se.Status,  vcmn_requ estRespons e.Data, vc mn_noteDes cription)
  2115                }
  2116                else {
  2117                    //Wr ite Failur e entry
  2118                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setValu e(vcmn_req uestRespon se.Status) ;
  2119                    Xrm. Page.getAt tribute('f tp_integra tionstatus ').setSubm itMode('al ways');
  2120                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setValue (vcmn_requ estRespons e.ErrorMes sage + "   DebugInfo: " + vcmn_r equestResp onse.Debug Info);
  2121                    Xrm. Page.getAt tribute('f tp_integra tionerror' ).setSubmi tMode('alw ays');
  2122                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setValue( new Date() );
  2123                    Xrm. Page.getAt tribute('f tp_integra tiondate') .setSubmit Mode('alwa ys');
  2124                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setValu e('');
  2125                    Xrm. Page.getAt tribute('f tp_integra tionnoteid ').setSubm itMode('al ways');
  2126                    aler t('The not e creation  in VistA/ CPRS faile d!\nPlease  see the i ntegration  error fie ld for det ails.');
  2127                    Xrm. Page.getCo ntrol('ftp _integrati onerror'). setFocus() ;
  2128                    Xrm. Page.data. entity.sav e();
  2129                    Xrm. Page.ui.cl earFormNot ification( "SAVEVISTA ");
  2130                    retu rn false;
  2131                }
  2132           }
  2133       }
  2134       catch  (err) {
  2135           al ert('Progr ess Note R ibbon Func tion Error (vcmn_vist AIntegrati onRequest_ response):  ' + err.m essage);
  2136           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2137       }
  2138   }
  2139  
  2140   function v cmn_finali zeNoteCrea tion(vcmn_ integratio nStatus, v cmn_integr ationNoteI d, vcmn_no teDescript ion) {
  2141       //The  Note was s ucessfully  created i n Vista/CP RS, add ad ditional s igners if  needed
  2142       try {
  2143           // Determine  if additio nal signer s exists
  2144           if  (vcmn_Add lSignersNa meArray !=  null && v cmn_AddlSi gnersIenAr ray != nul l) {
  2145                //Get th e current  CRM User's  assigned  site/facil ity
  2146                var vcmn _userSiteI d = "";
  2147                var vcmn _UserSiteN o = "";
  2148                var vcmn _duz = "";
  2149                var vcmn _providern ame = "";
  2150  
  2151                var vcmn _userData  = vcmn_get SingleEnti tyDataSync ('SystemUs erSet', 'f tp_Facilit ySiteId',  Xrm.Page.c ontext.get UserId());
  2152                if (vcmn _userData  != null) {
  2153                    if ( vcmn_userD ata.d.ftp_ FacilitySi teId != nu ll) {
  2154                         vcmn_userS iteId = vc mn_userDat a.d.ftp_Fa cilitySite Id.Id;
  2155                    }
  2156                }
  2157  
  2158                //Lookup  the Facil ity/Site #
  2159                if (vcmn _userSiteI d != null  && vcmn_us erSiteId ! = '') {
  2160                    var  vcmn_facil ityData =  vcmn_getSi ngleEntity DataSync(' ftp_facili tySet', 'f tp_facilit ycode', vc mn_userSit eId);
  2161                    if ( vcmn_facil ityData !=  null) {
  2162                         if (vcmn_f acilityDat a.d.ftp_fa cilitycode  != null)  { vcmn_Use rSiteNo =  vcmn_facil ityData.d. ftp_facili tycode; }
  2163                    }
  2164                }
  2165  
  2166                //Check  if VIA Log in cookie  exist (not  expired)
  2167                var vcmn _ViaLoginC ookie = vc mn_getCook ie("viases sionlink") ;
  2168                if (vcmn _ViaLoginC ookie != n ull && vcm n_ViaLogin Cookie !=  '') {
  2169                    var  vcmn_cooki earray = v cmn_ViaLog inCookie.s plit("~~~~ ", 2);
  2170                    vcmn _duz = vcm n_cookiear ray[0];
  2171                    vcmn _providern ame = vcmn _cookiearr ay[1];
  2172                }
  2173  
  2174                //Create  text stri ngs from a dditional  signers ar ray
  2175                var vcmn _SignerIEN  = "";
  2176                for (var  i = 0; i  <= vcmn_Ad dlSignersI enArray.le ngth - 1;  i++) {
  2177                    if ( i == 1) {  vcmn_Signe rIEN = vcm n_AddlSign ersIenArra y[i]; }
  2178                    if ( i > 1) { v cmn_Signer IEN = vcmn _SignerIEN  + " " + v cmn_AddlSi gnersIenAr ray[i]; }
  2179                }
  2180  
  2181                //Create  the Addit ional Sign ers
  2182                var vcmn _viaSigner s = new Ob ject();
  2183                vcmn_via Signers.Pr oviderName  = vcmn_pr ovidername ;
  2184                vcmn_via Signers.Du z = vcmn_d uz;
  2185                vcmn_via Signers.Lo ginSiteCod e = vcmn_U serSiteNo;
  2186                vcmn_via Signers.Ta rget = vcm n_integrat ionNoteId;
  2187                vcmn_via Signers.Su pplemental Parameters  = vcmn_Si gnerIEN;
  2188  
  2189                $.ajax({
  2190                    type : "POST",
  2191                    url:  vcmn_AddS ignersUrl,
  2192                    data : JSON.str ingify(vcm n_viaSigne rs),
  2193                    cont entType: " applicatio n/json; ch arset=utf- 8",
  2194                    data Type: "jso n",
  2195                    succ ess: funct ion (data)  {
  2196                         vcmn_viaSi gnersRespo nse = JSON .stringify (data.Data );
  2197                         //Test for  Failure
  2198                         if (vcmn_v iaSignersR esponse.Er rorOccurre d == true)  {
  2199                             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!");
  2200                         }
  2201                    },
  2202                    erro r: functio n (jqXHR,  textStatus , errorThr own) {
  2203                         //System E rror
  2204                         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!");
  2205                    },
  2206                    asyn c: false,
  2207                    cach e: false
  2208                });
  2209  
  2210                if (vcmn _localStor ageVarName  != "" &&  vcmn_local StorageVar Name != nu ll) {
  2211                    //Cl ear existi ng session  storage v ariable.
  2212                    loca lStorage.r emoveItem( vcmn_local StorageVar Name);
  2213                }
  2214           }
  2215  
  2216           // Perform st andard for m updates  to signify  completio n
  2217           // Write Succ ess entry
  2218           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_noteDesc ription);
  2219           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  2220           Xr m.Page.get Attribute( 'ftp_integ rationstat us').setVa lue(vcmn_i ntegration Status);
  2221           Xr m.Page.get Attribute( 'ftp_integ rationstat us').setSu bmitMode(' always');
  2222           Xr m.Page.get Attribute( 'ftp_integ rationerro r').setVal ue(null);
  2223           Xr m.Page.get Attribute( 'ftp_integ rationerro r').setSub mitMode('a lways');
  2224           Xr m.Page.get Attribute( 'ftp_integ rationdate ').setValu e(new Date ());
  2225           Xr m.Page.get Attribute( 'ftp_integ rationdate ').setSubm itMode('al ways');
  2226           Xr m.Page.get Attribute( 'ftp_integ rationnote id').setVa lue(vcmn_i ntegration NoteId);
  2227           Xr m.Page.get Attribute( 'ftp_integ rationnote id').setSu bmitMode(' always');
  2228           Xr m.Page.get Control('f tp_integra tionstatus ').setFocu s();
  2229           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!');
  2230           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2231           Xr m.Page.dat a.entity.s ave();
  2232       }
  2233       catch  (err) {
  2234           al ert('Progr ess Note R ibbon Func tion Error (vcmn_fina lizeNoteCr eation): '  + err.mes sage);
  2235           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2236       }
  2237   }
  2238  
  2239   function v cmn_getCoo kie(cname)  {
  2240       try {
  2241           va r name = c name + "=" ;
  2242           va r ca = doc ument.cook ie.split(' ;');
  2243           fo r (var i =  0; i < ca .length; i ++) {
  2244                var c =  ca[i];
  2245                while (c .charAt(0)  == ' ') {
  2246                    c =  c.substrin g(1);
  2247                }
  2248                if (c.in dexOf(name ) == 0) {
  2249                    retu rn c.subst ring(name. length, c. length);
  2250                }
  2251           }
  2252           re turn "";
  2253       }
  2254       catch  (err) {
  2255           al ert('Progr ess Note R ibbon Func tion Error (vcmn_getC ookie): '  + err.mess age);
  2256       }
  2257   }
  2258  
  2259   function v cmn_initVi aDropdownC ontrols()  {
  2260       //Init ialize VIA  DropDown  Controls
  2261       //Func tion is tr iggered by  The VistA  Login Con trol and o nchange of  Facility  attribute
  2262       try {
  2263           // *Xrm.Page. getControl ("WebResou rce_Hospit alLocation ").setSrc( Xrm.Page.g etControl( "WebResour ce_Hospita lLocation" ).getSrc() );
  2264           // *Xrm.Page. getControl ("WebResou rce_LocalN otesTitle" ).setSrc(X rm.Page.ge tControl(" WebResourc e_LocalNot esTitle"). getSrc());
  2265           Xr m.Page.get Control("W ebResource _ViaWorklo adLookup") .setSrc(Xr m.Page.get Control("W ebResource _ViaWorklo adLookup") .getSrc()) ;
  2266           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());
  2267       }
  2268       catch  (err) {
  2269           al ert('Progr ess Note V IA Login F unction Er ror(vcmn_i nitViaDrop downContro ls): ' + e rr.message );
  2270       }
  2271   }
  2272  
  2273   function v cmn_facili tyGroupDef ault_respo nse(vcmn_f acilityGro upData, vc mn_lastSki p, vcmn_fa cilitySite Id) {
  2274       try {
  2275           // vcmn_lastS kip is the  starting  point in t he result  (use if mo re than 50  records)  //Not used  in this s cenario
  2276           fo r (var i =  0; i <= v cmn_facili tyGroupDat a.d.result s.length -  1; i++) {
  2277                //Get Va lues and W rite to Pr ogress Not e
  2278                if (vcmn _facilityG roupData.d .results[i ].ftp_loca lnotestitl e != null)  {
  2279                    Xrm. Page.getAt tribute("f tp_localno testitle") .setValue( vcmn_facil ityGroupDa ta.d.resul ts[i].ftp_ localnotes title);
  2280                    Xrm. Page.getAt tribute('f tp_localno testitle') .setSubmit Mode('alwa ys');
  2281                }
  2282                if (vcmn _facilityG roupData.d .results[i ].ftp_hosp itallocati on != null ) {
  2283                    Xrm. Page.getAt tribute("f tp_hospita llocation" ).setValue (vcmn_faci lityGroupD ata.d.resu lts[i].ftp _hospitall ocation);
  2284                    Xrm. Page.getAt tribute('f tp_hospita llocation' ).setSubmi tMode('alw ays');
  2285                }
  2286                break;
  2287           }
  2288       }
  2289       catch  (err) {
  2290           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_faci lityGroupD efault_res ponse): '  + err.mess age);
  2291       }
  2292   }
  2293  
  2294   function v cmn_buildQ ueryFilter (field, va lue, and)  {
  2295       try {
  2296           if  (value ==  '') {
  2297                if (and)  {
  2298                    retu rn " and "  + field +  " eq null ";
  2299                } else {
  2300                    retu rn field +  " eq null ";
  2301                }
  2302           }
  2303           el se {
  2304                if (and)  {
  2305                    retu rn " and "  + field +  " eq '" +  value + " '";
  2306                } else {
  2307                    retu rn field +  " eq '" +  value + " '";
  2308                }
  2309           }
  2310       }
  2311       catch  (err) {
  2312           al ert('Progr ess Note R ibbon Func tion Error (vcmn_buil dQueryFilt er): ' + e rr.message );
  2313           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2314       }
  2315   }
  2316  
  2317   function v cmn_unatte ndedMviSea rch(firstn ame, lastn ame, dobda te, ssn) {
  2318       try {
  2319           va r filter =  "";
  2320           va r filterPr efix = "$s elect=*&$f ilter=";
  2321           va r edipi =  "";
  2322           va r dobstrin g = "";
  2323           if  (dobdate  != null) {
  2324                dobstrin g = dobdat e;
  2325           }
  2326  
  2327           if  (ssn != " " && ssn ! = null) {
  2328                ssn = ss n.replace( /-/g, "");
  2329           }
  2330  
  2331           // if we have  edipi, se arch using  just it
  2332           if  (edipi !=  "") {
  2333                filter =  vcmn_buil dQueryFilt er("crme_E DIPI", edi pi, false) ;
  2334                filter + = vcmn_bui ldQueryFil ter("crme_ ClassCode" , 'MIL', t rue);
  2335                filter + = vcmn_bui ldQueryFil ter("crme_ SearchType ", 'Search ByIdentifi er', true) ;
  2336  
  2337                //set se arch type  as unatten ded
  2338                filter + = " and cr me_IsAtten ded eq fal se";
  2339           }
  2340           el se {
  2341                //otherw ise search  using las tname, fir stname, ss n, dob
  2342                filter =  vcmn_buil dQueryFilt er("crme_L astName",  lastname,  false); // assuming l astname wi ll never b e blank
  2343  
  2344                if (firs tname != " " && first name != nu ll) {
  2345                    filt er += vcmn _buildQuer yFilter("c rme_FirstN ame", firs tname, tru e);
  2346                }
  2347  
  2348                if (ssn  != "" && s sn != null ) {
  2349                    filt er += vcmn _buildQuer yFilter("c rme_SSN",  ssn, true) ;
  2350                }
  2351  
  2352                if (dobs tring != " ") {
  2353                    filt er += " an d crme_DOB String eq  '" + dobst ring + "'" ;
  2354                }
  2355                filter + = vcmn_bui ldQueryFil ter("crme_ SearchType ", 'Search ByFilter',  true);
  2356  
  2357                //set se arch type  as attende d (for now )
  2358                filter + = " and cr me_IsAtten ded eq tru e";
  2359           }
  2360  
  2361           fi lter = enc odeURIComp onent(filt er);
  2362           fi lter = fil terPrefix  + filter;
  2363           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);
  2364       }
  2365       catch  (err) {
  2366           al ert('Progr ess Note R ibbon Func tion Error (vcmn_unat tendedMviS earch): '  + err.mess age);
  2367           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2368       }
  2369   }
  2370  
  2371   function v cmn_unatte ndedMviSea rchCallbac k(returnDa ta) {
  2372       try {
  2373           if  (returnDa ta != null  && return Data.lengt h >= 1) {
  2374                // check  for excep tions 1st
  2375                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."))  {
  2376                    //do  nothing,  pass empty  ICN
  2377                    vcmn _ribbonBut tonSaveToV istA_with_ ICN("");
  2378                }
  2379                else {
  2380                    var  patientMvi Identifier  = returnD ata[0].crm e_PatientM viIdentifi er == null  ? "" : re turnData[0 ].crme_Pat ientMviIde ntifier;
  2381                    if ( patientMvi Identifier  != "") {
  2382                         var idpart s = patien tMviIdenti fier.split ("^");
  2383  
  2384                         if (idpart s.length >  0) {
  2385                             var na tionalId =  idparts[0 ];
  2386                             _icn =  nationalI d;
  2387                             //Pass  on the IC N and cont inue valid ation
  2388                             vcmn_r ibbonButto nSaveToVis tA_with_IC N(_icn);
  2389                         }
  2390                    }
  2391                }
  2392           }
  2393           el se {
  2394                //Return  empty ICN
  2395                vcmn_rib bonButtonS aveToVistA _with_ICN( "");
  2396           }
  2397       }
  2398       catch  (err) {
  2399           al ert('Progr ess Note R ibbon Func tion Error (vcmn_unat tendedMviS earchCallb ack): ' +  err.messag e);
  2400           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2401       }
  2402   }
  2403  
  2404   function v cmn_unatte ndedMviSea rchComplet e() {
  2405       //do n othing
  2406   }
  2407  
  2408   function v cmn_buildQ ueryFilter SCD(field,  value, an d) {
  2409       try {
  2410           if  (value ==  '') {
  2411                if (and)  {
  2412                    retu rn " and "  + field +  " eq null ";
  2413                } else {
  2414                    retu rn field +  " eq null ";
  2415                }
  2416           }
  2417           el se {
  2418                if (and)  {
  2419                    retu rn " and "  + field +  " eq '" +  value + " '";
  2420                } else {
  2421                    retu rn field +  " eq '" +  value + " '";
  2422                }
  2423           }
  2424       }
  2425       catch  (err) {
  2426           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_buil dQueryFilt erSCD): '  + err.mess age);
  2427           Xr m.Page.ui. clearFormN otificatio n("SAVEVIS TA");
  2428       }
  2429   }
  2430  
  2431   function v cmn_unatte ndedMviSea rchSCD(fir stname, la stname, do bdate, ssn ) {
  2432       try {
  2433           va r filter =  "";
  2434           va r filterPr efix = "$s elect=*&$f ilter=";
  2435           va r edipi =  "";
  2436           va r dobstrin g = "";
  2437           if  (dobdate  != null) {
  2438                dobstrin g = dobdat e;
  2439           }
  2440  
  2441           if  (ssn != " " && ssn ! = null) {
  2442                ssn = ss n.replace( /-/g, "");
  2443           }
  2444  
  2445           // if we have  edipi, se arch using  just it
  2446           if  (edipi !=  "") {
  2447                filter =  vcmn_buil dQueryFilt erSCD("crm e_EDIPI",  edipi, fal se);
  2448                filter + = vcmn_bui ldQueryFil terSCD("cr me_ClassCo de", 'MIL' , true);
  2449                filter + = vcmn_bui ldQueryFil terSCD("cr me_SearchT ype", 'Sea rchByIdent ifier', tr ue);
  2450  
  2451                //set se arch type  as unatten ded
  2452                filter + = " and cr me_IsAtten ded eq fal se";
  2453           }
  2454           el se {
  2455                //otherw ise search  using las tname, fir stname, ss n, dob
  2456                filter =  vcmn_buil dQueryFilt erSCD("crm e_LastName ", lastnam e, false);  //assumin g lastname  will neve r be blank
  2457  
  2458                if (firs tname != " " && first name != nu ll) {
  2459                    filt er += vcmn _buildQuer yFilterSCD ("crme_Fir stName", f irstname,  true);
  2460                }
  2461  
  2462                if (ssn  != "" && s sn != null ) {
  2463                    filt er += vcmn _buildQuer yFilterSCD ("crme_SSN ", ssn, tr ue);
  2464                }
  2465  
  2466                if (dobs tring != " ") {
  2467                    filt er += " an d crme_DOB String eq  '" + dobst ring + "'" ;
  2468                }
  2469                filter + = vcmn_bui ldQueryFil terSCD("cr me_SearchT ype", 'Sea rchByFilte r', true);
  2470  
  2471                //set se arch type  as attende d (for now )
  2472                filter + = " and cr me_IsAtten ded eq tru e";
  2473           }
  2474  
  2475           fi lter = enc odeURIComp onent(filt er);
  2476           fi lter = fil terPrefix  + filter;
  2477           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) ;
  2478       }
  2479       catch  (err) {
  2480           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_unat tendedMviS earchSCD):  ' + err.m essage);
  2481       }
  2482   }
  2483  
  2484   function v cmn_unatte ndedMviSea rchCallbac kSCD(retur nData) {
  2485       try {
  2486           if  (returnDa ta != null  && return Data.lengt h >= 1) {
  2487                // check  for excep tions 1st
  2488                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."))  {
  2489                    //do  nothing,  pass empty  ICN
  2490                    vcmn _getServic eConnected Disabiliti es("");
  2491                }
  2492                else {
  2493                    var  patientMvi Identifier  = returnD ata[0].crm e_PatientM viIdentifi er == null  ? "" : re turnData[0 ].crme_Pat ientMviIde ntifier;
  2494                    if ( patientMvi Identifier  != "") {
  2495                         var idpart s = patien tMviIdenti fier.split ("^");
  2496  
  2497                         if (idpart s.length >  0) {
  2498                             var na tionalId =  idparts[0 ];
  2499                             _icn =  nationalI d;
  2500                             //Pass  on the IC N and cont inue with  SCD
  2501                             vcmn_g etServiceC onnectedDi sabilities (_icn);
  2502                         }
  2503                    }
  2504                }
  2505           }
  2506           el se {
  2507                //Return  empty ICN
  2508                vcmn_get ServiceCon nectedDisa bilities(" ");
  2509           }
  2510       }
  2511       catch  (err) {
  2512           al ert('Progr ess Note F orm Load S cript Func tion Error (vcmn_unat tendedMviS earchCallb ackSCD): '  + err.mes sage);
  2513       }
  2514   }
  2515  
  2516   //Standalo ne form lo ad functio ns
  2517   function v cmn_secure ProgressNo te() {
  2518       try {
  2519           // Disable al l form att ributes if  form is o pened by a  user who  does not o wn the pro gress note
  2520           // Only handl e forms in  create st ate
  2521           if  (Xrm.Page .ui.getFor mType() !=  2) { retu rn false;  } //2 = CR M Update S tatus
  2522           // Get the cu rrent owne r of the r ecord and  compare to  the curre nt user
  2523           va r vcmn_rec ordOwnerId  = Xrm.Pag e.getAttri bute('owne rid').getV alue();
  2524           // 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
  2525           if  ((vcmn_re cordOwnerI d[0].id).t oUpperCase () != (Xrm .Page.cont ext.getUse rId()).toU pperCase() ) {
  2526                Xrm.Page .data.enti ty.attribu tes.forEac h(function  (attribut e, index)  {
  2527                    var  control =  Xrm.Page.g etControl( attribute. getName()) ;
  2528                    if ( control) {
  2529                         control.se tDisabled( true)
  2530                    }
  2531                });
  2532           }
  2533       }
  2534       catch  (err) {
  2535           al ert('Progr ess Note F orm Load F unction Er ror(vcmn_s ecureProgr essNote):  ' + err.me ssage);
  2536       }
  2537   }
  2538  
  2539   function v cmn_initFi nancialDis claimer()  {
  2540       //This  function  is used to  initialze  the Finan cial Discl aimer tab  on the pro gress note  form
  2541       try {
  2542           va r vcmn_isR eadDisclai mer = Xrm. Page.getAt tribute("f tp_isreadd isclaimer" ).getValue ();
  2543           va r vcmn_res ponseToDis claimer =  Xrm.Page.g etAttribut e("ftp_isd isclaimerr ead").getV alue();
  2544           Xr m.Page.get Attribute( "ftp_patie ntcallersr easonfordi sagreeing" ).setSubmi tMode("alw ays");
  2545           if  (vcmn_isR eadDisclai mer == tru e && vcmn_ responseTo Disclaimer  == true)  {
  2546                Xrm.Page .ui.tabs.g et("Tab_Fi nancialDis claimer"). setVisible (true);
  2547                Xrm.Page .getAttrib ute("ftp_i spatientag ree").setR equiredLev el("requir ed");
  2548                var vcmn _isPatient Agree = Xr m.Page.get Attribute( "ftp_ispat ientagree" ).getValue ();
  2549                if (vcmn _isPatient Agree == f alse) {
  2550                    Xrm. Page.getAt tribute("f tp_patient callersrea sonfordisa greeing"). setRequire dLevel("re quired");
  2551                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tVisible(t rue);
  2552                }
  2553                else { X rm.Page.ge tControl(" ftp_patien tcallersre asonfordis agreeing") .setVisibl e(false);  }
  2554           }
  2555       }
  2556       catch  (err) {
  2557           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ initFinanc ialDisclai mer): ' +  err.messag e);
  2558       }
  2559   }
  2560  
  2561   //Standalo ne form at tribute on  change ev ent functi ons
  2562   function v cmn_needTo ReadDiscla imer_OnCha nge() {
  2563       //This  function  is used to  display t he Financi al Disclai mer prompt
  2564       try {
  2565           va r vcmn_isR eadDisclai mer = Xrm. Page.getAt tribute("f tp_isreadd isclaimer" ).getValue ();
  2566           if  (vcmn_isR eadDisclai mer == tru e) {
  2567                //Financ ial Discla imer is ne eded
  2568                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.") ;
  2569                if (vcmn _responseT oDisclaime r == true)  {
  2570                    Xrm. Page.ui.ta bs.get("Ta b_Financia lDisclaime r").setVis ible(true) ;
  2571                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setValue (true);
  2572                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setSubmi tMode("alw ays");
  2573                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setRequire dLevel("re quired");
  2574                    //Se t Default  Value to N ot Agreein g and Requ ire Reason  for disag reeing
  2575                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setValue(f alse);
  2576                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setSubmitM ode("alway s");
  2577                    Xrm. Page.getAt tribute("f tp_patient callersrea sonfordisa greeing"). setRequire dLevel("re quired");
  2578                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tVisible(t rue);
  2579                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tFocus();
  2580                }
  2581                else {
  2582                    Xrm. Page.ui.ta bs.get("Ta b_Financia lDisclaime r").setVis ible(false );
  2583                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setValue (false);
  2584                    Xrm. Page.getAt tribute("f tp_isdiscl aimerread" ).setSubmi tMode("alw ays");
  2585                    Xrm. Page.getAt tribute("f tp_ispatie ntagree"). setRequire dLevel("no ne");
  2586                    Xrm. Page.getAt tribute("f tp_patient callersrea sonfordisa greeing"). setRequire dLevel("no ne");
  2587                    Xrm. Page.getCo ntrol("ftp _patientca llersreaso nfordisagr eeing").se tVisible(f alse);
  2588                }
  2589           }
  2590           el se {
  2591                //No Fin ancial Dis claimer ne eded  (Hid e Financia l Disclaim er section )
  2592                Xrm.Page .ui.tabs.g et("Tab_Fi nancialDis claimer"). setVisible (false);
  2593                Xrm.Page .getAttrib ute("ftp_i spatientag ree").setR equiredLev el("none") ;
  2594                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setR equiredLev el("none") ;
  2595                Xrm.Page .getContro l("ftp_pat ientcaller sreasonfor disagreein g").setVis ible(false );
  2596           }
  2597       }
  2598       catch  (err) {
  2599           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ needToRead Disclaimer _OnChange) : ' + err. message);
  2600       }
  2601   }
  2602  
  2603   function v cmn_isPati entInAgree ment_OnCha nge() {
  2604       try {
  2605           va r vcmn_isP atientAgre e = Xrm.Pa ge.getAttr ibute("ftp _ispatient agree").ge tValue();
  2606           if  (vcmn_isP atientAgre e == false ) {
  2607                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setR equiredLev el("requir ed");
  2608                Xrm.Page .getContro l("ftp_pat ientcaller sreasonfor disagreein g").setVis ible(true) ;
  2609           }
  2610           el se {
  2611                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setR equiredLev el("none") ;
  2612                Xrm.Page .getAttrib ute("ftp_p atientcall ersreasonf ordisagree ing").setV alue(null) ;
  2613                Xrm.Page .getContro l("ftp_pat ientcaller sreasonfor disagreein g").setVis ible(false );
  2614                //Update  Note
  2615                vcmn_app endNoteFin ancialDisc laimer_OnC hange();
  2616           }
  2617       }
  2618       catch  (err) {
  2619           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ isPatientI nAgreement _OnChange) : ' + err. message);
  2620       }
  2621   }
  2622  
  2623   function v cmn_append NoteFinanc ialDisclai mer_OnChan ge() {
  2624       //This  function  adds Finan cial Discl aimer text  to the en d of the N ote
  2625       try {
  2626           // Get Curren t Note Tex t
  2627           va r vcmn_cur rentNoteTe xt = Xrm.P age.getAtt ribute('ft p_notedeta il').getVa lue();
  2628           if  (vcmn_cur rentNoteTe xt == null ) { vcmn_c urrentNote Text = "";  }
  2629           // Create new  Financial  Disclaime r Text
  2630           va r vcmn_fin ancialDisc laimerText  = "";
  2631  
  2632           va r vcmn_sta ndardText  = "\n\nFIN ANCIAL DIS CLAIMER\n"  +
  2633                "------- ---------- ---------- ---------- ---------- ---------- ---------- ---\n" +
  2634                "The fol lowing dis claimer wa s read to  the caller :\n" +
  2635                "Patient  was instr ucted, 'Th is is not  an authori zation for  VA\n" +
  2636                "Payment  and also  'To have h ospital co ntact the  nearest VA \n" +
  2637                "Facilit y for tran sfer upon  stabilizat ion.\n";
  2638           va r vcmn_ter minationTe xt = "\n-- ---------- ---------- ---------- ---------- ---------- ---------- --------\n ";
  2639  
  2640           va r vcmn_isR eadDisclai mer = Xrm. Page.getAt tribute("f tp_isreadd isclaimer" ).getValue ();
  2641           va r vcmn_res ponseToDis claimer =  Xrm.Page.g etAttribut e("ftp_isd isclaimerr ead").getV alue();
  2642           if  (vcmn_isR eadDisclai mer == tru e && vcmn_ responseTo Disclaimer  == true)  {
  2643                var vcmn _isPatient Agree = Xr m.Page.get Attribute( "ftp_ispat ientagree" ).getValue ();
  2644                if (vcmn _isPatient Agree == t rue) {
  2645                    vcmn _financial Disclaimer Text = vcm n_standard Text +
  2646                         "\nPatient /Caller ag rees with  plan." + v cmn_termin ationText;
  2647                }
  2648                else {
  2649                    var  vcmn_reaso nForDisagr eeing = Xr m.Page.get Attribute( "ftp_patie ntcallersr easonfordi sagreeing" ).getValue ();
  2650                    if ( vcmn_reaso nForDisagr eeing == n ull) { vcm n_reasonFo rDisagreei ng = ""; }
  2651                    vcmn _financial Disclaimer Text = vcm n_standard Text +
  2652                         "\nPatient /Caller do es not agr ee with th e plan bec ause:\n" +
  2653                         vcmn_reaso nForDisagr eeing + vc mn_termina tionText;
  2654                }
  2655           }
  2656  
  2657           // Append to  existing N ote
  2658           Xr m.Page.get Attribute( 'ftp_noted etail').se tValue(vcm n_currentN oteText +  vcmn_finan cialDiscla imerText);
  2659           Xr m.Page.get Attribute( 'ftp_noted etail').se tSubmitMod e('always' );
  2660       }
  2661       catch  (err) {
  2662           al ert('Progr ess Note F inancial D isclaimer  Function E rror(vcmn_ appendNote FinancialD isclaimer_ OnChange):  ' + err.m essage);
  2663       }
  2664   }
  2665  
  2666   function v cmn_execut eCrmOdataG etRequest( vcmn_jsonQ uery, vcmn _aSync, vc mn_aSyncCa llback, vc mn_skipCou nt, vcmn_o ptionArray ) {
  2667       //This  function  executes a  CRM Odata  web servi ce call to  retrieve  Crm data
  2668       //*vcm n_jsonQuer y* - a pro perly form atted CRM  Odata Quer y string ( required)
  2669       //*vcm n_aSync* -  specify ' true' to e xecute asy nchronousl y otherwis e 'false'  (required)
  2670       //*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 '')
  2671       //*vcm n_skipCoun t* - Initi al setting  is always  '0', incr ements by  50 per CRM  SDK Odata  standards  (required )
  2672       //*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)
  2673       try {
  2674           va r vcmn_ent ityData =  null;
  2675           $. ajax({
  2676                type: 'G ET',
  2677                contentT ype: 'appl ication/js on; charse t=utf-8',
  2678                datatype : 'json',
  2679                url: vcm n_jsonQuer y,
  2680                beforeSe nd: functi on (XMLHtt pRequest)  {
  2681                    XMLH ttpRequest .setReques tHeader('A ccept', 'a pplication /json');
  2682                },
  2683                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  2684                    vcmn _entityDat a = data;
  2685                    if ( vcmn_aSync  == true)  {
  2686                         vcmn_aSync Callback(v cmn_entity Data, vcmn _skipCount , vcmn_opt ionArray);
  2687                    }
  2688                },
  2689                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  2690                    aler t('Fail: A jax Error  in vcmn_ex ecuteCrmOd ataGetRequ est: ' + e rrorThrown  + " Reque st: " + vc mn_jsonQue ry);
  2691                },
  2692                async: v cmn_aSync,
  2693                cache: f alse
  2694           }) ;
  2695           re turn vcmn_ entityData ;
  2696       }
  2697       catch  (err) {
  2698           al ert('An er ror occure d in the v cmn_execut eCrmOdataG etRequest  function.   Error Det ail Messag e: ' + err );
  2699       }
  2700   }
  2701  
  2702   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) {
  2703       //This  function  returns a  CRM JSON d ataset for  all entit y records  matching c riteria pr ovided Asy ncronously
  2704       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  2705       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  2706       //*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
  2707       //*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'
  2708       //*vcm n_sortDire ction* - i s a string  specifyin g the sort  as Ascend ing or Des cending e. g. 'asc' o r 'desc'
  2709       //*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)
  2710       //*vcm n_aSyncCal lback* - i s the name  of the fu nction to  call when  returning  the result
  2711       //*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
  2712  
  2713       try {
  2714           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;
  2715           vc mn_execute CrmOdataGe tRequest(v cmn_jsonQu ery, true,  vcmn_aSyn cCallback,  vcmn_skip Count, vcm n_optionAr ray);
  2716       }
  2717       catch  (err) {
  2718           al ert('An er ror occure d in the v cmn_getMul tipleEntit yDataAsync  function.   Error De tail Messa ge: ' + er r);
  2719       }
  2720   }
  2721  
  2722   function v cmn_getSin gleEntityD ataSync(vc mn_entityS etName, vc mn_attribu teSet, vcm n_entityId ) {
  2723       //This  function  returns a  CRM JSON d ataset for  a single  entity rec ord based  on the ent ity id pro vided Sync ronously
  2724       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  2725       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  2726       //*vcm n_entityId * - is the  Guid for  the entity  record
  2727  
  2728       try {
  2729           va r vcmn_ent ityIdNoBra cket = vcm n_entityId .replace(/ ({|})/g, ' ');
  2730           va r vcmn_sel ectString  = '(guid'  + "'" + vc mn_entityI dNoBracket  + "'" + ' )?$select= ' + vcmn_a ttributeSe t;
  2731           va r vcmn_jso nQuery = v cmn_server Url + vcmn _crmOdataE ndPoint +  '/' + vcmn _entitySet Name + vcm n_selectSt ring;
  2732           va r vcmn_ent ityData =  vcmn_execu teCrmOdata GetRequest (vcmn_json Query, fal se, '', 0,  null);
  2733           re turn vcmn_ entityData ;
  2734       }
  2735       catch  (err) {
  2736           al ert('An er ror occure d in the v cmn_getSin gleEntityD ataSync fu nction.  E rror Detai l Message:  ' + err);
  2737       }
  2738   }
  2739  
  2740   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) {
  2741       //This  function  returns a  CRM JSON d ataset for  all entit y records  matching c riteria pr ovided Syn cronously
  2742       //*vcm n_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  2743       //*vcm n_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  2744       //*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
  2745       //*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'
  2746       //*vcm n_sortDire ction* - i s a string  specifyin g the sort  as Ascend ing or Des cending e. g. 'asc' o r 'desc'
  2747       //*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)
  2748  
  2749       try {
  2750           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;
  2751           va r vcmn_ent ityData =  vcmn_execu teCrmOdata GetRequest (vcmn_json Query, fal se, '', vc mn_skipCou nt, null);
  2752           re turn vcmn_ entityData ;
  2753       }
  2754       catch  (err) {
  2755           al ert('An er ror occure d in the v cmn_getMul tipleEntit yDataSync  function.   Error Det ail Messag e: ' + err );
  2756       }
  2757   }