unit U_MakeNorm;

interface

uses
  Windows, U_LNG, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, U_BaseCommon, U_BaseConstants, ExtCtrls, cxLookAndFeelPainters, cxCheckBox,
  StdCtrls, cxButtons, cxCurrencyEdit, cxControls, cxContainer, cxEdit,
  cxTextEdit, cxMaskEdit, cxDropDownEdit, RzPanel, RzEdit, Mask, RzTabs,
  RzCmboBx, RzButton, siComp, siLngLnk, kbmMemTable, RzRadChk;

type
  TF_MakeNorm = class(TForm)
    GroupBox_OkCancel: TRzGroupBox;
    pnMain: TRzPanel;
    pnResourceData: TRzPanel;
    Label3: TLabel;
    cbResourceType: TRzComboBox;
    pnCommon: TRzPanel;
    Label1: TLabel;
    Label2: TLabel;
    Label4: TLabel;
    edCypher: TRzEdit;
    edIzm: TRzEdit;
    meName: TRzMemo;
    cbCypherTytle: TRzComboBox;
    nePrice: TRzNumericEdit;
    Label5: TLabel;
    btOk: TRzBitBtn;
    btCancel: TRzBitBtn;
    Timer_DropDownResourceType: TTimer;
    lng_Forms: TsiLangLinked;
    cbApplyForAllSame: TRzCheckBox;
    Timer_OnCloseUpCypherTitle: TTimer;
    pnOther: TRzPanel;
    pnNormData: TRzPanel;
    Label6: TLabel;
    cbTimeUOM: TRzComboBox;
    neLaborTimeHr: TRzNumericEdit;
    Label7: TLabel;
    nePricePerTime: TRzNumericEdit;
    neLaborTimeMin: TRzNumericEdit;
    procedure FormShow(Sender: TObject);
    procedure FormHide(Sender: TObject);
    procedure btOkClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure edCypherExit(Sender: TObject);
    procedure cbResourceTypeChange(Sender: TObject);
    procedure edCypherKeyPress(Sender: TObject; var Key: Char);
    procedure Timer_DropDownResourceTypeTimer(Sender: TObject);
    procedure cbCypherTytleChange(Sender: TObject);
    procedure cbCypherTytleSelEndOk(Sender: TObject);
    procedure cbCypherTytleContextPopup(Sender: TObject; MousePos: TPoint;
      var Handled: Boolean);
    procedure cbCypherTytleEnter(Sender: TObject);
    procedure Timer_OnCloseUpCypherTitleTimer(Sender: TObject);
    procedure nePriceChange(Sender: TObject);
    procedure neLaborTimeHrChange(Sender: TObject);
    procedure cbTimeUOMChange(Sender: TObject);
    procedure nePricePerTimeChange(Sender: TObject);
    procedure neLaborTimeMinChange(Sender: TObject);
    procedure cbCypherTytleCloseUp(Sender: TObject);

  private
    { Private declarations }
    //NormRect: TRect;

    FCurrCypherTitles: TStringList;
    FNormCypherTitles: TStringList;
    FResMatCypherTitles: TStringList;
    FResMashMechCypherTitles: TStringList;
    FResPriceCypherTitles: TStringList;
    FMemTable: TkbmMemTable;

    FPrevCypherTitle: String;
    FPrevCypherTitleItemIndex: Integer;

    FCalcCount: Integer;

    //function GetCorrectCypher(ATitleCyper, ABodyCypher: String): String;
    procedure CorrectCypher(var AMainCyper, ARestCypher: String);
    procedure PrepareCypherControls(AAllCypher: String; ADivide: Boolean);
    procedure CalcCostTime(aControl: TObject);
    function GetLaborTimeMin: Integer;
    procedure SetLaborTimeMin(aVal: Integer);
  public
    GForm: TForm;

    GViewKind: TViewKind;
    GFormMode: TFormMode;
    GID: Integer;

    property ResMatCypherTitles: TStringList read FResMatCypherTitles;
    property ResMashMechCypherTitles: TStringList read FResMashMechCypherTitles;
    property ResPriceCypherTitles: TStringList read FResPriceCypherTitles;

    procedure  FormView(AHeight, AWidth: Integer);

    constructor Create(AOwner: TComponent; AForm: TForm);
    destructor  Destroy; override;

    function Execute(AViewKind: TViewKind; AFormMode: TFormMode; AMemTable: TkbmMemTable): Boolean;
  end;

{var
  F_MakeNorm: TF_MakeNorm; }

implementation
uses Unit_DM_SCS, U_Main, DB, pFIBDataSet;

{$R *.dfm}

{ TF_MakeNorm }

constructor TF_MakeNorm.Create(AOwner: TComponent; AForm: TForm);
begin
  GForm := AForm;
  inherited Create(AOwner);
end;

destructor TF_MakeNorm.Destroy;
begin
  inherited;
end;

function TF_MakeNorm.Execute(AViewKind: TViewKind; AFormMode: TFormMode; AMemTable: TkbmMemTable): Boolean;
var
  NBNormID: Integer;
  NBResourceID: Integer;

  NormInfo: TNormInfo;
  ResourceInfo: TResourceInfo;
  MakeEdit: TmakeEdit;

  AllCypher: String;
  RType: Integer;

  CurrID: Integer;
  ResCypher: String;
begin
  Result := false;
  GFormMode := AFormMode;
  GViewKind := AViewKind;
  GID := -1;
  FMemTable := AMemTable;

  NBNormID := 0;
  NBResourceID := 0;

  MakeEdit := GetMakeEditByFormMode(AFormMode);

  AllCypher := '';
  FCurrCypherTitles := nil;
  cbApplyForAllSame.Visible := AMemTable <> nil; //24.09.2010 (GViewKind = vkResource) and (AMemTable <> nil);
  cbApplyForAllSame.Enabled := cbApplyForAllSame.Visible and (AMemTable.FieldByName(fnIsNew).asBoolean=false);
  cbApplyForAllSame.Checked := false;
  case GViewKind of
    vkNorm:
      begin
        //FormView(232, 338);
        //FormView(GroupBox_Norm.Height + GroupBox_OkCancel.Height+8, GroupBox_OkCancel.Width+8);
        //GroupBox_Norm.Visible := true;
        //GroupBox_Norm.Align := alClient;
        //pcMain.ActivePage := tsNorms;
        //CurrencyEdit_NormZarplat.Properties.DisplayFormat := GetDisplayFormat(TF_Main(GForm).GCurrencyM.NameBrief);
        //Edit_NormCypher.SetFocus;
        case GFormMode of
          fmMake:
            begin
              Caption := cMakeNorm_Msg1_4_1;

              edCypher.Text := '';
              meName.Lines.Text := '';
              //Edit_NormWorkKind.Text := '';
              edIzm.Text := '';
              //neNormZarplat.Value := 0;  //CurrencyEdit_NormZarplat.Value := 0;
              nePrice.Value := 0;//23.09.2010

              Inc(FCalcCount);
              try
                neLaborTimeHr.Value := 0;
                neLaborTimeMin.Value := 0;
                nePricePerTime.Value := 0;
              finally
                Dec(FCalcCount);
              end;
              //cbTimeUOM.ItemIndex := -1;
            end;
          fmEdit:
            begin
              Caption := cMakeNorm_Msg1_4_2;

              if AMemTable <> nil then
              begin
                NBNormID := AMemTable.FieldByName(fnID).AsInteger;
                edCypher.Text := AMemTable.FieldByName(fnCypher).AsString;
                meName.Lines.Text := AMemTable.FieldByName(fnName).AsString;
                edIzm.Text := AMemTable.FieldByName(fnIzm).AsString;
                nePrice.Value := Round3(AMemTable.FieldByName(fnPrice).AsFloat);//23.09.2010
                cbApplyForAllSame.Checked := AMemTable.FieldByName(fnApplyForAllSame).AsBoolean; //24.09.2010

                Inc(FCalcCount);
                try
                  //neLaborTime.Value := AMemTable.FieldByName(fnLaborTime).AsFloat;
                  SetLaborTimeMin(AMemTable.FieldByName(fnLaborTime).AsInteger);
                  nePricePerTime.Value := AMemTable.FieldByName(fnPricePerTime).AsFloat;
                  //SelectItemByIDinComboRz(cbTimeUOM, AMemTable.FieldByName(fnTimeUOM).AsInteger);
                finally
                  Dec(FCalcCount);
                end;
              end
              else
              with F_NormBase.DM do
              begin
                NBNormID := DataSet_NB_NORMS.FN(fnID).AsInteger;
                edCypher.Text := DataSet_NB_NORMS.FN(fnCypher).AsString;
                meName.Lines.Text := DataSet_NB_NORMS.FN(fnName).AsString;
                //Edit_NormWorkKind.Text := FN('Work_Kind').AsString;
                edIzm.Text := DataSet_NB_NORMS.FN(fnIzm).AsString;
                //CurrencyEdit_NormZarplat.Value := FN('Zarplat').AsFloat;
                nePrice.Value := Round3(DataSet_NB_NORMS.FN(fnPrice).AsFloat); //23.09.2010

                Inc(FCalcCount);
                try
                  //neLaborTime.Value := DataSet_NB_NORMS.FN(fnLaborTime).AsFloat;
                  SetLaborTimeMin(DataSet_NB_NORMS.FN(fnLaborTime).AsInteger);
                  nePricePerTime.Value := DataSet_NB_NORMS.FN(fnPricePerTime).AsFloat;
                  //SelectItemByIDinComboRz(cbTimeUOM, DataSet_NB_NORMS.FN(fnTimeUOM).AsInteger);
                finally
                  Dec(FCalcCount);
                end;
              end;
            end;
        end;
      end;
    vkResource:
      begin
        RType := rtMat;
        case GFormMode of
          fmMake:
            begin
              Caption := cMakeNorm_Msg1_5_1;

              edCypher.Text := '';
              meName.Text := '';
              edIzm.Text := '';
              nePrice.Value := 0;
              //neAdditionalPrice.Value := 0;
              //CurrencyEdit_ResourceCost.Value := 0;
              //SelectItemByIDinCombo(ComboBox_ResourceRType, rtMat);
              RType := rtMat;

              Timer_DropDownResourceType.Enabled := true;
            end;
          fmEdit:
            begin
              Caption := cMakeNorm_Msg1_5_2;

              if AMemTable <> nil then
              begin
                NBResourceID := AMemTable.FieldByName(fnID).AsInteger;
                edCypher.Text := AMemTable.FieldByName(fnCypher).AsString;
                meName.Lines.Text := AMemTable.FieldByName(fnName).AsString;
                edIzm.Text := AMemTable.FieldByName(fnIzm).AsString;
                nePrice.Value := Round3(AMemTable.FieldByName(fnPrice).AsFloat);
                RType := AMemTable.FieldByName(fnRType).AsInteger;

                cbApplyForAllSame.Checked := AMemTable.FieldByName(fnApplyForAllSame).AsBoolean;
              end
              else
              with F_NormBase.DM do
              begin
                NBResourceID := DataSet_NB_RESOURCES.FN(fnID).AsInteger;
                edCypher.Text := DataSet_NB_RESOURCES.FN(fnCypher).AsString;
                meName.Text := DataSet_NB_RESOURCES.FN(fnName).AsString;
                edIzm.Text := DataSet_NB_RESOURCES.FN(fnIzm).AsString;
                nePrice.Value := Round3(DataSet_NB_RESOURCES.FN(fnPrice).AsFloat);
                //neAdditionalPrice.Value := FN(fnAdditionalPrice).AsFloat;
                //CurrencyEdit_ResourceCost.Value := Round3(FN('Price').AsFloat);
                RType := DataSet_NB_RESOURCES.FN(fnRType).AsInteger;
                //SelectItemByIDinCombo(ComboBox_ResourceRType, RType);
              end;
            end;
        end;
        SelectItemByIDinComboRz(cbResourceType, RType);
      end;
  end;
  AllCypher := edCypher.Text;

  (*
  {$IF Defined (FINAL_SCS)}
    cbCypherTytle.ReadOnly := (GFormMode = fmEdit);
    edCypher.ReadOnly := (GFormMode = fmEdit);
    edIzm.ReadOnly := (GFormMode = fmEdit);
    cbResourceType.ReadOnly  := (GFormMode = fmEdit);
  {$IFEND}
    *)

  pnNormData.Visible := (GViewKind = vkNorm);
  pnResourceData.Visible := (GViewKind = vkResource);
  Self.AutoSize := false;
  pnMain.AutoSize := false;
  //pnMain.Align := alTop;
  pnMain.AutoSize := true;
  Self.AutoSize := true;

  PrepareCypherControls(AllCypher, true);

  if ShowModal = mrOK then
  begin
    edCypherExit(edCypher);
    ResCypher := cbCypherTytle.Text + edCypher.Text;
    CurrID := -1;
    case GViewKind of
      vkNorm:
        begin
          if AMemTable <> nil then
          begin
            case GFormMode of
              fmEdit: CurrID := AMemTable.FieldByName(fnID).AsInteger;
            end;
            if GFormMode = fmMake then
              AMemTable.Append;
            AMemTable.Edit;

            AMemTable.FieldByName(fnCypher).AsString := ResCypher;
            AMemTable.FieldByName(fnName).AsString := meName.Lines.Text;
            //FN('Work_Kind').AsString := Edit_NormWorkKind.Text;
            AMemTable.FieldByName(fnIzm).AsString := edIzm.Text;
            //FN('Zarplat').AsFloat := CurrencyEdit_NormZarplat.Value;
            AMemTable.FieldByName(fnPrice).AsFloat := nePrice.Value; //23.09.2010
            AMemTable.FieldByName(fnIsModified).AsBoolean := true;
            AMemTable.FieldByName(fnApplyForAllSame).AsBoolean := cbApplyForAllSame.Checked; //24.09.2010

            AMemTable.FieldByName(fnLaborTime).AsInteger := GetLaborTimeMin; //neLaborTime.Value;
            AMemTable.FieldByName(fnPricePerTime).AsFloat := nePricePerTime.Value;
            //AMemTable.FieldByName(fnTimeUOM).AsInteger := GetIDFromComboBoxRz(cbTimeUOM);
            AMemTable.Post;
            GID := AMemTable.FieldByName(fnID).AsInteger;
          end
          else
          with F_NormBase.DM do
          begin
            //*** Проверить не используется ли шифр
            case GFormMode of
              fmEdit: CurrID := DataSet_NB_NORMS.FN(fnID).AsInteger;
            end;

            if Not F_NormBase.DM.CheckCypher(ResCypher, tnNBNorms, CurrID) then
            begin
              MessageModal(cMakeNorm_Msg2_1+' "'+ ResCypher +'" '+cMakeNorm_Msg2_2,
                           cMakeNorm_Msg2_3, MB_ICONINFORMATION or MB_OK);
              ModalResult := mrNone;
              Exit;
            end;

            ZeroMemory(@NormInfo, SizeOf(TNormInfo));
            NormInfo.ID := NBNormID;
            NormInfo.Cypher := ResCypher;
            NormInfo.Name := meName.Lines.Text;
            NormInfo.Izm := edIzm.Text;
            NormInfo.Price := nePrice.Value;
            NormInfo.LaborTime := GetLaborTimeMin; //neLaborTime.Value;
            NormInfo.PricePerTime := nePricePerTime.Value;
            //NormInfo.TimeUOM := GetIDFromComboBoxRz(cbTimeUOM);
            SaveNorm(MakeEdit, @NormInfo);
            if MakeEdit = meMake then
              GID := NormInfo.ID
            else
            if MakeEdit = meEdit then
              DataSet_NB_NORMS.FullRefresh;

            {
            if GFormMode = fmMake then
              DataSet_NB_NORMS.Append;
            DataSet_NB_NORMS.Edit;

            DataSet_NB_NORMS.FN(fnCypher).AsString := ResCypher;
            DataSet_NB_NORMS.FN(fnName).AsString := meName.Lines.Text;
            //FN('Work_Kind').AsString := Edit_NormWorkKind.Text;
            DataSet_NB_NORMS.FN(fnIzm).AsString := edIzm.Text;
            //FN('Zarplat').AsFloat := CurrencyEdit_NormZarplat.Value;
            DataSet_NB_NORMS.Post;
            GID := DataSet_NB_NORMS.FN(fnID).AsInteger; }
          end;
        end;
      vkResource:
        begin
          if AMemTable <> nil then
          begin
            case GFormMode of
              fmEdit: CurrID := AMemTable.FieldByName(fnID).AsInteger;
            end;
            if GFormMode = fmMake then
              AMemTable.Append;
            AMemTable.Edit;
            AMemTable.FieldByName(fnCypher).AsString := ResCypher;
            AMemTable.FieldByName(fnName).AsString := meName.Text;
            AMemTable.FieldByName(fnIzm).AsString := edIzm.Text;
            AMemTable.FieldByName(fnPrice).AsFloat := nePrice.Value; //CurrencyEdit_ResourceCost.Value;
            //FN(fnAdditionalPrice).AsFloat := neAdditionalPrice.Value;
            AMemTable.FieldByName(fnRType).AsInteger := GetIDFromComboBoxRz(cbResourceType);
            AMemTable.FieldByName(fnIsModified).AsBoolean := true;
            AMemTable.FieldByName(fnApplyForAllSame).AsBoolean := cbApplyForAllSame.Checked;
            AMemTable.Post;
            GID := AMemTable.FieldByName(fnID).AsInteger;
          end
          else
          with F_NormBase.DM do
          begin
            //*** Проверить не используется ли шифр
            case GFormMode of
              fmEdit: CurrID := DataSet_NB_RESOURCES.FN(fnID).AsInteger;
            end;

            if Not F_NormBase.DM.CheckCypher(ResCypher, tnNBResources, CurrID) then
            begin
              MessageModal(cMakeNorm_Msg3_1+' "'+ ResCypher +' " '+cMakeNorm_Msg3_2,
                                      cMakeNorm_Msg3_3, MB_ICONINFORMATION or MB_OK);
              ModalResult := mrNone;
              Exit;
            end;

            ZeroMemory(@ResourceInfo, SizeOf(TResourceInfo));
            ResourceInfo.ID := NBResourceID;
            ResourceInfo.Cypher := ResCypher;
            ResourceInfo.Name := meName.Text;
            ResourceInfo.Izm := edIzm.Text;
            ResourceInfo.Price := nePrice.Value; //CurrencyEdit_ResourceCost.Value;
            ResourceInfo.RType := GetIDFromComboBoxRz(cbResourceType);
            SaveResource(MakeEdit, @ResourceInfo);
            if MakeEdit = meMake then
              GID := ResourceInfo.ID
            else
            if MakeEdit = meEdit then
              DataSet_NB_RESOURCES.FullRefresh;

            {
            if GFormMode = fmMake then
              DataSet_NB_RESOURCES.Append;
            DataSet_NB_RESOURCES.Edit;
            DataSet_NB_RESOURCES.FN(fnCypher).AsString := ResCypher;
            DataSet_NB_RESOURCES.FN(fnName).AsString := meName.Text;
            DataSet_NB_RESOURCES.FN(fnIzm).AsString := edIzm.Text;
            DataSet_NB_RESOURCES.FN(fnPrice).AsFloat := nePrice.Value; //CurrencyEdit_ResourceCost.Value;
            //FN(fnAdditionalPrice).AsFloat := neAdditionalPrice.Value;
            DataSet_NB_RESOURCES.FN(fnRType).AsInteger := GetIDFromComboBoxRz(cbResourceType);
            DataSet_NB_RESOURCES.Post;
            GID := DataSet_NB_RESOURCES.FN(fnID).AsInteger;}
          end;
        end;
    end;
    Result := true;
  end;
end;

(*
// ##### Коректирует шифр. ATitleCypher - заглавие; ACurrCypher - тело шифра  #####
function TF_MakeNorm.GetCorrectCypher(ATitleCyper, ABodyCypher: String): String;
// E47-xxxxx (7) -xxxxxx (6) -xxxx (4) -xxxx (2) -xxxx (2) -xxxx (2)
var
  //KolvoZnak: array [0..6] of integer; // = (5, 6, 4, 3, 2, 2, 2);
  KolvoZnak: array [0..5] of integer;

  TempShifr: string;
  CharIndex: Integer;
  CharIndexInBlock: Integer;
  BlockIndex: Integer;
  MaxZnakCount: Integer;
  ZnakIndex: Integer;
  i: Integer;
  //i, j, k: integer;
begin
  Result := ABodyCypher;
  if ABodyCypher = '' then
    Exit; ///// EXIT /////

  //*** Количество знаков в блоке
  {KolvoZnak[0] := 7;
  KolvoZnak[1] := 6;
  KolvoZnak[2] := 4;
  KolvoZnak[3] := 3;
  KolvoZnak[4] := 2;
  KolvoZnak[5] := 2;
  KolvoZnak[6] := 2; }
  KolvoZnak[0] := 8;
  KolvoZnak[1] := 6;
  KolvoZnak[2] := 4;
  KolvoZnak[3] := 4;
  KolvoZnak[4] := 4;
  KolvoZnak[5] := 4;
  if KolvoZnak[0] > Length(ATitleCyper) then
    KolvoZnak[0] := KolvoZnak[0] - Length(ATitleCyper);

  MaxZnakCount := 0;
  for i := 0 to Length(KolvoZnak) - 1 do
    MaxZnakCount := MaxZnakCount + KolvoZnak[i];

  TempShifr := AnsiUpperCase(ABodyCypher);

  //*** Удалить все лишние символы
  while (not (TempShifr[1] in ['А'..'Я', 'Ь', 'Ъ', 'Ы', 'Ё', 'І', 'Ї', '0'..'9'])) and (Length(TempShifr) > 0) do
  begin
    Delete(TempShifr, 1, 1);
  end;

  //*** Прсотавить тире и поудалять лишние нули
  ZnakIndex := 0;
  CharIndex := 1;
  CharIndexInBlock := 1;
  BlockIndex := 0;
  while CharIndex <= Length(TempShifr) do
  begin
    //*** Удалить лишние нули и тире
    if TempShifr[CharIndex] in ['0', '-'] then
    begin
      if //(CharIndex <> 1) and // Первый символ строки м.б. тире
         (CharIndexInBlock = 1) then
      begin
        Delete(TempShifr, CharIndex, 1);
        Continue; ///// CONTINUE /////
      end;
    end
    else
    begin
      //*** Удалять вышедшие за придел символы
      //if CharIndexInBlock > KolvoZnak[BlockIndex] then
      if ZnakIndex > MaxZnakCount then
      begin
        Delete(TempShifr, CharIndex, 1);
        Continue; ///// CONTINUE /////
      end
      else
        Inc(ZnakIndex);
    end;
    //*** Если тире, то перейти на след-й блок
    if TempShifr[CharIndex] = '-' then
      if BlockIndex < Length(KolvoZnak) - 1 then
      begin
        Inc(BlockIndex);
        CharIndexInBlock := 0;
      end;
    //*** Перейти на след блок, если индекс блока вышел за колво символов в блоке
    if CharIndexInBlock = KolvoZnak[BlockIndex] then
    begin
      //*** Не выйти за предел последнего блока
      if BlockIndex < Length(KolvoZnak) - 1 then
      begin
        Inc(BlockIndex);
        CharIndexInBlock := 0;
        //*** Не вставлять тире в конец
        if CharIndex < Length(TempShifr) then
        begin
          Inc(CharIndex);
          Insert('-', TempShifr, CharIndex);
        end;
      end;
    end;
    Inc(CharIndexInBlock);
    Inc(CharIndex);
  end;

  //*** Татереть в конце тире
  while TempShifr[Length(TempShifr)] = '-' do
    Delete(TempShifr, Length(TempShifr), 1);

  Result := TempShifr;



  {
  i := 1;
  while (Length(TempShifr) >= i) do
  begin
    if (not (TempShifr[i] in ['А'..'Я', '0'..'9', '-'])) then
    begin
      Delete(TempShifr, i, 1);
    end
    else
      Inc(i);
  end;

  i := 1;
  j := 1;
  k := 1;
  while (Length(TempShifr) >= i) do
  begin
    if k > 6 then
    begin
      TempShifr := copy(TempShifr, 1, i - 2);
      break;
    end;
    if TempShifr[i] = '-' then
    begin
      if j = 1 then
      begin
        Delete(TempShifr, i, 1);
        continue;
      end;
      Inc(i);
      Inc(k);
      j := 1;
      continue;
    end;
    if (j > KolvoZnak[k]) then
    begin
      Insert('-', TempShifr, i);
      Inc(i);
      Inc(k);
      j := 1;
      continue;
    end;
    Inc(i);
    Inc(j);
  end;

  if not (TempShifr[Length(TempShifr)] in ['А'..'Я', '0'..'9']) then
  begin
    Delete(TempShifr, Length(TempShifr), 1);
  end;

  ShifrEdit := TempShifr;
  Result := ShifrEdit;   }

  //-----------------------------

  {Result := ACurrCypher;
  if ACurrCypher = '' then
    Exit; ///// EXIT ///// 

  ShifrEdit := AnsiUpperCase(ACurrCypher);
  TempShifr := ShifrEdit;

  while (not (TempShifr[1] in ['А'..'Я', '0'..'9'])) and (Length(TempShifr) > 0) do
  begin
    Delete(TempShifr, 1, 1);
  end;

  i := 1;
  while (Length(TempShifr) >= i) do
  begin
    if (not (TempShifr[i] in ['А'..'Я', '0'..'9', '-'])) then
    begin
      Delete(TempShifr, i, 1);
    end
    else
      Inc(i);
  end;

  i := 1;
  j := 1;
  k := 1;
  while (Length(TempShifr) >= i) do
  begin
    if k > 6 then
    begin
      TempShifr := copy(TempShifr, 1, i - 2);
      break;
    end;
    if TempShifr[i] = '-' then
    begin
      if j = 1 then
      begin
        Delete(TempShifr, i, 1);
        continue;
      end;
      Inc(i);
      Inc(k);
      j := 1;
      continue;
    end;
    if (j > KolvoZnak[k]) then
    begin
      Insert('-', TempShifr, i);
      Inc(i);
      Inc(k);
      j := 1;
      continue;
    end;
    Inc(i);
    Inc(j);
  end;

  if not (TempShifr[Length(TempShifr)] in ['А'..'Я', '0'..'9']) then
  begin
    Delete(TempShifr, Length(TempShifr), 1);
  end;

  ShifrEdit := TempShifr;
  Result := ShifrEdit; }
end;
*)

procedure TF_MakeNorm.CorrectCypher(var AMainCyper, ARestCypher: String);
var
  WholeCypher: String;

  KolvoZnak: array [0..5] of integer;

  TempShifr: string;
  MainPartShifr: string;
  RestPartShifr: string;
  CharIndex: Integer;
  CharIndexInBlock: Integer;
  BlockIndex: Integer;
  MaxZnakCount: Integer;
  ZnakIndex: Integer;
  i: Integer;
  //i, j, k: integer;
begin
  // Стандартный Шифр имеет вид (XXXX-YYYY)
  // Фирменный имеет вид (XXXX-YYYYFFFF-FFFFFF-FFFF-FFFF-FFFF-FFFF)
  //                            8 симв   6       4   4    4    4    - максимальные количества символов
  // где XXXX-YYYY - часть от стандартного


  //*** Количество знаков в блоке
  KolvoZnak[0] := 8;
  KolvoZnak[1] := 6;
  KolvoZnak[2] := 4;
  KolvoZnak[3] := 4;
  KolvoZnak[4] := 4;
  KolvoZnak[5] := 4;
  //if KolvoZnak[0] > Length(ATitleCyper) then
  //  KolvoZnak[0] := KolvoZnak[0] - Length(ATitleCyper);

  WholeCypher := AnsiUpperCase(AMainCyper + ARestCypher);

  MaxZnakCount := 0;
  for i := 0 to Length(KolvoZnak) - 1 do
    MaxZnakCount := MaxZnakCount + KolvoZnak[i];

  //*** Удалить все лишние символы
  while (Length(WholeCypher) > 0) and (not (WholeCypher[1] in ['A'..'Z', 'a'..'z', 'А'..'Я', 'Ь', 'Ъ', 'Ы', 'Ё', 'І', 'Ї', '0'..'9'])) do
    Delete(WholeCypher, 1, 1);

  // Отделяем Основную часть (от начала до первого встречного дефиса) от дополнительной
  MainPartShifr := WholeCypher;
  RestPartShifr := '';
  CharIndex := 1;
  while CharIndex <= Length(MainPartShifr) do
  begin
    if MainPartShifr[CharIndex] = '-' then
    begin
      if CharIndex = 1 then
      begin
        Delete(MainPartShifr, CharIndex, 1);
        continue;
      end
      else
      begin
        if (CharIndex + 1) < Length(MainPartShifr) then
        begin
          RestPartShifr := Copy(MainPartShifr, CharIndex+1, Length(MainPartShifr)-CharIndex);
          Delete(MainPartShifr, CharIndex+1, Length(MainPartShifr)-CharIndex);
        end;
        Break; //// BREAK ////
      end;
    end;
    CharIndex := CharIndex + 1;
  end;


  //*** Прсотавить тире и поудалять лишние нули В остальной части шифра
  TempShifr := RestPartShifr;
  ZnakIndex := 0;
  CharIndex := 1;
  CharIndexInBlock := 1;
  BlockIndex := 0;
  while CharIndex <= Length(TempShifr) do
  begin
    //*** Удалить лишние нули и тире
    if TempShifr[CharIndex] in ['0', '-'] then
    begin
      if //(CharIndex <> 1) and // Первый символ строки м.б. тире
         (CharIndexInBlock = 1) then
      begin
        Delete(TempShifr, CharIndex, 1);
        Continue; ///// CONTINUE /////
      end;
    end
    else
    begin
      //*** Удалять вышедшие за придел символы
      //if CharIndexInBlock > KolvoZnak[BlockIndex] then
      if ZnakIndex > MaxZnakCount then
      begin
        Delete(TempShifr, CharIndex, 1);
        Continue; ///// CONTINUE /////
      end
      else
        Inc(ZnakIndex);
    end;
    //*** Если тире, то перейти на след-й блок
    if TempShifr[CharIndex] = '-' then
      if BlockIndex < Length(KolvoZnak) - 1 then
      begin
        Inc(BlockIndex);
        CharIndexInBlock := 0;
      end;
    //*** Перейти на след блок, если индекс блока вышел за колво символов в блоке
    if CharIndexInBlock = KolvoZnak[BlockIndex] then
    begin
      //*** Не выйти за предел последнего блока
      if BlockIndex < Length(KolvoZnak) - 1 then
      begin
        Inc(BlockIndex);
        CharIndexInBlock := 0;
        //*** Не вставлять тире в конец
        if CharIndex < Length(TempShifr) then
        begin
          Inc(CharIndex);
          Insert('-', TempShifr, CharIndex);
        end;
      end;
    end;
    Inc(CharIndexInBlock);
    Inc(CharIndex);
  end;
  //*** Затереть в конце тире
  while (Length(TempShifr) > 0) and (TempShifr[Length(TempShifr)] = '-') do
    Delete(TempShifr, Length(TempShifr), 1);
  RestPartShifr := TempShifr;

  AMainCyper := MainPartShifr;
  ARestCypher := RestPartShifr;
end;

procedure TF_MakeNorm.PrepareCypherControls(AAllCypher: String; ADivide: Boolean);
var
  CypherTitle: String;
  FindedTytle: Boolean;

  BodyCypher: String;
  RType: Integer;

  AllCypherTitles: TStringList;
begin
  try
    CypherTitle := '';

    FCurrCypherTitles := nil;
    case GViewKind of
      vkNorm:
        FCurrCypherTitles := FNormCypherTitles;
      vkResource:
        begin
          RType := GetIDFromComboBoxRz(cbResourceType);
          case RType of
            rtMat:
              FCurrCypherTitles := FResMatCypherTitles;
            rtMachMech:
              FCurrCypherTitles := FResMashMechCypherTitles;
            rtPrice:
              FCurrCypherTitles := FResPriceCypherTitles;
          end;
        end;
    end;
    cbCypherTytle.Clear;
    if FCurrCypherTitles <> nil then
    begin
      cbCypherTytle.Items.AddStrings(FCurrCypherTitles);
      if cbCypherTytle.Items.IndexOf(CypherTitle) <> -1 then
        cbCypherTytle.ItemIndex := cbCypherTytle.Items.IndexOf(CypherTitle)
      else
        cbCypherTytle.ItemIndex := 0;
    end;

    FindedTytle := false;
    AllCypherTitles := TStringList.Create;
    try
      AllCypherTitles.AddStrings(FNormCypherTitles);
      AllCypherTitles.AddStrings(FResMatCypherTitles);
      AllCypherTitles.AddStrings(FResMashMechCypherTitles);
      AllCypherTitles.AddStrings(FResPriceCypherTitles);
      if FindCypherTytleAtStringList(AllCypherTitles, AAllCypher, CypherTitle) then
        FindedTytle := true;
    finally
      AllCypherTitles.Free;
    end;

    if ADivide then
    begin
      BodyCypher := AAllCypher;
      if FindedTytle then
      begin
        Delete(BodyCypher, 1, Length(CypherTitle));
        //BodyCypher := cbCypherTytle.Text + BodyCypher;
      end;
      cbCypherTytle.Text := CypherTitle;
      edCypher.Text := BodyCypher;
      edCypherExit(edCypher);
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_MakeNorm.PrepareCypherControls', E.Message);
  end;
end;

procedure TF_MakeNorm.CalcCostTime(aControl: TObject);
var
  //TimeOUM: Integer;
  //TimeDivider: Integer;
  LaborTimeHr, LaborTimeMin: Double;
begin
  if FCalcCount = 0 then
  begin
    Inc(FCalcCount);
    if GViewKind = vkNorm then
    begin
      //TimeOUM := GetIDFromComboBoxRz(cbTimeUOM);
//      if TimeOUM <> 0 then
//      begin
//        TimeDivider := 1;
//        if TimeOUM = tuMin then
//          TimeDivider := 60;
//        if (aControl = neLaborTime) or (aControl = cbTimeUOM) or (aControl = nePricePerTime) then
//        begin
//          if (neLaborTime.Value <> 0) and (nePricePerTime.Value <> 0) then
//            nePrice.Value := Round2(RoundX(neLaborTime.Value/TimeDivider, 5) * nePricePerTime.Value)
//          else if nePrice.Value <> 0 then
//          begin
//            if (neLaborTime.Value <> 0) and (nePricePerTime.Value = 0) and (aControl <> nePricePerTime) then
//              nePricePerTime.Value := Round2(nePrice.Value / RoundX(neLaborTime.Value/TimeDivider, 5))
//            else if (neLaborTime.Value = 0) and (nePricePerTime.Value <> 0) and (aControl <> neLaborTime) then
//              neLaborTime.Value := Round2(nePrice.Value / RoundX(nePricePerTime.Value/TimeDivider, 5));
//          end;
//        end
//        else if aControl = nePrice then
//        begin
//          if neLaborTime.Value <> 0 then
//            nePricePerTime.Value := Round2(nePrice.Value / RoundX(neLaborTime.Value/TimeDivider, 5))
//          else if (neLaborTime.Value = 0) and (nePricePerTime.Value <> 0) then
//            neLaborTime.Value := Round2(nePrice.Value / RoundX(nePricePerTime.Value/TimeDivider, 5));
//        end;
//      end;

      LaborTimeMin := GetLaborTimeMin;
      LaborTimeHr := RoundX(LaborTimeMin / 60, 5);
      if (aControl = neLaborTimeHr) or (aControl = neLaborTimeMin) or (aControl = nePricePerTime) then
      begin
        if (LaborTimeMin <> 0) and (nePricePerTime.Value <> 0) then
          nePrice.Value := Round2(LaborTimeHr * nePricePerTime.Value)
        else
        begin
          if (aControl = neLaborTimeHr) or (aControl = neLaborTimeMin) then
          begin
            if LaborTimeMin <> 0 then
              nePricePerTime.Value := Round2(nePrice.Value / LaborTimeHr)
          end
          else
          if aControl = nePricePerTime then
          begin
            if nePricePerTime.Value <> 0 then
              //SetLaborTimeMin(Round2(nePrice.Value / nePricePerTime));
              SetLaborTimeMin(Round((nePrice.Value / nePricePerTime.Value) * 60));
          end;
        end;
      end
      else if aControl = nePrice then
      begin
        if LaborTimeMin <> 0 then
          nePricePerTime.Value := Round2(nePrice.Value / LaborTimeHr)
        else if nePricePerTime.Value <> 0 then
          SetLaborTimeMin(Round((nePrice.Value / nePricePerTime.Value) * 60));
      end;
    end;
    Dec(FCalcCount);
  end;
end;

function TF_MakeNorm.GetLaborTimeMin: Integer;
begin
  Result := neLaborTimeHr.IntValue * 60 + neLaborTimeMin.IntValue;
end;

procedure TF_MakeNorm.SetLaborTimeMin(aVal: Integer);
begin
  neLaborTimeHr.Value := aVal div 60;
  neLaborTimeMin.Value := aVal mod 60;
end;

procedure TF_MakeNorm.FormView(AHeight, AWidth: Integer);
begin
  Height := AHeight;
  Width := AWidth;
end;



// ##### Создание формы #####
procedure TF_MakeNorm.FormCreate(Sender: TObject);
var
  i: Integer;

begin
  //*** Загрузить типы ресурсов
  AddIDToComboRz(rtMat , cMakeNorm_Msg1_1, cbResourceType);
  AddIDToComboRz(rtMachMech , cMakeNorm_Msg1_2, cbResourceType);
  AddIDToComboRz(rtPrice , cMakeNorm_Msg1_3, cbResourceType);
  cbResourceType.ItemIndex := 0;

  //AddIDToComboRz(tuMin, cBaseCommon85_1, cbTimeUOM);
  //AddIDToComboRz(tuHr, cBaseCommon85_2, cbTimeUOM);
  //cbTimeUOM.ItemIndex := 0;

  FCurrCypherTitles := nil;
  FNormCypherTitles := TStringList.Create;
{$IF DEFINED(SCS_PE) or Defined(SCS_SPA)}
  FNormCypherTitles.Add('E');
  FNormCypherTitles.Add('M');
  FNormCypherTitles.Add('R');
  FNormCypherTitles.Add('P');
  FNormCypherTitles.Add('B');
  FNormCypherTitles.Add('PY');
  FNormCypherTitles.Add('PM');
  FNormCypherTitles.Add('PX');
  FNormCypherTitles.Add('PR');
  FNormCypherTitles.Add('PE');
  FNormCypherTitles.Add('PP');
  FNormCypherTitles.Add('GR');
  FNormCypherTitles.Add('GT');
  FNormCypherTitles.Add('TR');
  FNormCypherTitles.Add('SD');
  FNormCypherTitles.Add('Y');

  FResMatCypherTitles := TStringList.Create;
  FResMatCypherTitles.Add('C1');

  FResMashMechCypherTitles := TStringList.Create;
  FResMashMechCypherTitles.Add('C2');

  FResPriceCypherTitles := TStringList.Create;
  FResPriceCypherTitles.Add('ES');
  FResPriceCypherTitles.Add('K');
{$ELSE}
  FNormCypherTitles.Add('Е');
  FNormCypherTitles.Add('М');
  FNormCypherTitles.Add('Р');
  FNormCypherTitles.Add('П');
  FNormCypherTitles.Add('В');
  FNormCypherTitles.Add('ПУ');
  FNormCypherTitles.Add('ПМ');
  FNormCypherTitles.Add('ПХ');
  FNormCypherTitles.Add('ПР');
  FNormCypherTitles.Add('ПЕ');
  FNormCypherTitles.Add('ПП');
  FNormCypherTitles.Add('ЖР');
  FNormCypherTitles.Add('ЖТ');
  FNormCypherTitles.Add('ТР');
  FNormCypherTitles.Add('ШД');
  FNormCypherTitles.Add('У');

  FResMatCypherTitles := TStringList.Create;
  FResMatCypherTitles.Add('С1');

  FResMashMechCypherTitles := TStringList.Create;
  FResMashMechCypherTitles.Add('С2');

  FResPriceCypherTitles := TStringList.Create;
  FResPriceCypherTitles.Add('ЭС');
  FResPriceCypherTitles.Add('К');
{$IFEND}

  for i := 1 to 9 do
    FResPriceCypherTitles.Add(IntToStr(i));

  FCalcCount := 0;
end;



// ##### Показать форму #####
procedure TF_MakeNorm.FormShow(Sender: TObject);
var
  AllCypher: String;
  RType: Integer;
begin
  //GroupBox_Norm.Visible := false;
  //GroupBox_Resources.Visible := false;

  //neNormZarplat.DisplayFormat := GetDisplayFormat(TF_Main(GForm).GCurrencyM.NameBrief);
  //neAdditionalPrice.DisplayFormat := neNormZarplat.DisplayFormat;

  (*
  AllCypher := '';
  FCurrCypherTitles := nil;
  case GViewKind of
    vkNorm:
      begin
        //FormView(232, 338);
        //FormView(GroupBox_Norm.Height + GroupBox_OkCancel.Height+8, GroupBox_OkCancel.Width+8);
        //GroupBox_Norm.Visible := true;
        //GroupBox_Norm.Align := alClient;
        //pcMain.ActivePage := tsNorms;
        //CurrencyEdit_NormZarplat.Properties.DisplayFormat := GetDisplayFormat(TF_Main(GForm).GCurrencyM.NameBrief);
        //Edit_NormCypher.SetFocus;
        case GFormMode of
          fmMake:
            begin
              Caption := cMakeNorm_Msg1_4_1;

              edCypher.Text := '';
              meName.Lines.Text := ''; //Edit_NormName.Text := '';
              //Edit_NormWorkKind.Text := '';
              edIzm.Text := '';
              //neNormZarplat.Value := 0;  //CurrencyEdit_NormZarplat.Value := 0;
            end;
          fmEdit:
              with F_NormBase.DM.DataSet_NB_NORMS do
              begin
                Caption := cMakeNorm_Msg1_4_2;

                AllCypher := FN('Cypher').AsString;
                edCypher.Text := FN('Cypher').AsString;
                //Edit_NormName.Text := FN('Name').AsString;
                meName.Lines.Text := FN('Name').AsString;
                //Edit_NormWorkKind.Text := FN('Work_Kind').AsString;
                edIzm.Text := FN('Izm').AsString;
                //CurrencyEdit_NormZarplat.Value := FN('Zarplat').AsFloat;
              end;
        end;
      end;
    vkResource:
      begin
        //GroupBox_Resources.Visible := true;
        //GroupBox_Resources.Align := alClient;
        //FormView(252, 325);
        //pcMain.ActivePage := tsResources;
        //CurrencyEdit_ResourceCost.Properties.DisplayFormat := GetDisplayFormat(TF_Main(GForm).GCurrencyM.NameBrief);
        //Edit_ResourceCypher.SetFocus;
        RType := rtMat;
        case GFormMode of
          fmMake:
            begin
              Caption := cMakeNorm_Msg1_5_1;

              edCypher.Text := '';
              meName.Text := '';
              edIzm.Text := '';
              nePrice.Value := 0;
              //neAdditionalPrice.Value := 0;
              //CurrencyEdit_ResourceCost.Value := 0;
              //SelectItemByIDinCombo(ComboBox_ResourceRType, rtMat);
              RType := rtMat;

              Timer_DropDownResourceType.Enabled := true;
            end;
          fmEdit:
            with F_NormBase.DM.DataSet_NB_RESOURCES do
            begin
              Caption := cMakeNorm_Msg1_5_2;

              AllCypher := FN('Cypher').AsString;
              edCypher.Text := FN('Cypher').AsString;
              meName.Text := FN('Name').AsString;
              edIzm.Text := FN('Izm').AsString;
              nePrice.Value := Round3(FN('Price').AsFloat);
              //neAdditionalPrice.Value := FN(fnAdditionalPrice).AsFloat;
              //CurrencyEdit_ResourceCost.Value := Round3(FN('Price').AsFloat);
              RType := FN('RType').AsInteger;
              //SelectItemByIDinCombo(ComboBox_ResourceRType, RType);
            end;
        end;
        SelectItemByIDinComboRz(cbResourceType, RType);
      end;
  end;

  pnResourceData.Visible := (GViewKind = vkResource);

  PrepareCypherControls(AllCypher, true);
  *)

  (*
  {$IF Defined (FINAL_SCS)}
    cbCypherTytle.ReadOnly := (GFormMode = fmEdit);
    edCypher.ReadOnly := (GFormMode = fmEdit);
    edIzm.ReadOnly := (GFormMode = fmEdit);
    cbResourceType.ReadOnly  := (GFormMode = fmEdit);
  {$IFEND}
    *)
end;


// ##### Скрытие формы #####
procedure TF_MakeNorm.FormHide(Sender: TObject);
begin
    //
end;


// ##### Нажат OK #####
procedure TF_MakeNorm.btOkClick(Sender: TObject);
var
  CurrID: Integer;
  ResCypher: String;
begin
  {ResCypher := cbCypherTytle.Text + edCypher.Text;
  CurrID := -1;
  case GViewKind of
    vkNorm:
      with F_NormBase.DM.DataSet_NB_NORMS do
      begin
        //*** Проверить не используется ли шифр
        case GFormMode of
          fmEdit: CurrID := FN('ID').AsInteger;
        end;

        if Not F_NormBase.DM.CheckCypher(ResCypher, tnNBNorms, CurrID) then
        begin
          MessageModal(cMakeNorm_Msg2_1+' "'+ ResCypher +'" '+cMakeNorm_Msg2_2,
                       cMakeNorm_Msg2_3, MB_ICONINFORMATION or MB_OK);
          ModalResult := mrNone;
          Exit;
        end;

        if GFormMode = fmMake then
          Append;
        Edit;

        FN(fnCypher).AsString := ResCypher;
        FN(fnName).AsString := meName.Lines.Text;
        //FN('Work_Kind').AsString := Edit_NormWorkKind.Text;
        FN(fnIzm).AsString := edIzm.Text;
        //FN('Zarplat').AsFloat := CurrencyEdit_NormZarplat.Value;
        Post;
        GID := FN(fnID).AsInteger;
      end;
    vkResource:
      with F_NormBase.DM.DataSet_NB_RESOURCES do
      begin
        //*** Проверить не используется ли шифр
        case GFormMode of
          fmEdit: CurrID := FN(fnID).AsInteger;
        end;

        if Not F_NormBase.DM.CheckCypher(ResCypher, tnNBResources, CurrID) then
        begin
          MessageModal(cMakeNorm_Msg3_1+' "'+ ResCypher +' " '+cMakeNorm_Msg3_2,
                                  cMakeNorm_Msg3_3, MB_ICONINFORMATION or MB_OK);
          ModalResult := mrNone;
          Exit;
        end;

        if GFormMode = fmMake then
          Append;
        Edit;
        FN(fnCypher).AsString := ResCypher;
        FN(fnName).AsString := meName.Text;
        FN(fnIzm).AsString := edIzm.Text;
        FN(fnPrice).AsFloat := nePrice.Value; //CurrencyEdit_ResourceCost.Value;
        //FN(fnAdditionalPrice).AsFloat := neAdditionalPrice.Value;
        FN(fnRType).AsInteger := GetIDFromComboBoxRz(cbResourceType);
        Post;
        GID := FN(fnID).AsInteger;
      end;
  end;}

  ResCypher := cbCypherTytle.Text + edCypher.Text;
  CurrID := -1;
  if FMemTable = nil then
    case GViewKind of
      vkNorm:
        with F_NormBase.DM do
        begin
          //*** Проверить не используется ли шифр
          if GFormMode = fmEdit then
            CurrID := DataSet_NB_NORMS.FN(fnID).AsInteger;

          if Not F_NormBase.DM.CheckCypher(ResCypher, tnNBNorms, CurrID) then
          begin
            MessageModal(cMakeNorm_Msg2_1+' "'+ ResCypher +'" '+cMakeNorm_Msg2_2,
                         cMakeNorm_Msg2_3, MB_ICONINFORMATION or MB_OK);
            ModalResult := mrNone;
          end;
        end;
      vkResource:
        with F_NormBase.DM do
        begin
          //*** Проверить не используется ли шифр
          if GFormMode = fmEdit then
            CurrID := DataSet_NB_RESOURCES.FN(fnID).AsInteger;

          if Not F_NormBase.DM.CheckCypher(ResCypher, tnNBResources, CurrID) then
          begin
            MessageModal(cMakeNorm_Msg3_1+' "'+ ResCypher +' " '+cMakeNorm_Msg3_2,
                                    cMakeNorm_Msg3_3, MB_ICONINFORMATION or MB_OK);
            ModalResult := mrNone;
          end;
        end;
    end;
end;

procedure TF_MakeNorm.FormDestroy(Sender: TObject);
begin
  ClearComboBoxRz(cbResourceType);
  //ClearComboBoxRz(cbTimeUOM);

  FreeAndNil(FNormCypherTitles);
  FreeAndNil(FResMatCypherTitles);
  FreeAndNil(FResMashMechCypherTitles);
  FreeAndNil(FResPriceCypherTitles);
end;

procedure TF_MakeNorm.edCypherExit(Sender: TObject);
var
  MainPart: String;
  RestPart: String;
begin
  //edCypher.Text := GetCorrectCypher(cbCypherTytle.Text, edCypher.Text);

  MainPart := cbCypherTytle.Text + edCypher.Text;
  RestPart := '';
  CorrectCypher(MainPart, RestPart);

  cbCypherTytle.Text := MainPart;
  edCypher.Text := RestPart;
end;

procedure TF_MakeNorm.cbResourceTypeChange(Sender: TObject);
begin
  PrepareCypherControls(cbCypherTytle.Text + edCypher.Text, true);
  cbCypherTytle.Text := cbCypherTytle.Items[0];
end;

procedure TF_MakeNorm.edCypherKeyPress(Sender: TObject; var Key: Char);
begin
  {$IF Not Defined(SCS_PE)}
    if Key in ['А'..'Я', 'а'..'я', '0'..'9'] then
    begin
      if Key in ['Ь', 'Ъ', 'Ы', 'Ё', 'І', 'Ї',  'ь', 'ъ', 'ы', 'ё', 'і', 'ї'] then
        Key := #0;
    end
    else
      if Not(Key in ['-', Chr(VK_BACK)]) then
        Key := #0;

    if Key = #0 then
      Beep;
  {$ELSE}
    if Key in ['A'..'Z', 'a'..'z', 'А'..'Я', 'а'..'я', '0'..'9'] then
    begin
      if Key in ['Ь', 'Ъ', 'Ы', 'Ё', 'І', 'Ї',  'ь', 'ъ', 'ы', 'ё', 'і', 'ї'] then
        Key := #0;
    end
    else
      if Not(Key in ['-', Chr(VK_BACK)]) then
        Key := #0;

    if Key = #0 then
      Beep;
  {$IFEND}
end;

procedure TF_MakeNorm.Timer_DropDownResourceTypeTimer(Sender: TObject);
begin
  TTimer(Sender).Enabled := false;
  cbResourceType.DroppedDown := true;
end;

procedure TF_MakeNorm.cbCypherTytleChange(Sender: TObject);
begin
  //edCypher.Text := GetCorrectCypher(cbCypherTytle.Text, edCypher.Text);
  FPrevCypherTitle := cbCypherTytle.Text;
  Timer_OnCloseUpCypherTitle.Enabled := true;
end;

procedure TF_MakeNorm.cbCypherTytleSelEndOk(Sender: TObject);
begin
  //FPrevCypherTitle := cbCypherTytle.Text;
  //FPrevCypherTitleItemIndex := cbCypherTytle.ItemIndex;
end;

procedure TF_MakeNorm.cbCypherTytleContextPopup(Sender: TObject;
  MousePos: TPoint; var Handled: Boolean);
begin
  //
end;

procedure TF_MakeNorm.cbCypherTytleEnter(Sender: TObject);
var
  i: integer;
begin
  FPrevCypherTitle := cbCypherTytle.Text;
  for i := 0 to cbCypherTytle.Items.Count - 1 do
  begin
    if Pos(cbCypherTytle.Items[i], cbCypherTytle.Text) = 1 then
      FPrevCypherTitleItemIndex := i;//cbCypherTytle.ItemIndex;
  end;  
end;

procedure TF_MakeNorm.Timer_OnCloseUpCypherTitleTimer(Sender: TObject);
var
  CypherTitle: String;
  PrefixToRemove: String;
  PrefixToInsert: String;
begin
  TTimer(Sender).Enabled := false;
{
  // устанавливаем новый префикс, и оставляем остальную часть
  CypherTitle := FPrevCypherTitle;
  PrefixToRemove := cbCypherTytle.Items[FPrevCypherTitleItemIndex];
  PrefixToInsert := cbCypherTytle.Text;
  if Pos(PrefixToRemove, CypherTitle) = 1 then
  begin
    Delete(CypherTitle, 1, Length(PrefixToRemove));
    Insert(PrefixToInsert, CypherTitle, 1);
    cbCypherTytle.Text := CypherTitle;
  end;
}
  {$IF Not Defined(SCS_PE)}
    if FPrevCypherTitleItemIndex <> -1 then
    begin
      CypherTitle := FPrevCypherTitle;
      PrefixToInsert := cbCypherTytle.Items[FPrevCypherTitleItemIndex];
      if Pos(PrefixToInsert, CypherTitle) <> 1 then
      begin
        Insert(PrefixToInsert, CypherTitle, 1);
        cbCypherTytle.Text := PrefixToInsert;
      end;
    end;
  {$IFEND}
end;

procedure TF_MakeNorm.nePriceChange(Sender: TObject);
begin
  CalcCostTime(Sender);
end;

procedure TF_MakeNorm.neLaborTimeHrChange(Sender: TObject);
begin
  CalcCostTime(Sender);
end;

procedure TF_MakeNorm.cbTimeUOMChange(Sender: TObject);
begin
  CalcCostTime(Sender);
end;

procedure TF_MakeNorm.nePricePerTimeChange(Sender: TObject);
begin
  CalcCostTime(Sender);
end;

procedure TF_MakeNorm.neLaborTimeMinChange(Sender: TObject);
begin
  CalcCostTime(Sender);
end;

procedure TF_MakeNorm.cbCypherTytleCloseUp(Sender: TObject);
begin
  FPrevCypherTitleItemIndex := cbCypherTytle.ItemIndex;
end;

end.
