unit U_CaseForm;

interface

uses
  Windows, U_LNG, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls, ToolWin, cxLookAndFeelPainters, cxButtons,
  cxDropDownEdit, cxCalendar, cxSpinEdit, cxMaskEdit, cxCheckBox,
  cxControls, cxContainer, cxEdit, cxTextEdit, ImgList, cxStyles,
  cxCustomData, cxGraphics, cxFilter, cxData, DB, cxDBData, cxGridLevel,
  cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
  cxGridDBTableView, cxGrid, ActnList, cxEditRepositoryItems, Menus,
  cxDataStorage, cxCurrencyEdit, kbmMemTable, FIBDataSet, pFIBDataSet, U_BaseCommon,
  ExtCtrls, Grids, DBGrids, cxButtonEdit, Gauges, ActnMan, ExtDlgs,
  cxDBLookupComboBox, cxImage, cxColorComboBox, Mask, RzEdit, RzPanel,
  RzButton, RzTabs, cxMemo, RzSpnEdt, RzStatus, ClipBrd,

  U_SCSLists, U_BaseConstants, U_SCSComponent, cxCalc, siComp, siLngLnk, RzRadChk,
  U_MakeEditGuideFile, cxLookAndFeels, cxNavigator, dxCore, cxDateUtils, XPMenu;

type
  TDelInterfKind = (dkInterface, dkInterfLink);


type
  TCaseFormParams = record
    ActiveGroupControl: TWinControl;
    ActiveGrid: TcxGrid;
    ActiveGridDBTableView: TcxGridDBTableView;
    CaptionForActions: String[50];
    CaptionForForm: String[50];
  end;

  TF_CaseForm = class(TForm)
    ToolBar_Edit: TToolBar;
    ToolButton_Make: TToolButton;
    ToolButton_Edit: TToolButton;
    ToolButton_Del: TToolButton;
    ActionList1: TActionList;
    Act_Make: TAction;
    Act_Edit: TAction;
    Act_Del: TAction;
    PopupMenu_Tree: TPopupMenu;
    Act_EnableSCDel: TAction;
    Act_DisableSCDel: TAction;
    GroupBox_Directories: TGroupBox;
    Tree_InterfType: TTreeView;
    Act_AddInterfaceLink: TAction;
    PopupMenu_DropToInterfType: TPopupMenu;
    Act_MoveInterface: TAction;
    pmnu_DropMove: TMenuItem;
    pmnu_DropAddLink: TMenuItem;
    pmnu_DropCancel: TMenuItem;
    Panel_Data: TPanel;
    Splitter_Tree: TSplitter;
    ToolBar_InterfaceType: TToolBar;
    ToolButton2: TToolButton;
    ToolButton3: TToolButton;
    ToolButton4: TToolButton;
    Act_MakeNode: TAction;
    Act_EditNode: TAction;
    Act_DelNode: TAction;
    ToolButton5: TToolButton;
    ToolButton6: TToolButton;
    ToolButton7: TToolButton;
    ToolButton8: TToolButton;
    ToolButton9: TToolButton;
    ToolButton10: TToolButton;
    ToolButton11: TToolButton;
    ToolButton12: TToolButton;
    Act_PanelFind: TAction;
    Panel_Find: TPanel;
    Panel3: TPanel;
    Gauge: TGauge;
    ListView_Find: TListView;
    Splitter_GuideFind: TSplitter;
    Act_ExpandTree: TAction;
    Act_CollapseTree: TAction;
    Act_MoveNodeDown: TAction;
    Act_MoveNodeUp: TAction;
    Panel_Tree: TPanel;
    Act_AddIcon_: TAction;
    Act_EditIcon_: TAction;
    Act_DelIcon_: TAction;
    OpenPictureDialog: TOpenPictureDialog;
    N1: TMenuItem;
    N2: TMenuItem;
    N3: TMenuItem;
    N4: TMenuItem;
    N5: TMenuItem;
    N6: TMenuItem;
    N7: TMenuItem;
    PopupMenu_Data: TPopupMenu;
    N8: TMenuItem;
    N9: TMenuItem;
    N10: TMenuItem;
    Act_AddResourceRel: TAction;
    Act_EditResourceRel: TAction;
    Act_DelResourceRel: TAction;
    Act_MakeResource: TAction;
    Act_EditResource: TAction;
    Act_DelResource: TAction;
    Act_MakeTZ: TAction;
    Act_EditTZ: TAction;
    Act_DelTZ: TAction;
    Panel_Kolvo: TPanel;
    Label_Kolvo: TLabel;
    PopupMenu_Resources: TPopupMenu;
    ActAddResourceRel1: TMenuItem;
    ActEditResourceRel1: TMenuItem;
    ActDelResourceRel1: TMenuItem;
    CurrencyEdit_Kolvo_: TcxCurrencyEdit;
    Act_AddCompTypeProperty: TAction;
    Act_EditCompTypeProperty: TAction;
    Act_DelCompTypeProperty: TAction;
    Timer_PostGridRecord: TTimer;
    Label_CaptLength_: TLabel;
    Panel_OkCancel: TRzPanel;
    Act_AddInterfData: TAction;
    Act_EditInterfData: TAction;
    Act_DelInterfData: TAction;
    PopupMenu_InterfData: TPopupMenu;
    ActAddInterfData1: TMenuItem;
    ActEditInterfData1: TMenuItem;
    ActDelInterfData1: TMenuItem;
    PopupMenu_ComponTypeProperties: TPopupMenu;
    N11: TMenuItem;
    N12: TMenuItem;
    N13: TMenuItem;
    SpinEdit_Kolvo: TcxSpinEdit;
    pcDirectories: TRzPageControl;
    tsCurrency: TRzTabSheet;
    tsNetTypes: TRzTabSheet;
    tsProducers: TRzTabSheet;
    tsInterfaces: TRzTabSheet;
    tsProperties: TRzTabSheet;
    tsComponentTypes: TRzTabSheet;
    tsObjectIcons: TRzTabSheet;
    tsNBNorms: TRzTabSheet;
    tsNBResources: TRzTabSheet;
    GroupBox_Currency: TGroupBox;
    Grid_Currency: TcxGrid;
    GT_CURRENCY: TcxGridDBTableView;
    GT_CURRENCYNAME: TcxGridDBColumn;
    GT_CURRENCYNAME_BRIEF: TcxGridDBColumn;
    GT_CURRENCYRATIO: TcxGridDBColumn;
    GL_CURRENCY: TcxGridLevel;
    GroupBox_NetType: TGroupBox;
    Grid_NetType: TcxGrid;
    GT_NetType: TcxGridDBTableView;
    GT_NetTypeNAME: TcxGridDBColumn;
    GL_NetType: TcxGridLevel;
    GroupBox_Producers: TGroupBox;
    Grid_Producers: TcxGrid;
    GT_Producers: TcxGridDBTableView;
    GT_ProducersName: TcxGridDBColumn;
    GL_Producers: TcxGridLevel;
    GroupBox_Interfaces: TGroupBox;
    Splitter2: TSplitter;
    Grid_Interface: TcxGrid;
    GT_Interfaces: TcxGridDBTableView;
    GT_InterfacesNAME: TcxGridDBColumn;
    GT_InterfacesConstructiveWidth: TcxGridDBColumn;
    GT_InterfacesIDNetType: TcxGridDBColumn;
    GL_Interfaces: TcxGridLevel;
    Panel_InterfData: TRzPanel;
    PageControl_InterfData: TRzPageControl;
    tsInterfaceNorms: TRzTabSheet;
    Grid_InterfaceNorms: TcxGrid;
    GT_InterfaceNorms: TcxGridDBTableView;
    GT_InterfaceNormsCypher: TcxGridDBColumn;
    GT_InterfaceNormsNormName: TcxGridDBColumn;
    GT_InterfaceNormsExpense: TcxGridDBColumn;
    GT_InterfaceNormsIzm: TcxGridDBColumn;
    GT_InterfaceNormsInterfIsBusy: TcxGridDBColumn;
    GL_InterfaceNorms: TcxGridLevel;
    tsInterfAccordance: TRzTabSheet;
    Grid_InterfAccordance: TcxGrid;
    GT_InterfAccordance: TcxGridDBTableView;
    GT_InterfAccordanceInterfComponIsline: TcxGridDBColumn;
    GT_InterfAccordanceName: TcxGridDBColumn;
    GT_InterfAccordanceAccordComponIsline: TcxGridDBColumn;
    GL_InterfAccordance: TcxGridLevel;
    Toolbar_InterfData: TRzToolbar;
    RzToolButton1: TRzToolButton;
    RzToolButton2: TRzToolButton;
    RzToolButton3: TRzToolButton;
    GroupBox_Properties: TGroupBox;
    Grid_Properties: TcxGrid;
    GT_Properties: TcxGridDBTableView;
    GT_PropertiesNAME: TcxGridDBColumn;
    GT_PropertiesIZM: TcxGridDBColumn;
    GT_PropertiesVALUE_REQ: TcxGridDBColumn;
    GT_PropertiesDataType: TcxGridDBColumn;
    GT_PropertiesMIN_VALUE: TcxGridDBColumn;
    GT_PropertiesMAX_VALUE: TcxGridDBColumn;
    GT_PropertiesDEFAULT: TcxGridDBColumn;
    GT_PropertiesDESCRIPTION: TcxGridDBColumn;
    GT_PropertiesIsStandart: TcxGridDBColumn;
    GT_PropertiesDBColumn1: TcxGridDBColumn;
    GL_PROPERTIES: TcxGridLevel;
    Panel_Value: TPanel;
    Label_Value: TLabel;
    lbValue: TLabel;
    Edit_Value: TcxTextEdit;
    SpinEdit_Value: TcxSpinEdit;
    DateEdit_Value: TcxDateEdit;
    ComboBox_Value: TcxComboBox;
    ColorEdit_Value: TRzColorEdit;
    sbProperties: TRzStatusBar;
    spPropertyType: TRzStatusPane;
    spPropertyItemType: TRzStatusPane;
    GroupBox_ComponentTypes: TGroupBox;
    Splitter4: TSplitter;
    Grid_ComponentTypes: TcxGrid;
    GT_ComponentTypes: TcxGridDBTableView;
    GT_ComponentTypesName: TcxGridDBColumn;
    GT_ComponentTypesPortKind: TcxGridDBColumn;
    GT_ComponentTypesActiveState: TcxGridDBColumn;
    GT_ComponentTypesIsLine: TcxGridDBColumn;
    GT_ComponentTypesIsStandart: TcxGridDBColumn;
    GT_ComponentTypesMarkMask: TcxGridDBColumn;
    GT_ComponentTypesNamePlural: TcxGridDBColumn;
    GL_ComponentTypes: TcxGridLevel;
    GroupBox_Comp_Type_Properties: TGroupBox;
    ToolBar_Comp_Type_Properties: TToolBar;
    ToolButton17: TToolButton;
    ToolButton18: TToolButton;
    ToolButton19: TToolButton;
    Grid_CompTypeProp: TcxGrid;
    GT_CompTypeProp: TcxGridDBTableView;
    GT_CompTypePropNAME: TcxGridDBColumn;
    GT_CompTypePropPVALUE: TcxGridDBColumn;
    GT_CompTypePropIZM: TcxGridDBColumn;
    GT_CompTypePropTAKE_INTO_Connect: TcxGridDBColumn;
    GT_CompTypePropTAKE_INTO_JOIN: TcxGridDBColumn;
    GT_CompTypePropDESCRIPTION: TcxGridDBColumn;
    GT_CompTypePropID_DATA_TYPE: TcxGridDBColumn;
    GL_CompTypeProp: TcxGridLevel;
    GroupBox_ObjectIcons: TGroupBox;
    Grid_ObjectIcons: TcxGrid;
    GT_ObjectIcons: TcxGridDBTableView;
    GT_ObjectIconsNAME: TcxGridDBColumn;
    GT_ObjectIconsPROJ_BMP: TcxGridDBColumn;
    GT_ObjectIconsACTIVE_BMP: TcxGridDBColumn;
    GT_ObjectIconsRESERV_BMP: TcxGridDBColumn;
    GL_ObjectIcons: TcxGridLevel;
    GroupBox_NB_Norms: TGroupBox;
    Splitter1: TSplitter;
    Grid_NB_Norms: TcxGrid;
    GT_NB_Norms: TcxGridDBTableView;
    GT_NB_NormsCYPHER: TcxGridDBColumn;
    GT_NB_NormsNAME: TcxGridDBColumn;
    GT_NB_NormsWORK_KIND: TcxGridDBColumn;
    GT_NB_NormsIZM: TcxGridDBColumn;
    GT_NB_NormsZARPLAT: TcxGridDBColumn;
    GL_NB_Norms: TcxGridLevel;
    Grid_NB_NormResourceRel: TcxGrid;
    GT_NB_NormResourceRel: TcxGridDBTableView;
    GT_NB_NormResourceRelISON: TcxGridDBColumn;
    GT_NB_NormResourceRelCYPHER: TcxGridDBColumn;
    GT_NB_NormResourceRelNAME: TcxGridDBColumn;
    GT_NB_NormResourceRelIZM: TcxGridDBColumn;
    GT_NB_NormResourceRelPRICE: TcxGridDBColumn;
    GT_NB_NormResourceRelAdditionalPrice: TcxGridDBColumn;
    GT_NB_NormResourceRelKOLVO: TcxGridDBColumn;
    GT_NB_NormResourceRelCOST: TcxGridDBColumn;
    GL_NB_NormResourceRel: TcxGridLevel;
    ToolBar_Resources: TToolBar;
    ToolButton13: TToolButton;
    ToolButton14: TToolButton;
    ToolButton15: TToolButton;
    GroupBox_NB_Resources: TGroupBox;
    Grid_NB_Resources: TcxGrid;
    GT_NB_Resources: TcxGridDBTableView;
    GT_NB_ResourcesCYPHER: TcxGridDBColumn;
    GT_NB_ResourcesNAME: TcxGridDBColumn;
    GT_NB_ResourcesIZM: TcxGridDBColumn;
    GT_NB_ResourcesPRICE: TcxGridDBColumn;
    GT_NB_ResourcesAdditionalPrice: TcxGridDBColumn;
    GL_NB_Resources: TcxGridLevel;
    gbNBNormResourcesRel: TRzGroupBox;
    GT_NB_ResourcesRType: TcxGridDBColumn;
    Button_Ok: TRzBitBtn;
    Button_Exit: TRzBitBtn;
    Button_Cancel: TRzBitBtn;
    tsSuppliesKinds: TRzTabSheet;
    gbSuppliesKinds: TGroupBox;
    Grid_SuppliesKinds: TcxGrid;
    GT_SuppliesKinds: TcxGridDBTableView;
    GT_SuppliesKindsNAME: TcxGridDBColumn;
    GT_SuppliesKindsIZM: TcxGridDBColumn;
    GT_SuppliesKindsUNIT_KOLVO: TcxGridDBColumn;
    GL_SuppliesKinds: TcxGridLevel;
    GT_ProducersDescription: TcxGridDBColumn;
    GT_CURRENCYKOLVO: TcxGridDBColumn;
    GT_CURRENCYISCOUNTRY: TcxGridDBColumn;
    pmPcDirectories: TPopupMenu;
    Timer_CallMake: TTimer;
    GT_ComponentTypesCOORDZ: TcxGridDBColumn;
    GT_InterfacesNameNetType: TcxGridDBColumn;
    GT_ComponentTypesSysName: TcxGridDBColumn;
    Act_EditObjectIconInCAD: TAction;
    CAD1: TMenuItem;
    GT_ComponentTypesComponentIndex: TcxGridDBColumn;
    lng_Forms: TsiLangLinked;
    GT_CURRENCYMain: TcxGridDBColumn;
    GT_InterfAccordanceKolvo: TcxGridDBColumn;
    GT_InterfacesDescription: TcxGridDBColumn;
    Act_SetIconFromCAD: TAction;
    N14: TMenuItem;
    tsUnitsOfMeasure: TRzTabSheet;
    tsDimensions: TRzTabSheet;
    gbUnitsOfMeasure: TGroupBox;
    Grid_UnitsOfMeasure: TcxGrid;
    GT_UnitsOfMeasure: TcxGridDBTableView;
    GT_UnitsOfMeasureName: TcxGridDBColumn;
    GL_UnitsOfMeasure: TcxGridLevel;
    gbDimensions: TGroupBox;
    Grid_Dimensions: TcxGrid;
    GT_Dimensions: TcxGridDBTableView;
    cxGridDBColumn1: TcxGridDBColumn;
    GL_Dimensions: TcxGridLevel;
    Act_ShowComponTempateInNB: TAction;
    N15: TMenuItem;
    GT_InterfacesIsVisible: TcxGridDBColumn;
    CheckBox_TakeIntoJoin: TRzCheckBox;
    CheckBox_TakeIntoConnect: TRzCheckBox;
    CheckBox_Value: TRzCheckBox;
    GT_PropertiesSysName: TcxGridDBColumn;
    GT_CompTypePropSysName: TcxGridDBColumn;
    Act_GlobalMake: TAction;
    Act_GlobalEdit: TAction;
    Act_GlobalDel: TAction;
    ToolButton1: TToolButton;
    Act_Import: TAction;
    ActImport1: TMenuItem;
    Act_DuplicateCompType: TAction;
    N16: TMenuItem;
    GT_ComponentTypesID: TcxGridDBColumn;
    tsCompSpecifications: TRzTabSheet;
    gbCompSpecifications: TRzGroupBox;
    Grid_CompSpecifications: TcxGrid;
    GT_CompSpecifications: TcxGridDBTableView;
    GT_CompSpecificationsName: TcxGridDBColumn;
    GL_CompSpecifications: TcxGridLevel;
    GT_CompSpecificationsDescription: TcxGridDBColumn;
    GT_CompSpecificationsFileExt: TcxGridDBColumn;
    GT_ObjectIconsID: TcxGridDBColumn;
    GT_ObjectIconsGUID: TcxGridDBColumn;
    Act_CopyGUIDToClipboard: TAction;
    CopyGUIDtoclipboard1: TMenuItem;
    GT_NB_NormsPrice: TcxGridDBColumn;
    Panel1: TPanel;
    Label7: TLabel;
    ButtonEdit_Find: TcxButtonEdit;
    GT_NB_NormsID: TcxGridDBColumn;
    GT_NB_ResourcesID: TcxGridDBColumn;
    GT_NB_NormsLaborTime: TcxGridDBColumn;
    GT_NB_NormsPricePerTime: TcxGridDBColumn;
    GT_NB_NormsTimeUOM: TcxGridDBColumn;
    GT_NetTypeDBColumn1: TcxGridDBColumn;
    XPMenu: TXPMenu;
    procedure FormShow(Sender: TObject);
    procedure Button_OkClick(Sender: TObject);
    procedure ComboBox_PDataTypePropertiesChange(Sender: TObject);
    procedure Act_MakeExecute(Sender: TObject);
    procedure Act_EditExecute(Sender: TObject);
    procedure Act_DelExecute(Sender: TObject);
    procedure GT_CURRENCYDblClick(Sender: TObject);
    procedure GT_PropertiesFocusedRecordChanged(
      Sender: TcxCustomGridTableView; APrevFocusedRecord,
      AFocusedRecord: TcxCustomGridRecord;
      ANewItemRecordFocusingChanged: Boolean);
    procedure GT_PropertiesDataTypeGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_PropertiesDEFAULTGetProperties(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AProperties: TcxCustomEditProperties);
    procedure GT_PropertiesMIN_VALUEGetProperties(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AProperties: TcxCustomEditProperties);
    procedure GT_PROPERTIESMAX_VALUEGetProperties(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AProperties: TcxCustomEditProperties);
    procedure Button_ExitClick(Sender: TObject);
    procedure FormHide(Sender: TObject);
    procedure Act_EnableSCDelExecute(Sender: TObject);
    procedure Act_DisableSCDelExecute(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Tree_InterfTypeExpanding(Sender: TObject; Node: TTreeNode;
      var AllowExpansion: Boolean);
    procedure Tree_InterfTypeChange(Sender: TObject; Node: TTreeNode);
    procedure Act_AddInterfaceLinkExecute(Sender: TObject);
    procedure GT_InterfacesDragOver(Sender, Source: TObject; X, Y: Integer;
      State: TDragState; var Accept: Boolean);
    procedure Tree_InterfTypeDragOver(Sender, Source: TObject; X,
      Y: Integer; State: TDragState; var Accept: Boolean);
    procedure Tree_InterfTypeDragDrop(Sender, Source: TObject; X,
      Y: Integer);
    procedure GT_InterfacesMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure Act_MoveInterfaceExecute(Sender: TObject);
    procedure Act_MakeNodeExecute(Sender: TObject);
    procedure Act_EditNodeExecute(Sender: TObject);
    procedure Act_DelNodeExecute(Sender: TObject);
    procedure Act_PanelFindExecute(Sender: TObject);
    procedure ButtonEdit_FindPropertiesButtonClick(Sender: TObject;
      AButtonIndex: Integer);
    procedure ListView_FindChange(Sender: TObject; Item: TListItem;
      Change: TItemChange);
    procedure Act_ExpandTreeExecute(Sender: TObject);
    procedure Act_CollapseTreeExecute(Sender: TObject);
    procedure ButtonEdit_FindKeyPress(Sender: TObject; var Key: Char);
    procedure Act_MoveNodeDownExecute(Sender: TObject);
    procedure Act_MoveNodeUpExecute(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure Tree_InterfTypeEnter(Sender: TObject);
    procedure Panel_DataEnter(Sender: TObject);
    procedure ButtonEdit_FindEnter(Sender: TObject);
    procedure Act_AddResourceRelExecute(Sender: TObject);
    procedure Act_EditResourceRelExecute(Sender: TObject);
    procedure Act_DelResourceRelExecute(Sender: TObject);
    procedure Act_MakeResourceExecute(Sender: TObject);
    procedure Act_EditResourceExecute(Sender: TObject);
    procedure Act_DelResourceExecute(Sender: TObject);
    procedure Act_MakeTZExecute(Sender: TObject);
    procedure Act_EditTZExecute(Sender: TObject);
    procedure Act_DelTZExecute(Sender: TObject);
    procedure GT_NB_NormsFocusedRecordChanged(Sender: TcxCustomGridTableView;
      APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord;
      ANewItemRecordFocusingChanged: Boolean);
    procedure GT_NB_NormResourceRelEditValueChanged(
      Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
    procedure GT_NB_NormResourceRelKOLVOPropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure GT_NB_NormResourceRelCellClick(
      Sender: TcxCustomGridTableView;
      ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
      AShift: TShiftState; var AHandled: Boolean);
    procedure GT_ComponentTypesPortKindGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_ComponentTypesActiveStateGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_ComponentTypesIsLineGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure Act_AddCompTypePropertyExecute(Sender: TObject);
    procedure Act_EditCompTypePropertyExecute(Sender: TObject);
    procedure Act_DelCompTypePropertyExecute(Sender: TObject);
    procedure GT_ComponentTypesFocusedRecordChanged(
      Sender: TcxCustomGridTableView; APrevFocusedRecord,
      AFocusedRecord: TcxCustomGridRecord;
      ANewItemRecordFocusingChanged: Boolean);
    procedure GT_CompTypePropPVALUEGetProperties(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AProperties: TcxCustomEditProperties);
    procedure Timer_PostGridRecordTimer(Sender: TObject);
    procedure GT_CompTypePropEditValueChanged(
      Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
    procedure Panel_OkCancelResize(Sender: TObject);
    procedure GT_InterfAccordance_InterfComponIslineGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure Act_AddInterfDataExecute(Sender: TObject);
    procedure Act_EditInterfDataExecute(Sender: TObject);
    procedure Act_DelInterfDataExecute(Sender: TObject);
    procedure PageControl_InterfDataChange(Sender: TObject);
    procedure GT_InterfacesFocusedRecordChanged(
      Sender: TcxCustomGridTableView; APrevFocusedRecord,
      AFocusedRecord: TcxCustomGridRecord;
      ANewItemRecordFocusingChanged: Boolean);
    procedure GT_InterfAccordanceInterfComponIslineGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_InterfAccordanceAccordComponIslineGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_InterfacesNAMEPropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure GT_InterfacesConstructiveWidthPropertiesValidate(
      Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure GT_InterfacesIDNetTypePropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure GT_NB_NormResourceRelPRICEPropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure GT_NB_NormResourceRelAdditionalPricePropertiesValidate(
      Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure pcDirectoriesChange(Sender: TObject);
    procedure GT_NB_ResourcesRTypeGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure pmPcDirectoriesPopup(Sender: TObject);
    procedure Timer_CallMakeTimer(Sender: TObject);
    procedure Act_EditObjectIconInCADExecute(Sender: TObject);
    procedure PopupMenu_TreePopup(Sender: TObject);
    procedure Tree_InterfTypeMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure GT_CURRENCYMainGetDisplayText(Sender: TcxCustomGridTableItem;
      ARecord: TcxCustomGridRecord; var AText: String);
    procedure GT_ObjectIconsCellClick(Sender: TcxCustomGridTableView;
      ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
      AShift: TShiftState; var AHandled: Boolean);
    procedure Act_SetIconFromCADExecute(Sender: TObject);
    procedure pcDirectoriesMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure Act_ShowComponTempateInNBExecute(Sender: TObject);
    procedure PopupMenu_DataPopup(Sender: TObject);
    procedure GT_PropertiesDEFAULTGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_CompTypePropPVALUEGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_PropertiesMIN_VALUEGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_PropertiesIZMGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_CompTypePropIZMGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_InterfacesConstructiveWidthGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_ComponentTypesCOORDZGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure Act_GlobalMakeExecute(Sender: TObject);
    procedure Act_GlobalDelExecute(Sender: TObject);
    procedure Act_GlobalEditExecute(Sender: TObject);
    procedure Tree_InterfTypeMouseDown(Sender: TObject;
      Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
    procedure Act_ImportExecute(Sender: TObject);
    procedure Act_DuplicateCompTypeExecute(Sender: TObject);
    procedure pcDirectoriesChanging(Sender: TObject; NewIndex: Integer;
      var AllowChange: Boolean);
    procedure Act_CopyGUIDToClipboardExecute(Sender: TObject);
    procedure Tree_InterfTypeGetImageIndex(Sender: TObject;
      Node: TTreeNode);
    procedure GT_NB_NormsLaborTimeGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_ObjectIconsCustomDrawCell(Sender: TcxCustomGridTableView;
      ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
      var ADone: Boolean);
    procedure Tree_InterfTypeCustomDrawItem(Sender: TCustomTreeView;
      Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean);
  private
    FParentForm: TForm; // F_MasterNewList;

    GGridDBTable: TcxCustomGridTableView;
    GCurrRecNoObjectIcons: Integer;

    FViewKind: TViewKind;
    FItemType: Integer;
    FFormMode: TFormMode;

    FCaseFormParams: TCaseFormParams;
    FDirTypeInfo: TDirTypeInfo;
    FDragIDPointer: Integer;
    FOldViewKind: TViewKind;

    FShowedTables: TIntList;

    FAddedObjectIcon: Boolean;
    FDefIconName: String;
    FDefFileBmp: String;
    FDefFileBlk: String;
    FDefIconType: Integer;

    FMainSpravochnik: TSpravochnik;
//    FSpravochnik: TSpravochnik;

    FHiddenTabs: TList;
    FTabsSelectedDir: TStringList;


    procedure AddCurrencyToMemTable(ACurrency: TNBCurrency; AAsModified: Boolean);
//    procedure AddComponentTypeToMemTable(AComponentType: TNBComponentType; AAsModified: Boolean);
    procedure AddInterfaceToMemTable(AInterface: TNBInterface; AAsModified: Boolean);
    procedure AddNetTypeToMemTable(ANetType: TNBNetType; AAsModified: Boolean);
    procedure AddNormToMemTable(ANorm: TNBNorm; AAsNew, AAsModified: Boolean);
    procedure AddObjectIconToMemTable(AObjectIcon: TNBObjectIcon; AAsModified: Boolean);
    procedure AddProducerToMemTable(AProducer: TNBProducer; AAsModified: Boolean);
    procedure AddPropertyToMemTable(AProperty: TNBProperty; AMemTable, AmtPropValRel, AmtPropValNormRes: TkbmMemtable; AAsModified: Boolean);
    procedure AddResourceToMemTable(AResource: TNBResource; AAsNew, AAsModified: Boolean);
    procedure AddSuppliesKindToMemTable(ASuppliesKind: TNBSuppliesKind; AAsModified: Boolean);
    function CheckAddObjectToMTByGUID(AObjectName, AGUIDToAdd, ANameToAdd: String; AMemTable: TkbmMemTable): Boolean;
    function GetNBCurrencyFromMemTable: TNBCurrency;
    function GetNBCurrencyFromMemTableByMain(AMainType: Integer): TNBCurrency;
    function GetNBCurrencyFromMemTableByGUID(AGUID: String): TNBCurrency;

    //function  MinMaxReqControl(AValue: String): Boolean;
    //procedure ShowHintEdits(AisShow: Boolean);
    //procedure FormView(AVKind: TViewKind; ACaption: String; AHeight, AWidth: Integer;
    //                   AisToolBar: Boolean; AToolHint : String);
    //procedure ChoiceEdit;
    procedure EnableEditDel;
    //procedure EnableEditDelObjectIcons;
    procedure EnableEditDelResourceRel;
    procedure EnableEditCompTypeProperties;
    procedure EnableEditDelInterfData;
    //procedure ShowValue(ADataType: Integer; AValue: String);
    procedure ShowPropItemType(AItemType: TItemType);
    function GetDirTypeInfo(AViewKind: TViewKind): TDirTypeInfo;
    function GetFormParams(AViewKind: TViewKind): TCaseFormParams;
    //function GetValueFromEdit( ADataType: Integer): String;
    //function GetLastNppObjIcon(AIDCompStateType: Integer): Integer;
    function GetTabSheetByViewKind(AViewKind: TViewKind): TRzTabSheet;
    procedure SetCaptionToActions(ACaption: String);

    //procedure UpdateNormResorceCost

    //procedure AddEditIcon(AMakeEdit: TMakeEdit);
    procedure AddEditResource(AMakeEdit: TMakeEdit);
    procedure AddEditCompTypeProperty(AMakeEdit: TMakeEdit);
    procedure AddEditInterfData(AFormMode: TFormMode);
    //procedure ParseNoWithGroupItems;

    procedure pcDirectoriesMenuClick(Sender: TObject);
  public
    FSpravochnik: TSpravochnik;

    mtComponentType: TkbmMemTable;
    mtCompTypePropRelation: TkbmMemTable;
    mtCurrency: TkbmMemTable;
    mtInterface: TkbmMemTable;
    mtInterfaceAccordance: TkbmMemTable;
    mtInterfaceNorms: TkbmMemTable;
    mtNetType: TkbmMemTable;
    mtNorms: TkbmMemTable;
    mtObjectIcons: TkbmMemTable;
    mtProducers: TkbmMemTable;
    mtProperties: TkbmMemTable;
    mtPropValRel: TkbmMemTable;
    mtPropValNormRes: TkbmMemTable;
    mtResources: TkbmMemTable;
    mtSuppliesKinds: TkbmMemTable;
    dsComponentType: TDataSource;
    dsCompTypePropRelation: TDataSource;
    dsCurrency: TDataSource;
    dsInterface: TDataSource;
    dsInterfaceAccordance: TDataSource;
    dsInterfaceNorms: TDataSource;
    dsNetType: TDataSource;
    dsNorms: TDataSource;
    dsObjectIcons: TDataSource;
    dsProducers: TDataSource;
    dsProperties: TDataSource;
    dsPropValRel: TDataSource;
    dsPropValNormRes: TDataSource;
    dsResources: TDataSource;
    dsSuppliesKinds: TDataSource;

    MemTableComponTypes: TkbmMemTable;
    MemTableProperties: TkbmMemTable;

    GForm: TForm;
    GValue: String;
    GTakeIntoConnect: Integer;
    GTakeIntoJoin: Integer;
    GItemType: TItemType;
    GItemFieldName: String;
    GGUIDToLocate: String;
    GIDToLocate: Integer;
    GValueChanged: Boolean;
    GUseMemTable: TkbmMemTable;

    GIDNotDel: Integer;
    GChangetNetType: Boolean;

    GMouseButtonBeforeDrag: TMouseButton;
    GSNode: TTreeNode;
    GTNode: TTreeNode;
    GDropMenuResult: TDropMenuResult;
    FChangedAnySpavElemen: Boolean;
    FUOM: Integer;

    procedure AddComponentTypeToMemTable(AComponentType: TNBComponentType; AAsModified: Boolean);


    property DirTypeInfo: TDirTypeInfo read FDirTypeInfo;
    property FormMode: TFormMode read FFormMode;

    function NotDelDataUsedInMemTable(AMTKeyField, ADelKind, AItName: String;
                                       ADSKeyValue: Integer): Boolean;
    function CheckChange: Boolean;
    function CheckNoUseCompData(ASql, ADelName: String; AMakeEdit: TMakeEdit;
                                ATableKind: TTableKind; AMessType: TShowMessageType; ANeedAnsw: boolean = True): Boolean;
    //function CheckNoUseCompData(ASql, ADelName: String; AMakeEdit: TMakeEdit;
    //            ATableKind: TTableKind; AMessType: TShowMessageType): Boolean;
    function CheckNoUsingCurrCompType(AMakeEdit: TMakeEdit; AMessType: TShowMessageType; AIDCompType: Integer): Boolean;

    //*** Процедуры для работы с деревом
    procedure  AddNodes(ANode: TTreeNode);
    function   DefineTextNode(ANode: TTreeNode): String;

    //procedure  MoveInterface(AID_SourceDir, AID_TargetDir, AID_Interface: Integer);
    procedure MoveItemBetweenNodes(ASrcNode, ATrgNode: TTreeNode; AID_Item: Integer);
    procedure MoveNodes(ASourceNode, ATargetNode: TTreeNode);
    function GetNodeFromTreeByID(AIDNode: Integer): TTreeNode;
    function GetRoomHeight: Double;
    function GetViewKindByTabSheet(ATabSheet: TRzTabSheet): TViewKind;
    function FindNodeByID(AIDNode: Integer): TTreeNode;
    function LocateItemByGUID(AGUIDItem: String): Boolean;
    function LocateItemByID(AIDItem: Integer): Boolean;

    procedure PrepareForm(AViewKind: TViewKind; AFormMode: TFormMode);
    procedure RenameNode(ANode: TTreeNode; ANewName: String);
    procedure SendFromSpravochnikToMemTables(ASpravochnik: TSpravochnik; ASprElements: TSprElements);
    procedure SendFromMemTablesToSpravochnik(ASpravochnik: TSpravochnik; ASprElements: TSprElements;
                AChangedInterfNorm: PBoolean);
    procedure RefreshKolNode(ANode: TTreeNode; AKolvo: Integer = -1);
    procedure RefreshNodes(AIDToSelect: Integer);
    procedure SaveSelectTabNode;
    procedure SelectLastTabNode;
    function SelectNodeByID(AID: Integer): Boolean;
    procedure SetCurrencyBriefToControls(ACurrency: TCurrency);
    procedure SetCurrencyBriefToControlsFromMT;
    procedure SetKolChildNodes(ANode: TTreeNode);
    function SetSortID(ANode: TTreeNode): Integer;
    procedure SetPageByViewKind(AViewKind: TViewKind);
    procedure MoveTreeNode(AMoveType: TMoveType);
    procedure SetUOMToCaptions;

    Constructor Create(AOwner: TComponent; AForm, AParentForm: TForm; AItemType: Integer);
    Destructor Destroy;  override;

    function AddObjectIconFromFile(AIconName, AFileIconBmp, AFileIconBlk: String): Boolean;
    function Execute(AViewKind: TViewKind; AFormMode: TFormMode): Boolean;
  end;

const
    // InterfDataTabIntex
    idiInterfNorms = 0;
    idiInterfAccordance = 1;
{
var
  F_CaseForm: TF_CaseForm; }

implementation
Uses Unit_DM_SCS, U_DMCommon, U_CanDelete, U_MakeCurrency, U_MakeProperty, U_Main, U_Common,
  FIBQuery, pFIBProps, U_InputBox, pFIBQuery, cxDBEditRepository,
  U_MakeEditComponentType, U_MakeEditObjectIcons,
  U_MakeNorm, U_MakeEditSupplyKind, U_MakeEditProducer, U_MasterNewList;
{$R *.dfm}


procedure TF_CaseForm.AddCurrencyToMemTable(ACurrency: TNBCurrency; AAsModified: Boolean);
begin
  mtCurrency.Append;
  mtCurrency.FieldByName(fnID).AsInteger := ACurrency.Data.ID;
  mtCurrency.FieldByName(fnIDCatalog).AsInteger := ACurrency.IDCatalog;
  mtCurrency.FieldByName(fnIDItemType).AsInteger := ACurrency.CatalogItemType;
  mtCurrency.FieldByName(fnGuid).AsString := ACurrency.Data.GUID;
  mtCurrency.FieldByName(fnName).AsString := ACurrency.Data.Name;
  mtCurrency.FieldByName(fnNameBrief).AsString := ACurrency.Data.NameBrief;
  mtCurrency.FieldByName(fnKolvo).AsInteger := ACurrency.Data.Kolvo;
  mtCurrency.FieldByName(fnRatio).AsFloat := ACurrency.Data.Ratio;
  mtCurrency.FieldByName(fnMain).AsInteger := ACurrency.Data.Main;
  mtCurrency.FieldByName(fnSavedMain).AsInteger := ACurrency.Data.Main;
  //mtCurrency.FieldByName(fnSortID).AsInteger :=
  mtCurrency.FieldByName(fnIsCountry).AsInteger := ACurrency.Data.IsCountry;
  mtCurrency.FieldByName(fnIsModified).AsBoolean := AAsModified;
  mtCurrency.Post;
end;

procedure TF_CaseForm.AddComponentTypeToMemTable(AComponentType: TNBComponentType; AAsModified: Boolean);
var
  i: Integer;
  NBCompTypePropRel: TNBCompTypeProperty;

  NormBaseProperty: TNBProperty;
begin
  mtComponentType.Append;
  mtComponentType.FieldByName(fnID).AsInteger := AComponentType.ComponentType.ID;
  mtComponentType.FieldByName(fnIDCatalog).AsInteger := AComponentType.IDCatalog;
  mtComponentType.FieldByName(fnIDItemType).AsInteger := AComponentType.CatalogItemType;
  mtComponentType.FieldByName(fnGuid).AsString := AComponentType.ComponentType.GUID;
  mtComponentType.FieldByName(fnName).AsString := AComponentType.ComponentType.Name;
  mtComponentType.FieldByName(fnNamePlural).AsString := AComponentType.ComponentType.NamePlural;
  mtComponentType.FieldByName(fnSysName).AsString := AComponentType.ComponentType.SysName;
  mtComponentType.FieldByName(fnMarkMask).AsString := AComponentType.ComponentType.MarkMask;
  mtComponentType.FieldByName(fnPortKind).AsInteger := AComponentType.ComponentType.PortKind;
  mtComponentType.FieldByName(fnActiveState).AsInteger := AComponentType.ComponentType.ActiveState;
  mtComponentType.FieldByName(fnIDDesignIcon).AsInteger := AComponentType.ComponentType.IDDesignIcon;
  mtComponentType.FieldByName(fnGUIDDesignIcon).AsString := AComponentType.ComponentType.GUIDDesignIcon;
  mtComponentType.FieldByName(fnIsLine).AsInteger := AComponentType.ComponentType.IsLine;
  mtComponentType.FieldByName(fnisStandart).AsInteger := AComponentType.ComponentType.IsStandart;
  mtComponentType.FieldByName(fnCoordZ).AsFloat := AComponentType.ComponentType.CoordZ;
  mtComponentType.FieldByName(fnComponentIndex).AsInteger := AComponentType.ComponentType.ComponentIndex + 1;
  mtComponentType.FieldByName(fnCanUseAsPoint).AsInteger := AComponentType.ComponentType.CanUseAsPoint;
  mtComponentType.FieldByName(fnPropsCount).AsInteger := AComponentType.PropsCount;
  mtComponentType.FieldByName(fnIsModified).AsBoolean := AAsModified;
  mtComponentType.Post;

  for i := 0 to AComponentType.Properties.Count - 1 do
  begin
    NBCompTypePropRel := TNBCompTypeProperty(AComponentType.Properties[i]);

    //NormBaseProperty := TF_Main(GForm).FNormBase.GSCSBase.NBSpravochnik.GetPropertyByGUID(NBCompTypePropRel.PropertyData.GUIDProperty);
    NormBaseProperty := FSpravochnik.GetPropertyByGUID(NBCompTypePropRel.PropertyData.GUIDProperty);
    if FMainSpravochnik <> nil then
      NormBaseProperty := FMainSpravochnik.GetPropertyByGUID(NBCompTypePropRel.PropertyData.GUIDProperty);

    if NormBaseProperty = nil then
      NormBaseProperty := F_NormBase.GSCSBase.NBSpravochnik.GetPropertyByGUID(NBCompTypePropRel.PropertyData.GUIDProperty);

    mtCompTypePropRelation.Append;
    mtCompTypePropRelation.FieldByName(fnGuidComponentType).AsString := NBCompTypePropRel.GuidComponentType;
    mtCompTypePropRelation.FieldByName(fnGUID).AsString := NBCompTypePropRel.PropertyData.Guid;
    mtCompTypePropRelation.FieldByName(fnID).AsInteger := NBCompTypePropRel.PropertyData.ID;
    mtCompTypePropRelation.FieldByName(fnIDComponentType).AsInteger := NBCompTypePropRel.PropertyData.IDMaster;
    mtCompTypePropRelation.FieldByName(fnIDProperty).AsInteger := NBCompTypePropRel.PropertyData.ID_Property;
    mtCompTypePropRelation.FieldByName(fnGuidProperty).AsString := NBCompTypePropRel.PropertyData.GUIDProperty;
    mtCompTypePropRelation.FieldByName(fnTakeIntoConnect).AsInteger := NBCompTypePropRel.PropertyData.TakeIntoConnect;
    mtCompTypePropRelation.FieldByName(fnTakeIntoJoin).AsInteger := NBCompTypePropRel.PropertyData.TakeIntoJoin;

    mtCompTypePropRelation.FieldByName(fnPValue).AsString := NBCompTypePropRel.PropertyData.Value;
    mtCompTypePropRelation.FieldByName(fnisStandart).AsInteger := NBCompTypePropRel.PropertyData.IsDefault;
    mtCompTypePropRelation.FieldByName(fnIsModified).AsBoolean := AAsModified;
    if NormBaseProperty <> nil then
    begin
      mtCompTypePropRelation.FieldByName(fnName).AsString := NormBaseProperty.PropertyData.Name;
      mtCompTypePropRelation.FieldByName(fnSysName).AsString := NormBaseProperty.PropertyData.SysName;
      mtCompTypePropRelation.FieldByName(fnIzm).AsString := NormBaseProperty.PropertyData.Izm;
      mtCompTypePropRelation.FieldByName(fnIDDataType).AsInteger := NormBaseProperty.PropertyData.IDDataType;
    end;

    mtCompTypePropRelation.Post;
  end;
end;

procedure TF_CaseForm.AddInterfaceToMemTable(AInterface: TNBInterface; AAsModified: Boolean);
var
  NBInterfaceAccordance: TNBInterfaceAccordance;
  NBInterfaceNorm: TNBInterfaceNorm;

  NormBaseInterfAccordance: TNBInterface;
  NormBaseNetType: TNBNetType;
  NormBaseNorm: TNBNorm;
  i: Integer;
begin
  NormBaseNetType := FSpravochnik.GetNetTypeByGUID(AInterface.GuidNetType); //TF_Main(GForm).FNormBase.GSCSBase.NBSpravochnik.GetNetTypeByGUID(AInterface.GuidNetType);

  mtInterface.Append;
  mtInterface.FieldByName(fnID).AsInteger := AInterface.ID;
  mtInterface.FieldByName(fnIDCatalog).AsInteger := AInterface.IDCatalog;
  mtInterface.FieldByName(fnIDItemType).AsInteger := AInterface.CatalogItemType;
  mtInterface.FieldByName(fnGuid).AsString := AInterface.GUID;
  mtInterface.FieldByName(fnName).AsString := AInterface.Name;
  mtInterface.FieldByName(fnGuidNetType).AsString := AInterface.GuidNetType;
  mtInterface.FieldByName(fnIDNetType).AsInteger := AInterface.IDNetType;
  mtInterface.FieldByName(fnSortID).AsInteger := AInterface.SortID;
  if AInterface.ConstructiveWidth = 0 then
    mtInterface.FieldByName(fnConstructiveWidth).Value := null
  else
    mtInterface.FieldByName(fnConstructiveWidth).AsFloat := AInterface.ConstructiveWidth;
  mtInterface.FieldByName(fnDescription).AsString := AInterface.Description;
  mtInterface.FieldByName(fnIsUniversal).AsInteger := AInterface.IsUniversal;
  mtInterface.FieldByName(fnInterfNormsCount).AsInteger := AInterface.InterfNormsCount;
  mtInterface.FieldByName(fnIsModified).AsBoolean := AAsModified;
  if NormBaseNetType <> nil then
    mtInterface.FieldByName(fnNameNetType).AsString := NormBaseNetType.Name;
  mtInterface.Post;


  for i := 0 to AInterface.InterfaceAccordance.Count - 1 do
  begin
    NBInterfaceAccordance := TNBInterfaceAccordance(AInterface.InterfaceAccordance[i]);

    NormBaseInterfAccordance := FSpravochnik.GetInterfaceByGUID(NBInterfaceAccordance.GUIDAccordance);
    if NormBaseInterfAccordance = nil then
      NormBaseInterfAccordance := F_NormBase.GSCSBase.NBSpravochnik.GetInterfaceByGUID(NBInterfaceAccordance.GUIDAccordance);

    mtInterfaceAccordance.Append;
    mtInterfaceAccordance.FieldByName(fnID).AsInteger := NBInterfaceAccordance.ID;
    mtInterfaceAccordance.FieldByName(fnGUID).AsString := NBInterfaceAccordance.GUID;
    mtInterfaceAccordance.FieldByName(fnGUIDInterface).AsString := NBInterfaceAccordance.GuidInterface;
    mtInterfaceAccordance.FieldByName(fnIDInterface).AsInteger := NBInterfaceAccordance.IDInterface;
    mtInterfaceAccordance.FieldByName(fnInterfComponIsLine).AsInteger := NBInterfaceAccordance.InterfComponIsLine;
    mtInterfaceAccordance.FieldByName(fnGUIDAccordance).AsString := NBInterfaceAccordance.GUIDAccordance;
    mtInterfaceAccordance.FieldByName(fnIDAccordance).AsInteger := NBInterfaceAccordance.IDAccordance;
    mtInterfaceAccordance.FieldByName(fnAccordComponIsLine).AsInteger := NBInterfaceAccordance.AccordComponIsLine;
    mtInterfaceAccordance.FieldByName(fnKolvo).AsInteger := NBInterfaceAccordance.Kolvo;
    mtInterfaceAccordance.FieldByName(fnIsModified).AsBoolean := AAsModified;

    if NormBaseInterfAccordance <> nil then
      mtInterfaceAccordance.FieldByName(fnName).AsString := NormBaseInterfAccordance.Name;

    mtInterfaceAccordance.Post;
  end;

  for i := 0 to AInterface.InterfaceNorms.Count - 1 do
  begin
    NBInterfaceNorm := TNBInterfaceNorm(AInterface.InterfaceNorms[i]);

    //SCSNorm := NBNorms.GetNormByGuidNB(NBInterfaceNorm.GuidNBNorm, True);
    //if SCSNorm = nil then
    //begin
    //  SCSNorm := TSCSNorm.Create(F_NormBase, ntNB);
    //  SCSNorm.LoadNormByGUID(NBInterfaceNorm.GuidNBNorm, false);
    // NBNorms.Add(SCSNorm);
    //end;

    NormBaseNorm := FSpravochnik.GetNormByGUID(NBInterfaceNorm.GuidNBNorm);
    //*** подтянуть из нормативки
    if NormBaseNorm = nil then
      NormBaseNorm := F_NormBase.GSCSBase.NBSpravochnik.GetNormByGUID(NBInterfaceNorm.GuidNBNorm);

    mtInterfaceNorms.Append;
    mtInterfaceNorms.FieldByName(fnID).AsInteger := NBInterfaceNorm.ID;
    mtInterfaceNorms.FieldByName(fnGuid).AsString := NBInterfaceNorm.GUID;
    mtInterfaceNorms.FieldByName(fnGuidInterface).AsString := NBInterfaceNorm.GuidInterface;
    mtInterfaceNorms.FieldByName(fnIDInterface).AsInteger := NBInterfaceNorm.IDInterface;
    mtInterfaceNorms.FieldByName(fnGuidNBNorm).AsString := NBInterfaceNorm.GuidNBNorm;
    mtInterfaceNorms.FieldByName(fnIDNBNorm).AsInteger := NBInterfaceNorm.IDNBNorm;
    mtInterfaceNorms.FieldByName(fnExpense).AsFloat := NBInterfaceNorm.Expense;
    mtInterfaceNorms.FieldByName(fnInterfaceIsBusy).AsInteger := NBInterfaceNorm.InterfaceIsBusy;

    mtInterfaceNorms.FieldByName(fnGuidComponentType).AsString := NBInterfaceNorm.GUIDComponentType;
    mtInterfaceNorms.FieldByName(fnIDComponentType).AsInteger := NBInterfaceNorm.IDComponentType;
    mtInterfaceNorms.FieldByName(fnKoefLengthForCompl).AsFloat := NBInterfaceNorm.KoefLengthForCompl;

    mtInterfaceNorms.FieldByName(fnIsModified).AsBoolean := AAsModified;
    if NormBaseNorm <> nil then
    begin
      mtInterfaceNorms.FieldByName(fnCypher).AsString := NormBaseNorm.Cypher;
      mtInterfaceNorms.FieldByName(fnName).AsString := NormBaseNorm.Name;
      mtInterfaceNorms.FieldByName(fnIzm).AsString := NormBaseNorm.Izm;
    end;
    mtInterfaceNorms.Post;
  end;
end;

procedure TF_CaseForm.AddNetTypeToMemTable(ANetType: TNBNetType; AAsModified: Boolean);
begin
  mtNetType.Append;
  mtNetType.FieldByName(fnID).AsInteger := ANetType.ID;
  mtNetType.FieldByName(fnIDCatalog).AsInteger := ANetType.IDCatalog;
  mtNetType.FieldByName(fnIDItemType).AsInteger := ANetType.CatalogItemType;
  mtNetType.FieldByName(fnGuid).AsString := ANetType.GUID;
  mtNetType.FieldByName(fnName).AsString := ANetType.Name;
  mtNetType.FieldByName(fnIsModified).AsBoolean := AAsModified;
  mtNetType.Post;
end;

procedure TF_CaseForm.AddNormToMemTable(ANorm: TNBNorm; AAsNew, AAsModified: Boolean);
begin
  mtNorms.Append;
  mtNorms.FieldByName(fnID).AsInteger := ANorm.ID;
  mtNorms.FieldByName(fnIDCatalog).AsInteger := ANorm.IDCatalog;
  mtNorms.FieldByName(fnIDItemType).AsInteger := ANorm.CatalogItemType;
  mtNorms.FieldByName(fnGuid).AsString := ANorm.GUID;
  mtNorms.FieldByName(fnCypher).AsString := ANorm.Cypher;
  mtNorms.FieldByName(fnName).AsString := ANorm.Name;
  mtNorms.FieldByName(fnIzm).AsString := ANorm.Izm;

  mtNorms.FieldByName(fnLaborTime).AsInteger := ANorm.LaborTime;
  mtNorms.FieldByName(fnPricePerTime).AsFloat := ANorm.PricePerTime;
  //mtNorms.FieldByName(fnTimeUOM).AsInteger := ANorm.TimeUOM;

  mtNorms.FieldByName(fnPrice).AsFloat := ANorm.Price;
  mtNorms.FieldByName(fnGuidESmeta).AsString := ANorm.GUIDESmeta;
  mtNorms.FieldByName(fnApplyForAllSame).AsBoolean := false;
  mtNorms.FieldByName(fnIsNew).AsBoolean := AAsNew;
  mtNorms.FieldByName(fnIsModified).AsBoolean := AAsModified;
  mtNorms.Post;
end;

procedure TF_CaseForm.AddObjectIconToMemTable(AObjectIcon: TNBObjectIcon; AAsModified: Boolean);
begin
  mtObjectIcons.Append;
  if mtObjectIcons.State = dsBrowse then
    mtObjectIcons.Edit;
  mtObjectIcons.FieldByName(fnID).AsInteger := AObjectIcon.ID;
  mtObjectIcons.FieldByName(fnIDCatalog).AsInteger := AObjectIcon.IDCatalog;
  mtObjectIcons.FieldByName(fnIDItemType).AsInteger := AObjectIcon.CatalogItemType;
  mtObjectIcons.FieldByName(fnGuid).AsString := AObjectIcon.GUID;
  mtObjectIcons.FieldByName(fnName).AsString := AObjectIcon.Name;
  LoadFromStreamToMT(mtObjectIcons, AObjectIcon.ProjBlk, fnProjBlk);
  LoadFromStreamToMT(mtObjectIcons, AObjectIcon.ProjBmp, fnProjBmp);
  LoadFromStreamToMT(mtObjectIcons, AObjectIcon.ActiveBlk, fnActiveBlk);
  LoadFromStreamToMT(mtObjectIcons, AObjectIcon.ActiveBmp, fnActiveBmp);
  mtObjectIcons.FieldByName(fnIsModified).AsBoolean := AAsModified;
  mtObjectIcons.Post;
end;

procedure TF_CaseForm.AddProducerToMemTable(AProducer: TNBProducer; AAsModified: Boolean);
begin
  mtProducers.Append;
  mtProducers.FieldByName(fnID).AsInteger := AProducer.ID;
  mtProducers.FieldByName(fnIDCatalog).AsInteger := AProducer.IDCatalog;
  mtProducers.FieldByName(fnIDItemType).AsInteger := AProducer.CatalogItemType;
  mtProducers.FieldByName(fnGuid).AsString := AProducer.GUID;
  mtProducers.FieldByName(fnName).AsString := AProducer.Name;
  mtProducers.FieldByName(fnDescription).AsString := AProducer.Description;
  mtProducers.FieldByName(fnIsModified).AsBoolean := AAsModified;
  mtProducers.Post;
end;

procedure TF_CaseForm.AddPropertyToMemTable(AProperty: TNBProperty; AMemTable, AmtPropValRel, AmtPropValNormRes: TkbmMemtable; AAsModified: Boolean);
var
  NBPropValRel: TNBPropValRel;
  NBPropValNormRes: TNBPropValNormRes;
  i, j: Integer;
begin
  AMemTable.Append;
  AMemTable.FieldByName(fnID).AsInteger := AProperty.PropertyData.ID;
  AMemTable.FieldByName(fnIDCatalog).AsInteger := AProperty.IDCatalog;
  AMemTable.FieldByName(fnIDItemType).AsInteger := AProperty.CatalogItemType;
  AMemTable.FieldByName(fnGUID).AsString := AProperty.PropertyData.GUID;
  AMemTable.FieldByName(fnIDDataType).AsInteger := AProperty.PropertyData.IDDataType;
  AMemTable.FieldByName(fnName).AsString := AProperty.PropertyData.Name;
  AMemTable.FieldByName(fnSysName).AsString := AProperty.PropertyData.SysName;
  AMemTable.FieldByName(fnIzm).AsString := AProperty.PropertyData.Izm;
  AMemTable.FieldByName(fnValueReq).AsInteger := AProperty.PropertyData.ValueReq;
  AMemTable.FieldByName(fnMinValue).AsFloat := AProperty.PropertyData.MinValue;
  AMemTable.FieldByName(fnMaxValue).AsFloat := AProperty.PropertyData.MaxValue;
  AMemTable.FieldByName(fnDefValue).AsString := AProperty.PropertyData.DefValue;
  AMemTable.FieldByName(fnDescription).AsString := AProperty.PropertyData.Description;
  AMemTable.FieldByName(fnIsStandart).AsInteger := AProperty.PropertyData.IsStandart;
  AMemTable.FieldByName(fnSortID).AsInteger := AProperty.PropertyData.SortID;
  AMemTable.FieldByName(fnISProject).AsInteger := AProperty.PropertyData.ISProject;
  AMemTable.FieldByName(fnISFolder).AsInteger := AProperty.PropertyData.ISFolder;
  AMemTable.FieldByName(fnISList).AsInteger := AProperty.PropertyData.ISList;
  AMemTable.FieldByName(fnISRoom).AsInteger := AProperty.PropertyData.ISRoom;
  AMemTable.FieldByName(fnISSCSLine).AsInteger := AProperty.PropertyData.ISSCSLine;
  AMemTable.FieldByName(fnISSCSConnector).AsInteger := AProperty.PropertyData.ISSCSConnector;
  AMemTable.FieldByName(fnISComponLine).AsInteger := AProperty.PropertyData.ISComponLine;
  AMemTable.FieldByName(fnISComponConn).AsInteger := AProperty.PropertyData.ISComponConn;
  AMemTable.FieldByName(fnIsForWholeComponent).AsInteger := AProperty.PropertyData.IsForWholeComponent;
  AMemTable.FieldByName(fnIsValueRelToObj).AsInteger := AProperty.PropertyData.IsValueRelToObj;
  AMemTable.FieldByName(fnIsModified).AsBoolean := AAsModified;
  AMemTable.Post;

  if AmtPropValRel <> nil then
    for i := 0 to AProperty.PropValRelList.Count - 1 do
    begin
      NBPropValRel := TNBPropValRel(AProperty.PropValRelList[i]);

      AmtPropValRel.Append;
      AmtPropValRel.FieldByName(fnID).AsInteger := NBPropValRel.ID;
      AmtPropValRel.FieldByName(fnGUID).AsString := NBPropValRel.GUID;
      AmtPropValRel.FieldByName(fnIDProperty).AsInteger := NBPropValRel.IDProperty;
      AmtPropValRel.FieldByName(fnGuidProperty).AsString := NBPropValRel.GuidProperty;
      if NBPropValRel.PValue <> '' then
        AmtPropValRel.FieldByName(fnPValue).AsString := NBPropValRel.PValue
      else
        AmtPropValRel.FieldByName(fnPValue).Value := null;
      if NBPropValRel.MinValue <> '' then
        AmtPropValRel.FieldByName(fnMinValue).AsString := NBPropValRel.MinValue
      else
        AmtPropValRel.FieldByName(fnMinValue).Value := null;
      if NBPropValRel.MaxValue <> '' then
        AmtPropValRel.FieldByName(fnMaxValue).AsString := NBPropValRel.MaxValue
      else
        AmtPropValRel.FieldByName(fnMaxValue).Value := null;
      AmtPropValRel.FieldByName(fnIsNew).AsBoolean := false;
      AmtPropValRel.FieldByName(fnIsModified).AsBoolean := AAsModified;
      AmtPropValRel.Post;

      if AmtPropValNormRes <> nil then
        for j := 0 to NBPropValRel.PropValNormResList.Count - 1 do
        begin
          NBPropValNormRes := TNBPropValNormRes(NBPropValRel.PropValNormResList[j]);

          AmtPropValNormRes.Append;
          AmtPropValNormRes.FieldByName(fnID).AsInteger := NBPropValNormRes.ID;
          AmtPropValNormRes.FieldByName(fnGUID).AsString := NBPropValNormRes.GUID;
          AmtPropValNormRes.FieldByName(fnIDPropValRel).AsInteger := NBPropValNormRes.IDPropValRel;
          AmtPropValNormRes.FieldByName(fnGuidPropValRel).AsString := NBPropValNormRes.GuidPropValRel;
          AmtPropValNormRes.FieldByName(fnIDNBComponent).AsInteger := NBPropValNormRes.IDNBComponent;
          AmtPropValNormRes.FieldByName(fnGuidNBComponent).AsString := NBPropValNormRes.GuidNBComponent;
          AmtPropValNormRes.FieldByName(fnIDNBRes).AsInteger := NBPropValNormRes.IDNBRes;
          AmtPropValNormRes.FieldByName(fnGuidNBRes).AsString := NBPropValNormRes.GuidNBRes;
          AmtPropValNormRes.FieldByName(fnIDNBNorm).AsInteger := NBPropValNormRes.IDNBNorm;
          AmtPropValNormRes.FieldByName(fnGuidNBNorm).AsString := NBPropValNormRes.GuidNBNorm;
          AmtPropValNormRes.FieldByName(fnName).AsString:= '';
          AmtPropValNormRes.FieldByName(fnKolvo).AsFloat := NBPropValNormRes.Kolvo;
          AmtPropValNormRes.FieldByName(fnExpenseForLength).AsFloat := NBPropValNormRes.ExpenseForLength;
          AmtPropValNormRes.FieldByName(fnCountForPoint).AsFloat := NBPropValNormRes.CountForPoint;
          AmtPropValNormRes.FieldByName(fnStepOfPoint).AsFloat := NBPropValNormRes.StepOfPoint;
          AmtPropValNormRes.FieldByName(fnIsNew).AsBoolean := false;
          AmtPropValNormRes.FieldByName(fnIsModified).AsBoolean := AAsModified;
          AmtPropValNormRes.Post;
        end;
    end;
end;

procedure TF_CaseForm.AddResourceToMemTable(AResource: TNBResource; AAsNew, AAsModified: Boolean);
begin
  mtResources.Append;
  mtResources.FieldByName(fnID).AsInteger := AResource.ID;
  mtResources.FieldByName(fnIDCatalog).AsInteger := AResource.IDCatalog;
  mtResources.FieldByName(fnIDItemType).AsInteger := AResource.CatalogItemType;
  mtResources.FieldByName(fnGuid).AsString := AResource.GUID;
  mtResources.FieldByName(fnCypher).AsString := AResource.Cypher;
  mtResources.FieldByName(fnName).AsString := AResource.Name;
  mtResources.FieldByName(fnIzm).AsString := AResource.Izm;
  mtResources.FieldByName(fnPrice).AsFloat := AResource.Price;
  mtResources.FieldByName(fnRType).AsInteger := AResource.RType;
  mtResources.FieldByName(fnApplyForAllSame).AsBoolean := false;
  mtResources.FieldByName(fnIsNew).AsBoolean := AAsNew;
  mtResources.FieldByName(fnIsModified).AsBoolean := AAsModified;
  mtResources.Post;
end;

procedure TF_CaseForm.AddSuppliesKindToMemTable(ASuppliesKind: TNBSuppliesKind; AAsModified: Boolean);
begin
  mtSuppliesKinds.Append;
  mtSuppliesKinds.FieldByName(fnID).AsInteger := ASuppliesKind.Data.ID;
  mtSuppliesKinds.FieldByName(fnIDCatalog).AsInteger := ASuppliesKind.IDCatalog;
  mtSuppliesKinds.FieldByName(fnIDItemType).AsInteger := ASuppliesKind.CatalogItemType;
  mtSuppliesKinds.FieldByName(fnGUID).AsString := ASuppliesKind.Data.GUID;
  mtSuppliesKinds.FieldByName(fnName).AsString := ASuppliesKind.Data.Name;
  mtSuppliesKinds.FieldByName(fnNameTradUOM).AsString := ASuppliesKind.Data.NameTradUOM;
  mtSuppliesKinds.FieldByName(fnIzm).AsString := ASuppliesKind.Data.Izm;
  mtSuppliesKinds.FieldByName(fnIzmTradUOM).AsString := ASuppliesKind.Data.IzmTradUOM;
  mtSuppliesKinds.FieldByName(fnUnitKolvo).AsFloat := ASuppliesKind.Data.UnitKolvo;
  mtSuppliesKinds.FieldByName(fnUnitKolvoTradUOM).AsFloat := ASuppliesKind.Data.UnitKolvoTradUOM;
  mtSuppliesKinds.FieldByName(fnIsModified).AsBoolean := AAsModified;
  mtSuppliesKinds.Post;
end;

function TF_CaseForm.CheckAddObjectToMTByGUID(AObjectName, AGUIDToAdd, ANameToAdd: String; AMemTable: TkbmMemTable): Boolean;
begin
  Result := true;
  if CheckLocate(AMemTable, fnGuid, AGUIDToAdd) then
  begin
    Result := false;
    MessageModal(AObjectName+' '+ ANameToAdd +' '+cNowExists+'.',
                ApplicationName, MB_ICONINFORMATION or MB_OK);
    //MessageModal(cCaseForm_Msg35_1 + ANameToAdd+', '+AObjectName+' '+cNowExists+'.',
    //            ApplicationName, MB_ICONINFORMATION or MB_OK);
  end;
end;

function TF_CaseForm.GetNBCurrencyFromMemTable: TNBCurrency;
begin
  Result := TNBCurrency.Create(GForm);

  Result.Data.ID := mtCurrency.FieldByName(fnID).AsInteger;
  Result.IDCatalog := mtCurrency.FieldByName(fnIDCatalog).AsInteger;
  Result.CatalogItemType := mtCurrency.FieldByName(fnIDItemType).AsInteger;
  Result.Data.GUID := mtCurrency.FieldByName(fnGuid).AsString;
  Result.Data.Name := mtCurrency.FieldByName(fnName).AsString;
  Result.Data.NameBrief := mtCurrency.FieldByName(fnNameBrief).AsString;
  Result.Data.Kolvo := mtCurrency.FieldByName(fnKolvo).AsInteger;
  Result.Data.Ratio := mtCurrency.FieldByName(fnRatio).AsFloat;
  Result.Data.Main := mtCurrency.FieldByName(fnMain).AsInteger;
  Result.SavedMain := mtCurrency.FieldByName(fnSavedMain).AsInteger;
  // := mtCurrency.FieldByName(fnSortID).AsInteger;
  Result.Data.IsCountry := mtCurrency.FieldByName(fnIsCountry).AsInteger;
  Result.IsModified := mtCurrency.FieldByName(fnIsModified).AsBoolean;
end;

function TF_CaseForm.GetNBCurrencyFromMemTableByMain(AMainType: Integer): TNBCurrency;
var
  //BookmarkStr: String;
  BookmarkStr: TBookMark;
begin
  Result := nil;
  //BookmarkStr := mtCurrency.Bookmark;
  BookmarkStr := mtCurrency.GetBookmark;
  try
    if mtCurrency.Locate(fnMain, AMainType, []) then
      Result := GetNBCurrencyFromMemTable;
  finally
    //mtCurrency.Bookmark := BookmarkStr;
    if BookmarkStr <> nil then
    begin
      mtCurrency.GotoBookmark(BookmarkStr);
      mtCurrency.FreeBookmark(BookmarkStr);
    end;
  end;
end;

function TF_CaseForm.GetNBCurrencyFromMemTableByGUID(AGUID: String): TNBCurrency;
var
  //BookmarkStr: String;
  BookmarkStr: TBookMark;
begin
  Result := nil;
  //BookmarkStr := mtCurrency.Bookmark;
  BookmarkStr := mtCurrency.GetBookmark;
  try
    if mtCurrency.Locate(fnGuid, AGUID, []) then
      Result := GetNBCurrencyFromMemTable;
  finally
    if BookmarkStr <> nil then
    begin
      mtCurrency.GotoBookmark(BookmarkStr);
      mtCurrency.FreeBookmark(BookmarkStr);
    end;
    //mtCurrency.Bookmark := BookmarkStr;
  end;
end;

// #############################################################################
// #############################################################################
//
// ##### Контроль значение на минимум, максимум и обязательность #####
{
Function TF_CaseForm.MinMaxReqControl(AValue: String): Boolean;
//Var Len: Integer;
begin
  Result := True;
  case TF_Main(GForm).DM.DataSet_PROPERTIES.FN('ID_Data_Type').AsInteger of
      dtFloat , dtInteger: // 0 or 1
        begin
          if TF_Main(GForm).DM.DataSet_PROPERTIES.FN('Min_Value').AsFloat <> 0 then
            if StrToFloat_My(AValue) < TF_Main(GForm).DM.DataSet_PROPERTIES.FN('Min_Value').AsFloat then
            begin
              MessageDlg(cCaseForm_Msg9, mtInformation, [mbOK], 0);
              Result := false;
            end;

          if TF_Main(GForm).DM.DataSet_PROPERTIES.FN('Max_Value').AsFloat <> 0 then
            if StrToFloat_My(AValue) > TF_Main(GForm).DM.DataSet_PROPERTIES.FN('Max_Value').AsFloat then
            begin
              MessageDlg(cCaseForm_Msg10, mtInformation, [mbOK], 0);
              Result := false;
            end;
        end;
      dtDate:
        begin
          if TF_Main(GForm).DM.DataSet_PROPERTIES.FN('Min_Value').AsFloat <> 0 then
           if StrToDate(AValue) < FloatToDateTime( TF_Main(GForm).DM.DataSet_PROPERTIES.FN('Min_Value').AsFloat) then
           begin
             MessageDlg(cCaseForm_Msg11,
                mtInformation, [mbOK], 0);
              Result := false;
           end;

          if TF_Main(GForm).DM.DataSet_PROPERTIES.FN('Max_Value').AsFloat <> 0 then
            if StrToDate(AValue) > FloatToDateTime( TF_Main(GForm).DM.DataSet_PROPERTIES.FN('Max_Value').AsFloat) then
            begin
              MessageDlg(cCaseForm_Msg12,
                  mtInformation, [mbOK], 0);
              Result := false;
            end;
        end;
  end;

  if (TF_Main(GForm).DM.DataSet_PROPERTIES.FN('Value_Req').AsInteger = 1) and
     (Length(AValue) = 0) then
  begin
   MessageDlg(cCaseForm_Msg13,
               mtInformation, [mbOK], 0);
   Result := false;
  end;
end;
}

{
procedure TF_CaseForm.FormView(AVKind: TViewKind; ACaption: String; AHeight,
  AWidth: Integer; AisToolBar: Boolean; AToolHint: String);
begin
    GroupBox_Properties.Visible := false;
    GroupBox_Interfaces.Visible := false;
    GroupBox_Currency.Visible := false;
    GroupBox_NetType.Visible := false;
    GroupBox_Producers.Visible := false;
    GroupBox_ObjectIcons.Visible := false;
    GroupBox_ComponentTypes.Visible := false;
    GroupBox_NB_Resources.Visible := false;
    GroupBox_NB_Norms.Visible := false;

    Caption := ACaption;
    Height := AHeight;
    Width := AWidth;

    if AisToolBar then
      begin
          ToolBar_Edit.Visible := true;
          ToolButton_Make.Hint := 'Создать ' + AToolHint;
          ToolButton_Edit.Hint := 'Изменить ' + AToolHint;
          ToolButton_Del.Hint  := 'Удалить ' + AToolHint;

          Act_Make.Caption := ToolButton_Make.Hint;
          Act_Edit.Caption := ToolButton_Edit.Hint;
          Act_Del.Caption := ToolButton_Del.Hint;
      end
    else
      ToolBar_Edit.Visible := false;

    case AVKind of
        vkProperty  : GroupBox_Properties.Visible := true;
        vkInterface : GroupBox_Interfaces.Visible := true;
        vkCurrency  : GroupBox_Currency.Visible := true;
        vkNetType   : GroupBox_NetType.Visible := true;
        vkProducers : GroupBox_Producers.Visible := true;
        vkObjectIcons: GroupBox_ObjectIcons.Visible := true;
        vkComponentType: GroupBox_ComponentTypes.Visible := true;
        vkResource  : GroupBox_NB_Resources.Visible := true;
        vkNorm      : GroupBox_NB_Norms.Visible := true;
    end;

end;}




// ##### Значение Edit-а представить в строку #####
{function TF_CaseForm.GetValueFromEdit( ADataType: Integer): String;
var _Value : String;
begin
    Result := '';

    case ADataType of
      dtFloat  : _Value := FloatToStr(SpinEdit_Value.Value);
      dtInteger: _Value := IntToStr(SpinEdit_Value.Value);
      dtBoolean: if CheckBox_Value.Checked then
                   _Value := '1'
                 else
                   _Value := '0';
      dtString : _Value := Edit_Value.Text;
      dtDate   : _Value := DateToStr(DateEdit_Value.Date);
      dtCompStateType: _Value := IntToStr(GetIDFromComboBox(ComboBox_Value));
      dtColor: _Value := IntToStr(ColorEdit_Value.SelectedColor);
    end;
   Result := _Value;
end;}

{
// ##### Значение (в строке) представить в соответствии с типом данных в Эдите #####
procedure TF_Caseform.ShowValue( ADataType: Integer; AValue: String);
begin
    Edit_Value.Visible := false;
    SpinEdit_Value.Visible := false;
    CheckBox_Value.Visible := False;
    DateEdit_Value.Visible := false;
    ComboBox_Value.Visible := false;
    ColorEdit_Value.Visible := false;
    lbValue.Visible := false;

    ClearComboBox(ComboBox_Value);

    CheckBox_TakeIntoConnect.Visible := true;
    CheckBox_TakeIntoJoin.Visible := true;

    //if Act_Edit.Enabled and Act_Del.Enabled then
    Case ADataType of
      dtFloat  : begin
                     SpinEdit_Value.Visible := true;
                     SpinEdit_Value.Properties.ValueType := vtFloat;
                     if AValue <> '' then
                      SpinEdit_Value.Value := StrToFloat_My(AValue);
                 end;
      dtInteger :begin
                     SpinEdit_Value.Visible := true;
                     SpinEdit_Value.Properties.ValueType := vtInt;
                     if AValue <> '' then
                      SpinEdit_Value.Value := StrToInt(AValue);
                 end;
      dtBoolean :begin
                     CheckBox_Value.Visible := true;
                     if AValue = '1' then
                       CheckBox_Value.Checked := true
                     else
                       CheckBox_Value.Checked := false
                 end;
      dtString  :begin
                     Edit_Value.Visible := true;
                     Edit_Value.Text := AValue;
                 end;
      dtDate    :begin
                     DateEdit_Value.Visible := true;
                     if AValue <> '' then
                      DateEdit_Value.Date := StrToDate(AValue);
                 end;
      dtCompStateType:
          begin
              AddIDToCombo(oitProjectible, cCaseForm_Msg15_1, ComboBox_Value);
              AddIDToCombo(oitActive, cCaseForm_Msg15_2, ComboBox_Value);

              ComboBox_Value.Visible := true;
              if AValue <> '' then
                SelectItemByIDinCombo(ComboBox_Value, StrToInt(AValue));
          end;
      dtColor:
          begin
              ColorEdit_Value.Visible := true;
              if AValue <> '' then
                ColorEdit_Value.SelectedColor := StrToInt(AValue);
          end;
      dtCableCanalElementType:
        begin
          CheckBox_TakeIntoConnect.Visible := false;
          CheckBox_TakeIntoJoin.Visible := false;

          lbValue.Visible := true;
          lbValue.Caption := cCaseForm_Msg14;
        end;
    end;
end;
}

procedure TF_CaseForm.ShowPropItemType(AItemType: TItemType);
var strOwner: String;

  procedure AddToownerString(AOwnerName: String);
  begin
      if strOwner <> '' then
        strOwner := strOwner + '; ';
      strOwner := strOwner + AOwnerName;
  end;

begin
    strOwner := '';
    with TF_Main(GForm).DM.DataSet_PROPERTIES do
      begin
          if FN(fnIsProject).AsInteger = biTrue then
            AddToownerString(cCaseForm_Msg16_2_1);
          if FN(fnIsFolder).AsInteger = biTrue then
            AddToownerString(cCaseForm_Msg16_2_2);
          if FN(fnIsList).AsInteger = biTrue then
            AddToownerString(cCaseForm_Msg16_2_3);
          if FN(fnIsRoom).AsInteger = biTrue then
            AddToownerString(cCaseForm_Msg16_2_4);
          if FN(fnIsSCSline).AsInteger = biTrue then
            AddToownerString(cCaseForm_Msg16_2_5);
          if FN(fnIsSCSConnector).AsInteger = biTrue then
            AddToownerString(cCaseForm_Msg16_2_6);
          if FN(fnIsComponLine).AsInteger = biTrue then
            AddToownerString(cCaseForm_Msg16_2_7);
          if FN(fnIsComponConn).AsInteger = biTrue then
            AddToownerString(cCaseForm_Msg16_2_8);
      end;
    spPropertyItemType.Caption := cCaseForm_Msg16_1+': '+strOwner;
end;


function TF_CaseForm.GetDirTypeInfo(AViewKind: TViewKind): TDirTypeInfo;
var
  DBMode: TDBKind;
begin
  DBMode := TF_Main(GForm).GDBMode;
  ZeroMemory(@Result, SizeOf(TDirTypeInfo));
  Result.ViewKind := AViewKind; 
  Result.DataSet := nil;
  Result.DataSrc := nil;
  Result.FldName := fnName;
  case AViewKind of
    vkComponentType:
      begin
        Result.ItemType := ditComponentType;
        Result.TableName := tnComponentTypes;
        Result.TableCaption := cCaseForm_Msg17_1;
        if DBMode = bkNormBase then
          Result.DataSet := TF_Main(GForm).DM.DataSet_COMPONENT_TYPES
        else
        if DBMode = bkProjectManager then
          Result.DataSet := mtComponentType;
      end;
    vkCurrency:
      begin
        Result.ItemType := ditCurrency;
        Result.TableName := tnCurrency;
        Result.TableCaption := cCaseForm_Msg17_2;
        if DBMode = bkNormBase then
          Result.DataSet := TF_Main(GForm).DM.DataSet_CURRENCY
        else
        if DBMode = bkProjectManager then
          Result.DataSet := mtCurrency;
      end;
    vkInterface:
      begin
        Result.ItemType := ditInterface;
        Result.TableName := tnInterface;
        Result.TableCaption := cCaseForm_Msg17_3;
        if DBMode = bkNormBase then
          Result.DataSet := TF_Main(GForm).DM.DataSet_INTERFACE
        else
        if DBMode = bkProjectManager then
          Result.DataSet := mtInterface;
      end;
    vkNetType:
      begin
        Result.ItemType := ditNetType;
        Result.TableName := tnNetType;
        Result.TableCaption := cCaseForm_Msg17_4;
        if DBMode = bkNormBase then
          Result.DataSet := TF_Main(GForm).DM.DataSet_NET_TYPE
        else
        if DBMode = bkProjectManager then
          Result.DataSet := mtNetType;
      end;
    vkNorm:
      begin
        Result.ItemType := ditNBNorm;
        Result.TableName := tnNBNorms;
        Result.TableCaption := cCaseForm_Msg17_5;
        if DBMode = bkNormBase then
          Result.DataSet := TF_Main(GForm).DM.DataSet_NB_NORMS
        else
        if DBMode = bkProjectManager then
          Result.DataSet := mtNorms;
      end;
    vkObjectIcons:
      begin
        Result.ItemType := ditObjectIcon;
        Result.TableName := tnObjectIcons;
        Result.TableCaption := cCaseForm_Msg17_6;
        if DBMode = bkNormBase then
          Result.DataSet := TF_Main(GForm).DM.DataSet_OBJECT_ICONS
        else
        if DBMode = bkProjectManager then
          Result.DataSet := mtObjectIcons;
      end;
    vkProducers:
      begin
        Result.ItemType := ditProducer;
        Result.TableName := tnProducers;
        Result.TableCaption := cCaseForm_Msg17_7;
        if DBMode = bkNormBase then
          Result.DataSet := TF_Main(GForm).DM.DataSet_PRODUCERS
        else
        if DBMode = bkProjectManager then
          Result.DataSet := mtProducers;
      end;
    vkProperty:
      begin
        Result.ItemType := ditProperty;
        Result.TableName := tnProperties;
        Result.TableCaption := cCaseForm_Msg17_8;
        if DBMode = bkNormBase then
          Result.DataSet := TF_Main(GForm).DM.DataSet_PROPERTIES
        else
        if DBMode = bkProjectManager then
          Result.DataSet := mtProperties;
      end;
    vkResource:
      begin
        Result.ItemType := ditNBResource;
        Result.TableName := tnNBResources;
        Result.TableCaption := cCaseForm_Msg17_9;
        if DBMode = bkNormBase then
          Result.DataSet := TF_Main(GForm).DM.DataSet_NB_RESOURCES
        else
        if DBMode = bkProjectManager then
          Result.DataSet := mtResources;
      end;
    vkSuppliesKind:
      begin
        Result.ItemType := ditSuppliesKinds;
        Result.TableName := tnSuppliesKinds;
        Result.TableCaption := cCaseForm_Msg17_10;
        if DBMode = bkNormBase then
          Result.DataSet := TF_Main(GForm).DM.DataSet_SuppliesKinds
        else
        if DBMode = bkProjectManager then
          Result.DataSet := mtSuppliesKinds;
      end;
    vkUnitsOfMeasure:
      begin
        Result.ItemType := ditUnitsOfMeasure;
        Result.TableName := tnInputStrings;
        Result.TableCaption := cCaseForm_Msg17_11;
        if DBMode = bkNormBase then
          //Result.DataSet := TF_Main(GForm).DM.dsetUnitsOfMeasure;
          Result.DataSrc := TF_Main(GForm).DM.dsrcUnitsOfMeasure;
        //else
        //if DBMode = bkProjectManager then
        //  Result.DataSet := nil;
      end;
    vkDimensions:
      begin
        Result.ItemType := ditDimensions;
        Result.TableName := tnInputStrings;
        Result.TableCaption := cCaseForm_Msg17_12;
        if DBMode = bkNormBase then
          //Result.DataSet := TF_Main(GForm).DM.dsetDimensions;
          Result.DataSrc := TF_Main(GForm).DM.dsrcDimensions; 
        //else
        //if DBMode = bkProjectManager then
        //  Result.DataSet := nil;
      end;
    vkCompSpecifications:
      begin
        Result.ItemType := ditCompSpecifications;
        Result.TableName := tnFiles;
        Result.TableCaption := cCaseForm_Msg17_13;
        Result.FldName := fnFileName;
        if DBMode = bkNormBase then
          //Result.DataSet := TF_Main(GForm).DM.dsetCompSpecifications;
          Result.DataSrc := TF_Main(GForm).DM.dsrcCompSpecifications;

        //else
        //if DBMode = bkProjectManager then
        //  Result.DataSet := nil;
      end;
  end;

  if (Result.DataSet = nil) and (Result.DataSrc <> nil) then
    Result.DataSet := Result.DataSrc.DataSet;

  Result.MasterFieldName := GetMasterFNameByDirItemType(Result.ItemType);
end;

function TF_CaseForm.GetFormParams(AViewKind: TViewKind): TCaseFormParams;
begin
  ZeroMemory(@Result, SizeOf(TDirTypeInfo));
  case AViewKind of
    vkComponentType:
      begin
        Result.ActiveGroupControl := GroupBox_ComponentTypes;
        Result.ActiveGrid := Grid_ComponentTypes;
        Result.ActiveGridDBTableView := GT_ComponentTypes;
        Result.CaptionForActions := cCaseForm_Msg18_1_1;
        Result.CaptionForForm := cCaseForm_Msg18_1_2;
      end;
    vkCurrency:
      begin
        Result.ActiveGroupControl := GroupBox_Currency;
        Result.ActiveGrid := Grid_Currency;
        Result.ActiveGridDBTableView := GT_CURRENCY;
        Result.CaptionForActions := cCaseForm_Msg18_2_1;
        Result.CaptionForForm := cCaseForm_Msg18_2_2;
      end;
    vkInterface:
      begin
        Result.ActiveGroupControl := GroupBox_Interfaces;
        Result.ActiveGrid := Grid_Interface;
        Result.ActiveGridDBTableView := GT_Interfaces;
        Result.CaptionForActions := cCaseForm_Msg18_3_1;
        Result.CaptionForForm := cCaseForm_Msg18_3_2;
      end;
    vkNetType:
      begin
        Result.ActiveGroupControl := GroupBox_NetType;
        Result.ActiveGrid := Grid_NetType;
        Result.ActiveGridDBTableView := GT_NetType;
        Result.CaptionForActions := cCaseForm_Msg18_4_1;
        Result.CaptionForForm := cCaseForm_Msg18_4_2;
      end;
    vkNorm:
      begin
        Result.ActiveGroupControl := GroupBox_NB_Norms;
        Result.ActiveGrid := Grid_NB_Norms;
        Result.ActiveGridDBTableView := GT_NB_Norms;
        Result.CaptionForActions := cCaseForm_Msg18_5_1;
        Result.CaptionForForm := cCaseForm_Msg18_5_2;
      end;
    vkObjectIcons:
      begin
        Result.ActiveGroupControl := GroupBox_ObjectIcons;
        Result.ActiveGrid := Grid_ObjectIcons;
        Result.ActiveGridDBTableView := GT_ObjectIcons;
        Result.CaptionForActions := cCaseForm_Msg18_6_1;
        Result.CaptionForForm := cCaseForm_Msg18_6_2;
      end;
    vkProducers:
      begin
        Result.ActiveGroupControl := GroupBox_Producers;
        Result.ActiveGrid := Grid_Producers;
        Result.ActiveGridDBTableView := GT_Producers;
        Result.CaptionForActions := cCaseForm_Msg18_7_1;
        Result.CaptionForForm := cCaseForm_Msg18_7_2;
      end;
    vkProperty:
      begin
        Result.ActiveGroupControl := GroupBox_Properties;
        Result.ActiveGrid := Grid_Properties;
        Result.ActiveGridDBTableView := GT_Properties;
        Result.CaptionForActions := cCaseForm_Msg18_8_1;
        Result.CaptionForForm := cCaseForm_Msg18_8_2;
      end;
    vkResource:
      begin
        Result.ActiveGroupControl := GroupBox_NB_Resources;
        Result.ActiveGrid := Grid_NB_Resources;
        Result.ActiveGridDBTableView := GT_NB_Resources;
        Result.CaptionForActions := cCaseForm_Msg18_9_1;
        Result.CaptionForForm := cCaseForm_Msg18_9_2;
      end;
    vkSuppliesKind:
      begin
        Result.ActiveGroupControl := gbSuppliesKinds;
        Result.ActiveGrid := Grid_SuppliesKinds;
        Result.ActiveGridDBTableView := GT_SuppliesKinds;
        Result.CaptionForActions := cCaseForm_Msg18_10_1;
        Result.CaptionForForm := cCaseForm_Msg18_10_2;
      end;
    vkUnitsOfMeasure:
      begin
        Result.ActiveGroupControl := gbUnitsOfMeasure;
        Result.ActiveGrid := Grid_UnitsOfMeasure;
        Result.ActiveGridDBTableView := GT_UnitsOfMeasure;
        Result.CaptionForActions := cCaseForm_Msg18_11_1;
        Result.CaptionForForm := cCaseForm_Msg18_11_2;
      end;
    vkDimensions:
      begin
        Result.ActiveGroupControl := gbDimensions;
        Result.ActiveGrid := Grid_Dimensions;
        Result.ActiveGridDBTableView := GT_Dimensions;
        Result.CaptionForActions := cCaseForm_Msg18_12_1;
        Result.CaptionForForm := cCaseForm_Msg18_12_2;
      end;
    vkCompSpecifications:
      begin
        Result.ActiveGroupControl := gbCompSpecifications;
        Result.ActiveGrid := Grid_CompSpecifications;
        Result.ActiveGridDBTableView := GT_CompSpecifications;
        Result.CaptionForActions := cCaseForm_Msg18_13_1;
        Result.CaptionForForm := cCaseForm_Msg18_13_2;
      end;
  end;
end;


function TF_CaseForm.NotDelDataUsedInMemTable(AMTKeyField, ADelKind, AItName: String; ADSKeyValue: Integer): Boolean;
var MTRecNo: Integer;
    DelName: String;
begin
  Result := false;

  if GUseMemTable = nil then
    Exit;

  if GUseMemTable.Active then
  begin
    if GUseMemTable.RecordCount > 0 then
    begin
      MTRecNo := GUseMemTable.RecNo;
      GUseMemTable.First;
      while Not GUseMemTable.Eof do
      begin
        if GUseMemTable.FieldByName(AMTKeyField).asInteger = ADSKeyValue then
        begin
          DelName := GUseMemTable.FieldByName('Name').AsString;
          MessageModal(cImpossibleDel+' '+ ADelKind+ ' "'+ DelName +'" '+cSince+' '+AItName+' '+cUsing,
                cActNameDeleting, MB_ICONINFORMATION or MB_OK);
          Result := true;
          Break;
        end;
        GUseMemTable.Next;
      end;
      GUseMemTable.RecNo := MTRecNo;
    end;
  end;
end;


// #############################################################################
// #############################################################################
//
// ##### Создание формы #####
procedure TF_CaseForm.FormCreate(Sender: TObject);
var
  DisplayFormatBaseCurrency: String;
  EmptyDisplayFormat: String;
begin
    FOldViewKind := vkNone;

    DisplayFormatBaseCurrency := '';
    DisplayFormatBaseCurrency := GetDisplayFormat(TF_Main(GForm).GCurrencyM.NameBrief);
    EmptyDisplayFormat := GetDisplayFormat('');

    //*** Repositoris
    with TF_Main(GForm).DM do
    begin
      GT_NB_NormResourceRelPRICE.RepositoryItem := ceRepositoryCommon;
      GT_NB_NormResourceRelAdditionalPrice.RepositoryItem := ceRepositoryCommon;
      GT_NB_NormResourceRelCOST.RepositoryItem := ceRepositoryCommon;
    end;

    TcxCurrencyEditProperties(GT_CURRENCYRATIO.Properties).DisplayFormat := GetDisplayFormatForFloat;
    //TcxCurrencyEditProperties(GT_NB_NormResourceRelPRICE.Properties).DisplayFormat := DisplayFormatBaseCurrency;
    //TcxCurrencyEditProperties(GT_NB_NormResourceRelAdditionalPrice.Properties).DisplayFormat := DisplayFormatBaseCurrency;
    //TcxCurrencyEditProperties(GT_NB_NormResourceRelCOST.Properties).DisplayFormat := DisplayFormatBaseCurrency;

    //27.10.2013
    //TcxCurrencyEditProperties(GT_NB_ResourcesAdditionalPrice.Properties).DisplayFormat := DisplayFormatBaseCurrency;
    //TcxCurrencyEditProperties(GT_NB_ResourcesPRICE.Properties).DisplayFormat := DisplayFormatBaseCurrency;
    //TcxCurrencyEditProperties(GT_NB_NormsPrice.Properties).DisplayFormat := DisplayFormatBaseCurrency;
    SetCurrencyBriefToControls(TF_Main(GForm).GCurrencyM); //27.10.2013

    TcxCurrencyEditProperties(GT_InterfacesConstructiveWidth.Properties).DisplayFormat := GetDisplayFormatForFloatByPrecision(PrecisionNormKolvo);
    if TF_Main(GForm).GDBMode = bkNormBase then
      TcxLookupComboBoxProperties(GT_InterfacesIDNetType.Properties).KeyFieldNames := fnID
    else
      TcxLookupComboBoxProperties(GT_InterfacesIDNetType.Properties).KeyFieldNames := fnGUID;

    TcxCurrencyEditProperties(GT_InterfaceNormsExpense.Properties).DisplayFormat := GetDisplayFormatForFloatByPrecision(PrecisionNormKolvo);
    TcxCurrencyEditProperties(GT_InterfaceNormsExpense.Properties).DecimalPlaces := PrecisionNormKolvo;

    TcxCurrencyEditProperties(GT_SuppliesKindsUNIT_KOLVO.Properties).DisplayFormat := GetDisplayFormatForFloat;

    {if GDBActiveKind = bkNormBase then
      begin
          Label_Prop_Caption.Visible := false;
          Label_PropItemType.Visible := false;
      end; }
    GCurrRecNoObjectIcons := 0;

    {
    GT_PROPERTIES.DataController.DataSource := TF_Main(GForm).DM.DataSource_PROPERTIES;
    GT_Interfaces.DataController.DataSource := TF_Main(GForm).DM.DataSource_INTERFACE;
    GT_InterfAccordance.DataController.DataSource := TF_Main(GForm).DM.DataSource_InterfAccordance;
    GT_InterfaceNorms.DataController.DataSource := TF_Main(GForm).DM.DataSource_Interface_Norms;
    GT_CURRENCY.DataController.DataSource := TF_Main(GForm).DM.DataSource_CURRENCY;
    GT_NetType.DataController.DataSource := TF_Main(GForm).DM.DataSource_NET_TYPE;
    GT_Producers.DataController.DataSource := TF_Main(GForm).DM.DataSource_PRODUCERS;

    GT_NB_Norms.DataController.DataSource := TF_Main(GForm).DM.DataSource_NB_NORMS;
    GT_NB_NormResourceRel.DataController.DataSource := TF_Main(GForm).DM.DataSource_NB_NORM_RESOURCE_REL;
    GT_NB_Resources.DataController.DataSource := TF_Main(GForm).DM.DataSource_NB_RESOURCES;

    GT_ComponentTypes.DataController.DataSource := TF_Main(GForm).DM.DataSource_COMPONENT_TYPES;
    GT_CompTypeProp.DataController.DataSource := TF_Main(GForm).DM.DataSource_COMP_TYPE_PROP_RELATION;
    }

    {
    GT_NB_Norms.DataController.DataSource := F_NormBase.DM.DataSource_NB_NORMS;
    GT_NB_NormResourceRel.DataController.DataSource := F_NormBase.DM.DataSource_NB_NORM_RESOURCE_REL;
    GT_NB_Resources.DataController.DataSource := F_NormBase.DM.DataSource_NB_RESOURCES; }


    //AddNodes(nil);
    //Tree_InterfType.Selected := Tree_InterfType.TopItem;

    if Assigned(Panel_Kolvo) then
      Panel_Kolvo.Visible := false;

    GT_InterfacesIsVisible.Visible := IsShowUnvisibleInterface and (TF_Main(GForm).GDBMode = bkNormBase);

    FShowedTables := TIntList.Create;

    //**** Значения параметров по умолчанию
    FDefIconName := '';
    FDefFileBmp := '';
    FDefFileBlk := '';


    //*** Справочники проекта/листа
    mtComponentType := nil;
    mtCompTypePropRelation := nil;
    mtCurrency := nil;
    mtInterface := nil;
    mtInterfaceAccordance := nil;
    mtInterfaceNorms := nil;
    mtNetType := nil;
    mtNorms := nil;
    mtObjectIcons := nil;
    mtProducers := nil;
    mtProperties := nil;
    mtPropValRel := nil;
    mtPropValNormRes := nil;
    mtResources := nil;
    mtSuppliesKinds := nil;
    dsComponentType := nil;
    dsCompTypePropRelation := nil;
    dsCurrency := nil;
    dsInterface := nil;
    dsInterfaceAccordance := nil;
    dsInterfaceNorms := nil;
    dsNetType := nil;
    dsNorms := nil;
    dsObjectIcons := nil;
    dsProducers := nil;
    dsProperties := nil;
    dsPropValRel := nil;
    dsPropValNormRes := nil;
    dsResources := nil;
    dsSuppliesKinds := nil;

    MemTableComponTypes := nil;
    MemTableProperties := nil;

    if TF_Main(GForm).GDBMode = bkNormBase then
    begin
      GT_InterfacesNameNetType.Visible := false;
      GT_ComponentTypesComponentIndex.Free;
    end;

    if TF_Main(GForm).GDBMode = bkProjectManager then
    begin
      FFormMode := fmView;

      mtComponentType := TkbmMemTable.Create(Self);
      mtCompTypePropRelation := TkbmMemTable.Create(Self);
      mtCurrency := TkbmMemTable.Create(Self);
      mtInterface := TkbmMemTable.Create(Self);
      mtInterfaceAccordance := TkbmMemTable.Create(Self);
      mtInterfaceNorms := TkbmMemTable.Create(Self);
      mtNetType := TkbmMemTable.Create(Self);
      mtNorms := TkbmMemTable.Create(Self);
      mtObjectIcons := TkbmMemTable.Create(Self);
      mtProducers := TkbmMemTable.Create(Self);
      mtProperties := TkbmMemTable.Create(Self);
      mtPropValRel := TkbmMemTable.Create(Self);
      mtPropValNormRes := TkbmMemTable.Create(Self);
      mtResources := TkbmMemTable.Create(Self);
      mtSuppliesKinds := TkbmMemTable.Create(Self);
      dsComponentType := TDataSource.Create(Self);
      dsCompTypePropRelation := TDataSource.Create(Self);
      dsInterface := TDataSource.Create(Self);
      dsInterfaceAccordance := TDataSource.Create(Self);
      dsInterfaceNorms := TDataSource.Create(Self);
      dsCurrency := TDataSource.Create(Self);
      dsNetType := TDataSource.Create(Self);
      dsNorms := TDataSource.Create(Self);
      dsObjectIcons := TDataSource.Create(Self);
      dsProducers := TDataSource.Create(Self);
      dsProperties := TDataSource.Create(Self);
      dsPropValRel := TDataSource.Create(Self);
      dsPropValNormRes := TDataSource.Create(Self);
      dsResources := TDataSource.Create(Self);
      dsSuppliesKinds := TDataSource.Create(Self);

      dsComponentType.DataSet := mtComponentType;
      dsCompTypePropRelation.DataSet := mtCompTypePropRelation;
      dsCurrency.DataSet := mtCurrency;
      dsInterface.DataSet := mtInterface;
      dsInterfaceAccordance.DataSet := mtInterfaceAccordance;
      dsInterfaceNorms.DataSet := mtInterfaceNorms;
      dsNetType.DataSet := mtNetType;
      dsNorms.DataSet := mtNorms;
      dsObjectIcons.DataSet := mtObjectIcons;
      dsProducers.DataSet := mtProducers;
      dsProperties.DataSet := mtProperties;
      dsPropValRel.DataSet := mtPropValRel;
      dsPropValNormRes.DataSet := mtPropValNormRes;
      dsResources.DataSet := mtResources;
      dsSuppliesKinds.DataSet := mtSuppliesKinds;


      mtComponentType.FieldDefs.Add(fnID, ftInteger);
      mtComponentType.FieldDefs.Add(fnIDCatalog, ftInteger);
      mtComponentType.FieldDefs.Add(fnIDItemType, ftInteger);
      mtComponentType.FieldDefs.Add(fnGuid, ftString, 40);
      mtComponentType.FieldDefs.Add(fnName, ftString, 255);
      mtComponentType.FieldDefs.Add(fnNamePlural, ftString, 255);
      mtComponentType.FieldDefs.Add(fnMarkMask, ftString, 255);
      mtComponentType.FieldDefs.Add(fnPortKind, ftInteger);
      mtComponentType.FieldDefs.Add(fnActiveState, ftInteger);
      mtComponentType.FieldDefs.Add(fnIDDesignIcon, ftInteger);
      mtComponentType.FieldDefs.Add(fnGUIDDesignIcon, ftString, 40);
      mtComponentType.FieldDefs.Add(fnIsLine, ftInteger);
      mtComponentType.FieldDefs.Add(fnisStandart, ftInteger);
      mtComponentType.FieldDefs.Add(fnCoordZ, ftFloat);
      mtComponentType.FieldDefs.Add(fnSysName, ftString, 100);
      mtComponentType.FieldDefs.Add(fnComponentIndex, ftLargeint);
      mtComponentType.FieldDefs.Add(fnCanUseAsPoint, ftInteger);
      mtComponentType.FieldDefs.Add(fnPropsCount, ftInteger);
      mtComponentType.FieldDefs.Add(fnIsModified, ftBoolean);

      mtCompTypePropRelation.FieldDefs.Add(fnGUID, ftString, 40);
      mtCompTypePropRelation.FieldDefs.Add(fnID, ftInteger);
      mtCompTypePropRelation.FieldDefs.Add(fnIDComponentType, ftInteger);
      mtCompTypePropRelation.FieldDefs.Add(fnIDProperty, ftInteger);
      mtCompTypePropRelation.FieldDefs.Add(fnGuidComponentType, ftString, 40);
      mtCompTypePropRelation.FieldDefs.Add(fnGuidProperty, ftString, 40);
      mtCompTypePropRelation.FieldDefs.Add(fnTakeIntoConnect, ftInteger);
      mtCompTypePropRelation.FieldDefs.Add(fnTakeIntoJoin, ftInteger);
      mtCompTypePropRelation.FieldDefs.Add(fnPValue, ftString, 255);
      mtCompTypePropRelation.FieldDefs.Add(fnisStandart, ftInteger);
      mtCompTypePropRelation.FieldDefs.Add(fnName, ftString, 255);
      mtCompTypePropRelation.FieldDefs.Add(fnSysName, ftString, 200);
      mtCompTypePropRelation.FieldDefs.Add(fnIzm, ftString, 200);
      mtCompTypePropRelation.FieldDefs.Add(fnIDDataType, ftInteger);
      mtCompTypePropRelation.FieldDefs.Add(fnIsModified, ftBoolean);

      mtCompTypePropRelation.MasterSource := dsComponentType;
      mtCompTypePropRelation.MasterFields := fnGUID;
      mtCompTypePropRelation.DetailFields := fnGuidComponentType;

      mtCurrency.FieldDefs.Add(fnID, ftInteger);
      mtCurrency.FieldDefs.Add(fnIDCatalog, ftInteger);
      mtCurrency.FieldDefs.Add(fnIDItemType, ftInteger);
      mtCurrency.FieldDefs.Add(fnGuid, ftString, 40);
      mtCurrency.FieldDefs.Add(fnName, ftString, 255);
      mtCurrency.FieldDefs.Add(fnNameBrief, ftString, 255);
      mtCurrency.FieldDefs.Add(fnKolvo, ftInteger);
      mtCurrency.FieldDefs.Add(fnRatio, ftFloat);
      mtCurrency.FieldDefs.Add(fnMain, ftSmallint);
      mtCurrency.FieldDefs.Add(fnSavedMain, ftSmallint);
      mtCurrency.FieldDefs.Add(fnSortID, ftInteger);
      mtCurrency.FieldDefs.Add(fnIsCountry, ftInteger);
      mtCurrency.FieldDefs.Add(fnIsModified, ftBoolean);


      mtInterface.FieldDefs.Add(fnID, ftInteger);
      mtInterface.FieldDefs.Add(fnIDCatalog, ftInteger);
      mtInterface.FieldDefs.Add(fnIDItemType, ftInteger);
      mtInterface.FieldDefs.Add(fnGuid, ftString, 40);
      mtInterface.FieldDefs.Add(fnName, ftString, 255);
      mtInterface.FieldDefs.Add(fnGuidNetType, ftString, 40);
      mtInterface.FieldDefs.Add(fnIDNetType, ftInteger);
      mtInterface.FieldDefs.Add(fnSortID, ftInteger);
      mtInterface.FieldDefs.Add(fnConstructiveWidth, ftFloat);
      mtInterface.FieldDefs.Add(fnDescription, ftString, 255);
      mtInterface.FieldDefs.Add(fnIsUniversal, ftInteger);
      mtInterface.FieldDefs.Add(fnInterfNormsCount, ftInteger);
      mtInterface.FieldDefs.Add(fnNameNetType, ftString, 255);
      mtInterface.FieldDefs.Add(fnIsModified, ftBoolean);

      mtInterfaceAccordance.FieldDefs.Add(fnID, ftInteger);
      mtInterfaceAccordance.FieldDefs.Add(fnGUID, ftString, 40);
      mtInterfaceAccordance.FieldDefs.Add(fnGUIDInterface, ftString, 40);
      mtInterfaceAccordance.FieldDefs.Add(fnIDInterface, ftInteger);
      mtInterfaceAccordance.FieldDefs.Add(fnInterfComponIsLine, ftInteger);
      mtInterfaceAccordance.FieldDefs.Add(fnGUIDAccordance, ftString, 40);
      mtInterfaceAccordance.FieldDefs.Add(fnIDAccordance, ftInteger);
      mtInterfaceAccordance.FieldDefs.Add(fnAccordComponIsLine, ftInteger);
      mtInterfaceAccordance.FieldDefs.Add(fnName, ftString, 255);
      mtInterfaceAccordance.FieldDefs.Add(fnKolvo, ftInteger);
      mtInterfaceAccordance.FieldDefs.Add(fnIsModified, ftBoolean);

      mtInterfaceNorms.FieldDefs.Add(fnID, ftInteger);
      mtInterfaceNorms.FieldDefs.Add(fnGuid, ftString, 40);
      mtInterfaceNorms.FieldDefs.Add(fnGuidInterface, ftString, 40);
      mtInterfaceNorms.FieldDefs.Add(fnIDInterface, ftInteger);
      mtInterfaceNorms.FieldDefs.Add(fnGuidNBNorm, ftString, 40);
      mtInterfaceNorms.FieldDefs.Add(fnIDNBNorm, ftInteger);
      mtInterfaceNorms.FieldDefs.Add(fnExpense, ftFloat);
      mtInterfaceNorms.FieldDefs.Add(fnIDComponentType, ftInteger);
      mtInterfaceNorms.FieldDefs.Add(fnGuidComponentType, ftString, 40);
      mtInterfaceNorms.FieldDefs.Add(fnInterfaceIsBusy, ftInteger);
      mtInterfaceNorms.FieldDefs.Add(fnKoefLengthForCompl, ftFloat);
      mtInterfaceNorms.FieldDefs.Add(fnCypher, ftString, 200);
      mtInterfaceNorms.FieldDefs.Add(fnName, ftString, 255);
      mtInterfaceNorms.FieldDefs.Add(fnIzm, ftString, 255);
      mtInterfaceNorms.FieldDefs.Add(fnIsNew, ftBoolean);
      mtInterfaceNorms.FieldDefs.Add(fnIsModified, ftBoolean);

      mtInterfaceAccordance.MasterSource := dsInterface;
      mtInterfaceAccordance.MasterFields := fnGUID;
      mtInterfaceAccordance.DetailFields := fnGuidInterface;

      mtInterfaceNorms.MasterSource := dsInterface;
      mtInterfaceNorms.MasterFields := fnGUID;
      mtInterfaceNorms.DetailFields := fnGuidInterface;


      mtNetType.FieldDefs.Add(fnID, ftInteger);
      mtNetType.FieldDefs.Add(fnIDCatalog, ftInteger);
      mtNetType.FieldDefs.Add(fnIDItemType, ftInteger);
      mtNetType.FieldDefs.Add(fnGuid, ftString, 40);
      mtNetType.FieldDefs.Add(fnName, ftString, 255);
      mtNetType.FieldDefs.Add(fnIsModified, ftBoolean);

      mtNorms.FieldDefs.Add(fnID, ftInteger);
      mtNorms.FieldDefs.Add(fnIDCatalog, ftInteger);
      mtNorms.FieldDefs.Add(fnIDItemType, ftInteger);
      mtNorms.FieldDefs.Add(fnGuid, ftString, 40);
      mtNorms.FieldDefs.Add(fnCypher, ftString, 255);
      mtNorms.FieldDefs.Add(fnName, ftString, 255);
      mtNorms.FieldDefs.Add(fnIzm, ftString, 200);
      mtNorms.FieldDefs.Add(fnLaborTime, ftInteger);
      mtNorms.FieldDefs.Add(fnPricePerTime, ftFloat);
      //mtNorms.FieldDefs.Add(fnTimeUOM, ftInteger);
      mtNorms.FieldDefs.Add(fnPrice, ftFloat);
      mtNorms.FieldDefs.Add(fnGuidESmeta, ftString, 40);
      mtNorms.FieldDefs.Add(fnApplyForAllSame, ftBoolean); //24.09.2010
      mtNorms.FieldDefs.Add(fnIsNew, ftBoolean);
      mtNorms.FieldDefs.Add(fnIsModified, ftBoolean);

      mtObjectIcons.FieldDefs.Add(fnID, ftInteger);
      mtObjectIcons.FieldDefs.Add(fnIDCatalog, ftInteger);
      mtObjectIcons.FieldDefs.Add(fnIDItemType, ftInteger);
      mtObjectIcons.FieldDefs.Add(fnGuid, ftString, 40);
      mtObjectIcons.FieldDefs.Add(fnName, ftString, 255);
      mtObjectIcons.FieldDefs.Add(fnProjBlk, ftBlob);
      mtObjectIcons.FieldDefs.Add(fnProjBmp, ftBlob);
      mtObjectIcons.FieldDefs.Add(fnActiveBlk, ftBlob);
      mtObjectIcons.FieldDefs.Add(fnActiveBmp, ftBlob);
      mtObjectIcons.FieldDefs.Add(fnIsModified, ftBoolean);

      mtProducers.FieldDefs.Add(fnID, ftInteger);
      mtProducers.FieldDefs.Add(fnIDCatalog, ftInteger);
      mtProducers.FieldDefs.Add(fnIDItemType, ftInteger);
      mtProducers.FieldDefs.Add(fnGuid, ftString, 40);
      mtProducers.FieldDefs.Add(fnName, ftString, 255);
      mtProducers.FieldDefs.Add(fnDescription, ftString, 255);
      mtProducers.FieldDefs.Add(fnIsModified, ftBoolean);

      mtProperties.FieldDefs.Add(fnID, ftInteger);
      mtProperties.FieldDefs.Add(fnIDCatalog, ftInteger);
      mtProperties.FieldDefs.Add(fnIDItemType, ftInteger);
      mtProperties.FieldDefs.Add(fnGUID, ftString, 40);
      mtProperties.FieldDefs.Add(fnIDDataType, ftInteger);
      mtProperties.FieldDefs.Add(fnName, ftString, 255);
      mtProperties.FieldDefs.Add(fnSysName, ftString, 200);
      mtProperties.FieldDefs.Add(fnIzm, ftString, 200);
      mtProperties.FieldDefs.Add(fnValueReq, ftInteger);
      mtProperties.FieldDefs.Add(fnMinValue, ftFloat);
      mtProperties.FieldDefs.Add(fnMaxValue, ftFloat);
      mtProperties.FieldDefs.Add(fnDefValue, ftString, 255);
      mtProperties.FieldDefs.Add(fnDescription, ftString, 255);
      mtProperties.FieldDefs.Add(fnIsStandart, ftInteger);
      mtProperties.FieldDefs.Add(fnSortID, ftInteger);
      mtProperties.FieldDefs.Add(fnISProject, ftInteger);
      mtProperties.FieldDefs.Add(fnISFolder, ftInteger);
      mtProperties.FieldDefs.Add(fnISList, ftInteger);
      mtProperties.FieldDefs.Add(fnISRoom, ftInteger);
      mtProperties.FieldDefs.Add(fnISSCSLine, ftInteger);
      mtProperties.FieldDefs.Add(fnISSCSConnector, ftInteger);
      mtProperties.FieldDefs.Add(fnISComponLine, ftInteger);
      mtProperties.FieldDefs.Add(fnISComponConn, ftInteger);
      mtProperties.FieldDefs.Add(fnIsForWholeComponent, ftInteger);
      mtProperties.FieldDefs.Add(fnIsValueRelToObj, ftSmallint);
      mtProperties.FieldDefs.Add(fnIsModified, ftBoolean);

      mtPropValRel.FieldDefs.Add(fnID, ftInteger);
      mtPropValRel.FieldDefs.Add(fnGUID, ftString, cnstGUIDLength);
      mtPropValRel.FieldDefs.Add(fnIDProperty, ftInteger);
      mtPropValRel.FieldDefs.Add(fnGuidProperty, ftString, cnstGUIDLength);
      mtPropValRel.FieldDefs.Add(fnPValue, ftString, 255);
      mtPropValRel.FieldDefs.Add(fnMinValue, ftString, 255);
      mtPropValRel.FieldDefs.Add(fnMaxValue, ftString, 255);
      mtPropValRel.FieldDefs.Add(fnIsNew, ftBoolean);
      mtPropValRel.FieldDefs.Add(fnIsModified, ftBoolean);
      mtPropValRel.MasterSource := dsProperties;
      mtPropValRel.MasterFields := fnGuid;
      mtPropValRel.DetailFields := fnGuidProperty;

      mtPropValNormRes.FieldDefs.Add(fnID, ftInteger);
      mtPropValNormRes.FieldDefs.Add(fnGUID, ftString, cnstGUIDLength);
      mtPropValNormRes.FieldDefs.Add(fnIDPropValRel, ftInteger);
      mtPropValNormRes.FieldDefs.Add(fnGuidPropValRel, ftString, cnstGUIDLength);
      mtPropValNormRes.FieldDefs.Add(fnIDNBComponent, ftInteger);
      mtPropValNormRes.FieldDefs.Add(fnGuidNBComponent, ftString, cnstGUIDLength);
      mtPropValNormRes.FieldDefs.Add(fnIDNBRes, ftInteger);
      mtPropValNormRes.FieldDefs.Add(fnGuidNBRes, ftString, cnstGUIDLength);
      mtPropValNormRes.FieldDefs.Add(fnIDNBNorm, ftInteger);
      mtPropValNormRes.FieldDefs.Add(fnGuidNBNorm, ftString, cnstGUIDLength);
      mtPropValNormRes.FieldDefs.Add(fnName, ftString, 255);
      mtPropValNormRes.FieldDefs.Add(fnKolvo, ftFloat);
      mtPropValNormRes.FieldDefs.Add(fnExpenseForLength, ftFloat);
      mtPropValNormRes.FieldDefs.Add(fnCountForPoint, ftFloat);
      mtPropValNormRes.FieldDefs.Add(fnStepOfPoint, ftFloat);
      mtPropValNormRes.FieldDefs.Add(fnIsNew, ftBoolean);
      mtPropValNormRes.FieldDefs.Add(fnIsModified, ftBoolean);

      mtPropValNormRes.MasterSource := dsPropValRel;
      mtPropValNormRes.MasterFields := fnGUID;
      mtPropValNormRes.DetailFields := fnGuidPropValRel;

      mtResources.FieldDefs.Add(fnID, ftInteger);
      mtResources.FieldDefs.Add(fnIDCatalog, ftInteger);
      mtResources.FieldDefs.Add(fnIDItemType, ftInteger);
      mtResources.FieldDefs.Add(fnGuid, ftString, 40);
      mtResources.FieldDefs.Add(fnCypher, ftString, 255);
      mtResources.FieldDefs.Add(fnName, ftString, 255);
      mtResources.FieldDefs.Add(fnIzm, ftString, 200);
      mtResources.FieldDefs.Add(fnPrice, ftFloat);
      mtResources.FieldDefs.Add(fnRType, ftInteger);
      mtResources.FieldDefs.Add(fnApplyForAllSame, ftBoolean);
      mtResources.FieldDefs.Add(fnIsNew, ftBoolean);
      mtResources.FieldDefs.Add(fnIsModified, ftBoolean);

      mtSuppliesKinds.FieldDefs.Add(fnID, ftInteger);
      mtSuppliesKinds.FieldDefs.Add(fnIDCatalog, ftInteger);
      mtSuppliesKinds.FieldDefs.Add(fnIDItemType, ftInteger);
      mtSuppliesKinds.FieldDefs.Add(fnGUID, ftString, 40);
      mtSuppliesKinds.FieldDefs.Add(fnName, ftString, 255);
      mtSuppliesKinds.FieldDefs.Add(fnNameTradUOM, ftString, 255);
      mtSuppliesKinds.FieldDefs.Add(fnIzm, ftString, 200);
      mtSuppliesKinds.FieldDefs.Add(fnIzmTradUOM, ftString, 200);
      mtSuppliesKinds.FieldDefs.Add(fnUnitKolvo, ftFloat);
      mtSuppliesKinds.FieldDefs.Add(fnUnitKolvoTradUOM, ftFloat);
      mtSuppliesKinds.FieldDefs.Add(fnIsModified, ftBoolean);

      mtComponentType.Active := true;
      mtCompTypePropRelation.Active := true;
      mtCurrency.Active := true;
      mtInterface.Active := true;
      mtInterfaceAccordance.Active := true;
      mtInterfaceNorms.Active := true;
      mtNetType.Active := true;
      mtNorms.Active := true;
      mtObjectIcons.Active := true;
      mtProducers.Active := true;
      mtProperties.Active := true;
      mtResources.Active := true;
      mtSuppliesKinds.Active := true;

      MemTableComponTypes := mtComponentType;

      GT_InterfacesIDNetType.Visible := false;
      GT_InterfacesNameNetType.Visible := true;

      //Act_Make.Visible := false;
      Act_Del.Visible := false;

      pcDirectories.OnChange := nil;
      if FItemType <> itProject then
      begin
        tsCurrency.TabVisible := false;
        tsNetTypes.TabVisible := false;
        tsProducers.TabVisible := false;
        tsInterfaces.TabVisible := false;
        tsProperties.TabVisible := false;
        tsComponentTypes.TabVisible := false;
        tsObjectIcons.TabVisible := false;
        tsNBNorms.TabVisible := false;
        tsNBResources.TabVisible := false;
        tsSuppliesKinds.TabVisible := false;
      end
      else
        tsComponentTypes.TabVisible := false;

      tsUnitsOfMeasure.TabVisible := false;
      tsDimensions.TabVisible := false;
      tsCompSpecifications.TabVisible := false;

      //if FItemType = itProject then
      //begin
      //  tsCurrency.TabVisible := true;
      //  tsInterfaces.TabVisible := true;
      //  //pcDirectories.TabStyle := tsCutCorner;
      //  //pcDirectories.TabOrientation := toLeft;
      //end;

      pcDirectories.OnChange := pcDirectoriesChange;
      //tsInterfAccordance.TabVisible := false;



      Panel_Tree.Visible := false;
      Splitter_Tree.Visible := false;
    end;

  FHiddenTabs := TList.Create;
  {$IF Defined(NORMSCS_PE) or Defined(SCS_SPA)}
    FHiddenTabs.Add(tsNBNorms);
    FHiddenTabs.Add(tsInterfaceNorms);

    PageControl_InterfData.ActivePage := tsInterfAccordance;
  {$IFEND}
  FTabsSelectedDir := CreateStringListSorted;

  {$IF Not Defined(FINAL_SCS) or Defined(BASEADM_SCS)}
    GT_ComponentTypesID.Visible := true;
    GT_ObjectIconsID.Visible := true;
    GT_ObjectIconsGUID.Visible := true;

    Act_CopyGUIDToClipboard.Visible := true;
  {$IFEND}

  // Для лайта скрываем ин интерфейсы
  if Not GUseVisibleInterfaces then
    FHiddenTabs.Add(tsInterfaces);

end;


// ##### Удалить форму #####
procedure TF_CaseForm.FormDestroy(Sender: TObject);
begin
  try
    ClearTree(Tree_InterfType);
    ClearComboBox(ComboBox_Value);
    FreeAndNil(FShowedTables);

    if (GForm <> nil) and (TF_Main(GForm).GDBMode = bkProjectManager) then
    begin
      mtComponentType.Active := false;
      mtCompTypePropRelation.Active := false;
      mtCurrency.Active := false;
      mtInterface.Active := false;
      mtInterfaceAccordance.Active := false;
      mtInterfaceNorms.Active := false;
      mtNetType.Active := false;
      mtNorms.Active := false;
      mtObjectIcons.Active := false;
      mtProducers.Active := false;
      mtProperties.Active := false;
      mtResources.Active := false;
      mtSuppliesKinds.Active := false;

      FreeAndNil(mtComponentType);
      FreeAndNil(mtCompTypePropRelation);
      FreeAndNil(mtCurrency);
      FreeAndNil(mtInterface);
      FreeAndNil(mtInterfaceAccordance);
      FreeAndNil(mtInterfaceNorms);
      FreeAndNil(mtNetType);
      FreeAndNil(mtNorms);
      FreeAndNil(mtObjectIcons);
      FreeAndNil(mtProducers);
      FreeAndNil(mtProperties);
      FreeAndNil(mtResources);
      FreeAndNil(mtSuppliesKinds);

      FreeAndNil(dsComponentType);
      FreeAndNil(dsCompTypePropRelation);
      FreeAndNil(dsCurrency);
      FreeAndNil(dsInterface);
      FreeAndNil(dsInterfaceAccordance);
      FreeAndNil(dsInterfaceNorms);
      FreeAndNil(dsNetType);
      FreeAndNil(dsNorms);
      FreeAndNil(dsObjectIcons);
      FreeAndNil(dsProducers);
      FreeAndNil(dsProperties);
      FreeAndNil(dsResources);
      FreeAndNil(dsSuppliesKinds);
    end;
    FreeAndNil(FHiddenTabs);
    FreeAndNil(FTabsSelectedDir);
  except
    on E: Exception do AddExceptionToLogEx('TF_CaseForm.FormDestroy', E.Message);
  end;
end;



// ##### Показать форму #####
procedure TF_CaseForm.FormShow(Sender: TObject);
//var Capt: String;
    //NotifyEvent: TNotifyEvent;
var
  i: Integer;
begin
  for i := 0 to FHiddenTabs.Count - 1 do
    TRzTabSheet(FHiddenTabs[i]).TabVisible := false;

  //if Assigned(FCaseFormParams.ActiveGrid) then
  //  FCaseFormParams.ActiveGrid.SetFocus;

    (*
    //GT_PROPERTIES.OnFocusedRecordChanged := nil;
    //Panel_Tree.Visible := false;
    //Splitter_Tree.Visible := false;

    //*** Отобразить панель с количеством
    if (FFormMode in [fmMake, fmEdit]) and
       (FViewKind in [vkTZ, vkResource, vkNorm]) then
      begin
          if Assigned(Panel_Kolvo) then
            Panel_Kolvo.Visible := true;
      end
    else
      if Assigned(Panel_Kolvo) then
        Panel_Kolvo.Visible := false;

    //*** Отображение кнопок ОК и Отмена
    if FFormMode = fmView then
      begin
          Button_Ok.Visible := false;
          Button_Cancel.Visible := false;
          Button_Exit.Visible := true;
      end
    else
      begin
          Button_Ok.Visible := true;
          Button_Cancel.Visible := true;
          Button_Exit.Visible := false;
      end;
    //if GFormMode = fmView then
      //Panel_OkCancel.Visible := false
    //else
      //Panel_OkCancel.Visible := true;

      
    if GViewKind <> FOldViewKind then
    begin
      FDirTypeInfo := GetDirTypeInfo(GViewKind);
      ClearTreeView(Tree_InterfType);
      AddNodes(nil);
      if Tree_InterfType.Items.Count > 0 then
        Tree_InterfType.Selected := Tree_InterfType.Items[0]
      else
        EnableEditDel;
    end;

    NotifyEvent := nil;
    if GFormMode <> fmView then
      NotifyEvent := Button_OkClick;
    GT_PROPERTIES.OnDblClick := NotifyEvent;
    GT_Interfaces.OnDblClick := NotifyEvent;
    GT_CURRENCY.OnDblClick := NotifyEvent;
    GT_NetType.OnDblClick := NotifyEvent;
    GT_Producers.OnDblClick := NotifyEvent;
    GT_ObjectIcons.OnDblClick := NotifyEvent;
    GT_ComponentTypes.OnDblClick := NotifyEvent;
    GT_NB_Norms.OnDblClick := NotifyEvent;
    GT_NB_Resources.OnDblClick := NotifyEvent;



    //TF_Main(GForm).DM.GItemType := PObjectData(TF_Main(GForm).Tree_Catalog.Selected.Data).ItemType;
    case GViewKind of
        vkProperty : begin        // type Form Mode - fmMake
                       //FillComboBox(ComboBox_Value, F_NormBase.DM.DataSet_COMP_STATE_TYPE, false, 'ID', 'Name');
                       Grid_PROPERTIES.Enabled := true;
                       case GFormMode of
                         fmMake: begin
                                    //capt := 'Добавление свойства';
                                    //F_AddProperty.Caption := 'Добавление свойства';
                                    {ShowHintEdits(true);
                                    Label_Value.Visible := true; }
                                    Panel_Value.Visible := true;
                                    Grid_PROPERTIES.Height := 162;

                                    GValueChanged := false;
                                    GTakeIntoConnect := biFalse;
                                    GTakeIntoJoin := biFalse;
                                    TF_Main(GForm).DM.DataSet_PROPERTIES.First;
                                    ShowValue( TF_Main(GForm).DM.DataSet_PROPERTIES.FN('ID_DAta_TYPE').AsInteger,
                                    TF_Main(GForm).DM.DataSet_PROPERTIES.FN(fnDefValue).AsString);
                                end;
                         fmEdit: begin
                                    //Capt := 'Изменение свойства';
                                    //F_AddProperty.Caption := 'Редактирование свойства';
                                    {ShowHintEdits(true);
                                    Label_Value.Visible := true;}
                                    Panel_Value.Visible := true;
                                    Grid_PROPERTIES.Height := 162;

                                    GValueChanged := True;
                                    SearchRecord(TF_Main(GForm).DM.DataSet_Properties,'ID', GID_Property);
                                    //Edit_Value.Text := TF_Main(GForm).TF_Main(GForm).DM...DataSet_COMP_PROP_RELATION.FN('PValue').AsString;
                                    ShowValue(TF_Main(GForm).DM.DataSet_PROPERTIES.FN('ID_DAta_TYPE').AsInteger,
                                                    GValue);
                                    //*** Если редактируемое свойство явл. стандартным то не дать выбрать на его место другое
                                    if TF_Main(GForm).DM.DataSet_PROPERTIES.FN('isStandart').AsInteger = 1 then
                                      Grid_PROPERTIES.Enabled := false;
                                end;
                         fmView: begin
                                    //Capt := 'Пользовательские свойства';
                                    {ShowHintEdits(false);
                                    Label_Value.Visible := false;}
                                    Panel_Value.Visible := false;
                                    Grid_PROPERTIES.Height := 208;
                                end;
                       end;
                     FormView(vkProperty, 'Свойства объектов',332, 710, true, 'свойство');
                     {GroupBox_Properties.Height := 228;
                     GroupBox_Properties.Width := 705;}
                     Button_Ok.ModalResult := mrNone;
                     //Grid_PROPERTIES.SetFocus;
                     Grid_PROPERTIES.Align := alClient;
                     GroupBox_Properties.Align := alClient;

                     if GTakeIntoConnect = -1 then
                       CheckBox_TakeIntoConnect.Visible := false
                     else
                       CheckBox_TakeIntoConnect.Visible := true;
                     if GTakeIntoConnect = biTrue then
                       CheckBox_TakeIntoConnect.Checked := true
                     else
                       CheckBox_TakeIntoConnect.Checked := false;

                     if GTakeIntoJoin = -1 then
                       CheckBox_TakeIntoJoin.Visible := false
                     else
                       CheckBox_TakeIntoJoin.Visible := true;
                     if GTakeIntoJoin = biTrue then
                       CheckBox_TakeIntoJoin.Checked := true
                     else
                       CheckBox_TakeIntoJoin.Checked := false;

                     if {(TF_Main(GForm).GDBMode = bkProjectManager) and} (GFormMode <> fmView) then
                       begin
                          TF_Main(GForm).DM.SelectProperty(GFormMode, GItemType);
                          case GItemType of
                            itDir:
                              spPropertyType.Caption := 'Свойства папки';
                            itProject:
                              spPropertyType.Caption := 'Свойство проекта';
                            itList:
                              spPropertyType.Caption := 'Свойства листа';
                            itSCSLine:
                              spPropertyType.Caption := 'Свойства линейного объкта';
                            itSCSConnector:
                              spPropertyType.Caption := 'Свойства точечного объкта';
                            itComponLine:
                              spPropertyType.Caption := 'Свойства лин. компоненты';
                            itComponCon:
                              spPropertyType.Caption := 'Свойства точ. компоненты';
                          end;
                          spPropertyItemType.Caption := '';
                       end
                     else if {(TF_Main(GForm).GDBMode = bkProjectManager) and} (GFormMode =fmView) then
                       begin
                           TF_Main(GForm).DM.SelectProperty(GFormMode, GItemType);
                           spPropertyType.Caption := 'Все свойства';
                           ShowPropItemType(TF_Main(GForm).DM.DataSet_PROPERTIES.FN('ID_ITEM_TYPE').AsInteger);
                       end;
                     //GT_PROPERTIES.OnFocusedRecordChanged := GT_PROPERTIESFocusedRecordChanged;
                     end;
        vkInterface :begin
                         if Not Assigned(Tree_InterfType.Selected) then
                           if Tree_InterfType.Items.Count > 0 then
                             Tree_InterfType.Selected := Tree_InterfType.Items[0];

                         Splitter_Tree.Visible := true;
                         FormView(vkInterface, 'Интерфейсы',385, 680, true, 'интерфейс');
                         Button_Ok.ModalResult := mrOK;
                         Grid_Interface.SetFocus;
                         GroupBox_Interfaces.Align := alClient;
                         //Panel_Tree.Visible := true;
                         //Tree_InterfType.OnChange(Self, Tree_InterfType.Selected);
                         Panel_Find.Visible := false;
                         if GFormMode = fmView then
                          begin
                              Tree_InterfType.Items.BeginUpdate;
                              CollapseTree(GForm, ttGuide);
                              Tree_InterfType.TopItem.Expanded := true;
                              Tree_InterfType.Items.EndUpdate;
                          end;
                     end;
        vkInterfaceAccordance:
                    begin
                        FormView(vkInterfaceAccordance, 'Соответствие интерфейсов', 240, 389, true, 'соответствие');
                        Button_Ok.ModalResult := mrOK;
                        //Grid_InterfAccordance_.SetFocus;
                        //GroupBox_InterfaceAccordance.Align := alClient;
                    end;
        vkCurrency  :begin
                         FormView(vkCurrency, 'Валюты',332, 281, true, 'валюту');
                         Button_Ok.ModalResult := mrOK;
                         Grid_Currency.SetFocus;
                         GroupBox_Currency.Align := alClient;
                     end;
        vkNetType   :begin
                         FormView(vkNetType, 'Типы Сетей',332, 281, true, 'Тип Сети');
                         Button_Ok.ModalResult := mrOK;
                         GChangetNetType := false;
                         Grid_NetType.SetFocus;
                         GroupBox_NetType.Align := alClient;
                     end;
        vkProducers:
            begin
                FormView(vkProducers, 'Производители',332, 257, true, 'Производителя');
                Button_Ok.ModalResult := mrOK;
                Grid_Producers.SetFocus;
                GroupBox_Producers.Align := alClient;
            end;
        vkObjectIcons:
            begin
                FormView(vkObjectIcons, 'Условные обозначения',270, 360, true, 'тип условного обозначения');
                //ToolBar_Edit.Parent := Panel_StateType;

                Button_Ok.ModalResult := mrOK;
                GroupBox_ObjectIcons.Align := alClient;
                EnableEditDel;
                //id_CompStateType.Align := alClient
            end;
        vkComponentType:
            begin
                FormView(vkComponentType, 'Типы компонент',332, 633, true, 'Тип компоненты');
                //ToolBar_Edit.Parent := GroupBox_CompTypes;
                //ToolBar_Edit.Visible := false;

                Button_Ok.ModalResult := mrOK;
                Grid_ComponentTypes.SetFocus;
                GroupBox_ComponentTypes.Align := alClient;
            end;
        {vkTZ:
            begin
                FormView(vkTZ, 'Трудозатраты',332, 345, true, 'трудозатрату');
                Button_Ok.ModalResult := mrOK;
                Grid_TZ.SetFocus;
                Grid_TZ.Align := alClient;
                if GFormMode in [fmMake, fmEdit] then
                  if Assigned(Panel_Kolvo) then
                    Panel_Kolvo.Parent := GroupBox_TZ;
            end; }
        vkResource:
            begin
                FormView(vkResource, 'Нормативная база ресурсов',332, 415, true, 'ресурс');
                Button_Ok.ModalResult := mrOK;
                Grid_NB_Resources.SetFocus;
                Grid_NB_Resources.Align := alClient;
                //CurrencyEdit_Kolvo.Properties.DisplayFormat := ',0.00;-,0.00';
                if GFormMode = fmMake then
                  SpinEdit_Kolvo.Value := 1;
                if GFormMode in [fmMake, fmEdit] then
                  if Assigned(Panel_Kolvo) then
                    Panel_Kolvo.Parent := GroupBox_NB_Resources;
                GroupBox_NB_Resources.Align := alClient;
                {if GFormMode = fmEdit then
                  SearchRecord(F_NormBase.DM.DataSet_NB_RESOURCES, 'ID', StrToInt(GValue));}
            end;
        vkNorm:
            begin
                //ToolBar_Edit.Parent := Panel_Norms;

                FormView(vkNorm, 'Нормативная база работ и затрат',433, 665, true, 'норму');
                Button_Ok.ModalResult := mrOK;
                Grid_NB_Norms.SetFocus;

                GroupBox_NB_Norms.Align := alClient;
                //Grid_Resources.Align := alClient;
                //if GFormMode = fmMake then
                //  CurrencyEdit_Kolvo.Value := 1;
                if GFormMode in [fmMake, fmEdit] then
                  if Assigned(Panel_Kolvo) then
                    Panel_Kolvo.Parent := GroupBox_NB_Norms;

                EnableEditDelResourceRel;
            end;
    end;   *)
end;


// ##### Создать #####
procedure TF_CaseForm.Act_MakeExecute(Sender: TObject);
var
  NewName: String;
  NewGUID: string;
  NewID: Integer;

  //FirstID: Integer;
  //Stream: TStream;

  NetType: TNetType;
  IDNetType: Integer;
  IDCurrDirectoryType: Integer;

  NBComponentType: TNBComponentType;
  NBCurrency: TNBCurrency;
  NBInterface: TNBInterface;
  NBNetType: TNBNetType;
  NBNorm: TNBNorm;
  NBNormTmp: TNBNorm;
  NBObjectIcon: TNBObjectIcon;
  NBProducer: TNBProducer;
  NBPropert: TNBProperty;
  NBResource: TNBResource;
  NBResourceTmp: TNBResource;
  NBSuppliesKind: TNBSuppliesKind;

  NewNBCurrency: TNBCurrency;
  CurrMainCurrency: TNBCurrency;
  CurrSecondCurrency: TNBCurrency;
  CurrencyProperNBMain: TNBCurrency;
  NBCurrencyAsCurrMain: TNBCurrency;

  i: Integer;
  LookedGUIDsInterface: TStringList;

  procedure AddInterfByGUID(AGUIDInterface: String);
  var
    i: Integer;
    SprInterface: TNBInterface;
    SprInterfaceAccordance: TNBInterfaceAccordance;
    SprNorm: TNBNorm;
  begin
    if LookedGUIDsInterface.IndexOf(AGUIDInterface) = -1 then
    begin
      LookedGUIDsInterface.Add(AGUIDInterface);
      if Not CheckLocate(mtInterface, fnGuid, AGUIDInterface) then
      begin
        SprInterface := F_NormBase.GSCSBase.NBSpravochnik.GetInterfaceByGUID(AGUIDInterface);
        if SprInterface <> nil then
        begin
          AddInterfaceToMemTable(SprInterface, true);

          //*** Соответствия интерфейсов
          for i := 0 to SprInterface.InterfaceAccordance.Count - 1 do
          begin
            SprInterfaceAccordance := TNBInterfaceAccordance(SprInterface.InterfaceAccordance[i]);
            AddInterfByGUID(SprInterfaceAccordance.GUIDAccordance);
          end;
          //*** Нормы интерфейсов
          for i := 0 to SprInterface.InterfaceNorms.Count - 1 do
            if Not CheckLocate(mtNorms, fnGuid, TNBInterfaceNorm(SprInterface.InterfaceNorms[i]).GuidNBNorm) then
            begin
              SprNorm := F_NormBase.GSCSBase.NBSpravochnik.GetNormByGUID(TNBInterfaceNorm(SprInterface.InterfaceNorms[i]).GuidNBNorm);
              if SprNorm <> nil then
                AddNormToMemTable(SprNorm, True, True);
            end;
        end;
      end;
    end;
  end;
  
begin
  if Not CheckChange then
    Exit; ///// EXIT /////

  NewID := -1;
  NewGUID := '';

  if TF_Main(GForm).GDBMode = bkProjectManager then
  begin
    NewID := TF_Main(GForm).DM.GetTableIDFromGuide(FviewKind, -1, fmEdit, NewGUID);
    if NewGUID = '' then
      Exit; ///// EXIT /////
  end;

  LookedGUIDsInterface := TStringList.Create;
  CurrMainCurrency := nil;
  CurrencyProperNBMain := nil;

  IDCurrDirectoryType := 0;
  if (Tree_InterfType.Selected <> nil) and (Tree_InterfType.Selected.Data <> nil) then
    IDCurrDirectoryType := PObjectData(Tree_InterfType.Selected.Data).ObjectID;
  case FviewKind of
    vkProperty:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        if TF_Main(GForm).CreateFMakeProperty.MakeEditProperty(meMake, GItemType, mtProperties, mtPropValRel, mtPropValNormRes) then
          NewID := TF_Main(GForm).F_MakeProperty.GID;
      end
      else
      if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        NBPropert := F_NormBase.GSCSBase.NBSpravochnik.GetPropertyByGUID(NewGUID);
        if NBPropert <> nil then
          if CheckAddObjectToMTByGUID(cNamePropertyB, NBPropert.PropertyData.GUID, NBPropert.PropertyData.Name, mtProperties) then
            AddPropertyToMemTable(NBPropert, mtProperties, mtPropValRel, mtPropValNormRes, true);
      end;
    vkInterface:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        with TF_Main(GForm).DM.DataSet_INTERFACE do
        begin
          if TF_Main(GForm).CreateFMakeEditInterface.Execute(meMake, mtInterface, mtNetType) then
            NewID := TF_Main(GForm).F_MakeEditInterface.NewID;
        end;
      end
      else
      if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        NBInterface := F_NormBase.GSCSBase.NBSpravochnik.GetInterfaceByGUID(NewGUID);
        if NBInterface <> nil then
          if CheckAddObjectToMTByGUID(cNameInterfaceB, NBInterface.GUID, NBInterface.Name, mtInterface) then
          begin
            AddInterfByGUID(NBInterface.GUID);
            {
            AddInterfaceToMemTable(NBInterface, true);
            //*** Соответствия интерфейсов
            for i := 0 to NBInterface.InterfaceAccordance.Count - 1 do
              AddInterfAccordanceByGUID(TNBInterfaceAccordance(NBInterface.InterfaceAccordance[i]).GUIDAccordance);
            //*** Нормы интерфейсов
            for i := 0 to NBInterface.InterfaceNorms.Count - 1 do
              if Not CheckLocate(mtNorms, fnGuidNB, TNBInterfaceNorm(NBInterface.InterfaceNorms[i]).GuidNBNorm) then
              begin
                NBNorm := F_NormBase.GSCSBase.NBSpravochnik.GetNormByGUID(TNBInterfaceNorm(NBInterface.InterfaceNorms[i]).GuidNBNorm);
                if NBNorm <> nil then
                  AddNormToMemTable(NBNorm, True);
              end;}
          end;
      end;
    vkCurrency:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        if TF_Main(GForm).F_MakeCurrency.Execute(meMake, mtCurrency, mtNorms, mtResources) then
          NewID := TF_Main(GForm).F_MakeCurrency.GID;
      end
      else
      if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        NBCurrency := F_NormBase.GSCSBase.NBSpravochnik.GetCurrencyByGUID(NewGUID);
        if NBCurrency <> nil then
          if CheckAddObjectToMTByGUID(cNameCurrencyB, NBCurrency.Data.GUID, NBCurrency.Data.Name, mtCurrency) then
          begin
            CurrMainCurrency := GetNBCurrencyFromMemTableByMain(ctMain);
            CurrSecondCurrency := GetNBCurrencyFromMemTableByMain(ctSecond);

            NewNBCurrency := TNBCurrency.Create(GForm);
            NewNBCurrency.Assign(NBCurrency);

            //*** Если главная валюта уже есть. то перевести курс добавляемой относительно главной
            if NewNBCurrency.Data.Main = ctMain then
              if CurrMainCurrency <> nil then
              begin
                NBCurrencyAsCurrMain := F_NormBase.GSCSBase.NBSpravochnik.GetCurrencyByGUID(CurrMainCurrency.Data.GUID);
                if NBCurrencyAsCurrMain <> nil then
                  NewNBCurrency.Data.Ratio :=  GetPriceAfterChangeCurrency(NewNBCurrency.Data.Ratio, NewNBCurrency.Data, NBCurrencyAsCurrMain.Data, valEpsilonCurrency);
                NewNBCurrency.Data.Main := ctSimple;
              end;
            if NewNBCurrency.Data.Main = ctSecond then
              NewNBCurrency.Data.Main := ctSimple;

            AddCurrencyToMemTable(NewNBCurrency, true);

            FreeAndNil(NewNBCurrency);
            if CurrMainCurrency <> nil then
              FreeAndNil(CurrMainCurrency);
            if CurrSecondCurrency <> nil then
              FreeAndNil(CurrSecondCurrency);
          end;
      end;
    vkNetType:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        with TF_Main(GForm).DM do
        begin
          NewName := InputForm(GForm, cCaseForm_Msg19_1_1, cCaseForm_Msg19_1_2, '');
          if NewName <> '' then
          begin
            ZeroMemory(@NetType, SizeOf(TNetType));
            NetType.Name := NewName;
            SaveNetType(meMake, @NetType);
            NewID := NetType.ID;

            //DataSet_NET_TYPE.Last;
            //DataSet_NET_TYPE.Append;
            //DataSet_NET_TYPE.FN('Name').AsString := NewName;
            //DataSet_NET_TYPE.Post;
            //NewID := DataSet_NET_TYPE.FN(fnID).AsInteger;
          end;
          GChangetNetType := true;
        end;
      end
      else
      if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        NBNetType := F_NormBase.GSCSBase.NBSpravochnik.GetNetTypeByGUID(NewGUID);
        if NBNetType <> nil then
          if CheckAddObjectToMTByGUID(cNameNetTypeB, NBNetType.GUID, NBNetType.Name, mtNetType) then
            AddNetTypeToMemTable(NBNetType, true);
      end;
    vkProducers:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        if TF_Main(GForm).CreateFMakeEditProducer.Execute(meMake, mtProducers) then
          NewID := TF_Main(GForm).F_MakeEditProducer.NewID;
      end
      else
      if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        NBProducer := F_NormBase.GSCSBase.NBSpravochnik.GetProducerByGUID(NewGUID);
        if NBProducer <> nil then
          if CheckAddObjectToMTByGUID(cNameProducerB, NBProducer.GUID, NBProducer.Name, mtProducers) then
            AddProducerToMemTable(NBProducer, true);
      end;
    vkComponentType:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        if TF_Main(GForm).F_MakeEditComponentType.MakeEditComponentType(fmMake, nil, GetRoomHeight) then
          NewID := TF_Main(GForm).F_MakeEditComponentType.GID;
      end
      else
      if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        NBComponentType := F_NormBase.GSCSBase.NBSpravochnik.GetComponentTypeByGUID(NewGUID);
        if NBComponentType <> nil then
          if CheckAddObjectToMTByGUID(cNameComponentTypeB, NBComponentType.ComponentType.GUID, NBComponentType.ComponentType.Name, mtComponentType) then
          begin
            AddComponentTypeToMemTable(NBComponentType, true);
            //*** вкинуть свойства типов
            if (FSpravochnik <> nil) and (FSpravochnik.OwnerObject <> nil) and (FSpravochnik.OwnerObject is TSCSCatalog) then
              for i := 0 to NBComponentType.Properties.Count - 1 do
                if Not CheckLocate(MemTableProperties, fnSysName, TNBCompTypeProperty(NBComponentType.Properties[i]).PropertyData.GUIDProperty) then
                begin
                  NBPropert := F_NormBase.GSCSBase.NBSpravochnik.GetPropertyByGUID(TNBCompTypeProperty(NBComponentType.Properties[i]).PropertyData.GUIDProperty);

                  //*** Если Лист, то добавить свойство в справочник проекта
                  if (FSpravochnik.OwnerObject is TSCSList) and (TSCSList(FSpravochnik.OwnerObject).ProjectOwner <> nil) then
                  begin
                    AddStringToStringListOnce(
                      TSCSList(FSpravochnik.OwnerObject).ProjectOwner.Spravochnik.NewGUIDsProperties,
                      TNBCompTypeProperty(NBComponentType.Properties[i]).PropertyData.GUIDProperty);
                    TSCSList(FSpravochnik.OwnerObject).ProjectOwner.Spravochnik.DefineDataFromOtherSpravByNewGUIDs(F_NormBase.GSCSBase.NBSpravochnik);

                    // добавить свойство в MemTable как сущ-е
                    if NBPropert <> nil then
                      AddPropertyToMemTable(NBPropert, MemTableProperties, nil, nil, false);
                  end
                  else
                  //*** Если проект, то добавить свойство в MemTable как новое
                  if FSpravochnik.OwnerObject is TSCSProject then
                    if NBPropert <> nil then
                      AddPropertyToMemTable(NBPropert, MemTableProperties, nil, nil, true);
                end; 
          end;
      end;
    vkObjectIcons:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        if TF_Main(GForm).CreateFMakeEditObjectIcons.MakeEdit(fmMake, mtObjectIcons, FDefIconName, FDefFileBmp, FDefFileBlk, oitAll) then
        begin
          NewID := TF_Main(GForm).F_MakeEditObjectIcons.GID;
          FAddedObjectIcon := true;

          //FDefIconName := '';
          //FDefFileBmp := '';
          //FDefFileBlk := '';
        end;
      end
      else 
      if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        NBObjectIcon := F_NormBase.GSCSBase.NBSpravochnik.GetObjectIconByGUID(NewGUID);
        if NBObjectIcon <> nil then
          if CheckAddObjectToMTByGUID(cNameObjectIconB, NBObjectIcon.GUID, NBObjectIcon.Name, mtObjectIcons) then
            AddObjectIconToMemTable(NBObjectIcon, true);
      end;
    vkNorm:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        if F_NormBase.CreateFMakeNorm.Execute(vkNorm, fmMake, mtNorms) then
        begin
          NewID := F_NormBase.F_MakeNorm.GID;
          EnableEditDelResourceRel;
        end;
      end
      else
      if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        NBNorm := F_NormBase.GSCSBase.NBSpravochnik.GetNormByGUID(NewGUID);
        if NBNorm <> nil then
          if CheckAddObjectToMTByGUID(cNameNormB, NBNorm.GUID, NBNorm.Name, mtNorms) then
          begin
            CurrMainCurrency := GetNBCurrencyFromMemTableByMain(ctMain);
            CurrencyProperNBMain := GetNBCurrencyFromMemTableByGUID(TF_Main(GForm).FNormBase.GCurrencyM.GUID);

            NBNormTmp := TNBNorm.Create(NBNorm.ActiveForm);
            NBNormTmp.Assign(NBNorm);
            if (CurrMainCurrency <> nil) and (CurrencyProperNBMain <> nil)then
              NBNormTmp.Price := GetPriceAfterChangeCurrency(NBNormTmp.Price,
                                        CurrencyProperNBMain.Data, CurrMainCurrency.Data);
            AddNormToMemTable(NBNormTmp, true, true);
            FreeAndNil(NBNormTmp);
          end;
      end;
    vkResource:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        if F_NormBase.CreateFMakeNorm.Execute(vkResource, fmMake, mtResources) then
          NewID := F_NormBase.F_MakeNorm.GID;
      end
      else
      if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        NBResource := F_NormBase.GSCSBase.NBSpravochnik.GetResourceByGUID(NewGUID);
        if NBResource <> nil then
          if CheckAddObjectToMTByGUID(cNameResourceB, NBResource.GUID, NBResource.Name, mtResources) then
          begin
            CurrMainCurrency := GetNBCurrencyFromMemTableByMain(ctMain);
            CurrencyProperNBMain := GetNBCurrencyFromMemTableByGUID(TF_Main(GForm).FNormBase.GCurrencyM.GUID);
            
            NBResourceTmp := TNBResource.Create(NBResource.ActiveForm);
            NBResourceTmp.Assign(NBResource);
            if (CurrMainCurrency <> nil) and (CurrencyProperNBMain <> nil)then
              NBResourceTmp.Price := GetPriceAfterChangeCurrency(NBResourceTmp.Price,
                                        CurrencyProperNBMain.Data, CurrMainCurrency.Data);
            AddResourceToMemTable(NBResourceTmp, true, true);
            FreeAndNil(NBResourceTmp);
          end;
      end;
    vkSuppliesKind:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        if F_NormBase.CreateFMakeEditSupplyKind.Execute(meMake, mtSuppliesKinds) then
          NewID := F_NormBase.F_MakeEditSupplyKind.NewID;
      end
      else
      if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        NBSuppliesKind := F_NormBase.GSCSBase.NBSpravochnik.GetSuppliesKindByGUID(NewGUID);
        if NBSuppliesKind <> nil then
          if CheckAddObjectToMTByGUID(cNameSuppliesKindB, NBSuppliesKind.Data.GUID, NBSuppliesKind.Data.Name, mtSuppliesKinds) then
            AddSuppliesKindToMemTable(NBSuppliesKind, true);
      end;
    vkUnitsOfMeasure:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        NewName := InputForm(GForm, cCaseForm_Msg19_2_1, cCaseForm_Msg19_2_2, '', dtString);
        if NewName <> '' then
          if Not TF_Main(GForm).DM.CheckExistsInputString(NewName, stUnitsOfMeasure, true) then
          begin
            TF_Main(GForm).DM.dsetUnitsOfMeasure.Append;
            TF_Main(GForm).DM.dsetUnitsOfMeasure.FN(fnName).AsString := NewName;
            TF_Main(GForm).DM.dsetUnitsOfMeasure.Post;
            NewID := TF_Main(GForm).DM.dsetUnitsOfMeasure.FN(fnID).AsInteger;
          end;
      end;
    vkDimensions:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        NewName := InputForm(GForm, cCaseForm_Msg19_3_1, cCaseForm_Msg19_3_2, '', dtString);
        if NewName <> '' then
          if Not TF_Main(GForm).DM.CheckExistsInputString(NewName, stDimensions, true) then
          begin
            TF_Main(GForm).DM.dsetDimensions.Append;
            TF_Main(GForm).DM.dsetDimensions.FN(fnName).AsString := NewName;
            TF_Main(GForm).DM.dsetDimensions.Post;
            NewID := TF_Main(GForm).DM.dsetDimensions.FN(fnID).AsInteger;
          end;
      end;
    vkCompSpecifications:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        if MakeEditGuideFileExecute(meMake, gftCompSpecification) then
          NewID := F_MakeEditGuideFile.NewID;
      end;
  end;
  if CurrMainCurrency <> nil then
    FreeAndNil(CurrMainCurrency);
  if CurrencyProperNBMain <> nil then
    FreeAndNil(CurrencyProperNBMain);

  if NewID > 0 then
  begin
    if TF_Main(GForm).GDBMode = bkNormBase then
    begin
      TF_Main(GForm).DM.InsertToDirecoryTypeRel(IDCurrDirectoryType, NewID, FDirTypeInfo.MasterFieldName);
      if FDirTypeInfo.DataSet is TpFIBDataSet then
        TpFIBDataSet(FDirTypeInfo.DataSet).FullRefresh;
      TpFIBDataSet(FDirTypeInfo.DataSet).Locate(fnID, NewID, []);
      DefineTextNode(Tree_InterfType.Selected);
    end
    else
    if TF_Main(GForm).GDBMode = bkProjectManager then
      if NewGUID <> '' then
      begin
        FDirTypeInfo.DataSet.Locate(fnGuid, NewGUID, []);
      end;
  end;

  FreeAndNil(LookedGUIDsInterface);
  EnableEditDel;
end;


// ##### Редактировать #####
procedure TF_CaseForm.Act_EditExecute(Sender: TObject);
var
  NewName: String;
  EditName: String;
  ChangedElement: Boolean;
begin
  if Not CheckChange then
    Exit; ///// EXIT /////

  ChangedElement := false;
  case FviewKind of
    vkProperty:
      if TF_Main(GForm).CreateFMakeProperty.MakeEditProperty(meEdit, GItemType, mtProperties, mtPropValRel, mtPropValNormRes) then
        ChangedElement := true;
    vkInterface:
      if TF_Main(GForm).CreateFMakeEditInterface.Execute(meEdit, mtInterface, mtNetType) then
        ChangedElement := true;
    vkInterfaceAccordance:
      if TF_Main(GForm).CreateFMakeEditInterfaceAccordance.MakeEdit(fmEdit, nil, nil) then
        ChangedElement := true;
    vkCurrency:
      begin
        case TF_Main(GForm).GDBMode of
          bkNormBase:
             //25.09.2010 if TF_Main(GForm).DM.DataSet_CURRENCY.FN('Main').AsInteger <> 0 then

             //if TF_Main(GForm).DM.DataSet_CURRENCY.FN(fnMain).AsInteger = ctMain then
             //   MessageDlg(cCaseForm_Msg20_1_1 + #13 +
             //              cCaseForm_Msg20_1_2, mtInformation, [mbOK], 0)
             //else
             begin
               if TF_Main(GForm).F_MakeCurrency.Execute(meEdit, nil, nil, nil) then
                ChangedElement := true;
             end;
          bkProjectManager:
            begin
              if TF_Main(GForm).F_MakeCurrency.Execute(meEdit, mtCurrency, mtNorms, mtResources) then
                ChangedElement := true;
              SetCurrencyBriefToControlsFromMT;
            end;
        end;
      end;
    vkNetType:
      with TF_Main(GForm).DM do
      begin
        NewName := '';
        if TF_Main(GForm).GDBMode = bkNormBase then
          NewName := InputForm(GForm, cCaseForm_Msg20_2_1, cCaseForm_Msg20_2_2, DataSet_NET_TYPE.FN(fnName).AsString)
        else
          NewName := InputForm(GForm, cCaseForm_Msg20_2_1, cCaseForm_Msg20_2_2, mtNetType.FieldByName(fnName).AsString);
        if NewName <> '' then
        begin
          ChangedElement := true;
          if TF_Main(GForm).GDBMode = bkNormBase then
          begin
            DataSet_NET_TYPE.Edit;
            DataSet_NET_TYPE.FN(fnName).AsString := NewName;
            DataSet_NET_TYPE.Post;
          end
          else
          begin
            mtNetType.Edit;
            mtNetType.FieldByName(fnName).AsString := NewName;
            mtNetType.FieldByName(fnIsModified).AsBoolean := true;
            mtNetType.Post;
          end;
        end;
      end;
    vkProducers:
      if TF_Main(GForm).CreateFMakeEditProducer.Execute(meEdit, mtProducers) then
        ChangedElement := true;
    vkComponentType:
        with TF_Main(GForm) do
        begin
          //EditName := DM.DataSet_COMPONENT_TYPES.FN('NAME').AsString;
          {if DM.DataSet_COMPONENT_TYPES.FN('ISSTANDART').AsInteger = 1 then
            begin
                MessageModal(Self.Handle, PChar('Тип компоненты "'+ EditName +'" является стандартным и не может быть редактирован'), 'Редактирование типа компоненты', MB_ICONINFORMATION or MB_OK);
                Exit; ///// EXIT /////
            end; }
          if F_MakeEditComponentType.MakeEditComponentType(fmEdit, mtComponentType, GetRoomHeight) then
            ChangedElement := true;
        end;
    vkObjectIcons:
      if TF_Main(GForm).CreateFMakeEditObjectIcons.MakeEdit(fmEdit, mtObjectIcons) then
        ChangedElement := true;
    vkNorm:
      if TF_Main(GForm).CreateFMakeNorm.Execute(vkNorm, fmEdit, mtNorms) then
        ChangedElement := true;
    vkResource:
      if TF_Main(GForm).CreateFMakeNorm.Execute(vkResource, fmEdit, mtResources) then
        ChangedElement := true;
    //vkTZ:
    //    begin
    //        F_NormBase.F_MakeNorm.Execute(vkTZ, fmEdit);
    //        //F_NormBase.F_MakeNorm.GViewKind := vkTZ;
    //        //F_NormBase.F_MakeNorm.GFormMode := fmEdit;
    //        //F_NormBase.F_MakeNorm.ShowModal;
    //    end;
    vkSuppliesKind:
      if F_NormBase.CreateFMakeEditSupplyKind.Execute(meEdit, mtSuppliesKinds) then
        ChangedElement := true;
    vkUnitsOfMeasure:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        EditName := TF_Main(GForm).DM.dsetUnitsOfMeasure.FN(fnName).AsString;
        NewName := InputForm(GForm, cCaseForm_Msg20_3_1, cCaseForm_Msg19_2_2, EditName, dtString);
        if NewName <> '' then
          if Not TF_Main(GForm).DM.CheckExistsInputString(NewName, stUnitsOfMeasure, true) then
          begin
            TF_Main(GForm).DM.dsetUnitsOfMeasure.Edit;
            TF_Main(GForm).DM.dsetUnitsOfMeasure.FN(fnName).AsString := NewName;
            TF_Main(GForm).DM.dsetUnitsOfMeasure.Post;
          end;
      end;
    vkDimensions:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        EditName := TF_Main(GForm).DM.dsetDimensions.FN(fnName).AsString;
        NewName := InputForm(GForm, cCaseForm_Msg20_4_1, cCaseForm_Msg19_3_2, EditName, dtString);
        if NewName <> '' then
          if Not TF_Main(GForm).DM.CheckExistsInputString(NewName, stDimensions, true) then
          begin
            TF_Main(GForm).DM.dsetDimensions.Edit;
            TF_Main(GForm).DM.dsetDimensions.FN(fnName).AsString := NewName;
            TF_Main(GForm).DM.dsetDimensions.Post;
          end;
      end;
    vkCompSpecifications:
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        if MakeEditGuideFileExecute(meEdit, gftCompSpecification) then
          ChangedElement := true;
      end;
  end;
  
  if ChangedElement then
    FChangedAnySpavElemen := true;
end;


// ##### Удалить #####
procedure TF_CaseForm.Act_DelExecute(Sender: TObject);
var
    i, ID_Property: Integer;
    ID_Interface: Integer;
    //ID_InterfaceType: Integer;
    //ID_Currency : Integer;
    ID_NetType: Integer;
    ID_Producer: Integer;
    ID_ComponentType: Integer;
    ID_ObjectIcon: Integer;
    ID_SuppleisKind: Integer;
    ID_: integer;
    ItemType: TItemType;
    DelInterfKind: TDelInterfKind;

    DelName : String;
    //KolInterfLinks: Integer;

begin
  if Not CheckChange then
    Exit; ///// EXIT /////

  case FViewKind of
    vkProperty:
      begin
        DelName := TF_Main(GForm).DM.DataSet_PROPERTIES.FN('Name').AsString;
        with TF_Main(GForm).DM do
        begin
          ID_Property := DataSet_PROPERTIES.FN('ID').AsInteger;
          ItemType := DataSet_PROPERTIES.FN('ID_ITEM_TYPE').AsInteger;

          //*** Если свойство стандартное то не удалять его
          if DataSet_PROPERTIES.FN('IsStandart').AsInteger = 1 then
          begin
            MessageModal(cNamePropertyB+' "'+ DelName +'" '+cbMessage12, cActNameDeletingProperty, MB_ICONINFORMATION or MB_OK);
            Exit; //// EXIT ////
          end;


          if Not NotDelDataUsedInMemTable('ID_Property', cNameProperty, cNameIt, ID_Property) then
            if CheckNoUseCompData('SELECT COMPONENT.ID, COMPONENT.NAME, isLine FROM COMPONENT, COMP_PROP_RELATION ' +
                                  'WHERE (ID_PROPERTY = '''+IntToStr(ID_Property)+''') and ' +
                                        '(COMPONENT.ID = ID_COMPONENT)',
                                 DelName, meDel, tkProperty, smtDisplay) then
              DataSet_PROPERTIES.Delete;

          //if (ItemType in [itComponLine, itComponCon]) {or (TF_Main(GForm).GDBMode = bkNormBase)} then
          //begin
          //  if Not NotDelDataUsedInMemTable('ID_Property', cNameProperty, cNameIt, ID_Property) then
          //    if CheckNoUseCompData(' SELECT ID, NAME, isLine FROM COMPONENT ' +
          //                        ' WHERE ID in ( SELECT ID_COMPONENT FROM COMP_PROP_RELATION ' +
          //                        ' WHERE ID_PROPERTY = ''' + IntToStr(ID_Property) + ''' ) ',
          //                         DelName, meDel, tkProperty, smtDisplay) then
          //      DataSet_PROPERTIES.Delete;
          //end
          //else
          //if {(TF_Main(GForm).GDBMode = bkProjectManager) and }Not(ItemType in [itComponLine, itComponCon]) then
          //begin
          // SetSQLToQuery(F_ProjMan.DM.scsQ,
          //         ' SELECT ID, NAME, ID_ITEM_TYPE FROM KATALOG ' +
          //         '   WHERE ID in (SELECT ID_CATALOG FROM CATALOG_PROP_RELATION' +
          //         '               WHERE ID_PROPERTY = ''' + IntToStr(ID_Property) + ''' ) ');
          //  if F_ProjMan.DM.scsQ.RecordCount = 0 then
          //  begin
          //    if MessageModal(cQuastDelProperty+' "'+DelName+'"?', Application.Title, MB_ICONQUESTION or MB_YESNO) = IDYES then
          //      DataSet_PROPERTIES.Delete;
          //  end
          //  else
          //    ShowList(F_ProjMan, trkCatalog,  FFormMode, cImpossibleDelProperty+' "' + DataSet_PROPERTIES.FN('Name').AsString +'"'+ #13 +
          //               cIsUsePropertiesInNextObjects+':', false);
          //end;
        end;
      end;
    vkInterface:
      begin
        DelName := TF_Main(GForm).DM.DataSet_INTERFACE.FN('Name').AsString;
        ID_Interface := TF_Main(GForm).DM.DataSet_INTERFACE.FN(fnID).AsInteger;
        with TF_Main(GForm).DM do
        begin
           if Not NotDelDataUsedInMemTable('ID_Interface', cNameInterface, cNameHe, ID_Interface) then
             if CheckNOUseCompData(' SELECT ID, NAME, isLine FROM COMPONENT ' +
                                 ' WHERE ID in ( SELECT ID_COMPONENT FROM INTERFACE_RELATION ' +
                                               ' WHERE ID_INTERFACE = ''' + IntToStr(ID_Interface) + ''' ) ',
                   DelName, meDel, tkInterface, smtDisplay) then
             begin
               TF_Main(GForm).DM.DataSet_INTERFACE.Delete;
             end;
        end;
      end;
    vkInterfaceAccordance:
      with TF_Main(GForm).DM do
      begin
        DelName := GetInterfName(DataSet_InterfAccordance.FN(fnIDInterface).AsInteger);
        DelName := DelName + ' - ' + GetInterfName(DataSet_InterfAccordance.FN('ID_ACCORDANCE').AsInteger);
        if MessageModal(cQuastDelInterfAccordance+' "' + DelName + '" ?',
                        cActNameDeletingInterfAccordance,
                      MB_YESNO or MB_ICONQUESTION) = IDYES then
          DataSet_InterfAccordance.Delete;
      end;
   vkCurrency : begin
                    DelName := TF_Main(GForm).DM.DataSet_CURRENCY.FN('Name').AsString;
                    if TF_Main(GForm).DM.DataSet_CURRENCY.FN('Main').AsInteger <> 0 then
                        MessageModal(cImpossibleDelCurrency+' "'+ DelName + '" ' + cSinceSheUse, cActNameDeletingCurrency,
                                   MB_OK or MB_ICONINFORMATION)
                     else
                       with TF_Main(GForm).DM do
                         begin
                            if GIDNotDel = DataSet_CURRENCY.FN('ID').AsInteger then
                              MessageModal(cImpossibleDelCurrency+' "'+ DelName +'" '+cSinceSheUseInAnotherPrice,
                                 cActNameDeletingCurrency, MB_OK or MB_ICONINFORMATION)
                            else
                              if MessageModal(cQuastDelCurrency+' "' + DelName + '" ?', cActNameDeletingCurrency,
                                            MB_YESNO or MB_ICONQUESTION) = IDYES then
                                TF_Main(GForm).DM.DataSet_CURRENCY.Delete;
                          end;
                    end;

   vkNetType :   with TF_Main(GForm).DM do
                   begin
                       ID_NetType := DataSet_NET_TYPE.FN('ID').AsInteger;
                       DelName := DataSet_NET_TYPE.FN('Name').AsString;
                       if GIDNotDel = ID_NetType then
                         MessageModal(cImpossibleDelNetType+' "'+ DelName +'" '+ cSinceHeUse,
                                 cActNameDeletingNetType, MB_OK or MB_ICONINFORMATION)
                       else
                         if CheckNoUseCompData(' SELECT ID, NAME, isLine FROM COMPONENT ' +
                                             ' WHERE ID_Net_Type = ''' + IntToStr(ID_NetType) + ''' ',
                                             DelName, meDel, tkNetType, smtDisplay) then
                           TF_Main(GForm).DM.DataSet_NET_TYPE.Delete;
                       GChangetNetType := true;
                   end;
   vkProducers :
      with TF_Main(GForm).DM do
        begin
           ID_Producer := DataSet_PRODUCERS.FN('ID').AsInteger;
           DelName := DataSet_PRODUCERS.FN('Name').AsString;
           if GIDNotDel = ID_Producer then
             MessageModal(cImpossibleDelProducer+' "'+ DelName +'" ' + cSinceHeUse,
                          cActNameDeletingProducer, MB_OK or MB_ICONINFORMATION)
           else
             if CheckNoUseCompData(' SELECT ID, NAME, isLine FROM COMPONENT ' +
                                 ' WHERE ID_Producer = ''' + IntToStr(ID_Producer) + ''' ',
                                 DelName, meDel, tkProducers, smtDisplay) then
               TF_Main(GForm).DM.DataSet_PRODUCERS.Delete;
        end;
   vkComponentType:
      with TF_Main(GForm).FNormBase.DM do
      begin
          DelName := DataSet_COMPONENT_TYPES.FN('NAME').AsString;
          ID_ComponentType := DataSet_COMPONENT_TYPES.FN('ID').AsInteger;
          if DataSet_COMPONENT_TYPES.FN('ISSTANDART').AsInteger = 1 then
          begin
            MessageModal(cComponentType+' "'+ DelName +'" '+cbMessage13, cActNameDeletingComponentType, MB_ICONINFORMATION or MB_OK);
            Exit; ///// EXIT /////
          end;

          {if GIDNotDel = ID_ComponentType then
            MessageModal(Self.Handle,PAnsiChar(' Нельзя удалить тип компоненты "'+ DelName +
                                                      '" ' +#13 + 'так как он в данный момент используется.' ),
                    'Удаление типа сети ', MB_OK or MB_ICONINFORMATION)
          else
            if CheckDelCompData(' SELECT ID, NAME, isLine FROM COMPONENT ' +
                                 ' WHERE ID_Component_type = ''' + IntToStr(ID_ComponentType) + ''' ',
                                 DelName, tkComponentTypes) then }
          if CheckNoUsingCurrCompType(meDel, smtDisplay, ID_ComponentType) then
            TF_Main(GForm).DM.DataSet_COMPONENT_TYPES.Delete;
      end;
   vkObjectIcons :
      with TF_Main(GForm).DM do
      begin
          if GT_ObjectIcons.Controller.SelectedRecordCount > 1 then
          begin
            if MessageModal(cQuastDelSelected + '?', cActNameDeleting, MB_ICONQUESTION or MB_YESNO) = IDYES then
            begin
              //GT_ObjectIcons.BeginUpdate;
              //GT_ObjectIcons.ViewData.BeginUpdate;
              GT_ObjectIcons.DataController.BeginUpdate;
              //DataSet_OBJECT_ICONS.DisableControls;
              //DataSet_OBJECT_ICONS.DisableScrollEvents;
              try
                for i := 0 to GT_ObjectIcons.Controller.SelectedRecordCount - 1 do
                begin
                  //if GT_ObjectIcons.ViewData.Records[i].Selected then
                  begin
                    //ID_ObjectIcon := GT_ObjectIcons.ViewData.Records[i].Values[4]; //DataSet_OBJECT_ICONS.FN('ID').AsInteger;
                    //DelName := GT_ObjectIcons.ViewData.Records[i].Values[0]; //DataSet_OBJECT_ICONS.FN('Name').AsString;
                    DataSet_OBJECT_ICONS.Bookmark := GT_ObjectIcons.DataController.GetSelectedBookmark(i);
                    ID_ObjectIcon := DataSet_OBJECT_ICONS.FN('ID').AsInteger;
                    DelName := DataSet_OBJECT_ICONS.FN('Name').AsString;

                    if DataSet_OBJECT_ICONS.Locate('ID', ID_ObjectIcon, []) then
                    begin
                        if CheckNoUseCompData(' SELECT ID, NAME, isLine, ID_OBJECT_ICON FROM COMPONENT ' +
                                              ' WHERE ID_OBJECT_ICON = '''+IntTOstr(ID_ObjectIcon)+''' ',
                                            DelName,  meDel, tkCompStateType, smtDisplay, false) then
                          DataSet_OBJECT_ICONS.Delete;
                    end;
                  end;
                end;
              except
              end;
              //DataSet_OBJECT_ICONS.EnableScrollEvents;
              //DataSet_OBJECT_ICONS.EnableControls;
              GT_ObjectIcons.DataController.EndUpdate;
              //GT_ObjectIcons.ViewData.EndUpdate;
              //GT_ObjectIcons.EndUpdate;
            end;  
          end
          else
          begin
            ID_ObjectIcon := DataSet_OBJECT_ICONS.FN('ID').AsInteger;
            DelName := DataSet_OBJECT_ICONS.FN('Name').AsString;
            //if Not NotDelDataUsedInMemTable('ID_OBJECT_ICON', 'тип условного обозначения', ID_CompStateType) then
            if CheckNoUseCompData(' SELECT ID, NAME, isLine, ID_OBJECT_ICON FROM COMPONENT ' +
                                  ' WHERE ID_OBJECT_ICON = '''+IntTOstr(ID_ObjectIcon)+''' ',
                                   DelName,  meDel, tkCompStateType, smtDisplay, true) then
              DataSet_OBJECT_ICONS.Delete;
          end;
      end;
   vkNorm:
        begin
          if GT_NB_Norms.Controller.SelectedRecordCount > 1 then
          begin
            if MessageModal(cQuastDelSelected + '?', cActNameDeletingNorm, MB_ICONQUESTION or MB_YESNO) = IDYES then
            begin
              GT_NB_Norms.DataController.BeginUpdate;
              try
                for i := 0 to GT_NB_Norms.Controller.SelectedRecordCount - 1 do
                begin
                  ID_ := GT_NB_Norms.Controller.SelectedRecords[0].Values[6];
                  if F_NormBase.DM.DataSet_NB_NORMS.Locate('ID', ID_, []) then
                  begin
                    DelName := F_NormBase.DM.DataSet_NB_NORMS.FN('Name').AsString;
                    //if MessageModal(cQuastDelNorm+' "'+ DelName +'" ?', cActNameDeletingNorm, MB_ICONQUESTION or MB_YESNO) = IDYES then
                    F_NormBase.DM.DataSet_NB_NORMS.Delete;
                  end;
                end;
              except
              end;
              GT_NB_Norms.DataController.EndUpdate;
            end;
          end
          else
          begin
            DelName := F_NormBase.DM.DataSet_NB_NORMS.FN('Name').AsString;
            if MessageModal(cQuastDelNorm+' "'+ DelName +'" ?', cActNameDeletingNorm, MB_ICONQUESTION or MB_YESNO) = IDYES then
              F_NormBase.DM.DataSet_NB_NORMS.Delete;
          end;
        end;
   vkResource:
        begin
          if GT_NB_Resources.Controller.SelectedRecordCount > 1 then
          begin
            if MessageModal(cQuastDelSelected + '?', cActNameDeletingResource, MB_ICONQUESTION or MB_YESNO) = IDYES then
            begin
              GT_NB_Resources.DataController.BeginUpdate;
              try
                for i := 0 to GT_NB_Resources.Controller.SelectedRecordCount - 1 do
                begin
                  ID_ := GT_NB_Resources.Controller.SelectedRecords[0].Values[6];
                  if F_NormBase.DM.DataSet_NB_RESOURCES.Locate('ID', ID_, []) then
                  begin
                    DelName := F_NormBase.DM.DataSet_NB_RESOURCES.FN('Name').AsString;
                    F_NormBase.DM.DataSet_NB_RESOURCES.Delete;
                  end;
                end;
              except
              end;
              GT_NB_Resources.DataController.EndUpdate;
            end;
          end
          else
          begin
            DelName := F_NormBase.DM.DataSet_NB_RESOURCES.FN('Name').AsString;
            if MessageModal(cQuastDelResource+' "'+ DelName +'" ?', cActNameDeletingResource, MB_ICONQUESTION or MB_YESNO) = IDYES then
              F_NormBase.DM.DataSet_NB_RESOURCES.Delete;
          end;
        end;
    vkSuppliesKind:
      with TF_Main(GForm).DM do
        begin
          ID_SuppleisKind := DataSet_SuppliesKinds.FN(fnID).AsInteger;
          DelName := DataSet_SuppliesKinds.FN(fnName).AsString;
          if GIDNotDel = ID_SuppleisKind then
           MessageModal(cImpossibleDelSuppliesKind+' "'+ DelName +'" ' + cSinceHeUse,
                   cActNameDeletingSuppliesKind, MB_OK or MB_ICONINFORMATION)
          else
           if CheckNoUseCompData(' SELECT ID, NAME, isLine FROM COMPONENT ' +
                               ' WHERE ID_SUPPLIES_KIND = ''' + IntToStr(ID_SuppleisKind) + ''' ',
                               DelName, meDel, tkSuppliesKind, smtDisplay) then
             TF_Main(GForm).DM.DataSet_SuppliesKinds.Delete;
        end;
    vkUnitsOfMeasure:
      begin
        DelName := TF_Main(GForm).DM.dsetUnitsOfMeasure.FN(fnName).AsString;
        if MessageModal(cQuastDel +' '+ FCaseFormParams.CaptionForActions +' "'+ DelName +'" ?',
          ApplicationName, MB_ICONQUESTION or MB_YESNO) = IDYES then
          TF_Main(GForm).DM.dsetUnitsOfMeasure.Delete;
      end;
    vkDimensions:
      begin
        DelName := TF_Main(GForm).DM.dsetDimensions.FN(fnName).AsString;
        if MessageModal(cQuastDel +' '+ FCaseFormParams.CaptionForActions +' "'+ DelName +'" ?',
          ApplicationName, MB_ICONQUESTION or MB_YESNO) = IDYES then
          TF_Main(GForm).DM.dsetDimensions.Delete;
      end;
   {vkTZ:
        begin
            DelName := F_NormBase.DM.DataSet_TZ.FN('Name').AsString;
            if MessageModal(Self.Handle, PChar(' Удалить трудозатрату "'+ DelName +'" ?'), 'Удаление трудозатраты', MB_ICONQUESTION or MB_YESNO) = IDYES then
              F_NormBase.DM.DataSet_TZ.Delete;
        end;   }

    vkCompSpecifications:
      begin
        DelName := TF_Main(GForm).DM.dsetCompSpecifications.FN(fnFileName).AsString;
        if MessageModal(cQuastDel +' '+ FCaseFormParams.CaptionForActions +' "'+ DelName +'" ?',
          ApplicationName, MB_ICONQUESTION or MB_YESNO) = IDYES then
          TF_Main(GForm).DM.dsetCompSpecifications.Delete;
      end;
  end;

  DefineTextNode(Tree_InterfType.Selected);
  EnableEditDel;
end;



// ##### Разрешить удаление по ShortCut #####
procedure TF_CaseForm.Act_EnableSCDelExecute(Sender: TObject);
begin
    //Act_Del.ShortCut := ShortCut(VK_DELETE, []);
end;

// ##### Запретить удаление по ShortCut #####
procedure TF_CaseForm.Act_DisableSCDelExecute(Sender: TObject);
begin
    //Act_Del.ShortCut := ShortCut(VK_NONAME, []);
end;



// ##### Выбор типа  #####
procedure TF_CaseForm.ComboBox_PDataTypePropertiesChange(Sender: TObject);
begin
    GValue := '';
    //ChoiceEdit;
end;


// ##### Нажат OK #####
procedure TF_CaseForm.Button_OkClick(Sender: TObject);
var
  ItemTypeName: String;
begin
  if FFormMode = fmEdit then
  begin
    if FViewKind = vkProperty then
    begin
      ItemTypeName := GetItemTypeName(GItemType);
      //*** Не дать выбрать свойство, которое не предназначено для заданого элемента дерева
      if (GItemFieldName <> '') and (ItemTypeName <> '') then
        if TF_Main(GForm).DM.DataSet_Properties.RecordCount > 0 then
          if TF_Main(GForm).DM.DataSet_Properties.FN(GItemFieldName).AsInteger = biFalse then
          begin
            MessageModal(cNamePropertyB+' "'+TF_Main(GForm).DM.DataSet_Properties.FN(fnName).AsString+
                        '" '+cbMessage14+' "'+ItemTypeName+'".', ApplicationName,
                        MB_ICONINFORMATION or MB_OK);
            ModalResult := mrNone;
            Exit; ///// EXIT /////
          end;          
    end;
  end;

    try
      if FFormMode <> fmView then
        begin
            case FViewKind of  {
              vkProperty: begin
                              GValue := GetValueFromEdit(TF_Main(GForm).DM.DataSet_PROPERTIES.FN('ID_DATA_TYPE').AsInteger);
                              GTakeIntoConnect := biFalse;
                              if CheckBox_TakeIntoConnect.Visible then
                                if CheckBox_TakeIntoConnect.Checked then
                                  GTakeIntoConnect := biTrue;

                              GTakeIntoJoin := biFalse;
                              if CheckBox_TakeIntoJoin.Visible then
                                if CheckBox_TakeIntoJoin.Checked then
                                  GTakeIntoJoin := biTrue;

                              if MinMaxReqControl(GValue) then
                                ModalResult := mrOK
                              else
                                ModalResult := mrNone;
                          end;}
             vkInterface: begin
                              TF_Main(GForm).DM.DataSet_INTERFACE.Edit;
                              TF_Main(GForm).DM.DataSet_INTERFACE.FN('Name').AsString := GT_InterfacesNAME.DataBinding.Field.AsString;
                              TF_Main(GForm).DM.DataSet_INTERFACE.Post;
                          end;
              vkNetType:  begin
                              TF_Main(GForm).DM.DataSet_NET_TYPE.Edit;
                              TF_Main(GForm).DM.DataSet_NET_TYPE.FN('Name').AsString := GT_NetTypeNAME.DataBinding.Field.AsString;
                              TF_Main(GForm).DM.DataSet_NET_TYPE.Post;
                          end;
            end;
              //if FViewKind <> vkProperty then
              //  ModalResult := mrOK;
            ModalResult := mrOK;
        end
      else
        ModalResult := mrOK;
    except
    end;
end;

procedure TF_CaseForm.GT_CURRENCYDblClick(Sender: TObject);
begin
    Act_Edit.Execute;
end;

procedure TF_CaseForm.GT_PropertiesFocusedRecordChanged(
  Sender: TcxCustomGridTableView; APrevFocusedRecord,
  AFocusedRecord: TcxCustomGridRecord;
  ANewItemRecordFocusingChanged: Boolean);
begin
  (*
  if TF_Main(GForm).DM.DataSet_PROPERTIES.Active then
  begin
    if (FFormMode <> fmView) and (Visible) and (GroupBox_Properties.Visible) then
      ShowValue(TF_Main(GForm).DM.DataSet_PROPERTIES.FN('ID_DAta_TYPE').AsInteger,
                TF_Main(GForm).DM.DataSet_PROPERTIES.FN(fnDefValue).AsString);
    if {(TF_Main(GForm).GDBMode = bkProjectManager) and }(FFormMode = fmView) then
      begin
          ShowPropItemType(TF_Main(GForm).DM.DataSet_PROPERTIES.FN('ID_ITEM_TYPE').AsInteger);
          {case TF_Main(GForm).DM.DataSet_PROPERTIES.FN('ID_ITEM_TYPE').AsInteger of
              itDir          : Label_PropItemType.Caption := '[ свойство папки ]';
              itList         : Label_PropItemType.caption := '[ свойство листа ]';
              itScsline      : Label_PropItemType.caption := '[ свойство линейного объккта ]';
              itScsconnector : Label_PropItemType.caption := '[ свойство точечного объккта ]';
              itComponLine, itComponCon  : Label_PropItemType.caption := '[ свойство компоненты ]';
              itCommon       : Label_PropItemType.caption := '[ общее свойство ]';
          end; }
      end;
  end;
  *)
end;


procedure TF_CaseForm.GT_PropertiesDEFAULTGetProperties(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;  var AProperties: TcxCustomEditProperties);
//var DisplayValue: Variant;
    //ErrText: TCaption;
    //Error: Boolean;
begin
  if ARecord.Values[3] <> null then
    with TF_Main(GForm).DM do
    begin
      case ARecord.Values[3] of
        dtBoolean:
          AProperties := EditRepositoryCheckBoxItem.Properties;
        //dtFloat  :   AProperties := EditRepositorySpinItem.Properties;
        //dtInteger:   AProperties := EditRepositorySpinItem.Properties;
        //dtDate:
        //  AProperties := EditRepositoryDateItem.Properties;
        dtCompStateType:
          AProperties := EditRepositoryLookupCompSateType.Properties;
        dtColor:
          AProperties := EditRepositoryColorComboBox.Properties;
        dtCableCanalElementType:
          AProperties := EditRepositoryLookupCableCanalElementType.Properties;
        //dtSectionSide:
        //  AProperties := EditRepositoryMaskItemSectionSide.Properties;
      end;
    end;
end;


procedure TF_CaseForm.GT_PropertiesDEFAULTGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
//var
//  CurrFloat: Double;
  var DoSetDisplay: boolean; // IGOR 04/07/2019 --
begin
   // IGOR 04/07/2019 --
  DoSetDisplay := True;
  if ARecord.Values[3] <> null then
  begin
    if (ARecord.Values[3] = dtBoolean) or (ARecord.Values[3] = dtCompStateType)
      or (ARecord.Values[3] = dtColor) or (ARecord.Values[3] = dtCableCanalElementType) then
      DoSetDisplay := False;
  end;
  if DoSetDisplay then
  //
    SetDisplayTextToGridTablePropValue(AText, ARecord, 3, 10, TF_Main(GForm).FUOM);
  {if ARecord.Values[3] <> null then
    case ARecord.Values[3] of
      dtFloat:
        try
          CurrFloat := StrToFloatU(AText);
          if GPropSysNameInUOM.IndexOf(ARecord.Values[10]) <> -1 then
            CurrFloat := RoundCP(FloatInUOM(CurrFloat, umMetr, TF_Main(GForm).FUOM));
          AText := FloatToStr(CurrFloat);
        except
        end;
      dtDate:
        try
          AText := DateToStr(StrToDateU(AText));
        except
        end;
    end;}
end;


procedure TF_CaseForm.GT_PropertiesMIN_VALUEGetProperties(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AProperties: TcxCustomEditProperties);
begin
  if ARecord.Values[3] <> null then
  begin
    with TF_Main(GForm).DM do
      case ARecord.Values[3] of
        dtBoolean:
          AProperties := EditRepositoryCheckBoxItem.Properties;
        dtFloat:
          AProperties := EditRepositoryCurrencyItemForFloat.Properties;
        dtDate:
          AProperties := EditRepositoryDateItem.Properties;
        dtCompStateType:
          AProperties := EditRepositoryLookupCompSateType.Properties;
        dtColor:
          AProperties := EditRepositoryColorComboBox.Properties;
        dtCableCanalElementType:
          AProperties := EditRepositoryLookupCableCanalElementType.Properties;
        //dtSectionSide:
        //  AProperties := EditRepositoryMaskItemSectionSide.Properties;
      end;
  end;
end;

procedure TF_CaseForm.GT_PROPERTIESMAX_VALUEGetProperties(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AProperties: TcxCustomEditProperties);
begin
  //if ARecord.Values[3] <> null then
  //  if ARecord.Values[3] = dtDate then
  //    AProperties := TF_Main(GForm).DM.EditRepositoryDateItem.Properties;

  if ARecord.Values[3] <> null then
    with TF_Main(GForm).DM do
    begin
      case ARecord.Values[3] of
        dtBoolean:
          AProperties := EditRepositoryCheckBoxItem.Properties;
        dtFloat:
          AProperties := EditRepositoryCurrencyItemForFloat.Properties;
        dtDate:
          AProperties := EditRepositoryDateItem.Properties;
        dtCompStateType:
          AProperties := EditRepositoryLookupCompSateType.Properties;
        dtColor:
          AProperties := EditRepositoryColorComboBox.Properties;
        dtCableCanalElementType:
          AProperties := EditRepositoryLookupCableCanalElementType.Properties;
        //dtSectionSide:
        //  AProperties := EditRepositoryMaskItemSectionSide.Properties;
      end;
    end;
end;




{procedure TF_CaseForm.ShowHintEdits(AisShow: Boolean);
begin
    Edit_Value.Visible := AisShow;
    SpinEdit_Value.Visible := AisShow;
    CheckBox_Value.Visible := AisShow;
    DateEdit_Value.Visible := AisShow;
end;}

procedure TF_CaseForm.GT_PropertiesDataTypeGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
    //if AText = '1' then
    //  AText := cCaseForm_Msg21_1
    //else if AText = '2' then
    //  AText := cCaseForm_Msg21_2
    //else if AText = '3' then
    //  AText := cCaseForm_Msg21_3
    //else if AText = '4' then
    //  AText := cCaseForm_Msg21_4
    //else if AText = '5' then
    //  AText := cCaseForm_Msg21_5
    //else if AText = '6' then
    //  AText := cCaseForm_Msg21_6
    //else if AText = IntTostr(dtColor) then
    //  AText := cCaseForm_Msg21_7
    //else if AText = IntTostr(dtCableCanalElementType) then
    //  ATExt := cCaseForm_Msg21_8
    //else if AText = IntToStr(dtDimensions) then
    //  AText := cDimensionsB
    //else if AText = IntToStr(dtConnectionKind) then
    //  AText := cNameConnectionKind
    //else if AText = IntToStr(dtStringList) then
    //  AText := cNameStringListB;
  try
    AText := GetDataTypeName(StrToInt(AText));
  except
  end;
end;

procedure TF_CaseForm.Button_ExitClick(Sender: TObject);
begin
    Close;
end;

procedure TF_CaseForm.FormHide(Sender: TObject);
begin
  // ##### При Следующем вsзове, Отображать эту форму в средине Главной #####
  //F_CaseForm.Position := poMainFormCenter;
  GIDNotDel := -1;
  GIDToLocate := -1;
  GGUIDToLocate := '';

  FDefIconName := '';
  FDefFileBmp := '';
  FDefFileBlk := '';

  if Act_PanelFind.Checked then
    Act_PanelFind.Execute;

  if FViewKind = vkInterface then
    with TF_Main(GForm).DM do
    begin
      if DataSet_InterfaceLookUp.Active then
      begin
        DataSet_InterfaceLookUp.Active := false;
        DataSet_InterfaceLookUp.Active := true;
      end;
    end;

  //if FViewKind in [vkComponentType, vkNorm] then
  //  begin
  //      ToolBar_Edit.Visible := true;
  //      ToolBar_Edit.Parent := Panel_Data;
  //  end;
  if Assigned(Panel_Kolvo) then
    if Panel_Kolvo.Visible = true then
      Panel_Kolvo.Visible := false;

  TF_Main(GForm).RefreshNode;
  //F_NormBase.RefreshNode;
  //F_ProjMan.RefreshNode;
end;


// ##### Разрешить / запретить редактирование и удаление #####
procedure TF_CaseForm.EnableEditDel;
var //TableName: String;
    //RecCount: Integer;
    CanEnable: Boolean;

  procedure EnableED(AEnabled: Boolean);
  begin
      Act_Edit.Enabled := AEnabled;
      Act_Del.Enabled := AEnabled;
      Panel_Value.Enabled := AEnabled;
      {Act_EditObjectIconInCAD.Visible := AEnabled and (FViewKind = vkObjectIcons);
      Act_EditObjectIconInCAD.Enabled := Act_EditObjectIconInCAD.Visible and ExistsOpenedCAD;
      Act_SetIconFromCAD.Visible := AEnabled and (FViewKind = vkObjectIcons) and (TF_Main(GForm).GDBMode = bkNormBase);
      Act_SetIconFromCAD.Enabled := false;
      Act_ShowComponTempateInNB.Visible := AEnabled and (FViewKind = vkComponentType) and (TF_Main(GForm).GDBMode = bkNormBase);
      Act_ShowComponTempateInNB.Enabled := false;}
      Edit_Value.Enabled := AEnabled;
      SpinEdit_Value.Enabled := AEnabled;
      CheckBox_Value.Enabled := AEnabled;
      DateEdit_Value.Enabled := AEnabled;

      if FFormMode <> fmview then
        Button_OK.Enabled := AEnabled
      else
        Button_OK.Enabled := true;
  end;

begin
  CanEnable := false;

  if Assigned(FDirTypeInfo.DataSet) then
    if FDirTypeInfo.DataSet.RecordCount > 0 then
      CanEnable := true;
  EnableED(CanEnable);

  if FViewKind = vkInterface then
    EnableEditDelInterfData;


   { case GViewKind of
      vkCurrency  : TableName := 'CURRENCY';
      vkInterface : TableName := tnInterface;
      vkInterfaceAccordance:
          TableName := 'INTERFACE_ACCORDANCE';
      vkNetType   : TableName := 'NET_TYPE';
      vkProducers : TableName := 'PRODUCERS';
      vkProperty  : TableName := 'PROPERTIES';
      vkObjectIcons:  TableName := 'OBJECT_ICONS';
      vkComponentType:  TableName := 'COMPONENT_TYPES';
      vkResource  : TableName := 'NB_RESOURCES';
      //vkTZ        : TableName := 'TZ';
      vkNorm      : TableName := 'NB_NORMS';
    end;

    with TF_Main(GForm).DM do
      begin
          SetSQLToQuery(scsQSelect, 'SELECT Count(*) As Cnt FROM '+ TableName);
          RecCount := scsQSelect.GetFNAsInteger('Cnt');

          if RecCount = 0 then
            EnableED(false)
          else
            EnableED(true);
      end;

    case GViewKind of
      vkInterface:
          EnableEditDelInterfData;
    end; }
end;

{
procedure TF_CaseForm.EnableEditDelObjectIcons;
begin
    if TF_Main(GForm).DM.DataSet_OBJECT_ICONS.RecordCount = 0 then
      begin
          Act_EditIcon.Enabled := false;
          Act_DelIcon.Enabled := false;
      end
    else
      begin
          Act_EditIcon.Enabled := true;
          Act_DelIcon.Enabled := true;
      end;
end;
}

procedure TF_CaseForm.EnableEditDelResourceRel;
var
  CurrID: Integer;
begin
  CurrID := 0;
  with TF_Main(GForm).DM do
    if TF_Main(GForm).GDBMode = bkNormBase then
    begin
      if DataSet_NB_NORMS.RecordCount = 0 then
        Act_AddResourceRel.Enabled := false
      else
      begin
        CurrID := DataSet_NB_NORMS.FN(fnID).AsInteger;
        Act_AddResourceRel.Enabled := true;
      end;

      //if DataSet_NB_NORM_RESOURCE_REL.RecordCount = 0 then
      if GetDetailRecCount(tnNBNormResourceRel, fnIDNBNorm, CurrID) = 0 then
      begin
        Act_EditResourceRel.Enabled := false;
        Act_DelResourceRel.Enabled := false;
      end
      else
      begin
        Act_EditResourceRel.Enabled := true;
        Act_DelResourceRel.Enabled := true;
      end;
    end;
end;


procedure TF_CaseForm.EnableEditCompTypeProperties;
var
  CurrID: Integer;
  RecordCount: Integer;
begin
  try
    CurrID := 0;
    RecordCount := 0;
    if mtComponentType <> nil then
    begin
      if mtComponentType.Active then
        RecordCount := mtComponentType.RecordCount;
    end
    else
    begin
      RecordCount := F_NormBase.DM.DataSet_COMPONENT_TYPES.RecordCount;
    end;

    if RecordCount = 0 then
      Act_AddCompTypeProperty.Enabled := false
    else
    begin
      if mtComponentType = nil then
        CurrID := TF_Main(GForm).DM.DataSet_COMPONENT_TYPES.FN(fnID).AsInteger;
      Act_AddCompTypeProperty.Enabled := true;
    end;

    //if TF_Main(GForm).DM.DataSet_COMP_TYPE_PROP_RELATION.RecordCount = 0 then
    if TF_Main(GForm).DM.GetDetailRecCount(tnCompTypePropRelation, fnIDComponentType, CurrID, mtCompTypePropRelation) = 0 then
    begin
      Act_EditCompTypeProperty.Enabled := false;
      Act_DelCompTypeProperty.Enabled := false;
    end
    else
    begin
      Act_EditCompTypeProperty.Enabled := true;
      Act_DelCompTypeProperty.Enabled := true;
    end;
  except
    on E: Exception do AddExceptionToLog('TF_CaseForm.EnableEditCompTypeProperties'+ E.Message);
  end;
end;


procedure TF_CaseForm.EnableEditDelInterfData;
var
  CanEnable: Boolean;
  CurrID: Integer;
  RecCount: Integer;
begin
  CanEnable := false;
  with TF_Main(GForm).DM do
  begin
    CurrID := -1;
    RecCount := 0;
    if mtInterface <> nil then
    begin
      if mtInterface.Active then
      begin
        CurrID := mtInterface.FieldByName(fnID).AsInteger;
        RecCount := mtInterface.RecordCount;
      end;
    end
    else
    begin
      CurrID := DataSet_INTERFACE.FN(fnID).AsInteger;
      RecCount := DataSet_INTERFACE.RecordCount;
    end;


    if PageControl_InterfData.ActivePage = tsInterfaceNorms then
      //if DataSet_Interface_Norms.RecordCount > 0 then
      if GetDetailRecCount(tnInterfaceNorms, fnIDInterface, CurrID, mtInterfaceNorms) > 0 then
        CanEnable := true;
    if PageControl_InterfData.ActivePage = tsInterfAccordance then
      //if DataSet_InterfAccordance.RecordCount > 0 then
      if GetDetailRecCount(tnInterfaceAccordance, fnIDInterface, CurrID, mtInterfaceAccordance) > 0 then
        CanEnable := true;


    Act_EditInterfData.Enabled := CanEnable;
    Act_DelInterfData.Enabled := CanEnable;

    if RecCount > 0 then
      Act_AddInterfData.Enabled := true
    else
      Act_AddInterfData.Enabled := false;
  end;
end;


function TF_CaseForm.CheckNoUsingCurrCompType(AMakeEdit: TMakeEdit;
  AMessType: TShowMessageType; AIDCompType: Integer): Boolean;
var TypeName: String;
    ID_ComponentType: Integer;
    strActTo: String;
    strActIng: String;
begin
    Result := false;
    try
      with TF_Main(GForm).DM do
        begin
            TypeName := DataSet_COMPONENT_TYPES.FN('NAME').AsString;
            ID_ComponentType := DataSet_COMPONENT_TYPES.FN('ID').AsInteger;

            case AMakeEdit of
              meEdit:
                  begin
                      strActTo := cCaseForm_Msg22_2_1;
                      strActIng := cCaseForm_Msg22_2_2;
                  end;
              meDel:
                  begin
                      strActTo := cCaseForm_Msg22_2_3;
                      strActIng := cCaseForm_Msg22_2_4;
                  end;
            end;

            if GIDNotDel = ID_ComponentType then
              ShowMessageByType(Self.Handle, AMessType, cCaseForm_Msg22_1+' '+strActTo+' '+cCaseForm_Msg22_3+' "'+ TypeName +
                                                        '" ' +#13 + cCaseForm_Msg22_4,
                      strActIng + ' '+cCaseForm_Msg22_5+' ', MB_OK or MB_ICONINFORMATION)
            else
              if CheckNoUseCompData(' SELECT ID, NAME, isLine FROM COMPONENT ' +
                                   ' WHERE ID_Component_type = ''' + IntToStr(AIDCompType) + ''' ',
                                   TypeName, AMakeEdit, tkComponentTypes, AMessType) then
                Result := true;
        end;
    except
      on E: Exception do AddExceptionToLog('TF_CaseForm.CheckNoUsingCurrCompType: '+E.Message);
    end;
end;


{
// ##### Добавляет/ Изменяет условное обозначение (иконку) #####
procedure TF_CaseForm.AddEditIcon(AMakeEdit: TMakeEdit);
var Stream: TStream;
    BlockStream: TStream;
    IconFName: String;
    BlockFName: String;

    LastNpp: Integer;

    CompStID: ^Integer;
    CompStIDList: TList;
    i: Integer;
begin
    if OpenPictureDialog.Execute then
      begin
          IconFName := OpenPictureDialog.FileName;
          BlockFName := ChangeFileExt(IconFName, '.blk');
          if Not FileExists(BlockFName) then
            begin
                MessageModal(Self.Handle, PChar('Не удалось найти файл "'+ ExtractFileName(BlockFName) +'"'),
                                        'Ошибка', MB_OK or MB_ICONERROR);
                Exit;
            end;

          BlockStream := TFileStream.Create(BlockFName, fmOpenRead);
          BlockStream.Position := 0;
          Stream := TFileStream.Create(IconFName, fmOpenRead);
          Stream.Position := 0;

          try
            with TF_Main(GForm).DM do
              case AMakeEdit of
                meEdit:
                    begin
                        DataSet_OBJECT_ICONS.Edit;
                        DataSet_OBJECT_ICONSICON.LoadFromStream(Stream);
                        DataSet_OBJECT_ICONSBLOCK.LoadFromStream(BlockStream);
                        DataSet_OBJECT_ICONS.Post;
                    end;
                meAdd:
                    begin
                        LastNPP := GetLastNppObjIcon(DataSet_COMP_STATE_TYPE.FN('ID').AsInteger);
                        SetSQLToQuery(scsQ, ' SELECT ID FROM COMP_STATE_TYPE ');
                        CompSTIDList := TList.Create;

                        //*** Составить список ID-в всех типов усл-х обознач-й
                        IntFieldToList(CompSTIDList, scsQ, 'ID');

                        scsQOperat.Close;
                        scsQOperat.SQL.Clear;
                        scsQOperat.SQL.Add('INSERT INTO OBJECT_ICONS(ID_COMP_STATE_TYPE, NPP_ID, ICON, BLOCK) '+
                                             'VALUES(:ID_COMP_STATE_TYPE, :NPP_ID, :ICON, :BLOCK) ');

                        //*** Занести новую иконку во все типы
                        for i := 0 to CompSTIDList.Count - 1 do
                          begin
                              CompStID := CompSTIDList.Items[i];
                              scsQOperat.Close;
                              scsQOperat.ParamByName('ID_COMP_STATE_TYPE').AsInteger := CompStID^;
                              scsQOperat.ParamByName('NPP_ID').AsInteger := LastNPP + 1;
                              scsQOperat.ParamByName('ICON').LoadFromStream(Stream);
                              scsQOperat.ParamByName('BLOCK').LoadFromStream(BlockStream);
                              scsQOperat.ExecQuery;
                          end;

                        DataSet_OBJECT_ICONS.Active := false;
                        DataSet_OBJECT_ICONS.Active := true;
                        DataSet_OBJECT_ICONS.Last;
                    end;
              end;
            finally
                Stream.Free;
                BlockStream.Free;
            end;
      end;
end;}


// ##### Вернет последний номер обозначения типа с AIDCompStateType #####
{function TF_CaseForm.GetLastNppObjIcon(AIDCompStateType: Integer): Integer;
begin
    Result := 0;
    with F_NormBase.DM do
      begin
          SetSQLToQuery(scsQ, ' SELECT MAX(NPP_ID) as max_npp_id FROM OBJECT_ICONS '+
                               ' WHERE  ID_COMP_STATE_TYPE = '''+ IntToStr(AIDCompStateType) +''' ');
          Result := scsQ.GetFNAsInteger('max_npp_id');
      end;
end;}

function TF_CaseForm.GetTabSheetByViewKind(AViewKind: TViewKind): TRzTabSheet;
begin
  Result := nil;
  case AViewKind of
    vkComponentType:
      Result := tsComponentTypes;
    vkCurrency:
      Result := tsCurrency;
    vkInterface:
      Result := tsInterfaces;
    vkNetType:
      Result := tsNetTypes;
    vkNorm:
      Result := tsNBNorms;
    vkObjectIcons:
      Result := tsObjectIcons;
    vkProducers:
      Result := tsProducers;
    vkProperty:
      Result := tsProperties;
    vkResource:
      Result := tsNBResources;
    vkSuppliesKind:
      Result := tsSuppliesKinds;
    vkUnitsOfMeasure:
      Result := tsUnitsOfMeasure;
    vkDimensions:
      Result := tsDimensions;
    vkCompSpecifications:
      Result := tsCompSpecifications;
  end;
end;

function TF_CaseForm.GetViewKindByTabSheet(ATabSheet: TRzTabSheet): TViewKind;
begin
  Result := vkNone;
  if ATabSheet.Name = 'tsCurrency' then
    Result := vkCurrency
  else
  if ATabSheet.Name = 'tsNetTypes' then
    Result := vkNetType
  else
  if ATabSheet.Name = 'tsProducers' then
    Result := vkProducers
  else
  if ATabSheet.Name = 'tsInterfaces' then
    Result := vkInterface
  else
  if ATabSheet.Name = 'tsProperties' then
    Result := vkProperty
  else
  if ATabSheet.Name = 'tsComponentTypes' then
    Result := vkComponentType
  else
  if ATabSheet.Name = 'tsObjectIcons' then
    Result := vkObjectIcons
  else
  if ATabSheet.Name = 'tsNBNorms' then
    Result := vkNorm
  else
  if ATabSheet.Name = 'tsNBResources' then
    Result := vkResource
  else
  if ATabSheet.Name = 'tsSuppliesKinds' then
    Result := VKSuppliesKind
  else
  if ATabSheet.Name = 'tsUnitsOfMeasure' then
    Result := vkUnitsOfMeasure
  else
  if ATabSheet.Name = 'tsDimensions' then
    Result := vkDimensions
  else if ATabSheet.Name = 'tsCompSpecifications' then
    Result := vkCompSpecifications;
end;


constructor TF_CaseForm.Create(AOwner: TComponent; AForm, AParentForm: TForm; AItemType: Integer);
begin
  GForm := AForm;
  FParentForm := AParentForm;
  FItemType := AItemType;
  inherited Create(AOwner);
end;

destructor TF_CaseForm.Destroy;
begin
  GForm := nil;
  inherited;
end;

function TF_CaseForm.AddObjectIconFromFile(AIconName, AFileIconBmp, AFileIconBlk: String): Boolean;
begin
  Result := false;
  FUOM := TF_Main(GForm).FUOM;

  FDefIconName := AIconName;
  FDefFileBmp := AFileIconBmp;
  FDefFileBlk := AFileIconBlk;

  SetPageByViewKind(vkObjectIcons);
  PrepareForm(vkObjectIcons, fmNone);

  Timer_CallMake.Enabled := true;
  ShowModal;

  SaveSelectTabNode;

  Result := FAddedObjectIcon;
end;

function TF_CaseForm.Execute(AViewKind: TViewKind; AFormMode: TFormMode): Boolean;
var
  ActiveTabSheet: TRzTabSheet;
  SavedOnChangePageCotrol: TNotifyEvent;
  // Tolik 28/08/2019 --
  //OldTick, CurrTick: Cardinal;
  OldTick, CurrTick: Dword;
  //
begin
  Result := false;
  FUOM := TF_Main(GForm).FUOM;

  SetPageByViewKind(AViewKind);
  FShowedTables.Clear;

  //*** Поле типа элемента в котором может находится свойство
  GItemFieldName := ItemTypeToIsOwnerFieldName(GItemType);

  PrepareForm(AViewKind, AFormMode);
  if AFormMode = fmMake then
    FDirTypeInfo.DataSet.First
  else
  begin
    if GGUIDToLocate <> '' then
      LocateItemByGUID(GGUIDToLocate);
    if GIDToLocate > 0 then
      LocateItemByID(GIDToLocate);
  end;
  
  if ShowModal = mrOk then
    Result := true;

  OldTick := GetTickCount;

  ProcessMessagesEx;
  Screen.Cursor := crHourGlass;
  try
    SaveSelectTabNode;
    
    with TF_Main(GForm) do
    begin
      if FShowedTables.IndexOf(Ord(vkCurrency)) <> -1 then
        GSCSBase.NBSpravochnik.LoadCurrencies;

      if FShowedTables.IndexOf(Ord(vkComponentType)) <> -1 then
        GSCSBase.NBSpravochnik.LoadComponentTypes;
      if FShowedTables.IndexOf(Ord(vkInterface)) <> -1 then
        GSCSBase.NBSpravochnik.LoadInterfaces;
      if FShowedTables.IndexOf(Ord(vkNetType)) <> -1 then
        GSCSBase.NBSpravochnik.LoadNetTypes;
      if FShowedTables.IndexOf(Ord(vkNorm)) <> -1 then
        GSCSBase.NBSpravochnik.Norms.Clear;
      if FShowedTables.IndexOf(Ord(vkObjectIcons)) <> -1 then
        GSCSBase.NBSpravochnik.ObjectIcons.Clear;
      if FShowedTables.IndexOf(Ord(vkProducers)) <> -1 then
        GSCSBase.NBSpravochnik.LoadProducers;
      if FShowedTables.IndexOf(Ord(vkProperty)) <> -1 then
        GSCSBase.NBSpravochnik.LoadProperties;
      if FShowedTables.IndexOf(Ord(vkResource)) <> -1 then
        GSCSBase.NBSpravochnik.Resources.Clear;
      if FShowedTables.IndexOf(Ord(vkSuppliesKind)) <> -1 then
        GSCSBase.NBSpravochnik.LoadSuppliesKinds;
    end;
  finally
    Screen.Cursor := crDefault;
  end;
  CurrTick := GetTickCount - OldTick;
  CurrTick := GetTickCount - OldTick;
  GItemType := -1;
end;

procedure TF_CaseForm.pcDirectoriesMenuClick(Sender: TObject);
begin
  if TMenuItem(Sender).Tag <> -1 then
    pcDirectories.ActivePageIndex := TMenuItem(Sender).Tag;
end;

procedure TF_CaseForm.PrepareForm(AViewKind: TViewKind; AFormMode: TFormMode);
var
  NotifyEvent: TNotifyEvent;
begin
  FViewKind := AViewKind;
  FFormMode := AFormMode;

  //*** Отобразить панель с количеством
  if (FFormMode in [fmMake, fmEdit]) and
     (FViewKind in [vkTZ, vkResource, vkNorm]) then
  begin
    if Assigned(Panel_Kolvo) then
      Panel_Kolvo.Visible := true;
  end
  else
  if Assigned(Panel_Kolvo) then
    Panel_Kolvo.Visible := false;

  //*** Отображение кнопок ОК и Отмена
  Button_Ok.Visible := false;
  Button_Cancel.Visible := false;
  if FFormMode = fmView then
  begin
    if Parent = nil then //}if Not (Owner is TForm) then
    begin
      Button_Exit.Visible := true;
      ShowHidePageControlTabls(pcDirectories, true, FHiddenTabs);
    end;
  end
  else
  begin
    if FFormMode in [fmMake, fmEdit] then
      Button_Ok.Visible := true;
    Button_Cancel.Visible := true;
    Button_Exit.Visible := false;
    ShowHidePageControlTabls(pcDirectories, false, FHiddenTabs);
  end;


  //*** Настроить TreeView
  if TF_Main(GForm).GDBMode = bkNormBase then
  begin
    if FViewKind <> FOldViewKind then
    begin
      FDirTypeInfo := GetDirTypeInfo(FViewKind);
      ClearTreeView(Tree_InterfType);
      AddNodes(nil);
      if Tree_InterfType.Items.Count > 0 then
        Tree_InterfType.Selected := Tree_InterfType.Items[0]
      else
        EnableEditDel;

      SelectLastTabNode;
    end;
    if Not Assigned(Tree_InterfType.Selected) then
      if Tree_InterfType.Items.Count > 0 then
        Tree_InterfType.Selected := Tree_InterfType.Items[0];
    Panel_Find.Visible := false;
    if FFormMode = fmView then
    begin
      Tree_InterfType.Items.BeginUpdate;
      //CollapseTree(GForm, ttGuide);
      Tree_InterfType.TopItem.Expanded := true;
      Tree_InterfType.Items.EndUpdate;
      if FDirTypeInfo.DataSet.RecordCount > 0 then
       FDirTypeInfo.DataSet.First;
    end;
  end
  else
  begin
    //Act_Make.Enabled := FViewKind <> vkCurrency;
    if FViewKind <> FOldViewKind then
    begin
      FDirTypeInfo := GetDirTypeInfo(FViewKind);
      EnableEditDel;
    end;
  end;

  FCaseFormParams := GetFormParams(FViewKind);

  NotifyEvent := nil;
  if FFormMode <> fmView then
    NotifyEvent := Button_OkClick
  else
    NotifyEvent := Act_EditExecute;
  GT_PROPERTIES.OnDblClick := NotifyEvent;
  GT_Interfaces.OnDblClick := NotifyEvent;
  GT_CURRENCY.OnDblClick := NotifyEvent;
  GT_NetType.OnDblClick := NotifyEvent;
  GT_Producers.OnDblClick := NotifyEvent;
  GT_ObjectIcons.OnDblClick := NotifyEvent;
  GT_ComponentTypes.OnDblClick := NotifyEvent;
  GT_NB_Norms.OnDblClick := NotifyEvent;
  GT_NB_Resources.OnDblClick := NotifyEvent;
  GT_SuppliesKinds.OnDblClick := NotifyEvent;
  GT_UnitsOfMeasure.OnDblClick := NotifyEvent;
  GT_Dimensions.OnDblClick := NotifyEvent;
  GT_CompSpecifications.OnDblClick := NotifyEvent;

  FAddedObjectIcon := false;

  Act_EditObjectIconInCAD.Visible := false;
  Act_Import.Visible := false;


  //TF_Main(GForm).DM.GItemType := PObjectData(TF_Main(GForm).Tree_Catalog.Selected.Data).ItemType;
  case FViewKind of
    vkProperty:
      begin
        if TF_Main(GForm).GDBMode = bkNormBase then
          GT_PROPERTIES.DataController.DataSource := TF_Main(GForm).DM.DataSource_PROPERTIES
        else
        if TF_Main(GForm).GDBMode = bkProjectManager then
          GT_PROPERTIES.DataController.DataSource := dsProperties;

        Grid_PROPERTIES.Enabled := true;
        Panel_Value.Visible := false;
        case FFormMode of
          fmMake:
            begin
              //Panel_Value.Visible := true;
              GValueChanged := false;
              GTakeIntoConnect := biFalse;
              GTakeIntoJoin := biFalse;

              //TF_Main(GForm).DM.DataSet_PROPERTIES.First;
              //ShowValue(TF_Main(GForm).DM.DataSet_PROPERTIES.FN(fnIDDataType).AsInteger,
              //          TF_Main(GForm).DM.DataSet_PROPERTIES.FN(fnDefValue).AsString);
            end;
         fmEdit:
            begin
              //Panel_Value.Visible := true;

              GValueChanged := True;
              //TF_Main(GForm).DM.DataSet_Properties.Locate(fnId, GIDToLocate, []);  //SearchRecord(TF_Main(GForm).DM.DataSet_Properties,'ID', GID_Property);
              //ShowValue(TF_Main(GForm).DM.DataSet_PROPERTIES.FN('ID_DAta_TYPE').AsInteger, GValue);
              //*** Если редактируемое свойство явл. стандартным то не дать выбрать на его место другое

              //if TF_Main(GForm).DM.DataSet_PROPERTIES.FN('isStandart').AsInteger = 1 then
              //  Grid_PROPERTIES.Enabled := false;
            end;
         fmView:
            begin
              Panel_Value.Visible := false;
            end;
        end;
        Button_Ok.ModalResult := mrNone;
               {
        if GTakeIntoConnect = -1 then
         CheckBox_TakeIntoConnect.Visible := false
        else
         CheckBox_TakeIntoConnect.Visible := true;
        if GTakeIntoConnect = biTrue then
         CheckBox_TakeIntoConnect.Checked := true
        else
         CheckBox_TakeIntoConnect.Checked := false;

        if GTakeIntoJoin = -1 then
         CheckBox_TakeIntoJoin.Visible := false
        else
         CheckBox_TakeIntoJoin.Visible := true;
        if GTakeIntoJoin = biTrue then
         CheckBox_TakeIntoJoin.Checked := true
        else
         CheckBox_TakeIntoJoin.Checked := false;
                       }
        if {(TF_Main(GForm).GDBMode = bkProjectManager) and} (FFormMode <> fmView) then
        begin
          //TF_Main(GForm).DM.SelectProperty(FFormMode, GItemType);
          case GItemType of
            itDir:
              spPropertyType.Caption := cCaseForm_Msg23_1;
            itProject:
              spPropertyType.Caption := cCaseForm_Msg23_2;
            itList:
              spPropertyType.Caption := cCaseForm_Msg23_3;
            itSCSLine:
              spPropertyType.Caption := cCaseForm_Msg23_4;
            itSCSConnector:
              spPropertyType.Caption := cCaseForm_Msg23_5;
            itComponLine:
              spPropertyType.Caption := cCaseForm_Msg23_6;
            itComponCon:
              spPropertyType.Caption := cCaseForm_Msg23_7;
          end;
          spPropertyItemType.Caption := '';
        end
        else
        if {(TF_Main(GForm).GDBMode = bkProjectManager) and} (FFormMode =fmView) then
        begin
          //TF_Main(GForm).DM.SelectProperty(FFormMode, GItemType);
          spPropertyType.Caption := cCaseForm_Msg23_8;
          //ShowPropItemType(TF_Main(GForm).DM.DataSet_PROPERTIES.FN('ID_ITEM_TYPE').AsInteger);
        end;
        //GT_PROPERTIES.OnFocusedRecordChanged := GT_PROPERTIESFocusedRecordChanged;
      end;
    vkInterface:
      begin
        if TF_Main(GForm).GDBMode = bkNormBase then
        begin
          GT_Interfaces.DataController.DataSource := TF_Main(GForm).DM.DataSource_INTERFACE;
          GT_InterfAccordance.DataController.DataSource := TF_Main(GForm).DM.DataSource_InterfAccordance;
          GT_InterfaceNorms.DataController.DataSource := TF_Main(GForm).DM.DataSource_Interface_Norms;

          TcxLookupComboBoxProperties(GT_InterfacesIDNetType.Properties).ListSource := TF_Main(GForm).DM.DataSource_NET_TYPE;
          SetSellSQLToDataSet(TF_Main(GForm).DM.DataSet_NET_TYPE, GetSQLByParams(qtSelect, tnNetType, '', nil, fnAll));
          //Tolik
          PageControl_InterfData.ActivePage := tsInterfaceNorms;
        end
        else
        if TF_Main(GForm).GDBMode = bkProjectManager then
        begin
          GT_Interfaces.DataController.DataSource := dsInterface;
          GT_InterfAccordance.DataController.DataSource := dsInterfaceAccordance;
          GT_InterfaceNorms.DataController.DataSource := dsInterfaceNorms;
        end;
        Button_Ok.ModalResult := mrOK;
        PageControl_InterfDataChange(PageControl_InterfData);
      end;
    vkCurrency:
      begin
        if TF_Main(GForm).GDBMode = bkNormBase then
          GT_CURRENCY.DataController.DataSource := TF_Main(GForm).DM.DataSource_CURRENCY
        else
        if TF_Main(GForm).GDBMode = bkProjectManager then
          GT_CURRENCY.DataController.DataSource := dsCurrency;
        Button_Ok.ModalResult := mrOK;
      end;
    vkNetType:
      begin
        if TF_Main(GForm).GDBMode = bkNormBase then
          GT_NetType.DataController.DataSource := TF_Main(GForm).DM.DataSource_NET_TYPE
        else
        if TF_Main(GForm).GDBMode = bkProjectManager then
          GT_NetType.DataController.DataSource := dsNetType;
        TcxLookupComboBoxProperties(GT_InterfacesIDNetType.Properties).ListSource := nil;

        Button_Ok.ModalResult := mrOK;
        GChangetNetType := false;
      end;
    vkProducers:
      begin
        if TF_Main(GForm).GDBMode = bkNormBase then
          GT_Producers.DataController.DataSource := TF_Main(GForm).DM.DataSource_PRODUCERS
        else
        if TF_Main(GForm).GDBMode = bkProjectManager then
          GT_Producers.DataController.DataSource := dsProducers;
        Button_Ok.ModalResult := mrOK;
      end;
    vkObjectIcons:
      begin
        if TF_Main(GForm).GDBMode = bkNormBase then
          GT_ObjectIcons.DataController.DataSource := TF_Main(GForm).DM.DataSource_OBJECT_ICONS
        else
        if TF_Main(GForm).GDBMode = bkProjectManager then
          GT_ObjectIcons.DataController.DataSource := dsObjectIcons;
        Act_EditObjectIconInCAD.Visible := true;
        Button_Ok.ModalResult := mrOK;
      end;
    vkComponentType:
      begin
        if TF_Main(GForm).GDBMode = bkNormBase then
        begin
          GT_ComponentTypes.DataController.DataSource := TF_Main(GForm).DM.DataSource_COMPONENT_TYPES;
          GT_CompTypeProp.DataController.DataSource := TF_Main(GForm).DM.DataSource_COMP_TYPE_PROP_RELATION;
        end
        else
        if TF_Main(GForm).GDBMode = bkProjectManager then
        begin
          GT_ComponentTypes.DataController.DataSource := dsComponentType;
          GT_CompTypeProp.DataController.DataSource := dsCompTypePropRelation;
        end;
        Button_Ok.ModalResult := mrOK;
      end;
    vkResource:
      begin
        if TF_Main(GForm).GDBMode = bkNormBase then
          GT_NB_Resources.DataController.DataSource := TF_Main(GForm).DM.DataSource_NB_RESOURCES
        else
        if TF_Main(GForm).GDBMode = bkProjectManager then
          GT_NB_Resources.DataController.DataSource := dsResources;

        Button_Ok.ModalResult := mrOK;
        if FFormMode = fmMake then
          SpinEdit_Kolvo.Value := 1;
        if FFormMode in [fmMake, fmEdit] then
          if Assigned(Panel_Kolvo) then
            Panel_Kolvo.Parent := GroupBox_NB_Resources;
        Act_Import.Visible := true;
        Act_Import.Caption := cMasterUpdatePrice_Msg1_2;
      end;
    vkNorm:
      begin
        if TF_Main(GForm).GDBMode = bkNormBase then
          GT_NB_Norms.DataController.DataSource := TF_Main(GForm).DM.DataSource_NB_NORMS
        else
        if TF_Main(GForm).GDBMode = bkProjectManager then
        begin
          GT_NB_Norms.DataController.DataSource := nil;
          GT_NB_Norms.DataController.DataSource := dsNorms;
        end;
        //GT_NB_NormResourceRel.DataController.DataSource := TF_Main(GForm).DM.DataSource_NB_NORM_RESOURCE_REL;

        Button_Ok.ModalResult := mrOK;
        if Assigned(Panel_Kolvo) then
          Panel_Kolvo.Visible := false;
        //if FFormMode in [fmMake, fmEdit] then
        //  if Assigned(Panel_Kolvo) then
        //    Panel_Kolvo.Parent := GroupBox_NB_Norms;

        Act_Import.Visible := true;
        Act_Import.Caption := cMasterUpdatePrice_Msg1_3;
        EnableEditDelResourceRel;
      end;
    vkSuppliesKind:
      begin
        if TF_Main(GForm).GDBMode = bkNormBase then
          GT_SuppliesKinds.DataController.DataSource := TF_Main(GForm).DM.DSrc_SuppliesKinds
        else
        if TF_Main(GForm).GDBMode = bkProjectManager then
          GT_SuppliesKinds.DataController.DataSource := dsSuppliesKinds;
        Button_Ok.ModalResult := mrOK;
      end;
//    vkUnitsOfMeasure:
//      begin
//        GT_UnitsOfMeasure.DataController.DataSource := TF_Main(GForm).DM.dsrcUnitsOfMeasure;
//        Button_Ok.ModalResult := mrOK;
//      end;
//    vkDimensions:
//      begin
//        GT_Dimensions.DataController.DataSource := TF_Main(GForm).DM.dsrcDimensions;
//        Button_Ok.ModalResult := mrOK;
//      end;
//    vkCompSpecifications:
//      begin
//        GT_CompSpecifications.DataController.DataSource := TF_Main(GForm).DM.dsrcCompSpecifications;
//        Button_Ok.ModalResult := mrOK;
//      end;
    else
    begin
      if (FCaseFormParams.ActiveGridDBTableView <> nil) and (FDirTypeInfo.DataSrc <> nil) then
      begin
        FCaseFormParams.ActiveGridDBTableView.DataController.DataSource := FDirTypeInfo.DataSrc;
        Button_Ok.ModalResult := mrOK;
      end;
    end;
  end;
  Act_Import.Hint := Act_Import.Caption;
  if TF_Main(GForm).GDBMode = bkProjectManager then
    Act_Import.Visible := false;

  Caption := FCaseFormParams.CaptionForForm;
  SetCaptionToActions(FCaseFormParams.CaptionForActions);
  ToolBar_Edit.Parent := FCaseFormParams.ActiveGroupControl;
  Panel_OkCancel.OnResize(Panel_OkCancel);
  SetUOMToCaptions;

  if FShowedTables.IndexOf(Ord(AViewKind)) = -1 then
    FShowedTables.Add(Ord(AViewKind));
end;

procedure TF_CaseForm.SendFromSpravochnikToMemTables(ASpravochnik: TSpravochnik; ASprElements: TSprElements);
var
  ProjectOwner: TSCSProject;

  SavedMasterSourceCompTypePropRelation: TDataSource;
  SavedMasterSourceInterfacesAccordance: TDataSource;
  SavedMasterSourceInterfacesNorms: TDataSource;
  SavedMasterSourcePropValRel: TDataSource;
  SavedMasterSourcePropValNormRes: TDataSource;

  SavedCompTypePropRelationDetailFields: String;
  SavedInterfacesAccordanceDetailFields: String;
  SavedInterfacesNormsDetailFields: String;
  SavedPropValRelDetailFields: String;
  SavedPropValNormResDetailFields: String;


  i, j, k: Integer;
  NBComponentType: TNBComponentType;
  NBCurrency: TNBCurrency;
  NBInterface: TNBInterface;
  NBInterfaceAccordance: TNBInterfaceAccordance;
  NBInterfaceNorm: TNBInterfaceNorm;
  NBNetType: TNBNetType;
  NBNorm: TNBNorm;
  NBObjectIcon: TNBObjectIcon;
  NBProducer: TNBProducer;
  NBProperty: TNBProperty;
  NBResource: TNBResource;
  NBSuppliesKind: TNBSuppliesKind;

  NormBaseNetType: TNBNetType;
  NormBaseProperty: TNBProperty;
  NormBaseInterfAccordance: TNBInterface;
  NormBaseNorm: TNBNorm;

  CompTypePropCount: Integer;

  LookedCompTypes: TStringList;
  LookedCurrencies: TStringList;
  LookedInterfaces: TStringList;
  LookedInterfaceAccordances: TStringList;
  LookedInterfaceNorms: TStringList;
  LookedNetTypes: TStringList;
  LookedNorms: TStringList;
  LookedObjectIcons: TStringList;
  LookedProducers: TStringList;
  LookedProperties: TStringList;
  LookedPropValRels: TStringList;
  LookedPropValNormRes: TStringList;
  LookedResources: TStringList;
  LookedSuppliesKinds: TStringList;
  //NBNorms: TSCSNorms;
  //SCSNorm: TSCSNorm;
begin
  FChangedAnySpavElemen := false;

  SavedMasterSourceCompTypePropRelation := mtCompTypePropRelation.MasterSource;
  SavedMasterSourceInterfacesAccordance := mtInterfaceAccordance.MasterSource;
  SavedMasterSourceInterfacesNorms := mtInterfaceNorms.MasterSource;
  SavedMasterSourcePropValNormRes := mtPropValNormRes.MasterSource;
  SavedMasterSourcePropValRel := mtPropValRel.MasterSource;
  SavedCompTypePropRelationDetailFields := mtCompTypePropRelation.DetailFields;
  SavedInterfacesAccordanceDetailFields := mtInterfaceAccordance.DetailFields;
  SavedInterfacesNormsDetailFields := mtInterfaceNorms.DetailFields;
  SavedPropValNormResDetailFields := mtPropValNormRes.DetailFields;
  SavedPropValRelDetailFields := mtPropValRel.DetailFields;
  mtCompTypePropRelation.MasterSource := nil;
  mtInterfaceAccordance.MasterSource := nil;
  mtInterfaceNorms.MasterSource := nil;
  mtPropValNormRes.MasterSource := nil;
  mtPropValRel.MasterSource := nil;
  mtCompTypePropRelation.DetailFields := '';
  mtInterfaceAccordance.DetailFields := '';
  mtInterfaceNorms.DetailFields := '';
  mtPropValNormRes.DetailFields := '';
  mtPropValRel.DetailFields := '';

  //mtComponentType.EmptyTable;
  //mtObjectIcons.EmptyTable;

  mtCompTypePropRelation.Active := false;
  mtComponentType.Active := false;
  mtCurrency.Active := false;
  mtInterfaceAccordance.Active := false;
  mtInterfaceNorms.Active := false;
  mtInterface.Active := false;
  mtNetType.Active := false;
  mtNorms.Active := false;
  mtObjectIcons.Active := false;
  mtProducers.Active := false;
  mtPropValNormRes.Active := false;
  mtPropValRel.Active := false;
  mtProperties.Active := false;
  mtResources.Active := false;
  mtSuppliesKinds.Active := false;

  mtInterface.Active := true;
  mtInterfaceAccordance.Active := true;
  mtInterfaceNorms.Active := true;
  mtCurrency.Active := true;
  mtComponentType.Active := true;
  mtCompTypePropRelation.Active := true;
  mtNetType.Active := true;
  mtNorms.Active := true;
  mtObjectIcons.Active := true;
  mtProducers.Active := true;
  mtProperties.Active := true;
  mtPropValRel.Active := true;
  mtPropValNormRes.Active := true;
  mtResources.Active := true;
  mtSuppliesKinds.Active := true;


  mtComponentType.DisableControls;
  mtCompTypePropRelation.DisableControls;
  mtCurrency.DisableControls;
  mtInterface.DisableControls;
  mtInterfaceAccordance.DisableControls;
  mtInterfaceNorms.DisableControls;
  mtNetType.DisableControls;
  mtNorms.DisableControls;
  mtObjectIcons.DisableControls;
  mtProducers.DisableControls;
  mtPropValNormRes.DisableControls;
  mtPropValRel.DisableControls;
  mtProperties.DisableControls;
  mtResources.DisableControls;
  mtSuppliesKinds.DisableControls;

  CompTypePropCount := 0;

  LookedCompTypes := CreateStringListSorted;
  LookedCurrencies := CreateStringListSorted;
  LookedInterfaces := CreateStringListSorted;
  LookedInterfaceAccordances := CreateStringListSorted;
  LookedInterfaceNorms := CreateStringListSorted;
  LookedNetTypes := CreateStringListSorted;
  LookedNorms := CreateStringListSorted;
  LookedObjectIcons := CreateStringListSorted;
  LookedProducers := CreateStringListSorted;
  LookedProperties := CreateStringListSorted;
  LookedPropValRels := CreateStringListSorted;
  LookedPropValNormRes := CreateStringListSorted;
  LookedResources := CreateStringListSorted;
  LookedSuppliesKinds := CreateStringListSorted;

  //NBNorms := TSCSNorms.Create(true);
  try
    FSpravochnik := ASpravochnik;
    FMainSpravochnik := ASpravochnik;
    ProjectOwner := nil;
    if (FSpravochnik.OwnerObject <> nil) and (FSpravochnik.OwnerObject is TSCSCatalog) then
    begin
      ProjectOwner := TSCSCatalog(FSpravochnik.OwnerObject).ProjectOwner;
      if (FSpravochnik.OwnerObject is TSCSList) and (ProjectOwner <> nil) then
        FMainSpravochnik := ProjectOwner.Spravochnik;
    end;

    //*** Типы клмпонент - без проверки на vkAll, чтобы не попала на проект
    if vkComponentType in ASprElements then
    begin
      for i := 0 to ASpravochnik.ComponentTypes.Count - 1 do
      begin
        NBComponentType := TNBComponentType(ASpravochnik.ComponentTypes[i]);
        CompTypePropCount := CompTypePropCount + NBComponentType.Properties.Count;
        if LookedCompTypes.IndexOf(NBComponentType.ComponentType.GUID) = -1 then
        begin
          AddComponentTypeToMemTable(NBComponentType, false);
          LookedCompTypes.Add(NBComponentType.ComponentType.GUID);
        end;
      end;
      mtCompTypePropRelation.First;
    end;
    //*** Валюты
    if (vkCurrency in ASprElements) or (vkAll in ASprElements) then
    begin
      for i := 0 to ASpravochnik.Currencies.Count - 1 do
      begin
        NBCurrency := TNBCurrency(ASpravochnik.Currencies[i]);
        if LookedCurrencies.IndexOf(NBCurrency.Data.GUID) = -1 then
        begin
          AddCurrencyToMemTable(NBCurrency, false);
          LookedCurrencies.Add(NBCurrency.Data.GUID);
        end;
      end;
      mtCurrency.First;
    end;
    //*** Интерфейсы
    if (vkInterface in ASprElements) or (vkAll in ASprElements) then
    begin
      for i := 0 to ASpravochnik.Interfaces.Count - 1 do
      begin
        NBInterface := TNBInterface(ASpravochnik.Interfaces[i]);
        if LookedInterfaces.IndexOf(NBInterface.GUID) = -1 then
        begin
          AddInterfaceToMemTable(NBInterface, false);
          LookedInterfaces.Add(NBInterface.GUID);
        end;
      end;
      mtInterface.First;
    end;
    // типы сетей
    if (vkNetType in ASprElements) or (vkAll in ASprElements) then
    begin
      for i := 0 to ASpravochnik.NetTypes.Count - 1 do
      begin
        NBNetType := TNBNetType(ASpravochnik.NetTypes[i]);
        if LookedNetTypes.IndexOf(NBNetType.GUID) = -1 then
        begin
          AddNetTypeToMemTable(NBNetType, false);
          LookedNetTypes.Add(NBNetType.GUID);
        end;
      end;
      mtNetType.First;
    end;
    // нормы
    if (vkNorm in ASprElements) or (vkAll in ASprElements) then
    begin
      for i := 0 to ASpravochnik.Norms.Count - 1 do
      begin
        NBNorm := TNBNorm(ASpravochnik.Norms[i]);
        if LookedNorms.IndexOf(NBNorm.GUID) = -1 then
        begin
          AddNormToMemTable(NBNorm, false, false);
          LookedNorms.Add(NBNorm.GUID);
        end;
      end;
      mtNorms.First;
    end;
    // условные обозначения
    if (vkObjectIcons in ASprElements) or (vkAll in ASprElements) then
    begin
      for i := 0 to ASpravochnik.ObjectIcons.Count - 1 do
      begin
        NBObjectIcon := TNBObjectIcon(ASpravochnik.ObjectIcons[i]);
        if LookedObjectIcons.IndexOf(NBObjectIcon.GUID) = -1 then
        begin
          AddObjectIconToMemTable(NBObjectIcon, false);
          LookedObjectIcons.Add(NBObjectIcon.GUID);
        end;
      end;
      mtObjectIcons.First;
    end;
    // производители
    if (vkProducers in ASprElements) or (vkAll in ASprElements) then
    begin
      for i := 0 to ASpravochnik.Producers.Count - 1 do
      begin
        NBProducer := TNBProducer(ASpravochnik.Producers[i]);
        if LookedProducers.IndexOf(NBProducer.GUID) = -1 then
        begin
          AddProducerToMemTable(NBProducer, false);
          LookedProducers.Add(NBProducer.GUID);
        end;
      end;
      mtProducers.First;
    end;
    // свойства
    if (vkProperty in ASprElements) or (vkAll in ASprElements) then
    begin
      for i := 0 to ASpravochnik.Properties.Count - 1 do
      begin
        NBProperty := TNBProperty(ASpravochnik.Properties[i]);
        if LookedProperties.IndexOf(NBProperty.PropertyData.GUID) = -1 then
        begin
          AddPropertyToMemTable(NBProperty, mtProperties, mtPropValRel, mtPropValNormRes, false);
          LookedProperties.Add(NBProperty.PropertyData.GUID);
        end;
      end;
      mtProperties.First;
    end;
    // ресурсы
    if (vkResource in ASprElements) or (vkAll in ASprElements) then
    begin
      for i := 0 to ASpravochnik.Resources.Count - 1 do
      begin
        NBResource := TNBResource(ASpravochnik.Resources[i]);
        if LookedResources.IndexOf(NBResource.GUID) = -1 then
        begin
          AddResourceToMemTable(NBResource, false, false);
          LookedResources.Add(NBResource.GUID);
        end;
      end;
      mtResources.First;
    end;
    // виды поставок
    if (vkSuppliesKind in ASprElements) or (vkAll in ASprElements) then
    begin
      for i := 0 to ASpravochnik.SuppliesKinds.Count - 1 do
      begin
        NBSuppliesKind := TNBSuppliesKind(ASpravochnik.SuppliesKinds[i]);
        if LookedSuppliesKinds.IndexOf(NBSuppliesKind.Data.GUID) = -1 then 
        begin
          AddSuppliesKindToMemTable(NBSuppliesKind, false);
          LookedSuppliesKinds.Add(NBSuppliesKind.Data.GUID);
        end;
      end;
      mtSuppliesKinds.First;
    end;

    SetCurrencyBriefToControlsFromMT;
  finally
    //NBNorms.Free;

    mtSuppliesKinds.EnableControls;
    mtResources.EnableControls;
    mtPropValNormRes.EnableControls;
    mtPropValRel.EnableControls;
    mtProperties.EnableControls;
    mtProducers.EnableControls;
    mtObjectIcons.EnableControls;
    mtNorms.EnableControls;
    mtNetType.EnableControls;
    mtInterfaceNorms.EnableControls;
    mtInterfaceAccordance.EnableControls;
    mtInterface.EnableControls;
    mtCurrency.EnableControls;
    mtCompTypePropRelation.EnableControls;
    mtComponentType.EnableControls;

    mtCompTypePropRelation.DetailFields := SavedCompTypePropRelationDetailFields;
    mtPropValRel.DetailFields := SavedPropValRelDetailFields;
    mtPropValNormRes.DetailFields := SavedPropValNormResDetailFields;
    mtInterfaceAccordance.DetailFields := SavedInterfacesAccordanceDetailFields;
    mtInterfaceNorms.DetailFields := SavedInterfacesNormsDetailFields;

    mtCompTypePropRelation.MasterSource := SavedMasterSourceCompTypePropRelation;
    mtPropValRel.MasterSource := SavedMasterSourcePropValRel;
    mtPropValNormRes.MasterSource := SavedMasterSourcePropValNormRes;
    mtInterfaceAccordance.MasterSource := SavedMasterSourceInterfacesAccordance;
    mtInterfaceNorms.MasterSource := SavedMasterSourceInterfacesNorms;

    FreeAndNil(LookedCompTypes);
    FreeAndNil(LookedCurrencies);
    FreeAndNil(LookedInterfaces);
    FreeAndNil(LookedInterfaceAccordances);
    FreeAndNil(LookedInterfaceNorms);
    FreeAndNil(LookedNetTypes);
    FreeAndNil(LookedNorms);
    FreeAndNil(LookedObjectIcons);
    FreeAndNil(LookedProducers);
    FreeAndNil(LookedProperties);
    FreeAndNil(LookedPropValRels);
    FreeAndNil(LookedPropValNormRes);
    FreeAndNil(LookedResources);
    FreeAndNil(LookedSuppliesKinds);

    EnableEditCompTypeProperties;
    EnableEditDelInterfData;
  end;
end;

procedure TF_CaseForm.SendFromMemTablesToSpravochnik(ASpravochnik: TSpravochnik; ASprElements: TSprElements;
  AChangedInterfNorm: PBoolean);
var
  //SavedMasterSourceCompTypePropRelation: TDataSource;
  //SavedMasterSourceInterfacesNorms: TDataSource;

  NBComponentType: TNBComponentType;
  NBCompTypePropRel: TNBCompTypeProperty;
  NBCurrency: TNBCurrency;
  NBInterface: TNBInterface;
  NBInterfaceAccordance: TNBInterfaceAccordance;
  NBInterfaceNorm: TNBInterfaceNorm;
  NBNetType: TNBNetType;
  NBNorm: TNBNorm;
  NBObjectIcon: TNBObjectIcon;
  NBProducer: TNBProducer;
  NBProperty: TNBProperty;
  NBPropValRel: TNBPropValRel;
  NBPropValNormRes: TNBPropValNormRes;
  NBResource: TNBResource;
  NBSuppliesKind: TNBSuppliesKind;

  CurrGUIDCurrency: String;
  CurrGUIDCComponentType: String;
  CurrGUIDCInterface: String;
  CurrGUIDCNetType: String;
  CurrGUIDCNorm: String;
  CurrGUIDCObjectIcon: String;
  CurrGUIDCProducer: String;
  CurrGUIDCProperty: String;
  CurrGUIDCResource: String;
  CurrGUIDCSuppliesKind: String;

  SCSCatalog: TSCSCatalog;
  SCSComponent: TSCSComponent;
  SCSResource: TSCSResourceRel;
  SCSNorm: TSCSNorm;
  i, j, k: Integer;

  CompTypePropCount: Integer;
  //CompTypesGuids: TStringList;
  //CompTypePropsGuids: TStringList;
begin
  //SavedMasterSourceCompTypePropRelation := mtCompTypePropRelation.MasterSource;
  //SavedMasterSourceInterfacesNorms := mtInterfaceNorms.MasterSource;
  //mtCompTypePropRelation.MasterSource := nil;
  //mtInterfaceNorms.MasterSource := nil;

  //mtComponentType.DisableControls;
  //mtCompTypePropRelation.DisableControls;
  //mtInterface.DisableControls;
  //mtInterfaceNorms.DisableControls;

  GT_ComponentTypes.BeginUpdate;
  GT_CompTypeProp.BeginUpdate;
  mtCurrency.DisableControls;
  GT_Interfaces.BeginUpdate;
  GT_InterfAccordance.BeginUpdate;
  GT_InterfaceNorms.BeginUpdate;
  mtNetType.DisableControls;
  mtNorms.DisableControls;
  mtObjectIcons.DisableControls;
  mtProducers.DisableControls;
  //mtProperties.DisableControls;
  mtResources.DisableControls;
  mtSuppliesKinds.DisableControls;
  try
    if AChangedInterfNorm <> nil then
      AChangedInterfNorm^ := false;

    ASpravochnik.LastCurrency := nil;
    ASpravochnik.LastComponentType := nil;
    ASpravochnik.LastInterface := nil;
    ASpravochnik.LastNetType := nil;
    ASpravochnik.LastNorm := nil;
    ASpravochnik.LastObjectIcon := nil;
    ASpravochnik.LastProducer := nil;
    ASpravochnik.LastProperty := nil;
    ASpravochnik.LastResource := nil;
    ASpravochnik.LastSuppliesKind := nil;

    CompTypePropCount := 0;
    //CompTypesGuids := TStringList.Create;
    //CompTypePropsGuids := TStringList.Create;

    //*** Типы компонент - без проверки на vkAll, чтобы не попала на проект
    if vkComponentType in ASprElements then
    begin
      ASpravochnik.ClearComponentTypes;
      CurrGUIDCComponentType := '';
      if mtComponentType.RecordCount > 0 then
        CurrGUIDCComponentType := mtComponentType.FieldByName(fnGuid).AsString;

      mtComponentType.First;
      while Not mtComponentType.Eof do
      begin
        NBComponentType := TNBComponentType.Create(GForm);

        NBComponentType.ComponentType.ID := mtComponentType.FieldByName(fnID).AsInteger;
        NBComponentType.IDCatalog := mtComponentType.FieldByName(fnIDCatalog).AsInteger;
        NBComponentType.CatalogItemType := mtComponentType.FieldByName(fnIDItemType).AsInteger;
        NBComponentType.ComponentType.GUID := mtComponentType.FieldByName(fnGuid).AsString;
        NBComponentType.ComponentType.Name := mtComponentType.FieldByName(fnName).AsString;
        NBComponentType.ComponentType.NamePlural := mtComponentType.FieldByName(fnNamePlural).AsString;
        NBComponentType.ComponentType.SysName := mtComponentType.FieldByName(fnSysName).AsString;
        NBComponentType.ComponentType.MarkMask := mtComponentType.FieldByName(fnMarkMask).AsString;
        NBComponentType.ComponentType.PortKind := mtComponentType.FieldByName(fnPortKind).AsInteger;
        NBComponentType.ComponentType.ActiveState := mtComponentType.FieldByName(fnActiveState).AsInteger;
        NBComponentType.ComponentType.IDDesignIcon := mtComponentType.FieldByName(fnIDDesignIcon).AsInteger;
        NBComponentType.ComponentType.GUIDDesignIcon := mtComponentType.FieldByName(fnGUIDDesignIcon).AsString;
        NBComponentType.ComponentType.IsLine := mtComponentType.FieldByName(fnIsLine).AsInteger;
        NBComponentType.ComponentType.IsStandart := mtComponentType.FieldByName(fnisStandart).AsInteger;
        NBComponentType.ComponentType.CoordZ := mtComponentType.FieldByName(fnCoordZ).AsFloat;
        NBComponentType.ComponentType.ComponentIndex := mtComponentType.FieldByName(fnComponentIndex).AsInteger - 1;
        NBComponentType.ComponentType.CanUseAsPoint := mtComponentType.FieldByName(fnCanUseAsPoint).AsInteger;
        NBComponentType.IsModified := mtComponentType.FieldByName(fnIsModified).AsBoolean;

        ASpravochnik.AddComponentType(NBComponentType);
        if CurrGUIDCComponentType = NBComponentType.ComponentType.GUID then
          ASpravochnik.LastComponentType := NBComponentType;

        //if CompTypesGuids.IndexOf(NBComponentType.ComponentType.GUID) <> -1 then
        //  EmptyProcedure;
        //CompTypesGuids.Add(NBComponentType.ComponentType.GUID);

        mtCompTypePropRelation.First;
        while Not mtCompTypePropRelation.Eof do
        begin
          if mtCompTypePropRelation.FieldByName(fnGuidComponentType).AsString = NBComponentType.ComponentType.GUID then
          begin
            NBCompTypePropRel := TNBCompTypeProperty.Create(GForm);

            NBCompTypePropRel.GuidComponentType := mtCompTypePropRelation.FieldByName(fnGuidComponentType).AsString;
            NBCompTypePropRel.PropertyData.Guid := mtCompTypePropRelation.FieldByName(fnGUID).AsString;
            NBCompTypePropRel.PropertyData.ID := mtCompTypePropRelation.FieldByName(fnID).AsInteger;
            NBCompTypePropRel.PropertyData.IDMaster := mtCompTypePropRelation.FieldByName(fnIDComponentType).AsInteger;
            NBCompTypePropRel.PropertyData.ID_Property := mtCompTypePropRelation.FieldByName(fnIDProperty).AsInteger;
            NBCompTypePropRel.PropertyData.GUIDProperty := mtCompTypePropRelation.FieldByName(fnGuidProperty).AsString;
            NBCompTypePropRel.PropertyData.TakeIntoConnect := mtCompTypePropRelation.FieldByName(fnTakeIntoConnect).AsInteger;
            NBCompTypePropRel.PropertyData.TakeIntoJoin := mtCompTypePropRelation.FieldByName(fnTakeIntoJoin).AsInteger;
            NBCompTypePropRel.PropertyData.Value := mtCompTypePropRelation.FieldByName(fnPValue).AsString;
            NBCompTypePropRel.PropertyData.IsDefault := mtCompTypePropRelation.FieldByName(fnisStandart).AsInteger;
            NBCompTypePropRel.IsModified := mtCompTypePropRelation.FieldByName(fnIsModified).AsBoolean;

            NBComponentType.AddProperty(NBCompTypePropRel);
            CompTypePropCount := CompTypePropCount + 1;

            //if CompTypePropsGuids.IndexOf(NBCompTypePropRel.PropertyData.GUID) <> -1 then
            //  EmptyProcedure;
            //CompTypePropsGuids.Add(NBCompTypePropRel.PropertyData.GUID);
          end
          else
            EmptyProcedure;

          mtCompTypePropRelation.Next;
        end;
        NBComponentType.PropsCount := NBComponentType.Properties.Count;

        mtComponentType.Next;
      end;
    end;


    //*** Валюты
    if (vkCurrency in ASprElements) or (vkAll in ASprElements) then
    begin
      ASpravochnik.ClearCurrencies;
      CurrGUIDCurrency := '';
      if mtCurrency.RecordCount > 0 then
        CurrGUIDCurrency := mtCurrency.FieldByName(fnGuid).AsString;

      mtCurrency.First;
      while Not mtCurrency.Eof do
      begin
        //NBCurrency := TNBCurrency.Create(GForm);
//
//        NBCurrency.Data.ID := mtCurrency.FieldByName(fnID).AsInteger;
//        NBCurrency.IDCatalog := mtCurrency.FieldByName(fnIDCatalog).AsInteger;
//        NBCurrency.CatalogItemType := mtCurrency.FieldByName(fnIDItemType).AsInteger;
//        NBCurrency.Data.GUID := mtCurrency.FieldByName(fnGuid).AsString;
//        NBCurrency.Data.Name := mtCurrency.FieldByName(fnName).AsString;
//        NBCurrency.Data.NameBrief := mtCurrency.FieldByName(fnNameBrief).AsString;
//        NBCurrency.Data.Kolvo := mtCurrency.FieldByName(fnKolvo).AsInteger;
//        NBCurrency.Data.Ratio := mtCurrency.FieldByName(fnRatio).AsFloat;
//        NBCurrency.Data.Main := mtCurrency.FieldByName(fnMain).AsInteger;
//        NBCurrency.SavedMain := mtCurrency.FieldByName(fnSavedMain).AsInteger;
//        // := mtCurrency.FieldByName(fnSortID).AsInteger;
//        NBCurrency.Data.IsCountry := mtCurrency.FieldByName(fnIsCountry).AsInteger;
//        NBCurrency.IsModified := mtCurrency.FieldByName(fnIsModified).AsBoolean;

        NBCurrency := GetNBCurrencyFromMemTable;

        ASpravochnik.AddCurrency(NBCurrency);
        if CurrGUIDCurrency = NBCurrency.Data.GUID then
          ASpravochnik.LastCurrency := NBCurrency;
        mtCurrency.Next;
      end;
    end;

    //*** Интерфейсы
    if (vkInterface in ASprElements) or (vkAll in ASprElements) then
    begin
      ASpravochnik.ClearInterfaces;
      CurrGUIDCInterface := '';
      if mtInterface.RecordCount > 0 then
        CurrGUIDCInterface := mtInterface.FieldByName(fnGuid).AsString;

      mtInterface.First;
      while Not mtInterface.Eof do
      begin
        NBInterface := TNBInterface.Create(GForm);

        NBInterface.ID := mtInterface.FieldByName(fnID).AsInteger;
        NBInterface.IDCatalog := mtInterface.FieldByName(fnIDCatalog).AsInteger;
        NBInterface.CatalogItemType := mtInterface.FieldByName(fnIDItemType).AsInteger;
        NBInterface.GUID := mtInterface.FieldByName(fnGuid).AsString;
        NBInterface.Name := mtInterface.FieldByName(fnName).AsString;
        NBInterface.GuidNetType := mtInterface.FieldByName(fnGuidNetType).AsString;
        NBInterface.IDNetType := mtInterface.FieldByName(fnIDNetType).AsInteger;
        NBInterface.SortID := mtInterface.FieldByName(fnSortID).AsInteger;
        NBInterface.ConstructiveWidth := mtInterface.FieldByName(fnConstructiveWidth).AsFloat;
        NBInterface.Description := mtInterface.FieldByName(fnDescription).AsString;
        NBInterface.IsUniversal := mtInterface.FieldByName(fnIsUniversal).AsInteger;
        NBInterface.IsModified := mtInterface.FieldByName(fnIsModified).AsBoolean;

        ASpravochnik.AddInterface(NBInterface);
        if CurrGUIDCInterface = NBInterface.GUID then
          ASpravochnik.LastInterface := NBInterface;

        mtInterfaceAccordance.First;
        while Not mtInterfaceAccordance.Eof do
        begin
          NBInterfaceAccordance := TNBInterfaceAccordance.Create(ASpravochnik.ActiveForm);

          NBInterfaceAccordance.ID := mtInterfaceAccordance.FieldByName(fnID).AsInteger;
          NBInterfaceAccordance.GUID := mtInterfaceAccordance.FieldByName(fnGUID).AsString;
          NBInterfaceAccordance.GuidInterface := NBInterface.GUID; //mtInterfaceAccordance.FieldByName(fnGUIDInterface).AsString;
          NBInterfaceAccordance.IDInterface := NBInterface.ID; //mtInterfaceAccordance.FieldByName(fnIDInterface).AsInteger;
          NBInterfaceAccordance.InterfComponIsLine := mtInterfaceAccordance.FieldByName(fnInterfComponIsLine).AsInteger;
          NBInterfaceAccordance.GUIDAccordance := mtInterfaceAccordance.FieldByName(fnGUIDAccordance).AsString;
          NBInterfaceAccordance.IDAccordance := mtInterfaceAccordance.FieldByName(fnIDAccordance).AsInteger;
          NBInterfaceAccordance.AccordComponIsLine := mtInterfaceAccordance.FieldByName(fnAccordComponIsLine).AsInteger;
          NBInterfaceAccordance.Kolvo := mtInterfaceAccordance.FieldByName(fnKolvo).AsInteger;
          NBInterfaceAccordance.IsModified := mtInterfaceAccordance.FieldByName(fnIsModified).AsBoolean;

          NBInterface.AddInterfaceAccordance(NBInterfaceAccordance);
          mtInterfaceAccordance.Next;
        end;

        mtInterfaceNorms.First;
        while Not mtInterfaceNorms.Eof do
        begin
          NBInterfaceNorm := TNBInterfaceNorm.Create(GForm);

          NBInterfaceNorm.ID := mtInterfaceNorms.FieldByName(fnID).AsInteger;
          NBInterfaceNorm.GUID := mtInterfaceNorms.FieldByName(fnGuid).AsString;
          NBInterfaceNorm.GuidInterface := NBInterface.GUID; //mtInterfaceNorms.FieldByName(fnGuidInterface).AsString;
          NBInterfaceNorm.IDInterface := NBInterface.ID; //mtInterfaceNorms.FieldByName(fnIDInterface).AsInteger;
          NBInterfaceNorm.GuidNBNorm := mtInterfaceNorms.FieldByName(fnGuidNBNorm).AsString;
          NBInterfaceNorm.IDNBNorm := mtInterfaceNorms.FieldByName(fnIDNBNorm).AsInteger;
          NBInterfaceNorm.Expense := mtInterfaceNorms.FieldByName(fnExpense).AsFloat;
          NBInterfaceNorm.InterfaceIsBusy := mtInterfaceNorms.FieldByName(fnInterfaceIsBusy).AsInteger;

          NBInterfaceNorm.GUIDComponentType := mtInterfaceNorms.FieldByName(fnGuidComponentType).AsString;
          NBInterfaceNorm.IDComponentType := mtInterfaceNorms.FieldByName(fnIDComponentType).AsInteger;
          NBInterfaceNorm.KoefLengthForCompl := mtInterfaceNorms.FieldByName(fnKoefLengthForCompl).AsFloat;

          NBInterfaceNorm.IsModified := mtInterfaceNorms.FieldByName(fnIsModified).AsBoolean;

          if NBInterfaceNorm.IsModified and (AChangedInterfNorm <> nil) then
            AChangedInterfNorm^ := true;

          NBInterface.AddInterfaceNorm(NBInterfaceNorm);

          mtInterfaceNorms.Next;
        end;
        NBInterface.InterfNormsCount := NBInterface.InterfaceNorms.Count;
        
        mtInterface.Next;
      end;
    end;

    // типы сетей
    if (vkNetType in ASprElements) or (vkAll in ASprElements) then
    begin
      ASpravochnik.NetTypes.Clear;
      CurrGUIDCNetType := '';
      if mtNetType.RecordCount > 0 then
        CurrGUIDCNetType := mtNetType.FieldByName(fnGuid).AsString; 

      mtNetType.First;
      while Not mtNetType.Eof do
      begin
        NBNetType := TNBNetType.Create(ASpravochnik.ActiveForm);

        NBNetType.ID := mtNetType.FieldByName(fnID).AsInteger;
        NBNetType.IDCatalog := mtNetType.FieldByName(fnIDCatalog).AsInteger;
        NBNetType.CatalogItemType := mtNetType.FieldByName(fnIDItemType).AsInteger;
        NBNetType.GUID := mtNetType.FieldByName(fnGuid).AsString;
        NBNetType.Name := mtNetType.FieldByName(fnName).AsString;
        NBNetType.IsModified := mtNetType.FieldByName(fnIsModified).AsBoolean;

        ASpravochnik.AddNetType(NBNetType);
        if CurrGUIDCNetType = NBNetType.GUID then
          ASpravochnik.LastNetType := NBNetType;

        mtNetType.Next;
      end;
    end;

    // нормы
    if (vkNorm in ASprElements) or (vkAll in ASprElements) then
    begin
      ASpravochnik.Norms.Clear;
      CurrGUIDCNorm := '';
      if mtNorms.RecordCount > 0 then
        CurrGUIDCNorm := mtNorms.FieldByName(fnGuid).AsString;

      mtNorms.First;
      while Not mtNorms.Eof do
      begin
        NBNorm := TNBNorm.Create(ASpravochnik.ActiveForm);

        NBNorm.ID := mtNorms.FieldByName(fnID).AsInteger;
        NBNorm.IDCatalog := mtNorms.FieldByName(fnIDCatalog).AsInteger;
        NBNorm.CatalogItemType := mtNorms.FieldByName(fnIDItemType).AsInteger;
        NBNorm.GUID := mtNorms.FieldByName(fnGuid).AsString;
        NBNorm.Cypher := mtNorms.FieldByName(fnCypher).AsString;
        NBNorm.Name := mtNorms.FieldByName(fnName).AsString;
        NBNorm.Izm := mtNorms.FieldByName(fnIzm).AsString;
        NBNorm.LaborTime := mtNorms.FieldByName(fnLaborTime).AsInteger;
        NBNorm.PricePerTime := mtNorms.FieldByName(fnPricePerTime).AsFloat;
        //NBNorm.TimeUOM := mtNorms.FieldByName(fnTimeUOM).AsInteger;
        NBNorm.Price := mtNorms.FieldByName(fnPrice).AsFloat;
        NBNorm.GUIDESmeta := mtNorms.FieldByName(fnGuidESmeta).AsString;
        NBNorm.IsModified := mtNorms.FieldByName(fnIsModified).AsBoolean;

        NBNorm.IsApplyDataForAllSame := mtNorms.FieldByName(fnApplyForAllSame).AsBoolean;

        ASpravochnik.AddNorm(NBNorm);
        if CurrGUIDCNorm = NBNorm.GUID then
          ASpravochnik.LastNorm := NBNorm;

        //24.09.2010
        // Применять данные лучше после пререрасчета цен если мзменялась валюта
        //if mtNorms.FieldByName(fnApplyForAllSame).AsBoolean then
//          if ASpravochnik.OwnerObject is TSCSCatalog then
//          begin
//            SCSCatalog := TSCSCatalog(ASpravochnik.OwnerObject);
//            for i := 0 to SCSCatalog.ComponentReferences.Count - 1 do
//            begin
//              SCSComponent := SCSCatalog.ComponentReferences[i];
//              for j := 0 to SCSComponent.NormsResources.Norms.Count - 1 do
//              begin
//                SCSNorm := SCSComponent.NormsResources.Norms[j];
//                if SCSNorm.GuidNB = NBNorm.GUID then
//                begin
//                  SCSNorm.Cypher := NBNorm.Cypher;
//                  SCSNorm.Name := NBNorm.Name;
//                  SCSNorm.Izm_ := NBNorm.Izm;
//                  SCSNorm.Price := NBNorm.Price;
//                end;
//              end;
//            end;
//          end;

        mtNorms.Next;
      end;
    end;

    // условные обозначения
    if (vkObjectIcons in ASprElements) or (vkAll in ASprElements) then
    begin
      ASpravochnik.ObjectIcons.Clear;
      CurrGUIDCObjectIcon := '';
      if mtObjectIcons.RecordCount > 0 then
        CurrGUIDCObjectIcon := mtObjectIcons.FieldByName(fnGuid).AsString;

      mtObjectIcons.First;
      while Not mtObjectIcons.Eof do
      begin
        NBObjectIcon := TNBObjectIcon.Create(ASpravochnik.ActiveForm);

        NBObjectIcon.ID := mtObjectIcons.FieldByName(fnID).AsInteger;
        NBObjectIcon.IDCatalog := mtObjectIcons.FieldByName(fnIDCatalog).AsInteger;
        NBObjectIcon.CatalogItemType := mtObjectIcons.FieldByName(fnIDItemType).AsInteger;
        NBObjectIcon.GUID := mtObjectIcons.FieldByName(fnGuid).AsString;
        NBObjectIcon.Name := mtObjectIcons.FieldByName(fnName).AsString;
        SaveToStreamFromMT(mtObjectIcons, NBObjectIcon.ProjBlk, fnProjBlk);
        SaveToStreamFromMT(mtObjectIcons, NBObjectIcon.ProjBmp, fnProjBmp);
        SaveToStreamFromMT(mtObjectIcons, NBObjectIcon.ActiveBlk, fnActiveBlk);
        SaveToStreamFromMT(mtObjectIcons, NBObjectIcon.ActiveBmp, fnActiveBmp);
        NBObjectIcon.IsModified := mtObjectIcons.FieldByName(fnIsModified).AsBoolean;

        ASpravochnik.AddObjectIcon(NBObjectIcon);
        if CurrGUIDCObjectIcon = NBObjectIcon.GUID then
          ASpravochnik.LastObjectIcon := NBObjectIcon;
        mtObjectIcons.Next;
      end;
    end;

    // производители
    if (vkProducers in ASprElements) or (vkAll in ASprElements) then
    begin
      ASpravochnik.Producers.Clear;
      CurrGUIDCProducer := '';
      if mtProducers.RecordCount > 0 then
        CurrGUIDCProducer := mtProducers.FieldByName(fnGuid).AsString;

      mtProducers.First;
      while Not mtProducers.Eof do
      begin
        NBProducer := TNBProducer.Create(ASpravochnik.ActiveForm);

        NBProducer.ID := mtProducers.FieldByName(fnID).AsInteger;
        NBProducer.IDCatalog := mtProducers.FieldByName(fnIDCatalog).AsInteger;
        NBProducer.CatalogItemType := mtProducers.FieldByName(fnIDItemType).AsInteger;
        NBProducer.GUID := mtProducers.FieldByName(fnGuid).AsString;
        NBProducer.Name := mtProducers.FieldByName(fnName).AsString;
        NBProducer.Description := mtProducers.FieldByName(fnDescription).AsString;
        NBProducer.IsModified := mtProducers.FieldByName(fnIsModified).AsBoolean;

        ASpravochnik.AddProducer(NBProducer);
        if CurrGUIDCProducer = NBProducer.GUID then
          ASpravochnik.LastProducer := NBProducer;

        mtProducers.Next;
      end;
    end;

    // свойства
    if (vkProperty in ASprElements) or (vkAll in ASprElements) then
    begin
      ASpravochnik.ClearProperties; //ASpravochnik.Properties.Clear;
      CurrGUIDCProperty := '';
      if mtProperties.RecordCount > 0 then
        CurrGUIDCProperty := mtProperties.FieldByName(fnGUID).AsString;

      mtProperties.First;
      while Not mtProperties.Eof do
      begin
        NBProperty := TNBProperty.Create(ASpravochnik.ActiveForm);

        NBProperty.PropertyData.ID := mtProperties.FieldByName(fnID).AsInteger;
        NBProperty.IDCatalog := mtProperties.FieldByName(fnIDCatalog).AsInteger;
        NBProperty.CatalogItemType := mtProperties.FieldByName(fnIDItemType).AsInteger;
        NBProperty.PropertyData.GUID := mtProperties.FieldByName(fnGUID).AsString;
        NBProperty.PropertyData.IDDataType := mtProperties.FieldByName(fnIDDataType).AsInteger;
        NBProperty.PropertyData.Name := mtProperties.FieldByName(fnName).AsString;
        NBProperty.PropertyData.SysName := mtProperties.FieldByName(fnSysName).AsString;
        NBProperty.PropertyData.Izm := mtProperties.FieldByName(fnIzm).AsString;
        NBProperty.PropertyData.ValueReq := mtProperties.FieldByName(fnValueReq).AsInteger;
        NBProperty.PropertyData.MinValue := mtProperties.FieldByName(fnMinValue).AsFloat;
        NBProperty.PropertyData.MaxValue := mtProperties.FieldByName(fnMaxValue).AsFloat;
        NBProperty.PropertyData.DefValue := mtProperties.FieldByName(fnDefValue).AsString;
        NBProperty.PropertyData.Description := mtProperties.FieldByName(fnDescription).AsString;
        NBProperty.PropertyData.IsStandart := mtProperties.FieldByName(fnIsStandart).AsInteger;
        NBProperty.PropertyData.SortID := mtProperties.FieldByName(fnSortID).AsInteger;
        NBProperty.PropertyData.ISProject := mtProperties.FieldByName(fnISProject).AsInteger;
        NBProperty.PropertyData.ISFolder := mtProperties.FieldByName(fnISFolder).AsInteger;
        NBProperty.PropertyData.ISList := mtProperties.FieldByName(fnISList).AsInteger;
        NBProperty.PropertyData.ISRoom := mtProperties.FieldByName(fnISRoom).AsInteger;
        NBProperty.PropertyData.ISSCSLine := mtProperties.FieldByName(fnISSCSLine).AsInteger;
        NBProperty.PropertyData.ISSCSConnector := mtProperties.FieldByName(fnISSCSConnector).AsInteger;
        NBProperty.PropertyData.ISComponLine := mtProperties.FieldByName(fnISComponLine).AsInteger;
        NBProperty.PropertyData.ISComponConn := mtProperties.FieldByName(fnISComponConn).AsInteger;
        NBProperty.PropertyData.IsForWholeComponent := mtProperties.FieldByName(fnIsForWholeComponent).AsInteger;
        NBProperty.PropertyData.IsValueRelToObj := mtProperties.FieldByName(fnIsValueRelToObj).AsInteger;
        
        NBProperty.IsModified := mtProperties.FieldByName(fnIsModified).AsBoolean;

        ASpravochnik.AddProperty(NBProperty);
        if CurrGUIDCProperty = NBProperty.PropertyData.GUID then
          ASpravochnik.LastProperty := NBProperty;

        mtPropValRel.First;
        while Not mtPropValRel.Eof do
        begin
          NBPropValRel := TNBPropValRel.Create(NBProperty.ActiveForm);

          NBPropValRel.ID := mtPropValRel.FieldByName(fnID).AsInteger;
          NBPropValRel.GUID := mtPropValRel.FieldByName(fnGUID).AsString;
          NBPropValRel.IDProperty := mtPropValRel.FieldByName(fnIDProperty).AsInteger;
          NBPropValRel.GuidProperty := mtPropValRel.FieldByName(fnGuidProperty).AsString;
          NBPropValRel.PValue := mtPropValRel.FieldByName(fnPValue).AsString;
          NBPropValRel.MinValue := mtPropValRel.FieldByName(fnMinValue).AsString;
          NBPropValRel.MaxValue := mtPropValRel.FieldByName(fnMaxValue).AsString;
          NBPropValRel.IsModified := mtPropValRel.FieldByName(fnIsModified).AsBoolean or
                                     mtPropValRel.FieldByName(fnIsNew).AsBoolean;

          NBProperty.AddPropValRel(NBPropValRel);

          mtPropValNormRes.First;
          while Not mtPropValNormRes.Eof do
          begin
            NBPropValNormRes := TNBPropValNormRes.Create(NBPropValRel.ActiveForm);  

            NBPropValNormRes.ID := mtPropValNormRes.FieldByName(fnID).AsInteger;
            NBPropValNormRes.GUID := mtPropValNormRes.FieldByName(fnGUID).AsString;
            NBPropValNormRes.IDPropValRel := mtPropValNormRes.FieldByName(fnIDPropValRel).AsInteger;
            NBPropValNormRes.GuidPropValRel := mtPropValNormRes.FieldByName(fnGuidPropValRel).AsString;
            NBPropValNormRes.IDNBComponent := mtPropValNormRes.FieldByName(fnIDNBComponent).AsInteger;
            NBPropValNormRes.GuidNBComponent := mtPropValNormRes.FieldByName(fnGuidNBComponent).AsString;
            NBPropValNormRes.IDNBRes := mtPropValNormRes.FieldByName(fnIDNBRes).AsInteger;
            NBPropValNormRes.GuidNBRes := mtPropValNormRes.FieldByName(fnGuidNBRes).AsString;
            NBPropValNormRes.IDNBNorm := mtPropValNormRes.FieldByName(fnIDNBNorm).AsInteger;
            NBPropValNormRes.GuidNBNorm := mtPropValNormRes.FieldByName(fnGuidNBNorm).AsString;
            NBPropValNormRes.Kolvo := mtPropValNormRes.FieldByName(fnKolvo).AsFloat;
            NBPropValNormRes.ExpenseForLength := mtPropValNormRes.FieldByName(fnExpenseForLength).AsFloat;
            NBPropValNormRes.CountForPoint := mtPropValNormRes.FieldByName(fnCountForPoint).AsFloat;
            NBPropValNormRes.StepOfPoint := mtPropValNormRes.FieldByName(fnStepOfPoint).AsFloat;
            NBPropValNormRes.IsModified := mtPropValNormRes.FieldByName(fnIsModified).AsBoolean or
                                           mtPropValNormRes.FieldByName(fnIsNew).AsBoolean;

            NBPropValRel.AddPropValNormRes(NBPropValNormRes);

            mtPropValNormRes.Next;
          end;
          mtPropValRel.Next;
        end;
        mtProperties.Next;
      end;
    end;

    // ресурсы
    if (vkResource in ASprElements) or (vkAll in ASprElements) then
    begin
      ASpravochnik.Resources.Clear;
      CurrGUIDCResource := '';
      if mtResources.RecordCount > 0 then
        CurrGUIDCResource := mtResources.FieldByName(fnGuid).AsString;

      mtResources.First;
      while Not mtResources.Eof do
      begin
        NBResource := TNBResource.Create(ASpravochnik.ActiveForm);

        NBResource.ID := mtResources.FieldByName(fnID).AsInteger;
        NBResource.IDCatalog := mtResources.FieldByName(fnIDCatalog).AsInteger;
        NBResource.CatalogItemType := mtResources.FieldByName(fnIDItemType).AsInteger;
        NBResource.GUID := mtResources.FieldByName(fnGuid).AsString;
        NBResource.Cypher := mtResources.FieldByName(fnCypher).AsString;
        NBResource.Name := mtResources.FieldByName(fnName).AsString;
        NBResource.Izm := mtResources.FieldByName(fnIzm).AsString;
        NBResource.Price := mtResources.FieldByName(fnPrice).AsFloat;
        NBResource.RType := mtResources.FieldByName(fnRType).AsInteger;
        NBResource.IsModified := mtResources.FieldByName(fnIsModified).AsBoolean;

        NBResource.IsApplyDataForAllSame := mtResources.FieldByName(fnApplyForAllSame).AsBoolean;

        ASpravochnik.AddResource(NBResource);
        if CurrGUIDCResource = NBResource.GUID then
          ASpravochnik.LastResource := NBResource;

        //24.09.2010
        // Применять данные лучше после пререрасчета цен если мзменялась валюта
        //if mtResources.FieldByName(fnApplyForAllSame).AsBoolean then
//          if ASpravochnik.OwnerObject is TSCSCatalog then
//          begin
//            SCSCatalog := TSCSCatalog(ASpravochnik.OwnerObject);
//            for i := 0 to SCSCatalog.ComponentReferences.Count - 1 do
//            begin
//              SCSComponent := SCSCatalog.ComponentReferences[i];
//              for j := 0 to SCSComponent.NormsResources.Resources.Count - 1 do
//              begin
//                SCSResource := SCSComponent.NormsResources.Resources[j];
//                if SCSResource.GuidNB = NBResource.GUID then
//                begin
//                  SCSResource.Cypher := NBResource.Cypher;
//                  SCSResource.Name := NBResource.Name;
//                  SCSResource.Izm := NBResource.Izm;
//                  SCSResource.Price := NBResource.Price;
//                  SCSResource.RType := NBResource.RType;
//                end;
//              end;
//            end;
//          end;
        mtResources.Next;
      end;
    end;

    // виды поставок
    if (vkSuppliesKind in ASprElements) or (vkAll in ASprElements) then
    begin
      ASpravochnik.SuppliesKinds.Clear;
      CurrGUIDCSuppliesKind := '';
      if mtSuppliesKinds.RecordCount > 0 then
        CurrGUIDCSuppliesKind := mtSuppliesKinds.FieldByName(fnGUID).AsString;

      mtSuppliesKinds.First;
      while Not mtSuppliesKinds.Eof do
      begin
        NBSuppliesKind := TNBSuppliesKind.Create(ASpravochnik.ActiveForm);

        NBSuppliesKind.Data.ID := mtSuppliesKinds.FieldByName(fnID).AsInteger;
        NBSuppliesKind.IDCatalog := mtSuppliesKinds.FieldByName(fnIDCatalog).AsInteger;
        NBSuppliesKind.CatalogItemType := mtSuppliesKinds.FieldByName(fnIDItemType).AsInteger;
        NBSuppliesKind.Data.GUID := mtSuppliesKinds.FieldByName(fnGUID).AsString;
        NBSuppliesKind.Data.Name := mtSuppliesKinds.FieldByName(fnName).AsString;
        NBSuppliesKind.Data.NameTradUOM := mtSuppliesKinds.FieldByName(fnNameTradUOM).AsString;
        NBSuppliesKind.Data.Izm := mtSuppliesKinds.FieldByName(fnIzm).AsString;
        NBSuppliesKind.Data.IzmTradUOM := mtSuppliesKinds.FieldByName(fnIzmTradUOM).AsString;
        NBSuppliesKind.Data.UnitKolvo := mtSuppliesKinds.FieldByName(fnUnitKolvo).AsFloat;
        NBSuppliesKind.Data.UnitKolvoTradUOM := mtSuppliesKinds.FieldByName(fnUnitKolvoTradUOM).AsFloat;
        NBSuppliesKind.IsModified := mtSuppliesKinds.FieldByName(fnIsModified).AsBoolean;

        ASpravochnik.AddSuppliesKind(NBSuppliesKind);
        if CurrGUIDCSuppliesKind = NBSuppliesKind.Data.GUID then
          ASpravochnik.LastSuppliesKind := NBSuppliesKind;
        mtSuppliesKinds.Next;
      end;
    end;

    //FreeAndNil(CompTypesGuids);
    //FreeAndNil(CompTypePropsGuids);
  finally
    mtSuppliesKinds.EnableControls;
    mtResources.EnableControls;
    //mtProperties.EnableControls;
    mtProducers.EnableControls;
    mtObjectIcons.EnableControls;
    mtNorms.EnableControls;
    mtNetType.EnableControls;
    GT_ComponentTypes.EndUpdate;
    GT_CompTypeProp.EndUpdate;
    mtCurrency.EnableControls;
    GT_Interfaces.EndUpdate;
    GT_InterfAccordance.EndUpdate;
    GT_InterfaceNorms.EndUpdate;

    //mtInterfaceNorms.EnableControls;
    //mtInterface.EnableControls;
    //mtCompTypePropRelation.EnableControls;
    //mtComponentType.EnableControls;

    //mtCompTypePropRelation.MasterSource := SavedMasterSourceCompTypePropRelation;
    //mtInterfaceNorms.MasterSource := SavedMasterSourceInterfacesNorms;
  end;
end;

procedure TF_CaseForm.SetCaptionToActions(ACaption: String);
begin
  if TF_Main(GForm).GDBMode = bkNormBase then
    Act_Make.Caption := cCaseForm_Msg24_1+' ' + ACaption
  else
  if TF_Main(GForm).GDBMode = bkProjectManager then
    Act_Make.Caption := cCaseForm_Msg36_1+' ' + ACaption + ' '+ cCaseForm_Msg36_2;
    
  Act_Edit.Caption := cCaseForm_Msg24_2+' ' + ACaption;
  Act_Del.Caption := cCaseForm_Msg24_3+' ' + ACaption;

  Act_Make.Hint := Act_Make.Caption;
  Act_Edit.Hint := Act_Edit.Caption;
  Act_Del.Hint := Act_Del.Caption;
end;

procedure TF_CaseForm.SetPageByViewKind(AViewKind: TViewKind);
var
  ActiveTabSheet: TRzTabSheet;
  SavedOnChangePageCotrol: TNotifyEvent;
begin
  ActiveTabSheet := GetTabSheetByViewKind(AViewKind);
  if Assigned(ActiveTabSheet) then
  begin
    SavedOnChangePageCotrol := pcDirectories.OnChange;
    pcDirectories.OnChange := nil;
    try
      pcDirectories.ActivePage := ActiveTabSheet;
    finally
      pcDirectories.OnChange := SavedOnChangePageCotrol;
    end;
  end;
end;



// #########################  Работа с деревом  ################################
// #############################################################################
//
// ##### Переименование ветви #####
procedure TF_CaseForm.RenameNode(ANode: TTreeNode; ANewName: String);
var
  CurrID: Integer;
begin
  CurrID := PObjectData(ANode.Data).ObjectID;
  with TF_Main(GForm).DM do
    UpdateStrTableFieldByID(tnDirectoryType, fnName, CurrID, ANewName, qmPhisical);
  DefineTextNode(ANode);
end;


// ##### Устанавливает имя ветви + количество (кот-е в параметре) #####
procedure TF_CaseForm.RefreshKolNode(ANode: TTreeNode;
  AKolvo: Integer = -1);
//var  NameNode: String;
     //Kolvo: Integer;
     //InterfTypeData: PObjectData;
begin
    if ANode.IsFirstNode then
      Exit;

    {if AKolvo = -1 then
    begin
        InterfTypeData := ANode.Data;
        Kolvo := InterfTypeData.ChildNodesCount;
    end
    else
      Kolvo := Akolvo;

    NameNode := ANode.Text;
    CutColFromStr(NameNode);
    NameNode := NameNode + '  [ ' + IntToStr(Kolvo) + ' ]';
    ANode.Text := NameNode;}
end;

procedure TF_CaseForm.RefreshNodes(AIDToSelect: Integer);
var
  IDToSelect: Integer;

  IDListToExpand: TIntList;
  Node: TTreeNode;
  ParentNode: TTreeNode;
  i: Integer;
begin
  try
    IDToSelect := AIDToSelect;
    if IDToSelect <= 0 then
      if Tree_InterfType.Selected <> nil then
        IDToSelect := PObjectData(Tree_InterfType.Selected.Data).ObjectID;

    IDListToExpand := TIntList.Create;
    // Запоминаем раскрытые ветки
    Node := nil;
    if Tree_InterfType.Items.Count > 0 then
      Node := Tree_InterfType.Items[0];
    while Node <> nil do
    begin
      if Node.Expanded then
      begin
        // убираем из списка всех парентов
        ParentNode := Node.Parent;
        while ParentNode <> nil do
        begin
          IDListToExpand.Remove(PObjectData(ParentNode.Data).ObjectID);
          ParentNode := ParentNode.Parent;
        end;
        // добавляем тек. ID
        IDListToExpand.Add(PObjectData(Node.Data).ObjectID);
      end;
      Node := Node.GetNextVisible;
    end;

    // Перегружаем дерево
    ClearTreeView(Tree_InterfType);
    AddNodes(nil);

    // востанавливаем открытые ветки
    for i := 0 to IDListToExpand.Count - 1 do
    begin
      Node := FindNodeByID(IDListToExpand[i]);
      if Node <> nil then
        Node.Expanded := true;
    end;

    if IDToSelect <> 0 then
    begin
      Node := FindNodeByID(IDToSelect);
      if Node <> nil then
        Tree_InterfType.Selected := Node;
    end;

    FreeAndNil(IDListToExpand);
  except
    on E: Exception do AddExceptionToLogEx('TF_CaseForm.RefreshNodes', E.Message);
  end;
end;

procedure TF_CaseForm.SaveSelectTabNode;
var
  StringsIndex: Integer;
  DirTypeData: PObjectData;
begin
  if Tree_InterfType.Selected <> nil then
  begin
    DirTypeData := Tree_InterfType.Selected.Data;
    StringsIndex := FTabsSelectedDir.IndexOf(IntToStr(pcDirectories.ActivePageIndex));
    if StringsIndex = -1 then
      FTabsSelectedDir.AddObject(IntToStr(pcDirectories.ActivePageIndex), TObject(DirTypeData.ObjectID))
    else
      FTabsSelectedDir.Objects[StringsIndex] := TObject(DirTypeData.ObjectID);
  end;
end;

procedure TF_CaseForm.SelectLastTabNode;
var
  StringsIndex: Integer;
begin
  if ((GIDToLocate = 0) or (GIDToLocate = -1)) and (GGUIDToLocate = '') then
  begin
    StringsIndex := FTabsSelectedDir.IndexOf(IntToStr(pcDirectories.ActivePageIndex));
    if StringsIndex <> -1 then
    begin
      SelectNodeByID(Integer(FTabsSelectedDir.Objects[StringsIndex]));
    end;
  end;
end;

function TF_CaseForm.SelectNodeByID(AID: Integer): Boolean;
var
  Node: TTreeNode;
begin
  Result := false;
  Node := FindNodeByID(AID);
  if Assigned(Node) then
  begin
    Tree_InterfType.Selected := Node;
    Result := true;
  end;
end;

procedure TF_CaseForm.SetCurrencyBriefToControls(ACurrency: TCurrency);
var
  DisplayFormat: String;
begin
  DisplayFormat := GetDisplayFormat(ACurrency.NameBrief);

  TcxCurrencyEditProperties(GT_NB_ResourcesPRICE.Properties).DisplayFormat := DisplayFormat;
  TcxCurrencyEditProperties(GT_NB_ResourcesAdditionalPrice.Properties).DisplayFormat := DisplayFormat;

  TcxCurrencyEditProperties(GT_NB_NormsPrice.Properties).DisplayFormat := DisplayFormat;
  TcxCurrencyEditProperties(GT_NB_NormsPricePerTime.Properties).DisplayFormat := DisplayFormat;
end;

procedure TF_CaseForm.SetCurrencyBriefToControlsFromMT;
var
  //BookmarkStr: String;
  BookmarkStr: TBookMark;
  Currency: TCurrency;
begin
  if (mtCurrency <> nil) and mtCurrency.Active then
  begin
    //BookmarkStr := mtCurrency.Bookmark;
    BookmarkStr := mtCurrency.GetBookmark;
    mtCurrency.DisableControls;
    try
      if mtCurrency.Locate(fnMain, ctMain, []) then
      begin
        Currency := GetCurrencyFromMemTable(mtCurrency);
        SetCurrencyBriefToControls(Currency);
      end;
    finally
      //mtCurrency.Bookmark := BookmarkStr;
      if BookmarkStr <> nil then
      begin
        mtCurrency.GotoBookmark(BookmarkStr);
        mtCurrency.FreeBookmark(BookmarkStr);
      end;
      mtCurrency.EnableControls;
    end;
  end;
end;

// ##### Определить количество подпапок #####
procedure TF_CaseForm.SetKolChildNodes(ANode: TTreeNode);
//var InterfTypeData: PObjectData;
    //KolChildNodes: Integer;
begin
    {if ANode.IsFirstNode then
      Exit;

    InterfTypeData := ANode.Data;
    with TF_Main(GForm).DM do
      begin
          SetSQLToQuery(scsQ, ' SELECT Count(*) As Cnt FROM INTERFACE_TYPE '+
                               ' WHERE PARENT_ID = '''+ IntToStr(InterfTypeData.ObjectID) +''' '
                               );
          KolChildNodes := scsQ.GetFNAsInteger('Cnt');
          InterfTypeData.ChildNodesCount := KolChildNodes;
          SetSQLToQuery(scsQOperat, ' UPDATE INTERFACE_TYPE SET '+
                       '   KOL_CHILD_NODES = '''+ IntToStr(KolChildNodes) +''' '+
                       ' WHERE ID = '''+ IntToStr(InterfTypeData.ObjectID) +'''  '
                       );
          RefreshKolNode(ANode);
      end;}
end;



// ##### Переместить интерфейс #####
procedure TF_CaseForm.Act_MoveInterfaceExecute(Sender: TObject);
begin
  if FDragIDPointer > 0 then
    if CheckChange then
    begin
      MoveItemBetweenNodes(GSNode, GTNode, FDragIDPointer);
      Tree_InterfType.Selected := GTNode;
    end;
end;


// ##### Перемещает папку ASourceNode в ATargetNode #####
procedure TF_CaseForm.MoveNodes(ASourceNode, ATargetNode: TTreeNode);
var //InterfTypeData: PObjectData;
    IDTarget: Integer;
    IDSource: Integer;
    SourceParentNode: TTreeNode;
begin
    IDTarget := PObjectData(ATargetNode.Data).ObjectID;
    IDSource := PObjectData(ASourceNode.Data).ObjectID;
    SourceParentNode := ASourceNode.Parent;

    ASourceNode.MoveTo(ATargetNode, naAddChild);
    with TF_Main(GForm).DM do
      UpdateIntTableFieldByID(tnDirectoryType, fnParentID, IDSource, IDTarget, qmPhisical);
    SetSortID(ASourceNode);
//      SetSQlToQuery(scsQOperat, ' UPDATE INTERFACE_TYPE SET '+
//                                '   PARENT_ID = '''+ IntToStr(IDTarget) +''' '+
//                                ' WHERE ID = '''+ IntToStr(IDSource) +''' '
//                          );
//    SetKolChildNodes(ATargetNode);
//    SetKolChildNodes(SourceParentNode);
end;




// ##### Насыпает в дерево ветви #####
procedure TF_CaseForm.AddNodes(ANode: TTreeNode);
var Parent_ID: Integer;
    NewNode: TTreeNode;
    NameNewNode: String;

    KolChildNodes: Integer; //*** Количество загруженых подпапок
    KolChildDir: Integer;   //*** Количество подпапок в базе
    CurrNode: TTreeNode;
    CurrNodeData: PObjectData;
    TabSheet: TRzTabSheet;

  procedure Step(AParentNode: TTreeNode; AisFirstCalling: Boolean);
  var
    DirectoryTypeList: TList;
    DirTypeData: PObjectData;
    DirectoryType: PDirectoryType;

    i: Integer;
    strWhere: String;
    ChildItemCount: Integer;
  begin
    strWhere := '';
    if AParentNode = nil then
    begin
      Parent_ID := 0;
      strWhere := '(Parent_ID is null)';
    end
    else
    begin
      Parent_Id := PObjectData(AParentNode.Data).ObjectID;
      strWhere := '(PARENT_ID = '''+ IntToStr(Parent_ID) +''')';
    end;
    strWhere := strWhere + ' and ('+fnDirItemType+' = '''+IntTostr(FDirTypeInfo.ItemType)+''')';

    with TF_Main(GForm).DM do
    begin
      SetSQLToQuery(scsQSelect, ' SELECT * FROM '+tnDirectoryType+' '+
                           ' WHERE '+strWhere+' ORDER BY SORT_ID ');
      DirectoryTypeList := TList.Create;
      while Not scsQSelect.Eof do
      begin
        GetMem(DirectoryType, SizeOf(TDirectoryType));
        DirectoryType.ID := scsQSelect.GetFNAsInteger(fnID);
        DirectoryType.ParentID := scsQSelect.GetFNAsInteger(fnParentID);
        DirectoryType.NAME :=	scsQSelect.GetFNAsString(fnName);
        DirectoryType.ItemsCount :=	scsQSelect.GetFNAsInteger(fnItemsCount);
        DirectoryType.ContentKolvo := scsQSelect.GetFNAsInteger(fnContentKolvo);
        DirectoryType.SortID := scsQSelect.GetFNAsInteger(fnSortID);
        // Если первая верхняя ветка
        if (AParentNode = nil) and (DirectoryTypeList.Count = 0) then
        begin
          TabSheet := GetTabSheetByViewKind(FDirTypeInfo.ViewKind);
          if TabSheet <> nil then
            DirectoryType.NAME := TabSheet.Caption;
        end;
        DirectoryTypeList.Add(DirectoryType);
        scsQSelect.Next;
      end;

      for i := 0 to DirectoryTypeList.Count - 1 do
      begin
        DirectoryType := DirectoryTypeList.Items[i];
        //*** Определить количество интерфейсов, если запрещено отображение скрытых
        if (FViewKind = vkInterface) and Not IsShowUnvisibleInterface then
        begin
          {SetSQLToFIBQuery(TF_Main(GForm).DM.Query_Select,
            'SELECT COUNT(ID) FROM '+FDirTypeInfo.TableName+', '+tnDirectoryTypeRel+ ' '+
            'WHERE ('+fnIDDirectoryType+' = '''+IntTostr(DirectoryType.ID)+''') AND '+
                  '('+FDirTypeInfo.TableName+'.ID = '+tnDirectoryTypeRel+'.'+FDirTypeInfo.MasterFieldName+') AND '+
                  '('+FDirTypeInfo.TableName+'.'+fnIsVisible+' = '''+IntToStr(biTrue)+''')');
          DirectoryType.ContentKolvo := TF_Main(GForm).DM.Query_Select.FN(fnCount).AsInteger;}
          DirectoryType.ContentKolvo := TF_Main(GForm).DM.GetContensCountFromDir(DirectoryType.ID, FDirTypeInfo, GetSQLForIsVisible(FDirTypeInfo.TableName));
        end;

        NameNewNode := GetNameAndKol(DirectoryType.Name, DirectoryType.ContentKolvo);
        if Parent_ID = 0 then
          NewNode := Tree_InterfType.Items.AddFirst(AParentNode, NameNewNode)
        else
        begin
          //NameNewNode := GetNameAndKol(NameNewNode, DirectoryType.ContentKolvo); //NameNewNode + '  [ '+ IntToStr(DirectoryType.ItemsCount) + ' ]';
          NewNode := Tree_InterfType.Items.AddChild(AParentNode, NameNewNode);
        end;
        NewNode.ImageIndex := 0;
        NewNode.SelectedIndex := NewNode.ImageIndex;
        NewData(DirTypeData, ttGuide);
        DirTypeData.ObjectID := DirectoryType.ID;
        DirTypeData.ChildNodesCount := DirectoryType.ItemsCount;
        DirTypeData.SortID := DirectoryType.SortID;
        NewNode.Data := DirTypeData;
        //RefreshKolNode(NewNode);

        //*** Определить, есть ли в загруженой ветви еще подветви
        ChildItemCount := GetIntFromTableByID(tnDirectoryType, fnItemsCount, DirectoryType.ID, qmPhisical);
        if (AisFirstCalling = true) and (ChildItemCount > 0) then
          Step(NewNode, false);

      end;
      FreeList(DirectoryTypeList);
    end;
  end;

begin
  Tree_InterfType.Items.BeginUpdate;
  try
    if ANode = nil then
      Step(nil, true)
    else
    begin
      CurrNode := ANode.GetFirstChild;
      if CurrNode <> nil then
        while CurrNode <> nil do
        begin
          KolChildNodes := CurrNode.Count;
          CurrNodeData := CurrNode.Data;
          with TF_Main(GForm).DM do
          begin
            KolChildDir := GetIntFromTableByID(tnDirectoryType, fnItemsCount, CurrNodeData.ObjectID, qmPhisical);
            if (KolChildNodes > 0) and (KolChildNodes <> KolChildDir) then
            begin
              DeleteChildNodes(CurrNode);
              KolChildNodes := 0;
            end;
            if (KolChildNodes = 0) and (KolChildDir > 0) then
              Step(CurrNode, true);
          end;
          CurrNode := CurrNode.getNextSibling;
        end
      else
        Step(ANode, true);
    end;
  finally
    Tree_InterfType.Items.EndUpdate;
  end;
end;


function TF_CaseForm.DefineTextNode(ANode: TTreeNode): String;
var
  ContentKolvo: Integer;
begin
  Result := '';
  if Assigned(ANode) then
  begin
    with TF_Main(GForm).DM do
    begin
      Result := GetStringFromTableByID(tnDirectoryType, fnName, PObjectData(ANode.Data).ObjectID, qmPhisical);
      if (FViewKind = vkInterface) and Not IsShowUnvisibleInterface then
        ContentKolvo := GetContensCountFromDir(PObjectData(ANode.Data).ObjectID, FDirTypeInfo, GetSQLForIsVisible(FDirTypeInfo.TableName))
      else
        ContentKolvo := GetIntFromTableByID(tnDirectoryType, fnContentKolvo, PObjectData(ANode.Data).ObjectID, qmPhisical);
      Result := GetNameAndKol(Result, ContentKolvo);
    end;
    ANode.Text := Result;
  end;
end;

function TF_CaseForm.GetNodeFromTreeByID(AIDNode: Integer): TTreeNode;
var
  i: Integer;
  CurrNode: TTreeNode;
begin
  Result := nil;
  for i := 0 to Tree_InterfType.Items.Count - 1 do
  begin
    CurrNode := Tree_InterfType.Items[i];
    if PObjectData(CurrNode.Data).ObjectID = AIDNode then
    begin
      Result := CurrNode;
      Break; ///// BREAK /////
    end;
  end;
end;

function TF_CaseForm.GetRoomHeight: Double;
var
  strValue: String;
begin
  Result := -1;
  if FParentForm <> nil then
    if FParentForm is TF_MasterNewList then
    begin
      strValue := TF_MasterNewList(FParentForm).edRoomHeight.Text;
      try
       Result := StrToFloat_My(strValue);
       Result := FloatInUOM(Result, TF_MasterNewList(FParentForm).FCurrProjUnitOfMeasure, umM);
      except
      end;
    end;
end;


// ##### Ищет ветвь по ID #####
function TF_CaseForm.FindNodeByID(AIDNode: Integer): TTreeNode;
    type TListDat = record
        ID: Integer;
        Parent_ID: Integer;
     end;
     PListDat = ^TlistDat;

Var Road: TList;
    ListDat: PListDat;
    Dat: PObjectData;
    Node: TTreeNode;
    SubNode: TTreeNode;
    //ID_Component: Integer;
    ID_Catalog: Integer;
    Parent_ID: Integer;

    i: Integer;
    RCount: Integer; // Record Count
    //NCount: Integer; // Node Count
    FindedNode: TTreeNode;
    isFindedNode: Boolean;

    //Item: TListItem;
begin
  Result := nil;
  SubNode := nil;

  ID_Catalog := AIDNode;

  Road := TList.Create;

  //Построить спписок Пути
  Parent_ID := 10000;
  with (GForm as TF_Main) do
    while Parent_ID <> 0 do
    begin
      SetSQLToQuery(DM.scsQSelect, ' SELECT ID, PARENT_ID FROM '+tnDirectoryType+' '+
                              ' WHERE ID = '''+ IntToStr(ID_Catalog) +''' ');
      ID_Catalog := DM.scsQSelect.GetFNAsInteger('ID');
      Parent_ID := DM.scsQSelect.GetFNAsInteger('Parent_ID');

      New(ListDat);
      ListDat.ID := ID_Catalog;
      ListDat.Parent_ID := Parent_ID;
      Road.Add(ListDat);
      ID_Catalog := Parent_ID;
    end;

  //*** Выйти на самый верх дерева
  Node := nil;
  if Tree_InterfType.Items.Count > 0 then
    Node := Tree_InterfType.Items[0];
  while Node <> nil do
  begin
    SubNode := Node;
    Node := Node.Parent;
  end;
  //Tree_Catalog.Selected := SubNode;

  //Построить путь
  FindedNode := nil;
  RCount := Road.Count;
  //SubNode := Tree_Catalog.TopItem;
  for i := RCount - 1 downto 0 do
  begin
    ID_Catalog := PListDat(Road.Items[i]).ID;
    //Проверить, созданна ли такая папка
    isFindedNode := false;
    while SubNode <> nil do
    begin
      Dat := SubNode.Data;
      if Dat.ObjectID = ID_Catalog then
      begin
        if Not SubNode.HasChildren then
          AddNodes(SubNode);
        FindedNode := SubNode;
        if SubNode.HasChildren then
          SubNode := SubNode.getFirstChild;
        break;
      end
      else
        SubNode := SubNode.getNextSibling;
    end;
  end;
  Node := FindedNode;

  Result := Node;

  // Очистка Списка
  FreeList(Road);
end;

function TF_CaseForm.LocateItemByGUID(AGUIDItem: String): Boolean;
var
  ItemID: Integer;
begin
  Result := false;
  case TF_Main(GForm).GDBMode of
    bkNormBase:
      begin
        ItemID := TF_Main(GForm).DM.GetIntFromTableByGUID(FDirTypeInfo.TableName, fnID, GGUIDToLocate, qmPhisical);
        if ItemID > 0 then
          LocateItemByID(ItemID);
      end;
    bkProjectManager:
      begin
        if FCaseFormParams.ActiveGridDBTableView <> nil then
          if FCaseFormParams.ActiveGridDBTableView.DataController.DataSet <> nil then
            Result := FCaseFormParams.ActiveGridDBTableView.DataController.DataSet.Locate(fnGUID, AGUIDItem, []);
      end;
  end;
end;

// ##### Ищет элемент в дереве -> гриде #####
function TF_CaseForm.LocateItemByID(AIDItem: Integer): Boolean;
var
  DirType: TDirectoryType;
  //DirTypeNode: TTreeNode;
begin
  Result := false;
  //DirTypeNode := nil;

  DirType := TF_Main(GForm).DM.GetDirectoryTypeByContentItem(AIDItem, FDirTypeInfo.MasterFieldName);
  //DirTypeNode := FindNodeByID(DirType.ID);
  //if Assigned(DirTypeNode) then
  //begin
  //  Tree_InterfType.Selected := DirTypeNode;
  //  FDirTypeInfo.DataSet.Locate(fnID, AIDItem, []);
  //end;
  if SelectNodeByID(DirType.ID) then
  begin
    FDirTypeInfo.DataSet.Locate(fnID, AIDItem, []);
  end;
end;

// ##### Установит новый SORT_ID #####
function TF_CaseForm.SetSortID(ANode: TTreeNode): Integer;
var NodeData: PObjectData;
    ParentNode: TTreeNode;
    NodeID: Integer;
    ParentID: Integer;
    NewSortID: Integer;
begin
  Result := -1;
  if ANode.IsFirstNode then
    Exit;

  ParentNode := ANode.Parent;
  ParentID := PObjectData(ParentNode.Data).ObjectID;
  NodeData := ANode.Data;

  NodeID := NodeData.ObjectID;
  //with TF_Main(GForm).DM do
  //begin
    //SetSQLToQuery(scsQSelect, 'SELECT MAX(SORT_ID) as max_sort_id FROM '+tnDirectoryType+' '+
    //                          'WHERE PARENT_ID = '''+ IntTostr(ParentID) +'''');
    //NewSortID := scsQSelect.GetFNAsInteger('max_sort_id');

    NewSortID := TF_Main(GForm).DM.GetMaxSortIDFromTable(tnDirectoryType, fnParentID, fnSortID, ParentID);
    Inc(NewSortID);
    NodeData.SortID := NewSortID;

    TF_Main(GForm).DM.UpdateIntTableFieldByID(tnDirectoryType, fnSortID, NodeID, NewSortID, qmPhisical);
  //end;
end;


// ##### Перемещает папку Вверх / Вниз #####
procedure TF_CaseForm.MoveTreeNode(AMoveType: TMoveType);
var CurrNode: TTreeNode;
    PrevNode: TTreeNode;
    NextNode: TTreeNode;
    LastNode: TTreeNode;
    NextDat: PObjectData;
begin
  CurrNode := Tree_InterfType.Selected;
  if CurrNode.IsFirstNode then
  begin
    Beep;
    Exit;
  end;

  case AMoveType of
    mtUp:
      begin
        PrevNode := CurrNode.getPrevSibling;
        if PrevNode <> nil then
        begin
          CurrNode.MoveTo(PrevNode, naInsert);
          TF_Main(GForm).DM.ExchangeNodes(PrevNode, CurrNode, tkDirectoryType);
        end;
      end;
    mtDown:
      begin
        NextNode := CurrNode.getNextSibling;
        LastNode := CurrNode.Parent.GetLastChild;
        if NextNode <> nil then
        begin
          NextDat := NextNode.Data;
          if NextNode.Index < LastNode.Index then
            CurrNode.MoveTo(NextNode.GetNextVisible, naInsert)
          else
            CurrNode.MoveTo(NextNode, naAdd);
          TF_Main(GForm).DM.ExchangeNodes(NextNode, CurrNode, tkDirectoryType);
        end;
      end;
  end;
end;

procedure TF_CaseForm.SetUOMToCaptions;
var
  ActiveViewKind: TViewKind;
begin
  GT_InterfacesConstructiveWidth.Caption :=  cCaseForm_Msg39 + ', ' + GetNameUOM(TF_Main(GForm).FUOM, true);
  GT_ComponentTypesCOORDZ.Caption := cMakeEditComponentType_Msg9+', '+GetNameUOM(TF_Main(GForm).FUOM, true);
  if CheckIsMetricUOM(TF_Main(GForm).FUOM) then
  begin
    GT_SuppliesKindsNAME.DataBinding.FieldName := fnName;
    GT_SuppliesKindsIZM.DataBinding.FieldName := fnIzm;
    GT_SuppliesKindsUNIT_KOLVO.DataBinding.FieldName := fnUnitKolvo;
  end
  else
  if CheckIsTradUOM(TF_Main(GForm).FUOM) then
  begin
    GT_SuppliesKindsNAME.DataBinding.FieldName := fnNameTradUOM;
    GT_SuppliesKindsIZM.DataBinding.FieldName := fnIzmTradUOM;
    GT_SuppliesKindsUNIT_KOLVO.DataBinding.FieldName := fnUnitKolvoTradUOM;
  end;

  ActiveViewKind := GetViewKindByTabSheet(pcDirectories.ActivePage);
  case ActiveViewKind of
    vkComponentType:
      begin
        GT_ComponentTypes.DataController.UpdateItems(true);
        GT_CompTypeProp.DataController.UpdateItems(true);
      end;
    vkInterface:
      GT_Interfaces.DataController.UpdateItems(true);
    vkNetType:
      ;
    vkNorm:
      ;
    vkObjectIcons:
      ;
    vkProducers:
      ;
    vkProperty:
      GT_Properties.DataController.UpdateItems(true);
    vkResource:
      ;
    vkSuppliesKind:
      GT_SuppliesKinds.DataController.UpdateItems(true);
  end;
end;



// ####################  Обработка событий для дерева  #########################
// #############################################################################

// ##### Раскрытие ветви #####
procedure TF_CaseForm.Tree_InterfTypeExpanding(Sender: TObject;
  Node: TTreeNode; var AllowExpansion: Boolean);
begin
  AddNodes(Node);
end;


// ##### Изменение курсора ветви #####
procedure TF_CaseForm.Tree_InterfTypeChange(Sender: TObject;
  Node: TTreeNode);
var
  IDDirType: Integer;
  StrWhere: string;
begin
  try
    IDDirType := -1;
    with TF_Main(GForm).DM do
    begin
      StrWhere := '';
      //*** Учитывать скрытые интерфейсы
      if (FViewKind = vkInterface) and Not IsShowUnvisibleInterface then
        StrWhere := GetSQLForIsVisible(FDirTypeInfo.TableName);

      if Node.IsFirstNode then
      begin
        Act_DelNode.Enabled := false;
        Act_EditNode.Enabled := false;
      end
      else
      begin
        Act_DelNode.Enabled := true;
        Act_EditNode.Enabled := true;
      end;
      IDDirType := PObjectData(Node.Data).ObjectID;
      SelectDSetByDirectoryType(IDDirType, FDirTypeInfo, StrWhere);
    end;
    EnableEditDel;
  except
    on E: Exception do AddExceptionToLogExt(ClassName, MethodName(@TF_CaseForm.Tree_InterfTypeChange), E.Message);
  end;
end;


// ##### Добавить ссылку интерфейса на текущую ветвь Типов интерфейса #####
procedure TF_CaseForm.Act_AddInterfaceLinkExecute(Sender: TObject);
//var ID_TargetNode: Integer;
    //ExistingCount: Integer;
begin
    {#//*** Проверить, есть ли уде в папке такая ссылка
    ID_TargetNode := PObjectData(GTNode.Data).ObjectID;
    with TF_Main(GForm).DM do
      begin
          SetSQLToQuery(scsQ, ' SELECT COUNT(*) FROM INTERFACE_TYPE_REL ' +
                               ' WHЁERE (ID_Interface_type = '''+ IntToStr(ID_TargetNode) +''') and '+
                               '       (ID_Interface = '''+ IntToStr(FDragIDPointer) +''') '
                               );
          ExistingCount := scsQ.FN('Count').AsInteger;
          if ExistingCount > 0 then
            MessageModal(Self.Handle, 'В типе уже есть такая ссылка ', 'Добавление ссылки', MB_ICONINFORMATION or MB_OK)
          else
            begin
                TF_Main(GForm).DM.AddToInterfTypeRel(ID_TargetNode, FDragIDPointer);
                Tree_InterfType.Selected := GTNode;
                RewriteProjManTable(tkInterfaceTypeRel);
            end;
      end;#}
end;



// ##### Запомнить кнопку мыши нажатую на комплектующую #####
procedure TF_CaseForm.GT_InterfacesMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
    GMouseButtonBeforeDrag := Button;
end;


// ##### Перетаскивание интерфейса по Гриду #####
procedure TF_CaseForm.GT_InterfacesDragOver(Sender, Source: TObject; X,
  Y: Integer; State: TDragState; var Accept: Boolean);
begin
    Accept := false;
end;



// ##### Тип комоненты интерфейса #####
procedure TF_CaseForm.GT_InterfAccordance_InterfComponIslineGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
    if AText = '0' then
      AText := cCaseForm_Msg25_1;

    if AText = '1' then
      AText := cCaseForm_Msg25_2;
end;



// ##### Перетаскивание интерфейса, или папки по Дереву типов интерфейса #####
procedure TF_CaseForm.Tree_InterfTypeDragOver(Sender, Source: TObject; X,
  Y: Integer; State: TDragState; var Accept: Boolean);
var TargetNode: TTreeNode;
    SourceNode: TTreeNode;
begin
   //try
      // Скролинг дерева
  FDragIDPointer := -1;
  //ScrollTreeOnDrag(Tree_InterfType, X, Y);
  ScrollTreeOnDragByRect(Self, Tree_InterfType);

  TargetNode := nil;
  TargetNode := Tree_InterfType.GetNodeAt(X, Y);
  SourceNode := Tree_InterfType.Selected;

  ExpandCursorNodeByTimer(Self, Tree_InterfType, TargetNode, 700);
  //if WaitBeforeDragExpand(900, TargetNode) then
  //begin
  //  AddNodes(TargetNode);
  //  TargetNode.Expanded := true;
  //  Tree_InterfType.Repaint;
  //end;

  if Sender = Source then
  begin
    if TargetNode = nil then
      Accept := false
    else
    begin
      Accept := true;
      if HaveNodeSub(SourceNode, TargetNode) then
        Accept := false;
    end;
  end;

  if Sender <> Source then
    if Source is TcxDragControlObject then
    begin
      if TargetNode = nil then
        Accept := false
      else
      begin
        //if TargetNode.IsFirstNode then
        //  Accept := false
        //else
        //begin
          Accept := true;
          if FDirTypeInfo.DataSet is TpFIBDataSet then
            FDragIDPointer := TpFIBDataSet(FDirTypeInfo.DataSet).FN(fnID).AsInteger;
        //end;
      end;
    end;

  if {(SourceNode.IsFirstNode) or} (TargetNode = nil) or (TargetNode = SourceNode) then
    Accept := false;
{ except
end; }
end;

// ##### Интерфейс был кинут на дерево #####
procedure TF_CaseForm.Tree_InterfTypeDragDrop(Sender, Source: TObject; X,
  Y: Integer);
var TargetNode: TTreeNode;
    SourceNode: TTreeNode;
    CanSelectTargetNode: Boolean;
    ScrPoint: TPoint;
begin
  TargetNode := Tree_InterfType.GetNodeAt(X, Y);
  SourceNode := Tree_InterfType.Selected;
  if TargetNode = nil then
    Exit;

  //TcxDragControlObject(Source).Control
  //TcxGridSite(TcxDragControlObject(Source).Control).Owner
  //GT_Interfaces.d
  CanSelectTargetNode := false;
  if Source <> Sender then
    if Source is TcxDragControlObject then
      case GMouseButtonBeforeDrag of
        mbLeft:
          if FDragIDPointer > 0 then
          begin
            //Tree_InterfType.Selected := TargetNode;
            if CheckChange then
              MoveItemBetweenNodes(SourceNode, TargetNode, FDragIDPointer);
          end;
        mbRight:
          begin
            GSNode := SourceNode;
            GTNode := TargetNode;
            GetCursorPos(ScrPoint);
            PopupMenu_DropToInterfType.Popup(ScrPoint.X, ScrPoint.Y);
          end;
      end;

  if Source = Sender then
    MoveNodes(SourceNode, TargetNode);
end;


// ##### Перемещает интерфейс с одной  папки в другую #####
procedure TF_CaseForm.MoveItemBetweenNodes(ASrcNode, ATrgNode: TTreeNode; AID_Item: Integer);
var SrcDat: PObjectData;
    TrgDat: PObjectData;
    //strFilter: String;
    //GroupName: String;
    ItemName: String;
    IDDirectoryTypeRel: Integer;
    DirTypeWithItem: TDirectoryType;
    SrcNodeWithItem: TTreeNode;
    SavedRecNo: Integer;
    //RecCount: Integer;
begin
  if (ASrcNode = nil) or (ASrcNode.Data = nil) or (ATrgNode = nil) or (ATrgNode.Data = nil) then
    Exit; //// EXIT /////
  try
    SrcDat := ASrcNode.Data;
    TrgDat := ATrgNode.Data;

    SrcNodeWithItem := nil;
    with TF_Main(GForm).DM do
    begin
      DirTypeWithItem := GetDirectoryTypeByContentItem(AID_Item, FDirTypeInfo.MasterFieldName);
      //*** Если такая запись не была найдена, то создаем новую
      if DirTypeWithItem.ID = 0 then
        InsertToDirecoryTypeRel(TrgDat.ObjectID, AID_Item, FDirTypeInfo.MasterFieldName)
      else
      begin
        //*** Если в целевой папке уже есть такая запись, то ничего не делать
        if DirTypeWithItem.ID = TrgDat.ObjectID then
          ShowMessageByType(Self.Handle, smtDisplay, cCaseForm_Msg26_1+' "'+DirTypeWithItem.Name+'" '+cCaseForm_Msg26_2+' '+FDirTypeInfo.TableCaption+' "'+ItemName+'"',
            Application.Title, MB_ICONINFORMATION or MB_OK)
        else //*** Переместить в целевую папку
        begin
          IDDirectoryTypeRel := GetIDDirTypeRelByIDPointer(AID_Item, FDirTypeInfo.MasterFieldName);
          UpdateIntTableFieldByID(tnDirectoryTypeRel, fnIDDirectoryType, IDDirectoryTypeRel, TrgDat.ObjectID, qmPhisical);
          SrcNodeWithItem := GetNodeFromTreeByID(DirTypeWithItem.ID);
        end;
      end;

      SavedRecNo := FDirTypeInfo.DataSet.RecNo;
      FDirTypeInfo.DataSet.DisableControls;
      try
        FDirTypeInfo.DataSet.Active := false;
        FDirTypeInfo.DataSet.Active := True;
        try
          if SavedRecNo > -1 then // Tolik 28/12/2019 --
            FDirTypeInfo.DataSet.RecNo := SavedRecNo;
        except
        end;
      finally
        FDirTypeInfo.DataSet.EnableControls;
        EnableEditDel;
      end;

      //DefineTextNode(ASrcNode);
      DefineTextNode(ATrgNode);
      if Assigned(SrcNodeWithItem) then
        DefineTextNode(SrcNodeWithItem);
    end;

    (*
    with TF_Main(GForm).DM do
    begin
      GroupName := GetStringFromTableByID(tnDirectoryType, fnName, TrgDat.ObjectID, qmPhisical);
      ItemName := GetStringFromTableByID(FDirTypeInfo.TableName, fnName, AID_Item, qmPhisical);
      if GetIDDirTypeRelByParams(TrgDat.ObjectID, AID_Item, FDirTypeInfo.MasterFieldName) > 0 then
      begin
        FDirTypeInfo.DataSet.Locate(fnID, AID_Item, []);
        ShowMessageByType(Self.Handle, smtDisplay, FDirTypeInfo.TableCaption+' "'+ItemName+'" уже есть в группе "'+GroupName+'".',
          Application.Title, MB_ICONINFORMATION or MB_OK);
        //ShowMessageByType(Self.Handle, smtDisplay, 'В группе "'+GroupName+'" уже есть '+FDirTypeInfo.TableCaption+' "'+ItemName+'"',
        //  Application.Title, MB_ICONINFORMATION or MB_OK)
      end
      else
      begin
        //*** Содержиться ли пункт (интерфейс...) в какойто  директории
        IDDirectoryTypeRel := GetIDDirTypeRelByParams(SrcDat.ObjectID, AID_Item, FDirTypeInfo.MasterFieldName);

        if IDDirectoryTypeRel > 0 then
        begin
          //*** Изменяем связь
          UpdateIntTableFieldByID(tnDirectoryTypeRel, fnIDDirectoryType, IDDirectoryTypeRel, TrgDat.ObjectID, qmPhisical);
        end;

        if IDDirectoryTypeRel = 0 then
          InsertToDirecoryTypeRel(TrgDat.ObjectID, AID_Item, FDirTypeInfo.MasterFieldName);
        

        //SelectDSetByDirectoryType(TrgDat.ObjectID, FDirTypeInfo);

        {FDirTypeInfo.DataSet.DisableControls;
        try
          FDirTypeInfo.DataSet.Active := false;
          FDirTypeInfo.DataSet.Active := True;
          FDirTypeInfo.DataSet.Locate(fnID, AID_Item, []);
        finally
          FDirTypeInfo.DataSet.EnableControls;
        end;}

        DefineTextNode(ASrcNode);
        DefineTextNode(ATrgNode);
      end;
    end; *)
  except
    on E: Exception do AddExceptionToLog('TF_CaseForm.MoveInterface: '+E.Message);
  end;
end;




// ##### Добавить ветвь #####
procedure TF_CaseForm.Act_MakeNodeExecute(Sender: TObject);
var NewNode: TTreeNode;
    NewNodeName: String;

    FieldNames: TStringList;

    CurrNode: TTreeNode;
    NewNodeData: PObjectData;
    NewID: Integer;
begin
  if Not CheckChange then
    Exit; ///// EXIT /////

  CurrNode := Tree_InterfType.Selected;
  NewNodeName := InputForm(GForm, cCaseForm_Msg27_1, cCaseForm_Msg27_2,'');
  if NewNodeName <> '' then
  begin
    {FieldNames := TStringList.Create;
    try
      FieldNames.Add(fnName);
      FieldNames.Add(fnParentID);
      FieldNames.Add(fnDirItemType);
      with TF_Main(GForm).DM do
      begin
        SQLBuilder(scsQOperat, qtInsert, tnDirectoryType, '', FieldNames, false);
        scsQOperat.SetParamAsString(fnName, NewNodeName);
        scsQOperat.SetParamAsInteger(fnParentID, PObjectData(CurrNode.Data).ObjectID);
        scsQOperat.SetParamAsInteger(fnDirItemType, FDirTypeInfo.ItemType);
        scsQOperat.ExecQuery;
        NewID := GenIDFromTable(Query_Select, gnDirectoryTypeID, 0);
      end;
    finally
      FieldNames.Free;
    end; }

    NewID := TF_Main(GForm).DM.InsertDirTypeFolder(NewNodeName, FDirTypeInfo.ItemType, PObjectData(CurrNode.Data).ObjectID);

    NewNode := Tree_InterfType.Items.AddChild(CurrNode, NewNodeName);
    NewNode.ImageIndex := 0;
    NewNode.SelectedIndex := NewNode.ImageIndex;
    NewData(NewNodeData, ttGuide);

    NewNodeData.ObjectID := NewID;
    NewNode.Data := NewNodeData;
    DefineTextNode(NewNode.Parent);
    //SetSortID(NewNode);
    Tree_InterfType.Selected := NewNode;
  end;
end;

// ##### Редактировать ветвь #####
procedure TF_CaseForm.Act_EditNodeExecute(Sender: TObject);
var
  NewName: String;
  CurrName: String;
begin
  if Tree_InterfType.Selected.IsFirstNode then
    Exit;
  if Not CheckChange then
    Exit; ///// EXIT /////

  CurrName := Tree_InterfType.Selected.Text;
  CutColFromStr(CurrName);
  NewName := InputForm(GForm, cCaseForm_Msg28_1, cCaseForm_Msg28_2, CurrName);
  if NewName <> '' then
    RenameNode(Tree_InterfType.Selected, NewName);
end;

// ##### Удалить ветвь #####
procedure TF_CaseForm.Act_DelNodeExecute(Sender: TObject);
var DelName: String;
    IDDel: Integer;
    SavedOnChange: TTVChangedEvent;
    //InterfTypeRel: PDirectoryTypeRel;
    //ListItem: TListItem;
    //HaveBusyNode: Boolean;
  {
  procedure CheckNodeForBusyNode(AIDParent: Integer);
  var SubDirsID: TList;
      SubDirID: ^Integer;
      i: Integer;
  begin
    with TF_Main(GForm) do
    begin
        SetSQLToQuery(DM.scsQSelect, 'SELECT ID FROM '+tnDirectoryType+' '+
                               'WHERE PARENT_ID = '''+ IntToStr(AIDParent) +''' ');
        SubDirsID := Tlist.Create;
        DM.IntFieldToList(SubDirsID, DM.scsQSelect, fnID);
        for i := 0 to SubDirsID.Count - 1 do
        begin
          SubDirID := SubDirsID.Items[i];
          CheckNodeForBusyNode(SubDirID^);
        end;
        FreeList(SubDirsID);

        //SetSQLToQuery(DM.scsQSelect, ' SELECT ID_INTERFACE_TYPE, ID_INTERFACE, NAME FROM INTERFACE_TYPE_REL, INTERFACE '+
        //                        ' WHERE (ID_INTERFACE_TYPE = '''+ IntToStr(AIDParent) +''') AND '+
        //                        '       (ID_Interface in (Select ID_Interface from Interface_Relation)  ) and'+
        //                        '       (INTERFACE.ID = ID_INTERFACE) ');

        SetSQLToQuery(DM.scsQSelect, 'SELECT '+fnIDDirectoryType+', ID_INTERFACE, NAME FROM INTERFACE_TYPE_REL, INTERFACE '+
                                ' WHERE ('+fnIDDirectoryType+' = '''+ IntToStr(AIDParent) +''') AND '+
                                '       (ID_Interface in (Select ID_Interface from Interface_Relation)  ) and'+
                                '       (INTERFACE.ID = ID_INTERFACE) ');
        while Not DM.scsQSelect.Eof do
        begin
          ListItem := F_InputBox.ListView_Compons.Items.Add;
          ListItem.Caption := DM.scsQSelect.GetFNAsString('Name');
          ListItem.ImageIndex := -1;
          New(InterfTypeRel);
          InterfTypeRel.ID_Interface := DM.scsQSelect.GetFNAsInteger('ID_Interface');
          InterfTypeRel.ID_InterfaceType := DM.scsQSelect.GetFNAsInteger('ID_Interface_Type');
          ListItem.Data := InterfTypeRel;
          HaveBusyNode := true;
          DM.scsQSelect.Next;
        end;
    end;
  end;}

  procedure DelFolder(AID_Dir: Integer);
  var SubDirsID: TList;
      SubDirID: ^Integer;
      i: Integer;
  begin
    with TF_Main(GForm).DM do
    begin
      SetSQLToQuery(scsQ, 'SELECT ID FROM '+tnDirectoryType+' '+
                          'WHERE PARENT_ID = '''+ IntToStr(AID_Dir) +''' ');
      SubDirsID := Tlist.Create;
      IntFieldToList(SubDirsID, scsQ, fnID);
      for i := 0 to SubDirsID.Count - 1 do
      begin
        SubDirID := SubDirsID.Items[i];
        DelFolder(SubDirID^);
      end;
      FreeList(SubDirsID);

      DeleteRecordFromTableByID(tnDirectoryType, AID_Dir, qmPhisical);
      //SetSQLToQuery(scsQOperat, ' DELETE FROM INTERFACE_TYPE ' +
      //           ' WHERE ID = '''+ IntToStr(AID_Dir) +''' ');
    end;
  end;

begin
  if Not CheckChange then
    Exit; ///// EXIT /////

  DelName := Tree_InterfType.Selected.Text;
  CutColFromStr(DelName);

  with TF_Main(GForm).DM do
  begin
    IDDel := PObjectData(Tree_InterfType.Selected.Data).ObjectID;
    {HaveBusyNode := false;
    CheckNodeForBusyNode(IDDel);
    if HaveBusyNode then
      with TF_Main(GForm).F_InputBox do
      begin
          GInputFormMode := imListForTree;
          GListKind := lkBusyInterfaces;
          GTreeKind := trkGuide;

          Caption := 'Удаление типа интерфейса';
          Label_Messg.Caption := 'Нельзя удалить тип "'+ DelName +'" т.к. в нем имеются интерфейсы, которые используются: ';
          Show;
      end
    else   }

      if FDirTypeInfo.DataSet.RecordCount > 0 then
        MessageModal(cCaseForm_Msg37, ApplicationName, MB_ICONINFORMATION or MB_OK)
      else
      //if MessageModal(cQuastDelDir+' "'+ DelName +'"('+cContents+' '+FDirTypeInfo.TableCaptionPlural+' '+cCaseForm_Msg2_2+')?',
      //                cCaseForm_Msg3, MB_ICONQUESTION or MB_YESNO ) = IDYES Then
      if MessageModal(cCaseForm_Msg38+' "'+DelName+'"?', cCaseForm_Msg3, MB_ICONQUESTION or MB_YESNO ) = IDYES Then
      begin
        Tree_InterfType.Items.BeginUpdate;
        try
          SavedOnChange := Tree_InterfType.OnChange;
          Tree_InterfType.OnChange := nil;
          try
            DelFolder(IDDel);
            DeleteNode(Tree_InterfType.Selected);
          finally
            Tree_InterfType.OnChange := SavedOnChange;
            if Assigned(Tree_InterfType.OnChange) then
              Tree_InterfType.OnChange(Tree_InterfType, Tree_InterfType.Selected);
          end;
        finally
          Tree_InterfType.Items.EndUpdate;
        end;
      end;
  end;
end;



// ##### Показывает/ Закрывает панель поиска #####
procedure TF_CaseForm.Act_PanelFindExecute(Sender: TObject);
begin
  Panel_Find.Visible := Act_PanelFind.Checked;
  Splitter_GuideFind.Visible := Panel_Find.Visible;
  if Panel_Find.Visible = true then
    ButtonEdit_Find.SetFocus
  else
     //*** Очистка списка
     ClearListView(ListView_Find);
end;



// ##### Запускает поиск  #####
procedure TF_CaseForm.ButtonEdit_FindPropertiesButtonClick(Sender: TObject;
  AButtonIndex: Integer);
var IDList: TList;
    IDAndName: PIDAndName;

    i: Integer;
    LCount: Integer;
    ListItem: TListItem;
    DirectoryTypeRel: PDirectoryTypeRel;

    FindName: String;
    CurrName: String;
begin
  ListView_Find.OnChange := nil;

  ClearListView(ListView_Find);
  ButtonEdit_Find.Enabled := false;
  Gauge.Visible := true;
  Gauge.Progress := 0;

  with TF_Main(GForm).DM do
  begin
    FindName := AnsiLowerCase(ButtonEdit_Find.Text);

    SetSQLToQuery(scsQ, ' SELECT ID, NAME FROM '+FDirTypeInfo.TableName+' ');

    IDList := TList.Create;
    while Not scsQ.Eof do
    begin
      CurrName := AnsiLowerCase(scsQ.GetFNAsString('Name'));
      if Pos(FindName, CurrName) <> 0 then
      begin
        GetMem(IDAndName, SizeOf(TIDAndName));
        IDAndName.ID := scsQ.GetFNAsInteger('ID');
        IDAndName.NAME := scsQ.GetFNAsString('Name');
        IDList.Add(IDAndName);
      end;
      scsQ.Next;
    end;

    LCount := IDList.Count;
    for i := 0 to LCount - 1 do
    begin
      IDAndName := IDList.Items[i];
      SetSQLToQuery(scsQ, ' SELECT * FROM '+tnDirectoryTypeRel+' '+
                           ' WHERE '+FDirTypeInfo.MasterFieldName+' = '''+ IntToStr(IDAndName.ID) +''' '
                           );
      while Not scsQ.Eof do
      begin
        ListItem := ListView_Find.Items.Add;
        ListItem.Caption := IDAndName.NAME;
        GetMem(DirectoryTypeRel, SizeOf(TDirectoryTypeRel)); //New(InterfTypeRel);
        DirectoryTypeRel.ID_Pointer := scsQ.GetFNAsInteger(FDirTypeInfo.MasterFieldName);
        DirectoryTypeRel.ID_DirecoryType := scsQ.GetFNAsInteger(fnIDDirectoryType);
        ListItem.Data := DirectoryTypeRel;
        scsQ.Next;
      end;
      Gauge.Progress := Round(i / LCount * 100);
    end;
    FreeList(IDList);
  end;

  Gauge.Visible := false;
  ButtonEdit_Find.Enabled := true;
  ListView_Find.OnChange := ListView_FindChange;
end;

// ##### Нажат Enter ####
procedure TF_CaseForm.ButtonEdit_FindKeyPress(Sender: TObject;
  var Key: Char);
begin
    Button_Ok.Default := false;
    if Key = #13 then
      begin
          ButtonEdit_FindPropertiesButtonClick(Self, 0);
          Key := #0;
      end;
    Button_Ok.Default := true;
end;



// ##### Перемещение по найденному списку #####
procedure TF_CaseForm.ListView_FindChange(Sender: TObject; Item: TListItem;
  Change: TItemChange);
var Node: TTreeNode;
    DirectoryTypeRel: PDirectoryTypeRel;
begin
  if Item <> nil then
  begin
    DirectoryTypeRel := Item.Data;
    Node := nil;
    Node := FindNodeByID(DirectoryTypeRel.ID_DirecoryType);
    if Node <> nil then
    begin
      Tree_InterfType.Selected := Node;
      FDirTypeInfo.DataSet.Locate(fnID, DirectoryTypeRel.ID_Pointer, []);
      //SearchRecord(TF_Main(GForm).DM.DataSet_INTERFACE, 'ID', InterfTypeRel.ID_Interface);
    end;
  end;
end;



// ##### Разворачивает дерево #####
procedure TF_CaseForm.Act_ExpandTreeExecute(Sender: TObject);
begin
  //ExpandTree(GForm, ttGuide);
  ExpandNode(Tree_InterfType.Selected, true);
end;


// ##### Сворачивает дерево #####
procedure TF_CaseForm.Act_CollapseTreeExecute(Sender: TObject);
begin
  //CollapseTree(GForm, ttGuide);
  CollapseNode(Tree_InterfType.Selected, true);
end;


// ##### Переместит папку вниз #####
procedure TF_CaseForm.Act_MoveNodeDownExecute(Sender: TObject);
begin
  if Not CheckChange then
    Exit; ///// EXIT /////
  MoveTreeNode(mtDown);
end;

// ##### Переместит папку вверх #####
procedure TF_CaseForm.Act_MoveNodeUpExecute(Sender: TObject);
begin
  if Not CheckChange then
    Exit; ///// EXIT /////
  MoveTreeNode(mtUp);
end;



// ##### Устаговлен фокус на дерево #####
procedure TF_CaseForm.Tree_InterfTypeEnter(Sender: TObject);
begin
    {Act_MakeNode.ShortCut := ShortCut(VK_INSERT, []);
    Act_EditNode.ShortCut := ShortCut(VK_F2, []);
    Act_DelNode.ShortCut := ShortCut(VK_DELETE, []);

    Act_Make.ShortCut := ShortCut(VK_NONAME, []);
    Act_Edit.ShortCut := ShortCut(VK_NONAME, []);
    Act_Del.ShortCut := ShortCut(VK_NONAME, []);}
end;


// ##### Установлен фокус на Грид #####
procedure TF_CaseForm.Panel_DataEnter(Sender: TObject);
begin
    {Act_Make.ShortCut := ShortCut(VK_INSERT, []);
    Act_Edit.ShortCut := ShortCut(VK_F2, []);
    Act_Del.ShortCut := ShortCut(VK_DELETE, []);

    Act_MakeNode.ShortCut := ShortCut(VK_NONAME, []);
    Act_EditNode.ShortCut := ShortCut(VK_NONAME, []);
    Act_DelNode.ShortCut := ShortCut(VK_NONAME, []);}
end;


// ##### Установлен фокус на ButtonEdit_Find #####
procedure TF_CaseForm.ButtonEdit_FindEnter(Sender: TObject);
begin
    {Act_MakeNode.ShortCut := ShortCut(VK_NONAME, []);
    Act_EditNode.ShortCut := ShortCut(VK_NONAME, []);
    Act_DelNode.ShortCut := ShortCut(VK_NONAME, []);

    Act_Make.ShortCut := ShortCut(VK_NONAME, []);
    Act_Edit.ShortCut := ShortCut(VK_NONAME, []);
    Act_Del.ShortCut := ShortCut(VK_NONAME, []); }
end;


function TF_CaseForm.CheckNoUseCompData(ASql, ADelName: String; AMakeEdit: TMakeEdit;
  ATableKind: TTableKind; AMessType: TShowMessageType; ANeedAnsw: boolean = True): Boolean;
const gdHe = 0;
      gdIt = 1;

var prToDel: String;
    prDeling: String;
    prActToB: String;
    prActIng: String;
    prHeIt: String;
    WhoDel: Integer;
    CheckForm: Boolean;

  function CheckForForm(AForm: TForm): Boolean;
  begin
    Result := false;
    SetSQLToQuery(TF_Main(AForm).DM.scsQ, ASql);
    if TF_Main(AForm).DM.scsQ.RecordCount = 0 then
      Result := true
    else
    if AMessType = smtDisplay then
      ShowList(AForm, trkCatalog,  FFormMode, cCaseForm_Msg4_1+' '+ AnsiLowerCase(prActToB) +' '+ prToDel +' "' + ADelName +'"' + #13 +
              cCaseForm_Msg4_2+' '+ prHeIt +' '+cCaseForm_Msg4_3+':', false);
  end;

begin
  Result := false;
  try
    WhoDel := gdIt;

    prActToB := '';
    prActIng := '';

    case AMakeEdit of
      meEdit:
        begin
          prActToB := cCaseForm_Msg4_4_1;
          prActIng := cCaseForm_Msg4_4_2;
        end;
      meDel:
        begin
          prActToB := cCaseForm_Msg4_4_3;
          prActIng := cCaseForm_Msg4_4_4;
        end;
    end;

    case ATableKind of
      tkProperty:
        begin
          prToDel := cCaseForm_Msg4_4_5;
          prDeling := cCaseForm_Msg4_4_6;
          WhoDel := gdIt;
        end;

      tkInterface:
        begin
          prToDel := cCaseForm_Msg4_4_7;
          prDeling := cCaseForm_Msg4_4_8;
          WhoDel := gdHe;
        end;

      tkNetType:
        begin
          prToDel := cCaseForm_Msg4_4_9;
          prDeling := cCaseForm_Msg4_4_10;
          WhoDel := gdHe;
        end;

      tkComponentTypes:
        begin
          prToDel := cCaseForm_Msg4_4_11;
          prDeling := cCaseForm_Msg4_4_12;
          WhoDel := gdHe;
        end;

      tkProducers:
        begin
          prToDel := cCaseForm_Msg4_4_13;
          prDeling := cCaseForm_Msg4_4_14;
          WhoDel := gdHe;
        end;

      tkCompStateType:
        begin
          prToDel := cCaseForm_Msg4_4_15;
          prDeling := cCaseForm_Msg4_4_16;
          WhoDel := gdHe;
        end;
      tkObjectIcon:
        begin
          prToDel := cCaseForm_Msg4_4_17;
          prDeling := cCaseForm_Msg4_4_18;
          WhoDel := gdIt;
        end;
      tkSuppliesKind:
        begin
          prToDel := cCaseForm_Msg4_4_19;
          prDeling := cCaseForm_Msg4_4_20;
          WhoDel := gdHe;
        end;
    end;

    case WhoDel of
      gdHe: prHeIt := cCaseForm_Msg4_5_1;
      gdIt: prHeIt := cCaseForm_Msg4_5_2;
    end;

    CheckForm := CheckForForm(F_NormBase);
    //if CheckForm then
    //  CheckForm := CheckForForm(F_ProjMan);

    if CheckForm then
    begin
     if AMakeEdit = meDel then
     begin
       if ANeedAnsw then
       begin
         if MessageModal(prActToB +' '+ prToDel +' "' + ADelName +'" ?',
                         prActIng +' '+ prDeling,
                         MB_YESNO or MB_ICONQUESTION) = IDYES then
           Result := true;
       end
       else
         Result := true;
     end
     else
       Result := true;
    end;
  except
    on E: Exception do AddExceptionToLog('TF_CaseForm.CheckNoUseCompData: '+E.Message);
  end;
end;



// ######################  Ресурсы и трудозатраты  #############################
// #############################################################################
//
// ##### Добавляет / изменяет норму #####
procedure TF_CaseForm.AddEditResource(AMakeEdit: TMakeEdit);
var ResourcesForm: TF_CaseForm;
    ResourcesFormMode: TFormMode;
    //ModRes: TModalResult;
    qSQL: String;
    ID_ResourceRel: Integer;
    ID_Resource: Integer;
begin
    ID_ResourceRel := -1;
    ID_Resource := -1;

    ResourcesFormMode := fmNone;
    ResourcesForm := TF_CaseForm.Create(Owner, GForm, nil, itNone);
    //ResourcesForm.FViewKind := vkResource;
    case AMakeEdit of
     meMake : ResourcesFormMode := fmMake;
     meEdit:
        begin
            ResourcesFormMode := fmEdit;
            ID_ResourceRel := F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.FN('ID').AsInteger;
            ID_Resource := F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.FN('ID_NB_Resource').AsInteger;
            ResourcesForm.SpinEdit_Kolvo.Value := RoundX(F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.FN('KOLVO').AsFloat, 10);
            //ResourcesForm.SpinEdit_Kolvo.Value := F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.FN('KOLVO').AsFloat;

            ResourcesForm.GIDToLocate := ID_Resource;
            //DataSetLocateByID(F_NormBase.DM.DataSet_NB_RESOURCES, ID_Resource);
            //SearchRecord(F_NormBase.DM.DataSet_NB_RESOURCES, fnID, ID_Resource);
        end;
    end;
    ResourcesForm.GValue := IntToStr(ID_Resource);
    //ModRes := ResourcesForm.ShowModal;

    //if ModRes = mrOK then
    if ResourcesForm.Execute(vkResource, ResourcesFormMode) then
      with F_NormBase.DM.scsQOperat do
        begin
            case AMakeEdit of
              meMake: qSQL := ' insert into nb_norm_resource_rel (id_nb_norm, id_nb_resource, kolvo) '+
                              ' values (:id_nb_norm, :id_nb_resource, :kolvo) ';
              meEdit: qSQL := ' update nb_norm_resource_rel set id_nb_norm = :id_nb_norm, id_nb_resource = :id_nb_resource, kolvo= :kolvo '+
                              ' where id = '''+ IntToStr(ID_ResourceRel)+''' ';
            end;

            Close;
            SQL.Clear;
            SQL.Add(qSQL);
            SetParamAsInteger('id_nb_norm', F_NormBase.DM.DataSet_NB_NORMS.FN('id').AsInteger);
            SetParamAsInteger('id_nb_resource', F_NormBase.DM.DataSet_NB_RESOURCES.FN('id').AsInteger);
            //ParamByName('ison').AsInteger := 1;
            SetParamAsFloat('kolvo', ResourcesForm.SpinEdit_Kolvo.Value);
            ExecQuery;
            Close;

            case AMakeEdit of
              meMake:
                  begin
                      F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.Active := false;
                      F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.Active := true;
                      F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.Last;
                  end;
              {meEdit:
                  F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.Refresh;}
            end;
        end;
    F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.Refresh;
    FreeAndNil(ResourcesForm);
end;


procedure TF_CaseForm.AddEditCompTypeProperty(AMakeEdit: TMakeEdit);
var
  CurrCompTypeID: Integer;
  PropFromTable: TProperty;
  DataSet: TDataSet;
  DataSource: TDataSource;
begin
  ZeroMemory(@PropFromTable, SizeOf(TProperty));
  try
    with TF_Main(GForm) do
    begin
      CurrCompTypeID := -1;
      DataSet := nil;
      DataSource := nil;
      if mtCompTypePropRelation <> nil then
      begin
        CurrCompTypeID := mtComponentType.FieldByName(fnID).AsInteger;
        DataSet := mtCompTypePropRelation;
        DataSource := dsCompTypePropRelation;
      end
      else
      begin
        CurrCompTypeID := DM.DataSet_COMPONENT_TYPES.FN(fnID).AsInteger;
        DataSet := DM.DataSet_COMP_TYPE_PROP_RELATION;
        DataSource := DM.DataSource_comp_type_prop_relation;

        if FShowedTables.IndexOf(Ord(vkProperty)) <> -1 then
          GSCSBase.NBSpravochnik.LoadProperties;
      end;

      if AMakeEdit = meEdit then
        PropFromTable := DM.GetPropertyFromTable(DataSource);
      if CreateFMakeEditPropRel.Execute(AMakeEdit, tkCompTypePropRelation, @PropFromTable, DataSet, itNone, MemTableProperties, nil) then
      begin
        PropFromTable.IDMaster := CurrCompTypeID;

        case AMakeEdit of
          meMake:
            DataSet.Append;
          meEdit:
            DataSet.Edit;
        end;
        if DataSet.State <> dsBrowse then
        begin
          DM.SetPropertyToTable(DataSource, PropFromTable);

          if mtCompTypePropRelation <> nil then
          begin
            DataSet.FieldByName(fnGuid).AsString := CreateGUID;
            DataSet.FieldByName(fnIDComponentType).AsInteger := CurrCompTypeID;
            DataSet.FieldByName(fnGuidComponentType).AsString := mtComponentType.FieldByName(fnGUID).AsString;
            if AMakeEdit = meEdit then
              DataSet.FieldByName(fnIsModified).AsBoolean := true;
          end
          else
            TpFIBDataSet(DataSet).FN(fnIDComponentType).AsInteger := CurrCompTypeID;
          DataSet.Post;
        end;
      end;
    end;
  except
    on E: Exception do AddExceptionToLog('TF_CaseForm.AddEditCompTypeProperty: '+E.Message);
  end;


    {PropFormMode := fmNone;
    PropertyForm := TF_CaseForm.Create(GForm, GForm);
    try
      try
        with TF_Main(GForm).DM do
          begin
              case AMakeEdit of
                meMake:
                    PropFormMode := fmMake;
                meEdit:
                    begin
                        IDProperty := DataSet_COMP_TYPE_PROP_RELATION.FN('ID_PROPERTY').AsInteger;
                        PName := DataSet_COMP_TYPE_PROP_RELATION.FN('NAME').AsString;
                        if DataSet_COMP_TYPE_PROP_RELATION.FN('ISSTANDART').AsInteger = biTrue then
                          begin
                              MessageModal('Свойство "'+ PName +'" является стандартным и не может быть изменено.',
                                  'Изменение свойства типа компоненты', MB_ICONINFORMATION or MB_OK);
                              Exit; ////// EXIT //////
                          end;

                        PropFormMode := fmEdit;
                        PropertyForm.GIDToLocate := IDProperty;
                        PropertyForm.GValue := DataSet_COMP_TYPE_PROP_RELATION.FN('PVALUE').AsString;
                        PropertyForm.GTakeIntoConnect := DataSet_COMP_TYPE_PROP_RELATION.FN('TAKE_INTO_CONNECT').AsInteger;
                        PropertyForm.GTakeIntoJoin := DataSet_COMP_TYPE_PROP_RELATION.FN('TAKE_INTO_JOIN').AsInteger;
                    end;
              end;

              //PropertyForm.GViewKind := vkProperty;
              if DataSet_COMPONENT_TYPES.FN(fnIsLine).AsInteger = biTrue then
                PropertyForm.GItemType := itComponLine;
              if DataSet_COMPONENT_TYPES.FN(fnIsLine).AsInteger = biFalse then
                PropertyForm.GItemType := itComponCon;

              //PropertyForm.GItemType := itComponent;
              //ModRes := PropertyForm.ShowModal;
              //if ModRes = mrOk then
              if PropertyForm.Execute(vkProperty, PropFormMode) then
                begin
                    //*** Проверить, существует ли такое свойство для даного типа компоненты
                    SetSQLToQuery(scsQSelect, 'select count(id) from '+tnCompTypePropRelation+ ' '+
                                              'where ('+fnIDComponentType+' = '''+intToStr(DataSet_COMPONENT_TYPES.FN('ID').AsInteger)+''') and '+
                                                    '('+fnIDProperty+' = '''+intToStr(DataSet_PROPERTIES.FN('ID').AsInteger)+''' )');
                    if (AMakeEdit = meMake) and (scsQSelect.GetFNAsInteger(fnCount) > 0) then
                      ShowMessageByType(Self.Handle, smtDisplay, 'Свойство '+DataSet_PROPERTIES.FN(fnName).AsString+' уже существует.', Application.Title, MB_ICONINFORMATION or MB_OK)
                    else
                      begin
                          DataSet_COMP_TYPE_PROP_RELATION.DisableControls;
                          GT_CompTypeProp.DataController.DataSource := nil;
                          try
                            if AMakeEdit = meMake then
                            begin
                              DataSet_COMP_TYPE_PROP_RELATION.Last;
                              DataSet_COMP_TYPE_PROP_RELATION.Append;
                            end
                            else
                              DataSet_COMP_TYPE_PROP_RELATION.Edit;
                            DataSet_COMP_TYPE_PROP_RELATION.FN('ID_COMPONENT_TYPE').AsInteger := DataSet_COMPONENT_TYPES.FN('ID').AsInteger;
                            DataSet_COMP_TYPE_PROP_RELATION.FN('ID_PROPERTY').AsInteger := DataSet_PROPERTIES.FN('ID').AsInteger;
                            DataSet_COMP_TYPE_PROP_RELATION.FN('PVALUE').AsString := PropertyForm.GValue;
                            DataSet_COMP_TYPE_PROP_RELATION.FN('TAKE_INTO_CONNECT').AsInteger := PropertyForm.GTakeIntoConnect;
                            DataSet_COMP_TYPE_PROP_RELATION.FN('TAKE_INTO_JOIN').AsInteger := PropertyForm.GTakeIntoJoin;
                            DataSet_COMP_TYPE_PROP_RELATION.FN('ISSTANDART').AsInteger := biFalse;
                            DataSet_COMP_TYPE_PROP_RELATION.Post;
                            //DataSet_COMP_TYPE_PROP_RELATION.Refresh;
                            //DataSet_COMP_TYPE_PROP_RELATION.Refresh
                            //DataSet_COMP_TYPE_PROP_RELATION.Active := false;
                            //DataSet_COMP_TYPE_PROP_RELATION.Active := true;
                          finally
                            DataSet_COMP_TYPE_PROP_RELATION.EnableControls;
                            DataSet_COMP_TYPE_PROP_RELATION.Refresh;
                            DataSet_COMPONENT_TYPES.Refresh;
                            GT_CompTypeProp.DataController.DataSource := DataSource_comp_type_prop_relation;
                          end;
                      end;
                end;
          end;
      except
        on E: Exception do AddExceptionToLog('TF_CaseForm.AddEditСompTypeProperty: '+E.Message);
      end;
    finally
      FreeAndNil(PropertyForm);
    end; }
end;

            {
// ##### Распарсить не привязанные к группам элементы #####
procedure TF_CaseForm.ParseNoWithGroupItems;
var
  IDList: TList;
  TopDat: PObjectData;
  i: Integer;
  ItemID: Integer;
begin
  //FDirTypeInfo.
  IDList := TList.Create;
  try
    with F_NormBase.DM do
    begin
      SetSQLToQuery(scsQSelect, 'select id from '+FDirTypeInfo.TableName+' '+
                                'where Not(id in (select '+FDirTypeInfo.MasterFieldName+' from '+tnDirectoryTypeRel+'))');
      IntFieldToList(IDList, scsQSelect, fnID);

      //*** Засунуть записи  в верхнюю папку
      TopDat := Tree_InterfType.Items[0].Data;
      for i := 0 to IDList.Count - 1 do
      begin
        ItemID := Integer(IDList[i]^);
        InsertToDirecoryTypeRel(TopDat.ObjectID, ItemID, FDirTypeInfo.MasterFieldName);
      end;
    end;
  finally
    FreeList(IDList);
  end;
end;   }

procedure TF_CaseForm.AddEditInterfData(AFormMode: TFormMode);
var
  InterfID: Integer;
  InterfGUID: String;
begin
  InterfID := -1;
  InterfGUID := '';
  with TF_Main(GForm) do
  begin
    if mtInterface <> nil then
    begin
      InterfID := mtInterface.FieldByName(fnID).AsInteger;
      InterfGUID := mtInterface.FieldByName(fnGUID).AsString;
    end
    else
    begin
      InterfID := DM.DataSet_INTERFACE.FN(fnID).AsInteger;
      InterfGUID := DM.DataSet_INTERFACE.FN(fnGUID).AsString;
    end;

    if PageControl_InterfData.ActivePage = tsInterfaceNorms then
      CreateFMakeEditInterfNorm.MakeEdit(AFormMode, InterfGUID, InterfID, mtInterfaceNorms, mtNorms, MemTableComponTypes)
    else
    if PageControl_InterfData.ActivePage = tsInterfAccordance then
      CreateFMakeEditInterfaceAccordance.MakeEdit(AFormMode, mtInterfaceAccordance, mtInterface);
  end;
  if AFormMode = fmMake then
    EnableEditDelInterfData;
end;


// ##### Добавить ресурс в норму #####
procedure TF_CaseForm.Act_AddResourceRelExecute(Sender: TObject);
begin
    AddEditResource(meMake);
    EnableEditDelResourceRel;
end;

// ##### Изменить ресурс в норме #####
procedure TF_CaseForm.Act_EditResourceRelExecute(Sender: TObject);
begin
    AddEditResource(meEdit);
end;

// ##### Удалить ресурс из нормы #####
procedure TF_CaseForm.Act_DelResourceRelExecute(Sender: TObject);
var DelName: String;
begin
    try
      DelName := F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.FN('Name').AsString;
      if MessageModal(cCaseForm_Msg5_1+' "'+ DelName +'" '+cCaseForm_Msg5_2+'?',
                    cCaseForm_Msg5_3, MB_ICONQUESTION or MB_YESNO) = IDYES then
        begin
            F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.Delete;
            EnableEditDelResourceRel;
        end;
    except
      on E: Exception do AddExceptionToLog('TF_CaseForm.Act_DelResourceRelExecute: '+E.Message);
    end;
end;





// ##### Создать ресурс #####
procedure TF_CaseForm.Act_MakeResourceExecute(Sender: TObject);
begin
    //
end;


// ##### Изменить ресурс #####
procedure TF_CaseForm.Act_EditResourceExecute(Sender: TObject);
begin
    //
end;


// ##### Удалить ресурс #####
procedure TF_CaseForm.Act_DelResourceExecute(Sender: TObject);
begin
    //
end;





// ##### Создать трудозатрату #####
procedure TF_CaseForm.Act_MakeTZExecute(Sender: TObject);
begin
    //
end;


// ##### Изменить трудозатрату #####
procedure TF_CaseForm.Act_EditTZExecute(Sender: TObject);
begin
    //
end;


// ##### Удалить трудозатрату #####
procedure TF_CaseForm.Act_DelTZExecute(Sender: TObject);
begin
    //
end;


// ##### Перемещение по нормам #####
procedure TF_CaseForm.GT_NB_NormsFocusedRecordChanged(
  Sender: TcxCustomGridTableView; APrevFocusedRecord,
  AFocusedRecord: TcxCustomGridRecord;
  ANewItemRecordFocusingChanged: Boolean);
begin
  EnableEditDelResourceRel;
end;



// ##### Нажатие на гриде #####
procedure TF_CaseForm.GT_NB_NormResourceRelCellClick(
  Sender: TcxCustomGridTableView;
  ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
  AShift: TShiftState; var AHandled: Boolean);
var fldIsOn: Integer;
begin
    with TF_Main(GForm).DM do
      try
        try
          if ACellViewInfo.Item.Index = 0 then  //*** Поле "Включен"
            begin
                //RecordNo := MemTable_ResourcesRel.RecNo;
                fldIsOn := DataSet_NB_NORM_RESOURCE_REL.FN('IsOn').AsInteger;
                DataSet_NB_NORM_RESOURCE_REL.Edit;
                DataSet_NB_NORM_RESOURCE_REL.FN('IsOn').AsInteger := 1 - fldIsOn;
                DataSet_NB_NORM_RESOURCE_REL.Post;
                AHandled := true;
            end;
          except
            on E: Exception do AddExceptionToLog('TF_CaseForm.GT_NB_NormResourceRelCellClick: '+E.Message);
          end;
      finally
        //MemTable_ResourcesRel.RecNo := RecordNo;
      end;
end;



procedure TF_CaseForm.GT_NB_NormResourceRelEditValueChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
begin
    //GT_NB_NormResourceRel.DataController
    {GT_NB_NormResourceRel.DataController.UpdateData;
    F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.UpdateRecord;
    F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.Next;
    F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL.Prior;
    GT_NB_NormResourceRel.DataController.Post; }
    //Beep;
    //if AItem.Index = 0 then
    //  GT_NB_NormResourceRel.DataController.Post;
    //GT_NB_NormResourceRel.DataController.Post;
end;

procedure TF_CaseForm.GT_NB_NormResourceRelPRICEPropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
//var cost, price, AdditionalPrice, kolvo: Double;
begin     {
    Error := false;
    with F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL do
      begin
          price := DisplayValue;
          AdditionalPrice := FN(fnAdditionalPrice).AsFloat;
          kolvo := FN(fnKolvo).AsFloat;
          cost := (price + AdditionalPrice) * kolvo;

          Edit;
          FN(fnCost).AsFloat := cost;
          FN(fnPrice).AsFloat := DisplayValue;
          Post;
      end;  }
end;

procedure TF_CaseForm.GT_NB_NormResourceRelAdditionalPricePropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
//var cost, price, kolvo: Double;
begin     {
    Error := false;
    with F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL do
      begin
          price := FN('Price').AsFloat;
          kolvo := DisplayValue; //MemTable_ResourcesRel.FieldByName('kolvo').AsInteger;
          cost := price * kolvo;
          Edit;
          FN('COST').AsFloat := cost;
          FN('Kolvo').AsFloat := DisplayValue;
          Post;
      end;  }
end;

procedure TF_CaseForm.GT_NB_NormResourceRelKOLVOPropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
//var cost, price, kolvo: Double;
begin      {
    Error := false;
    with F_NormBase.DM.DataSet_NB_NORM_RESOURCE_REL do
      begin
          price := FN('Price').AsFloat;
          kolvo := DisplayValue; //MemTable_ResourcesRel.FieldByName('kolvo').AsInteger;
          cost := price * kolvo;
          Edit;
          FN('COST').AsFloat := cost;
          FN('Kolvo').AsFloat := DisplayValue;
          Post;
      end;     }
end;




// ##### Изменение позиции типа компоненты #####
procedure TF_CaseForm.GT_ComponentTypesFocusedRecordChanged(
  Sender: TcxCustomGridTableView; APrevFocusedRecord,
  AFocusedRecord: TcxCustomGridRecord;
  ANewItemRecordFocusingChanged: Boolean);
begin
  EnableEditCompTypeProperties;
end;


procedure TF_CaseForm.GT_ComponentTypesPortKindGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
    if AText = '0' then
      AText := cCaseForm_Msg29_1;
    if AText = '1' then
      AText := cCaseForm_Msg29_2;
end;

procedure TF_CaseForm.GT_ComponentTypesActiveStateGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
    if AText = '0' then
      AText := cCaseForm_Msg30_1;
    if AText = '1' then
      AText := cCaseForm_Msg30_2;
end;

procedure TF_CaseForm.GT_ComponentTypesIsLineGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
    if AText = '0' then
      AText := cCaseForm_Msg31_1;
    if AText = '1' then
      AText := cCaseForm_Msg31_2;
end;

procedure TF_CaseForm.GT_CompTypePropPVALUEGetProperties(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AProperties: TcxCustomEditProperties);
begin
  if ARecord.Values[6] <> null then
    with TF_Main(GForm).DM do
    begin
      case ARecord.Values[6] of
        dtFloat, dtInteger:
          AProperties := EditRepositorySpinItem.Properties;
        dtBoolean:
          AProperties := EditRepositoryCheckBoxItem.Properties;
        dtDate:
          AProperties := EditRepositoryDateItem.Properties;
        dtCompStateType:
          AProperties := EditRepositoryLookupCompSateType.Properties;
        dtColor:
          AProperties := EditRepositoryColorComboBox.Properties;
        dtCableCanalElementType:
          AProperties := EditRepositoryLookupCableCanalElementType.Properties;
      end;
    end;
end;

procedure TF_CaseForm.GT_CompTypePropPVALUEGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
//var
//  CurrFloat: Double;
  var DoSetDisplay: boolean; // IGOR 04/07/2019 --
begin
   // IGOR 04/07/2019 --
  DoSetDisplay := True;
  if ARecord.Values[6] <> null then
  begin
    if (ARecord.Values[6] = dtBoolean) or (ARecord.Values[6] = dtCompStateType)
      or (ARecord.Values[6] = dtColor) or (ARecord.Values[6] = dtCableCanalElementType) then
      DoSetDisplay := False;
  end;
  if DoSetDisplay then
  //
    SetDisplayTextToGridTablePropValue(AText, ARecord, 6, 7, TF_Main(GForm).FUOM);
  {if ARecord.Values[6] <> null then
    case ARecord.Values[6] of
      dtFloat:
        try
          CurrFloat := StrToFloatU(AText);
          if GPropSysNameInUOM.IndexOf(ARecord.Values[7]) <> -1 then
            CurrFloat := RoundCP(FloatInUOM(CurrFloat, umMetr, TF_Main(GForm).FUOM));
          AText := FloatToStr(CurrFloat);
        except
        end;
      dtDate:
        try
          AText := DateToStr(StrToDateU(AText));
        except
        end;
    end;}
end;

procedure TF_CaseForm.Act_AddCompTypePropertyExecute(Sender: TObject);
begin
  if Not CheckChange then
    Exit; ///// EXIT /////
  AddEditCompTypeProperty(meMake);
  EnableEditCompTypeProperties;
end;

procedure TF_CaseForm.Act_EditCompTypePropertyExecute(Sender: TObject);
begin
  if Not CheckChange then
    Exit; ///// EXIT /////
  AddEditCompTypeProperty(meEdit);
end;

procedure TF_CaseForm.Act_DelCompTypePropertyExecute(Sender: TObject);
var DelName: String;
    IsStandart: Integer;
    MemTable: TkbmMemTable;
begin
  if Not CheckChange then
    Exit; ///// EXIT /////
  try
    MemTable := mtCompTypePropRelation;
    with TF_Main(GForm).DM do
    begin
      DelName := '';
      IsStandart := biFalse;
      if MemTable <> nil then
      begin
        DelName := MemTable.FieldByName(fnName).AsString;
        IsStandart := MemTable.FieldByName(fnisStandart).AsInteger;
      end
      else
      begin
        DelName := DataSet_COMP_TYPE_PROP_RELATION.FN(fnName).AsString;
        IsStandart := DataSet_COMP_TYPE_PROP_RELATION.FN(fnisStandart).AsInteger;
      end;
      if IsStandart = biTrue then
        MessageModal(cCaseForm_Msg6_1+' "'+ DelName +'" '+cCaseForm_Msg6_2,
            cCaseForm_Msg6_3, MB_ICONINFORMATION or MB_OK)
      else
      begin
        if MessageModal(cCaseForm_Msg7_1+' "'+ DelName +'" ?',
            cCaseForm_Msg7_2, MB_ICONQUESTION or MB_YESNO) = ID_YES then
        begin
          if MemTable <> nil then
            MemTable.Delete
          else
            DataSet_COMP_TYPE_PROP_RELATION.Delete;
          EnableEditCompTypeProperties;
        end;
      end;
    end;
  except
    on E: Exception do AddExceptionToLog('TF_CaseForm.Act_DelCompTypePropertyExecute: '+E.Message);
  end;
end;

procedure TF_CaseForm.Timer_PostGridRecordTimer(Sender: TObject);
begin
    //if GGridDBTable <> nil then
    //  GGridDBTable.DataController.Post;
    //TTimer(Sender).Enabled := false;
end;

procedure TF_CaseForm.GT_CompTypePropEditValueChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
begin
    //GGridDBTable := Sender;
    //Timer_PostGridRecord.Enabled := true;
end;

procedure TF_CaseForm.Panel_OkCancelResize(Sender: TObject);
begin
  SetMiddleControlChilds(TControl(Sender), TControl(Self));
end;


// ##### Создать данные интерфейсов #####
procedure TF_CaseForm.Act_AddInterfDataExecute(Sender: TObject);
begin
  if Not CheckChange then
    Exit; ///// EXIT /////
  AddEditInterfData(fmMake);
end;

// ##### Редактировать данные интерфейсов #####
procedure TF_CaseForm.Act_EditInterfDataExecute(Sender: TObject);
begin
  if Not CheckChange then
    Exit; ///// EXIT /////
  AddEditInterfData(fmEdit);
end;

// ##### Удалить данные интерфейсов #####
procedure TF_CaseForm.Act_DelInterfDataExecute(Sender: TObject);
var DelDataSet: TpFIBDataSet;
    DelName: String;
    MemTable: TkbmMemTable;
begin
  if Not CheckChange then
    Exit; ///// EXIT /////

  DelDataSet := nil;
  DelName := '';
  MemTable := nil;
  with TF_Main(GForm).DM do
  begin
    if PageControl_InterfData.ActivePage = tsInterfaceNorms then
    begin
      DelDataSet := DataSet_Interface_Norms;
      DelName := cCaseForm_Msg8_2_1;
      MemTable := mtInterfaceNorms;
    end;
    if PageControl_InterfData.ActivePage = tsInterfAccordance then
    begin
      DelDataSet := DataSet_InterfAccordance;
      DelName := cCaseForm_Msg8_2_2;
      MemTable := mtInterfaceAccordance;
    end;
  end;

  if Assigned(DelDataSet) then
  begin
    if MessageModal(cCaseForm_Msg8_1+' '+DelName+'?', cCaseForm_Msg8_2_3, MB_YESNO or MB_ICONQUESTION) = IDYES then
    begin
      if MemTable <> nil then
        MemTable.Delete
      else
        DelDataSet.Delete;
    end;
  end;
  EnableEditDelInterfData;
end;

procedure TF_CaseForm.PageControl_InterfDataChange(Sender: TObject);
begin
  if PageControl_InterfData.ActivePage = tsInterfaceNorms then
  begin
    Act_AddInterfData.Caption := cCaseForm_Msg32_1;
    Act_EditInterfData.Caption := cCaseForm_Msg32_2;
    Act_DelInterfData.Caption := cCaseForm_Msg32_3;
  end;

  if PageControl_InterfData.ActivePage = tsInterfAccordance then
  begin
    Act_AddInterfData.Caption := cCaseForm_Msg32_4;
    Act_EditInterfData.Caption := cCaseForm_Msg32_5;
    Act_DelInterfData.Caption := cCaseForm_Msg32_6;
  end;

  Act_AddInterfData.Hint := Act_AddInterfData.Caption;
  Act_EditInterfData.Hint := Act_EditInterfData.Caption;
  Act_DelInterfData.Hint := Act_DelInterfData.Caption;

  EnableEditDelInterfData;
end;

procedure TF_CaseForm.GT_InterfacesFocusedRecordChanged(
  Sender: TcxCustomGridTableView; APrevFocusedRecord,
  AFocusedRecord: TcxCustomGridRecord;
  ANewItemRecordFocusingChanged: Boolean);
begin
  EnableEditDelInterfData;
end;

procedure TF_CaseForm.GT_InterfAccordanceInterfComponIslineGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
    if AText = '0' then
      AText := cCaseForm_Msg25_1
    else
    if AText = '1' then
      AText := cCaseForm_Msg25_2
    else
    if AText = '2' then
      AText := cCaseForm_Msg25_3;
end;

procedure TF_CaseForm.GT_InterfAccordanceAccordComponIslineGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  if AText = '0' then
    AText := cCaseForm_Msg25_1
  else
  if AText = '1' then
    AText := cCaseForm_Msg25_2
  else
  if AText = '2' then
    AText := cCaseForm_Msg25_3;
end;

procedure TF_CaseForm.GT_InterfacesNAMEPropertiesValidate(Sender: TObject;
  var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
begin
    with TF_Main(GForm).DM do
      WriteToDataSet(DataSet_Interface, fnName, DisplayValue);
end;

procedure TF_CaseForm.GT_InterfacesConstructiveWidthPropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
begin
    with TF_Main(GForm).DM do
      if DisplayValue <> '' then
        WriteToDataSet(DataSet_Interface, fnConstructiveWidth, DisplayValue)
      else
        WriteToDataSet(DataSet_Interface, fnConstructiveWidth, Null);
end;

procedure TF_CaseForm.GT_InterfacesIDNetTypePropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
begin
    //with TF_Main(GForm).DM do
    //  WriteToDataSet(DataSet_Interface, fnIDNetType, DisplayValue);
    //with TF_Main(GForm).DM do
    //  DataSet_INTERFACE.UpdateRecord;
    //GT_Interfaces.DataController.Post;
    //GT_InterfacesIDNetType.DataBinding.
end;

procedure TF_CaseForm.pcDirectoriesChange(Sender: TObject);
var
  ActiveViewKind: TViewKind;
  //SavedOnMessage: TMessageEvent;
begin
  ActiveViewKind := GetViewKindByTabSheet(TRzPageControl(Sender).ActivePage);
  if ActiveViewKind <> vkNone then
  begin
    LockControl(Self, true);
    try
      PrepareForm(ActiveViewKind, FFormMode);
      //ParseNoWithGroupItems;
    finally
      LockControl(Self, false);
    end;
  end;
end;

procedure TF_CaseForm.GT_NB_ResourcesRTypeGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  if AText <> '' then
  begin
    if (StrToInt(AText) = rtMat) then
      AText := cCaseForm_Msg33_1
    else
    if (StrToInt(AText) = rtMachMech) then
      AText := cCaseForm_Msg33_2
    else
    if (StrToInt(AText) = rtPrice) then
      AText := cCaseForm_Msg33_3;
  end;
end;

procedure TF_CaseForm.pmPcDirectoriesPopup(Sender: TObject);
var
  MenuItem: TMenuItem;
  i: Integer;
  TabSheet: TRzTabSheet;
begin
  pmPcDirectories.Items.Clear;
  for i := 0 to pcDirectories.PageCount - 1 do
  begin
    TabSheet := pcDirectories.Pages[i];
    if TabSheet.TabVisible then
    begin
      MenuItem := TMenuItem.Create(pmPcDirectories);
      MenuItem.Caption := TabSheet.Caption;
      MenuItem.Tag := TabSheet.PageIndex;
      MenuItem.OnClick := pcDirectoriesMenuClick;
      if TabSheet.PageIndex = pcDirectories.ActivePageIndex then
        MenuItem.Checked := true;
      pmPcDirectories.Items.Add(MenuItem);
    end;
  end;
  MenuItem := TMenuItem.Create(pmPcDirectories);
  MenuItem.Caption := '-';
  pmPcDirectories.Items.Add(MenuItem);

  MenuItem := TMenuItem.Create(pmPcDirectories);
  MenuItem.Caption := cCaseForm_Msg34;
  pmPcDirectories.Items.Add(MenuItem);

  XPMenu.Active := false;
  XPMenu.Active := true;
end;

procedure TF_CaseForm.Timer_CallMakeTimer(Sender: TObject);
begin
  Timer_CallMake.Enabled := false;
  Act_Make.Execute;
end;

procedure TF_CaseForm.Act_EditObjectIconInCADExecute(Sender: TObject);
var
  ProjectBLK: TMemoryStream;
  ActiveBLK: TMemoryStream;
begin
  ProjectBLK := nil;
  ActiveBLK := nil;

  if TF_Main(GForm).GDBMode = bkNormBase then
  begin
    ProjectBLK := TF_Main(GForm).DM.GetStreamFromDataSet(TF_Main(GForm).DM.DataSet_OBJECT_ICONS, fnProjBlk);
    ActiveBLK := TF_Main(GForm).DM.GetStreamFromDataSet(TF_Main(GForm).DM.DataSet_OBJECT_ICONS, fnActiveBlk);
  end
  else
  if TF_Main(GForm).GDBMode = bkProjectManager then
  begin
    ProjectBLK := TMemoryStream.Create;
    ActiveBLK := TMemoryStream.Create;
    SaveToStreamFromMT(mtObjectIcons, ProjectBLK, fnProjBlk);
    SaveToStreamFromMT(mtObjectIcons, ActiveBLK, fnActiveBlk);
  end;
  if (ProjectBLK <> nil) or (ActiveBLK <> nil) then
  begin
    EditBlockOnCAD(ActiveBLK, ProjectBLK);

    //*** Очистить память
    if ProjectBLK <> nil then
      FreeAndNil(ProjectBLK);
    if ActiveBLK <> nil then
      FreeAndNil(ActiveBLK);
  end;
end;

procedure TF_CaseForm.PopupMenu_TreePopup(Sender: TObject);
begin
  //
end;

procedure TF_CaseForm.Tree_InterfTypeMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if Button = mbRight then
    Tree_InterfType.PopupMenu := nil;
end;


procedure TF_CaseForm.Tree_InterfTypeMouseUp(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  Node: TTreeNode;
  ClientXY: TPoint;
  ScreenXY: TPoint;
begin
  if Button = mbRight then
  begin
    Tree_InterfType.PopupMenu := PopupMenu_Tree;

    ScreenXY.X := X;
    ScreenXY.Y := Y;
    ClientXY := Tree_InterfType.ScreenToClient(ScreenXY);

    Node := Tree_InterfType.GetNodeAt(ClientXY.X, ClientXY.Y);
    if Node <> nil then
    begin
      Tree_InterfType.Selected := Node;
      PopupMenu_Tree.Popup(ScreenXY.X, ScreenXY.Y);
    end;
  end;
end;

procedure TF_CaseForm.GT_CURRENCYMainGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  if AText = '0' then
    AText := cMain_Msg33
  else
  if AText = '1' then
    AText := cMain_Msg122
  else
  if AText = '2' then
    AText := cMain_Msg123;
end;

procedure TF_CaseForm.GT_ObjectIconsCellClick(
  Sender: TcxCustomGridTableView;
  ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
  AShift: TShiftState; var AHandled: Boolean);
var
  Point: TPoint;
  CurrColumnFieldName: String;
begin
  //*** Нажать правая кновка мышки
  {if AButton = mbRight then
  begin
    //*** Пункт Меню "Установить с листа"
    FDefIconType := oitNone;
    if (FDefFileBmp <> '') and (FDefFileBlk <> '') then
      if FileExists(FDefFileBmp) and FileExists(FDefFileBlk) then
      begin
        //*** Определить колонку с типом обозначения - проектируемым, или действующим
        CurrColumnFieldName := TcxGridDBColumn(TcxGridTableView(Sender).Columns[ACellViewInfo.Item.Index]).DataBinding.FieldName;
        if CurrColumnFieldName = fnProjBmp then
          FDefIconType := oitProjectible
        else
        if CurrColumnFieldName = fnActiveBmp then
          FDefIconType := oitActive;
      end;
    Act_SetIconFromCAD.Enabled := FDefIconType <> oitNone;

    //*** Показать меню
    GetCursorPos(Point);
    PopupMenu_Data.Popup(Point.X, Point.Y);
  end;}
end;

procedure TF_CaseForm.Act_SetIconFromCADExecute(Sender: TObject);
begin
  TF_Main(GForm).CreateFMakeEditObjectIcons.MakeEdit(fmEdit, mtObjectIcons, FDefIconName, FDefFileBmp, FDefFileBlk, FDefIconType);
  FDefIconType := oitNone;
end;

procedure TF_CaseForm.pcDirectoriesMouseUp(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  Point: TPoint;
begin
  if Button = mbRight then
  begin
    GetCursorPos(Point);
    pmPcDirectories.Popup(Point.X, Point.Y);
  end;
end;


procedure TF_CaseForm.PopupMenu_DataPopup(Sender: TObject);
var
  CurrColumnFieldName: String;
  ScrPoint: TPoint;
  Point: TPoint;
  GridHitTestResult: TcxCustomGridHitTest;
  ColumnIndex: Integer;

  IDComponentTemplate: Integer;
begin
  Act_EditObjectIconInCAD.Visible := false;
  Act_SetIconFromCAD.Visible := false;
  Act_ShowComponTempateInNB.Visible := false;
  Act_DuplicateCompType.Visible := false;
  case FViewKind of
    vkObjectIcons:
      begin
        {Act_EditObjectIconInCAD.Visible := (GT_ObjectIcons.Controller.FocusedRecordIndex <> -1) and (FViewKind = vkObjectIcons);
        Act_EditObjectIconInCAD.Enabled := Act_EditObjectIconInCAD.Visible and ExistsOpenedCAD;
        Act_SetIconFromCAD.Visible := (GT_ObjectIcons.Controller.FocusedRecordIndex <> -1) and (TF_Main(GForm).GDBMode = bkNormBase);
        Act_SetIconFromCAD.Enabled := false;}
        if GT_ObjectIcons.Controller.FocusedRecordIndex <> -1 then
        begin
          Act_EditObjectIconInCAD.Visible := true;
          Act_EditObjectIconInCAD.Enabled := ExistsOpenedCAD;
          Act_SetIconFromCAD.Visible := (TF_Main(GForm).GDBMode = bkNormBase);
          Act_SetIconFromCAD.Enabled := false;

          //*** Пункт Меню "Установить с листа"
          FDefIconType := oitNone;
          if (FDefFileBmp <> '') and (FDefFileBlk <> '') then
            if FileExists(FDefFileBmp) and FileExists(FDefFileBlk) then
            begin
              //*** Определить колонку с типом обозначения - проектируемым, или действующим
              GetCursorPos(ScrPoint);
              Point := GT_ObjectIcons.Site.ScreenToClient(ScrPoint);
              GridHitTestResult := GT_ObjectIcons.ViewInfo.GetHitTest(Point);
              if (GridHitTestResult <> nil) and (GridHitTestResult.ViewInfo is TcxGridTableDataCellViewInfo) then
              begin
                ColumnIndex := TcxGridTableDataCellViewInfo(GridHitTestResult.ViewInfo).Item.Index;
                CurrColumnFieldName := GT_ObjectIcons.Columns[ColumnIndex].DataBinding.FieldName;
                if CurrColumnFieldName = fnProjBmp then
                  FDefIconType := oitProjectible
                else
                if CurrColumnFieldName = fnActiveBmp then
                  FDefIconType := oitActive;
              end;
            end;
          Act_SetIconFromCAD.Enabled := FDefIconType <> oitNone;
        end;
      end;
    vkComponentType:
      if (GT_ComponentTypes.Controller.FocusedRecordIndex <> -1) and (TF_Main(GForm).GDBMode = bkNormBase) then
      begin
        Act_ShowComponTempateInNB.Visible := true;
        IDComponentTemplate := TF_Main(GForm).DM.DataSet_COMPONENT_TYPES.FN(fnIDComponTemplate).AsInteger;
        Act_ShowComponTempateInNB.Enabled := IDComponentTemplate <> 0;
        Act_DuplicateCompType.Visible := true;
      end;
  end;
end;

procedure TF_CaseForm.Act_ShowComponTempateInNBExecute(Sender: TObject);
var
  IDComponentTemplate: Integer;
begin
  IDComponentTemplate := TF_Main(GForm).DM.DataSet_COMPONENT_TYPES.FN(fnIDComponTemplate).AsInteger;
  if IDComponentTemplate <> 0 then
    TF_Main(GForm).SelectComponByIDInTree(IDComponentTemplate);
end;


function TF_CaseForm.CheckChange: Boolean;
begin
  Result := true;
  if (TF_Main(GForm).GDBMode = bkNormBase) and Not TF_Main(GForm).CheckWriteNB(true) then
    Result := false;
end;

procedure TF_CaseForm.GT_PropertiesMIN_VALUEGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
var
  CurrFloat: Double;
begin
  if ARecord.Values[3] <> null then
    case ARecord.Values[3] of
      dtFloat, dtInteger:
        try
          CurrFloat := StrToFloatU(AText);
          if ARecord.Values[10] <> null then
            PropValueInUOM(CurrFloat, ARecord.Values[10], umMetr, TF_Main(GForm).FUOM);
          //if GPropSysNameInUOM.IndexOf(ARecord.Values[10]) <> -1 then
          //  CurrFloat := RoundCP(FloatInUOM(CurrFloat, umMetr, TF_Main(GForm).FUOM));
          CurrFloat := RoundCP(CurrFloat);
          AText := FloatToStr(CurrFloat);
        except
        end;
    end;
end;

procedure TF_CaseForm.GT_PropertiesIZMGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  SetDisplayTextToGridTablePropIzm(AText, ARecord, 10, TF_Main(GForm).FUOM);
end;

procedure TF_CaseForm.GT_CompTypePropIZMGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  SetDisplayTextToGridTablePropIzm(AText, ARecord, 7, TF_Main(GForm).FUOM);
end;

procedure TF_CaseForm.GT_InterfacesConstructiveWidthGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
var
  ValueFloat: Double;
begin
  try
    if AText <> '' then
    begin
      ValueFloat := StrToFloat_My(AText);
      ValueFloat := FloatInUOM(ValueFloat, umMetr, TF_Main(GForm).FUOM);
      AText := FloatToStr(RoundCP(ValueFloat));
    end;
  except
  end;
end;

procedure TF_CaseForm.GT_ComponentTypesCOORDZGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  if AText <> IntToStr(-1) then
    AText := GetDisplayTextInFLoatUOM(AText, TF_Main(GForm).FUOM);
end;

procedure TF_CaseForm.Act_GlobalMakeExecute(Sender: TObject);
begin
  //
end;

procedure TF_CaseForm.Act_GlobalDelExecute(Sender: TObject);
begin
  //
end;

procedure TF_CaseForm.Act_GlobalEditExecute(Sender: TObject);
begin
  //
end;


procedure TF_CaseForm.Act_ImportExecute(Sender: TObject);
var
  ExecRes: Boolean;
begin
  if Not F_NormBase.CheckWriteNB(false) then
    MessageModal(cNBIsReadOnly, ApplicationName, MB_ICONINFORMATION or MB_OK)
  else
  begin
    ExecRes := false;
    TF_Main(GForm).CreateFMasterUpdatePrice;
    if pcDirectories.ActivePage = tsNBNorms then
      ExecRes := TF_Main(GForm).F_MasterUpdatePrice.Execute(fmImportNorms, Self)
    else
    if pcDirectories.ActivePage = tsNBResources then
      ExecRes := TF_Main(GForm).F_MasterUpdatePrice.Execute(fmImportResources, Self);

    if ExecRes then
    begin
      BeginProgress;
      try
        RefreshNodes(TF_Main(GForm).F_MasterUpdatePrice.FInsertedDirTypeID);
      finally
        EndProgress;
      end;
    end;
  end;
end;

procedure TF_CaseForm.Act_DuplicateCompTypeExecute(Sender: TObject);
var
  SrcComponentType: TNBComponentType;
  NBComponentType: TNBComponentType;
  NBComponentTypeProp: TNBCompTypeProperty;
  DirID: Integer;
  DupName: String;

  i: Integer;
begin
  try
    DirID := 0;
    if Tree_InterfType.Selected <> nil then
      if Tree_InterfType.Selected.Data <> nil then
        DirID := PObjectData(Tree_InterfType.Selected.Data).ObjectID;

    if DirID <> 0 then
    begin
      with TF_Main(GForm).DM do
      begin
        //SetSQLToFIBQuery(Query_Select, GetSQLByParams(qtSelect, tnComponentTypes, fnID+'=:'+fnID, nil, fnAll), true);
        //Query_Select.Params[0].AsInteger := DataSet_COMPONENT_TYPES.FN(fnID).AsInteger;
        //Query_Select.ExecQuery;
        //if Query_Select.RecordCount > 0 then
        //begin
        //  NBComponentType := TNBComponentType.Create(GForm);
        //  try
        //    NBComponentType.ComponentType := GetComponentTypeFromQuery(Query_Select);
        //    NBComponentType.Save(meMake);
        //
        //    InsertToDirecoryTypeRel(DirID, NBComponentType.ComponentType.ID, GetMasterFNameByDirItemType(ditComponentType));
        //
        //  finally
        //    FreeAndNil(NBComponentType);
        //  end;
        //  DataSet_COMPONENT_TYPES.ReopenLocate(fnID);
        //end;
        //Query_Select.Close;
      end;

      TF_Main(GForm).GSCSBase.NBSpravochnik.LoadComponentTypes;
      SrcComponentType := TF_Main(GForm).GSCSBase.NBSpravochnik.GetComponentTypeByGUID(TF_Main(GForm).DM.DataSet_COMPONENT_TYPES.FN(fnGUID).AsString);
      if SrcComponentType <> nil then
      begin
        DupName := InputForm(GForm, ApplicationName, cCaseForm_Msg40, SrcComponentType.ComponentType.Name, dtString);
        if DupName <> '' then
        begin
          NBComponentType := TNBComponentType.Create(GForm);
          try
            NBComponentType.Assign(SrcComponentType);
            NBComponentType.ComponentType.GUID := '';
            NBComponentType.ComponentType.IDComponTemplate := 0;
            NBComponentType.ComponentType.Name := DupName;
            NBComponentType.Save(meMake);

            TF_Main(GForm).DM.InsertToDirecoryTypeRel(DirID, NBComponentType.ComponentType.ID, GetMasterFNameByDirItemType(ditComponentType));

            //*** Свойства типа компоненты
            for i := 0 to NBComponentType.Properties.Count - 1 do
            begin
              NBComponentTypeProp := TNBCompTypeProperty(NBComponentType.Properties[i]);
              NBComponentTypeProp.PropertyData.IDMaster := NBComponentType.ComponentType.ID;
              TF_Main(GForm).DM.SavePropertyRelation(meMake, pkCompTypePropRel, @NBComponentTypeProp.PropertyData);
            end;
          finally
            FreeAndNil(NBComponentType);
          end;
          TF_Main(GForm).DM.DataSet_COMPONENT_TYPES.ReopenLocate(fnID);
        end;
      end;                                       
    end;
  except
    on E: Exception do AddExceptionToLogExt(ClassName, MethodName(@TF_CaseForm.Act_DuplicateCompTypeExecute), E.Message);
  end;
end;

procedure TF_CaseForm.pcDirectoriesChanging(Sender: TObject;
  NewIndex: Integer; var AllowChange: Boolean);
begin
  if Visible then
    SaveSelectTabNode;
end;

procedure TF_CaseForm.Act_CopyGUIDToClipboardExecute(Sender: TObject);
begin
  if (FDirTypeInfo.DataSet <> nil) and (FDirTypeInfo.DataSet.Active) then
  begin
    Clipboard.AsText := FDirTypeInfo.DataSet.FieldByName(fnGUID).AsString;
  end;
end;

procedure TF_CaseForm.Tree_InterfTypeGetImageIndex(Sender: TObject;
  Node: TTreeNode);
begin
  if Node.Expanded then
    Node.ImageIndex := tciiDirOpened
  else
    Node.ImageIndex := tciiDir;
  Node.SelectedIndex := Node.ImageIndex;
end;

procedure TF_CaseForm.GT_NB_NormsLaborTimeGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
var
  //TimeUOM: Integer;
  TimeMin: Integer;
  Hr, Min: Integer;
begin
  {if AText <> '' then
  begin
    TimeMin := StrToIntDef(AText, 0);
    Hr := TimeMin div 60;
    Min := TimeMin mod 60;
    if (Hr <> 0) and (Min <> 0) then
      AText := IntToStr(Hr)+'/'+IntToStr(Min);

    //TimeUOM := ARecord.Values[GT_NB_NormsTimeUOM.Index];
    //if TimeUOM <> 0 then
    //  AText := AText +' '+ GetTimeUOMName(TimeUOM);
  end;}
  AText := GetDisplayTextToNORMLaborTime(AText);
end;

procedure TF_CaseForm.GT_ObjectIconsCustomDrawCell(
  Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
  AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
begin
  if Self.ActiveControl <> Sender.Site then
  begin
    if AViewInfo.RecordViewInfo.Focused  then
    begin
      ACanvas.Brush.Color := ColorToRGB(clInactiveBorder) - $305050 ; // clGreen;
    end
  end
  else
  begin
    if AViewInfo.RecordViewInfo.Focused and not AViewInfo.RecordViewInfo.Selected  then
    begin
      if GetBValue(ColorToRGB(clHighlight)) < 200 then
        ACanvas.Brush.Color := RGB(GetRValue(ColorToRGB(clHighlight)), GetGValue(ColorToRGB(clHighlight)),
                         GetBValue(ColorToRGB(clHighlight)) + $20) // + $100000;
      else
        ACanvas.Brush.Color := RGB(GetRValue(ColorToRGB(clHighlight)), GetGValue(ColorToRGB(clHighlight)),
                         GetBValue(ColorToRGB(clHighlight)) - $20) // + $100000;
    end
  end;
end;

procedure TF_CaseForm.Tree_InterfTypeCustomDrawItem(
  Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState;
  var DefaultDraw: Boolean);
begin
  if (Self.ActiveControl <> Sender) and Node.Selected then
    Sender.Canvas.Brush.Color := ColorToRGB(clInactiveBorder) - $305050 ; // clGreen;
end;

end.



