unit fAnticoagulator;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, RpRender, RpRenderCanvas,RPCConf1, RpRenderPrinter, RpDefine, RpCon,
  RpRave, RpBase, RpSystem, Trpcb, ORNet, ORFn, ORDtTm, TeEngine,
  Series, ExtCtrls, TeeProcs, Chart, ComCtrls, Grids, xwbHash, DateUtils,StrUtils,
  ORCtrls, fCosign, ExtDlgs, fSplash, VA508AccessibilityManager, fTimeout, uInit,
  Menus, Mask, VclTee.TeeGDIPlus, Vcl.AppEvnts,
  // interceptor unit should be listed last
  u508Interceptors;

type

  //ZZZZZZBELLC - Record holds sting value to display on chart
  tSeriesValues = record
   SeriesIndex: Integer;
   SeriesValue: string;
   SeriesDTH: String;
   SeriesFloat: String;
  end;

  TfrmAnticoagulate = class(TForm)
    RvCustomConnection: TRvCustomConnection;
    RvProject: TRvProject;
    RvSystem: TRvSystem;
    pnlTop: TPanel;
    lblIndication: TLabel;
    lblINRGoal: TLabel;
    gbxContactInfo: TGroupBox;
    cbxINRGoal: TComboBox;
    pnlINR: TPanel;
    gbxINRset: TGroupBox;
    lblMinINRGoal: TLabel;
    lblMaxINRGoal: TLabel;
    edtMin: TEdit;
    edtMax: TEdit;
    btnNGOK: TButton;
    btnNGClose: TButton;
    pcMain: TPageControl;
    tsDem: TTabSheet;
    gbxPC: TGroupBox;
    btnSwitch: TButton;
    gbxShow: TGroupBox;
    gbxLastHCT: TGroupBox;
    btnRemind: TButton;
    pnlRemind: TPanel;
    lblRemDate: TLabel;
    lblRemindText: TLabel;
    dtpRemind: TDateTimePicker;
    memRemind: TMemo;
    btnRemClear: TButton;
    btnRemOK: TButton;
    btnRemCan: TButton;
    chrtINR: TChart;
    serINR: TLineSeries;
    pnlNewPt: TPanel;
    btnCloseInstr: TButton;
    tsUp: TTabSheet;
    gbxUpdate: TGroupBox;
    lblRisks: TLabel;
    lblDuration: TLabel;
    lblStartDate: TLabel;
    lblOrientationDate: TLabel;
    lblSpecialInstructions: TLabel;
    lblStop: TLabel;
    ckbRestrict: TCheckBox;
    ckbMsg: TCheckBox;
    ckbPmsg: TCheckBox;
    memPeople: TMemo;
    ckbAMmeds: TCheckBox;
    memRisk: TMemo;
    btnCUpdate: TButton;
    memSpInE: TMemo;
    pnlLevelOfComplexity: TPanel;
    lblLevelOfComplexity: TLabel;
    rbComp: TRadioButton;
    rbStand: TRadioButton;
    ckbSA: TCheckBox;
    ckbNoStop: TCheckBox;
    ckbDC: TCheckBox;
    lstINRtemp: TListBox;
    btnSExit: TButton;
    pnlRestrict: TPanel;
    lblRstrctDrawDays: TLabel;
    ckbRM: TCheckBox;
    ckbRF: TCheckBox;
    ckbRT: TCheckBox;
    ckbRTh: TCheckBox;
    ckbRW: TCheckBox;
    btnROK: TButton;
    btnRCan: TButton;
    tsFlow: TTabSheet;
    stgAC: TStringGrid;
    sbxComm: TScrollBox;
    lblFS: TLabel;
    memComm: TMemo;
    btnEdit: TButton;
    gbxEdit: TGroupBox;
    lblEditDate: TLabel;
    lblEComm: TLabel;
    lblINREdit: TLabel;
    lblPtNotifEdit: TLabel;
    lblTWDEdit: TLabel;
    lblEditDuz: TLabel;
    edtEditINR: TEdit;
    memEDIT: TMemo;
    btnEditCan: TButton;
    btnEditOK: TButton;
    dtpEdit: TDateTimePicker;
    edtPN: TEdit;
    edtTWD: TEdit;
    ckbEditDel: TCheckBox;
    tsInfo: TTabSheet;
    pcInfo: TPageControl;
    tsNewFSEntry: TTabSheet;
    pnlNComm: TPanel;
    lblINR: TLabel;
    lblNINRDt: TLabel;
    lblNoteDt: TLabel;
    lblNTWD: TLabel;
    lblPtNotice: TLabel;
    lblFSentry: TLabel;
    lblComments: TLabel;
    memNCom: TMemo;
    edtPtNote: TEdit;
    btnClose: TButton;
    btnCanEnt: TButton;
    btnNEntry: TButton;
    btnNoINR: TButton;
    btnMissedAppt: TButton;
    tsOLD: TTabSheet;
    gbxINREnter: TGroupBox;
    lblNewINR: TLabel;
    lblINRDate: TLabel;
    lblLabLoc: TLabel;
    lblStandingOrderExp: TLabel;
    lblHistory: TLabel;
    lblLabPhone: TLabel;
    lblLabFax: TLabel;
    lblNewHCT: TLabel;
    edtNewInr: TEdit;
    dtpINR: TDateTimePicker;
    edtLoc: TEdit;
    btnINRClose: TButton;
    btnCancel: TButton;
    dtpLAB: TDateTimePicker;
    btnYHx: TButton;
    btnNHx: TButton;
    pnlFee: TPanel;
    lblFeeBasis: TLabel;
    lblexp: TLabel;
    rbFeeNo: TRadioButton;
    rbFeePrim: TRadioButton;
    rbFeeSec: TRadioButton;
    dtpExp: TDateTimePicker;
    edtLFax: TEdit;
    edtLPhone: TEdit;
    edtNewHCT: TEdit;
    tsComplications: TTabSheet;
    ckbTT: TCheckBox;
    pnlMajorC: TPanel;
    lblComplMinor: TLabel;
    ckbMCH: TCheckBox;
    ckbMCtran: TCheckBox;
    ckbMChgb: TCheckBox;
    ckbMCR: TCheckBox;
    ckbMCDeath: TCheckBox;
    ckbMinorC: TCheckBox;
    memMinorC: TMemo;
    tsHidden: TTabSheet;
    tsExit: TTabSheet;
    gbxLabs: TGroupBox;
    ckbINROrder: TCheckBox;
    ckbCBC: TCheckBox;
    pnlLettNote: TPanel;
    lblLetter: TLabel;
    lblProgNotes: TLabel;
    btnMA: TButton;
    btnCV: TButton;
    btnIntakeNote: TButton;
    btnInterimNote: TButton;
    btnDCstart: TButton;
    btnComp: TButton;
    btnTempSave: TButton;
    gbxPCE: TGroupBox;
    lblPhoneVisit: TLabel;
    lblLettVisit: TLabel;
    lblICDPrim: TLabel;
    lblVisit: TLabel;
    ckbNone: TCheckBox;
    ckbCBOC: TCheckBox;
    edtICD9: TEdit;
    rbPhoneS: TRadioButton;
    rbPhoneC: TRadioButton;
    rbOVisit: TRadioButton;
    rbLetter: TRadioButton;
    rbPharm: TRadioButton;
    gbxCA: TGroupBox;
    lblCL: TLabel;
    memCL: TMemo;
    pnlMChange: TPanel;
    lblHoldDays: TLabel;
    lblTabsToday: TLabel;
    ckbHold: TCheckBox;
    edtHDays: TEdit;
    ckbTake: TCheckBox;
    edtTTabs: TEdit;
    ckbWS: TCheckBox;
    btnCVL: TButton;
    btnCA: TButton;
    gbxMA: TGroupBox;
    lblNewAppt: TLabel;
    lblNAppt: TLabel;
    lblEnterTxt: TLabel;
    lblMADt: TLabel;
    btnMAPreview: TButton;
    btnMAClose: TButton;
    dtpMA: TDateTimePicker;
    gbxSig: TGroupBox;
    lblESig: TLabel;
    lblESExplain: TLabel;
    edtSig: TEdit;
    btnESCancel: TButton;
    btnESSubmit: TButton;
    gbxDC: TGroupBox;
    memDC: TMemo;
    pnlDCedt: TPanel;
    memDCnote: TMemo;
    pnlConsult: TPanel;
    lblSelConsult: TLabel;
    lbxConsult: TListBox;
    btnConsult: TButton;
    btnCanCon: TButton;
    pnlNoDraw: TPanel;
    tsSTAT: TTabSheet;
    lblPercentInGoal: TLabel;
    lblDays: TLabel;
    lbl45DayLoad: TLabel;
    lblLTFDays: TLabel;
    lblLTFQuery: TLabel;
    lblUnlock: TLabel;
    btnUnlock: TButton;
    btnLost: TButton;
    edtLTF: TEdit;
    btnTWeek: TButton;
    btnXPC: TButton;
    edtXDays: TEdit;
    sbxXPC: TScrollBox;
    pnlPC: TPanel;
    memXPC: TMemo;
    pnlXPC: TPanel;
    lblXPct: TLabel;
    pnlCount: TPanel;
    lblCount: TLabel;
    pnlLTF: TPanel;
    lblLTF: TLabel;
    pnlPtLookUp: TPanel;
    lblLast4: TLabel;
    btnCancelUnlock: TButton;
    btnUnlockRec: TButton;
    ckbTWD: TCheckBox;
    gbxDailyDosing: TGroupBox;
    lblSun: TLabel;
    lblThu: TLabel;
    lblWed: TLabel;
    lblMon: TLabel;
    lblSat: TLabel;
    lblFri: TLabel;
    lblTue: TLabel;
    lblTotals: TLabel;
    lblTablets: TLabel;
    lblMilligrams: TLabel;
    lblAM: TLabel;
    edtCTSat: TEdit;
    edtCTFri: TEdit;
    edtCTSun: TEdit;
    edtCTMon: TEdit;
    edtCTTue: TEdit;
    edtCTWed: TEdit;
    edtCTThu: TEdit;
    edtCMSun: TEdit;
    edtCMMon: TEdit;
    edtCMTue: TEdit;
    edtCMWed: TEdit;
    edtCMThu: TEdit;
    edtCMFri: TEdit;
    edtCMSat: TEdit;
    btnDD: TButton;
    edtTotT: TEdit;
    edtTotM: TEdit;
    btnCanDose: TButton;
    lblPillStrength: TLabel;
    lblRedLine: TLabel;
    ckbMCother: TCheckBox;
    rbOclass: TRadioButton;
    rbSoffice: TRadioButton;
    ckbAddt: TCheckBox;
    dtpComp: TDateTimePicker;
    lblComplDt: TLabel;
    btnFileC: TButton;
    btnCCom: TButton;
    btnXComp: TButton;
    gbxComments: TGroupBox;
    memMCother: TMemo;
    ckbCC: TCheckBox;
    ckbEditCompR: TCheckBox;
    orbxPTlU: TORComboBox;
    AccessibilityManager: TVA508AccessibilityManager;
    gbxReturnForINR: TGroupBox;
    dtpNextApp: TDateTimePicker;
    ckbPlusDay: TCheckBox;
    memMA: TMemo;
    rbMC: TRadioButton;
    rbNoMC: TRadioButton;
    pnlDCBottom: TPanel;
    pnlDCsign: TPanel;
    lblDCSign: TLabel;
    btnDC: TButton;
    btnDCsign: TButton;
    edtSigDC: TEdit;
    pnlDCETop: TPanel;
    lblNBox: TLabel;
    pnlDCERight: TPanel;
    lblPNEdit: TLabel;
    pnlDCTop: TPanel;
    ckbPMove: TCheckBox;
    edtPMove: TEdit;
    ckbPViol: TCheckBox;
    ckbPtDC: TCheckBox;
    edtPDC: TEdit;
    lblDCOn: TLabel;
    dtpDC: TDateTimePicker;
    lblDCFor: TLabel;
    ckbOther: TCheckBox;
    mnuMain: TMainMenu;
    mnuFile: TMenuItem;
    mnuExit: TMenuItem;
    mnuEdit: TMenuItem;
    mnuCut: TMenuItem;
    mnuCopy: TMenuItem;
    mnuPaste: TMenuItem;
    mnuView: TMenuItem;
    mnuDemographics: TMenuItem;
    mnuPtPreferences: TMenuItem;
    mnuFlowSheet: TMenuItem;
    mnuEnterInformation: TMenuItem;
    mnuExitTab: TMenuItem;
    mnuUtilities: TMenuItem;
    mnuHelp: TMenuItem;
    mnuAnticoagulationManagementHelp: TMenuItem;
    N1: TMenuItem;
    mnuAbout: TMenuItem;
    mnuUndo: TMenuItem;
    splEdit: TMenuItem;
    lbldenom: TStaticText;
    lblPCgoal: TStaticText;
    lblPctOfVisits: TStaticText;
    lblRSR: TStaticText;
    lblHCT: TStaticText;
    lblHCTdate: TStaticText;
    memNewPtInst: TMemo;
    lblNewPtInst: TStaticText;
    mnuEnterOutsideLab: TMenuItem;
    mnuNewFlowSheetEntry: TMenuItem;
    Complications1: TMenuItem;
    lblACAct: TStaticText;
    lblComplications: TStaticText;
    lblThrombosis: TStaticText;
    lblBleeding: TStaticText;
    lblComplMajor: TStaticText;
    lblRecur: TStaticText;
    lblXPC: TStaticText;
    lblPtsNotAtGoal: TStaticText;
    pnlTWeek: TPanel;
    memTWeek: TMemo;
    lblBOX: TStaticText;
    lblLU: TLabel;
    btnDCGClose: TButton;
    lblLastINR: TLabel;
    lblINRval: TVA508StaticText;
    lblINRdt: TVA508StaticText;
    lblComplex: TVA508StaticText;
    lblSSN: TVA508StaticText;
    lblPname: TVA508StaticText;
    lblCSZ: TVA508StaticText;
    lblHfone: TVA508StaticText;
    lblSadr1: TVA508StaticText;
    lblSadr2: TVA508StaticText;
    lblSadr3: TVA508StaticText;
    lblWfone: TVA508StaticText;
    lblMSG: TVA508StaticText;
    lblSign: TVA508StaticText;
    lblTemp: TVA508StaticText;
    btnPlus14: TButton;
    lblPlus14: TLabel;
    btnPlus28: TButton;
    lblPlus28: TLabel;
    lblNoDraw: TVA508StaticText;
    lblDrawRestr: TLabel;
    edtDur: TEdit;
    sbxPMsg: TScrollBox;
    lblPMsg: TStaticText;
    lblNINRval: TVA508StaticText;
    lblNidate: TVA508StaticText;
    lblNdate: TVA508StaticText;
    lblNTWDval: TVA508StaticText;
    edtStop: TEdit;
    edtSDate: TEdit;
    edtODate: TEdit;
    lblEntryComplete: TVA508StaticText;
    mnuHelpBroker: TMenuItem;
    ckbBridging: TCheckBox;
    ckbIncludeRisksInNote: TCheckBox;
    ckbBridgeComments: TCheckBox;
    ckbMAInclInst: TCheckBox;
    ckbCAInclInst: TCheckBox;
    dtpAppTime: TDateTimePicker;
    lblARTReminder: TVA508StaticText;
    cbxIndic: TORComboBox;
    lblAutoPrimIndicCap: TVA508StaticText;
    lblAutoPrimIndic: TVA508StaticText;
    cbxSite: TORComboBox;
    lblSiteName: TLabel;
    cboPS: TORComboBox;
    lblSelectOne: TLabel;
    lblAutoSecIndicCap: TVA508StaticText;
    lblAutoSecIndic: TVA508StaticText;
    ApplicationEvents1: TApplicationEvents;
    procedure btnCVClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure cbxINRGoalChange(Sender: TObject);
    procedure btnDDClick(Sender: TObject);
    procedure btnCompClick(Sender: TObject);
    procedure cbxIndicChange(Sender: TObject);
    procedure btnCUpdateClick(Sender: TObject);
    procedure memSpInEChange(Sender: TObject);
    procedure memRiskChange(Sender: TObject);
    procedure memPeopleChange(Sender: TObject);
    procedure stgACSelectCell(Sender: TObject; ACol, ARow: Integer;
      var CanSelect: Boolean);
    procedure btnCloseClick(Sender: TObject);
    procedure edtCTChange(Sender: TObject);
    procedure edtCMChange(Sender: TObject);
    procedure edtCMExit(Sender: TObject);
    procedure btnINRCloseClick(Sender: TObject);
    procedure btnCancelClick(Sender: TObject);
    procedure btnCanEntClick(Sender: TObject);
    procedure btnNEntryClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure btnTempSaveClick(Sender: TObject);
    procedure btnMAClick(Sender: TObject);
    procedure btnCanDoseClick(Sender: TObject);
    procedure rbMCClick(Sender: TObject);
    procedure rbNoMCClick(Sender: TObject);
    procedure btnCVLClick(Sender: TObject);
    procedure btnYHxClick(Sender: TObject);
    procedure tsUpExit(Sender: TObject);
    procedure btnNHxClick(Sender: TObject);
    procedure btnMACloseClick(Sender: TObject);
    procedure btnMAPreviewClick(Sender: TObject);
    procedure memMAKeyPress(Sender: TObject; var Key: Char);
    procedure btnIntakeNoteClick(Sender: TObject);
    procedure btnESCancelClick(Sender: TObject);
    procedure edtSigKeyPress(Sender: TObject; var Key: Char);
    procedure SetEClinic;
    procedure btnESSubmitClick(Sender: TObject);
    procedure ckbDCClick(Sender: TObject);
    procedure btnInterimNoteClick(Sender: TObject);
    procedure rbFeePrimClick(Sender: TObject);
    procedure rbFeeSecClick(Sender: TObject);
    procedure rbFeeNoClick(Sender: TObject);
    procedure cboPSExit(Sender: TObject);
    procedure btnNoINRClick(Sender: TObject);
    procedure ckbPmsgClick(Sender: TObject);
    procedure tsFlowExit(Sender: TObject);
    procedure btnNGCloseClick(Sender: TObject);
    procedure btnNGOKClick(Sender: TObject);
    procedure edtPtNoteKeyPress(Sender: TObject; var Key: Char);
    procedure btnESCloseClick(Sender: TObject);
    procedure btnXPCEnter(Sender: TObject);
    procedure btnXPCExit(Sender: TObject);
    procedure lblPercentInGoalMouseEnter(Sender: TObject);
    procedure lblPercentInGoalMouseLeave(Sender: TObject);
    procedure btnXPCClick(Sender: TObject);
    procedure btnTWeekClick(Sender: TObject);
    procedure lbl45DayLoadMouseEnter(Sender: TObject);
    procedure lbl45DayLoadMouseLeave(Sender: TObject);
    procedure btnLostClick(Sender: TObject);
    procedure ckbHoldClick(Sender: TObject);
    procedure ckbTakeClick(Sender: TObject);
    procedure ckbWSClick(Sender: TObject);
    procedure btnCAClick(Sender: TObject);
    procedure lblLTFQueryMouseEnter(Sender: TObject);
    procedure lblLTFQueryMouseLeave(Sender: TObject);
    procedure ckbPMoveClick(Sender: TObject);
    procedure ckbPViolClick(Sender: TObject);
    procedure btnDCGCloseClick(Sender: TObject);
    procedure ckbPtDCClick(Sender: TObject);
    procedure ckbOtherClick(Sender: TObject);
    procedure btnDCClick(Sender: TObject);
    procedure btnDCCloseClick(Sender: TObject);
    procedure btnDCsignClick(Sender: TObject);
    procedure btnDCstartClick(Sender: TObject);
    procedure edtSigDCKeyPress(Sender: TObject; var Key: Char);
    procedure btnConsultClick(Sender: TObject);
    procedure btnCanConClick(Sender: TObject);
    procedure btnEditClick(Sender: TObject);
    procedure btnEditCanClick(Sender: TObject);
    procedure ckbEditDelClick(Sender: TObject);
    procedure btnEditOKClick(Sender: TObject);
    procedure btnRemindClick(Sender: TObject);
    procedure btnRemCanClick(Sender: TObject);
    procedure btnRemOKClick(Sender: TObject);
    procedure btnRemClearClick(Sender: TObject);
    procedure btnCloseInstrClick(Sender: TObject);
    function AddTop(): string;
    procedure EnableChildControls(Control: TWinControl; Enable: Boolean);
    procedure SetStaticTextTabStopTrue;
    procedure SetDosingTabOrders;
    procedure ToggleDemVisible;
    procedure ToggleExitVisible(Sender: TObject);
    procedure btnSExitClick(Sender: TObject);
    procedure edtDurKeyPress(Sender: TObject; var Key: Char);
    procedure btnUnlockClick(Sender: TObject);
    procedure btnCancelUnlockClick(Sender: TObject);
    procedure btnUnlockRecClick(Sender: TObject);
    procedure btnSwitchClick(Sender: TObject);
    procedure btnMissedApptClick(Sender: TObject);
    procedure cbxINRGoalClick(Sender: TObject);
    procedure tsDemMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure pcMainChange(Sender: TObject);
    procedure btnPlus14Click(Sender: TObject);
    procedure btnROKClick(Sender: TObject);
    procedure ckbRestrictClick(Sender: TObject);
    procedure btnRCanClick(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure pcInfoChange(Sender: TObject);
    procedure ckbMCDeathClick(Sender: TObject);
    function complications():string;
    procedure ckbTTClick(Sender: TObject);
    procedure cbxINRGoalDropDown(Sender: TObject);
    procedure cbxINRGoalCloseUp(Sender: TObject);
    procedure cbxSiteSelect(Sender: TObject);
    procedure btnFileCClick(Sender: TObject);
    procedure btnCComClick(Sender: TObject);
    procedure btnXCompClick(Sender: TObject);
    procedure ckbCCClick(Sender: TObject);
    procedure tsExitShow(Sender: TObject);
    procedure mnuDemographicsClick(Sender: TObject);
    procedure mnuPtPreferencesClick(Sender: TObject);
    procedure mnuFlowSheetClick(Sender: TObject);
    procedure mnuEnterInformationClick(Sender: TObject);
    procedure mnuExitTabClick(Sender: TObject);
    procedure mnuUtilitiesClick(Sender: TObject);
    procedure mnuCutClick(Sender: TObject);
    procedure mnuEditClick(Sender: TObject);
    procedure mnuCopyClick(Sender: TObject);
    procedure mnuPasteClick(Sender: TObject);
    procedure mnuUndoClick(Sender: TObject);
    procedure mnuExitClick(Sender: TObject);
    procedure mnuAboutClick(Sender: TObject);
    procedure memNewPtInstEnter(Sender: TObject);
    procedure chrtINREnter(Sender: TObject);
    procedure mnuEnterOutsideLabClick(Sender: TObject);
    procedure mnuNewFlowSheetEntryClick(Sender: TObject);
    procedure Complications1Click(Sender: TObject);
    procedure tsFlowShow(Sender: TObject);
    procedure pnlRemindEnter(Sender: TObject);
    procedure memXPCEnter(Sender: TObject);
    procedure memTWeekEnter(Sender: TObject);
    procedure orbxPTlUEnter(Sender: TObject);
    procedure cbxIndicExit(Sender: TObject);
    procedure cbxINRGoalExit(Sender: TObject);
    procedure edtODateExit(Sender: TObject);
    procedure edtDurExit(Sender: TObject);
    procedure mnuAnticoagulationManagementHelpClick(Sender: TObject);
    procedure cbxSiteExit(Sender: TObject);
    procedure edtSDateExit(Sender: TObject);
    procedure dtpNextAppChange(Sender: TObject);
    procedure dtpNextAppExit(Sender: TObject);
    procedure mnuHelpBrokerClick(Sender: TObject);
    function TimeoutCondition: boolean;
    function GetTimedOut: boolean;
    procedure TimeOutAction;
    procedure ckbBridgingClick(Sender: TObject);
    procedure ckbBridgeCommentsClick(Sender: TObject);
    procedure memMAExit(Sender: TObject);
    procedure dtpAppTimeChange(Sender: TObject);
    procedure gbxINRsetExit(Sender: TObject);
    procedure edtCTKeyPress(Sender: TObject; var Key: Char);
    procedure edtCMKeyPress(Sender: TObject; var Key: Char);
    procedure edtCTExit(Sender: TObject);
    procedure edtCTKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure edtCMKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure edtPMoveChange(Sender: TObject);
    procedure edtPDCChange(Sender: TObject);
    procedure serINRGetMarkText(Sender: TChartSeries; ValueIndex: Integer;
      var MarkText: string);
    procedure memDCnoteChange(Sender: TObject);
    procedure cbxINRGoalKeyPress(Sender: TObject; var Key: Char);
    procedure edtMaxKeyPress(Sender: TObject; var Key: Char);
    procedure edtMinKeyPress(Sender: TObject; var Key: Char);
    procedure edtLocKeyPress(Sender: TObject; var Key: Char);
    procedure edtNewInrKeyPress(Sender: TObject; var Key: Char);
    procedure edtNewHCTKeyPress(Sender: TObject; var Key: Char);
    procedure edtLPhoneKeyPress(Sender: TObject; var Key: Char);
    procedure edtLFaxKeyPress(Sender: TObject; var Key: Char);
    procedure edtLocChange(Sender: TObject);
    procedure cbxIndicEnter(Sender: TObject);
    function ApplicationEvents1Help(Command: Word; Data: NativeInt;
      var CallHelp: Boolean): Boolean;
  private
    ReturnFocus: TObject;
    FEditCtrl: TCustomEdit;
    FCreateProgress: Integer;
    FTabCutWarn: Boolean;
    FDosageWarn: Boolean;
    FICD10Active: Boolean;
    IndicChanging: Boolean;
    GeneratedNoteText: String;
    SeriesValues: Array of tSeriesValues; //ZZZZZZBELLC
    function IsGUIVersionOK: boolean;
    function CheckDrawDay: Boolean;
    function PadString(InString: String): String;
    function DecDig(InNum: Single): Integer;
    procedure TabletsSum;
    procedure TabletsReset;
    procedure MilligramsSum;
    procedure MilligramsReset;
    procedure GenerateIntakeNote;
    procedure GenerateInterimNote;
    procedure IdentifyCPT;
    procedure FloatFilter(Sender: TObject; var Key: Char; digits: Integer = 2);
  protected

  public
    { Public declarations }
   //
  end;

type
   TCommArr = Array of TStrings;
   TDUZArr = Array of String;
   function orderit(PDFN:string; LDUZ:string; code:string): string;
var
  frmAnticoagulate: TfrmAnticoagulate;
  x, PDFN, PtName, ProvName, Gender, PtLocation, ClinicRef, PDUZ, SA: string;
  INR, inrdate, Proced, FMNow, VisitDate, IntakeNote, InterimNote, DischargeNote: string;
  ICD9new, lab, FileAs: string;
  FMsg, Meds, SP, ChRisk, Peep, cs, box, Add, NewPt, cdose, ResultDay, FB, ienmax: Integer;
  AMMeds, Msg, Contacts, RDate, NextDate, StartDate, Sign, labdate, LabExp, tempnoshow: string;
  PMSG: Array of String;
  PillDose, PillDoseOr, DefaultPillStrength: single;
  InclINRTime: Boolean;
  LetterINRTime: String;
  Comments, FlowArr, CmpTxt, BridgeComments, PatientInstructions: TStrings;
  CommArr: TCommArr;
  CompArr: TCommArr;
  fsduz: TDUZArr;
  Greet, GName, TempDose, MNote, MNoteCl, Instruct, NoteNumber: string;
  //test: Integer = 0;  SMT Change Test to Something meaningful (OutSideINR)
  OutSideINR :Boolean = False;
  Hist: Integer = 0;
  fsyes: Integer = 0;
  oldcs: Integer = 0;
  dcexit: Integer = 0;
  remindmsg:Integer = 0;
  DTIME, noshow, ConsultCtrl: Integer;
  Title, IndiText, TargetT, SevText, mDose, CINR, fstext, fstexta, OldINR, FSrow, FSien: string;
  inrold, inrdold, FileWas, INRGOAL, pcgoal, pcnoshow, ecnumber, DCNote, reason, ProvInit: string;
  OldDate, NextAppt, inrtempdt, dtPrevious: TDateTime;
  tmPrevious: Extended;
  NextAppTimeStr: String;
  Ldate, ReturnDate, lline, SiteHead, SiteAddA, SiteAddB, SiteAddC, ClinicName, ClinicPhone, TollFreePhone: string;
  SigName, SigTitle, Hloc, INRQuickOrder, CBCQuickOrder, ClinicFAX, SiteName, ListName, ConsultService: string;
  ClinicParams: TStrings;
  SimplePhoneCPT, ComplexPhoneCPT, PatientLetterCPT, InitialVisitCPT, OrientationClassCPT,
    csduz, csitem, csdft, ESIGN, EClinic, SubsequentVisitCPT: string;
  VisitClinic, PhoneClinic, NonCountClinic, SvcCat, ProvNarr, StationNumber, DSSId,
    DSSUnit, restr, ARemStr, temprge, NetworkPath, AutoPrimaryIndicationCode,
    AutoPrimaryIndicationText, AutoSecondaryIndicationCode, AutoSecondaryIndicationText: string;
  cofactor, compre: Integer;
  lowINR, highINR: single;
  LocationChanged: Boolean = false;
  HGBFlag: Boolean = false;
  CMChanging: Boolean = False;
  CTChanging: Boolean = False;
  SunTab, MonTab, TueTab, WedTab, ThuTab, FriTab, SatTab, TotTab: Single;
  SunMg, MonMg, TueMg, WedMg, ThuMg, FriMg, SatMg, TotMg: Single;

const
  BHGHT: Integer = 155;
  BLFT: Integer = 3;
  BTOP: Integer = 203;
  BWIDTH: Integer = 458;
  DCTOPHEIGHT: Integer = 102;
  MAXDOSE: Extended = 30.0; //max daily dosage

  //form create process markers
  FCP_SETHOOK = 10;         // form create about to set timeout hooks
  FCP_SERVER  = 30;         // form create about to connect to server
  FCP_CHKPT   = 40;         // form create about to check version
  FCP_PARAMS  = 50;         // form create about to create core objects
  FCP_FORMS   = 60;         // form create about to create child forms
  FCP_PTLOAD  = 70;         // form create about to select patient
  FCP_FINISH  = 99;         // form create finished successfully

implementation

uses
  Wsockc, Clipbrd, fAboutACM, VA508AccessibilityRouter, VAUtils, fPCE, fPCELex, rLex,
  fxBroker, fBridgeCommentsDialog, U_HelpMGR, System.UITypes, ORNetIntf;

{$R *.DFM}

function FilterTextPreserveLines(const aString: string): string;
begin
  // preserve line breaks, but strip anything else
  // and set tabs to be a single space
  Result := StringReplace(aString, #13#10, '^', [rfReplaceAll]);
  while (Result <> '') and (Result[Result.Length] = '^') do
    Delete(Result, Result.Length, 1);
  Result := FilteredString(Result);
end;

function dc(done: TDateTime; dtwo: TDateTime): Integer;
var
  yone, mone, day1, ytwo, mtwo, day2: word;
  rd: Integer;
begin
  rd := 0;
  DecodeDate(done, yone, mone, day1);
  DecodeDate(dtwo, ytwo, mtwo, day2);
  //SMT Protect against first INR being outside lab.
  if (ytwo = 1899) and (Length(frmAnticoagulate.lblINRdt.Caption) > 0) then
  begin
    OldDate := StrToDate(frmAnticoagulate.lblINRdt.Caption);
    DecodeDate(OldDate, ytwo, mtwo, day2);
    OldINR := frmAnticoagulate.lblINRval.Caption;
  end;
  if yone > ytwo then rd := 1;
  if ytwo > yone then rd := 2;
  if yone = ytwo then
  begin
    if mone > mtwo then rd := 1;
    if mtwo > mone then rd := 2;
    if mone = mtwo then
    begin
      if day1 > day2 then rd := 1;
      if day2 > day1 then rd := 2;
      if day1 = day2 then rd := 1;
    end;
  end;
  result := rd;
end;

procedure INRColor();
var
    cINR:single;
    lowStr: String;
    highStr: String;
begin
  if leftstr(frmAnticoagulate.lblINRval.Caption, 2) = '  ' then
    exit;  ///***diff
  if Pos('>', frmAnticoagulate.lblINRval.Caption) > 0 then
  begin
    frmAnticoagulate.pnlINR.Color := clRed;
    frmAnticoagulate.lblINRdt.Font.Color := clwhite;
    frmAnticoagulate.lblINRval.Font.Color := clwhite;
    frmAnticoagulate.lblLastINR.Font.Color := clwhite;
    exit;
  end;
  if Pos('<', frmAnticoagulate.lblINRval.Caption) > 0 then
  begin
    frmAnticoagulate.pnlINR.Color := clRed;
    frmAnticoagulate.lblINRdt.Font.Color := clwhite;
    frmAnticoagulate.lblINRval.Font.Color := clwhite;
    frmAnticoagulate.lblLastINR.Font.Color := clwhite;
    exit;
  end;
  if (length(frmAnticoagulate.lblINRval.Caption) > 0) and (frmAnticoagulate.cbxINRGoal.Text<>'') then
  begin
    if strtofloatdef(frmAnticoagulate.lblINRval.Caption, 999) = 999 then
      exit;

    // <CQ21999>
    lowStr := Piece(frmAnticoagulate.cbxINRGoal.Text, '-', 1);
    if lowStr <> '' then
      lowINR := StrToFloat(lowStr);
    highStr := Piece(frmAnticoagulate.cbxINRGoal.Text, '-', 2);
    if highStr <> '' then
      highINR := StrToFloat(highStr);
    // <CQ21999/>
    
    frmAnticoagulate.pnlINR.Color := clMoneyGreen;
    frmAnticoagulate.lblINRdt.Font.Color := clBlack;
    frmAnticoagulate.lblINRval.Font.Color := clBlack;
    frmAnticoagulate.lblLastINR.Font.Color := clBlack;
    cINR := strtofloat(frmAnticoagulate.lblINRval.Caption);
    if (cINR > highINR) OR (cINR < lowINR) then
    begin
      frmAnticoagulate.pnlINR.Color := clRed;
      frmAnticoagulate.lblINRdt.Font.Color := clWhite;
      frmAnticoagulate.lblINRval.Font.Color := clWhite;
      frmAnticoagulate.lblLastINR.Font.Color := clWhite;
    end;
  end;
end;

function CompleteConsult(): String;
begin
  if ConsultCtrl = 0 then exit;
  with frmAnticoagulate do
  begin
    var rpcResults := TStringList.Create;
    try
      CallVistA('ORAMX CONSULT', [PDFN,ConsultService], rpcResults);
      if (rpcResults.Count>0) and (rpcResults[0] <> '0') then
        lbxConsult.Items := rpcResults
      else
        lbxConsult.Items.Clear;
      if (rpcResults.Count>0) and (rpcResults[0] <> '0') then
      begin
        if InfoBox('There are pending anticoagulation consults.' + CRLF +
                   'Do you want to resolve with the same note?',
                   'Pending Consult(s)', MB_YESNO or MB_ICONQUESTION) = mrNo then
          exit
        else
          pnlConsult.Visible := true;
      end;
    finally
      rpcResults.Free;
    end;
  end;
end;

function cosigner(Title: String): String;
  var CoS, dflt, orES, orElse, orProvider: String;
begin
  //COSIGN CHECK   if CS = 1 then needs cosigner
  //cofactor = 1 NOTE,  = 2 order

  csduz := '';

  if (cofactor = 1) and (Title <> '') then
    CallVistA('TIU REQUIRES COSIGNATURE', [Title, 0, PDUZ], CoS)
  else if (cofactor = 2) then
  begin
    CallVistA('ORWU HASKEY', ['ORES'], orES);
    CallVistA('ORWU HASKEY', ['ORELSE'], orElse);
    CallVistA('ORWU HASKEY', ['PROVIDER'], orProvider);
    if (orES = '1') or ((orElse = '1') and (orProvider = '1')) then
      CoS := '0'
    else
      CoS := '1';
  end;
  if (CoS = '1') then
  begin
    CallVistA('ORWTPP GETDCOS', [], csdft);
    if csdft <> '' then
    begin
      dflt := piece(csdft, '^', 2);
      CallVistA('ORWTPP GETCOS', [UpperCase(dflt),1,''], frmCosign.lbCoSign.Items);
      frmCosign.edtCoSign.Text := dflt;
      if (dflt <> '') then
        frmCosign.lbCoSign.SelectByID(piece(csdft, '^', 1));
    end;
    if cofactor = 1 then
    begin
      frmCosign.butXCoSign.Caption := '&Cancel Note';
      frmCosign.pnlTop.Caption := 'You must choose a co-signer before signing this document.';
      frmCosign.Caption := 'Choose a Co-signer:';
    end;
    if cofactor = 2 then
    begin
      frmCosign.butXCoSign.Caption := '&Cancel Order';
      frmCosign.pnlTop.Caption := 'You must choose a Provider before placing order(s).';
      frmCosign.Caption := 'Choose a Provider for the Order(s).';
    end;
    frmCosign.ShowModal;
    //goes to cbxCoSign
  end; // cosign //submit
  result := CoS;
end;

function TfrmAnticoagulate.TimeoutCondition: boolean;
begin
  Result := (FCreateProgress < FCP_PTLOAD);
end;

function TfrmAnticoagulate.GetTimedOut: boolean;
begin
  Result := uInit.TimedOut;
end;

procedure TfrmAnticoagulate.TimeOutAction;
var
  ClosingACM: boolean;

  procedure CloseACM;
  begin
    if ClosingACM then
      halt;
    try
      ClosingACM := TRUE;
      Close;
    except
      halt;
    end;
  end;

begin
  ClosingACM := FALSE;
  try
    CloseACM;
  except
    CloseACM;
  end;
end;

function TfrmAnticoagulate.AddTop(): string;
var
  SpInNew, RiskNew, PeepNew, remind, ADate, Zero, NextDayCallBack,
  FeeDate, Indication, Bridging, BridgeComment: String;
  Z: Integer;
  StandArr: TStrings;
  aList: iORNetMult;
begin
  //package up Sp Instructions if changed
  SpInNew := '';

  RiskNew := '';
  PeepNew := '';
  if SP = 1 then
    SpInNew := FilterTextPreserveLines(memSpInE.Lines.Text);
  //package up if Risks changed
  if ChRisk = 1 then
    RiskNew := FilterTextPreserveLines(memRisk.Lines.Text);
  //package up if people to leave msg with changed
  if Peep = 1 then
    PeepNew := FilterTextPreserveLines(memPeople.Lines.Text)
  else PeepNew := '';

  //package up reminder
  if remindmsg = 1 then
  begin
    if memRemind.Lines.Count > 0 then
    begin
      remind := FilterTextPreserveLines(memRemind.Lines.Text);
      ADate := DateToStr(dtpRemind.Date);
    end;
  end //remindmsg = 1
  else
  begin
    remind := '';
    ADate := '';
  end;

  if ckbBridging.Checked then
    Bridging := '1'
  else
    Bridging := '0';

  BridgeComment := '';
  with BridgeCommentDlg.memBridgeComments do
    BridgeComment := FilterTextPreserveLines(Lines.Text);

  LabExp := ''; //DateToStr(dtpLAB.DateTime); 3/13/09 JER
  ReturnDate := DateToStr(dtpNextApp.date);
  if dtpAppTime.Visible then
  begin
    NextAppTimeStr := TimeToStr(dtpAppTime.Time);
    NextAppTimeStr := Pieces(NextAppTimeStr, ':', 1, 2) + ' ' + Piece(NextAppTimeStr, ' ', 2);
  end;

  if ckbPlusDay.Checked = true then
    NextDayCallback := '1'
  else
    NextDayCallback := '0';
  if (NextAppTimeStr <> '') then
    ReturnDate := ReturnDate + '@' + NextAppTimeStr;
  FeeDate := ''; //DateToStr(dtpExp.datetime); 3/13/09 JER
  if Piece(FeeDate,'/',3) = '2000' then
    FeeDate := '';
  if ckbDC.checked = true then
    ReturnDate := '';
  Sign := 'N';
  if ckbSA.Checked = true then
    Sign := 'Y';
  if ckbDC.Checked = true then
    cs := 2;
  Indication := cbxIndic.text + '=' + edtICD9.Text;

  Zero := PDFN + '^' + cbxINRGoal.Text + '^' + Indication + '^' + ReturnDate + '^' + edtSDate.Text + '^' + edtStop.Text + '^' + edtDur.text + '^' + Sign + '^' + edtODate.Text + '^' + IntToStr(cs) + '^' + Msg + '^' + AMMeds + '^' + FileWas + '^' + IntToStr(FB) + '^' + FeeDate + '^' + PDUZ + '^' + LabExp + '^' + ADate + '^0' + '^' + NextDayCallBack;

  StandArr := TStringList.Create;
  try
    with StandArr do
    begin
      Add(PDFN);
      Add(Zero);
      Add(SpInNew);
      Add(RiskNew);
      Add(PeepNew);
      Add(remind);
      Add(Bridging);
      Add(BridgeComment);
      Add(Piece(ClinicRef, ';', 1));
    end;
    neworNetMult(aList);
    for z := 0 to StandArr.Count - 1 do
      aList.AddSubscript([InttoStr(z)], StandArr[z]);
    CallVistA('ORAM1 ADDTOP', [aList]);
  finally
    StandArr.Free;
  end;
end;

procedure signme();
var
  EncSig,rr:string;
  aList: iORNetMult;
begin
  if EClinic = '' then
    EClinic := NonCountClinic;
  neworNetMult(aList);
  aList.AddSubscript(['1205'], EClinic);
  aList.AddSubscript(['1211'], EClinic);
  CallVistA('TIU UPDATE RECORD', [NoteNumber, aList], rr, True);
  // cvw Broker call *sometimes* returns NN^Description
  rr := Piece(rr, '^', 1);
  if StrToInt(rr) < 1 then
    InfoBox('Problem encountered assigning a cosigner.' + CRLF +
            'Please check in CPRS for the status of this note.',
            'Problem Assigning Cosigner', MB_OK or MB_ICONEXCLAMATION)
  else
  begin
    if frmAnticoagulate.edtSigDC.Text <> '' then
      EncSig := Encrypt(frmAnticoagulate.edtSigDC.Text)
    else if frmAnticoagulate.edtSig.text <> '' then
      EncSig := Encrypt(frmAnticoagulate.edtSig.text);

    CallVistA('TIU SIGN RECORD', [Notenumber,EncSig]);

    if Title = IntakeNote then
      CompleteConsult();
  end;
end;

procedure SetIndicators;
var
  i: Integer;
  rpcResults: TStringList;
begin
  //Populate Indicators Combo Box
  rpcResults := TStringList.Create;
  try
    CallVistA('ORAMSET INDICS', [VisitDate], rpcResults);
    if rpcResults[0] <> '0' then
    begin
      with frmAnticoagulate.cbxIndic do
      begin
        Items.Clear;
        for i := 0 to rpcResults.Count - 1 do
        begin
          if ((AutoPrimaryIndicationCode = '') or
             (AutoPrimaryIndicationCode <> Piece(rpcResults[i], '^', 2))) and
             ((AutoSecondaryIndicationCode = '') or
             (AutoSecondaryIndicationCode <> Piece(rpcResults[i], '^', 2))) then
            Items.Add(rpcResults[i]);
        end;
        Items.Add('Other');
      end;
    end
    else if rpcResults[0] = '0' then
    begin
      InfoBox('ORAM INDICATIONS FOR CARE Parameter is corrupt.' + CRLF + 'Contact IRM.', 'Configuration Required', MB_OK or MB_ICONSTOP);
      exit;
    end;
  finally
    rpcResults.Free;
  end;
end;

// Get parameters for Clinic Location
procedure GetParameters(ClinicLoc: string);
begin
  CallVistA('ORAMSET GET', [ClinicLoc, VisitDate], ClinicParams);

  if (ClinicParams[0] = '^^^^^^^^^^^^^^^^^') or (Piece(ClinicParams[1],'^',5) = '') then
  begin
    InfoBox('Anticoagulation Management Parameters must be set prior to using this program.',
            'Configuration Required', MB_OK or MB_ICONSTOP);
    Application.ShowMainForm := False;
    Application.Terminate;
    Exit;
  end;
  ConsultCtrl := StrToIntDEF(Piece(ClinicParams[0], '^', 12),999);
  if ConsultCtrl = 1 then
    ConsultService := Piece(ClinicParams[2], '^', 6);
  SiteHead := Piece(ClinicParams[1], '^', 5);
  SiteName := Piece(ClinicParams[0], '^', 1);
  DefaultPillStrength := StrToFloatDef(Piece(ClinicParams[1], '^', 6), 5);
  LetterINRTime := Piece(ClinicParams[1], '^', 7);
  if LetterINRTime = '' then
    LetterINRTime := '0';
  InclINRTime := (LetterINRTime = '1');
  ListName := SiteName;  ///in case site name is changed, this is the original site
  if SiteName <> '' then
    frmAnticoagulate.cbxSite.SelectByID(SiteName);
  SiteAddA := Piece(ClinicParams[0], '^', 16);
  SiteAddB := Piece(ClinicParams[0], '^', 17);
  SiteAddC := Piece(ClinicParams[0], '^', 18);
  ClinicName := Piece(ClinicParams[1], '^', 3);
  ClinicPhone := Piece(Piece(ClinicParams[1], '^', 4), '|', 1);
  TollFreePhone := Piece(ClinicParams[1],'^',8);
  ClinicFAX := Piece(Piece(ClinicParams[1], '^', 4), '|', 2);
  SigName := Piece(ClinicParams[1], '^', 1);
  SigTitle := Piece(ClinicParams[1], '^', 2);
  IntakeNote := Piece(ClinicParams[0], '^', 4);
  InterimNote := Piece(ClinicParams[0], '^', 5);
  DischargeNote := Piece(ClinicParams[0], '^', 6);
  SimplePhoneCPT := Piece(ClinicParams[0], '^', 7);
  SubsequentVisitCPT := Piece(ClinicParams[0], '^', 8);
  ComplexPhoneCPT := Piece(ClinicParams[0], '^', 9);
  InitialVisitCPT := Piece(ClinicParams[0], '^', 11);
  OrientationClassCPT := Piece(ClinicParams[0], '^', 10);
  PatientLetterCPT := Piece(ClinicParams[0], '^', 14);
  INRQuickOrder := '';
  CBCQuickOrder := '';
  VisitClinic := Piece(Piece(ClinicParams[2], '^', 1), '|', 1);
  PhoneClinic := Piece(Piece(ClinicParams[2], '^', 1), '|', 2);
  NonCountClinic := Piece(Piece(ClinicParams[2], '^', 1), '|', 3);
  StationNumber := Piece(ClinicParams[2], '^', 3);
  DSSUnit := Piece(ClinicParams[2], '^', 4);
  DSSId := Piece(ClinicParams[2], '^', 5);
  NetworkPath := Piece(ClinicParams[2], '^', 8);
  AutoPrimaryIndicationCode := Piece(ClinicParams[2], '^', 9);
  AutoPrimaryIndicationText := Piece(ClinicParams[2], '^', 10);
  frmAnticoagulate.FICD10Active := Piece(ClinicParams[2], '^', 11) = '1';
  AutoSecondaryIndicationCode := Piece(ClinicParams[3], '^', 1);
  AutoSecondaryIndicationText := Piece(ClinicParams[3], '^', 2);
  with frmAnticoagulate do
  begin
    if Piece(ClinicParams[0], '^', 13) <> '1' then
    begin
      EnableChildControls(gbxPCE, false);
      ckbNone.Checked := true;
      NonCountClinic := VisitClinic;
    end
    else
    begin
      EnableChildControls(gbxPCE, true);
      ckbNone.Checked := false;
    end;
    if Piece(ClinicParams[2], '^', 2) <> '' then
    begin
      INRQuickOrder := Piece(Piece(ClinicParams[2], '^', 2), '|', 1);
      if INRQuickOrder = '0' then
        INRQuickOrder := '';
      CBCQuickOrder := Piece(Piece(ClinicParams[2], '^', 2), '|', 2);
      if CBCQuickOrder = '0' then
        CBCQuickOrder := '';
    end;
    if INRQuickOrder = '' then
    begin
      ckbINROrder.Checked := false;
      ckbINROrder.Enabled := false;
    end;
    if CBCQuickOrder = '' then
      ckbCBC.Enabled := false;
    if InclINRTime then
    begin
      gbxReturnForINR.Width := dtpAppTime.Left + dtpAppTime.Width + 10;
      dtpAppTime.Visible := true;
      dtpAppTime.Enabled := true;
    end
    else
    begin
      dtpAppTime.Enabled := false;
      dtpAppTime.Visible := false;
      gbxReturnForINR.Width := 220;
    end;
    if AutoPrimaryIndicationCode <> '' then
    begin
      lblAutoPrimIndicCap.Visible := true;
      lblAutoPrimIndic.Caption := AutoPrimaryIndicationText;
      lblAutoPrimIndic.Visible := true;
      lblIndication.Caption := 'Add''l Indication:';
      lblICDPrim.Caption := lblIndication.Caption;
    end
    else
    begin
      lblAutoPrimIndicCap.Visible := false;
      lblAutoPrimIndic.Visible := false;
      lblIndication.Caption := 'Primary Indication:';
      if frmAnticoagulate.FICD10Active then
        lblICDPrim.Caption := 'Primary ICD-10:'
      else
        lblICDPrim.Caption := 'Primary ICD-9:';
    end;
    if AutoSecondaryIndicationCode <> '' then
    begin
      lblAutoSecIndicCap.Visible := true;
      lblAutoSecIndic.Caption := AutoSecondaryIndicationText;
      lblAutoSecIndic.Visible := true;
    end
    else
    begin
      lblAutoSecIndicCap.Visible := false;
      lblAutoSecIndic.Visible := false;
    end;
    if (NewPt = 1) then
    begin
      lblIndication.Caption := '* ' + lblIndication.Caption;
      lblIndication.Left := 233;
    end;
  end;  //frmAnticoagulate
  SetIndicators;
end;

procedure TfrmAnticoagulate.EnableChildControls(Control: TWinControl; Enable: Boolean);
var
  i: Integer;
begin
  with Control do
  begin
    //Enable/Disable Child Controls
    // DRM 10/19/2018 - Reversed order in case enabling a child component caused
    // an intercepted component to remove its static text 508 placeholder.
    // for i := 0 to ControlCount - 1 do
    for i := ControlCount - 1 downto 0 do
    begin
      Controls[i].Enabled := Enable;
    end;
    //finally, toggle the Enabled property of Control itself
    Enabled := Enable;
  end;
end;

procedure TfrmAnticoagulate.SetStaticTextTabStopTrue;
begin
  lblPname.TabStop := true;
  lblComplex.TabStop := true;
  lblSSN.TabStop := true;
  lblMSG.TabStop := true;
  lblPMsg.TabStop := true;
  lblSign.TabStop := true;
  if lblAutoPrimIndic.Visible then
    lblAutoPrimIndic.TabStop := true;
  if lblAutoSecIndic.Visible then
    lblAutoSecIndic.TabStop := true;
  lblTemp.TabStop := true;
  lblINRval.TabStop := true;
  lblINRdt.TabStop := true;
  if lblSadr1.Caption <> '' then
    lblSadr1.TabStop := true
  else
    lblSadr1.TabStop := false;
  if lblSadr2.Caption <> '' then
    lblSadr2.TabStop := true
  else
    lblSadr2.TabStop := false;
  if lblSadr3.Caption <> '' then
    lblSadr3.TabStop := true
  else
    lblSadr3.TabStop := false;
  if lblCSZ.Caption <> '' then
    lblCSZ.TabStop := true
  else
    lblCSZ.TabStop := false;
  if lblNoDraw.Caption <> '' then
  begin
    lblNoDraw.TabStop := true;
  end
  else
  begin
    lblNoDraw.TabStop := false;
  end;
  lblHfone.TabStop := true;
  lblWfone.TabStop := true;
  lbldenom.TabStop := true;
  lblPCgoal.TabStop := true;
  lblPctOfVisits.TabStop := true;
  lblRSR.TabStop := true;
  lblHCT.TabStop := true;
  lblHCTdate.TabStop := true;
  memNewPtInst.TabStop := true;
  chrtINR.TabStop := true;
  lblNewPtInst.TabStop := true;
  lblACAct.TabStop := true;
  lblComplications.TabStop := true;
  lblBleeding.TabStop := true;
  lblComplMajor.TabStop := true;
  memMinorC.TabStop := true;
  lblThrombosis.TabStop := true;
  lblRecur.TabStop := true;
  lblPtsNotAtGoal.TabStop := true;
  lblXPC.TabStop := true;
  lblBOX.TabStop := true;
  SetDosingTabOrders;
  edtTotT.TabStop := true;
  edtTotM.TabStop := true;
  lblNINRval.TabStop := true;
  lblNidate.TabStop := true;
  lblNdate.TabStop := true;
  lblNTWDval.TabStop := true;
  lblARTReminder.TabStop := true;
end;

procedure TfrmAnticoagulate.SetDosingTabOrders;
begin
  edtCMSun.TabOrder := 1;
  edtCTMon.TabOrder := 2;
  edtCMMon.TabOrder := 3;
  edtCTTue.TabOrder := 4;
  edtCMTue.TabOrder := 5;
  edtCTWed.TabOrder := 6;
  edtCMWed.TabOrder := 7;
  edtCTThu.TabOrder := 8;
  edtCMThu.TabOrder := 9;
  edtCTFri.TabOrder := 10;
  edtCMFri.TabOrder := 11;
  edtCTSat.TabOrder := 12;
  edtCMSat.TabOrder := 13;
  edtTotT.TabOrder := 14;
  edtTotM.TabOrder := 15;
end;

procedure TfrmAnticoagulate.ToggleDemVisible;
begin
  btnRemind.Visible := not btnRemind.Visible;
  chrtINR.Visible := not chrtINR.Visible;
  gbxLastHCT.Visible := not gbxLastHCT.Visible;
  gbxPC.Visible := not gbxPC.Visible;
  gbxShow.Visible := not gbxShow.Visible;
end;

function TfrmAnticoagulate.DecDig(InNum: Single): Integer;
var
  NumStr: String;
  DecPart: Integer;
begin
  NumStr := FloatToStrF(InNum, ffNumber, 6, 2);
  DecPart := StrToInt(Piece(NumStr, '.', 2));
  case DecPart of
    0: result := 0;
    1..9: result := 1;
    else
    begin
      if (DecPart mod 10 = 0) then
        result := 1
      else
        result := 2;
    end;
  end;
end;

procedure TfrmAnticoagulate.TabletsSum;
begin
  SunTab := StrToFloat(edtCTSun.text);
  MonTab := StrToFloat(edtCTMon.text);
  TueTab := StrToFloat(edtCTTue.text);
  WedTab := StrToFloat(edtCTWed.text);
  ThuTab := StrToFloat(edtCTThu.text);
  FriTab := StrToFloat(edtCTFri.text);
  SatTab := StrToFloat(edtCTSat.text);
  TotTab := SunTab + MonTab + TueTab + WedTab + ThuTab + FriTab + SatTab;
  edtTotT.Text := FloatToStrF(TotTab, ffNumber, 6, DecDig(TotTab));
end;

procedure TfrmAnticoagulate.TabletsReset;
begin
  SunTab := (StrToFloat(edtCMSun.text) / PillDose);
  edtCTSun.Text := FloatToStr(SunTab);
  MonTab := (StrToFloat(edtCMMon.text) / PillDose);
  edtCTMon.Text := FloatToStr(MonTab);
  TueTab := (StrToFloat(edtCMTue.text) / PillDose);
  edtCTTue.Text := FloatToStr(TueTab);
  WedTab := (StrToFloat(edtCMWed.text) / PillDose);
  edtCTWed.Text := FloatToStr(WedTab);
  ThuTab := (StrToFloat(edtCMThu.text) / PillDose);
  edtCTThu.Text := FloatToStr(ThuTab);
  FriTab := (StrToFloat(edtCMFri.text) / PillDose);
  edtCTFri.Text := FloatToStr(FriTab);
  SatTab := (StrToFloat(edtCMSat.text) / PillDose);
  edtCTSat.Text := FloatToStr(SatTab);
  TotTab := (SunTab + MonTab + TueTab + WedTab + ThuTab + FriTab + SatTab);
  edtTotT.Text := FloatToStrF(TotTab, ffNumber, 6, DecDig(TotTab));
end;

procedure TfrmAnticoagulate.MilligramsSum;
begin
  SunMg := StrToFloat(edtCMSun.text);
  MonMg := StrToFloat(edtCMMon.text);
  TueMg := StrToFloat(edtCMTue.text);
  WedMg := StrToFloat(edtCMWed.text);
  ThuMg := StrToFloat(edtCMThu.text);
  FriMg := StrToFloat(edtCMFri.text);
  SatMg := StrToFloat(edtCMSat.text);
  TotMg := SunMg + MonMg + TueMg + WedMg + ThuMg + FriMg + SatMg;
  edtTotM.Text := FloatToStrF(TotMg, ffNumber, 6, DecDig(TotMg));
end;

procedure TfrmAnticoagulate.MilligramsReset;
begin
  SunMg := (StrToFloat(edtCTSun.text) * PillDose);
  edtCMSun.Text := FloatToStr(SunMg);
  MonMg := (StrToFloat(edtCTMon.text) * PillDose);
  edtCMMon.Text := FloatToStr(MonMg);
  TueMg := (StrToFloat(edtCTTue.text) * PillDose);
  edtCMTue.Text := FloatToStr(TueMg);
  WedMg := (StrToFloat(edtCTWed.text) * PillDose);
  edtCMWed.Text := FloatToStr(WedMg);
  ThuMg := (StrToFloat(edtCTThu.text) * PillDose);
  edtCMThu.Text := FloatToStr(ThuMg);
  FriMg := (StrToFloat(edtCTFri.text) * PillDose);
  edtCMFri.Text := FloatToStr(FriMg);
  SatMg := (StrToFloat(edtCTSat.text) * PillDose);
  edtCMSat.Text := FloatToStr(SatMg);
  TotMg := SunMg + MonMg + TueMg + WedMg + ThuMg + FriMg + SatMg;
  edtTotM.Text := FloatToStrF(TotMg, ffNumber, 6, DecDig(TotMg));
end;

procedure TfrmAnticoagulate.GenerateIntakeNote;
var
  TabStr: String;
  DoseHeader: String;
  DoseTabs: String;
  DoseMgs: String;
  AdvEvents, lHCT: String;
  CodeSys: String;
  i: Integer;
begin
  TabStr := '   ';
  CodeSys := 'ICD-9-CM';
  if FICD10Active then
    CodeSys := 'ICD-10-CM';
  IndiText := CRLF + 'Primary Indication: ';
  if AutoPrimaryIndicationText <> '' then
  begin
    IndiText := IndiText + AutoPrimaryIndicationText;
    if AutoSecondaryIndicationText <> '' then
    begin
      IndiText := IndiText + CRLF + CRLF +
                  '  Add''l Indication: ' + AutoSecondaryIndicationText + CRLF +
                   '                    ' + cbxIndic.text + ' (' + CodeSys + ' ' + edtICD9.Text + ')' + CRLF;
    end
    else
    begin
      IndiText := IndiText + CRLF + CRLF +
                '  Add''l Indication: ' + cbxIndic.text + ' (' + CodeSys + ' ' + edtICD9.Text + ')' + CRLF;
    end;
  end
  else
    IndiText := Inditext + cbxIndic.Text + ' (' + CodeSys + ' ' + edtICD9.Text + ')' + CRLF;

  TargetT := '  INR Target Range: ' + cbxINRGoal.text;
  SevText := 'Patient is currently enrolled in the ' + SiteName;
  if not (pos('CLINIC', UpperCase(SiteName)) > 0) then
    SevText := SevText + ' Clinic.';
  //dosing info
  DoseHeader := TabStr + TabStr + 'Sun' + TabStr + 'Mon' + TabStr + 'Tue' + TabStr + 'Wed' + TabStr + 'Thu' + TabStr + 'Fri' + TabStr + 'Sat' + TabStr + TabStr + 'Tot';
  DoseTabs := 'tab' + PadString(edtCTSun.Text) + edtCTSun.Text + PadString(edtCTMon.Text) + edtCTMon.Text + PadString(edtCTTue.Text) + edtCTTue.Text + PadString(edtCTWed.Text) + edtCTWed.Text + PadString(edtCTThu.Text) + edtCTThu.Text + PadString(edtCTFri.Text) + edtCTFri.Text + PadString(edtCTSat.Text) + edtCTSat.Text + TabStr + PadString(edtTotT.Text) + edtTotT.Text;
  DoseMgs := 'mgs' + PadString(edtCMSun.Text) + edtCMSun.Text + PadString(edtCMMon.Text) + edtCMMon.Text + PadString(edtCMTue.Text) + edtCMTue.Text + PadString(edtCMWed.Text) + edtCMWed.Text + PadString(edtCMThu.Text) + edtCMThu.Text + PadString(edtCMFri.Text) + edtCMFri.Text + PadString(edtCMSat.Text) + edtCMSat.Text + TabStr + PadString(edtTotM.Text) + edtTotM.Text;
  //current INR
  CINR := '       Current INR: ' + lblINRval.Caption;
  lHCT := '          Last HCT: ';
  if HGBFlag then
    lHCT := '          Last Hgb: ';

  if (lblHCT.Caption <> '') then
  begin
    lHCT := lHCT + lblHCT.Caption;

    if (lblHCTDate.Caption <> '') then
      lHCT := lHCT + ' on ' + lblHCTDate.Caption;
  end;

  //complications
  AdvEvents := Complications;
  fstext := 'To see the anticoagulation flow sheet for this patient, go to the Reports';
  fstexta := 'Tab. Click on Anticoagulation Flowsheet.';
  Title := IntakeNote;
  lblNBox.Caption := 'Anticoagulation Start Note:';
  //build memDCnote text
  memDCnote.Lines.Add(SevText);
  memDCnote.Lines.Add(IndiText);
  if ckbIncludeRisksInNote.Checked then
  begin
    memDCnote.Lines.Add(' Secondary Indication(s)/Risks:');
    for i := 0 to memRisk.Lines.Count - 1 do
      memDCnote.Lines.Add('  ' + memRisk.Lines[i]);
  end;
  memDCnote.Lines.Add(' ');
  memDCnote.Lines.Add(TargetT);
  memDCnote.Lines.Add(CINR);
  memDCnote.Lines.Add(lHCT);
  memDCnote.Lines.Add(' ');
  //Conditionally include Pt. Instructions from Letter
  if (ckbCAInclInst.Checked or ckbMAInclInst.Checked) and (PatientInstructions.Count > 0) then
  begin
    memDCnote.Lines.Add('Patient Instructions (from Letter):');
    for i := 0 to PatientInstructions.Count - 1 do
      memDCnote.Lines.Add(PatientInstructions[i]);
    memDCNote.Lines.Add(' ');
  end;
  //Conditionally include dosing table
  if ckbTWD.Checked then
  begin
    memDCnote.Lines.Add(' Total Weekly Dose: ' + edtTotM.Text + ' mg.');
    memDCnote.Lines.Add(' ');
    memDCnote.Lines.Add('Current Dosing is (using a ' + cboPS.Text + ' mg tablet):');
    memDCnote.Lines.Add(DoseHeader);
    memDCnote.Lines.Add(DoseTabs);
    memDCnote.Lines.Add(DoseMgs);
    memDCnote.Lines.Add(' ');
  end;
  //Conditionally include Adverse Events
  if AdvEvents <> '' then
  begin
    memDCNote.Lines.Add('Complication(s):');
    //Add complications to note
    if pos('MB:', AdvEvents) > 0 then
      memDCNote.Lines.Add('  Major Bleed(s):');
    for i := 1 to DelimCount(AdvEvents, '^') do
      if pos('MB:', Piece(AdvEvents, '^', i)) > 0 then
        memDCNote.Lines.Add('    ' + Piece(Piece(AdvEvents, '^', i), ':', 2))
      else if pos('C:', Piece(AdvEvents, '^', i)) = 0 then
        memDCNote.Lines.Add('  ' + Piece(AdvEvents, '^', i));
    //Add comments to note
    if pos('C:', AdvEvents) > 0 then
      memDCNote.Lines.Add('  Comments:');
    for i := 1 to DelimCount(AdvEvents, '^') do
      if pos('C:', Piece(AdvEvents, '^', i)) > 0 then
        memDCNote.Lines.Add('    ' + Piece(Piece(AdvEvents, '^', i), ':', 2));
    memDCNote.Lines.Add(' ');
  end;
  //Remainder of note
  memDCnote.Lines.Add(fsText);
  memDCnote.Lines.Add(fsTexta);
  GeneratedNoteText := memDCnote.Lines.Text;
end;

procedure TfrmAnticoagulate.GenerateInterimNote;
var
  TabStr: string;
  i: Integer;
  AdvEvents: String;
  DoseMgs: String;
  DoseTabs: String;
  DoseHeader: String;
  FollowVerb, lHCT: String;
  CodeSys: String;
begin
  TabStr := '   ';
  CodeSys := 'ICD-9-CM';
  if FICD10Active then
    CodeSys := 'ICD-10-CM';
  if LocationChanged then
    FollowVerb := 'will now'
  else
    FollowVerb := 'continues to';
  IndiText := 'Patient ' + FollowVerb + ' be followed in the ' + SiteName;
  if not (pos('CLINIC', UpperCase(SiteName)) > 0) then
    IndiText := IndiText + ' Clinic.';
  IndiText := IndiText + CRLF + CRLF + 'Primary Indication: ';
  if AutoPrimaryIndicationText <> '' then
  begin
    IndiText := IndiText + AutoPrimaryIndicationText;
    if AutoSecondaryIndicationText <> '' then
    begin
      IndiText := IndiText + CRLF + CRLF +
                  '  Add''l Indication: ' + AutoSecondaryIndicationText + CRLF +
                   '                    ' + cbxIndic.text + ' (' + CodeSys + ' ' + edtICD9.Text + ')' + CRLF;
    end
    else
    begin
      IndiText := IndiText + CRLF + CRLF +
                '  Add''l Indication: ' + cbxIndic.text + ' (' + CodeSys + ' ' + edtICD9.Text + ')' + CRLF;
    end;
  end
  else
    IndiText := Inditext + cbxIndic.Text + ' (' + CodeSys + ' ' + edtICD9.Text + ')' + CRLF;

  TargetT := '  INR Target Range: ' + cbxINRGoal.text;
  SevText := 'Patient was started on Warfarin (Coumadin): ' + edtSDate.Text + '.';
  //dosing info
  DoseHeader := TabStr + TabStr + 'Sun' + TabStr + 'Mon' + TabStr + 'Tue' + TabStr + 'Wed' + TabStr + 'Thu' + TabStr + 'Fri' + TabStr + 'Sat' + TabStr + TabStr + 'Tot';
  DoseTabs := 'tab' + PadString(edtCTSun.Text) + edtCTSun.Text + PadString(edtCTMon.Text) + edtCTMon.Text + PadString(edtCTTue.Text) + edtCTTue.Text + PadString(edtCTWed.Text) + edtCTWed.Text + PadString(edtCTThu.Text) + edtCTThu.Text + PadString(edtCTFri.Text) + edtCTFri.Text + PadString(edtCTSat.Text) + edtCTSat.Text + TabStr + PadString(edtTotT.Text) + edtTotT.Text;
  DoseMgs := 'mgs' + PadString(edtCMSun.Text) + edtCMSun.Text + PadString(edtCMMon.Text) + edtCMMon.Text + PadString(edtCMTue.Text) + edtCMTue.Text + PadString(edtCMWed.Text) + edtCMWed.Text + PadString(edtCMThu.Text) + edtCMThu.Text + PadString(edtCMFri.Text) + edtCMFri.Text + PadString(edtCMSat.Text) + edtCMSat.Text + TabStr + PadString(edtTotM.Text) + edtTotM.Text;
  //current INR
  CINR := '       Current INR: ' + lblINRval.caption;
  lHCT := '          Last HCT: ';
  if HGBFlag then
    lHCT := '          Last Hgb: ';

  if (lblHCT.Caption <> '') then
  begin
    lHCT := lHCT + lblHCT.Caption;

    if (lblHCTDate.Caption <> '') then
      lHCT := lHCT + ' on ' + lblHCTDate.Caption;
  end;

  //complications
  AdvEvents := Complications;
  fstext := 'To see the anticoagulation flow sheet for this patient, go to the Reports';
  fstexta := 'Tab. Click on Anticoagulation Flowsheet.';
  Title := InterimNote;
  lblNBox.Caption := 'Anticoagulation Clinic Note:';
  //build memDCnote text
  memDCnote.Lines.Add(IndiText);
  if ckbIncludeRisksInNote.Checked then
  begin
    memDCnote.Lines.Add(' Secondary Indication(s)/Risks:');
    for i := 0 to memRisk.Lines.Count - 1 do
      memDCnote.Lines.Add('  ' + memRisk.Lines[i]);
  end;
  memDCnote.Lines.Add('');
  memDCnote.Lines.Add(SevText);
  memDCnote.Lines.Add(TargetT);
  memDCnote.Lines.Add(CINR);
  memDCnote.Lines.Add(lHCT);
  memDCnote.Lines.Add(' ');
  //Conditionally include Pt. Instructions from Letter
  if (ckbCAInclInst.Checked or ckbMAInclInst.Checked) and (PatientInstructions.Count > 0) then
  begin
    memDCnote.Lines.Add('Patient Instructions (from Letter):');
    for i := 0 to PatientInstructions.Count - 1 do
      memDCnote.Lines.Add(PatientInstructions[i]);
    memDCNote.Lines.Add(' ');
  end;
  //Conditionally include dosing table
  if ckbTWD.Checked then
  begin
    memDCnote.Lines.Add(' Total Weekly Dose: ' + edtTotM.Text + ' mg.');
    memDCnote.Lines.Add(' ');
    memDCnote.Lines.Add('Current Dosing is (using a ' + cboPS.Text + ' mg tablet):');
    memDCnote.Lines.Add(DoseHeader);
    memDCnote.Lines.Add(DoseTabs);
    memDCnote.Lines.Add(DoseMgs);
    memDCnote.Lines.Add(' ');
  end;
  //Conditionally include Adverse Event(s)
  if AdvEvents <> '' then
  begin
    memDCNote.Lines.Add('Complication(s):');
    //Add complications to note
    if pos('MB:', AdvEvents) > 0 then
      memDCNote.Lines.Add('  Major Bleed(s):');
    for i := 1 to DelimCount(AdvEvents, '^') do
      if pos('MB:', Piece(AdvEvents, '^', i)) > 0 then
        memDCNote.Lines.Add('    ' + Piece(Piece(AdvEvents, '^', i), ':', 2))
      else if pos('C:', Piece(AdvEvents, '^', i)) = 0 then
        memDCNote.Lines.Add('  ' + Piece(AdvEvents, '^', i));
    //Add comments to note
    if pos('C:', AdvEvents) > 0 then
      memDCNote.Lines.Add('  Comments:');
    for i := 1 to DelimCount(AdvEvents, '^') do
      if pos('C:', Piece(AdvEvents, '^', i)) > 0 then
        memDCNote.Lines.Add('    ' + Piece(Piece(AdvEvents, '^', i), ':', 2));
    memDCNote.Lines.Add(' ');
  end;
  //Remainder of note
  memDCnote.Lines.Add(fsText);
  memDCnote.Lines.Add(fsTexta);
  GeneratedNoteText := memDCnote.Lines.Text;
end;

procedure TfrmAnticoagulate.IdentifyCPT;
begin
  Proced := '';
  if (rbPhoneS.Checked = true) then
  begin
    Proced := SimplePhoneCPT;
    //Piece(SiteStr[0],'^',7);   //'99371';
    SvcCat := 'T';
  end;
  // if (rbPhoneI.Checked = true) then Proced := PhoneI;  //Piece(SiteStr[0],'^',8);   //'99372';  //check number
  if (rbPhoneC.Checked = true) then
  begin
    Proced := ComplexPhoneCPT;
    //Piece(SiteStr[0],'^',9);   //'99373';  //check number
    SvcCat := 'T';
  end;
  if (rbOVisit.Checked = true) then
    Proced := InitialVisitCPT;
  //Piece(SiteStr[0],'^',11);   //'99211';
  if rbSoffice.Checked = true then
    Proced := SubsequentVisitCPT;
  // //Piece(SiteStr[0],'^',8);
  if (rbOClass.Checked = true) then
    Proced := OrientationClassCPT;
  //Piece(SiteStr[0],'^',10);   //'99078';
  if (rbLetter.Checked = true) then
    Proced := PatientLetterCPT;
  //Piece(SiteStr[0],'^',14);   //'99371';
  if (ckbNone.Checked = true) then
    Proced := '0';
end;

// <CQ21999, CQ22001>

procedure TfrmAnticoagulate.FloatFilter(Sender: TObject; var Key: Char; digits: Integer = 2);
var
  n: Integer;
  val: Double;
  S: string;
begin
if key <> #8 then { Always let backspace through }
  begin
    if CharInSet(Key, ['0'..'9', FormatSettings.DecimalSeparator]) then
    begin
      { key is a candidate }
      with sender As TEdit do
      begin
        S:= Text;
        if SelLength > 0 then { key will replace selection }
          Delete( S, SelStart+1, SelLength );
        Insert( key, S, SelStart+1 );
        { S now has string as it would look after key is processed.
          Check if it is a valid floating point number. }
        val := StrToFloatDef(S, -1);
        if val <> -1 then
        begin
          {OK, it computes. Find the decimal point and count the
          digits after it. }
          n:= Pos( FormatSettings.decimalSeparator, S );
          if n > 0 then
            if (Length(S) - n) > digits then
            begin
              { too many digits, reject key }
              key := #0;
            end;
        end
        else
        begin
          { nope, reject key }
          key := #0;
        end;
      end;
    end
    else { key not acceptible }
    begin
      key := #0;
    end;
  end;
end;

// <CQ21999, CQ22001/>

procedure TfrmAnticoagulate.FormCreate(Sender: TObject);
var
  ServerStr: String;
  PortStr: String;
  MessageStr: String;
  TempDT, TempStr, PtStr, HCTString, TempDate, DTH, SpIn, TempCom,
  TempX: string;
  i, looper, x, r, Complex, Q, count, fsnum, mnum, rsf, cc, loop2: Integer;
  HeadArr, INRARR: TStrings;
  inrdate, temp1date: TDateTime;
  CONCATE, PtChk, drawloc, outinr, Olab, AlerText, tempnote, y, rdtemp: String;
  tempinr: single;
  DisplayInrOnChart: String; //ZZZZZZBELLC - no ">" or "<". needs to be number for the chart
  InrIndex, SerCnt: Integer; //ZZZZZZBELLC - Index on chart
  SerFound: Boolean; //ZZZZZZBELLC - Does this plot point already exist
  rpcResults: TStringList;
begin
  ServerStr := '';
  PortStr := '';
  PDFN := '';
  NextAppTimeStr := '';
  InclINRTime := False;
  PatientInstructions := TStringList.Create;
  sbxPMsg.DoubleBuffered := True;
  FTabCutWarn := False;
  FDosageWarn := False;
  IndicChanging := False;

  //initialize timeout
  FCreateProgress := FCP_SETHOOK;
  InitTimeOut(TimeoutCondition, TimeOutAction);

  //initialize RetainedRPCMax to 100 since most calls occur during FormCreate
  SetRetainedRPCMax(50);

  // connect to the server and create an option context
  FCreateProgress := FCP_SERVER;
  if not ConnectToServer('ORAM ANTICOAGULATION CONTEXT') then
  begin
    if Assigned(RPCBrokerV) then
      InfoBox(RPCBrokerV.RPCBError, 'Error', MB_OK or MB_ICONSTOP);
    Application.ShowMainForm := False;
    Application.Terminate;
    Exit;
  end;
  if TXWBWinsock(RPCBrokerV.XWBWinsock).CountWidth < 4 then
    TXWBWinsock(RPCBrokerV.XWBWinsock).CountWidth := 4;

  if not IsGUIVersionOK then
  begin
    Application.ShowMainForm := False;
    Application.Terminate;
    Exit;
  end;

  //if Pt ID passed as parameter, set PDFN
  if ParamCount > 0 then
  begin
    for i := 1 to ParamCount do
    begin
      if UpperCase(Piece(ParamStr(i), '=', 1)) = 'D' then
        PDFN := Piece(ParamStr(i), '=', 2);
    end;
  end;

  frmAnticoagulate.FormStyle := fsStayOnTop;
  AMMeds := '0';
  Msg := '0';
  Add := 0;
  loop2 := 0;
  FileAs := 'SAVE';
  SvcCat := 'A';
  ProvNarr := '';
  pcMain.ActivePage := tsDem;

  //initialize pt info
  CallVistA('ORAM PATIENT', [PDFN], PtStr);
  PDFN := Piece(PtStr, '^', 1);

  if (PDFN = '0') or (PDFN = '') then
  begin
    InfoBox('No patient selected in your name.' + CRLF +
            'Please sign into CPRS and then activate this tool.',
            'No Patient Selected', MB_OK or MB_ICONSTOP);
    Application.ShowMainForm := False;
    Application.Terminate;
    Exit;
  end;

  PtName := Piece(PtStr, '^', 2);
  lblPname.Caption := PtName + ' ';
  MessageStr := 'Anticoagulation Reminder message for ' + PtName;

  Gender := Piece(PtStr, '^', 3);
  FMNow := Piece(PtStr, '^', 5);

  //format SSN
  TempX := Piece(PtStr, '^', 6);
  Insert('-', TempX, 4);
  Insert('-', TempX, 7);
  lblSSN.Caption := TempX;

  //Return Date
  RDate :=  Piece(PtStr, '^', 7);
  SetLength(RDate, 8);

  //initialize date/time pickers
  dtpINR.DateTime := StrToDate(RDate);
  dtpComp.Date := today;

  ClinicRef := Piece(PtStr, '^', 8);
  PtLocation := ClinicRef;
  DTIME := StrToIntDef(Piece(PtStr, '^', 9), 300);
  // set the timeout to DTIME now that there is a connection
  UpdateTimeOutInterval(DTIME * 1000);  // DTIME * 1000 mSec

  VisitDate := Piece(PtStr, '^', 10);

  //Check Pt
  FCreateProgress := FCP_CHKPT;
  CallVistA('ORAM1 PTCHECK', [PDFN], PtChk);

  if StrToIntDef(PtChk, 999) = 1 then
  begin
    NewPt := 1;
    if InfoBox('Patient is NOT in Anticoagulation database.' + CRLF +
               'Add patient to file and continue?',
               'New Anticoagulation Patient', MB_YESNO or MB_ICONQUESTION) = mrNo then
    begin
      Application.ShowMainForm := False;
      Application.Terminate;
      Exit;
    end;
  end
  else if StrToIntDef(PtChk, 999) = 99 then
  begin
    InfoBox('Anticoagulation Management parameters must be set' + CRLF +
            'before patient data can be added', 'Configuration Required',
            MB_OK or MB_ICONSTOP);
    Application.ShowMainForm := False;
    Application.Terminate;
    Exit;
  end;

  //new for export
  ClinicParams := TStringList.Create;
  CallVistA('ORAM PROVIDER', [], y);
  PDUZ := Piece(y, '^', 1);
  ProvName := Piece(y, '^', 2);
  ProvInit := Piece(y, '^', 3);

  //get list of established AC Clinics
  rpcResults := TStringList.Create;
  try
    CallVistA('ORAMSET GETCLINS', [], rpcResults);

    if (rpcResults.Count > 0) and (rpcResults[0] <> '0') then
    begin
      // remove the first entry (its the count)
      rpcResults.Delete(0);

      cbxSite.Items := rpcResults;
      if cbxSite.Items.Count = 1 then
      begin
        cbxSite.ItemIndex := 0;
        ClinicRef := Piece(cbxSite.Items[0], '^', 2);
      end;
    end
    else
    begin
      InfoBox('Anticoagulation Management Parameters must be set' + CRLF +
        'prior to using this program.', 'Configuration Required',
        MB_OK or MB_ICONSTOP);
      Application.ShowMainForm := False;
      Application.Terminate;
      exit;
    end;
  finally
    rpcResults.Free;
  end;

  //call for parameters
  FCreateProgress := FCP_PARAMS;
  GetParameters(ClinicRef);

  //initialize field values on forms
  FCreateProgress := FCP_FORMS;

  CallVistA('ORAM HCT', [PDFN], HCTString);
  lblHCT.Caption := Piece(HCTString, '^', 1);
  lblHCTdate.Caption := Piece(HCTString, '^', 2);
  if (Pos('HGB', UpperCase(Piece(HCTString, '^', 3))) <> 0) or
     (Pos('HEMOGLOBIN', UpperCase(Piece(HCTString, '^', 3))) <> 0) then
  begin
     gbxLastHCT.Caption := 'Last Hgb';
     HGBFlag := true;
  end;
  //ZZZZZZBELLC - Clear the series array
  SetLength(SeriesValues, 0);

  try
    rpcResults := TStringList.Create;
    try
      CallVistA('ORAM INR', [PDFN], rpcResults);
      lstINRtemp.Items.Clear;
      if (rpcResults.Count <> 0) then
      begin
        for i := (rpcResults.Count - 1) downto 0 do
        begin
          lstINRtemp.Items.Add(rpcResults[i]);
          INR := Piece(lstINRtemp.Items[lstINRtemp.Items.count - 1], '^', 1);
          TempDate := Piece(lstINRtemp.Items[lstINRtemp.Items.count - 1], '^', 3);

          //****************************************************
          // ZZZZZZBELLC  -  12/05/12
          // Update below to stip "> and/or "<" and add to array
          //****************************************************
          DisplayInrOnChart := INR;

          if Pos('>', DisplayInrOnChart) > 0 then
            DisplayInrOnChart := Piece(DisplayInrOnChart, '>', 2);
          if Pos('<', DisplayInrOnChart) > 0 then
            DisplayInrOnChart := Piece(DisplayInrOnChart, '<', 2);

          if StrToFloatDef(DisplayInrOnChart, 999) <> 999 then
          begin
            if (StrToFloat(DisplayInrOnChart) >= 0) then     //   and (inr<= '9')
            begin
              DTH := (Piece(lstINRtemp.Items[lstINRtemp.Items.count - 1], '^', 4));
              with serINR do
              begin
                SerFound := False;
                For SerCnt := Low(SeriesValues) to High(SeriesValues) do
                begin
                   If (SeriesValues[SerCnt].SeriesDTH = DTH) and (SeriesValues[SerCnt].SeriesFloat = DisplayInrOnChart) then
                   begin
                      if SeriesValues[SerCnt].SeriesValue <> INR then
                       SeriesValues[SerCnt].SeriesValue := SeriesValues[SerCnt].SeriesValue + ' / ' + INR;
                      SerFound := True;
                   end;
                end;

                //Add to chart
                If not SerFound then
                begin
                 InrIndex := AddXY(StrToFloat(DTH), StrtoFloat(DisplayInrOnChart), TempDate);
                 //Reorder if index already exist
                 For SerCnt := Low(SeriesValues) to High(SeriesValues) do
                 begin
                  IF SeriesValues[SerCnt].SeriesIndex >= InrIndex then
                   Inc(SeriesValues[SerCnt].SeriesIndex);
                 end;

                 SetLength(SeriesValues, Length(SeriesValues) + 1);
                 SeriesValues[High(SeriesValues)].SeriesIndex := InrIndex;
                 SeriesValues[High(SeriesValues)].SeriesValue := INR;
                 SeriesValues[High(SeriesValues)].SeriesDTH := DTH;
                 SeriesValues[High(SeriesValues)].SeriesFloat := DisplayInrOnChart;
               end;

              end;
            end;
          end;  ///999
        end;// end for
      end; //end if
    finally
      rpcResults.Free;
    end;
  except
    on EBrokerError do
      InfoBox('A problem was encountered communicating with the server.',
              'Connection Error', MB_OK or MB_ICONERROR);
  end; {try}

  lblINRval.Caption := INR;
  lblINRdt.Caption := TempDate;
  if lblINRdt.Caption = '' then
    lblINRdt.TabStop := false;

  //Pt Address
  CallVistA('ORAM3 PTADR', [PDFN], TempStr);
  lblSadr1.Caption := Piece(TempStr, '^', 1) + ' ';
  lblSadr2.Caption := Piece(TempStr, '^', 2) + ' ';
  lblSadr3.Caption := Piece(TempStr, '^', 3) + ' ';
  if ((Piece(TempStr, '^', 4) <> '') or (Piece(TempStr, '^', 5) <> '') or (Piece(TempStr, '^', 6) <> '')) then
    lblCSZ.Caption := Piece(TempStr, '^', 4) + ',  ' + Piece(TempStr, '^', 5) + '  ' + Piece(TempStr, '^', 6) + ' '
  else
    lblCSZ.Caption := '';
  if lblSadr2.Caption = ' ' then
  begin
    lblSadr2.Caption := lblSadr3.Caption;
    lblSadr3.Caption := '';
  end;
  if lblSadr2.Caption = ' ' then
  begin
    lblSadr2.Caption := lblCSZ.Caption ;
    lblCSZ.Caption := '';
  end;
  if Piece(TempStr,'^',7) = '1' then
    InfoBox('Patient has a ''Bad Address Indicator'' flag.' + CRLF +
            'Please confirm his/her contact information and' + CRLF +
            'correct it if necessary.', 'Bad Address Indicator',
            MB_OK or MB_ICONEXCLAMATION);
  if Piece(TempStr,'^',8) = '.121' then
    gbxContactInfo.Caption := 'TEMPORARY address:';

  CallVistA('ORAM3 PTFONE', [PDFN], TempStr);
  lblHfone.Caption := lblHfone.Caption + ' ' + Piece(TempStr, '^', 1) + ' ';
  lblWfone.Caption := lblWfone.Caption + ' ' + Piece(TempStr, '^', 2) + ' ';

  //load patient data
  FCreateProgress := FCP_PTLOAD;
  if NewPt <> 1 then
  begin
    AlerText := '';
    HeadArr := TStringList.Create;
    try
      CallVistA('ORAM1 ACDATA', [PDFN, VisitDate], HeadArr);
      BridgeComments := TStringList.Create;
      x := 2;
      for r := 5 downto 0 do
      begin
        if r = 5 then
        begin
          ckbBridging.Checked := (Piece(HeadArr[r], '^', 1) = '1');
        end;
        while Piece(HeadArr[r], '^', x) <> '' do
        begin
          if r = 0 then memSpInE.lines.Add(Piece(HeadArr[r], '^', x))
          else if r = 1 then memRisk.Lines.Add(Piece(HeadArr[r], '^', x))
          else if r = 2 then memPeople.Lines.Add(Piece(HeadArr[r], '^', x))
          else if r = 4 then
          begin
            memRemind.Lines.Add(Piece(HeadArr[r], '^', x));
            AlerText := AlerText + ' ' + Piece(HeadArr[r], '^', x);
          end
          else if r = 5 then
          begin
            ckbBridgeComments.Visible := true;
            BridgeComments.Add(Piece(HeadArr[r], '^', x));
          end;

          x := x + 1;
        end;
        x := 2;
        if r = 3 then
        begin
          if Piece(HeadArr[3], '^', 2) <> '' then
          begin
            cbxINRGoal.Text := Piece(HeadArr[3], '^', 2);
            chrtINR.Title.Text[0] := 'INR  (Goal: ' + Piece(HeadArr[3], '^', 2) + ')';
          end;
          if Piece(HeadArr[3], '^', 3) <> '' then
          begin
            cbxIndic.SetTextAutoComplete(Piece(Piece(HeadArr[3], '^', 3), '=', 1));
            if edtICD9.Text = '' then
              edtICD9.Text := Piece(Piece(HeadArr[3], '^', 3), '=', 2);
          end;
          if Piece(HeadArr[3], '^', 4) <> '' then
          begin
            NextAppt := StrToDateTime(Piece(HeadArr[3], '^', 4));
            dtpNextApp.DateTime := NextAppt;
            if InclINRTime and (TimeOf(NextAppt) <> 0) then
              dtpAppTime.Time := TimeOf(NextAppt);
          end;
          if Piece(HeadArr[3], '^', 5) <> '' then
            edtSDate.Text := Piece(HeadArr[3], '^', 5);
          if Piece(HeadArr[3], '^', 6) <> '' then
            edtStop.Text := Piece(HeadArr[3], '^', 6);
          if edtStop.Text = 'Indefinite' then
            ckbNoStop.Checked := true;
          if edtStop.Text = 'Inactive' then
          begin
            ckbDC.Checked := true;
            lblComplex.Caption := 'Inactive Patient';
          end;
          if Piece(HeadArr[3], '^', 7) <> '' then
            edtDur.Text := Piece(HeadArr[3], '^', 7);
          if Piece(HeadArr[3], '^', 8) <> '' then
          begin
            SA := Piece(HeadArr[3], '^', 8);
            if SA = 'Y' then
              ckbSA.Checked := true
            else if SA = 'N' then
              lblSign.Caption := 'NO signed agreement.';
          end;

          if Piece(HeadArr[3], '^', 9)<>'' then
            edtODate.Text := (Piece(HeadArr[3], '^', 9));
          if (Piece(HeadArr[3], '^', 10) <> '') then   //  or (Piece(HeadArr[3],'^',10)<'1')
          begin
            Complex := StrToInt(Piece(HeadArr[3], '^', 10));
            if Complex = 0 then
            begin
              lblComplex.Visible := false;
              rbStand.checked := true;
              cs := 0;
            end
            else if Complex = 1 then
            begin
              lblComplex.Visible := true;
              rbComp.Checked := true;
              cs := 1;
              oldcs := 1;
            end
            else if Complex = 2 then
            begin
              lblComplex.caption := 'Inactive Patient';
              lblComplex.visible := true;
              if rbComp.Checked = true then
                rbComp.Checked := false;
              if rbStand.Checked = true then
                rbStand.Checked := false;
              dtpNextApp.visible := false;
              gbxReturnForINR.visible := false;
              ckbDC.checked := true;
              cs := 2;
            end;
          end;  //if no piece 10
          if Piece(HeadArr[3], '^', 11) <> '' then
          begin
            FMsg := StrToInt(Piece(HeadArr[3], '^', 11));
            if FMsg = 2 then
            begin
              ckbMsg.Checked := true;
              btnCUpdate.Click;
            end;
          end;
          if Piece(HeadArr[3], '^', 12) <> '' then
          begin
            Meds := StrToInt(Piece(HeadArr[3], '^', 12));
            if Meds = 1 then
            begin
              ckbAMmeds.Checked := true;
              btnCUpdate.Click;
            end;
          end;
          if Piece(HeadArr[3], '^', 13) <> '' then
            FileWas := Piece(HeadArr[3], '^', 13);
          if Piece(HeadArr[3], '^', 14) <> '' then
            FB := StrToInt(Piece(HeadArr[3], '^', 14));
          if FB = 0 then
            rbFeeNo.Checked := true
          else if FB = 1 then
            rbFeePrim.Checked := true
          else if FB = 2 then
            rbFeeSec.Checked := true;
          if Piece(HeadArr[3], '^', 15) <> '' then
            dtpExp.DateTime := StrToDate(Piece(HeadArr[3], '^', 15));
          if Piece(HeadArr[3], '^', 17) <> '' then
            dtpLab.DateTime := StrToDate(Piece(HeadArr[3], '^', 17));
          if Piece(HeadArr[3], '^', 18) <> '' then
          begin
            dtpRemind.DateTime := StrToDate(Piece(HeadArr[3], '^', 18));
            btnRemind.Caption := 'View &Reminder';
            remindmsg := 1;
            if CompareDate(dtpRemind.Date, Today) < 1 then
            begin
              ARemStr := MessageStr + ': ' + #13#10 + AlerText;
              remindmsg := 2;
            end;
          end;
          if Piece(Piece(HeadArr[3], '^', 19), '|', 1) = '1' then
          begin
            tempnote := Piece(Piece(HeadArr[3], '^', 19), '|', 2);
            Infobox('Chart for ' + PtName +' not accessible; in use by ' + tempnote +
                    '.', 'Chart Unavailable', MB_OK or MB_ICONSTOP);
            Application.ShowMainForm := False;
            Application.Terminate;
            Exit;
          end;
          //new 1/07
          if Piece(HeadArr[3], '^', 21) <> '' then
          begin
            rdtemp := Piece(HeadArr[3], '^', 21);
            if Pos('1', rdtemp) > 0 then
            begin
              ckbRM.Checked := true;
              lblNoDraw.Caption := 'Mon';
            end;
            if Pos('2', rdtemp) > 0 then
            begin
              ckbRT.Checked := true;
              lblNoDraw.Caption := lblNoDraw.Caption + ' Tues';
            end;
            if Pos('3', rdtemp) > 0 then
            begin
              ckbRW.Checked := true;
              lblNoDraw.Caption := lblNoDraw.Caption + ' Wed';
            end;
            if Pos('4', rdtemp) > 0 then
            begin
              ckbRTh.Checked := true;
              lblNoDraw.Caption := lblNoDraw.Caption + ' Thur';
            end;
            if Pos('5', rdtemp) > 0 then
            begin
              ckbRF.Checked := true;
              lblNoDraw.Caption := lblNoDraw.Caption + ' Fri';
            end;
            RESTR := Piece(HeadArr[3], '^', 21);
            pnlNoDraw.Visible := true;
            btnROK.Width := 50;
            btnROK.Caption := '&Revise';
            pnlRestrict.Visible := true;
          end;       //END NEW SECTION
        end; // r = 3
      end;      //for loop
    finally
      HeadArr.Free;
    end;  // end try
    tempnote := PDFN + '^' + PDUZ;
    CallVistA('ORAM1 LOCK', [tempnote]);
    if memPeople.Lines[0] <> '' then
    begin
      ckbPmsg.Checked := true;
      btnCUpdate.Click;
    end;

    rpcResults := TStringList.Create;
    try
      CallVistA('ORAM1 FLOWTT', [PDFN], rpcResults);
      FlowArr := TStringList.Create;                       //set lines
      //GETS FS COUNT THEN ZERO NODE THEN COMMENT ARRAY
      SetLength(CommArr, (rpcResults.Count));
      SetLength(CompArr, (rpcResults.Count));
      SetLength(fsduz, (rpcResults.Count));
      outinr := '^';
      Q := 0;
      fsnum := 0;
      FSien := '0';
      while Q <= (rpcResults.Count - 1) do
      begin
        FlowArr.Add(rpcResults[Q]);
        if Piece(FlowArr[fsnum],'^',2) <> '' then
        begin
          if StrToInt(FSien) < StrToIntdef(Piece(FlowArr[fsnum], '^', 2), -1) then
          begin
            FSien := Piece(FlowArr[fsnum], '^', 2);
            ienmax := fsnum;
          end;
        end;
        if (Piece(FlowArr[fsnum],'^',3) <> '') and ((Piece(FlowArr[fsnum],'^',4) <> 'PVAMC') or
          (Piece(FlowArr[fsnum],'^',4) <> 'VAMC')) then
        begin
          temp1date := StrToDate(Piece(Piece(FlowArr[fsnum], '^', 1), '|', 2));
          if MonthsBetween(now,temp1date) < 6 then
            outinr := outinr + '^' + Piece(FlowArr[fsnum],'^',3) + '^' + Piece(Piece(FlowArr[fsnum], '^', 1), '|', 2);
        end;
        stgAC.RowCount := rpcResults.Count;
        Comments := TStringList.Create;
        CmpTxt := TStringList.Create;
        if Piece(FlowArr[fsnum], '|', 1) <> '' then
        begin
          Looper := StrToIntDef(Piece(Piece(FlowArr[fsnum], '|', 1), ',', 1), 0);
          if Looper <> 0 then
          begin
            for x := 1 to Looper do
              Comments.Add(rpcResults[Q + x])
          end
          else if Looper = 0 then
            Comments.Add('none');
          Q := Q + Looper;
          CommArr[fsnum] := Comments;
          //NEW       8/08      complications
          loop2 := StrToIntDEF(Piece(Piece(FlowArr[fsnum], '|', 1), ',', 2), -1);
          if loop2 > 0 then
          begin
            for x := 1 to loop2 do
              CmpTxt.Add(rpcResults[Q + x])
          end;
          CompArr[fsnum] := CmpTxt;

          //END NEW
          fsduz[fsnum] := Piece(FlowArr[fsnum], '^', 10);
        end;

        with stgAC do
        begin
          Cells[0,0] := 'INR date';
          Cells[1,0] := 'INR';
          Cells[2,0] := 'Pt Notice';
          Cells[3,0] := 'TWD';
          Cells[4,0] := 'Comp';
          Cells[0,(fsnum + 1)] := Piece(Piece(FlowArr[fsnum], '^', 1), '|', 2);
          Cells[1,(fsnum + 1)] := Piece(FlowArr[fsnum], '^', 3);
          Cells[2,(fsnum + 1)] := Piece(FlowArr[fsnum], '^', 8);
          Cells[3,(fsnum + 1)] := Piece(FlowArr[fsnum], '^', 6);
          if loop2 > 0 then
            Cells[4,(fsnum + 1)] := ' *';
        end;

        if loop2 > 0 then
          Q := Q + loop2 + 1
        else
          Q := Q + 1;
        fsnum := fsnum + 1;
      end;   //for loop
      FSNUM := FSNUM - 1;
      if fsnum > 8 then
        stgAC.TopRow := fsnum - 6;
      if Piece(FlowArr[fsnum], '^', 4) = '' then
        edtLoc.Text := ''
      else
      begin
        Olab := Piece(FlowArr[fsnum], '^', 4);
        drawloc := Piece(Olab, '|', 1);
        if Piece(Olab, '|', 2) <> '' then
          edtLPhone.Text := Piece(Olab, '|', 2);
        if Piece(Olab, '|', 3) <> '' then
          edtLFax.Text := Piece(Olab, '|', 3);
        if ((drawloc = 'PVAMC') or (drawloc = 'VAMC')) then
          edtLoc.Text := ''
        else  //if (drawloc<>'VAMC') then
        begin
          edtLoc.Text := drawloc;
          pcInfo.ActivePage := tsOLD;
        end;
      end;
    finally
      rpcResults.Free;
    end;

    if Piece(FlowArr[fsnum], '^', 7) <> '' then
    begin
      TempDose := Piece(FlowArr[fsnum], '^', 7);
      edtCMSun.Text := Piece(TempDose, '|', 1);
      if edtCMSun.Text < '0' then
        edtCMSun.Text := '0';
      edtCMMon.Text := Piece(TempDose, '|', 2);
      if edtCMMon.Text < '0' then
        edtCMMon.Text := '0';
      edtCMTue.Text := Piece(TempDose, '|', 3);
      if edtCMTue.Text < '0' then
        edtCMTue.Text := '0';
      edtCMWed.Text := Piece(TempDose, '|', 4);
      if edtCMWed.Text < '0' then
        edtCMWed.Text := '0';
      edtCMThu.Text := Piece(TempDose, '|', 5);
      if edtCMThu.Text < '0' then
        edtCMThu.Text := '0';
      edtCMFri.Text := Piece(TempDose, '|', 6);
      if edtCMFri.Text < '0' then
        edtCMFri.Text := '0';
      edtCMSat.Text := Piece(TempDose, '|', 7);
      if edtCMSat.Text < '0' then
        edtCMSat.Text := '0';
      edtTotM.Text := FloatToStr(StrToFloat(edtCMSun.Text) + StrToFloat(edtCMMon.Text) + StrToFloat(edtCMTue.Text) + StrToFloat(edtCMWed.Text) + StrToFloat(edtCMThu.Text) + StrToFloat(edtCMFri.Text) + StrToFloat(edtCMSat.Text));
      //calculates tablets based on mg and pilldose
      if ((Piece(FlowArr[fsnum], '^', 5) = '') or (Piece(FlowArr[fsnum], '^', 5) = '0')) then
        PillDose := DefaultPillStrength
      else
        PillDose := StrToFloat(Piece(FlowArr[fsnum], '^', 5));
      cboPS.SelectByID(FloatToStr(PillDose));
      if cboPS.Text = '' then
        cboPS.Text := FloatToStr(PillDose);
      TabletsReset;
    end
    else
    begin
      edtCTSun.Text := '1';
      edtCTMon.Text := '1';
      edtCTTue.Text := '1';
      edtCTWed.Text := '1';
      edtCTThu.Text := '1';
      edtCTFri.Text := '1';
      edtCTSat.Text := '1';
      edtTotT.Text := '5';
      if Piece(FlowArr[fsnum], '^', 5) = '' then
        PillDose := DefaultPillStrength
      else
      begin
        PillDose := StrToFloat(Piece(FlowArr[fsnum], '^', 5));
        PillDoseOr := PillDose;
      end;
      cboPS.SelectByID(FloatToStr(PillDose));
      if cboPS.Text = '' then
        cboPS.Text := FloatToStr(PillDose);
      MilligramsReset;
      gbxDailyDosing.Caption := 'Suggested Daily Dosing';
    end;

    if Piece(FlowArr[fsnum], '^', 13) <> '' then
      tempnoshow := (Piece(FlowArr[fsnum], '^', 13));             //FSNUM-1
    if FileWas = 'TEMPSAVE' then
    begin
      pcMain.ActivePage := tsInfo;
      pnlNComm.Visible := true;
      btnNEntry.Visible := true;
      if tempnoshow <> '' then
        noshow := StrToInt(tempnoshow);
      lblFSentry.Caption := 'Flow Sheet Entry in Progress:';
      if CommArr[ienmax] <> nil then
      begin
        memNCom.Lines := CommArr[ienmax];     //[fsnum-1]
        mnum := memNCom.Lines.Count;
        memNCom.Lines[mnum - 1] := '';
      end;
      lblTemp.Visible := true;
      if (drawloc <> '') and (drawloc <> 'VAMC') then
      begin
        edtLoc.Text := drawloc;
        if Piece(Olab, '|', 2) <> '' then
          edtLPhone.Text := Piece(Olab, '|', 2);
        if Piece(Olab, '|', 3) <> '' then
          edtLFax.Text := Piece(Olab, '|', 3);
        if Piece(FlowArr[fsnum], '^', 3) <> '' then
        begin
          edtNewInr.Text := Piece(FlowArr[ienmax], '^', 3);
          dtpINR.DateTime := StrToDate(Piece(Piece(FlowArr[ienmax], '^', 1), '|', 2));
        end;
      end;
      //Never set a new HCT, always leave it blanks, but always save an entry.
      //if Piece(FlowArr[fsnum], '^', 14) <> '' then
      //  edtNewHCT.Text := Piece(Piece(FlowArr[ienmax], '^', 14),'|',1);
      edtPtNote.Text := Piece(FlowArr[ienmax], '^', 8);
    end;
  end; //if NewPt<>1

  if NewPt = 1 then
  begin
    pcMain.ActivePage := tsDem;
    sbxComm.Visible := False;
    pnlNComm.Visible := TRUE;
    cbxIndic.Color := clYellow;
    if pos('*', lblIndication.Caption) = 0 then
    begin
      lblIndication.Caption := '* ' + lblIndication.Caption;
      lblIndication.Left := 233;
    end;
    cbxINRGoal.Color := clYellow;
    lblINRGoal.Caption := '* ' + lblINRGoal.Caption;
    lblINRGoal.Left := lblINRGoal.Left - 7;
    cbxSite.Color := clYellow;
    lblSiteName.Caption := '* ' + lblSiteName.Caption;
    lblSiteName.Left := lblSiteName.Left - 7;
    edtODate.Color := clYellow;
    lblOrientationDate.Caption := '* ' + lblOrientationDate.Caption;
    lblOrientationDate.Left := lblOrientationDate.Left - 7;
    edtDur.Color := clYellow;
    btnSExit.Enabled := false;
    btnFileC.Enabled := false;
    lblDuration.Caption := '* ' + lblDuration.Caption;
    lblDuration.Left := lblDuration.Left - 7;
    rbStand.Color := clYellow;
    rbStand.Caption := '* ' + rbStand.Caption;
    rbStand.Checked := true;
    rbComp.Color := clYellow;
    rbComp.Caption := '* ' + rbComp.Caption;
    rbComp.Checked := false;
    edtSig.Color := clYellow;
    lblESig.Caption := '* ' + lblESig.Caption;
    lblESig.Left := lblESig.Left - 7;
    cboPS.Color := clYellow;
    lblPillStrength.Caption := '* ' + lblPillStrength.Caption;
    pnlNewPt.Visible := true;
    dtpNextApp.Color := clYellow;
    gbxReturnForINR.Caption := '* ' + gbxReturnForINR.Caption;
    ckbTWD.Checked := false;
    dtpNextApp.DateTime := StrToDate(RDate);
    edtODate.Text := (RDate);
    edtSDate.Text := RDate;
    edtCTSun.Text := '1';
    edtCTMon.Text := '1';
    edtCTTue.Text := '1';
    edtCTWed.Text := '1';
    edtCTThu.Text := '1';
    edtCTFri.Text := '1';
    edtCTSat.Text := '1';
    edtTotT.Text := '5';
    PillDose := DefaultPillStrength;
    cboPS.SelectByID(FloatToStr(PillDose));
    if cboPS.Text = '' then
      cboPS.Text := FloatToStr(PillDose);
    MilligramsReset;
    gbxDailyDosing.Caption := 'Suggested Daily Dosing';
    memSpInE.Lines[0] := TrimRight(lblHfone.Caption) + ';  ' + TrimRight(lblWfone.Caption);
    ToggleDemVisible;
  end;
  if Gender = 'M' then
    Greet := 'Mr. ';
  if Gender = 'F' then
    Greet := 'Ms. ';
  GName := Greet + Piece(PtName, ',', 2) + ' ' + Piece(PtName, ',', 1);
  rpcResults := TStringList.Create;
  try
    INRARR := TStringList.Create;
    try
      CallVistA('ORAM1 OUTINR', [outinr], rpcResults);
      count := 0;
      try
        if (rpcResults.Count <> 0) then
        begin
          for i := (rpcResults.Count - 1) downto 0 do
          begin
            INRARR.Add(rpcResults[i]);
            INR := Piece(INRARR[count], '^', 1);

            //****************************************************
            // ZZZZZZBELLC  -  12/05/12
            // Update below to stip "> and/or "<" and add to array
            //****************************************************
            DisplayInrOnChart := INR;

            TempDate := Piece(INRARR[count], '^', 3);
            DTH := Piece(INRARR[count], '^', 2);
            if DisplayInrOnChart <> '' then
            begin
              if Pos('>', DisplayInrOnChart) > 0 then
               DisplayInrOnChart := Piece(DisplayInrOnChart, '>', 2);
              if Pos('<', DisplayInrOnChart) > 0 then
               DisplayInrOnChart := Piece(DisplayInrOnChart, '<', 2);

              if strtofloatdef(DisplayInrOnChart,999)<>999 then
              begin
                if strtofloat(DisplayInrOnChart) > 7 then
                  chrtINR.LeftAxis.Maximum := strtofloat(DisplayInrOnChart);

                with serINR do
                begin
                  SerFound := False;
                  For SerCnt := Low(SeriesValues) to High(SeriesValues) do
                  begin
                     If (SeriesValues[SerCnt].SeriesDTH = DTH) and (SeriesValues[SerCnt].SeriesFloat = DisplayInrOnChart) then
                     begin
                        if SeriesValues[SerCnt].SeriesValue <> INR then
                         SeriesValues[SerCnt].SeriesValue := SeriesValues[SerCnt].SeriesValue + ' / ' + INR;
                        SerFound := True;
                     end;
                  end;

                  //Add to chart
                  If not SerFound then
                  begin
                   InrIndex := AddXY(StrToFloat(DTH), StrtoFloat(DisplayInrOnChart), TempDate);
                   //Reorder if index already exist
                   For SerCnt := Low(SeriesValues) to High(SeriesValues) do
                   begin
                    IF SeriesValues[SerCnt].SeriesIndex >= InrIndex then
                     Inc(SeriesValues[SerCnt].SeriesIndex);
                   end;

                   SetLength(SeriesValues, Length(SeriesValues) + 1);
                   SeriesValues[High(SeriesValues)].SeriesIndex := InrIndex;
                   SeriesValues[High(SeriesValues)].SeriesValue := INR;
                   SeriesValues[High(SeriesValues)].SeriesDTH := DTH;
                   SeriesValues[High(SeriesValues)].SeriesFloat := DisplayInrOnChart;
                 end;

                end;
              end; //999
            end; //if inr
            count := count + 1;
          end;// end i for
          INR := Piece(INRARR[0], '^', 1);
          TempDate := Piece(INRARR[0], '^', 3);
          if Length(INR) > 0 then
          begin
            inrtempdt := StrToDate(TempDate);
            if Length(lblINRdt.caption) < 1 then
            begin
              lblINRdt.Caption := TempDate;
              lblINRval.Caption := INR;
            end
            else if Length(lblINRdt.caption) > 0 then
              ResultDay := dc(StrToDate(lblINRdt.caption), inrtempdt);

            if ResultDay = 2 then
            begin
              lblINRdt.Caption := TempDate;
              lblINRval.Caption := INR;
            end;
          end;
        end; //end if
      except
        on EBrokerError do
          InfoBox('A problem was encountered communicating with the servers.',
                  'Connection Error', MB_OK or MB_ICONERROR);
      end; {try}
    finally
      INRARR.Free;
    end;
  finally
    rpcResults.Free;
  end;

  CallVistA('ORAM1 PCGOAL', [PDFN, '1'], pcgoal);
  lblPCgoal.Caption := Piece(pcgoal, '^', 1) + '%';
  lbldenom.Caption := 'of ' + Piece(pcgoal, '^', 2) + ' INR values:';
  btnNEntry.Click;
  CallVistA('ORAM2 SHOWRATE', [PDFN], pcnoshow);
  if Piece(pcnoshow,'^',1) = '' then
  begin
    lblRSR.Caption := 'None';
    lblPctOfVisits.Caption := '';
  end
  else
  begin
    lblRSR.Caption := Piece(pcnoshow, '^', 1) + '%';
    lblPctOfVisits.Caption := 'of '+ Piece(pcnoshow, '^', 2) + ' visits:';
  end;
  if cbxINRGoal.Text <> '' then
    INRColor();

  if (NextAppt = 0) then
    btnMA.Enabled := false;

  if ScreenReaderActive then
    SetStaticTextTabStopTrue;

  frmAnticoagulate.BringToFront;

  //FormCreate Process Complete
  FCreateProgress := FCP_FINISH;
end;


procedure TfrmAnticoagulate.gbxINRsetExit(Sender: TObject);
begin
  with gbxINRSet do
    if visible then
      edtMin.SetFocus;
end;

//end oncreate  section (***** needs refactoring for next national release)


procedure TfrmAnticoagulate.cbxINRGoalChange(Sender: TObject);
begin
  if cbxINRGoal.ItemIndex = 3 then
  begin
    temprge := cbxINRGoal.Text;
    gbxINRset.Visible := true;
    edtMin.SetFocus;
    gbxContactInfo.Visible := false;
  end;
  chrtINR.Title.Text[0] := 'INR  (Goal: ' + cbxINRGoal.Text + ')';
  lblPCgoal.Enabled := false;
end;

procedure TfrmAnticoagulate.btnDDClick(Sender: TObject);
begin
  if btnDD.Caption = 'Change &daily dosing' then
  begin
//    with frmAnticoagulate do
//    begin
//      edtTotM.Text := FloatToStr(StrToFloat(edtCMSun.Text)+StrToFloat(edtCMMon.Text)+StrToFloat(edtCMTue.Text)+StrToFloat(edtCMWed.Text) +StrToFloat(edtCMThu.Text) + StrToFloat(edtCMFri.Text) + StrToFloat(edtCMSat.Text));
//      TabletsReset;
//    end;
    Add := 1;
    cdose := 0;
    btnCanDose.Visible := true;
    edtCTSat.Enabled := True;
    edtCTFri.Enabled := True;
    edtCTSun.Enabled := True;
    edtCTMon.Enabled := True;
    edtCTTue.Enabled := True;
    edtCTWed.Enabled := True;
    edtCTThu.Enabled := True;
    edtCMSun.Enabled := True;
    edtCMMon.Enabled := True;
    edtCMTue.Enabled := True;
    edtCMWed.Enabled := True;
    edtCMThu.Enabled := True;
    edtCMFri.Enabled := True;
    edtCMSat.Enabled := True;
    cboPS.Enabled := False;
    edtCTSun.SetFocus;
    gbxDailyDosing.Caption := 'New Daily Dosing';
    edtTotT.Enabled := ScreenReaderSystemActive;
    edtTotM.Enabled := ScreenReaderSystemActive;
    btnDD.Caption := '&OK';
  end
  else
  begin
    Add := 0;
    cdose := 1;
    btnCanDose.Visible := false;
    edtCTSat.Enabled := false;
    edtCTFri.Enabled := false;
    edtCTSun.Enabled := false;
    edtCTMon.Enabled := false;
    edtCTTue.Enabled := false;
    edtCTWed.Enabled := false;
    edtCTThu.Enabled := false;
    edtCMSun.Enabled := false;
    edtCMMon.Enabled := false;
    edtCMTue.Enabled := false;
    edtCMWed.Enabled := false;
    edtCMThu.Enabled := false;
    edtCMFri.Enabled := false;
    edtCMSat.Enabled := false;
    edtTotT.Enabled := false;
    edtTotM.Enabled := false;
    cboPS.Enabled := True;
    gbxDailyDosing.Caption := 'New Daily Dosing';
    btnDD.Caption := 'Change &daily dosing'
  end;
end;

procedure TfrmAnticoagulate.btnCompClick(Sender: TObject);      //PREPARES AND SENDS DATA; CLOSES FORM
var
  CommNew, FSEntry, loc, DD, cstest, ProvDUZ, CodeSys: String;
  ECHzero, plusday, missed, DTEXT, HCT, bleed, ListIdentified, p6: String;
  CommtArr: TStrings;
  x, dtest: Integer;
  aList: iORNetMult;
begin
  cofactor := 0;  //new 11/06 to allow cosign to be used for ordering as well
  ///EXIT SECTION ONE DOES CHECKS PRIOR TO EXITING             //changed code to not allow callback change on TEMPSAVE

  //checks if callback is in past (ignored if temp save or DC entry)
  if (CompareDate(dtpNextApp.Date,today)<0) and (FileAs<>'TEMPSAVE') and (ckbDC.checked = false) then
  begin
    if (lblINRdt.Caption = '') or (noshow = 3) then
    begin
      if InfoBox('Record as missed appointment?',
                 'Possible No Show', MB_YESNO or MB_ICONQUESTION) = mrYes then
        noshow := 3
      else
        noshow := 0;
      if lblINRdt.Caption = '' then
        lblINRdt.TabStop := false;
    end;
    InfoBox('The next lab draw date of ' + DateToStr(dtpNextApp.Date) + ' is NOT a future date.' + CRLF +
            'Please adjust it to complete the update.', 'Invalid Date', MB_OK or MB_ICONEXCLAMATION);
    exit;
  end;     //past date
  if (CompareDate(dtpNextApp.Date,NextAppt) = 0) and (FileAs<>'TEMPSAVE') then  //if future call back date has not been changed, ask if that is OK
  begin
    if InfoBox('The next lab draw date of ' + DateToStr(dtpNextApp.Date) + ' has not been changed.' + CRLF +
               'If it is incorrect, click NO and change the date' + CRLF + 'before completing the visit.',
               'Draw Date Not Changed', MB_YESNO or MB_ICONQUESTION) = mrNo then
    exit;
  end;
  if (FileAs = 'TEMPSAVE') and (CompareDate(dtpNextApp.Date,today)>0) then
  begin
    dtpNextApp.Date := TODAY;
    InfoBox('Next appointment date is set to TODAY on a temporary save.',
            'Next Appointment Date', MB_OK or MB_ICONEXCLAMATION);
  end;
  if memNCom.Lines.Count = 0 then
  begin
    if InfoBox('There are no comments listed.  Do you want to file remaining flowsheet data?',
      'No Comments Listed', MB_YESNO or MB_ICONQUESTION) = mrNo then
      exit;
  end;
  if lblINRdt.Caption <> '' then
  begin
    dtest := DaysBetween(StrToDate(lblINRdt.Caption), NextAppt);  //nextappt is the last appt, when they were to return for the next draw
    if dtest = 0 then
      noshow := 0
    else if dtest = 1 then
      noshow := 1
    else if dtest > 1 then
      noshow := 2;
  end;
  if cbxSite.Text = '' then
  begin
    InfoBox('Must indicate the Clinic which is following this patient.',
            'No Clinic Selected', MB_OK or MB_ICONEXCLAMATION);
    pcMain.ActivePage := tsDem;
    cbxSite.SetFocus;
    exit;
  end;

  CodeSys := 'ICD-9-CM';
  if FICD10Active then
    CodeSys := 'ICD-10-CM';

  // ** Don't procede if no indication specified
  ICD9new := edtICD9.Text;
  if (ICD9new = '') and (ckbNone.Checked = false) then
  begin
    InfoBox('Please choose a valid ' + CodeSys + ' indication before proceeding', 'Incomplete Encounter Information', MB_OK or MB_ICONEXCLAMATION);
    cbxIndic.SetFocus;
    exit;
  end;


  // ** Don't procede if no procedure selected
  Proced := '';
  IdentifyCPT;
  if (Proced = '') and (ckbNone.Checked = false) then
  begin
    InfoBox('Please complete PCE Data before proceeding', 'Incomplete Encounter Information', MB_OK or MB_ICONEXCLAMATION);
    exit;
  end;

  //Encounter location needed for ordering
  if (EClinic = '') then
    SetEClinic;

  // ** begin ordering section
  if FileAs = 'SAVE' then
  begin
    if (ckbINROrder.checked = true) or (ckbCBC.checked = true) and
       (ckbDC.Checked = false) then                       //orders labs
    begin
      cofactor := 2;
      cstest := cosigner('');
      if (StrToInt(cstest) = 0) then
      begin
        if ckbINROrder.checked = true then
        begin
          lab := 'INR';
          orderit(PDFN,PDUZ,lab);
        end;
        if ckbCBC.checked = true then
        begin
          lab := 'CBC';
          orderit(PDFN,PDUZ,lab);
        end;
      end;    //cs = 0
    end;  //ORDERIT
  end;  // ** ordering section

  // ** begin PCE section
  if (ckbNone.Checked = false) then
  begin
    //this code invalidated setEclinic
    //if (Proced = SimplePhoneCPT) or (Proced = ComplexPhoneCPT) or
    //   (Proced = PatientLetterCPT) then
    //  EClinic := PhoneClinic
    //else
    //  EClinic := VisitClinic;

    //new pce rsf 2/11/09

    frmPCE.initialize(PDFN, VisitDate, EClinic);
    if uSCCond.AskAny then
    begin
      with frmPCE do
      begin
        repeat
          ShowModal;
        until ((ModalResult = mrOK) or (ModalResult = mrCancel));

        if ModalResult = mrCancel then
          exit;
      end;
    end;

    //echzero = duz^dssid^Proced^ICD9new
    if ckbNone.Checked = true then
        EClinic := NonCountClinic;

    ProvNarr := cbxIndic.Text;

    if (csduz <> '') then
      ProvDUZ := csduz + '~' + PDUZ
    else
      ProvDUZ := PDUZ;

    ECHzero := ProvDUZ + '|' + DSSId + '|' + Proced +'|' + Trim(ICD9new) + '|' + uPCEData.GetSCString;
    CallVistA('ORAMX PCESET', [PDFN, ECHzero, EClinic, VisitDate, SvcCat, ProvNarr,
                           AutoPrimaryIndicationCode + '^' + AutoPrimaryIndicationText,
                           AutoSecondaryIndicationCode + '^' + AutoSecondaryIndicationText]);
    //end new
  end; //if (ckbNone.Checked = false)
  // ** end PCE section

  //if SAVE and not NewPt, remove pt. from current list
  if (FileAs = 'SAVE') and (NewPt <> 1) then
  begin
    try
      if (CompareDate(dtpNextApp.Date, TODAY) = 1) or (ckbDC.Checked = true) then
      begin
        CallVistA('ORAM1 TERASE', [PDFN, ListName], ListIdentified);
        if Piece(ListIdentified, '^', 1) = '0' then
          InfoBox(Piece(ListIdentified, '^', 2) + CRLF + 'Please notify your CAC.',
            'Clinic Parameter Undefined', MB_OK or MB_ICONWARNING);
      end;
    except
      Application.HandleException(Self)
    end;
  end;

  //this adds a new patient to the file
  if EClinic = '' then
    EClinic := NonCountClinic;
  if NewPt = 1 then
    CallVistA('ORAM1 PTENTER', [PDFN]);
  AddTop;    //this packages and sends patient parameters to the file
  //packing up data and sending to ANTICOAG PT file
  if Hist < 1 then
  begin
    if (lblINRval.Caption <> '') then
      RDATE := lblINRdt.Caption
    else
      lblINRdt.Caption := RDate;
    if Not OutSideINR then
      loc := 'VAMC'  //stores VAMC in the file for INR values from lab file
    else
      loc := edtloc.Text + '|' + edtLPhone.text +'|'+edtLFax.text;
  end
  else if Hist = 1 then          //historic entry from an outside lab
  begin
    loc := edtLoc.Text + '|' + edtLPhone.text + '|' + edtLFax.text;
    RDATE := DateToStr(dtpINR.DateTime);
    lblINRval.Caption := edtNewInr.Text;
  end;
  if ckbTWD.Checked = false then
    edtTotM.Text := '---';

  DTEXT := 'Next draw: ';
  if noshow = 3 then //SMT MOVED to use inrold for Missed appt HD523093
  begin
    DTEXT := 'Missed Appt; return: ';
    if inrdold <> '' then RDate := inrdold;
  end;

  DD := edtCMSun.Text + '|' + edtCMMon.Text + '|' + edtCMTue.Text + '|' +
    edtCMWed.Text + '|' + edtCMThu.Text + '|' + edtCMFri.Text + '|' + edtCMSat.Text;
  FSEntry := RDate + '^^' + lblINRval.Caption + '^' + loc + '^' + FloatToStr(PillDose) +
    '^' + edtTotM.Text + '^' + DD + '^' + FilteredString(edtPtNote.Text) + '^' +
    VisitDate + '^' + PDUZ + '^' + cbxIndic.Text + '^' + cbxINRGoal.Text + '^' + IntToStr(noshow);
  CommNew := '';
  plusday := '';
  missed := '';

  if ckbPlusDay.Checked = true then
    plusday := #13#10 + 'Callback: ' + DateToStr(IncDay(dtpNextApp.Date, 1));
  //rsf complications 9/08
  bleed := '';
  if compre > 0 then
  begin
    bleed := complications;
    bleed := INTTOSTR(compre) + '|' + datetostr(dtpComp.Date) + '^' + bleed;  //note if the first piece is <100, then bleed, > 100, then clot.
  end;

  if ckbDC.checked = true then
    CommNew := 'Patient d/c''d from clinic - ' + ProvInit
  else if FileAs = 'TEMPSAVE' then
    CommNew := 'ENTRY IN PROGRESS' + ' - ' + LowerCase(ProvInit)
  else if rbComp.Checked = true then
    CommNew := 'COMPLEX PATIENT' + #13#10 + DTEXT + ReturnDate + plusday + ' -' + ProvInit
  else
    CommNew := DTEXT + ReturnDate + plusday + ' -' + ProvInit;

  memNCom.Lines.Add(CommNew);
  CommtArr := TStringList.Create;
  if restr < '1' then
    restr := '';
  //rsf 9/08
  if edtNewHCT.Text <> '' then
    HCT := edtNewHCT.Text + '|' + Datetostr(dtpINR.Date) + '|' + edtLoc.Text
  else
    HCT := '';

  // ^ORAM(103,D0,6)= (#95) RESTRICT LAB DRAWS [1F] ^ (#101) CLINIC [2P:44] ^
  // (#102) CMPLX [3P:100.21] ^ (#110) OUTSIDE HCT [4F] ^ (#111) ELIGIBLE FOR LMWH BRIDGING [5S] ^
  p6 := RESTR + '^' + Piece(ClinicRef, ';', 1) + '^^' + HCT;

  try
    with CommtArr do
    begin
      Add(PDFN);
      Add(FSEntry);
      Add(FileAs);
      Add(p6);            //rsf 9/08 chnaged order
      Add(bleed);             //rsf 9/08
      Add(IntToStr(memNCom.Lines.Count));
      for x := 0 to (memNCom.Lines.Count - 1) do
        Add(FilteredString(memNCom.Lines[x]));
      Add(IntToStr(PatientInstructions.Count));
      for x := 0 to PatientInstructions.Count - 1 do
        Add(FilteredString(PatientInstructions[x]));
    end;
    neworNetMult(aList);
    for x := 0 to CommtArr.Count - 1 do
      aList.AddSubscript([IntToStr(x)], CommtArr[x]);
    CallVistA('ORAM1 COMPTEST', [aList]);
  finally
    CommtArr.Free;
  end;

  FlowArr.Free;

  if NoteNumber <> '' then
       signme();

  if lbxConsult.Count > 0 then
    exit;

  Application.Terminate;
end;

procedure TfrmAnticoagulate.cbxIndicChange(Sender: TObject);
var
  ICDCode: String;
  ICDDesc: String;
  sl: TStringList;
  idx: integer;
  OldIdx: integer;
begin
  if (csLoading in ComponentState) then
    Exit;

  cbxIndic.DroppedDown := False;

  if (not IndicChanging) and (cbxIndic.ItemIndex > -1) then
  begin
    IndicChanging := True;
    try
      // <CQ22002>
      if Piece(cbxIndic.Items[cbxIndic.ItemIndex], '^', 1) = 'Other' then
      begin
        OldIdx := cbxIndic.ItemIndex;
        LexiconLookup(ICDCode, LX_ICD, MakeFMDateTime(VisitDate), False, '', FICD10Active);
        if ICDCode <> '' then
        begin
          ICDDesc := Piece(ICDCode, U, 2) + U + Piece(ICDCode, U, 1);

          if not cbxIndic.Items.IndexOf(ICDDesc) > -1 then
          begin
            sl := TStringList.Create;
            try
              sl.Text := cbxIndic.Items.Text;
              sl.Delete(cbxIndic.Items.Count - 1);
              sl.Sorted := True;
              sl.Add(ICDDesc);
              sl.Sorted := False;
              sl.Add('Other');
              idx := sl.IndexOf(ICDDesc);
              cbxIndic.Items.Text := sl.Text;
              cbxIndic.ItemIndex := idx;

              edtICD9.Text := Piece(ICDCode, U, 1);
            finally
              sl.Free;
            end;
          end;
        end
        else
        begin
          edtICD9.Text := '';
          cbxIndic.ItemIndex := OldIdx;
        end;
      end  // <CQ22002/>
      else
        edtICD9.Text := Piece(cbxIndic.Items[cbxIndic.ItemIndex], '^', 2);

    finally
      IndicChanging := False;
    end;
  end;
end;

procedure TfrmAnticoagulate.cbxIndicEnter(Sender: TObject);
begin
  cbxIndic.ListItemsOnly := True;
end;

procedure TfrmAnticoagulate.cbxIndicExit(Sender: TObject);
var
  CodeSys: String;
begin
  CodeSys := 'ICD-9-CM';
  if FICD10Active then
    CodeSys := 'ICD-10-CM';

  with cbxIndic do
  begin
    if ((NewPt = 1) and (Text = '')) then
    begin
      InfoBox('Indication is required for New Patients.' + CRLF +
              'Please choose a valid ' + CodeSys + ' indication...', 'Indication Required',
               MB_OK or MB_ICONEXCLAMATION);
      SetFocus;
    end
    else if gbxPCE.Enabled and ((Text = '') or (Text = 'Other') or (edtICD9.Text = '')) then
    begin
      InfoBox('No specific indication entered.' + CRLF +
              'Please choose a valid ' + CodeSys + ' indication...', 'Indication Required',
               MB_OK or MB_ICONEXCLAMATION);
      SetFocus;
    end;
  end;
end;

procedure TfrmAnticoagulate.btnCUpdateClick(Sender: TObject);
var
  i:Integer;
begin
  AMMeds := '0';
  Msg := '1';
  if ckbAMmeds.Checked = true then
  begin
    AMMeds := '1';
    lblAM.Visible := True;
  end;
  if ckbAMmeds.Checked = false then
  begin
    AMMeds := '0';
    lblAM.Visible := false;
  end;
  if ckbMsg.Checked = true then
  begin
    Msg := '2';
    lblMSG.Caption := 'OK to leave anticoag information on answering machine. ';
  end;
  if ckbMsg.Checked = false then
  begin
    Msg := '1';
    lblMSG.Caption := 'Pt has not given permission to leave anticoag messages on answering machine. ';
  end;
  if rbStand.Checked = true then
  begin
    lblComplex.Visible := false;
    cs := 0;
  end;
  if rbComp.Checked = true then
  begin
    lblComplex.Visible := true;
    cs := 1;
  end;
  if ckbDC.Checked = true then
    cs := 2;
  if ckbSA.Checked = true then
  begin
    Sign := 'Y';
    lblSign.Caption := 'Pt has a signed agreement.';
  end;
  if ckbSA.Checked = false then
  begin
    Sign := 'N';
    lblSign.Caption := 'NO signed agreement';
  end;
  if ckbPmsg.Checked = true then
  begin
    SetLength(PMSG, memPeople.Lines.Count);
    lblPMsg.Visible := true;
    Contacts := '';
    if memPeople.Lines.Count > 0 then
    begin
      for i := 0 to memPeople.Lines.Count - 1 do
      begin
        PMSG[i] := ReplaceStr(memPeople.Lines[i], '&', '&&');
        if (i < (memPeople.Lines.Count - 1)) then
        begin
          if ((Copy(PMSG[i], Length(PMSG[i]), 1) <> ',')) then
              PMSG[i] := PMSG[i] + ',';
          PMSG[i] := PMSG[i] + ' ';
        end
        else // last person
        begin
          if ((i <> 0) and (Copy(PMSG[i], 0, 1) <> '&')) then
            PMSG[i] := ' && ' + PMSG[i];

          if ((Copy(PMSG[i], Length(PMSG[i]), 1) <> '.')) then
            PMSG[i] := PMSG[i] + '.';
        end;

        lblPMsg.Caption := '';
        Contacts := Contacts + PMSG[i];
      end;
      if PMSG[0]<>'' then
        lblPMsg.Caption := 'OK to leave anticoag message with ' + Contacts
      else
      begin
        InfoBox('Please enter person(s) allowed to take message',
                'Identify Person(s)', MB_OK or MB_ICONEXCLAMATION);
        exit;
      end;
    end // memPeople.Lines.Count > 0
    else
    begin
      ckbPmsg.Checked := false;
      Peep := 0;
    end;
  end // ckbPmsg.checked = true
  else if ckbPmsg.Checked = false then
    Peep := 0;

end;

procedure TfrmAnticoagulate.memSpInEChange(Sender: TObject);
begin
  //edited special instructions
  SP := 1;
end;

procedure TfrmAnticoagulate.memTWeekEnter(Sender: TObject);
begin
  memTweek.SelStart := 0;
end;

procedure TfrmAnticoagulate.memXPCEnter(Sender: TObject);
begin
  memXPC.SelStart := 0;
end;

procedure TfrmAnticoagulate.mnuAboutClick(Sender: TObject);
begin
  ShowAboutACM;
end;

procedure TfrmAnticoagulate.mnuAnticoagulationManagementHelpClick(
  Sender: TObject);
begin
  //SMT Reset current directory before calling Help HD514093
  SetCurrentDir(ExtractFilePath(Application.ExeName));
//  WinHelp( Application.Handle, PChar(Application.HelpFile), HELP_FINDER, 0);
  Application.HelpContext(0);
end;

procedure TfrmAnticoagulate.mnuCopyClick(Sender: TObject);
begin
  FEditCtrl.CopyToClipboard;
end;

procedure TfrmAnticoagulate.mnuCutClick(Sender: TObject);
begin
  FEditCtrl.CutToClipboard;
end;

procedure TfrmAnticoagulate.mnuDemographicsClick(Sender: TObject);
begin
  pcMain.ActivePage := tsDem;
  tsDem.SetFocus;
  tsDem.Invalidate;
end;

procedure TfrmAnticoagulate.mnuEditClick(Sender: TObject);
var
  IsReadOnly: Boolean;
begin
  FEditCtrl := nil;
  if Screen.ActiveControl is TCustomEdit then FEditCtrl := TCustomEdit(Screen.ActiveControl);
  if FEditCtrl <> nil then
  begin
    if      FEditCtrl is TMemo     then IsReadOnly := TMemo(FEditCtrl).ReadOnly
    else if FEditCtrl is TEdit     then IsReadOnly := TEdit(FEditCtrl).ReadOnly
    else if FEditCtrl is TRichEdit then IsReadOnly := TRichEdit(FEditCtrl).ReadOnly
    else IsReadOnly := True;
    mnuUndo.Enabled := FEditCtrl.Perform(EM_CANUNDO, 0, 0) <> 0;
    mnuCut.Enabled := FEditCtrl.SelLength > 0;
    mnuCopy.Enabled := mnuCut.Enabled;
    mnuPaste.Enabled := (IsReadOnly = False) and Clipboard.HasFormat(CF_TEXT);
  end else
  begin
    mnuUndo.Enabled := False;
    mnuCut.Enabled  := False;
    mnuCopy.Enabled := False;
    mnuPaste.Enabled := False;
  end;
end;

procedure TfrmAnticoagulate.mnuEnterInformationClick(Sender: TObject);
begin
  pcMain.ActivePage := tsInfo;
  tsInfo.SetFocus;
end;

procedure TfrmAnticoagulate.mnuEnterOutsideLabClick(Sender: TObject);
begin
  pcInfo.ActivePage := tsOLD;
end;

procedure TfrmAnticoagulate.mnuExitClick(Sender: TObject);
begin
  Close;
end;

procedure TfrmAnticoagulate.mnuExitTabClick(Sender: TObject);
begin
  pcMain.ActivePage := tsExit;
  if NewPt <> 1 then
    tsExit.SetFocus;
end;

procedure TfrmAnticoagulate.mnuFlowSheetClick(Sender: TObject);
begin
  pcMain.ActivePage := tsFlow;
  tsFlow.SetFocus;
end;

procedure TfrmAnticoagulate.mnuHelpBrokerClick(Sender: TObject);
begin
  ShowBroker;
end;

procedure TfrmAnticoagulate.mnuNewFlowSheetEntryClick(Sender: TObject);
begin
  pcInfo.ActivePage := tsNewFSEntry;
end;

procedure TfrmAnticoagulate.mnuPasteClick(Sender: TObject);
begin
  FEditCtrl.SelText := Clipboard.AsText;
end;

procedure TfrmAnticoagulate.mnuPtPreferencesClick(Sender: TObject);
begin
  pcMain.ActivePage := tsUp;
  tsUp.SetFocus;
end;

procedure TfrmAnticoagulate.mnuUndoClick(Sender: TObject);
begin
  FEditCtrl.Perform(EM_UNDO, 0, 0);
end;

procedure TfrmAnticoagulate.mnuUtilitiesClick(Sender: TObject);
begin
  pcMain.ActivePage := tsSTAT;
  tsSTAT.SetFocus;
end;

procedure TfrmAnticoagulate.orbxPTlUEnter(Sender: TObject);
begin
  if ScreenReaderSystemActive then
    GetScreenReader.Speak('Type patient name, last initial/last 4, or use the up or down cursor keys to find the patient whose record you wish to unlock.');

  orbxPTlU.ItemIndex := 0;
end;

procedure TfrmAnticoagulate.memRiskChange(Sender: TObject);
begin
    ChRisk := 1;
end;

procedure TfrmAnticoagulate.memPeopleChange(Sender: TObject);
begin
   Peep := 1;
end;

procedure TfrmAnticoagulate.stgACSelectCell(Sender: TObject; ACol, ARow: Integer;
  var CanSelect: Boolean);

var
  eComm: TStrings;
  cc: Integer;

begin
  try
    cc := 0;
    if ACol = 4 then
    begin
      if stgAC.Cells[acol,arow] = ' *' then
      begin
        cc := 1;
        lblFS.Caption := 'Complications Noted:';
        memComm.Lines := CompArr[ARow-1];
      end;
    end;
    if cc = 0 then
    begin
      memComm.Lines := CommArr[ARow-1];
      lblFS.Caption := 'Comments:';
    end;
  except
    on Exception do
    begin
      InfoBox('No results for this entry', 'No Results', MB_OK or MB_ICONEXCLAMATION);
      exit;
    end;
  end;

  if lblACAct.Caption = 'EDIT MODE' then
  begin
    FSrow := IntToStr(ARow);
    FSien := Piece(FlowArr[ARow-1], '^', 2);
    Ldate := Piece(Piece(FlowArr[ARow-1], '^', 1), '|', 2);
    stgAC.Enabled := false;
    gbxEdit.Caption := 'EDIT MODE - ' + stgAC.Cells[0, ARow];
    dtpEdit.Date := StrToDate(stgAC.Cells[0, ARow]);
    edtEditINR.Text := stgAC.Cells[1, ARow];
    edtPN.Text := stgAC.Cells[2, ARow];
    edtTWD.Text := stgAC.Cells[3, ARow];
    gbxEdit.Visible := true;
    dtpEdit.SetFocus;
    try
      if CompArr[Arow-1].count > 0 then
        ckbEditCompR.Visible := True
      else
        ckbEditCompR.Visible := False;

      eComm := CommArr[Arow-1];
      if Piece(eComm[eComm.Count-1], ' ', 1) = 'Next' then
      begin
        lline := eComm[eComm.Count-1];
        eComm.Delete(eComm.Count-1);
      end
      else if Piece(eComm[eComm.Count-1], ' ', 1) = 'Missed' then
      begin
        lline := eComm[eComm.Count-1];
        eComm.Delete(eComm.Count-1);
      end
      else if Piece(eComm[eComm.Count-1], ' ', 1) = 'Edited' then
      begin
        if Piece(eComm[eComm.Count-2],' ',1) = 'Next' then
        begin
          lline := eComm[eComm.Count-2];
          eComm.Delete(eComm.Count-2);
        end
        else if Piece(eComm[eComm.Count-2], ' ', 1) = 'Missed' then
        begin
          lline := eComm[eComm.Count - 2];
          eComm.Delete(eComm.Count - 2);
        end;
      end
      else
      begin
        lline := 'Next draw: ' + eComm[eComm.Count - 1];
        eComm.Delete(eComm.Count - 1);
      end;
      memEDIT.Lines := CommArr[ARow - 1];
    except
      on Exception do
      begin
        memEdit.Lines[0] := '';
      end;
    end; //try

    try
      lblEditDuz.Caption := 'Entered by: '+  fsduz[ARow-1];
    except
      on Exception do
      begin
        lblEditDuz.Caption := '';
      end;
    end; //try
  end;
end;


procedure TfrmAnticoagulate.btnCloseClick(Sender: TObject);
begin
  fsyes := 1;
  if Length(memNCom.Lines.Text) < 1 then
    memNCom.Lines[0] := 'NONE';
  if ((Not OutSideINR) and (edtLoc.Text <> '')) then
    pcInfo.ActivePage := tsOLD
  else
    pcInfo.ActivePage := tsHidden;
end;


procedure TfrmAnticoagulate.edtCTChange(Sender: TObject);
var
  Tablets: Single;
  DecPart: String;
begin
  with Sender as TEdit do
  begin
    if Length(Text) = 0 then
    begin
      Text := '0';
      SelectAll;
    end
    else
    begin
      Tablets := StrToFloat(Text);
      DecPart := Piece(Text, '.', 2);
      if (Length(DecPart) >= 2) then
      begin
        if (Copy(DecPart, 0, 1) = '0') then
          Text := FloatToStrF(Tablets, ffNumber, 6, 0)
        else
          Text := FloatToStrF(Tablets, ffNumber, 6, 2);
      end
      else
      begin
        SelStart := Length(Text);
      end;

      if (Sender as TEdit).Focused and (not FTabCutWarn) and (FCreateProgress = FCP_FINISH) and
         (Length(DecPart) > 0) and (StrToFloat(('0.' + DecPart)) <> 0.0) and (StrToFloat(('0.' + DecPart)) <> 0.5) then
      begin
        FTabCutWarn := True;
        InfoBox('Fractions of tablets other than one half are not reliable.' + CRLF + 'You may wish to reconsider.',
          'Unreliable Partial Tablet', MB_OK or MB_ICONWARNING);
        SelStart := pos(FormatSettings.DecimalSeparator, Text);
        SelLength := Length(DecPart);
      end
      else
        SelStart := Length(Text);
    end;
  end;
end;

procedure TfrmAnticoagulate.edtCMChange(Sender: TObject);
var
  Dosage: Single;
  DecPart: String;
begin
  with Sender as TEdit do
  begin
    if Length(Text) = 0 then
    begin
      Text := '0';
      SelectAll;
    end
    else
    begin
      Dosage := StrToFloat(Text);
      DecPart := Piece(Text, '.', 2);

      if (Length(DecPart) >= 2) then
      begin
        if (Copy(DecPart, 0, 1) = '0') then
          Text := FloatToStrF(Dosage, ffNumber, 6, 0)
        else
          Text := FloatToStrF(Dosage, ffNumber, 6, 2);
      end
      else
      begin
        SelStart := Length(Text);
      end;

      if (not FDosageWarn) and (FCreateProgress = FCP_FINISH) and (Dosage > MAXDOSE) then
      begin
        FDosageWarn := True;
        InfoBox('Dosage excedes daily maximum of ' + FloatToStr(MAXDOSE) + ' mg.' + CRLF + 'You may wish to reconsider.',
          'Excessive Dosage Entered', MB_OK or MB_ICONWARNING);
        SelectAll;
      end
      else
        SelStart := Length(Text);
    end;
  end;
end;

procedure TfrmAnticoagulate.edtCMExit(Sender: TObject);
begin
  FDosageWarn := False;
end;

procedure TfrmAnticoagulate.edtCTKeyPress(Sender: TObject; var Key: Char);
begin
  if not CharInSet(Key, ['0'..'9', #8, FormatSettings.DecimalSeparator]) then
    Key := #0
  else
  begin
    with Sender as TEdit do
    begin
      if (Key = FormatSettings.DecimalSeparator) and (pos(FormatSettings.DecimalSeparator, Text) >0) then
        Key := #0;
    end;
  end;
end;

procedure TfrmAnticoagulate.edtCTExit(Sender: TObject);
begin
  FTabCutWarn := False;
end;

procedure TfrmAnticoagulate.edtCTKeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  with frmAnticoagulate do
  begin
    TabletsSum;
    MilligramsReset;
  end;
end;

procedure TfrmAnticoagulate.edtCMKeyPress(Sender: TObject; var Key: Char);
begin
  if not CharInSet(Key, ['0'..'9', #8, FormatSettings.DecimalSeparator]) then
    Key := #0
  else
  begin
    with Sender as TEdit do
    begin
      if (Key = FormatSettings.DecimalSeparator) and (pos(FormatSettings.DecimalSeparator, Text) >0) then
        Key := #0
    end;
  end;
end;

procedure TfrmAnticoagulate.edtCMKeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  MilligramsSum;
  TabletsReset;
end;

procedure TfrmAnticoagulate.btnINRCloseClick(Sender: TObject);
var
  HxINR: Boolean;
begin
  HxINR := false; // initialize historical INR flag to false
  if Length(edtLoc.text) = 0 then
  begin
    InfoBox('A lab draw location MUST be entered.',
            'Location Required', MB_OK or MB_ICONEXCLAMATION);
    exit;
  end;
  //rsf 9/4/08 added HCT
  if (Length(edtNewInr.Text) = 0) and (Length(edtNewHCT.text) = 0) then
  begin
    InfoBox('Please enter an outside lab value or cancel.',
            'Lab Value Needed', MB_OK or MB_ICONEXCLAMATION);
    exit;
  end
  else  //has INR or HCT text entered
  begin
    ResultDay := dc(Now, dtpINR.DateTime);
    if ResultDay = 2 then
    begin
      InfoBox('Future dates are not acceptable',
              'Future Date Entered', MB_OK or MB_ICONEXCLAMATION);
      exit;
    end;

    //SMT Update to account for Clearing INR before entering outside lab. HD523093
    if (Length(lblINRdt.Caption) <> 0) then
    begin
      OldDate := StrToDate(lblINRdt.Caption);
      OldINR := lblINRval.Caption;
    end
    else if (Length(inrdold) <> 0) then  //SMT Protect against first entering outside info as first INR
    begin
      OldDate := StrToDate(inrdold);
      OldINR := inrold;
    end;

    ResultDay := dc(Now, dtpINR.DateTime);
    if ResultDay = 2 then
    begin
      InfoBox('Future dates are not acceptable',
              'Future Date Entered', MB_OK or MB_ICONEXCLAMATION);
      exit;
    end;
    ResultDay := dc(dtpINR.DateTime, OldDate);
    if ResultDay = 1 then             //new date is more recent
    begin
      lblINRdt.Caption := DateToStr(dtpINR.DateTime);
      lblINRval.Caption := edtNewInr.Text;
      ckbINROrder.Checked := false;
      // gbxINREnter.Visible := false;
    end
    else if ResultDay = 2 then               //old date is more recent
    begin
      lblINRdt.Caption := DateToStr(OldDate);
      lblINRval.Caption := OldINR;
      pnlFee.Visible := false;
      lblHistory.Visible := true;
      btnYHx.Visible := true;
      btnNHx.Visible := true;
      HxINR := true;
    end;
    if FileWas = 'TEMPSAVE' then
    begin
      lblINRdt.Caption := DateToStr(dtpINR.DateTime);
      lblINRval.Caption := edtNewInr.Text;
      ckbINROrder.Checked := false;
    end;
    OutSideINR := True;
  end;

  if (edtNewHCT.Text<>'') and (lblHCTdate.Caption<>'') then
  begin
    if CompareDate(dtpINR.Date,strtodate(lblHCTdate.Caption))< 0 then
    begin
      if InfoBox('More recent HCT already recorded for this patient.' + CRLF +
                 'do you want to replace it?', 'Newer HCT Available',
                  MB_YESNO or MB_ICONQUESTION) = mrNo then
      begin
        edtNewHCT.Text := '';
        exit;
      end
      else
      begin
        lblHCT.caption := edtNewHCT.Text;
        lblHCTdate.Caption := DateToStr(dtpINR.DateTime);
      end;

    end
  end;
  if HxINR then
    btnYHx.SetFocus
  else
  begin
    if (fsyes < 1) then
    begin
      btnNEntry.Click;
      pcinfo.ActivePage := tsNewFSEntry;
    end
    else
      pcInfo.ActivePage := tsHidden;     //rsf 9/04/08
  end;
  INRColor();
end;

procedure TfrmAnticoagulate.btnCancelClick(Sender: TObject);
begin
  if OutSideINR then
  begin
    if InfoBox('Cancel outside INR data?',
               'Update Cancelled', MB_YESNO or MB_ICONQUESTION) = mrNo then
      exit
    else
    begin
      edtNewInr.Text := '';
      edtLoc.Text := '';
      edtLPhone.Text := '';
      edtLFax.Text := '';
    end;
  end
  else if NOT OutSideINR then
  begin
    edtNewInr.Text := '';
    edtLoc.Text := '';
    edtLPhone.Text := '';
    edtLFax.Text := '';
  end;
  pcInfo.ActivePage := tsHidden;
end;

function orderit(PDFN: string; LDUZ: string; code: string): string;
var
  qoDlg: string;
  nxtDt: string;
begin
  //Quick Order Dialog
  if code = 'INR' then
    qoDlg := INRQuickOrder
  else if code = 'CBC' then
    qoDlg := CBCQuickOrder;
  nxtDt := DateToStr(frmAnticoagulate.dtpNextApp.date);
  if frmAnticoagulate.dtpAppTime.Visible then
    nxtDt := nxtDt + '@' + Pieces(TimeToStr(frmAnticoagulate.dtpAppTime.Time), ':', 1, 2);
  CallVistA('ORAM ORDER', [PDFN, LDUZ, EClinic, qoDlg, nxtDt], Result);
  if Piece(Result, '^', 1) = '0' then
    InfoBox(Piece(Result, '^', 2), 'Order Failed!', MB_OKCANCEL or MB_ICONERROR);
end;

function TfrmAnticoagulate.complications(): string;
  var cc: Integer;
begin
  result := '';
  with frmAnticoagulate do
  begin
    if ckbMCDeath.Checked = true then
      result := result + 'MB:' + ckbMCDeath.Caption + '^';
    if ckbMCR.Checked = true then
      result := result + 'MB:' + ckbMCR.Caption + '^';
    if ckbMCH.Checked = true then
      result := result + 'MB:' + ckbMCH.Caption + '^';
    if ckbMChgb.Checked = true then
      result := result + 'MB:' + ckbMChgb.Caption + '^';
    if ckbMCtran.Checked = true then
      result := result + 'MB:' + ckbMCtran.Caption + '^';
    if ckbMinorC.Checked = true then
      result := result + 'Minor Bleed' + '^';
    if ckbTT.Checked = true then
      result := result + 'Thrombotic event' + '^';
    if (ckbCC.Checked = true) then
      for cc := 0 to memMCother.Lines.Count - 1 do
        result := result + 'C:' + FilteredString(memMCother.Lines[cc]) + '^';
  end;     //frmAnticoagulate
end;

procedure TfrmAnticoagulate.Complications1Click(Sender: TObject);
begin
  pcInfo.ActivePage := tsComplications;
end;

procedure TfrmAnticoagulate.dtpAppTimeChange(Sender: TObject);
var
  tmCurrent, HoD: Extended;
begin
  with Sender as TDateTimePicker do
  begin
    tmCurrent := Time;
    if tmCurrent <> tmPrevious then
    begin
      HoD := HourOf(tmCurrent);
      if (HoD < 7) or (HoD > 17) then
        Time := tmPrevious
      else
      begin
        NextAppTimeStr := FormatDateTime('HH:mm', DateTime);
        tmPrevious := tmCurrent;
      end;
    end;
  end;
end;

{
  Note: Tried to implement an OnChange event, so that changes to the calendar
  whould be dynamically evaluated, but invoking a modal dialog in DateTimePicker.OnChange
  causes an infinite loop. Found a proprietary blog that claimed to have a solution:
  http://www.experts-exchange.com/Programming/Languages/Pascal/Delphi/Q_21298145.html
  but they wanted my Credit card, so I decided to enter a ticket on Embarcadero's bug site.
  http://qc.embarcadero.com/wc/qcmain.aspx?d=72908
  Report #: 72908
}
procedure TfrmAnticoagulate.dtpNextAppChange(Sender: TObject);
//var
//  dtCurrent: TDateTime;
begin
{  with Sender as TDateTimePicker do
  begin
    dtCurrent := Date;
    if (dtCurrent <> dtPrevious) then
    begin
      dtPrevious := dtCurrent;
      if not CheckDrawDay then
      begin
        SetFocus;
      end;
    end;
  end;}
end;

procedure TfrmAnticoagulate.dtpNextAppExit(Sender: TObject);
begin
  with Sender as TDateTimePicker do
  begin
    if not CheckDrawDay then
    begin
      if NextAppt <> 0 then
        Date := NextAppt
      else
        Date := today;
      SetFocus;
      Invalidate;
    end;
  end;
end;

procedure TfrmAnticoagulate.btnMAPreviewClick(Sender: TObject);
var
  T: Integer;
  AddText, NextAppStr: String;
begin
  noshow := 3;
  for T := 0 to (memMA.Lines.Count - 1) do
  begin
    if T = 0 then AddText := FilteredString(memMA.Lines[0])
    else
      AddText := AddText+ #13#10 + FilteredString(memMA.Lines[T]);
  end;
  NextAppStr := FormatDateTime('dddddd', dtpNextApp.DateTime);
  if dtpAppTime.Visible then
    NextAppStr := NextAppStr + ' at ' + FormatDateTime('hh:nn ampm', dtpAppTime.Time);
  case StrToInt(LetterINRTime) of
    0, 1:
      NextAppStr := NextAppStr + '.';
    2:
      NextAppStr := NextAppStr + ' in the morning.';
    3:
      NextAppStr := NextAppStr + ' in the afternoon.';
    4:
      NextAppStr := NextAppStr + ' per Lab procedures as directed.';
  end;
  PatientInstructions.Clear;
  PatientInstructions.Add(memMA.Text);
  RvProject.ClearParams;
  RvProject.ProjectFile := NetworkPath + 'MAppt.rav';
  With RvProject do
  begin
    open;
    SetParam('Heading1',SiteHead);
    SetParam('siteadr1',SiteAddA);
    SetParam('FAX','FAX:      ' + ClinicFAX);    //    SetParam('FAX',FAX);
    if SiteAddB <> '' then
    begin
      SetParam('siteadr2',SiteAddB);
      SetParam('siteadr3',SiteAddC);
    end
    else
      SetParam('siteadr2',SiteAddC);
    SetParam('X',GName);
    SetParam('Date', lblINRdt.Caption);
    SetParam('adr1', lblSadr1.Caption);
    SetParam('adr2', lblSadr2.Caption);
    SetParam('adr3', lblSadr3.Caption);
    SetParam('adr4', lblCSZ.Caption);
    SetParam('MAppt', FormatDateTime('dddddd', dtpMA.DateTime));
    SetParam('TDate', FormatDateTime('mmmm dd, yyyy', Today));
    SetParam('NextAppt', NextAppStr);
    SetParam('addinfo', AddText);
    SetParam('clinic', ClinicName);
    SetParam('phone', ClinicPhone);
    if (TollFreePhone <> '') then
      SetParam('TollFreeTag', 'or call Toll-free:')
    else
      SetParam('TollFreeTag', '');
    SetParam('TollFree', TollFreePhone);
    SetParam('sig', SigName);
    SetParam('title', SigTitle);
    ExecuteReport('rptNoShow');
    Close;
    FreeOnRelease;
  end;
  gbxMA.Visible := false;
  ToggleExitVisible(btnMA);
  btnMA.SetFocus;
end;


procedure TfrmAnticoagulate.btnCanEntClick(Sender: TObject);
begin
  memNCom.Lines.Clear;
  edtPtNote.Text := '';
  fsyes := 0;
end;

procedure TfrmAnticoagulate.btnCComClick(Sender: TObject);
begin
  if compre < 1 then
  begin
    InfoBox('Nothing to file.', 'No Changes', MB_OK or MB_ICONEXCLAMATION);
    exit;
  end;
  pcInfo.ActivePage := tsHidden;
end;

procedure TfrmAnticoagulate.btnNEntryClick(Sender: TObject);
begin
  lblNINRval.Caption := lblINRval.Caption;
  lblNidate.Caption := lblINRdt.Caption;
  lblNdate.Caption := RDate;
  lblNTWDval.Caption := edtTotM.Text;
end;

procedure TfrmAnticoagulate.FormActivate(Sender: TObject);
begin
  SplashClose;
  frmAnticoagulate.FormStyle := fsNormal;
  frmAnticoagulate.Show;
  if remindmsg = 2 then
  begin
    InfoBox(ARemStr, 'Reminder', MB_OK or MB_ICONINFORMATION);
    remindmsg := 1;
  end;
  //rsf 9/04 for flow sheet entry
  lblNINRval.Caption := lblINRval.Caption;
  lblNidate.Caption := lblINRdt.Caption;
  lblNdate.Caption := RDate;
  lblNTWDval.Caption := edtTotM.Text;
  pcInfo.ActivePage := tsNewFSEntry;
  if (edtLoc.Text<>'') and (edtloc.Text<>'VAMC') then
    pcInfo.ActivePage := tsOLD;
end;

procedure TfrmAnticoagulate.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if (NewPt <> 1) then
    CallVistA('ORAM1 UNLOCK', [PDFN]);
  if NoteNumber <> '' then
  begin
    if InfoBox('You have a progress note, do you want to file it?',
               'File Progress Note?', MB_YESNO or MB_ICONQUESTION) = mrYes then
      signme()
    else
      CallVistA('TIU DELETE RECORD', [NoteNumber]);
  end; //notenumber
    //ZZZZZZBELLC - Clear the series array
  SetLength(SeriesValues, 0);
end;

procedure TfrmAnticoagulate.btnTempSaveClick(Sender: TObject);
begin
    FileAs := 'TEMPSAVE';
    ckbNone.Checked := true;
    btnComp.Click;
end;

procedure TfrmAnticoagulate.btnCVClick(Sender: TObject);

begin
  if not (dtpNextApp.Date > today) then
  begin
    InfoBox('You must select a future Return Date to send a Letter.', 'Invalid Return Date for Letter', MB_OK or MB_ICONEXCLAMATION);
    dtpNextApp.SetFocus;
    exit;
  end;
  gbxMA.Visible := false;
  with gbxCA do
  begin
    align := alnone;
    Visible := true;
    height := BHGHT;
    top := BTOP;
    width := BWIDTH;
    left := BLFT;
  end;
  //setFocus on Meds Changed radio button
  rbMC.SetFocus;
  ToggleExitVisible(Sender);
end;

procedure TfrmAnticoagulate.btnMAClick(Sender: TObject);
begin
  if not (dtpNextApp.Date > today) then
  begin
    InfoBox('You must select a future Return Date to send a Letter.', 'Invalid Return Date for Letter', MB_OK or MB_ICONEXCLAMATION);
    dtpNextApp.SetFocus;
    exit;
  end;
  gbxCA.Visible := false;
  dtpMA.Date := NextAppt;
  with gbxMA do
  begin
    align := alnone;
    Visible := true;
    height := BHGHT;
    top := BTOP;
    width := BWIDTH;
    left := BLFT;
  end;
  lblNAppt.Caption := DateToStr(dtpNextApp.DateTime);
  dtpMA.SetFocus;
  ToggleExitVisible(Sender);
end;

procedure TfrmAnticoagulate.btnCanDoseClick(Sender: TObject);
begin
  if NewPt <> 1 then
  begin
    edtCMSun.Text := Piece(TempDose, '|', 1);
    edtCMMon.Text := Piece(TempDose, '|', 2);
    edtCMTue.Text := Piece(TempDose, '|', 3);
    edtCMWed.Text := Piece(TempDose, '|', 4);
    edtCMThu.Text := Piece(TempDose, '|', 5);
    edtCMFri.Text := Piece(TempDose, '|', 6);
    edtCMSat.Text := Piece(TempDose, '|', 7);
    edtTotM.Text := FloatToStr(StrToFloat(edtCMSun.Text) + StrToFloat(edtCMMon.Text)+StrToFloat(edtCMTue.Text)+StrToFloat(edtCMWed.Text) +StrToFloat(edtCMThu.Text) + StrToFloat(edtCMFri.Text) + StrToFloat(edtCMSat.Text));
    if PillDoseOr = -1 then
      PillDose := DefaultPillStrength        //check, will this include null?
    else
    begin
      if PillDoseOr > 0 then
        PillDose := PillDoseOr;
    end;
    cboPS.SelectByID(FloatToStr(PillDose));
    if cboPS.Text = '' then
      cboPS.Text := FloatToStr(PillDose);
    TabletsReset;
    edtCTSun.Enabled := false;
    edtCTMon.Enabled := false;
    edtCTTue.Enabled := false;
    edtCTWed.Enabled := false;
    edtCTThu.Enabled := false;
    edtCTFri.Enabled := false;
    edtCTSat.Enabled := false;
    edtCMSun.Enabled := false;
    edtCMMon.Enabled := false;
    edtCMTue.Enabled := false;
    edtCMWed.Enabled := false;
    edtCMThu.Enabled := false;
    edtCMFri.Enabled := false;
    edtCMSat.Enabled := false;
    edtTotT.Enabled := false;
    edtTotM.Enabled := false;
    cboPS.Enabled := True;
    gbxDailyDosing.Caption := 'Current Daily Dosing';
    btnCanDose.Visible := false;
    btnDD.Caption := 'Change &daily dosing';
  end
  else if NewPt = 1 then
  begin
    edtCTSun.Text := '1';
    edtCTMon.Text := '1';
    edtCTTue.Text := '1';
    edtCTWed.Text := '1';
    edtCTThu.Text := '1';
    edtCTFri.Text := '1';
    edtCTSat.Text := '1';
    edtTotT.Text := '5';
    PillDose := DefaultPillStrength;
    cboPS.SelectByID(FloatToStr(PillDose));
    if cboPS.Text = '' then
      cboPS.Text := FloatToStr(PillDose);
    MilligramsReset;
    edtCTSun.Enabled := false;
    edtCTMon.Enabled := false;
    edtCTTue.Enabled := false;
    edtCTWed.Enabled := false;
    edtCTThu.Enabled := false;
    edtCTFri.Enabled := false;
    edtCTSat.Enabled := false;
    edtCMSun.Enabled := false;
    edtCMMon.Enabled := false;
    edtCMTue.Enabled := false;
    edtCMWed.Enabled := false;
    edtCMThu.Enabled := false;
    edtCMFri.Enabled := false;
    edtCMSat.Enabled := false;
    edtTotT.Enabled := false;
    edtTotM.Enabled := false;
    cboPS.Enabled := True;
    gbxDailyDosing.Caption := 'Suggested Daily Dosing';
    btnCanDose.Visible := false;
    btnDD.Caption := 'Change &daily dosing';
  end;
end;

procedure TfrmAnticoagulate.rbMCClick(Sender: TObject);
begin
  if rbMC.Checked = true then
  begin
    memCL.Visible := false;
    lblCL.Visible := false;
    pnlMChange.Visible := true;
    btnCVL.Width := 75;
    btnCVL.Caption := '&OK';
    btnCVL.Enabled := false;
    ckbCAInclInst.Enabled := false;
  end;
end;

procedure TfrmAnticoagulate.ckbMCDeathClick(Sender: TObject);
begin
  with Sender as TCheckBox do
  begin
    if Checked = true then
    begin
      compre := compre + 1;
      if name = 'ckbMCother' then
        ckbCC.Checked := true;
      if name = 'ckbMinorC' then
        compre := compre + 9;  //adds 10 if minor
    end
    else if compre > 0 then
    begin
      compre := compre - 1;
      if (name = 'ckbMCother') and (memMCother.Lines.Count < 1) then
        ckbCC.Checked := false;
      if name = 'ckbMinorC' then
        compre := compre - 9;  //subs 10 if minor
    end;
  end;
end;

procedure TfrmAnticoagulate.rbNoMCClick(Sender: TObject);
begin
  if rbNoMC.Checked = true then
  begin
    memCL.Clear;
    pnlMChange.Visible := false;
    MNote := 'Please do not make any changes in your weekly dosages.  Continue weekly schedule as below.';
    MNoteCl := 'Please contact us if you are taking a different dosage of warfarin or if you have any questions, ' +
               'concerns, signs of bleeding, or if you need to reschedule this appointment. ' + #13#10;
    memCL.Lines[0] := MNote;
    memCL.Visible := true;
    lblCL.Visible := true;
    btnCVL.Enabled := true;
    if not (memDCnote.Lines.Count > 0) then
      ckbCAInclInst.Enabled := true;
    btnCVL.Width := 90;
    btnCVL.Left := 125;
    btnCVL.Caption := '&Preview/Print';
  end;
end;

//****************************************************
// ZZZZZZBELLC  -  12/05/12
// find the index in the array and overwrite the
// Marktext with the INR string
//****************************************************
procedure TfrmAnticoagulate.serINRGetMarkText(Sender: TChartSeries;
  ValueIndex: Integer; var MarkText: string);
var
 I: Integer;
begin
 For i := Low(SeriesValues) to High(SeriesValues) do begin
  If SeriesValues[i].SeriesIndex = ValueIndex then begin
    MarkText := SeriesValues[i].SeriesValue;
    break;
  end;
 end;
end;

procedure TfrmAnticoagulate.btnCVLClick(Sender: TObject);
var
  doseit, inrit, NextAppStr: String;
  STab, MTab, TTab, WTab, HTab, FTab, ATab: String;
begin
  if btnCVL.Caption = '&OK' then
  begin
    if (ckbHold.Checked = true) and (edtHDays.Text = '') then
    begin
      InfoBox('Please indicate number of days to hold Warfarin (Coumadin).',
              'Hold Interval Needed', MB_OK or MB_ICONEXCLAMATION);
      exit;
    end;
    if (ckbTake.Checked = true) and ((edtTTabs.Text = '')) then
      InfoBox('Please indicate number of tablets to take for adjustment dose.',
              'Number of Tablets Needed', MB_OK or MB_ICONEXCLAMATION);
    if (ckbHold.Checked = true) and (edtHdays.Text <> '') then
    begin
      MNote := 'Please HOLD (do not take any Warfarin (Coumadin)) as you were directed on ' + FormatDateTime('dddddd', Today) + ' and for the next ' + IntToStr(StrToInt(edtHDays.Text)-1)+ ' days.  '+#13#10+#13#10+'Then continue with the schedule below.'+#13#10;
      MNoteCl := 'Please contact us if you have any questions, concerns, signs of bleeding, or if you need to reschedule this appointment. '+#13#10;
      if StrToInt(edtHDays.Text) = 2 then
        MNote := 'Please HOLD (do not take any Warfarin (Coumadin)) as you were directed on ' + FormatDateTime('dddddd', Today) + ' and the next day.  Then continue with the schedule below.'+#13#10;
      if StrToInt(edtHDays.Text) <= 1 then
        MNote := 'Please HOLD (do not take any Warfarin (Coumadin)) as you were directed on ' + FormatDateTime('dddddd', Today) + '.  Then continue with the schedule below.'+#13#10;
    end;
    if (ckbTake.Checked = true) and (edtTTabs.Text <> '') then
    begin
      MNote := 'Using a ' + cboPS.Text + 'mg tablet please take ' + edtTTabs.Text + ' tablets on ' + FormatDateTime('dddddd', Today) + '.  Then continue with the schedule below.' + #13#10;
      MNoteCl := 'Remember to let us know if you have missed Warfarin (Coumadin) doses, taken extra Warfarin (Coumadin) doses, or if you’ve had changes in your other medications, your diet, or your health.' + #13#10;;
      //'Please contact us if you have missed any doses of warfarin within the previous 10 days or if you have any questions, concerns, signs of bleeding, or if you need to reschedule this appointment. ' + #13#10;
    end;
    if ckbWS.Checked = true then
    begin
      MNote := 'There is a ***CHANGE*** to your weekly Warfarin (Coumadin) dosing, please see the weekly dosing schedule below.' + #13#10;
      MNoteCl := 'Remember to let us know if you have missed Warfarin (Coumadin) doses, taken extra Warfarin (Coumadin) doses, or if you’ve had changes in your other medications, your diet, or your health.' + #13#10;
      //'Please contact us if you have missed any doses of warfarin within the previous 10 days or if you have any questions, concerns, signs of bleeding, or if you need to reschedule this appointment. ' + #13#10;
    end;
    memCL.Lines[0] := MNote;

    memCL.Visible := true;
    lblCL.Visible := true;
    btnCVL.Width := 90;
    btnCVL.Left := 125;
    btnCVL.Caption := '&Preview/Print';
  end
  else if btnCVL.Caption = '&Preview/Print' then
  begin
    Instruct := FilteredString(memCL.Text);
    PatientInstructions.Clear;
    PatientInstructions.Add(memCL.Text);

    // Fractional Tablet Formatting for Letter...
    // Sunday
    if Piece(edtCTSun.Text,'.',2) = '5' then
    begin
      if Piece(edtCTSun.Text,'.',1) = '0' then
        STab := '½'
      else
        STab := Piece(edtCTSun.Text,'.',1) + '½';
    end
    else if Piece(edtCTSun.Text,'.',2) = '25' then
    begin
      if Piece(edtCTSun.Text,'.',1) = '0' then
        STab := '¼'
      else
        STab := Piece(edtCTSun.Text,'.',1) + '¼';
    end
    else if Piece(edtCTSun.Text,'.',2) = '75' then
    begin
      if Piece(edtCTSun.Text,'.',1) = '0' then
        STab := '¾'
      else
        STab := Piece(edtCTSun.Text,'.',1) + '¾';
    end
    else
      STab := edtCTSun.Text;

    // Monday
    if Piece(edtCTMon.Text,'.',2) = '5' then
    begin
      if Piece(edtCTMon.Text,'.',1) = '0' then
        MTab := '½'
      else
        MTab := Piece(edtCTMon.Text,'.',1) + '½';
    end
    else if Piece(edtCTMon.Text,'.',2) = '25' then
    begin
      if Piece(edtCTMon.Text,'.',1) = '0' then MTab := '¼' //HD719861
      else
        MTab := Piece(edtCTMon.Text,'.',1) + '¼';
    end
    else if Piece(edtCTMon.Text,'.',2) = '75' then
    begin
      if Piece(edtCTMon.Text,'.',1) = '0' then
        MTab := '¾'
      else
        MTab := Piece(edtCTMon.Text,'.',1) + '¾';
    end
    else
      MTab := edtCTMon.Text;

    // Tuesday
    if Piece(edtCTTue.Text,'.',2) = '5' then
    begin
      if Piece(edtCTTue.Text,'.',1) = '0' then
        TTab := '½'
      else
        TTab := Piece(edtCTTue.Text,'.',1) + '½';
    end
    else if Piece(edtCTTue.Text,'.',2) = '25' then
    begin
      if Piece(edtCTTue.Text,'.',1) = '0' then
        TTab := '¼'
      else
        TTab := Piece(edtCTTue.Text,'.',1) + '¼';
    end
    else if Piece(edtCTTue.Text,'.',2) = '75' then
    begin
      if Piece(edtCTTue.Text,'.',1) = '0' then
        TTab := '¾'
      else
        TTab := Piece(edtCTTue.Text,'.',1) + '¾';
    end
    else
      TTab := edtCTTue.Text;

    // Wednesday
    if Piece(edtCTWed.Text,'.',2) = '5' then
    begin
      if Piece(edtCTWed.Text,'.',1) = '0' then
        WTab := '½'
      else
        WTab := Piece(edtCTWed.Text,'.',1) + '½';
    end
    else if Piece(edtCTWed.Text,'.',2) = '25' then
    begin
      if Piece(edtCTWed.Text,'.',1) = '0' then
        WTab := '¼'
      else
        WTab := Piece(edtCTWed.Text,'.',1) + '¼';
    end
    else if Piece(edtCTWed.Text,'.',2) = '75' then
    begin
      if Piece(edtCTWed.Text,'.',1) = '0' then
        WTab := '¾'
      else
        WTab := Piece(edtCTWed.Text,'.',1) + '¾';
    end
    else
      WTab := edtCTWed.Text;

    // Thursday
    if Piece(edtCTThu.Text,'.',2) = '5' then
    begin
      if Piece(edtCTThu.Text,'.',1) = '0' then
        HTab := '½'
      else
        HTab := Piece(edtCTThu.Text,'.',1) + '½';
    end
    else if Piece(edtCTThu.Text,'.',2) = '25' then
    begin
      if Piece(edtCTThu.Text,'.',1) = '0' then
        HTab := '¼'
      else
        HTab := Piece(edtCTThu.Text,'.',1) + '¼';
    end
    else if Piece(edtCTThu.Text,'.',2) = '75' then
    begin
      if Piece(edtCTThu.Text,'.',1) = '0' then
        HTab := '¾'
      else
        HTab := Piece(edtCTThu.Text,'.',1) + '¾';
    end
    else
      HTab := edtCTThu.Text;

    // Friday
    if Piece(edtCTFri.Text,'.',2) = '5' then
    begin
      if Piece(edtCTFri.Text,'.',1) = '0' then
        FTab := '½'
      else
        FTab := Piece(edtCTFri.Text,'.',1) + '½';
    end
    else if Piece(edtCTFri.Text,'.',2) = '25' then
    begin
      if Piece(edtCTFri.Text,'.',1) = '0' then
        FTab := '¼'
      else
        FTab := Piece(edtCTFri.Text,'.',1) + '¼';
    end
    else if Piece(edtCTFri.Text,'.',2) = '75' then
    begin
      if Piece(edtCTFri.Text,'.',1) = '0' then
        FTab := '¾'
      else
        FTab := Piece(edtCTFri.Text,'.',1) + '¾';
    end
    else
      FTab := edtCTFri.Text;

    // Saturday
    if Piece(edtCTSat.Text,'.',2) = '5' then
    begin
      if Piece(edtCTSat.Text,'.',1) = '0' then
        ATab := '½'
      else
        ATab := Piece(edtCTSat.Text,'.',1) + '½';
    end
    else if Piece(edtCTSat.Text,'.',2) = '25' then
    begin
      if Piece(edtCTSat.Text,'.',1) = '0' then
        ATab := '¼'
      else
        ATab := Piece(edtCTSat.Text,'.',1) + '¼';
    end
    else if Piece(edtCTSat.Text,'.',2) = '75' then
    begin
      if Piece(edtCTSat.Text,'.',1) = '0' then
        ATab := '¾'
      else
        ATab := Piece(edtCTSat.Text,'.',1) + '¾';
    end
    else
      ATab := edtCTSat.Text;
    // END - Fractional Tablet Formatting for Letter.

    if lblINRdt.Caption <> '' then
      inrit := 'Your last INR was ' + lblINRval.Caption + ' taken on ' + FormatDateTime('dddddd', StrToDate(lblINRdt.Caption));
    Doseit := 'Your weekly Warfarin (Coumadin) dose is (using a ' + cboPS.text + ' mg tablet):';
    NextAppStr := FormatDateTime('dddddd', dtpNextApp.DateTime);
    if dtpAppTime.Visible then
      NextAppStr := NextAppStr + ' at ' + FormatDateTime('hh:nn ampm', dtpAppTime.Time);
    case StrToInt(LetterINRTime) of
      0, 1:
        NextAppStr := NextAppStr + '.';
      2:
        NextAppStr := NextAppStr + ' in the morning.';
      3:
        NextAppStr := NextAppStr + ' in the afternoon.';
      4:
        NextAppStr := NextAppStr + ' per Lab procedures as directed.';
    end;
    RvProject.ProjectFile := NetworkPath + 'CVisit.rav';
    With RvProject do
    begin
      open;
      SetParam('Heading1', SiteHead);
      SetParam('siteadr1', SiteAddA);
      SetParam('FAX','FAX:      ' + ClinicFAX);
      if SiteAddB <> '' then
      begin
        SetParam('siteadr2', SiteAddB);
        SetParam('siteadr3', SiteAddC);
      end
      else
        SetParam('siteadr2', SiteAddC);

      SetParam('X', GName);
      SetParam('INR', inrit);
      SetParam('Date', lblINRdt.Caption);
      SetParam('adr1', lblSadr1.Caption);
      SetParam('adr2', lblSadr2.Caption);
      SetParam('adr3', lblSadr3.Caption);
      SetParam('adr4', lblCSZ.Caption);
      SetParam('SUNT', STab);
      SetParam('MONT', MTab);
      SetParam('TUET', TTab);
      SetParam('WEDT', WTab);
      SetParam('THUT', HTab);
      SetParam('FRIT', FTab);
      SetParam('SATT', ATab);
      SetParam('SUNM', edtCMSun.Text);
      SetParam('MONM', edtCMMon.Text);
      SetParam('TUEM', edtCMTue.Text);
      SetParam('WEDM', edtCMWed.Text);
      SetParam('THUM', edtCMThu.Text);
      SetParam('FRIM', edtCMFri.Text);
      SetParam('SATM', edtCMSat.Text);
      SetParam('addtext', Instruct);
      SetParam('ProvN', ProvName);
      SetParam('TDate', FormatDateTime('mmmm dd, yyyy', Today));
      SetParam('NextAppt', NextAppStr);
      SetParam('MNote', MNoteCl);
      SetParam('Dose', Doseit);
      SetParam('clinic', ClinicName);
      SetParam('phone', ClinicPhone);
      if TollFreePhone <> '' then
        SetParam('TollFreeTag', 'or call Toll-free:')
      else
        SetParam('TollFreeTag', '');
      SetParam('TollFree', TollFreePhone);
      SetParam('sig', SigName);
      SetParam('title', SigTitle);
      ExecuteReport('VComp');
      Close;
      FreeOnRelease;
    end;
    gbxCA.Visible := false;
    ToggleExitVisible(btnCV);
    btnCV.SetFocus;
  end;
end;

procedure TfrmAnticoagulate.btnYHxClick(Sender: TObject);
begin
  if InfoBox('Flow sheet data will be for a past INR. ' +
             'All information will refer to that past INR.' + CRLF + CRLF +
             'Be sure to COMPLETE (not temp save) the entry before exiting.' + CRLF +
             'No PCE data will be sent.', 'Past INR',
              MB_OKCANCEL or MB_ICONINFORMATION) = mrCancel then
  begin
    dtpINR.SetFocus;
    edtNewINR.Clear;
    Hist := 0;
    ckbNone.checked := false;
    lblHistory.Visible := false;
    btnYHx.Visible := false;
    btnNHx.Visible := false;
    pnlFee.visible := false;
    btnTempSave.Enabled := true;
    EnableChildControls(gbxPCE, true);
  end
  else
  begin
    Hist := 1;
    ckbNone.checked := true;
    lblLastINR.Caption := 'Old INR:';
    lblINRval.caption := edtNewInr.text;
    lblINRdt.caption := DateToStr(dtpINR.DateTime);
//  gbxINREnter.visible := false;
    lblHistory.Visible := false;
    btnYHx.Visible := false;
    btnNHx.Visible := false;
    {
    pnlFee.visible := true;
    rbFeeNo.SetFocus;
    }
    btnTempSave.Enabled := false;
    EnableChildControls(gbxPCE, false);
    btnNEntry.Click;
    pcinfo.ActivePage := tsNewFSEntry;
  end;
end;

procedure TfrmAnticoagulate.tsUpExit(Sender: TObject);
begin
  btnCUpdate.Click;
end;



procedure TfrmAnticoagulate.btnNHxClick(Sender: TObject);
begin
  btnCancel.Click;
  ckbNone.checked := false;
  EnableChildControls(gbxPCE, true);
  lblHistory.Visible := false;
  btnYHx.Visible := false;
  btnNHx.Visible := false;
end;

procedure TfrmAnticoagulate.btnMACloseClick(Sender: TObject);
begin
  gbxMA.Visible := false;
  ToggleExitVisible(Sender);
  btnMA.SetFocus;
end;

procedure TfrmAnticoagulate.memDCnoteChange(Sender: TObject);
begin
  // <CQ21998/>
  if ckbOther.Checked then
  begin
    if (Trim(memDCnote.Text) <> '') and (Trim(memDCNote.Text) <> Trim(DCNote)) then
      btnDCsign.Enabled := True
    else
      btnDCsign.Enabled := False;
  end
  else
    btnDCSign.Enabled := True;
end;

procedure TfrmAnticoagulate.memMAExit(Sender: TObject);
begin
  if (memMA.Text <> '') and not (memDCnote.Lines.Count > 0) then
  begin
    ckbMAInclInst.Enabled := true;
    ckbMAInclInst.SetFocus;
  end;
end;

procedure TfrmAnticoagulate.memMAKeyPress(Sender: TObject; var Key: Char);
begin
  if (Key = Chr(13)) then
  begin
    if (memMA.Lines.Count > 5) then
    begin
      InfoBox('Space on letter will not accept more than 5 lines of text.',
              'Line Limit Exceded', MB_OK or MB_ICONEXCLAMATION);
      exit;
    end;
  end;
end;

procedure TfrmAnticoagulate.memNewPtInstEnter(Sender: TObject);
begin
  memNewPtInst.SelStart := 0;
end;

procedure TfrmAnticoagulate.btnIntakeNoteClick(Sender: TObject);
var CodeSys: String;
begin
  CodeSys := 'ICD-9-CM';
  if FICD10Active then
    CodeSys := 'ICD-10-CM';

  // ** Don't procede if no indication specified
  if ((edtICD9.Text = '') or (cbxIndic.Text = '')) then
  begin
    InfoBox('Please choose a valid '+ CodeSys + ' indication before proceeding', 'Incomplete Encounter Information', MB_OK or MB_ICONEXCLAMATION);
    cbxIndic.SetFocus;
    exit;
  end;

  //Check whether location can be determined
  IdentifyCPT;
  if (Proced = '') and (ckbNone.Checked = false) then
  begin
    InfoBox('Please complete PCE Data before entering note.', 'Incomplete Encounter Information', MB_OK or MB_ICONEXCLAMATION);
    exit;
  end;

  ReturnFocus := Sender;
  memDCNOTE.Clear;
  pnlDCTop.Visible := false;
  btnDCGClose.Visible := false;

  GenerateIntakeNote;

  with gbxDC do
  begin
    Visible := true;
    align := alClient;
    pnlDCedt.Height := 290;
    pnlDCedt.Width := gbxdc.Width;
    pnlDCsign.Top := pnlDCedt.Height + 17;
    Caption := 'Anticoagulation Clinic Start Note';
  end;
  btnDCGClose.Visible := false;
  pnlDCedt.Visible := true;
  btnDC.Visible := true;
  btnDCsign.Enabled := TRUE;
  edtSigDC.Visible := true;
  lblDCSign.Visible := true;
  if NewPt <> 1 then
    edtSigDC.SetFocus
  else
  begin
    memDCNote.SetFocus;
    if ScreenReaderSystemActive then
      memDCnote.SelStart := 0;
  end;
  btnDCsign.Caption := '&Submit Note';
  AccessibilityManager.AccessText[btnDCsign] := 'Click to submit the changes to the Progress Note.';
  btnDC.Caption := '&Cancel';
  AccessibilityManager.AccessText[btnDC] := 'Click to discard changes to Progress Note.';
  ToggleExitVisible(Sender);
end;

procedure TfrmAnticoagulate.btnESCancelClick(Sender: TObject);
begin
  edtSig.text := '';
  gbxSig.visible := false;
end;

procedure TfrmAnticoagulate.edtSigKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = Chr(13) then btnESSubmit.Click;
end;

procedure TfrmAnticoagulate.SetEClinic;
begin
  if (rbPhoneS.Checked = true) or (rbPhoneC.Checked = true) or
     (rbLetter.Checked = true) then
  begin
    EClinic := PhoneClinic;
    SvcCat := 'T';
  end
  else
  begin
    EClinic := VisitClinic;
    SvcCat := 'A';
  end;
  if ckbNone.Checked = true then
    EClinic := NonCountClinic;
end;

procedure TfrmAnticoagulate.btnESSubmitClick(Sender: TObject);
var
  StartNote: TStrings;
  TempStr: String;
  i: Integer;
  aList: iORNetMult;
begin
  //submit note for CPRS
  CallVistA('ORAM SIGCHECK', [edtSig.Text], TempStr);
  if TempStr <> '1' then
  begin
    InfoBox('Please retype your signature code',
            'Invalid Signature Code', MB_OK or MB_ICONEXCLAMATION);
    edtSig.Text := '';
    exit;
  end;
  if NewPt = 1 then
  begin
    IndiText := 'Indication for anticoagulation: ' + cbxIndic.text;
    TargetT := 'INR Target Range: ' + cbxINRGoal.text;
    mDose := ' ';
    CINR := 'Current INR is ' + lblINRval.caption;
  end;
  StartNote := TStringList.Create;
  try
    with StartNote do
    begin
      Add(IndiText);
      Add(TargetT);
      Add(SevText);
      Add(mDose);
      Add(CINR);
      Add(fstext);
      Add(fstexta);
    end;

    SetEClinic;

    neworNetMult(aList);
    aList.AddSubscript(['TEXT','1','0'], ''); //command to stuff text

    if StartNote.Count > 0 then
      for I := 0 to StartNote.Count - 1 do
        aList.AddSubscript(['TEXT',IntToStr(i),'0'], FilteredString(StartNote[I]));

    CallVistA('TIU CREATE RECORD', [PDFN, Title, '', '', '', aList,
      EClinic + ';' + VisitDate + ';' + SvcCat], Notenumber);
  finally
    StartNote.Free;
  end;
  cofactor := 1;
  cosigner(Title);  //COSIGN CHECK   if CS = 1 then needs cosigner
  gbxSig.Visible := false;
  btnIntakeNote.Enabled := false;
  btnInterimNote.Enabled := false;
  btnDCstart.Enabled := false;
end;

procedure TfrmAnticoagulate.ckbBridgeCommentsClick(Sender: TObject);
var
  ii: integer;
begin
  if BridgeCommentDlg <> nil then
  begin
    with BridgeCommentDlg do
    begin
      if ckbBridgeComments.Checked then
      begin
        if (BridgeComments <> nil) and (BridgeComments.Count > 0) then
        begin
          memBridgeComments.Clear;
          memBridgeComments.Lines.AddStrings(BridgeComments);
        end;

        repeat
          ShowModal;
        until ((ModalResult = mrOK) or (ModalResult = mrCancel));

        if ModalResult = mrOK then
        begin
          BridgeComments.Clear;
          for ii := 0 to memBridgeComments.Lines.Count - 1 do
            BridgeComments.Add(FilteredString(memBridgeComments.Lines[ii]));
        end
        else
        begin
          memBridgeComments.Clear;
          memBridgeComments.Lines.AddStrings(BridgeComments);
        end;
        ckbBridgeComments.Checked := false;
      end;
    end;
  end;
end;

procedure TfrmAnticoagulate.ckbBridgingClick(Sender: TObject);
begin
  if BridgeCommentDlg <> nil then
  begin
    with BridgeCommentDlg do
    begin
      if ckbBridging.Checked then
      begin
        repeat
          ShowModal;
        until ((ModalResult = mrOK) or (ModalResult = mrCancel));

        if ModalResult = mrCancel then
        begin
          memBridgeComments.Clear;
          exit;
        end;
      end
      else
        memBridgeComments.Clear;
    end;
  end;
end;

procedure TfrmAnticoagulate.ckbCCClick(Sender: TObject);
begin
  if ckbCC.Checked = true then
  begin
    if compre < 1 then
    begin
      InfoBox('Please select a complication to comment on.',
              'Select Complication', MB_OK or MB_ICONEXCLAMATION);
      ckbCC.checked := false;
      exit;
    end;
    gbxComments.Visible := true ;
    gbxComments.SetFocus;
  end
  else
  gbxComments.Visible := false;
end;

procedure TfrmAnticoagulate.ckbDCClick(Sender: TObject);
begin
  if ckbDC.checked = true then
  begin
    ckbNoStop.checked := false;
    edtDur.enabled := false;
    lblStop.Enabled := true;
    edtStop.enabled := true;
    edtStop.Color := clWindow;
    edtStop.text := DateToStr(Now);
    lblComplex.caption := 'Inactive Patient';
    lblComplex.visible := true;
    dtpNextApp.visible := false;
    gbxReturnForINR.visible := false;
    if rbComp.Checked = true then
      rbComp.Checked := false;
    if rbStand.Checked = true then
      rbStand.Checked := false;
    rbStand.Enabled := false;
    rbComp.Enabled := false;
    ckbINROrder.Checked := false;
    ckbINROrder.Enabled := false;
    ckbCBC.Checked := false;
    ckbCBC.Enabled := false;
  end;
  if ckbDC.checked = false then
  begin
    edtDur.enabled := true;
    edtStop.enabled := false;
    lblStop.Enabled := false;
    edtStop.text := '';
    edtStop.Color := cl3dLight;
    lblComplex.caption := 'Complex Patient';
    lblComplex.visible := false;
    rbStand.Enabled := true;
    rbComp.Enabled := true;
    rbStand.Checked := true;
    dtpNextApp.visible := true;
    gbxReturnForINR.visible := true;
    if INRQuickOrder = '' then
    begin
      ckbINROrder.Checked := false;
      ckbINROrder.Enabled := false;
    end
    else
    begin
      ckbINROrder.Enabled := true;
      ckbINROrder.Checked := true;
    end;
    if CBCQuickOrder = '' then
      ckbCBC.Enabled := false
    else
      ckbCBC.Enabled := true;
    ckbCBC.Checked := false;
    if NextAppt <> 0 then
      dtpNextApp.DateTime := NextAppt
    else
      dtpNextApp.Date := Today;
  end;
end;

function TfrmAnticoagulate.PadString(InString: String): String;
var
  pad: String;
begin
  pad := '      ';
  result := Copy(pad, 0, (6 - Length(InString)));
end;

procedure TfrmAnticoagulate.btnInterimNoteClick(Sender: TObject);
var
  CodeSys: String;
begin
  CodeSys := 'ICD-9-CM';
  if FICD10Active then
    CodeSys := 'ICD-10-CM';

  //Check whether location can be determined
  IdentifyCPT;

  // ** Don't procede if no indication specified
  if ((edtICD9.Text = '') or (cbxIndic.Text = '')) then
  begin
    InfoBox('Please choose a valid ' + CodeSys + ' indication before proceeding', 'Incomplete Encounter Information', MB_OK or MB_ICONEXCLAMATION);
    cbxIndic.SetFocus;
    exit;
  end;

  if (Proced = '') and (ckbNone.Checked = false) then
  begin
    InfoBox('Please complete PCE Data before entering note.', 'Incomplete Encounter Information', MB_OK or MB_ICONEXCLAMATION);
    exit;
  end;

  ReturnFocus := Sender;
  memDCNOTE.Clear;
  pnlDCTop.Visible := false;
  btnDCGClose.Visible := false;

  GenerateInterimNote;

  with gbxDc do
  begin
    Visible := true;
    align := alClient;
    pnlDCedt.Height := 290;
    pnlDCedt.Width := gbxdc.Width;
    pnlDCsign.Top := pnlDCedt.Height+17;
    Caption := 'Interim Progress Note';
  end;
  pnlDCedt.Visible := true;
  btnDCGClose.Visible := false;
  btnDC.Visible := true;
  btnDCsign.Enabled := TRUE;
  edtSigDC.Visible := true;
  lblDCSign.Visible := true;
  memDCnote.SetFocus;
  if ScreenReaderSystemActive then
    memDCnote.SelStart := 0;
  btnDCsign.Caption := '&Submit Note';
  AccessibilityManager.AccessText[btnDCsign] := 'Click to submit the changes to the Progress Note.';
  btnDC.Caption := '&Cancel';
  AccessibilityManager.AccessText[btnDC] := 'Click to discard changes to Progress Note.';
  ToggleExitVisible(Sender);
end;

procedure TfrmAnticoagulate.rbFeePrimClick(Sender: TObject);
begin
  if rbFeePrim.checked = true then
  begin
    lblexp.visible := true;
    dtpExp.visible := true;
    FB := 1;
  end
end;

procedure TfrmAnticoagulate.rbFeeSecClick(Sender: TObject);
begin
  if rbFeeSec.checked = true then
  begin
    lblexp.visible := true;
    dtpExp.visible := true;
    FB := 2;
  end;
end;

procedure TfrmAnticoagulate.rbFeeNoClick(Sender: TObject);
begin
  if rbFeeNo.checked = true then
  begin
    lblexp.visible := false;
    dtpExp.visible := false;
    FB := 0;
  end;
end;

procedure TfrmAnticoagulate.cboPSExit(Sender: TObject);
begin
  with cboPS do
    if ((NewPt = 1) and (Text = '')) then
    begin
      InfoBox('Pill Strength is required for New Patients.' + CRLF +
              'Please enter a valid strenght in milligrams (e.g., 5)...',
              'Pill Strength Required',
               MB_OK or MB_ICONEXCLAMATION);
      SetFocus;
      exit;
    end;
  PillDoseOr := PillDose;
  PillDose := StrToFloat(cboPS.text);
  if (PillDose < 1) or (cboPS.Text = '') then
    PillDose := PillDoseOr
  else
  begin
    TabletsReset;
  end;
end;

procedure TfrmAnticoagulate.btnNoINRClick(Sender: TObject);
begin
  if btnNoINR.Caption = 'C&lear INR' then
  begin                                   //SMT don't clear again. HD523093
    if lblINRval.caption <> '' then
      inrold := lblINRval.caption;
    if lblINRdt.caption <> '' then
      inrdold := lblINRdt.caption;

    lblINRval.caption := '';
    lblINRdt.caption := '';
    lblINRdt.TabStop := false;
    lblNINRval.Caption := '';
    lblNidate.Caption := lblINRdt.Caption;
    btnNoINR.Caption := '&Undo';
  end
  else
  begin
    lblINRval.caption := inrold;
    lblINRdt.caption := inrdold;
    if lblINRdt.Caption = '' then
      lblINRdt.TabStop := false;
    lblNINRval.Caption := inrold;
    lblNidate.Caption := lblINRdt.Caption;
    btnNoINR.Caption := 'C&lear INR';
  end;
end;

procedure TfrmAnticoagulate.ckbPmsgClick(Sender: TObject);
begin
  if ckbPmsg.checked = true then
  begin
    memPeople.color := clWindow;
    memPeople.Enabled := True;
    memPeople.ReadOnly := False;
  end
  else
  begin
    memPeople.color := clMenu;
    memPeople.Enabled := False;
    memPeople.ReadOnly := True;
    memPeople.Clear;
  end;
end;

procedure TfrmAnticoagulate.tsFlowExit(Sender: TObject);
begin
  if btnDD.Caption = '&OK' then
  begin
    InfoBox('Please ACCEPT or CANCEL changes to daily dosing',
            'Accept Changes', MB_OK or MB_ICONEXCLAMATION);
    pcMain.ActivePage := tsFlow;
  end;
end;

procedure TfrmAnticoagulate.tsFlowShow(Sender: TObject);
var
  rr: integer;
begin
  if stgAC.Cells[0, 1] = '' then
  begin
    btnEdit.Enabled := false;
    InfoBox('This tab is designed for editing existing flowsheet entries,' + CRLF +
      'but none are yet available for this patient.' + CRLF + CRLF +
      'Please use the Enter Information tab to create an initial entry.',
      'No Flowsheet Entries', MB_OK or MB_ICONEXCLAMATION);
  end
  else if stgAC.RowCount > 1 then
  begin
    rr := stgAC.RowCount - 1;
    while (rr > 0) and (stgAC.Cells[0, rr] = '') do
      Dec(rr);
    if rr <= 0 then
      rr := 1;
    stgAC.Col := 0;
    stgAC.Row := rr;
  end;
end;

procedure TfrmAnticoagulate.btnNGCloseClick(Sender: TObject);
begin
  gbxINRset.Visible := false;
  gbxContactInfo.Visible := true;
  cbxINRGoal.SetFocus;
end;

procedure TfrmAnticoagulate.btnNGOKClick(Sender: TObject);
var
  tempStr: string;
begin
  if (Length(edtMin.text) = 0) or (Length(edtMax.text) = 0) then
  begin
    InfoBox('Please complete all fields', 'Incomplete Record', MB_OK or MB_ICONEXCLAMATION);
    exit;
  end;
  if (StrToFloat(edtMin.Text) > StrToFloat(edtMax.Text)) then
  begin
    tempStr := edtMin.Text;
    edtMin.Text := edtMax.Text;
    edtMax.Text := tempStr;
  end;
  INRGOAL := edtMin.text + '-' + edtMax.text;
  cbxINRGoal.Text := INRGOAL;
  gbxINRset.Visible := false;
  chrtINR.Title.Text[0] := 'INR  (Goal: ' + cbxINRGoal.Text + ')';
  //changes the goal % to cooincide with new goals
  lblPCgoal.Enabled := false;
  gbxContactInfo.Visible := true;
  cbxINRGoal.SetFocus;
end;

procedure TfrmAnticoagulate.edtPDCChange(Sender: TObject);
begin
   If (Trim(edtPDC.Text) <> '') and (Trim(memDC.Text) <> '') then
   btnDCsign.Enabled := True
  else
   btnDCsign.Enabled := False;
end;

procedure TfrmAnticoagulate.edtPMoveChange(Sender: TObject);
begin
  If Trim(edtPMove.Text) <> '' then
   btnDCsign.Enabled := True
  else
   btnDCsign.Enabled := False;
end;

procedure TfrmAnticoagulate.edtPtNoteKeyPress(Sender: TObject; var Key: Char);
begin
  if key = chr(13) then memNCom.SetFocus;
end;

procedure TfrmAnticoagulate.btnESCloseClick(Sender: TObject);
begin
         gbxSig.Visible := FALSE;
end;

procedure TfrmAnticoagulate.btnXPCEnter(Sender: TObject);
begin
  pnlXPC.Visible := true;
end;

procedure TfrmAnticoagulate.btnXPCExit(Sender: TObject);
begin
  pnlXPC.Visible := false;
end;

procedure TfrmAnticoagulate.lblPercentInGoalMouseEnter(Sender: TObject);
begin
  pnlXPC.Visible := true;
  pnlCount.Visible := false;
end;

procedure TfrmAnticoagulate.lblPercentInGoalMouseLeave(Sender: TObject);
begin
      pnlXPC.Visible := false;
end;

procedure TfrmAnticoagulate.btnXCompClick(Sender: TObject);
begin
  compre := 0;
  ckbMCDeath.Checked := false;
  ckbMCR.Checked := false;
  ckbMCH.Checked := false;
  ckbMChgb.Checked := false;
  ckbMCtran.Checked := false;
  ckbMinorC.Checked := false;
  ckbTT.Checked := false;
  ckbMCother.Checked := false;
  memMCother.Clear;
  ckbCC.Checked := false;
  pcInfo.ActivePage := tsHidden;
end;

procedure TfrmAnticoagulate.btnXPCClick(Sender: TObject);
var
  i: Integer;
begin
  memXPC.Lines.Clear;
  sbxXPC.Visible := true;
  pnlPC.Visible := true;
  pnlTWeek.Visible := false;
  var rpcResults := TStringList.Create;
  try
    CallVistA('ORAM2 ALLGOAL', [edtXDays.Text, Piece(ClinicRef, ';', 1)], rpcResults);
    if rpcResults.Count <> 0 then
    begin
      lblXPC.Caption := SiteName + ': ';
      if rpcResults[0] = '' then
        lblXPC.Caption := lblXPC.Caption + 'No Activity Last ' + edtXDays.Text + ' days.'
      else
        lblXPC.Caption := lblXPC.Caption + rpcResults[0] + '% Last ' + edtXDays.Text + ' days.';

      for i := 1 to rpcResults.Count - 1 do
      begin
        memXPC.lines.Add(rpcResults[i]);
      end;
      lblXPC.SetFocus;
    end;
  finally
    rpcResults.Free;
  end;
end;

procedure TfrmAnticoagulate.btnTWeekClick(Sender: TObject);
begin
  sbxXPC.Visible := true;
  pnlPC.Visible := false;
  pnlTWeek.Visible := true;
  lblBOX.Caption := SiteName + ': Forty-five Day Clinic Load';
  memTWeek.Clear;
  var rpcResults := TStringList.Create;
  try
    CallVistA('ORAM2 PTAPPT', [Piece(ClinicRef, ';', 1)], rpcResults);
    if (rpcResults.Count <> 0) then
      memTWeek.Lines := rpcResults;
  finally
    rpcResults.Free;
  end;
  lblBOX.SetFocus;
end;

procedure TfrmAnticoagulate.lbl45DayLoadMouseEnter(Sender: TObject);
begin
  pnlCount.Visible := true;
  pnlXPC.Visible := false;
end;


procedure TfrmAnticoagulate.lbl45DayLoadMouseLeave(Sender: TObject);
begin
  pnlCount.Visible := false;
end;

procedure TfrmAnticoagulate.btnFileCClick(Sender: TObject);
var mcomp:string;
begin
  if compre < 1 then
  begin
    InfoBox('Nothing to file.', 'No Changes Made', MB_OK or MB_ICONINFORMATION);
    exit;
  end;
  mcomp := '';
  if InfoBox('This will file JUST the complications report and exit.' + CRLF +
             'No other information will be saved.',
             'File Complications Only', MB_OKCANCEL or MB_ICONINFORMATION) = mrCancel then
    exit;
  if compre > 0 then
  begin
    mcomp := complications;
    mcomp := mcomp + '^         entered: '+datetostr(today)+' -'+ ProvInit;
    CallVistA('ORAM3 COMPENT', [PDFN, PDUZ, inttostr(compre), mcomp, DATETOSTR(dtpComp.Date)]);
  end;
  CallVistA('ORAM1 UNLOCK', [PDFN]);
  Application.Terminate;
end;

procedure TfrmAnticoagulate.btnLostClick(Sender: TObject);
begin
  sbxXPC.Visible := true;
  pnlPC.Visible := true;
  pnlTWeek.Visible := true;
  lblXPC.Caption := '';
  lblBOX.Caption := SiteName + ': Patients Lost to Follow-Up';
  memTWeek.Clear;
  var rpcResults := TStringList.Create;
  try
    CallVistA('ORAM2 NOACT', [edtLTF.Text, Piece(ClinicRef, ';', 1)], rpcResults);
    if (rpcResults.Count <> 0) then
      memTWeek.Lines := rpcResults
    else
      memTWeek.Lines[0] := 'No patient lost to follow-up noted';
  finally
    rpcResults.Free;
  end;
  lblBOX.SetFocus;
end;

procedure TfrmAnticoagulate.ckbHoldClick(Sender: TObject);
begin
  if ckbHold.Checked = true then
  begin
    ckbTake.Checked := false;
    edtTTabs.Text := '';
    //edtTDays.Text := '';
    ckbWS.Checked := false;
    btnCVL.Enabled := true;
    if not (memDCNote.Lines.Count > 0) then
      ckbCAInclInst.Enabled := true;
    btnCVL.Width := 75;
    btnCVL.Caption := '&OK';
    memCL.Clear;
  end
  else
  begin
    btnCVL.Enabled := false;
    ckbCAInclInst.Enabled := false;
  end;
end;

procedure TfrmAnticoagulate.ckbTakeClick(Sender: TObject);
begin
    if ckbTake.Checked = true then
    begin
        ckbHold.Checked := false;
        edtHDays.Text := '';
        ckbWS.Checked := false;
        btnCVL.Enabled := true;
        if not (memDCnote.Lines.Count > 0) then
          ckbCAInclInst.Enabled := true;
        btnCVL.Width := 75;
        btnCVL.Caption := '&OK';
        memCL.Clear;
    end
    else
    begin
      btnCVL.Enabled := false;
      ckbCAInclInst.Enabled := false;
    end;
end;

procedure TfrmAnticoagulate.ckbTTClick(Sender: TObject);
begin
              with sender as tcheckbox do
              begin
                 if checked = true then
                 begin
                        compre := compre+100;
                        ckbCC.Checked := true;
                 end
                 else if compre>0 then
                 begin
                      compre := compre-100;
                      if memMCother.Lines.Count<1 then ckbCC.Checked := false;
                 end;
              end;
end;

procedure TfrmAnticoagulate.ckbWSClick(Sender: TObject);
begin
  if ckbWS.Checked = true then
  begin
    ckbHold.Checked := false;
    edtHDays.Text := '';
    ckbTake.Checked := false;
    edtTTabs.Text := '';
    btnCVL.Enabled := true;
    if not (memDCnote.Lines.Count > 0) then
      ckbCAInclInst.Enabled := true;
    btnCVL.Width := 75;
    btnCVL.Caption := '&OK';
    memCL.Clear;
  end
  else
  begin
    btnCVL.Enabled := false;
    ckbCAInclInst.Enabled := true;
  end;
end;

procedure TfrmAnticoagulate.cbxSiteExit(Sender: TObject);
begin
  if cbxSite.Text = '' then
  begin
    InfoBox('Must have a Clinic selected to proceed.', 'Clinic Required', MB_OK or MB_ICONEXCLAMATION);
//    pcmain.ActivePage := tsDem;
    cbxSite.SetFocus;
  end;
end;

procedure TfrmAnticoagulate.cbxSiteSelect(Sender: TObject);
begin
  if csLoading in ComponentState then
    Exit;
  if FCreateProgress <> FCP_FINISH then
    Exit;
  if cbxSite.ItemIndex > -1 then
  begin
    ClinicRef := Piece(cbxSite.Items[cbxSite.ItemIndex], '^', 2);
    LocationChanged := (PtLocation <> ClinicRef);
    GetParameters(ClinicRef);
    CallVistA('ORAM APPTMTCH', [PDFN, ClinicRef], VisitDate);
    if NewPt = 1 then
    begin
      if PillDoseOr > 0 then
        PillDose := PillDose
      else
        PillDose := DefaultPillStrength;
      cboPS.SelectByID(FloatToStr(PillDose));
      if cboPS.Text = '' then
        cboPS.Text := FloatToStr(PillDose);
      TabletsReset;
    end;
  end;
end;

procedure TfrmAnticoagulate.chrtINREnter(Sender: TObject);
var
  i: Integer;
begin
  if ScreenReaderSystemActive then
  begin
    GetScreenReader.Speak('This chart plots INR as a function of time.');
    if serINR.Count = 0 then
      GetScreenReader.Speak('There are no INR values to report.');
    with serINR do
    begin
      for i := 0 to Count - 1 do
      begin
        GetScreenReader.Speak('The INR value was ' + YValueToText(YValue[i]));
        GetScreenReader.Speak('on ' + XLabel[i]);
      end;
    end;
  end;
end;

function TfrmAnticoagulate.ApplicationEvents1Help(Command: Word;
  Data: NativeInt; var CallHelp: Boolean): Boolean;
begin
  LoadHelpFile(Application.HelpFile);
  Result := True;
end;

procedure TfrmAnticoagulate.btnCAClick(Sender: TObject);
begin
  gbxCA.Visible := false;
  if rbMC.Checked = true then
  begin
    rbMC.Enabled := true;
    pnlMChange.Visible := true;
    btnCVL.Enabled := true;
    if not (memDCnote.Lines.Count > 0) then
      ckbCAInclInst.Enabled := true;
    rbMC.Checked := true;
    ckbWS.Checked := false;
    ckbTake.Checked := false;
    edtTTabs.Text := '';
    ckbHold.Checked := false;
    edtHDays.Text := '' ;
    MNote := '';
    memCL.Visible := false;
    lblCL.Visible := false;
    btnCVL.Width := 75;
    btnCVL.Caption := '&OK';
  end;
  if rbNoMC.Checked = true then
  begin
    memCL.Clear;
    rbNoMC.Checked := false;
    rbNoMC.Enabled := true;
    pnlMChange.Visible := false;
    MNote := '';
    memCL.Visible := false;
    lblCL.Visible := false;
    btnCVL.Enabled := true;
    if not (memDCnote.Lines.Count > 0) then
      ckbCAInclInst.Enabled := true;
    btnCVL.Width := 75;
    btnCVL.Caption := '&OK';
  end;
  ToggleExitVisible(btnCV);
  btnCV.SetFocus;
end;

procedure TfrmAnticoagulate.lblLTFQueryMouseEnter(Sender: TObject);
begin
    pnlLTF.Visible := true;
    pnlCount.Visible := false;
end;

procedure TfrmAnticoagulate.lblLTFQueryMouseLeave(Sender: TObject);
begin
     pnlLTF.Visible := false;
end;

procedure TfrmAnticoagulate.ckbPMoveClick(Sender: TObject);
begin
    if ckbPMove.Checked = true then
    begin
        ckbPViol.Checked := false;
        ckbPtDC.Checked := false;
        edtPDC.Text := '';
        memDC.clear;
        memDC.Visible := false;
        ckbOther.Checked := false;
        edtPMove.Enabled := true;
        edtPMove.Color := clWindow;
        If Trim(edtPMove.Text) <> '' then
         btnDCsign.Enabled := True;
    end else
    begin
     btnDCsign.Enabled := false;
     edtPMove.Enabled := False;
     edtPMove.Color := cl3DLight;
    end;
end;

procedure TfrmAnticoagulate.ckbPViolClick(Sender: TObject);
begin
       if ckbPViol.Checked = true then
    begin
        ckbPMove.Checked := false;
        edtPMove.Text := '';
        ckbPtDC.Checked := false;
        edtPDC.Text := '';
        memDC.Clear;
        memDC.Visible := false;
        ckbOther.Checked := false;
        btnDCsign.Enabled := true;
    end else btnDCsign.Enabled :=false;
end;

procedure TfrmAnticoagulate.btnDCGCloseClick(Sender: TObject);
begin
  gbxDC.Visible := false;
  btnDC.Enabled := true;
  btnDCGClose.Visible := true;
  ckbPMove.Checked := false;
  ckbPtDC.Checked := false;
  ckbPViol.Checked := false;
  ckbOther.Checked := false;
  memDCnote.Clear;
  dcexit := 0;
  ToggleExitVisible(ReturnFocus);
  btnDCsign.Caption := '&Sign Note';
  (ReturnFocus as TButton).SetFocus;
end;

procedure TfrmAnticoagulate.ckbPtDCClick(Sender: TObject);
begin
  if ckbPtDC.Checked = true then
  begin
    if (pos(':', lblDCFor.Caption) = 0) then
      lblDCFor.Caption := lblDCFor.Caption + ':';
    memDC.Visible := true;
    pnlDCTop.Height := pnlDCTop.Height - 17;
    edtPDC.Enabled := true;
    edtPDC.Color := clWindow;
    dtpDC.Enabled := true;
    dtpDC.Color := clWindow;
    ckbPViol.Checked := false;
    ckbPMove.Checked := false;
    edtPMove.Text := '';
    ckbOther.Checked := false;
    ckbOther.Visible := false;
    //zzzzzzbellc
    if ((Trim(edtPDC.text) <> '') and (memDC.Lines.Count > 0)) then //zzzzzzbellc
      btnDCsign.Enabled := true;
  end
  else
  begin
    edtPDC.Enabled := false;
    edtPDC.Color := cl3DLight;
    dtpDC.Enabled := false;
    dtpDC.Color := cl3DLight;
    memDC.Visible := false;
    ckbOther.Visible := true;
    pnlDCTop.Height := DCTOPHEIGHT;
    pnlDCedt.Visible := false;
    memDC.Text := '';
    btnDCsign.Enabled := False;
  end;
end;

procedure TfrmAnticoagulate.ckbOtherClick(Sender: TObject);
begin
    if ckbOther.Checked = true then
    begin
      ckbPViol.Checked := false;
      ckbPtDC.Checked := false;
      edtPDC.Text := '';
      memDC.Clear;
      memDC.Visible := false;
      ckbPMove.Checked := false;
      edtPMove.Text := '';
    end else btnDCsign.Enabled := false;
end;




procedure TfrmAnticoagulate.btnDCClick(Sender: TObject);
var
  r:Integer;
begin
  edtSigDC.Visible := false;
  lblDCSign.Visible := false;
  pnlDCsign.Align := alBottom;
  if btnDC.Caption = '&Cancel' then
  begin
    memDCnote.Clear;
    dcexit := 0;
    pnlDCedt.Visible := false;
    ckbPMove.Checked := False;
    ckbPViol.Checked := false;
    ckbPtDC.Checked := false;
    ckbOther.Checked := False;
    btnDC.Caption := '&View/Edit';
    AccessibilityManager.AccessText[btnDC] := 'Click to view and edit Progress Note.';
    btnDCsign.Caption := '&Sign Note';
    AccessibilityManager.AccessText[btnDCsign] := 'Click to apply your electronic signature to the Progress Note.';
    gbxDC.Visible := false;
    edtSigDC.Visible := true;
    lblDCSign.Visible := true;
    ToggleExitVisible(ReturnFocus);
    (ReturnFocus as TButton).SetFocus;
  end
  else
  begin
    if ckbPMove.Checked = true then
    begin
      if edtPMove.Text = '' then
      begin
        InfoBox('Please indicate where anticoagulation management will be transferred to.',
                'Destination Needed', MB_OK or MB_ICONEXCLAMATION);
        edtPMove.SetFocus;
        exit;
      end
      else
      begin
        DCNote := 'Patient has moved from the ' + SiteName + ' service area and will be transferring anticoagulation management to ' + edtPMove.text;
      end;
    end //if PMOVE checked
    else if ckbPViol.Checked = true then
      DCNote := 'Patient has not maintained conditions of Anticoagulation Treatment Agreement.  He/she has been notified that they have been discharged from this clinic, and will no longer receive warfarin from this facility.'
    else if ckbPtDC.Checked = true then
    begin
      if ((edtPDC.text = '') or (memDC.Lines.Count = 0)) then
      begin
        InfoBox('Please add required information',
                'Required Information Needed', MB_OK or MB_ICONEXCLAMATION);
        exit;
      end
      else
      begin
        reason := '';
        for r := 0 to memDC.lines.Count - 1 do
          reason := reason + #13#10 + FilteredString(memDC.lines[r]);
        DCNote := 'Anticoagulation discontinued on ' + DateToStr(dtpDC.DateTime) + ' by ' + edtPDC.text + ' for the following reason: ' + reason + #13#10;
      end;
    end  // PtDC checked
    else if ckbOther.Checked = true then
    begin
      btnDCsign.Enabled := true;
      DCNote := 'Patient discharged from Anticoagulation Clinic for the following reason(s): ' + #13#10;
      InfoBox('Please add discharge reason to note.', 'Discharge Reason Needed',
               MB_OK or MB_ICONEXCLAMATION);
    end
    else
    begin
      InfoBox('Must check one of the options.', 'Information Required', MB_OK or MB_ICONEXCLAMATION);
      btnDC.Caption := '&View/Edit';
      AccessibilityManager.AccessText[btnDC] := 'Click to view and edit Progress Note.';
      btnDCsign.Caption := '&Sign Note';
      AccessibilityManager.AccessText[btnDCsign] := 'Click to apply your electronic signature to the Progress Note.';
      lblDCSign.Visible := false;
      edtSigDC.Visible := false;
      exit;
    end;
    lblNBox.Caption := 'Anticoag Discharge Note:';
    pnlDCedt.Visible := true;
    pnlDCTop.Visible := false;
    btnDCGClose.Visible := false;
    edtSigDC.Visible := true;
    lblDCSign.Visible := true;
    pnldcedt.Height := pnlDCsign.top - 10;
    btnDC.caption := '&Cancel';
    AccessibilityManager.AccessText[btnDC] := 'Click to discard changes to Progress Note.';
    btnDCsign.Enabled := TRUE;
    memDCnote.Lines[0] := DCNote;
    memDCnote.SetFocus;
    if ScreenReaderSystemActive then
      memDCnote.SelStart := 0;
    dcexit := 1;
  end;
end;

procedure TfrmAnticoagulate.btnDCCloseClick(Sender: TObject);
begin
  pnlDCedt.Visible := false;
  memDCnote.Clear;
  edtSigDC.Visible := false;
  lblDCSign.Visible := false;
  btnDC.Caption := '&View/Edit';
  AccessibilityManager.AccessText[btnDC] := 'Click to view and edit Progress Note.';
  btnDC.Enabled := true;
  btnDCsign.Caption := '&Sign Note';
  AccessibilityManager.AccessText[btnDCsign] := 'Click to apply your electronic signature to the Progress Note.';
  btnDCGClose.Visible := true;
end;

procedure TfrmAnticoagulate.btnDCsignClick(Sender: TObject);
var
  s: Integer;
  TempStr: String;
  aList: iORNetMult;
begin
  if btnDCsign.Caption = '&Sign Note' then
  begin
    lblDCSign.Visible := true;
    edtSigDC.Visible := true;
    edtSigDC.SetFocus;
    btnDCsign.Caption := '&Submit Note';
    AccessibilityManager.AccessText[btnDCsign] := 'Click to submit the changes to the Progress Note.';
  end
  else if btnDCsign.Caption = '&Submit Note' then
  begin
    CallVistA('ORAM SIGCHECK', [edtSigDC.Text], TempStr);
    if (TempStr <> '1') and (edtSigDC.Text <> '') then
    begin
      InfoBox('Please retype your signature code',
              'Invalid Signature Code', MB_OK or MB_ICONEXCLAMATION);
      edtSigDC.Text := '';
      edtSigDC.SetFocus;
      exit;
    end
    else
    begin
      if edtSigDC.Text = '' then
      begin
        if (InfoBox('Would you like to save your note without signing?',
                    'Save Without Signature?', MB_YESNO or MB_ICONQUESTION) = mrNo) then
        begin
          edtSigDC.Text := '';
          edtSigDC.SetFocus;
          exit;
        end;
      end;
      if Title = DischargeNote then
      begin
        if InfoBox('Sending a Discharge note will also inactivate patient from anticoagulation clinic.  Send Note?',
                   'Confirm Discharge', MB_YESNO or MB_ICONQUESTION) = mrNo then
          exit;
        if dcexit <> 1 then btnDC.Click;
      end;

      edtSigDC.Visible := false;
      lblDCSign.Visible := false;
      SetEClinic;
      neworNetMult(aList);
      for s := 0 to memDCnote.Lines.Count - 1 do
        aList.AddSubscript(['TEXT',IntToStr(s+1),'0'],  FilteredString(memDCnote.Lines[s]));
      CallVistA('TIU CREATE RECORD', [PDFN, Title, '', '', '', aList,
        EClinic + ';' + VisitDate + ';' + SvcCat], NoteNumber);
      cofactor := 1;
      cosigner(Title); //COSIGN CHECK   if CS = 1 then needs cosigner
      if Title = DischargeNote  then
        ckbDC.Checked := true;
      gbxDC.Visible := false;
      btnIntakeNote.Enabled := false;
      btnInterimNote.Enabled := false;
      btnDCstart.Enabled := false;
    end;  // good sig
    ToggleExitVisible(ReturnFocus);
  end; // but is submit now
  btnComp.SetFocus;
end;


procedure TfrmAnticoagulate.btnDCstartClick(Sender: TObject);
var
  CodeSys: String;
begin
  //DC NOTE

  CodeSys := 'ICD-9-CM';
  if FICD10Active then
    CodeSys := 'ICD-10-CM';

  // ** Don't procede if no indication specified
  if ((edtICD9.Text = '') or (cbxIndic.Text = '')) then
  begin
    InfoBox('Please choose a valid ' + CodeSys + ' indication before proceeding', 'Incomplete Encounter Information', MB_OK or MB_ICONEXCLAMATION);
    cbxIndic.SetFocus;
    exit;
  end;

  btnDCsign.Enabled := false;
  ReturnFocus := Sender;
  pnlDCTop.Visible := true;
  btnDCGClose.Visible := true;
  with gbxDc do
  begin
    align := alNone;
    Visible := true;
    height := BHGHT;
    top := BTOP;
    width := BWIDTH;
    left := BLFT;
    pnlDCsign.Top := 90;
    pnlDCedt.Width := gbxdc.Width;
    Caption := 'D/C from ' + SiteName + ' Anticoagulation Clinic note';
  end;
  btnDCGClose.Visible := true;
  pnlDCedt.Visible := false;
  edtSigDC.Visible := false;
  lblDCSign.Visible := false;
  Title := DischargeNote;     //'3057';
  dtpDC.Date := Now;
  btnDC.Caption := '&View/Edit';
  AccessibilityManager.AccessText[btnDC] := 'Click to view and edit Progress Note.';
  ToggleExitVisible(Sender);
  ckbPMove.SetFocus;
end;

procedure TfrmAnticoagulate.ToggleExitVisible(Sender: TObject);
begin
  pnlLettNote.Visible := not pnlLettNote.Visible;
  if ((Sender = btnIntakeNote) or (Sender = btnInterimNote)) then
  begin
    gbxReturnForINR.Visible := not gbxReturnForINR.Visible;
    gbxLabs.Visible := not gbxLabs.Visible;
    gbxPCE.Visible := not gbxPCE.Visible;
    btnTempSave.Visible := not btnTempSave.Visible;
    btnComp.Visible := not btnComp.Visible;
  end;
end;

procedure TfrmAnticoagulate.edtSDateExit(Sender: TObject);
begin
  with edtSDate do
    if (Text = '') then
    begin
      InfoBox('You must supply a Start Date.' + CRLF +
              'Please enter valid date (or “pending,” “refused,” or “unknown”)...', 'Start Date Required',
               MB_OK or MB_ICONEXCLAMATION);
      SetFocus;
    end;
end;

function TfrmAnticoagulate.IsGUIVersionOK: boolean;
var
 chkVer, ReqVer: String;
begin
  chkVer := FileVersionValue(Application.ExeName, FILE_VER_FILEVERSION);
  CallVistA('ORWU PARAM', ['ORAM GUI VERSION'], ReqVer);
  if not VersionOK(chkVer, ReqVer) then
  begin
    TaskMessageDlg('Version Mismatch', Format('Unable to start %s.' + #13 + #13 +
        'This version ''%s'' is not the correct version.' + #13 + #13 +
        '''%s'' is the required version.',
        [Application.ExeName, chkVer, ReqVer]),
        mtError, [mbOk], 0);
    Result := false;
  end else
   Result := true;
end;

function TfrmAnticoagulate.CheckDrawDay: Boolean;
var
  dow: Word;
  weekend: Integer;
begin
  //dayoftheweek
  dow := DayOfTheWeek(dtpNextApp.Date);
  //these statements check for return date of Sat or Sun and change to Monday
  if dow = 6 then
  begin
    weekend := InfoBox('You''ve selected a Saturday. Are you sure?' + CRLF + CRLF
                + '(If not, we''ll increment the draw date to Monday).', 'Saturday Draw Date', MB_YESNO or MB_ICONQUESTION);
    if (weekend = IDNO) then
      dtpNextApp.Date := IncDay(dtpNextApp.date, 2);
  end;
  if dow = 7 then
  begin
    weekend := InfoBox('You''ve selected a Sunday. Are you sure?' + CRLF + CRLF
                + '(If not, we''ll increment the draw date to Monday).', 'Sunday Draw Date', MB_YESNO or MB_ICONQUESTION);
    if (weekend = IDNO) then
      dtpNextApp.Date := IncDay(dtpNextApp.date, 1);
  end;
  //checks for do not draw days
  if pnlNoDraw.Visible = true then
  begin
    if ckbRM.Checked = true then
      restr := '1';
    if ckbRT.Checked = true then
      restr := restr + '2';
    if ckbRW.Checked = true then
      restr := restr + '3';
    if ckbRTh.Checked = true then
      restr := restr + '4';
    if ckbRF.Checked = true then
      restr := restr + '5';
    if Pos(inttostr(dow), restr) > 0 then
    begin
      InfoBox('This is a "no draw" day, please use calender to adjust it.', 'No Draw Day', MB_OK or MB_ICONEXCLAMATION);
      result := false;
      exit;
    end;
  end;
  result := true;
end;

procedure TfrmAnticoagulate.edtSigDCKeyPress(Sender: TObject; var Key: Char);
begin
  if key = chr(13) then
  begin
    btnDCsign.Caption := '&Submit Note';
    AccessibilityManager.AccessText[btnDCsign] := 'Click to submit the changes to the Progress Note.';
    btnDC.Caption := '&View/Edit';
    AccessibilityManager.AccessText[btnDC] := 'Click to view and edit Progress Note.';
    btnDCsign.Click;
  end;
end;

procedure TfrmAnticoagulate.btnConsultClick(Sender: TObject);
{  INC5452451 - The REQUESTING PACKAGE REFERENCE field (#1405) in the TIU
                DOCUMENT record (^TIU(8925) was not being set when the record
                was linked to a consult.  Calls to DDR GETS ENTRY DATA and
                DDR FILER were added to resolve the issue.  DDR GETS ENTRY
                DATA retrieves the value of the field; if no value exists,
                DDR FILER sets the value to link the record to the consult. tjl}
var
  iConsult: Integer;
  sLinkInfo, sResults: String;
  aList: iORNetMult;
begin
  iConsult := 0;
  if lbxConsult.Count = 1 then  // when only one Consult is listed, use that record
     iConsult := StrToInt(Piece(lbxConsult.Items[0], '^', 2))
  else if lbxConsult.ItemIndex = -1 then  // display a message dialog if no item is selected
     InfoBox('Please highlight consult to complete', 'Choose Consult', MB_OK or MB_ICONEXCLAMATION)
  else   // get the Consult number from the item selected in the list
     iConsult := StrToInt(Piece(lbxConsult.Items[lbxConsult.ItemIndex], '^', 2));

  if iConsult > 0 then  // Consult selected
     begin
       pnlConsult.Visible := FALSE;
       neworNetMult(aList);
       aList.AddSubscript(['FIELDS'], '1405');
       aList.AddSubscript(['FILE'], '8925');
       aList.AddSubscript(['FLAGS'], 'I');
       aList.AddSubscript(['IENS'], NoteNumber);

       CallVistA('DDR GETS ENTRY DATA', [aList], sResults);

       if Piece(sResults, '^', 4) = '' then  // If the field is empty, link the consult
          begin
            // Link Info - FileNo ^ FieldNo ^ TIU IEN ^ iConsult;GMR(123,
            sLinkInfo := '8925^1405^' + NoteNumber + '^' + IntToStr(iConsult) + ';GMR(123,';
            neworNetMult(aList);
            aList.AddSubscript(['1'], sLinkInfo);

            CallVistA('DDR FILER', ['EDIT', aList], sResults);

            if Pos('[Data]',sResults) = 0 then
               InfoBox('Problem encountered attempting to update the REQUESTING PACKAGE REFERENCE field (#1405) of the TIU record.'
               + CRLF + 'Unable to link the consult to the record.', 'Consult Not Linked', MB_OK or MB_ICONEXCLAMATION);
          end
       else
          InfoBox('The record has already been linked to a consult.', 'Consult Not Linked', MB_OK or MB_ICONEXCLAMATION);

       CallVistA('ORAM CONCOMP', [IntToStr(iConsult), NoteNumber, PDUZ], sResults);

       if sResults <> '1' then
          InfoBox('Unable to complete consult.', 'Consult Incomplete', MB_OK or MB_ICONEXCLAMATION)
       else
          begin
            InfoBox('Consult completed; alert sent.', 'Consult Complete', MB_OK or MB_ICONEXCLAMATION);
            NoteNumber := '';
          end;
     end;

  frmAnticoagulate.Close;
end;

procedure TfrmAnticoagulate.btnCanConClick(Sender: TObject);
begin
    pnlConsult.Visible := false;
    notenumber := '';
    frmAnticoagulate.Close;
end;

procedure TfrmAnticoagulate.btnEditClick(Sender: TObject);
begin
  if btnEdit.Caption = '&Edit' then
  begin
    btnEdit.Width := 95;
    btnEdit.Left := 253;
    btnEdit.Hint := 'Edit Complete';
    btnEdit.Caption := 'Edit &Complete';
    lblACAct.Caption := 'EDIT MODE';
    lblACAct.Font.Color := clYellow;
    lblACAct.Color := clBlack;
    stgAC.Color := clYellow;
    InfoBox('Select row to edit any or all contents (including COMMENTS).',
            'Select Row', MB_OK or MB_ICONEXCLAMATION);
  end
  else
  begin
    lblACAct.Caption := 'Anticoagulation Activity (in order of INR entry)';
    stgAC.Color := clWindow;
    lblACAct.Font.Color := clWindowText;
    lblACAct.Color := cl3DLight;
    btnEdit.Caption := '&Edit';
    btnEdit.Width := 75;
    btnEdit.Left := 263;
  end;
end;

procedure TfrmAnticoagulate.btnEditCanClick(Sender: TObject);
begin
      btnEdit.Click;
      stgAC.Enabled := true;
      gbxEdit.Caption := 'EDIT MODE';
      edtEditINR.Text := '';
      edtPtNote.Text := '';
      edtTWD.Text := '';
      gbxEdit.Visible := false;
      memEDIT.Clear;
end;



procedure TfrmAnticoagulate.ckbEditDelClick(Sender: TObject);
begin
  if ckbEditDel.Checked = true then
  begin
    if InfoBox('This will delete the flow sheet entry associated with this specific date.  OK?',
                'Delete Flowsheet Entry', MB_YESNO or MB_ICONQUESTION) = mrNo then
    begin
      ckbEditDel.Checked := false;
      exit;
    end
    else
    begin
      dtpEdit.Date := StrToDate(Ldate);
      edtEditINR.Text := '';
      edtPN.Text := '';
      edtTWD.Text := '';
      memEDIT.Clear;
      btnEditOK.Click;
      ckbEditDel.Checked := false;
    end;
  end;
end;

procedure TfrmAnticoagulate.btnEditOKClick(Sender: TObject);
var
  newFS:TStrings;
  j,row:Integer;
  comp:STRING;
  aList: iORNetMult;
begin
  if InfoBox('This will change the file NOW.  OK?', 'Apply Changes',
              MB_YESNO or MB_ICONQUESTION) = mrNo then
    exit;
  comp := '';

  if ckbEditCompR.Checked = true then
  begin
    memEDIT.Lines.Add('Complication entry deleted by: ' + ProvInit + ' on ' + DateToStr(Date));
    comp := '0';
  end;

  if ckbEditDel.Checked = true then
    memEDIT.Lines.Add('Entry deleted by: ' + ProvInit + ' on ' + DateToStr(Date))
  else
  begin
    memEDIT.Lines.Add('Edited by: ' + ProvInit + ' - ' + DatetimeToStr(now));
    memEDIT.Lines.Add(lline);
  end;

  newFS := TStringList.Create;
  try
    with newFS do
    begin
      Add(PDFN);
      Add(FSien);
      Add(DatetoStr(dtpEdit.Date));
      Add(edtEditINR.Text);
      Add(edtPN.Text);
      Add(edtTWD.Text);
      Add(PDUZ);
      Add(IntToStr(memEDIT.Lines.Count));
      for j := 0 to (memEDIT.Lines.Count-1) do
        Add(FilteredString(memEDIT.Lines[j]));
    end;
    neworNetMult(aList);
    for j := 0 to newFS.Count - 1 do
      aList.AddSubscript([IntToStr(j)], newFS[j]);
    CallVistA('ORAM1 LOG', [aList, comp]);
  finally
    newFS.Free;
  end;

  row := StrToInt(FSrow);
  stgAC.Cells[0,row] := DatetoStr(dtpEdit.Date);
  stgAC.Cells[1,row] := edtEditINR.Text;
  stgAC.Cells[2,row] := edtPN.Text;
  stgAC.Cells[3,row] := edtTWD.Text;
  CommArr[row-1].Assign(memEDIT.Lines);
  memComm.Lines := CommArr[row - 1];
  lblFS.Caption := 'Comments:';
  btnEdit.Click;
  stgAC.Enabled := true;
  gbxEdit.Caption := 'EDIT MODE';
  edtEditINR.Text := '';
  edtPtNote.Text := '';
  edtTWD.Text := '';
  gbxEdit.Visible := false;
  memEDIT.Clear;
end;

procedure TfrmAnticoagulate.btnRemindClick(Sender: TObject);
begin
  pnlRemind.Visible := true;
  if btnRemind.Caption = 'Set &Reminder' then
    dtpRemind.Date := Today;
  dtpRemind.SetFocus;
end;

procedure TfrmAnticoagulate.btnRCanClick(Sender: TObject);
begin
  ckbRestrict.Checked := FALSE;
  btnROK.Width := 20;
  btnROK.Caption := '&OK';
  ckbRM.Checked := false;
  ckbRT.Checked := false;
  ckbRW.Checked := false;
  ckbRTh.Checked := false;
  ckbRF.Checked := false;
  pnlRestrict.Visible := FALSE;
  pnlNoDraw.Visible := false;
end;

procedure TfrmAnticoagulate.btnRemCanClick(Sender: TObject);
begin
  pnlRemind.Visible := false;
end;

procedure TfrmAnticoagulate.btnRemOKClick(Sender: TObject);
VAR
  RStr, ADate: String;
begin
  if memRemind.Lines.Count < 1 then
    InfoBox('Please enter the reminder text', 'Reminder Text Needed', MB_OK or MB_ICONEXCLAMATION)
  else if CompareDate(dtpRemind.Date, Now) <> 1 then
    InfoBox('Reminder date must be in the future', 'Future Dates Only', MB_OK or MB_ICONEXCLAMATION)
  else
  begin
    remindmsg := 1;
    pnlRemind.Visible := false;
    btnRemind.Caption := 'View &Reminder';
    InfoBox('Reminder Set', 'Reminder Complete', MB_OK or MB_ICONINFORMATION);
    if NewPt <> 1 then
    begin
      if InfoBox('Do you want to EXIT the program at this time?',
               'Exit Now?', MB_YESNO or MB_ICONQUESTION) = mrNo then
        exit
      else
      begin
        RStr := FilterTextPreserveLines(memRemind.Lines.Text);
        ADate := DateToStr(dtpRemind.Date);
        CallVistA('ORAM2 REMIND', [PDFN, ADate,RStr]);
        frmAnticoagulate.Close;
      end; //else
    end; //not NewPt
  end;
end;

procedure TfrmAnticoagulate.btnRemClearClick(Sender: TObject);
begin
  remindmsg := 2;      //clear reminder
  memRemind.Clear;
  dtpRemind.Date := Today;
  pnlRemind.visible := false;
  btnRemind.Caption := 'Set &Reminder';
  InfoBox('Reminder will be eliminated upon completion.', 'Reminder Cleared', MB_OK or MB_ICONEXCLAMATION);
end;

procedure TfrmAnticoagulate.btnCloseInstrClick(Sender: TObject);
begin
  pnlNewPt.Visible := false;
  ToggleDemVisible;
  chrtINR.SetFocus;
end;

procedure TfrmAnticoagulate.btnSExitClick(Sender: TObject);
var
  ListIdentified: String;
begin
  if InfoBox('This will update heading information in the file and exit the program. No flow sheet entry will be made. OK?',
             'Update Preferences & Exit', MB_YESNO or MB_ICONQUESTION) = mrNo then
    exit
  else
  begin
    btnCUpdate.Click;
    AddTop;
    //if pt. is being discharged from the clinic, remove pt. from current list
    if ckbDC.Checked then
    begin
      try
        CallVistA('ORAM1 TERASE', [PDFN, ListName], ListIdentified);
        if Piece(ListIdentified, '^', 1) = '0' then
          InfoBox(Piece(ListIdentified, '^', 2) + CRLF + 'Please notify your CAC.',
            'Clinic Parameter Undefined', MB_OK or MB_ICONWARNING);
      except
        Application.HandleException(Self)
      end;
    end;
    Application.Terminate;
  end;
end;

// <CQ22001>

procedure TfrmAnticoagulate.edtNewHCTKeyPress(Sender: TObject; var Key: Char);
begin
  FloatFilter(Sender, Key, 1);
end;

procedure TfrmAnticoagulate.edtNewInrKeyPress(Sender: TObject; var Key: Char);
begin
  FloatFilter(Sender, Key);
end;

// <CQ22001/>

procedure TfrmAnticoagulate.edtODateExit(Sender: TObject);
begin
  with edtOdate do
    if ((NewPt = 1) and (Text = '')) then
    begin
      InfoBox('Orientation Date is required for New Patients.' + CRLF +
              'Please choose a valid date...', 'Orientation Date Required',
               MB_OK or MB_ICONEXCLAMATION);
      SetFocus;
    end;
end;

procedure TfrmAnticoagulate.edtDurExit(Sender: TObject);
begin
  with edtDur do
    if ((NewPt = 1) and (Text = '')) then
    begin
      InfoBox('Duration is required for New Patients.' + CRLF +
              'Please enter valid number of days (or indefinite)...', 'Duration Required',
               MB_OK or MB_ICONEXCLAMATION);
      SetFocus;
    end;
end;

procedure TfrmAnticoagulate.edtDurKeyPress(Sender: TObject; var Key: Char);
var
  tl: string;
begin
  tl := IntToStr(Length(edtDur.Text) + 1);
  if StrToInt(tl) >= 30 then
  begin
    InfoBox('Reached character limit', 'Long Duration', MB_OK or MB_ICONEXCLAMATION);
    edtDur.Text := LeftStr(edtDur.text, 30);
  end;
end;

// <CQ22000>

procedure TfrmAnticoagulate.edtLFaxKeyPress(Sender: TObject; var Key: Char);
begin
  if not CharInSet(Key, ['0'..'9', '(', ')', '-', 'x', 'X', #8]) then
    Key := #0;
end;

procedure TfrmAnticoagulate.edtLocChange(Sender: TObject);
var
  lt: String;
begin
  lt := edtLoc.Text;
  lt := StringReplace(StringReplace(lt, #10, ' ', [rfReplaceAll]), #13, '', [rfReplaceAll]);
  edtLoc.Text := lt;
end;

procedure TfrmAnticoagulate.edtLocKeyPress(Sender: TObject; var Key: Char);
begin
  if not CharInSet(Key, ['0'..'9', 'A'..'Z', 'a'..'z', ',', #32, #8]) then
    Key := #0;
end;

procedure TfrmAnticoagulate.edtLPhoneKeyPress(Sender: TObject; var Key: Char);
begin
  if not CharInSet(Key, ['0'..'9', '(', ')', '-', 'x', 'X', #8]) then
    Key := #0;
end;

// <CQ22000/>

// <CQ22001>

procedure TfrmAnticoagulate.edtMaxKeyPress(Sender: TObject; var Key: Char);
begin
  if not CharInSet(Key, ['0'..'9', #8, FormatSettings.DecimalSeparator]) then
    Key := #0;
end;

procedure TfrmAnticoagulate.edtMinKeyPress(Sender: TObject; var Key: Char);
begin
  if not CharInSet(Key, ['0'..'9', #8, FormatSettings.DecimalSeparator]) then
    Key := #0;
end;

// <CQ22001/>

procedure TfrmAnticoagulate.btnUnlockClick(Sender: TObject);
begin
  pnlPtLookUp.Visible := true;
  CallVistA('ORAM1 GETPT', [], orbxPTlU.Items);
  orbxPTlU.SetFocus;
end;

procedure TfrmAnticoagulate.btnCancelUnlockClick(Sender: TObject);
begin
  pnlPtLookUp.Visible := false;
end;

procedure TfrmAnticoagulate.btnUnlockRecClick(Sender: TObject);
VAR
  ptien: string;
begin
  ptien := Piece(orbxPTlU.Items[orbxPTlU.ItemIndex],'^',1);
  CallVistA('ORAM1 UNLOCK', [ptien]);
  pnlPtLookUp.Visible := false;
end;

procedure TfrmAnticoagulate.btnSwitchClick(Sender: TObject);
var
  stable: string;
begin
  if gbxPC.Caption = 'Percent in Goal (stable):' then
  begin
    gbxPC.Caption := 'Percent in Goal (ALL):';
    stable := '';
  end
  else
  begin
    gbxPC.Caption := 'Percent in Goal (stable):';
    stable := '1';
  end;
  CallVistA('ORAM1 PCGOAL', [PDFN,stable], pcgoal);
  lblPCgoal.Caption := Piece(pcgoal, '^', 1) + '%';
  lbldenom.Caption := 'of ' + Piece(pcgoal, '^', 2) + ' INR values:';
  if ScreenReaderSystemActive then
  begin
    GetScreenReader.Speak(gbxPC.Caption);
    GetScreenReader.Speak(lblDenom.Caption);
    GetScreenReader.Speak(lblPCGoal.Caption);
  end;
end;

procedure TfrmAnticoagulate.btnMissedApptClick(Sender: TObject);
begin
  noshow := 3;
  btnNoINR.Caption := 'C&lear INR';
  btnNoINR.Click;
  InfoBox('Missed appointment flag set.', 'Flag Set', MB_OK or MB_ICONINFORMATION);
end;

procedure TfrmAnticoagulate.cbxINRGoalClick(Sender: TObject);
begin
  frmAnticoagulate.FormStyle := fsNormal;
end;

procedure TfrmAnticoagulate.cbxINRGoalCloseUp(Sender: TObject);
begin
  if cbxINRGoal.Text <> 'Other' then
    INRColor();  //rsf 7/31/08
end;

procedure TfrmAnticoagulate.cbxINRGoalDropDown(Sender: TObject);
begin
  temprge := cbxINRGoal.Text;
end;

procedure TfrmAnticoagulate.cbxINRGoalExit(Sender: TObject);
begin
  with cbxINRGoal do
  begin
    if ((NewPt = 1) and (Text = '')) then
    begin
      InfoBox('INR Goal Range is required for New Patients.' + CRLF +
              'Please choose a valid range...', 'INR Goal Range Required',
               MB_OK or MB_ICONEXCLAMATION);
      SetFocus;
    end
    else if ((not gbxINRset.Visible) and (Text = 'Other')) then
    begin
      InfoBox('No specific INR Goal Range entered.' + CRLF +
              'Please specify a valid range...', 'INR Goal Range Required',
               MB_OK or MB_ICONEXCLAMATION);
      SetFocus;
    end;
  end;
end;

// <CQ21999>

procedure TfrmAnticoagulate.cbxINRGoalKeyPress(Sender: TObject; var Key: Char);
begin
  if not CharInSet(Key, ['0'..'9', 'o', 'O', FormatSettings.DecimalSeparator, '-', #8, #13]) then
    Key := #0;
end;

// <CQ21999/>

procedure TfrmAnticoagulate.tsDemMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  frmAnticoagulate.FormStyle := fsNormal;
end;

procedure TfrmAnticoagulate.tsExitShow(Sender: TObject);
begin
  if (NoteNumber = '') then
  begin
    if (NewPt = 1) then
    begin
      IdentifyCPT;
      if (edtICD9.Text <> '') and (Proced <> '') and (Proced <> '0') then
      begin
        if (gbxDC.Visible = false) then
          btnIntakeNote.Click
        else
        if memDCnote.Lines.Text = GeneratedNoteText then
        begin
          memDCnote.Lines.Clear;
          GenerateIntakeNote;
        end;
      end;
    end
    else
    begin
      if gbxDC.Visible and (memDCnote.Lines.Text = GeneratedNoteText) then
      begin
        memDCnote.Lines.Clear;
        if Title = InterimNote then
          GenerateInterimNote
        else if Title = IntakeNote then
          GenerateIntakeNote;
      end;
    end;
  end;
end;

procedure TfrmAnticoagulate.pcInfoChange(Sender: TObject);
begin
  if pcinfo.ActivePage = tsNewFSEntry then
    btnNEntry.Click;
end;

procedure TfrmAnticoagulate.pcMainChange(Sender: TObject);
begin
  frmAnticoagulate.FormStyle := fsNormal;
  if cbxSite.text = '' then
  begin
    InfoBox('Must have a Clinic selected to proceed.', 'Clinic Required', MB_OK or MB_ICONEXCLAMATION);
    pcmain.ActivePage := tsDem;
    cbxSite.SetFocus;
  end;
end;

procedure TfrmAnticoagulate.pnlRemindEnter(Sender: TObject);
begin
  if ScreenReaderSystemActive then
    GetScreenReader.Speak('Enter the date of the Reminder.');
end;

procedure TfrmAnticoagulate.btnPlus14Click(Sender: TObject);
var
  XDATE: TDate;
begin
  with Sender as TButton do
  begin
    XDATE := today;
    if lblINRdt.Caption <> '' then
      XDATE := strtodate(lblINRdt.Caption)
    else if lblINRdt.Caption = '' then
      XDATE := today;
    if Name = btnPlus14.Name then
    begin
      dtpNextApp.Date := IncDay(XDATE, 14);
    end
    else if Name = btnPlus28.Name then
    begin
      dtpNextApp.Date := IncDay(xdate, 28);
    end;

    if (CompareDate(dtpNextApp.Date, today) < 0) then
    begin
      if Name = btnPlus14.Name then
      begin
        dtpNextApp.Date := IncDay(today, 14);
      end
      else if Name = btnPlus28.Name then
      begin
        dtpNextApp.Date := IncDay(today, 28);
      end;
    end;
  end;

  CheckDrawDay;
  dtpNextApp.SetFocus;
  dtpNextApp.InitiateAction;
end;

procedure TfrmAnticoagulate.btnROKClick(Sender: TObject);
begin
  btnROK.Width := 50;
  btnROK.Caption := '&Revise';
  restr := '';
  if ckbRM.Checked = true then
    restr := '1';
  if ckbRT.Checked = true then
    restr := restr + '2';
  if ckbRW.Checked = true then
    restr := restr + '3';
  if ckbRTh.Checked = true then
    restr := restr + '4';
  if ckbRF.Checked = true then
    restr := restr + '5';
  InfoBox('Changes will be made upon completion of the visit.',
          'Changes Applied on Completion', MB_OK or MB_ICONINFORMATION);
  pnlNoDraw.Visible := true;
  lblNoDraw.Caption := '';
  if Pos('1', restr) > 0 then
    lblNoDraw.Caption := 'Mon';
  if Pos('2', restr) > 0 then
    lblNoDraw.Caption := lblNoDraw.Caption + ' Tues';
  if Pos('3', restr) > 0 then
    lblNoDraw.Caption := lblNoDraw.Caption + ' Wed';
  if Pos('4', restr) > 0 then
    lblNoDraw.Caption := lblNoDraw.Caption + ' Thurs';
  if Pos('5', restr) > 0 then
    lblNoDraw.Caption := lblNoDraw.Caption + ' Fri';
end;

procedure TfrmAnticoagulate.ckbRestrictClick(Sender: TObject);
begin
  if ckbRestrict.Checked = true then
    pnlRestrict.Visible := true
  else
    pnlRestrict.Visible := false;
end;

initialization
  SpecifyFormIsNotADialog(TfrmAnticoagulate);

end.
