Index: cprs/branches/HealthSevak-CPRS/CPRS-Chart/Orders/fODMeds.pas
===================================================================
--- cprs/branches/HealthSevak-CPRS/CPRS-Chart/Orders/fODMeds.pas	(revision 1676)
+++ cprs/branches/HealthSevak-CPRS/CPRS-Chart/Orders/fODMeds.pas	(revision 1693)
@@ -189,4 +189,15 @@
     procedure cboXSequenceEnter(Sender: TObject);
     procedure txtRefillsChange(Sender: TObject);
+    procedure QuantityMessageCheck(Tag: integer)  ;
+    procedure pnlXDurationButtonEnter(Sender: TObject);
+    procedure cboRouteKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
+    procedure cboScheduleKeyUp(Sender: TObject; var Key: Word;
+      Shift: TShiftState);
+    procedure cboXScheduleKeyUp(Sender: TObject; var Key: Word;
+      Shift: TShiftState);
+    procedure cboXSequenceKeyUp(Sender: TObject; var Key: Word;
+      Shift: TShiftState);
+    procedure cboPriorityKeyUp(Sender: TObject; var Key: Word;
+      Shift: TShiftState);
     //procedure btnNSSClick(Sender: TObject);
   private
@@ -289,5 +300,5 @@
     procedure UpdateDefaultSupply(const CurUnits, CurSchedule, CurDuration, CurDispDrug: string;
       var CurSupply: Integer; var CurQuantity: double; var SkipQtyCheck: Boolean);
-    procedure UpdateSupplyQuantity(const CurUnits, CurSchedule, CurDuration, CurDispDrug: string;
+    procedure UpdateSupplyQuantity(const CurUnits, CurSchedule, CurDuration, CurDispDrug, CurInstruct: string;
       var CurSupply: Integer; var CurQuantity: double);
     procedure UpdateDurationControls( FreeText: boolean);
@@ -397,4 +408,5 @@
   FLD_COMMENT   = 80;
   FLD_PTINSTR   = 85;
+  FLD_DRUG_ID_INT = 90;
   {dosage type tab index values}
   TI_DOSE       =  0;
@@ -542,4 +554,8 @@
   end;
   if self.EvtID > 0  then FAdminTimeText := 'To Be Determined';
+  if (isIMO = True) then self.Caption := 'Clinic Orders Medications'
+  else if FInptDlg = True then self.Caption := 'Inpatient Medications'
+  else if DlgFormID = OD_MEDOUTPT then self.Caption := 'Outpatient Medications'
+  else self.Caption := 'Medications Orders';
   ListForOrderable(FCacheIEN, ListCount, x);
   lstAll.Items.Count := ListCount;
@@ -614,6 +630,6 @@
 procedure TfrmODMeds.SetupDialog(OrderAction: Integer; const ID: string);
 var
-  AnInstr, OrderID, nsSch, Text, tempOrder, tempSchString, tempSchType, AdminTime: string;
-  ix: integer;
+  AnInstr, OrderID, nsSch, Text, tempOrder, tempSchString, tempSchType, AdminTime, x: string;
+  i, ix: integer;
   LocChange: boolean;
   AResponse: TResponse;
@@ -631,5 +647,5 @@
   //AGP 27.72 Order Action behave similar to QO this is why Edit and Copy are setting FIsQuickOrder to true
   //this is not the best approach but this should fix the problem with order edit losing the quantity value.
-  if (OrderAction = ORDER_QUICK) or (OrderAction = ORDER_EDIT) or (OrderAction = ORDER_COPY) then
+  if ((OrderAction = ORDER_QUICK) or (OrderAction = ORDER_EDIT) or (OrderAction = ORDER_COPY)) then
   begin
     FIsQuickOrder := True;
@@ -647,4 +663,15 @@
     Changing := True;
     txtMed.Tag  := StrToIntDef(Responses.IValueFor('ORDERABLE', 1), 0);
+    if OrderAction = ORDER_QUICK then
+      begin
+        if DEACheckFailed(txtMed.Tag, FInptDlg) then
+          begin
+            //btnSelect.Visible := False;
+            btnSelect.Enabled := False;
+            InfoBox(TX_NO_DEA, TC_NO_DEA, MB_OK);
+            AbortOrder := True;
+            Exit;
+          end;
+      end;
     if (OrderAction = ORDER_QUICK) and (uOrders.PassDrugTstCall = False) and
      (uOrders.OutptDisp = OutptDisp) and (PassDrugTest(txtMed.Tag, 'Q', false) = False) then Exit;
@@ -672,5 +699,5 @@
              if length(nsSch) > 0 then
              begin
-                SetSchedule(nsSch);
+                SetSchedule(UpperCase(nsSch));
                 {cboSchedule.SelectByID(nsSch);
                 if cboSchedule.ItemIndex < 0 then
@@ -694,5 +721,5 @@
               AResponse := Responses.FindResponseByName('ADMIN', 1);
               if AResponse <> nil then AdminTime := AResponse.EValue;
-              if self.cboSchedule.ItemIndex > -1 then
+              if (self.cboSchedule.ItemIndex > -1) and (AdminTime <> '') then
                 begin
                   tempSchString := self.cboSchedule.Items.Strings[cboSchedule.itemindex];
@@ -700,5 +727,5 @@
                   self.cboSchedule.Items.strings[cboSchedule.ItemIndex] := tempSchString;
                 end;
-              if self.tabDose.TabIndex = TI_COMPLEX then
+              if (self.tabDose.TabIndex = TI_COMPLEX) and (Responses.InstanceCount('INSTR') = 1) and (AdminTime <> '') then
                 begin
                   if self.cboXSchedule.ItemIndex > -1 then
@@ -722,5 +749,5 @@
                      end;
                   end;
-               if self.tabDose.TabIndex = TI_COMPLEX then
+               if (self.tabDose.TabIndex = TI_COMPLEX) and (Responses.InstanceCount('INSTR') = 1) then
                 begin
                   if self.cboXSchedule.ItemIndex > -1 then
@@ -742,5 +769,27 @@
       end;
     if ((OrderAction <> Order_COPY) and (OrderAction <> Order_EDIT)) or
-    (XfInToOutNow = true) or (FIsQuickOrder) then UpdateRelated(FALSE); //AGP Change
+       (XfInToOutNow = true) or (FIsQuickOrder) then
+       begin
+         UpdateRelated(FALSE); //AGP Change
+         //Need to do the following code to reset the FLastUnits and FLastSchedule in case a free text Dose is found. If the following
+         //code is not done than the quantity will reset to zero
+         if not FInptDlg  then
+         begin
+           FLastUnits := '';
+           FLastSchedule := '';
+           FLastInstruct := '';
+           //Lasti := Responses.InstanceCount('INSTR');
+           //Lasti := Responses.NextInstance('DOSE', 0);
+           for I := 1 to Responses.InstanceCount('INSTR') do
+             begin
+               x := ValueOfResponse(FLD_DOSEUNIT,  i);
+               FLastUnits  := FLastUnits   + x  + U;
+               x := Responses.IValueFor('INSTR',    i);
+               FLastInstruct := FLastInstruct + x + U;
+               x := ValueOfResponse(FLD_SCHEDULE,  i);
+               FLastSchedule := FLastSchedule + x + U;
+             end;
+         end;
+       end;
     Changing := False;
     if ((OrderAction = Order_Copy) or (OrderAction = Order_Edit)) and
@@ -762,4 +811,5 @@
     memComment.Clear;  // sometimes the sig is in the comment
   end;
+  FQOInitial := False;
   ControlChange(Self);
   if Self.IsSupply then
@@ -818,4 +868,9 @@
     ADrug  := ValueOfResponse(FLD_DRUG_ID,  AnInstance);
     tmpX := x; //Changed for CQ: 7370 - it was tmpX := Trim(x);
+    if Pos(CRLF, tmpX)> 0 then
+      begin
+        SetError('Schedule cannot contains control characters');
+        Exit;
+      end;
     if (Length(tmpX) = 0) and (not FInptDlg) then SetError(TX_NO_SCHED)
     else if (Length(tmpX) = 0) and FInptDlg and ScheduleRequired(txtMed.Tag, ARoute, ADrug)
@@ -824,4 +879,8 @@
     begin
       if FInptDlg then ValidLevel := ValidSchedule(tmpX) else ValidLevel := ValidSchedule(tmpX, 'O');
+   (*   if FInptDlg and (tmpX <> '') and (cboSchedule.ItemIndex = -1) and
+      (self.tabDose.TabIndex = TI_DOSE) then
+         //SetError('Unique Schedule Selection Required');
+         SetError('More than one schedule starts with "'+tmpX+'". Please select a schedule from the list.');  *)
       if ValidLevel = SCH_NO_RTN then
       begin
@@ -857,6 +916,13 @@
       if Length(Responses.IValueFor('INSTR', i)) > 60       then
       begin
-         SetError(TX_DOSE_LEN);
-         cboDosage.SetFocus;  //CQ: 7467
+         if self.tabDose.TabIndex = TI_COMPLEX then
+           begin
+              SetError('Dosage: ' + Responses.IValueFor('INSTR', i) + CRLF + TX_DOSE_LEN);
+           end
+         else
+           begin
+              SetError(TX_DOSE_LEN);
+              cboDosage.SetFocus;  //CQ: 7467
+           end;
       end;
     end;
@@ -889,4 +955,12 @@
                 Exit;
               end;
+           if Uppercase(ValFor(Col_Sequence, i)) = 'THEN' then
+             begin
+                if ValFor(Col_Duration,i) = '' then
+                  begin
+                    SetError('A duration is required when using "Then" as a sequence.');
+                    Exit;
+                  end;
+             end;
          end;
     end;
@@ -1318,7 +1392,10 @@
   chunk := GetCacheChunkIndex(Item.Index);
   list := TStringList(FMedCache[chunk]);
-  x := list[Item.Index mod MED_CACHE_CHUNK_SIZE];
-  Item.Caption := Piece(x, U, 2);
-  Item.Data := Pointer(StrToIntDef(Piece(x, U, 1), 0));
+  //This is to make sure that the index that is being used is not outside of the stringlist
+  If Item.Index mod MED_CACHE_CHUNK_SIZE < list.Count then begin
+   x := list[Item.Index mod MED_CACHE_CHUNK_SIZE];
+   Item.Caption := Piece(x, U, 2);
+   Item.Data := Pointer(StrToIntDef(Piece(x, U, 1), 0));
+  end;
 end;
 
@@ -1415,5 +1492,4 @@
         end; *)
       FAltChecked := True;
-      ;
       SetOnMedSelect;   // set up for this medication
       SetOnQuickOrder;  // insert quick order responses
@@ -1424,4 +1500,5 @@
       if (txtQuantity.Text = '0') and (Length(QOQuantityStr)>0) then
         txtQuantity.Text := QOQuantityStr;
+      //FQOInitial := False;
     end
     else if (FActiveMedList = lstAll) and (lstAll.Selected <> nil) then  // orderable item
@@ -1453,6 +1530,7 @@
       begin
         temp := self.MedName;
-        CheckFormularyOI(MedIEN, temp, FInptDlg);
+        CheckFormularyOI(medIEN, temp, FInptDlg);
         FAltChecked := True;
+        txtMed.Text := '';
       end;
       if MedIEN <> txtMed.Tag then
@@ -1481,4 +1559,6 @@
   else ShowMedSelect;                             // show the selection fields
   FNoZERO   := False;
+  if FQOInitial = True then FQOInitial := False;
+  
 end;
 
@@ -1585,5 +1665,5 @@
     // set up lists & initial values based on orderable item
     SetControl(txtMed,       'Medication');
-    if (self.MedName <> '') then
+        if (self.MedName <> '') then
        begin
          if (txtMed.Text <> self.MedName) then
@@ -1603,5 +1683,5 @@
     AResponse := Responses.FindResponseByName('SCHEDULE',1);
     if (AResponse <> nil) and (AResponse.EValue <> '') then  x := AResponse.EValue;
-    SetSchedule(x);
+    SetSchedule(UpperCase(x));
    (* if x <> '' then
     begin
@@ -1716,5 +1796,5 @@
 var
   AResponse: TResponse;
-  x,LocRoute,TempSch,DispGrp: string;
+  x,LocRoute,TempSch,DispGrp, SchType: string;
   i, DispDrug: Integer;
 begin
@@ -1730,5 +1810,7 @@
         SetDosage(IValueFor('INSTR', i));
         with cboDosage do
-          if ItemIndex > -1 then x := Text + TAB + Items[ItemIndex]
+          //agp change QO code to populate the Grid with the same fields after selection CQ 15933
+          //if ItemIndex > -1 then x := Text + TAB + Items[ItemIndex]
+          if ItemIndex > -1 then x := Piece(Text, TAB, 1) + TAB + Items[ItemIndex]
          else x := IValueFor('INSTR',i); //AGP Change 26.41 for CQ 9102 PSI-05-015 affect copy and edit functionality
         grdDoses.Cells[COL_DOSAGE, i] := x;
@@ -1737,11 +1819,5 @@
           if ItemIndex > -1 then x := Text + TAB + Items[ItemIndex] else x := Text;
         grdDoses.Cells[COL_ROUTE,  i] := x;
-        if FIsQuickOrder then TempSch := cboSchedule.Text;
-        SetSchedule(IValueFor('SCHEDULE', i));
-        if (cboSchedule.Text = '') and (FIsQuickOrder) and (NSSchedule = False) then
-        begin
-          cboSchedule.SelectByID(TempSch);
-          cboSchedule.Text := TempSch;
-        end;
+        SetSchedule(UpperCase(IValueFor('SCHEDULE', i)));
         if (cboSchedule.Text = '') and (FIsQuickOrder) and (NSSchedule = True) then cboSchedule.ItemIndex := -1;
         x := cboSchedule.Text;
@@ -1755,10 +1831,20 @@
           begin
             if IValueFor('ADMIN', i) <> '' then grdDoses.Cells[COL_ADMINTIME, i] := IValueFor('ADMIN', i)
-            else if cboSchedule.ItemIndex > -1 then
+            else if (cboSchedule.ItemIndex > -1) and (chkPRN.Checked = false) then
                grdDoses.Cells[COL_ADMINTIME, i] := Piece(cboSchedule.Items.Strings[cboSchedule.itemIndex],U,4)
             else grdDoses.Cells[COL_ADMINTIME, i] := '';
             if grdDoses.Cells[COL_ADMINTIME, i] = '' then grdDoses.Cells[COL_ADMINTIME, i] := 'Not Defined';
             if FAdminTimeText <> '' then grdDoses.Cells[COL_ADMINTIME, i] := FAdminTimeText;
+            //done to prevent admin time showing up in schedules that should not have admin times. Also remove Not Defined for schedule
+            //should not show the admin time
+            if (cboSchedule.ItemIndex > -1) or (chkPRN.Checked = True) then
+              begin
+                SchType := '';
+                if (cboSchedule.ItemIndex > -1) then SchType := Piece(cboSchedule.Items.Strings[cboSchedule.itemIndex],U,3);
+                if (SchType = 'P') or (SchType = 'O') or (SchType = 'OC') or (ChkPRN.Checked = True) then
+                  grdDoses.Cells[COL_ADMINTIME, i] := '';
+              end;
           end;
+        chkPRN.Checked := false;
         if      IValueFor('CONJ', i) = 'A' then x := 'AND'
         else if IValueFor('CONJ', i) = 'T' then x := 'THEN'
@@ -1779,5 +1865,5 @@
         SetDosage(IValueFor('INSTR', 1));
       SetControl(cboRoute,  'ROUTE',     1);
-      SetSchedule(IValueFor('SCHEDULE',  1));
+      SetSchedule(UpperCase(IValueFor('SCHEDULE',  1)));
       if (cboSchedule.Text = '') and (FIsQuickOrder) and (NSSchedule = False) then
       begin
@@ -1845,5 +1931,5 @@
     end; {if FInptDlg..else}
   end; {with}
- if FInptDlg then
+ if (FInptDlg) then
   begin
     x := ValueOfResponse(FLD_SCHEDULE, 1);
@@ -1901,5 +1987,5 @@
   btnSelect.Default := False;
   cmdAccept.Visible := True;
-  cmdAccept.Default := True;
+  cmdAccept.Default := False;
   cmdAccept.Left := cmdQuit.Left;
   cmdAccept.Top := MemOrder.Top;
@@ -1996,4 +2082,5 @@
 begin
   tabDose.TabIndex := TI_COMPLEX;
+  lblAdminSchSetTexT('');
   MoveCombo(cboDosage,   cboXDosage);
   MoveCombo(cboRoute,    cboXRoute);
@@ -2079,7 +2166,13 @@
       end;
     cboSchedule.ItemIndex := -1;
+    cboSchedule.Text := '';
     if chkPRN.Checked = True then chkPRN.Checked := False;
     cboSchedule.SelectByID(x);
     if cboSchedule.ItemIndex > -1 then exit;
+    if (X = ' PRN') or (X = 'PRN') then
+      begin
+        chkPRN.Checked := True;
+        Exit;
+      end;
    // if cboSchedule.ItemIndex < 0 then
     //begin
@@ -2433,4 +2526,11 @@
 end;
 
+procedure TfrmODMeds.cboRouteKeyUp(Sender: TObject; var Key: Word;
+  Shift: TShiftState);
+begin
+  inherited;
+  if (Key = VK_BACK) and (cboRoute.Text = '') then cboRoute.ItemIndex := -1;
+end;
+
 { cboSchedule ----------------------------------- }
 
@@ -2472,6 +2572,7 @@
     if length(trim(othSch)) > 1 then
     begin
+      othSch := othSch + U + U + NSSScheduleType + U + NSSAdminTime;
       cboSchedule.Items.Add(othSch);
-      idx := cboSchedule.Items.IndexOf(OthSch);
+      idx := cboSchedule.Items.IndexOf(Piece(OthSch, U, 1));
       cboSchedule.ItemIndex := idx;
     end;
@@ -2526,4 +2627,27 @@
   txtXDurationChange(Sender);
   ControlChange(Sender);
+end;
+
+procedure TfrmODMeds.QuantityMessageCheck(tag: integer);
+var
+DispDrug: integer;
+x: string;
+
+begin
+  if FInptDlg then Exit;
+  DispDrug := StrToIntDef(ValueOf(FLD_DRUG_ID, tag), 0);
+  if DispDrug > 0 then
+  begin
+    if not FSuppressMsg then
+    begin
+      DispOrderMessage(DispenseMessage(DispDrug));
+      FSuppressMsg  := False;
+    end;
+    x := QuantityMessage(DispDrug);
+  end
+  else x := '';
+  if Length(x) > 0
+    then lblQtyMsg.Caption := TX_QTY_PRE + x + TX_QTY_POST
+    else lblQtyMsg.Caption := '';
 end;
 
@@ -2742,5 +2866,7 @@
     for i := 0 to Pred(FAllDoses.Count) do
     begin
-      if AnsiSameText(DoseDrug, Copy(FAllDoses[i], 1, Length(DoseDrug))) then
+       // CQ #16957 - Corrected code that would potentially mis-match drugs - JCS
+      //if AnsiSameText(DoseDrug, Copy(FAllDoses[i], 1, Length(DoseDrug))) then
+      if AnsiSameText(DoseDrug, Pieces(FAllDoses[i],U,1,2)) then
       begin
         Result := Piece(FAllDoses[i], U, 3);
@@ -3142,5 +3268,5 @@
       if Piece(x, ' ', 2) = 'MONTHS'  then DoseMinutes := ExtractInteger(x) * 43200;
       if Piece(x, ' ', 2) = 'WEEKS'   then DoseMinutes := ExtractInteger(x) * 10080;
-      if Piece(x, ' ', 2) = 'DAYS'    then DoseMinutes := ExtractInteger(x) * 1440;
+      if Pos('DAY',Piece(x, ' ', 2))>0    then DoseMinutes := ExtractInteger(x) * 1440;
       if Piece(x, ' ', 2) = 'HOURS'   then DoseMinutes := ExtractInteger(x) * 60;
       if Piece(x, ' ', 2) = 'MINUTES' then DoseMinutes := ExtractInteger(x);
@@ -3182,5 +3308,5 @@
   with grdDoses do
   begin
-    i := grdDoses.Width - 12;                 // 12 = 4 pixel margin + 8 pixel column 0
+    i := grdDoses.Width - 20;                 // 20 = 12 pixel margin + 8 pixel column 0
     i := i - GetSystemMetrics(SM_CXVSCROLL);  // compensate for appearance of scroll bar
     if (not FinptDlg) or (FAdminTimeText = 'Not defined for Clinic Locations') then
@@ -3464,4 +3590,5 @@
   DisableDefaultButton(self);
   DisableCancelButton(self);
+  QuantityMessageCheck(cboXDosage.Tag);
 end;
 
@@ -3730,4 +3857,10 @@
   str := str + CRLF + CRLF + AdminTimeHelpText;
   infoBox(str,'Administration Time Information',MB_OK);
+end;
+
+procedure TfrmODMeds.pnlXDurationButtonEnter(Sender: TObject);
+begin
+  inherited;
+  QuantityMessageCheck(self.grdDoses.Row);
 end;
 
@@ -4074,5 +4207,5 @@
     FLD_QUANTITY  :
     begin
-       if Pos(',', txtQuantity.Text)>0 then 
+       if Pos(',', txtQuantity.Text)>0 then
         Result := Piece(txtQuantity.Text,',',1) + Piece(txtQuantity.Text,',',2)
        else
@@ -4129,5 +4262,5 @@
 begin
   Checked := false;
-  if ((StrToFloatDef(txtQuantity.Text, 0) = 0) and (StrToIntDef(txtSupply.Text, 0) = 0) and
+ if ((StrToFloatDef(txtQuantity.Text, 0) = 0) and (StrToIntDef(txtSupply.Text, 0) = 0) and
      (txtQuantity.Tag = 0) and (txtSupply.Tag = 0) and (cboDosage.Text <> ''))
      or ((cboDosage.ItemIndex < 0) and (not FIsQuickOrder)) or
@@ -4137,5 +4270,5 @@
     ADrug := Piece(CurDispDrug, U, 1);
     CurSupply := DefaultDays(ADrug, CurUnits, CurSchedule);
-    if CurSupply > 0 then
+    if CurSupply > 0 then           
     begin
       spnSupply.Position := CurSupply;
@@ -4160,5 +4293,5 @@
       SkipQtyCheck := TRUE;
     end;
-    if FQOInitial = true then FQOInitial := False;    
+    //if FQOInitial = true then FQOInitial := False;
   end;
   if (IsClozapineOrder = true) and (CurDispDrug <> '') and (CurDispDrug <> U)and (Checked = false) then
@@ -4185,5 +4318,7 @@
 end;
 
-procedure TfrmODMeds.UpdateSupplyQuantity(const CurUnits, CurSchedule, CurDuration, CurDispDrug: string;
+//add CURInstrcut to this procedure. This address a problem with an user starting with a free-text dosage and changing
+//to another free-text dose and the quantity value not updating.
+procedure TfrmODMeds.UpdateSupplyQuantity(const CurUnits, CurSchedule, CurDuration, CurDispDrug, CurInstruct: string;
   var CurSupply: Integer; var CurQuantity: double);
 const
@@ -4197,7 +4332,6 @@
   ADrug: string;
   SaveChanging: Boolean;
-  tmpQuty: Double;
-begin
-  tmpQuty := 0;
+  tmpQuantity: double;
+begin
   if (tabDose.TabIndex = TI_COMPLEX) and (txtSupply.Tag = 0) and (txtQuantity.Tag = 0) then
   begin
@@ -4220,5 +4354,6 @@
      (CurDuration = FLastDuration) and
      (CurQuantity = FLastQuantity) and
-     (CurSupply   = FLastSupply)   then Exit;
+     (CurSupply   = FLastSupply)   and
+     (CurInstruct = FLastInstruct) then Exit;
   // exit if supply & quantity have both been directly edited
   if (txtSupply.Tag > 0) and (txtQuantity.Tag > 0) then Exit;
@@ -4229,5 +4364,5 @@
   else if (CurSupply <> FLastSupply) and (txtQuantity.Tag = 0) then UpdateControl := UPD_QUANTITY
   else if (CurQuantity <> FLastQuantity) and (txtSupply.Tag = 0) then UpdateControl := UPD_SUPPLY;
-  if (UpdateControl = UPD_NONE) and ((CurUnits <> FLastUnits) or (CurSchedule <> FLastSchedule)) then
+  if (UpdateControl = UPD_NONE) and (((CurUnits <> FLastUnits) or (CurInstruct <> FLastInstruct)) or (CurSchedule <> FLastSchedule)) then
   begin
     if txtQuantity.Tag = 0    then UpdateControl := UPD_QUANTITY
@@ -4239,15 +4374,9 @@
                    if FIsQuickOrder and (CurQuantity > 0) and FQOInitial then
                    begin
-                     FQOInitial := False;
+                     txtQuantity.Text := FloatToStr(CurQuantity);
                      Exit;
                    end;
-                   if FIsQuickOrder and (CurQuantity > 0) then
-                     tmpQuty := CurQuantity;
                    CurQuantity := DaysToQty(CurSupply,   CurUnits, CurSchedule, CurDuration, ADrug);
-                   if (tmpQuty > 0) and (CurQuantity <= 0) then
-                   begin
-                     txtQuantity.Text := FloatToStr(tmpQuty);
-                     CurQuantity := tmpQuty;
-                   end else if (CurQuantity >= 0) then
+                   if (CurQuantity >= 0) then
                      txtQuantity.Text := FloatToStr(CurQuantity);
                  end;
@@ -4258,18 +4387,19 @@
   UPD_BOTH     : begin
                    txtSupply.Text     := IntToStr(CurSupply);
-                   tmpQuty := 0;
+                   spnSupply.Position := StrToIntDef(txtSupply.Text, 0);
+                   tmpQuantity := DaysToQty(CurSupply,   CurUnits, CurSchedule, CurDuration, ADrug);
                    if FIsQuickOrder and (CurQuantity > 0) and FQOInitial then
+                      begin
+                        txtQuantity.Text := FloatToStr(CurQuantity);
+                        Exit;
+                      end;
+                  (* if FIsQuickOrder and (CurQuantity > 0) and (tmpQuantity = 0) and FQOInitial then
                    begin
-                     FQOInitial := False;
+                     txtQuantity.Text := FloatToStr(CurQuantity);
                      Exit;
-                   end;
-                   if FIsQuickOrder and (CurQuantity > 0) then
-                     tmpQuty := CurQuantity;
-                   CurQuantity := DaysToQty(CurSupply,   CurUnits, CurSchedule, CurDuration, ADrug);
-                   if (tmpQuty > 0) and (CurQuantity <= 0) then
-                   begin
-                     txtQuantity.Text := FloatToStr(tmpQuty);
-                     CurQuantity := tmpQuty;
-                   end else if CurQuantity >= 0 then
+                   end;  *)
+                   //CurQuantity := DaysToQty(CurSupply,   CurUnits, CurSchedule, CurDuration, ADrug);
+                   CurQuantity := tmpQuantity;
+                   if CurQuantity >= 0 then
                      txtQuantity.Text := FloatToStr(CurQuantity);
                  end;
@@ -4579,29 +4709,13 @@
           lblAdminTime.Caption := '';
     end;
-   if (self.tabDose.TabIndex = TI_DOSE) and (CurSchedule <> FLastSchedule) then UpdateStartExpires(CurSchedule);
-   //AGP remove this code for CQ 11772
-  (*if (ValueOf(FLD_SCHED_TYP) = 'O')
-      or (Responses.EventType in ['A','D','T','M','O'])
-      or ((Length(cboSchedule.Text)>0) and (cboSchedule.ItemIndex < 0)) then
-    begin
-      if (chkDoseNow.Checked) and (chkDoseNow.Visible) then
-      begin
-        chkDoseNowClick(Self);
-        chkDoseNow.Checked := False;
-      end;
-          chkDoseNow.Visible := False;
-          lblAdminTime.Visible := False;
-    end
-    else
-      begin
-        chkDoseNow.Visible := TRUE;
-        lblAdminTime.Visible := not chkDoseNow.Checked;
-      end;  *)
+   if (self.tabDose.TabIndex = TI_DOSE) and (CurSchedule <> FLastSchedule) then
+     UpdateStartExpires(CurSchedule);
     if Responses.EventType in ['A','D','T','M','O'] then lblAdminTime.Visible := False;
   end;
-    if not FInptDlg then
+  if not FInptDlg then
   begin
     CurSchedule := CurScheduleOut;
     if ((CurInstruct <> FLastInstruct) and (CurUnits <> U)) or ((IsClozapineOrder = true) and (CurDispDrug <> '') and (CurDispDrug <> U)) //AGP Change 26.48 Do not update quantity and day supply if no matching dose on the server
+    //if ((CurInstruct <> FLastInstruct) and (CurUnits <> U))
       then UpdateDefaultSupply(CurUnits, CurSchedule, CurDuration, CurDispDrug, CurSupply, CurQuantity,
                                LackQtyInfo);
@@ -4611,5 +4725,5 @@
     end
     else
-      UpdateSupplyQuantity(CurUnits, CurSchedule, CurDuration, CurDispDrug, CurSupply, CurQuantity);
+      UpdateSupplyQuantity(CurUnits, CurSchedule, CurDuration, CurDispDrug, CurInstruct, CurSupply, CurQuantity);
    // if (CurDispDrug <> FLastDispDrug) then UpdateSC(CurDispDrug);
     if ((CurDispDrug <> FLastDispDrug) or (CurSupply <> FLastSupply)) and ((CurDispDrug <> '') and (CurSupply > 0))  then
@@ -4633,4 +4747,5 @@
   if FUpdated then ControlChange(Self);
   FScheduleChanged := false;
+  //FQOInitial := False;
 end;
 
@@ -4644,4 +4759,5 @@
     Exit;
   end;
+  if timCheckChanges.Enabled = True then sleep(1500);
   //AGP Change for 26.45 PSI-04-069
   if self.tabDose.TabIndex = 1 then
@@ -4690,7 +4806,8 @@
   T  = '"';
   T1 = 'By checking the "Give additional dose now" box, you have actually entered two orders for the same medication "';
-  T2 = #13#13'The first order''s administrative schedule is "';
-  T3 = #13'The second order''s administrative schedule is "';
+  T2 = #13#13'The "Give additional dose now" order has an administration schedule of "';
+  T3 = #13'The "Ongoing" order has an administration schedule of "';
   T4 = #13#13'Do you want to continue?';
+  T5 = '" and a priority of "';            
   T1A = 'By checking the "Give additional dose now" box, you have actually entered a new order with the schedule "NOW"';
   T2A = ' in addition to the one you are placing for the same medication "';
@@ -4698,4 +4815,5 @@
   medNm: string;
   theSch: string;
+  ordPriority: string;
 begin
   inherited;
@@ -4704,8 +4822,10 @@
     medNm := txtMed.Text;
     theSch := cboSchedule.Text;
+    ordPriority := cboPriority.SelText;
     if length(theSch)>0 then
     begin
       //if ( (ValueOf(FLD_SCHED_TYP) <> 'O') and (InfoBox(T1+medNm+T+T2+theSch+T+T3+'NOW"'+T4, 'Warning', MB_OKCANCEL or MB_ICONWARNING) = IDCANCEL) )then
-      if InfoBox(T1+medNm+T+T2+theSch+T+T3+'NOW"'+T4, 'Warning', MB_OKCANCEL or MB_ICONWARNING) = IDCANCEL then
+      //if InfoBox(T1+medNm+T+T2+theSch+T+T3+'NOW"'+T4, 'Warning', MB_OKCANCEL or MB_ICONWARNING) = IDCANCEL then
+      if InfoBox(T1+medNm+T+T2+'NOW'+T5+ordPriority+T+T3+theSch+T5+ordPriority+T+T4, 'Warning', MB_OKCANCEL or MB_ICONWARNING) = IDCANCEL then
       begin
         chkDoseNow.Checked := False;
@@ -4832,5 +4952,5 @@
      lblAdminTime.Caption := '';
      PrnPos := Pos('PRN',cboSchedule.Text);
-     if (PrnPos < 1) then
+     if (PrnPos < 1) and (FQOInitial = false) then
         UpdateStartExpires(cboSchedule.Text + ' PRN');
   end
@@ -4840,5 +4960,5 @@
     begin
       tempSch := ';'+Trim(cboSchedule.Text);
-      UpdateStartExpires(tempSch);
+      if FQOInitial = false then UpdateStartExpires(tempSch);
     end;
     //lblAdminTime.Caption := FAdminTimeLbl;
@@ -4846,4 +4966,6 @@
       cboScheduleClick(Self);
   end;
+  if FQOInitial = false then updateRelated(False);
+  //updateRelated(False);
   ControlChange(Self);
 end;
@@ -4965,12 +5087,10 @@
 procedure TfrmODMeds.FormKeyPress(Sender: TObject; var Key: Char);
 begin
- (* if (Key = #13) and (ActiveControl = grdDoses{pnlXSequence}) then
-  begin
-    ShowEditor(grdDoses.Col, grdDoses.Row, #0);
-    Key := #0;  //Don't let the base class turn it into a forward tab!
-  end *)
-  //else
-  if (Key = #13) and (ActiveControl = txtMed) then
-    Key := #0;   //Don't let the base class turn it into a forward tab!
+ if (Key = #13) and (ActiveControl = txtMed) then
+  Key := #0   //Don't let the base class turn it into a forward tab!
+ else if (Key = #13) and (self.tabDose.TabIndex = TI_Complex) then
+      Key := #0
+ else
+  inherited;
 end;
 
@@ -4993,4 +5113,5 @@
   DisableDefaultButton(self);
   DisableCancelButton(self);
+  QuantityMessageCheck(self.grdDoses.Row);
 end;
 
@@ -5041,4 +5162,17 @@
   tempAdmin := lblAdminSchGetText;
   if tempAdmin <> '' then lblAdminSchSetText('Admin Time: ' + tempAdmin);
+  if not (FInptDLG) then
+    begin
+      if self.cboPriority.Left < (self.grpPickup.Left + self.grpPickup.Width) then
+        begin
+          self.cboPriority.Left := self.grpPickup.Left + self.grpPickup.Width + 2;
+          if self.Width < (self.cboPriority.Left + self.cboPriority.Width) then
+                begin
+                  self.Width := self.cboPriority.Left + self.cboPriority.Width + 9;
+                  self.cboPriority.Left := self.pnlBottom.Width - self.cboPriority.Width - 2;
+                end;
+          self.lblPriority.Left := self.cboPriority.Left;
+        end;
+    end;
 end;
 
@@ -5134,7 +5268,14 @@
   result := False;
   IsInptDlg := False;
-  Td := FMToday;
+  // CQ #15188 - changed to use function to determine Td value - TDP
+  //Td := FMToday;
+  Td := IMOTimeFrame;
   if DlgFormID = MedsInDlgFormId  then IsInptDlg := TRUE;
   IsIMOLocation := IsValidIMOLoc(Encounter.Location,Patient.DFN);
+
+  // CQ #15188 - allow IMO functionality 23 hours after encounter date/time - JCS
+  // CQ #15188 - changed to use function to set Td.  Reverted this line back to original - TDP
+  {if (IsInptDlg) and (not Patient.Inpatient) and IsIMOLocation and
+    (Encounter.DateTime > DateTimeToFMDateTime(FMDateTimeToDateTime(FMNow) - (23/24))) then}
   if (IsInptDlg) and (not Patient.Inpatient) and IsIMOLocation and (Encounter.DateTime > Td) then
     result := True;
@@ -5271,4 +5412,13 @@
     cboSchedule.ItemIndex := -1;
   ValidateInpatientSchedule(cboSchedule);
+  updateRelated(False);
+end;
+
+
+procedure TfrmODMeds.cboScheduleKeyUp(Sender: TObject; var Key: Word;
+  Shift: TShiftState);
+begin
+  inherited;
+  if (Key = VK_BACK) and (cboSchedule.Text = '') then cboSchedule.itemindex:= -1;
 end;
 
@@ -5285,5 +5435,5 @@
     ScheduleCombo.Text := TrimLeft(UpperCase(ScheduleCombo.Text));
     {if user entered schedule verify it is in list}
-  if ScheduleCombo.ItemIndex < 0 then // CQ: 7397
+  if (ScheduleCombo.ItemIndex < 0) and (not FInptDlg) then // CQ: 7397  and CQ 17934
   begin //Fix for CQ: 9299 - Outpatient Med orders will not accept free text schedule
     tmpIndex := GetSchedListIndex(ScheduleCombo,ScheduleCombo.Text);
@@ -5298,8 +5448,10 @@
                            ' select ''OTHER'' from the list.',
                            'Incorrect Schedule.');
+          ScheduleCombo.ItemIndex := -1;
+          ScheduleCombo.Text := '';
     FShowPnlXScheduleOk := True;  //Added for CQ: 7370
     if ScheduleCombo.CanFocus then
       ScheduleCombo.SetFocus;
-    ScheduleCombo.SelStart := Length(ScheduleCombo.Text);
+    //ScheduleCombo.SelStart := Length(ScheduleCombo.Text);
   end;
 end;
@@ -5369,4 +5521,12 @@
             doesn't for simple orders }
   ValidateInpatientSchedule(cboXSchedule);
+end;
+
+
+procedure TfrmODMeds.cboXScheduleKeyUp(Sender: TObject; var Key: Word;
+  Shift: TShiftState);
+begin
+  inherited;
+  if (Key = VK_BACK) and (cboXSchedule.Text = '') then cboXSchedule.ItemIndex := -1;
 end;
 
@@ -5396,4 +5556,5 @@
   DisableDefaultButton(self);
   DisableCancelButton(self);
+  QuantityMessageCheck(self.grdDoses.Row);
 end;
 
@@ -5427,4 +5588,12 @@
 end;
 
+
+procedure TfrmODMeds.cboXSequenceKeyUp(Sender: TObject; var Key: Word;
+  Shift: TShiftState);
+begin
+  inherited;
+  if (Key = VK_BACK) and (cboXSequence.Text = '') then cboXSequence.ItemIndex := -1;
+end;
+
 procedure TfrmODMeds.cboXSequence1Exit(Sender: TObject);
 begin
@@ -5437,4 +5606,5 @@
 begin
   inherited;
+  if (Key = VK_BACK) and (cboDosage.Text = '') then cboDosage.ItemIndex := -1;
   //Fix for CQ: 7545
   if cboDosage.ItemIndex > -1 then
@@ -5444,8 +5614,17 @@
 end;
 
+
+procedure TfrmODMeds.cboPriorityKeyUp(Sender: TObject; var Key: Word;
+  Shift: TShiftState);
+begin
+  inherited;
+  if (Key = VK_BACK) and (cboPriority.Text = '') then cboPriority.ItemIndex := -1;
+end;
+
 procedure TfrmODMeds.cboXDosageKeyUp(Sender: TObject; var Key: Word;
   Shift: TShiftState);
 begin
   inherited;
+  if (Key = VK_BACK) and (cboXDosage.Text = '') then cboXDosage.itemindex := -1;
   //Fix for CQ: 7545
   if cboXDosage.ItemIndex > -1 then
@@ -5506,4 +5685,5 @@
   //agp Change CQ 10719
    self.chkXPRN.OnClick(self.chkXPRN);
+   QuantityMessageCheck(self.grdDoses.Row);
 end;
 
