Module

fNotes

Path

C:\CPRS\CPRS30\fNotes.pas

Last Modified

7/15/2014 3:26:38 PM

Initialization Code

initialization
  SpecifyFormIsNotADialog(TfrmNotes);
  uPCEEdit := TPCEData.Create;
  uPCEShow := TPCEData.Create;

Finalization Code

finalization
  if (uPCEEdit <> nil) then uPCEEdit.Free; //CQ7012 Added test for nil
  if (uPCEShow <> nil) then uPCEShow.Free; //CQ7012 Added test for nil
   
end.

Units Used in Interface

Name Comments
fBase508Form -
fDrawers -
fHSplit -
fNoteST -
fNoteSTStop -
fPrintList -
fRptBox -
rTIU -
uConst -
uDocTree -
uPCE -
uTIU -

Units Used in Implementation

Name Comments
dShared -
fAddlSigners -
fConsults -
fEncnt -
fEncounterFrame -
fFrame -
fIconLegend -
fNoteBA -
fNoteBD -
fNoteCslt -
fNoteDR -
fNoteIDParents -
fNoteProps -
fNotePrt -
fNotesBP -
fPCEEdit -
fReminderDialog -
fReminderTree -
fSignItem -
fTemplateDialog -
fTemplateEditor -
fTemplateFieldEditor -
fTIUView -
fVisit -
rConsults -
rCore -
rPCE -
rSurgery -
rTemplates -
rVitals -
uCore -
uInit -
uOrders -
uReminders -
uSpell -
uSurgery -
uTemplates -
uVA508CPRSCompatibility -

Classes

Name Comments
TfrmNotes -

Procedures

Name Owner Declaration Scope Comments
AssignBoilerText - procedure AssignBoilerText; Local -
AssignRemForm TfrmNotes procedure AssignRemForm; Public -
ClearEditControls TfrmNotes procedure ClearEditControls; Private
General procedures ----------------------------------------------------------------------- 

 resets controls used for entering a new progress note
ClearPtData TfrmNotes procedure ClearPtData; override; Public Clear all controls that contain patient specific information
cmdChangeClick TfrmNotes procedure cmdChangeClick(Sender: TObject); Public/Published -
cmdChangeExit TfrmNotes procedure cmdChangeExit(Sender: TObject); Public/Published -
cmdNewNoteClick TfrmNotes procedure cmdNewNoteClick(Sender: TObject); Public/Published Maps 'New Note' button to the New Progress Note menu item
cmdNewNoteExit TfrmNotes procedure cmdNewNoteExit(Sender: TObject); Public/Published -
cmdPCEClick TfrmNotes procedure cmdPCEClick(Sender: TObject); Public/Published -
cmdPCEExit TfrmNotes procedure cmdPCEExit(Sender: TObject); Public/Published -
DisplayPage TfrmNotes procedure DisplayPage; override; Public Causes page to be visible and conditionally executes initialization code
DisplayPCE TfrmNotes procedure DisplayPCE; Private Displays PCE information if appropriate & enables/disabled editing of PCE data
dlgFindTextFind TfrmNotes procedure dlgFindTextFind(Sender: TObject); Public/Published -
dlgReplaceTextFind TfrmNotes procedure dlgReplaceTextFind(Sender: TObject); Public/Published -
dlgReplaceTextReplace TfrmNotes procedure dlgReplaceTextReplace(Sender: TObject); Public/Published -
DoAttachIDChild TfrmNotes procedure DoAttachIDChild(AChild, AParent: TORTreeNode); Private -
DoAutoSave TfrmNotes procedure DoAutoSave(Suppress: integer = 1); Private -
EnableDisableIDNotes TfrmNotes procedure EnableDisableIDNotes; Private -
FormClose TfrmNotes procedure FormClose(Sender: TObject; var Action: TCloseAction); Public/Published -
FormCreate TfrmNotes procedure FormCreate(Sender: TObject); Public/Published Form events ------------------------------------------------------------------------------
FormDestroy TfrmNotes procedure FormDestroy(Sender: TObject); Public/Published -
FormHide TfrmNotes procedure FormHide(Sender: TObject); Public/Published -
FormShow TfrmNotes procedure FormShow(Sender: TObject); Public/Published -
frmDrawerEdtSearchExit TfrmNotes procedure frmDrawerEdtSearchExit(Sender: TObject); Private -
frmDrawerPnlEncounterButtonExit TfrmNotes procedure frmDrawerPnlEncounterButtonExit(Sender: TObject); Private -
frmDrawerPnlTemplatesButtonExit TfrmNotes procedure frmDrawerPnlTemplatesButtonExit(Sender: TObject); Private -
frmFramePnlPatientExit TfrmNotes procedure frmFramePnlPatientExit(Sender: TObject); Private -
InsertAddendum TfrmNotes procedure InsertAddendum; Private Sets up fields of pnlWrite to write an addendum for the selected note
InsertNewNote TfrmNotes procedure InsertNewNote(IsIDChild: boolean; AnIDParent: integer); Private
Create, edit & save notes 

 creates the editing context for a new progress note & inserts stub into top of view list
LoadForEdit TfrmNotes procedure LoadForEdit; Private Retrieves an existing note and places the data in the fields of pnlWrite
LoadNotes TfrmNotes procedure LoadNotes; Private
Added for treeview
===================  Added for sort/search enhancements ======================
lstNotesClick TfrmNotes procedure lstNotesClick(Sender: TObject); Public/Published
Left panel (selector) events ------------------------------------------------------------- 

 loads the text for the selected note or displays the editing panel for the selected note
LstNotesToPrint TfrmNotes procedure LstNotesToPrint; Public -
lvNotesColumnClick TfrmNotes procedure lvNotesColumnClick(Sender: TObject; Column: TListColumn); Public/Published ===================== Listview events =================================
lvNotesCompare TfrmNotes procedure lvNotesCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); Public/Published -
lvNotesResize TfrmNotes procedure lvNotesResize(Sender: TObject); Public/Published -
lvNotesSelectItem TfrmNotes procedure lvNotesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); Public/Published -
memNewNoteChange TfrmNotes procedure memNewNoteChange(Sender: TObject); Public/Published -
memNewNoteKeyDown TfrmNotes procedure memNewNoteKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); Public/Published -
memNewNoteKeyPress TfrmNotes procedure memNewNoteKeyPress(Sender: TObject; var Key: Char); Public/Published -
memNewNoteKeyUp TfrmNotes procedure memNewNoteKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); Public/Published -
memPCEShowExit TfrmNotes procedure memPCEShowExit(Sender: TObject); Public/Published -
mnuActAddendClick TfrmNotes procedure mnuActAddendClick(Sender: TObject); Public/Published Make an addendum to an existing note
mnuActAddIDEntryClick TfrmNotes procedure mnuActAddIDEntryClick(Sender: TObject); Public/Published Switches to current new note or creates a new note if none is being edited already
mnuActAttachtoIDParentClick TfrmNotes procedure mnuActAttachtoIDParentClick(Sender: TObject); Public/Published -
mnuActChangeClick TfrmNotes procedure mnuActChangeClick(Sender: TObject); Public/Published Right panel (editor) events --------------------------------------------------------------
mnuActDeleteClick TfrmNotes procedure mnuActDeleteClick(Sender: TObject); Public/Published Delete the selected progress note & remove from the Encounter object if necessary
mnuActDetachFromIDParentClick TfrmNotes procedure mnuActDetachFromIDParentClick(Sender: TObject); Public/Published -
mnuActEditClick TfrmNotes procedure mnuActEditClick(Sender: TObject); Public/Published Load the selected progress note for editing
mnuActIdentifyAddlSignersClick TfrmNotes procedure mnuActIdentifyAddlSignersClick(Sender: TObject); Public/Published -
mnuActLoadBoilerClick TfrmNotes procedure mnuActLoadBoilerClick(Sender: TObject); Public/Published -
mnuActNewClick TfrmNotes procedure mnuActNewClick(Sender: TObject); Public/Published Switches to current new note or creates a new note if none is being edited already
mnuActSaveClick TfrmNotes procedure mnuActSaveClick(Sender: TObject); Public/Published Saves the note that is currently being edited
mnuActSignClick TfrmNotes procedure mnuActSignClick(Sender: TObject); Public/Published Sign the currently selected note, save first if necessary
mnuActSignListClick TfrmNotes procedure mnuActSignListClick(Sender: TObject); Public/Published Add the note to the Encounter object, see mnuActSignClick - copied
mnuChartTabClick TfrmNotes procedure mnuChartTabClick(Sender: TObject); Public/Published Reroute to Chart Tab menu of the parent form: frmFrame
mnuEditDialgFieldsClick TfrmNotes procedure mnuEditDialgFieldsClick(Sender: TObject); Public/Published -
mnuEditSharedTemplatesClick TfrmNotes procedure mnuEditSharedTemplatesClick(Sender: TObject); Public/Published -
mnuEditTemplatesClick TfrmNotes procedure mnuEditTemplatesClick(Sender: TObject); Public/Published -
mnuIconLegendClick TfrmNotes procedure mnuIconLegendClick(Sender: TObject); Public/Published -
mnuNewSharedTemplateClick TfrmNotes procedure mnuNewSharedTemplateClick(Sender: TObject); Public/Published -
mnuNewTemplateClick TfrmNotes procedure mnuNewTemplateClick(Sender: TObject); Public/Published -
mnuOptionsClick TfrmNotes procedure mnuOptionsClick(Sender: TObject); Public/Published -
mnuViewClick TfrmNotes procedure mnuViewClick(Sender: TObject); Public/Published
View menu events ------------------------------------------------------------------------- 

 changes the list of notes available for viewing
mnuViewDetailClick TfrmNotes procedure mnuViewDetailClick(Sender: TObject); Public/Published -
mnuViewInformationClick TfrmNotes procedure mnuViewInformationClick(Sender: TObject); Public/Published -
mnuViewReturntoDefaultClick TfrmNotes procedure mnuViewReturntoDefaultClick(Sender: TObject); Public/Published -
mnuViewSaveAsDefaultClick TfrmNotes procedure mnuViewSaveAsDefaultClick(Sender: TObject); Public/Published -
pnlFieldsResize TfrmNotes procedure pnlFieldsResize(Sender: TObject); Public/Published Center the reference date on the panel
pnlReadExit TfrmNotes procedure pnlReadExit(Sender: TObject); Public/Published -
pnlRightResize TfrmNotes procedure pnlRightResize(Sender: TObject); Public/Published MemNote (TRichEdit) doesn't repaint appropriately unless it's parent panel is refreshed
pnlWriteResize TfrmNotes procedure pnlWriteResize(Sender: TObject); Public/Published -
popNoteListCollapseAllClick TfrmNotes procedure popNoteListCollapseAllClick(Sender: TObject); Public/Published -
popNoteListCollapseSelectedClick TfrmNotes procedure popNoteListCollapseSelectedClick(Sender: TObject); Public/Published -
popNoteListExpandAllClick TfrmNotes procedure popNoteListExpandAllClick(Sender: TObject); Public/Published -
popNoteListExpandSelectedClick TfrmNotes procedure popNoteListExpandSelectedClick(Sender: TObject); Public/Published -
popNoteListPopup TfrmNotes procedure popNoteListPopup(Sender: TObject); Public/Published -
popNoteMemoAddlSignClick TfrmNotes procedure popNoteMemoAddlSignClick(Sender: TObject); Public/Published -
popNoteMemoCopyClick TfrmNotes procedure popNoteMemoCopyClick(Sender: TObject); Public/Published -
popNoteMemoCutClick TfrmNotes procedure popNoteMemoCutClick(Sender: TObject); Public/Published -
popNoteMemoFindClick TfrmNotes procedure popNoteMemoFindClick(Sender: TObject); Public/Published
Var
hData: THandle;  //CQ8300
pData: ^ClipboardData; //CQ8300
popNoteMemoGrammarClick TfrmNotes procedure popNoteMemoGrammarClick(Sender: TObject); Public/Published -
popNoteMemoInsTemplateClick TfrmNotes procedure popNoteMemoInsTemplateClick(Sender: TObject); Public/Published -
popNoteMemoPasteClick TfrmNotes procedure popNoteMemoPasteClick(Sender: TObject); Public/Published -
popNoteMemoPopup TfrmNotes procedure popNoteMemoPopup(Sender: TObject); Public/Published -
popNoteMemoPreviewClick TfrmNotes procedure popNoteMemoPreviewClick(Sender: TObject); Public/Published -
popNoteMemoReformatClick TfrmNotes procedure popNoteMemoReformatClick(Sender: TObject); Public/Published -
popNoteMemoReplaceClick TfrmNotes procedure popNoteMemoReplaceClick(Sender: TObject); Public/Published -
popNoteMemoSaveContinueClick TfrmNotes procedure popNoteMemoSaveContinueClick(Sender: TObject); Public/Published -
popNoteMemoSpellClick TfrmNotes procedure popNoteMemoSpellClick(Sender: TObject); Public/Published -
popNoteMemoTemplateClick TfrmNotes procedure popNoteMemoTemplateClick(Sender: TObject); Public/Published -
popNoteMemoViewCsltClick TfrmNotes procedure popNoteMemoViewCsltClick(Sender: TObject); Public/Published -
ProcessNotifications TfrmNotes procedure ProcessNotifications; Private -
RemovePCEFromChanges TfrmNotes procedure RemovePCEFromChanges(IEN: Int64; AVisitStr: string = ''); Private -
RequestMultiplePrint TfrmNotes procedure RequestMultiplePrint(AForm: TfrmPrintList); Public For printing multiple notes
RequestPrint TfrmNotes procedure RequestPrint; override; Public -
SaveCurrentNote TfrmNotes procedure SaveCurrentNote(var Saved: Boolean); Private Called whenever a note should be saved - uses IEN to call appropriate save logic
SaveEditedNote TfrmNotes procedure SaveEditedNote(var Saved: Boolean); Private Validates fields and sends the updated note to the server
SaveSignItem TfrmNotes procedure SaveSignItem(const ItemID, ESCode: string); Public Saves and optionally signs a progress note or addendum
SetEditingIndex TfrmNotes procedure SetEditingIndex(const Value: Integer); Private -
SetFontSize TfrmNotes procedure SetFontSize(NewFontSize: Integer); override; Public Adjusts the font size of any controls that don't have ParentFont = True
SetSubjectVisible TfrmNotes procedure SetSubjectVisible(ShouldShow: Boolean); Private Hide/show subject & resize panel accordingly - leave 6 pixel margin above memNewNote
SetViewContext TfrmNotes procedure SetViewContext(AContext: TTIUContext); Private -
ShowPCEButtons TfrmNotes procedure ShowPCEButtons(Editing: boolean); Private -
ShowPCEControls TfrmNotes procedure ShowPCEControls(ShouldShow: Boolean); Private -
sptHorzCanResize TfrmNotes procedure sptHorzCanResize(Sender: TObject; var NewSize: Integer; var Accept: Boolean); Public/Published -
timAutoSaveTimer TfrmNotes procedure timAutoSaveTimer(Sender: TObject); Public/Published -
tvNotesChange TfrmNotes procedure tvNotesChange(Sender: TObject; Node: TTreeNode); Public/Published -
tvNotesClick TfrmNotes procedure tvNotesClick(Sender: TObject); Public/Published -
tvNotesCollapsed TfrmNotes procedure tvNotesCollapsed(Sender: TObject; Node: TTreeNode); Public/Published -
tvNotesDragDrop TfrmNotes procedure tvNotesDragDrop(Sender, Source: TObject; X, Y: Integer); Public/Published -
tvNotesDragOver TfrmNotes procedure tvNotesDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); Public/Published -
tvNotesExit TfrmNotes procedure tvNotesExit(Sender: TObject); Public/Published
Tab Order tricks.  Need to change
  tvNotes

  frmDrawers.pnlTemplateButton
  frmDrawers.pnlEncounterButton
  cmdNewNote
  cmdPCE

  lvNotes
  memNote

to
  tvNotes

  lvNotes
  memNote

  frmDrawers.pnlTemplateButton
  frmDrawers.pnlEncounterButton
  cmdNewNote
  cmdPCE
tvNotesExpanded TfrmNotes procedure tvNotesExpanded(Sender: TObject; Node: TTreeNode); Public/Published -
tvNotesStartDrag TfrmNotes procedure tvNotesStartDrag(Sender: TObject; var DragObject: TDragObject); Public/Published Saved: boolean;
UnlockConsultRequest TfrmNotes procedure UnlockConsultRequest(ANote: Int64; AConsult: Integer = 0); Private
Var
  x: string;
UpdateEncounterInfo - procedure UpdateEncounterInfo; Local -
UpdateFormForInput TfrmNotes procedure UpdateFormForInput; Public -
UpdateNoteAuthor TfrmNotes procedure UpdateNoteAuthor(DocInfo: string); Private -
UpdateTreeView TfrmNotes procedure UpdateTreeView(DocList: TStringList; Tree: TORTreeView); Private -
ViewInfo TfrmNotes procedure ViewInfo(Sender: TObject); Public/Published -

Functions

Name Owner Declaration Scope Comments
ActiveEditOf TfrmNotes function ActiveEditOf(AnIEN: Int64; ARequest: integer): Boolean; Public -
AllowContextChange TfrmNotes function AllowContextChange(var WhyNot: string): Boolean; override; Public TPage common methods ---------------------------------------------------------------------
CanFinishReminder TfrmNotes function CanFinishReminder: boolean; Private -
GetDrawers TfrmNotes function GetDrawers: TfrmDrawers; Private -
GetTitleText TfrmNotes function GetTitleText(AnIndex: Integer): string; Private
Supporting calls for writing notes 

 returns non-tabbed text for the title of a note given the ItemIndex in lstNotes
LacksRequiredForCreate TfrmNotes function LacksRequiredForCreate: Boolean; Private Determines if the fields required to create the note are present
LockConsultRequest TfrmNotes function LockConsultRequest(AConsult: Integer): Boolean; Private
Consult request and note locking 

 returns true if consult successfully locked
LockConsultRequestAndNote TfrmNotes function LockConsultRequestAndNote(AnIEN: Int64): Boolean; Private Returns true if note and associated request successfully locked
SetDateRangeText - function SetDateRangeText(AContext: TTIUContext): string; Local -
SetNoteTreeLabel TfrmNotes function SetNoteTreeLabel(AContext: TTIUContext): string; Private -
SortByDate - function SortByDate(Node1, Node2: TTreeNode; Data: Longint): Integer; stdcall; Local -
SortByTitle - function SortByTitle(Node1, Node2: TTreeNode; Data: Longint): Integer; stdcall; Local -
StartNewEdit TfrmNotes function StartNewEdit(NewNoteType: integer): Boolean; Private
Action menu events ----------------------------------------------------------------------- 

 if currently editing a note, returns TRUE if the user wants to start a new one
VerifyNoteTitle TfrmNotes function VerifyNoteTitle: Boolean; Private -

Global Variables

Name Type Declaration Comments
ColumnSortForward Boolean ColumnSortForward: Boolean; -
ColumnToSort Integer ColumnToSort: Integer; -
frmDrawers TfrmDrawers frmDrawers: TfrmDrawers; -
frmNotes TfrmNotes frmNotes: TfrmNotes; -
NoteTotal UnicodeString NoteTotal: string; -
SearchTextStopFlag Boolean SearchTextStopFlag: Boolean; Text Search CQ: HDS00002856
uChanging Boolean uChanging: Boolean; -
uIDNotesActive Boolean uIDNotesActive: Boolean; -
uPCEEdit TPCEData uPCEShow, uPCEEdit: TPCEData; -
uPCEShow TPCEData uPCEShow, uPCEEdit: TPCEData; -
uTIUContext uTIUContext: TTIUContext; -
ViewContext Integer ViewContext: Integer; -

Constants

Name Declaration Scope Comments
NT_ACT_ADDENDUM 3 Global -
NT_ACT_EDIT_NOTE 4 Global -
NT_ACT_ID_ENTRY 5 Global -
NT_ACT_NEW_NOTE 2 Global -
NT_ADDENDUM -20 Global Holder IEN for a new addendum
NT_NEW_NOTE -10 Global Holder IEN for a new note
TC_ABSAVE 'Possible Missing Text' Global -
TC_BLR_CLEAR 'Clear Previous Boilerplate Text' Global -
TC_EMPTY_NOTE 'Empty Note' Global -
TC_NEW_SAVE2 'Create New Note' Global -
TC_NEW_SAVE3 'Create New Addendum' Global -
TC_NEW_SAVE4 'Edit Different Note' Global -
TC_NEW_SAVE5 'Create New Interdisciplinary Entry' Global -
TC_NO_BOIL 'Load Boilerplate Text' Global -
TC_NO_LOCK 'Unable to Lock Note' Global -
TC_NO_ORD_CHG 'Locked Consult Request' Global -
TC_ORDER_LOCKED 'Unable to access record' Global -
TX_ABSAVE 'It appears the session terminated abnormally when this' + CRLF + Global -
TX_ADDEND_NO 'Cannot make an addendum to a note that is being edited' Global -
TX_AUTH_SIGNED 'Author has not signed, are you SURE you want to sign.' +CRLF Global -
TX_BLR_CLEAR 'Do you want to clear the previously loaded boilerplate text?' Global -
TX_CAP_NO_ALERT 'Unable to Process Alert' Global -
TX_COSIGN 'Cosign Note' Global -
TX_CREATE_ERR 'Error Creating Note' Global -
TX_DEL_ERR 'Unable to Delete Note' Global -
TX_DEL_OK CRLF + CRLF + 'Delete this progress note?' Global -
TX_DETACH_CNF 'Confirm Detachment' Global -
TX_DETACH_FAILURE 'Detach failed' Global -
TX_EMPTY_NOTE CRLF + CRLF + 'This note contains no text and will not be saved.' + CRLF + Global -
TX_EMPTY_NOTE1 'This note contains no text and can not be signed.' Global -
TX_NEED_VISIT 'A visit is required before creating a new progress note.' Global -
TX_NEW_SAVE1 'You are currently editing:' + CRLF + CRLF Global -
TX_NEW_SAVE2 CRLF + CRLF + 'Do you wish to save this note and begin a new one?' Global -
TX_NEW_SAVE3 CRLF + CRLF + 'Do you wish to save this note and begin a new addendum?' Global -
TX_NEW_SAVE4 CRLF + CRLF + 'Do you wish to save this note and edit the one selected?' Global -
TX_NEW_SAVE5 CRLF + CRLF + 'Do you wish to save this note and begin a new Interdisciplinary entry?' Global -
TX_NO_ALERT 'There is insufficient information to process this alert.' + CRLF + Global -
TX_NO_BOIL 'There is no boilerplate text associated with this title.' Global -
TX_NO_NOTE 'No progress note is currently being edited' Global -
TX_NO_ORD_CHG 'The note is still associated with the previously selected request.' + CRLF + Global -
TX_NONOTE 'No progress note is currently selected.' Global
TX_SCREQD     = 'This progress note title requires the service connected questions to be '+
                  'answered.  The Encounter form will now be opened.  Please answer all '+
                 'service connected questions.';
  TX_SCREQD_T   = 'Response required for SC questions.';
TX_NONOTE_CAP 'No Note Selected' Global -
TX_NOPRT_NEW 'This progress note may not be printed until it is saved' Global -
TX_NOPRT_NEW_CAP 'Save Progress Note' Global -
TX_ORDER_LOCKED 'This record is locked by an action underway on the Consults tab' Global -
TX_RETRACT 'This document will now be RETRACTED. As Such, it has been removed' +CRLF + Global -
TX_RETRACT_CAP 'Retraction Notice' Global -
TX_SAVE_NOTE 'Save Progress Note' Global -
TX_SIGN 'Sign Note' Global -
TX_SIGN_ERR 'Unable to Sign Note' Global -
TX_UPDATE_ERR 'Error Updating Note' Global -


Module Source

1     unit fNotes;
2     {$O-}
3     
4     interface
5     
6     uses
7       Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
8       fHSplit, StdCtrls, ExtCtrls, Menus, ComCtrls, ORCtrls, ORFn, uConst, ORDtTm,
9       uPCE, ORClasses, fDrawers, ImgList, rTIU, uTIU, uDocTree, fRptBox, fPrintList,
10      fNoteST, ORNet, fNoteSTStop, fBase508Form, VA508AccessibilityManager,
11      VA508ImageListLabeler, RichEdit;
12    
13    type
14      TfrmNotes = class(TfrmHSplit)
15        mnuNotes: TMainMenu;
16        mnuView: TMenuItem;
17        mnuViewChart: TMenuItem;
18        mnuChartReports: TMenuItem;
19        mnuChartLabs: TMenuItem;
20        mnuChartDCSumm: TMenuItem;
21        mnuChartCslts: TMenuItem;
22        mnuChartNotes: TMenuItem;
23        mnuChartOrders: TMenuItem;
24        mnuChartMeds: TMenuItem;
25        mnuChartProbs: TMenuItem;
26        mnuChartCover: TMenuItem;
27        Z1: TMenuItem;
28        mnuViewDetail: TMenuItem;
29        mnuAct: TMenuItem;
30        mnuActNew: TMenuItem;
31        Z2: TMenuItem;
32        mnuActSave: TMenuItem;
33        mnuActDelete: TMenuItem;
34        mnuActEdit: TMenuItem;
35        mnuActSign: TMenuItem;
36        mnuActAddend: TMenuItem;
37        lblNotes: TOROffsetLabel;
38        pnlRead: TPanel;
39        lblTitle: TOROffsetLabel;
40        memNote: TRichEdit;
41        pnlWrite: TPanel;
42        memNewNote: TRichEdit;
43        Z3: TMenuItem;
44        mnuViewAll: TMenuItem;
45        mnuViewByAuthor: TMenuItem;
46        mnuViewByDate: TMenuItem;
47        mnuViewUncosigned: TMenuItem;
48        mnuViewUnsigned: TMenuItem;
49        mnuActSignList: TMenuItem;
50        cmdNewNote: TORAlignButton;
51        cmdPCE: TORAlignButton;
52        lblSpace1: TLabel;
53        popNoteMemo: TPopupMenu;
54        popNoteMemoCut: TMenuItem;
55        popNoteMemoCopy: TMenuItem;
56        popNoteMemoPaste: TMenuItem;
57        Z10: TMenuItem;
58        popNoteMemoSignList: TMenuItem;
59        popNoteMemoDelete: TMenuItem;
60        popNoteMemoEdit: TMenuItem;
61        popNoteMemoSave: TMenuItem;
62        popNoteMemoSign: TMenuItem;
63        popNoteList: TPopupMenu;
64        popNoteListAll: TMenuItem;
65        popNoteListByAuthor: TMenuItem;
66        popNoteListByDate: TMenuItem;
67        popNoteListUncosigned: TMenuItem;
68        popNoteListUnsigned: TMenuItem;
69        sptVert: TSplitter;
70        memPCEShow: TRichEdit;
71        mnuActIdentifyAddlSigners: TMenuItem;
72        popNoteMemoAddlSign: TMenuItem;
73        Z11: TMenuItem;
74        popNoteMemoSpell: TMenuItem;
75        popNoteMemoGrammar: TMenuItem;
76        mnuViewCustom: TMenuItem;
77        N1: TMenuItem;
78        mnuViewSaveAsDefault: TMenuItem;
79        ReturntoDefault1: TMenuItem;
80        pnlDrawers: TPanel;
81        lstNotes: TORListBox;
82        splDrawers: TSplitter;
83        popNoteMemoTemplate: TMenuItem;
84        Z12: TMenuItem;
85        mnuOptions: TMenuItem;
86        mnuEditTemplates: TMenuItem;
87        mnuNewTemplate: TMenuItem;
88        N2: TMenuItem;
89        mnuEditSharedTemplates: TMenuItem;
90        mnuNewSharedTemplate: TMenuItem;
91        popNoteMemoAddend: TMenuItem;
92        pnlFields: TPanel;
93        lblNewTitle: TStaticText;
94        lblRefDate: TStaticText;
95        lblAuthor: TStaticText;
96        lblVisit: TStaticText;
97        lblCosigner: TStaticText;
98        cmdChange: TButton;
99        lblSubject: TStaticText;
100       txtSubject: TCaptionEdit;
101       timAutoSave: TTimer;
102       popNoteMemoPaste2: TMenuItem;
103       popNoteMemoReformat: TMenuItem;
104       Z4: TMenuItem;
105       mnuActChange: TMenuItem;
106       mnuActLoadBoiler: TMenuItem;
107       bvlNewTitle: TBevel;
108       popNoteMemoSaveContinue: TMenuItem;
109       N3: TMenuItem;
110       mnuEditDialgFields: TMenuItem;
111       tvNotes: TORTreeView;
112       lvNotes: TCaptionListView;
113       sptList: TSplitter;
114       N4: TMenuItem;
115       popNoteListExpandSelected: TMenuItem;
116       popNoteListExpandAll: TMenuItem;
117       popNoteListCollapseSelected: TMenuItem;
118       popNoteListCollapseAll: TMenuItem;
119       popNoteListCustom: TMenuItem;
120       mnuActDetachFromIDParent: TMenuItem;
121       N5: TMenuItem;
122       popNoteListDetachFromIDParent: TMenuItem;
123       popNoteListAddIDEntry: TMenuItem;
124       mnuActAddIDEntry: TMenuItem;
125       mnuIconLegend: TMenuItem;
126       N6: TMenuItem;
127       popNoteMemoFind: TMenuItem;
128       dlgFindText: TFindDialog;
129       dlgReplaceText: TReplaceDialog;
130       popNoteMemoReplace: TMenuItem;
131       N7: TMenuItem;
132       mnuChartSurgery: TMenuItem;
133       mnuActAttachtoIDParent: TMenuItem;
134       popNoteListAttachtoIDParent: TMenuItem;
135       N8: TMenuItem;
136       popNoteMemoPreview: TMenuItem;
137       popNoteMemoInsTemplate: TMenuItem;
138       popNoteMemoEncounter: TMenuItem;
139       mnuSearchForText: TMenuItem;
140       popSearchForText: TMenuItem;
141       mnuViewInformation: TMenuItem;
142       mnuViewDemo: TMenuItem;
143       mnuViewVisits: TMenuItem;
144       mnuViewPrimaryCare: TMenuItem;
145       mnuViewMyHealtheVet: TMenuItem;
146       mnuInsurance: TMenuItem;
147       mnuViewFlags: TMenuItem;
148       mnuViewReminders: TMenuItem;
149       mnuViewRemoteData: TMenuItem;
150       mnuViewPostings: TMenuItem;
151       popNoteMemoViewCslt: TMenuItem;
152       mnuEncounter: TMenuItem;
153       imgLblNotes: TVA508ImageListLabeler;
154       imgLblImages: TVA508ImageListLabeler;
155       procedure mnuChartTabClick(Sender: TObject);
156       procedure lstNotesClick(Sender: TObject);
157       procedure pnlRightResize(Sender: TObject);
158       procedure cmdNewNoteClick(Sender: TObject);
159       procedure mnuActNewClick(Sender: TObject);
160       procedure mnuActAddIDEntryClick(Sender: TObject);
161       procedure mnuActSaveClick(Sender: TObject);
162       procedure mnuViewClick(Sender: TObject);
163       procedure mnuActAddendClick(Sender: TObject);
164       procedure mnuActDetachFromIDParentClick(Sender: TObject);
165       procedure mnuActSignListClick(Sender: TObject);
166       procedure mnuActDeleteClick(Sender: TObject);
167       procedure mnuActEditClick(Sender: TObject);
168       procedure mnuActSignClick(Sender: TObject);
169       procedure cmdPCEClick(Sender: TObject);
170       procedure popNoteMemoCutClick(Sender: TObject);
171       procedure popNoteMemoCopyClick(Sender: TObject);
172       procedure popNoteMemoPasteClick(Sender: TObject);
173       procedure popNoteMemoPopup(Sender: TObject);
174       procedure pnlWriteResize(Sender: TObject);
175       procedure FormCreate(Sender: TObject);
176       procedure mnuViewDetailClick(Sender: TObject);
177       procedure FormClose(Sender: TObject; var Action: TCloseAction);
178       procedure mnuActIdentifyAddlSignersClick(Sender: TObject);
179       procedure popNoteMemoAddlSignClick(Sender: TObject);
180       procedure popNoteMemoSpellClick(Sender: TObject);
181       procedure popNoteMemoGrammarClick(Sender: TObject);
182       procedure mnuViewSaveAsDefaultClick(Sender: TObject);
183       procedure mnuViewReturntoDefaultClick(Sender: TObject);
184       procedure popNoteMemoTemplateClick(Sender: TObject);
185       procedure mnuEditTemplatesClick(Sender: TObject);
186       procedure mnuNewTemplateClick(Sender: TObject);
187       procedure mnuEditSharedTemplatesClick(Sender: TObject);
188       procedure mnuNewSharedTemplateClick(Sender: TObject);
189       procedure mnuOptionsClick(Sender: TObject);
190       procedure FormDestroy(Sender: TObject);
191       procedure cmdChangeClick(Sender: TObject);
192       procedure pnlFieldsResize(Sender: TObject);
193       procedure timAutoSaveTimer(Sender: TObject);
194       procedure memNewNoteChange(Sender: TObject);
195       procedure popNoteMemoReformatClick(Sender: TObject);
196       procedure mnuActChangeClick(Sender: TObject);
197       procedure mnuActLoadBoilerClick(Sender: TObject);
198       procedure popNoteMemoSaveContinueClick(Sender: TObject);
199       procedure mnuEditDialgFieldsClick(Sender: TObject);
200       procedure tvNotesChange(Sender: TObject; Node: TTreeNode);
201       procedure tvNotesClick(Sender: TObject);
202       procedure tvNotesCollapsed(Sender: TObject; Node: TTreeNode);
203       procedure tvNotesExpanded(Sender: TObject; Node: TTreeNode);
204       procedure tvNotesStartDrag(Sender: TObject;
205         var DragObject: TDragObject);
206       procedure tvNotesDragDrop(Sender, Source: TObject; X, Y: Integer);
207       procedure tvNotesDragOver(Sender, Source: TObject; X, Y: Integer;
208         State: TDragState; var Accept: Boolean);
209       procedure lvNotesColumnClick(Sender: TObject; Column: TListColumn);
210       procedure lvNotesCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer);
211       procedure lvNotesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
212       procedure popNoteListExpandAllClick(Sender: TObject);
213       procedure popNoteListCollapseAllClick(Sender: TObject);
214       procedure popNoteListExpandSelectedClick(Sender: TObject);
215       procedure popNoteListCollapseSelectedClick(Sender: TObject);
216       procedure popNoteListPopup(Sender: TObject);
217       procedure lvNotesResize(Sender: TObject);
218       procedure mnuIconLegendClick(Sender: TObject);
219       procedure popNoteMemoFindClick(Sender: TObject);
220       procedure dlgFindTextFind(Sender: TObject);
221       procedure popNoteMemoReplaceClick(Sender: TObject);
222       procedure dlgReplaceTextReplace(Sender: TObject);
223       procedure dlgReplaceTextFind(Sender: TObject);
224       procedure mnuActAttachtoIDParentClick(Sender: TObject);
225       procedure memNewNoteKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
226       procedure sptHorzCanResize(Sender: TObject; var NewSize: Integer; var Accept: Boolean);
227       procedure popNoteMemoInsTemplateClick(Sender: TObject);
228       procedure popNoteMemoPreviewClick(Sender: TObject);
229       procedure tvNotesExit(Sender: TObject);
230       procedure pnlReadExit(Sender: TObject);
231       procedure cmdNewNoteExit(Sender: TObject);
232       procedure FormHide(Sender: TObject);
233       procedure FormShow(Sender: TObject);
234       procedure memNewNoteKeyPress(Sender: TObject; var Key: Char);
235       procedure memNewNoteKeyUp(Sender: TObject; var Key: Word;
236         Shift: TShiftState);
237       procedure memPCEShowExit(Sender: TObject);
238       procedure cmdChangeExit(Sender: TObject);
239       procedure cmdPCEExit(Sender: TObject);
240       procedure ViewInfo(Sender: TObject);
241       procedure mnuViewInformationClick(Sender: TObject);
242       procedure popNoteMemoViewCsltClick(Sender: TObject);
243     private
244       FNavigatingTab : Boolean; //Currently Using tab to navigate
245       FEditingIndex: Integer;                      // index of note being currently edited
246       FChanged: Boolean;                           // true if any text has changed in the note
247       FEditCtrl: TCustomEdit;
248       FSilent: Boolean;
249       FCurrentContext: TTIUContext;
250       FDefaultContext: TTIUContext;
251       FOrderID: string;
252       FImageFlag: TBitmap;
253       FEditNote: TEditNoteRec;
254       FVerifyNoteTitle: Integer;
255       FDocList: TStringList;
256       FConfirmed: boolean;
257       FLastNoteID: string;
258       FNewIDChild: boolean;
259       FEditingNotePCEObj: boolean;
260       FDeleted: boolean;
261       FOldFramePnlPatientExit: TNotifyEvent;
262       FOldDrawerPnlTemplatesButtonExit: TNotifyEvent;
263       FOldDrawerPnlEncounterButtonExit: TNotifyEvent;
264       FOldDrawerEdtSearchExit: TNotifyEvent;
265       FStarting: boolean;
266       procedure frmFramePnlPatientExit(Sender: TObject);
267       procedure frmDrawerPnlTemplatesButtonExit(Sender: TObject);
268       procedure frmDrawerPnlEncounterButtonExit(Sender: TObject);
269       procedure frmDrawerEdtSearchExit(Sender: TObject);
270       procedure ClearEditControls;
271       procedure DoAutoSave(Suppress: integer = 1);
272       function GetTitleText(AnIndex: Integer): string;
273       procedure InsertAddendum;
274       procedure InsertNewNote(IsIDChild: boolean; AnIDParent: integer);
275       function LacksRequiredForCreate: Boolean;
276       procedure LoadForEdit;
277       function LockConsultRequest(AConsult: Integer): Boolean;
278       function LockConsultRequestAndNote(AnIEN: Int64): Boolean;
279       procedure RemovePCEFromChanges(IEN: Int64; AVisitStr: string = '');
280       procedure SaveEditedNote(var Saved: Boolean);
281       procedure SaveCurrentNote(var Saved: Boolean);
282       procedure SetEditingIndex(const Value: Integer);
283       procedure SetSubjectVisible(ShouldShow: Boolean);
284       procedure ShowPCEControls(ShouldShow: Boolean);
285       function StartNewEdit(NewNoteType: integer): Boolean;
286       procedure UnlockConsultRequest(ANote: Int64; AConsult: Integer = 0);
287       procedure ProcessNotifications;
288       procedure SetViewContext(AContext: TTIUContext);
289       property EditingIndex: Integer read FEditingIndex write SetEditingIndex;
290       function GetDrawers: TfrmDrawers;
291       function CanFinishReminder: boolean;
292       procedure DisplayPCE;
293       function VerifyNoteTitle: Boolean;
294       //  added for treeview
295       procedure LoadNotes;
296       procedure UpdateTreeView(DocList: TStringList; Tree: TORTreeView);
297       procedure  EnableDisableIDNotes;
298       procedure ShowPCEButtons(Editing: boolean);
299       procedure DoAttachIDChild(AChild, AParent: TORTreeNode);
300       function SetNoteTreeLabel(AContext: TTIUContext): string;
301       procedure UpdateNoteAuthor(DocInfo: string);
302     public
303       function ActiveEditOf(AnIEN: Int64; ARequest: integer): Boolean;
304       function AllowContextChange(var WhyNot: string): Boolean; override;
305       procedure ClearPtData; override;
306       procedure DisplayPage; override;
307       procedure RequestPrint; override;
308       procedure RequestMultiplePrint(AForm: TfrmPrintList);
309       procedure SetFontSize(NewFontSize: Integer); override;
310       procedure SaveSignItem(const ItemID, ESCode: string);
311       procedure AssignRemForm;
312       property  OrderID: string read FOrderID;
313       procedure LstNotesToPrint;
314       procedure UpdateFormForInput;
315     published
316       property Drawers: TfrmDrawers read GetDrawers; // Keep Drawers published
317     end;
318   
319   var
320     frmNotes: TfrmNotes;
321     SearchTextStopFlag: Boolean;   // Text Search CQ: HDS00002856
322   
323   implementation
324   
325   {$R *.DFM}
326   
327   uses fFrame, fVisit, fEncnt, rCore, uCore, fNoteBA, fNoteBD, fSignItem, fEncounterFrame,
328        rPCE, Clipbrd, fNoteCslt, fNotePrt, rVitals, fAddlSigners, fNoteDR, fConsults, uSpell,
329        fTIUView, fTemplateEditor, uReminders, fReminderDialog, uOrders, rConsults, fReminderTree,
330        fNoteProps, fNotesBP, fTemplateFieldEditor, dShared, rTemplates,
331        fIconLegend, fPCEEdit, fNoteIDParents, rSurgery, uSurgery, uTemplates,
332        fTemplateDialog, DateUtils, uInit, uVA508CPRSCompatibility, VA508AccessibilityRouter,
333     VAUtils;
334        
335   const
336   
337     NT_NEW_NOTE = -10;                             // Holder IEN for a new note
338     NT_ADDENDUM = -20;                             // Holder IEN for a new addendum
339   
340     NT_ACT_NEW_NOTE  = 2;
341     NT_ACT_ADDENDUM  = 3;
342     NT_ACT_EDIT_NOTE = 4;
343     NT_ACT_ID_ENTRY  = 5;
344   
345     TX_NEED_VISIT = 'A visit is required before creating a new progress note.';
346     TX_CREATE_ERR = 'Error Creating Note';
347     TX_UPDATE_ERR = 'Error Updating Note';
348     TX_NO_NOTE    = 'No progress note is currently being edited';
349     TX_SAVE_NOTE  = 'Save Progress Note';
350     TX_ADDEND_NO  = 'Cannot make an addendum to a note that is being edited';
351     TX_DEL_OK     = CRLF + CRLF + 'Delete this progress note?';
352     TX_DEL_ERR    = 'Unable to Delete Note';
353     TX_SIGN       = 'Sign Note';
354     TX_COSIGN     = 'Cosign Note';
355     TX_SIGN_ERR   = 'Unable to Sign Note';
356   //  TX_SCREQD     = 'This progress note title requires the service connected questions to be '+
357   //                  'answered.  The Encounter form will now be opened.  Please answer all '+
358   //                 'service connected questions.';
359   //  TX_SCREQD_T   = 'Response required for SC questions.';
360     TX_NONOTE     = 'No progress note is currently selected.';
361     TX_NONOTE_CAP = 'No Note Selected';
362     TX_NOPRT_NEW  = 'This progress note may not be printed until it is saved';
363     TX_NOPRT_NEW_CAP = 'Save Progress Note';
364     TX_NO_ALERT   = 'There is insufficient information to process this alert.' + CRLF +
365                     'Either the alert has already been deleted, or it contained invalid data.' + CRLF + CRLF +
366                     'Click the NEXT button if you wish to continue processing more alerts.';
367     TX_CAP_NO_ALERT = 'Unable to Process Alert';
368     TX_ORDER_LOCKED = 'This record is locked by an action underway on the Consults tab';
369     TC_ORDER_LOCKED = 'Unable to access record';
370     TX_NO_ORD_CHG   = 'The note is still associated with the previously selected request.' + CRLF +
371                       'Finish the pending action on the consults tab, then try again.';
372     TC_NO_ORD_CHG   = 'Locked Consult Request';
373     TX_NEW_SAVE1    = 'You are currently editing:' + CRLF + CRLF;
374     TX_NEW_SAVE2    = CRLF + CRLF + 'Do you wish to save this note and begin a new one?';
375     TX_NEW_SAVE3    = CRLF + CRLF + 'Do you wish to save this note and begin a new addendum?';
376     TX_NEW_SAVE4    = CRLF + CRLF + 'Do you wish to save this note and edit the one selected?';
377     TX_NEW_SAVE5    = CRLF + CRLF + 'Do you wish to save this note and begin a new Interdisciplinary entry?';
378     TC_NEW_SAVE2    = 'Create New Note';
379     TC_NEW_SAVE3    = 'Create New Addendum';
380     TC_NEW_SAVE4    = 'Edit Different Note';
381     TC_NEW_SAVE5    = 'Create New Interdisciplinary Entry';
382     TX_EMPTY_NOTE   = CRLF + CRLF + 'This note contains no text and will not be saved.' + CRLF +
383                       'Do you wish to delete this note?';
384     TC_EMPTY_NOTE   = 'Empty Note';
385     TX_EMPTY_NOTE1   = 'This note contains no text and can not be signed.';
386     TC_NO_LOCK      = 'Unable to Lock Note';
387     TX_ABSAVE       = 'It appears the session terminated abnormally when this' + CRLF +
388                       'note was last edited. Some text may not have been saved.' + CRLF + CRLF +
389                       'Do you wish to continue and sign the note?';
390     TC_ABSAVE       = 'Possible Missing Text';
391     TX_NO_BOIL      = 'There is no boilerplate text associated with this title.';
392     TC_NO_BOIL      = 'Load Boilerplate Text';
393     TX_BLR_CLEAR    = 'Do you want to clear the previously loaded boilerplate text?';
394     TC_BLR_CLEAR    = 'Clear Previous Boilerplate Text';
395     TX_DETACH_CNF     = 'Confirm Detachment';
396     TX_DETACH_FAILURE = 'Detach failed';
397     TX_RETRACT_CAP    = 'Retraction Notice';
398     TX_RETRACT        = 'This document will now be RETRACTED.  As Such, it has been removed' +CRLF +
399                         ' from public view, and from typical Releases of Information,' +CRLF +
400                         ' but will remain indefinitely discoverable to HIMS.' +CRLF +CRLF;
401     TX_AUTH_SIGNED    = 'Author has not signed, are you SURE you want to sign.' +CRLF;
402   {
403   type
404     //CQ8300
405     ClipboardData = record
406        Text: array[0..255] of char;
407     end;
408   }
409   var
410     uPCEShow, uPCEEdit:  TPCEData;
411     ViewContext: Integer;
412     frmDrawers: TfrmDrawers;
413     uTIUContext: TTIUContext;
414     ColumnToSort: Integer;
415     ColumnSortForward: Boolean;
416     uChanging: Boolean;
417     uIDNotesActive: Boolean;
418     NoteTotal: string;
419   
420   
421   { TPage common methods --------------------------------------------------------------------- }
422   function TfrmNotes.AllowContextChange(var WhyNot: string): Boolean;
423   begin
424     dlgFindText.CloseDialog;
425     Result := inherited AllowContextChange(WhyNot);  // sets result = true
426     if Assigned(frmTemplateDialog) then
427       if Screen.ActiveForm = frmTemplateDialog then
428       //if (fsModal in frmTemplateDialog.FormState) then
429       case BOOLCHAR[frmFrame.CCOWContextChanging] of
430         '1': begin
431                WhyNot := 'A template in progress will be aborted.  ';
432                Result := False;
433              end;
434         '0': begin
435                if WhyNot = 'COMMIT' then
436                  begin
437                    FSilent := True;
438                    frmTemplateDialog.Silent := True;
439                    frmTemplateDialog.ModalResult := mrCancel;
440                  end;
441              end;
442       end;
443     if Assigned(frmRemDlg) then
444       case BOOLCHAR[frmFrame.CCOWContextChanging] of
445         '1': begin
446                WhyNot := 'All current reminder processing information will be discarded.  ';
447                Result := False;
448              end;
449         '0': begin
450                if WhyNot = 'COMMIT' then
451                  begin
452                    FSilent := True;
453                    frmRemDlg.Silent := True;
454                    frmRemDlg.btnCancelClick(Self);
455                  end;
456                //agp fix for a problem with reminders not clearing out when switching patients
457                if WhyNot = '' then
458                   begin
459                    frmRemDlg.btnCancelClick(Self);
460                    if assigned(frmRemDlg) then
461                      begin
462                        result := false;
463                        exit;
464                      end;
465                   end;
466              end;
467       end;
468     if EditingIndex <> -1 then
469       case BOOLCHAR[frmFrame.CCOWContextChanging] of
470         '1': begin
471                if memNewNote.GetTextLen > 0 then
472                  WhyNot := WhyNot + 'A note in progress will be saved as unsigned.  '
473                else
474                  WhyNot := WhyNot + 'An empty note in progress will be deleted.  ';
475                Result := False;
476              end;
477         '0': begin
478                if WhyNot = 'COMMIT' then FSilent := True;
479                SaveCurrentNote(Result);
480              end;
481       end;
482     if Assigned(frmEncounterFrame) then
483       if Screen.ActiveForm = frmEncounterFrame then
484       //if (fsModal in frmEncounterFrame.FormState) then
485       case BOOLCHAR[frmFrame.CCOWContextChanging] of
486         '1': begin
487                WhyNot := WhyNot + 'Encounter information being edited will not be saved';
488                Result := False;
489              end;
490         '0': begin
491                if WhyNot = 'COMMIT' then
492                  begin
493                    FSilent := True;
494                    frmEncounterFrame.Abort := False;
495                    frmEncounterFrame.Cancel := True;
496                  end;
497              end;
498       end;
499   end;
500   
501   procedure TfrmNotes.LstNotesToPrint;       
502   var
503     AParentID: string;
504     SavedDocID: string;
505     Saved: boolean;
506   begin
507     inherited;
508     if not uIDNotesActive then exit;
509     if lstNotes.ItemIEN = 0 then exit;           
510     SavedDocID := lstNotes.ItemID;
511     if EditingIndex <> -1 then
512     begin
513       SaveCurrentNote(Saved);
514       if not Saved then Exit;
515       LoadNotes;
516       with tvNotes do Selected := FindPieceNode(SavedDocID, U, Items.GetFirstNode);
517     end;
518     if tvNotes.Selected = nil then exit;
519     AParentID := frmPrintList.SelectParentFromList(tvNotes,CT_NOTES);
520     if AParentID = '' then exit;
521     with tvNotes do Selected := FindPieceNode(AParentID, 1, U, Items.GetFirstNode);
522   end;
523   
524   procedure TfrmNotes.ClearPtData;
525   { clear all controls that contain patient specific information }
526   begin
527     inherited ClearPtData;
528     ClearEditControls;
529     uChanging := True;
530     tvNotes.Items.BeginUpdate;
531     KillDocTreeObjects(tvNotes);
532     tvNotes.Items.Clear;
533     tvNotes.Items.EndUpdate;
534     lvNotes.Items.Clear;
535     uChanging := False;
536     lstNotes.Clear;
537     memNote.Clear;
538     memPCEShow.Clear;
539     uPCEShow.Clear;
540     uPCEEdit.Clear;
541     frmDrawers.ResetTemplates;
542     NoteTotal := sCallV('ORCNOTE GET TOTAL', [Patient.DFN]);
543   end;
544   
545   procedure TfrmNotes.DisplayPage;
546   { causes page to be visible and conditionally executes initialization code }
547   begin
548     inherited DisplayPage;
549     frmFrame.ShowHideChartTabMenus(mnuViewChart);
550     frmFrame.mnuFilePrint.Tag := CT_NOTES;
551     frmFrame.mnuFilePrint.Enabled := True;
552     frmFrame.mnuFilePrintSetup.Enabled := True;
553     frmFrame.mnuFilePrintSelectedItems.Enabled := True;
554     if InitPage then
555     begin
556       EnableDisableIDNotes;
557       FDefaultContext := GetCurrentTIUContext;
558       FCurrentContext := FDefaultContext;
559       popNoteMemoSpell.Visible   := SpellCheckAvailable;
560       popNoteMemoGrammar.Visible := popNoteMemoSpell.Visible;
561       Z11.Visible                := popNoteMemoSpell.Visible;
562       timAutoSave.Interval := User.AutoSave * 1000;  // convert seconds to milliseconds
563       SetEqualTabStops(memNewNote);
564     end;
565     // to indent the right margin need to set Paragraph.RightIndent for each paragraph?
566     if InitPatient and not (CallingContext = CC_NOTIFICATION) then
567       begin
568         SetViewContext(FDefaultContext);
569       end;
570     case CallingContext of
571       CC_INIT_PATIENT: if not InitPatient then
572                          begin
573                            SetViewContext(FDefaultContext);
574                          end;
575       CC_NOTIFICATION:  ProcessNotifications;
576     end;
577   end;
578   
579   procedure TfrmNotes.RequestPrint;
580   var
581     Saved: Boolean;
582   begin
583     with lstNotes do
584     begin
585       if ItemIndex = EditingIndex then
586       //if ItemIEN < 0 then
587       begin
588         SaveCurrentNote(Saved);
589         if not Saved then Exit;
590       end;
591       if ItemIEN > 0 then PrintNote(ItemIEN, MakeNoteDisplayText(Items[ItemIndex])) else
592       begin
593         if ItemIEN = 0 then InfoBox(TX_NONOTE, TX_NONOTE_CAP, MB_OK);
594         if ItemIEN < 0 then InfoBox(TX_NOPRT_NEW, TX_NOPRT_NEW_CAP, MB_OK);
595       end;
596     end;
597   end;
598   
599   {for printing multiple notes}
600   procedure TfrmNotes.RequestMultiplePrint(AForm: TfrmPrintList);
601   var
602     NoteIEN: int64;
603     i: integer;
604   begin
605     with AForm.lbIDParents do
606     begin
607       for i := 0 to Items.Count - 1 do
608        begin
609          if Selected[i] then
610           begin
611            AForm.lbIDParents.ItemIndex := i;
612            NoteIEN := ItemIEN;  //StrToInt64def(Piece(TStringList(Items.Objects[i])[0],U,1),0);
613            if NoteIEN > 0 then PrintNote(NoteIEN, DisplayText[i], TRUE) else
614            begin
615              if NoteIEN = 0 then InfoBox(TX_NONOTE, TX_NONOTE_CAP, MB_OK);
616              if NoteIEN < 0 then InfoBox(TX_NOPRT_NEW, TX_NOPRT_NEW_CAP, MB_OK);
617            end;
618           end; {if selected}
619        end; {for}
620     end; {with}
621   end;
622   
623   procedure TfrmNotes.SetFontSize(NewFontSize: Integer);
624   { adjusts the font size of any controls that don't have ParentFont = True }
625   begin
626     inherited SetFontSize(NewFontSize);
627     frmDrawers.Font.Size  := NewFontSize;
628     SetEqualTabStops(memNewNote);
629     pnlWriteResize(Self);
630   end;
631   
632   procedure TfrmNotes.mnuChartTabClick(Sender: TObject);
633   { reroute to Chart Tab menu of the parent form: frmFrame }
634   begin
635     inherited;
636     frmFrame.mnuChartTabClick(Sender);
637   end;
638   
639   { General procedures ----------------------------------------------------------------------- }
640   
641   procedure TfrmNotes.ClearEditControls;
642   { resets controls used for entering a new progress note }
643   begin
644     // clear FEditNote (should FEditNote be an object with a clear method?)
645     with FEditNote do
646     begin
647       DocType      := 0;
648       Title        := 0;
649       TitleName    := '';
650       DateTime     := 0;
651       Author       := 0;
652       AuthorName   := '';
653       Cosigner     := 0;
654       CosignerName := '';
655       Subject      := '';
656       Location     := 0;
657       LocationName := '';
658       PkgIEN       := 0;
659       PkgPtr       := '';
660       PkgRef       := '';
661       NeedCPT      := False;
662       Addend       := 0;
663       {LastCosigner & LastCosignerName aren't cleared because they're used as default for next note.}
664       Lines        := nil;
665       PRF_IEN := 0;
666       ActionIEN := '';
667     end;
668     // clear the editing controls (also clear the new labels?)
669     txtSubject.Text := '';
670     SearchTextStopFlag := false;
671     if memNewNote <> nil then memNewNote.Clear; //CQ7012 Added test for nil
672     timAutoSave.Enabled := False;
673     // clear the PCE object for editing
674     uPCEEdit.Clear;
675     // set the tracking variables to initial state
676     EditingIndex := -1;
677     FChanged := False;
678   end;
679   
680   procedure TfrmNotes.ShowPCEControls(ShouldShow: Boolean);
681   begin
682     sptVert.Visible    := ShouldShow;
683     memPCEShow.Visible := ShouldShow;
684     if(ShouldShow) then
685       sptVert.Top := memPCEShow.Top - sptVert.Height;
686     memNote.Invalidate;
687   end;
688   
689   procedure TfrmNotes.DisplayPCE;
690   { displays PCE information if appropriate & enables/disabled editing of PCE data }
691   var
692     EnableList, ShowList: TDrawers;
693     VitalStr:   TStringlist;
694     NoPCE:      boolean;
695     ActionSts: TActionRec;
696     AnIEN: integer;
697   begin
698     memPCEShow.Clear;
699     with lstNotes do if ItemIndex = EditingIndex then
700     begin
701       with uPCEEdit do
702       begin
703         AddStrData(memPCEShow.Lines);
704         NoPCE := (memPCEShow.Lines.Count = 0);
705         VitalStr  := TStringList.create;
706         try
707           GetVitalsFromDate(VitalStr, uPCEEdit);
708           AddVitalData(VitalStr, memPCEShow.Lines);
709         finally
710           VitalStr.free;
711         end;
712         ShowPCEButtons(TRUE);
713         ShowPCEControls(cmdPCE.Enabled or (memPCEShow.Lines.Count > 0));
714         if(NoPCE and memPCEShow.Visible) then
715           memPCEShow.Lines.Insert(0, TX_NOPCE);
716         memPCEShow.SelStart := 0;
717   
718         if(InteractiveRemindersActive) then
719         begin
720           if(GetReminderStatus = rsNone) then
721             EnableList := [odTemplates]
722           else
723             if FutureEncounter(uPCEEdit) then
724               begin
725                 EnableList := [odTemplates];
726                 ShowList := [odTemplates];
727               end
728             else
729               begin
730                 EnableList := [odTemplates, odReminders];
731                 ShowList := [odTemplates, odReminders];
732               end;
733         end
734         else
735         begin
736           EnableList := [odTemplates];
737           ShowList := [odTemplates];
738         end;
739         frmDrawers.DisplayDrawers(TRUE, EnableList, ShowList);
740       end;
741     end else
742     begin
743       ShowPCEButtons(FALSE);
744       frmDrawers.DisplayDrawers(TRUE, [odTemplates], [odTemplates]);
745       AnIEN := lstNotes.ItemIEN;
746       ActOnDocument(ActionSts, AnIEN, 'VIEW');
747       if ActionSts.Success then
748       begin
749         StatusText('Retrieving encounter information...');
750         with uPCEShow do
751         begin
752           NoteDateTime := MakeFMDateTime(Piece(lstNotes.Items[lstNotes.ItemIndex], U, 3));
753           PCEForNote(AnIEN, uPCEEdit);
754           AddStrData(memPCEShow.Lines);
755           NoPCE := (memPCEShow.Lines.Count = 0);
756           VitalStr  := TStringList.create;
757           try
758             GetVitalsFromNote(VitalStr, uPCEShow, AnIEN);
759             AddVitalData(VitalStr, memPCEShow.Lines);
760           finally
761             VitalStr.free;
762           end;
763           ShowPCEControls(memPCEShow.Lines.Count > 0);
764           if(NoPCE and memPCEShow.Visible) then
765             memPCEShow.Lines.Insert(0, TX_NOPCE);
766           memPCEShow.SelStart := 0;
767         end;
768         StatusText('');
769       end
770       else
771         ShowPCEControls(FALSE);
772     end; {if ItemIndex}
773     mnuEncounter.Enabled := cmdPCE.Visible;
774   end;
775   
776   { supporting calls for writing notes }
777   
778   function TfrmNotes.GetTitleText(AnIndex: Integer): string;
779   { returns non-tabbed text for the title of a note given the ItemIndex in lstNotes }
780   begin
781     with lstNotes do
782       Result := FormatFMDateTime('mmm dd,yy', MakeFMDateTime(Piece(Items[AnIndex], U, 3))) +
783                 '  ' + Piece(Items[AnIndex], U, 2) + ', ' + Piece(Items[AnIndex], U, 6) + ', ' +
784                 Piece(Piece(Items[AnIndex], U, 5), ';', 2)
785   end;
786   
787   function TfrmNotes.LacksRequiredForCreate: Boolean;
788   { determines if the fields required to create the note are present }
789   var
790     CurTitle: Integer;
791   begin
792     Result := False;
793     with FEditNote do
794     begin
795       if Title <= 0    then Result := True;
796       if Author <= 0   then Result := True;
797       if DateTime <= 0 then Result := True;
798       if IsConsultTitle(Title) and (PkgIEN = 0) then Result := True;
799       if IsSurgeryTitle(Title) and (PkgIEN = 0) then Result := True;
800       if IsPRFTitle(Title) and (PRF_IEN = 0) and (not DocType = TYP_ADDENDUM) then Result := True;
801       if (DocType = TYP_ADDENDUM) then
802       begin
803         if AskCosignerForDocument(Addend, Author, DateTime) and (Cosigner <= 0) then Result := True;
804       end else
805       begin
806         if Title > 0 then CurTitle := Title else CurTitle := DocType;
807         if AskCosignerForTitle(CurTitle, Author, DateTime) and (Cosigner <= 0) then Result := True;
808       end;
809     end;
810   end;
811   
812   function TfrmNotes.VerifyNoteTitle: Boolean;
813   const
814     VNT_UNKNOWN = 0;
815     VNT_NO      = 1;
816     VNT_YES     = 2;
817   var
818     AParam: string;
819   begin
820     if FVerifyNoteTitle = VNT_UNKNOWN then
821     begin
822       AParam := GetUserParam('ORWOR VERIFY NOTE TITLE');
823       if AParam = '1' then FVerifyNoteTitle := VNT_YES else FVerifyNoteTitle := VNT_NO;
824     end;
825     Result := FVerifyNoteTitle = VNT_YES;
826   end;
827   
828   procedure TfrmNotes.SetSubjectVisible(ShouldShow: Boolean);
829   { hide/show subject & resize panel accordingly - leave 6 pixel margin above memNewNote }
830   begin
831     if ShouldShow then
832     begin
833       lblSubject.Visible := True;
834       txtSubject.Visible := True;
835       pnlFields.Height   := txtSubject.Top + txtSubject.Height + 6;
836     end else
837     begin
838       lblSubject.Visible := False;
839       txtSubject.Visible := False;
840       pnlFields.Height   := lblVisit.Top + lblVisit.Height + 6;
841     end;
842   end;
843   
844   { consult request and note locking }
845   
846   function TfrmNotes.LockConsultRequest(AConsult: Integer): Boolean;
847   { returns true if consult successfully locked }
848   begin
849     // *** I'm not sure about the FOrderID field - if the user is editing one note and
850     //     deletes another, FOrderID will be for editing note, then delete note, then null
851     Result := True;
852     FOrderID := GetConsultOrderIEN(AConsult);
853     if (FOrderID <> '') and (FOrderID = frmConsults.OrderID) then
854     begin
855       InfoBox(TX_ORDER_LOCKED, TC_ORDER_LOCKED, MB_OK);
856       Result := False;
857       Exit;
858     end;
859     if (FOrderId <> '') then
860       if not OrderCanBeLocked(FOrderID) then Result := False;
861     if not Result then FOrderID := '';
862   end;
863   
864   function TfrmNotes.LockConsultRequestAndNote(AnIEN: Int64): Boolean;
865   { returns true if note and associated request successfully locked }
866   var
867     AConsult: Integer;
868     LockMsg, x: string;
869   begin
870     Result := True;
871     AConsult := 0;
872     if frmConsults.ActiveEditOf(AnIEN) then
873       begin
874         InfoBox(TX_ORDER_LOCKED, TC_ORDER_LOCKED, MB_OK);
875         Result := False;
876         Exit;
877       end;
878       if Changes.Exist(CH_DOC, IntToStr(AnIEN)) then Exit;  // already locked
879     // try to lock the consult request first, if there is one
880     if IsConsultTitle(TitleForNote(AnIEN)) then
881     begin
882       x := GetPackageRefForNote(lstNotes.ItemIEN);
883       AConsult := StrToIntDef(Piece(x, ';', 1), 0);
884       Result := LockConsultRequest(AConsult);
885     end;
886     // now try to lock the note
887     if Result then
888     begin
889       LockDocument(AnIEN, LockMsg);
890       if LockMsg <> '' then
891       begin
892         Result := False;
893         // if can't lock the note, unlock the consult request that was just locked
894         if AConsult > 0 then
895         begin
896           UnlockOrderIfAble(FOrderID);
897           FOrderID := '';
898         end;
899         InfoBox(LockMsg, TC_NO_LOCK, MB_OK);
900       end;
901     end;
902   end;
903   
904   procedure TfrmNotes.UnlockConsultRequest(ANote: Int64; AConsult: Integer = 0);
905   (*var
906     x: string;*)
907   begin
908   (*  if (AConsult = 0) and IsConsultTitle(TitleForNote(ANote)) then
909       begin
910         x := GetPackageRefForNote(ANote);
911         AConsult := StrToIntDef(Piece(x, ';', 1), 0);
912       end;
913     if AConsult = 0 then Exit;*)
914     if AConsult = 0 then AConsult := GetConsultIENforNote(ANote);
915     if AConsult <= 0 then exit;
916     FOrderID := GetConsultOrderIEN(AConsult);
917     UnlockOrderIfAble(FOrderID);
918     FOrderID := '';
919   end;
920   
921   function TfrmNotes.ActiveEditOf(AnIEN: Int64; ARequest: integer): Boolean;
922   begin
923     Result := False;
924     if EditingIndex < 0 then Exit;
925     if lstNotes.GetIEN(EditingIndex) = AnIEN then
926       begin
927         Result := True;
928         Exit;
929       end;
930     with FEditNote do if (PkgIEN = ARequest) and (PkgPtr = PKG_CONSULTS) then Result := True;
931   end;
932   
933   { create, edit & save notes }
934   
935   procedure TfrmNotes.InsertNewNote(IsIDChild: boolean; AnIDParent: integer);
936   { creates the editing context for a new progress note & inserts stub into top of view list }
937   var
938     EnableAutosave, HaveRequired: Boolean;
939     CreatedNote: TCreatedDoc;
940     TmpBoilerPlate: TStringList;
941     tmpNode: TTreeNode;
942     x, WhyNot, DocInfo: string;
943   begin
944     if frmFrame.Timedout then Exit;
945   
946     FNewIDChild := IsIDChild;
947     EnableAutosave := FALSE;
948     TmpBoilerPlate := nil;
949     try
950       ClearEditControls;
951       FillChar(FEditNote, SizeOf(FEditNote), 0);  //v15.7
952       with FEditNote do
953       begin
954         DocType      := TYP_PROGRESS_NOTE;
955         IsNewNote    := True;
956         Title        := DfltNoteTitle;
957         TitleName    := DfltNoteTitleName;
958         if IsIDChild and (not CanTitleBeIDChild(Title, WhyNot)) then
959           begin
960             Title := 0;
961             TitleName := '';
962           end;
963         if IsSurgeryTitle(Title) then    // Don't want surgery title sneaking in unchallenged
964           begin
965             Title := 0;
966             TitleName := '';
967           end;
968         DateTime     := FMNow;
969         Author       := User.DUZ;
970         AuthorName   := User.Name;
971         Location     := Encounter.Location;
972         LocationName := Encounter.LocationName;
973         VisitDate    := Encounter.DateTime;
974         if IsIDChild then
975           IDParent   := AnIDParent
976         else
977           IDParent   := 0;
978         // Cosigner & PkgRef, if needed, will be set by fNoteProps
979       end;
980       // check to see if interaction necessary to get required fields
981       GetUnresolvedConsultsInfo;
982       if LacksRequiredForCreate or VerifyNoteTitle or uUnresolvedConsults.UnresolvedConsultsExist
983         then HaveRequired := ExecuteNoteProperties(FEditNote, CT_NOTES, IsIDChild, FNewIDChild, '', 0)
984         else HaveRequired := True;
985       // lock the consult request if there is a consult
986       with FEditNote do if (PkgIEN > 0) and (PkgPtr = PKG_CONSULTS) then HaveRequired := LockConsultRequest(PkgIEN);
987       if HaveRequired then
988       begin
989         // set up uPCEEdit for entry of new note
990         uPCEEdit.UseEncounter := True;
991         uPCEEdit.NoteDateTime := FEditNote.DateTime;
992         uPCEEdit.PCEForNote(USE_CURRENT_VISITSTR, uPCEShow);
993         FEditNote.NeedCPT  := uPCEEdit.CPTRequired;
994          // create the note
995         PutNewNote(CreatedNote, FEditNote);
996         uPCEEdit.NoteIEN := CreatedNote.IEN;
997         if CreatedNote.IEN > 0 then LockDocument(CreatedNote.IEN, CreatedNote.ErrorText);
998         if CreatedNote.ErrorText = '' then
999         begin
1000          //x := $$RESOLVE^TIUSRVLO formatted string
1001          //7348^Note Title^3000913^NERD, YOURA  (N0165)^1329;Rich Vertigan;VERTIGAN,RICH^8E REHAB MED^complete^Adm: 11/05/98;2981105.095547^        ;^^0^^^2
1002          with FEditNote do
1003          begin
1004            x := IntToStr(CreatedNote.IEN) + U + TitleName + U + FloatToStr(FEditNote.DateTime) + U +
1005                 Patient.Name + U + IntToStr(Author) + ';' + AuthorName + U + LocationName + U + 'new' + U +
1006                 U + U + U + U + U + U + U;
1007            //Link Note to PRF Action
1008            if PRF_IEN <> 0 then
1009              if sCallV('TIU LINK TO FLAG', [CreatedNote.IEN,PRF_IEN,ActionIEN,Patient.DFN]) = '0' then
1010                ShowMsg('TIU LINK TO FLAG: FAILED');
1011          end;
1012  
1013          lstNotes.Items.Insert(0, x);
1014          uChanging := True;
1015          tvNotes.Items.BeginUpdate;
1016          if IsIDChild then
1017            begin
1018              tmpNode := tvNotes.FindPieceNode(IntToStr(AnIDParent), 1, U, tvNotes.Items.GetFirstNode);
1019              tmpNode.ImageIndex := IMG_IDNOTE_OPEN;
1020              tmpNode.SelectedIndex := IMG_IDNOTE_OPEN;
1021              tmpNode := tvNotes.Items.AddChildObjectFirst(tmpNode, MakeNoteDisplayText(x), MakeNoteTreeObject(x));
1022              tmpNode.ImageIndex := IMG_ID_CHILD;
1023              tmpNode.SelectedIndex := IMG_ID_CHILD;
1024            end
1025          else
1026            begin
1027              tmpNode := tvNotes.Items.AddObjectFirst(tvNotes.Items.GetFirstNode, 'New Note in Progress',
1028                                                      MakeNoteTreeObject('NEW^New Note in Progress^^^^^^^^^^^%^0'));
1029              TORTreeNode(tmpNode).StringData := 'NEW^New Note in Progress^^^^^^^^^^^%^0';
1030              tmpNode.ImageIndex := IMG_TOP_LEVEL;
1031              tmpNode := tvNotes.Items.AddChildObjectFirst(tmpNode, MakeNoteDisplayText(x), MakeNoteTreeObject(x));
1032              tmpNode.ImageIndex := IMG_SINGLE;
1033              tmpNode.SelectedIndex := IMG_SINGLE;
1034            end;
1035          tmpNode.StateIndex := IMG_NO_IMAGES;
1036          TORTreeNode(tmpNode).StringData := x;
1037          tvNotes.Selected := tmpNode;
1038          tvNotes.Items.EndUpdate;
1039          uChanging := False;
1040          Changes.Add(CH_DOC, IntToStr(CreatedNote.IEN), GetTitleText(0), '', CH_SIGN_YES);
1041          lstNotes.ItemIndex := 0;
1042          EditingIndex := 0;
1043          SetSubjectVisible(AskSubjectForNotes);
1044          if not assigned(TmpBoilerPlate) then
1045            TmpBoilerPlate := TStringList.Create;
1046          LoadBoilerPlate(TmpBoilerPlate, FEditNote.Title);
1047          FChanged := False;
1048          cmdChangeClick(Self); // will set captions, sign state for Changes
1049          lstNotesClick(Self);  // will make pnlWrite visible
1050          if timAutoSave.Interval <> 0 then EnableAutosave := TRUE;
1051          if txtSubject.Visible then txtSubject.SetFocus else memNewNote.SetFocus;
1052        end else
1053        begin
1054          // if note creation failed or failed to get note lock (both unlikely), unlock consult
1055          with FEditNote do if (PkgIEN > 0) and (PkgPtr = PKG_CONSULTS) then UnlockConsultRequest(0, PkgIEN);
1056          InfoBox(CreatedNote.ErrorText, TX_CREATE_ERR, MB_OK);
1057          HaveRequired := False;
1058        end; {if CreatedNote.IEN}
1059      end; {if HaveRequired}
1060      if not HaveRequired then
1061      begin
1062        ClearEditControls;
1063        ShowPCEButtons(False);
1064      end;
1065    finally
1066      if assigned(TmpBoilerPlate) then
1067      begin
1068        DocInfo := MakeXMLParamTIU(IntToStr(CreatedNote.IEN), FEditNote);
1069        ExecuteTemplateOrBoilerPlate(TmpBoilerPlate, FEditNote.Title, ltTitle, Self, 'Title: ' + FEditNote.TitleName, DocInfo);
1070        QuickCopyWith508Msg(TmpBoilerPlate, memNewNote);
1071        UpdateNoteAuthor(DocInfo);
1072        TmpBoilerPlate.Free;
1073      end;
1074      if EnableAutosave then // Don't enable autosave until after dialog fields have been resolved
1075        timAutoSave.Enabled := True;
1076    end;
1077    frmNotes.pnlWriteResize(Self);
1078  end;
1079  
1080  procedure TfrmNotes.InsertAddendum;
1081  { sets up fields of pnlWrite to write an addendum for the selected note }
1082  const
1083    AS_ADDENDUM = True;
1084    IS_ID_CHILD = False;
1085  var
1086    HaveRequired: Boolean;
1087    CreatedNote: TCreatedDoc;
1088    tmpNode: TTreeNode;
1089    x: string;
1090  begin
1091    ClearEditControls;
1092    with FEditNote do
1093    begin
1094      DocType      := TYP_ADDENDUM;
1095      IsNewNote    := False;
1096      Title        := TitleForNote(lstNotes.ItemIEN);
1097      TitleName    := Piece(lstNotes.Items[lstNotes.ItemIndex], U, 2);
1098      if Copy(TitleName,1,1) = '+' then TitleName := Copy(TitleName, 3, 199);
1099      DateTime     := FMNow;
1100      Author       := User.DUZ;
1101      AuthorName   := User.Name;
1102      x            := GetPackageRefForNote(lstNotes.ItemIEN);
1103      if Piece(x, U, 1) <> '-1' then
1104        begin
1105          PkgRef       := GetPackageRefForNote(lstNotes.ItemIEN);
1106          PkgIEN       := StrToIntDef(Piece(PkgRef, ';', 1), 0);
1107          PkgPtr       := Piece(PkgRef, ';', 2);
1108        end;
1109      Addend       := lstNotes.ItemIEN;
1110      //Lines        := memNewNote.Lines;
1111      // Cosigner, if needed, will be set by fNoteProps
1112      // Location info will be set after the encounter is loaded
1113    end;
1114    // check to see if interaction necessary to get required fields
1115    if LacksRequiredForCreate
1116      then HaveRequired := ExecuteNoteProperties(FEditNote, CT_NOTES, IS_ID_CHILD, False, '', 0)
1117      else HaveRequired := True;
1118    // lock the consult request if there is a consult
1119    if HaveRequired then
1120      with FEditNote do
1121        if (PkgIEN > 0) and (PkgPtr = PKG_CONSULTS) then HaveRequired := LockConsultRequest(PkgIEN);
1122    if HaveRequired then
1123    begin
1124      uPCEEdit.NoteDateTime := FEditNote.DateTime;
1125      uPCEEdit.PCEForNote(FEditNote.Addend, uPCEShow);
1126      FEditNote.Location     := uPCEEdit.Location;
1127      FEditNote.LocationName := ExternalName(uPCEEdit.Location, 44);
1128      FEditNote.VisitDate    := uPCEEdit.DateTime;
1129      PutAddendum(CreatedNote, FEditNote, FEditNote.Addend);
1130      uPCEEdit.NoteIEN := CreatedNote.IEN;
1131      if CreatedNote.IEN > 0 then LockDocument(CreatedNote.IEN, CreatedNote.ErrorText);
1132      if CreatedNote.ErrorText = '' then
1133      begin
1134        with FEditNote do
1135          begin
1136            x := IntToStr(CreatedNote.IEN) + U + 'Addendum to ' + TitleName + U + FloatToStr(DateTime) + U +
1137                 Patient.Name + U + IntToStr(Author) + ';' + AuthorName + U + LocationName + U + 'new' + U +
1138                 U + U + U + U + U + U + U;
1139          end;
1140  
1141        lstNotes.Items.Insert(0, x);
1142        uChanging := True;
1143        tvNotes.Items.BeginUpdate;
1144        tmpNode := tvNotes.Items.AddObjectFirst(tvNotes.Items.GetFirstNode, 'New Addendum in Progress',
1145                                                MakeNoteTreeObject('ADDENDUM^New Addendum in Progress^^^^^^^^^^^%^0'));
1146        TORTreeNode(tmpNode).StringData := 'ADDENDUM^New Addendum in Progress^^^^^^^^^^^%^0';
1147        tmpNode.ImageIndex := IMG_TOP_LEVEL;
1148        tmpNode := tvNotes.Items.AddChildObjectFirst(tmpNode, MakeNoteDisplayText(x), MakeNoteTreeObject(x));
1149        TORTreeNode(tmpNode).StringData := x;
1150  
1151        tmpNode.ImageIndex := IMG_ADDENDUM;
1152        tmpNode.SelectedIndex := IMG_ADDENDUM;
1153        tvNotes.Selected := tmpNode;
1154        tvNotes.Items.EndUpdate;
1155        uChanging := False;
1156        Changes.Add(CH_DOC, IntToStr(CreatedNote.IEN), GetTitleText(0), '', CH_SIGN_YES);
1157        lstNotes.ItemIndex := 0;
1158        EditingIndex := 0;
1159        SetSubjectVisible(AskSubjectForNotes);
1160        cmdChangeClick(Self); // will set captions, sign state for Changes
1161        lstNotesClick(Self);  // will make pnlWrite visible
1162        if timAutoSave.Interval <> 0 then timAutoSave.Enabled := True;
1163        memNewNote.SetFocus;
1164      end else
1165      begin
1166        // if note creation failed or failed to get note lock (both unlikely), unlock consult
1167        with FEditNote do if (PkgIEN > 0) and (PkgPtr = PKG_CONSULTS)  then UnlockConsultRequest(0, PkgIEN);
1168        InfoBox(CreatedNote.ErrorText, TX_CREATE_ERR, MB_OK);
1169        HaveRequired := False;
1170      end; {if CreatedNote.IEN}
1171    end; {if HaveRequired}
1172    if not HaveRequired then ClearEditControls;
1173  end;
1174  
1175  procedure TfrmNotes.LoadForEdit;
1176  { retrieves an existing note and places the data in the fields of pnlWrite }
1177  var
1178    tmpNode: TTreeNode;
1179    x: string;
1180  begin
1181    ClearEditControls;
1182    if not LockConsultRequestAndNote(lstNotes.ItemIEN) then Exit;
1183    EditingIndex := lstNotes.ItemIndex;
1184    Changes.Add(CH_DOC, lstNotes.ItemID, GetTitleText(EditingIndex), '', CH_SIGN_YES);
1185    GetNoteForEdit(FEditNote, lstNotes.ItemIEN);
1186    memNewNote.Lines.Assign(FEditNote.Lines);
1187    FChanged := False;
1188    if FEditNote.Title = TYP_ADDENDUM then
1189    begin
1190      FEditNote.DocType := TYP_ADDENDUM;
1191      FEditNote.TitleName := Piece(lstNotes.Items[lstNotes.ItemIndex], U, 2);
1192      if Copy(FEditNote.TitleName,1,1) = '+' then FEditNote.TitleName := Copy(FEditNote.TitleName, 3, 199);
1193      if CompareText(Copy(FEditNote.TitleName, 1, 8), 'Addendum') <> 0
1194        then FEditNote.TitleName := FEditNote.TitleName + 'Addendum to ';
1195    end;
1196  
1197    uChanging := True;
1198    tvNotes.Items.BeginUpdate;
1199  
1200    tmpNode := tvNotes.FindPieceNode('EDIT', 1, U, nil);
1201    if tmpNode = nil then
1202      begin
1203        tmpNode := tvNotes.Items.AddObjectFirst(tvNotes.Items.GetFirstNode, 'Note being edited',
1204                                                MakeNoteTreeObject('EDIT^Note being edited^^^^^^^^^^^%^0'));
1205        TORTreeNode(tmpNode).StringData := 'EDIT^Note being edited^^^^^^^^^^^%^0';
1206      end
1207    else
1208      tmpNode.DeleteChildren;
1209    x := lstNotes.Items[lstNotes.ItemIndex];
1210    tmpNode.ImageIndex := IMG_TOP_LEVEL;
1211    tmpNode := tvNotes.Items.AddChildObjectFirst(tmpNode, MakeNoteDisplayText(x), MakeNoteTreeObject(x));
1212    TORTreeNode(tmpNode).StringData := x;
1213    if CompareText(Copy(FEditNote.TitleName, 1, 8), 'Addendum') <> 0 then
1214      tmpNode.ImageIndex := IMG_SINGLE
1215    else
1216      tmpNode.ImageIndex := IMG_ADDENDUM;
1217    tmpNode.SelectedIndex := tmpNode.ImageIndex;
1218    tvNotes.Selected := tmpNode;
1219    tvNotes.Items.EndUpdate;
1220    uChanging := False;
1221  
1222    uPCEEdit.NoteDateTime := MakeFMDateTime(Piece(lstNotes.Items[lstNotes.ItemIndex], U, 3));
1223    uPCEEdit.PCEForNote(lstNotes.ItemIEN, uPCEShow);
1224    FEditNote.NeedCPT := uPCEEdit.CPTRequired;
1225    txtSubject.Text := FEditNote.Subject;
1226    SetSubjectVisible(AskSubjectForNotes);
1227    cmdChangeClick(Self); // will set captions, sign state for Changes
1228    lstNotesClick(Self);  // will make pnlWrite visible
1229    if timAutoSave.Interval <> 0 then timAutoSave.Enabled := True;
1230    memNewNote.SetFocus;
1231  end;
1232  
1233  procedure TfrmNotes.SaveEditedNote(var Saved: Boolean);
1234  { validates fields and sends the updated note to the server }
1235  var
1236    UpdatedNote: TCreatedDoc;
1237    x: string;
1238  begin
1239    Saved := False;
1240    if (memNewNote.GetTextLen = 0) or (not ContainsVisibleChar(memNewNote.Text)) then
1241    begin
1242      lstNotes.ItemIndex := EditingIndex;
1243      x := lstNotes.ItemID;
1244      uChanging := True;
1245      tvNotes.Selected := tvNotes.FindPieceNode(x, 1, U, tvNotes.Items.GetFirstNode);
1246      uChanging := False;
1247      tvNotesChange(Self, tvNotes.Selected);
1248      if FSilent or
1249         ((not FSilent) and
1250        (InfoBox(GetTitleText(EditingIndex) + TX_EMPTY_NOTE, TC_EMPTY_NOTE, MB_YESNO) = IDYES))
1251      then
1252        begin
1253          FConfirmed := True;
1254          mnuActDeleteClick(Self);
1255          Saved := True;
1256          FDeleted := True;
1257        end
1258      else
1259        FConfirmed := False;
1260      Exit;
1261    end;
1262    //ExpandTabsFilter(memNewNote.Lines, TAB_STOP_CHARS);
1263    FEditNote.Lines    := memNewNote.Lines;
1264    //FEditNote.Lines:= SetLinesTo74ForSave(memNewNote.Lines, Self);
1265    FEditNote.Subject  := txtSubject.Text;
1266    FEditNote.NeedCPT  := uPCEEdit.CPTRequired;
1267    timAutoSave.Enabled := False;
1268    try
1269      PutEditedNote(UpdatedNote, FEditNote, lstNotes.GetIEN(EditingIndex));
1270    finally
1271      timAutoSave.Enabled := True;
1272    end;
1273    // there's no unlocking here since the note is still in Changes after a save
1274    if UpdatedNote.IEN > 0 then
1275    begin
1276      if lstNotes.ItemIndex = EditingIndex then
1277      begin
1278        EditingIndex := -1;
1279        lstNotesClick(Self);
1280      end;
1281      EditingIndex := -1; // make sure EditingIndex reset even if not viewing edited note
1282      Saved := True;
1283      FNewIDChild := False;
1284      FChanged := False;
1285    end else
1286    begin
1287      if not FSilent then
1288        InfoBox(TX_SAVE_ERROR1 + UpdatedNote.ErrorText + TX_SAVE_ERROR2, TC_SAVE_ERROR, MB_OK or MB_ICONWARNING);
1289    end;
1290  end;
1291  
1292  procedure TfrmNotes.SaveCurrentNote(var Saved: Boolean);
1293  { called whenever a note should be saved - uses IEN to call appropriate save logic }
1294  begin
1295    if EditingIndex < 0 then Exit;
1296    SaveEditedNote(Saved);
1297  end;
1298  
1299  { Form events ------------------------------------------------------------------------------ }
1300  
1301  procedure TfrmNotes.FormCreate(Sender: TObject);
1302  begin
1303    inherited;
1304    PageID := CT_NOTES;
1305    EditingIndex := -1;
1306    FEditNote.LastCosigner := 0;
1307    FEditNote.LastCosignerName := '';
1308    FLastNoteID := '';
1309    frmDrawers := TfrmDrawers.CreateDrawers(Self, pnlDrawers, [],[]);
1310    frmDrawers.Align := alBottom;
1311    frmDrawers.RichEditControl := memNewNote;
1312    frmDrawers.NewNoteButton := cmdNewNote;
1313    frmDrawers.Splitter := splDrawers;
1314    frmDrawers.DefTempPiece := 1;
1315    FImageFlag := TBitmap.Create;
1316    FDocList := TStringList.Create;
1317  end;
1318  
1319  procedure TfrmNotes.pnlRightResize(Sender: TObject);
1320  { memNote (TRichEdit) doesn't repaint appropriately unless it's parent panel is refreshed }
1321  begin
1322    inherited;
1323    pnlRight.Refresh;
1324    memNote.Repaint;
1325  end;
1326  
1327  procedure TfrmNotes.pnlWriteResize(Sender: TObject);
1328  const
1329    LEFT_MARGIN = 4;
1330  begin
1331    inherited;
1332    LimitEditWidth(memNewNote, MAX_PROGRESSNOTE_WIDTH - 1);
1333  
1334    //CQ7012 Added test for nil
1335    if memNewNote <> nil then
1336       memNewNote.Constraints.MinWidth := TextWidthByFont(memNewNote.Font.Handle, StringOfChar('X', MAX_PROGRESSNOTE_WIDTH)) + (LEFT_MARGIN * 2) + ScrollBarWidth;
1337    //CQ7012 Added test for nil
1338     if (Self <> nil) and (pnlLeft <> nil) and (pnlWrite <> nil) and (sptHorz <> nil) then
1339       pnlLeft.Width := self.ClientWidth - pnlWrite.Width - sptHorz.Width;
1340    UpdateFormForInput;
1341  end;
1342  
1343  { Left panel (selector) events ------------------------------------------------------------- }
1344  
1345  procedure TfrmNotes.lstNotesClick(Sender: TObject);
1346  { loads the text for the selected note or displays the editing panel for the selected note }
1347  var
1348    x: string;
1349  begin
1350    inherited;
1351    with lstNotes do if ItemIndex = -1 then Exit
1352    else if ItemIndex = EditingIndex then
1353    begin
1354      pnlWrite.Visible := True;
1355      pnlRead.Visible := False;
1356      mnuViewDetail.Enabled    := False;
1357      if (FEditNote.IDParent <> 0) and (not FNewIDChild) then
1358        mnuActChange.Enabled     := False
1359      else
1360        mnuActChange.Enabled     := True;
1361      mnuActLoadBoiler.Enabled := True;
1362      UpdateReminderFinish;
1363      UpdateFormForInput;
1364    end else
1365    begin
1366      StatusText('Retrieving selected progress note...');
1367      Screen.Cursor := crHourGlass;
1368      pnlRead.Visible := True;
1369      pnlWrite.Visible := False;
1370      UpdateReminderFinish;
1371      lblTitle.Caption := Piece(Piece(Items[ItemIndex], U, 8), ';', 1) + #9 + Piece(Items[ItemIndex], U, 2) + ', ' +
1372                          Piece(Items[ItemIndex], U, 6) + ', ' + Piece(Piece(Items[ItemIndex], U, 5), ';', 2) +
1373                          '  (' + FormatFMDateTime('mmm dd,yy@hh:nn', MakeFMDateTime(Piece(Items[ItemIndex], U, 3)))
1374                          + ')';
1375      lvNotes.Caption := lblTitle.Caption;
1376      LoadDocumentText(memNote.Lines, ItemIEN);
1377      memNote.SelStart := 0;
1378      mnuViewDetail.Enabled    := True;
1379      mnuViewDetail.Checked    := False;
1380      mnuActChange.Enabled     := False;
1381      mnuActLoadBoiler.Enabled := False;
1382      Screen.Cursor := crDefault;
1383      StatusText('');
1384    end;
1385    if(assigned(frmReminderTree)) then
1386      frmReminderTree.EnableActions;
1387    DisplayPCE;
1388    pnlRight.Refresh;
1389    memNewNote.Repaint;
1390    memNote.Repaint;
1391    x := 'TIU^' + lstNotes.ItemID;
1392    SetPiece(x, U, 10, Piece(lstNotes.Items[lstNotes.ItemIndex], U, 11));
1393    NotifyOtherApps(NAE_REPORT, x);
1394  end;
1395  
1396  procedure TfrmNotes.cmdNewNoteClick(Sender: TObject);
1397  { maps 'New Note' button to the New Progress Note menu item }
1398  begin
1399    inherited;
1400    mnuActNewClick(Self);
1401  end;
1402  
1403  procedure TfrmNotes.cmdPCEClick(Sender: TObject);
1404  var
1405    Refresh: boolean;
1406    ActionSts: TActionRec;
1407    AnIEN: integer;
1408    PCEObj, tmpPCEEdit: TPCEData;
1409  
1410    procedure UpdateEncounterInfo;
1411    begin
1412      if not FEditingNotePCEObj then
1413      begin
1414        PCEObj := nil;
1415        AnIEN := lstNotes.ItemIEN;
1416        if (AnIEN <> 0) and (memNote.Lines.Count > 0) then
1417        begin
1418          ActOnDocument(ActionSts, AnIEN, 'VIEW');
1419          if ActionSts.Success then
1420          begin
1421            uPCEShow.CopyPCEData(uPCEEdit);
1422            PCEObj := uPCEEdit;
1423          end;
1424        end;
1425        Refresh := EditPCEData(PCEObj);
1426      end
1427      else
1428      begin
1429        UpdatePCE(uPCEEdit);
1430        Refresh := TRUE;
1431      end;
1432      if Refresh and (not frmFrame.Closing) then
1433        DisplayPCE;
1434    end;
1435  
1436  begin
1437    inherited;
1438    cmdPCE.Enabled := FALSE;
1439    if lstNotes.ItemIndex <> EditingIndex then
1440      // save uPCEEdit for note being edited, before updating current note's encounter, then restore  (RV - TAM-0801-31056)
1441      begin
1442        tmpPCEEdit := TPCEData.Create;
1443        try
1444          uPCEEdit.CopyPCEData(tmpPCEEdit);
1445          UpdateEncounterInfo;
1446          tmpPCEEdit.CopyPCEData(uPCEEdit);
1447        finally
1448          tmpPCEEdit.Free;
1449        end;
1450      end
1451    else
1452      // no other note being edited, so just proceed as before.
1453      UpdateEncounterInfo;
1454    if cmdPCE <> nil then
1455      cmdPCE.Enabled := TRUE
1456  end;
1457  
1458  { Right panel (editor) events -------------------------------------------------------------- }
1459  
1460  procedure TfrmNotes.mnuActChangeClick(Sender: TObject);
1461  begin
1462    inherited;
1463    if (FEditingIndex < 0) or (lstNotes.ItemIndex <> FEditingIndex) then Exit;
1464    cmdChangeClick(Sender);
1465  end;
1466  
1467  procedure TfrmNotes.mnuActLoadBoilerClick(Sender: TObject);
1468  var
1469    NoteEmpty: Boolean;
1470    BoilerText: TStringList;
1471    DocInfo: string;
1472  
1473    procedure AssignBoilerText;
1474    begin
1475      ExecuteTemplateOrBoilerPlate(BoilerText, FEditNote.Title, ltTitle, Self, 'Title: ' + FEditNote.TitleName, DocInfo);
1476      QuickCopyWith508Msg(BoilerText, memNewNote);
1477      UpdateNoteAuthor(DocInfo);
1478      FChanged := False;
1479    end;
1480  
1481  begin
1482    inherited;
1483    if (FEditingIndex < 0) or (lstNotes.ItemIndex <> FEditingIndex) then Exit;
1484    BoilerText := TStringList.Create;
1485    try
1486      NoteEmpty := memNewNote.Text = '';
1487      LoadBoilerPlate(BoilerText, FEditNote.Title);
1488      if (BoilerText.Text <> '') or
1489         assigned(GetLinkedTemplate(IntToStr(FEditNote.Title), ltTitle)) then
1490      begin
1491        DocInfo := MakeXMLParamTIU(IntToStr(lstNotes.ItemIEN), FEditNote);
1492        if NoteEmpty then AssignBoilerText else
1493        begin
1494          case QueryBoilerPlate(BoilerText) of
1495          0:  { do nothing } ;                         // ignore
1496          1: begin
1497               ExecuteTemplateOrBoilerPlate(BoilerText, FEditNote.Title, ltTitle, Self, 'Title: ' + FEditNote.TitleName, DocInfo);
1498               QuickAddWith508Msg(BoilerText, memNewNote);  // append
1499               UpdateNoteAuthor(DocInfo);
1500             end;
1501          2: AssignBoilerText;                         // replace
1502          end;
1503        end;
1504      end else
1505      begin
1506        if Sender = mnuActLoadBoiler
1507          then InfoBox(TX_NO_BOIL, TC_NO_BOIL, MB_OK)
1508          else
1509          begin
1510            if not NoteEmpty then
1511  //            if not FChanged and (InfoBox(TX_BLR_CLEAR, TC_BLR_CLEAR, MB_YESNO) = ID_YES)
1512              if (InfoBox(TX_BLR_CLEAR, TC_BLR_CLEAR,
1513                          MB_ICONQUESTION or MB_YESNO or MB_DEFBUTTON2) = ID_YES)
1514                then memNewNote.Lines.Clear;
1515          end;
1516      end; {if BoilerText.Text <> ''}
1517    finally
1518      BoilerText.Free;
1519    end;
1520  end;
1521  
1522  procedure TfrmNotes.cmdChangeClick(Sender: TObject);
1523  var
1524    LastTitle, LastConsult: Integer;
1525    OKPressed, IsIDChild: Boolean;
1526    x: string;
1527    DisAssoText : String;
1528  begin
1529    inherited;
1530    IsIDChild := uIDNotesActive and (FEditNote.IDParent > 0);
1531    LastTitle   := FEditNote.Title;
1532    FEditNote.IsNewNote := False;
1533    DisAssoText := '';
1534    if (FEditNote.PkgPtr = PKG_CONSULTS) then
1535      DisAssoText := 'Consults';
1536    if (FEditNote.PkgPtr = PKG_PRF) then
1537      DisAssoText := 'Patient Record Flags';
1538    if (DisAssoText <> '') and (Sender <> Self) then
1539      if InfoBox('If this title is changed, Any '+DisAssoText+' will be disassociated'+
1540                 ' with this note',
1541                 'Disassociate '+DisAssoText+'?',MB_OKCANCEL) = IDCANCEL	 then
1542        exit;
1543    if FEditNote.PkgPtr = PKG_CONSULTS then LastConsult := FEditNote.PkgIEN else LastConsult := 0;;
1544    if Sender <> Self then OKPressed := ExecuteNoteProperties(FEditNote, CT_NOTES, IsIDChild, FNewIDChild, '', 0)
1545      else OKPressed := True;
1546    if not OKPressed then Exit;
1547    // update display fields & uPCEEdit
1548    lblNewTitle.Caption := ' ' + FEditNote.TitleName + ' ';
1549    if (FEditNote.Addend > 0) and (CompareText(Copy(lblNewTitle.Caption, 2, 8), 'Addendum') <> 0)
1550      then lblNewTitle.Caption := ' Addendum to:' + lblNewTitle.Caption;
1551    with lblNewTitle do bvlNewTitle.SetBounds(Left - 1, Top - 1, Width + 2, Height + 2);
1552    lblRefDate.Caption := FormatFMDateTime('mmm dd,yyyy@hh:nn', FEditNote.DateTime);
1553    lblAuthor.Caption  := FEditNote.AuthorName;
1554    if uPCEEdit.Inpatient then x := 'Adm: ' else x := 'Vst: ';
1555    x := x + FormatFMDateTime('mm/dd/yy', FEditNote.VisitDate) + '  ' + FEditNote.LocationName;
1556    lblVisit.Caption   := x;
1557    if Length(FEditNote.CosignerName) > 0
1558      then lblCosigner.Caption := 'Expected Cosigner: ' + FEditNote.CosignerName
1559      else lblCosigner.Caption := '';
1560    uPCEEdit.NoteTitle  := FEditNote.Title;
1561    // modify signature requirements if author or cosigner changed
1562    if (User.DUZ <> FEditNote.Author) and (User.DUZ <> FEditNote.Cosigner)
1563      then Changes.ReplaceSignState(CH_DOC, lstNotes.ItemID, CH_SIGN_NA)
1564      else Changes.ReplaceSignState(CH_DOC, lstNotes.ItemID, CH_SIGN_YES);
1565    x := lstNotes.Items[EditingIndex];
1566    SetPiece(x, U, 2, lblNewTitle.Caption);
1567    SetPiece(x, U, 3, FloatToStr(FEditNote.DateTime));
1568    tvNotes.Selected.Text := MakeNoteDisplayText(x);
1569    TORTreeNode(tvNotes.Selected).StringData := x;
1570    lstNotes.Items[EditingIndex] := x;
1571    Changes.ReplaceText(CH_DOC, lstNotes.ItemID, GetTitleText(EditingIndex));
1572    with FEditNote do
1573    begin
1574    if (PkgPtr = PKG_CONSULTS) and (LastConsult <> PkgIEN) then
1575    begin
1576      // try to lock the new consult, reset to previous if unable
1577      if (PkgIEN > 0) and not LockConsultRequest(PkgIEN) then
1578      begin
1579        Infobox(TX_NO_ORD_CHG, TC_NO_ORD_CHG, MB_OK);
1580        PkgIEN := LastConsult;
1581      end else
1582      begin
1583        // unlock the previous consult
1584        if LastConsult > 0 then UnlockOrderIfAble(GetConsultOrderIEN(LastConsult));
1585        if PkgIEN = 0 then FOrderID := '';
1586      end;
1587    end;
1588    //Link Note to PRF Action
1589    if PRF_IEN <> 0 then
1590      if sCallV('TIU LINK TO FLAG', [lstNotes.ItemIEN,PRF_IEN,ActionIEN,Patient.DFN]) = '0' then
1591        ShowMsg('TIU LINK TO FLAG: FAILED');
1592    end;
1593  
1594    if LastTitle <> FEditNote.Title then mnuActLoadBoilerClick(Self);
1595  end;
1596  
1597  procedure TfrmNotes.memNewNoteChange(Sender: TObject);
1598  begin
1599    inherited;
1600    FChanged := True;
1601  end;
1602  
1603  procedure TfrmNotes.pnlFieldsResize(Sender: TObject);
1604  { center the reference date on the panel }
1605  begin
1606    inherited;
1607    lblRefDate.Left := (pnlFields.Width - lblRefDate.Width) div 2;
1608    if lblRefDate.Left < (lblNewTitle.Left + lblNewTitle.Width + 6)
1609      then lblRefDate.Left := (lblNewTitle.Left + lblNewTitle.Width);
1610    UpdateFormForInput;
1611  end;
1612  
1613  procedure TfrmNotes.DoAutoSave(Suppress: integer = 1);
1614  var
1615    ErrMsg: string;
1616  begin
1617    if fFrame.frmFrame.DLLActive = true then Exit;
1618    if (EditingIndex > -1) and FChanged then
1619    begin
1620      StatusText('Autosaving note...');
1621      //PutTextOnly(ErrMsg, memNewNote.Lines, lstNotes.GetIEN(EditingIndex));
1622      timAutoSave.Enabled := False;
1623      try
1624        SetText(ErrMsg, memNewNote.Lines, lstNotes.GetIEN(EditingIndex), Suppress);
1625      finally
1626        timAutoSave.Enabled := True;
1627      end;
1628      FChanged := False;
1629      StatusText('');
1630    end;
1631    if ErrMsg <> '' then
1632      InfoBox(TX_SAVE_ERROR1 + ErrMsg + TX_SAVE_ERROR2, TC_SAVE_ERROR, MB_OK or MB_ICONWARNING);
1633    //Assert(ErrMsg = '', 'AutoSave: ' + ErrMsg);
1634  end;
1635  
1636  procedure TfrmNotes.timAutoSaveTimer(Sender: TObject);
1637  begin
1638    inherited;
1639    DoAutoSave;
1640  end;
1641  
1642  { View menu events ------------------------------------------------------------------------- }
1643  
1644  procedure TfrmNotes.mnuViewClick(Sender: TObject);
1645  { changes the list of notes available for viewing }
1646  var
1647    AuthCtxt: TAuthorContext;
1648    SearchCtxt: TSearchContext; // Text Search CQ: HDS00002856
1649    DateRange: TNoteDateRange;
1650    Saved: Boolean;
1651  begin
1652    inherited;
1653    // save note at EditingIndex?
1654    if EditingIndex <> -1 then
1655    begin
1656      SaveCurrentNote(Saved);
1657      if not Saved then Exit;
1658    end;
1659    FLastNoteID := lstNotes.ItemID;
1660    mnuViewDetail.Checked := False;
1661    StatusText('Retrieving progress note list...');
1662    if Sender is TMenuItem then ViewContext := TMenuItem(Sender).Tag
1663      else if FCurrentContext.Status <> '' then ViewContext := NC_CUSTOM
1664      else ViewContext := NC_RECENT;
1665    case ViewContext of
1666    NC_RECENT:     begin
1667                     FillChar(FCurrentContext, SizeOf(FCurrentContext), 0);
1668                     lblNotes.Caption := 'Last ' + IntToStr(ReturnMaxNotes) + ' Notes';
1669                     FCurrentContext.Status := IntToStr(ViewContext);
1670                     FCurrentContext.MaxDocs := ReturnMaxNotes;
1671                     LoadNotes;
1672                   end;
1673    NC_ALL:        begin
1674                     FillChar(FCurrentContext, SizeOf(FCurrentContext), 0);
1675                     lblNotes.Caption := 'All Signed Notes';
1676                     FCurrentContext.Status := IntToStr(ViewContext);
1677                     LoadNotes;
1678                   end;
1679    NC_UNSIGNED:   begin
1680                     FillChar(FCurrentContext, SizeOf(FCurrentContext), 0);
1681                     lblNotes.Caption := 'Unsigned Notes';
1682                     FCurrentContext.Status := IntToStr(ViewContext);
1683                     LoadNotes;
1684                   end;
1685    // Text Search CQ: HDS00002856 --------------------
1686    NC_SEARCHTEXT: begin;
1687                     SearchTextStopFlag := False;
1688                     SelectSearchText(Font.Size, FCurrentContext.SearchString, SearchCtxt, StringReplace(TMenuItem(Sender).Caption, '&', '', [rfReplaceAll]) );
1689                     with SearchCtxt do if Changed then
1690                     begin
1691                       //FCurrentContext.Status := IntToStr(ViewContext);
1692                       frmSearchStop.Show;
1693                       lblNotes.Caption := 'Search: '+ SearchString;
1694                       frmSearchStop.lblSearchStatus.Caption := lblNotes.Caption;
1695                       FCurrentContext.SearchString := SearchString;
1696                       LoadNotes;
1697                     end;
1698                     // Only do LoadNotes if something changed 
1699                   end;
1700    // Text Search CQ: HDS00002856 --------------------
1701    NC_UNCOSIGNED: begin
1702                     FillChar(FCurrentContext, SizeOf(FCurrentContext), 0);
1703                     lblNotes.Caption := 'Uncosigned Notes';
1704                     FCurrentContext.Status := IntToStr(ViewContext);
1705                     LoadNotes;
1706                   end;
1707    NC_BY_AUTHOR:  begin
1708                     SelectAuthor(Font.Size, FCurrentContext, AuthCtxt);
1709                     with AuthCtxt do if Changed then
1710                     begin
1711                       FillChar(FCurrentContext, SizeOf(FCurrentContext), 0);
1712                       lblNotes.Caption := AuthorName + ': Signed Notes';
1713                       FCurrentContext.Status := IntToStr(NC_BY_AUTHOR);
1714                       FCurrentContext.Author := Author;
1715                       FCurrentContext.TreeAscending := Ascending;
1716                       LoadNotes;
1717                     end;
1718                   end;
1719    NC_BY_DATE:    begin
1720                     SelectNoteDateRange(Font.Size, FCurrentContext, DateRange);
1721                     with DateRange do if Changed then
1722                     begin
1723                       FillChar(FCurrentContext, SizeOf(FCurrentContext), 0);
1724                       lblNotes.Caption := FormatFMDateTime('mmm dd,yy', FMBeginDate) + ' to ' +
1725                                           FormatFMDateTime('mmm dd,yy', FMEndDate) + ': Signed Notes';
1726                       FCurrentContext.BeginDate     := BeginDate;
1727                       FCurrentContext.EndDate       := EndDate;
1728                       FCurrentContext.FMBeginDate   := FMBeginDate;
1729                       FCurrentContext.FMEndDate     := FMEndDate;
1730                       FCurrentContext.TreeAscending := Ascending;
1731                       FCurrentContext.Status        := IntToStr(NC_BY_DATE);
1732                       LoadNotes;
1733                     end;
1734                   end;
1735    NC_CUSTOM:     begin
1736                     if Sender is TMenuItem then
1737                       begin
1738                         SelectTIUView(Font.Size, True, FCurrentContext, uTIUContext);
1739                         //lblNotes.Caption := 'Custom List';
1740                       end;
1741                     with uTIUContext do if Changed then
1742                     begin
1743                       //if not (Sender is TMenuItem) then lblNotes.Caption := 'Default List';
1744                       //if MaxDocs = 0 then MaxDocs   := ReturnMaxNotes;
1745                       FCurrentContext.BeginDate     := BeginDate;
1746                       FCurrentContext.EndDate       := EndDate;
1747                       FCurrentContext.FMBeginDate   := FMBeginDate;
1748                       FCurrentContext.FMEndDate     := FMEndDate;
1749                       FCurrentContext.Status        := Status;
1750                       FCurrentContext.Author        := Author;
1751                       FCurrentContext.MaxDocs       := MaxDocs;
1752                       FCurrentContext.ShowSubject   := ShowSubject;
1753                       // NEW PREFERENCES:
1754                       FCurrentContext.SortBy        := SortBy;
1755                       FCurrentContext.ListAscending := ListAscending;
1756                       FCurrentContext.GroupBy       := GroupBy;
1757                       FCurrentContext.TreeAscending := TreeAscending;
1758                       FCurrentContext.SearchField   := SearchField;
1759                       FCurrentContext.Keyword       := Keyword;
1760                       FCurrentContext.Filtered      := Filtered;
1761                       LoadNotes;
1762                     end;
1763                   end;
1764    end; {case}
1765    lblNotes.Caption := SetNoteTreeLabel(FCurrentContext);
1766    // Text Search CQ: HDS00002856 --------------------
1767    If FCurrentContext.SearchString <> '' then
1768      lblNotes.Caption := lblNotes.Caption+', containing "'+FCurrentContext.SearchString+'"';
1769    If SearchTextStopFlag = True then begin;
1770      lblNotes.Caption := 'Search for "'+FCurrentContext.SearchString+'" was stopped!';
1771    end;
1772    //Clear the search text. We are done searching
1773    FCurrentContext.SearchString := '';
1774    frmSearchStop.Hide;
1775    // Text Search CQ: HDS00002856 --------------------
1776    lblNotes.Caption := lblNotes.Caption + ' (Total: ' + NoteTotal + ')'; 
1777    lblNotes.hint := lblNotes.Caption;
1778    tvNotes.Caption := lblNotes.Caption;
1779    StatusText('');
1780  end;
1781  
1782  { Action menu events ----------------------------------------------------------------------- }
1783  
1784  function TfrmNotes.StartNewEdit(NewNoteType: integer): Boolean;
1785  { if currently editing a note, returns TRUE if the user wants to start a new one }
1786  var
1787    Saved: Boolean;
1788    Msg, CapMsg: string;
1789  begin
1790    FStarting := False;
1791    Result := True;
1792    cmdNewNote.Enabled := False;
1793    if EditingIndex > -1 then
1794    begin
1795      FStarting := True;
1796      case NewNoteType of
1797        NT_ACT_ADDENDUM:  begin
1798                            Msg := TX_NEW_SAVE1 + MakeNoteDisplayText(lstNotes.Items[EditingIndex]) + TX_NEW_SAVE3;
1799                            CapMsg := TC_NEW_SAVE3;
1800                          end;
1801        NT_ACT_EDIT_NOTE: begin
1802                            Msg := TX_NEW_SAVE1 + MakeNoteDisplayText(lstNotes.Items[EditingIndex]) + TX_NEW_SAVE4;
1803                            CapMsg := TC_NEW_SAVE4;
1804                          end;
1805        NT_ACT_ID_ENTRY:  begin
1806                            Msg := TX_NEW_SAVE1 + MakeNoteDisplayText(lstNotes.Items[EditingIndex]) + TX_NEW_SAVE5;
1807                            CapMsg := TC_NEW_SAVE5;
1808                          end;
1809      else
1810        begin
1811          Msg := TX_NEW_SAVE1 + MakeNoteDisplayText(lstNotes.Items[EditingIndex]) + TX_NEW_SAVE2;
1812          CapMsg := TC_NEW_SAVE2;
1813        end;
1814      end;
1815      if InfoBox(Msg, CapMsg, MB_YESNO) = IDNO then
1816      begin
1817        Result := False;
1818        FStarting := False;
1819      end
1820      else
1821        begin
1822          SaveCurrentNote(Saved);
1823          if not Saved then Result := False else LoadNotes;
1824          FStarting := False;
1825        end;
1826    end;
1827    cmdNewNote.Enabled := (Result = False) and (FStarting = False);
1828  end;
1829  
1830  procedure TfrmNotes.mnuActNewClick(Sender: TObject);
1831  const
1832    IS_ID_CHILD = False;
1833  { switches to current new note or creates a new note if none is being edited already }
1834  begin
1835    inherited;
1836    if not StartNewEdit(NT_ACT_NEW_NOTE) then Exit;
1837    //LoadNotes;
1838    // make sure a visit (time & location) is available before creating the note
1839    if Encounter.NeedVisit then
1840    begin
1841      UpdateVisit(Font.Size, DfltTIULocation);
1842      frmFrame.DisplayEncounterText;
1843    end;
1844    if Encounter.NeedVisit then
1845    begin
1846      InfoBox(TX_NEED_VISIT, TX_NO_VISIT, MB_OK or MB_ICONWARNING);
1847      ShowPCEButtons(False);
1848      Exit;
1849    end;
1850    InsertNewNote(IS_ID_CHILD, 0);
1851  end;
1852  
1853  procedure TfrmNotes.mnuActAddIDEntryClick(Sender: TObject);
1854  const
1855    IS_ID_CHILD = True;
1856  var
1857    AnIDParent: integer;
1858  { switches to current new note or creates a new note if none is being edited already }
1859  begin
1860    inherited;
1861    AnIDParent := lstNotes.ItemIEN;
1862    if not StartNewEdit(NT_ACT_ID_ENTRY) then Exit;
1863    //LoadNotes;
1864    with tvNotes do Selected := FindPieceNode(IntToStr(AnIDParent), U, Items.GetFirstNode);
1865    // make sure a visit (time & location) is available before creating the note
1866    if Encounter.NeedVisit then
1867    begin
1868      UpdateVisit(Font.Size, DfltTIULocation);
1869      frmFrame.DisplayEncounterText;
1870    end;
1871    if Encounter.NeedVisit then
1872    begin
1873      InfoBox(TX_NEED_VISIT, TX_NO_VISIT, MB_OK or MB_ICONWARNING);
1874      Exit;
1875    end;
1876    InsertNewNote(IS_ID_CHILD, AnIDParent);
1877  end;
1878  
1879  procedure TfrmNotes.mnuActAddendClick(Sender: TObject);
1880  { make an addendum to an existing note }
1881  var
1882    ActionSts: TActionRec;
1883    ANoteID: string;
1884  begin
1885    inherited;
1886    if lstNotes.ItemIEN <= 0 then Exit;
1887    ANoteID := lstNotes.ItemID;
1888    if not StartNewEdit(NT_ACT_ADDENDUM) then Exit;
1889    //LoadNotes;
1890    with tvNotes do Selected := FindPieceNode(ANoteID, 1, U, Items.GetFirstNode);
1891    if lstNotes.ItemIndex = EditingIndex then
1892    begin
1893      InfoBox(TX_ADDEND_NO, TX_ADDEND_MK, MB_OK);
1894      Exit;
1895    end;
1896    ActOnDocument(ActionSts, lstNotes.ItemIEN, 'MAKE ADDENDUM');
1897    if not ActionSts.Success then
1898    begin
1899      InfoBox(ActionSts.Reason, TX_IN_AUTH, MB_OK);
1900      Exit;
1901    end;
1902    with lstNotes do if TitleForNote(lstNotes.ItemIEN) = TYP_ADDENDUM then
1903    begin
1904      InfoBox(TX_ADDEND_AD, TX_ADDEND_MK, MB_OK);
1905      Exit;
1906    end;
1907    InsertAddendum;
1908  end;
1909  
1910  procedure TfrmNotes.mnuActDetachFromIDParentClick(Sender: TObject);
1911  var
1912    DocID, WhyNot: string;
1913    Saved: boolean;
1914    SavedDocID: string;
1915  begin
1916    if lstNotes.ItemIEN = 0 then exit;
1917    SavedDocID := lstNotes.ItemID;
1918    if EditingIndex <> -1 then
1919    begin
1920      SaveCurrentNote(Saved);
1921      if not Saved then Exit;
1922      LoadNotes;
1923      with tvNotes do Selected := FindPieceNode(SavedDocID, U, Items.GetFirstNode);
1924    end;
1925    if not CanBeAttached(PDocTreeObject(tvNotes.Selected.Data)^.DocID, WhyNot) then
1926      begin
1927        WhyNot := StringReplace(WhyNot, 'ATTACH', 'DETACH', [rfIgnoreCase]);
1928        WhyNot := StringReplace(WhyNot, 'to an ID', 'from an ID', [rfIgnoreCase]);
1929        InfoBox(WhyNot, TX_DETACH_FAILURE, MB_OK);
1930        Exit;
1931      end;
1932    if (InfoBox('DETACH:   ' + tvNotes.Selected.Text + CRLF +  CRLF +
1933                '  FROM:   ' + tvNotes.Selected.Parent.Text + CRLF + CRLF +
1934                'Are you sure?', TX_DETACH_CNF, MB_YESNO or MB_DEFBUTTON2 or MB_ICONQUESTION) <> IDYES)
1935        then Exit;
1936    DocID := PDocTreeObject(tvNotes.Selected.Data)^.DocID;
1937    SavedDocID := PDocTreeObject(tvNotes.Selected.Parent.Data)^.DocID;
1938    if DetachEntryFromParent(DocID, WhyNot) then
1939      begin
1940        LoadNotes;
1941        with tvNotes do Selected := FindPieceNode(SavedDocID, U, Items.GetFirstNode);
1942        if tvNotes.Selected <> nil then tvNotes.Selected.Expand(False);
1943      end
1944    else
1945      begin
1946        WhyNot := StringReplace(WhyNot, 'ATTACH', 'DETACH', [rfIgnoreCase]);
1947        WhyNot := StringReplace(WhyNot, 'to an ID', 'from an ID', [rfIgnoreCase]);
1948        InfoBox(WhyNot, TX_DETACH_FAILURE, MB_OK);
1949      end;
1950  end;
1951  
1952  procedure TfrmNotes.mnuActSignListClick(Sender: TObject);
1953  { add the note to the Encounter object, see mnuActSignClick - copied}
1954  const
1955    SIG_COSIGN = 'COSIGNATURE';
1956    SIG_SIGN   = 'SIGNATURE';
1957  var
1958    ActionType, SignTitle: string;
1959    ActionSts: TActionRec;
1960  begin
1961    inherited;
1962    if lstNotes.ItemIEN = 0 then Exit;
1963    if lstNotes.ItemIndex = EditingIndex then Exit;  // already in signature list
1964    if not NoteHasText(lstNotes.ItemIEN) then
1965      begin
1966        InfoBox(TX_EMPTY_NOTE1, TC_EMPTY_NOTE, MB_OK or MB_ICONERROR);
1967        Exit;
1968      end;
1969    if not LastSaveClean(lstNotes.ItemIEN) and
1970      (InfoBox(TX_ABSAVE, TC_ABSAVE, MB_YESNO or MB_DEFBUTTON2 or MB_ICONWARNING) <> IDYES) then Exit;
1971    if CosignDocument(lstNotes.ItemIEN) then
1972    begin
1973      SignTitle := TX_COSIGN;
1974      ActionType := SIG_COSIGN;
1975    end else
1976    begin
1977      SignTitle := TX_SIGN;
1978      ActionType := SIG_SIGN;
1979    end;
1980    ActOnDocument(ActionSts, lstNotes.ItemIEN, ActionType);
1981    if not ActionSts.Success then
1982    begin
1983      InfoBox(ActionSts.Reason, TX_IN_AUTH, MB_OK);
1984      Exit;
1985    end;
1986    LockConsultRequestAndNote(lstNotes.ItemIEN);
1987    with lstNotes do Changes.Add(CH_DOC, ItemID, GetTitleText(ItemIndex), '', CH_SIGN_YES);
1988  end;
1989  
1990  procedure TfrmNotes.RemovePCEFromChanges(IEN: Int64; AVisitStr: string = '');
1991  begin
1992    if IEN = NT_ADDENDUM then Exit;  // no PCE information entered for an addendum
1993    // do we need to call DeletePCE(AVisitStr), as was done with NT_NEW_NOTE (ien=-10)???
1994    if AVisitStr = '' then AVisitStr := VisitStrForNote(IEN);
1995    Changes.Remove(CH_PCE, 'V' + AVisitStr);
1996    Changes.Remove(CH_PCE, 'P' + AVisitStr);
1997    Changes.Remove(CH_PCE, 'D' + AVisitStr);
1998    Changes.Remove(CH_PCE, 'I' + AVisitStr);
1999    Changes.Remove(CH_PCE, 'S' + AVisitStr);
2000    Changes.Remove(CH_PCE, 'A' + AVisitStr);
2001    Changes.Remove(CH_PCE, 'H' + AVisitStr);
2002    Changes.Remove(CH_PCE, 'E' + AVisitStr);
2003    Changes.Remove(CH_PCE, 'T' + AVisitStr);
2004  end;
2005  
2006  procedure TfrmNotes.mnuActDeleteClick(Sender: TObject);
2007  { delete the selected progress note & remove from the Encounter object if necessary }
2008  var
2009    DeleteSts, ActionSts: TActionRec;
2010    SaveConsult, SavedDocIEN: Integer;
2011    ReasonForDelete, AVisitStr, SavedDocID, x: string;
2012    Saved: boolean;
2013  begin
2014    inherited;
2015    if lstNotes.ItemIEN = 0 then Exit;
2016    if assigned(frmRemDlg) then
2017      begin
2018         frmRemDlg.btnCancelClick(Self);
2019         if assigned(frmRemDlg) then exit;
2020      end;
2021    ActOnDocument(ActionSts, lstNotes.ItemIEN, 'DELETE RECORD');
2022    if ShowMsgOn(not ActionSts.Success, ActionSts.Reason, TX_IN_AUTH) then Exit;
2023    ReasonForDelete := SelectDeleteReason(lstNotes.ItemIEN);
2024    if ReasonForDelete = DR_CANCEL then Exit;
2025    // suppress prompt for deletion when called from SaveEditedNote (Sender = Self)
2026    if (Sender <> Self) and (InfoBox(MakeNoteDisplayText(lstNotes.Items[lstNotes.ItemIndex]) + TX_DEL_OK,
2027      TX_DEL_CNF, MB_YESNO or MB_DEFBUTTON2 or MB_ICONQUESTION) <> IDYES) then Exit;
2028    // do the appropriate locking
2029    if not LockConsultRequestAndNote(lstNotes.ItemIEN) then Exit;
2030    // retraction notification message
2031    if JustifyDocumentDelete(lstNotes.ItemIEN) then
2032       InfoBox(TX_RETRACT, TX_RETRACT_CAP, MB_OK);
2033    SavedDocID := lstNotes.ItemID;
2034    SavedDocIEN := lstNotes.ItemIEN;
2035    if (EditingIndex > -1) and (not FConfirmed) and (lstNotes.ItemIndex <> EditingIndex) and (memNewNote.GetTextLen > 0) then
2036      begin
2037        SaveCurrentNote(Saved);
2038        if not Saved then Exit;
2039      end;
2040    EditingIndex := -1;
2041    FConfirmed := False;
2042    (*  if Saved then
2043      begin
2044        EditingIndex := -1;
2045        mnuViewClick(Self);
2046        with tvNotes do Selected := FindPieceNode(SavedDocID, U, Items.GetFirstNode);
2047     end;*)
2048    // remove the note
2049    DeleteSts.Success := True;
2050    x := GetPackageRefForNote(SavedDocIEN);
2051    SaveConsult := StrToIntDef(Piece(x, ';', 1), 0);
2052    AVisitStr := VisitStrForNote(SavedDocIEN);
2053    RemovePCEFromChanges(SavedDocIEN, AVisitStr);
2054    if (SavedDocIEN > 0) and (lstNotes.ItemIEN = SavedDocIEN) then DeleteDocument(DeleteSts, SavedDocIEN, ReasonForDelete);
2055    if not Changes.Exist(CH_DOC, SavedDocID) then UnlockDocument(SavedDocIEN);
2056    Changes.Remove(CH_DOC, SavedDocID);  // this will unlock the document if in Changes
2057    UnlockConsultRequest(0, SaveConsult);     // note has been deleted, so 1st param = 0
2058    // reset the display now that the note is gone
2059    if DeleteSts.Success then
2060    begin
2061      DeletePCE(AVisitStr);  // removes PCE data if this was the only note pointing to it
2062      ClearEditControls;
2063      //ClearPtData;   WRONG - fixed in v15.10 - RV
2064      LoadNotes;
2065  (*    with tvNotes do Selected := FindPieceNode(SavedDocID, U, Items.GetFirstNode);
2066      if tvNotes.Selected <> nil then tvNotesChange(Self, tvNotes.Selected) else
2067      begin*)
2068        pnlWrite.Visible := False;
2069        pnlRead.Visible := True;
2070        UpdateReminderFinish;
2071        ShowPCEControls(False);
2072        frmDrawers.DisplayDrawers(TRUE, [odTemplates], [odTemplates]); //FALSE);
2073        ShowPCEButtons(FALSE);
2074      //end; {if ItemIndex}
2075    end {if DeleteSts}
2076    else InfoBox(DeleteSts.Reason, TX_DEL_ERR, MB_OK or MB_ICONWARNING);
2077  end;
2078  
2079  procedure TfrmNotes.mnuActEditClick(Sender: TObject);
2080  { load the selected progress note for editing }
2081  var
2082    ActionSts: TActionRec;
2083    ANoteID: string;
2084  begin
2085    inherited;
2086    if lstNotes.ItemIndex = EditingIndex then Exit;
2087    ANoteID := lstNotes.ItemID;
2088    if not StartNewEdit(NT_ACT_EDIT_NOTE) then Exit;
2089    //LoadNotes;
2090    with tvNotes do Selected := FindPieceNode(ANoteID, 1, U, Items.GetFirstNode);
2091    ActOnDocument(ActionSts, lstNotes.ItemIEN, 'EDIT RECORD');
2092    if not ActionSts.Success then
2093    begin
2094      InfoBox(ActionSts.Reason, TX_IN_AUTH, MB_OK);
2095      Exit;
2096    end;
2097    LoadForEdit;
2098  end;
2099  
2100  procedure TfrmNotes.mnuActSaveClick(Sender: TObject);
2101  { saves the note that is currently being edited }
2102  var
2103    Saved: Boolean;
2104    SavedDocID: string;
2105  begin
2106    inherited;
2107    if EditingIndex > -1 then
2108      begin
2109        SavedDocID := Piece(lstNotes.Items[EditingIndex], U, 1);
2110        FLastNoteID := SavedDocID;
2111        SaveCurrentNote(Saved);
2112        if Saved and (EditingIndex < 0) and (not FDeleted) then   
2113        //if Saved then
2114          begin
2115            LoadNotes;
2116            with tvNotes do Selected := FindPieceNode(SavedDocID, U, Items.GetFirstNode);
2117         end;
2118      end
2119    else InfoBox(TX_NO_NOTE, TX_SAVE_NOTE, MB_OK or MB_ICONWARNING);
2120  end;
2121  
2122  procedure TfrmNotes.mnuActSignClick(Sender: TObject);
2123  { sign the currently selected note, save first if necessary }
2124  const
2125    SIG_COSIGN = 'COSIGNATURE';
2126    SIG_SIGN   = 'SIGNATURE';
2127  var
2128    Saved, NoteUnlocked: Boolean;
2129    ActionType, ESCode, SignTitle: string;
2130    ActionSts, SignSts: TActionRec;
2131    OK: boolean;
2132    SavedDocID, tmpItem: string;
2133    EditingID: string;                                         //v22.12 - RV
2134    tmpNode: TTreeNode;
2135  begin
2136    inherited;
2137  (*  if lstNotes.ItemIndex = EditingIndex then                //v22.12 - RV
2138    begin                                                      //v22.12 - RV
2139      SaveCurrentNote(Saved);                                  //v22.12 - RV
2140      if (not Saved) or FDeleted then Exit;                    //v22.12 - RV
2141    end                                                        //v22.12 - RV
2142    else if EditingIndex > -1 then                             //v22.12 - RV
2143      tmpItem := lstNotes.Items[EditingIndex];                 //v22.12 - RV
2144    SavedDocID := lstNotes.ItemID;*)                           //v22.12 - RV
2145    SavedDocID := lstNotes.ItemID;                             //v22.12 - RV
2146    FLastNoteID := SavedDocID;                                 //v22.12 - RV
2147    if lstNotes.ItemIndex = EditingIndex then                  //v22.12 - RV
2148    begin                                                      //v22.12 - RV
2149      SaveCurrentNote(Saved);                                  //v22.12 - RV
2150      if (not Saved) or FDeleted then Exit;                    //v22.12 - RV
2151    end                                                        //v22.12 - RV
2152    else if EditingIndex > -1 then                             //v22.12 - RV
2153    begin                                                      //v22.12 - RV
2154      tmpItem := lstNotes.Items[EditingIndex];                 //v22.12 - RV
2155      EditingID := Piece(tmpItem, U, 1);                       //v22.12 - RV
2156    end;                                                       //v22.12 - RV
2157    if not NoteHasText(lstNotes.ItemIEN) then
2158      begin
2159        InfoBox(TX_EMPTY_NOTE1, TC_EMPTY_NOTE, MB_OK or MB_ICONERROR);
2160        Exit;
2161      end;
2162    if not LastSaveClean(lstNotes.ItemIEN) and
2163      (InfoBox(TX_ABSAVE, TC_ABSAVE, MB_YESNO or MB_DEFBUTTON2 or MB_ICONWARNING) <> IDYES) then Exit;
2164    if CosignDocument(lstNotes.ItemIEN) then
2165    begin
2166      SignTitle := TX_COSIGN;
2167      ActionType := SIG_COSIGN;
2168    end else
2169    begin
2170      SignTitle := TX_SIGN;
2171      ActionType := SIG_SIGN;
2172    end;
2173    if not LockConsultRequestAndNote(lstNotes.ItemIEN) then Exit;
2174    // no exits after things are locked
2175    NoteUnlocked := False;
2176    ActOnDocument(ActionSts, lstNotes.ItemIEN, ActionType);
2177    if ActionSts.Success then
2178    begin
2179      OK := IsOK2Sign(uPCEShow, lstNotes.ItemIEN);
2180      if frmFrame.Closing then exit;
2181      if(uPCEShow.Updated) then
2182      begin
2183        uPCEShow.CopyPCEData(uPCEEdit);
2184        uPCEShow.Updated := FALSE;
2185        lstNotesClick(Self);
2186      end;
2187      if not AuthorSignedDocument(lstNotes.ItemIEN) then
2188      begin
2189        if (InfoBox(TX_AUTH_SIGNED +
2190            GetTitleText(lstNotes.ItemIndex),TX_SIGN ,MB_YESNO)= ID_NO) then exit;
2191      end;
2192      if(OK) then
2193      begin
2194        with lstNotes do SignatureForItem(Font.Size, MakeNoteDisplayText(Items[ItemIndex]), SignTitle, ESCode);
2195        if Length(ESCode) > 0 then
2196        begin
2197          SignDocument(SignSts, lstNotes.ItemIEN, ESCode);
2198          RemovePCEFromChanges(lstNotes.ItemIEN);
2199          NoteUnlocked := Changes.Exist(CH_DOC, lstNotes.ItemID);
2200          Changes.Remove(CH_DOC, lstNotes.ItemID);  // this will unlock if in Changes
2201          if SignSts.Success then
2202          begin
2203            SendMessage(frmConsults.Handle, UM_NEWORDER, ORDER_SIGN, 0);      {*REV*}
2204            lstNotesClick(Self);
2205          end
2206          else InfoBox(SignSts.Reason, TX_SIGN_ERR, MB_OK);
2207        end  {if Length(ESCode)}
2208        else
2209          NoteUnlocked := Changes.Exist(CH_DOC, lstNotes.ItemID);
2210      end;
2211    end
2212    else InfoBox(ActionSts.Reason, TX_IN_AUTH, MB_OK);
2213    if not NoteUnlocked then UnlockDocument(lstNotes.ItemIEN);
2214    UnlockConsultRequest(lstNotes.ItemIEN);
2215    //SetViewContext(FCurrentContext);  //v22.12 - RV
2216    LoadNotes;                          //v22.12 - RV
2217    //if EditingIndex > -1 then         //v22.12 - RV
2218    if (EditingID <> '') then           //v22.12 - RV
2219      begin
2220        lstNotes.Items.Insert(0, tmpItem);
2221        tmpNode := tvNotes.Items.AddObjectFirst(tvNotes.Items.GetFirstNode, 'Note being edited',
2222                   MakeNoteTreeObject('EDIT^Note being edited^^^^^^^^^^^%^0'));
2223        TORTreeNode(tmpNode).StringData := 'EDIT^Note being edited^^^^^^^^^^^%^0';
2224        tmpNode.ImageIndex := IMG_TOP_LEVEL;
2225        tmpNode := tvNotes.Items.AddChildObjectFirst(tmpNode, MakeNoteDisplayText(tmpItem), MakeNoteTreeObject(tmpItem));
2226        TORTreeNode(tmpNode).StringData := tmpItem;
2227        SetTreeNodeImagesAndFormatting(TORTreeNode(tmpNode), FCurrentContext, CT_NOTES);
2228        EditingIndex := lstNotes.SelectByID(EditingID);                 //v22.12 - RV
2229      end;
2230    //with tvNotes do Selected := FindPieceNode(SavedDocID, U, Items.GetFirstNode);  //v22.12 - RV
2231    with tvNotes do                                                                  //v22.12 - RV
2232    begin                                                                            //v22.12 - RV
2233      Selected := FindPieceNode(FLastNoteID, U, Items.GetFirstNode);                 //v22.12 - RV
2234      if Selected <> nil then
2235        tvNotesChange(Self, Selected)                                 //v22.12 - RV
2236      else
2237        tvNotes.Selected := tvNotes.Items[0]; //first Node in treeview
2238    end;                                                                             //v22.12 - RV
2239  end;
2240  
2241  procedure TfrmNotes.SaveSignItem(const ItemID, ESCode: string);
2242  { saves and optionally signs a progress note or addendum }
2243  const
2244    SIG_COSIGN = 'COSIGNATURE';
2245    SIG_SIGN   = 'SIGNATURE';
2246  var
2247    AnIndex, IEN, i: Integer;
2248    Saved, ContinueSign: Boolean;  {*RAB* 8/26/99}
2249    ActionSts, SignSts: TActionRec;
2250    APCEObject: TPCEData;
2251    OK: boolean;
2252    ActionType, SignTitle: string;
2253  begin
2254    AnIndex := -1;
2255    IEN := StrToIntDef(ItemID, 0);
2256    if IEN = 0 then Exit;
2257    if frmFrame.TimedOut and (EditingIndex <> -1) then FSilent := True;
2258    with lstNotes do for i := 0 to Items.Count - 1 do if lstNotes.GetIEN(i) = IEN then
2259    begin
2260      AnIndex := i;
2261      break;
2262    end;
2263    if (AnIndex > -1) and (AnIndex = EditingIndex) then
2264    begin
2265      SaveCurrentNote(Saved);
2266      if not Saved then Exit;
2267      if FDeleted then
2268        begin
2269          FDeleted := False;
2270          Exit;
2271        end;
2272      AnIndex := lstNotes.SelectByIEN(IEN);
2273      //IEN := lstNotes.GetIEN(AnIndex);                    // saving will change IEN
2274    end;
2275    if Length(ESCode) > 0 then
2276    begin
2277      if CosignDocument(IEN) then
2278      begin
2279        SignTitle := TX_COSIGN;
2280        ActionType := SIG_COSIGN;
2281      end else
2282      begin
2283        SignTitle := TX_SIGN;
2284        ActionType := SIG_SIGN;
2285      end;
2286      ActOnDocument(ActionSts, IEN, ActionType);
2287      if not ActionSts.Success then
2288        begin
2289          InfoBox(ActionSts.Reason, TX_IN_AUTH, MB_OK);
2290          ContinueSign := False;
2291        end
2292      else if not NoteHasText(IEN) then
2293        begin
2294          InfoBox(TX_EMPTY_NOTE1, TC_EMPTY_NOTE, MB_OK or MB_ICONERROR);
2295          ContinueSign := False;
2296        end
2297      else if not LastSaveClean(IEN) and
2298        (InfoBox(TX_ABSAVE, TC_ABSAVE, MB_YESNO or MB_DEFBUTTON2 or MB_ICONWARNING) <> IDYES)
2299         then ContinueSign := False
2300      else ContinueSign := True;
2301      if ContinueSign then
2302      begin
2303        if (AnIndex >= 0) and (AnIndex = lstNotes.ItemIndex) then
2304          APCEObject := uPCEShow
2305        else
2306          APCEObject := nil;
2307        OK := IsOK2Sign(APCEObject, IEN);
2308        if frmFrame.Closing then exit;
2309        if(assigned(APCEObject)) and (uPCEShow.Updated) then
2310        begin
2311          uPCEShow.CopyPCEData(uPCEEdit);
2312          uPCEShow.Updated := FALSE;
2313          lstNotesClick(Self);
2314        end
2315        else
2316          uPCEEdit.Clear;
2317        if(OK) then
2318        begin
2319          //if ((not FSilent) and IsSurgeryTitle(TitleForNote(IEN))) then DisplayOpTop(IEN);
2320          SignDocument(SignSts, IEN, ESCode);
2321          if not SignSts.Success then InfoBox(SignSts.Reason, TX_SIGN_ERR, MB_OK);
2322        end; {if OK}
2323      end; {if ContinueSign}
2324    end; {if Length(ESCode)}
2325  
2326    UnlockConsultRequest(IEN);
2327    // GE 14926; added if (AnIndex> -1) to by pass LoadNotes when creating on narking Allerg Entered In error.
2328    if (AnIndex > -1) and (AnIndex = lstNotes.ItemIndex) and (not frmFrame.ContextChanging) then
2329      begin
2330        LoadNotes;
2331          with tvNotes do Selected := FindPieceNode(IntToStr(IEN), U, Items.GetFirstNode);
2332      end;
2333  end;
2334  
2335  procedure TfrmNotes.popNoteMemoPopup(Sender: TObject);
2336  begin
2337    inherited;
2338    if PopupComponent(Sender, popNoteMemo) is TCustomEdit
2339      then FEditCtrl := TCustomEdit(PopupComponent(Sender, popNoteMemo))
2340      else FEditCtrl := nil;
2341    if FEditCtrl <> nil then
2342    begin
2343      popNoteMemoCut.Enabled      := FEditCtrl.SelLength > 0;
2344      popNoteMemoCopy.Enabled     := popNoteMemoCut.Enabled;
2345      popNoteMemoPaste.Enabled    := (not TORExposedCustomEdit(FEditCtrl).ReadOnly) and
2346                                     Clipboard.HasFormat(CF_TEXT);
2347      popNoteMemoTemplate.Enabled := frmDrawers.CanEditTemplates and popNoteMemoCut.Enabled;
2348      popNoteMemoFind.Enabled := FEditCtrl.GetTextLen > 0;
2349    end else
2350    begin
2351      popNoteMemoCut.Enabled      := False;
2352      popNoteMemoCopy.Enabled     := False;
2353      popNoteMemoPaste.Enabled    := False;
2354      popNoteMemoTemplate.Enabled := False;
2355    end;
2356    if pnlWrite.Visible then
2357    begin
2358      popNoteMemoSpell.Enabled    := True;
2359      popNoteMemoGrammar.Enabled  := True;
2360      popNoteMemoReformat.Enabled := True;
2361      popNoteMemoReplace.Enabled  := (FEditCtrl.GetTextLen > 0);
2362      popNoteMemoPreview.Enabled  := (frmDrawers.TheOpenDrawer = odTemplates) and Assigned(frmDrawers.tvTemplates.Selected);
2363      popNoteMemoInsTemplate.Enabled  := (frmDrawers.TheOpenDrawer = odTemplates) and Assigned(frmDrawers.tvTemplates.Selected);
2364      popNoteMemoViewCslt.Enabled := (FEditNote.PkgPtr = PKG_CONSULTS); // if editing consult title
2365    end else
2366    begin
2367      popNoteMemoSpell.Enabled    := False;
2368      popNoteMemoGrammar.Enabled  := False;
2369      popNoteMemoReformat.Enabled := False;
2370      popNoteMemoReplace.Enabled  := False;
2371      popNoteMemoPreview.Enabled  := False;
2372      popNoteMemoInsTemplate.Enabled  := False;
2373      popNoteMemoViewCslt.Enabled := FALSE;
2374    end;
2375  end;
2376  
2377  procedure TfrmNotes.popNoteMemoCutClick(Sender: TObject);
2378  begin
2379    inherited;
2380    FEditCtrl.CutToClipboard;
2381  end;
2382  
2383  procedure TfrmNotes.popNoteMemoCopyClick(Sender: TObject);
2384  begin
2385    inherited;
2386    FEditCtrl.CopyToClipboard;
2387  end;
2388  
2389  procedure TfrmNotes.popNoteMemoPasteClick(Sender: TObject);
2390  begin
2391    inherited;
2392    Sendmessage(FEditCtrl.Handle,EM_PASTESPECIAL,CF_TEXT,0);
2393    frmNotes.pnlWriteResize(Self);
2394    //FEditCtrl.PasteFromClipboard;        // use AsText to prevent formatting
2395  end;
2396  
2397  procedure TfrmNotes.popNoteMemoReformatClick(Sender: TObject);
2398  begin
2399    inherited;
2400    if Screen.ActiveControl <> memNewNote then Exit;
2401    ReformatMemoParagraph(memNewNote);
2402  end;
2403  
2404  procedure TfrmNotes.popNoteMemoSaveContinueClick(Sender: TObject);
2405  begin
2406    inherited;
2407    FChanged := True;
2408    DoAutoSave;
2409  end;
2410  
2411  procedure TfrmNotes.popNoteMemoFindClick(Sender: TObject);
2412  //var
2413    //hData: THandle;  //CQ8300
2414    //pData: ^ClipboardData; //CQ8300
2415  begin
2416    inherited;
2417    SendMessage(TRichEdit(popNoteMemo.PopupComponent).Handle, WM_VSCROLL, SB_TOP, 0);
2418    with dlgFindText do
2419      begin
2420        Position := Point(Application.MainForm.Left + pnlLeft.Width, Application.MainForm.Top);
2421        FindText := '';
2422        Options := [frDown, frHideUpDown];
2423  {
2424        //CQ8300
2425        OpenClipboard(dlgFindText.Handle);
2426        hData := GetClipboardData(CF_TEXT);
2427        pData := GlobalLock(hData);
2428        FindText := pData^.Text;
2429        GlobalUnlock(hData);
2430        CloseClipboard;
2431        //end CQ8300
2432  }
2433        Execute;
2434      end;
2435  end;
2436  
2437  procedure TfrmNotes.dlgFindTextFind(Sender: TObject);
2438  begin
2439    dmodShared.FindRichEditText(dlgFindText, TRichEdit(popNoteMemo.PopupComponent));
2440  end;
2441  
2442  procedure TfrmNotes.popNoteMemoReplaceClick(Sender: TObject);
2443  begin
2444    inherited;
2445    SendMessage(TRichEdit(popNoteMemo.PopupComponent).Handle, WM_VSCROLL, SB_TOP, 0);
2446    with dlgReplaceText do
2447      begin
2448        Position := Point(Application.MainForm.Left + pnlLeft.Width, Application.MainForm.Top);
2449        FindText := '';
2450        ReplaceText := '';
2451        Options := [frDown, frHideUpDown];
2452        Execute;
2453      end;
2454  end;
2455  
2456  procedure TfrmNotes.dlgReplaceTextFind(Sender: TObject);
2457  begin
2458    inherited;
2459    dmodShared.FindRichEditText(dlgFindText, TRichEdit(popNoteMemo.PopupComponent));
2460  end;
2461  
2462  procedure TfrmNotes.dlgReplaceTextReplace(Sender: TObject);
2463  begin
2464    inherited;
2465    dmodShared.ReplaceRichEditText(dlgReplaceText, TRichEdit(popNoteMemo.PopupComponent));
2466  end;
2467  
2468  procedure TfrmNotes.popNoteMemoSpellClick(Sender: TObject);
2469  begin
2470    inherited;
2471    DoAutoSave(0);
2472    timAutoSave.Enabled := False;
2473    try
2474      SpellCheckForControl(memNewNote);
2475    finally
2476      FChanged := True;
2477      DoAutoSave(0);
2478      timAutoSave.Enabled := True;
2479    end;
2480  end;
2481  
2482  procedure TfrmNotes.popNoteMemoGrammarClick(Sender: TObject);
2483  begin
2484    inherited;
2485    DoAutoSave(0);
2486    timAutoSave.Enabled := False;
2487    try
2488      GrammarCheckForControl(memNewNote);
2489    finally
2490      FChanged := True;
2491      DoAutoSave(0);
2492      timAutoSave.Enabled := True;
2493    end;
2494  end;
2495  
2496  procedure TfrmNotes.popNoteMemoViewCsltClick(Sender: TObject);
2497  var
2498    CsltIEN: integer ;
2499    ConsultDetail: TStringList;
2500    x: string;
2501  begin
2502    inherited;
2503    if (Screen.ActiveControl <> memNewNote) or (FEditNote.PkgPtr <> PKG_CONSULTS) then Exit;
2504    CsltIEN := FEditNote.PkgIEN;
2505    x := FindConsult(CsltIEN);
2506    ConsultDetail := TStringList.Create;
2507    try
2508      LoadConsultDetail(ConsultDetail, CsltIEN) ;
2509      ReportBox(ConsultDetail, 'Consult Details: #' + IntToStr(CsltIEN) + ' - ' + Piece(x, U, 4), TRUE);
2510    finally
2511      ConsultDetail.Free;
2512    end;
2513  end;
2514  
2515  procedure TfrmNotes.mnuViewDetailClick(Sender: TObject);
2516  begin
2517    inherited;
2518    if lstNotes.ItemIEN <= 0 then Exit;
2519    mnuViewDetail.Checked := not mnuViewDetail.Checked;
2520    if mnuViewDetail.Checked then
2521      begin
2522        StatusText('Retrieving progress note details...');
2523        Screen.Cursor := crHourGlass;
2524        LoadDetailText(memNote.Lines, lstNotes.ItemIEN);
2525        Screen.Cursor := crDefault;
2526        StatusText('');
2527        memNote.SelStart := 0;
2528        memNote.Repaint;
2529      end
2530    else
2531      lstNotesClick(Self);
2532    SendMessage(memNote.Handle, WM_VSCROLL, SB_TOP, 0);
2533  end;
2534  
2535  procedure TfrmNotes.FormClose(Sender: TObject; var Action: TCloseAction);
2536  var
2537    Saved: Boolean;
2538    IEN: Int64;
2539    ErrMsg: string;
2540    DeleteSts: TActionRec;
2541  begin
2542    inherited;
2543    if frmFrame.TimedOut and (EditingIndex <> -1) then
2544    begin
2545      FSilent := True;
2546      if memNewNote.GetTextLen > 0 then SaveCurrentNote(Saved)
2547      else
2548      begin
2549        IEN := lstNotes.GetIEN(EditingIndex);
2550        if not LastSaveClean(IEN) then             // means note hasn't been committed yet
2551        begin
2552          LockDocument(IEN, ErrMsg);
2553          if ErrMsg = '' then
2554          begin
2555            DeleteDocument(DeleteSts, IEN, '');
2556            UnlockDocument(IEN);
2557          end; {if ErrMsg}
2558        end; {if not LastSaveClean}
2559      end; {else}
2560    end; {if frmFrame}
2561  end;
2562  
2563  procedure TfrmNotes.mnuActIdentifyAddlSignersClick(Sender: TObject);
2564  var
2565    Exclusions: TStrings;
2566    Saved, x, y: boolean;
2567    SignerList: TSignerList;
2568    ActionSts: TActionRec;
2569    SigAction: integer;
2570    SavedDocID: string;
2571    ARefDate: TFMDateTime;
2572  begin
2573    inherited;
2574    if lstNotes.ItemIEN = 0 then exit;
2575    SavedDocID := lstNotes.ItemID;
2576    if lstNotes.ItemIndex = EditingIndex then
2577      begin
2578        SaveCurrentNote(Saved);
2579        if not Saved then Exit;
2580        LoadNotes;
2581        with tvNotes do Selected := FindPieceNode(SavedDocID, U, Items.GetFirstNode);
2582      end;
2583    x := CanChangeCosigner(lstNotes.ItemIEN);
2584    ActOnDocument(ActionSts, lstNotes.ItemIEN, 'IDENTIFY SIGNERS');
2585    y := ActionSts.Success;
2586    if x and not y then
2587      begin
2588        if InfoBox(ActionSts.Reason + CRLF + CRLF +
2589                   'Would you like to change the cosigner?',
2590                   TX_IN_AUTH, MB_YESNO or MB_DEFBUTTON2 or MB_ICONQUESTION) = ID_YES then
2591      	SigAction := SG_COSIGNER
2592        else
2593  	Exit;
2594      end
2595    else if y and not x then SigAction := SG_ADDITIONAL
2596    else if x and y then SigAction := SG_BOTH
2597    else
2598      begin
2599        InfoBox(ActionSts.Reason, TX_IN_AUTH, MB_OK);
2600        Exit;
2601      end;
2602  
2603    if not LockConsultRequestAndNote(lstNotes.ItemIEN) then Exit;
2604    Exclusions := GetCurrentSigners(lstNotes.ItemIEN);
2605    ARefDate := StrToFloat(Piece(lstNotes.Items[lstNotes.ItemIndex], U, 3));
2606    SelectAdditionalSigners(Font.Size, lstNotes.ItemIEN, SigAction, Exclusions, SignerList, CT_NOTES, ARefDate);
2607    with SignerList do
2608      begin
2609        case SigAction of
2610          SG_ADDITIONAL:  if Changed and (Signers <> nil) and (Signers.Count > 0) then
2611                            UpdateAdditionalSigners(lstNotes.ItemIEN, Signers);
2612          SG_COSIGNER:    if Changed then ChangeCosigner(lstNotes.ItemIEN, Cosigner);
2613          SG_BOTH:        if Changed then
2614                            begin
2615                              if (Signers <> nil) and (Signers.Count > 0) then
2616                                UpdateAdditionalSigners(lstNotes.ItemIEN, Signers);
2617                              ChangeCosigner(lstNotes.ItemIEN, Cosigner);
2618                            end;
2619        end;
2620        lstNotesClick(Self);
2621      end;
2622    UnlockDocument(lstNotes.ItemIEN);
2623    UnlockConsultRequest(lstNotes.ItemIEN);
2624  end;
2625  
2626  procedure TfrmNotes.popNoteMemoAddlSignClick(Sender: TObject);
2627  begin
2628    inherited;
2629    mnuActIdentifyAddlSignersClick(Self);
2630  end;
2631  
2632  procedure TfrmNotes.ProcessNotifications;
2633  var
2634    x: string;
2635    Saved: boolean;
2636    tmpNode: TTreeNode;
2637    AnObject: PDocTreeObject;
2638  begin
2639    if EditingIndex <> -1 then
2640    begin
2641      SaveCurrentNote(Saved);
2642      if not Saved then Exit;
2643    end;
2644    lblNotes.Caption := Notifications.Text;
2645    tvNotes.Caption := Notifications.Text;
2646    EditingIndex := -1;
2647    lstNotes.Enabled := True ;
2648    pnlRead.BringToFront ;
2649    //  show ALL unsigned/uncosigned for a patient, not just the alerted one
2650    //  what about cosignature?  How to get correct list?  ORB FOLLOWUP TYPE = OR alerts only
2651    x := Notifications.AlertData;
2652    if StrToIntDef(Piece(x, U, 1), 0) = 0 then
2653      begin
2654        InfoBox(TX_NO_ALERT, TX_CAP_NO_ALERT, MB_OK);
2655        Exit;
2656      end;
2657    uChanging := True;
2658    tvNotes.Items.BeginUpdate;
2659    lstNotes.Clear;
2660    KillDocTreeObjects(tvNotes);
2661    tvNotes.Items.Clear;
2662    lstNotes.Items.Add(x);
2663    AnObject := MakeNoteTreeObject('ALERT^Alerted Note^^^^^^^^^^^%^0');
2664    tmpNode := tvNotes.Items.AddObjectFirst(tvNotes.Items.GetFirstNode, AnObject.NodeText, AnObject);
2665    TORTreeNode(tmpNode).StringData := 'ALERT^Alerted Note^^^^^^^^^^^%^0';
2666    tmpNode.ImageIndex := IMG_TOP_LEVEL;
2667    AnObject := MakeNoteTreeObject(x);
2668    tmpNode := tvNotes.Items.AddChildObjectFirst(tmpNode, AnObject.NodeText, AnObject);
2669    TORTreeNode(tmpNode).StringData := x;
2670    SetTreeNodeImagesAndFormatting(TORTreeNode(tmpNode), FCurrentContext, CT_NOTES);
2671    tvNotes.Selected := tmpNode;
2672    tvNotes.Items.EndUpdate;
2673    uChanging := False;
2674    tvNotesChange(Self, tvNotes.Selected);
2675    case Notifications.Followup of
2676      NF_NOTES_UNSIGNED_NOTE:   ;  //Automatically deleted by sig action!!!
2677    end;
2678    if Copy(Piece(Notifications.RecordID, U, 2), 1, 6) = 'TIUADD' then Notifications.Delete;
2679    if Copy(Piece(Notifications.RecordID, U, 2), 1, 5) = 'TIUID' then Notifications.Delete;
2680  end;
2681  
2682  procedure TfrmNotes.SetViewContext(AContext: TTIUContext);
2683  var
2684    Saved: boolean;
2685  begin
2686    if EditingIndex <> -1 then
2687    begin
2688      SaveCurrentNote(Saved);
2689      if not Saved then Exit;
2690    end;
2691    FCurrentContext := AContext;
2692    EditingIndex := -1;
2693    tvNotes.Enabled := True ;
2694    pnlRead.BringToFront ;
2695    if FCurrentContext.Status <> '' then with uTIUContext do
2696      begin
2697        BeginDate      := FCurrentContext.BeginDate;
2698        EndDate        := FCurrentContext.EndDate;
2699        FMBeginDate    := FCurrentContext.FMBeginDate;
2700        FMEndDate      := FCurrentContext.FMEndDate;
2701        Status         := FCurrentContext.Status;
2702        Author         := FCurrentContext.Author;
2703        MaxDocs        := FCurrentContext.MaxDocs;
2704        ShowSubject    := FCurrentContext.ShowSubject;
2705        GroupBy        := FCurrentContext.GroupBy;
2706        SortBy         := FCurrentContext.SortBy;
2707        ListAscending  := FCurrentContext.ListAscending;
2708        TreeAscending  := FCurrentContext.TreeAscending;
2709        Keyword        := FCurrentContext.Keyword;
2710        SearchField    := FCurrentContext.SearchField;
2711        Filtered       := FCurrentContext.Filtered;
2712        Changed        := True;
2713        mnuViewClick(Self);
2714      end
2715    else
2716      begin
2717        ViewContext := NC_RECENT ;
2718        mnuViewClick(Self);
2719      end;
2720  end;
2721  
2722  procedure TfrmNotes.mnuViewSaveAsDefaultClick(Sender: TObject);
2723  const
2724    TX_NO_MAX =  'You have not specified a maximum number of notes to be returned.' + CRLF +
2725                 'If you save this preference, the result will be that ALL notes for every' + CRLF +
2726                 'patient will be saved as your default view.' + CRLF + CRLF +
2727                 'For patients with large numbers of notes, this could result in some lengthy' + CRLF +
2728                 'delays in loading the list of notes.' + CRLF + CRLF +
2729                 'Are you sure you mean to do this?';
2730    TX_REPLACE = 'Replace current defaults?';
2731  begin
2732    inherited;
2733    if FCurrentContext.MaxDocs = 0 then
2734       if InfoBox(TX_NO_MAX,'Warning', MB_YESNO or MB_ICONWARNING) = IDNO then
2735         begin
2736           mnuViewClick(mnuViewCustom);
2737           Exit;
2738         end;
2739    if InfoBox(TX_REPLACE,'Confirmation', MB_YESNO or MB_ICONQUESTION) = IDYES then
2740      begin
2741        SaveCurrentTIUContext(FCurrentContext);
2742        FDefaultContext := FCurrentContext;
2743        //lblNotes.Caption := 'Default List';
2744      end;
2745  end;
2746  
2747  procedure TfrmNotes.mnuViewReturntoDefaultClick(Sender: TObject);
2748  begin
2749    inherited;
2750    SetViewContext(FDefaultContext);
2751  end;
2752  
2753  procedure TfrmNotes.popNoteMemoTemplateClick(Sender: TObject);
2754  begin
2755    inherited;
2756    EditTemplates(Self, TRUE, FEditCtrl.SelText);
2757  end;
2758  
2759  procedure TfrmNotes.popNoteListPopup(Sender: TObject);
2760  begin
2761    inherited;
2762    N4.Visible                          := (popNoteList.PopupComponent is TORTreeView);
2763    popNoteListExpandAll.Visible        := N4.Visible;
2764    popNoteListExpandSelected.Visible   := N4.Visible;
2765    popNoteListCollapseAll.Visible      := N4.Visible;
2766    popNoteListCollapseSelected.Visible := N4.Visible;
2767  end;
2768  
2769  procedure TfrmNotes.popNoteListExpandAllClick(Sender: TObject);
2770  begin
2771    inherited;
2772    tvNotes.FullExpand;
2773  end;
2774  
2775  procedure TfrmNotes.popNoteListCollapseAllClick(Sender: TObject);
2776  begin
2777    inherited;
2778    tvNotes.Selected := nil;
2779    lvNotes.Items.Clear;
2780    memNote.Clear;
2781    tvNotes.FullCollapse;
2782    tvNotes.Selected := tvNotes.TopItem;
2783  end;
2784  
2785  procedure TfrmNotes.popNoteListExpandSelectedClick(Sender: TObject);
2786  begin
2787    inherited;
2788    if tvNotes.Selected = nil then exit;
2789    with tvNotes.Selected do if HasChildren then Expand(True);
2790  end;
2791  
2792  procedure TfrmNotes.popNoteListCollapseSelectedClick(Sender: TObject);
2793  begin
2794    inherited;
2795    if tvNotes.Selected = nil then exit;
2796    with tvNotes.Selected do if HasChildren then Collapse(True);
2797  end;
2798  
2799  procedure TfrmNotes.mnuEditTemplatesClick(Sender: TObject);
2800  begin
2801    inherited;
2802    EditTemplates(Self);
2803  end;
2804  
2805  procedure TfrmNotes.mnuNewTemplateClick(Sender: TObject);
2806  begin
2807    inherited;
2808    EditTemplates(Self, TRUE);
2809  end;
2810  
2811  procedure TfrmNotes.mnuEditSharedTemplatesClick(Sender: TObject);
2812  begin
2813    inherited;
2814    EditTemplates(Self, FALSE, '', TRUE);
2815  end;
2816  
2817  procedure TfrmNotes.mnuNewSharedTemplateClick(Sender: TObject);
2818  begin
2819    inherited;
2820    EditTemplates(Self, TRUE, '', TRUE);
2821  end;
2822  
2823  procedure TfrmNotes.mnuOptionsClick(Sender: TObject);
2824  begin
2825    inherited;
2826    mnuEditTemplates.Enabled := frmDrawers.CanEditTemplates;
2827    mnuNewTemplate.Enabled := frmDrawers.CanEditTemplates;
2828    mnuEditSharedTemplates.Enabled := frmDrawers.CanEditShared;
2829    mnuNewSharedTemplate.Enabled := frmDrawers.CanEditShared;
2830    mnuEditDialgFields.Enabled := CanEditTemplateFields;
2831  end;
2832  
2833  procedure TfrmNotes.SetEditingIndex(const Value: Integer);
2834  begin
2835    FEditingIndex := Value;
2836    if(FEditingIndex < 0) then
2837      KillReminderDialog(Self);
2838    if(assigned(frmReminderTree)) then
2839      frmReminderTree.EnableActions;
2840  end;
2841  
2842  function TfrmNotes.CanFinishReminder: boolean;
2843  begin
2844    if(EditingIndex < 0) then
2845      Result := FALSE
2846    else
2847      Result := (lstNotes.ItemIndex = EditingIndex);
2848  end;
2849  
2850  procedure TfrmNotes.FormDestroy(Sender: TObject);
2851  begin
2852    FDocList.Free;
2853    FImageFlag.Free;
2854    KillDocTreeObjects(tvNotes);
2855    inherited;
2856  end;
2857  
2858  function TfrmNotes.GetDrawers: TfrmDrawers;
2859  begin
2860    Result := frmDrawers;
2861  end;
2862  
2863  procedure TfrmNotes.AssignRemForm;
2864  begin
2865    with RemForm do
2866    begin
2867      Form := Self;
2868      PCEObj := uPCEEdit;
2869      RightPanel := pnlRight;
2870      CanFinishProc := CanFinishReminder;
2871      DisplayPCEProc := DisplayPCE;
2872      Drawers := frmDrawers;
2873      NewNoteRE := memNewNote;
2874      NoteList := lstNotes;
2875    end;
2876  end;
2877  
2878  procedure TfrmNotes.mnuEditDialgFieldsClick(Sender: TObject);
2879  begin
2880    inherited;
2881    EditDialogFields;
2882  end;
2883  
2884  //===================  Added for sort/search enhancements ======================
2885  procedure TfrmNotes.LoadNotes;
2886  const
2887    INVALID_ID = -1;
2888    INFO_ID = 1;
2889  var
2890    tmpList: TStringList;
2891    ANode: TORTreeNode;
2892    x,xx,noteId: integer;   // Text Search CQ: HDS00002856
2893    Dest: TStrings;  // Text Search CQ: HDS00002856
2894    KeepFlag: Boolean;  // Text Search CQ: HDS00002856
2895    NoteCount, NoteMatches: integer;  // Text Search CQ: HDS00002856
2896  begin
2897    tmpList := TStringList.Create;
2898    try
2899      FDocList.Clear;
2900      uChanging := True;
2901      RedrawSuspend(memNote.Handle);
2902      RedrawSuspend(lvNotes.Handle);
2903      tvNotes.Items.BeginUpdate;
2904      lstNotes.Items.Clear;
2905      KillDocTreeObjects(tvNotes);
2906      tvNotes.Items.Clear;
2907      tvNotes.Items.EndUpdate;
2908      lvNotes.Items.Clear;
2909      memNote.Clear;
2910      memNote.Invalidate;
2911      lblTitle.Caption := '';
2912      lvNotes.Caption := '';
2913      with FCurrentContext do
2914        begin
2915          if Status <> IntToStr(NC_UNSIGNED) then
2916            begin
2917              ListNotesForTree(tmpList, NC_UNSIGNED, 0, 0, 0, 0, TreeAscending);
2918              if tmpList.Count > 0 then
2919                begin
2920                  CreateListItemsForDocumentTree(FDocList, tmpList, NC_UNSIGNED, GroupBy, TreeAscending, CT_NOTES);
2921                  UpdateTreeView(FDocList, tvNotes);
2922                end;
2923              tmpList.Clear;
2924              FDocList.Clear;
2925            end;
2926          if Status <> IntToStr(NC_UNCOSIGNED) then
2927            begin
2928              ListNotesForTree(tmpList, NC_UNCOSIGNED, 0, 0, 0, 0, TreeAscending);
2929              if tmpList.Count > 0 then
2930                begin
2931                  CreateListItemsForDocumentTree(FDocList, tmpList, NC_UNCOSIGNED, GroupBy, TreeAscending, CT_NOTES);
2932                  UpdateTreeView(FDocList, tvNotes);
2933                end;
2934              tmpList.Clear;
2935              FDocList.Clear;
2936            end;
2937          ListNotesForTree(tmpList, StrToIntDef(Status, 0), FMBeginDate, FMEndDate, Author, MaxDocs, TreeAscending);
2938          CreateListItemsForDocumentTree(FDocList, tmpList, StrToIntDef(Status, 0), GroupBy, TreeAscending, CT_NOTES);
2939  
2940          // Text Search CQ: HDS00002856 ---------------------------------------
2941          if FCurrentContext.SearchString<>''  then   // Text Search CQ: HDS00002856
2942            begin
2943              NoteMatches := 0;
2944              Dest:=TStringList.Create;
2945              NoteCount:=FDocList.Count-1;
2946              if FDocList.Count>0 then
2947                for x := FDocList.Count-1 downto 1 do begin;  // Don't do 0, because it's informational
2948                  KeepFlag:=False;
2949                  lblNotes.Caption:='Scanning '+IntToStr(NoteCount-x+1)+' of '+IntToStr(NoteCount)+', '+IntToStr(NoteMatches);
2950                  If NoteMatches=1 then lblNotes.Caption:=lblNotes.Caption+' match' else
2951                                        lblNotes.Caption:=lblNotes.Caption+' matches';
2952                  frmSearchStop.lblSearchStatus.Caption := lblNotes.Caption;
2953                  frmSearchStop.lblSearchStatus.Repaint;
2954                  lblNotes.Repaint;
2955                  // Free up some ticks so they can click the "Stop" button
2956                  application.processmessages;
2957                  application.processmessages;
2958                  application.processmessages;
2959                  If SearchTextStopFlag = False then begin
2960                    noteId := StrToIntDef(Piece(FDocList.Strings[x],'^',1),-1);
2961                    if (noteId = INVALID_ID) or (noteId = INFO_ID) then
2962                      Continue;
2963                    CallV('TIU GET RECORD TEXT', [Piece(FDocList.Strings[x],'^',1)]);
2964                    FastAssign(RPCBrokerV.Results, Dest);
2965                    If Dest.Count > 0 then
2966                       for xx := 0 to Dest.Count-1 do
2967                       begin
2968                        //Dest.Strings[xx] := StringReplace(Dest.Strings[xx],'#13',' ',[rfReplaceAll, rfIgnoreCase]);
2969                        if Pos(Uppercase(FCurrentContext.SearchString),Uppercase(Dest.Strings[xx]))>0 then
2970                          keepflag:=true;
2971                       end;
2972                    If KeepFlag=False then begin;
2973                      if FDocList.Count >= x then
2974                        FDocList.Delete(x);
2975                      if (tmpList.Count >= x) and (x > 0) then
2976                        tmpList.Delete(x-1);
2977                    end else
2978                      Inc(NoteMatches);
2979                  end;
2980                end;
2981              Dest.Free;
2982            end else
2983            //Reset the caption
2984            lblNotes.Caption := SetNoteTreeLabel(FCurrentContext);
2985            NoteTotal := sCallV('ORCNOTE GET TOTAL', [Patient.DFN]);
2986            lblNotes.Caption := lblNotes.Caption + ' (Total: ' + NoteTotal + ')';
2987          // Text Search CQ: HDS00002856 ---------------------------------------
2988  
2989          UpdateTreeView(FDocList, tvNotes);
2990        end;
2991      with tvNotes do
2992        begin
2993          uChanging := True;
2994          tvNotes.Items.BeginUpdate;
2995          RemoveParentsWithNoChildren(tvNotes, FCurrentContext);  // moved here in v15.9 (RV)
2996          if FLastNoteID <> '' then
2997            Selected := FindPieceNode(FLastNoteID, 1, U, nil);
2998          if Selected = nil then
2999            begin
3000              if (FCurrentContext.GroupBy <> '') or (FCurrentContext.Filtered) then
3001                begin
3002                  ANode := TORTreeNode(Items.GetFirstNode);
3003                  while ANode <> nil do
3004                    begin
3005                      ANode.Expand(False);
3006                      Selected := ANode;
3007                      ANode := TORTreeNode(ANode.GetNextSibling);
3008                    end;
3009                end
3010              else
3011                begin
3012                  ANode := tvNotes.FindPieceNode(FCurrentContext.Status, 1, U, nil);
3013                  if ANode <> nil then ANode.Expand(False);
3014                  ANode := tvNotes.FindPieceNode(IntToStr(NC_UNSIGNED), 1, U, nil);
3015                  if ANode = nil then
3016                    ANode := tvNotes.FindPieceNode(IntToStr(NC_UNCOSIGNED), 1, U, nil);
3017                  if ANode = nil then
3018                    ANode := tvNotes.FindPieceNode(FCurrentContext.Status, 1, U, nil);
3019                  if ANode <> nil then
3020                    begin
3021                      if ANode.getFirstChild <> nil then
3022                        Selected := ANode.getFirstChild
3023                      else
3024                        Selected := ANode;
3025                    end;
3026                end;
3027            end;
3028          memNote.Clear;
3029          with lvNotes do
3030            begin
3031              Selected := nil;
3032              if FCurrentContext.SortBy <> '' then
3033                ColumnToSort := Pos(FCurrentContext.SortBy, 'RDSAL') - 1;
3034              if not FCurrentContext.ShowSubject then
3035                begin
3036                  Columns[1].Width := 2 * (Width div 5);
3037                  Columns[2].Width := 0;
3038                end
3039              else
3040                begin
3041                  Columns[1].Width := Width div 5;
3042                  Columns[2].Width := Columns[1].Width;
3043                end;
3044            end;
3045          //RemoveParentsWithNoChildren(tvNotes, FCurrentContext);  // moved FROM here in v15.9 (RV)
3046          tvNotes.Items.EndUpdate;
3047          uChanging := False;
3048          SendMessage(tvNotes.Handle, WM_VSCROLL, SB_TOP, 0);
3049          if Selected <> nil then tvNotesChange(Self, Selected);
3050        end;
3051    finally
3052      RedrawActivate(memNote.Handle);
3053      RedrawActivate(lvNotes.Handle);
3054      tmpList.Free;
3055    end;
3056  end;
3057  
3058  procedure TfrmNotes.UpdateTreeView(DocList: TStringList; Tree: TORTreeView);
3059  begin
3060    with Tree do
3061      begin
3062        uChanging := True;
3063        Items.BeginUpdate;
3064        FastAddStrings(DocList, lstNotes.Items);
3065        BuildDocumentTree(DocList, '0', Tree, nil, FCurrentContext, CT_NOTES);
3066        Items.EndUpdate;
3067        uChanging := False;
3068      end;
3069  end;
3070  
3071  procedure TfrmNotes.tvNotesChange(Sender: TObject; Node: TTreeNode);
3072  var
3073    x, MySearch, MyNodeID: string;
3074    i: integer;
3075    WhyNot: string;
3076  begin
3077    if uChanging then Exit;
3078    //This gives the change a chance to occur when keyboarding, so that WindowEyes
3079    //doesn't use the old value.
3080    Application.ProcessMessages;
3081    with tvNotes do
3082      begin
3083        memNote.Clear;
3084        if Selected = nil then Exit;
3085        if uIDNotesActive then
3086          begin
3087            mnuActDetachFromIDParent.Enabled := (Selected.ImageIndex in [IMG_ID_CHILD, IMG_ID_CHILD_ADD]);
3088            popNoteListDetachFromIDParent.Enabled := mnuActDetachFromIDParent.Enabled;
3089            if (Selected.ImageIndex in [IMG_SINGLE, IMG_PARENT, IMG_ID_CHILD, IMG_ID_CHILD_ADD]) then
3090              mnuActAttachtoIDParent.Enabled := CanBeAttached(PDocTreeObject(Selected.Data)^.DocID, WhyNot)
3091            else
3092              mnuActAttachtoIDParent.Enabled := False;
3093            popNoteListAttachtoIDParent.Enabled := mnuActAttachtoIDParent.Enabled;
3094            if (Selected.ImageIndex in [IMG_SINGLE, IMG_PARENT,
3095                                        IMG_IDNOTE_OPEN, IMG_IDNOTE_SHUT,
3096                                        IMG_IDPAR_ADDENDA_OPEN, IMG_IDPAR_ADDENDA_SHUT]) then
3097              mnuActAddIDEntry.Enabled := CanReceiveAttachment(PDocTreeObject(Selected.Data)^.DocID, WhyNot)
3098            else
3099              mnuActAddIDEntry.Enabled := False;
3100            popNoteListAddIDEntry.Enabled := mnuActAddIDEntry.Enabled
3101          end;
3102        RedrawSuspend(lvNotes.Handle);
3103        RedrawSuspend(memNote.Handle);
3104        popNoteListExpandSelected.Enabled := Selected.HasChildren;
3105        popNoteListCollapseSelected.Enabled := Selected.HasChildren;
3106        x := TORTreeNode(Selected).StringData;
3107        if (Selected.ImageIndex in [IMG_TOP_LEVEL, IMG_GROUP_OPEN, IMG_GROUP_SHUT]) then
3108          begin
3109            lvNotes.Visible := True;
3110            lvNotes.Items.Clear;
3111            lvNotes.Height := (2 * lvNotes.Parent.Height) div 5;
3112            with lblTitle do
3113              begin
3114                Caption := Trim(Selected.Text);
3115                if (FCurrentContext.SearchField <> '') and (FCurrentContext.Filtered) then
3116                  begin
3117                    case FCurrentContext.SearchField[1] of
3118                      'T': MySearch := 'TITLE';
3119                      'S': MySearch := 'SUBJECT';
3120                      'B': MySearch := 'TITLE or SUBJECT';
3121                    end;
3122                    Caption := Caption + ' where ' + MySearch + ' contains "' + UpperCase(FCurrentContext.Keyword) + '"';
3123                  end;
3124                lvNotes.Caption := Caption;
3125              end;
3126  
3127            if Selected.ImageIndex = IMG_TOP_LEVEL then
3128              MyNodeID := Piece(TORTreeNode(Selected).StringData, U, 1)
3129            else if Selected.Parent.ImageIndex = IMG_TOP_LEVEL then
3130              MyNodeID := Piece(TORTreeNode(Selected.Parent).StringData, U, 1)
3131            else if Selected.Parent.Parent.ImageIndex = IMG_TOP_LEVEL then
3132              MyNodeID := Piece(TORTreeNode(Selected.Parent.Parent).StringData, U, 1);
3133  
3134            uChanging := True;
3135            TraverseTree(tvNotes, lvNotes, Selected.GetFirstChild, MyNodeID, FCurrentContext);
3136            with lvNotes do
3137              begin
3138                for i := 0 to Columns.Count - 1 do
3139                  Columns[i].ImageIndex := IMG_NONE;
3140                ColumnSortForward := FCurrentContext.ListAscending;
3141                if ColumnToSort = 5 then ColumnToSort := 0;
3142                if ColumnSortForward then
3143                  Columns[ColumnToSort].ImageIndex := IMG_ASCENDING
3144                else
3145                  Columns[ColumnToSort].ImageIndex := IMG_DESCENDING;
3146                if ColumnToSort = 0 then ColumnToSort := 5;
3147                AlphaSort;
3148                Columns[5].Width := 0;
3149                Columns[6].Width := 0;
3150              end;
3151            uChanging := False;
3152            with lvNotes do
3153              if Items.Count > 0 then
3154                begin
3155                  Selected := Items[0];
3156                  lvNotesSelectItem(Self, Selected, True);
3157                end
3158              else
3159                begin
3160                  Selected := nil;
3161                  lstNotes.ItemIndex := -1;
3162                  memPCEShow.Clear;
3163                  ShowPCEControls(False);
3164                end;
3165            pnlWrite.Visible := False;
3166            pnlRead.Visible := True;
3167            //  uncommented next 4 lines in v17.5  (RV)
3168            //-----------------------------
3169            UpdateReminderFinish;
3170            ShowPCEControls(False);
3171            frmDrawers.DisplayDrawers(TRUE, [odTemplates], [odTemplates]); //FALSE);
3172            ShowPCEButtons(FALSE);
3173            //-----------------------------
3174            //memNote.Clear;
3175          end
3176        else if StrToIntDef(Piece(x, U, 1), 0) > 0 then
3177          begin
3178            memNote.Clear;
3179            lvNotes.Visible := False;
3180            lstNotes.SelectByID(Piece(x, U, 1));
3181            lstNotesClick(Self);
3182            SendMessage(memNote.Handle, WM_VSCROLL, SB_TOP, 0);
3183          end;
3184        SendMessage(tvNotes.Handle, WM_HSCROLL, SB_THUMBTRACK, 0);
3185        RedrawActivate(lvNotes.Handle);
3186        RedrawActivate(memNote.Handle);
3187      end;
3188  end;
3189  
3190  procedure TfrmNotes.tvNotesCollapsed(Sender: TObject; Node: TTreeNode);
3191  begin
3192    with Node do
3193      begin
3194        if (ImageIndex in [IMG_GROUP_OPEN, IMG_IDNOTE_OPEN, IMG_IDPAR_ADDENDA_OPEN]) then
3195          ImageIndex := ImageIndex - 1;
3196        if (SelectedIndex in [IMG_GROUP_OPEN, IMG_IDNOTE_OPEN, IMG_IDPAR_ADDENDA_OPEN]) then
3197          SelectedIndex := SelectedIndex - 1;
3198      end;
3199  end;
3200  
3201  procedure TfrmNotes.tvNotesExpanded(Sender: TObject; Node: TTreeNode);
3202  
3203    function SortByTitle(Node1, Node2: TTreeNode; Data: Longint): Integer; stdcall;
3204    begin
3205      { Within an ID parent node, sorts in ascending order by title
3206      BUT - addenda to parent document are always at the top of the sort, in date order}
3207      if (Copy(PDocTreeObject(Node1.Data)^.DocTitle, 1, 8) = 'Addendum') and
3208         (Copy(PDocTreeObject(Node2.Data)^.DocTitle, 1, 8) = 'Addendum') then
3209        begin
3210          Result :=  AnsiStrIComp(PChar(PDocTreeObject(Node1.Data)^.DocFMDate),
3211                                  PChar(PDocTreeObject(Node2.Data)^.DocFMDate));
3212        end
3213      else if Copy(PDocTreeObject(Node1.Data)^.DocTitle, 1, 8) = 'Addendum' then Result := -1
3214      else if Copy(PDocTreeObject(Node2.Data)^.DocTitle, 1, 8) = 'Addendum' then Result := 1
3215      else
3216        begin
3217          if Data = 0 then
3218            Result :=  AnsiStrIComp(PChar(PDocTreeObject(Node1.Data)^.DocTitle),
3219                                    PChar(PDocTreeObject(Node2.Data)^.DocTitle))
3220          else
3221            Result := -AnsiStrIComp(PChar(PDocTreeObject(Node1.Data)^.DocTitle),
3222                                    PChar(PDocTreeObject(Node2.Data)^.DocTitle));
3223        end
3224    end;
3225  
3226    function SortByDate(Node1, Node2: TTreeNode; Data: Longint): Integer; stdcall;
3227    begin
3228      { Within an ID parent node, sorts in ascending order by document date
3229      BUT - addenda to parent document are always at the top of the sort, in date order}
3230      if (Copy(PDocTreeObject(Node1.Data)^.DocTitle, 1, 8) = 'Addendum') and
3231         (Copy(PDocTreeObject(Node2.Data)^.DocTitle, 1, 8) = 'Addendum') then
3232        begin
3233          Result :=  AnsiStrIComp(PChar(PDocTreeObject(Node1.Data)^.DocFMDate),
3234                                  PChar(PDocTreeObject(Node2.Data)^.DocFMDate));
3235        end
3236      else if Copy(PDocTreeObject(Node1.Data)^.DocTitle, 1, 8) = 'Addendum' then Result := -1
3237      else if Copy(PDocTreeObject(Node2.Data)^.DocTitle, 1, 8) = 'Addendum' then Result := 1
3238      else
3239        begin
3240          if Data = 0 then
3241            Result :=  AnsiStrIComp(PChar(PDocTreeObject(Node1.Data)^.DocFMDate),
3242                                    PChar(PDocTreeObject(Node2.Data)^.DocFMDate))
3243          else
3244            Result := -AnsiStrIComp(PChar(PDocTreeObject(Node1.Data)^.DocFMDate),
3245                                    PChar(PDocTreeObject(Node2.Data)^.DocFMDate));
3246        end;
3247    end;
3248  
3249  begin
3250    with Node do
3251      begin
3252        if Assigned(Data) then
3253          if (Pos('<', PDocTreeObject(Data)^.DocHasChildren) > 0) then
3254            begin
3255              if (PDocTreeObject(Node.Data)^.OrderByTitle) then
3256                CustomSort(@SortByTitle, 0)
3257              else
3258                CustomSort(@SortByDate, 0);
3259            end;
3260        if (ImageIndex in [IMG_GROUP_SHUT, IMG_IDNOTE_SHUT, IMG_IDPAR_ADDENDA_SHUT]) then
3261          ImageIndex := ImageIndex + 1;
3262        if (SelectedIndex in [IMG_GROUP_SHUT, IMG_IDNOTE_SHUT, IMG_IDPAR_ADDENDA_SHUT]) then
3263          SelectedIndex := SelectedIndex + 1;
3264      end;
3265  end;
3266  
3267  procedure TfrmNotes.tvNotesClick(Sender: TObject);
3268  begin
3269  (*  if tvNotes.Selected = nil then exit;
3270    if (tvNotes.Selected.ImageIndex in [IMG_TOP_LEVEL, IMG_GROUP_OPEN, IMG_GROUP_SHUT]) then
3271      begin
3272        uChanging := True;
3273        lvNotes.Selected := nil;
3274        uChanging := False;
3275        memNote.Clear;
3276      end;*)
3277  end;
3278  
3279  procedure TfrmNotes.tvNotesDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
3280  var
3281    AnItem: TORTreeNode;
3282  begin
3283    Accept := False;
3284    if not uIDNotesActive then exit;
3285    AnItem := TORTreeNode(tvNotes.GetNodeAt(X, Y));
3286    if (AnItem = nil) or (AnItem.ImageIndex in [IMG_GROUP_OPEN, IMG_GROUP_SHUT, IMG_TOP_LEVEL]) then Exit;
3287    with tvNotes.Selected do
3288      if (ImageIndex in [IMG_SINGLE, IMG_PARENT, IMG_ID_CHILD, IMG_ID_CHILD_ADD]) then
3289        Accept := (AnItem.ImageIndex in [IMG_SINGLE, IMG_PARENT,
3290                                         IMG_IDNOTE_OPEN, IMG_IDNOTE_SHUT,
3291                                         IMG_IDPAR_ADDENDA_OPEN, IMG_IDPAR_ADDENDA_SHUT])
3292      else if (ImageIndex in [IMG_IDNOTE_OPEN, IMG_IDNOTE_SHUT, IMG_IDPAR_ADDENDA_OPEN, IMG_IDPAR_ADDENDA_SHUT]) then
3293        Accept := (AnItem.ImageIndex in [IMG_GROUP_OPEN, IMG_GROUP_SHUT, IMG_TOP_LEVEL])
3294      else if (ImageIndex in [IMG_ADDENDUM, IMG_GROUP_OPEN, IMG_GROUP_SHUT, IMG_TOP_LEVEL]) then
3295        Accept := False;
3296  end;
3297  
3298  procedure TfrmNotes.tvNotesDragDrop(Sender, Source: TObject; X, Y: Integer);
3299  var
3300    HT: THitTests;
3301    Saved: boolean;
3302    ADestNode: TORTreeNode;
3303  begin
3304    if not uIDNotesActive then
3305      begin
3306        CancelDrag;
3307        exit;
3308      end;
3309    if tvNotes.Selected = nil then exit;
3310    if EditingIndex <> -1 then
3311    begin
3312      SaveCurrentNote(Saved);
3313      if not Saved then Exit;
3314    end;
3315    HT := tvNotes.GetHitTestInfoAt(X, Y);
3316    ADestNode := TORTreeNode(tvNotes.GetNodeAt(X, Y));
3317    DoAttachIDChild(TORTreeNode(tvNotes.Selected), ADestNode);
3318  end;
3319  
3320  procedure TfrmNotes.tvNotesStartDrag(Sender: TObject; var DragObject: TDragObject);
3321  const
3322    TX_CAP_NO_DRAG = 'Item cannot be moved';
3323    TX_NO_EDIT_DRAG = 'Items can not be dragged while a note is being edited.';
3324  var
3325    WhyNot: string;
3326    //Saved: boolean;
3327  begin
3328    if EditingIndex <> -1 then
3329    begin
3330      InfoBox(TX_NO_EDIT_DRAG, TX_CAP_NO_DRAG, MB_ICONERROR or MB_OK);
3331      CancelDrag;
3332      Exit;
3333    end;
3334    if (tvNotes.Selected.ImageIndex in [IMG_ADDENDUM, IMG_GROUP_OPEN, IMG_GROUP_SHUT, IMG_TOP_LEVEL]) or
3335       (not uIDNotesActive) or
3336       (lstNotes.ItemIEN = 0) then
3337      begin
3338        CancelDrag;
3339        Exit;
3340      end;
3341  (*  if EditingIndex <> -1 then
3342    begin
3343      SaveCurrentNote(Saved);
3344      if not Saved then Exit;
3345    end;*)
3346    if not CanBeAttached(PDocTreeObject(tvNotes.Selected.Data)^.DocID, WhyNot) then
3347      begin
3348        InfoBox(WhyNot, TX_CAP_NO_DRAG, MB_OK);
3349        CancelDrag;
3350      end;
3351  end;
3352  
3353  //=====================  Listview events  =================================
3354  
3355  procedure TfrmNotes.lvNotesColumnClick(Sender: TObject; Column: TListColumn);
3356  var
3357    i, ClickedColumn: Integer;
3358  begin
3359    if Column.Index = 0 then ClickedColumn := 5 else ClickedColumn := Column.Index;
3360    if ClickedColumn = ColumnToSort then
3361      ColumnSortForward := not ColumnSortForward
3362    else
3363      ColumnSortForward := True;
3364    for i := 0 to lvNotes.Columns.Count - 1 do
3365      lvNotes.Columns[i].ImageIndex := IMG_NONE;
3366    if ColumnSortForward then lvNotes.Columns[Column.Index].ImageIndex := IMG_ASCENDING
3367    else lvNotes.Columns[Column.Index].ImageIndex := IMG_DESCENDING;
3368    ColumnToSort := ClickedColumn;
3369    case ColumnToSort of
3370      5:  FCurrentContext.SortBy := 'R';
3371      1:  FCurrentContext.SortBy := 'D';
3372      2:  FCurrentContext.SortBy := 'S';
3373      3:  FCurrentContext.SortBy := 'A';
3374      4:  FCurrentContext.SortBy := 'L';
3375    else
3376      FCurrentContext.SortBy := 'R';
3377    end;
3378    FCurrentContext.ListAscending := ColumnSortForward;
3379    (Sender as TCustomListView).AlphaSort;
3380    //with lvNotes do if Selected <> nil then Scroll(0,  Selected.Top - TopItem.Top);
3381  end;
3382  
3383  procedure TfrmNotes.lvNotesCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer);
3384  var
3385    ix: Integer;
3386  begin
3387    if ColumnToSort = 0 then
3388      Compare := CompareText(Item1.Caption,Item2.Caption)
3389    else begin
3390     ix := ColumnToSort - 1;
3391     Compare := CompareText(Item1.SubItems[ix],Item2.SubItems[ix]);
3392    end;
3393    if not ColumnSortForward then Compare := -Compare;
3394  end;
3395  
3396  procedure TfrmNotes.lvNotesSelectItem(Sender: TObject; Item: TListItem;
3397    Selected: Boolean);
3398  begin
3399    if uChanging or (not Selected) then Exit;
3400    with lvNotes do
3401      begin
3402        StatusText('Retrieving selected progress note...');
3403        lstNotes.SelectByID(Item.SubItems[5]);
3404        lstNotesClick(Self);
3405        SendMessage(memNote.Handle, WM_VSCROLL, SB_TOP, 0);
3406      end;
3407  end;
3408  
3409  procedure TfrmNotes.lvNotesResize(Sender: TObject);
3410  begin
3411    inherited;
3412    with lvNotes do
3413      begin
3414        if not FCurrentContext.ShowSubject then
3415          begin
3416            Columns[1].Width := 2 * (Width div 5);
3417            Columns[2].Width := 0;
3418          end
3419        else
3420          begin
3421            Columns[1].Width := Width div 5;
3422            Columns[2].Width := Columns[1].Width;
3423          end;
3424      end;
3425  end;
3426  
3427  procedure TfrmNotes.EnableDisableIDNotes;
3428  begin
3429    uIDNotesActive := IDNotesInstalled;
3430    mnuActDetachFromIDParent.Visible := uIDNotesActive;
3431    popNoteListDetachFromIDParent.Visible := uIDNotesActive;
3432    mnuActAddIDEntry.Visible := uIDNotesActive;
3433    popNoteListAddIDEntry.Visible := uIDNotesActive;
3434    mnuActAttachtoIDParent.Visible := uIDNotesActive;
3435    popNoteListAttachtoIDParent.Visible := uIDNotesActive;
3436    if uIDNotesActive then
3437      tvNotes.DragMode := dmAutomatic
3438    else
3439      tvNotes.DragMode := dmManual;
3440  end;
3441  
3442  procedure TfrmNotes.ShowPCEButtons(Editing: boolean);
3443  begin
3444    if frmFrame.Timedout then Exit;
3445  
3446    FEditingNotePCEObj := Editing;
3447    if Editing or AnytimeEncounters then
3448    begin
3449      cmdPCE.Visible := TRUE;
3450      if Editing then
3451      begin
3452        cmdPCE.Enabled := CanEditPCE(uPCEEdit);
3453        cmdNewNote.Visible := AnytimeEncounters;
3454        cmdNewNote.Enabled := FALSE;
3455      end
3456      else
3457      begin
3458        cmdPCE.Enabled     := (GetAskPCE(0) <> apDisable);
3459        cmdNewNote.Visible := TRUE;
3460        cmdNewNote.Enabled := (FStarting = False); //TRUE;
3461      end;
3462      if cmdNewNote.Visible then
3463        cmdPCE.Top := cmdNewNote.Top-cmdPCE.Height;
3464    end
3465    else
3466    begin
3467      cmdPCE.Enabled := FALSE;
3468      cmdPCE.Visible := FALSE;
3469      cmdNewNote.Visible := TRUE;
3470      cmdNewNote.Enabled := (FStarting = False); //TRUE;
3471    end;
3472    if cmdPCE.Visible then
3473      lblSpace1.Top := cmdPCE.Top - lblSpace1.Height
3474    else
3475      lblSpace1.Top := cmdNewNote.Top - lblSpace1.Height;
3476    popNoteMemoEncounter.Enabled := cmdPCE.Enabled;
3477    popNoteMemoEncounter.Visible := cmdPCE.Visible;
3478  end;
3479  
3480  procedure TfrmNotes.mnuIconLegendClick(Sender: TObject);
3481  begin
3482    inherited;
3483    ShowIconLegend(ilNotes);
3484  end;
3485  
3486  procedure TfrmNotes.mnuActAttachtoIDParentClick(Sender: TObject);
3487  var
3488    AChildNode: TORTreeNode;
3489    AParentID: string;
3490    SavedDocID: string;
3491    Saved: boolean;
3492  begin
3493    inherited;
3494    if not uIDNotesActive then exit;
3495    if lstNotes.ItemIEN = 0 then exit;
3496    SavedDocID := lstNotes.ItemID;
3497    if EditingIndex <> -1 then
3498    begin
3499      SaveCurrentNote(Saved);
3500      if not Saved then Exit;
3501      LoadNotes;
3502      with tvNotes do Selected := FindPieceNode(SavedDocID, U, Items.GetFirstNode);
3503    end;
3504    if tvNotes.Selected = nil then exit;
3505    AChildNode := TORTreeNode(tvNotes.Selected);
3506    AParentID := SelectParentNodeFromList(tvNotes);
3507    if AParentID = '' then exit;
3508    with tvNotes do Selected := FindPieceNode(AParentID, 1, U, Items.GetFirstNode);
3509    DoAttachIDChild(AChildNode, TORTreeNode(tvNotes.Selected));
3510  end;
3511  
3512  procedure TfrmNotes.DoAttachIDChild(AChild, AParent: TORTreeNode);
3513  const
3514    TX_ATTACH_CNF     = 'Confirm Attachment';
3515    TX_AT