VERSION 5.00
Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.1#0"; "mscomctl.OCX"
Begin VB.UserControl SfbClaimManager 
   ClientHeight    =   9990
   ClientLeft      =   0
   ClientTop       =   0
   ClientWidth     =   14715
   ScaleHeight     =   9990
   ScaleWidth      =   14715
   Begin VB.Frame frm_linkedFiles 
      Caption         =   "#Linked files"
      Height          =   3300
      Left            =   4440
      TabIndex        =   354
      Tag             =   "frm_linkedFiles"
      Top             =   3240
      Visible         =   0   'False
      Width           =   10200
      Begin VB.CommandButton btn_deleteLinkedEmails 
         Caption         =   "#Delete selection"
         Height          =   360
         Left            =   120
         TabIndex        =   356
         Tag             =   "btn_deleteLinkedEmails"
         Top             =   2820
         Width           =   1800
      End
      Begin VB.CommandButton btn_closeLinkedEmails 
         Caption         =   "#Close"
         Height          =   360
         Left            =   9000
         TabIndex        =   355
         Tag             =   "btn_closeValidTo"
         Top             =   2820
         Width           =   1035
      End
      Begin Project1.ArmGrid grd_linkedFiles 
         Height          =   2460
         Left            =   120
         TabIndex        =   357
         TabStop         =   0   'False
         Tag             =   "grd_linkedFiles"
         Top             =   270
         Width           =   9975
         _ExtentX        =   17595
         _ExtentY        =   4339
      End
   End
   Begin VB.Frame fra_frames 
      Height          =   9945
      Index           =   1
      Left            =   6240
      TabIndex        =   13
      Top             =   1080
      Width           =   14235
      Begin VB.Frame fra_detailFrames 
         Height          =   6615
         Index           =   0
         Left            =   360
         TabIndex        =   16
         Top             =   1440
         Width           =   11055
         Begin VB.CommandButton cmd_linkedFiles 
            Caption         =   "#Linked files"
            Height          =   345
            Left            =   7560
            TabIndex        =   353
            Tag             =   "cmd_linkedFiles"
            Top             =   5640
            Width           =   1575
         End
         Begin Project1.A_calocx cal_GenReportDate 
            Height          =   375
            Left            =   9030
            TabIndex        =   27
            Top             =   240
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   661
         End
         Begin Project1.A_calocx cal_GenInitDate 
            Height          =   375
            Left            =   9000
            TabIndex        =   32
            Top             =   960
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   661
         End
         Begin Project1.A_calocx cal_GenFinishDate 
            Height          =   375
            Left            =   9000
            TabIndex        =   33
            Top             =   1440
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   661
         End
         Begin Project1.A_calocx cal_GenUpdateDate 
            Height          =   375
            Left            =   9000
            TabIndex        =   34
            Top             =   1920
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   661
         End
         Begin VB.Frame fra_GenChangeDates 
            Height          =   1695
            Left            =   5490
            TabIndex        =   51
            Top             =   720
            Width           =   5415
            Begin VB.Label lbl_Label 
               Caption         =   "#Last update"
               Height          =   255
               Index           =   5
               Left            =   120
               TabIndex        =   54
               Tag             =   "lbl_LastUpdate"
               Top             =   1320
               Width           =   1575
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Finalized date"
               Height          =   255
               Index           =   4
               Left            =   120
               TabIndex        =   53
               Tag             =   "lbl_FinalizedDate"
               Top             =   840
               Width           =   1575
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Init date"
               Height          =   255
               Index           =   3
               Left            =   120
               TabIndex        =   52
               Tag             =   "lbl_InitDate"
               Top             =   360
               Width           =   1575
            End
         End
         Begin VB.Frame fra_GenReason 
            Height          =   1215
            Left            =   120
            TabIndex        =   48
            Top             =   4320
            Width           =   10815
            Begin Project1.ArmCombobox cbo_Gen2ndReason2 
               Height          =   345
               Left            =   5520
               TabIndex        =   44
               Top             =   720
               Width           =   5175
               _ExtentX        =   8916
               _ExtentY        =   609
            End
            Begin Project1.ArmCombobox cbo_Gen2ndReason1 
               Height          =   345
               Left            =   1800
               TabIndex        =   43
               Top             =   720
               Width           =   3375
               _ExtentX        =   5953
               _ExtentY        =   609
            End
            Begin Project1.ArmCombobox cbo_GenMainReason2 
               Height          =   345
               Left            =   5520
               TabIndex        =   42
               Top             =   240
               Width           =   5175
               _ExtentX        =   8916
               _ExtentY        =   609
            End
            Begin Project1.ArmCombobox cbo_GenMainReason1 
               Height          =   345
               Left            =   1800
               TabIndex        =   41
               Top             =   240
               Width           =   3375
               _ExtentX        =   5953
               _ExtentY        =   609
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#2nd reason"
               Height          =   255
               Index           =   14
               Left            =   240
               TabIndex        =   50
               Tag             =   "lbl_Reason2"
               Top             =   840
               Width           =   1575
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Main reason"
               Height          =   255
               Index           =   13
               Left            =   240
               TabIndex        =   49
               Tag             =   "lbl_Reason1"
               Top             =   360
               Width           =   1455
            End
         End
         Begin VB.TextBox txt_GenReport 
            Height          =   345
            Left            =   1920
            TabIndex        =   26
            Top             =   240
            Width           =   3375
         End
         Begin VB.Frame fra_GenLocation 
            Caption         =   "#Location"
            Height          =   1695
            Left            =   120
            TabIndex        =   19
            Tag             =   "frm_Location"
            Top             =   2520
            Width           =   10815
            Begin Project1.ArmCombobox cbo_GenRespSalesRep 
               Height          =   345
               Left            =   7200
               TabIndex        =   40
               Top             =   1200
               Width           =   3495
               _ExtentX        =   5953
               _ExtentY        =   609
            End
            Begin Project1.ArmCombobox cbo_GenTerritory 
               Height          =   345
               Left            =   7200
               TabIndex        =   39
               Top             =   720
               Width           =   3495
               _ExtentX        =   5953
               _ExtentY        =   609
            End
            Begin Project1.ArmCombobox cbo_GenCountry 
               Height          =   345
               Left            =   7200
               TabIndex        =   38
               Top             =   240
               Width           =   3495
               _ExtentX        =   5953
               _ExtentY        =   609
            End
            Begin Project1.ArmCombobox cbo_GenSalesMarket 
               Height          =   345
               Left            =   1800
               TabIndex        =   37
               Top             =   1200
               Width           =   3375
               _ExtentX        =   5953
               _ExtentY        =   609
            End
            Begin Project1.ArmCombobox cbo_GenSalesOffice 
               Height          =   345
               Left            =   1800
               TabIndex        =   36
               Top             =   720
               Width           =   3375
               _ExtentX        =   5953
               _ExtentY        =   609
            End
            Begin Project1.ArmCombobox cbo_GenCoordinator 
               Height          =   345
               Left            =   1800
               TabIndex        =   35
               Top             =   240
               Width           =   3375
               _ExtentX        =   5953
               _ExtentY        =   609
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Resp. sales rep."
               Height          =   255
               Index           =   11
               Left            =   5520
               TabIndex        =   25
               Tag             =   "lbl_Originator"
               Top             =   1320
               Width           =   1575
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Territory"
               Height          =   255
               Index           =   10
               Left            =   5520
               TabIndex        =   24
               Tag             =   "lbl_Territory"
               Top             =   840
               Width           =   1575
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Country"
               Height          =   255
               Index           =   9
               Left            =   5520
               TabIndex        =   23
               Tag             =   "lbl_Country"
               Top             =   360
               Width           =   1575
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Sales market"
               Height          =   255
               Index           =   8
               Left            =   120
               TabIndex        =   22
               Tag             =   "lbl_SalesMarket"
               Top             =   1320
               Width           =   1575
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Sales office"
               Height          =   255
               Index           =   7
               Left            =   120
               TabIndex        =   21
               Tag             =   "lbl_SalesOffice"
               Top             =   840
               Width           =   1575
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Coordinator"
               Height          =   255
               Index           =   6
               Left            =   120
               TabIndex        =   20
               Tag             =   "lbl_Coordinator"
               Top             =   360
               Width           =   1575
            End
         End
         Begin VB.Frame fra_GenStatus 
            Caption         =   "#Status"
            Height          =   1695
            Left            =   120
            TabIndex        =   18
            Tag             =   "lbl_Status"
            Top             =   720
            Width           =   5175
            Begin VB.OptionButton opt_GenStatus 
               Caption         =   "#Initialized"
               Height          =   255
               Index           =   0
               Left            =   240
               TabIndex        =   28
               Tag             =   "INITIALIZED®©I®©1"
               Top             =   240
               Width           =   3375
            End
            Begin VB.OptionButton opt_GenStatus 
               Caption         =   "#Finalized"
               Height          =   255
               Index           =   1
               Left            =   240
               TabIndex        =   29
               Tag             =   "FINALIZED®©F"
               Top             =   600
               Width           =   3375
            End
            Begin VB.OptionButton opt_GenStatus 
               Caption         =   "#Refused"
               Height          =   255
               Index           =   2
               Left            =   240
               TabIndex        =   30
               Tag             =   "REFUSED®©R"
               Top             =   960
               Width           =   3375
            End
            Begin VB.OptionButton opt_GenStatus 
               Caption         =   "#Settled"
               Height          =   255
               Index           =   3
               Left            =   240
               TabIndex        =   31
               Tag             =   "SETTLED®©S"
               Top             =   1320
               Width           =   3375
            End
         End
         Begin VB.CommandButton cmd_GenComments 
            Caption         =   "#Comments"
            Height          =   345
            Left            =   5640
            TabIndex        =   17
            Tag             =   "cmd_Comments"
            Top             =   5640
            Width           =   1815
         End
         Begin Project1.ArmCombobox cbo_GenOutcomeAction 
            Height          =   345
            Left            =   7320
            TabIndex        =   47
            Top             =   6120
            Width           =   3495
            _ExtentX        =   6165
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_GenOutcome 
            Height          =   345
            Left            =   1920
            TabIndex        =   46
            Top             =   6120
            Width           =   3375
            _ExtentX        =   5953
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_GenAction 
            Height          =   345
            Left            =   1920
            TabIndex        =   45
            Top             =   5640
            Width           =   3375
            _ExtentX        =   4260
            _ExtentY        =   609
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Recomm. Action"
            Height          =   255
            Index           =   12
            Left            =   360
            TabIndex        =   59
            Tag             =   "lbl_Action"
            Top             =   5760
            Width           =   1575
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Report date"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   255
            Index           =   1
            Left            =   5640
            TabIndex        =   58
            Tag             =   "lbl_ReportDate"
            Top             =   360
            Width           =   1575
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Report"
            Height          =   255
            Index           =   0
            Left            =   240
            TabIndex        =   57
            Tag             =   "lbl_Report"
            Top             =   360
            Width           =   1575
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Outcome"
            Height          =   255
            Index           =   119
            Left            =   360
            TabIndex        =   56
            Tag             =   "cbo_GenOutcome"
            Top             =   6240
            Width           =   1455
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Outcome Action"
            Height          =   255
            Index           =   120
            Left            =   5640
            TabIndex        =   55
            Tag             =   "cbo_GenOutcomeAction"
            Top             =   6240
            Width           =   1575
         End
      End
      Begin MSComctlLib.TabStrip tbs_ClaimTabs 
         Height          =   375
         Index           =   2
         Left            =   60
         TabIndex        =   351
         Top             =   180
         Width           =   11055
         _ExtentX        =   19500
         _ExtentY        =   661
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   1
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Suppl./Plant"
               Key             =   "sup"
               Object.Tag             =   "PLANT_INFO"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin MSComctlLib.TabStrip tbs_ClaimTabs 
         Height          =   375
         Index           =   0
         Left            =   60
         TabIndex        =   14
         Top             =   180
         Width           =   11055
         _ExtentX        =   19500
         _ExtentY        =   661
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   6
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#General"
               Key             =   "gen"
               Object.Tag             =   "GENERAL_INFO"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Cost"
               Key             =   "cos"
               Object.Tag             =   "COST_INFO"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Customer"
               Key             =   "cus"
               Object.Tag             =   "CUSTOMER_INFO"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab4 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Project"
               Key             =   "pro"
               Object.Tag             =   "PROJECT_INFO"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab5 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Item"
               Key             =   "ite"
               Object.Tag             =   "ITEM_INFO"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab6 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Suppl./Plant"
               Key             =   "sup"
               Object.Tag             =   "PLANT_INFO"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin MSComctlLib.TabStrip tbs_ClaimTabs 
         Height          =   375
         Index           =   1
         Left            =   150
         TabIndex        =   15
         Top             =   180
         Width           =   11055
         _ExtentX        =   19500
         _ExtentY        =   661
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   3
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#General"
               Key             =   "gen"
               Object.Tag             =   "GENERAL_INFO"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Item"
               Key             =   "ite"
               Object.Tag             =   "ITEM_INFO"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Suppl./Plant"
               Key             =   "sup"
               Object.Tag             =   "PLANT_INFO"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin VB.Frame fra_detailFrames 
         Height          =   6615
         Index           =   1
         Left            =   4440
         TabIndex        =   60
         Top             =   810
         Visible         =   0   'False
         Width           =   11055
         Begin VB.CommandButton btn_costMoveEst 
            Height          =   645
            Left            =   3930
            Style           =   1  'Graphical
            TabIndex        =   352
            Top             =   1620
            Width           =   645
         End
         Begin VB.Frame fra_CostEstimatedCost 
            Caption         =   "#Estimated cost"
            Height          =   2295
            Left            =   120
            TabIndex        =   84
            Tag             =   "frm_EstimatedCost"
            Top             =   720
            Width           =   3765
            Begin VB.TextBox txt_CostEstOtherCost 
               Alignment       =   1  'Right Justify
               Height          =   345
               Left            =   1320
               TabIndex        =   73
               Top             =   1200
               Width           =   2200
            End
            Begin VB.TextBox txt_CostEstTotalCost 
               Alignment       =   1  'Right Justify
               Height          =   345
               Left            =   1320
               TabIndex        =   74
               Top             =   1800
               Width           =   2200
            End
            Begin VB.TextBox txt_CostEstLaborCost 
               Alignment       =   1  'Right Justify
               Height          =   345
               Left            =   1320
               TabIndex        =   72
               Top             =   720
               Width           =   2200
            End
            Begin VB.TextBox txt_CostEstMaterialCost 
               Alignment       =   1  'Right Justify
               Height          =   345
               Left            =   1350
               TabIndex        =   71
               Top             =   240
               Width           =   2200
            End
            Begin VB.Line lin_CostSeparator 
               BorderWidth     =   2
               Index           =   0
               X1              =   1200
               X2              =   3600
               Y1              =   1680
               Y2              =   1680
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Total cost"
               Height          =   255
               Index           =   18
               Left            =   120
               TabIndex        =   88
               Tag             =   "lbl_EstTotCost"
               Top             =   1920
               Width           =   1215
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Other cost"
               Height          =   255
               Index           =   17
               Left            =   120
               TabIndex        =   87
               Tag             =   "lbl_EstOthCost"
               Top             =   1320
               Width           =   1215
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Labor cost"
               Height          =   255
               Index           =   16
               Left            =   120
               TabIndex        =   86
               Tag             =   "lbl_EstLabCost"
               Top             =   840
               Width           =   1215
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Material cost"
               Height          =   255
               Index           =   15
               Left            =   120
               TabIndex        =   85
               Tag             =   "lbl_EstMatCost"
               Top             =   360
               Width           =   1215
            End
         End
         Begin VB.Frame fra_CostSettlementCost 
            Caption         =   "#Settlement cost"
            Height          =   2295
            Left            =   4620
            TabIndex        =   79
            Tag             =   "frm_SettlementCost"
            Top             =   720
            Width           =   3765
            Begin VB.TextBox txt_CostSetMaterialCost 
               Alignment       =   1  'Right Justify
               Height          =   345
               Left            =   1320
               TabIndex        =   75
               Top             =   240
               Width           =   2200
            End
            Begin VB.TextBox txt_CostSetLaborCost 
               Alignment       =   1  'Right Justify
               Height          =   345
               Left            =   1320
               TabIndex        =   76
               Top             =   720
               Width           =   2200
            End
            Begin VB.TextBox txt_CostSetTotalCost 
               Alignment       =   1  'Right Justify
               Height          =   345
               Left            =   1320
               TabIndex        =   78
               Top             =   1800
               Width           =   2200
            End
            Begin VB.TextBox txt_CostSetOtherCost 
               Alignment       =   1  'Right Justify
               Height          =   345
               Left            =   1320
               TabIndex        =   77
               Top             =   1200
               Width           =   2200
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Material cost"
               Height          =   255
               Index           =   2
               Left            =   120
               TabIndex        =   83
               Tag             =   "lbl_EstMatCost"
               Top             =   360
               Width           =   1215
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Labor cost"
               Height          =   255
               Index           =   20
               Left            =   120
               TabIndex        =   82
               Tag             =   "lbl_EstLabCost"
               Top             =   840
               Width           =   1215
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Other cost"
               Height          =   255
               Index           =   30
               Left            =   120
               TabIndex        =   81
               Tag             =   "lbl_EstOthCost"
               Top             =   1320
               Width           =   1215
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Total cost"
               Height          =   255
               Index           =   73
               Left            =   120
               TabIndex        =   80
               Tag             =   "lbl_EstTotCost"
               Top             =   1920
               Width           =   1215
            End
            Begin VB.Line lin_CostSeparator 
               BorderWidth     =   2
               Index           =   1
               X1              =   1200
               X2              =   3600
               Y1              =   1680
               Y2              =   1680
            End
         End
         Begin Project1.ToolbarControl tlb_CostNoteTasks 
            Height          =   3375
            Left            =   10200
            TabIndex        =   89
            Top             =   3120
            Width           =   690
            _ExtentX        =   1217
            _ExtentY        =   5953
         End
         Begin Project1.ArmCombobox cbo_CostCurrency 
            Height          =   345
            Left            =   1680
            TabIndex        =   70
            Top             =   240
            Width           =   4575
            _ExtentX        =   8070
            _ExtentY        =   609
         End
         Begin Project1.ArmGrid grd_CostNotes 
            Height          =   3375
            Left            =   90
            TabIndex        =   90
            Tag             =   "grd_CostNotesConst"
            Top             =   3150
            Width           =   9975
            _ExtentX        =   17595
            _ExtentY        =   5953
         End
         Begin VB.Frame fra_ClaimNoteMod 
            Height          =   2895
            Left            =   120
            TabIndex        =   61
            Top             =   150
            Visible         =   0   'False
            Width           =   10815
            Begin Project1.A_calocx cal_NoteDateIssued 
               Height          =   375
               Left            =   1800
               TabIndex        =   63
               Top             =   720
               Width           =   1815
               _ExtentX        =   3201
               _ExtentY        =   661
            End
            Begin VB.TextBox txt_NoteAmount 
               Height          =   345
               Left            =   1800
               TabIndex        =   64
               Top             =   1200
               Width           =   3855
            End
            Begin VB.TextBox txt_NoteCreditNote 
               Height          =   375
               Left            =   1800
               MaxLength       =   255
               TabIndex        =   62
               Top             =   240
               Width           =   3855
            End
            Begin Project1.ArmCombobox cbo_NoteCurrency 
               Height          =   345
               Left            =   1800
               TabIndex        =   65
               Top             =   1680
               Width           =   3855
               _ExtentX        =   6800
               _ExtentY        =   609
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Currency"
               BeginProperty Font 
                  Name            =   "MS Sans Serif"
                  Size            =   8.25
                  Charset         =   0
                  Weight          =   700
                  Underline       =   0   'False
                  Italic          =   0   'False
                  Strikethrough   =   0   'False
               EndProperty
               Height          =   255
               Index           =   117
               Left            =   120
               TabIndex        =   69
               Tag             =   "lbl_Currency"
               Top             =   1800
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Amount"
               BeginProperty Font 
                  Name            =   "MS Sans Serif"
                  Size            =   8.25
                  Charset         =   0
                  Weight          =   700
                  Underline       =   0   'False
                  Italic          =   0   'False
                  Strikethrough   =   0   'False
               EndProperty
               Height          =   255
               Index           =   116
               Left            =   120
               TabIndex        =   68
               Tag             =   "lbl_Amount"
               Top             =   1320
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Date issued"
               BeginProperty Font 
                  Name            =   "MS Sans Serif"
                  Size            =   8.25
                  Charset         =   0
                  Weight          =   700
                  Underline       =   0   'False
                  Italic          =   0   'False
                  Strikethrough   =   0   'False
               EndProperty
               Height          =   255
               Index           =   115
               Left            =   120
               TabIndex        =   67
               Tag             =   "lbl_DateIssued"
               Top             =   840
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Credit note"
               BeginProperty Font 
                  Name            =   "MS Sans Serif"
                  Size            =   8.25
                  Charset         =   0
                  Weight          =   700
                  Underline       =   0   'False
                  Italic          =   0   'False
                  Strikethrough   =   0   'False
               EndProperty
               Height          =   255
               Index           =   114
               Left            =   120
               TabIndex        =   66
               Tag             =   "lbl_CreditNote"
               Top             =   360
               Width           =   1695
            End
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Currency"
            Height          =   255
            Index           =   19
            Left            =   120
            TabIndex        =   91
            Tag             =   "lbl_Currency"
            Top             =   360
            Width           =   1455
         End
      End
      Begin VB.Frame fra_detailFrames 
         Height          =   6615
         Index           =   5
         Left            =   780
         TabIndex        =   217
         Top             =   1770
         Visible         =   0   'False
         Width           =   11055
         Begin VB.Frame fra_SupBatchNumber 
            Height          =   2175
            Left            =   120
            TabIndex        =   222
            Top             =   960
            Width           =   10815
            Begin VB.TextBox txt_SupBatchNumber4 
               Height          =   345
               Left            =   2160
               MaxLength       =   80
               TabIndex        =   226
               Top             =   1680
               Width           =   8535
            End
            Begin VB.TextBox txt_SupBatchNumber3 
               Height          =   345
               Left            =   2160
               MaxLength       =   80
               TabIndex        =   225
               Top             =   1200
               Width           =   8535
            End
            Begin VB.TextBox txt_SupBatchNumber2 
               Height          =   345
               Left            =   2160
               MaxLength       =   80
               TabIndex        =   224
               Top             =   720
               Width           =   8535
            End
            Begin VB.TextBox txt_SupBatchNumber1 
               Height          =   345
               Left            =   2160
               MaxLength       =   80
               TabIndex        =   223
               Top             =   240
               Width           =   8535
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Batch number"
               Height          =   255
               Index           =   50
               Left            =   240
               TabIndex        =   227
               Tag             =   "lbl_Batch"
               Top             =   240
               Width           =   1695
            End
         End
         Begin VB.Frame fra_SupSupplier 
            Height          =   735
            Left            =   120
            TabIndex        =   218
            Top             =   150
            Width           =   10815
            Begin VB.CommandButton cmd_SupComments 
               Caption         =   "#Comments"
               Height          =   345
               Left            =   5640
               TabIndex        =   219
               Tag             =   "cmd_PlantMemo"
               Top             =   240
               Width           =   1815
            End
            Begin Project1.ArmCombobox cbo_SupSupplier 
               Height          =   345
               Left            =   2160
               TabIndex        =   220
               Top             =   240
               Width           =   3255
               _ExtentX        =   5741
               _ExtentY        =   609
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Supplier/Plant"
               Height          =   255
               Index           =   49
               Left            =   240
               TabIndex        =   221
               Tag             =   "lbl_Plant"
               Top             =   360
               Width           =   1815
            End
         End
         Begin Project1.A_calocx cal_SupPlantCloseDate 
            Height          =   375
            Left            =   2310
            TabIndex        =   228
            Top             =   3240
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   661
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Plant close date"
            Height          =   255
            Index           =   51
            Left            =   240
            TabIndex        =   229
            Tag             =   "lbl_PlantClose"
            Top             =   3360
            Width           =   1935
         End
      End
      Begin VB.Frame fra_detailFrames 
         Height          =   6135
         Index           =   2
         Left            =   300
         TabIndex        =   92
         Top             =   990
         Visible         =   0   'False
         Width           =   11055
         Begin VB.Frame fra_CusWhoRaised 
            Caption         =   "#Who raised"
            Height          =   615
            Left            =   120
            TabIndex        =   157
            Tag             =   "lbl_WhoRaised"
            Top             =   240
            Width           =   10815
            Begin VB.OptionButton opt_CusWhoRaised 
               Caption         =   "#Distributor"
               Height          =   255
               Index           =   0
               Left            =   120
               TabIndex        =   112
               Tag             =   "tab_Customer0®©D"
               Top             =   240
               Width           =   1935
            End
            Begin VB.OptionButton opt_CusWhoRaised 
               Caption         =   "#Specifier"
               Height          =   255
               Index           =   1
               Left            =   2820
               TabIndex        =   113
               Tag             =   "tab_Customer1®©S"
               Top             =   240
               Width           =   1935
            End
            Begin VB.OptionButton opt_CusWhoRaised 
               Caption         =   "#Contractor"
               Height          =   255
               Index           =   2
               Left            =   5520
               TabIndex        =   114
               Tag             =   "tab_Customer2®©C"
               Top             =   240
               Width           =   1935
            End
         End
         Begin MSComctlLib.TabStrip tbs_CustTabs 
            Height          =   375
            Left            =   120
            TabIndex        =   158
            Top             =   960
            Width           =   10815
            _ExtentX        =   19076
            _ExtentY        =   661
            _Version        =   393216
            BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
               NumTabs         =   3
               BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
                  Caption         =   "#Distributor"
                  Key             =   "dis"
                  Object.Tag             =   "tab_Customer0"
                  ImageVarType    =   2
               EndProperty
               BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
                  Caption         =   "#Specifier"
                  Key             =   "spe"
                  Object.Tag             =   "tab_Customer1"
                  ImageVarType    =   2
               EndProperty
               BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
                  Caption         =   "#Contractor"
                  Key             =   "con"
                  Object.Tag             =   "tab_Customer2"
                  ImageVarType    =   2
               EndProperty
            EndProperty
         End
         Begin VB.Frame fra_CustTabs 
            Height          =   4695
            Index           =   1
            Left            =   120
            TabIndex        =   93
            Top             =   1320
            Visible         =   0   'False
            Width           =   10815
            Begin VB.CommandButton cmd_ResetCust 
               Caption         =   "X"
               Height          =   330
               Index           =   1
               Left            =   10290
               TabIndex        =   286
               Top             =   240
               Width           =   375
            End
            Begin VB.TextBox txt_CustSpeCountry 
               Height          =   345
               Left            =   1920
               TabIndex        =   231
               Top             =   2160
               Width           =   3255
            End
            Begin VB.TextBox txt_CustSpeName 
               Height          =   345
               Left            =   1950
               TabIndex        =   103
               Top             =   240
               Width           =   7815
            End
            Begin VB.TextBox txt_CustSpeAddress1 
               Height          =   345
               Left            =   1920
               TabIndex        =   102
               Top             =   720
               Width           =   8775
            End
            Begin VB.TextBox txt_CustSpeAddress2 
               Height          =   345
               Left            =   1920
               TabIndex        =   101
               Top             =   1200
               Width           =   8775
            End
            Begin VB.TextBox txt_CustSpeZipCode 
               Height          =   345
               Left            =   1920
               TabIndex        =   100
               Top             =   1680
               Width           =   1455
            End
            Begin VB.TextBox txt_CustSpeContact 
               Height          =   345
               Left            =   1920
               TabIndex        =   99
               Top             =   2640
               Width           =   3255
            End
            Begin VB.TextBox txt_CustSpeTown 
               Height          =   345
               Left            =   7320
               TabIndex        =   98
               Top             =   1680
               Width           =   3375
            End
            Begin VB.TextBox txt_CustSpeTelephone 
               Height          =   345
               Left            =   1920
               TabIndex        =   97
               Top             =   3120
               Width           =   3255
            End
            Begin VB.TextBox txt_CustSpeFax 
               Height          =   345
               Left            =   7320
               TabIndex        =   96
               Top             =   3120
               Width           =   3375
            End
            Begin VB.TextBox txt_CustSpeSAPCode 
               Height          =   345
               Left            =   1920
               TabIndex        =   95
               Top             =   3600
               Width           =   3255
            End
            Begin VB.CommandButton cmd_SelectCust 
               Caption         =   "..."
               Height          =   330
               Index           =   1
               Left            =   9870
               TabIndex        =   94
               Top             =   240
               Width           =   375
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Name"
               Height          =   255
               Index           =   53
               Left            =   120
               TabIndex        =   115
               Tag             =   "lbl_DistName"
               Top             =   360
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Address"
               Height          =   255
               Index           =   54
               Left            =   120
               TabIndex        =   111
               Tag             =   "lbl_DistAddress"
               Top             =   840
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Zip code"
               Height          =   255
               Index           =   55
               Left            =   120
               TabIndex        =   110
               Tag             =   "lbl_DistZipCode"
               Top             =   1800
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Country"
               Height          =   255
               Index           =   56
               Left            =   120
               TabIndex        =   109
               Tag             =   "lbl_Country"
               Top             =   2280
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Contact"
               Height          =   255
               Index           =   57
               Left            =   120
               TabIndex        =   108
               Tag             =   "lbl_DistContact"
               Top             =   2760
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Tel."
               Height          =   255
               Index           =   58
               Left            =   120
               TabIndex        =   107
               Tag             =   "lbl_DistPhone"
               Top             =   3240
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#SAP code"
               Height          =   255
               Index           =   59
               Left            =   120
               TabIndex        =   106
               Tag             =   "lbl_DistSAP"
               Top             =   3720
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Town"
               Height          =   255
               Index           =   60
               Left            =   5520
               TabIndex        =   105
               Tag             =   "lbl_DistTown"
               Top             =   1800
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Fax"
               Height          =   255
               Index           =   61
               Left            =   5520
               TabIndex        =   104
               Tag             =   "lbl_DistFax"
               Top             =   3240
               Width           =   1695
            End
         End
         Begin VB.Frame fra_CustTabs 
            Height          =   4695
            Index           =   2
            Left            =   120
            TabIndex        =   137
            Top             =   1320
            Visible         =   0   'False
            Width           =   10815
            Begin VB.CommandButton cmd_ResetCust 
               Caption         =   "X"
               Height          =   330
               Index           =   2
               Left            =   10290
               TabIndex        =   287
               Top             =   240
               Width           =   375
            End
            Begin VB.TextBox txt_CustConCountry 
               Height          =   345
               Left            =   1920
               TabIndex        =   230
               Top             =   2160
               Width           =   3255
            End
            Begin VB.TextBox txt_CustConName 
               Height          =   345
               Left            =   1920
               TabIndex        =   147
               Top             =   240
               Width           =   7815
            End
            Begin VB.TextBox txt_CustConAddress1 
               Height          =   345
               Left            =   1920
               TabIndex        =   146
               Top             =   720
               Width           =   8775
            End
            Begin VB.TextBox txt_CustConAddress2 
               Height          =   345
               Left            =   1920
               TabIndex        =   145
               Top             =   1200
               Width           =   8775
            End
            Begin VB.TextBox txt_CustConZipCode 
               Height          =   345
               Left            =   1920
               TabIndex        =   144
               Top             =   1680
               Width           =   1455
            End
            Begin VB.TextBox txt_CustConContact 
               Height          =   345
               Left            =   1920
               TabIndex        =   143
               Top             =   2640
               Width           =   3255
            End
            Begin VB.TextBox txt_CustConTown 
               Height          =   345
               Left            =   7320
               TabIndex        =   142
               Top             =   1680
               Width           =   3375
            End
            Begin VB.TextBox txt_CustConTelephone 
               Height          =   345
               Left            =   1920
               TabIndex        =   141
               Top             =   3120
               Width           =   3255
            End
            Begin VB.TextBox txt_CustConFax 
               Height          =   345
               Left            =   7320
               TabIndex        =   140
               Top             =   3120
               Width           =   3375
            End
            Begin VB.TextBox txt_CustConSAPCode 
               Height          =   345
               Left            =   1920
               TabIndex        =   139
               Top             =   3600
               Width           =   3255
            End
            Begin VB.CommandButton cmd_SelectCust 
               Caption         =   "..."
               Height          =   330
               Index           =   2
               Left            =   9870
               TabIndex        =   138
               Top             =   240
               Width           =   375
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Name"
               Height          =   255
               Index           =   64
               Left            =   120
               TabIndex        =   156
               Tag             =   "lbl_DistName"
               Top             =   360
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Address"
               Height          =   255
               Index           =   65
               Left            =   120
               TabIndex        =   155
               Tag             =   "lbl_DistAddress"
               Top             =   840
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Zip code"
               Height          =   255
               Index           =   66
               Left            =   120
               TabIndex        =   154
               Tag             =   "lbl_DistZipCode"
               Top             =   1800
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Country"
               Height          =   255
               Index           =   67
               Left            =   120
               TabIndex        =   153
               Tag             =   "lbl_Country"
               Top             =   2280
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Contact"
               Height          =   255
               Index           =   68
               Left            =   120
               TabIndex        =   152
               Tag             =   "lbl_DistContact"
               Top             =   2760
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Tel."
               Height          =   255
               Index           =   69
               Left            =   120
               TabIndex        =   151
               Tag             =   "lbl_DistPhone"
               Top             =   3240
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#SAP code"
               Height          =   255
               Index           =   70
               Left            =   120
               TabIndex        =   150
               Tag             =   "lbl_DistSAP"
               Top             =   3720
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Town"
               Height          =   255
               Index           =   71
               Left            =   5520
               TabIndex        =   149
               Tag             =   "lbl_DistTown"
               Top             =   1800
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Fax"
               Height          =   255
               Index           =   72
               Left            =   5520
               TabIndex        =   148
               Tag             =   "lbl_DistFax"
               Top             =   3240
               Width           =   1695
            End
         End
         Begin VB.Frame fra_CustTabs 
            Height          =   4695
            Index           =   0
            Left            =   120
            TabIndex        =   116
            Top             =   1320
            Width           =   10815
            Begin VB.CommandButton cmd_ResetCust 
               Caption         =   "X"
               Height          =   330
               Index           =   0
               Left            =   10290
               TabIndex        =   285
               Top             =   240
               Width           =   375
            End
            Begin VB.TextBox txt_CustDisCountry 
               Height          =   345
               Left            =   1920
               TabIndex        =   123
               Top             =   2160
               Width           =   3255
            End
            Begin VB.TextBox txt_CustDisSAPCode 
               Height          =   345
               Left            =   1920
               TabIndex        =   127
               Top             =   3600
               Width           =   3255
            End
            Begin VB.TextBox txt_CustDisFax 
               Height          =   345
               Left            =   7320
               TabIndex        =   126
               Top             =   3120
               Width           =   3375
            End
            Begin VB.TextBox txt_CustDisTelephone 
               Height          =   345
               Left            =   1920
               TabIndex        =   125
               Top             =   3120
               Width           =   3255
            End
            Begin VB.TextBox txt_CustDisTown 
               Height          =   345
               Left            =   7320
               TabIndex        =   122
               Top             =   1680
               Width           =   3375
            End
            Begin VB.TextBox txt_CustDisContact 
               Height          =   345
               Left            =   1920
               TabIndex        =   124
               Top             =   2640
               Width           =   3255
            End
            Begin VB.TextBox txt_CustDisZipCode 
               Height          =   345
               Left            =   1920
               TabIndex        =   121
               Top             =   1680
               Width           =   1455
            End
            Begin VB.TextBox txt_CustDisAddress2 
               Height          =   345
               Left            =   1920
               TabIndex        =   120
               Top             =   1200
               Width           =   8775
            End
            Begin VB.TextBox txt_CustDisAddress1 
               Height          =   345
               Left            =   1920
               TabIndex        =   119
               Top             =   720
               Width           =   8775
            End
            Begin VB.TextBox txt_CustDisName 
               Height          =   345
               Left            =   1920
               TabIndex        =   118
               Top             =   240
               Width           =   7815
            End
            Begin VB.CommandButton cmd_SelectCust 
               Caption         =   "..."
               Height          =   330
               Index           =   0
               Left            =   9870
               TabIndex        =   117
               Top             =   240
               Width           =   375
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Fax"
               Height          =   255
               Index           =   62
               Left            =   5520
               TabIndex        =   136
               Tag             =   "lbl_DistFax"
               Top             =   3240
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Town"
               Height          =   255
               Index           =   26
               Left            =   5520
               TabIndex        =   135
               Tag             =   "lbl_DistTown"
               Top             =   1800
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#SAP code"
               Height          =   255
               Index           =   25
               Left            =   120
               TabIndex        =   134
               Tag             =   "lbl_DistSAP"
               Top             =   3720
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Tel."
               Height          =   255
               Index           =   24
               Left            =   120
               TabIndex        =   133
               Tag             =   "lbl_DistPhone"
               Top             =   3240
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Contact"
               Height          =   255
               Index           =   63
               Left            =   120
               TabIndex        =   132
               Tag             =   "lbl_DistContact"
               Top             =   2760
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Country"
               Height          =   255
               Index           =   23
               Left            =   120
               TabIndex        =   131
               Tag             =   "lbl_Country"
               Top             =   2280
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Zip code"
               Height          =   255
               Index           =   27
               Left            =   120
               TabIndex        =   130
               Tag             =   "lbl_DistZipCode"
               Top             =   1800
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Address"
               Height          =   255
               Index           =   22
               Left            =   120
               TabIndex        =   129
               Tag             =   "lbl_DistAddress"
               Top             =   840
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Name"
               Height          =   255
               Index           =   21
               Left            =   120
               TabIndex        =   128
               Tag             =   "lbl_DistName"
               Top             =   360
               Width           =   1695
            End
         End
      End
      Begin VB.Frame fra_detailFrames 
         Height          =   7035
         Index           =   4
         Left            =   60
         TabIndex        =   181
         Top             =   1140
         Visible         =   0   'False
         Width           =   10995
         Begin Project1.A_calocx cal_ItemVisitDate 
            Height          =   375
            Left            =   2040
            TabIndex        =   190
            Top             =   2460
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   661
         End
         Begin VB.PictureBox pic_reloadItemDesc 
            AutoSize        =   -1  'True
            Height          =   735
            Left            =   210
            ScaleHeight     =   675
            ScaleWidth      =   675
            TabIndex        =   196
            Top             =   4530
            Width           =   735
         End
         Begin VB.Frame fra_ItemSize 
            Height          =   2955
            Left            =   90
            TabIndex        =   207
            Top             =   840
            Width           =   10815
            Begin VB.TextBox txt_ItemInvoiceNo 
               Height          =   345
               Left            =   1920
               MaxLength       =   80
               TabIndex        =   189
               Top             =   1140
               Width           =   3135
            End
            Begin VB.TextBox txt_ItemSampleReasonNo 
               Height          =   345
               Left            =   6840
               MaxLength       =   80
               TabIndex        =   195
               Top             =   2520
               Width           =   3855
            End
            Begin VB.TextBox txt_ItemClaimSize 
               Height          =   345
               Left            =   1920
               TabIndex        =   185
               Top             =   240
               Width           =   1815
            End
            Begin VB.TextBox txt_ItemTotalDelivery 
               BeginProperty DataFormat 
                  Type            =   0
                  Format          =   "0,00"
                  HaveTrueFalseNull=   0
                  FirstDayOfWeek  =   0
                  FirstWeekOfYear =   0
                  LCID            =   1051
                  SubFormatType   =   0
               EndProperty
               Height          =   345
               Left            =   1920
               TabIndex        =   187
               Top             =   720
               Width           =   1815
            End
            Begin VB.TextBox txt_ItemVisitedBy 
               Height          =   345
               Left            =   6840
               MaxLength       =   80
               TabIndex        =   191
               Top             =   1620
               Width           =   3855
            End
            Begin VB.TextBox txt_ItemSampleSentTo 
               Height          =   345
               Left            =   6840
               MaxLength       =   80
               TabIndex        =   194
               Top             =   2130
               Width           =   3855
            End
            Begin VB.OptionButton opt_ItemSampleSent 
               Caption         =   "#Yes"
               Height          =   255
               Index           =   0
               Left            =   1920
               TabIndex        =   192
               Tag             =   "YES®©Y"
               Top             =   2220
               Width           =   975
            End
            Begin VB.OptionButton opt_ItemSampleSent 
               Caption         =   "#No"
               Height          =   255
               Index           =   1
               Left            =   3000
               TabIndex        =   193
               Tag             =   "NO®©N®©1"
               Top             =   2220
               Width           =   1095
            End
            Begin Project1.ArmCombobox cbo_ItemUnitMeasureTD 
               Height          =   345
               Left            =   6840
               TabIndex        =   188
               Top             =   720
               Width           =   2055
               _extentx        =   3625
               _extenty        =   609
            End
            Begin Project1.ArmCombobox cbo_ItemUnitMeasureCS 
               Height          =   345
               Left            =   6840
               TabIndex        =   186
               Top             =   240
               Width           =   2055
               _extentx        =   3625
               _extenty        =   609
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Reason No Sample Sent"
               Height          =   255
               Index           =   78
               Left            =   4650
               TabIndex        =   233
               Tag             =   "lbl_SampleReasonNo"
               Top             =   2580
               Width           =   2205
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Invoice No"
               Height          =   255
               Index           =   52
               Left            =   120
               TabIndex        =   232
               Tag             =   "lbl_InvoiceNo"
               Top             =   1260
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Claim size"
               Height          =   255
               Index           =   36
               Left            =   120
               TabIndex        =   215
               Tag             =   "lbl_ClaimSize"
               Top             =   360
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Unit of Measure"
               Height          =   255
               Index           =   37
               Left            =   5160
               TabIndex        =   214
               Tag             =   "lbl_ProjectSizeMU"
               Top             =   360
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Total delivery"
               Height          =   255
               Index           =   38
               Left            =   120
               TabIndex        =   213
               Tag             =   "lbl_TotalDelivery"
               Top             =   840
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Unit of Measure"
               Height          =   255
               Index           =   39
               Left            =   5160
               TabIndex        =   212
               Tag             =   "lbl_ProjectSizeMU"
               Top             =   840
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#By"
               Height          =   255
               Index           =   42
               Left            =   5160
               TabIndex        =   211
               Tag             =   "lbl_ByWhom"
               Top             =   1740
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Visit date"
               Height          =   255
               Index           =   41
               Left            =   120
               TabIndex        =   210
               Tag             =   "lbl_VisitDate"
               Top             =   1740
               Width           =   2055
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Sample sent"
               Height          =   255
               Index           =   43
               Left            =   120
               TabIndex        =   209
               Tag             =   "lbl_SampleSent"
               Top             =   2220
               Width           =   1575
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#To"
               Height          =   255
               Index           =   44
               Left            =   5160
               TabIndex        =   208
               Tag             =   "lbl_SentTo"
               Top             =   2220
               Width           =   1695
            End
         End
         Begin VB.TextBox txt_ItemItem 
            Height          =   345
            Left            =   2040
            TabIndex        =   184
            Top             =   360
            Width           =   8415
         End
         Begin VB.Frame fra_ItemExtension 
            Height          =   2595
            Left            =   5040
            TabIndex        =   183
            Top             =   3900
            Width           =   5895
            Begin Project1.A_calocx cal_ItemInstalationDate 
               Height          =   375
               Left            =   1920
               TabIndex        =   197
               Top             =   240
               Width           =   1815
               _extentx        =   3201
               _extenty        =   661
            End
            Begin VB.OptionButton opt_ItemProjectDelay 
               Caption         =   "#Yes"
               Height          =   255
               Index           =   0
               Left            =   1920
               TabIndex        =   200
               Tag             =   "YES®©Y"
               Top             =   1770
               Width           =   975
            End
            Begin VB.OptionButton opt_ItemProjectDelay 
               Caption         =   "#No"
               Height          =   255
               Index           =   1
               Left            =   3000
               TabIndex        =   201
               Tag             =   "NO®©N®©1"
               Top             =   1770
               Width           =   855
            End
            Begin Project1.ArmCombobox cbo_ItemGridManufac 
               Height          =   345
               Left            =   1920
               TabIndex        =   198
               Top             =   720
               Width           =   3855
               _extentx        =   6588
               _extenty        =   609
            End
            Begin Project1.ArmCombobox cbo_ItemGridType 
               Height          =   345
               Left            =   1950
               TabIndex        =   199
               Top             =   1230
               Width           =   3855
               _extentx        =   6588
               _extenty        =   609
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Project delay"
               Height          =   255
               Index           =   45
               Left            =   120
               TabIndex        =   205
               Tag             =   "lbl_ProjectDelay"
               Top             =   1770
               Width           =   1575
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Instalation date"
               Height          =   255
               Index           =   46
               Left            =   120
               TabIndex        =   204
               Tag             =   "lbl_ProjectInstDate"
               Top             =   360
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Grid manufacturer"
               Height          =   255
               Index           =   47
               Left            =   120
               TabIndex        =   203
               Tag             =   "lbl_GridManuf"
               Top             =   840
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Grid type"
               Height          =   255
               Index           =   48
               Left            =   120
               TabIndex        =   202
               Tag             =   "lbl_GridType"
               Top             =   1320
               Width           =   1575
            End
         End
         Begin VB.CommandButton cmd_SelectItem 
            Caption         =   "..."
            Height          =   330
            Left            =   10560
            TabIndex        =   182
            Top             =   360
            Width           =   375
         End
         Begin Project1.ArmGrid grd_ItemDescription 
            Height          =   2535
            Left            =   120
            TabIndex        =   206
            Tag             =   "grd_ItemDescriptionConst"
            Top             =   3960
            Width           =   4815
            _extentx        =   8493
            _extenty        =   4471
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Item"
            Height          =   255
            Index           =   40
            Left            =   180
            TabIndex        =   216
            Tag             =   "lbl_Item"
            Top             =   420
            Width           =   1695
         End
      End
      Begin VB.Frame fra_detailFrames 
         Height          =   6135
         Index           =   3
         Left            =   1170
         TabIndex        =   159
         Top             =   1800
         Visible         =   0   'False
         Width           =   11055
         Begin VB.CommandButton cmd_ResetProj 
            Caption         =   "X"
            Height          =   330
            Left            =   10440
            TabIndex        =   318
            Top             =   420
            Width           =   375
         End
         Begin VB.Frame fra_ProAddress 
            Height          =   3135
            Left            =   120
            TabIndex        =   161
            Top             =   180
            Width           =   10815
            Begin VB.TextBox txt_ProSiteAddress2 
               Height          =   345
               Left            =   1920
               TabIndex        =   165
               Top             =   1230
               Width           =   8775
            End
            Begin VB.TextBox txt_ProCountry 
               Height          =   345
               Left            =   1920
               TabIndex        =   168
               Top             =   2640
               Width           =   4215
            End
            Begin VB.TextBox txt_ProTown 
               Height          =   345
               Left            =   1920
               TabIndex        =   167
               Top             =   2160
               Width           =   4215
            End
            Begin VB.TextBox txt_ProZipCode 
               Height          =   345
               Left            =   1920
               TabIndex        =   166
               Top             =   1680
               Width           =   1455
            End
            Begin VB.TextBox txt_ProSiteAddress1 
               Height          =   345
               Left            =   1920
               TabIndex        =   164
               Top             =   720
               Width           =   8775
            End
            Begin VB.TextBox txt_ProName 
               Height          =   345
               Left            =   1920
               TabIndex        =   163
               Top             =   270
               Width           =   7875
            End
            Begin VB.CommandButton cmd_SelectProj 
               Caption         =   "..."
               Height          =   330
               Left            =   9870
               TabIndex        =   162
               Top             =   240
               Width           =   375
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Country"
               Height          =   255
               Index           =   35
               Left            =   120
               TabIndex        =   178
               Tag             =   "lbl_Country"
               Top             =   2760
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Town"
               Height          =   255
               Index           =   34
               Left            =   120
               TabIndex        =   177
               Tag             =   "lbl_DistTown"
               Top             =   2280
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Zip code"
               Height          =   255
               Index           =   33
               Left            =   120
               TabIndex        =   176
               Tag             =   "lbl_DistZipCode"
               Top             =   1800
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Site address"
               Height          =   255
               Index           =   32
               Left            =   120
               TabIndex        =   175
               Tag             =   "lbl_ProjectAddress"
               Top             =   840
               Width           =   1695
            End
            Begin VB.Label lbl_Label 
               Caption         =   "#Name"
               Height          =   255
               Index           =   31
               Left            =   120
               TabIndex        =   174
               Tag             =   "lbl_DistName"
               Top             =   360
               Width           =   1695
            End
         End
         Begin VB.TextBox txt_ProSize 
            Height          =   345
            Left            =   2040
            TabIndex        =   169
            Top             =   3600
            Width           =   1455
         End
         Begin VB.Frame fra_ProSiteCondition 
            Caption         =   "#Site condition"
            Height          =   1335
            Left            =   6480
            TabIndex        =   160
            Tag             =   "lbl_SiteConditions"
            Top             =   3360
            Width           =   4455
            Begin VB.OptionButton opt_ProSiteCondition 
               Caption         =   "#Poor"
               Height          =   255
               Index           =   0
               Left            =   240
               TabIndex        =   170
               Tag             =   "POOR®©Poor"
               Top             =   240
               Width           =   2055
            End
            Begin VB.OptionButton opt_ProSiteCondition 
               Caption         =   "#Acceptable"
               Height          =   255
               Index           =   1
               Left            =   240
               TabIndex        =   172
               Tag             =   "ACCEPTABLE®©Acceptable"
               Top             =   960
               Width           =   2175
            End
            Begin VB.OptionButton opt_ProSiteCondition 
               Caption         =   "#Good"
               Height          =   255
               Index           =   2
               Left            =   240
               TabIndex        =   171
               Tag             =   "GOOD®©Good"
               Top             =   600
               Width           =   2055
            End
         End
         Begin Project1.ArmCombobox cbo_ProUnitMeasure 
            Height          =   345
            Left            =   2040
            TabIndex        =   173
            Top             =   4080
            Width           =   4215
            _extentx        =   7435
            _extenty        =   609
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Unit of Measure"
            Height          =   255
            Index           =   29
            Left            =   240
            TabIndex        =   180
            Tag             =   "lbl_ProjectSizeMU"
            Top             =   4200
            Width           =   1695
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Size"
            Height          =   255
            Index           =   28
            Left            =   240
            TabIndex        =   179
            Tag             =   "lbl_ProjectSize"
            Top             =   3720
            Width           =   1695
         End
      End
   End
   Begin VB.Frame fra_frames 
      Height          =   7095
      Index           =   2
      Left            =   3720
      TabIndex        =   234
      Top             =   540
      Visible         =   0   'False
      Width           =   11055
      Begin VB.Frame fra_ClaimMemoMod 
         Height          =   3945
         Left            =   90
         TabIndex        =   235
         Top             =   3030
         Width           =   10815
         Begin VB.TextBox txt_MemoCommentEng 
            Height          =   1335
            Left            =   1800
            MultiLine       =   -1  'True
            ScrollBars      =   2  'Vertical
            TabIndex        =   239
            Top             =   2430
            Width           =   8895
         End
         Begin VB.TextBox txt_MemoTitle 
            Height          =   345
            Left            =   1800
            MaxLength       =   100
            TabIndex        =   237
            Top             =   720
            Width           =   8895
         End
         Begin VB.TextBox txt_MemoComment 
            Height          =   1455
            Left            =   1800
            MultiLine       =   -1  'True
            ScrollBars      =   2  'Vertical
            TabIndex        =   238
            Top             =   1200
            Width           =   8895
         End
         Begin Project1.ArmCombobox cbo_MemoLanguage 
            Height          =   345
            Left            =   1770
            TabIndex        =   236
            Top             =   240
            Width           =   8895
            _extentx        =   15690
            _extenty        =   609
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Title"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   255
            Index           =   112
            Left            =   120
            TabIndex        =   244
            Tag             =   "lbl_Title"
            Top             =   840
            Width           =   1695
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Comment"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   255
            Index           =   113
            Left            =   120
            TabIndex        =   243
            Tag             =   "lbl_Comment"
            Top             =   1320
            Width           =   1575
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Language"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   255
            Index           =   118
            Left            =   120
            TabIndex        =   242
            Tag             =   "lbl_Language"
            Top             =   360
            Width           =   1695
         End
      End
      Begin Project1.ArmGrid grd_ClaimMemoList 
         Height          =   2535
         Left            =   120
         TabIndex        =   245
         Tag             =   "grd_ClaimMemoListConst"
         Top             =   240
         Width           =   10815
         _extentx        =   19076
         _extenty        =   4471
      End
   End
   Begin Project1.A_calocx cal_FilterAnyUpdated 
      Height          =   375
      Left            =   2040
      TabIndex        =   12
      Top             =   1140
      Width           =   1815
      _extentx        =   3201
      _extenty        =   661
   End
   Begin Project1.ToolbarControl tlb_main 
      Height          =   690
      Left            =   4170
      TabIndex        =   9
      Top             =   30
      Width           =   7335
      _extentx        =   12938
      _extenty        =   1217
   End
   Begin VB.Frame fra_SearchFilter 
      Caption         =   "#Filter"
      Height          =   975
      Left            =   -60
      TabIndex        =   3
      Tag             =   "frm_Filter"
      Top             =   660
      Width           =   4095
      Begin VB.OptionButton opt_SearchFilter 
         Caption         =   "#All"
         Height          =   195
         Index           =   0
         Left            =   120
         TabIndex        =   5
         Tag             =   "opt_All®©A"
         Top             =   240
         Value           =   -1  'True
         Width           =   2175
      End
      Begin VB.OptionButton opt_SearchFilter 
         Caption         =   "#Any updated after"
         Height          =   195
         Index           =   1
         Left            =   120
         TabIndex        =   4
         Tag             =   "opt_AnyClaims®©D"
         Top             =   600
         Width           =   2055
      End
   End
   Begin VB.Frame fra_SearchView 
      Caption         =   "#View"
      Height          =   615
      Left            =   30
      TabIndex        =   0
      Tag             =   "frm_View"
      Top             =   0
      Width           =   4095
      Begin VB.OptionButton opt_SearchView 
         Caption         =   "#Plant"
         Height          =   195
         Index           =   0
         Left            =   120
         TabIndex        =   2
         Tag             =   "opt_Plant®©P"
         Top             =   240
         Value           =   -1  'True
         Width           =   1695
      End
      Begin VB.OptionButton opt_SearchView 
         Caption         =   "#Sales office"
         Height          =   255
         Index           =   1
         Left            =   1860
         TabIndex        =   1
         Tag             =   "opt_Office®©O"
         Top             =   240
         Width           =   2175
      End
   End
   Begin VB.Frame fra_frames 
      Height          =   6615
      Index           =   0
      Left            =   4140
      TabIndex        =   10
      Top             =   780
      Width           =   11055
      Begin Project1.ArmGrid grd_ClaimMain 
         Height          =   6255
         Left            =   240
         TabIndex        =   11
         Tag             =   "grd_ClaimMainConst"
         Top             =   210
         Width           =   10815
         _extentx        =   19076
         _extenty        =   11033
      End
   End
   Begin VB.Frame fra_frames 
      Height          =   7695
      Index           =   7
      Left            =   1140
      TabIndex        =   319
      Top             =   660
      Visible         =   0   'False
      Width           =   11175
      Begin VB.TextBox txt_SelectItemClsItemNo 
         Height          =   345
         Left            =   1560
         MaxLength       =   20
         TabIndex        =   332
         Top             =   2640
         Width           =   2055
      End
      Begin VB.Frame fra_SelectItemType 
         Height          =   1335
         Left            =   7440
         TabIndex        =   321
         Top             =   120
         Width           =   3495
         Begin VB.OptionButton opt_SelectItemType 
            Caption         =   "#All"
            Height          =   195
            Index           =   0
            Left            =   120
            TabIndex        =   333
            Tag             =   "opt_All®©"
            Top             =   240
            Width           =   1455
         End
         Begin VB.OptionButton opt_SelectItemType 
            Caption         =   "#Standart"
            Height          =   195
            Index           =   1
            Left            =   120
            TabIndex        =   334
            Tag             =   "opt_Standart®©STD®©1"
            Top             =   600
            Value           =   -1  'True
            Width           =   1455
         End
         Begin VB.OptionButton opt_SelectItemType 
            Caption         =   "#Special"
            Height          =   195
            Index           =   2
            Left            =   120
            TabIndex        =   335
            Tag             =   "opt_Special®©SPC"
            Top             =   990
            Width           =   1455
         End
      End
      Begin VB.Frame fra_SelectItemStatus 
         Height          =   1335
         Left            =   7440
         TabIndex        =   320
         Top             =   1560
         Width           =   3495
         Begin VB.OptionButton opt_SelectItemStatus 
            Caption         =   "#All"
            Height          =   195
            Index           =   0
            Left            =   120
            TabIndex        =   336
            Tag             =   "opt_All®©"
            Top             =   240
            Width           =   1455
         End
         Begin VB.OptionButton opt_SelectItemStatus 
            Caption         =   "#Dropped"
            Height          =   195
            Index           =   1
            Left            =   120
            TabIndex        =   337
            Tag             =   "opt_Dropped®©Y"
            Top             =   600
            Width           =   1455
         End
         Begin VB.OptionButton opt_SelectItemStatus 
            Caption         =   "#Non Dropped"
            Height          =   195
            Index           =   2
            Left            =   120
            TabIndex        =   338
            Tag             =   "opt_NonDropped®©N®©1"
            Top             =   960
            Value           =   -1  'True
            Width           =   1455
         End
      End
      Begin Project1.ArmCombobox cbo_SelectItemCategory 
         Height          =   345
         Left            =   1560
         TabIndex        =   322
         Top             =   240
         Width           =   2055
         _extentx        =   3625
         _extenty        =   609
      End
      Begin Project1.ArmGrid grd_SelectItemList 
         Height          =   3855
         Left            =   90
         TabIndex        =   339
         Tag             =   "grd_SelectItemListConst"
         Top             =   3090
         Width           =   10815
         _extentx        =   19076
         _extenty        =   6800
      End
      Begin Project1.ArmCombobox cbo_SelectItemBaseMaterial 
         Height          =   345
         Left            =   1560
         TabIndex        =   323
         Top             =   720
         Width           =   2055
         _extentx        =   3625
         _extenty        =   609
      End
      Begin Project1.ArmCombobox cbo_SelectItemFamily 
         Height          =   345
         Left            =   1560
         TabIndex        =   324
         Top             =   1200
         Width           =   2055
         _extentx        =   3625
         _extenty        =   609
      End
      Begin Project1.ArmCombobox cbo_SelectItemColour 
         Height          =   345
         Left            =   5160
         TabIndex        =   327
         Top             =   240
         Width           =   2055
         _extentx        =   3625
         _extenty        =   609
      End
      Begin Project1.ArmCombobox cbo_SelectItemPattern 
         Height          =   345
         Left            =   5160
         TabIndex        =   328
         Top             =   720
         Width           =   2055
         _extentx        =   3625
         _extenty        =   609
      End
      Begin Project1.ArmCombobox cbo_SelectItemProductRange 
         Height          =   345
         Left            =   5160
         TabIndex        =   329
         Top             =   1200
         Width           =   2055
         _extentx        =   3625
         _extenty        =   609
      End
      Begin Project1.ArmCombobox cbo_SelectItemEdgeDetail 
         Height          =   345
         Left            =   5160
         TabIndex        =   330
         Top             =   1680
         Width           =   2055
         _extentx        =   3625
         _extenty        =   609
      End
      Begin Project1.ArmCombobox cbo_SelectItemSurface 
         Height          =   345
         Left            =   1560
         TabIndex        =   325
         Top             =   1680
         Width           =   2055
         _extentx        =   3625
         _extenty        =   609
      End
      Begin Project1.ArmCombobox cbo_SelectItemShape 
         Height          =   345
         Left            =   1560
         TabIndex        =   326
         Top             =   2160
         Width           =   2055
         _extentx        =   3625
         _extenty        =   609
      End
      Begin Project1.ArmCombobox cbo_SelectItemDimensions 
         Height          =   345
         Left            =   5160
         TabIndex        =   331
         Top             =   2160
         Width           =   2055
         _extentx        =   3625
         _extenty        =   609
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Category"
         Height          =   255
         Index           =   121
         Left            =   120
         TabIndex        =   350
         Tag             =   "BI_Category"
         Top             =   360
         Width           =   1335
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Base material"
         Height          =   255
         Index           =   79
         Left            =   120
         TabIndex        =   349
         Tag             =   "BI_Material"
         Top             =   840
         Width           =   1335
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Family"
         Height          =   255
         Index           =   80
         Left            =   120
         TabIndex        =   348
         Tag             =   "BI_Family"
         Top             =   1320
         Width           =   1335
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Colour"
         Height          =   255
         Index           =   81
         Left            =   3840
         TabIndex        =   347
         Tag             =   "BI_Colour"
         Top             =   360
         Width           =   1335
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Pattern"
         Height          =   255
         Index           =   82
         Left            =   3840
         TabIndex        =   346
         Tag             =   "BI_Pattern"
         Top             =   840
         Width           =   1335
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Product range"
         Height          =   255
         Index           =   83
         Left            =   3840
         TabIndex        =   345
         Tag             =   "lbl_ProductRange"
         Top             =   1320
         Width           =   1335
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Edge detail"
         Height          =   255
         Index           =   84
         Left            =   3840
         TabIndex        =   344
         Tag             =   "BI_Edge"
         Top             =   1800
         Width           =   1335
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#CLS item No."
         Height          =   255
         Index           =   85
         Left            =   120
         TabIndex        =   343
         Tag             =   "lbl_CLSItemNo"
         Top             =   2760
         Width           =   1335
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Surface"
         Height          =   255
         Index           =   86
         Left            =   120
         TabIndex        =   342
         Tag             =   "BI_Surface"
         Top             =   1800
         Width           =   1335
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Shape"
         Height          =   255
         Index           =   87
         Left            =   120
         TabIndex        =   341
         Tag             =   "BI_Shape"
         Top             =   2280
         Width           =   1335
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Dimensions"
         Height          =   255
         Index           =   88
         Left            =   3840
         TabIndex        =   340
         Tag             =   "lbl_Dimensions"
         Top             =   2280
         Width           =   1335
      End
   End
   Begin VB.Frame fra_frames 
      Height          =   7095
      Index           =   6
      Left            =   1050
      TabIndex        =   298
      Top             =   2370
      Visible         =   0   'False
      Width           =   11055
      Begin Project1.A_calocx cal_SelProjModStartDate 
         Height          =   375
         Left            =   1800
         TabIndex        =   301
         Top             =   720
         Width           =   1815
         _extentx        =   3201
         _extenty        =   661
      End
      Begin VB.TextBox txt_SelProjModComments 
         Height          =   3855
         Left            =   1800
         MultiLine       =   -1  'True
         ScrollBars      =   2  'Vertical
         TabIndex        =   308
         Top             =   3120
         Width           =   9135
      End
      Begin VB.TextBox txt_SelProjModName 
         Height          =   345
         Left            =   1800
         MaxLength       =   80
         TabIndex        =   299
         Top             =   240
         Width           =   4575
      End
      Begin VB.TextBox txt_SelProjModSize 
         Height          =   345
         Left            =   8280
         TabIndex        =   300
         Top             =   240
         Width           =   2655
      End
      Begin VB.TextBox txt_SelProjModAddress1 
         Height          =   345
         Left            =   1800
         MaxLength       =   80
         TabIndex        =   303
         Top             =   1200
         Width           =   9135
      End
      Begin VB.TextBox txt_SelProjModAddress2 
         Height          =   345
         Left            =   1800
         MaxLength       =   80
         TabIndex        =   304
         Top             =   1680
         Width           =   9135
      End
      Begin VB.TextBox txt_SelProjModTown 
         Height          =   345
         Left            =   1800
         MaxLength       =   80
         TabIndex        =   305
         Top             =   2160
         Width           =   3255
      End
      Begin VB.TextBox txt_SelProjModZip 
         Height          =   345
         Left            =   8280
         MaxLength       =   15
         TabIndex        =   306
         Top             =   2160
         Width           =   2655
      End
      Begin Project1.ArmCombobox cbo_SelProjModUnitMeassure 
         Height          =   345
         Left            =   8280
         TabIndex        =   302
         Top             =   720
         Width           =   2655
         _extentx        =   4683
         _extenty        =   609
      End
      Begin Project1.ArmCombobox cbo_SelProjModCountry 
         Height          =   345
         Left            =   1800
         TabIndex        =   307
         Top             =   2640
         Width           =   3255
         _extentx        =   5741
         _extenty        =   609
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Name"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   103
         Left            =   120
         TabIndex        =   317
         Tag             =   "lbl_DistName"
         Top             =   360
         Width           =   1695
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Size"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   104
         Left            =   6600
         TabIndex        =   316
         Tag             =   "lbl_ProjectSize"
         Top             =   360
         Width           =   1695
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Start date"
         Height          =   255
         Index           =   105
         Left            =   120
         TabIndex        =   315
         Tag             =   "lbl_StartDate"
         Top             =   840
         Width           =   1695
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Unit of measure"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   106
         Left            =   6600
         TabIndex        =   314
         Tag             =   "lbl_ProjectSizeMU"
         Top             =   840
         Width           =   1695
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Address"
         Height          =   255
         Index           =   107
         Left            =   120
         TabIndex        =   313
         Tag             =   "lbl_DistAddress"
         Top             =   1320
         Width           =   1695
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Town"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   108
         Left            =   120
         TabIndex        =   312
         Tag             =   "lbl_DistTown"
         Top             =   2280
         Width           =   1695
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#ZIP"
         Height          =   255
         Index           =   109
         Left            =   6600
         TabIndex        =   311
         Tag             =   "lbl_DistZipCode"
         Top             =   2280
         Width           =   1695
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Country"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   110
         Left            =   120
         TabIndex        =   310
         Tag             =   "lbl_Country"
         Top             =   2760
         Width           =   1695
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Comments"
         Height          =   255
         Index           =   111
         Left            =   120
         TabIndex        =   309
         Tag             =   "lbl_Comments"
         Top             =   3240
         Width           =   1695
      End
   End
   Begin VB.Frame fra_frames 
      Height          =   7095
      Index           =   5
      Left            =   2520
      TabIndex        =   288
      Top             =   -30
      Visible         =   0   'False
      Width           =   11055
      Begin VB.Frame fra_SelectProjCountry 
         Height          =   735
         Left            =   120
         TabIndex        =   294
         Top             =   120
         Width           =   3855
         Begin Project1.ArmCombobox cbo_SelectProjCountry 
            Height          =   345
            Left            =   1200
            TabIndex        =   295
            Top             =   240
            Width           =   2535
            _extentx        =   4471
            _extenty        =   609
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Country"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   255
            Index           =   90
            Left            =   120
            TabIndex        =   296
            Tag             =   "lbl_Country"
            Top             =   360
            Width           =   975
         End
      End
      Begin VB.Frame fra_SelectProjLike 
         Caption         =   "#Like"
         Height          =   1815
         Left            =   120
         TabIndex        =   289
         Tag             =   "fra_Like"
         Top             =   960
         Width           =   3855
         Begin VB.TextBox txt_SelectProjLike 
            Height          =   345
            Left            =   120
            TabIndex        =   293
            Top             =   1320
            Width           =   3615
         End
         Begin VB.OptionButton opt_SelectProjLike 
            Caption         =   "#End by"
            Height          =   255
            Index           =   3
            Left            =   120
            TabIndex        =   292
            Tag             =   "opt_EndBy®©E"
            Top             =   960
            Width           =   3615
         End
         Begin VB.OptionButton opt_SelectProjLike 
            Caption         =   "#Contains"
            Height          =   255
            Index           =   0
            Left            =   120
            TabIndex        =   291
            Tag             =   "opt_Contains®©C"
            Top             =   600
            Width           =   3615
         End
         Begin VB.OptionButton opt_SelectProjLike 
            Caption         =   "#Begin by"
            Height          =   255
            Index           =   1
            Left            =   120
            TabIndex        =   290
            Tag             =   "opt_BeginBy®©B®©1"
            Top             =   240
            Value           =   -1  'True
            Width           =   3615
         End
      End
      Begin Project1.ArmGrid grd_SelectProjList 
         Height          =   6735
         Left            =   4080
         TabIndex        =   297
         Tag             =   "grd_SelectProjListConst"
         Top             =   240
         Width           =   6855
         _extentx        =   12091
         _extenty        =   11880
      End
   End
   Begin VB.Frame fra_frames 
      Height          =   7095
      Index           =   4
      Left            =   2490
      TabIndex        =   257
      Top             =   750
      Visible         =   0   'False
      Width           =   11055
      Begin VB.Frame fra_SelCustModContact 
         Height          =   2175
         Left            =   120
         TabIndex        =   279
         Top             =   3360
         Width           =   10815
         Begin VB.TextBox txt_SelCustModContact 
            Height          =   345
            Left            =   1800
            MaxLength       =   80
            TabIndex        =   267
            Top             =   240
            Width           =   8895
         End
         Begin VB.TextBox txt_SelCustModContactTitle 
            Height          =   345
            Left            =   1800
            MaxLength       =   80
            TabIndex        =   268
            Top             =   720
            Width           =   8895
         End
         Begin VB.TextBox txt_SelCustModPhone 
            Height          =   345
            Left            =   1800
            MaxLength       =   20
            TabIndex        =   269
            Top             =   1200
            Width           =   3495
         End
         Begin VB.TextBox txt_SelCustModFax 
            Height          =   345
            Left            =   7200
            MaxLength       =   20
            TabIndex        =   270
            Top             =   1200
            Width           =   3495
         End
         Begin VB.TextBox txt_SelCustModEmail 
            Height          =   345
            Left            =   1800
            MaxLength       =   80
            TabIndex        =   271
            Top             =   1680
            Width           =   8895
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Contact"
            Height          =   255
            Index           =   98
            Left            =   120
            TabIndex        =   284
            Tag             =   "lbl_DistContact"
            Top             =   360
            Width           =   1695
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Contact title"
            Height          =   255
            Index           =   99
            Left            =   120
            TabIndex        =   283
            Tag             =   "lbl_ContactTitle"
            Top             =   840
            Width           =   1695
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Phone"
            Height          =   255
            Index           =   100
            Left            =   120
            TabIndex        =   282
            Tag             =   "lbl_DistPhone"
            Top             =   1320
            Width           =   1695
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#E-mail"
            Height          =   255
            Index           =   101
            Left            =   120
            TabIndex        =   281
            Tag             =   "lbl_Email"
            Top             =   1800
            Width           =   1695
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Fax"
            Height          =   255
            Index           =   102
            Left            =   5520
            TabIndex        =   280
            Tag             =   "lbl_DistFax"
            Top             =   1320
            Width           =   1695
         End
      End
      Begin VB.Frame fra_SelCustModBase 
         Height          =   3135
         Left            =   120
         TabIndex        =   258
         Top             =   120
         Width           =   10815
         Begin VB.TextBox txt_SelCustModName 
            Height          =   345
            Left            =   1800
            MaxLength       =   80
            TabIndex        =   259
            Top             =   240
            Width           =   8895
         End
         Begin VB.TextBox txt_SelCustModAddress1 
            Height          =   345
            Left            =   1800
            MaxLength       =   80
            TabIndex        =   260
            Top             =   720
            Width           =   8895
         End
         Begin VB.TextBox txt_SelCustModAddress2 
            Height          =   345
            Left            =   1800
            MaxLength       =   80
            TabIndex        =   261
            Top             =   1200
            Width           =   8895
         End
         Begin VB.TextBox txt_SelCustModZipCode 
            Height          =   345
            Left            =   1800
            MaxLength       =   15
            TabIndex        =   262
            Top             =   1680
            Width           =   3495
         End
         Begin VB.TextBox txt_SelCustModTown 
            Height          =   345
            Left            =   1800
            MaxLength       =   80
            TabIndex        =   263
            Top             =   2160
            Width           =   3495
         End
         Begin Project1.ArmCombobox cbo_SelCustModType 
            Height          =   345
            Left            =   7200
            TabIndex        =   266
            Top             =   2640
            Width           =   3495
            _extentx        =   6165
            _extenty        =   609
         End
         Begin Project1.ArmCombobox cbo_SelCustModCountry 
            Height          =   345
            Left            =   7200
            TabIndex        =   264
            Top             =   2160
            Width           =   3495
            _extentx        =   6165
            _extenty        =   609
         End
         Begin Project1.ArmCombobox cbo_SelCustModCompany 
            Height          =   345
            Left            =   1800
            TabIndex        =   265
            Top             =   2580
            Width           =   3495
            _extentx        =   6165
            _extenty        =   609
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Name"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   255
            Index           =   91
            Left            =   120
            TabIndex        =   278
            Tag             =   "lbl_DistName"
            Top             =   360
            Width           =   1695
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Address"
            Height          =   255
            Index           =   92
            Left            =   120
            TabIndex        =   277
            Tag             =   "lbl_DistAddress"
            Top             =   840
            Width           =   1695
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Zip code"
            Height          =   255
            Index           =   93
            Left            =   120
            TabIndex        =   276
            Tag             =   "lbl_DistZipCode"
            Top             =   1800
            Width           =   1695
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Town"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   255
            Index           =   94
            Left            =   120
            TabIndex        =   275
            Tag             =   "lbl_DistTown"
            Top             =   2280
            Width           =   1695
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Company"
            Height          =   255
            Index           =   95
            Left            =   120
            TabIndex        =   274
            Tag             =   "lbl_Company"
            Top             =   2760
            Width           =   1695
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Country"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   255
            Index           =   96
            Left            =   5520
            TabIndex        =   273
            Tag             =   "lbl_Country"
            Top             =   2280
            Width           =   1695
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Customer type"
            Height          =   255
            Index           =   97
            Left            =   5520
            TabIndex        =   272
            Tag             =   "lbl_CustomerType"
            Top             =   2760
            Width           =   1695
         End
      End
   End
   Begin VB.Frame fra_frames 
      Height          =   7035
      Index           =   3
      Left            =   8580
      TabIndex        =   246
      Top             =   2670
      Visible         =   0   'False
      Width           =   10995
      Begin VB.Frame fra_SelectCustType 
         Height          =   975
         Left            =   120
         TabIndex        =   256
         Top             =   120
         Width           =   3855
         Begin VB.OptionButton opt_SelectCustType 
            Caption         =   "#SAP customer"
            Height          =   255
            Index           =   0
            Left            =   120
            TabIndex        =   240
            Tag             =   "opt_SAPCust®©SAP"
            Top             =   240
            Value           =   -1  'True
            Width           =   2535
         End
         Begin VB.OptionButton opt_SelectCustType 
            Caption         =   "#Claim customer"
            Height          =   255
            Index           =   1
            Left            =   120
            TabIndex        =   241
            Tag             =   "opt_ClaimCust®©Claim®©1"
            Top             =   600
            Width           =   2535
         End
      End
      Begin VB.Frame fra_SelectCustLike 
         Caption         =   "#Like"
         Height          =   1815
         Left            =   120
         TabIndex        =   251
         Tag             =   "fra_Like"
         Top             =   2040
         Width           =   3855
         Begin VB.OptionButton opt_SelectCustLike 
            Caption         =   "#Begin by"
            Height          =   255
            Index           =   0
            Left            =   120
            TabIndex        =   252
            Tag             =   "opt_BeginBy®©B®©1"
            Top             =   240
            Value           =   -1  'True
            Width           =   3615
         End
         Begin VB.OptionButton opt_SelectCustLike 
            Caption         =   "#Contains"
            Height          =   255
            Index           =   1
            Left            =   120
            TabIndex        =   253
            Tag             =   "opt_Contains®©C"
            Top             =   600
            Width           =   3615
         End
         Begin VB.OptionButton opt_SelectCustLike 
            Caption         =   "#End by"
            Height          =   255
            Index           =   2
            Left            =   120
            TabIndex        =   254
            Tag             =   "opt_EndBy®©E"
            Top             =   960
            Width           =   3615
         End
         Begin VB.TextBox txt_SelectCustLike 
            Height          =   345
            Left            =   120
            TabIndex        =   255
            Top             =   1320
            Width           =   3615
         End
      End
      Begin VB.Frame fra_SelectCustCountry 
         Height          =   735
         Left            =   120
         TabIndex        =   248
         Top             =   1200
         Width           =   3855
         Begin Project1.ArmCombobox cbo_SelectCustCountry 
            Height          =   345
            Left            =   1200
            TabIndex        =   249
            Top             =   240
            Width           =   2535
            _extentx        =   4471
            _extenty        =   609
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Country"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   255
            Index           =   89
            Left            =   120
            TabIndex        =   250
            Tag             =   "lbl_Country"
            Top             =   360
            Width           =   975
         End
      End
      Begin Project1.ArmGrid grd_SelectCustList 
         Height          =   6735
         Left            =   4080
         TabIndex        =   247
         Tag             =   "grd_SelectCustListConst"
         Top             =   240
         Width           =   6855
         _extentx        =   12091
         _extenty        =   11880
      End
   End
   Begin VB.Frame fra_SearchList 
      Height          =   6015
      Left            =   -60
      TabIndex        =   6
      Top             =   1710
      Width           =   4095
      Begin VB.PictureBox pic_ReloadSearch 
         AutoSize        =   -1  'True
         Height          =   735
         Left            =   120
         ScaleHeight     =   675
         ScaleWidth      =   675
         TabIndex        =   7
         Top             =   240
         Visible         =   0   'False
         Width           =   735
      End
      Begin Project1.ArmTreeView tvw_SearchList 
         Height          =   5655
         Left            =   120
         TabIndex        =   8
         Top             =   240
         Width           =   3855
         _extentx        =   6800
         _extenty        =   9975
      End
   End
End
Attribute VB_Name = "SfbClaimManager"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit
' **************************************************************************************************
' ************************************* EXTERNAL DECLARATIONS **************************************
' **************************************************************************************************
Private Declare Function GetTempPath Lib "Kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Private Declare Function LockWindowUpdate Lib "user32" (ByVal hwnd As Long) As Long
' **************************************************************************************************

' **************************************************************************************************
' **************************************** TOOL CONSTANTS ******************************************
' **************************************************************************************************
' colors for enable states
Private Const CL_COLOR_ENABLED As Long = &H80000005
Private Const CL_COLOR_DISABLED As Long = &H8000000F
Private Const SEP1 As String = "®"
Private Const SEP2 As String = "©"
Private Const SEP As String = SEP1 + SEP2
Private Const C_MODULE_NAME As String = "Claim Manager"     ' module name used in log table
Private Const C_MODULE_LOC_NAME As String = "Claims"        ' module name used for localization
Private Const C_SCREENMODE_STACK_SIZE As Long = 5           ' size of stack for active screens

Private Const C_TLB_SCREEN_ID As Long = 2400                ' screen ID for toolbar
Private Const C_TLB_MAIN As Long = 2402                     ' main toolbar ID
Private Const C_TLB_COSTNOTE As Long = 2403                 ' special toolbar for notes on cost screen
Private Const C_TOOLBARFACE_ITEM_LST As String = "0"        ' toolbar for main list
Private Const C_TOOLBARFACE_MEMO_MTNC As String = "1"        ' toolbar for memo
Private Const C_TOOLBARFACE_ITEM_MTNC As String = "2"       ' for add, update
Private Const C_TOOLBARFACE_ITEM_VIEW As String = "3"       ' for view, delete
Private Const C_TOOLBARFACE_PROD_LST As String = "4"        ' for product selection
Private Const C_TOOLBARFACE_CUST_LST As String = "5"        ' for customer selection
Private Const C_TOOLBARFACE_NOTES_LST As String = "0"       ' toolbar for memo
Private Const C_TOOLBARFACE_NOTES_MTNC As String = "1"      ' toolbar for memo, add,update
Private Const C_TOOLBARFACE_NOTES_VIEW As String = "2"      ' toolbar for memo, delete


Private Const SIFYB_CM_ERROR_MESSAGE = 2400                 ' const for base of error messages ids
Private Const C_COST_VALUE_FORMAT As String = "#0.00"
Private Const C_NUMERIC_VALUE_FORMAT As String = "#0.00"
' resolution of the pri nter
Private Const C_Scalewidth As Long = 3000
Private Const C_ScaleHeight As Long = 3000
Private Const C_CellMargin As Long = 5
Private mi_LCurrPaper As Integer

' ****************************************** TOOL CONSTANTS ***************************************

' **************************************************************************************************
' **************************************** USER DEFINED ERRORS *************************************
' **************************************************************************************************
Private Enum ArmErr
    DBCnxFailed = vbObjectError + 1              ' Unable to connect to the database
    CPTAlreadyInitialized = vbObjectError + 2    ' We try to initialize a component that is already initialized
    CPTNotInitialized = vbObjectError + 3        ' We try to use or free that is not initialized yet
    InvalidArgument = vbObjectError + 4
    PropertyNotSet = vbObjectError + 5
    SQLFailure = vbObjectError + 6               ' A SQL runtime error has occured : syntax wrong....
    SQLBadRowAffectedCount = vbObjectError + 7   ' A SQL request has not affected the expected rowcount (ex: one Update do nothing)
    SQLBadRowExpectedCount = vbObjectError + 8   ' A SQL request does not return the expected rowcount : select an item return nothing...
    DrivingError = vbObjectError + 9
    CompFncFailed = vbObjectError + 10           ' when component function fail
    GridLoadFailed = vbObjectError + 11          ' load function failed ... bad sql
    QuietException = vbObjectError + 12          ' do not display error message
    SQLTableReferenceConstraint = vbObjectError + 13 ' A SQL request cannot be executed : Table reference constraint
    DuplicityDetected = vbObjectError + 2301     ' detected row with same unique id
End Enum

Private Enum ErrMsg
    ErrMsgNone = 0
    ErrMsgNoPrinter = 135
    ErrMsgAddMemos_Q = 49
    ErrMsgMandatoryAreEmpty = SIFYB_CM_ERROR_MESSAGE + 1
    WarMsgDoYouRemove = SIFYB_CM_ERROR_MESSAGE + 2
    ErrMsgIConcurency = SIFYB_CM_ERROR_MESSAGE + 3
    WarMsgSelectRow = SIFYB_CM_ERROR_MESSAGE + 4
    ErrMsgNumericRequired = SIFYB_CM_ERROR_MESSAGE + 5
    WarMsgItemExists = SIFYB_CM_ERROR_MESSAGE + 6
    ErrMsgAtLeastOneItemChecked = SIFYB_CM_ERROR_MESSAGE + 7
    ErrMsgFileDoesntExists = SIFYB_CM_ERROR_MESSAGE + 8
    ErrMsgBadValue = SIFYB_CM_ERROR_MESSAGE + 9
    ErrMsgNoValidRateExists = SIFYB_CM_ERROR_MESSAGE + 10
    ErrMsgTotalClaimsTooLarge = SIFYB_CM_ERROR_MESSAGE + 11
    ErrMsgCannotDeleteRecord = SIFYB_CM_ERROR_MESSAGE + 12
    ErrMsgOnlyNumericIsValid = SIFYB_CM_ERROR_MESSAGE + 13
    ErrMsgRecordDeleted = SIFYB_CM_ERROR_MESSAGE + 14
    ErrMsgMandatoryByFilter = SIFYB_CM_ERROR_MESSAGE + 15
    WarMsgItemNotFound = SIFYB_CM_ERROR_MESSAGE + 16
    WarMsgResetFilters = SIFYB_CM_ERROR_MESSAGE + 17
    MsgCannotInsertFile = SIFYB_CM_ERROR_MESSAGE + 40
    ErrMsgFatal = SIFYB_CM_ERROR_MESSAGE + 41
    ErrMsg_M360 = SIFYB_CM_ERROR_MESSAGE + 360
End Enum
' *************************************** USER DEFINED ERRORS **************************************

' **************************************************************************************************
' *************************************** CONTROL MEMBERS ******************************************
' **************************************************************************************************
' common global variables
Private ms_LanguageCode As String           ' Language code
Private mb_Initialized As Boolean           ' Initialized user control flag
Private mb_Initializing As Boolean          ' Flag of initializing
Private ms_LoginName As String              ' login name
Private ml_UserCode As Long                 ' User code

Dim mo_userRights As UserRights_t   ' rights assigned for current user
Dim mua_ActiveMode() As ArmScreenMode
Dim ml_detailIconcurrencyCursor As Long ' cursor for all iConcurrency fields needed for detail/
Dim ml_DetailCursor() As Long           ' cursor to hold all detail data
Dim ms_detailRequests() As String       ' requests for cursors
Dim ms_detailRequestsUpd() As String    ' update requests
Dim ms_detailRequestsAdd As String      ' Insert requests separated with standard separator SEP
Dim ms_detailRequestsDel As String      ' Delete requests separated with standard separator SEP
Dim mv_memoRequests As Variant          ' global variable used by memo screens - initialized when entering memo
Dim ml_memoCursor As Long
Dim ml_notesCursor As Long
Dim ml_custCursor As Long
Dim ml_projCursor  As Long
Dim ml_codePageCursor As Long           ' code pages used to translate controls

Dim ms_Title As String                  ' title of user control - can be assigned as Caption to the parent form or title for printing
Dim ml_itemDescLabelsCursor As Long     ' cursor for loading labels into item description grid in Item tab
Dim ml_treeNodeDescCursor As Long       ' cursor for creating last node in filter treeview - if created programatically

Dim ms_aktTvwPath As String             ' path defining actualy selected node in search treeView - optimalization purpose
Dim ms_DecimalSeparator As String       ' decimal separator obtained from local settings

Dim md_actSelectedFilterDate As Double  ' to substitue strange behaviour of lostFocus event in A_calocx component

Private Enum ArmScreenMode
    smRefreshOnly                       ' do not change active screen, only refresh active
    smMain
    smAdd
    smUpdate
    smDelete
    smView
    smMemoMain
    smMemoAdd
    smMemoUpdate
    smMemoDelete
    smNotesAdd
    smNotesUpdate
    smNotesDelete
    smCustMain
    smCustAdd
    smCustUpdate
    smCustDelete
    smCustView
    smProjMain
    smProjAdd
    smProjUpdate
    smProjDelete
    smProjView
    smItemMain
End Enum

' sets of sql result count types
Private Enum ArmSQLResultType
    ArmSQLExactOne                      ' 1..1
    ArmSQLMaxOne                        ' 0..1
    ArmSQLAtLeastOne                    ' 1..N
    ArmSQLAny                           ' 0..N
End Enum

Private Type UserRights_t
    allowAdd As Boolean
    loginCoordinator As Boolean
End Type


#If LIVE = 1 Then
    Dim mo_Db As Object
#Else
    Dim mo_Db As ARMSYSCOMLib.ArmDb
#End If

Dim ml_DEBUG_CursorCount As Long

' *************************************** CONTROL MEMBERS ******************************************

' **************************************************************************************************
' *********************************** PUBLIC CONTROL EVENTS ****************************************
' **************************************************************************************************
Public Event quit()
Public Event PrintDetail(ByVal av_detailKey As Variant)
Public Event AuditClick(ByVal as_CLA_code As String)

' *********************************** PUBLIC CONTROL EVENTS ****************************************

' **************************************************************************************************
' ********************************* PUBLIC CONTROL PROPERTIES **************************************
' **************************************************************************************************
' database controler property
' Params:
' ao_db (ARMSYSCOMLib.ArmDb) - ArmSysCom instance
#If LIVE Then
Public Property Set Db(ByRef ao_Db As Object)
#Else
Public Property Set Db(ByRef ao_Db As ARMSYSCOMLib.ArmDb)
#End If

On Error GoTo ErrHandler
    If Not mo_Db Is Nothing Then Err.Raise ArmErr.CPTAlreadyInitialized
    If ao_Db Is Nothing Then Err.Raise ArmErr.InvalidArgument
    
    Set mo_Db = ao_Db
    
    Exit Property
ErrHandler:
    Call ErrorMessage("ArmDb(Set)")
End Property


Public Property Let LoginName(ByVal as_loginName As String)
On Error GoTo ErrHandler
    
    If mb_Initialized Then Call Err.Raise(ArmErr.CPTAlreadyInitialized)
    ms_LoginName = as_loginName
    Exit Property
ErrHandler:
    Call ErrorMessage("LoginName(Let)")
End Property

Public Sub Move(ByVal aLeft As Single, ByVal aTop As Single, ByVal aWidth As Single, ByVal aHeight As Single)
    Call UserControl.Extender.Move(aLeft, aTop, aWidth, aHeight)
End Sub
Public Property Let Visible(ByVal aVisible As Boolean)
    UserControl.Extender.Visible = aVisible
End Property
Public Property Get Visible() As Boolean
    Visible = UserControl.Extender.Visible
End Property

' User code used in logs
Public Property Let U_Code(ByVal al_UserCode As Long)
On Error GoTo ErrHandler
    
    If mb_Initialized Then Call Err.Raise(ArmErr.CPTAlreadyInitialized)
    ml_UserCode = al_UserCode
    Exit Property
ErrHandler:
    Call ErrorMessage("U_Code(Let)")
End Property

' Setting language code
Public Property Let Language_Code(ByVal as_newValue As String)
On Error GoTo ErrHandler
    If mb_Initialized Then Call Err.Raise(ArmErr.CPTAlreadyInitialized)
    If Len(as_newValue) <> 1 Then Call Err.Raise(ArmErr.InvalidArgument, "", "Language_code must contains only 1 char")
    
    ms_LanguageCode = as_newValue
    
    Exit Property
ErrHandler:
     Call ErrorMessage("Language_Code")
End Property

Public Property Get Title() As String
    Title = ms_Title
End Property
' ********************************* PUBLIC CONTROL PROPERTIES **************************************

' **************************************************************************************************
' ******************************* PUBLIC USER CONTROL METHODS **************************************
' **************************************************************************************************
' initialize user control
Public Function Load_A_COM()
    On Error GoTo ErrHandler
    Load_A_COM = False
    
    If mb_Initialized Then Err.Raise ArmErr.CPTAlreadyInitialized
    If mo_Db Is Nothing Then Err.Raise ArmErr.PropertyNotSet, "ArmDb not initialized"
    If ms_LanguageCode = "" Then Err.Raise ArmErr.PropertyNotSet, "LanguageCode not initialized"
    If ml_UserCode = 0 Then Err.Raise ArmErr.PropertyNotSet, "UserCode not initialized"
    
    ' init debug variable
    ml_DEBUG_CursorCount = mo_Db.CursorCount
    
    ' open code page cursor
    ml_codePageCursor = OpenCodePageCursor(mo_Db)
    
    ' get decimal separator for conversion from string to double
    ms_DecimalSeparator = Format(0, ".")
   
    Call GetUserRight(mo_userRights)
    
    'alloc detail cursor for each tab
    ReDim ml_DetailCursor(tbs_ClaimTabs(0).Tabs.Count - 1) As Long
    'set requests
    Call SafeRedimString(ms_detailRequests, tbs_ClaimTabs(0).Tabs.Count)
    Debug.Assert (UBound(ms_detailRequests, 1) = 5)
    ms_detailRequests(0) = "EXEC Clm_claim_sel '$Code$', '$LangCode$'"
    ms_detailRequests(1) = "EXEC Clm_Cost_t_lst '$Code$', '$LangCode$'"
    ms_detailRequests(2) = "EXEC Clm_Customer_t_lst '$Code$', '$LangCode$'"
    ms_detailRequests(3) = "EXEC Clm_Project_t_sel '$Code$', '$LangCode$'"
    ms_detailRequests(4) = "EXEC Clm_Item_t_lst '$Code$', '$LangCode$'"
    ms_detailRequests(5) = "EXEC Clm_Plant_t_sel '$Code$', '$LangCode$'"
    
    ' define updat requests
    Call SafeRedimString(ms_detailRequestsUpd, tbs_ClaimTabs(0).Tabs.Count)
    ms_detailRequestsUpd(0) = "EXEC Clm_upd '$ClaimCode$', '$Status$', '$Originator$', '$TerrCode$', $CLECode1$, $CLECode2$, $CRECode$, $CLOCode$, $CLOACode$, '$Internet$', '$DropFlag$', $DropDate$, $iConcurrency$, '$LOGINNAME$'" & SEP _
                            & "EXEC Clm_Claim_Statistic_upd '$ClaimCode$', '$LOGINNAME$'"
    ms_detailRequestsUpd(1) = "EXEC Clm_Cost_upd '$ClaimCode$', 1, '$CurrCode$', $CSSEstMatCost$, $CSSEstLabCost$, $CSSEstOthCost$, $CSSEstTotCost$, $iConcurrencyCost1$, '$LOGINNAME$'" & SEP _
                            & "EXEC Clm_Cost_upd '$ClaimCode$', 2, '$CurrCode$', $CSSProMatCost$, $CSSProLabCost$, $CSSProOthCost$, $CSSProTotCost$, $iConcurrencyCost2$, '$LOGINNAME$'" & SEP _
                            & "EXEC Clm_Cost_upd '$ClaimCode$', 3, '$CurrCode$', $CSSSetMatCost$, $CSSSetLabCost$, $CSSSetOthCost$, $CSSSetTotCost$, $iConcurrencyCost3$, '$LOGINNAME$'"
    ms_detailRequestsUpd(2) = "EXEC Clm_Customer_upd '$ClaimCode$', '$CLAWhoRaised$', $CLADistCode$, $CLASpecCode$, $CLAContCode$, $iConcurrency$"
    ms_detailRequestsUpd(3) = "EXEC Clm_project_upd '$ClaimCode$', $CPRCode$, $iConcurrency$" & SEP _
                            & "EXEC Clm_project_upd2 '$ClaimCode$', $CITSize$, '$UMCode$', '$CITCondition$', $ItemiConcurrency$"
    ms_detailRequestsUpd(4) = "EXEC Clm_Item_upd '$ClaimCode$', '$BISapCode$', $GTCode$, 0, $GMCode$, $CITDateInst$, '$CITProjDelay$', $CITVisitDate, '$CITVisitor$', '$CITSampleSent$', '$CITSampleDest$', '$CIT_sample_ReasonNo$', '$CITInvoiceNo$', $CITClaimSize$, '$CITClaimUMCode$', $CITDelivSize$, '$CITDelivUMCode$', $ItemiConcurrency$, '$LOGINNAME$'" & SEP _
                            & "EXEC Clm_Cost_upd_SAP '$ClaimCode$', 1, '$BISapCode$', $iConcurrencyCost1$, '$LOGINNAME$'" & SEP _
                            & "EXEC Clm_Cost_upd_SAP '$ClaimCode$', 2, '$BISapCode$', $iConcurrencyCost2$, '$LOGINNAME$'" & SEP _
                            & "EXEC Clm_Cost_upd_SAP '$ClaimCode$', 3, '$BISapCode$', $iConcurrencyCost3$, '$LOGINNAME$'" & SEP _
                            & "EXEC Clm_Plant_upd_SAP '$ClaimCode$', '$BISapCode$', $iConcurrencyPlant$, '$LOGINNAME$'"

    ms_detailRequestsUpd(5) = "EXEC Clm_Plant_upd '$ClaimCode$', '$MFGPCode$', '$SPCode$', '$Batch1$', '$Batch2$', '$Batch3$', '$Batch4$', $iConcurrencyPlant$, '$LOGINNAME$'"

    ms_detailRequestsAdd = "EXEC Clm_Claim_ins '$ClaimCode$', '$Status$', $ReportDate$, '$Originator$', '$CoordName$', '$SaleOffCode$', '$TerrCode$', $CLECode1$, $CLECode2$, $CRECode$, $CLOCode$, $CLOACode$, '$Internet$', '$DropFlag$', $DropDate$, '$LOGINNAME$'" & SEP _
                         & "EXEC Clm_Claim_Statistic_ins '$ClaimCode$', '$LOGINNAME$'" & SEP _
                         & "EXEC Clm_Item_ins '$ClaimCode$', '$BISapCode$', $GTCode$, 0, $GMCode$, $CITDateInst$, '$CITProjDelay$', $CITVisitDate, '$CITVisitor$', '$CITSampleSent$', '$CITSampleDest$', '$CIT_sample_ReasonNo$', '$CITInvoiceNo$', $CITClaimSize$, '$CITClaimUMCode$', $CITDelivSize$, '$CITDelivUMCode$', '$LOGINNAME$'" & SEP _
                         & "EXEC Claim_Cost_ins '$ClaimCode$', '$BISapCode$', 1" & SEP _
                         & "EXEC Claim_Cost_ins '$ClaimCode$', '$BISapCode$', 2" & SEP _
                         & "EXEC Claim_Cost_ins '$ClaimCode$', '$BISapCode$', 3" & SEP _
                         & "EXEC Clm_Plant_ins '$ClaimCode$', '$BISapCode$', '$MFGPCode$', '$SPCode$', '$Batch1$', '$Batch2$', '$Batch3$', '$Batch4$', '$LOGINNAME$'" & SEP _
                         & "EXEC Clm_updDescription '$ClaimCode$', 1"
    ms_detailRequestsDel = "1" & SEP1 & "EXEC Clm_Claim_del '$ClaimCode$', $iConcurrency$, '$LOGINNAME$'"

    ' init armDb
    Set tlb_Main.ArmDb = mo_Db
    Set grd_ClaimMain.ArmDb = mo_Db
    Set tvw_SearchList.ArmDb = mo_Db
    Set cbo_Gen2ndReason1.ArmDb = mo_Db
    Set cbo_Gen2ndReason2.ArmDb = mo_Db
    Set cbo_GenAction.ArmDb = mo_Db
    Set cbo_GenCoordinator.ArmDb = mo_Db
    Set cbo_GenCountry.ArmDb = mo_Db
    Set cbo_GenMainReason1.ArmDb = mo_Db
    Set cbo_GenMainReason2.ArmDb = mo_Db
    Set cbo_GenOutcome.ArmDb = mo_Db
    Set cbo_GenOutcomeAction.ArmDb = mo_Db
    Set cbo_GenRespSalesRep.ArmDb = mo_Db
    Set cbo_GenSalesMarket.ArmDb = mo_Db
    Set cbo_GenSalesOffice.ArmDb = mo_Db
    Set cbo_GenTerritory.ArmDb = mo_Db
    Set tlb_CostNoteTasks.ArmDb = mo_Db
    Set cbo_CostCurrency.ArmDb = mo_Db
    Set grd_CostNotes.ArmDb = mo_Db
    Set cbo_NoteCurrency.ArmDb = mo_Db
    Set cbo_ProUnitMeasure.ArmDb = mo_Db
    Set cbo_ItemUnitMeasureCS.ArmDb = mo_Db
    Set cbo_ItemUnitMeasureTD.ArmDb = mo_Db
    Set cbo_ItemGridManufac.ArmDb = mo_Db
    Set cbo_ItemGridType.ArmDb = mo_Db
    Set grd_ItemDescription.ArmDb = mo_Db
    Set cbo_SupSupplier.ArmDb = mo_Db
    Set cbo_MemoLanguage.ArmDb = mo_Db
    Set grd_ClaimMemoList.ArmDb = mo_Db
    Set grd_SelectCustList.ArmDb = mo_Db
    Set cbo_SelectCustCountry.ArmDb = mo_Db
    Set cbo_SelCustModCountry.ArmDb = mo_Db
    Set cbo_SelCustModType.ArmDb = mo_Db
    Set cbo_SelCustModCompany.ArmDb = mo_Db
    Set grd_SelectProjList.ArmDb = mo_Db
    Set cbo_SelProjModUnitMeassure.ArmDb = mo_Db
    Set cbo_SelProjModCountry.ArmDb = mo_Db
    Set cbo_SelectProjCountry.ArmDb = mo_Db
    Set cbo_SelectItemBaseMaterial.ArmDb = mo_Db
    Set cbo_SelectItemCategory.ArmDb = mo_Db
    Set cbo_SelectItemColour.ArmDb = mo_Db
    Set cbo_SelectItemDimensions.ArmDb = mo_Db
    Set cbo_SelectItemEdgeDetail.ArmDb = mo_Db
    Set cbo_SelectItemFamily.ArmDb = mo_Db
    Set cbo_SelectItemPattern.ArmDb = mo_Db
    Set cbo_SelectItemProductRange.ArmDb = mo_Db
    Set cbo_SelectItemShape.ArmDb = mo_Db
    Set cbo_SelectItemSurface.ArmDb = mo_Db
    Set grd_SelectItemList.ArmDb = mo_Db
    Set grd_linkedFiles.ArmDb = mo_Db

    ' Initialize language
    tlb_Main.Language = ms_LanguageCode
    cal_FilterAnyUpdated.Language = ms_LanguageCode
    cal_GenFinishDate.Language = ms_LanguageCode
    cal_GenInitDate.Language = ms_LanguageCode
    cal_GenReportDate.Language = ms_LanguageCode
    cal_GenUpdateDate.Language = ms_LanguageCode
    tlb_CostNoteTasks.Language = ms_LanguageCode
    cal_NoteDateIssued.Language = ms_LanguageCode
    cal_ItemVisitDate.Language = ms_LanguageCode
    cal_ItemInstalationDate.Language = ms_LanguageCode
    cal_SupPlantCloseDate.Language = ms_LanguageCode
    cal_SelProjModStartDate.Language = ms_LanguageCode
    
    ' init controls and set layouts
    Call ChangeCharset(UserControl.Controls, GetCodePageFromLanguage(ml_codePageCursor, ms_LanguageCode))
    Call InitComponents
    'Call InitCtrlSize
    ReDim Preserve mua_ActiveMode(0)
    mua_ActiveMode(UBound(mua_ActiveMode)) = ArmScreenMode.smMain

    ' load labels
    Call LoadLabels(mo_Db, UserControl.Controls, C_MODULE_LOC_NAME, ms_LanguageCode)

    mb_Initialized = True

    ' init entry screen
    Call SetOptionButtonCode(opt_SearchView, IIf(mo_userRights.loginCoordinator, "O", "P"))
    ' display starting face
    Call ResetScreen(activeScreenMode)
    Call UpdateUI
    pic_ReloadSearch.Visible = False
    Call loadSearchTreeView(tvw_SearchList, GetOptionButtonCode(opt_SearchView), IIf(GetOptionButtonCode(opt_SearchFilter) = "D", cal_FilterAnyUpdated.date_dt, 0))
    tvw_SearchList.Visible = True
    
    Load_A_COM = True
    Exit Function
ErrHandler:
    Call ErrorMessage("Load_A_Com")
End Function

' uninitialize user control
Public Sub Unload_A_COM()
On Error GoTo ErrHandler

    Call mo_Db.Close(ml_itemDescLabelsCursor)
    ml_itemDescLabelsCursor = 0
    Call mo_Db.Close(ml_treeNodeDescCursor)
    ml_treeNodeDescCursor = 0
    Call mo_Db.Close(ml_codePageCursor)
    ml_codePageCursor = 0

    ' close detail cursors
    Call Item_CloseCursors
    Call Memo_CloseCursor
    Call Note_CloseCursor
    Call Cust_CloseCursor
    Call Proj_CloseCursor

    Call tlb_Main.Unload_A_COM
    Call grd_ClaimMain.Unload_A_COM
    Call tvw_SearchList.Unload_A_COM
    Call cbo_Gen2ndReason1.Unload_A_COM
    Call cbo_Gen2ndReason2.Unload_A_COM
    Call cbo_GenAction.Unload_A_COM
    Call cbo_GenCoordinator.Unload_A_COM
    Call cbo_GenCountry.Unload_A_COM
    Call cbo_GenMainReason1.Unload_A_COM
    Call cbo_GenMainReason2.Unload_A_COM
    Call cbo_GenOutcome.Unload_A_COM
    Call cbo_GenOutcomeAction.Unload_A_COM
    Call cbo_GenRespSalesRep.Unload_A_COM
    Call cbo_GenSalesMarket.Unload_A_COM
    Call cbo_GenSalesOffice.Unload_A_COM
    Call cbo_GenTerritory.Unload_A_COM
    Call tlb_CostNoteTasks.Unload_A_COM
    Call cbo_CostCurrency.Unload_A_COM
    Call grd_CostNotes.Unload_A_COM
    Call cbo_NoteCurrency.Unload_A_COM
    Call cbo_ProUnitMeasure.Unload_A_COM
    Call cbo_ItemUnitMeasureCS.Unload_A_COM
    Call cbo_ItemUnitMeasureTD.Unload_A_COM
    Call cbo_ItemGridManufac.Unload_A_COM
    Call cbo_ItemGridType.Unload_A_COM
    Call grd_ItemDescription.Unload_A_COM
    Call cbo_SupSupplier.Unload_A_COM
    Call cbo_MemoLanguage.Unload_A_COM
    Call grd_ClaimMemoList.Unload_A_COM
    Call grd_SelectCustList.Unload_A_COM
    Call cbo_SelectCustCountry.Unload_A_COM
    Call cbo_SelCustModCountry.Unload_A_COM
    Call cbo_SelCustModType.Unload_A_COM
    Call cbo_SelCustModCompany.Unload_A_COM
    Call grd_SelectProjList.Unload_A_COM
    Call cbo_SelProjModUnitMeassure.Unload_A_COM
    Call cbo_SelProjModCountry.Unload_A_COM
    Call cbo_SelectProjCountry.Unload_A_COM
    Call cbo_SelectItemBaseMaterial.Unload_A_COM
    Call cbo_SelectItemCategory.Unload_A_COM
    Call cbo_SelectItemColour.Unload_A_COM
    Call cbo_SelectItemDimensions.Unload_A_COM
    Call cbo_SelectItemEdgeDetail.Unload_A_COM
    Call cbo_SelectItemFamily.Unload_A_COM
    Call cbo_SelectItemPattern.Unload_A_COM
    Call cbo_SelectItemProductRange.Unload_A_COM
    Call cbo_SelectItemShape.Unload_A_COM
    Call cbo_SelectItemSurface.Unload_A_COM
    Call grd_SelectItemList.Unload_A_COM
    Call grd_linkedFiles.Unload_A_COM
        

    mb_Initialized = False

' DEBUG
    Debug.Assert (mo_Db.CursorCount = ml_DEBUG_CursorCount)
    
    Set mo_Db = Nothing
    
    Exit Sub
ErrHandler:
    If ml_itemDescLabelsCursor <> 0 Then
        Call mo_Db.Close(ml_itemDescLabelsCursor)
        ml_itemDescLabelsCursor = 0
    End If
    If ml_treeNodeDescCursor <> 0 Then
        Call mo_Db.Close(ml_treeNodeDescCursor)
    End If
    If ml_codePageCursor <> 0 Then
        Call mo_Db.Close(ml_codePageCursor)
    End If
     Call ErrorMessage("Unload_A_COM")
End Sub
' ******************************* PUBLIC USER CONTROL METHODS **************************************

' ************************************************************************************
' ***************************** SECURITY FUNCTIONS ***********************************
' ************************************************************************************

Private Sub GetUserRight(ByRef ao_rights As UserRights_t)
Const C_REQ As String = "EXEC Claim_Security_Alias_sel"
On Error GoTo ErrorHandler
    Dim ll_Cursor As Long
    
' default user rights
    ao_rights.allowAdd = False
    ao_rights.loginCoordinator = False

    ll_Cursor = OpenSQLSafe(mo_Db, C_REQ)
    Debug.Assert (ll_Cursor <> 0)
    
    Call mo_Db.First(ll_Cursor)
    Debug.Assert (Not mo_Db.EOF(ll_Cursor))
    If Not mo_Db.EOF(ll_Cursor) Then
        If mo_Db.GetFields(ll_Cursor, 0) <> "" Then
            ao_rights.allowAdd = True
            ao_rights.loginCoordinator = True
        End If
    End If

    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    Exit Sub
ErrorHandler:
    If ll_Cursor <> 0 Then Call mo_Db.Close(ll_Cursor)
    Call ErrorHandler("GetUserRight()")
End Sub

Private Sub ApplyRightsOnToolbar(ByRef ao_Toolbar As ToolbarControl, Optional ByVal av_itemKeyVal As Variant = Empty)
On Error GoTo ErrorHandler
    
    ao_Toolbar.ButtonVisible("A") = mo_userRights.allowAdd
    
    If Not IsEmpty(av_itemKeyVal) Then
        Debug.Assert (IsArray(av_itemKeyVal))
        Debug.Assert (UBound(av_itemKeyVal) >= 3)   ' index 3 = CSA_Function
        ao_Toolbar.ButtonVisible("B") = av_itemKeyVal(3) = "COORD" Or av_itemKeyVal(3) = "CONTACT"
        ao_Toolbar.ButtonVisible("C") = av_itemKeyVal(3) = "COORD"
        ao_Toolbar.ButtonVisible("D") = True
    Else
        ao_Toolbar.ButtonVisible("B") = False
        ao_Toolbar.ButtonVisible("C") = False
        ao_Toolbar.ButtonVisible("D") = False
    End If
    Exit Sub
ErrorHandler:
    Call ErrorHandler("ApplyRightsOnToolbar()")
End Sub
' ************************************************************************************

' ************************************************************************************
' **************************** REDIM FUNCTION ****************************************
' ************************************************************************************
Sub SafeRedimString(ByRef as_Array() As String, al_NumElements As Long)

On Error GoTo ErrHandler

  If al_NumElements = 0 Then
          ReDim as_Array(-1 To -1)
  Else
          'MS REDIMM
          Call SafeRedimPreserve(as_Array, al_NumElements - 1)
  End If
  Exit Sub
ErrHandler:
    Call ErrorHandler("SafeRedimString()")
End Sub

Sub SafeRedim(ByRef av_Array() As Variant, al_NumElements As Long)

On Error GoTo ErrHandler

  If al_NumElements = 0 Then
          ReDim av_Array(-1 To -1)
  Else
          'MS REDIMM
          Call SafeRedimPreserve(av_Array, al_NumElements - 1)
  End If
  Exit Sub
ErrHandler:
    Call ErrorHandler("SafeRedim()")
End Sub
' **************************** REDIM FUNCTION ****************************************

' ************************************************************************************
' ********************** ERROR-HANDLING SUPPORT FUNCTIONS ****************************
' ************************************************************************************
' Standard error handler
Private Sub ErrorHandler(ByVal as_Fct As String)
    Err.Raise Err.Number, as_Fct & SEP1 & Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
End Sub

' display standard error message
' Params:
' as_Fct (String) - Error CallStack
' display standard error message
Private Sub ErrorMessage(ByVal as_Fct As String)
    If Err.Number = QuietException Then Exit Sub
    Dim ll_oldMP As MousePointerConstants
    
    'save mouse pointer
    ll_oldMP = Screen.MousePointer
    Screen.MousePointer = vbDefault
    
    Dim ls_ErrSource As String
    Dim ls_errDescription As String
    ls_ErrSource = Extender.Name & "." & as_Fct & SEP1 & Err.Source
    ls_errDescription = Err.Description
    
    Call LogMessage(App.ProductName & " exception raised. Err.Number:" & Err.Number & ", Err.Source:" & ls_ErrSource & ", Err.Description " & ls_errDescription & ".", "E", False)
    Call MsgBox("Error occured, please contact IT" & vbCrLf & ls_ErrSource & vbCrLf & "Description: " & ls_errDescription, , "Error message: " & as_Fct)
    
    'restore mouse pointer
    Screen.MousePointer = ll_oldMP
End Sub


' logs message to database
Private Sub LogMessage(ByVal as_LogMsg As String, Optional ByVal as_LogType As String = "I", Optional ab_throwException As Boolean = True)
On Error GoTo ErrHandler
Const InsertReq As String = "EXEC A_log_ins $UCODE$, '$LOGTYPE$', '$MSG$', '$APP$'"
    Dim ls_req As String
    Dim ll_Cursor As Long
    
    ls_req = Replace(InsertReq, "$UCODE$", CStr(ml_UserCode), , , vbTextCompare)
    ls_req = Replace(ls_req, "$APP$", SqlStr(C_MODULE_NAME & " " & App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision, 50), , , vbTextCompare)
    ls_req = Replace(ls_req, "$MSG$", SqlStr(as_LogMsg, 4000), , , vbTextCompare)
    ls_req = Replace(ls_req, "$LOGTYPE$", SqlStr(as_LogType), 1, , vbTextCompare)
    
    Call ExecuteSQLSafe(mo_Db, ls_req)
    
    Exit Sub
ErrHandler:
    If ab_throwException Then Call ErrorHandler("LogMessage - " & Err.Number & ": " & Err.Description)
End Sub

' ********************** ERROR-HANDLING SUPPORT FUNCTIONS ****************************


' ************************************************************************************
' **************************** FRAMEWORK FUNCTIONS ***********************************
' ************************************************************************************
Private Property Get activeScreenMode(Optional ByVal al_fromTop As Long = 0) As ArmScreenMode
On Error GoTo ErrHandler
    Debug.Assert (IsArray(mua_ActiveMode))
    activeScreenMode = mua_ActiveMode(UBound(mua_ActiveMode) - al_fromTop)
    Exit Property
ErrHandler:
     Call ErrorHandler("activeScreenMode(Get)")
End Property

Private Sub popScreenMode()
On Error GoTo ErrHandler
    Debug.Assert (UBound(mua_ActiveMode) >= 1)
    
    If UBound(mua_ActiveMode) < 1 Then
        Call SendMessage("E", ErrMsgFatal, "Something went wrong. Please restart Application!", , vbCritical)
        Exit Sub
    End If
    
    ReDim Preserve mua_ActiveMode(UBound(mua_ActiveMode) - 1)
    Exit Sub
ErrHandler:
    Call ErrorHandler("popScreenMode")
End Sub

Private Sub InitComponents()
Const CL_REQUEST_TB As String = "EXEC A_ToolbarDef_sel NULL, NULL, $screenID$, NULL"
On Error GoTo ErrHandler
    mb_Initializing = True
    pic_ReloadSearch.Picture = LoadResPicture(116, vbResIcon)
    pic_reloadItemDesc.Picture = LoadResPicture(116, vbResIcon)
    btn_costMoveEst.Picture = LoadResPicture(37, vbResIcon)
    

    ' load toolbars
    Dim ll_Cursor As Long
    ll_Cursor = OpenSQLSafe(mo_Db, Replace(CL_REQUEST_TB, "$screenID$", C_TLB_SCREEN_ID, , , vbTextCompare), ArmSQLAny)
    
    If mo_Db.Find(ll_Cursor, "id", C_TLB_MAIN) < 0 Then
        Call Err.Raise(CompFncFailed, "mo_Db.Find", "Toolbar definition is missing." & "(" & C_TLB_MAIN & ")")
    End If
    Call tlb_Main.Load_A_COM
    Call tlb_Main.SetToolbarInfoStringParameters(mo_Db.GetFields(ll_Cursor, "info"), "031")

    If mo_Db.Find(ll_Cursor, "id", C_TLB_COSTNOTE) < 0 Then
        Call Err.Raise(CompFncFailed, "mo_Db.Find", "Toolbar definition is missing." & "(" & C_TLB_COSTNOTE & ")")
    End If
    Call tlb_CostNoteTasks.Load_A_COM
    Call tlb_CostNoteTasks.SetToolbarInfoStringParameters(mo_Db.GetFields(ll_Cursor, "info"), "032")
    Call tlb_CostNoteTasks.DisplayFace("0")


    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    ' init tags
    tbs_ClaimTabs(0).Tag = "tbs_ClaimTabsEdit"
    tbs_ClaimTabs(1).Tag = "tbs_ClaimTabsAdd"
    tbs_ClaimTabs(2).Tag = "tbs_ClaimTabsPlantEdit"
    fra_frames(0).Tag = "fra_main"
    fra_frames(1).Tag = "fra_detail"
    fra_frames(2).Tag = "fra_memo"
    fra_frames(3).Tag = "fra_SelectCustomer"
    fra_frames(4).Tag = "fra_SelectCusMod"
    fra_frames(5).Tag = "fra_ClaimSelectProject"
    fra_frames(6).Tag = "fra_SelectProjMod"
    fra_frames(7).Tag = "fra_ClaimSelectItem"
    
    Call InitTabStrip(tbs_ClaimTabs(0))
    ' map tab keys
    Debug.Assert (tbs_ClaimTabs(1).Tabs.Count = 3)
    tbs_ClaimTabs(1).Tabs(1).Key = tbs_ClaimTabs(0).Tabs(1).Key
    tbs_ClaimTabs(1).Tabs(2).Key = tbs_ClaimTabs(0).Tabs(5).Key
    tbs_ClaimTabs(1).Tabs(3).Key = tbs_ClaimTabs(0).Tabs(6).Key
    ' map keys to plant edit tabstrip
    tbs_ClaimTabs(2).Tabs(1).Key = tbs_ClaimTabs(0).Tabs(6).Key
    
    Call InitTabStrip(tbs_CustTabs)
    
    cal_GenReportDate.reinit_cal
    cal_GenReportDate.date_courte = Format(Now, "dd\/mm\/yyyy")
    
    cal_FilterAnyUpdated.reinit_cal
    cal_FilterAnyUpdated.date_courte = ""   'Format(Now, "dd\/mm\/yyyy")
    md_actSelectedFilterDate = 0

    cal_GenFinishDate.reinit_cal
    cal_GenFinishDate.date_courte = Format(Now, "dd\/mm\/yyyy")
    
    cal_GenInitDate.reinit_cal
    cal_GenInitDate.date_courte = Format(Now, "dd\/mm\/yyyy")

    cal_GenUpdateDate.reinit_cal
    cal_GenUpdateDate.date_courte = Format(Now, "dd\/mm\/yyyy")
    
    cal_NoteDateIssued.reinit_cal
    cal_NoteDateIssued.date_courte = Format(Now, "dd\/mm\/yyyy")

    cal_ItemInstalationDate.reinit_cal
    cal_ItemInstalationDate.date_courte = Format(Now, "dd\/mm\/yyyy")
    
    cal_ItemVisitDate.reinit_cal
    cal_ItemVisitDate.date_courte = Format(Now, "dd\/mm\/yyyy")

    cal_SupPlantCloseDate.reinit_cal
    cal_SupPlantCloseDate.date_courte = Format(Now, "dd\/mm\/yyyy")

    cal_SelProjModStartDate.reinit_cal
    cal_SelProjModStartDate.date_courte = Format(Now, "dd\/mm\/yyyy")

    grd_ItemDescription.Load_A_COM
    grd_ItemDescription.UnBound = True
    grd_ItemDescription.AllowSort = False
    grd_ItemDescription.Title = "#Description"
    Call grd_ItemDescription.SetColumns(Array( _
    Join(Array("BIDESCID", 2000, 1, "", "#Type"), SEP), _
    Join(Array("BIVALUE", 2000, 0, "", "#Value", "", "", "Left"), SEP)))

    grd_ClaimMain.Load_A_COM
    grd_ClaimMain.Title = "#Claims"
    grd_ClaimMain.MultiSelect = False
    grd_ClaimMain.SetColumns Array( _
        Join(Array("CLA_code", 1400, 1, "CLA_code", "#Claim code"), SEP), _
        Join(Array("CT_code", 0, 1, "CT_code", "#Country"), SEP), _
        Join(Array("CLA_status", 0, 1, "CLA_status", "#Status"), SEP), _
        Join(Array("CSA_function", 0, 1, "CSA_function", "#Function"), SEP), _
        Join(Array("CCU_desc_1", 3000, 0, "CCU_desc_1", "#Distributor"), SEP), _
        Join(Array("CCU_desc_3", 3000, 0, "CCU_desc_3", "#Contractor"), SEP))

    grd_CostNotes.Load_A_COM
    grd_CostNotes.Title = "#Notes"
    grd_CostNotes.MultiSelect = False
    grd_CostNotes.SetColumns Array( _
        Join(Array("CCR_Order", 0, 1, "CCR_Order", "#Order"), SEP), _
        Join(Array("CCR_info", 3000, 0, "CCR_info", "#Code note"), SEP), _
        Join(Array("CCR_date", 1000, 0, "CCR_date", "#Date issued"), SEP), _
        Join(Array("CCR_amount", 1000, 0, "CCR_amount", "#Amount"), SEP), _
        Join(Array("CURR_desc", 4000, 0, "CURR_desc", "#Currency"), SEP))
    
    
    
    grd_ClaimMemoList.Load_A_COM
    grd_ClaimMemoList.Title = "#Comments"
    grd_ClaimMemoList.MultiSelect = False
    grd_ClaimMemoList.SetColumns Array( _
        Join(Array("CMM_CODE", 0, 1, "language_code", "#Language code"), SEP), _
        Join(Array("SECURITY", 0, 0, "SECURITY", "#security"), SEP), _
        Join(Array("CMM_CODE_DESC", 2000, 0, "language_desc", "#Language"), SEP), _
        Join(Array("CMM_TITLE", 2000, 0, "CMM_title", "#Title"), SEP), _
        Join(Array("CMM_DESC", 6000, 0, "CMM_desc", "#Description"), SEP))

    grd_SelectCustList.Load_A_COM
    grd_SelectCustList.Title = "#Customers"
    grd_SelectCustList.MultiSelect = False
    grd_SelectCustList.SetColumns Array( _
        Join(Array("CCU_code", 0, 1, "CCU_code", "#Code"), SEP), _
        Join(Array("COMP_code", 0, 1, "COMP_code", ""), SEP), _
        Join(Array("CCU_desc", 4000, 0, "CCU_desc", "#Description"), SEP))

    grd_SelectProjList.Load_A_COM
    grd_SelectProjList.Title = "#Projects"
    grd_SelectProjList.MultiSelect = False
    grd_SelectProjList.SetColumns Array( _
        Join(Array("SP_code", 0, 1, "SP_code", "#Code"), SEP), _
        Join(Array("SP_desc", 4000, 0, "SP_desc", "#Description"), SEP))

    grd_SelectItemList.Load_A_COM
    grd_SelectItemList.Title = "#Items"
    grd_SelectItemList.MultiSelect = False
    grd_SelectItemList.SetColumns Array( _
        Join(Array("BI_SAP_Code", 1400, 1, "BI_SAP_Code", "#SAP code"), SEP), _
        Join(Array("Origin_Type", 0, 0, "Origin_Type", "#Origin Type"), SEP), _
        Join(Array("BI_SHORT_Code", 0, 0, "BI_SHORT_Code", "#MKT code"), SEP), _
        Join(Array("BI_Type", 430, 0, "BI_Type", "#Type"), SEP), _
        Join(Array("BI_Desc", 2500, 0, "BI_Desc", "#Description"), SEP), _
        Join(Array("BML_Desc", 1500, 0, "BML_Desc", "#Base material"), SEP), _
        Join(Array("PF_Desc", 1200, 0, "PF_Desc", "#Product family"), SEP), _
        Join(Array("COLOUR_Desc", 700, 0, "COLOUR_Desc", "#Colour"), SEP), _
        Join(Array("PP_Desc", 800, 0, "PP_Desc", "#Pattern"), SEP), _
        Join(Array("PS_Desc", 1100, 0, "PS_Desc", "#Product range"), SEP), _
        Join(Array("PE_Desc", 900, 0, "PE_Desc", "#Edge detail"), SEP), _
        Join(Array("SF_Desc", 900, 0, "SF_Desc", "#Surface"), SEP), _
        Join(Array("SH_Desc", 1000, 0, "SH_Desc", "#Shape"), SEP), _
        Join(Array("PD_Desc", 1500, 0, "PD_Desc", "#Dimension"), SEP), _
        Join(Array("Drop_Flag", 430, 0, "Drop_Flag", "#Drop"), SEP))
        
    grd_linkedFiles.Load_A_COM
    grd_linkedFiles.Title = "#Linked files and emails"
    grd_linkedFiles.MultiSelect = False
    
    grd_linkedFiles.AllowExcelExport = True
    grd_linkedFiles.ExportTitles = True
    grd_linkedFiles.AllowSort = False
    grd_linkedFiles.ExportOnlyVisibleColumns = True
    grd_linkedFiles.OleDropMode = flexOLEDragAutomatic
    Call grd_linkedFiles.SetColumns(Array( _
          Join(Array("CLA_FILE_ID", 0, 1, "CLA_FILE_ID", "#CLA_FILE_ID", "Number", "", "Left"), SEP) _
        , Join(Array("CLA_ZIP_ID", 0, 0, "CLA_ZIP_ID", "#CLA_ZIP_ID", "Number", "", "Left"), SEP) _
        , Join(Array("FILE_Name", 2000, 0, "FILE_Name", "#File name", "String", "", "Left"), SEP) _
        , Join(Array("EML_Subject", 2500, 0, "EML_Subject", "#Subject", "String", "", "Left"), SEP) _
        , Join(Array("EML_SenderName", 2100, 0, "EML_SenderName", "#From", "String", "", "Left"), SEP) _
        , Join(Array("EML_To", 2100, 0, "EML_To", "#To", "String", "", "Left"), SEP) _
        , Join(Array("EML_Attachements", 500, 0, "EML_Attachements", "#Attachements", "Number", "", "Left"), SEP) _
        , Join(Array("EML_CreationTime", 1200, 0, "EML_CreationTime", "#Creation time", "Date", "", "Left"), SEP) _
        , Join(Array("iConcurrency", 0, 0, "iConcurrency", "", "Number", "", "Left"), SEP) _
        , Join(Array("EmailInfoIconc", 0, 0, "EmailInfoIconc", "", "Number", "", "Left"), SEP) _
        ))

    cbo_Gen2ndReason1.Load_A_COM
    cbo_Gen2ndReason1.FirstBlankItem = True
    cbo_Gen2ndReason1.Request = "EXEC Clm_Nature_cbo '" & ms_LanguageCode & "'"
    
    cbo_Gen2ndReason2.Load_A_COM
    cbo_Gen2ndReason2.FirstBlankItem = True
    cbo_Gen2ndReason2.Request = ""
    
    cbo_GenAction.Load_A_COM
    cbo_GenAction.FirstBlankItem = False
    cbo_GenAction.Request = "EXEC Clm_Recommendation_cbo '" & ms_LanguageCode & "'"
    
    cbo_GenCoordinator.Load_A_COM
    cbo_GenCoordinator.FirstBlankItem = False
    cbo_GenCoordinator.Request = "EXEC Clm_Claim_Coordinator_t_lst '" & ms_LoginName & "'"
    
    cbo_GenCountry.Load_A_COM
    cbo_GenCountry.FirstBlankItem = False
    cbo_GenCountry.Request = ""
    
    cbo_GenMainReason1.Load_A_COM
    cbo_GenMainReason1.FirstBlankItem = True
    cbo_GenMainReason1.Request = "EXEC Clm_Nature_cbo '" & ms_LanguageCode & "'"
    
    cbo_GenMainReason2.Load_A_COM
    cbo_GenMainReason2.FirstBlankItem = True
    cbo_GenMainReason2.Request = ""
    
    cbo_GenRespSalesRep.Load_A_COM
    cbo_GenRespSalesRep.FirstBlankItem = False
    cbo_GenRespSalesRep.Request = ""
    
    cbo_GenSalesMarket.Load_A_COM
    cbo_GenSalesMarket.FirstBlankItem = False
    cbo_GenSalesMarket.Request = ""
    
    cbo_GenSalesOffice.Load_A_COM
    cbo_GenSalesOffice.FirstBlankItem = False
    cbo_GenSalesOffice.Request = ""
  
    cbo_GenTerritory.Load_A_COM
    cbo_GenTerritory.FirstBlankItem = False
    cbo_GenTerritory.Request = ""
    
    cbo_GenOutcome.Load_A_COM
    cbo_GenOutcome.FirstBlankItem = True
    cbo_GenOutcome.Request = "EXEC Clm_OutCome_cbo '" & ms_LanguageCode & "'"
    
    cbo_GenOutcomeAction.Load_A_COM
    cbo_GenOutcomeAction.FirstBlankItem = True
    cbo_GenOutcomeAction.Request = "EXEC Clm_OutComeAction_cbo '" & ms_LanguageCode & "'"
    
    cbo_CostCurrency.Load_A_COM
    cbo_CostCurrency.FirstBlankItem = False
    cbo_CostCurrency.Request = "EXEC Clm_Currencies_cbo '" & ms_LanguageCode & "'"
    
    cbo_NoteCurrency.Load_A_COM
    cbo_NoteCurrency.FirstBlankItem = False
    cbo_NoteCurrency.Request = "EXEC Clm_Currencies_cbo '" & ms_LanguageCode & "'"

    cbo_ProUnitMeasure.Load_A_COM
    cbo_ProUnitMeasure.FirstBlankItem = False
    cbo_ProUnitMeasure.Request = "EXEC Clm_Unit_of_measure_cbo '" & ms_LanguageCode & "'"

    cbo_ItemGridManufac.Load_A_COM
    cbo_ItemGridManufac.FirstBlankItem = False
    cbo_ItemGridManufac.Request = "EXEC Clm_Grid_Manufacturer_cbo '" & ms_LanguageCode & "'"
    
    cbo_ItemUnitMeasureCS.Load_A_COM
    cbo_ItemUnitMeasureCS.FirstBlankItem = False
    cbo_ItemUnitMeasureCS.Request = "EXEC Clm_Unit_of_measure_cbo '" & ms_LanguageCode & "'"
    
    cbo_ItemUnitMeasureTD.Load_A_COM
    cbo_ItemUnitMeasureTD.FirstBlankItem = False
    cbo_ItemUnitMeasureTD.Request = "EXEC Clm_Unit_of_measure_cbo '" & ms_LanguageCode & "'"
    
    cbo_ItemGridType.Load_A_COM
    cbo_ItemGridType.FirstBlankItem = False
    cbo_ItemGridType.Request = ""
    
    cbo_SupSupplier.Load_A_COM
    cbo_SupSupplier.FirstBlankItem = False
    cbo_SupSupplier.Request = ""

    cbo_MemoLanguage.Load_A_COM
    cbo_MemoLanguage.FirstBlankItem = False
    cbo_MemoLanguage.Request = ""

    cbo_SelectCustCountry.Load_A_COM
    cbo_SelectCustCountry.FirstBlankItem = False
    cbo_SelectCustCountry.Request = "EXEC Clm_CountriesCust_cbo '" & ms_LanguageCode & "'"

    cbo_SelCustModCountry.Load_A_COM
    cbo_SelCustModCountry.FirstBlankItem = False
    cbo_SelCustModCountry.Request = "EXEC Clm_Countries_cbo2 '" & ms_LanguageCode & "'"
        
    cbo_SelCustModType.Load_A_COM
    cbo_SelCustModType.FirstBlankItem = False
    cbo_SelCustModType.Request = "EXEC Clm_CustomerType_cbo '" & ms_LanguageCode & "'"
    
    cbo_SelCustModCompany.Load_A_COM
    cbo_SelCustModCompany.FirstBlankItem = False
    cbo_SelCustModCompany.Request = "EXEC companies_cbo"

    cbo_SelectProjCountry.Load_A_COM
    cbo_SelectProjCountry.FirstBlankItem = True
    cbo_SelectProjCountry.Request = "EXEC Clm_CountriesProj_cbo '" & ms_LanguageCode & "'"

    cbo_SelProjModUnitMeassure.Load_A_COM
    cbo_SelProjModUnitMeassure.FirstBlankItem = False
    cbo_SelProjModUnitMeassure.Request = "EXEC Clm_Unit_of_measure_cbo '" & ms_LanguageCode & "'"
    
    cbo_SelProjModCountry.Load_A_COM
    cbo_SelProjModCountry.FirstBlankItem = False
    cbo_SelProjModCountry.Request = "EXEC Clm_Countries_cbo2 '" & ms_LanguageCode & "'"

    cbo_SelectItemBaseMaterial.Load_A_COM
    cbo_SelectItemBaseMaterial.FirstBlankItem = True
    cbo_SelectItemBaseMaterial.Request = ""

    cbo_SelectItemCategory.Load_A_COM
    cbo_SelectItemCategory.FirstBlankItem = True
    cbo_SelectItemCategory.Request = "EXEC Clm_categories_cbo '" & ms_LanguageCode & "'"
    
    cbo_SelectItemColour.Load_A_COM
    cbo_SelectItemColour.FirstBlankItem = True
    cbo_SelectItemColour.Request = ""
    
    cbo_SelectItemDimensions.Load_A_COM
    cbo_SelectItemDimensions.FirstBlankItem = True
    cbo_SelectItemDimensions.Request = ""
    
    cbo_SelectItemEdgeDetail.Load_A_COM
    cbo_SelectItemEdgeDetail.FirstBlankItem = True
    cbo_SelectItemEdgeDetail.Request = ""
    
    cbo_SelectItemFamily.Load_A_COM
    cbo_SelectItemFamily.FirstBlankItem = True
    cbo_SelectItemFamily.Request = ""
    
    cbo_SelectItemPattern.Load_A_COM
    cbo_SelectItemPattern.FirstBlankItem = True
    cbo_SelectItemPattern.Request = ""
    
    cbo_SelectItemProductRange.Load_A_COM
    cbo_SelectItemProductRange.FirstBlankItem = True
    cbo_SelectItemProductRange.Request = ""
    
    cbo_SelectItemShape.Load_A_COM
    cbo_SelectItemShape.FirstBlankItem = True
    cbo_SelectItemShape.Request = ""
    
    cbo_SelectItemSurface.Load_A_COM
    cbo_SelectItemSurface.FirstBlankItem = True
    cbo_SelectItemSurface.Request = ""

    tvw_SearchList.Load_A_COM
    tvw_SearchList.Language = ms_LanguageCode
    tvw_SearchList.Levels = 3
    tvw_SearchList.StartDemandLevel = 1
    tvw_SearchList.UseImages = True
    tvw_SearchList.Images = Array(1, 1, 1)
    tvw_SearchList.SelectedImages = Array(2, 2, 2)
    tvw_SearchList.RemoveNodeDuplicity = True
    
    tvw_SearchList.Visible = False
    pic_ReloadSearch.Visible = True
    
    ' set mandatory labels to bold
    ' general
    GetControl(lbl_Label, "lbl_ReportDate").FontBold = True
    fra_GenStatus.FontBold = True
    GetControl(lbl_Label, "lbl_Coordinator").FontBold = True
    GetControl(lbl_Label, "lbl_SalesOffice").FontBold = True
    GetControl(lbl_Label, "lbl_SalesMarket").FontBold = True
    GetControl(lbl_Label, "lbl_Country").FontBold = True
    GetControl(lbl_Label, "lbl_Territory").FontBold = True
    GetControl(lbl_Label, "lbl_Originator").FontBold = True
    
    ' item
    GetControl(lbl_Label, "lbl_Item").FontBold = True
    
    ' plant all modes
    GetControl(lbl_Label, "lbl_Plant").FontBold = True
    
    ' project
    GetControl(lbl_Label, "lbl_ProjectSize").FontBold = True
    
    

    mb_Initializing = False
    Exit Sub
ErrHandler:
    If ll_Cursor <> 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    Call ErrorHandler("InitComponents")
End Sub

' initialize controls position and size
Private Sub InitCtrlSize()
On Error GoTo ErrHandler
    Dim ll_frmSpace As Long, lLeft As Long, lTop As Long, lWidth As Long, lHeight As Long
    Dim lo_auxObj As Object
    
    ll_frmSpace = 60
    
    Call SafeCtrlMove(fra_SearchView, 0, 0)
    
    lTop = fra_SearchView.Top + fra_SearchView.Height + ll_frmSpace
    Call SafeCtrlMove(fra_SearchFilter, 0, lTop)
    Call SafeCtrlMove(cal_FilterAnyUpdated, fra_SearchFilter.Left + fra_SearchFilter.Width - cal_FilterAnyUpdated.Width - ll_frmSpace, lTop + fra_SearchFilter.Height - cal_FilterAnyUpdated.Height - 180)
    
    lTop = lTop + fra_SearchFilter.Height
    Call SafeCtrlMove(fra_SearchList, 0, lTop, fra_SearchList.Width, UserControl.ScaleHeight - lTop)
    
    
    lTop = fra_SearchList.FontSize * 20
    Call SafeCtrlMove(tvw_SearchList, ll_frmSpace, lTop, fra_SearchList.Width - (ll_frmSpace * 2), fra_SearchList.Height - (lTop + ll_frmSpace))
    
    lLeft = fra_SearchView.Left + fra_SearchView.Width + ll_frmSpace
    lWidth = UserControl.Extender.Width - lLeft
    Call SafeCtrlMove(tlb_Main, lLeft, 0, lWidth)
    
    lTop = tlb_Main.Top + tlb_Main.Height
    For Each lo_auxObj In fra_frames
        Call SafeCtrlMove(lo_auxObj, lLeft, lTop, lWidth, UserControl.ScaleHeight - lTop)
    Next
    
    lTop = fra_frames(0).FontSize * 20
    Call SafeCtrlMove(grd_ClaimMain, ll_frmSpace, lTop, fra_frames(0).Width - (ll_frmSpace * 2), fra_frames(0).Height - (lTop + ll_frmSpace))
    For Each lo_auxObj In tbs_ClaimTabs
        Call SafeCtrlMove(lo_auxObj, ll_frmSpace, lTop, fra_frames(1).Width - (ll_frmSpace * 2))
    Next
    Call SafeCtrlMove(fra_ClaimMemoMod, ll_frmSpace, fra_frames(2).Height - fra_ClaimMemoMod.Height - ll_frmSpace, fra_frames(2).Width - 2 * ll_frmSpace)
    Call SafeCtrlMove(grd_ClaimMemoList, ll_frmSpace, lTop, fra_frames(2).Width - 2 * ll_frmSpace, fra_frames(2).Height - fra_ClaimMemoMod.Height - lTop - ll_frmSpace)
    Call SafeCtrlMove(cbo_MemoLanguage, cbo_MemoLanguage.Left, cbo_MemoLanguage.Top, fra_ClaimMemoMod.Width - cbo_MemoLanguage.Left - ll_frmSpace)
    Call SafeCtrlMove(txt_MemoTitle, txt_MemoTitle.Left, txt_MemoTitle.Top, fra_ClaimMemoMod.Width - txt_MemoTitle.Left - ll_frmSpace)
    Call SafeCtrlMove(txt_MemoComment, txt_MemoComment.Left, txt_MemoComment.Top, fra_ClaimMemoMod.Width - txt_MemoComment.Left - ll_frmSpace, fra_ClaimMemoMod.Height - txt_MemoComment.Top - ll_frmSpace)
    Call SafeCtrlMove(txt_MemoCommentEng, txt_MemoCommentEng.Left, txt_MemoCommentEng.Top, fra_ClaimMemoMod.Width - txt_MemoCommentEng.Left - ll_frmSpace, fra_ClaimMemoMod.Height - txt_MemoCommentEng.Top - ll_frmSpace)
    Call SafeCtrlMove(grd_SelectCustList, grd_SelectCustList.Left, lTop, fra_frames(3).Width - grd_SelectCustList.Left - ll_frmSpace, fra_frames(3).Height - lTop - ll_frmSpace)
    Call SafeCtrlMove(grd_SelectProjList, grd_SelectProjList.Left, lTop, fra_frames(5).Width - grd_SelectProjList.Left - ll_frmSpace, fra_frames(3).Height - lTop - ll_frmSpace)
    Call SafeCtrlMove(grd_SelectItemList, ll_frmSpace, grd_SelectItemList.Top, fra_frames(7).Width - ll_frmSpace * 2, fra_frames(3).Height - grd_SelectItemList.Top - ll_frmSpace)
    
    lTop = tbs_ClaimTabs(0).Top + tbs_ClaimTabs(0).Height
    For Each lo_auxObj In fra_detailFrames
        Call SafeCtrlMove(lo_auxObj, ll_frmSpace, lTop, fra_frames(1).Width - 2 * ll_frmSpace, fra_frames(1).Height - lTop - ll_frmSpace)
    Next
    
    Call SafeCtrlMove(grd_CostNotes, grd_CostNotes.Left, grd_CostNotes.Top, grd_CostNotes.Width, fra_detailFrames(1).Height - grd_CostNotes.Top - ll_frmSpace)
    Call SafeCtrlMove(tlb_CostNoteTasks, tlb_CostNoteTasks.Left, tlb_CostNoteTasks.Top, tlb_CostNoteTasks.Width, fra_detailFrames(1).Height - tlb_CostNoteTasks.Top - ll_frmSpace)
    
    Call SafeCtrlMove(grd_ItemDescription, grd_ItemDescription.Left, grd_ItemDescription.Top, grd_ItemDescription.Width, fra_detailFrames(4).Height - grd_ItemDescription.Top - ll_frmSpace)
    Call SafeCtrlMove(fra_ItemExtension, fra_ItemExtension.Left, fra_ItemExtension.Top, fra_ItemExtension.Width, fra_detailFrames(4).Height - fra_ItemExtension.Top - ll_frmSpace)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("InitCtrlSize")
End Sub

' Load the labels of a containers
Private Sub LoadLabels(ByRef ao_Armdb As ArmDb, ByRef ao_Container As Object, ByVal as_ScreenName As String, ByVal as_Language As String)
Dim lc_Labels As Long       ' The cursor of the labels
Dim lc_Control As Control   ' A control of the container
Dim li_idx As Integer, li_Count As Integer
Dim li_Label As Integer      ' A label idx
Dim ls_Request As String
    
    On Error GoTo Trace_Err
    Call LockScreen(True)
    
    ls_Request = "exec Screen_csts_secure '" & as_ScreenName & "','" & as_Language & "'"
    lc_Labels = OpenSQLSafe(ao_Armdb, ls_Request)
    
    If lc_Labels = 0 Then
        GoTo Trace_End
    End If
    
    
    li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", "title", , 1)
    If li_Label >= 0 Then
        ms_Title = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
    End If
    
    ' Iterate the container for loading the label of each element which has defined a tag
    For Each lc_Control In ao_Container
        Select Case UCase(TypeName(lc_Control))
            Case UCase("TabStrip") ' Component is a tabstrip, we load the caption of each tab defined
                Dim lo_Tbs
                Set lo_Tbs = lc_Control ' Cast for use of intellisense
                li_Count = lo_Tbs.Tabs.Count
                For li_idx = 1 To li_Count
                    If lo_Tbs.Tabs(li_idx).Tag <> "" Then
                        li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_Tbs.Tabs(li_idx).Tag, , 1)
                        If li_Label >= 0 Then
                            lo_Tbs.Tabs(li_idx).Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                        End If
                    End If
                Next
                Set lo_Tbs = Nothing
            
            Case UCase("ListView") ' Component is a listview, we load the caption of each columns
                Dim lo_ListView As ListView
                Set lo_ListView = lc_Control
                li_Count = lo_ListView.ColumnHeaders.Count
                For li_idx = 1 To li_Count
                    If lo_ListView.ColumnHeaders(li_idx).Tag <> "" Then
                        li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_ListView.ColumnHeaders(li_idx).Tag, , 1)
                        If li_Label >= 0 Then
                            lo_ListView.ColumnHeaders(li_idx).Text = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                        End If
                    End If
                Next
                Set lo_ListView = Nothing
        
            Case UCase("TextBox")  ' Component is a textbox
                Dim lo_TextBox As TextBox
                Set lo_TextBox = lc_Control
                If lo_TextBox.Tag <> "" Then
                    li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_TextBox.Tag, , 1)
                    If li_Label >= 0 Then
                        lo_TextBox.Text = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                    End If
                End If
                Set lo_TextBox = Nothing
            
            Case UCase("OptionButton") ' Component is option button
                Dim lValues As Variant
                Dim ls_Value As String
                lValues = Split(lc_Control.Tag, SEP)
                        
                If UBound(lValues) > 0 Then
                    ls_Value = lValues(0)
                Else
                    ls_Value = lc_Control.Tag
                End If
                
                If ls_Value <> "" Then
                    'Print #1, lc_Control.Tag & "," & lc_Control.Caption
                    li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", ls_Value, , 1)
                    If li_Label >= 0 Then
                        lc_Control.Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                    End If
                End If
            Case UCase("Label"), UCase("Frame"), UCase("CommandButton"), UCase("CheckBox")
                If lc_Control.Tag <> "" Then
                    'Print #1, lc_Control.Tag & "," & lc_Control.Caption
                    li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lc_Control.Tag, , 1)
                    If li_Label >= 0 Then
                        lc_Control.Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                    End If
                End If
            Case UCase("ArmGrid")
                li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lc_Control.Tag, , 1)
                If li_Label >= 0 Then
                  Call lc_Control.LoadConstants(ptStatic, ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT"), ctColumns)
                End If
                li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lc_Control.Name, , 1)
                If li_Label >= 0 Then
                  lc_Control.Title = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                End If
            Case UCase("Menu")
                If lc_Control.Name <> "" Then
                    li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lc_Control.Name, , 1)
                    If li_Label >= 0 Then
                        lc_Control.Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                    End If
                End If
        End Select
    Next
        
Trace_End:
    ' save filtered values for grid
    ml_itemDescLabelsCursor = mo_Db.Filter(lc_Labels, "Field_name", "begin", "BI_")
    ' save filter for adding new node into last level of tree
    ml_treeNodeDescCursor = mo_Db.Filter(lc_Labels, "Field_name", "=", "INITIALIZED")
    ml_treeNodeDescCursor = mo_Db.JoinOr(ml_treeNodeDescCursor, mo_Db.Filter(lc_Labels, "Field_name", "=", "REFUSED"), 1)
    ml_treeNodeDescCursor = mo_Db.JoinOr(ml_treeNodeDescCursor, mo_Db.Filter(lc_Labels, "Field_name", "=", "SETTLED"), 1)
    ml_treeNodeDescCursor = mo_Db.JoinOr(ml_treeNodeDescCursor, mo_Db.Filter(lc_Labels, "Field_name", "=", "FINALIZED"), 1)
    
    Call ao_Armdb.Close(lc_Labels)
    Call LockScreen(False)
    Exit Sub
    
Trace_Err:
    Call LockScreen(False)
    Call ao_Armdb.Close(lc_Labels)
End Sub

' throw error message if detected
Private Function ThrowErrorMessage(ByVal lu_Msg As ErrMsg) As Boolean
On Error GoTo ErrHandler
    ThrowErrorMessage = False
    Select Case lu_Msg
        Case ErrMsgNumericRequired
            SendMessage ms_LanguageCode, lu_Msg, "#Number required."
            ThrowErrorMessage = True
            Exit Function
        Case ErrMsgMandatoryAreEmpty
            SendMessage ms_LanguageCode, lu_Msg, "#Mandatory fields are not filled."
            ThrowErrorMessage = True
            Exit Function
        Case ErrMsgMandatoryByFilter
            SendMessage ms_LanguageCode, lu_Msg, "#Data selection is mandatory if filter is selected."
            ThrowErrorMessage = True
            Exit Function
        Case ErrMsgBadValue
            SendMessage ms_LanguageCode, lu_Msg, "#Wrong value entered."
            ThrowErrorMessage = True
            Exit Function
        Case ErrMsgNoValidRateExists
            SendMessage ms_LanguageCode, lu_Msg, "#No valid rate exists. Please contact IT support."
            ThrowErrorMessage = True
            Exit Function
        Case ErrMsgTotalClaimsTooLarge
            SendMessage ms_LanguageCode, lu_Msg, "#Total claims value > than the amount you are authorized to approve. Please get the claims settled via Sales management."
            ThrowErrorMessage = True
            Exit Function
    End Select
    Exit Function
ErrHandler:
    Call ErrorHandler("ThrowErrorMessage")
End Function

Private Sub LockScreen(ByVal ab_lock As Boolean)

    Dim ll_errNumber As Long, ls_ErrSrc As String, ls_ErrDesc As String
    ll_errNumber = Err.Number
    ls_ErrSrc = Err.Source
    ls_ErrDesc = Err.Description

On Error GoTo ErrHandler
    Static ll_Count As Long
    Static ll_Mousepointer As Long
    Static lb_Locked As Boolean
      
    ll_Count = ll_Count + IIf(ab_lock, 1, -1)
    Debug.Assert (ll_Count >= 0)
    
    ' First lock
    If Not lb_Locked And ab_lock Then
        ll_Mousepointer = Screen.MousePointer
        Screen.MousePointer = vbHourglass
        LockWindowUpdate UserControl.hwnd
        lb_Locked = True
    End If
    
    ' Unlock
    If ll_Count = 0 Then
        DoEvents ' Flush events
        LockWindowUpdate 0
        UserControl.Refresh ' Repaint immediately
        Screen.MousePointer = ll_Mousepointer
        lb_Locked = False
    End If
    
    Err.Number = ll_errNumber
    Err.Source = ls_ErrSrc
    Err.Description = ls_ErrDesc
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("LockScreen")
End Sub

Private Sub ResetScreen(ByVal au_mode As ArmScreenMode)
On Error GoTo ErrHandler
    ' apply face
    Dim lo_ctrl As Object

    Select Case au_mode
        Case smMain
            Set lo_ctrl = GetControl(fra_frames, "fra_main")
            
            ' enable filtering a browsing
            Call SetEnabled(GetContainedControlsChain(fra_SearchFilter), True)
            Call SetEnabled(GetContainedControlsChain(fra_SearchList), True)
            Call SetEnabled(GetContainedControlsChain(fra_SearchView), True)
            Call SetEnabledCtrl(cal_FilterAnyUpdated, GetOptionButtonCode(opt_SearchFilter, "A") = "D")
            
        Case smAdd
            ' we are in Add section
            ' disable all controls
            Call SetEnabled(GetContainedControlsChain(GetControl(fra_frames, "fra_detail")), False)
            ' disable filtering a browsing
            Call SetEnabled(GetContainedControlsChain(fra_SearchFilter), False)
            Call SetEnabled(GetContainedControlsChain(fra_SearchList), False)
            Call SetEnabled(GetContainedControlsChain(fra_SearchView), False)
            Call SetEnabledCtrl(cal_FilterAnyUpdated, False)
            
            ' enable necessary controls
            ' others wil be managed via events
            Call SetEnabledCtrl(opt_GenStatus(0), True)
            Call SetEnabledCtrl(cal_GenReportDate, True)
            Call SetEnabledCtrl(cbo_GenCoordinator, True)
            Call SetEnabledCtrl(cbo_GenMainReason1, True)
            Call SetEnabledCtrl(cbo_GenAction, True)
            Call SetEnabledCtrl(cbo_GenOutcome, True)
            Call SetEnabledCtrl(grd_CostNotes, True)
            Call SetEnabled(opt_ItemProjectDelay, True)
            Call SetEnabled(opt_ItemSampleSent, True)
            Call SetEnabledCtrl(txt_ItemClaimSize, True)
            Call SetEnabledCtrl(txt_ItemTotalDelivery, True)
            Call SetEnabledCtrl(txt_ItemInvoiceNo, True)
            Call SetEnabledCtrl(cal_ItemVisitDate, True)
            Call SetEnabledCtrl(cal_ItemInstalationDate, True)
            Call SetEnabledCtrl(cbo_ItemUnitMeasureCS, True)
            Call SetEnabledCtrl(cbo_ItemUnitMeasureTD, True)
            Call SetEnabledCtrl(cbo_ItemGridManufac, True)
            Call SetEnabledCtrl(grd_ItemDescription, True)
            Call SetEnabledCtrl(cmd_SelectItem, True)
            Call SetEnabledCtrl(pic_reloadItemDesc, True)
            
            Call SetEnabledCtrl(cbo_SupSupplier, True)
            Call SetEnabledCtrl(txt_SupBatchNumber1, True)
            Call SetEnabledCtrl(txt_SupBatchNumber2, True)
            Call SetEnabledCtrl(txt_SupBatchNumber3, True)
            Call SetEnabledCtrl(txt_SupBatchNumber4, True)
            
            ' set up tabs
            Call SetEnabled(tbs_ClaimTabs, True)
        Case smUpdate
            ' we are in Update section
            ' disable all controls
            Call SetEnabled(GetContainedControlsChain(GetControl(fra_frames, "fra_detail")), False)
            ' disable filtering a browsing
            Call SetEnabled(GetContainedControlsChain(fra_SearchFilter), False)
            Call SetEnabled(GetContainedControlsChain(fra_SearchList), False)
            Call SetEnabled(GetContainedControlsChain(fra_SearchView), False)
            Call SetEnabledCtrl(cal_FilterAnyUpdated, False)
            
            ' enable necessary controls
            ' others wil be managed via events
            Call SetEnabled(opt_GenStatus, True)
            Call SetEnabledCtrl(cbo_GenCoordinator, True)
            Call SetEnabledCtrl(cbo_GenMainReason1, True)
            Call SetEnabledCtrl(cbo_GenAction, True)
            Call SetEnabledCtrl(cbo_GenOutcome, True)
            Call SetEnabledCtrl(cmd_GenComments, True)
            Call SetEnabledCtrl(cmd_linkedFiles, True)
            Call SetEnabled(GetContainedControlsChain(frm_linkedFiles), True)
            Call SetEnabledCtrl(grd_CostNotes, True)
            Call SetEnabled(opt_CusWhoRaised, True)
            Call SetEnabledCtrl(cbo_CostCurrency, True)
            
            Call SetEnabled(GetContainedControlsChain(fra_CostEstimatedCost), True)
            Call SetEnabled(GetContainedControlsChain(fra_CostSettlementCost), True)
            Call SetEnabledCtrl(txt_CostEstTotalCost, False)
            Call SetEnabledCtrl(txt_CostSetTotalCost, False)
            
            Call SetEnabled(cmd_SelectCust, True)
            Call SetEnabled(cmd_ResetCust, True)
            Call SetEnabled(opt_ProSiteCondition, True)
            
            Call SetEnabledCtrl(txt_ProSize, True)
            Call SetEnabledCtrl(cbo_ProUnitMeasure, True)
            Call SetEnabledCtrl(cmd_SelectProj, True)
            Call SetEnabledCtrl(cmd_ResetProj, True)
            Call SetEnabledCtrl(grd_CostNotes, True)
            Call SetEnabledCtrl(grd_CostNotes, True)
            Call SetEnabled(opt_ItemProjectDelay, True)
            Call SetEnabled(opt_ItemSampleSent, True)
            
            Call SetEnabledCtrl(txt_ItemClaimSize, True)
            Call SetEnabledCtrl(txt_ItemTotalDelivery, True)
            Call SetEnabledCtrl(txt_ItemInvoiceNo, True)
            Call SetEnabledCtrl(cal_ItemVisitDate, True)
            Call SetEnabledCtrl(cal_ItemInstalationDate, True)
            Call SetEnabledCtrl(cbo_ItemUnitMeasureCS, True)
            Call SetEnabledCtrl(cbo_ItemUnitMeasureTD, True)
            Call SetEnabledCtrl(cbo_ItemGridManufac, True)
            Call SetEnabledCtrl(grd_ItemDescription, True)
            Call SetEnabledCtrl(cmd_SelectItem, True)
            Call SetEnabledCtrl(pic_reloadItemDesc, True)
            Call SetEnabledCtrl(cbo_SupSupplier, True)
            Call SetEnabledCtrl(txt_SupBatchNumber1, True)
            Call SetEnabledCtrl(txt_SupBatchNumber2, True)
            Call SetEnabledCtrl(txt_SupBatchNumber3, True)
            Call SetEnabledCtrl(txt_SupBatchNumber4, True)
            Call SetEnabledCtrl(cmd_SupComments, True)
            
            ' set up tabs
            Call SetEnabled(tbs_ClaimTabs, True)
            Call SetEnabledCtrl(tbs_CustTabs, True)
            
        Case smDelete
            ' we are in PreView section
            ' disable all controls
            Call SetEnabled(GetContainedControlsChain(GetControl(fra_frames, "fra_detail")), False)
            ' disable filtering a browsing
            Call SetEnabled(GetContainedControlsChain(fra_SearchFilter), False)
            Call SetEnabled(GetContainedControlsChain(fra_SearchList), False)
            Call SetEnabled(GetContainedControlsChain(fra_SearchView), False)
            Call SetEnabledCtrl(cal_FilterAnyUpdated, False)
            
            Call SetEnabledCtrl(grd_CostNotes, True)
            Call SetEnabledCtrl(pic_reloadItemDesc, True)
            Call SetEnabledCtrl(grd_ItemDescription, True)
            
            ' set up tabs
            Call SetEnabled(tbs_ClaimTabs, True)
            Call SetEnabledCtrl(tbs_CustTabs, True)
            
        Case smView
            ' we are in PreView section
            ' disable all controls
            Call SetEnabled(GetContainedControlsChain(GetControl(fra_frames, "fra_detail")), False)
            ' disable filtering a browsing
            Call SetEnabled(GetContainedControlsChain(fra_SearchFilter), False)
            Call SetEnabled(GetContainedControlsChain(fra_SearchList), False)
            Call SetEnabled(GetContainedControlsChain(fra_SearchView), False)
            Call SetEnabledCtrl(cal_FilterAnyUpdated, False)
            
            Call SetEnabledCtrl(grd_CostNotes, True)
            Call SetEnabledCtrl(cmd_GenComments, True)
            Call SetEnabledCtrl(cmd_linkedFiles, True)
            Call SetEnabled(GetContainedControlsChain(frm_linkedFiles), True)
            Call SetEnabledCtrl(cmd_SupComments, True)
            Call SetEnabledCtrl(pic_reloadItemDesc, True)
            Call SetEnabledCtrl(grd_ItemDescription, True)

            ' set up tabs
            Call SetEnabled(tbs_ClaimTabs, True)
            Call SetEnabledCtrl(tbs_CustTabs, True)
        Case smMemoMain
            ' we are in memo screen
            Call SetEnabled(GetContainedControlsChain(GetControl(fra_frames, "fra_memo")), False)
            Call SetEnabledCtrl(grd_ClaimMemoList, True)
        Case smMemoUpdate, smMemoAdd
            Call SetEnabled(GetContainedControlsChain(GetControl(fra_frames, "fra_memo")), False)
            Call SetEnabled(GetContainedControlsChain(fra_ClaimMemoMod), True)
            Call SetEnabledCtrl(cbo_MemoLanguage, au_mode = smMemoAdd)
            Call SetEnabledCtrl(txt_MemoCommentEng, False)
        Case smMemoDelete
            Call SetEnabled(GetContainedControlsChain(GetControl(fra_frames, "fra_memo")), False)
        Case smNotesAdd, smNotesUpdate, smNotesDelete
            Call SetEnabled(GetContainedControlsChain(fra_ClaimNoteMod), au_mode <> smNotesDelete)
            Call SetEnabled(tbs_ClaimTabs, False)
            Call SetEnabledCtrl(grd_CostNotes, False)
        Case smCustMain
            ' we are in customer screen
            Call SetEnabled(GetContainedControlsChain(GetControl(fra_frames, "fra_SelectCustomer")), True)
        Case smCustAdd, smCustUpdate, smCustDelete, smCustView
            ' we are in customer screen
            Call SetEnabled(GetContainedControlsChain(GetControl(fra_frames, "fra_SelectCusMod")), au_mode <> smCustDelete And au_mode <> smCustView)
        Case smProjMain
            ' we are in project screen
            Call SetEnabled(GetContainedControlsChain(GetControl(fra_frames, "fra_ClaimSelectProject")), True)
        Case smProjAdd, smProjUpdate, smProjDelete, smProjView
            ' we are in customer screen
            Call SetEnabled(GetContainedControlsChain(GetControl(fra_frames, "fra_SelectProjMod")), au_mode <> smProjDelete And au_mode <> smProjView)
        Case smItemMain
            ' we are in Select item screen
            Call SetEnabled(GetContainedControlsChain(GetControl(fra_frames, "fra_ClaimSelectItem")), True)
        Case Else
            Debug.Assert (False)
    End Select

    Exit Sub
ErrHandler:
    Call ErrorHandler("ResetScreen()")
End Sub

Private Sub UpdateUI(Optional ByVal au_mode As ArmScreenMode = ArmScreenMode.smRefreshOnly)
On Error GoTo ErrHandler

    ' set active face
    If au_mode <> smRefreshOnly Then
        If UBound(mua_ActiveMode) = C_SCREENMODE_STACK_SIZE - 1 Then
            ' move array left
            Debug.Print ("Stack is too small. Increase C_SCREENMODE_STACK_SIZE constant please.")
            Dim ll_Index As Long
            For ll_Index = 1 To UBound(mua_ActiveMode)
                mua_ActiveMode(ll_Index - 1) = mua_ActiveMode(ll_Index)
            Next
        Else
            ' allocate one more item
            ReDim Preserve mua_ActiveMode(UBound(mua_ActiveMode) + 1)
        End If
        mua_ActiveMode(UBound(mua_ActiveMode)) = au_mode
    End If

    ' apply face
    Dim lo_ctrl As Object

    ' hide all frames
    For Each lo_ctrl In fra_frames
        lo_ctrl.Visible = False
    Next
    frm_linkedFiles.Visible = False
    tlb_Main.Visible = False
    tlb_Main.Redraw = False
    Dim ls_actStatus  As String
    ls_actStatus = GenGetStatus()

    ' we have clean screen we can display proper controls
    Select Case activeScreenMode
        Case smMain
            Set lo_ctrl = GetControl(fra_frames, "fra_main")
            lo_ctrl.Visible = True
            
            Call tlb_Main.DisplayFace(C_TOOLBARFACE_ITEM_LST)
            Call ApplyRightsOnToolbar(tlb_Main, grd_ClaimMain.SelectedKey(0))
            tlb_Main.Visible = True
        Case smAdd
            ' we are in Add section
            Set lo_ctrl = GetControl(fra_frames, "fra_detail")
            lo_ctrl.Visible = True
            pic_reloadItemDesc.Visible = (grd_ItemDescription.Rows = 0)
            
            btn_costMoveEst.Visible = False

            Call tlb_Main.DisplayFace(C_TOOLBARFACE_ITEM_MTNC)
            tlb_Main.Visible = True
        Case smUpdate
            ' we are in Update section
            Set lo_ctrl = GetControl(fra_frames, "fra_detail")
            lo_ctrl.Visible = True
            pic_reloadItemDesc.Visible = (grd_ItemDescription.Rows = 0)
            fra_ClaimNoteMod.Visible = False
            fra_CostEstimatedCost.Visible = True
            fra_CostSettlementCost.Visible = (ls_actStatus = "S")
            btn_costMoveEst.Visible = (ls_actStatus = "S")
            cbo_CostCurrency.Visible = True
            ' HARDCODED !!!!!!! lbl_Currency for cbo_costCurrency
            lbl_Label(19).Visible = True
            
            tlb_CostNoteTasks.Visible = True
            Call tlb_Main.DisplayFace(C_TOOLBARFACE_ITEM_MTNC)
            Call tlb_CostNoteTasks.DisplayFace(C_TOOLBARFACE_NOTES_LST)
            tlb_Main.Visible = True
        Case smDelete
            ' we are in PreView section
            Set lo_ctrl = GetControl(fra_frames, "fra_detail")
            lo_ctrl.Visible = True
            pic_reloadItemDesc.Visible = (grd_ItemDescription.Rows = 0)
            fra_ClaimNoteMod.Visible = False
            fra_CostEstimatedCost.Visible = True
            fra_CostSettlementCost.Visible = (ls_actStatus = "S")
            btn_costMoveEst.Visible = False
            cbo_CostCurrency.Visible = True
            ' HARDCODED !!!!!!! lbl_Currency for cbo_costCurrency
            lbl_Label(19).Visible = True
            
            tlb_CostNoteTasks.Visible = False
            Call tlb_Main.DisplayFace(C_TOOLBARFACE_ITEM_VIEW)
            tlb_Main.ButtonVisible("Y") = False
            tlb_Main.ButtonVisible("Z") = False
            tlb_Main.Visible = True
        Case smView
            ' we are in preview section
            Set lo_ctrl = GetControl(fra_frames, "fra_detail")
            lo_ctrl.Visible = True
            pic_reloadItemDesc.Visible = (grd_ItemDescription.Rows = 0)
            fra_ClaimNoteMod.Visible = False
            fra_CostEstimatedCost.Visible = True
            fra_CostSettlementCost.Visible = (ls_actStatus = "S")
            btn_costMoveEst.Visible = False
            cbo_CostCurrency.Visible = True
            ' HARDCODED !!!!!!! lbl_Currency for cbo_costCurrency
            lbl_Label(19).Visible = True
            
            tlb_CostNoteTasks.Visible = False
            Call tlb_Main.DisplayFace(C_TOOLBARFACE_ITEM_LST)
            tlb_Main.ButtonVisible("M") = False
            Call ApplyRightsOnToolbar(tlb_Main, grd_ClaimMain.SelectedKey(0))
            tlb_Main.ButtonVisible("A") = False
            tlb_Main.Visible = True
        Case smMemoMain
            ' we are in memo screen
            Set lo_ctrl = GetControl(fra_frames, "fra_memo")
            lo_ctrl.Visible = True
            txt_MemoCommentEng.Visible = False
            txt_MemoComment.Height = fra_ClaimMemoMod.Height - txt_MemoComment.Top - 60
            
            Call tlb_Main.DisplayFace(C_TOOLBARFACE_MEMO_MTNC)
            Dim lb_securityValue As Boolean
            lb_securityValue = grd_ClaimMemoList.Row <> -1
            If lb_securityValue Then
                lb_securityValue = (activeScreenMode(1) = smUpdate) And (grd_ClaimMemoList.SelectedLine(0, "SECURITY") = 1)
            End If
            
            tlb_Main.ButtonVisible("A") = (activeScreenMode(1) = smUpdate)    ' only if item is in update mode
            tlb_Main.ButtonVisible("B") = lb_securityValue
            tlb_Main.ButtonVisible("C") = lb_securityValue
            tlb_Main.Visible = True
        Case smMemoAdd, smMemoUpdate, smMemoDelete
            ' we are in memo screen update mode
            Set lo_ctrl = GetControl(fra_frames, "fra_memo")
            lo_ctrl.Visible = True
            txt_MemoCommentEng.Visible = (cbo_MemoLanguage.Request <> "")
            txt_MemoComment.Height = fra_ClaimMemoMod.Height - txt_MemoComment.Top - IIf(txt_MemoCommentEng.Visible, txt_MemoCommentEng.Height + 60, 60)

            Call tlb_Main.DisplayFace(IIf(activeScreenMode = smMemoDelete, C_TOOLBARFACE_ITEM_VIEW, C_TOOLBARFACE_ITEM_MTNC))
            tlb_Main.ButtonVisible("Y") = False
            tlb_Main.ButtonVisible("Z") = False
            tlb_Main.Visible = True
        Case smNotesAdd, smNotesDelete, smNotesUpdate
            Set lo_ctrl = GetControl(fra_frames, "fra_detail")
            lo_ctrl.Visible = True
            fra_ClaimNoteMod.Visible = True
            fra_CostEstimatedCost.Visible = False
            fra_CostSettlementCost.Visible = False
            btn_costMoveEst.Visible = False
            cbo_CostCurrency.Visible = False
            ' HARDCODED !!!!!!! lbl_Currency for cbo_costCurrency
            lbl_Label(19).Visible = False
            
            Call tlb_CostNoteTasks.DisplayFace(IIf(activeScreenMode = smNotesDelete, C_TOOLBARFACE_NOTES_VIEW, C_TOOLBARFACE_NOTES_MTNC))
        Case smCustMain
            ' we are in customer screen
            Set lo_ctrl = GetControl(fra_frames, "fra_SelectCustomer")
            lo_ctrl.Visible = True
            Call tlb_Main.DisplayFace(IIf(GetOptionButtonCode(opt_SelectCustType, "Claim") = "Claim", C_TOOLBARFACE_CUST_LST, C_TOOLBARFACE_PROD_LST))
            tlb_Main.Visible = True
        Case smCustAdd, smCustUpdate, smCustDelete, smCustView
            ' we are in customer screen
            Set lo_ctrl = GetControl(fra_frames, "fra_SelectCusMod")
            lo_ctrl.Visible = True
            Call tlb_Main.DisplayFace(IIf(activeScreenMode = smCustDelete Or activeScreenMode = smCustView, C_TOOLBARFACE_ITEM_VIEW, C_TOOLBARFACE_ITEM_MTNC))
            tlb_Main.ButtonVisible("H") = activeScreenMode <> smCustView
            tlb_Main.ButtonVisible("Y") = activeScreenMode = smCustView
            tlb_Main.ButtonVisible("Z") = activeScreenMode = smCustView
            tlb_Main.Visible = True
        Case smProjMain
            ' we are in select project screen
            Set lo_ctrl = GetControl(fra_frames, "fra_ClaimSelectProject")
            lo_ctrl.Visible = True
            Call tlb_Main.DisplayFace(C_TOOLBARFACE_CUST_LST)
            tlb_Main.Visible = True
        Case smProjAdd, smProjUpdate, smProjDelete, smProjView
            ' we are in project screen
            Set lo_ctrl = GetControl(fra_frames, "fra_SelectProjMod")
            lo_ctrl.Visible = True
            Call tlb_Main.DisplayFace(IIf(activeScreenMode = smProjDelete Or activeScreenMode = smProjView, C_TOOLBARFACE_ITEM_VIEW, C_TOOLBARFACE_ITEM_MTNC))
            tlb_Main.ButtonVisible("H") = activeScreenMode <> smProjView
            tlb_Main.ButtonVisible("Y") = activeScreenMode = smProjView
            tlb_Main.ButtonVisible("Z") = activeScreenMode = smProjView
            tlb_Main.Visible = True
        Case smItemMain
            ' we are in Select item screen
            Set lo_ctrl = GetControl(fra_frames, "fra_ClaimSelectItem")
            lo_ctrl.Visible = True
            Call tlb_Main.DisplayFace(C_TOOLBARFACE_PROD_LST)
            tlb_Main.Visible = True
        Case Else
            Debug.Assert (False)
    End Select
    
    tlb_Main.Redraw = True

    ' to display face immidiatelly
    UserControl.Refresh
    Exit Sub
ErrHandler:
    Call ErrorHandler("UpdateUI()")
End Sub

Private Sub InitTabStrip(ByVal ao_tbStrip As MSComctlLib.TabStrip)
On Error GoTo ErrHandler
Dim lo_Object As Object
    For Each lo_Object In ao_tbStrip.Tabs
        lo_Object.Key = "_" & lo_Object.Index - 1
    Next
    Exit Sub
ErrHandler:
    Call ErrorHandler("InitTabStrip()")
End Sub

Private Sub UpdateTabStrip(ByVal ao_tbStrip As MSComctlLib.TabStrip, ByRef ao_tabs As Object)
On Error GoTo ErrHandler
Dim lo_Object As Object
    For Each lo_Object In ao_tabs
        lo_Object.Visible = (lo_Object.Index = CLng(Mid(ao_tbStrip.SelectedItem.Key, 2)))
    Next
    Exit Sub
ErrHandler:
    Call ErrorHandler("UpdateTabStrip()")
End Sub

Private Sub SetTabStripVisible(ByRef ao_tbStrip As MSComctlLib.TabStrip, ByRef ao_tabs As Object, ByVal ab_Visible As Boolean)
On Error GoTo ErrHandler
    ao_tbStrip.Visible = ab_Visible

    If ab_Visible Then
        Call UpdateTabStrip(ao_tbStrip, ao_tabs)
    Else
        Dim lo_Object As Object
        ' hide all tabs
        For Each lo_Object In ao_tabs
            lo_Object.Visible = False
        Next
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("SetTabStripVisible()")
End Sub

Private Function FormatD(ls_Date As String, ls_Format As String, Optional ls_SrcFormat As String = "dd/mm/yyyy") As String
On Error GoTo ErrHandler
    If ls_Date = "" Then
        FormatD = ""
        Exit Function
    End If
    
    Select Case ls_SrcFormat
         Case "dd/mm/yyyy", "dd.mm.yyyy"
            Select Case ls_Format
                Case "mm/dd/yyyy"
                    FormatD = Mid(ls_Date, 4, 2) & "/" & Mid(ls_Date, 1, 2) & "/" & Mid(ls_Date, 7, 4)
                Case "yyyymmdd"
                    FormatD = Mid(ls_Date, 7, 4) & Mid(ls_Date, 4, 2) & Mid(ls_Date, 1, 2)
                Case "ddd dd/mm/yyyy"
                    FormatD = Format(DateSerial(Mid(ls_Date, 7, 4), Mid(ls_Date, 4, 2), Mid(ls_Date, 1, 2)), "ddd") & " " & ls_Date
            End Select
    End Select
    Exit Function
ErrHandler:
    Call ErrorHandler("FormatD")
End Function

Private Sub LoadSearchGrid(ByRef ao_grid As ArmGrid, ByVal av_Requests As Variant, ByVal ab_UseReloadIcon As Boolean)
On Error GoTo ErrHandler
    If Not ao_grid.Load(av_Requests, False, , , ab_UseReloadIcon) Then
        Call Err.Raise(CompFncFailed, "ao_grid.Load")
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("LoadSearchGrid")
End Sub

' update searchlist view options
Private Sub loadSearchTreeView(ByRef ao_tvw As ArmTreeView, ByVal as_viewType As String, ByVal ao_dateFilter As Date)
On Error GoTo ErrHandler
    
     ao_tvw.NodeRequests = Array( _
        "EXEC Clm_Out_lst1" & as_viewType & " " & SQLDateTime(ao_dateFilter) & ", '" & ms_LanguageCode & "', '" & ms_LoginName & "'", _
        "EXEC Clm_Out_lst2" & as_viewType & " " & SQLDateTime(ao_dateFilter) & ", $0$, '" & ms_LanguageCode & "', '" & ms_LoginName & "'", _
        "EXEC Clm_Out_lst3" & as_viewType & " " & SQLDateTime(ao_dateFilter) & ", $1$, $0$, '" & SqlStr(GetStatusTranslation("INITIALIZED")) & "', '" & SqlStr(GetStatusTranslation("REFUSED")) & "', '" & SqlStr(GetStatusTranslation("SETTLED")) & "', '" & SqlStr(GetStatusTranslation("FINALIZED")) & "', '" & ms_LoginName & "'")
    
    ao_tvw.GridRequests = Array( _
        "EXEC Clm_Out_Items_lst" & as_viewType & " " & SQLDateTime(ao_dateFilter) & ", $0$, NULL, NULL, '" & ms_LoginName & "'", _
        "EXEC Clm_Out_Items_lst" & as_viewType & " " & SQLDateTime(ao_dateFilter) & ", $1$, $0$, NULL, '" & ms_LoginName & "'", _
        "EXEC Clm_Out_Items_lst" & as_viewType & " " & SQLDateTime(ao_dateFilter) & ", $1@1$, $1$, $0$, '" & ms_LoginName & "'")

    ao_tvw.FindRequests = Array( _
        "Clm_Out_Items_search1" & as_viewType & " " & SQLDateTime(ao_dateFilter) & ", $0$, '" & SqlStr(ms_LoginName, 15) & "', '" & ms_LanguageCode & "'", _
        "Clm_Out_Items_search2" & as_viewType & " " & SQLDateTime(ao_dateFilter) & ", $0$, '" & SqlStr(ms_LoginName, 15) & "', '" & ms_LanguageCode & "'", _
        "Clm_Out_Items_search3" & as_viewType & " " & SQLDateTime(ao_dateFilter) & ", $0$, '" & SqlStr(GetStatusTranslation("INITIALIZED")) & "', '" & SqlStr(GetStatusTranslation("REFUSED")) & "', '" & SqlStr(GetStatusTranslation("SETTLED")) & "', '" & SqlStr(GetStatusTranslation("FINALIZED")) & "', '" & SqlStr(ms_LoginName, 15) & "', '" & ms_LanguageCode & "'")
    
    If Not ao_tvw.LoadTree(LoadTypeChildsDemand) Then
        Err.Raise CompFncFailed, "ao_tvw.LoadTree", "Treeview of items cannot be loaded."
    End If
    ms_aktTvwPath = ""
    Exit Sub
ErrHandler:
    Call ErrorHandler("UpdateSearchList")
End Sub

' this will set requests at level3 to search for item insetead of searching for status
Private Sub SetTreeViewSearchRequestsItem(ByRef ao_tvw As ArmTreeView, ByVal as_viewType As String, ByVal ao_dateFilter As Date)
On Error GoTo ErrHandler
    ao_tvw.FindRequests = Array( _
        "Clm_Out_Items_search1" & as_viewType & " " & SQLDateTime(ao_dateFilter) & ", $0$, '" & SqlStr(ms_LoginName, 15) & "', '" & ms_LanguageCode & "'", _
        "Clm_Out_Items_search2" & as_viewType & " " & SQLDateTime(ao_dateFilter) & ", $0$, '" & SqlStr(ms_LoginName, 15) & "', '" & ms_LanguageCode & "'", _
        "Clm_Out_Items_search4" & as_viewType & " " & SQLDateTime(ao_dateFilter) & ", $0$, '" & SqlStr(ms_LoginName, 15) & "', '" & ms_LanguageCode & "'")
    Exit Sub
ErrHandler:
    Call ErrorHandler("UpdateSearchList")
End Sub

' retrieve selected code from option button group
Private Function GetOptionButtonCode(ByRef aao_OptionGroup As Object, Optional ByVal as_DefaultValue As String = "NULL", Optional ByVal al_codeIndex As Long = 1) As String
On Error GoTo ErrHandler
    GetOptionButtonCode = as_DefaultValue
    Dim lo_OptionButton As OptionButton
    For Each lo_OptionButton In aao_OptionGroup
        If lo_OptionButton.Value Then
            Dim lva_Values As Variant
            lva_Values = Split(lo_OptionButton.Tag, SEP)
            If UBound(lva_Values) >= al_codeIndex Then
                GetOptionButtonCode = lva_Values(al_codeIndex)
            Else
                GetOptionButtonCode = as_DefaultValue
            End If
        End If
    Next
    Exit Function
ErrHandler:
    Call ErrorHandler("GetOptionButtonCode")
End Function

' function will return Caption property if al_returnIndex is not valid
' if al_returnIndex = -1 .. return Tag property
Private Function GetOptionButtonTag(ByRef aao_OptionGroup As Object, ByVal al_compareIndex As Long, ByVal as_compareValue As String, Optional al_returnIndex As Long = -1, Optional ByVal as_DefaultValue As String = "") As String
On Error GoTo ErrHandler
    GetOptionButtonTag = as_DefaultValue
    Dim lo_OptionButton As OptionButton
    For Each lo_OptionButton In aao_OptionGroup
        Dim lva_Values As Variant
        lva_Values = Split(lo_OptionButton.Tag, SEP)
        If lva_Values(al_compareIndex) = as_compareValue Then
            If al_returnIndex <> -1 And UBound(lva_Values) >= al_returnIndex Then
                GetOptionButtonTag = lva_Values(al_returnIndex)
            Else
                If al_returnIndex = -1 Then
                    GetOptionButtonTag = lo_OptionButton.Tag
                Else
                    GetOptionButtonTag = lo_OptionButton.Caption
                End If
                Exit Function
            End If
        End If
    Next
    Exit Function
ErrHandler:
    Call ErrorHandler("GetOptionButtonTag")
End Function

Private Function GetContainedControlsChain(ByVal ao_parent As Object) As Collection
On Error GoTo ErrHandler
    Dim lo_retCollection As New Collection
    Dim lo_Control As Object
    
    For Each lo_Control In Controls
        If Not TypeOf lo_Control.Container Is SfbClaimManager Then
            If ao_parent.hwnd = lo_Control.Container.hwnd Then
                If TypeOf lo_Control Is Frame Then
                    Dim lo_aux_collection As New Collection
                    Dim ll_i As Long
                    Set lo_aux_collection = GetContainedControlsChain(lo_Control)
                    For ll_i = 1 To lo_aux_collection.Count
                        lo_retCollection.Add (lo_aux_collection.Item(ll_i))
                    Next
                Else
                    Call lo_retCollection.Add(lo_Control)
                End If
            End If
        End If
    Next
    Set GetContainedControlsChain = lo_retCollection
    Exit Function
ErrHandler:
    Call ErrorHandler("GetContainedControlsChain()")
End Function

' as_Name equals to Tag definition string

Private Function GetControl(ByVal ao_array As Object, ByVal as_Name As String) As Object
On Error GoTo ErrHandler
    Dim lo_ctrl As Object
    For Each lo_ctrl In ao_array
        If StrComp(lo_ctrl.Tag, as_Name, vbTextCompare) = 0 Then
            Set GetControl = lo_ctrl
            Exit For
        End If
    Next
    Exit Function
ErrHandler:
    Call ErrorHandler("GetControl()")
End Function

Private Sub SetEnabled(ByVal ao_srcCtrl As Object, ByVal ab_Value As Boolean)
On Error GoTo ErrHandler
    Dim lo_ctrl As Object
    For Each lo_ctrl In ao_srcCtrl
        Call SetEnabledCtrl(lo_ctrl, ab_Value)
    Next
    Exit Sub
ErrHandler:
     Call ErrorHandler("SetEnabled()")
End Sub

Private Sub SetEnabledCtrl(ByRef ao_ctrl As Control, ByVal ab_Value As Boolean)
On Error GoTo ErrHandler
        Select Case UCase(TypeName(ao_ctrl))
        Case "TEXTBOX"
            ao_ctrl.Locked = Not ab_Value
            ao_ctrl.BackColor = IIf(ab_Value, CL_COLOR_ENABLED, CL_COLOR_DISABLED)
        Case "TABSTRIP", "A_CALOCX", "ARMGRID", "ARMCOMBOBOX", "FRAME", "DIRLISTBOX", "DRIVELISTBOX", "FILELISTBOX", "OPTIONBUTTON", "ARMTREEVIEW", "COMMANDBUTTON", "PICTUREBOX"
            ao_ctrl.Enabled = ab_Value
        End Select
    Exit Sub
ErrHandler:
     Call ErrorHandler("SetEnabledCtrl()")
End Sub


' initialize view mode
Private Sub Item_ViewInit(ByVal as_detailKey As Variant, ByVal as_rights As String)
On Error GoTo ErrHandler
    Dim lo_editTab As MSComctlLib.TabStrip
    ' reset detail
    Set lo_editTab = setObjectVisible(tbs_ClaimTabs, "tbs_ClaimTabsEdit")
    Debug.Assert (Not lo_editTab Is Nothing)
    
    Call ResetScreen(ArmScreenMode.smView)
    Call Item_Clear
    
    ' loading values
    txt_GenReport.Text = CStr(as_detailKey(0))
    Call Item_LoadIconcurrencyCursor(txt_GenReport.Text)
    Call tbs_ClaimTabs_Click(lo_editTab.Index)
    
    Call UpdateUI(ArmScreenMode.smView)
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_ViewInit")
End Sub

' initialize add mode
Private Sub Item_AddInit()
On Error GoTo ErrHandler
    Dim lo_editTab As MSComctlLib.TabStrip
    Set lo_editTab = setObjectVisible(tbs_ClaimTabs, "tbs_ClaimTabsAdd")
    Debug.Assert (Not lo_editTab Is Nothing)
    
    ' close cursors if opened
    Call Item_CloseCursors
    
    ' clearing form
    Call ResetScreen(ArmScreenMode.smAdd)
    Call Item_Clear
    
    ' set detail cursors to -1
    Dim ll_Index As Long
    For ll_Index = 0 To UBound(ml_DetailCursor)
        Debug.Assert (ml_DetailCursor(ll_Index) = 0)
        ml_DetailCursor(ll_Index) = -1
    Next
    txt_GenReport.Text = ""
    ' set values/default values into controls
    Call Item_LoadValues(-1)
    Call Item_ApplyLogic(ArmScreenMode.smAdd)
    Call UpdateTabStrip(lo_editTab, fra_detailFrames)
    Call UpdateUI(ArmScreenMode.smAdd)
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_AddInit")
End Sub

' initialize delete mode
Private Sub Item_DeleteInit(ByVal as_detailKey As Variant, ByVal as_rights As String)
On Error GoTo ErrHandler
    Dim lo_editTab As MSComctlLib.TabStrip
    Set lo_editTab = setObjectVisible(tbs_ClaimTabs, IIf(as_rights = "COORD", "tbs_ClaimTabsEdit", "tbs_ClaimTabsPlantEdit"))
    Debug.Assert (Not lo_editTab Is Nothing)
    
    Call ResetScreen(ArmScreenMode.smDelete)
    Call Item_Clear
        
    txt_GenReport.Text = CStr(as_detailKey(0))
    
    Call Item_LoadIconcurrencyCursor(txt_GenReport.Text)
    Call tbs_ClaimTabs_Click(lo_editTab.Index)
    
    Call UpdateUI(ArmScreenMode.smDelete)
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_DeleteInit")
End Sub

' set object visible and return it
Private Function setObjectVisible(ByRef ao_objArray As Object, ByVal as_Tag As String) As Object
On Error GoTo ErrHandler
    Dim lo_auxObj As Object
    For Each lo_auxObj In ao_objArray
        If lo_auxObj.Tag = as_Tag Then
            lo_auxObj.Visible = True
            Set setObjectVisible = lo_auxObj
        Else
            lo_auxObj.Visible = False
        End If
    Next
    Exit Function
ErrHandler:
    Call ErrorHandler("setObjectVisible")
End Function

' return first visible object from array
Private Function getObjectVisible(ByRef ao_objArray As Object) As Object
On Error GoTo ErrHandler
    Dim lo_auxObj As Object
    For Each lo_auxObj In ao_objArray
        If lo_auxObj.Visible Then
            Set getObjectVisible = lo_auxObj
            Exit Function
        End If
    Next
    Exit Function
ErrHandler:
    Call ErrorHandler("getObjectVisible")
End Function

' initialize update mode
Private Sub Item_UpdateInit(ByVal as_detailKey As Variant, ByVal as_rights As String)
On Error GoTo ErrHandler
    Dim lo_editTab As MSComctlLib.TabStrip
    Set lo_editTab = setObjectVisible(tbs_ClaimTabs, IIf(as_rights = "COORD", "tbs_ClaimTabsEdit", "tbs_ClaimTabsPlantEdit"))
    Debug.Assert (Not lo_editTab Is Nothing)
    ' clearing form
    Call ResetScreen(ArmScreenMode.smUpdate)
    Call Item_Clear
        
    ' open detail cursor according to selected tab
    txt_GenReport.Text = CStr(as_detailKey(0))
    Call Item_LoadIconcurrencyCursor(txt_GenReport.Text)

    Dim ll_detTabIndex As Long
    ll_detTabIndex = CLng(Mid(lo_editTab.SelectedItem.Key, 2))
    
    If ml_DetailCursor(ll_detTabIndex) = 0 Then
        Debug.Assert (txt_GenReport.Text <> "")
        ' it is possible to load data into tab
        Call Item_LoadDB(ml_DetailCursor(ll_detTabIndex), ml_detailIconcurrencyCursor, _
                            ms_detailRequests(ll_detTabIndex), _
                            txt_GenReport.Text)
    End If
    Call Item_LoadValues(ml_DetailCursor(ll_detTabIndex))
    Call Item_ApplyLogic(ArmScreenMode.smUpdate)
    Call UpdateTabStrip(lo_editTab, fra_detailFrames)
    Call UpdateUI(ArmScreenMode.smUpdate)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_UpdateInit")
End Sub

' workw with smView, smUpdate and smDelete mode
Private Sub Item_Restore()
On Error GoTo ErrHandler
    Debug.Assert (txt_GenReport.Text <> "")
    Dim lo_editTab As MSComctlLib.TabStrip
    ' close all cursors
    Call Item_CloseCursors
    
    ' save old itemID
    Dim ls_ID As String
    ls_ID = txt_GenReport.Text
    ' clearing form
    Call ResetScreen(activeScreenMode)
    Call Item_Clear
    
    Set lo_editTab = getObjectVisible(tbs_ClaimTabs)
    Debug.Assert (Not lo_editTab Is Nothing)
    
    txt_GenReport.Text = ls_ID
    Call Item_LoadIconcurrencyCursor(txt_GenReport.Text)
    ' open detail cursor according to selected tab
    Dim ll_detTabIndex As Long
    ll_detTabIndex = CLng(Mid(lo_editTab.SelectedItem.Key, 2))
    
    If ml_DetailCursor(ll_detTabIndex) = 0 Then
        Debug.Assert (txt_GenReport.Text <> "")
        ' it is possible to load data into tab
        Call Item_LoadDB(ml_DetailCursor(ll_detTabIndex), ml_detailIconcurrencyCursor, _
                            ms_detailRequests(ll_detTabIndex), _
                            txt_GenReport.Text)
    End If
    Call Item_LoadValues(ml_DetailCursor(ll_detTabIndex))
    Call Item_ApplyLogic(activeScreenMode)
    Call UpdateTabStrip(lo_editTab, fra_detailFrames)
    Call UpdateUI
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_Restore")
End Sub

' adds current edited item
Private Function Item_Add() As Variant
On Error GoTo ErrHandler
    ' check values and throw message if neccessary
    Dim lo_ctrl As MSComctlLib.Tab
    Dim ll_detTabIndex As Long

    ' check values and throw message if neccessary
    For Each lo_ctrl In tbs_ClaimTabs(1).Tabs
        ll_detTabIndex = CLng(Mid(lo_ctrl.Key, 2))
        If ThrowErrorMessage(Item_Check(fra_detailFrames(ll_detTabIndex))) Then
            Exit Function
        End If
    Next
    
    Dim lb_inTransaction As Boolean
    
    ASC_BeginTransaction mo_Db, "CM_ADD"
    lb_inTransaction = True
    
    Dim ls_newCode As String
    ' get new code
    Debug.Assert (Not cbo_GenSalesMarket.SelectedItem Is Nothing)
    ls_newCode = GetNextFreeClaimCode(cbo_GenSalesMarket.SelectedItem.Key)

    Call Item_AddDB(ms_detailRequestsAdd, ls_newCode)
    
    ASC_CommitTransaction mo_Db, "CM_ADD"
    lb_inTransaction = False
    
    Item_Add = CVar(Array(ls_newCode, SQLComboBoxValue(cbo_GenCountry, ""), GetOptionButtonCode(opt_GenStatus), "COORD"))
    Exit Function
ErrHandler:
    If lb_inTransaction Then
        ASC_RollBackTransaction mo_Db, "CM_ADD"
        lb_inTransaction = False
    End If
    If Err.Number = SQLBadRowAffectedCount Then
        Call MsgBox("Error occured while inserting record, please contact IT")
        Exit Function
    End If

    Call ErrorHandler("Item_Add")
End Function

' update current edited item
Private Function Item_Update(ByVal av_oldKey As Variant) As Variant
On Error GoTo ErrHandler
    Debug.Assert (txt_GenReport.Text = av_oldKey(0))
    
    ' update data per tab
    Dim lo_tabEditStrip As MSComctlLib.TabStrip
    Dim lo_ctrl As MSComctlLib.Tab
    Dim ll_detTabIndex As Long
    
    Set lo_tabEditStrip = getObjectVisible(tbs_ClaimTabs)
    Debug.Assert (Not lo_tabEditStrip Is Nothing)
    Debug.Assert (lo_tabEditStrip.Visible)

    ' check values and throw message if neccessary
    For Each lo_ctrl In lo_tabEditStrip.Tabs
        ll_detTabIndex = CLng(Mid(lo_ctrl.Key, 2))
        
        Debug.Assert (ml_DetailCursor(ll_detTabIndex) <> -1)
        
        If ml_DetailCursor(ll_detTabIndex) > 0 Then
            If ThrowErrorMessage(Item_Check(fra_detailFrames(ll_detTabIndex))) Then
                Exit Function
            End If
        End If
    Next
    
    Dim lo_iconcurrencyCounter As New Collection
    Dim lb_inTransaction As Boolean
    
    ASC_BeginTransaction mo_Db, "CM_UPDATE"
    lb_inTransaction = True

    For Each lo_ctrl In lo_tabEditStrip.Tabs
        ll_detTabIndex = CLng(Mid(lo_ctrl.Key, 2))
        
        Debug.Assert (ml_DetailCursor(ll_detTabIndex) <> -1)
        If ml_DetailCursor(ll_detTabIndex) > 0 Then
            ' save tab
            Call Item_UpdateDB(ml_DetailCursor(ll_detTabIndex), _
                                ms_detailRequestsUpd(ll_detTabIndex), _
                                av_oldKey(0), _
                                lo_iconcurrencyCounter)
        End If
    Next
    
    ' update description
    Dim ls_req As String
    ls_req = Replace("EXEC Clm_updDescription '$ClaimCode$', $iConcurrency$", "$ClaimCode$", av_oldKey(0), , , vbTextCompare)
    ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
    ' try all cursors to replace iconncurrency field
    For Each lo_ctrl In lo_tabEditStrip.Tabs
        ll_detTabIndex = CLng(Mid(lo_ctrl.Key, 2))
        If ml_DetailCursor(ll_detTabIndex) > 0 Then
            ls_req = ReplaceIconcurrency(ls_req, "$iConcurrency$", lo_iconcurrencyCounter, ml_DetailCursor(ll_detTabIndex), "iConcurrency")
        End If
    Next
    If Not InStr(1, ls_req, "$iConcurrency$", vbTextCompare) > 0 Then
        Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    End If

    ASC_CommitTransaction mo_Db, "CM_UPDATE"
    lb_inTransaction = False
    
    Item_Update = CVar(Array(av_oldKey(0), SQLComboBoxValue(cbo_GenCountry, av_oldKey(1)), GetOptionButtonCode(opt_GenStatus, av_oldKey(2)), av_oldKey(3)))

    Exit Function
ErrHandler:
    If lb_inTransaction Then
        ASC_RollBackTransaction mo_Db, "CM_UPDATE"
        lb_inTransaction = False
    End If
   If Err.Number = SQLBadRowAffectedCount Then
        Err.Clear
        SendMessage ms_LanguageCode, ErrMsgIConcurency, "#Someone changed detail of this record and detail screen will be reloaded."
        Call Item_Restore
        Exit Function
    End If
    Call ErrorHandler("Item_Update")
End Function

' deletes claim item
Private Function Item_Delete(ByVal av_oldKey As Variant) As Variant
On Error GoTo ErrHandler
    
    Dim lb_inTransaction As Boolean
    
    If SendMessage(ms_LanguageCode, WarMsgDoYouRemove, "#Delete record ?", "Delete ", vbQuestion + vbYesNo) = vbYes Then

        Dim ll_detTabIndex As Long
        ll_detTabIndex = CLng(Mid(getObjectVisible(tbs_ClaimTabs).SelectedItem.Key, 2))
        
        Debug.Assert (ml_DetailCursor(ll_detTabIndex) <> 0)
        
        ASC_BeginTransaction mo_Db, "CM_DEL"
        lb_inTransaction = True
    
        Call Item_DeleteDB(ml_DetailCursor(ll_detTabIndex), ms_detailRequestsDel, av_oldKey(0))
        
        ASC_CommitTransaction mo_Db, "CM_DEL"
        lb_inTransaction = False
    
        Item_Delete = av_oldKey
    End If
    Exit Function
ErrHandler:
    If lb_inTransaction Then
        ASC_RollBackTransaction mo_Db, "CM_DEL"
        lb_inTransaction = False
    End If
   If Err.Number = SQLBadRowAffectedCount Then
        Err.Clear
        SendMessage ms_LanguageCode, ErrMsgIConcurency, "#Someone changed detail of this record and detail screen will be reloaded."
        Call Item_Restore
        Exit Function
    End If
    Call ErrorHandler("Item_Delete")
End Function

Private Sub Item_UpdateLastUpd(ByVal as_claCode As String)
On Error GoTo ErrHandler
Const REQ As String = "EXEC Clm_Claim_LastUpd_upd '$ClaimCode$', '$LOGINNAME$'"
    ' update db
    Dim ls_req As String
    ls_req = Replace(REQ, "$ClaimCode$", as_claCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
    
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    If ml_DetailCursor(0) > 0 Then
        ' detail for general tab was loaded so update cal_GenUpdateDate control
        Call SetCalendarText(cal_GenUpdateDate, Format(Date, "dd\/mm\/yyyy"))
    End If
    
    Exit Sub
ErrHandler:
   If Err.Number = SQLBadRowAffectedCount Then
        Err.Clear
        SendMessage ms_LanguageCode, ErrMsgRecordDeleted, "#Someone removed detail of this record. Please exit screen and retype detail or contact IT support."
        Exit Sub
    End If
    Call ErrorHandler("Item_UpdateLastUpd")
End Sub


' copy & pasted ( & cleaned from wrong code) functions from sifyb tools module to use transaction
Public Function ASC_BeginTransaction(ByRef ao_Armdb As Object, Optional ByVal as_Name As String = "") As Boolean
On Error GoTo ErrHandler
    Dim ls_Request As String
    ASC_BeginTransaction = False
    ls_Request = "BEGIN TRAN " & as_Name
    'Execute the request
    ao_Armdb.ExecuteSQL ls_Request
    ASC_BeginTransaction = True
    Exit Function
ErrHandler:
    Call ErrorHandler("ASC_BeginTransaction")
End Function

Public Function ASC_CommitTransaction(ByRef ao_Armdb As Object, Optional ByVal as_Name As String = "") As Boolean
On Error GoTo ErrHandler
    Dim ls_Request As String

    ASC_CommitTransaction = False
    ls_Request = "COMMIT TRAN " & as_Name
    'Execute the request
    ao_Armdb.ExecuteSQL ls_Request
    ASC_CommitTransaction = True
    Exit Function
ErrHandler:
    Call ErrorHandler("ASC_CommitTransaction")
End Function

Public Function ASC_RollBackTransaction(ByRef ao_Armdb As Object, Optional ByVal as_Name As String = "") As Boolean
    Dim ls_Request As String
  
    ASC_RollBackTransaction = False
    ls_Request = "ROLLBACK TRAN " & as_Name
    'Execute the request
    ao_Armdb.ExecuteSQL ls_Request
    ASC_RollBackTransaction = True
End Function

Private Function IsNumericArm(ByVal as_Value As String) As Boolean
On Error GoTo ErrHandler
    as_Value = Replace(as_Value, ".", ms_DecimalSeparator, , , vbTextCompare)
    
    IsNumericArm = isNumeric(as_Value)
    Exit Function
ErrHandler:
    Call ErrorHandler("IsNumericArm")
End Function

Private Function ToStr(ByVal av_Value As Variant, Optional ByVal as_Format As String = "") As String
On Error GoTo ErrHandler
' task 299.3, bugfix
    If as_Format <> "" Then
        av_Value = Format(av_Value, as_Format)
    End If
    ToStr = Replace(av_Value, ms_DecimalSeparator, ".", , , vbTextCompare)
    Exit Function
ErrHandler:
    Call ErrorHandler("ToStr")
End Function

Private Function ToDouble(ByVal as_str As String) As Double
On Error GoTo ErrHandler
    ' replace '.' with decimal separator obtained from locale
    as_str = Replace(as_str, ".", ms_DecimalSeparator, , , vbTextCompare)
    
    If isNumeric(as_str) Then
        ToDouble = CDbl(as_str)
    Else
        ToDouble = 0
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("ToDouble")
End Function

Private Function GetItemCount(ByVal ao_Collection As Collection, ByVal as_FieldName) As Long
On Error GoTo ErrHandler
    Dim ll_Ret As Long
    Dim ls_Item As Variant
    ll_Ret = 0
    If Not ao_Collection Is Nothing Then
        For Each ls_Item In ao_Collection
            If ls_Item = as_FieldName Then ll_Ret = ll_Ret + 1
        Next
    End If
    GetItemCount = ll_Ret
    Exit Function
ErrHandler:
    Call ErrorHandler("GetItemCount")
End Function

' function will remember number of times iconcurrency was processed
Private Function ReplaceIconcurrency(ByVal as_req As String, ByVal as_find As String, ByRef ao_iconcurrencyCounter As Collection, ByVal al_Cursor As Long, ByVal as_iconnFieldName As String) As String
On Error GoTo ErrHandler
    
    ReplaceIconcurrency = as_req
    If InStr(1, as_req, as_find, vbTextCompare) > 0 Then
        ' replace will work
        Dim lv_val As Variant
        lv_val = mo_Db.GetFields(al_Cursor, as_iconnFieldName)
        
        If IsEmpty(lv_val) Then
            ' expecting some incourrency, but nothing found
            Call LogMessage("Expected " & as_iconnFieldName & " but nothing found in cursor (" & al_Cursor & ")! Current rows:" & mo_Db.RowCount(al_Cursor) & ". iConcCursor:" & ml_detailIconcurrencyCursor, "I", False)
            
            If al_Cursor = ml_detailIconcurrencyCursor Then
                
                Call LogMessage("Reloading cursor for '" & txt_GenReport.Text & "'", "E", False)
                
                If ml_detailIconcurrencyCursor <> 0 Then
                    Call mo_Db.Close(ml_detailIconcurrencyCursor)
                End If
                ml_detailIconcurrencyCursor = 0
    
                Call Item_LoadIconcurrencyCursor(txt_GenReport.Text)
            
                lv_val = mo_Db.GetFields(ml_detailIconcurrencyCursor, as_iconnFieldName)
            
                If IsEmpty(lv_val) Then
                  ' expecting some incourrency, but nothing found
                   Call LogMessage("Reload failed! Expected " & as_iconnFieldName & " but nothing found in cursor (" & ml_detailIconcurrencyCursor & ")! Current rows:" & mo_Db.RowCount(ml_detailIconcurrencyCursor) & ". Reloading cursor for '" & txt_GenReport.Text & "'", "E", False)
                End If
            End If
        End If
        
        If Not IsEmpty(lv_val) Then
            ' field in cursor found
            ReplaceIconcurrency = Replace(as_req, as_find, CStr(lv_val + GetItemCount(ao_iconcurrencyCounter, as_iconnFieldName + CStr(mo_Db.Position(al_Cursor)))), , , vbTextCompare)
            If Not ao_iconcurrencyCounter Is Nothing Then Call ao_iconcurrencyCounter.Add(as_iconnFieldName + CStr(mo_Db.Position(al_Cursor)))
        End If
    End If

    Exit Function
ErrHandler:
    Call ErrorHandler("ReplaceIconcurrency")
End Function

Private Function GetNextFreeClaimCode(ByVal as_SMK_code As String) As String
On Error GoTo ErrHandler
Const C_REQ As String = "EXEC Clm_Claim_Code_gen '$SaleMarketCode$', 'E'"
    ' retrieve new claim code
    Dim lc_Cursor As Long
    lc_Cursor = OpenSQLSafe(mo_Db, Replace(C_REQ, "$SaleMarketCode$", as_SMK_code, , , vbTextCompare), 1)
    
    GetNextFreeClaimCode = mo_Db.GetFields(lc_Cursor, "CLA_code")
    
    Call mo_Db.Close(lc_Cursor)
    lc_Cursor = 0
    Exit Function
ErrHandler:
    If lc_Cursor <> 0 Then
        Call mo_Db.Close(lc_Cursor)
        lc_Cursor = 0
    End If
    Call ErrorHandler("GetNextFreeCode")
End Function

Private Sub Item_AddDB(ByVal as_reqTmpl As String, ByVal as_ClaimCode As String)
On Error GoTo ErrHandler
    Dim lsa_reqTmp() As String
    Dim ls_req As String
    Dim ll_Index As Long
    lsa_reqTmp = Split(as_reqTmpl, SEP)

    For ll_Index = 0 To UBound(lsa_reqTmp)
        ' common placeholders
        ls_req = Replace(lsa_reqTmp(ll_Index), "$ClaimCode$", as_ClaimCode, , , vbTextCompare)
        ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
    
        ls_req = Item_ReplacePlaceholders(ls_req)
        
        Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    Next
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_AddDb")
End Sub

Private Sub Item_UpdateDB(ByVal al_Cursor As Long, ByVal as_reqTmpl As String, ByVal as_ClaimCode As String, ByRef ao_iconcurrencyCounter As Collection)
On Error GoTo ErrHandler
    Dim lsa_reqTmp() As String
    Dim ls_req As String
    Dim ll_Index As Long
    lsa_reqTmp = Split(as_reqTmpl, SEP)
    
    Call mo_Db.First(al_Cursor)
    For ll_Index = 0 To UBound(lsa_reqTmp)
    
        ' common placeholders
        ls_req = Replace(lsa_reqTmp(ll_Index), "$ClaimCode$", as_ClaimCode, , , vbTextCompare)
        ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
        ls_req = ReplaceIconcurrency(ls_req, "$iConcurrency$", ao_iconcurrencyCounter, ml_detailIconcurrencyCursor, "iConcurrency")
        ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyCost1$", ao_iconcurrencyCounter, ml_detailIconcurrencyCursor, "iConcurrencyCost1")
        ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyCost2$", ao_iconcurrencyCounter, ml_detailIconcurrencyCursor, "iConcurrencyCost2")
        ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyCost3$", ao_iconcurrencyCounter, ml_detailIconcurrencyCursor, "iConcurrencyCost3")
        ls_req = ReplaceIconcurrency(ls_req, "$ItemiConcurrency$", ao_iconcurrencyCounter, ml_detailIconcurrencyCursor, "iConcurrency_I")
        ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyPlant$", ao_iconcurrencyCounter, ml_detailIconcurrencyCursor, "iConcurrencyPlant")
        ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyStat$", ao_iconcurrencyCounter, ml_detailIconcurrencyCursor, "iConcurrencyStat")

        ls_req = Item_ReplacePlaceholders(ls_req)
        
        Call ExecuteSQLSafe(mo_Db, ls_req)
        If mo_Db.SQLRowsAffected = 0 Then
            Err.Raise ArmErr.SQLBadRowAffectedCount, "SQL : " & ls_req, "1..3" & "<>" & mo_Db.SQLRowsAffected
        End If

        Call mo_Db.Next(al_Cursor)
        If mo_Db.EOF(al_Cursor) Then mo_Db.First (al_Cursor)
    Next
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_UpdateDb")
End Sub

Private Sub Item_DeleteDB(ByVal al_Cursor As Long, ByVal as_reqTmpl As String, ByVal as_ClaimCode As String)
On Error GoTo ErrHandler
    Dim lsa_reqTmp() As String
    Dim ls_req As String
    Dim ll_Index As Long
    lsa_reqTmp = Split(as_reqTmpl, SEP)

    For ll_Index = 0 To UBound(lsa_reqTmp)
        Dim lsa_redef() As String
        lsa_redef = Split(lsa_reqTmp(ll_Index), SEP1)
        Debug.Assert (UBound(lsa_redef) = 1)
        ' common placeholders
        ls_req = Replace(lsa_redef(UBound(lsa_redef)), "$ClaimCode$", as_ClaimCode, , , vbTextCompare)
        ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
        ls_req = ReplaceIconcurrency(ls_req, "$iConcurrency$", Nothing, ml_detailIconcurrencyCursor, "iConcurrency")
        ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyCost1$", Nothing, ml_detailIconcurrencyCursor, "iConcurrencyCost1")
        ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyCost2$", Nothing, ml_detailIconcurrencyCursor, "iConcurrencyCost2")
        ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyCost3$", Nothing, ml_detailIconcurrencyCursor, "iConcurrencyCost3")
        ls_req = ReplaceIconcurrency(ls_req, "$ItemiConcurrency$", Nothing, ml_detailIconcurrencyCursor, "iConcurrency_I")
        ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyPlant$", Nothing, ml_detailIconcurrencyCursor, "iConcurrencyPlant")
        ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyStat$", Nothing, ml_detailIconcurrencyCursor, "iConcurrencyStat")

        Call ExecuteSQLSafe(mo_Db, ls_req, CLng(lsa_redef(0)))
    Next

    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_DeleteDb")
End Sub

' exits mode to main
Private Sub Item_ExitToGrid(ByRef ao_grid As ArmGrid, ByVal av_gridKey As Variant)
On Error GoTo ErrHandler
    
    Call UpdateGridAfterAction(ao_grid, activeScreenMode, av_gridKey)

    ' close detail cursors
    Select Case activeScreenMode
        Case ArmScreenMode.smAdd, ArmScreenMode.smDelete, ArmScreenMode.smUpdate, ArmScreenMode.smView
            Call Item_CloseCursors
        Case ArmScreenMode.smMemoAdd, ArmScreenMode.smMemoUpdate
            Call Memo_CloseCursor
        Case ArmScreenMode.smMemoDelete
            Call Memo_CloseCursor
            ' init view on selected item
            If grd_ClaimMemoList.SelectedCount <> 0 Then
                Call Memo_ViewInit(grd_ClaimMemoList.SelectedKey(0)(0))
            Else
                ' clear controls
                Memo_LoadValues (-1)
            End If
        Case ArmScreenMode.smNotesAdd, ArmScreenMode.smNotesDelete, ArmScreenMode.smNotesUpdate
            Call Note_CloseCursor
        Case smCustMain, smCustAdd, smCustUpdate, smCustDelete, smCustView
            Call Cust_CloseCursor
        Case smProjMain, smProjAdd, smProjUpdate, smProjDelete, smProjView
            Call Proj_CloseCursor
        Case smItemMain ' do nothing
        Case Else
            Debug.Assert (False)
    End Select

    ' pop last item in screen mode stack
    Call popScreenMode
    
    Call ResetScreen(activeScreenMode)
    Call Item_ApplyLogic(activeScreenMode)
    Call UpdateUI
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_ExitToGrid")
End Sub

' test if ao_ParentNode and nodes contain definitions in av_nodeDescArray
' return true if ao_ParentNode is noting
Private Function RepositionTreeViewTest(ByVal ao_parentNode As MSComctlLib.Node, ByVal av_nodeDescArray As Variant) As Boolean
On Error GoTo ErrHandler
    Dim ab_ret As Boolean
    ab_ret = (ao_parentNode Is Nothing)
    If Not ab_ret Then
        Do
            If ao_parentNode.Tag.GetData(0) <> av_nodeDescArray(ao_parentNode.Tag.ml_Level)(0) Then
                ab_ret = True
                Exit Do
            End If
            Set ao_parentNode = ao_parentNode.Parent
        Loop Until ao_parentNode Is Nothing
    End If
    RepositionTreeViewTest = ab_ret
    Exit Function
ErrHandler:
    Call ErrorHandler("RepositionTreeViewTest")
End Function

' av_nodeDescArray ... two dimensional array of (key, descrition) coupples
' ao_treeView ... must be loaded
Private Function RepositionTreeView(ByRef ao_TreeView As ArmTreeView, ByVal av_nodeDescArray As Variant)
On Error GoTo ErrHandler

'    Debug.Assert (ao_TreeView.Count <> 0)
    Dim ll_Index As Long
    Dim lo_parentNode As MSComctlLib.Node
    Dim lo_newParentNode As MSComctlLib.Node
    
    Dim lb_doNavigation As Boolean
    Dim lb_auxBool As Boolean
    
    
    ' replace empty strings in array with values from treeView
    Set lo_parentNode = ao_TreeView.SelectedItem
    If Not lo_parentNode Is Nothing Then
        Do
            If av_nodeDescArray(lo_parentNode.Tag.ml_Level)(0) = "" Then
                av_nodeDescArray(lo_parentNode.Tag.ml_Level)(0) = lo_parentNode.Tag.GetData(0)
                av_nodeDescArray(lo_parentNode.Tag.ml_Level)(1) = lo_parentNode.Tag.TextValue
            End If
            Set lo_parentNode = lo_parentNode.Parent
        Loop Until lo_parentNode Is Nothing
    End If
    
    ' test if current selected item correspond to designed node
    lb_doNavigation = RepositionTreeViewTest(ao_TreeView.SelectedItem, av_nodeDescArray)
    If lb_doNavigation Then
        Debug.Assert (lo_parentNode Is Nothing)
        For ll_Index = LBound(av_nodeDescArray, 1) To UBound(av_nodeDescArray, 1)
            If Not ao_TreeView.Find(av_nodeDescArray(ll_Index)(0), 0, lo_parentNode, ll_Index) Then
                ' insert new node into tree
                ' save mb_ChildrenLoaded
                If Not lo_parentNode Is Nothing Then lb_auxBool = lo_parentNode.Tag.mb_ChildrenLoaded
                Set lo_newParentNode = ao_TreeView.AddNode(lo_parentNode, av_nodeDescArray(ll_Index)(0), av_nodeDescArray(ll_Index)(1), 1, 2, LoadTypeChildsDemand)
                ' restore mb_ChildrenLoaded
                If Not lo_parentNode Is Nothing Then lo_parentNode.Tag.mb_ChildrenLoaded = lb_auxBool
                Set lo_parentNode = lo_newParentNode
'                Call ao_TreeView.ExpandNode(lo_ParentNode)
            Else
                Debug.Assert (Not ao_TreeView.SelectedItem Is Nothing)
                Set lo_parentNode = ao_TreeView.SelectedItem
            End If
        Next
        ' this will also expand parent of lo_ParentNode node if parent of lo_ParentNode is not mb_ChildrenLoaded
        Set ao_TreeView.SelectedItem = lo_parentNode
    Else
        ' test if selected node/ if any/ has expected child
        If Not ao_TreeView.SelectedItem Is Nothing Then
            Set lo_parentNode = ao_TreeView.SelectedItem
            If lo_parentNode.children > 0 Then   ' indicates that node was loaded before
                Debug.Assert (ao_TreeView.Levels > lo_parentNode.Tag.ml_Level + 1)
                If Not ao_TreeView.Find(av_nodeDescArray(lo_parentNode.Tag.ml_Level + 1)(0), 0, lo_parentNode) Then
                    ' node does not exists
                    Call ao_TreeView.AddNode(lo_parentNode, av_nodeDescArray(lo_parentNode.Tag.ml_Level + 1)(0), av_nodeDescArray(lo_parentNode.Tag.ml_Level + 1)(1), 1, 2, LoadTypeChildsDemand)
                Else
                    ' set selected node back / find will set found node as selected / all we need is just test if child exists
                    Set ao_TreeView.SelectedItem = lo_parentNode
                End If
            End If
        End If
    End If
    RepositionTreeView = lb_doNavigation
    Exit Function
ErrHandler:
    Call ErrorHandler("RepositionTreeView")
End Function

Private Function Item_RepositionFilter(ByVal av_Key As Variant) As Boolean
On Error GoTo ErrHandler
    Dim lv_auxVal As Variant
    Dim ls_auxDesc As String
    
    Item_RepositionFilter = False
    
    ' first level is based on type of search view
    If GetOptionButtonCode(opt_SearchView) = "P" Then
        ' plant
        lv_auxVal = cbo_SupSupplier.GetItemData(SQLComboBoxValue(cbo_SupSupplier), "MFGP_code")
        ls_auxDesc = SQLComboBoxValue(cbo_SupSupplier, "unknown", False)
        If Not IsEmpty(cbo_SupSupplier.GetItemData(SQLComboBoxValue(cbo_SupSupplier), "SP_CODE")) Then
            ' what if combo is filled with suppliers
            Debug.Assert (IsEmpty(lv_auxVal))
            ' this item will not appear in this type of filter
            ' user will lost it - or it can be positioned into special folder that will be removed after refres treeview
'            lv_auxVal = cbo_SupSupplier.GetItemData(SQLComboBoxValue(cbo_SupSupplier), "SP_CODE")
'            ls_auxDesc = "Special folder: " & ls_auxDesc
        End If
    Else
        ' sales office
        lv_auxVal = cbo_GenSalesOffice.GetItemData(SQLComboBoxValue(cbo_GenSalesOffice), 0)
        ls_auxDesc = SQLComboBoxValue(cbo_GenSalesOffice, "unknown", False)
    End If
    
    If RepositionTreeView(tvw_SearchList, _
            Array(Array(IIf(IsEmpty(lv_auxVal), "", CStr(lv_auxVal)), ls_auxDesc), _
                  Array(av_Key(1), SQLComboBoxValue(cbo_GenCountry, "unknown - " & av_Key(1), False)), _
                  Array(av_Key(2), GetStatusTranslation(GetOptionButtonCode(opt_GenStatus, "", 0))))) _
        Or grd_ClaimMain.Rows = 0 Then

        Call LoadSearchGrid(grd_ClaimMain, tvw_SearchList.SelectedNodeRequest(), False)
        
        Item_RepositionFilter = grd_ClaimMain.SearchKey(True, av_Key)
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("Item_RepositionFilter")
End Function

Private Function GetStatusTranslation(ByVal as_statusKey As String) As String
On Error GoTo ErrHandler
    Call mo_Db.Find(ml_treeNodeDescCursor, "Field_name", as_statusKey, 0)
    GetStatusTranslation = mo_Db.GetFields(ml_treeNodeDescCursor, "Local_text")
    Exit Function
ErrHandler:
    Call ErrorHandler("GetStatusTranslation")
End Function

Private Sub UpdateGridAfterAction(ByRef ao_grid As ArmGrid, ByVal au_action As ArmScreenMode, ByVal av_Key As Variant)
On Error GoTo ErrHandler
    Dim lsa_newRow() As String
    Dim ll_KeyIndex As Long
    Dim ll_Index As Long
    Dim lo_Column As ArmColumn
    Dim lo_ctrl As Control
    Dim ll_i As Long

    Select Case au_action
    Case ArmScreenMode.smAdd
        ' navigate treeView into
        ' Plant/Countries_Sales_Markets/Status or
        ' Sales Office/Countries_Sales_Markets/Status
        Debug.Assert (Not cbo_SupSupplier.SelectedItem Is Nothing)
        Debug.Assert (Not cbo_GenSalesOffice.SelectedItem Is Nothing)
        Debug.Assert (Not cbo_GenCountry.SelectedItem Is Nothing)
        Debug.Assert (GetOptionButtonCode(opt_GenStatus) <> "NULL")
        
        ' check filter condition (date?) and set it to include claim just inserted
        If GetOptionButtonCode(opt_SearchFilter) = "D" Then
            If cal_FilterAnyUpdated.date_dt > cal_GenReportDate.date_dt Then
                md_actSelectedFilterDate = cal_GenReportDate.date_dt
                cal_FilterAnyUpdated.date_courte = Format(cal_GenReportDate.date_dt, "dd\/mm\/yyyy")
                tvw_SearchList.Visible = False
                Call tvw_SearchList.Clear
                Call grd_ClaimMain.ClearGrid
                pic_ReloadSearch.Visible = True
            End If
        End If

        
        If tvw_SearchList.Count = 0 Then
            pic_ReloadSearch.Visible = False
            Call loadSearchTreeView(tvw_SearchList, GetOptionButtonCode(opt_SearchView), IIf(GetOptionButtonCode(opt_SearchFilter) = "D", cal_FilterAnyUpdated.date_dt, 0))
            tvw_SearchList.Visible = True
        End If
        If Not Item_RepositionFilter(av_Key) Then
            ' remove previous selection
            Call ao_grid.DeselectRow
            ' insert row at the end of grid
            Debug.Assert (ao_grid.Cols > 0)
            
            Call SafeRedimString(lsa_newRow, ao_grid.Cols)
            ll_KeyIndex = 0
            
            For ll_Index = 0 To ao_grid.Cols - 1
                Set lo_Column = ao_grid.Columns(ll_Index)
                If lo_Column.Key Then
                    Debug.Assert (UBound(av_Key) >= ll_KeyIndex)
                    lsa_newRow(ll_Index) = av_Key(ll_KeyIndex)
                    ll_KeyIndex = ll_KeyIndex + 1
                Else
                    lsa_newRow(ll_Index) = GetDataSrcForGrid(lo_Column)
                End If
            Next
            Call ao_grid.AddLine(lsa_newRow)
        End If
        
    Case ArmScreenMode.smUpdate

        If Not Item_RepositionFilter(av_Key) And ao_grid.Row <> -1 Then
            Debug.Assert (tvw_SearchList.Count <> 0)
            Debug.Assert (ao_grid.Row <> -1)
            Debug.Assert (ao_grid.SelectedKey(0)(0) = av_Key(0))
            ' update row in the grid
            ' need to update all values including key fields
            ll_KeyIndex = 0

            For ll_Index = 0 To ao_grid.Cols - 1
                Set lo_Column = ao_grid.Columns(ll_Index)
                If lo_Column.Key Then
                    Debug.Assert (UBound(av_Key) >= ll_KeyIndex)
                    If Not lo_Column.SetData(ao_grid.Row, av_Key(ll_KeyIndex)) Then
                        Call Err.Raise(CompFncFailed, "lo_Column.SetData", "Cannot update grid.")
                    End If
                    ll_KeyIndex = ll_KeyIndex + 1
                Else
                    If Not lo_Column.SetData(ao_grid.Row, GetDataSrcForGrid(lo_Column)) Then
                        Call Err.Raise(CompFncFailed, "lo_Column.SetData", "Cannot update grid.")
                    End If
                End If
            Next

        End If
        
    Case smDelete, smNotesDelete, smNotesDelete, smMemoDelete, smCustDelete, smProjDelete
        ' remove row from grid
        If Not ao_grid.DeleteLine(av_Key) Then
            Call Err.Raise(CompFncFailed, "ao_grid.DeleteLine", "Cannot delete line.")
        End If
        
    Case smMemoAdd, smNotesAdd
        Debug.Assert (ao_grid.Cols > 0)
        
        Call SafeRedimString(lsa_newRow, ao_grid.Cols)
        ll_KeyIndex = 0
        
        For ll_Index = 0 To ao_grid.Cols - 1
            Set lo_Column = ao_grid.Columns(ll_Index)
            If lo_Column.Key Then
                Debug.Assert (UBound(av_Key) >= ll_KeyIndex)
                lsa_newRow(ll_Index) = av_Key(ll_KeyIndex)
                ll_KeyIndex = ll_KeyIndex + 1
            Else
                lsa_newRow(ll_Index) = GetDataSrcForGrid(lo_Column)
            End If
        Next
        Call ao_grid.AddLine(lsa_newRow)
            
    Case smProjAdd
        Debug.Assert (ao_grid.Cols > 0)
        Debug.Assert (Not cbo_SelProjModCountry.SelectedItem Is Nothing)
        
        If Proj_RepositionFilter(SQLComboBoxValue(cbo_SelProjModCountry, ""), SQLComboBoxValue(cbo_SelProjModCountry, "unknown", False)) Then
            ' crear grid
            Call ao_grid.ClearGrid
        End If
        
        Call SafeRedimString(lsa_newRow, ao_grid.Cols)
        ll_KeyIndex = 0
        
        For ll_Index = 0 To ao_grid.Cols - 1
            Set lo_Column = ao_grid.Columns(ll_Index)
            If lo_Column.Key Then
                Debug.Assert (UBound(av_Key) >= ll_KeyIndex)
                lsa_newRow(ll_Index) = av_Key(ll_KeyIndex)
                ll_KeyIndex = ll_KeyIndex + 1
            Else
                lsa_newRow(ll_Index) = GetDataSrcForGrid(lo_Column)
            End If
        Next
        Call ao_grid.AddLine(lsa_newRow)
        
    Case smCustAdd
        Debug.Assert (ao_grid.Cols > 0)
        Debug.Assert (Not cbo_SelectCustCountry.SelectedItem Is Nothing)
        
        If Cust_RepositionFilter(SQLComboBoxValue(cbo_SelCustModCountry, ""), SQLComboBoxValue(cbo_SelCustModCountry, "unknown", False)) Then
            ' crear grid
            Call ao_grid.ClearGrid
        End If

        Call SafeRedimString(lsa_newRow, ao_grid.Cols)
        ll_KeyIndex = 0
        
        For ll_Index = 0 To ao_grid.Cols - 1
            Set lo_Column = ao_grid.Columns(ll_Index)
            If lo_Column.Key Then
                Debug.Assert (UBound(av_Key) >= ll_KeyIndex)
                lsa_newRow(ll_Index) = av_Key(ll_KeyIndex)
                ll_KeyIndex = ll_KeyIndex + 1
            Else
                lsa_newRow(ll_Index) = GetDataSrcForGrid(lo_Column)
            End If
        Next
        Call ao_grid.AddLine(lsa_newRow)
    

    Case smMemoUpdate, smNotesUpdate
        ' update row in the grid
        ' need to update all values including key fields
        ll_KeyIndex = 0

        For ll_Index = 0 To ao_grid.Cols - 1
            Set lo_Column = ao_grid.Columns(ll_Index)
            If lo_Column.Key Then
                Debug.Assert (UBound(av_Key) >= ll_KeyIndex)
                If Not lo_Column.SetData(ao_grid.Row, av_Key(ll_KeyIndex)) Then
                    Call Err.Raise(CompFncFailed, "lo_Column.SetData", "Cannot update grid.")
                End If
                ll_KeyIndex = ll_KeyIndex + 1
            Else
                If Not lo_Column.SetData(ao_grid.Row, GetDataSrcForGrid(lo_Column)) Then
                    Call Err.Raise(CompFncFailed, "lo_Column.SetData", "Cannot update grid.")
                End If
            End If
        Next
            
    Case smProjUpdate
        Debug.Assert (ao_grid.Cols > 0)
        Debug.Assert (Not cbo_SelProjModCountry.SelectedItem Is Nothing)
        
        If Proj_RepositionFilter(SQLComboBoxValue(cbo_SelProjModCountry, ""), SQLComboBoxValue(cbo_SelProjModCountry, "unknown", False)) Then
            ' crear grid
            Call ao_grid.ClearGrid
            Call SafeRedimString(lsa_newRow, ao_grid.Cols)
            ll_KeyIndex = 0
            
            For ll_Index = 0 To ao_grid.Cols - 1
                Set lo_Column = ao_grid.Columns(ll_Index)
                If lo_Column.Key Then
                    Debug.Assert (UBound(av_Key) >= ll_KeyIndex)
                    lsa_newRow(ll_Index) = av_Key(ll_KeyIndex)
                    ll_KeyIndex = ll_KeyIndex + 1
                Else
                    lsa_newRow(ll_Index) = GetDataSrcForGrid(lo_Column)
                End If
            Next
            Call ao_grid.AddLine(lsa_newRow)
        Else
            ' update row in the grid
            ' need to update all values including key fields
            ll_KeyIndex = 0
    
            For ll_Index = 0 To ao_grid.Cols - 1
                Set lo_Column = ao_grid.Columns(ll_Index)
                If lo_Column.Key Then
                    Debug.Assert (UBound(av_Key) >= ll_KeyIndex)
                    If Not lo_Column.SetData(ao_grid.Row, av_Key(ll_KeyIndex)) Then
                        Call Err.Raise(CompFncFailed, "lo_Column.SetData", "Cannot update grid.")
                    End If
                    ll_KeyIndex = ll_KeyIndex + 1
                Else
                    If Not lo_Column.SetData(ao_grid.Row, GetDataSrcForGrid(lo_Column)) Then
                        Call Err.Raise(CompFncFailed, "lo_Column.SetData", "Cannot update grid.")
                    End If
                End If
            Next

        End If
        

    Case smCustUpdate
        Debug.Assert (ao_grid.Cols > 0)
        Debug.Assert (Not cbo_SelectCustCountry.SelectedItem Is Nothing)
        
        If Cust_RepositionFilter(SQLComboBoxValue(cbo_SelCustModCountry, ""), SQLComboBoxValue(cbo_SelCustModCountry, "unknown", False)) Then
            ' crear grid
            Call ao_grid.ClearGrid
            
            Call SafeRedimString(lsa_newRow, ao_grid.Cols)
            ll_KeyIndex = 0
            
            For ll_Index = 0 To ao_grid.Cols - 1
                Set lo_Column = ao_grid.Columns(ll_Index)
                If lo_Column.Key Then
                    Debug.Assert (UBound(av_Key) >= ll_KeyIndex)
                    lsa_newRow(ll_Index) = av_Key(ll_KeyIndex)
                    ll_KeyIndex = ll_KeyIndex + 1
                Else
                    lsa_newRow(ll_Index) = GetDataSrcForGrid(lo_Column)
                End If
            Next
            Call ao_grid.AddLine(lsa_newRow)

        Else
            ' update row in the grid
            ' need to update all values including key fields
            ll_KeyIndex = 0

            For ll_Index = 0 To ao_grid.Cols - 1
                Set lo_Column = ao_grid.Columns(ll_Index)
                If lo_Column.Key Then
                    Debug.Assert (UBound(av_Key) >= ll_KeyIndex)
                    If Not lo_Column.SetData(ao_grid.Row, av_Key(ll_KeyIndex)) Then
                        Call Err.Raise(CompFncFailed, "lo_Column.SetData", "Cannot update grid.")
                    End If
                    ll_KeyIndex = ll_KeyIndex + 1
                Else
                    If Not lo_Column.SetData(ao_grid.Row, GetDataSrcForGrid(lo_Column)) Then
                        Call Err.Raise(CompFncFailed, "lo_Column.SetData", "Cannot update grid.")
                    End If
                End If
            Next

        End If

    Case smCustMain
        ' fill customer data into selected tab
        Debug.Assert (Not tbs_CustTabs.SelectedItem Is Nothing)
        Debug.Assert (ml_custCursor > 0)
        Select Case tbs_CustTabs.SelectedItem.Key
            Case "_0"   ' distributor
                Call SetTextBoxTextDB(ml_custCursor, "CCU_desc", txt_CustDisName, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_addr1", txt_CustDisAddress1, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_addr2", txt_CustDisAddress2, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_zip", txt_CustDisZipCode, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_town", txt_CustDisTown, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_contact", txt_CustDisContact, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_tel", txt_CustDisTelephone, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_fax", txt_CustDisFax, True)
                Call SetTextBoxTextDB(ml_custCursor, "CUST_code", txt_CustDisSAPCode, True)
                Call SetTextBoxTextDB(ml_custCursor, "CT_desc", txt_CustDisCountry, True)
                Call SetControlTagDB(ml_custCursor, "CCU_code", cmd_SelectCust(0), True, av_Key(0))
            Case "_1"   ' specifier
                Call SetTextBoxTextDB(ml_custCursor, "CCU_desc", txt_CustSpeName, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_addr1", txt_CustSpeAddress1, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_addr2", txt_CustSpeAddress2, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_zip", txt_CustSpeZipCode, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_town", txt_CustSpeTown, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_contact", txt_CustSpeContact, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_tel", txt_CustSpeTelephone, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_fax", txt_CustSpeFax, True)
                Call SetTextBoxTextDB(ml_custCursor, "CUST_code", txt_CustSpeSAPCode, True)
                Call SetTextBoxTextDB(ml_custCursor, "CT_desc", txt_CustSpeCountry, True)
                Call SetControlTagDB(ml_custCursor, "CCU_code", cmd_SelectCust(1), True, av_Key(0))
            Case "_2"   ' contractor
                Call SetTextBoxTextDB(ml_custCursor, "CCU_desc", txt_CustConName, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_addr1", txt_CustConAddress1, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_addr2", txt_CustConAddress2, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_zip", txt_CustConZipCode, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_town", txt_CustConTown, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_contact", txt_CustConContact, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_tel", txt_CustConTelephone, True)
                Call SetTextBoxTextDB(ml_custCursor, "CCU_fax", txt_CustConFax, True)
                Call SetTextBoxTextDB(ml_custCursor, "CUST_code", txt_CustConSAPCode, True)
                Call SetTextBoxTextDB(ml_custCursor, "CT_desc", txt_CustConCountry, True)
                Call SetControlTagDB(ml_custCursor, "CCU_code", cmd_SelectCust(2), True, av_Key(0))
        End Select
    Case smProjMain
        ' fill project data into selected tab
        Debug.Assert (ml_projCursor > 0)
        Call SetControlTagDB(ml_projCursor, "CPR_code", cmd_SelectProj, True, av_Key(0))
        Call SetTextBoxTextDB(ml_projCursor, "SP_desc", txt_ProName, True)
        Call SetTextBoxTextDB(ml_projCursor, "SP_addr1", txt_ProSiteAddress1, True)
        Call SetTextBoxTextDB(ml_projCursor, "SP_addr2", txt_ProSiteAddress2, True)
        Call SetTextBoxTextDB(ml_projCursor, "SP_zip", txt_ProZipCode, True)
        Call SetTextBoxTextDB(ml_projCursor, "SP_town", txt_ProTown, True)
        Call SetTextBoxTextDB(ml_projCursor, "CT_desc", txt_ProCountry, True)
    Case smItemMain
Const C_REQ1 As String = "EXEC Base_Item_Plants_cbo '$SAP_CODE$', '$LANG$'"
Const C_REQ2 As String = "EXEC Base_Item_Suppliers_cbo '$SAP_CODE$', '$LANG$'"
        Debug.Assert (ao_grid.SelectedKey(0)(0) = av_Key(0))
        
        ' fill item data into selected tab
        txt_ItemItem.Text = av_Key(0)
        
        Call cbo_SupSupplier.Clear
        Dim ls_req As String
        ls_req = Replace(IIf(ao_grid.CurrentLine("Origin_Type") = "Manufactured", C_REQ1, C_REQ2), "$SAP_CODE$", av_Key(0), , , vbTextCompare)
        cbo_SupSupplier.Request = Replace(ls_req, "$LANG$", ms_LanguageCode, , , vbTextCompare)
        Call cbo_SupSupplier.InitColumnNames(IIf(ao_grid.CurrentLine("Origin_Type") = "Manufactured", CVar(Array("MFGP_code", "MFGP_name")), CVar(Array("SP_code", "SPP_desc"))))
        
        ' load plant tab, because supplier depends of item
        If ml_DetailCursor(5) = 0 Then
            Debug.Assert (txt_GenReport.Text <> "")
            ' it is possible to load data into tab
            Call Item_LoadDB(ml_DetailCursor(5), ml_detailIconcurrencyCursor, _
                                ms_detailRequests(5), _
                                txt_GenReport.Text)
            Call Item_LoadValues(ml_DetailCursor(5))
        End If
        
        ' reset item description detail
        grd_ItemDescription.Requests = txt_ItemItem.Text
        Call grd_ItemDescription.ClearGrid
        pic_reloadItemDesc.Visible = True

    Case Else
        Debug.Assert (False)
    End Select
    Exit Sub
ErrHandler:
     Call ErrorHandler("UpdateGridAfterAction()")
End Sub

' when updating main grid from detail
Private Function GetDataSrcForGrid(ByVal ao_Column As ArmColumn) As String
On Error GoTo ErrHandler
    Select Case ao_Column.FieldName
        Case "CCU_desc_1"
            ' distributor for grd_claimMain grid - data are located on tab Customer
            If ml_DetailCursor(2) > 0 Then
                '- tab was opened => copy data from control
                GetDataSrcForGrid = txt_CustDisName
            Else
                '- tab was not seen => leave current data
                If ao_Column.Grid.Row = -1 Then
                    GetDataSrcForGrid = ""
                Else
                    GetDataSrcForGrid = ao_Column.GetData(ao_Column.Grid.Row)
                End If
            End If
        Case "CCU_desc_3"
            ' contractor for grd_claimMain grid
            If ml_DetailCursor(2) > 0 Then
                '- tab was opened => copy data from control
                GetDataSrcForGrid = txt_CustConName
            Else
                '- tab was not seen => leave current data
                If ao_Column.Grid.Row = -1 Then
                    GetDataSrcForGrid = ""
                Else
                    GetDataSrcForGrid = ao_Column.GetData(ao_Column.Grid.Row)
                End If
            End If
        Case "language_desc"
            ' language description for memo
            GetDataSrcForGrid = SQLComboBoxValue(cbo_MemoLanguage, ao_Column.GetData(ao_Column.Grid.Row), False)
        Case "CMM_title"
            ' title for memo
            GetDataSrcForGrid = txt_MemoTitle.Text
        Case "CMM_desc"
            ' description for memo
            GetDataSrcForGrid = txt_MemoComment.Text
        Case "SECURITY"
            ' security for memo
            ' only authorised user can insert/update record so in this place we return 1
            GetDataSrcForGrid = 1
        Case "CCR_info"
            ' info for notes
            GetDataSrcForGrid = txt_NoteCreditNote.Text
        Case "CCR_date"
            ' date for notes
            GetDataSrcForGrid = FormatD(cal_NoteDateIssued.date_courte, "mm/dd/yyyy")
        Case "CCR_amount"
            ' amount for notes
            GetDataSrcForGrid = ToDouble(txt_NoteAmount.Text)
        Case "CURR_desc"
            ' currency description for notes
            GetDataSrcForGrid = SQLComboBoxValue(cbo_NoteCurrency, ao_Column.GetData(ao_Column.Grid.Row), False)
        Case "CCU_desc"
            ' customer description for customer grid
            GetDataSrcForGrid = txt_SelCustModName.Text
        Case "SP_desc"
            ' project description for project grid
            GetDataSrcForGrid = txt_SelProjModName.Text
        Case Else
            Debug.Assert (False)
    End Select
    Exit Function
ErrHandler:
     Call ErrorHandler("GetDataSrcForGrid()")
End Function

Private Function Item_ReplacePlaceholders(ByVal as_tmplStr As String) As String
On Error GoTo ErrHandler
    Dim ls_req As String
        
    ' general
    ls_req = Replace(as_tmplStr, "$Status$", GetOptionButtonCode(opt_GenStatus), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CoordName$", SqlStr(SQLComboBoxValue(cbo_GenCoordinator, "", False)), , , vbTextCompare)
    ls_req = Replace(ls_req, "$SaleOffCode$", SQLComboBoxValue(cbo_GenSalesOffice, ""), , , vbTextCompare)
    ls_req = Replace(ls_req, "$TerrCode$", SQLComboBoxValue(cbo_GenTerritory, ""), , , vbTextCompare)
    ls_req = Replace(ls_req, "$Originator$", SQLComboBoxValue(cbo_GenRespSalesRep, ""), , , vbTextCompare)
    ls_req = Replace(ls_req, "$ReportDate$", SQLDateTime(cal_GenReportDate.date_dt))

'    ls_req = Replace(ls_req, "$CNACode$", SQLComboBoxValue(cbo_GenMainReason1, "0"))
    ls_req = Replace(ls_req, "$CLECode1$", SQLComboBoxValue(cbo_GenMainReason2, "0"), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CLECode2$", SQLComboBoxValue(cbo_Gen2ndReason2, "0"), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CRECode$", SQLComboBoxValue(cbo_GenAction, "0"), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CLOCode$", SQLComboBoxValue(cbo_GenOutcome, "0"), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CLOACode$", SQLComboBoxValue(cbo_GenOutcomeAction, "0"), , , vbTextCompare)
    ls_req = Replace(ls_req, "$Internet$", "", , , vbTextCompare)
    ls_req = Replace(ls_req, "$DropFlag$", "", , , vbTextCompare)
    ls_req = Replace(ls_req, "$DropDate$", SQLDateTime(0), , , vbTextCompare)
    
    ' cost common
    ls_req = Replace(ls_req, "$CurrCode$", SQLComboBoxValue(cbo_CostCurrency, ""), , , vbTextCompare)
    
    ' estimate cost
    ls_req = Replace(ls_req, "$CSSEstMatCost$", SQLNum(ToDouble(txt_CostEstMaterialCost.Text)), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CSSEstLabCost$", SQLNum(ToDouble(txt_CostEstLaborCost.Text)), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CSSEstOthCost$", SQLNum(ToDouble(txt_CostEstOtherCost.Text)), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CSSEstTotCost$", SQLNum(ToDouble(txt_CostEstTotalCost.Text)), , , vbTextCompare)
    
    ' proposed cost depends on status
    Select Case GenGetStatus()
    Case "I", "F", "R"
        ' data comes from estimated
        ls_req = Replace(ls_req, "$CSSProMatCost$", SQLNum(ToDouble(txt_CostEstMaterialCost.Text)), , , vbTextCompare)
        ls_req = Replace(ls_req, "$CSSProLabCost$", SQLNum(ToDouble(txt_CostEstLaborCost.Text)), , , vbTextCompare)
        ls_req = Replace(ls_req, "$CSSProOthCost$", SQLNum(ToDouble(txt_CostEstOtherCost.Text)), , , vbTextCompare)
        ls_req = Replace(ls_req, "$CSSProTotCost$", SQLNum(ToDouble(txt_CostEstTotalCost.Text)), , , vbTextCompare)
    Case "S"
        ' data comes from settlement
        ls_req = Replace(ls_req, "$CSSProMatCost$", SQLNum(ToDouble(txt_CostSetMaterialCost.Text)), , , vbTextCompare)
        ls_req = Replace(ls_req, "$CSSProLabCost$", SQLNum(ToDouble(txt_CostSetLaborCost.Text)), , , vbTextCompare)
        ls_req = Replace(ls_req, "$CSSProOthCost$", SQLNum(ToDouble(txt_CostSetOtherCost.Text)), , , vbTextCompare)
        ls_req = Replace(ls_req, "$CSSProTotCost$", SQLNum(ToDouble(txt_CostSetTotalCost.Text)), , , vbTextCompare)
    Case Else
        Debug.Assert (False)
    End Select
    
    ' settled cost
    ls_req = Replace(ls_req, "$CSSSetMatCost$", SQLNum(ToDouble(txt_CostSetMaterialCost.Text)), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CSSSetLabCost$", SQLNum(ToDouble(txt_CostSetLaborCost.Text)), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CSSSetOthCost$", SQLNum(ToDouble(txt_CostSetOtherCost.Text)), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CSSSetTotCost$", SQLNum(ToDouble(txt_CostSetTotalCost.Text)), , , vbTextCompare)
    
    ' Customer
    ls_req = Replace(ls_req, "$CLAWhoRaised$", GetOptionButtonCode(opt_CusWhoRaised, ""), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CLADistCode$", SQLNum(ToDouble(cmd_SelectCust(0).Tag)), , , vbTextCompare)      ' must be synchronized with fra_CustTabs!!! => the same index
    ls_req = Replace(ls_req, "$CLASpecCode$", SQLNum(ToDouble(cmd_SelectCust(1).Tag)), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CLAContCode$", SQLNum(ToDouble(cmd_SelectCust(2).Tag)), , , vbTextCompare)
    
    ' Project
    ls_req = Replace(ls_req, "$CPRCode$", SQLNum(ToDouble(cmd_SelectProj.Tag)), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CITSize$", SQLNum(ToDouble(txt_ProSize.Text)), , , vbTextCompare)
    ls_req = Replace(ls_req, "$UMCode$", SQLComboBoxValue(cbo_ProUnitMeasure, ""), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CITCondition$", GetOptionButtonCode(opt_ProSiteCondition, ""), , , vbTextCompare)
    
    ' Item
    ls_req = Replace(ls_req, "$BISapCode$", GetItemSAPCode()) ' SqlStr(txt_ItemItem.Text))
    ls_req = Replace(ls_req, "$GTCode$", SQLComboBoxValue(cbo_ItemGridType), , , vbTextCompare)
    ls_req = Replace(ls_req, "$GMCode$", SQLComboBoxValue(cbo_ItemGridManufac), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CITDateInst$", SQLDateTime(cal_ItemInstalationDate.date_dt), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CITProjDelay$", GetOptionButtonCode(opt_ItemProjectDelay), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CITVisitDate", SQLDateTime(cal_ItemVisitDate.date_dt), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CITVisitor$", SqlStr(txt_ItemVisitedBy.Text, 80), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CITSampleSent$", GetOptionButtonCode(opt_ItemSampleSent), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CITSampleDest$", SqlStr(txt_ItemSampleSentTo.Text, txt_ItemSampleSentTo.MaxLength), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CIT_sample_ReasonNo$", SqlStr(txt_ItemSampleReasonNo.Text, txt_ItemSampleReasonNo.MaxLength), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CITClaimSize$", SQLNum(ToDouble(txt_ItemClaimSize.Text)), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CITClaimUMCode$", SQLComboBoxValue(cbo_ItemUnitMeasureCS, ""), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CITDelivSize$", SQLNum(ToDouble(txt_ItemTotalDelivery.Text)), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CITInvoiceNo$", SqlStr(txt_ItemInvoiceNo.Text, txt_ItemInvoiceNo.MaxLength), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CITDelivUMCode$", SQLComboBoxValue(cbo_ItemUnitMeasureTD, ""), , , vbTextCompare)
    
    ' Suppl
    Dim lv_auxVal As Variant
    lv_auxVal = cbo_SupSupplier.GetItemData(SQLComboBoxValue(cbo_SupSupplier), "MFGP_code")
    ls_req = Replace(ls_req, "$MFGPCode$", IIf(IsEmpty(lv_auxVal), "", lv_auxVal), , , vbTextCompare)
    lv_auxVal = cbo_SupSupplier.GetItemData(SQLComboBoxValue(cbo_SupSupplier), "SP_code")
    ls_req = Replace(ls_req, "$SPCode$", IIf(IsEmpty(lv_auxVal), "", lv_auxVal))
    ls_req = Replace(ls_req, "$Batch1$", SqlStr(txt_SupBatchNumber1.Text, txt_SupBatchNumber1.MaxLength))
    ls_req = Replace(ls_req, "$Batch2$", SqlStr(txt_SupBatchNumber2.Text, txt_SupBatchNumber2.MaxLength))
    ls_req = Replace(ls_req, "$Batch3$", SqlStr(txt_SupBatchNumber3.Text, txt_SupBatchNumber3.MaxLength))
    ls_req = Replace(ls_req, "$Batch4$", SqlStr(txt_SupBatchNumber4.Text, txt_SupBatchNumber4.MaxLength))
    
    Item_ReplacePlaceholders = ls_req
    Exit Function
ErrHandler:
    Call ErrorHandler("Item_ReplacePlaceholders")
End Function

Private Sub Item_LoadIconcurrencyCursor(ByVal as_CLA_code As String)
On Error GoTo ErrHandler
Const REQ As String = "EXEC Clm_iConcurrency_sel '$Code$'"
    Debug.Assert (ml_detailIconcurrencyCursor = 0)

    Call Item_LoadDB(ml_detailIconcurrencyCursor, 0, REQ, as_CLA_code)
    Debug.Assert (mo_Db.RowCount(ml_detailIconcurrencyCursor) = 1)
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_LoadIconcurrencyCursor")
End Sub

Private Sub Item_CloseCursors()
On Error GoTo ErrHandler
    
    Dim ll_Index As Long
    For ll_Index = 0 To UBound(ml_DetailCursor)
        If ml_DetailCursor(ll_Index) > 0 Then
            Call mo_Db.Close(ml_DetailCursor(ll_Index))
        End If
        ml_DetailCursor(ll_Index) = 0
    Next

    If ml_detailIconcurrencyCursor <> 0 Then
        Call mo_Db.Close(ml_detailIconcurrencyCursor)
    End If
    ml_detailIconcurrencyCursor = 0
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_CloseCursors")
End Sub
'load claim item data to cursor
Private Sub Item_LoadDB(ByRef al_Cursor As Long, ByVal al_iConcCursor As Long, ByVal as_reqTmpl As String, ByVal as_Code As String)
On Error GoTo ErrHandler
    Debug.Assert (al_Cursor = 0)

    Dim ls_req As String
    
    ' replace standard placeholders
    ls_req = Replace(as_reqTmpl, "$Code$", SqlStr(as_Code), , , vbTextCompare)
    ls_req = Replace(ls_req, "$LangCode$", ms_LanguageCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$LoginName$", SqlStr(ms_LoginName), , , vbTextCompare)
    ls_req = ReplaceIconcurrency(ls_req, "$iConcurrency$", Nothing, al_iConcCursor, "iConcurrency")
    ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyCost1$", Nothing, al_iConcCursor, "iConcurrencyCost1")
    ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyCost2$", Nothing, al_iConcCursor, "iConcurrencyCost2")
    ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyCost3$", Nothing, al_iConcCursor, "iConcurrencyCost3")
    ls_req = ReplaceIconcurrency(ls_req, "$ItemiConcurrency$", Nothing, al_iConcCursor, "iConcurrency_I")
    ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyPlant$", Nothing, al_iConcCursor, "iConcurrencyPlant")
    ls_req = ReplaceIconcurrency(ls_req, "$iConcurrencyStat$", Nothing, al_iConcCursor, "iConcurrencyStat")

    al_Cursor = OpenSQLSafe(mo_Db, ls_req, ArmSQLAny)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_LoadDb")
End Sub

Public Sub Item_Print(ByVal as_CLA_code As String)
Const REQ_DATA As String = "EXEC Clm_Claim_print '$Code$', '$LangCode$'"
Const REQ_GEN_COMMENT As String = "EXEC Clm_Comment_Memo_Sel '$Code$', '$LangCode$'"
Const REQ_SUP_COMMENT As String = "EXEC Clm_Plant_Memo_Sel '$Code$', '$LangCode$'"

On Error GoTo ErrHandler
    Dim li_return As VbMsgBoxResult
    Dim ll_dataCursor As Long
    Dim ll_memoCommentCursor As Long
    Dim ll_memoPlantCursor As Long
    
    
    If Printers.Count = 0 Then
        SendMessage ms_LanguageCode, ErrMsgNoPrinter, "#No printer is installed on your computer. Please, contact your system administrator."
        Exit Sub
    End If
    li_return = SendMessage(ms_LanguageCode, ErrMsgAddMemos_Q, "#Add memos to report ?", , vbQuestion + vbYesNoCancel)
    If li_return = vbCancel Then
        Exit Sub
    End If
    

'PrintClaim (li_return = vbYes)


    Call Item_LoadDB(ll_dataCursor, 0, REQ_DATA, as_CLA_code)
    If li_return = vbYes Then
        Call Item_LoadDB(ll_memoCommentCursor, 0, REQ_GEN_COMMENT, as_CLA_code)
        Call Item_LoadDB(ll_memoPlantCursor, 0, REQ_SUP_COMMENT, as_CLA_code)
    End If

    ' init printer
    Call InitPrinter(1)
    
    ' Claim code
    Printer.Font.Size = 14
    Printer.Font.Bold = True
    Printer.Print "                   " & ms_Title & " N° " & as_CLA_code

    Call Item_PrintData(ll_dataCursor, ll_memoCommentCursor, ll_memoPlantCursor)
    
    ' finish printer job
    Printer.EndDoc
    
    Call mo_Db.Close(ll_dataCursor)
    ll_dataCursor = 0
    
    Call mo_Db.Close(ll_memoCommentCursor)
    ll_memoCommentCursor = 0
    
    Call mo_Db.Close(ll_memoPlantCursor)
    ll_memoPlantCursor = 0

    Exit Sub
ErrHandler:
    If ll_dataCursor <> 0 Then
        Call mo_Db.Close(ll_dataCursor)
        ll_dataCursor = 0
    End If
    If ll_memoCommentCursor <> 0 Then
        Call mo_Db.Close(ll_memoCommentCursor)
        ll_memoCommentCursor = 0
    End If
    If ll_memoPlantCursor <> 0 Then
        Call mo_Db.Close(ll_memoPlantCursor)
        ll_memoPlantCursor = 0
    End If
    Call ErrorHandler("Item_Print")
End Sub

Private Sub Item_PrintData(ByVal al_DataCursor As Long, ByVal al_memoCommentCursor As Long, ByVal al_memoPlantCursor As Long)
Const C_REQ_CREDITS As String = "EXEC Clm_Credit_t_lst '$CLA_CODE$', '$LANG$'"
Const C_REQ2 As String = "EXEC Base_Item_dtl '$BI_SAP_CODE$', '$LANG$'"
Const C_REQ3 As String = "EXEC Base_Item_dtl2 '$BI_SAP_CODE$', '$LANG$'"

On Error GoTo ErrHandler
    Debug.Assert (al_DataCursor <> 0)
    Dim ls_req As String
    Dim ls_CG_Code As String
    Dim ll_cursorDesc As Long

    ' General Info
    Printer.Print ""
    Printer.Print tbs_ClaimTabs(0).Tabs("_0").Caption
    Printer.Font.Size = 10
    Printer.Font.Bold = False
    Printer.Print ""
    PrintBold (GetControl(lbl_Label, "lbl_ReportDate") & " ")
    Printer.Print FormatDateTime(mo_Db.GetFields(al_DataCursor, "CLA_report_date")) & "   ";
    PrintBold (GetControl(lbl_Label, "lbl_InitDate") & " ")
    Printer.Print FormatDateTime(mo_Db.GetFields(al_DataCursor, "Z_creation")) & "   ";
    PrintBold (GetControl(lbl_Label, "lbl_LastUpdate") & " ")
    Printer.Print FormatDateTime(mo_Db.GetFields(al_DataCursor, "Z_last_upd"))
    
    If mo_Db.GetFields(al_DataCursor, "CLA_final_date") = 0 Then
        PrintBold (GetControl(lbl_Label, "lbl_Originator") & " ")
        Printer.Print mo_Db.GetFields(al_DataCursor, "SR_name") & "   ";
        PrintBold (fra_GenStatus.Caption & " ")
        Printer.Print mo_Db.GetFields(al_DataCursor, "CLA_status")
    Else
        PrintBold (GetControl(lbl_Label, "lbl_Originator") & " ")
        Printer.Print mo_Db.GetFields(al_DataCursor, "SR_name") & "   "
        PrintBold (fra_GenStatus.Caption & " ")
        Printer.Print GetOptionButtonTag(opt_GenStatus, 1, mo_Db.GetFields(al_DataCursor, "CLA_status"), 100) & "   "
        PrintBold (GetControl(lbl_Label, "lbl_FinalizedDate") & " ")
        Printer.Print FormatDateTime(mo_Db.GetFields(al_DataCursor, "CLA_final_date"))
    End If
    PrintBold (GetControl(lbl_Label, "lbl_Coordinator") & " ")
    Printer.Print mo_Db.GetFields(al_DataCursor, "CCO_desc") & "   ";
    PrintBold (GetControl(lbl_Label, "lbl_SalesOffice") & " ")
    Printer.Print mo_Db.GetFields(al_DataCursor, "SO_desc")
    
    PrintBold (GetControl(lbl_Label, "lbl_SalesMarket") & " ")
    Printer.Print mo_Db.GetFields(al_DataCursor, "SMK_desc") & "   ";
    PrintBold (GetControl(lbl_Label, "lbl_Country") & " ")
    Printer.Print mo_Db.GetFields(al_DataCursor, "CT_desc") & "   ";
    PrintBold (GetControl(lbl_Label, "lbl_Territory") & " ")
    Printer.Print mo_Db.GetFields(al_DataCursor, "TER_desc")
    
    PrintBold (GetControl(lbl_Label, "lbl_Reason1"))
    If mo_Db.GetFields(al_DataCursor, "reason11_desc") <> "" And mo_Db.GetFields(al_DataCursor, "reason12_desc") <> "" Then
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "reason11_desc") & "     " & mo_Db.GetFields(al_DataCursor, "reason12_desc")
    Else
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "reason11_desc")
    End If
    
    PrintBold (GetControl(lbl_Label, "lbl_Reason2"))
    If mo_Db.GetFields(al_DataCursor, "reason21_desc") <> "" And mo_Db.GetFields(al_DataCursor, "reason22_desc") <> "" Then
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "reason21_desc") & "     " & mo_Db.GetFields(al_DataCursor, "reason22_desc")
    Else
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "reason22_desc")
    End If
    
    PrintBold (GetControl(lbl_Label, "lbl_Action"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CRE_desc")
    If al_memoCommentCursor <> 0 Then
    
        PrintBold (Replace(cmd_GenComments.Caption, "...", "", , , vbTextCompare) & " :      ")
        Call Memo_Print(al_memoCommentCursor)
    End If

    If mo_Db.GetFields(al_DataCursor, "CLO_desc") <> "" Or mo_Db.GetFields(al_DataCursor, "CLOA_desc") <> "" Then
        PrintBold (GetControl(lbl_Label, "cbo_GenOutcome"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CLO_desc") & "     ";
        PrintBold (GetControl(lbl_Label, "cbo_GenOutcomeAction"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CLOA_desc")
    End If

    ' Cost Info
    Printer.Print ""
    Printer.Font.Size = 14
    PrintBold (tbs_ClaimTabs(0).Tabs("_1").Caption)
    Printer.Print ""
    Printer.Font.Size = 10
    Printer.Print ""
    
    Printer.Print fra_CostEstimatedCost.Caption
    PrintBold (GetControl(lbl_Label, "lbl_EstMatCost") & " ")
    Printer.Print mo_Db.GetFields(al_DataCursor, "EST_mat_cost") & "   ";
    PrintBold (GetControl(lbl_Label, "lbl_EstLabCost") & " ")
    Printer.Print mo_Db.GetFields(al_DataCursor, "EST_lab_cost") & "   ";
    PrintBold (GetControl(lbl_Label, "lbl_EstOthCost") & " ")
    Printer.Print mo_Db.GetFields(al_DataCursor, "EST_oth_cost") & "   ";
    PrintBold (GetControl(lbl_Label, "lbl_EstTotCost") & " ")
    Printer.Print mo_Db.GetFields(al_DataCursor, "EST_tot_cost")
    
    If mo_Db.GetFields(al_DataCursor, "CLA_status") = "S" Then
        Printer.Print fra_CostSettlementCost.Caption
        PrintBold (GetControl(lbl_Label, "lbl_EstMatCost") & " ")
        Printer.Print mo_Db.GetFields(al_DataCursor, "SET_mat_cost") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_EstLabCost") & " ")
        Printer.Print mo_Db.GetFields(al_DataCursor, "SET_lab_cost") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_EstOthCost") & " ")
        Printer.Print mo_Db.GetFields(al_DataCursor, "SET_oth_cost") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_EstTotCost") & " ")
        Printer.Print mo_Db.GetFields(al_DataCursor, "SET_tot_cost")
    End If
    PrintBold (GetControl(lbl_Label, "lbl_Currency"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CURR_desc")
    
    ' load credit notes
    Dim ll_crCursor As Long
    ls_req = Replace(C_REQ_CREDITS, "$CLA_CODE$", mo_Db.GetFields(al_DataCursor, "CLA_code"), , , vbTextCompare)
    ls_req = Replace(ls_req, "$LANG$", ms_LanguageCode, , , vbTextCompare)
    ll_crCursor = OpenSQLSafe(mo_Db, ls_req)
    
    Call Note_Print(ll_crCursor)
    
    Call mo_Db.Close(ll_crCursor)
    ll_crCursor = 0

    ' Customer Info
    Printer.Print ""
    Printer.Font.Size = 14
    PrintBold (tbs_ClaimTabs(0).Tabs("_2").Caption)
    Printer.Print ""
    Printer.Font.Size = 10
    Printer.Print ""
    PrintBold (fra_CusWhoRaised.Caption)
    Printer.Print " " & GetOptionButtonTag(opt_CusWhoRaised, 1, mo_Db.GetFields(al_DataCursor, "CLA_who_raised"), 100)
    If mo_Db.GetFields(al_DataCursor, "CLA_dist_code") <> 0 Then
        Printer.Print tbs_CustTabs.Tabs("_0").Caption
        PrintBold (GetControl(lbl_Label, "lbl_DistName"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_desc_1")
        
        PrintBold (GetControl(lbl_Label, "lbl_DistAddress"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_addr1_1") & ";       " & mo_Db.GetFields(al_DataCursor, "CCU_addr2_1")
        
        PrintBold (GetControl(lbl_Label, "lbl_DistZipCode"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_zip_1") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_DistTown"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_town_1") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_Country"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CT_desc_1")
        
        PrintBold (GetControl(lbl_Label, "lbl_DistContact"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_contact_1") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_DistPhone"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_tel_1") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_DistFax"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_fax_1")
    End If
    If mo_Db.GetFields(al_DataCursor, "CLA_spec_code") <> 0 Then
        Printer.Print tbs_CustTabs.Tabs("_1").Caption
        PrintBold (GetControl(lbl_Label, "lbl_DistName"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_desc_2")
        
        PrintBold (GetControl(lbl_Label, "lbl_DistAddress"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_addr1_2") & ";       " & mo_Db.GetFields(al_DataCursor, "CCU_addr2_2")
        
        PrintBold (GetControl(lbl_Label, "lbl_DistZipCode"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_zip_2") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_DistTown"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_town_2") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_Country"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CT_desc_2")
        
        PrintBold (GetControl(lbl_Label, "lbl_DistContact"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_contact_2") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_DistPhone"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_tel_2") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_DistFax"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_fax_2")
    End If
    If mo_Db.GetFields(al_DataCursor, "CLA_cont_code") <> 0 Then
        Printer.Print tbs_CustTabs.Tabs("_2").Caption
        PrintBold (GetControl(lbl_Label, "lbl_DistName"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_desc_3")
        
        PrintBold (GetControl(lbl_Label, "lbl_DistAddress"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_addr1_3") & ";       " & mo_Db.GetFields(al_DataCursor, "CCU_addr2_3")
        
        PrintBold (GetControl(lbl_Label, "lbl_DistZipCode"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_zip_3") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_DistTown"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_town_3") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_Country"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CT_desc_3")
        
        PrintBold (GetControl(lbl_Label, "lbl_DistContact"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_contact_3") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_DistPhone"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_tel_3") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_DistFax"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CCU_fax_3")
    End If

    ' Project Info
    Printer.Print ""
    Printer.Font.Size = 14
    PrintBold (tbs_ClaimTabs(0).Tabs("_3").Caption)
    Printer.Print ""
    Printer.Font.Size = 10
    
    Printer.Print ""
    PrintBold (GetControl(lbl_Label, "lbl_DistName"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "SP_desc")
    
    PrintBold (GetControl(lbl_Label, "lbl_ProjectAddress"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "SP_addr1") & ";       " & mo_Db.GetFields(al_DataCursor, "SP_addr2")
    
    PrintBold (GetControl(lbl_Label, "lbl_DistZipCode"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "SP_zip") & "   ";
    PrintBold (GetControl(lbl_Label, "lbl_DistTown"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "SP_town") & "   ";
    PrintBold (GetControl(lbl_Label, "lbl_Country"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CT_desc_P")
    
    PrintBold (GetControl(lbl_Label, "lbl_ProjectSize"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CIT_Size_P") & "  " _
        & mo_Db.GetFields(al_DataCursor, "UM_desc_P") & "       ";
    PrintBold (fra_ProSiteCondition.Caption)
    Printer.Print " " & GetOptionButtonTag(opt_ProSiteCondition, 1, mo_Db.GetFields(al_DataCursor, "CIT_condition"), 100)


    ' Item Info
    Printer.Print ""
    Printer.Font.Size = 14
    PrintBold (tbs_ClaimTabs(0).Tabs("_4").Caption)
    Printer.Print ""
    Printer.Font.Size = 10
    Printer.Print ""
    
    PrintBold (GetControl(lbl_Label, "lbl_ClaimSize"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CIT_claim_size") & "  " & mo_Db.GetFields(al_DataCursor, "CIT_claim_UM_desc") & "    ";
    PrintBold (GetControl(lbl_Label, "lbl_TotalDelivery"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CIT_deliv_size") & "  " & mo_Db.GetFields(al_DataCursor, "CIT_deliv_UM_desc")
    PrintBold (GetControl(lbl_Label, "lbl_InvoiceNo"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CIT_Invoice_No")
        
    PrintBold (GetControl(lbl_Label, "lbl_Item"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "BI_SAP_code")
    
'Task 327 August 2006
'    If mo_Db.GetFields(al_dataCursor, "CG_code") <> "" Then
'
'        ls_CG_code = mo_Db.GetFields(al_dataCursor, "CG_code")
'        ls_Req = IIf(ls_CG_code = "C006" Or ls_CG_code = "C001", C_REQ2, C_REQ3)
'        ls_Req = Replace(ls_Req, "$BI_SAP_CODE$", mo_Db.GetFields(al_dataCursor, "BI_SAP_code"))
'        ls_Req = Replace(ls_Req, "$LANG$", ms_LanguageCode)
'        ll_cursorDesc = OpenSQLSafe(mo_Db, ls_Req, ArmSQLExactOne)
'
'        Dim ll_Index As Long
'        Dim lv_Fields As Variant
'        lv_Fields = mo_Db.Fields(ll_cursorDesc)
'        For ll_Index = 0 To mo_Db.FieldCount(ll_cursorDesc) - 1
'            grd_ItemDescription.Rows = grd_ItemDescription.Rows + 1
'            If mo_Db.Find(ml_itemDescLabelsCursor, "Field_name", lv_Fields(ll_Index), 0) > -1 Then
'                Printer.CurrentX = 200
'                Printer.Print "  " & TruncField(mo_Db.GetFields(ml_itemDescLabelsCursor, "Local_text"), 40);
'                Printer.CurrentX = 1500
'                Printer.Print TruncField(mo_Db.GetFields(ll_cursorDesc, lv_Fields(ll_Index)), 40)
'            Else
'                Debug.Assert (False)
'            End If
'        Next
'        mo_Db.Close (ll_cursorDesc)
'        ll_cursorDesc = 0
'
'    End If

    PrintBold (GetControl(lbl_Label, "lbl_ProjectInstDate"))
    Printer.Print " " & FormatDateTime(mo_Db.GetFields(al_DataCursor, "CIT_date_inst")) & "     ";
    PrintBold (GetControl(lbl_Label, "lbl_GridType"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "GT_desc") & "    ";
    PrintBold (GetControl(lbl_Label, "lbl_GridManuf"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "GM_desc") & "    "
    
    If mo_Db.GetFields(al_DataCursor, "CIT_visit_date") <> 0 And mo_Db.GetFields(al_DataCursor, "CIT_visitor") <> "" Then
        PrintBold (GetControl(lbl_Label, "lbl_VisitDate"))
        Printer.Print " " & FormatDateTime(mo_Db.GetFields(al_DataCursor, "CIT_visit_date")) & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_ByWhom"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CIT_visitor")
    Else
        PrintBold (GetControl(lbl_Label, "lbl_VisitDate"))
        Printer.Print " " & FormatDateTime(mo_Db.GetFields(al_DataCursor, "CIT_visit_date"))
    End If
    
    If mo_Db.GetFields(al_DataCursor, "CIT_sample_sent") = "Y" And mo_Db.GetFields(al_DataCursor, "CIT_sample_dest") <> "" Then
        PrintBold (GetControl(lbl_Label, "lbl_ProjectDelay"))
        Printer.Print " " & GetOptionButtonTag(opt_ItemProjectDelay, 1, mo_Db.GetFields(al_DataCursor, "CIT_proj_delay"), 100, "not specified") & "    ";
        PrintBold (GetControl(lbl_Label, "lbl_SampleSent"))
        Printer.Print " " & GetOptionButtonTag(opt_ItemSampleSent, 1, mo_Db.GetFields(al_DataCursor, "CIT_sample_sent"), 100, "not specified") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_SentTo"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CIT_sample_dest")
    Else
        PrintBold (GetControl(lbl_Label, "lbl_ProjectDelay"))
        Printer.Print " " & GetOptionButtonTag(opt_ItemProjectDelay, 1, mo_Db.GetFields(al_DataCursor, "CIT_proj_delay"), 100, "not specified") & "    ";
        PrintBold (GetControl(lbl_Label, "lbl_SampleSent"))
        Printer.Print " " & GetOptionButtonTag(opt_ItemSampleSent, 1, mo_Db.GetFields(al_DataCursor, "CIT_sample_sent"), 100, "not specified") & "   ";
        PrintBold (GetControl(lbl_Label, "lbl_SampleReasonNo"))
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CIT_sample_ReasonNo")
    End If

    ' Plant Info
    Printer.Print ""
    Printer.Font.Size = 14
    PrintBold (tbs_ClaimTabs(0).Tabs("_5").Caption)
    Printer.Print ""
    Printer.Font.Size = 10
    Printer.Print ""
    PrintBold (GetControl(lbl_Label, "lbl_Plant"))
    If mo_Db.GetFields(al_DataCursor, "MFGP_code") <> 0 Then
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "MFGP_name")
    End If
    If mo_Db.GetFields(al_DataCursor, "SP_code") <> 0 Then
        Printer.Print " " & mo_Db.GetFields(al_DataCursor, "SPP_desc")
    End If

    If al_memoPlantCursor <> 0 Then
        PrintBold (Replace(cmd_GenComments.Caption, "...", "", , , vbTextCompare) & " :      ")
        Call Memo_Print(al_memoPlantCursor)
    End If

    PrintBold (GetControl(lbl_Label, "lbl_PlantClose"))
    Printer.Print " " & FormatDateTime(mo_Db.GetFields(al_DataCursor, "CLA_Plant_Date"))
    PrintBold (GetControl(lbl_Label, "lbl_Batch"))
    Printer.Print " " & mo_Db.GetFields(al_DataCursor, "CPL_Batch1")
    Printer.Print "             " & mo_Db.GetFields(al_DataCursor, "CPL_Batch2")
    Printer.Print "             " & mo_Db.GetFields(al_DataCursor, "CPL_Batch3")
    Printer.Print "             " & mo_Db.GetFields(al_DataCursor, "CPL_Batch4")
    Printer.Print ""

    Exit Sub
ErrHandler:
    If ll_crCursor <> 0 Then
        Call mo_Db.Close(ll_crCursor)
        ll_crCursor = 0
    End If
    If ll_cursorDesc <> 0 Then
        Call mo_Db.Close(ll_cursorDesc)
        ll_cursorDesc = 0
    End If
    
    Call ErrorHandler("Item_PrintData")
End Sub


' assign value only if as_field occured in cursor
Private Sub SetTextBoxTextDB(ByVal al_Cursor As Long, ByVal as_Field As String, ByRef ao_Control As VB.TextBox, Optional ByVal ab_clearIfNotExists As Boolean = True, Optional as_emptyVal As String = "", Optional ByVal as_Format As String = "")
On Error GoTo ErrHandler
    Dim lv_val As Variant
    lv_val = mo_Db.GetFields(al_Cursor, as_Field)
    If Not IsEmpty(lv_val) Then
'        ao_control.Text = CStr(lv_val)
        ao_Control.Text = ToStr(lv_val, as_Format)
    Else
        If ab_clearIfNotExists Or mo_Db.GetFieldIndex(al_Cursor, as_Field) <> -1 Then
            ao_Control.Text = ToStr(as_emptyVal, as_Format)
        End If
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("SetTextBoxTextDB")
End Sub

' assign value only if as_field occured in cursor
Private Sub SetArmGridLoadDB(ByVal al_Cursor As Long, ByVal as_Field As String, ByVal as_valueTmpl As String, ByRef ao_Control As ArmGrid, Optional ByVal ab_clearIfNotExists As Boolean = True)
On Error GoTo ErrHandler
    Dim lv_val As Variant
    lv_val = mo_Db.GetFields(al_Cursor, as_Field)
    If Not IsEmpty(lv_val) Then
        as_valueTmpl = Replace(as_valueTmpl, "$DBVALUE$", CStr(lv_val), , , vbTextCompare)
        If ao_Control.UnBound Then
            ' only set tag value of a control and clear content
            ao_Control.Requests = as_valueTmpl
            Call ao_Control.ClearGrid
        Else
            ' try to load grid
            If Not ao_Control.Load(as_valueTmpl, False) Then
                Call Err.Raise(CompFncFailed, "ao_control.Load")
            End If
        End If
    Else
        If ab_clearIfNotExists Or mo_Db.GetFieldIndex(al_Cursor, as_Field) <> -1 Then
            Call ao_Control.ClearGrid
        End If
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("SetTextBoxTextDB")
End Sub

Private Sub SetOptionButtonCodeDB(ByVal al_Cursor As Long, ByVal as_Field As String, ByRef aao_OptionGroup As Object, Optional ByVal ab_clearIfNotExists As Boolean = True)
On Error GoTo ErrHandler
    Dim lv_val As Variant
    lv_val = mo_Db.GetFields(al_Cursor, as_Field)
    If Not IsEmpty(lv_val) Then
        Call SetOptionButtonCode(aao_OptionGroup, CStr(lv_val))
    Else
        If ab_clearIfNotExists Or mo_Db.GetFieldIndex(al_Cursor, as_Field) <> -1 Then
            ' set default values
            Dim lo_ctrl As Control
            Dim ls_defValue As String
            ls_defValue = ""
            For Each lo_ctrl In aao_OptionGroup
                Dim lValues() As String
                lValues = Split(lo_ctrl.Tag, SEP)
                If UBound(lValues) > 1 Then
                    If lValues(2) = "1" Then ls_defValue = lValues(1)
                    Exit For
                End If
            Next
            Call SetOptionButtonCode(aao_OptionGroup, ls_defValue)
        End If
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("SetOptionButtonCodeDB")
End Sub

' assign value only if as_field occured in cursor
Private Sub SetControlTagDB(ByVal al_Cursor As Long, ByVal as_Field As String, ByRef ao_Control As Object, Optional ByVal ab_clearIfNotExists As Boolean = True, Optional ByVal as_clearVal As String = "")
On Error GoTo ErrHandler
    Dim lv_val As Variant
    lv_val = mo_Db.GetFields(al_Cursor, as_Field)
    If Not IsEmpty(lv_val) Then
        ao_Control.Tag = CStr(lv_val)
    Else
        If ab_clearIfNotExists Or mo_Db.GetFieldIndex(al_Cursor, as_Field) <> -1 Then
            ao_Control.Tag = as_clearVal
        End If
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("SetTextBoxTextDB")
End Sub

' select option button by code
Private Sub SetOptionButtonCode(ByRef aao_OptionGroup As Object, Optional ByVal as_Code As String = "")
On Error GoTo ErrHandler
    Dim lo_OptionButton As OptionButton
    For Each lo_OptionButton In aao_OptionGroup
        Dim lva_Values As Variant
        lva_Values = Split(lo_OptionButton.Tag, SEP)
        If UBound(lva_Values) > 0 Then
            lo_OptionButton.Value = (lva_Values(1) = as_Code)
        End If
    Next
    Exit Sub
ErrHandler:
    Call ErrorHandler("SetOptionButtonCode")
End Sub

Private Sub SetCalendarTextDB(ByVal al_Cursor As Long, ByVal as_Field As String, ByRef ao_Calendar As A_calocx, Optional ByVal ab_clearIfNotExists As Boolean = True)
On Error GoTo ErrHandler
    Dim lv_val As Variant
    lv_val = mo_Db.GetFields(al_Cursor, as_Field)
    If Not IsEmpty(lv_val) Then
        Call SetCalendarText(ao_Calendar, IIf(lv_val = 0, "", Format(lv_val, "dd\/mm\/yyyy")))
    Else
        If ab_clearIfNotExists Or mo_Db.GetFieldIndex(al_Cursor, as_Field) <> -1 Then
            Call SetCalendarText(ao_Calendar, "")
        End If
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("SetCalendarTextDB")
End Sub

' Sets calendar text
Private Sub SetCalendarText(ByRef ao_Calendar As A_calocx, ByVal as_Date As String)
On Error GoTo ErrHandler
    If as_Date = "" Then
        ao_Calendar.reinit_cal
    Else
        ao_Calendar.date_courte = as_Date
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("SetCalendarText")
End Sub

Private Sub SetComboBoxTextDB(ByVal al_Cursor As Long, ByVal as_keyField As String, ByVal as_DescField As String, ByRef ao_Combobox As ArmCombobox, Optional ByVal ab_clearIfNotExists As Boolean = True)
On Error GoTo ErrHandler
    Dim lv_val As Variant
    lv_val = mo_Db.GetFields(al_Cursor, CVar(Array(as_keyField, as_DescField)))
    If Not IsEmpty(lv_val) Then
        Debug.Assert (UBound(lv_val) = 1)
        Call SetComboBoxText(ao_Combobox, CStr(lv_val(0)), CStr(lv_val(1)))
    Else
        If ab_clearIfNotExists Or mo_Db.GetFieldIndex(al_Cursor, as_keyField) <> -1 Then
            Call ao_Combobox.Clear
        End If
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("SetComboBoxTextDB")
End Sub

' Sets combobox selected item
' Params:
' ao_ComboBox (ArmCombobox)
' as_Key (String)
' as_Desc (String)
Private Sub SetComboBoxText(ByRef ao_Combobox As ArmCombobox, ByVal as_Key As String, ByVal as_desc As String)
On Error GoTo ErrHandler
    If Not ao_Combobox.SearchItem(as_Key) Then
        ' key not found ... set value from parameter
        If as_Key = "" Or as_Key = "0" Then     ' zero or empty string is not valid key
            Set ao_Combobox.SelectedItem = Nothing
        Else
            Call ao_Combobox.AddItem(Array(as_Key, as_desc), True)
            ' to make vb raise event
            Call ao_Combobox.SearchItem(as_Key)
        End If
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("SetComboBoxText")
End Sub

' loads values from cursor into form. if cursor=0 then reset whole detail
Private Sub Item_LoadValues(ByVal al_Cursor As Long)
On Error GoTo ErrHandler
Const C_REQ As String = "EXEC Clm_Credit_t_lst '$CLA_CODE$', '$LANG$'"
    Debug.Assert (al_Cursor <> 0)   ' loading uninitialized cursor?
    
    mb_Initializing = True
    
    Dim lb_clearControls As Boolean
    Dim lv_val As Variant
    lb_clearControls = (al_Cursor = -1)
    
    Call mo_Db.First(al_Cursor)
    Do
        ' general tab
                    
        Call SetCalendarTextDB(al_Cursor, "cla_report_date", cal_GenReportDate, lb_clearControls)
        Call SetCalendarTextDB(al_Cursor, "z_creation", cal_GenInitDate, lb_clearControls)
        Call SetCalendarTextDB(al_Cursor, "z_last_upd", cal_GenUpdateDate, lb_clearControls)
        Call SetCalendarTextDB(al_Cursor, "CLA_final_date", cal_GenFinishDate, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "CRE_code", "CRE_desc", cbo_GenAction, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "CLO_code", "CLO_desc", cbo_GenOutcome, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "CLOA_code", "CLOA_desc", cbo_GenOutcomeAction, lb_clearControls)
        Call SetOptionButtonCodeDB(al_Cursor, "CLA_Status", opt_GenStatus, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "CCO_code", "CCO_desc", cbo_GenCoordinator, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "SO_code", "SO_desc", cbo_GenSalesOffice, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "SMK_code", "SMK_desc", cbo_GenSalesMarket, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "CT_code", "CT_desc", cbo_GenCountry, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "reason11_code", "reason11_desc", cbo_GenMainReason1, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "reason12_code", "reason12_desc", cbo_GenMainReason2, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "reason21_code", "reason21_desc", cbo_Gen2ndReason1, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "reason22_code", "reason22_desc", cbo_Gen2ndReason2, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "TER_code", "TER_desc", cbo_GenTerritory, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "SR_code", "SR_name", cbo_GenRespSalesRep, lb_clearControls)
        
        ' cost tab
        lv_val = mo_Db.GetFields(al_Cursor, "CCS_order")
        If Not IsEmpty(lv_val) Then
            Select Case lv_val
                Case 1: ' Estimated cost
                    Call SetTextBoxTextDB(al_Cursor, "CCS_mat_cost", txt_CostEstMaterialCost, lb_clearControls, "", C_COST_VALUE_FORMAT)
                    Call SetTextBoxTextDB(al_Cursor, "CCS_lab_cost", txt_CostEstLaborCost, lb_clearControls, "", C_COST_VALUE_FORMAT)
                    Call SetTextBoxTextDB(al_Cursor, "CCS_oth_cost", txt_CostEstOtherCost, lb_clearControls, "", C_COST_VALUE_FORMAT)
                    Call SetTextBoxTextDB(al_Cursor, "CCS_tot_cost", txt_CostEstTotalCost, lb_clearControls, "", C_COST_VALUE_FORMAT)
                    
                    Call SetComboBoxTextDB(al_Cursor, "CURR_code", "CURR_desc", cbo_CostCurrency, lb_clearControls)
                    Dim ls_req As String
                    ls_req = Replace(C_REQ, "$CLA_CODE$", txt_GenReport.Text, , , vbTextCompare)
                    ls_req = Replace(ls_req, "$LANG$", ms_LanguageCode, , , vbTextCompare)
                    Call SetArmGridLoadDB(al_Cursor, "CCS_order", ls_req, grd_CostNotes, lb_clearControls)
                Case 2: ' Proposed cost - not processed
'                    Call SetTextBoxTextDB(al_Cursor, "CCS_mat_cost", txt_CostProMaterialCost, lb_clearControls, "", C_COST_VALUE_FORMAT)
'                    Call SetTextBoxTextDB(al_Cursor, "CCS_lab_cost", txt_CostProLaborCost, lb_clearControls, "", C_COST_VALUE_FORMAT)
'                    Call SetTextBoxTextDB(al_Cursor, "CCS_oth_cost", txt_CostProOtherCost, lb_clearControls, "", C_COST_VALUE_FORMAT)
'                    Call SetTextBoxTextDB(al_Cursor, "CCS_tot_cost", txt_CostProTotalCost, lb_clearControls, "", C_COST_VALUE_FORMAT)
                Case 3: ' Settled cost
                    If GenGetStatus() = "S" Then
                        Call SetTextBoxTextDB(al_Cursor, "CCS_mat_cost", txt_CostSetMaterialCost, lb_clearControls, "", C_COST_VALUE_FORMAT)
                        Call SetTextBoxTextDB(al_Cursor, "CCS_lab_cost", txt_CostSetLaborCost, lb_clearControls, "", C_COST_VALUE_FORMAT)
                        Call SetTextBoxTextDB(al_Cursor, "CCS_oth_cost", txt_CostSetOtherCost, lb_clearControls, "", C_COST_VALUE_FORMAT)
                        Call SetTextBoxTextDB(al_Cursor, "CCS_tot_cost", txt_CostSetTotalCost, lb_clearControls, "", C_COST_VALUE_FORMAT)
                    Else
                        txt_CostSetMaterialCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                        txt_CostSetLaborCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                        txt_CostSetOtherCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                        txt_CostSetTotalCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                    End If
            End Select
        Else
            If lb_clearControls Then
                txt_CostEstMaterialCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                txt_CostEstLaborCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                txt_CostEstOtherCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                txt_CostEstTotalCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                
                txt_CostSetMaterialCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                txt_CostSetLaborCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                txt_CostSetOtherCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                txt_CostSetTotalCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                Call cbo_CostCurrency.Clear
                Call grd_CostNotes.ClearGrid
            End If
        End If

        
        ' customer tab
        If Not IsEmpty(mo_Db.GetFields(al_Cursor, "CLA_who_raised")) Then
            Call SetOptionButtonCodeDB(al_Cursor, "CLA_who_raised", opt_CusWhoRaised, lb_clearControls)
            ' set also fra_custTabs
            Select Case (GetOptionButtonCode(opt_CusWhoRaised, "NULL"))
            Case "D"
                tbs_CustTabs.SelectedItem = tbs_CustTabs.Tabs.Item("_0")
            Case "S"
                tbs_CustTabs.SelectedItem = tbs_CustTabs.Tabs.Item("_1")
            Case "C"
                tbs_CustTabs.SelectedItem = tbs_CustTabs.Tabs.Item("_2")
            End Select
'            Call UpdateTabStrip(tbs_CustTabs, fra_CustTabs)
        End If
        Call SetControlTagDB(al_Cursor, "CLA_dist_code", cmd_SelectCust(0), lb_clearControls, "0")
        Call SetControlTagDB(al_Cursor, "CLA_spec_code", cmd_SelectCust(1), lb_clearControls, "0")
        Call SetControlTagDB(al_Cursor, "CLA_cont_code", cmd_SelectCust(2), lb_clearControls, "0")
        
        ' Distributor frame
        Call SetTextBoxTextDB(al_Cursor, "CCU_desc", txt_CustDisName, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_addr1", txt_CustDisAddress1, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_addr2", txt_CustDisAddress2, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_zip", txt_CustDisZipCode, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_town", txt_CustDisTown, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_contact", txt_CustDisContact, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_tel", txt_CustDisTelephone, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_fax", txt_CustDisFax, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CUST_code", txt_CustDisSAPCode, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CT_desc_1", txt_CustDisCountry, lb_clearControls)
                
        ' Specifier frame
        Call SetTextBoxTextDB(al_Cursor, "CCU_desc_2", txt_CustSpeName, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_addr1_2", txt_CustSpeAddress1, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_addr2_2", txt_CustSpeAddress2, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_zip_2", txt_CustSpeZipCode, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_town_2", txt_CustSpeTown, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_contact_2", txt_CustSpeContact, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_tel_2", txt_CustSpeTelephone, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_fax_2", txt_CustSpeFax, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CUST_code_2", txt_CustSpeSAPCode, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CT_desc_2", txt_CustSpeCountry, lb_clearControls)
                
        ' Contractor frame
        Call SetTextBoxTextDB(al_Cursor, "CCU_desc_3", txt_CustConName, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_addr1_3", txt_CustConAddress1, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_addr2_3", txt_CustConAddress2, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_zip_3", txt_CustConZipCode, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_town_3", txt_CustConTown, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_contact_3", txt_CustConContact, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_tel_3", txt_CustConTelephone, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CCU_fax_3", txt_CustConFax, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CUST_code_3", txt_CustConSAPCode, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CT_desc_3", txt_CustConCountry, lb_clearControls)
        
        ' Project frame
        Call SetControlTagDB(al_Cursor, "CPR_code", cmd_SelectProj, lb_clearControls, "0")
        Call SetTextBoxTextDB(al_Cursor, "SP_desc", txt_ProName, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "SP_addr1", txt_ProSiteAddress1, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "SP_addr2", txt_ProSiteAddress2, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "SP_zip", txt_ProZipCode, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "SP_town", txt_ProTown, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CIT_size", txt_ProSize, lb_clearControls, "0", C_NUMERIC_VALUE_FORMAT)
        Call SetTextBoxTextDB(al_Cursor, "CT_desc_P", txt_ProCountry, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "UM_code", "UM_desc", cbo_ProUnitMeasure, lb_clearControls)
        Call SetOptionButtonCodeDB(al_Cursor, "CIT_condition", opt_ProSiteCondition, lb_clearControls)

        ' item frame
        Call SetOptionButtonCodeDB(al_Cursor, "CIT_proj_delay", opt_ItemProjectDelay, lb_clearControls)
        Call SetOptionButtonCodeDB(al_Cursor, "CIT_sample_sent", opt_ItemSampleSent, lb_clearControls)
                
        Call SetCalendarTextDB(al_Cursor, "CIT_date_inst", cal_ItemInstalationDate, lb_clearControls)
        
        ' this is special line of code to handle that txt_ItemVisitedBy is driven by cal_ItemVisitDate
        lv_val = mo_Db.GetFields(al_Cursor, "CIT_visit_date")
        If Not IsEmpty(lv_val) Then
            Call SetCalendarTextDB(al_Cursor, "CIT_visit_date", cal_ItemVisitDate, lb_clearControls)
            If lv_val <> "" Then
                Call SetEnabledCtrl(txt_ItemVisitedBy, (activeScreenMode = smAdd) Or (activeScreenMode = smCustUpdate))
            End If
        Else
            If lb_clearControls Then
                cal_ItemVisitDate.reinit_cal
            End If
        End If
        
        ' grid is driven by pic_
        If Not IsEmpty(mo_Db.GetFields(al_Cursor, "BI_SAP_code")) Then
            Call SetArmGridLoadDB(al_Cursor, "BI_SAP_code", "$DBVALUE$", grd_ItemDescription, lb_clearControls)
            pic_reloadItemDesc.Visible = True
            Call SetTextBoxTextDB(al_Cursor, "BI_SAP_code", txt_ItemItem, lb_clearControls)
        End If
        Call SetTextBoxTextDB(al_Cursor, "CIT_claim_size", txt_ItemClaimSize, lb_clearControls, "0", C_NUMERIC_VALUE_FORMAT)
        Call SetTextBoxTextDB(al_Cursor, "CIT_deliv_size", txt_ItemTotalDelivery, lb_clearControls, "0", C_NUMERIC_VALUE_FORMAT)
        Call SetTextBoxTextDB(al_Cursor, "CIT_Invoice_No", txt_ItemInvoiceNo, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CIT_sample_dest", txt_ItemSampleSentTo, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CIT_sample_ReasonNo", txt_ItemSampleReasonNo, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CIT_visitor", txt_ItemVisitedBy, lb_clearControls)
               
        Call SetComboBoxTextDB(al_Cursor, "GM_code", "GM_desc", cbo_ItemGridManufac, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "GT_code", "GT_desc", cbo_ItemGridType, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "CIT_claim_UM_code", "CIT_claim_UM_desc", cbo_ItemUnitMeasureCS, lb_clearControls)
        Call SetComboBoxTextDB(al_Cursor, "CIT_deliv_UM_code", "CIT_deliv_UM_desc", cbo_ItemUnitMeasureTD, lb_clearControls)

        ' suppl./plant frame
        If mo_Db.GetFieldIndex(al_Cursor, "MFGP_code") <> -1 Then
            If cbo_SupSupplier.Request = "" Then
                Debug.Assert (Not IsEmpty(mo_Db.GetFields(al_Cursor, "BI_SAP_codeOld")))
                ' test inconsistency in system ( difference in BI_SAP_code Claim_Plant/Claim_Item)
                Debug.Assert (txt_ItemItem.Text = "" Or txt_ItemItem.Text = mo_Db.GetFields(al_Cursor, "BI_SAP_codeOld"))
                ' Supplier was not initialized yet, so init it from current cursor
                ' in case combo is initialized - item was changed - so we must accept changes and not replace from cursor
                Call cbo_SupSupplier.Clear
Const C_REQ1 As String = "EXEC Base_Item_Plants_cbo '$SAP_CODE$', '$LANG$'"
Const C_REQ2 As String = "EXEC Base_Item_Suppliers_cbo '$SAP_CODE$', '$LANG$'"
                
                If txt_ItemItem.Text = "" Then txt_ItemItem.Text = mo_Db.GetFields(al_Cursor, "BI_SAP_codeOld")
                
                Dim lv_columnNames As Variant
                If mo_Db.GetFields(al_Cursor, "MFGP_code") <> "" Then
                    ls_req = Replace(C_REQ1, "$SAP_CODE$", txt_ItemItem.Text, , , vbTextCompare)
                    lv_columnNames = CVar(Array("MFGP_code", "MFGP_name"))
                    Call SetComboBoxTextDB(al_Cursor, "MFGP_code", "MFGP_name", cbo_SupSupplier)
                Else
                    ls_req = Replace(C_REQ2, "$SAP_CODE$", txt_ItemItem.Text, , , vbTextCompare)
                    lv_columnNames = CVar(Array("SP_code", "SPP_desc"))
                    Call SetComboBoxTextDB(al_Cursor, "SP_code", "SPP_desc", cbo_SupSupplier)
                End If
                ls_req = Replace(ls_req, "$LANG$", ms_LanguageCode, , , vbTextCompare)
                cbo_SupSupplier.Request = ls_req
                Call cbo_SupSupplier.InitColumnNames(lv_columnNames)
            Else
                ' to proof that item was changged
                Debug.Assert (txt_ItemItem.Text <> "")
            End If
        Else
            If lb_clearControls Then
                Call cbo_SupSupplier.Clear
            End If
        End If

        Call SetTextBoxTextDB(al_Cursor, "CPL_Batch1", txt_SupBatchNumber1, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CPL_Batch2", txt_SupBatchNumber2, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CPL_Batch3", txt_SupBatchNumber3, lb_clearControls)
        Call SetTextBoxTextDB(al_Cursor, "CPL_Batch4", txt_SupBatchNumber4, lb_clearControls)
                
        Call SetCalendarTextDB(al_Cursor, "CLA_Plant_Date", cal_SupPlantCloseDate, lb_clearControls)

        Call mo_Db.Next(al_Cursor)
    Loop Until mo_Db.EOF(al_Cursor)
    
    If al_Cursor <> -1 Then
        grd_linkedFiles.Requests = "EXEC Claim_LinkedFiles_lst " & txt_GenReport.Text
    Else
        grd_linkedFiles.Requests = ""
    End If
    
    mb_Initializing = False

    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_LoadValues")
End Sub

' clear all controls values
Private Sub Item_Clear()
On Error GoTo ErrHandler
    mb_Initializing = True
    ClearForm UserControl.Controls, GetControl(fra_frames, "fra_detail")
    cbo_SupSupplier.Request = ""
    mb_Initializing = False
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_Clear")
End Sub

' clear all controls values
Private Sub Item_ClearTab(ByVal as_TabKey As String)
On Error GoTo ErrHandler
    Dim ll_detTabIndex As Long
    mb_Initializing = True
    ll_detTabIndex = CLng(Mid(as_TabKey, 2))
    Call ClearForm(UserControl.Controls, fra_detailFrames(ll_detTabIndex), Array(txt_GenReport))
    
    ' additional clearing code dependent of clearing tab
    Select Case as_TabKey
    Case "_4"           ' item tab
Const C_REQ1 As String = "EXEC Base_Item_Plants_cbo '$SAP_CODE$', '$LANG$'"
Const C_REQ2 As String = "EXEC Base_Item_Suppliers_cbo '$SAP_CODE$', '$LANG$'"
        Debug.Assert (ml_DetailCursor(4) <> 0)
        If ml_DetailCursor(5) > 0 Then
            ' load combo
            Dim ls_req As String
            Dim lv_columnNames As Variant
            If mo_Db.GetFields(ml_DetailCursor(5), "MFGP_code") <> "" Then
                ls_req = Replace(C_REQ1, "$SAP_CODE$", mo_Db.GetFields(ml_DetailCursor(4), "BI_SAP_code"), , , vbTextCompare)
                Call SetComboBoxTextDB(ml_DetailCursor(5), "MFGP_code", "MFGP_name", cbo_SupSupplier)
                lv_columnNames = CVar(Array("MFGP_code", "MFGP_name"))
            Else
                ls_req = Replace(C_REQ2, "$SAP_CODE$", mo_Db.GetFields(ml_DetailCursor(4), "BI_SAP_code"), , , vbTextCompare)
                Call SetComboBoxTextDB(ml_DetailCursor(5), "SP_code", "SPP_desc", cbo_SupSupplier)
                lv_columnNames = CVar(Array("SP_code", "SPP_desc"))
            End If
            ls_req = Replace(ls_req, "$LANG$", ms_LanguageCode, , , vbTextCompare)
            cbo_SupSupplier.Request = ls_req
            Call cbo_SupSupplier.InitColumnNames(lv_columnNames)
        Else
            Call cbo_SupSupplier.Clear
            cbo_SupSupplier.Request = ""
        End If
        
    Case "_5"           ' plant tab
        Debug.Assert (ml_DetailCursor(5) <> 0)
        ' clear supplier combobox only if item was not changed
        If txt_ItemItem.Text = mo_Db.GetFields(ml_DetailCursor(5), "BI_SAP_codeOld") Then
            cbo_SupSupplier.Request = ""    ' this will make Item_LoadValues to reload combobox
        End If
    End Select
    
    mb_Initializing = False
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_ClearTab")
End Sub

' select nonselected tab on tabstrip
Private Sub SelectTab(ByRef ao_TabStrip As MSComctlLib.TabStrip, ByVal as_TabKey As String, Optional ab_lockEventClick As Boolean = False)
On Error GoTo ErrHandler
    If Not ao_TabStrip.Tabs(as_TabKey).Selected Then
        ab_lockEventClick = ab_lockEventClick And Not mb_Initializing
        If ab_lockEventClick Then mb_Initializing = True
        
        ao_TabStrip.Tabs(as_TabKey).Selected = True     ' raise event Click
        
        If ab_lockEventClick Then mb_Initializing = False
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("SelectTab")
End Sub

Private Function GetFirstCredit() As Boolean
On Error GoTo ErrHandler
    If ml_DetailCursor(1) > 0 Then
        ' cost tab is viewed
        GetFirstCredit = (grd_CostNotes.Rows = 0)
    Else
        If ml_DetailCursor(0) > 0 Then
            GetFirstCredit = (mo_Db.GetFields(ml_DetailCursor(0), "FIRSTCREDIT") = 0)
        Else
            ' default
            GetFirstCredit = False
        End If
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("GetFirstCredit")
End Function
' function check if there is status set on the screen
' if not set then select "CLA_status" from any opened ml_detailCursor - if not found return "NULL"
Private Function GenGetStatus() As String
On Error GoTo ErrHandler
    Dim ls_ret As String
    ls_ret = GetOptionButtonCode(opt_GenStatus)
    If ls_ret = "NULL" Then
        Dim lv_auxVal As Variant
        Dim ll_Index As Long
        For ll_Index = LBound(ml_DetailCursor) To UBound(ml_DetailCursor)
            If ml_DetailCursor(ll_Index) > 0 Then
                lv_auxVal = mo_Db.GetFields(ml_DetailCursor(ll_Index), "CLA_statusOld")
                If Not IsEmpty(lv_auxVal) Then
                    ' status found
                    ls_ret = CStr(lv_auxVal)
                    Exit For
                End If
            End If
        Next
    End If
    GenGetStatus = ls_ret
    Exit Function
ErrHandler:
    Call ErrorHandler("GenGetStatus")
End Function

' same for cal_GenFinishDate as GenGetStatus
Private Function GetGenFinalizedDate() As Date
On Error GoTo ErrHandler
    Dim ld_ret As Date
    ld_ret = cal_GenFinishDate.date_dt()
    If ld_ret = 0 Then
        Dim lv_auxVal As Variant
        Dim ll_Index As Long
        For ll_Index = LBound(ml_DetailCursor) To UBound(ml_DetailCursor)
            If ml_DetailCursor(ll_Index) > 0 Then
                lv_auxVal = mo_Db.GetFields(ml_DetailCursor(ll_Index), "CLA_final_dateOld")
                If Not IsEmpty(lv_auxVal) Then
                    ' date found
                    ld_ret = CDate(lv_auxVal)
                    Exit For
                End If
            End If
        Next
    End If
    GetGenFinalizedDate = ld_ret
    Exit Function
ErrHandler:
    Call ErrorHandler("GetGenFinalizedDate")
End Function

' same for cal_GenFinishDate as GenGetStatus
Private Function GetItemSAPCode() As String
On Error GoTo ErrHandler
    Dim ls_ret As String
    ls_ret = txt_ItemItem.Text
    If ls_ret = "" Then
        Dim lv_auxVal As Variant
        Dim ll_Index As Long
        For ll_Index = LBound(ml_DetailCursor) To UBound(ml_DetailCursor)
            If ml_DetailCursor(ll_Index) > 0 Then
                lv_auxVal = mo_Db.GetFields(ml_DetailCursor(ll_Index), "BI_SAP_codeOld")
                If Not IsEmpty(lv_auxVal) Then
                    ' SAP_code found
                    ls_ret = CStr(lv_auxVal)
                    Exit For
                End If
            End If
        Next
    End If
    GetItemSAPCode = ls_ret
    Exit Function
ErrHandler:
    Call ErrorHandler("GetItemSAPCode")
End Function

' set mandatory fields and disable non editable fields according to actual data on the form
' to speed up process - general mandatory fields are set in InitComponents
Private Sub Item_ApplyLogic(ByVal au_mode As ArmScreenMode)
On Error GoTo ErrHandler

    GetControl(lbl_Label, "lbl_ProjectInstDate").FontBold = (Not cbo_ItemGridManufac.SelectedItem Is Nothing) Or (Not cbo_ItemGridType.SelectedItem Is Nothing)
    GetControl(lbl_Label, "lbl_GridManuf").FontBold = (cal_ItemInstalationDate.date_dt <> 0)
    GetControl(lbl_Label, "lbl_GridType").FontBold = (cal_ItemInstalationDate.date_dt <> 0)
    GetControl(lbl_Label, "lbl_VisitDate").FontBold = (txt_ItemVisitedBy.Text <> "")
    GetControl(lbl_Label, "lbl_ByWhom").FontBold = (cal_ItemVisitDate.date_dt <> 0)
    GetControl(GetContainedControlsChain(cbo_ProUnitMeasure.Container), "lbl_ProjectSizeMU").FontBold = (ToDouble(txt_ProSize.Text) > 0) Or (Not GetOptionButtonCode(opt_ProSiteCondition) = "NULL")
    GetControl(lbl_Label, "lbl_ProjectSize").FontBold = (Not cbo_ProUnitMeasure.SelectedItem Is Nothing) Or (Not GetOptionButtonCode(opt_ProSiteCondition) = "NULL")
    fra_ProSiteCondition.FontBold = (Not cbo_ProUnitMeasure.SelectedItem Is Nothing) Or ToDouble(txt_ProSize.Text) > 0
    
    ' based on general status - settled
    Dim ls_actStatus As String, ls_whoRaised As String
    Dim lo_ctrl As Control
    Dim lo_fraControls As Collection
    ls_actStatus = GenGetStatus()
    ls_whoRaised = GetOptionButtonCode(opt_CusWhoRaised)
    
    ' based on general status - finalized
    GetControl(lbl_Label, "lbl_Reason1").FontBold = (ls_actStatus = "F")
    GetControl(lbl_Label, "lbl_Action").FontBold = (ls_actStatus = "F")
    ' HARDCODED !!!!!!! lbl_Currency for cbo_costCurrency
    lbl_Label(19).FontBold = ((ls_actStatus = "F") Or ((ls_actStatus = "S")))
    Debug.Assert (lbl_Label(19).Tag = "lbl_Currency")
    GetControl(GetContainedControlsChain(txt_CostEstTotalCost.Container), "lbl_EstTotCost").FontBold = (ls_actStatus = "F")
    fra_CusWhoRaised.FontBold = (ls_actStatus = "F")
    
    GetControl(GetContainedControlsChain(fra_CustTabs(CLng(Mid(tbs_CustTabs.Tabs(1).Key, 2)))), "lbl_DistName").FontBold = (ls_actStatus = "F") And (ls_whoRaised = "D")
    GetControl(GetContainedControlsChain(fra_CustTabs(CLng(Mid(tbs_CustTabs.Tabs(2).Key, 2)))), "lbl_DistName").FontBold = (ls_actStatus = "F") And (ls_whoRaised = "S")
    GetControl(GetContainedControlsChain(fra_CustTabs(CLng(Mid(tbs_CustTabs.Tabs(3).Key, 2)))), "lbl_DistName").FontBold = (ls_actStatus = "F") And (ls_whoRaised = "C")
    
    GetControl(GetContainedControlsChain(fra_ProAddress), "lbl_DistName").FontBold = (ls_actStatus = "F")
    GetControl(lbl_Label, "lbl_ClaimSize").FontBold = (ls_actStatus = "F")
    ' HARDCODED !!!!!!! lbl_ProjectSizeMU for cbo_ItemUnitMeasureCS
    lbl_Label(37).FontBold = (ls_actStatus = "F")
    Debug.Assert (lbl_Label(37).Tag = "lbl_ProjectSizeMU")
    GetControl(lbl_Label, "lbl_TotalDelivery").FontBold = (ls_actStatus = "F")
    ' HARDCODED !!!!!!! lbl_ProjectSizeMU for cbo_ItemUnitMeasureTD
    lbl_Label(39).FontBold = (ls_actStatus = "F")
    Debug.Assert (lbl_Label(39).Tag = "lbl_ProjectSizeMU")
    GetControl(lbl_Label, "lbl_ProjectDelay").FontBold = (ls_actStatus = "F")
    GetControl(lbl_Label, "lbl_SentTo").FontBold = (ls_actStatus = "F") And GetOptionButtonCode(opt_ItemSampleSent) = "Y"
    GetControl(lbl_Label, "lbl_Batch").FontBold = (ls_actStatus = "F")
        
    ' SETTLED
    GetControl(lbl_Label, "cbo_GenOutcome").FontBold = (ls_actStatus = "S")
    GetControl(lbl_Label, "cbo_GenOutcomeAction").FontBold = (ls_actStatus = "S")
    GetControl(GetContainedControlsChain(txt_CostSetTotalCost.Container), "lbl_EstTotCost").FontBold = (ls_actStatus = "S")
    fra_CostSettlementCost.Visible = (ls_actStatus = "S")

    'enable controls
    GetControl(lbl_Label, "cbo_GenOutcome").Visible = (ls_actStatus <> "I")
    cbo_GenOutcome.Visible = (ls_actStatus <> "I")
    GetControl(lbl_Label, "cbo_GenOutcomeAction").Visible = (ls_actStatus <> "I")
    cbo_GenOutcomeAction.Visible = (ls_actStatus <> "I")
    
    If (au_mode = smAdd Or au_mode = smUpdate) Then
        Call SetEnabledCtrl(cbo_GenCoordinator, (ls_actStatus = "I") And (au_mode = smAdd))
        Call SetEnabledCtrl(cbo_GenSalesOffice, (ls_actStatus = "I") And (au_mode = smAdd) And (Not cbo_GenCoordinator.SelectedItem Is Nothing))
        Call SetEnabledCtrl(cbo_GenSalesMarket, (ls_actStatus = "I") And (au_mode = smAdd) And (Not cbo_GenSalesOffice.SelectedItem Is Nothing))
        Call SetEnabledCtrl(cbo_GenRespSalesRep, Not cbo_GenSalesOffice.SelectedItem Is Nothing)
        Call SetEnabledCtrl(cbo_GenCountry, Not cbo_GenSalesMarket.SelectedItem Is Nothing)
        Call SetEnabledCtrl(cbo_GenTerritory, Not cbo_GenCountry.SelectedItem Is Nothing)
        
        Call SetEnabledCtrl(cbo_GenAction, Not (ls_actStatus = "S"))
        Call SetEnabledCtrl(cbo_GenOutcomeAction, Not cbo_GenOutcome.SelectedItem Is Nothing)
        Call SetEnabledCtrl(txt_ItemVisitedBy, cal_ItemVisitDate.date_dt <> 0)
        Call SetEnabledCtrl(txt_ItemSampleSentTo, GetOptionButtonCode(opt_ItemSampleSent) = "Y")
        Call SetEnabledCtrl(txt_ItemSampleReasonNo, GetOptionButtonCode(opt_ItemSampleSent) = "N")
        ' initialize control
        If au_mode = smUpdate Then
            Debug.Assert (grd_ClaimMain.SelectedCount = 1)
            Select Case grd_ClaimMain.SelectedKey(0)(2)
                Case "I"
                    Call SetEnabledCtrl(opt_GenStatus(2), False)
                    Call SetEnabledCtrl(opt_GenStatus(3), False)
                Case "F"
                    Call SetEnabledCtrl(opt_GenStatus(0), False)
                Case "R"
                    Call SetEnabledCtrl(opt_GenStatus(0), False)
                    Call SetEnabledCtrl(opt_GenStatus(3), False)
                Case "S"
                    Call SetEnabledCtrl(opt_GenStatus(0), False)
                    Call SetEnabledCtrl(opt_GenStatus(1), GetFirstCredit())
                    Call SetEnabledCtrl(opt_GenStatus(2), False)
            End Select
        End If
        
        Call SetEnabledCtrl(btn_costMoveEst, ls_actStatus = "S")
        btn_costMoveEst.Visible = (ls_actStatus = "S")

    End If
    

    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_ApplyLogic")
End Sub
Private Function Item_Check(ByVal ao_Container As Object) As ErrMsg
On Error GoTo ErrHandler
    
    Dim lo_auxTabStrip As MSComctlLib.TabStrip
    
    For Each lo_auxTabStrip In tbs_ClaimTabs
        If lo_auxTabStrip.Visible Then Exit For
    Next
    Debug.Assert (lo_auxTabStrip.Visible)
    
    If HasContainer(cal_GenReportDate, ao_Container) And cal_GenReportDate.date_dt = 0 Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_0")
        Call SetFocusToCtrl(cal_GenReportDate)
        Exit Function
    End If
    
    If HasContainer(opt_GenStatus(0), ao_Container) And GetOptionButtonCode(opt_GenStatus) = "NULL" Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_0")
        Call SetFocusToCtrl(opt_GenStatus(0))
        opt_GenStatus(0).Value = False
        Exit Function
    End If
    
    If HasContainer(cbo_GenCoordinator, ao_Container) And SQLComboBoxValue(cbo_GenCoordinator) = "NULL" Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_0")
        Call SetFocusToCtrl(cbo_GenCoordinator)
        Exit Function
    End If
    
    If HasContainer(cbo_GenSalesOffice, ao_Container) And SQLComboBoxValue(cbo_GenSalesOffice) = "NULL" Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_0")
        Call SetFocusToCtrl(cbo_GenSalesOffice)
        Exit Function
    End If
    
    If HasContainer(cbo_GenSalesMarket, ao_Container) And SQLComboBoxValue(cbo_GenSalesMarket) = "NULL" Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_0")
        Call SetFocusToCtrl(cbo_GenSalesMarket)
        Exit Function
    End If
    
    If HasContainer(cbo_GenCountry, ao_Container) And SQLComboBoxValue(cbo_GenCountry) = "NULL" Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_0")
        Call SetFocusToCtrl(cbo_GenCountry)
        Exit Function
    End If
        
    If HasContainer(cbo_GenTerritory, ao_Container) And SQLComboBoxValue(cbo_GenTerritory) = "NULL" Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_0")
        Call SetFocusToCtrl(cbo_GenTerritory)
        Exit Function
    End If
    
    If HasContainer(cbo_GenRespSalesRep, ao_Container) And SQLComboBoxValue(cbo_GenRespSalesRep) = "NULL" Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_0")
        Call SetFocusToCtrl(cbo_GenRespSalesRep)
        Exit Function
    End If
    
    ' item all modes
    
    If HasContainer(txt_ItemItem, ao_Container) And txt_ItemItem.Text = "" Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_4")
        Call SetFocusToCtrl(txt_ItemItem)
        Exit Function
    End If
        
    If HasContainer(cal_ItemInstalationDate, ao_Container) And cal_ItemInstalationDate.date_dt = 0 And IsComboboxSelected(cbo_ItemGridManufac) Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_4")
        Call SetFocusToCtrl(cal_ItemInstalationDate)
        Exit Function
    End If
    
    If HasContainer(cal_ItemInstalationDate, ao_Container) And cal_ItemInstalationDate.date_dt <> 0 And Not IsComboboxSelected(cbo_ItemGridManufac) Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_4")
        Call SetFocusToCtrl(cbo_ItemGridManufac)
        Exit Function
    End If
 
    If HasContainer(cal_ItemInstalationDate, ao_Container) And cal_ItemInstalationDate.date_dt = 0 And IsComboboxSelected(cbo_ItemGridType) Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_4")
        Call SetFocusToCtrl(cal_ItemInstalationDate)
        Exit Function
    End If
    
    If HasContainer(cal_ItemInstalationDate, ao_Container) And cal_ItemInstalationDate.date_dt <> 0 And Not IsComboboxSelected(cbo_ItemGridType) Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_4")
        Call SetFocusToCtrl(cbo_ItemGridType)
        Exit Function
    End If
    
    If HasContainer(cal_ItemVisitDate, ao_Container) And cal_ItemVisitDate.date_dt = 0 And txt_ItemVisitedBy.Text <> "" Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_4")
        Call SetFocusToCtrl(cal_ItemVisitDate)
        Exit Function
    End If
    
    If HasContainer(cal_ItemVisitDate, ao_Container) And cal_ItemVisitDate.date_dt <> 0 And txt_ItemVisitedBy.Text = "" Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_4")
        Call SetFocusToCtrl(txt_ItemVisitedBy)
        Exit Function
    End If
    
    ' plant all modes
    
    If HasContainer(cbo_SupSupplier, ao_Container) And SQLComboBoxValue(cbo_SupSupplier) = "NULL" Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_5")
        Call SetFocusToCtrl(cbo_SupSupplier)
        Exit Function
    End If
    
    If HasContainer(txt_ProSize, ao_Container) And txt_ProSize.Text = "" Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_3")
        Call SetFocusToCtrl(txt_ProSize)
        Exit Function
    End If
    
    If HasContainer(txt_ProSize, ao_Container) And Not IsNumericArm(txt_ProSize.Text) Then
        Item_Check = ErrMsgNumericRequired
        Call SelectTab(lo_auxTabStrip, "_3")
        Call SetFocusToCtrl(txt_ProSize)
        Exit Function
    End If

    If HasContainer(txt_ProSize, ao_Container) And ToDouble(txt_ProSize.Text) < 0 Then
        Item_Check = ErrMsgBadValue
        Call SelectTab(lo_auxTabStrip, "_3")
        Call SetFocusToCtrl(txt_ProSize)
        Exit Function
    End If

    If HasContainer(cbo_ProUnitMeasure, ao_Container) And Not IsComboboxSelected(cbo_ProUnitMeasure) And ToDouble(txt_ProSize.Text) > 0 Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_3")
        Call SetFocusToCtrl(cbo_ProUnitMeasure)
        Exit Function
    End If
    
    If HasContainer(cbo_ProUnitMeasure, ao_Container) And IsComboboxSelected(cbo_ProUnitMeasure) And ToDouble(txt_ProSize.Text) <= 0 Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_3")
        Call SetFocusToCtrl(txt_ProSize)
        Exit Function
    End If
    
    If HasContainer(opt_ProSiteCondition(0), ao_Container) And GetOptionButtonCode(opt_ProSiteCondition) = "NULL" And ToDouble(txt_ProSize.Text) > 0 Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_3")
        Call SetFocusToCtrl(opt_ProSiteCondition(0))
        opt_ProSiteCondition(0).Value = False
        Exit Function
    End If
    
    If HasContainer(opt_ProSiteCondition(0), ao_Container) And Not GetOptionButtonCode(opt_ProSiteCondition) = "NULL" And ToDouble(txt_ProSize.Text) <= 0 Then
        Item_Check = ErrMsgMandatoryAreEmpty
        Call SelectTab(lo_auxTabStrip, "_3")
        Call SetFocusToCtrl(cbo_ProUnitMeasure)
        Exit Function
    End If
    
    If HasContainer(txt_CostEstLaborCost, ao_Container) And Not IsNumericArm(txt_CostEstLaborCost.Text) And txt_CostEstLaborCost.Text <> "" Then
        Item_Check = ErrMsgNumericRequired
        Call SelectTab(lo_auxTabStrip, "_1")
        Call SetFocusToCtrl(txt_CostEstLaborCost)
        Exit Function
    End If
    If HasContainer(txt_CostEstMaterialCost, ao_Container) And Not IsNumericArm(txt_CostEstMaterialCost.Text) And txt_CostEstMaterialCost.Text <> "" Then
        Item_Check = ErrMsgNumericRequired
        Call SelectTab(lo_auxTabStrip, "_1")
        Call SetFocusToCtrl(txt_CostEstMaterialCost)
        Exit Function
    End If
    If HasContainer(txt_CostEstOtherCost, ao_Container) And Not IsNumericArm(txt_CostEstOtherCost.Text) And txt_CostEstOtherCost.Text <> "" Then
        Item_Check = ErrMsgNumericRequired
        Call SelectTab(lo_auxTabStrip, "_1")
        Call SetFocusToCtrl(txt_CostEstOtherCost)
        Exit Function
    End If
    
    If HasContainer(txt_CostSetLaborCost, ao_Container) And Not IsNumericArm(txt_CostSetLaborCost.Text) And txt_CostSetLaborCost.Text <> "" Then
        Item_Check = ErrMsgNumericRequired
        Call SelectTab(lo_auxTabStrip, "_1")
        Call SetFocusToCtrl(txt_CostSetLaborCost)
        Exit Function
    End If
    If HasContainer(txt_CostSetMaterialCost, ao_Container) And Not IsNumericArm(txt_CostSetMaterialCost.Text) And txt_CostSetMaterialCost.Text <> "" Then
        Item_Check = ErrMsgNumericRequired
        Call SelectTab(lo_auxTabStrip, "_1")
        Call SetFocusToCtrl(txt_CostSetMaterialCost)
        Exit Function
    End If
    If HasContainer(txt_CostSetOtherCost, ao_Container) And Not IsNumericArm(txt_CostSetOtherCost.Text) And txt_CostSetOtherCost.Text <> "" Then
        Item_Check = ErrMsgNumericRequired
        Call SelectTab(lo_auxTabStrip, "_1")
        Call SetFocusToCtrl(txt_CostSetOtherCost)
        Exit Function
    End If
    
    ' based on general status - settled
    Select Case GenGetStatus()
    Case "I"
    Case "F"
        ' based on general status - finalized
        If HasContainer(cbo_GenMainReason1, ao_Container) And SQLComboBoxValue(cbo_GenMainReason1) = "NULL" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_0")
            Call SetFocusToCtrl(cbo_GenMainReason1)
            Exit Function
        End If
        
        If HasContainer(cbo_GenMainReason2, ao_Container) And SQLComboBoxValue(cbo_GenMainReason2) = "NULL" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_0")
            Call SetFocusToCtrl(cbo_GenMainReason2)
            Exit Function
        End If
        
        If HasContainer(cbo_GenAction, ao_Container) And SQLComboBoxValue(cbo_GenAction) = "NULL" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_0")
            Call SetFocusToCtrl(cbo_GenAction)
            Exit Function
        End If

        If HasContainer(cbo_CostCurrency, ao_Container) And SQLComboBoxValue(cbo_CostCurrency) = "NULL" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_1")
            Call SetFocusToCtrl(cbo_CostCurrency)
            Exit Function
        End If
        
        If HasContainer(txt_CostEstTotalCost, ao_Container) And txt_CostEstTotalCost.Text = "" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_1")
            Call SetFocusToCtrl(txt_CostEstTotalCost)
            Exit Function
        End If
    
        If HasContainer(txt_CostEstTotalCost, ao_Container) And Not IsNumericArm(txt_CostEstTotalCost.Text) Then
            Item_Check = ErrMsgNumericRequired
            Call SelectTab(lo_auxTabStrip, "_1")
            Call SetFocusToCtrl(txt_CostEstTotalCost)
            Exit Function
        End If
        
        
        If HasContainer(txt_CostEstTotalCost, ao_Container) And ToDouble(txt_CostEstTotalCost.Text) = 0 Then
            Item_Check = ErrMsgBadValue
            Call SelectTab(lo_auxTabStrip, "_1")
            Call SetFocusToCtrl(txt_CostEstTotalCost)
            Exit Function
        End If

        Select Case GetOptionButtonCode(opt_CusWhoRaised)
            Case "NULL"
                If HasContainer(opt_CusWhoRaised(0), ao_Container) Then
                    Item_Check = ErrMsgMandatoryAreEmpty
                    Call SelectTab(lo_auxTabStrip, "_2")
                    Call SetFocusToCtrl(opt_CusWhoRaised(0))
                    opt_CusWhoRaised(0).Value = False
                    Exit Function
                End If
            Case "D"
                If HasContainer(cmd_SelectCust(0), ao_Container) And cmd_SelectCust(0).Tag = "0" Then
                    Item_Check = ErrMsgMandatoryAreEmpty
                    Call SelectTab(lo_auxTabStrip, "_2")
                    SelectTab tbs_CustTabs, "_0"
                    Call SetFocusToCtrl(txt_CustDisName)
                    Exit Function
                End If
            Case "S"
                If HasContainer(cmd_SelectCust(1), ao_Container) And cmd_SelectCust(1).Tag = "0" Then
                    Item_Check = ErrMsgMandatoryAreEmpty
                    Call SelectTab(lo_auxTabStrip, "_2")
                    SelectTab tbs_CustTabs, "_1"
                    Call SetFocusToCtrl(txt_CustSpeName)
                    Exit Function
                End If
            Case "C"
                If HasContainer(cmd_SelectCust(2), ao_Container) And cmd_SelectCust(2).Tag = "0" Then
                    Item_Check = ErrMsgMandatoryAreEmpty
                    Call SelectTab(lo_auxTabStrip, "_2")
                    SelectTab tbs_CustTabs, "_2"
                    Call SetFocusToCtrl(txt_CustConName)
                    Exit Function
                End If
        End Select
        
        If HasContainer(cmd_SelectProj, ao_Container) And cmd_SelectProj.Tag = "0" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_3")
            Call SetFocusToCtrl(txt_ProName)
            Exit Function
        End If

        If HasContainer(txt_ItemClaimSize, ao_Container) And txt_ItemClaimSize.Text = "" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_4")
            Call SetFocusToCtrl(txt_ItemClaimSize)
            Exit Function
        End If
        
        If HasContainer(txt_ItemClaimSize, ao_Container) And ToDouble(txt_ItemClaimSize.Text) < 0.001 Then
            Item_Check = ErrMsgBadValue
            Call SelectTab(lo_auxTabStrip, "_4")
            Call SetFocusToCtrl(txt_ItemClaimSize)
            Exit Function
        End If
        
        If HasContainer(cbo_ItemUnitMeasureCS, ao_Container) And SQLComboBoxValue(cbo_ItemUnitMeasureCS) = "NULL" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_4")
            Call SetFocusToCtrl(cbo_ItemUnitMeasureCS)
            Exit Function
        End If
        
        If HasContainer(txt_ItemTotalDelivery, ao_Container) And txt_ItemTotalDelivery.Text = "" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_4")
            Call SetFocusToCtrl(txt_ItemTotalDelivery)
            Exit Function
        End If
        
        If HasContainer(txt_ItemTotalDelivery, ao_Container) And ToDouble(txt_ItemTotalDelivery.Text) < 0.001 Then
            Item_Check = ErrMsgBadValue
            Call SelectTab(lo_auxTabStrip, "_4")
            Call SetFocusToCtrl(txt_ItemTotalDelivery)
            Exit Function
        End If
    
        If HasContainer(cbo_ItemUnitMeasureTD, ao_Container) And SQLComboBoxValue(cbo_ItemUnitMeasureTD) = "NULL" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_4")
            Call SetFocusToCtrl(cbo_ItemUnitMeasureTD)
            Exit Function
        End If
        
        If HasContainer(opt_ItemProjectDelay(0), ao_Container) And GetOptionButtonCode(opt_ItemProjectDelay) = "NULL" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_4")
            Call SetFocusToCtrl(opt_ItemProjectDelay(0))
            opt_ItemProjectDelay(0).Value = False
            Exit Function
        End If
        
        If HasContainer(opt_ItemSampleSent(0), ao_Container) And GetOptionButtonCode(opt_ItemSampleSent) = "Y" And txt_ItemSampleSentTo.Text = "" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_4")
            Call SetFocusToCtrl(txt_ItemSampleSentTo)
            Exit Function
        End If
        
        
        If HasContainer(txt_SupBatchNumber1, ao_Container) And txt_SupBatchNumber1.Text = "" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_5")
            Call SetFocusToCtrl(txt_SupBatchNumber1)
            Exit Function
        End If
    Case "R"
    Case "S"
        If HasContainer(cbo_GenOutcome, ao_Container) And SQLComboBoxValue(cbo_GenOutcome) = "NULL" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_0")
            Call SetFocusToCtrl(cbo_GenOutcome)
            Exit Function
        End If
        If HasContainer(cbo_GenOutcomeAction, ao_Container) And SQLComboBoxValue(cbo_GenOutcomeAction) = "NULL" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_0")
            Call SetFocusToCtrl(cbo_GenOutcomeAction)
            Exit Function
        End If
'    If GetOptionButtonCode(opt_GenStatus) = "S" Then 'And mu_ActiveMode <> smUpdate Then
            
        If HasContainer(txt_CostSetTotalCost, ao_Container) And txt_CostSetTotalCost.Text = "" Then
            Item_Check = ErrMsgMandatoryAreEmpty
            Call SelectTab(lo_auxTabStrip, "_1")
            Call SetFocusToCtrl(txt_CostSetTotalCost)
            Exit Function
        End If
    
        If HasContainer(txt_CostSetTotalCost, ao_Container) And Not IsNumericArm(txt_CostSetTotalCost.Text) Then
            Item_Check = ErrMsgNumericRequired
            Call SelectTab(lo_auxTabStrip, "_1")
            Call SetFocusToCtrl(txt_CostSetTotalCost)
            Exit Function
        End If
        
        If HasContainer(txt_CostSetTotalCost, ao_Container) And ToDouble(txt_CostSetTotalCost.Text) = 0 Then
            Item_Check = ErrMsgBadValue
            Call SelectTab(lo_auxTabStrip, "_1")
            Call SetFocusToCtrl(txt_CostSetTotalCost)
            Exit Function
        End If
    
        If HasContainer(cbo_CostCurrency, ao_Container) Then
        
            If cbo_CostCurrency.SelectedItem Is Nothing Then
                Item_Check = ErrMsgMandatoryAreEmpty
                Call SelectTab(lo_auxTabStrip, "_1")
                Call SetFocusToCtrl(cbo_CostCurrency)
                Exit Function
            End If
            
            Dim ls_CurrencCode As String
            Dim ld_Amount As Double
            Dim ld_ExchRate As Double
            
            ls_CurrencCode = cbo_CostCurrency.SelectedItem.Key
        
            If UCase(ls_CurrencCode) <> "EUR" Then
                If Not GetEuroConverion(ls_CurrencCode, GetGenFinalizedDate(), ld_ExchRate) Then
                    Item_Check = ErrMsgNoValidRateExists
                    Call SelectTab(lo_auxTabStrip, "_1")
                    Call SetFocusToCtrl(cbo_CostCurrency)
                    Exit Function
                End If
                Debug.Assert (HasContainer(txt_CostSetTotalCost, ao_Container))
                ld_Amount = ToDouble(txt_CostSetTotalCost.Text) / ld_ExchRate
            Else
                ld_Amount = ToDouble(txt_CostSetTotalCost.Text)
            End If
            
            Debug.Assert (GetItemSAPCode() <> "")
            If ld_Amount > GetMaxSettlement(GetItemSAPCode()) Then
                Item_Check = ErrMsgTotalClaimsTooLarge
                Call SelectTab(lo_auxTabStrip, "_1")
                Call SetFocusToCtrl(txt_CostSetTotalCost)
                Exit Function
            End If
        End If
    
    Case Else
        Debug.Assert (False)
    End Select
    
    If HasContainer(cbo_GenMainReason1, ao_Container) And IsComboboxSelected(cbo_GenMainReason1) And SQLComboBoxValue(cbo_GenMainReason2) = "NULL" Then
        Item_Check = ErrMsgMandatoryByFilter
        Call SelectTab(lo_auxTabStrip, "_0")
        Call SetFocusToCtrl(cbo_GenMainReason2)
        Exit Function
    End If
    If HasContainer(cbo_Gen2ndReason1, ao_Container) And IsComboboxSelected(cbo_Gen2ndReason1) And SQLComboBoxValue(cbo_Gen2ndReason2) = "NULL" Then
        Item_Check = ErrMsgMandatoryByFilter
        Call SelectTab(lo_auxTabStrip, "_0")
        Call SetFocusToCtrl(cbo_Gen2ndReason2)
        Exit Function
    End If
    
    Item_Check = ErrMsgNone

    Exit Function
ErrHandler:
    Call ErrorHandler("Item_Check")
End Function

Private Function IsComboboxSelected(ByRef as_combo As ArmCombobox) As Boolean
On Error GoTo ErrHandler
    IsComboboxSelected = False
    If Not as_combo.SelectedItem Is Nothing Then
        If Not IsEmpty(as_combo.SelectedItem.Key) Then
            IsComboboxSelected = True
        End If
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("IsComboboxSelected")
End Function

' retrieve max settlement value
Private Function GetMaxSettlement(ByVal as_ItemCode As String) As Long
Const C_REQ As String = "EXEC Clm_Claim_SettlementControl_Sel '$ItemCode$', '$LOGINNAME$'"
On Error GoTo ErrHandler
    
    Dim ls_SQL As String
    Dim lc_Cursor As Long
    
    ls_SQL = Replace(C_REQ, "$ItemCode$", SqlStr(as_ItemCode), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
    
    lc_Cursor = OpenSQLSafe(mo_Db, ls_SQL)
    If mo_Db.RowCount(lc_Cursor) > 0 Then
        GetMaxSettlement = mo_Db.GetFields(lc_Cursor, "Max_Settlement")
    Else
        GetMaxSettlement = 0
    End If
    
    Call mo_Db.Close(lc_Cursor)
    lc_Cursor = 0
    Exit Function
ErrHandler:
    If lc_Cursor <> 0 Then
        mo_Db.Close lc_Cursor
        lc_Cursor = 0
    End If
    Call ErrorHandler("GetMaxSettlement")
End Function

' retrieve if euro conversion is available
Private Function GetEuroConverion(ByVal as_CurrencCode As String, ByVal ao_FinallizeDate As Date, ByRef ad_ExchRate As Double) As Boolean
Const C_REQ As String = "EXEC euro_rate '$CurrencCode$', $FinallizeDate$"
On Error GoTo ErrHandler

    Dim ls_SQL As String
    Dim lc_Cursor As Long

    GetEuroConverion = False
    
    ls_SQL = Replace(C_REQ, "$CurrencCode$", SqlStr(as_CurrencCode), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$FinallizeDate$", SQLDateTime(ao_FinallizeDate), , , vbTextCompare)
    
    lc_Cursor = OpenSQLSafe(mo_Db, ls_SQL, ArmSQLExactOne)
    
    ad_ExchRate = mo_Db.GetFields(lc_Cursor, "exch_rate")
    
    Call mo_Db.Close(lc_Cursor)
    lc_Cursor = 0
    
    If ad_ExchRate <> 0 Then
        GetEuroConverion = True
    End If
    
    Exit Function
ErrHandler:
    If lc_Cursor <> 0 Then
        mo_Db.Close lc_Cursor
        lc_Cursor = 0
    End If
    Call ErrorHandler("GetEuroConverion")
End Function

Private Function HasContainer(ByRef aControl As Control, ByRef aContainer As Object) As Boolean
    HasContainer = False
    Dim lControl As Control
 
    Set lControl = aControl
    While Not (lControl Is Nothing)
        On Error GoTo NotFound
        If lControl.Container Is aContainer Then
            Set lControl = Nothing
            HasContainer = True
            Exit Function
        End If
        Set lControl = lControl.Container
    Wend
 
NotFound:
    Set lControl = Nothing
    HasContainer = False
End Function
 
Private Function IsSub(ByVal av_Name As Object, ByRef aav_Names As Variant)
On Error GoTo ErrHandler
    IsSub = False
    
    Dim ll_Idx As Long
    For ll_Idx = LBound(aav_Names) To UBound(aav_Names)
    
        If av_Name Is aav_Names(ll_Idx) Then
            IsSub = True
            Exit Function
        End If
    Next ll_Idx
    Exit Function
ErrHandler:
    Call ErrorHandler("IsSub")
End Function

' Clear values for each control to not initiliazed
Private Sub ClearForm(ByRef aControls As Variant, ByRef aContainer As Object, Optional ByRef aav_Except As Variant)
On Error GoTo ErrHandler
 
    'mb_internal = True
 
    Dim lIdx As Long, lCount As Long, lControl As Object
    lCount = aControls.Count - 1
    For lIdx = 0 To lCount
        Dim lb_Process As Boolean
        lb_Process = True
        Set lControl = aControls.Item(lIdx)
        If Not IsMissing(aav_Except) Then
            If IsSub(lControl, aav_Except) Then
                lb_Process = False
            End If
        End If
        If HasContainer(lControl, aContainer) And lb_Process Then
            Select Case UCase(TypeName(lControl))
                Case "TEXTBOX"
                    lControl.Text = ""
                Case "ARMCOMBOBOX"
'                    Set lControl.SelectedItem = Nothing
                    Call lControl.Clear
                Case "A_CALOCX"
                    lControl.reinit_cal
                Case "CHECKBOX"
                    lControl.Value = vbUnchecked
                Case "ARMCHECKVIEW"
                    lControl.UnCheckAll lControl.GetVisibleList
                    Dim ll_Idx As Long
                    For ll_Idx = 1 To lControl.RoleCount
                        lControl.RoleList(ll_Idx).ClearList
                    Next
                    lControl.SetVisibleList lControl.GetVisibleList
                    
                Case "FRAME", "LABEL", "TOOLBARCONTROL", "PICTUREBOX", "COMMANDBUTTON"
 
                Case "ARMGRID"
                    lControl.ClearGrid
                Case "LISTBOX"
                    lControl.ListIndex = -1
                Case "OPTIONBUTTON"
                        lControl.Value = False
                Case "TABSTRIP", "DRIVELISTBOX", "DIRLISTBOX", "FILELISTBOX", "TOOLBARCONTROL", "LINE"
 
                Case Else
                    Debug.Print "ClearForm " & UCase(TypeName(lControl))
            End Select
        End If
 
        Set lControl = Nothing
    Next
 
   ' mb_internal = False
    Exit Sub
ErrHandler:
    Call ErrorHandler("ClearForm")
End Sub

' Display an error message
' Params:
' as_LG_Code (String)
' ai_MsgCode (Integer)
' as_MsgDefault (String)
' as_MsgCxt (String = "")
' Buttons (VbMsgBoxStyle = vbOKOnly)
Private Function SendMessage(ByVal as_LG_Code As String, ByVal ai_MsgCode As Integer, ByVal as_MsgDefault As String, Optional ByVal as_MsgCxt As String = "", Optional Buttons As VbMsgBoxStyle = vbOKOnly) As VbMsgBoxResult
Dim ls_Message As String
Dim ll_Mouse As Long

    On Error GoTo Trace_Err
    
    If mo_Db Is Nothing Then
        ls_Message = as_MsgDefault
    Else
        If mo_Db.IsConnected = False Then
            ls_Message = as_MsgDefault
        Else
            ls_Message = MsgText(as_LG_Code, ai_MsgCode, as_MsgDefault)
        End If
    End If
    ls_Message = ls_Message & vbCrLf & Trim(as_MsgCxt)
    ll_Mouse = Screen.MousePointer
    Screen.MousePointer = vbArrow
    SendMessage = MsgBox(ls_Message, Buttons)
    Screen.MousePointer = ll_Mouse
Trace_End:
    Exit Function
    
Trace_Err:
    SendMessage = vbAbort
End Function

' Get error text
' Params:
' as_LG_Code (String)
' ai_MsgID (Integer)
' as_MsgDefault (String = "")
Private Function MsgText(ByVal as_LG_Code As String, ByVal ai_MsgID As Integer, Optional ByVal as_MsgDefault As String = "")
Const C_REQ As String = "SELECT Message_Text FROM Error_Message WHERE Language_Code = '$LANG$' AND MsgID = $MSGID$"
Dim ls_Msg As String, ls_Request As String

    On Error GoTo Trace_Err
   
    ls_Request = Replace(C_REQ, "$LANG$", as_LG_Code, , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$MSGID$", ai_MsgID, , , vbTextCompare)
    
    Dim lc_Msg  As Long
    lc_Msg = OpenSQLSafe(mo_Db, ls_Request, ArmSQLResultType.ArmSQLExactOne)
  
    ls_Msg = mo_Db.GetFields(lc_Msg, "MESSAGE_TEXT")
    Call mo_Db.Close(lc_Msg)
    lc_Msg = 0
    
    MsgText = IIf(Len(ls_Msg) <> 0, ls_Msg, as_MsgDefault)
    Exit Function
Trace_Err:
    If Not lc_Msg = 0 Then
        Call mo_Db.Close(lc_Msg)
    End If
    MsgText = IIf(Len(ls_Msg) <> 0, ls_Msg, as_MsgDefault)
    
End Function
' **************************** FRAMEWORK FUNCTIONS ***********************************

' ************************************************************************************
' ************************* MEMO FRAMEWORK FUNCTIONS *********************************
' ************************************************************************************
' inititialize memo
Private Sub Memo_MainInit(ByVal av_memoRequests As Variant)
On Error GoTo ErrHandler
    
    ' save to global variable
    mv_memoRequests = av_memoRequests
    
    ' clearing form
    Call ResetScreen(ArmScreenMode.smMemoMain)
    Call Memo_Clear
    
    ' loads data to grid
    Call Memo_LoadGrid(grd_ClaimMemoList, GetRequest("List", mv_memoRequests))
    
    Call UpdateUI(ArmScreenMode.smMemoMain)
    Exit Sub
ErrHandler:
    Call ErrorHandler("Memo_MainInit")
End Sub

' initialize view mode
Private Sub Memo_ViewInit(ByVal as_MemoCode As String)
On Error GoTo ErrHandler
    Call Memo_Clear
    
    ' close cursor if opened
    Call Memo_CloseCursor
    
    ' open cursor
    Call Item_LoadDB(ml_memoCursor, 0, GetRequest("Sel", mv_memoRequests), as_MemoCode)
    
    ' loading values into detail controls
    Call Memo_LoadValues(ml_memoCursor)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Memo_ViewInit")
End Sub

' initialize memo update
Private Sub Memo_UpdateInit(ByVal as_MemoCode As String)
On Error GoTo ErrHandler
    ' data were loaded from previous view mode
    If ml_memoCursor = 0 Then
        Call Memo_ViewInit(as_MemoCode)
    End If
    Debug.Assert (ml_memoCursor <> 0)
    
    Call ResetScreen(ArmScreenMode.smMemoUpdate)
    Call UpdateUI(ArmScreenMode.smMemoUpdate)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Memo_UpdateInit")
End Sub

' initialize memo add screen
Private Sub Memo_AddInit()
On Error GoTo ErrHandler
    ' data were loaded from previous view mode
    Call Memo_CloseCursor
    ml_memoCursor = -1

    ' clearing form
    Call ResetScreen(ArmScreenMode.smMemoAdd)
    Call Memo_Clear
    ' loading values into detail controls
    Call Memo_LoadValues(ml_memoCursor)
    
    ' set only available languages into combobox
    If grd_ClaimMemoList.SearchKey(True, "E") Then
        cbo_MemoLanguage.Request = Replace(GetRequest("Lng", mv_memoRequests), "$Code$", "", , , vbTextCompare)
        txt_MemoCommentEng.Text = grd_ClaimMemoList.SelectedLine(0, "CMM_DESC")
    Else
        ' only english
        cbo_MemoLanguage.Request = Replace(GetRequest("Lng", mv_memoRequests), "$Code$", "E", , , vbTextCompare)
    End If
    
    Call UpdateUI(ArmScreenMode.smMemoAdd)

    Exit Sub
ErrHandler:
    Call ErrorHandler("Memo_AddInit")
End Sub

' initialize memo delete mode
Private Sub Memo_DeleteInit(ByVal as_MemoCode As String)
On Error GoTo ErrHandler
    If ml_memoCursor = 0 Then
        Call Memo_ViewInit(as_MemoCode)
    End If
    Debug.Assert (ml_memoCursor <> 0)
    
    Call ResetScreen(ArmScreenMode.smMemoDelete)
    Call UpdateUI(ArmScreenMode.smMemoDelete)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Memo_DeleteInit")
End Sub

Private Sub Memo_Restore(ByVal as_MemoCode As String)
On Error GoTo ErrHandler

    Call Memo_ViewInit(as_MemoCode)
    
    Call ResetScreen(activeScreenMode)
    Call UpdateUI
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Memo_Restore")
End Sub

Private Function Memo_Update(ByVal av_oldKey As Variant) As Variant
On Error GoTo ErrHandler
    ' check values and throw message if neccessary
    If ThrowErrorMessage(Memo_Check()) Then
        Exit Function
    End If
    Call Memo_UpdateDb(ml_memoCursor, GetRequest("Upd", mv_memoRequests), av_oldKey(0))
    
    Call Item_UpdateLastUpd(GetRequest("CLACODE", mv_memoRequests))
   
    Memo_Update = av_oldKey
    Exit Function
ErrHandler:
   If Err.Number = SQLBadRowAffectedCount Then
        Err.Clear
        SendMessage ms_LanguageCode, ErrMsgIConcurency, "#Someone changed detail of this record and detail screen will be reloaded."
        Call Memo_Restore(av_oldKey(0))
        Exit Function
    End If
    Call ErrorHandler("Memo_Update")
End Function

' adds current edited memo
Private Function Memo_Add() As Variant
On Error GoTo ErrHandler
   ' check values and throw message if neccessary
    If ThrowErrorMessage(Memo_Check()) Then
        Exit Function
    End If
  
    Debug.Assert (Not cbo_MemoLanguage.SelectedItem Is Nothing)
    Call Memo_AddDb(GetRequest("Add", mv_memoRequests), cbo_MemoLanguage.SelectedItem.Key)
    
    Call Item_UpdateLastUpd(GetRequest("CLACODE", mv_memoRequests))
    
    Memo_Add = CVar(Array(cbo_MemoLanguage.SelectedItem.Key))
    Exit Function
ErrHandler:
    If Err.Number = SQLBadRowAffectedCount Then
        Call MsgBox("Error occured while inserting record, please contact IT")
        Exit Function
    End If
        If Err.Number = DuplicityDetected Then
        Err.Clear
        Call SetFocusToCtrl(cbo_MemoLanguage)
        SendMessage ms_LanguageCode, WarMsgItemExists, "#You are trying to add existing item in destination."
        Exit Function
    End If

    Call ErrorHandler("Memo_Add")
End Function

' deletes memo
Private Function Memo_Delete(ByVal av_oldKey As Variant) As Variant
On Error GoTo ErrHandler
    If SendMessage(ms_LanguageCode, WarMsgDoYouRemove, "#Delete record ?", "Delete ", vbQuestion + vbYesNo) = vbYes Then

        Call Memo_DeleteDb(ml_memoCursor, GetRequest("Del", mv_memoRequests), av_oldKey(0))
        
        Call Item_UpdateLastUpd(GetRequest("CLACODE", mv_memoRequests))
        
        Memo_Delete = av_oldKey
    End If
    
    Exit Function
ErrHandler:
   If Err.Number = SQLBadRowAffectedCount Then
        Err.Clear
        SendMessage ms_LanguageCode, ErrMsgIConcurency, "#Someone changed detail of this record and detail screen will be reloaded."
        Call Memo_Restore(av_oldKey(0))
        Exit Function
    End If
    Call ErrorHandler("Memo_Delete")
End Function

Private Sub Memo_AddDb(ByVal as_reqTmpl As String, ByVal as_MemoCode As String)
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ' common placeholders
    ls_req = Replace(as_reqTmpl, "$Code$", as_MemoCode, , , vbTextCompare)
    ls_req = Memo_ReplacePlaceholders(ls_req)
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    
    Exit Sub
ErrHandler:
    If IsArray(mo_Db.SQLErrorCodes) Then
        If GetArrayValue(mo_Db.SQLErrorCodes, 0) = 2627 Then
            ' error when inserting duplicate key
            Call Err.Raise(ArmErr.DuplicityDetected, Err.Source, Err.HelpFile, Err.HelpContext)
        End If
    End If
    Call ErrorHandler("Memo_AddDb")
End Sub

' update memo in db
Private Sub Memo_UpdateDb(ByVal al_Cursor As Long, ByVal as_reqTmpl As String, ByVal as_MemoCode As String)
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ' common placeholders
    ls_req = Replace(as_reqTmpl, "$Code$", as_MemoCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$iConcurrency$", mo_Db.GetFields(al_Cursor, "iConcurrency"), , , vbTextCompare)
    
    ls_req = Memo_ReplacePlaceholders(ls_req)
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)

    Exit Sub
ErrHandler:
   
    Call ErrorHandler("Memo_UpdateDb")
End Sub

' delete memo from db
Private Sub Memo_DeleteDb(ByVal al_Cursor As Long, ByVal as_reqTmpl As String, ByVal as_MemoCode As String)
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ' common placeholders
    ls_req = Replace(as_reqTmpl, "$Code$", as_MemoCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$iConcurrency$", mo_Db.GetFields(al_Cursor, "iConcurrency"), , , vbTextCompare)
    
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    
    Exit Sub
ErrHandler:

    Call ErrorHandler("Memo_DeleteDb")
End Sub

Private Function Memo_ReplacePlaceholders(ByVal as_tmplStr As String) As String
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ls_req = Replace(as_tmplStr, "$Title$", SqlStr(txt_MemoTitle.Text, 100), , , vbTextCompare)
    ls_req = Replace(ls_req, "$Desc$", SqlStr(txt_MemoComment.Text, 65535), , , vbTextCompare)
    
    Memo_ReplacePlaceholders = ls_req
    Exit Function
ErrHandler:
    Call ErrorHandler("Memo_ReplacePlaceholders")
End Function

' clear all controls values
Private Sub Memo_Clear()
On Error GoTo ErrHandler
    ClearForm UserControl.Controls, fra_ClaimMemoMod
    cbo_MemoLanguage.Request = ""
    Exit Sub
ErrHandler:
    Call ErrorHandler("Memo_Clear")
End Sub

' loads values to form
Private Sub Memo_LoadValues(ByVal al_Cursor As Long)
On Error GoTo ErrHandler
    
    Dim lb_clearControls As Boolean
    lb_clearControls = (al_Cursor = -1)
    
    Call mo_Db.First(al_Cursor)

    Call SetComboBoxTextDB(al_Cursor, "Language_code", "Language_desc", cbo_MemoLanguage, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "CMM_desc", txt_MemoComment, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "CMM_title", txt_MemoTitle, lb_clearControls)

    Exit Sub
ErrHandler:
    Call ErrorHandler("Memo_LoadValues")
End Sub

' check memo controls
Private Function Memo_Check() As ErrMsg
On Error GoTo ErrHandler
    
    If txt_MemoComment.Text = "" Then
        Memo_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(txt_MemoComment)
        Exit Function
    End If
    
    If txt_MemoTitle.Text = "" Then
        Memo_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(txt_MemoTitle)
        Exit Function
    End If

    If cbo_MemoLanguage.SelectedItem Is Nothing Then
        Memo_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(cbo_MemoLanguage)
        Exit Function
    End If

    Memo_Check = ErrMsgNone

    Exit Function
ErrHandler:
    Call ErrorHandler("Memo_Check")
End Function

Private Sub Memo_Print(ByVal al_memoCursor As Long)
On Error GoTo ErrHandler
    Debug.Assert (al_memoCursor <> 0)
    If mo_Db.RowCount(al_memoCursor) <> 0 Then
        Call mo_Db.First(al_memoCursor)
        While Not mo_Db.EOF(al_memoCursor)
            PrintMultiLine (mo_Db.GetFields(al_memoCursor, "CMM_title") & " : " & mo_Db.GetFields(al_memoCursor, "CMM_desc"))
            Call mo_Db.Next(al_memoCursor)
        Wend
    Else
        Printer.Print " - "
    End If
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Memo_Print")
End Sub

Private Function GetRequest(ByVal as_ID, ByVal av_reqArray As Variant) As String
On Error GoTo ErrHandler
    Dim ll_Index As Long
    
    For ll_Index = LBound(av_reqArray) To UBound(av_reqArray)
        If av_reqArray(ll_Index)(0) = as_ID Then
            GetRequest = Replace(av_reqArray(ll_Index)(1), "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
            Exit For
        End If
    Next
    Exit Function
ErrHandler:
    Call ErrorHandler("GetRequest")
End Function
' loads data to memo list
Private Sub Memo_LoadGrid(ByRef ao_grid As ArmGrid, ByVal as_reqTmpl As String)
On Error GoTo ErrHandler
    If Not ao_grid.Load(as_reqTmpl, False) Then
           Err.Raise CompFncFailed, "ao_grid.Load", "Grid load failed. SQL: " & as_reqTmpl
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("Memo_LoadGrid")
End Sub

Private Sub Memo_CloseCursor()
On Error GoTo ErrHandler
    
    If ml_memoCursor > 0 Then
        Call mo_Db.Close(ml_memoCursor)
    End If
    ml_memoCursor = 0

    Exit Sub
ErrHandler:
    Call ErrorHandler("Memo_CloseCursor")
End Sub
' ************************* MEMO FRAMEWORK FUNCTIONS *********************************

' ************************************************************************************
' ************************** NOTE FRAMEWORK FUNCTIONS ********************************
' ************************************************************************************
' initialize note add screen
Private Sub Note_AddInit()
On Error GoTo ErrHandler
    
    ' data was loaded from previous mode
    Call Memo_CloseCursor
    ml_notesCursor = -1

    ' clearing form
    Call ResetScreen(ArmScreenMode.smNotesAdd)
    Call Note_Clear
    ' loading values into detail controls
    Call Note_LoadValues(ml_notesCursor)
    
    Call UpdateUI(ArmScreenMode.smNotesAdd)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Note_AddInit")
End Sub

' initialize note update
Private Sub Note_UpdateInit(ByVal as_claCode As String, ByVal as_NoteCode As String)
Const C_REQ As String = "EXEC Clm_Credit_sel '$ClaimCode$', $Code$, '$LangCode$'"
On Error GoTo ErrHandler
    Debug.Assert (ml_notesCursor = 0)
    
    ' clearing form
    Call ResetScreen(ArmScreenMode.smNotesUpdate)
    Call Note_Clear
    
    ' open cursor
    Call Item_LoadDB(ml_notesCursor, 0, Replace(C_REQ, "$ClaimCode$", as_claCode, , , vbTextCompare), as_NoteCode)
    ' loading values
    Call Note_LoadValues(ml_notesCursor)
         
    Call UpdateUI(ArmScreenMode.smNotesUpdate)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Note_UpdateInit")
End Sub


' initialize note delete mode
Private Sub Note_DeleteInit(ByVal as_claCode As String, ByVal as_NoteCode As String)
Const C_REQ As String = "EXEC Clm_Credit_sel '$ClaimCode$', $Code$, '$LangCode$'"
On Error GoTo ErrHandler
    Debug.Assert (ml_notesCursor = 0)
    
    ' clearing form
    Call ResetScreen(ArmScreenMode.smNotesDelete)
    Call Note_Clear
    
    ' open cursor
    Call Item_LoadDB(ml_notesCursor, 0, Replace(C_REQ, "$ClaimCode$", as_claCode, , , vbTextCompare), as_NoteCode)
    ' loading values
    Call Note_LoadValues(ml_notesCursor)
    
    Call UpdateUI(ArmScreenMode.smNotesDelete)
    Exit Sub
ErrHandler:
    Call ErrorHandler("Note_DeleteInit")
End Sub
Private Sub Note_CloseCursor()
On Error GoTo ErrHandler
    
    If ml_notesCursor > 0 Then
        Call mo_Db.Close(ml_notesCursor)
    End If
    ml_notesCursor = 0

    Exit Sub
ErrHandler:
    Call ErrorHandler("Note_CloseCursor")
End Sub

' clear all controls values
Private Sub Note_Clear()
On Error GoTo ErrHandler
    ClearForm UserControl.Controls, fra_ClaimNoteMod
    Exit Sub
ErrHandler:
    Call ErrorHandler("Note_Clear")
End Sub

' loads values to form
Private Sub Note_LoadValues(ByVal al_Cursor As Long)
On Error GoTo ErrHandler
    
    Dim lb_clearControls As Boolean
    lb_clearControls = (al_Cursor = -1)
    
    Call mo_Db.First(al_Cursor)

    Call SetTextBoxTextDB(al_Cursor, "CCR_info", txt_NoteCreditNote, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "CCR_amount", txt_NoteAmount, lb_clearControls, "0", C_COST_VALUE_FORMAT)
    Call SetCalendarTextDB(al_Cursor, "CCR_Date", cal_NoteDateIssued, lb_clearControls)
    Call SetComboBoxTextDB(al_Cursor, "CURR_code", "CURR_desc", cbo_NoteCurrency, lb_clearControls)

    Exit Sub
ErrHandler:
    Call ErrorHandler("Note_LoadValues")
End Sub

Private Sub Note_Restore(ByVal as_claCode As String, ByVal as_NoteCode As String)
Const C_REQ As String = "EXEC Clm_Credit_sel '$ClaimCode$', $Code$, '$LangCode$'"
On Error GoTo ErrHandler
    ' close all cursors
    Call Note_CloseCursor
    
    ' clearing form
    Call ResetScreen(activeScreenMode)
    Call Note_Clear
    
    ' open cursor
    Call Item_LoadDB(ml_notesCursor, 0, Replace(C_REQ, "$ClaimCode$", as_claCode, , , vbTextCompare), as_NoteCode)
    
    ' loading values into detail controls
    Call Note_LoadValues(ml_notesCursor)
    
    Call UpdateUI
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Note_Restore")
End Sub

Private Function Note_Update(ByVal as_CLA_code As String, ByVal av_oldKey As Variant) As Variant
Const C_REQ As String = "EXEC Clm_Credit_upd '$ClaimCode$', $Code$, '$Info$', $DateIssued$, $Amount$, '$CURR_CODE$', $iConcurrency$, '$LOGINNAME$'"
On Error GoTo ErrHandler
    ' check values and throw message if neccessary
    If ThrowErrorMessage(Note_Check()) Then
        Exit Function
    End If
    Call Note_UpdateDb(ml_notesCursor, Replace(C_REQ, "$ClaimCode$", as_CLA_code, , , vbTextCompare), av_oldKey(0))
    
    Call Item_UpdateLastUpd(as_CLA_code)
   
    Note_Update = av_oldKey
    Exit Function
ErrHandler:
   If Err.Number = SQLBadRowAffectedCount Then
        Err.Clear
        SendMessage ms_LanguageCode, ErrMsgIConcurency, "#Someone changed detail of this record and detail screen will be reloaded."
        Call Note_Restore(as_CLA_code, av_oldKey(0))
        Exit Function
    End If
    Call ErrorHandler("Note_Update")
End Function

' adds current edited memo
Private Function Note_Add(ByVal as_CLA_code As String) As Variant
Const C_REQ As String = "EXEC Clm_Credit_ins '$ClaimCode$', $Code$, '$Info$', $DateIssued$, $Amount$, '$CURR_CODE$', '$LOGINNAME$'"
Const C_REQ_ID As String = "SELECT COALESCE(MAX(CCR_order),0) + 1 From Claim_Credit WHERE CLA_code = '$ClaimCode$' AND Language_code = 'E'"
On Error GoTo ErrHandler
   ' check values and throw message if neccessary
    If ThrowErrorMessage(Note_Check()) Then
        Exit Function
    End If
    Dim ll_newID As Long
    Dim ll_Cursor As Long
    Dim lb_inTransaction As Boolean
    
    ASC_BeginTransaction mo_Db, "CM_NOTE_ADD"
    lb_inTransaction = True
    
    ' get next id
    ll_Cursor = OpenSQLSafe(mo_Db, Replace(C_REQ_ID, "$ClaimCode$", as_CLA_code, , , vbTextCompare), ArmSQLExactOne, 1)
    ll_newID = CLng(mo_Db.GetFields(ll_Cursor, 0))
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    Call Note_AddDb(Replace(C_REQ, "$ClaimCode$", as_CLA_code, , , vbTextCompare), CStr(ll_newID))
    
    Call Item_UpdateLastUpd(as_CLA_code)
    
    ASC_CommitTransaction mo_Db, "CM_NOTE_ADD"
    lb_inTransaction = False
    
    Note_Add = CVar(Array(ll_newID))
    Exit Function
ErrHandler:
    If ll_Cursor <> 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    If lb_inTransaction Then
        ASC_RollBackTransaction mo_Db, "CM_NOTE_ADD"
        lb_inTransaction = False
    End If
    If Err.Number = SQLBadRowAffectedCount Then
        Call MsgBox("Error occured while inserting record, please contact IT")
        Exit Function
    End If

    Call ErrorHandler("Note_Add")
End Function

' deletes note
Private Function Note_Delete(ByVal as_CLA_code As String, ByVal av_oldKey As Variant) As Variant
Const C_REQ As String = "EXEC Clm_Credit_del '$ClaimCode$', $Code$, $iConcurrency$"
On Error GoTo ErrHandler
    If SendMessage(ms_LanguageCode, WarMsgDoYouRemove, "#Delete record ?", "Delete ", vbQuestion + vbYesNo) = vbYes Then

        Call Note_DeleteDb(ml_notesCursor, Replace(C_REQ, "$ClaimCode$", as_CLA_code, , , vbTextCompare), av_oldKey(0))
        
        Call Item_UpdateLastUpd(as_CLA_code)
        
        Note_Delete = av_oldKey
    End If
    
    Exit Function
ErrHandler:
   If Err.Number = SQLBadRowAffectedCount Then
        Err.Clear
        SendMessage ms_LanguageCode, ErrMsgIConcurency, "#Someone changed detail of this record and detail screen will be reloaded."
        Call Note_Restore(as_CLA_code, av_oldKey(0))
        Exit Function
    End If
    Call ErrorHandler("Note_Delete")
End Function

' delete note from db
Private Sub Note_DeleteDb(ByVal al_Cursor As Long, ByVal as_reqTmpl As String, ByVal as_MemoCode As String)
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ' common placeholders
    ls_req = Replace(as_reqTmpl, "$Code$", as_MemoCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$iConcurrency$", mo_Db.GetFields(al_Cursor, "iConcurrency"), , , vbTextCompare)
    
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Note_DeleteDb")
End Sub


Private Sub Note_AddDb(ByVal as_reqTmpl As String, ByVal as_NotesCode As String)
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ' common placeholders
    ls_req = Replace(as_reqTmpl, "$Code$", as_NotesCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)

    ls_req = Note_ReplacePlaceholders(ls_req)
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Note_AddDb")
End Sub

' update note in db
Private Sub Note_UpdateDb(ByVal al_Cursor As Long, ByVal as_reqTmpl As String, ByVal as_NoteCode As String)
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ' common placeholders
    ls_req = Replace(as_reqTmpl, "$Code$", as_NoteCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
    ls_req = Replace(ls_req, "$iConcurrency$", mo_Db.GetFields(al_Cursor, "iConcurrency"), , , vbTextCompare)
    
    ls_req = Note_ReplacePlaceholders(ls_req)
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)

    Exit Sub
ErrHandler:
   
    Call ErrorHandler("Note_UpdateDb")
End Sub

' check note controls
Private Function Note_Check() As ErrMsg
On Error GoTo ErrHandler
    
    If txt_NoteAmount.Text = "" Then
        Note_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(txt_NoteAmount)
        Exit Function
    End If
    
    If Not IsNumericArm(txt_NoteAmount.Text) Then
        Note_Check = ErrMsgNumericRequired
        Call SetFocusToCtrl(txt_NoteAmount)
        Exit Function
    End If

    If ToDouble(txt_NoteAmount.Text) < 0 Then
        Note_Check = ErrMsgBadValue
        Call SetFocusToCtrl(txt_NoteAmount)
        Exit Function
    End If
    
    If txt_NoteCreditNote.Text = "" Then
        Note_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(txt_NoteCreditNote)
        Exit Function
    End If

    If cal_NoteDateIssued.date_dt = 0 Then
        Note_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(cal_NoteDateIssued)
        Exit Function
    End If
    
    If cbo_NoteCurrency.SelectedItem Is Nothing Then
        Note_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(cbo_NoteCurrency)
        Exit Function
    End If

    Note_Check = ErrMsgNone

    Exit Function
ErrHandler:
    Call ErrorHandler("Note_Check")
End Function

Private Sub Note_Print(ByVal al_noteCursor As Long)
On Error GoTo ErrHandler
    Dim ls_Amount As String
    Dim ls_Currency As String
    Dim ls_CreditNote As String
    Dim ls_DateIssued As String
    
    Debug.Assert (al_noteCursor <> 0)
    
    If mo_Db.RowCount(al_noteCursor) > 0 Then
        ls_CreditNote = grd_CostNotes.Columns("CCR_info").Title
        ls_DateIssued = grd_CostNotes.Columns("CCR_date").Title
        ls_Amount = grd_CostNotes.Columns("CCR_amount").Title
        ls_Currency = grd_CostNotes.Columns("CURR_desc").Title
    
        Call mo_Db.First(al_noteCursor)
        While Not mo_Db.EOF(al_noteCursor)
            Printer.Print ls_CreditNote & " " & mo_Db.GetFields(al_noteCursor, "CCR_info") & "  " _
                & ls_DateIssued & " " & mo_Db.GetFields(al_noteCursor, "CCR_date") & " " _
                & ls_Amount & " " & mo_Db.GetFields(al_noteCursor, "CCR_Amount") & " " _
                & ls_Currency & " " & mo_Db.GetFields(al_noteCursor, "CURR_desc")
            Call mo_Db.Next(al_noteCursor)
        Wend
    End If
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Note_Print")
End Sub

Private Function Note_ReplacePlaceholders(ByVal as_tmplStr As String) As String
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ls_req = Replace(as_tmplStr, "$Info$", SqlStr(txt_NoteCreditNote.Text, 255), , , vbTextCompare)
    ls_req = Replace(ls_req, "$Amount$", SQLNum(ToDouble(txt_NoteAmount.Text)), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CURR_CODE$", SQLComboBoxValue(cbo_NoteCurrency, ""), , , vbTextCompare)
    ls_req = Replace(ls_req, "$DateIssued$", SQLDateTime(cal_NoteDateIssued.date_dt), , , vbTextCompare)
    
    Note_ReplacePlaceholders = ls_req
    Exit Function
ErrHandler:
    Call ErrorHandler("Note_ReplacePlaceholders")
End Function
' ************************** NOTE FRAMEWORK FUNCTIONS ********************************

' ************************************************************************************
' ********************** CUSTOMER FRAMEWORK FUNCTIONS ********************************
' ************************************************************************************
' inititialize serlect customer
Private Sub Cust_SelectInit(ByVal as_CT_Code As String, ByVal as_CT_desc As String)
On Error GoTo ErrHandler
    Debug.Assert (ml_custCursor = 0)
    ' clearing form
    Call ResetScreen(ArmScreenMode.smCustMain)
    Call Cust_Clear
    Call Cust_LoadValues(ml_custCursor)     ' reset main screen of customer
    
    ' default value
    If as_CT_Code <> "" Then
        Call SetComboBoxText(cbo_SelectCustCountry, as_CT_Code, as_CT_desc)
    End If
    
    Call UpdateUI(ArmScreenMode.smCustMain)
    Exit Sub
ErrHandler:
    Call ErrorHandler("Cust_SelectInit")
End Sub

' initialize customer update
Private Sub Cust_UpdateInit(ByVal as_CustCode As String)
Const C_REQ As String = "EXEC Clm_Customer_dtl $Code$, '$LangCode$'"
On Error GoTo ErrHandler
    Debug.Assert (ml_custCursor = 0)
    ' data was loaded from previous view mode
    Call ResetScreen(ArmScreenMode.smCustUpdate)
    Call Cust_Clear
    
    ' open cursor
    Call Item_LoadDB(ml_custCursor, 0, C_REQ, as_CustCode)
    
    ' loading values into detail controls
    Call Cust_LoadValues(ml_custCursor)

    Call UpdateUI(ArmScreenMode.smCustUpdate)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Cust_UpdateInit")
End Sub

' initialize customer add screen
Private Sub Cust_AddInit()
On Error GoTo ErrHandler
    Debug.Assert (ml_custCursor = 0)
    ' data was loaded from previous view mode
    ml_custCursor = -1

    ' clearing form
    Call ResetScreen(ArmScreenMode.smCustAdd)
    Call Cust_Clear
    ' loading values into detail controls
    Call Cust_LoadValues(ml_custCursor)
    
    Call UpdateUI(ArmScreenMode.smCustAdd)

    Exit Sub
ErrHandler:
    Call ErrorHandler("Cust_AddInit")
End Sub

' initialize customer add screen for SAP customer
Private Sub Cust_AddSAPInit(ByVal as_SAPCustCode As String)
Const C_REQ As String = "EXEC Clm_CustomerSAP_dtl '$Code$', '$LangCode$'"
On Error GoTo ErrHandler
    Debug.Assert (ml_custCursor = 0)
    
    ' clearing form
    Call ResetScreen(ArmScreenMode.smCustAdd)
    Call Cust_Clear
    
    ' open cursor
    Call Item_LoadDB(ml_custCursor, 0, C_REQ, as_SAPCustCode)
    Debug.Assert (ml_custCursor <> 0)
    
    ' loading values into detail controls
    Call Cust_LoadValues(ml_custCursor)
    
    Call UpdateUI(ArmScreenMode.smCustAdd)

    Exit Sub
ErrHandler:
    Call ErrorHandler("Cust_AddSAPInit")
End Sub

' initialize customer delete mode
Private Sub Cust_DeleteInit(ByVal as_CustCode As String)
Const C_REQ As String = "EXEC Clm_Customer_dtl $Code$, '$LangCode$'"
On Error GoTo ErrHandler
    Debug.Assert (ml_custCursor = 0)
    
    Call ResetScreen(ArmScreenMode.smCustDelete)
    Call Cust_Clear
    
    ' open cursor
    Call Item_LoadDB(ml_custCursor, 0, C_REQ, as_CustCode)
    
    ' loading values into detail controls
    Call Cust_LoadValues(ml_custCursor)
    
    Call UpdateUI(ArmScreenMode.smCustDelete)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Cust_DeleteInit")
End Sub

' initialize customer into view mode
Private Sub Cust_ViewInit(ByVal as_CustCode As String)
Const C_REQ As String = "EXEC Clm_Customer_dtl $Code$, '$LangCode$'"
Const C_REQ_SAP As String = "EXEC Clm_CustomerSAP_dtl '$Code$', '$LangCode$'"
On Error GoTo ErrHandler
    Debug.Assert (ml_custCursor = 0)
    
    Call ResetScreen(ArmScreenMode.smCustView)
    Call Cust_Clear
    
    ' open cursor
    Call Item_LoadDB(ml_custCursor, 0, IIf(GetOptionButtonCode(opt_SelectCustType, "Claim") = "Claim", C_REQ, C_REQ_SAP), as_CustCode)
    
    ' loading values into detail controls
    Call Cust_LoadValues(ml_custCursor)
    
    Call UpdateUI(ArmScreenMode.smCustView)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Cust_ViewInit")
End Sub

Private Sub Cust_Restore(ByVal as_CustCode As String)
Const C_REQ As String = "EXEC Clm_Customer_dtl $Code$, '$LangCode$'"
Const C_REQ_SAP As String = "EXEC Clm_CustomerSAP_dtl '$Code$', '$LangCode$'"
On Error GoTo ErrHandler
    ' close all cursors
    Call Cust_CloseCursor
    
    ' clearing form
    Call ResetScreen(activeScreenMode)
    Call Cust_Clear
    
    ' open cursor
    Call Item_LoadDB(ml_custCursor, 0, IIf(GetOptionButtonCode(opt_SelectCustType, "Claim") = "Claim", C_REQ, C_REQ_SAP), as_CustCode)
    
    ' loading values into detail controls
    Call Cust_LoadValues(ml_custCursor)
    
    Call UpdateUI
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Cust_Restore")
End Sub


Private Function Cust_Select() As Variant
Const C_REQ As String = "EXEC Clm_Customer_dtl $Code$, '$LangCode$'"
Const C_REQ_SAP_INS As String = "EXEC Clm_Customer_SAP_ins '$Code$', '$CompCode$', 'Claim', $CCU_code$, '$LOGINNAME$'"
Const C_REQ_CHK As String = "SELECT CCU_code FROM Claim_Customer WHERE CUST_Code='$Code$' AND COMP_code='$CompCode$' AND Language_code='E'"
'Const C_REQ_NEXTID As String = "SELECT MAX(CCU_code) FROM Claim_Customer"

On Error GoTo ErrHandler
    Dim lb_inTransaction As Boolean
    lb_inTransaction = False
    
    Debug.Assert (ml_custCursor = 0)
    ' check values and throw message if neccessary
    If grd_SelectCustList.SelectedCount = 0 Then
        SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
    Else
        Dim ls_ID As String
        If GetOptionButtonCode(opt_SelectCustType, "Claim") = "Claim" Then
            ' open cursor
            Call Item_LoadDB(ml_custCursor, 0, C_REQ, grd_SelectCustList.SelectedKey(0)(0))
            ls_ID = grd_SelectCustList.SelectedKey(0)(0)
        Else
                
            ' check if customer is mirrored into Claim_Customer
            Dim ll_auxCursor As Long
            Dim ls_req As String
            ls_req = Replace(C_REQ_CHK, "$Code$", grd_SelectCustList.SelectedKey(0)(0), , , vbTextCompare)
            ls_req = Replace(ls_req, "$CompCode$", grd_SelectCustList.SelectedKey(0)(1), , , vbTextCompare)
            ll_auxCursor = OpenSQLSafe(mo_Db, ls_req, ArmSQLAny)
            If mo_Db.RowCount(ll_auxCursor) = 0 Then
                ' create mirror
                ' get next id for customer
                
                ls_ID = mo_Db.SQLNextID("claim_customer")
                If ls_ID = "" Then Call Err.Raise(SQLFailure, "", "SQL Error: mo_ArmDb.SQLNextID(""claim_customer"") return nothing.")

                
                ASC_BeginTransaction mo_Db, "CM_ADDCUSTOMER"
                lb_inTransaction = True
                
                'Dim ll_IDCursor As Long
                'll_IDCursor = OpenSQLSafe(mo_Db, C_REQ_NEXTID, ArmSQLExactOne, 1)
                'ls_ID = CStr(mo_Db.GetFields(ll_IDCursor, 0) + 1)
                'Call mo_Db.Close(ll_IDCursor)
                'll_IDCursor = 0
                
                ' insert new record into Claim_Customer
                ls_req = Replace(C_REQ_SAP_INS, "$CCU_code$", ls_ID, , , vbTextCompare)
                ls_req = Replace(ls_req, "$CompCode$", grd_SelectCustList.SelectedKey(0)(1), , , vbTextCompare)
                Call Cust_AddDb(ml_custCursor, ls_req, grd_SelectCustList.SelectedKey(0)(0))
                
                ASC_CommitTransaction mo_Db, "CM_ADDCUSTOMER"
                lb_inTransaction = False

            Else
                ls_ID = mo_Db.GetFields(ll_auxCursor, "CCU_code")
            End If
            Call mo_Db.Close(ll_auxCursor)
            ll_auxCursor = 0
            
            ' open cursor
            Call Item_LoadDB(ml_custCursor, 0, C_REQ, ls_ID)
            Debug.Assert (ml_custCursor <> 0)
            
        End If
        Cust_Select = CVar(Array(ls_ID, grd_SelectCustList.SelectedKey(0)(1)))
    End If
    Exit Function
ErrHandler:
    If lb_inTransaction Then
        ASC_RollBackTransaction mo_Db, "CM_ADDCUSTOMER"
        lb_inTransaction = False
    End If

    If ll_auxCursor <> 0 Then
        Call mo_Db.Close(ll_auxCursor)
        ll_auxCursor = 0
    End If
'    If ll_IDCursor <> 0 Then
'        Call mo_Db.Close(ll_IDCursor)
'        ll_IDCursor = 0
'    End If
    Call ErrorHandler("Cust_Select")
End Function

' adds current edited customer
Private Function Cust_Add() As Variant
Const C_REQ As String = "EXEC Clm_Customer_ins $Code$, '$CustName$', '$Address1$', '$Address2$', '$Zip$', '$Town$', '$CTCode$', '$Contact$', '$Tel$', '$Fax$', '$CustTCode$', $SysCode$, '$Title$', '$CompCode$', '$Email$', '$CUST_code$','$LOGINNAME$'"
'Const C_REQ_NEXTID As String = "SELECT MAX(CCU_code) FROM Claim_Customer"
On Error GoTo ErrHandler
    Dim lb_inTransaction As Boolean
    lb_inTransaction = False

   ' check values and throw message if neccessary
    If ThrowErrorMessage(Cust_Check()) Then
        Exit Function
    End If
    
    Dim ls_ID As String
    ls_ID = mo_Db.SQLNextID("claim_customer")
    If ls_ID = "" Then Call Err.Raise(SQLFailure, "", "SQL Error: mo_ArmDb.SQLNextID(""claim_customer"") return nothing.")

    
    ASC_BeginTransaction mo_Db, "CM_ADDCUSTOMER"
    lb_inTransaction = True
    
    ' get next id for customer
'    Dim ll_IDCursor As Long
'    Dim ls_ID As String
'    ll_IDCursor = OpenSQLSafe(mo_Db, C_REQ_NEXTID, ArmSQLExactOne, 1)
'    ls_ID = CStr(mo_Db.GetFields(ll_IDCursor, 0) + 1)
'    Call mo_Db.Close(ll_IDCursor)
'    ll_IDCursor = 0

    Call Cust_AddDb(ml_custCursor, C_REQ, ls_ID)
    
    ASC_CommitTransaction mo_Db, "CM_ADDCUSTOMER"
    lb_inTransaction = False

    Cust_Add = CVar(Array(ls_ID, SQLComboBoxValue(cbo_SelCustModCompany, "")))
    Exit Function
ErrHandler:
    If lb_inTransaction Then
        ASC_RollBackTransaction mo_Db, "CM_ADDCUSTOMER"
        lb_inTransaction = False
    End If

'    If ll_IDCursor <> 0 Then
'        Call mo_Db.Close(ll_IDCursor)
'        ll_IDCursor = 0
'    End If
    
    If Err.Number = SQLBadRowAffectedCount Then
        Call MsgBox("Error occured while inserting record, please contact IT")
        Exit Function
    End If

    Call ErrorHandler("Cust_Add")
End Function


' update customer selection mod
Private Function Cust_Update(ByVal av_oldKey As Variant) As Variant
Const C_REQ As String = "EXEC Clm_Customer_upddtl $Code$, '$CustName$', '$Address1$', '$Address2$', '$Zip$', '$Town$', '$CTCode$', '$Contact$', '$Tel$', '$Fax$', '$CustTCode$', $SysCode$, '$Title$', '$CompCode$', '$Email$', '$LOGINNAME$', $iConcurrency$"
On Error GoTo ErrHandler
    ' check values and throw message if neccessary
    If ThrowErrorMessage(Cust_Check()) Then
        Exit Function
    End If
    
    Call Cust_UpdateDb(ml_custCursor, C_REQ, av_oldKey(0))
    
    Cust_Update = av_oldKey
    Exit Function
ErrHandler:
   If Err.Number = SQLBadRowAffectedCount Then
        Err.Clear
        SendMessage ms_LanguageCode, ErrMsgIConcurency, "#Someone changed detail of this record and detail screen will be reloaded."
        Call Cust_Restore(av_oldKey(0))
    Exit Function
    End If
    Call ErrorHandler("Cust_Update")
End Function

' update customer selection mod
Private Function Cust_Delete(ByVal av_oldKey As Variant) As Variant
Const C_REQ As String = "EXEC Clm_Customer_del $Code$, $iConcurrency$"
On Error GoTo ErrHandler
    
    If SendMessage(ms_LanguageCode, WarMsgDoYouRemove, "#Delete record ?", "Delete ", vbQuestion + vbYesNo) = vbYes Then
        Call Cust_DeleteDb(ml_custCursor, C_REQ, av_oldKey(0))
        
        Cust_Delete = av_oldKey
    End If
    Exit Function
ErrHandler:
    Select Case Err.Number
    Case ArmErr.SQLBadRowAffectedCount
        Err.Clear
        SendMessage ms_LanguageCode, ErrMsgIConcurency, "#Someone changed detail of this record and detail screen will be reloaded."
        Call Cust_Restore(av_oldKey(0))
        Exit Function
        
    Case ArmErr.SQLTableReferenceConstraint
        Err.Clear
        SendMessage ms_LanguageCode, ErrMsgCannotDeleteRecord, "#You cannot delete record. Record is still used in datbase."
        Exit Function
    End Select
    Call ErrorHandler("Cust_Delete")
End Function

Private Sub Cust_AddDb(ByVal al_Cursor As Long, ByVal as_reqTmpl As String, ByVal as_CustCode As String)
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ' common placeholders
    ls_req = Replace(as_reqTmpl, "$Code$", as_CustCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CUST_code$", SqlStr(mo_Db.GetFields(al_Cursor, "CUST_code"), 10), , , vbTextCompare)

    ls_req = Cust_ReplacePlaceholders(ls_req)
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Cust_AddDb")
End Sub

Private Sub Cust_UpdateDb(ByVal al_Cursor As Long, ByVal as_reqTmpl As String, ByVal as_CustCode As String)
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ' common placeholders
    ls_req = Replace(as_reqTmpl, "$Code$", as_CustCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
    ls_req = Replace(ls_req, "$iConcurrency$", mo_Db.GetFields(al_Cursor, "iConcurrency"), , , vbTextCompare)

    ls_req = Cust_ReplacePlaceholders(ls_req)
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Cust_UpdateDb")
End Sub

Private Sub Cust_DeleteDb(ByVal al_Cursor As Long, ByVal as_reqTmpl As String, ByVal as_CustCode As String)
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ' common placeholders
    ls_req = Replace(as_reqTmpl, "$Code$", as_CustCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
    ls_req = Replace(ls_req, "$iConcurrency$", mo_Db.GetFields(al_Cursor, "iConcurrency"), , , vbTextCompare)

    Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Cust_UpdateDb")
End Sub

' check customer selection mod controls
Private Function Cust_Check() As ErrMsg
On Error GoTo ErrHandler

    If txt_SelCustModName.Text = "" Then
        Cust_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(txt_SelCustModName)
        Exit Function
    End If
  
    If txt_SelCustModTown.Text = "" Then
        Cust_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(txt_SelCustModTown)
        Exit Function
    End If

    If cbo_SelCustModCountry.SelectedItem Is Nothing Then
        Cust_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(cbo_SelCustModCountry)
        Exit Function
    End If

    Cust_Check = ErrMsgNone

    Exit Function
ErrHandler:
    Call ErrorHandler("Cust_Check")
End Function

' clears selection customer mod frame
Private Sub Cust_Clear()
On Error GoTo ErrHandler
    ClearForm UserControl.Controls, GetControl(fra_frames, "fra_SelectCusMod")
    Exit Sub
ErrHandler:
    Call ErrorHandler("Cust_Clear")
End Sub

' loads values to form
Private Sub Cust_LoadValues(ByVal al_Cursor As Long)
On Error GoTo ErrHandler
    Dim lb_clearControls As Boolean
    lb_clearControls = (al_Cursor = -1)
    
    Call mo_Db.First(al_Cursor)

    Call SetTextBoxTextDB(al_Cursor, "CCU_desc", txt_SelCustModName, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "CCU_addr1", txt_SelCustModAddress1, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "CCU_addr2", txt_SelCustModAddress2, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "CCU_zip", txt_SelCustModZipCode, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "CCU_town", txt_SelCustModTown, lb_clearControls)
    Call SetComboBoxTextDB(al_Cursor, "CT_code", "CT_desc", cbo_SelCustModCountry, lb_clearControls)
    Call SetComboBoxTextDB(al_Cursor, "COMP_code", "COMP_name", cbo_SelCustModCompany, lb_clearControls)
    Call SetComboBoxTextDB(al_Cursor, "CUST_code", "CUST_desc", cbo_SelCustModType, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "CCU_contact", txt_SelCustModContact, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "CCU_contactTitle", txt_SelCustModContactTitle, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "CCU_tel", txt_SelCustModPhone, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "CCU_fax", txt_SelCustModFax, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "QDA_email", txt_SelCustModEmail, lb_clearControls)
    
    If al_Cursor = 0 Then
        Call SetOptionButtonCodeDB(al_Cursor, "", opt_SelectCustType, True)
        Call SetOptionButtonCodeDB(al_Cursor, "", opt_SelectCustLike, True)
'        Call SetComboBoxTextDB(al_Cursor, "", "", cbo_SelectCustCountry, True) ' do not reset country combo
        Call SetTextBoxTextDB(al_Cursor, "", txt_SelectCustLike, True)
        Call grd_SelectCustList.ClearGrid
    End If
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Cust_LoadValues")
End Sub

Private Sub Cust_LoadGrid()
Const C_REQ As String = "EXEC Clm_Customer_lst '$Country$', '$Like$', '$LikeType$'"
Const C_REQSAP As String = "EXEC Clm_CustomerSAP_lst '$Country$', '$Like$', '$LikeType$'"
On Error GoTo ErrHandler
    ' simple check
    If cbo_SelectCustCountry.SelectedItem Is Nothing Then
        Call SetFocusToCtrl(cbo_SelectCustCountry)
        SendMessage ms_LanguageCode, ErrMsgMandatoryAreEmpty, "#Mandatory fields are not filled."
        Exit Sub
    End If

    Dim ls_SQL As String
    ls_SQL = IIf(GetOptionButtonCode(opt_SelectCustType) = "Claim", C_REQ, C_REQSAP)
    ls_SQL = Replace(ls_SQL, "$Country$", SQLComboBoxValue(cbo_SelectCustCountry, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Like$", SqlStr(txt_SelectCustLike.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$LikeType$", GetOptionButtonCode(opt_SelectCustLike), , , vbTextCompare)
    
    If Not grd_SelectCustList.Load(ls_SQL, False) Then
        Err.Raise CompFncFailed, "grd_SelectCustList.Load", "Grid load failed. SQL: " & ls_SQL
    End If
        
    Exit Sub
    
ErrHandler:
    Call ErrorHandler("Cust_LoadGrid")
End Sub

Private Sub Cust_CloseCursor()
On Error GoTo ErrHandler
    
    If ml_custCursor > 0 Then
        Call mo_Db.Close(ml_custCursor)
    End If
    ml_custCursor = 0

    Exit Sub
ErrHandler:
    Call ErrorHandler("Cust_CloseCursor")
End Sub

Private Function Cust_ReplacePlaceholders(ByVal as_tmplStr As String) As String
On Error GoTo ErrHandler
    Dim ls_SQL As String
    
    ls_SQL = Replace(as_tmplStr, "$CustName$", SqlStr(txt_SelCustModName.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Address1$", SqlStr(txt_SelCustModAddress1.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Address2$", SqlStr(txt_SelCustModAddress2.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Zip$", SqlStr(txt_SelCustModZipCode.Text, 15), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Town$", SqlStr(txt_SelCustModTown.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$CTCode$", SQLComboBoxValue(cbo_SelCustModCountry, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Contact$", SqlStr(txt_SelCustModContact.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Tel$", SqlStr(txt_SelCustModPhone.Text, 20), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Fax$", SqlStr(txt_SelCustModFax.Text, 20), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$CustTCode$", SQLComboBoxValue(cbo_SelCustModType, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$SysCode$", 1, , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Title$", SqlStr(txt_SelCustModContactTitle.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$CompCode$", SQLComboBoxValue(cbo_SelCustModCompany, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Email$", SqlStr(txt_SelCustModEmail.Text, 80), , , vbTextCompare)
    
    Cust_ReplacePlaceholders = ls_SQL
    Exit Function
ErrHandler:
    Call ErrorHandler("Cust_ReplacePlaceholders")
End Function

Private Function Cust_RepositionFilter(ByVal as_Key As String, ByVal as_desc As String) As Boolean
On Error GoTo ErrHandler
    Dim lb_ret As Boolean
    lb_ret = False
    
    ' reposition: check if filter country is set to one we want
    If cbo_SelectCustCountry.SelectedItem Is Nothing Then
        ' select country
        Call SetComboBoxText(cbo_SelectCustCountry, as_Key, as_desc)
        lb_ret = True
    ElseIf cbo_SelectCustCountry.SelectedItem.Key <> as_Key Then
        ' select country
        Call SetComboBoxText(cbo_SelectCustCountry, as_Key, as_desc)
        lb_ret = True
    End If
    Cust_RepositionFilter = lb_ret
    Exit Function
ErrHandler:
    Call ErrorHandler("Cust_RepositionFilter")
End Function

' ********************** CUSTOMER FRAMEWORK FUNCTIONS ********************************

' ************************************************************************************
' *********************** PROJECT FRAMEWORK FUNCTIONS ********************************
' ************************************************************************************
' inititialize serlect customer
Private Sub Proj_SelectInit(ByVal as_CT_Code As String, ByVal as_CT_desc As String)
On Error GoTo ErrHandler
    Debug.Assert (ml_projCursor = 0)
    ' clearing form
    Call ResetScreen(ArmScreenMode.smCustMain)
    Call Proj_Clear
    Call Proj_LoadValues(ml_projCursor)      ' reset main screen of project
    
    ' default value
    If as_CT_Code <> "" Then
        Call SetComboBoxText(cbo_SelectProjCountry, as_CT_Code, as_CT_desc)
    End If
    
    Call UpdateUI(ArmScreenMode.smProjMain)
    Exit Sub
ErrHandler:
    Call ErrorHandler("Proj_SelectInit")
End Sub

' initialize project update
Private Sub Proj_UpdateInit(ByVal as_ProjCode As String)
Const C_REQ As String = "EXEC Clm_Sales_Project_t_sel $Code$, '$LangCode$'"
On Error GoTo ErrHandler
    Debug.Assert (ml_custCursor = 0)
    ' data was loaded from previous view mode
    Call ResetScreen(ArmScreenMode.smProjUpdate)
    Call Proj_Clear
    
    ' open cursor
    Call Item_LoadDB(ml_projCursor, 0, C_REQ, as_ProjCode)
    
    ' loading values into detail controls
    Call Proj_LoadValues(ml_projCursor)

    Call UpdateUI(ArmScreenMode.smProjUpdate)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Proj_UpdateInit")
End Sub

' initialize project add screen
Private Sub Proj_AddInit()
On Error GoTo ErrHandler
    Debug.Assert (ml_projCursor = 0)
    ' data was loaded from previous view mode
    ml_projCursor = -1

    ' clearing form
    Call ResetScreen(ArmScreenMode.smProjAdd)
    Call Proj_Clear
    ' loading values into detail controls
    Call Proj_LoadValues(ml_projCursor)
    
    Call UpdateUI(ArmScreenMode.smProjAdd)

    Exit Sub
ErrHandler:
    Call ErrorHandler("Proj_AddInit")
End Sub

' initialize project delete mode
Private Sub Proj_DeleteInit(ByVal as_ProjCode As String)
Const C_REQ As String = "EXEC Clm_Sales_Project_t_sel $Code$, '$LangCode$'"
On Error GoTo ErrHandler
    Debug.Assert (ml_projCursor = 0)
    
    Call ResetScreen(ArmScreenMode.smProjDelete)
    Call Proj_Clear
    
    ' open cursor
    Call Item_LoadDB(ml_projCursor, 0, C_REQ, as_ProjCode)
    
    ' loading values into detail controls
    Call Proj_LoadValues(ml_projCursor)
    
    Call UpdateUI(ArmScreenMode.smProjDelete)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Proj_DeleteInit")
End Sub

' initialize project into view mode
Private Sub Proj_ViewInit(ByVal as_ProjCode As String)
Const C_REQ As String = "EXEC Clm_Sales_Project_t_sel $Code$, '$LangCode$'"
On Error GoTo ErrHandler
    Debug.Assert (ml_projCursor = 0)
    
    Call ResetScreen(ArmScreenMode.smProjView)
    Call Proj_Clear
    
    ' open cursor
    Call Item_LoadDB(ml_projCursor, 0, C_REQ, as_ProjCode)
    
    ' loading values into detail controls
    Call Proj_LoadValues(ml_projCursor)
    
    Call UpdateUI(ArmScreenMode.smProjView)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Proj_ViewInit")
End Sub

Private Sub Proj_Restore(ByVal as_ProjCode As String)
Const C_REQ As String = "EXEC Clm_Sales_Project_t_sel $Code$, '$LangCode$'"
On Error GoTo ErrHandler
    ' close all cursors
    Call Proj_CloseCursor
    
    ' clearing form
    Call ResetScreen(activeScreenMode)
    Call Proj_Clear
    
    ' open cursor
    Call Item_LoadDB(ml_projCursor, 0, C_REQ, as_ProjCode)
    
    ' loading values into detail controls
    Call Proj_LoadValues(ml_projCursor)
    
    Call UpdateUI
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Proj_Restore")
End Sub



Private Function Proj_Select() As Variant
Const C_REQ As String = "EXEC Clm_Sales_Project_t_sel $Code$, '$LangCode$'"
On Error GoTo ErrHandler
    Debug.Assert (ml_projCursor = 0)
    ' check values and throw message if neccessary
    If grd_SelectProjList.SelectedCount = 0 Then
        SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
    Else
        ' open cursor
        Call Item_LoadDB(ml_projCursor, 0, C_REQ, grd_SelectProjList.SelectedKey(0)(0))
        Debug.Assert (ml_projCursor <> 0)
        
        Proj_Select = grd_SelectProjList.SelectedKey(0)
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("Proj_Select")
End Function

' adds current edited customer
Private Function Proj_Add() As Variant

Const C_REQ As String = "EXEC Clm_Sales_Project_Ins $Code$, '$CTCode$', '$UMCode$', '$Name$', $StartDate$, '$Address1$', '$Address2$', '$Zip$', '$Town$', $Size$, '1', '$LOGINNAME$'"
'Const C_REQ_NEXTID As String = "SELECT MAX(SP_code) FROM Sales_Project"
On Error GoTo ErrHandler
    Dim lb_inTransaction As Boolean
    lb_inTransaction = False

   ' check values and throw message if neccessary
    If ThrowErrorMessage(Proj_Check()) Then
        Exit Function
    End If
  
    Dim ls_ID As String
    ls_ID = mo_Db.SQLNextID("Sales_Project")
    If ls_ID = "" Then Call Err.Raise(SQLFailure, "", "SQL Error: mo_ArmDb.SQLNextID(""Sales_Project"") return nothing.")

  
    ASC_BeginTransaction mo_Db, "CM_ADDPROJECT"
    lb_inTransaction = True
    
    ' get next id for project
    
'    Dim ll_IDCursor As Long
'    ll_IDCursor = OpenSQLSafe(mo_Db, C_REQ_NEXTID, ArmSQLExactOne, 1)
'    ls_ID = CStr(mo_Db.GetFields(ll_IDCursor, 0) + 1)
'    Call mo_Db.Close(ll_IDCursor)
'    ll_IDCursor = 0

    Call Proj_AddDb(ml_projCursor, C_REQ, ls_ID)

    ASC_CommitTransaction mo_Db, "CM_ADDPROJECT"
    lb_inTransaction = False

    Proj_Add = CVar(Array(ls_ID))
    Exit Function
ErrHandler:
    If lb_inTransaction Then
        ASC_RollBackTransaction mo_Db, "CM_ADDPROJECT"
        lb_inTransaction = False
    End If

'    If ll_IDCursor <> 0 Then
'        Call mo_Db.Close(ll_IDCursor)
'        ll_IDCursor = 0
'    End If
    If Err.Number = SQLBadRowAffectedCount Then
        Call MsgBox("Error occured while inserting record, please contact IT")
        Exit Function
    End If

    Call ErrorHandler("Proj_Add")
End Function


' update project selection mod
Private Function Proj_Update(ByVal av_oldKey As Variant) As Variant
Const C_REQ As String = "EXEC Clm_Sales_Project_Upd $Code$, '$CTCode$', '$UMCode$', '$Name$', $StartDate$, '$Address1$', '$Address2$', '$Zip$', '$Town$', $Size$, '$LOGINNAME$', $iConcurrency$"
On Error GoTo ErrHandler
    ' check values and throw message if neccessary
    If ThrowErrorMessage(Proj_Check()) Then
        Exit Function
    End If
    
    Call Proj_UpdateDb(ml_projCursor, C_REQ, av_oldKey(0))
    
    Proj_Update = av_oldKey
    Exit Function
ErrHandler:
   If Err.Number = SQLBadRowAffectedCount Then
        Err.Clear
        SendMessage ms_LanguageCode, ErrMsgIConcurency, "#Someone changed detail of this record and detail screen will be reloaded."
        Call Proj_Restore(av_oldKey(0))
        Exit Function
    End If
    Call ErrorHandler("Proj_Update")
End Function

' update project selection mod
Private Function Proj_Delete(ByVal av_oldKey As Variant) As Variant
Const C_REQ As String = "EXEC Sales_Project_del $Code$, $iConcurrency$"
On Error GoTo ErrHandler
    If SendMessage(ms_LanguageCode, WarMsgDoYouRemove, "#Delete record ?", "Delete ", vbQuestion + vbYesNo) = vbYes Then
    
        Call Proj_DeleteDb(ml_projCursor, C_REQ, av_oldKey(0))
    
        Proj_Delete = av_oldKey
    End If
    Exit Function
ErrHandler:
    Select Case Err.Number
    Case ArmErr.SQLBadRowAffectedCount
        Err.Clear
        SendMessage ms_LanguageCode, ErrMsgIConcurency, "#Someone changed detail of this record and detail screen will be reloaded."
        Call Proj_Restore(av_oldKey(0))
        Exit Function
        
    Case ArmErr.SQLTableReferenceConstraint
        Err.Clear
        SendMessage ms_LanguageCode, ErrMsgCannotDeleteRecord, "#You cannot delete record. Record is still used in datbase."
        Exit Function
    End Select

    Call ErrorHandler("Proj_Delete")
End Function


Private Sub Proj_AddDb(ByVal al_Cursor As Long, ByVal as_reqTmpl As String, ByVal as_ProjCode As String)
On Error GoTo ErrHandler
Const REQ = "EXEC Cap_Memo_ins 'E', '$Comment_desc$', '$Comment$', 'N', 'N', Null, '$SP_CAPKEY$', '', 1, 0, '$MEM_Code$'"
    
    Dim ls_MEM_Code As String
    Dim ls_req As String
    
    ' common placeholders
    ls_req = Replace(as_reqTmpl, "$Code$", as_ProjCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)

    ls_req = Proj_ReplacePlaceholders(ls_req)
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    
' task 299.3 begin
    ' insert into cap_memo only 'E' language record, memo type=1(spare3_real)
    ls_MEM_Code = mo_Db.SQLNextID("Cap_Memo")
    If ls_MEM_Code = "" Then Call Err.Raise(SQLFailure, "", "SQL Error: mo_ArmDb.SQLNextID(""Cap_Memo"") return nothing.")
    
    ls_req = Replace(REQ, "$SP_CAPKEY$", right("0000000000000000" & as_ProjCode, 16), , , vbTextCompare)
    ls_req = Proj_ReplacePlaceholders(ls_req)
    ls_req = Replace(ls_req, "$MEM_Code$", ls_MEM_Code, , , vbTextCompare)
    Call ExecuteSQLSafe(mo_Db, ls_req, -1)
' task 299.3 end
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Proj_AddDb")
End Sub

Private Sub Proj_UpdateDb(ByVal al_Cursor As Long, ByVal as_reqTmpl As String, ByVal as_ProjCode As String)
' task 299.3
Const REQupd = "EXEC Clm_Sales_Project_comment_upd $Code$, '$Comment$', '$LOGINNAME$'"


On Error GoTo ErrHandler
    Dim ls_req As String
    Dim ll_Cursor  As Long
    
    ' common placeholders
    ls_req = Replace(as_reqTmpl, "$Code$", as_ProjCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
    ls_req = Replace(ls_req, "$iConcurrency$", mo_Db.GetFields(al_Cursor, "iConcurrency"), , , vbTextCompare)

    ls_req = Proj_ReplacePlaceholders(ls_req)
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    
' task 299.3 begin
    ' update cap_memo
    ls_req = Replace(REQupd, "$Code$", as_ProjCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
        ls_req = Proj_ReplacePlaceholders(ls_req)
        Call ExecuteSQLSafe(mo_Db, ls_req, -1)
' task 299.3 end
    
    Exit Sub
ErrHandler:
    If ll_Cursor <> 0 Then Call mo_Db.Close(ll_Cursor)
    Call ErrorHandler("Proj_UpdateDb")
End Sub

Private Sub Proj_DeleteDb(ByVal al_Cursor As Long, ByVal as_reqTmpl As String, ByVal as_ProjCode As String)
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ' common placeholders
    ls_req = Replace(as_reqTmpl, "$Code$", as_ProjCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$LOGINNAME$", SqlStr(ms_LoginName, 15), , , vbTextCompare)
    ls_req = Replace(ls_req, "$iConcurrency$", mo_Db.GetFields(al_Cursor, "iConcurrency"), , , vbTextCompare)

    Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Proj_DeleteDb")
End Sub

' check project selection mod controls
Private Function Proj_Check() As ErrMsg
On Error GoTo ErrHandler

    If txt_SelProjModName.Text = "" Then
        Proj_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(txt_SelProjModName)
        Exit Function
    End If
    
    If txt_SelProjModTown.Text = "" Then
        Proj_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(txt_SelProjModTown)
        Exit Function
    End If
    
    If txt_SelProjModSize.Text = "" Then
        Proj_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(txt_SelProjModSize)
        Exit Function
    End If
    
    If Not IsNumericArm(txt_SelProjModSize.Text) Then
        Proj_Check = ErrMsgNumericRequired
        Call SetFocusToCtrl(txt_ItemClaimSize)
        Exit Function
    End If

    If ToDouble(txt_SelProjModSize.Text) < 0 Then
        Proj_Check = ErrMsgBadValue
        Call SetFocusToCtrl(txt_SelProjModSize)
        Exit Function
    End If

    If cbo_SelProjModUnitMeassure.SelectedItem Is Nothing And ToDouble(txt_SelProjModSize.Text) > 0 Then
        Proj_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(cbo_SelProjModUnitMeassure)
        Exit Function
    End If
    
    If Not cbo_SelProjModUnitMeassure.SelectedItem Is Nothing And ToDouble(txt_SelProjModSize.Text) <= 0 Then
        Proj_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(txt_SelProjModSize)
        Exit Function
    End If
        
    If cbo_SelProjModCountry.SelectedItem Is Nothing Then
        Proj_Check = ErrMsgMandatoryAreEmpty
        Call SetFocusToCtrl(cbo_SelProjModCountry)
        Exit Function
    End If

    Proj_Check = ErrMsgNone
    Exit Function
ErrHandler:
    Call ErrorHandler("Proj_Check")
End Function

' clears selection project mod frame
Private Sub Proj_Clear()
On Error GoTo ErrHandler
    ClearForm UserControl.Controls, GetControl(fra_frames, "fra_SelectProjMod")
    Exit Sub
ErrHandler:
    Call ErrorHandler("Proj_Clear")
End Sub

' loads values to form
Private Sub Proj_LoadValues(ByVal al_Cursor As Long)
On Error GoTo ErrHandler
    Dim lb_clearControls As Boolean
    lb_clearControls = (al_Cursor = -1)
    
    Call mo_Db.First(al_Cursor)

    Call SetTextBoxTextDB(al_Cursor, "SP_Addr1", txt_SelProjModAddress1, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "SP_Addr2", txt_SelProjModAddress2, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "SP_Comment", txt_SelProjModComments, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "SP_desc", txt_SelProjModName, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "SP_Size", txt_SelProjModSize, lb_clearControls, "0", C_NUMERIC_VALUE_FORMAT)
    Call SetTextBoxTextDB(al_Cursor, "SP_Town", txt_SelProjModTown, lb_clearControls)
    Call SetTextBoxTextDB(al_Cursor, "SP_Zip", txt_SelProjModZip, lb_clearControls)
    Call SetComboBoxTextDB(al_Cursor, "CT_code", "CT_desc", cbo_SelProjModCountry, lb_clearControls)
    Call SetComboBoxTextDB(al_Cursor, "UM_code", "UM_desc", cbo_SelProjModUnitMeassure, lb_clearControls)
    Call SetCalendarTextDB(al_Cursor, "SP_StartDate", cal_SelProjModStartDate, lb_clearControls)
    
    If al_Cursor = 0 Then
        Call SetOptionButtonCodeDB(al_Cursor, "", opt_SelectProjLike, True)
'        Call SetComboBoxTextDB(al_Cursor, "", "", cbo_SelectProjCountry, True) ' do not reset country combo
        Call SetTextBoxTextDB(al_Cursor, "", txt_SelectProjLike, True)
        Call grd_SelectProjList.ClearGrid
    End If

    Exit Sub
ErrHandler:
    Call ErrorHandler("Proj_LoadValues")
End Sub

Private Sub Proj_LoadGrid()
Const C_REQ As String = "EXEC Clm_Sales_Project_lst '$Country$', '$Like$', '$LikeType$'"
On Error GoTo ErrHandler
    ' simple check
    If cbo_SelectProjCountry.SelectedItem Is Nothing Then
        Call SetFocusToCtrl(cbo_SelectProjCountry)
        SendMessage ms_LanguageCode, ErrMsgMandatoryAreEmpty, "#Mandatory fields are not filled."
        Exit Sub
    End If

    
    Dim ls_SQL As String
    ls_SQL = Replace(C_REQ, "$Country$", SQLComboBoxValue(cbo_SelectProjCountry, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Like$", SqlStr(txt_SelectProjLike.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$LikeType$", GetOptionButtonCode(opt_SelectProjLike), , , vbTextCompare)
    
    If Not grd_SelectProjList.Load(ls_SQL, False) Then
        Err.Raise CompFncFailed, "grd_SelectProjList.Load", "Grid load failed. SQL: " & ls_SQL
    End If

    Exit Sub
    
ErrHandler:
    Call ErrorHandler("Proj_LoadGrid")
End Sub

Private Sub Proj_CloseCursor()
On Error GoTo ErrHandler
    
    If ml_projCursor > 0 Then
        Call mo_Db.Close(ml_projCursor)
    End If
    ml_projCursor = 0

    Exit Sub
ErrHandler:
    Call ErrorHandler("Proj_CloseCursor")
End Sub

Private Function Proj_ReplacePlaceholders(ByVal as_tmplStr As String) As String
On Error GoTo ErrHandler
    Dim ls_SQL As String

    ls_SQL = Replace(as_tmplStr, "$CTCode$", SQLComboBoxValue(cbo_SelProjModCountry, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$UMCode$", SQLComboBoxValue(cbo_SelProjModUnitMeassure, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Name$", SqlStr(txt_SelProjModName.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$StartDate$", SQLDateTime(cal_SelProjModStartDate.date_dt), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Address1$", SqlStr(txt_SelProjModAddress1.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Address2$", SqlStr(txt_SelProjModAddress2.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Zip$", SqlStr(txt_SelProjModZip.Text, 15), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Town$", SqlStr(txt_SelProjModTown.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Size$", SQLNum(ToDouble(txt_SelProjModSize.Text)), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Comment$", SqlStr(txt_SelProjModComments.Text), , , vbTextCompare)          'taks 299.3
    ls_SQL = Replace(ls_SQL, "$Comment_desc$", SqlStr(txt_SelProjModComments.Text, 80), , , vbTextCompare) 'taks 299.3
    
    Proj_ReplacePlaceholders = ls_SQL
    Exit Function
ErrHandler:
    Call ErrorHandler("Proj_ReplacePlaceholders")
End Function

Private Function Proj_RepositionFilter(ByVal as_Key As String, ByVal as_desc As String) As Boolean
On Error GoTo ErrHandler
    Dim lb_ret As Boolean
    lb_ret = False
    
    ' reposition: check if filter country is set to one we want
    If cbo_SelectProjCountry.SelectedItem Is Nothing Then
        ' select country
        Call SetComboBoxText(cbo_SelectProjCountry, as_Key, as_desc)
        lb_ret = True
    ElseIf cbo_SelectProjCountry.SelectedItem.Key <> as_Key Then
        ' select country
        Call SetComboBoxText(cbo_SelectProjCountry, as_Key, as_desc)
        lb_ret = True
    End If
    Proj_RepositionFilter = lb_ret
    Exit Function
ErrHandler:
    Call ErrorHandler("Proj_RepositionFilter")
End Function

' ********************** PROJECT FRAMEWORK FUNCTIONS ********************************

' ************************************************************************************
' ******************** SELECT ITEM FRAMEWORK FUNCTIONS *******************************
' ************************************************************************************
' inititialize select item
Private Sub SelI_SelectInit()
On Error GoTo ErrHandler
    ' clearing form
    Call ResetScreen(ArmScreenMode.smItemMain)
    Call SelI_Clear
    Call SelI_LoadValues        ' reset main screen of Item
    
    Call UpdateUI(ArmScreenMode.smItemMain)
    Exit Sub
ErrHandler:
    Call ErrorHandler("SelI_SelectInit")
End Sub

Private Function SelI_Select() As Variant
On Error GoTo ErrHandler
    ' check values and throw message if neccessary
    If grd_SelectItemList.SelectedCount = 0 Then
        SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
    Else
        SelI_Select = grd_SelectItemList.SelectedKey(0)
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("SelI_Select")
End Function

' clears selection item mod frame
Private Sub SelI_Clear()
On Error GoTo ErrHandler
    ClearForm UserControl.Controls, GetControl(fra_frames, "fra_ClaimSelectItem")
    Exit Sub
ErrHandler:
    Call ErrorHandler("SelI_Clear")
End Sub

Private Sub SelI_LoadGrid()
Const C_REQ As String = "EXEC Clm_Base_Item_lst2 $CodeLevel$, '$LangCode$', '$Type$', '$DropStatus$', '$CategoryCode$', '$BaseMatCode$', '$FamilyCode$', '$ColourCode$', '$PatternCode$', '$RangeCode$', '$EdgeCode$', '$SurfaceCode$', '$ShapeCode$', '$DimensionsCode$', '$ItemSAP$', '$ItemShort$'"
On Error GoTo ErrHandler
    
    If SQLComboBoxValue(cbo_SelectItemBaseMaterial, "") = "" Then grd_SelectItemList.Columns("BML_Desc").Width = 1500 Else grd_SelectItemList.Columns("BML_Desc").Width = 0
    If SQLComboBoxValue(cbo_SelectItemFamily, "") = "" Then grd_SelectItemList.Columns("PF_Desc").Width = 1200 Else grd_SelectItemList.Columns("PF_Desc").Width = 0
    If SQLComboBoxValue(cbo_SelectItemColour, "") = "" Then grd_SelectItemList.Columns("COLOUR_Desc").Width = 700 Else grd_SelectItemList.Columns("COLOUR_Desc").Width = 0
    If SQLComboBoxValue(cbo_SelectItemPattern, "") = "" Then grd_SelectItemList.Columns("PP_Desc").Width = 800 Else grd_SelectItemList.Columns("PP_Desc").Width = 0
    If SQLComboBoxValue(cbo_SelectItemProductRange, "") = "" Then grd_SelectItemList.Columns("PS_Desc").Width = 1100 Else grd_SelectItemList.Columns("PS_Desc").Width = 0
    If SQLComboBoxValue(cbo_SelectItemEdgeDetail, "") = "" Then grd_SelectItemList.Columns("PE_Desc").Width = 900 Else grd_SelectItemList.Columns("PE_Desc").Width = 0
    If SQLComboBoxValue(cbo_SelectItemSurface, "") = "" Then grd_SelectItemList.Columns("SF_Desc").Width = 900 Else grd_SelectItemList.Columns("SF_Desc").Width = 0
    If SQLComboBoxValue(cbo_SelectItemShape, "") = "" Then grd_SelectItemList.Columns("SH_Desc").Width = 1000 Else grd_SelectItemList.Columns("SH_Desc").Width = 0
    If SQLComboBoxValue(cbo_SelectItemDimensions, "") = "" Then grd_SelectItemList.Columns("PD_Desc").Width = 1500 Else grd_SelectItemList.Columns("PD_Desc").Width = 0

    Dim ls_SQL As String
    ls_SQL = Replace(C_REQ, "$CodeLevel$", "0", , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$LangCode$", ms_LanguageCode, , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Type$", GetOptionButtonCode(opt_SelectItemType), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$DropStatus$", GetOptionButtonCode(opt_SelectItemStatus), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$CategoryCode$", SQLComboBoxValue(cbo_SelectItemCategory, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$BaseMatCode$", SQLComboBoxValue(cbo_SelectItemBaseMaterial, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$FamilyCode$", SQLComboBoxValue(cbo_SelectItemFamily, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$ColourCode$", SQLComboBoxValue(cbo_SelectItemColour, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$PatternCode$", SQLComboBoxValue(cbo_SelectItemPattern, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$RangeCode$", SQLComboBoxValue(cbo_SelectItemProductRange, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$EdgeCode$", SQLComboBoxValue(cbo_SelectItemEdgeDetail, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$SurfaceCode$", SQLComboBoxValue(cbo_SelectItemSurface, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$ShapeCode$", SQLComboBoxValue(cbo_SelectItemShape, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$DimensionsCode$", SQLComboBoxValue(cbo_SelectItemDimensions, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$ItemSAP$", SqlStr(txt_SelectItemClsItemNo.Text, 20), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$ItemShort$", "", , , vbTextCompare)

    
    If Not grd_SelectItemList.Load(ls_SQL, False) Then
        Err.Raise CompFncFailed, "grd_SelectItemList.Load", "Grid load failed. SQL: " & ls_SQL
    End If

    Exit Sub
    
ErrHandler:
    Call ErrorHandler("SelI_LoadGrid")
End Sub

Private Function SelI_ReplacePlaceholders(ByVal as_tmplStr As String) As String
On Error GoTo ErrHandler
    Dim ls_SQL As String

    ls_SQL = Replace(as_tmplStr, "$CTCode$", SQLComboBoxValue(cbo_SelProjModCountry, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$UMCode$", SQLComboBoxValue(cbo_SelProjModUnitMeassure, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Name$", SqlStr(txt_SelProjModName.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$StartDate$", SQLDateTime(cal_SelProjModStartDate.date_dt), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Address1$", SqlStr(txt_SelProjModAddress1.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Address2$", SqlStr(txt_SelProjModAddress2.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Zip$", SqlStr(txt_SelProjModZip.Text, 15), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Town$", SqlStr(txt_SelProjModTown.Text, 80), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Size$", SQLNum(ToDouble(txt_SelProjModSize.Text)), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Comment$", SqlStr(txt_SelProjModComments.Text, 254), , , vbTextCompare)
    
    SelI_ReplacePlaceholders = ls_SQL
    Exit Function
ErrHandler:
    Call ErrorHandler("SelI_ReplacePlaceholders")
End Function

' loads values to form
Private Sub SelI_LoadValues()
On Error GoTo ErrHandler

    Call SetOptionButtonCodeDB(0, "", opt_SelectItemType, True)
    Call SetOptionButtonCodeDB(0, "", opt_SelectItemStatus, True)
    Call SetComboBoxText(cbo_SelectItemCategory, "", "")
    Call SetComboBoxText(cbo_SelectItemColour, "", "")
    Call SetComboBoxText(cbo_SelectItemBaseMaterial, "", "")
    Call SetComboBoxText(cbo_SelectItemPattern, "", "")
    Call SetComboBoxText(cbo_SelectItemFamily, "", "")
    Call SetComboBoxText(cbo_SelectItemProductRange, "", "")
    Call SetComboBoxText(cbo_SelectItemSurface, "", "")
    Call SetComboBoxText(cbo_SelectItemEdgeDetail, "", "")
    Call SetComboBoxText(cbo_SelectItemShape, "", "")
    Call SetComboBoxText(cbo_SelectItemDimensions, "", "")
    Call SetTextBoxTextDB(0, "", txt_SelectItemClsItemNo, True)
    Call grd_SelectItemList.ClearGrid

    Exit Sub
ErrHandler:
    Call ErrorHandler("SelI_LoadValues")
End Sub

Private Sub SelI_UpdateFilters()
On Error GoTo ErrHandler
  
    grd_SelectItemList.ClearGrid
    Dim ls_SQL As String
    ls_SQL = "'$LangCode$', '$Type$', '$DropStatus$', '$CategoryCode$', '$BaseMatCode$', '$FamilyCode$', '$ColourCode$', '$PatternCode$', '$RangeCode$', '$EdgeCode$', '$SurfaceCode$', '$ShapeCode$', '$DimensionsCode$'"
    ls_SQL = Replace(ls_SQL, "$LangCode$", ms_LanguageCode, , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$Type$", GetOptionButtonCode(opt_SelectItemType), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$DropStatus$", GetOptionButtonCode(opt_SelectItemStatus), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$CategoryCode$", SQLComboBoxValue(cbo_SelectItemCategory, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$BaseMatCode$", SQLComboBoxValue(cbo_SelectItemBaseMaterial, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$FamilyCode$", SQLComboBoxValue(cbo_SelectItemFamily, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$ColourCode$", SQLComboBoxValue(cbo_SelectItemColour, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$PatternCode$", SQLComboBoxValue(cbo_SelectItemPattern, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$RangeCode$", SQLComboBoxValue(cbo_SelectItemProductRange, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$EdgeCode$", SQLComboBoxValue(cbo_SelectItemEdgeDetail, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$SurfaceCode$", SQLComboBoxValue(cbo_SelectItemSurface, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$ShapeCode$", SQLComboBoxValue(cbo_SelectItemShape, ""), , , vbTextCompare)
    ls_SQL = Replace(ls_SQL, "$DimensionsCode$", SQLComboBoxValue(cbo_SelectItemDimensions, ""), , , vbTextCompare)
    
    
    cbo_SelectItemColour.Request = "exec colours_cbo3 " & ls_SQL
    cbo_SelectItemDimensions.Request = "exec Product_Dimension_cbo4 " & ls_SQL
    cbo_SelectItemEdgeDetail.Request = "exec Products_Edges_cbo3 " & ls_SQL
    cbo_SelectItemFamily.Request = "exec Products_Families_cbo4 " & ls_SQL
    cbo_SelectItemPattern.Request = "exec Products_Patterns_cbo3 " & ls_SQL
    cbo_SelectItemProductRange.Request = "exec Products_Segmentation_cbo3 " & ls_SQL
    cbo_SelectItemShape.Request = "exec Shapes_cbo2 " & ls_SQL
    cbo_SelectItemSurface.Request = "exec Surfaces_cbo3 " & ls_SQL


    Exit Sub
ErrHandler:
    Call ErrorHandler("SelI_UpdateFilters")
End Sub


' ******************** SELECT ITEM FRAMEWORK FUNCTIONS *******************************

' ************************************************************************************
' **************************** DB-ACCESS FUNCTIONS ***********************************
' ************************************************************************************
' Return the result of a SQL request
' Convert SQL runtime errors and process errors to VB Error
#If LIVE = 1 Then
Private Function OpenSQLSafe(ByVal ao_Db As Object, ByVal as_Request As String, Optional ByVal au_SQLResultType As ArmSQLResultType = ArmSQLAny, Optional ByVal al_RowExpectedCount = -1) As Long
#Else
Private Function OpenSQLSafe(ByVal ao_Db As ARMSYSCOMLib.ArmDb, ByVal as_Request As String, Optional ByVal au_SQLResultType As ArmSQLResultType = ArmSQLAny, Optional ByVal al_RowExpectedCount = -1) As Long
#End If

On Error GoTo ErrHandler

    Dim lc_Data As Long
    lc_Data = ao_Db.OpenSQL(as_Request)
    
    If lc_Data = 0 Then
        Err.Raise ArmErr.SQLFailure, "SQL : " & as_Request, Join(ao_Db.SQLErrorCodes, SEP2) & SEP1 & Join(ao_Db.SQLErrorMessages, SEP2)
    End If
    
    Select Case au_SQLResultType
        Case ArmSQLExactOne
            If ao_Db.RowCount(lc_Data) <> 1 Then
                Err.Raise ArmErr.SQLBadRowExpectedCount, "SQL : " & as_Request, "doesn't match count rule 1..1 with result count: " & ao_Db.RowCount(lc_Data)
            End If
        Case ArmSQLMaxOne
            If ao_Db.RowCount(lc_Data) <> 1 And ao_Db.RowCount(lc_Data) <> 0 Then
                Err.Raise ArmErr.SQLBadRowExpectedCount, "SQL : " & as_Request, "doesn't match count rule 0..1 with result count: " & ao_Db.RowCount(lc_Data)
            End If
        Case ArmSQLAtLeastOne
            If ao_Db.RowCount(lc_Data) < 1 Then
                Err.Raise ArmErr.SQLBadRowExpectedCount, "SQL : " & as_Request, "doesn't match count rule 1..N with result count: " & ao_Db.RowCount(lc_Data)
            End If
        Case ArmSQLAny
            If al_RowExpectedCount <> -1 Then
                ' Then check the rowcount
                If ao_Db.RowCount(lc_Data) <> al_RowExpectedCount Then
                    Err.Raise ArmErr.SQLBadRowExpectedCount, "SQL : " & as_Request, al_RowExpectedCount & "<>" & ao_Db.RowCount(lc_Data)
                End If
            End If
    End Select
  

    OpenSQLSafe = lc_Data

    Exit Function

ErrHandler:
    If lc_Data <> 0 Then
        Call ao_Db.Close(lc_Data)
        lc_Data = 0
    End If
    
    Call ErrorHandler("OpenSQLSafe")
End Function


' Execute a SQL request returning no data
' Convert SQL runtime errors and process errors to VB Error
' Params:
' ao_Db (Object)
' as_Request (String)
' al_RowAffectedCount (String)
#If LIVE = 1 Then
Private Sub ExecuteSQLSafe(ByVal ao_Db As Object, ByVal as_Request As String, Optional ByVal al_RowAffectedCount = -1, Optional ab_DuplicityCheck As Boolean = False)
#Else
Private Sub ExecuteSQLSafe(ByVal ao_Db As ARMSYSCOMLib.ArmDb, ByVal as_Request As String, Optional ByVal al_RowAffectedCount = -1, Optional ab_DuplicityCheck As Boolean = False)
#End If
On Error GoTo ErrHandler

    ' First execute the request
    If Not ao_Db.ExecuteSQL(as_Request) Then
        If GetArrayValue(ao_Db.SQLErrorCodes, 0) = 547 Then
            Err.Raise ArmErr.SQLTableReferenceConstraint, "SQL : " & as_Request, Join(ao_Db.SQLErrorCodes, SEP2) & SEP1 & Join(ao_Db.SQLErrorMessages, SEP2)
        End If
        Err.Raise ArmErr.SQLFailure, "SQL : " & as_Request, Join(ao_Db.SQLErrorCodes, SEP2) & SEP1 & Join(ao_Db.SQLErrorMessages, SEP2)
    End If

    If al_RowAffectedCount <> -1 Then
        ' Then check the rowcount
        If ao_Db.SQLRowsAffected <> al_RowAffectedCount Then
            
            If ab_DuplicityCheck Then
                Err.Raise ArmErr.DuplicityDetected, "SQL : " & as_Request, al_RowAffectedCount & "<>" & ao_Db.SQLRowsAffected
            Else
                Err.Raise ArmErr.SQLBadRowAffectedCount, "SQL : " & as_Request, al_RowAffectedCount & "<>" & ao_Db.SQLRowsAffected
            End If
        End If
    End If
    
    Exit Sub

ErrHandler:
    Call ErrorHandler("ExecuteSQLSafe")
End Sub

Private Function SqlStr(ByVal as_str As String, Optional ByVal al_MaxLen As Long = 8000) As String
    SqlStr = Replace(Left(as_str, IIf(Len(as_str) <= al_MaxLen, Len(as_str), al_MaxLen)), "'", "''")
End Function

' tranlate date to sql format
' Params:
' ad_Date (Date)
Private Function SQLDateTime(ad_Date As Date) As String
On Error GoTo ErrHandler
  If ad_Date = 0 Then
    SQLDateTime = "Null"
  Else
    SQLDateTime = "{ ts '" & Format(ad_Date, "yyyy-mm-dd hh:mm:ss") & "'}"
  End If
    Exit Function
ErrHandler:
     Call ErrorHandler("SQLDateTime")
End Function

' safe retieving selected item from combobox
Private Function SQLComboBoxValue(ByRef ao_Combobox As ArmCombobox, Optional ByVal as_DefaultValue As String = "NULL", Optional ByVal ab_KeyTitle As Boolean = True) As String
On Error GoTo ErrHandler
    If IsComboboxSelected(ao_Combobox) Then
        SQLComboBoxValue = IIf(ab_KeyTitle, ao_Combobox.SelectedItem.Key, ao_Combobox.SelectedItem.DisplayText)
    Else
        SQLComboBoxValue = as_DefaultValue
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("SQLComboBoxValue")
End Function

Private Function SQLNum(ByVal av_Value As Double) As String
On Error GoTo ErrHandler

  SQLNum = Str(av_Value)
  Exit Function
ErrHandler:
  Call ErrorHandler("SQLNum")
End Function
' **************************** DB-ACCESS FUNCTIONS ***********************************


' ************************************************************************************
' ***************************** PRINTER FUNCTIONS ************************************
' ************************************************************************************
Public Sub InitPrinter(ByVal li_Landscape As Integer)
On Error GoTo ErrHandler
    Dim Xlast As Integer
    Dim Ylast As Integer
    
    ' init paper orientation
    ' 2 means landscape
    On Error Resume Next
    Printer.Orientation = li_Landscape
    If li_Landscape = 1 Then
        mi_LCurrPaper = 100
'        msng_ScreenToPrinter = 108.48
    Else
        If Printer.PaperSize = 1 Then
            mi_LCurrPaper = 135
'            msng_ScreenToPrinter = 108.48
        Else
            mi_LCurrPaper = 145
'            msng_ScreenToPrinter = 108.48
        End If
    End If
    
    ' init resolution
    Printer.Scale (0, 0)-(C_Scalewidth, C_ScaleHeight)
    SetFontName "Arial"
    SetFontSize 12

    Exit Sub
ErrHandler:
    Call ErrorMessage("PrintBold")
End Sub

Public Sub PrintBold(ByVal ls_Field As String)
On Error GoTo ErrHandler
    ' print a text in bold
    Printer.Font.Bold = True
    Printer.Print ls_Field;
    Printer.Font.Bold = False
    Exit Sub
ErrHandler:
    Call ErrorMessage("PrintBold")
End Sub
Public Sub SetFontName(ByVal ls_Name As String)
Dim Xlast As Integer
Dim Ylast As Integer

'Change the printer font
Printer.Font.Name = ls_Name
'calcul the new height of the font in the printer scale
Xlast = Printer.CurrentX
Ylast = Printer.CurrentY
Printer.Print ""
'mi_FontHeight = Printer.CurrentY - Ylast
Printer.CurrentX = Xlast
Printer.CurrentY = Ylast
'change the font of the label used to calcul the size of a text
'FrmMain.Lbl_ForPrinter.Font.Name = ls_Name

End Sub

Public Sub SetBold(ByVal lb_Flag As Boolean)

'Change the printer font
Printer.Font.Bold = lb_Flag

'change the font of the label used to calcul the size of a text
'FrmMain.Lbl_ForPrinter.Font.Bold = lb_Flag

End Sub
Public Sub SetFontSize(ByVal li_size As Integer)
Dim Xlast As Integer
Dim Ylast As Integer

'Change the printer font size
Printer.Font.Size = li_size
'calcul the new height of the font in the printer scale
Xlast = Printer.CurrentX
Ylast = Printer.CurrentY
Printer.Print ""
'mi_FontHeight = Printer.CurrentY - Ylast
Printer.CurrentX = Xlast
Printer.CurrentY = Ylast
'FrmMain.Lbl_ForPrinter.Font.Size = li_size

End Sub

Public Sub PrintMultiLine(ByVal ls_Field As String)
Dim li_Numchar As Integer
Dim c As String
Dim i As Integer
For li_Numchar = 1 To Len(ls_Field)
    If Printer.CurrentX > (C_Scalewidth - 104) Then
        Printer.Print ""
    End If
    c = Mid(ls_Field, li_Numchar, 1)
    If Asc(c) <> 10 Then
        Printer.Print c;
    End If
Next li_Numchar
Printer.Print ""

End Sub
Function TruncField(ByVal ls_Field As String, ByVal li_Long As Integer) As String
Dim ls_TempField As String

' mi_ScreenToPrinter est la taille estimé en nombre de pixel du label lbl_ForPrinter d'une colonne sur l'imprimante (pour une page en landscape divise en 145 colonnes)
If li_Long = 0 Then
    TruncField = ""
Else
'    FrmMain.Lbl_ForPrinter.Caption = ls_Field
'    '(mi_Scalewidth / mi_LCurrPaper)
'    While FrmMain.Lbl_ForPrinter.Width > ((msng_ScreenToPrinter * li_Long) - msng_ScreenToPrinter / (mi_Scalewidth / mi_LCurrPaper) * mi_CellMargin)
'        FrmMain.Lbl_ForPrinter.Caption = Left(FrmMain.Lbl_ForPrinter.Caption, Len(FrmMain.Lbl_ForPrinter.Caption) - 1)
'    Wend
'    TruncField = FrmMain.Lbl_ForPrinter.Caption
    ls_TempField = ls_Field
    While (Printer.TextWidth(ls_TempField) > ((C_Scalewidth / mi_LCurrPaper) * li_Long - 2 * C_CellMargin)) And (Len(ls_TempField) > 0)
        ls_TempField = Left(ls_TempField, Len(ls_TempField) - 1)
    Wend
    TruncField = ls_TempField
End If

End Function

Private Function FormatDateTime(ByVal av_val As Variant) As String
On Error GoTo ErrHandler
        FormatDateTime = IIf(av_val = 0, "", Format(av_val, "dd\/mm\/yyyy"))
    Exit Function
ErrHandler:
    Call ErrorHandler("FormatDateTime")
End Function


' ***************************** PRINTER FUNCTIONS ************************************

' ************************************************************************************
' *************************** INTERNATIONAL FUNCTIONS ********************************
' ************************************************************************************

Private Function OpenCodePageCursor(ByRef ao_Armdb As Object) As Long
On Error GoTo ErrHandler
Const C_REQ As String = "SELECT Language_code, Code_Page FROM Language"
    Dim ll_Cursor As Long
    
    ll_Cursor = OpenSQLSafe(ao_Armdb, C_REQ)
    Debug.Assert (ll_Cursor <> 0)
    
    OpenCodePageCursor = ll_Cursor
    Exit Function
ErrHandler:
    Call ErrorHandler("LoadCodePageCursor")
End Function

Private Function GetCodePageFromLanguage(ByVal al_codePageCursor As Long, ByVal as_Language As String) As Long
On Error GoTo ErrHandler
    Debug.Assert (al_codePageCursor <> 0)
    Dim ll_codePage As Long
    
    If mo_Db.Find(al_codePageCursor, "Language_code", as_Language) > -1 Then
        ll_codePage = CLng(mo_Db.GetFields(al_codePageCursor, "Code_Page"))
    Else
        ll_codePage = 0
    End If
    
    GetCodePageFromLanguage = ll_codePage
    Exit Function
ErrHandler:
    Call ErrorHandler("GetCodePageFromLanguage()")
End Function


'convert code page into charset integer
Private Function GetCharSetFromCodePage(ByVal al_CodePage As Long) As Long

On Error GoTo ErrHandler

    Select Case CStr(al_CodePage)
        Case 932 ' Japanese
            GetCharSetFromCodePage = 128
        Case 936 ' Simplified Chinese
            GetCharSetFromCodePage = 134
        Case 949 ' Korean
            GetCharSetFromCodePage = 129
        Case 950 ' Traditional Chinese
            GetCharSetFromCodePage = 136
        Case 1250 ' Eastern Europe
            GetCharSetFromCodePage = 238
        Case 1251 ' Russian
            GetCharSetFromCodePage = 204
        Case 1252 ' Western European Languages
            GetCharSetFromCodePage = 0
        Case 1253 ' Greek
            GetCharSetFromCodePage = 161
        Case 1254 ' Turkish
            GetCharSetFromCodePage = 162
        Case 1255 ' Hebrew
            GetCharSetFromCodePage = 177
        Case 1256 ' Arabic
            GetCharSetFromCodePage = 178
        Case 1257 ' Baltic
            GetCharSetFromCodePage = 186
        Case Else
            GetCharSetFromCodePage = 0
    End Select
    
    Exit Function
    
ErrHandler:
    Call ErrorHandler("GetCharSetFromCodePage()")
End Function


Private Sub ChangeCharset(ByRef ao_Container As Object, Optional ByVal aCodePage As Long)

On Error GoTo ErrHandler
   
    Dim lc_Control As Control
    Dim ll_Charset As Long
    
    On Error Resume Next
    ll_Charset = GetCharSetFromCodePage(aCodePage)
    
    For Each lc_Control In ao_Container
        Select Case UCase(TypeName(lc_Control))
        Case "TABSTRIP", "TEXTBOX", "LABEL", "FRAME", "COMMANDBUTTON", _
              "LISTVIEW", "CHECKBOX", "OPTIONBUTTON", _
              "ARMCHECKVIEW", "ARMTREEVIEW", "ARMGRID", "ARMCOMBOBOX", "ARMCHECKVIEW0"
            lc_Control.Font.Name = "Arial"
            lc_Control.Font.Charset = ll_Charset
        Case "A_SEEK", "A_SRCHTXT"
            lc_Control.Charset = ll_Charset
        End Select
    Next
    
    Exit Sub

ErrHandler:
    Call ErrorHandler("ChangeCharset")
End Sub
' ************************************************************************************


Private Sub btn_closeLinkedEmails_Click()
    frm_linkedFiles.Visible = False
End Sub


Private Function ShowMsg(ByVal al_ZipTableIndex As Long, ByVal as_fileName) As Boolean
On Error GoTo ErrHandler

Dim ls_TempDir As String
Dim lo_shell As Object

    ShowMsg = False
    If MsgBox(MsgText(ms_LanguageCode, 5170, "Are you sure to download outlook message file ? Operation can take long time"), vbYesNo) = vbNo Then Exit Function
    
    Dim lo_FSO  As Object
    Set lo_FSO = CreateObject("Scripting.FileSystemObject")
    
    ls_TempDir = GetTempDir()
    If Not lo_FSO.FolderExists(ls_TempDir) Then
      Call lo_FSO.CreateFolder(ls_TempDir)
    End If
    If DownloadMSGToFile(al_ZipTableIndex, ls_TempDir & "\" & as_fileName, lo_FSO) Then
        Set lo_shell = CreateObject("Shell.Application")
        Call lo_shell.ShellExecute(ls_TempDir & "\" & as_fileName, "", "", "open", 1)
        Set lo_shell = Nothing
        ShowMsg = True
    End If
    
    Set lo_FSO = Nothing
    Exit Function
ErrHandler:
    Call ErrorHandler("ShowMSG")
End Function

Private Function DownloadMSGToFile(ByVal al_ZipTableIndex As Long, ByVal as_fileName As String, ByRef ao_FSO As Object) As Boolean
On Error GoTo ErrHandler

Dim ll_Index As Long
Dim ls_RequestSel As String
Dim ls_RequestIns As String
Dim ls_Filename As String

    DownloadMSGToFile = False
    If ao_FSO.FileExists(as_fileName) Then
        If Not DeleteFile(as_fileName) Then
            Exit Function
        End If
    End If
    
    ls_RequestSel = "SELECT CLA_ZIP FROM Claim_LinkedFileZip WHERE CLA_ZIP_ID=$CLA_ZIP_ID$"
    ls_RequestSel = Replace(ls_RequestSel, "$CLA_ZIP_ID$", al_ZipTableIndex, , , vbTextCompare)
    
    If Not mo_Db.BlobToFileSQL(ls_RequestSel, as_fileName, True, False) Then
        Err.Raise ArmErr.CompFncFailed, "FileToBlobSQL", mo_Db.LastErrorMessage & " Error writing blob: " & ls_RequestSel & " File: " & ls_Filename
    End If
    DownloadMSGToFile = True
    Exit Function
ErrHandler:
    Call ErrorHandler("DownloadMSGToFile as_FileName=" & _
                               " CLA_ZIP_ID=" & al_ZipTableIndex)
End Function


Private Function GetTempDir() As String
Dim ls_Buff As String, ll_Count As Long

On Error GoTo ErrHandler
    ls_Buff = SPACE(4096)
    ll_Count = GetTempPath(4096, ls_Buff)
    
    ls_Buff = Left(ls_Buff, ll_Count)
    'this function can return path with trailing "\" character - strip it
    If ll_Count > 0 Then
      If right(ls_Buff, 1) = "\" Then
       ls_Buff = Left(ls_Buff, ll_Count - 1)
      End If
    End If
    GetTempDir = ls_Buff
  Exit Function
ErrHandler:
  Call ErrorHandler("GetTempDir")
End Function


Private Sub btn_deleteLinkedEmails_Click()
On Error GoTo ErrHandler
    If grd_linkedFiles.SelectedCount = 0 Then Exit Sub
    Call LockScreen(True)
    
    If SendMessage(ms_LanguageCode, ErrMsg_M360, "#Do you really want to delete this record.", "", vbQuestion + vbYesNo) = vbYes Then
        Call DeleteLinkedFile
    End If

    Call LockScreen(False)
    
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    ErrorMessage ("btn_deleteLinkedEmails_Click")
End Sub


Private Sub grd_linkedFiles_ItemSelected()
On Error GoTo ErrHandler
    Call LockScreen(True)
    ' Open selected message in outlook application
    
    Call ShowMsg(grd_linkedFiles.SelectedLine(0, "CLA_ZIP_ID"), grd_linkedFiles.SelectedLine(0, "FILE_Name"))
    Call LockScreen(False)
    Exit Sub
    
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("grd_linkedFiles_ItemSelected")
End Sub

' ************************************************************************************
' ******************************** EVENTS HANDLERS ***********************************
' ************************************************************************************
Private Sub tbs_ClaimTabs_Click(Index As Integer)
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    
    Call LockScreen(True)
    Dim ll_detTabIndex As Long
    ll_detTabIndex = CLng(Mid(tbs_ClaimTabs(Index).SelectedItem.Key, 2))
    
    If ml_DetailCursor(ll_detTabIndex) = 0 Then
        ' reset detail
        Debug.Assert (txt_GenReport.Text <> "")
        Debug.Assert (ml_detailIconcurrencyCursor <> 0)
        ' it is possible to load data into tab
        Call Item_LoadDB(ml_DetailCursor(ll_detTabIndex), ml_detailIconcurrencyCursor, _
                            ms_detailRequests(ll_detTabIndex), _
                            txt_GenReport.Text)
        Call Item_LoadValues(ml_DetailCursor(ll_detTabIndex))
        Call Item_ApplyLogic(activeScreenMode)
    End If

    Call UpdateTabStrip(tbs_ClaimTabs(Index), fra_detailFrames)

    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("tbs_ClaimTabs_Click")
End Sub

Private Sub tbs_CustTabs_Click()
On Error GoTo ErrHandler
    Call LockScreen(True)
    
    Call UpdateTabStrip(tbs_CustTabs, fra_CustTabs)

    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("tbs_CustTabs_Click")
End Sub

Private Sub opt_SearchView_Click(Index As Integer)
On Error GoTo ErrHandler
    If mb_Initializing Then
        Exit Sub
    End If
    Call LockScreen(True)
    
    tvw_SearchList.Visible = False
    Call tvw_SearchList.Clear
    Call grd_ClaimMain.ClearGrid
    pic_ReloadSearch.Visible = True
    
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("opt_SearchView_Click")
End Sub

Private Sub opt_SearchFilter_Click(Index As Integer)
On Error GoTo ErrHandler
    If mb_Initializing Then
        Exit Sub
    End If
    Call LockScreen(True)
    
    tvw_SearchList.Visible = False
    Call tvw_SearchList.Clear
    Call grd_ClaimMain.ClearGrid
    pic_ReloadSearch.Visible = True
    
    ' set enabled/disabled calendar
    Call SetEnabledCtrl(cal_FilterAnyUpdated, GetOptionButtonCode(opt_SearchFilter, "A") = "D")
    If Not cal_FilterAnyUpdated.Enabled Then Call cal_FilterAnyUpdated.reinit_cal
    
    
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("opt_SearchView_Click")
End Sub

Private Sub cal_FilterAnyUpdated_datechangee()
On Error GoTo ErrHandler
    If mb_Initializing Or (Int(md_actSelectedFilterDate) - Int(cal_FilterAnyUpdated.date_dt) = 0) Then Exit Sub
    md_actSelectedFilterDate = cal_FilterAnyUpdated.date_dt
    Call LockScreen(True)

    If GetOptionButtonCode(opt_SearchFilter) = "D" Then
        tvw_SearchList.Visible = False
        Call tvw_SearchList.Clear
        Call grd_ClaimMain.ClearGrid
        pic_ReloadSearch.Visible = True
    End If
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cal_FilterAnyUpdated_datechangee")
End Sub

Private Sub pic_ReloadSearch_Click()
On Error GoTo ErrHandler
    Call LockScreen(True)
    
    pic_ReloadSearch.Visible = False
    Call loadSearchTreeView(tvw_SearchList, GetOptionButtonCode(opt_SearchView), IIf(GetOptionButtonCode(opt_SearchFilter) = "D", cal_FilterAnyUpdated.date_dt, 0))
    tvw_SearchList.Visible = True
    
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("pic_ReloadSearch_Click")
End Sub

Private Sub tlb_CostNoteTasks_action(ByVal as_Role As String, as_Language As String)
On Error GoTo ErrHandler
    Dim lo_ctrl As Control
    Call LockScreen(True)
    Select Case as_Role
        Case "A" ' add mode
            Call Note_AddInit
        Case "B" ' update mode
            If grd_CostNotes.SelectedCount = 0 Then
                SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
            Else
                Debug.Assert (txt_GenReport.Text <> "")
                Call Note_UpdateInit(txt_GenReport.Text, grd_CostNotes.SelectedKey(0)(0))
            End If
        Case "C" ' delete mode
            If grd_CostNotes.SelectedCount = 0 Then
                SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
            Else
                Debug.Assert (txt_GenReport.Text <> "")
                Call Note_DeleteInit(txt_GenReport.Text, grd_CostNotes.SelectedKey(0)(0))
            End If
        Case "T" ' exit to previous screen mode
            Select Case activeScreenMode
                Case smNotesAdd, smNotesUpdate, smNotesDelete
                    Call Note_CloseCursor
                    
                    grd_CostNotes.Enabled = True
                    For Each lo_ctrl In tbs_ClaimTabs
                        lo_ctrl.Enabled = True
                    Next
                    
                    ' pop screen mode
                    Call popScreenMode
                    
                    Call UpdateUI
                Case Else
                    Debug.Assert (False)
            End Select
        Case "H" ' confirm
            Dim lv_itemKey As Variant
            
            Select Case activeScreenMode
                Case smNotesUpdate
                    lv_itemKey = Note_Update(txt_GenReport.Text, grd_CostNotes.SelectedKey(0)) ' update existing note
                Case smNotesAdd
                    lv_itemKey = Note_Add(txt_GenReport.Text) ' store new note
                Case smNotesDelete
                    lv_itemKey = Note_Delete(txt_GenReport.Text, grd_CostNotes.SelectedKey(0)) ' delete existing note
                Case Else
                    Debug.Assert (False)
            End Select
            If Not IsEmpty(lv_itemKey) Then
                Call Item_ExitToGrid(grd_CostNotes, lv_itemKey)
                Call Item_ApplyLogic(activeScreenMode)
            End If

        Case "I" ' restore values
            Select Case activeScreenMode
                Case smNotesAdd, smNotesUpdate
                    Call Note_LoadValues(ml_notesCursor)
                Case Else
                    Debug.Assert (False)
            End Select
    End Select

    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("tlb_main_action")
End Sub

Private Sub tlb_Main_action(ByVal as_Role As String, as_Language As String)
On Error GoTo ErrHandler
    Dim lv_itemKey As Variant

    Call LockScreen(True)
    Select Case as_Role
        Case "A" ' add mode
            Select Case activeScreenMode
                Case smMain
                    Call Item_AddInit
                Case smView
                    ' close detail cursors
                    Call Item_CloseCursors
                    ' pop screen mode
                    Call popScreenMode
                    Call tlb_Main_action(as_Role, as_Language)
                Case smMemoMain
                    Call Memo_AddInit
                Case smCustMain
                    Call Cust_AddInit
                Case smProjMain
                    Call Proj_AddInit
                Case Else
                    Debug.Assert (False)
            End Select
        Case "B" ' update mode
            Select Case activeScreenMode
                Case smMain
                    If grd_ClaimMain.SelectedCount = 0 Then
                        Call SendMessage(ms_LanguageCode, WarMsgSelectRow, "#Please select a row.")
                    Else
                        Call Item_UpdateInit(grd_ClaimMain.SelectedKey(0), grd_ClaimMain.SelectedLine(0, "CSA_function"))
                    End If
                Case smView
                    ' close detail cursors
                    Call Item_CloseCursors
                    ' pop screen mode
                    Call popScreenMode
                    Call tlb_Main_action(as_Role, as_Language)
                Case smMemoMain
                    If grd_ClaimMemoList.SelectedCount = 0 Then
                        Call SendMessage(ms_LanguageCode, WarMsgSelectRow, "#Please select a row.")
                    Else
                        Call Memo_UpdateInit(grd_ClaimMemoList.SelectedKey(0)(0))
                    End If
                Case smCustMain
                    If grd_SelectCustList.SelectedCount = 0 Then
                        SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
                    Else
                        Call Cust_UpdateInit(grd_SelectCustList.SelectedKey(0)(0))
                    End If
                Case smProjMain
                    If grd_SelectProjList.SelectedCount = 0 Then
                        SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
                    Else
                        Call Proj_UpdateInit(grd_SelectProjList.SelectedKey(0)(0))
                    End If
                Case Else
                    Debug.Assert (False)
            End Select
        Case "C" ' delete mode
            Select Case activeScreenMode
                Case smMain
                    If grd_ClaimMain.SelectedCount = 0 Then
                        Call SendMessage(ms_LanguageCode, WarMsgSelectRow, "#Please select a row.")
                    Else
                        Call Item_DeleteInit(grd_ClaimMain.SelectedKey(0), grd_ClaimMain.SelectedLine(0, "CSA_function"))
                    End If
                Case smView
                    ' close detail cursors
                    Call Item_CloseCursors
                    ' pop screen mode
                    Call popScreenMode
                    Call tlb_Main_action(as_Role, as_Language)
                Case smMemoMain
                    If grd_ClaimMemoList.SelectedCount = 0 Then
                        Call SendMessage(ms_LanguageCode, WarMsgSelectRow, "#Please select a row.")
                    Else
                        Call Memo_DeleteInit(grd_ClaimMemoList.SelectedKey(0)(0))
                    End If
                Case smCustMain
                    If grd_SelectCustList.SelectedCount = 0 Then
                        SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
                    Else
                        Call Cust_DeleteInit(grd_SelectCustList.SelectedKey(0)(0))
                    End If
                Case smProjMain
                    If grd_SelectProjList.SelectedCount = 0 Then
                        SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
                    Else
                        Call Proj_DeleteInit(grd_SelectProjList.SelectedKey(0)(0))
                    End If
                Case Else
                    Debug.Assert (False)
            End Select
        Case "D"              ' PRINT
            If grd_ClaimMain.SelectedCount = 0 Then
                Call SendMessage(ms_LanguageCode, WarMsgSelectRow, "#Please select a row.")
            Else
                RaiseEvent PrintDetail(grd_ClaimMain.SelectedKey(0))
            End If
        Case "T" ' exit to previous screen mode
            Select Case activeScreenMode
                Case smMain
                    'exit module
                    RaiseEvent quit
                Case smAdd, smUpdate, smDelete, smView
                    ' close detail cursors
                    Call Item_CloseCursors
                    
                    ' pop screen mode
                    Call popScreenMode
                    
                    Call ResetScreen(activeScreenMode)
                    Call UpdateUI
                
                Case smMemoMain
                    ' exit memo module
                    Call Memo_CloseCursor
                    
                    ' pop screen mode
                    Call popScreenMode
                    
                    Call UpdateUI
                    
                Case smMemoUpdate, smMemoAdd, smMemoDelete
                    If ml_memoCursor = -1 Then
                        ml_memoCursor = 0
                        Call grd_ClaimMemoList.DeselectRow
                    End If
                    
                    ' pop screen mode
                    Call popScreenMode
                    
                    Call ResetScreen(activeScreenMode)
                    Call Memo_LoadValues(ml_memoCursor)
                    Call UpdateUI
                Case smCustMain, smProjMain, smItemMain
                    ' exit customer module
                    Debug.Assert (ml_custCursor = 0)
                    Debug.Assert (ml_projCursor = 0)
                    
                    ' pop screen mode
                    Call popScreenMode
                    
                    Call UpdateUI
                Case smCustAdd, smCustUpdate, smCustDelete, smCustView
                    
                    Call Cust_CloseCursor
                    ' pop screen mode
                    Call popScreenMode
                    
                    Call UpdateUI
                Case smProjAdd, smProjUpdate, smProjDelete, smProjView
                    
                    Call Proj_CloseCursor
                    ' pop screen mode
                    Call popScreenMode
                    
                    Call UpdateUI
                Case Else
                    Debug.Assert (False)
            End Select
                
        Case "H" ' confirm
            Dim lo_exitGrid As ArmGrid
            
            Select Case activeScreenMode
                Case smAdd
                    lv_itemKey = Item_Add ' store new claim
                    Set lo_exitGrid = grd_ClaimMain
                Case smUpdate
                    lv_itemKey = Item_Update(grd_ClaimMain.SelectedKey(0)) ' update existing claim
                    Set lo_exitGrid = grd_ClaimMain
                Case smDelete
                    lv_itemKey = Item_Delete(grd_ClaimMain.SelectedKey(0))  ' delete existing claim
                    Set lo_exitGrid = grd_ClaimMain
                Case smMemoUpdate
                    lv_itemKey = Memo_Update(grd_ClaimMemoList.SelectedKey(0)) ' update existing memo
                    Set lo_exitGrid = grd_ClaimMemoList
                Case smMemoAdd
                    lv_itemKey = Memo_Add ' store new memo
                    Set lo_exitGrid = grd_ClaimMemoList
                Case smMemoDelete
                    lv_itemKey = Memo_Delete(grd_ClaimMemoList.SelectedKey(0)) ' delete existing memo
                    Set lo_exitGrid = grd_ClaimMemoList
                Case smCustMain
                    ' select customer
                    lv_itemKey = Cust_Select
                    Set lo_exitGrid = grd_SelectCustList
                Case smCustAdd
                    lv_itemKey = Cust_Add
                    Set lo_exitGrid = grd_SelectCustList
                Case smCustUpdate
                    lv_itemKey = Cust_Update(grd_SelectCustList.SelectedKey(0))
                    Set lo_exitGrid = grd_SelectCustList
                Case smCustDelete
                    lv_itemKey = Cust_Delete(grd_SelectCustList.SelectedKey(0))
                    Set lo_exitGrid = grd_SelectCustList
                Case smProjMain
                    ' select customer
                    lv_itemKey = Proj_Select
                    Set lo_exitGrid = grd_SelectProjList
                Case smProjAdd
                    lv_itemKey = Proj_Add
                    Set lo_exitGrid = grd_SelectProjList
                Case smProjUpdate
                    lv_itemKey = Proj_Update(grd_SelectProjList.SelectedKey(0))
                    Set lo_exitGrid = grd_SelectProjList
                Case smProjDelete
                    lv_itemKey = Proj_Delete(grd_SelectProjList.SelectedKey(0))
                    Set lo_exitGrid = grd_SelectProjList
                Case smItemMain
                    ' select item
                    lv_itemKey = SelI_Select
                    Set lo_exitGrid = grd_SelectItemList
                Case Else
                    Debug.Assert (False)
            End Select
            If Not IsEmpty(lv_itemKey) Then
                Dim old_sm As ArmScreenMode
                old_sm = activeScreenMode
                
                Call Item_ExitToGrid(lo_exitGrid, lv_itemKey)
                If old_sm = smAdd Then
                    Debug.Assert (activeScreenMode = smMain)
                    Debug.Assert (lo_exitGrid.Row <> -1)
                    Debug.Assert (lo_exitGrid.SelectedKey(0)(0) = lv_itemKey(0))
                    
                    ' automatically go to update mode
                    ' first set project tab
                    Call SelectTab(GetControl(tbs_ClaimTabs, "tbs_ClaimTabsEdit"), "_3", True)
                    
                    Call tlb_Main_action("B", tlb_Main.Language)
                End If
                
                
            End If

        Case "I" ' restore values
            Select Case activeScreenMode
                Case smAdd, smUpdate
                    Dim ll_detTabIndex As Long
                    Dim lo_visibleTabStrip As MSComctlLib.TabStrip
                    
                    Set lo_visibleTabStrip = getObjectVisible(tbs_ClaimTabs)
                    Debug.Assert (Not lo_visibleTabStrip Is Nothing)
                    
                    ll_detTabIndex = CLng(Mid(lo_visibleTabStrip.SelectedItem.Key, 2))
                    Call Item_ClearTab(lo_visibleTabStrip.SelectedItem.Key)
                    Call Item_LoadValues(ml_DetailCursor(ll_detTabIndex))
                    Call Item_ApplyLogic(activeScreenMode)
                Case smMemoAdd, smMemoUpdate
                    Call Memo_LoadValues(ml_memoCursor)
                Case smCustMain, smCustAdd, smCustUpdate, smCustDelete
                    Call Cust_LoadValues(ml_custCursor)
                Case smProjMain, smProjAdd, smProjUpdate, smProjDelete
                    Call Proj_LoadValues(ml_projCursor)
                Case smItemMain
                    Call SelI_LoadValues        ' reset main screen of Item
                Case Else
                    Debug.Assert (False)
            End Select
        Case "M" ' search items
            Select Case activeScreenMode
                Case smMain
                    lv_itemKey = Item_Search
                    If Not IsEmpty(lv_itemKey) Then
                        ' init view item detail
                        Debug.Assert (grd_ClaimMain.SelectedCount > 0)
                        Call Item_ViewInit(lv_itemKey, lv_itemKey(3))
                    End If
'                    tvw_SearchList.FindShow = True
                Case smCustMain
                    Call Cust_LoadGrid ' loads selection customer records to grid
                Case smProjMain
                    Call Proj_LoadGrid ' loads selection project records to grid
                Case smItemMain
                    Call SelI_LoadGrid
                Case Else
                    Debug.Assert (False)
            End Select
        Case "X" ' copy SAP customer to Claim customer
            Debug.Assert (activeScreenMode = smCustMain)
            
            If grd_SelectCustList.SelectedCount = 0 Then
                SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
            Else
                Call Cust_AddSAPInit(grd_SelectCustList.SelectedKey(0)(0))
            End If
        Case "Y" ' move down
            Select Case activeScreenMode
            Case smMain
                If Not grd_ClaimMain.NextLine Then
                    Call SendMessage(ms_LanguageCode, WarMsgItemNotFound, "#Item not found.")
                End If
            Case smView
                ' close detail cursors
                Call Item_CloseCursors
                ' pop screen mode
                Call popScreenMode
                
                If Not grd_ClaimMain.NextItem Then
                    If grd_ClaimMain.SelectedCount = 0 Then
                        Call ResetScreen(activeScreenMode)
                        Call UpdateUI
                    Else
                        Call Item_ViewInit(grd_ClaimMain.SelectedKey(0), grd_ClaimMain.SelectedLine(0, "CSA_function"))
                    End If
                    Call SendMessage(ms_LanguageCode, WarMsgItemNotFound, "#Item not found.")
                End If
            Case smCustMain
                If Not grd_SelectCustList.NextLine Then
                    Call SendMessage(ms_LanguageCode, WarMsgItemNotFound, "#Item not found.")
                End If
            Case smProjMain
                If Not grd_SelectProjList.NextLine Then
                    Call SendMessage(ms_LanguageCode, WarMsgItemNotFound, "#Item not found.")
                End If
            Case smCustView
                Call Cust_CloseCursor
                ' pop screen mode
                Call popScreenMode
                
                If Not grd_SelectCustList.NextItem Then
                    
                    If grd_SelectCustList.SelectedCount = 0 Then
                        Call UpdateUI
                    Else
                        Call Cust_ViewInit(grd_SelectCustList.SelectedKey(0)(0))
                    End If
                    Call SendMessage(ms_LanguageCode, WarMsgItemNotFound, "#Item not found.")
                End If
            Case smProjView
                Call Proj_CloseCursor
                ' pop screen mode
                Call popScreenMode
                
                If Not grd_SelectProjList.NextItem Then
                    
                    If grd_SelectProjList.SelectedCount = 0 Then
                        Call UpdateUI
                    Else
                        Call Proj_ViewInit(grd_SelectProjList.SelectedKey(0)(0))
                    End If
                    Call SendMessage(ms_LanguageCode, WarMsgItemNotFound, "#Item not found.")
                End If
            Case Else
                Debug.Assert (False)
            End Select
        Case "Z" ' move up
            Select Case activeScreenMode
            Case smMain
                If Not grd_ClaimMain.PreviousLine Then
                    Call SendMessage(ms_LanguageCode, WarMsgItemNotFound, "#Item not found.")
                End If
            Case smView
                ' close detail cursors
                Call Item_CloseCursors
                ' pop screen mode
                Call popScreenMode
                
                If Not grd_ClaimMain.PreviousItem Then
                    If grd_ClaimMain.SelectedCount = 0 Then
                        Call ResetScreen(activeScreenMode)
                        Call UpdateUI
                    Else
                        Call Item_ViewInit(grd_ClaimMain.SelectedKey(0), grd_ClaimMain.SelectedLine(0, "CSA_function"))
                    End If
                    Call SendMessage(ms_LanguageCode, WarMsgItemNotFound, "#Item not found.")
                End If
            Case smCustMain
                If Not grd_SelectCustList.PreviousLine Then
                    Call SendMessage(ms_LanguageCode, WarMsgItemNotFound, "#Item not found.")
                End If
            Case smProjMain
                If Not grd_SelectProjList.PreviousLine Then
                    Call SendMessage(ms_LanguageCode, WarMsgItemNotFound, "#Item not found.")
                End If
            Case smCustView
                Call Cust_CloseCursor
                ' pop screen mode
                Call popScreenMode
                
                If Not grd_SelectCustList.PreviousItem Then
                    
                    If grd_SelectCustList.SelectedCount = 0 Then
                        Call UpdateUI
                    Else
                        Call Cust_ViewInit(grd_SelectCustList.SelectedKey(0)(0))
                    End If
                    Call SendMessage(ms_LanguageCode, WarMsgItemNotFound, "#Item not found.")
                End If
            Case smProjView
                Call Proj_CloseCursor
                ' pop screen mode
                Call popScreenMode
                
                If Not grd_SelectProjList.PreviousItem Then
                    
                    If grd_SelectProjList.SelectedCount = 0 Then
                        Call UpdateUI
                    Else
                        Call Proj_ViewInit(grd_SelectProjList.SelectedKey(0)(0))
                    End If
                    Call SendMessage(ms_LanguageCode, WarMsgItemNotFound, "#Item not found.")
                End If
            Case Else
                Debug.Assert (False)
            End Select
        Case "N"    ' view detail
            Select Case activeScreenMode
            Case smCustMain
                If grd_SelectCustList.SelectedCount = 0 Then
                    SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
                Else
                    Call Cust_ViewInit(grd_SelectCustList.SelectedKey(0)(0))
                End If
            Case smProjMain
                If grd_SelectProjList.SelectedCount = 0 Then
                    SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
                Else
                    Call Proj_ViewInit(grd_SelectProjList.SelectedKey(0)(0))
                End If
            Case Else
                Debug.Assert (False)
            End Select
        Case "E"    ' audit
            If grd_ClaimMain.SelectedCount = 0 Then
                Call SendMessage(ms_LanguageCode, WarMsgSelectRow, "#Please select a row.")
            Else
                RaiseEvent AuditClick(grd_ClaimMain.SelectedLine(0, "CLA_code"))
            End If
        Case Else
            Debug.Assert (False)
    End Select

    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("tlb_main_action")
End Sub

Private Function getNodePath(ao_Node As MSComctlLib.Node) As String
On Error GoTo ErrHandler
    If Not ao_Node Is Nothing Then
        getNodePath = getNodePath(ao_Node.Parent) & "/" & ao_Node.Tag.IDValue
    End If
    Exit Function
ErrHandler:
    Call ErrorMessage("getNodePath")
End Function

Private Sub tvw_SearchList_NodeClick(ByVal Node As MSComctlLib.Node)
On Error GoTo ErrHandler
    If Not tvw_SearchList.Enabled Then Exit Sub
    Dim ls_aktTvwPath As String
    ls_aktTvwPath = getNodePath(Node)
    
    If Not (Node Is Nothing) And ls_aktTvwPath <> ms_aktTvwPath Then
        ms_aktTvwPath = ls_aktTvwPath
        Call LoadSearchGrid(grd_ClaimMain, tvw_SearchList.SelectedNodeRequest(), Node.Tag.ml_Level < tvw_SearchList.Levels - 1)
    End If
    Exit Sub
ErrHandler:
    Call ErrorMessage("tvw_SearchList_NodeClick")
End Sub

Private Sub tvw_SearchList_FindNextClick(as_findText As String, ab_doSearch As Boolean)
On Error GoTo ErrHandler
    ab_doSearch = (Trim(as_findText) <> "")
    Exit Sub
ErrHandler:
    Call ErrorMessage("tvw_SearchList_FindNextClick")
End Sub

' this function works only with specialsearch sp (like level4)
Private Sub Item_NodeFound()
On Error GoTo ErrHandler
    Dim lo_itemFoundNodeInfo As NodeInfo
    If Not tvw_SearchList.SelectedItem Is Nothing Then
        ' search item in grid
        If tvw_SearchList.SelectedItem.Tag.ml_Level = 2 Then
            Set lo_itemFoundNodeInfo = tvw_SearchList.FoundNodeInfo '.SelectedItem.Tag
            ' CLA_CODE, CT_CODE, CLA_STATUS, CSA_function
            Do Until grd_ClaimMain.SearchKey(False, CVar(Array(lo_itemFoundNodeInfo.GetData(3), lo_itemFoundNodeInfo.GetData(1), lo_itemFoundNodeInfo.GetData(2), lo_itemFoundNodeInfo.GetData(4))))
                If Not tvw_SearchList.FindNext Then
                    Exit Do
                End If
                Set lo_itemFoundNodeInfo = tvw_SearchList.FoundNodeInfo '.SelectedItem.Tag
            Loop
            Call grd_ClaimMain_SelChange
        End If
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("Item_NodeFound")
End Sub

Private Function Item_Search() As Variant
On Error GoTo ErrHandler
    Dim ls_searchClaim      As String
    Dim lv_retVal           As Variant
    Dim lv_saveRequests     As Variant
    Dim lo_itemFoundNodeInfo As NodeInfo
    Dim lb_initStatusOld    As Boolean

    lv_retVal = Empty
    
    ls_searchClaim = ""
    ls_searchClaim = InputBox("Claim", "Claim search", ls_searchClaim)
    
    If ls_searchClaim <> "" Then
        If tvw_SearchList.Count = 0 Then
            pic_ReloadSearch.Visible = False
            Call loadSearchTreeView(tvw_SearchList, GetOptionButtonCode(opt_SearchView), IIf(GetOptionButtonCode(opt_SearchFilter) = "D", cal_FilterAnyUpdated.date_dt, 0))
            tvw_SearchList.Visible = True
        End If
        ' set search sp to search whole database
        lv_saveRequests = tvw_SearchList.FindRequests
        Call SetTreeViewSearchRequestsItem(tvw_SearchList, "O", 0)
        If tvw_SearchList.FindSQL(ls_searchClaim, 2) Then
             Call Item_NodeFound                                ' select node in grid if filters accept
             ' assign ret value / can be Empty!
             lv_retVal = grd_ClaimMain.SelectedKey(0)
            ' restore find requests
            tvw_SearchList.FindRequests = lv_saveRequests
        End If
        If IsEmpty(lv_retVal) Then
            ' item not found - try to find it
            Set lo_itemFoundNodeInfo = tvw_SearchList.FoundNodeInfo
            If Not lo_itemFoundNodeInfo Is Nothing Then
                ' no item found for actual filters, but some can be found if we reset filter (date/plant-office)
                If SendMessage(ms_LanguageCode, WarMsgResetFilters, "#Do you want to reset current filters and search again?", "", vbOKCancel) = vbOK Then
                    ' we will reset filters
                    lb_initStatusOld = mb_Initializing
                    mb_Initializing = True
                    Call SetOptionButtonCode(opt_SearchFilter, "A")     ' no date filter
                    Call SetOptionButtonCode(opt_SearchView, "O")       ' Office view type
                    ' reset calendar
                    Call SetEnabledCtrl(cal_FilterAnyUpdated, False)
                    Call cal_FilterAnyUpdated.reinit_cal
                    ' restore initializing status
                    mb_Initializing = lb_initStatusOld
                    
                    Call loadSearchTreeView(tvw_SearchList, "O", 0)
                    tvw_SearchList.FoundNodeInfoIndex = 1               ' reset to start search from begining
                    If tvw_SearchList.FindNext Then
                        Call Item_NodeFound                             ' select node in grid
                        Debug.Assert (grd_ClaimMain.SelectedCount > 0)
                        ' init detail
                        lv_retVal = grd_ClaimMain.SelectedKey(0)
                    Else
                        Debug.Assert (False)
                    End If
                End If
            Else
                ' claim number can not be found at all
                Call SendMessage(ms_LanguageCode, WarMsgItemNotFound, "#Item not found.")
            End If
            ' restore find requests
            If IsEmpty(lv_retVal) Then
                tvw_SearchList.FindRequests = lv_saveRequests
            End If
        End If
    End If
    
    Item_Search = lv_retVal
    Exit Function
ErrHandler:
    Call ErrorHandler("Item_Search")
End Function

Private Sub grd_ClaimMain_SelChange()
On Error GoTo ErrHandler
    tlb_Main.Redraw = False
    Call ApplyRightsOnToolbar(tlb_Main, grd_ClaimMain.SelectedKey(0))
    tlb_Main.Redraw = True
    
    Exit Sub
ErrHandler:
    Call ErrorMessage("grd_ClaimMain_SelChange")
End Sub

Private Sub grd_ClaimMain_ItemSelected()
On Error GoTo ErrHandler
    Call LockScreen(True)
    If grd_ClaimMain.SelectedCount = 0 Then
        Call SendMessage(ms_LanguageCode, WarMsgSelectRow, "#Please select a row.")
    Else
        Call Item_ViewInit(grd_ClaimMain.SelectedKey(0), grd_ClaimMain.SelectedLine(0, "CSA_function"))
    End If
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("grd_ClaimMain_ItemSelected")
End Sub

Private Sub grd_SelectItemList_DblClick()
On Error GoTo ErrHandler
    Call tlb_Main_action("H", tlb_Main.Language)
    Exit Sub
ErrHandler:
    Call ErrorMessage("grd_SelectItemList_DblClick")
End Sub

Private Sub grd_SelectCustList_ItemSelected()
On Error GoTo ErrHandler
    If activeScreenMode = smCustMain Then
        ' selected from navigation icon in smCustView mode
        If grd_SelectCustList.SelectedCount = 0 Then
            SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
        Else
            Call Cust_ViewInit(grd_SelectCustList.SelectedKey(0)(0))
        End If
    End If

    Exit Sub
ErrHandler:
    Call ErrorMessage("grd_SelectCustList_ItemSelected")
End Sub

Private Sub grd_SelectProjList_ItemSelected()
On Error GoTo ErrHandler
    If activeScreenMode = smProjMain Then
        ' selected from navigation icon in smCustView mode
        If grd_SelectProjList.SelectedCount = 0 Then
            SendMessage ms_LanguageCode, WarMsgSelectRow, "#Please select a row."
        Else
            Call Proj_ViewInit(grd_SelectProjList.SelectedKey(0)(0))
        End If
    End If

    Exit Sub
ErrHandler:
    Call ErrorMessage("grd_SelectProjList_ItemSelected")
End Sub

Private Sub grd_SelectCustList_DblClick()
On Error GoTo ErrHandler
    Call tlb_Main_action("H", tlb_Main.Language)
    Exit Sub
ErrHandler:
    Call ErrorMessage("grd_SelectCustList_DblClick")
End Sub

Private Sub grd_SelectProjList_DblClick()
On Error GoTo ErrHandler
    Call tlb_Main_action("H", tlb_Main.Language)
    Exit Sub
ErrHandler:
    Call ErrorMessage("grd_SelectProjList_DblClick")
End Sub

Private Sub SetComboBoxRequest(ByRef ao_Combobox As ArmCombobox, ByVal as_req As String)
On Error GoTo ErrHandler
    ao_Combobox.Request = as_req
    ao_Combobox.Clear
    ao_Combobox.Enabled = (as_req <> "")
    Exit Sub
ErrHandler:
    Call ErrorHandler("SetComboBoxRequest")
End Sub
Private Sub cbo_GenCoordinator_ComboItemSelected()
Const C_REQ As String = "EXEC Sales_Office_cbo2 $CCO_CODE$, '$LANG$'"
On Error GoTo ErrHandler
    ' if control is not enabled even wil not be processed
    If Not cbo_GenCoordinator.Enabled Then Exit Sub

    Call LockScreen(True)

    cbo_GenSalesOffice.Clear

    Call SetComboBoxRequest(cbo_GenRespSalesRep, "")
    Call SetComboBoxRequest(cbo_GenSalesMarket, "")
    Call SetComboBoxRequest(cbo_GenCountry, "")
    Call SetComboBoxRequest(cbo_GenTerritory, "")
    
    Dim ls_req As String
    If Not cbo_GenCoordinator.SelectedItem Is Nothing Then
        ls_req = Replace(C_REQ, "$CCO_CODE$", cbo_GenCoordinator.SelectedItem.Key, , , vbTextCompare)
        ls_req = Replace(ls_req, "$LANG$", ms_LanguageCode, , , vbTextCompare)
    End If
    Call SetComboBoxRequest(cbo_GenSalesOffice, ls_req)
        
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_GenCoordinator_ComboItemSelected")
End Sub

Private Sub cbo_GenSalesOffice_ComboItemSelected()
Const C_REQ1 As String = "EXEC Sales_Market_cbo2 '$SO_CODE$', '$LANG$'"
Const C_REQ2 As String = "EXEC Claim_Originator_cbo '$SO_CODE$', $DATE$"
On Error GoTo ErrHandler
    ' if control is not enabled even wil not be processed
    If Not cbo_GenSalesOffice.Enabled Then Exit Sub
    
    Call LockScreen(True)
    
    Call SetComboBoxRequest(cbo_GenCountry, "")
    Call SetComboBoxRequest(cbo_GenTerritory, "")
    
    Dim ls_req As String
    If Not cbo_GenSalesOffice.SelectedItem Is Nothing Then
        ls_req = Replace(C_REQ1, "$SO_CODE$", cbo_GenSalesOffice.SelectedItem.Key, , , vbTextCompare)
        ls_req = Replace(ls_req, "$LANG$", ms_LanguageCode, , , vbTextCompare)
    End If
    Call SetComboBoxRequest(cbo_GenSalesMarket, ls_req)
    
    If Not cbo_GenSalesOffice.SelectedItem Is Nothing Then
        ls_req = Replace(C_REQ2, "$SO_CODE$", cbo_GenSalesOffice.SelectedItem.Key, , , vbTextCompare)
        ls_req = Replace(ls_req, "$DATE$", SQLDateTime(IIf(cal_GenReportDate.date_dt = 0, Date, cal_GenReportDate.date_dt)), , , vbTextCompare)
    End If
    Call SetComboBoxRequest(cbo_GenRespSalesRep, ls_req)
    
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_GenSalesOffice_ComboItemSelected")
End Sub

Private Sub cal_GenReportDate_datechangee()
Const C_REQ2 As String = "EXEC Claim_Originator_cbo '$SO_CODE$', $DATE$"
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    
    Call LockScreen(True)
    Dim ls_req As String
    
    If Not cbo_GenSalesOffice.SelectedItem Is Nothing Then
        ls_req = Replace(C_REQ2, "$SO_CODE$", cbo_GenSalesOffice.SelectedItem.Key, , , vbTextCompare)
        ls_req = Replace(ls_req, "$DATE$", SQLDateTime(IIf(cal_GenReportDate.date_dt = 0, Date, cal_GenReportDate.date_dt)), , , vbTextCompare)
    End If
    Call SetComboBoxRequest(cbo_GenRespSalesRep, ls_req)

    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cal_GenReportDate_datechangee")
End Sub

Private Sub cbo_GenSalesMarket_ComboItemSelected()
Const C_REQ As String = "EXEC Countries_cbo3 '$SMK_CODE$', '$LANG$'"
On Error GoTo ErrHandler
    ' if control is not enabled even wil not be processed
    If Not cbo_GenSalesMarket.Enabled Then Exit Sub
    
    Call LockScreen(True)
    
    Call SetComboBoxRequest(cbo_GenTerritory, "")
    
    Dim ls_req As String
    If Not cbo_GenSalesMarket.SelectedItem Is Nothing Then
        ls_req = Replace(C_REQ, "$SMK_CODE$", cbo_GenSalesMarket.SelectedItem.Key, , , vbTextCompare)
        ls_req = Replace(ls_req, "$LANG$", ms_LanguageCode, , , vbTextCompare)
    End If
    Call SetComboBoxRequest(cbo_GenCountry, ls_req)
    
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_GenSalesMarket_ComboItemSelected")
End Sub

Private Sub cbo_GenCountry_ComboItemSelected()
Const C_REQ As String = "EXEC Territories_cbo2 '$CT_CODE$', '$LANG$'"
On Error GoTo ErrHandler
    ' if control is not enabled even wil not be processed
    If Not cbo_GenCountry.Enabled Then Exit Sub
    
    Call LockScreen(True)

    Dim ls_req As String
    If Not cbo_GenCountry.SelectedItem Is Nothing Then
        ls_req = Replace(C_REQ, "$CT_CODE$", cbo_GenCountry.SelectedItem.Key, , , vbTextCompare)
        ls_req = Replace(ls_req, "$LANG$", ms_LanguageCode, , , vbTextCompare)
    End If
    Call SetComboBoxRequest(cbo_GenTerritory, ls_req)
   
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_GenCountry_ComboItemSelected")
End Sub

Private Sub cbo_GenMainReason1_ComboItemSelected()
Const C_REQ As String = "EXEC Claim_Letter_cbo $CNA_CODE$, '$LANG$'"
On Error GoTo ErrHandler
    ' if control is not enabled even wil not be processed
    If Not cbo_GenMainReason1.Enabled Then Exit Sub
    
    Call LockScreen(True)

    Dim ls_req As String
    If IsComboboxSelected(cbo_GenMainReason1) Then
        ls_req = Replace(C_REQ, "$CNA_CODE$", cbo_GenMainReason1.SelectedItem.Key, , , vbTextCompare)
        ls_req = Replace(ls_req, "$LANG$", ms_LanguageCode, , , vbTextCompare)
    End If
    Call SetComboBoxRequest(cbo_GenMainReason2, ls_req)
    
    cbo_Gen2ndReason1.Enabled = True
        
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_GenMainReason1_ComboItemSelected")
End Sub

Private Sub cbo_Gen2ndReason1_ComboItemSelected()
Const C_REQ As String = "EXEC Claim_Letter_cbo $CNA_CODE$, '$LANG$'"
On Error GoTo ErrHandler
    ' if control is not enabled even wil not be processed
    If Not cbo_Gen2ndReason1.Enabled Then Exit Sub
    
    Call LockScreen(True)
    
    Dim ls_req As String
    If IsComboboxSelected(cbo_Gen2ndReason1) Then
        ls_req = Replace(C_REQ, "$CNA_CODE$", cbo_Gen2ndReason1.SelectedItem.Key, , , vbTextCompare)
        ls_req = Replace(ls_req, "$LANG$", ms_LanguageCode, , , vbTextCompare)
    End If
    Call SetComboBoxRequest(cbo_Gen2ndReason2, ls_req)
    
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_Gen2ndReason1_ComboItemSelected")
End Sub

Private Sub opt_GenStatus_Click(Index As Integer)
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    Call LockScreen(True)
    ' here download all data dependent on selected status
    Select Case GetOptionButtonCode(opt_GenStatus)
        Case "I"
        Case "F"    ' load cost=1, customer=2, project=3, item=4, plant=5
            Dim ll_Index As Long
            For ll_Index = 1 To UBound(ml_DetailCursor)
                If ml_DetailCursor(ll_Index) = 0 Then
                    Call Item_LoadDB(ml_DetailCursor(ll_Index), ml_detailIconcurrencyCursor, _
                                        ms_detailRequests(ll_Index), _
                                        txt_GenReport.Text)
                    Call Item_LoadValues(ml_DetailCursor(ll_Index))
                End If
            Next
            If ml_DetailCursor(1) > 0 Then
                ' erase settlement cost fields
                txt_CostSetLaborCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                txt_CostSetMaterialCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                txt_CostSetOtherCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                txt_CostSetTotalCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
            End If
            
        Case "R"    ' load cost=1
            If ml_DetailCursor(1) = 0 Then
                Call Item_LoadDB(ml_DetailCursor(1), ml_detailIconcurrencyCursor, _
                                    ms_detailRequests(1), _
                                    txt_GenReport.Text)
                Call Item_LoadValues(ml_DetailCursor(1))
            Else
                ' erase settlement cost fields
                txt_CostSetLaborCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                txt_CostSetMaterialCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                txt_CostSetOtherCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
                txt_CostSetTotalCost.Text = ToStr(0, C_COST_VALUE_FORMAT)
            End If
        
        Case "S"    ' load cost=1
            If ml_DetailCursor(1) = 0 Then
                Call Item_LoadDB(ml_DetailCursor(1), ml_detailIconcurrencyCursor, _
                                    ms_detailRequests(1), _
                                    txt_GenReport.Text)
                Call Item_LoadValues(ml_DetailCursor(1))
            End If
        Case Else
            Debug.Assert (False)
    End Select
    Call Item_ApplyLogic(activeScreenMode)
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("opt_GenStatus_Click")
End Sub

Private Sub opt_CusWhoRaised_Click(Index As Integer)
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    Call Item_ApplyLogic(activeScreenMode)
    Exit Sub
ErrHandler:
    Call ErrorMessage("opt_CusWhoRaised_Click")
End Sub

Private Sub opt_ItemSampleSent_Click(Index As Integer)
On Error GoTo ErrHandler
    ' if control is not enabled even wil not be processed
    If mb_Initializing Then Exit Sub
    
    If GetOptionButtonCode(opt_ItemSampleSent) <> "Y" Then
        txt_ItemSampleSentTo.Text = ""
    Else
        txt_ItemSampleReasonNo.Text = ""
    End If
    
    Call Item_ApplyLogic(activeScreenMode)
    Exit Sub
ErrHandler:
    Call ErrorMessage("opt_ItemSampleSent_Click")
End Sub

Private Sub cal_ItemVisitDate_datechangee()
On Error GoTo ErrHandler
    ' if control is not enabled even wil not be processed
    If mb_Initializing Then Exit Sub
    
    If cal_ItemVisitDate.date_dt = 0 Then
        txt_ItemVisitedBy.Text = ""
    End If
    
    
    Call Item_ApplyLogic(activeScreenMode)
    
    Exit Sub
ErrHandler:
    Call ErrorMessage("cal_ItemVisitDate_datechangee")
End Sub

Private Sub cbo_ItemGridManufac_ComboItemSelected()
Const C_REQ As String = "EXEC Clm_Grid_Type_cbo $GM_CODE$, '$LANG$'"
On Error GoTo ErrHandler
    ' if control is not enabled even wil not be processed
    If Not cbo_ItemGridManufac.Enabled Then Exit Sub
    
    Call LockScreen(True)

    Dim ls_req As String
    If Not cbo_ItemGridManufac.SelectedItem Is Nothing Then
        ls_req = Replace(C_REQ, "$GM_CODE$", CLng(cbo_ItemGridManufac.SelectedItem.Key), , , vbTextCompare)
        ls_req = Replace(ls_req, "$LANG$", ms_LanguageCode, , , vbTextCompare)
    End If
    Call SetComboBoxRequest(cbo_ItemGridType, ls_req)
    
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_ItemGridManufac_ComboItemSelected")
End Sub

Private Sub pic_reloadItemDesc_Click()
On Error GoTo ErrHandler
Const C_REQ1 As String = "EXEC Claim_Item_sel '$BI_SAP_CODE$'"
Const C_REQ2 As String = "EXEC Base_Item_dtl '$BI_SAP_CODE$', '$LANG$'"
Const C_REQ3 As String = "EXEC Base_Item_dtl2 '$BI_SAP_CODE$', '$LANG$'"
    If txt_ItemItem.Text = "" Then Exit Sub
    Call LockScreen(True)
    ' load labels
    Debug.Assert (ml_itemDescLabelsCursor <> 0)
    Debug.Assert (txt_ItemItem.Text <> "")
    
    grd_ItemDescription.ClearGrid
    Dim ll_Cursor As Long
    ' get Category ( CG_code )
    ll_Cursor = OpenSQLSafe(mo_Db, Replace(C_REQ1, "$BI_SAP_CODE$", txt_ItemItem.Text, , , vbTextCompare), ArmSQLExactOne)
    
    Dim ls_CG_Code As String
    ls_CG_Code = mo_Db.GetFields(ll_Cursor, "CG_code")
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    Dim ls_req As String
    ls_req = IIf(ls_CG_Code = "C006" Or ls_CG_Code = "C001", C_REQ2, C_REQ3)
    ls_req = Replace(ls_req, "$BI_SAP_CODE$", txt_ItemItem.Text, , , vbTextCompare)
    ls_req = Replace(ls_req, "$LANG$", ms_LanguageCode, , , vbTextCompare)
    ll_Cursor = OpenSQLSafe(mo_Db, ls_req, ArmSQLExactOne)
    
    Dim ll_Index As Long
    Dim lv_Fields As Variant
    lv_Fields = mo_Db.Fields(ll_Cursor)
    For ll_Index = 0 To mo_Db.FieldCount(ll_Cursor) - 1
        grd_ItemDescription.Rows = grd_ItemDescription.Rows + 1
        If mo_Db.Find(ml_itemDescLabelsCursor, "Field_name", lv_Fields(ll_Index), 0) > -1 Then
            grd_ItemDescription.Data(grd_ItemDescription.Rows - 1, 0) = mo_Db.GetFields(ml_itemDescLabelsCursor, "Local_text")
            grd_ItemDescription.Data(grd_ItemDescription.Rows - 1, 1) = mo_Db.GetFields(ll_Cursor, lv_Fields(ll_Index))
        Else
            Debug.Assert (False)
        End If
    Next
    mo_Db.Close (ll_Cursor)
    ll_Cursor = 0
    
'    If grd_ItemDescription.Data(grd_ItemDescription.Rows - 1, 1) = "" Then
        ' last line is drop date - remove if not dropped
'        grd_ItemDescription.Rows = grd_ItemDescription.Rows - 1
'    End If

    pic_reloadItemDesc.Visible = False
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    If ll_Cursor <> 0 Then
        mo_Db.Close (ll_Cursor)
        ll_Cursor = 0
    End If
    Call LockScreen(False)
    Call ErrorMessage("pic_reloadItemDesc_Click")
End Sub

Private Sub cmd_GenComments_Click()
On Error GoTo ErrHandler
    Debug.Assert (grd_ClaimMain.Row <> -1)
    Call LockScreen(True)
    Dim lv_memoRequests As Variant
    Dim ls_CLA_code As String
    ls_CLA_code = grd_ClaimMain.SelectedKey(0)(0)
    
    lv_memoRequests = Array(Array("List", Replace("EXEC Clm_Comment_Memo_Lst '$ClaimCode$', '$LOGINNAME$'", "$ClaimCode$", ls_CLA_code, , , vbTextCompare)), _
                            Array("Sel", Replace("EXEC Clm_Comment_Memo_Sel '$ClaimCode$', '$Code$'", "$ClaimCode$", ls_CLA_code, , , vbTextCompare)), _
                            Array("Add", Replace("EXEC Claim_Comment_Memo_ins '$ClaimCode$', '$Code$', '$Title$', '$Desc$'", "$ClaimCode$", ls_CLA_code, , , vbTextCompare)), _
                            Array("Upd", Replace("EXEC Claim_Comment_Memo_upd '$ClaimCode$', '$Code$', '$Title$', '$Desc$', $iConcurrency$", "$ClaimCode$", ls_CLA_code, , , vbTextCompare)), _
                            Array("Del", Replace("EXEC Claim_Comment_Memo_del '$ClaimCode$', '$Code$', $iConcurrency$", "$ClaimCode$", ls_CLA_code, , , vbTextCompare)), _
                            Array("Lng", Replace("EXEC Clm_Comment_Memo_Lang_cbo '$ClaimCode$', '$Code$', '$LOGINNAME$'", "$ClaimCode$", ls_CLA_code, , , vbTextCompare)), _
                            Array("CLACODE", ls_CLA_code) _
                            )

    Call Memo_MainInit(lv_memoRequests)
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cmd_GenComments_Click")
End Sub

Private Sub cmd_SupComments_Click()
On Error GoTo ErrHandler
    Debug.Assert (grd_ClaimMain.Row <> -1)
    Call LockScreen(True)
    Dim lv_memoRequests As Variant
    Dim ls_CLA_code As String
    ls_CLA_code = grd_ClaimMain.SelectedKey(0)(0)
    
    lv_memoRequests = Array(Array("List", Replace("EXEC Clm_Plant_Memo_Lst  '$ClaimCode$', '$LOGINNAME$'", "$ClaimCode$", ls_CLA_code, , , vbTextCompare)), _
                            Array("Sel", Replace("EXEC Clm_Plant_Memo_Sel '$ClaimCode$', '$Code$'", "$ClaimCode$", ls_CLA_code, , , vbTextCompare)), _
                            Array("Add", Replace("EXEC Claim_Plant_Memo_ins '$ClaimCode$', '$Code$', '$Title$', '$Desc$'", "$ClaimCode$", ls_CLA_code, , , vbTextCompare)), _
                            Array("Upd", Replace("EXEC Claim_Plant_Memo_upd '$ClaimCode$', '$Code$', '$Title$', '$Desc$', $iConcurrency$", "$ClaimCode$", ls_CLA_code, , , vbTextCompare)), _
                            Array("Del", Replace("EXEC Claim_Plant_Memo_del '$ClaimCode$', '$Code$', $iConcurrency$", "$ClaimCode$", ls_CLA_code, , , vbTextCompare)), _
                            Array("Lng", Replace("EXEC Clm_Plant_Memo_Lang_cbo '$ClaimCode$', '$Code$', '$LOGINNAME$'", "$ClaimCode$", ls_CLA_code, , , vbTextCompare)), _
                            Array("CLACODE", ls_CLA_code) _
                            )

    Call Memo_MainInit(lv_memoRequests)
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cmd_SupComments_Click")
End Sub

Private Sub cmd_SelectCust_Click(Index As Integer)
On Error GoTo ErrHandler
    Call LockScreen(True)
    ' get default values for slecting customer (country from opened cursor)
    Dim ll_detTabIndex As Long
    Dim lo_visibleTabStrip As MSComctlLib.TabStrip
    
    Set lo_visibleTabStrip = getObjectVisible(tbs_ClaimTabs)
    Debug.Assert (Not lo_visibleTabStrip Is Nothing)
    
    ll_detTabIndex = CLng(Mid(lo_visibleTabStrip.SelectedItem.Key, 2))
    Debug.Assert (ml_DetailCursor(ll_detTabIndex) <> 0)
    
    Dim ls_CTCode As String, ls_CTDesc As String
    ls_CTCode = mo_Db.GetFields(ml_DetailCursor(ll_detTabIndex), "CT_code_" & (Index + 1))
    ls_CTDesc = mo_Db.GetFields(ml_DetailCursor(ll_detTabIndex), "CT_desc_" & (Index + 1))

    If ls_CTCode = "" Then
        ' try default tab general
        If Not cbo_GenCountry.SelectedItem Is Nothing Then
            ls_CTCode = SQLComboBoxValue(cbo_GenCountry)
            ls_CTDesc = SQLComboBoxValue(cbo_GenCountry, "unknown", False)
        Else
            ' try from tree viev
            If Not tvw_SearchList.SelectedItem Is Nothing Then
                If tvw_SearchList.SelectedItem.Tag.ml_Level > 0 Then
                    ' here we can obtain country from filter treeview
                    Dim lo_countryNode As MSComctlLib.Node
                    Set lo_countryNode = tvw_SearchList.SelectedItem
                    While lo_countryNode.Tag.ml_Level <> 1
                        Set lo_countryNode = lo_countryNode.Parent
                    Wend
                    ls_CTCode = lo_countryNode.Tag.GetData(0)
                    ls_CTDesc = lo_countryNode.Tag.TextValue
                End If
            End If
        End If
    End If


    Call Cust_SelectInit(ls_CTCode, ls_CTDesc)
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cmd_SelectCust_Click")
End Sub

Private Sub cmd_ResetCust_Click(Index As Integer)
On Error GoTo ErrHandler
    Debug.Assert (Not tbs_CustTabs.SelectedItem Is Nothing)
    Call LockScreen(True)
    ClearForm UserControl.Controls, fra_CustTabs(CLng(Mid(tbs_CustTabs.SelectedItem.Key, 2)))
    cmd_SelectCust(Index).Tag = "0"
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cmd_ResetCust_Click")
End Sub

Private Sub cmd_ResetProj_Click()
On Error GoTo ErrHandler
    Call LockScreen(True)
    ClearForm UserControl.Controls, fra_ProAddress
    cmd_SelectProj.Tag = "0"
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cmd_ResetProj_Click")
End Sub

Private Sub grd_ClaimMemoList_SelChange()
On Error GoTo ErrHandler
    If grd_ClaimMemoList.Row = -1 Then Exit Sub         ' kind of bug when clicked on edge of header
    
    Dim lb_securityValue  As Boolean
    Call LockScreen(True)
    Debug.Assert (grd_ClaimMemoList.Row <> -1)
    
    lb_securityValue = grd_ClaimMemoList.Row <> -1
    If lb_securityValue Then
        lb_securityValue = (activeScreenMode(1) = smUpdate) And (grd_ClaimMemoList.SelectedLine(0, "SECURITY") = 1)
    End If
    tlb_Main.Redraw = False
    tlb_Main.ButtonVisible("B") = lb_securityValue
    tlb_Main.ButtonVisible("C") = lb_securityValue
    tlb_Main.Redraw = True
    
    Call Memo_ViewInit(grd_ClaimMemoList.SelectedKey(0)(0))
    
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("grd_ClaimMemoList_SelChange")
End Sub

Private Sub opt_SelectCustType_Click(Index As Integer)
On Error GoTo ErrHandler
    Call LockScreen(True)
    Call grd_SelectCustList.ClearGrid
    Call UpdateUI
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("opt_SelectCustType_Click")
End Sub

Private Sub cmd_SelectProj_Click()
On Error GoTo ErrHandler
    Call LockScreen(True)
    ' get default values for slecting customer (country from opened cursor)
    Dim ll_detTabIndex As Long
    Dim lo_visibleTabStrip As MSComctlLib.TabStrip
    
    Set lo_visibleTabStrip = getObjectVisible(tbs_ClaimTabs)
    Debug.Assert (Not lo_visibleTabStrip Is Nothing)
    
    ll_detTabIndex = CLng(Mid(lo_visibleTabStrip.SelectedItem.Key, 2))
    Debug.Assert (ml_DetailCursor(ll_detTabIndex) <> 0)

    Dim ls_CTCode As String, ls_CTDesc As String
    ls_CTCode = mo_Db.GetFields(ml_DetailCursor(ll_detTabIndex), "CT_code_P")
    ls_CTDesc = mo_Db.GetFields(ml_DetailCursor(ll_detTabIndex), "CT_desc_P")

    If ls_CTCode = "" Then
        ' try default tab general
        If Not cbo_GenCountry.SelectedItem Is Nothing Then
            ls_CTCode = SQLComboBoxValue(cbo_GenCountry)
            ls_CTDesc = SQLComboBoxValue(cbo_GenCountry, "unknown", False)
        Else
            ' try from tree viev
            If Not tvw_SearchList.SelectedItem Is Nothing Then
                If tvw_SearchList.SelectedItem.Tag.ml_Level > 0 Then
                    ' here we can obtain country from filter treeview
                    Dim lo_countryNode As MSComctlLib.Node
                    Set lo_countryNode = tvw_SearchList.SelectedItem
                    While lo_countryNode.Tag.ml_Level <> 1
                        Set lo_countryNode = lo_countryNode.Parent
                    Wend
                    ls_CTCode = lo_countryNode.Tag.GetData(0)
                    ls_CTDesc = lo_countryNode.Tag.TextValue
                End If
            End If
        End If
    End If

    Call Proj_SelectInit(ls_CTCode, ls_CTDesc)
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cmd_SelectProj_Click")
End Sub

Private Sub cmd_SelectItem_Click()
On Error GoTo ErrHandler
    Call LockScreen(True)
    Call SelI_SelectInit
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cmd_SelectItem_Click")
End Sub

' update all other selections
Private Sub cbo_SelectItemBaseMaterial_ComboItemSelected()
On Error GoTo ErrHandler
    Call LockScreen(True)
    
    cbo_SelectItemColour.Clear
    cbo_SelectItemDimensions.Clear
    cbo_SelectItemEdgeDetail.Clear
    cbo_SelectItemFamily.Clear
    cbo_SelectItemPattern.Clear
    cbo_SelectItemProductRange.Clear
    cbo_SelectItemShape.Clear
    cbo_SelectItemSurface.Clear
    
    
    If cbo_SelectItemBaseMaterial.SelectedItem Is Nothing Then
        cbo_SelectItemColour.Request = ""
        cbo_SelectItemDimensions.Request = ""
        cbo_SelectItemEdgeDetail.Request = ""
        cbo_SelectItemFamily.Request = ""
        cbo_SelectItemPattern.Request = ""
        cbo_SelectItemProductRange.Request = ""
        cbo_SelectItemShape.Request = ""
        cbo_SelectItemSurface.Request = ""
    Else
       SelI_UpdateFilters
    End If
    
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_SelectItemBaseMaterial_ComboItemSelected")
End Sub

' update base material selection
Private Sub cbo_SelectItemCategory_ComboItemSelected()
On Error GoTo ErrHandler
    Call LockScreen(True)
    
    grd_SelectItemList.ClearGrid
    cbo_SelectItemBaseMaterial.Clear
    
    cbo_SelectItemColour.Clear
    cbo_SelectItemDimensions.Clear
    cbo_SelectItemEdgeDetail.Clear
    cbo_SelectItemFamily.Clear
    cbo_SelectItemPattern.Clear
    cbo_SelectItemProductRange.Clear
    cbo_SelectItemShape.Clear
    cbo_SelectItemSurface.Clear
    cbo_SelectItemColour.Request = ""
    cbo_SelectItemDimensions.Request = ""
    cbo_SelectItemEdgeDetail.Request = ""
    cbo_SelectItemFamily.Request = ""
    cbo_SelectItemPattern.Request = ""
    cbo_SelectItemProductRange.Request = ""
    cbo_SelectItemShape.Request = ""
    cbo_SelectItemSurface.Request = ""
    
    If cbo_SelectItemCategory.SelectedItem Is Nothing Then
        cbo_SelectItemBaseMaterial.Request = ""
        
        Call SetEnabledCtrl(cbo_SelectItemDimensions, False)
        cbo_SelectItemDimensions.Clear
        Call SetEnabledCtrl(cbo_SelectItemShape, False)
        cbo_SelectItemShape.Clear
        Call SetEnabledCtrl(cbo_SelectItemSurface, False)
        cbo_SelectItemSurface.Clear
    Else
        cbo_SelectItemBaseMaterial.Request = "exec Clm_Base_Material_Link_cbo " & SqlStr(cbo_SelectItemCategory.SelectedItem.Key) & ", " & SqlStr("E")
        
        Dim ls_CategoryCode As String
        ls_CategoryCode = cbo_SelectItemCategory.SelectedItem.Key
        If ls_CategoryCode = "C001" Or ls_CategoryCode = "C006" Then    ' TODO: maybe to change edge/group (this one is edge)
            cbo_SelectItemDimensions.Enabled = GetOptionButtonCode(opt_SelectItemType) = "STD"
            cbo_SelectItemShape.Enabled = True
            cbo_SelectItemSurface.Enabled = True
        Else                                                            ' TODO: maybe to change edge/group (this one is group)
            cbo_SelectItemShape.Enabled = False
            cbo_SelectItemShape.Clear
            cbo_SelectItemSurface.Enabled = False
            cbo_SelectItemSurface.Clear
            cbo_SelectItemDimensions.Enabled = False
            cbo_SelectItemDimensions.Clear
        End If
    End If
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_SelectItemCategory_ComboItemSelected")
End Sub

' update filter selections
Private Sub cbo_SelectItemColour_ComboItemSelected()
On Error GoTo ErrHandler
    Call LockScreen(True)
    SelI_UpdateFilters
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_SelectItemColour_ComboItemSelected")
End Sub
' update filter selections
Private Sub cbo_SelectItemDimensions_ComboItemSelected()
On Error GoTo ErrHandler
    Call LockScreen(True)
    SelI_UpdateFilters
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_SelectItemDimensions_ComboItemSelected")
End Sub

' update filter selections
Private Sub cbo_SelectItemEdgeDetail_ComboItemSelected()
On Error GoTo ErrHandler
    Call LockScreen(True)
    SelI_UpdateFilters
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_SelectItemEdgeDetail_ComboItemSelected")
End Sub
' update filter selections
Private Sub cbo_SelectItemFamily_ComboItemSelected()
On Error GoTo ErrHandler
    Call LockScreen(True)
    SelI_UpdateFilters
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_SelectItemFamily_ComboItemSelected")
End Sub

' update filter selections
Private Sub cbo_SelectItemPattern_ComboItemSelected()
On Error GoTo ErrHandler
    Call LockScreen(True)
    SelI_UpdateFilters
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_SelectItemPattern_ComboItemSelected")
End Sub

' update filter selections
Private Sub cbo_SelectItemProductRange_ComboItemSelected()
On Error GoTo ErrHandler
    Call LockScreen(True)
    SelI_UpdateFilters
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_SelectItemProductRange_ComboItemSelected")
End Sub

' update filter selections
Private Sub cbo_SelectItemShape_ComboItemSelected()
On Error GoTo ErrHandler
    Call LockScreen(True)
    SelI_UpdateFilters
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_SelectItemShape_ComboItemSelected")
End Sub

' update filter selections
Private Sub cbo_SelectItemSurface_ComboItemSelected()
On Error GoTo ErrHandler
    Call LockScreen(True)
    SelI_UpdateFilters
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cbo_SelectItemSurface_ComboItemSelected")
End Sub

Private Sub cal_ItemInstalationDate_datechangee()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    Call Item_ApplyLogic(activeScreenMode)
    Exit Sub
ErrHandler:
    Call ErrorMessage("cal_ItemInstalationDate_datechangee")
End Sub

Private Sub cbo_ItemUnitMeasureCS_ComboItemSelected()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    Call Item_ApplyLogic(activeScreenMode)
    Exit Sub
ErrHandler:
    Call ErrorMessage("cbo_ItemUnitMeasureCS_ComboItemSelected")
End Sub

Private Sub cbo_ItemUnitMeasureTD_ComboItemSelected()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    Call Item_ApplyLogic(activeScreenMode)
    Exit Sub
ErrHandler:
    Call ErrorMessage("cbo_ItemUnitMeasureTD_ComboItemSelected")
End Sub

Private Sub cbo_GenOutcome_ComboItemSelected()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    Call Item_ApplyLogic(activeScreenMode)
    Exit Sub
ErrHandler:
    Call ErrorMessage("cbo_GenOutcome_ComboItemSelected")
End Sub

Private Sub SetFocusToCtrl(ByRef ao_ctrl As Object)
On Error GoTo ErrHandler
    If ao_ctrl.Visible Then
        ao_ctrl.SetFocus
    End If
    Exit Sub
ErrHandler:
    Call ErrorMessage("SetFocusToCtrl")
End Sub

Private Sub SetSumm(ByRef ao_destCtrol As TextBox, ByVal ao_src1 As TextBox, ByVal ao_src2 As TextBox, ByVal ao_src3 As TextBox)
On Error GoTo ErrHandler
    If Not IsNumericArm(ao_src1.Text) And ao_src1.Text <> "" Then
        mb_Initializing = True
        SendMessage ms_LanguageCode, ErrMsgOnlyNumericIsValid, "#Only numeric field is valid."
        Call SetFocusToCtrl(ao_src1)
        DoEvents
        mb_Initializing = False
        Exit Sub
    End If
    If Not IsNumericArm(ao_src2.Text) And ao_src2.Text <> "" Then
        mb_Initializing = True
        SendMessage ms_LanguageCode, ErrMsgOnlyNumericIsValid, "#Only numeric field is valid."
        Call SetFocusToCtrl(ao_src2)
        DoEvents
        mb_Initializing = False
        Exit Sub
    End If

    If Not IsNumericArm(ao_src3.Text) And ao_src3.Text <> "" Then
        mb_Initializing = True
        SendMessage ms_LanguageCode, ErrMsgOnlyNumericIsValid, "#Only numeric field is valid."
        Call SetFocusToCtrl(ao_src3)
        DoEvents
        mb_Initializing = False
        Exit Sub
    End If
    
    ao_destCtrol.Text = ToStr(ToDouble(ao_src1.Text) + ToDouble(ao_src2.Text) + ToDouble(ao_src3.Text), C_COST_VALUE_FORMAT)
    Exit Sub
ErrHandler:
    mb_Initializing = False
    Call ErrorHandler("SetSumm")
End Sub



Private Sub txt_CostEstLaborCost_LostFocus()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    txt_CostEstLaborCost.Text = ToStr(ToDouble(txt_CostEstLaborCost.Text), C_COST_VALUE_FORMAT)
    
    Call SetSumm(txt_CostEstTotalCost, txt_CostEstLaborCost, txt_CostEstMaterialCost, txt_CostEstOtherCost)
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_CostEstLaborCost_LostFocus")
End Sub

Private Sub txt_CostEstMaterialCost_LostFocus()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    txt_CostEstMaterialCost.Text = ToStr(ToDouble(txt_CostEstMaterialCost.Text), C_COST_VALUE_FORMAT)
    
    Call SetSumm(txt_CostEstTotalCost, txt_CostEstLaborCost, txt_CostEstMaterialCost, txt_CostEstOtherCost)
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_CostEstMaterialCost_LostFocus")
End Sub

Private Sub txt_CostEstOtherCost_LostFocus()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    txt_CostEstOtherCost.Text = ToStr(ToDouble(txt_CostEstOtherCost.Text), C_COST_VALUE_FORMAT)
    
    Call SetSumm(txt_CostEstTotalCost, txt_CostEstLaborCost, txt_CostEstMaterialCost, txt_CostEstOtherCost)
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_CostEstOtherCost_LostFocus")
End Sub

Private Sub txt_CostSetLaborCost_LostFocus()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    txt_CostSetLaborCost.Text = ToStr(ToDouble(txt_CostSetLaborCost.Text), C_COST_VALUE_FORMAT)
    
    Call SetSumm(txt_CostSetTotalCost, txt_CostSetLaborCost, txt_CostSetMaterialCost, txt_CostSetOtherCost)
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_CostSetLaborCost_LostFocus")
End Sub

Private Sub txt_CostSetMaterialCost_LostFocus()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    txt_CostSetMaterialCost.Text = ToStr(ToDouble(txt_CostSetMaterialCost.Text), C_COST_VALUE_FORMAT)
    
    Call SetSumm(txt_CostSetTotalCost, txt_CostSetLaborCost, txt_CostSetMaterialCost, txt_CostSetOtherCost)
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_CostSetMaterialCost_LostFocus")
End Sub

Private Sub txt_CostSetOtherCost_LostFocus()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    txt_CostSetOtherCost.Text = ToStr(ToDouble(txt_CostSetOtherCost.Text), C_COST_VALUE_FORMAT)
    
    Call SetSumm(txt_CostSetTotalCost, txt_CostSetLaborCost, txt_CostSetMaterialCost, txt_CostSetOtherCost)
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_CostSetOtherCost_LostFocus")
End Sub

Private Sub txt_SelProjModSize_LostFocus()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    txt_SelProjModSize.Text = ToStr(ToDouble(txt_SelProjModSize.Text), C_NUMERIC_VALUE_FORMAT)
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_SelProjModSize_LostFocus")
End Sub

Private Sub txt_ItemClaimSize_LostFocus()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    txt_ItemClaimSize.Text = ToStr(ToDouble(txt_ItemClaimSize.Text), C_NUMERIC_VALUE_FORMAT)
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_ItemClaimSize_LostFocus")
End Sub

Private Sub txt_ItemTotalDelivery_LostFocus()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    txt_ItemTotalDelivery.Text = ToStr(ToDouble(txt_ItemTotalDelivery.Text), C_NUMERIC_VALUE_FORMAT)
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_ItemTotalDelivery_LostFocus")
End Sub

Private Sub txt_NoteAmount_LostFocus()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    txt_NoteAmount.Text = ToStr(ToDouble(txt_NoteAmount.Text), C_NUMERIC_VALUE_FORMAT)
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_NoteAmount_LostFocus")
End Sub

Private Sub txt_ProSize_LostFocus()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    txt_ProSize.Text = ToStr(ToDouble(txt_ProSize.Text), C_NUMERIC_VALUE_FORMAT)
    Call Item_ApplyLogic(activeScreenMode)
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_ProSize_LostFocus")
End Sub

Private Sub cbo_ProUnitMeasure_ComboItemSelected()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    Call Item_ApplyLogic(activeScreenMode)
    Exit Sub
ErrHandler:
    Call ErrorMessage("cbo_ProUnitMeasure_ComboItemSelected")
End Sub

Private Sub opt_ProSiteCondition_Click(Index As Integer)
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    Call Item_ApplyLogic(activeScreenMode)
    Exit Sub
ErrHandler:
    Call ErrorMessage("opt_ProSiteCondition_Click")
End Sub

Private Sub txt_SelectCustLike_KeyPress(KeyAscii As Integer)
On Error GoTo ErrHandler
    If KeyAscii = 13 Then Call tlb_Main_action("M", tlb_Main.Language)
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_SelectCustLike_KeyPress")
End Sub

Private Sub txt_SelectProjLike_KeyPress(KeyAscii As Integer)
On Error GoTo ErrHandler
    If KeyAscii = 13 Then Call tlb_Main_action("M", tlb_Main.Language)
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_SelectProjLike_KeyPress")
End Sub

Private Sub btn_costMoveEst_Click()
On Error GoTo ErrHandler
    txt_CostSetLaborCost.Text = txt_CostEstLaborCost.Text
    txt_CostSetMaterialCost.Text = txt_CostEstMaterialCost.Text
    txt_CostSetOtherCost.Text = txt_CostEstOtherCost.Text
    txt_CostSetTotalCost.Text = txt_CostEstTotalCost.Text
    Exit Sub
ErrHandler:
    Call ErrorMessage("btn_costMoveEst_Click")
End Sub

Private Sub cbo_MemoLanguage_ComboItemSelected()
On Error GoTo ErrHandler
    ' set charset for title and description
    Dim lo_array As Collection
    Set lo_array = New Collection
    
    ' controls that are language dependent of selected language, except grids - grids are set in fill functions
    Call lo_array.Add(txt_MemoTitle)
    Call lo_array.Add(txt_MemoComment)

    Call ChangeCharset(lo_array, GetCodePageFromLanguage(ml_codePageCursor, SQLComboBoxValue(cbo_MemoLanguage, "E")))
    Set lo_array = Nothing
    
    'txt_MemoCommentEng allways english
    
    Exit Sub
ErrHandler:
    Call ErrorMessage("cbo_MemoLanguage_ComboItemSelected")
End Sub


Private Sub cmd_linkedFiles_Click()
On Error GoTo ErrHandler
    frm_linkedFiles.Visible = True
    Call frm_linkedFiles.Zorder
    grd_linkedFiles.Refresh
    Exit Sub
ErrHandler:
    Call ErrorMessage("cmd_linkedFiles_Click")
End Sub


Private Sub grd_linkedFiles_OLEDragDrop(Data As MSFlexGridLib.DataObject, Effect As Long, Button As Integer, Shift As Integer, x As Single, y As Single)
On Error GoTo ErrHandler

    If txt_GenReport.Text = "" Then
        SendMessage ms_LanguageCode, MsgCannotInsertFile, "#Cannot link the file when claim is not recorded."
        Exit Sub
    End If
    ' get dropeed email from outlook express or dropped files
    If Data.GetFormat(vbCFText) Then
        ' it can be email
        Call UploadOutlookEmail(txt_GenReport.Text)
        
    ElseIf Data.GetFormat(vbCFFiles) Then
        ' it is one or more files
        Dim ll_i As Long
        
        For ll_i = 1 To Data.Files.Count
            Dim lsa_segments() As String
            lsa_segments = Split(Data.Files.Item(ll_i), "\")
            Call UploadLinkedFile(Data.Files.Item(ll_i), lsa_segments(UBound(lsa_segments)), txt_GenReport.Text)
        Next
    End If
    
    ' refresh the grid
    Call grd_linkedFiles.Refresh

    Exit Sub
ErrHandler:
    Call ErrorMessage("grd_linkedFiles_OLEDragDrop")
End Sub

Private Function UploadLinkedFile(ByVal as_filePath As String, ByVal as_fileName As String, ByVal as_CLA_code As String) As Long
On Error GoTo ErrHandler
Const C_REQ_ZIPFILE As String = "INSERT INTO Claim_LinkedFileZip VALUES($CLA_ZIP_ID$, ?)"
Const C_REQ_FILE As String = "Claim_LinkedFile_ins $CLA_FILE_ID$, '$CLA_CODE$', $CLA_ZIP_ID$, '$FILE_NAME$', $Z_Creator$"
    
    Dim ls_CLA_FILE_ID As String
    Dim ls_CLA_ZIP_ID As String

    UploadLinkedFile = -1
    
    ' getnext ID for the file
    ls_CLA_FILE_ID = mo_Db.SQLNextID("Claim_LinkedFile")
    If ls_CLA_FILE_ID = "" Then
        Err.Raise ArmErr.CompFncFailed, "mo_Db.SQLNextID", "SQLNextID failed for: Claim_LinkedFile"
    End If
    
    ls_CLA_ZIP_ID = mo_Db.SQLNextID("Claim_LinkedFileZip")
    If ls_CLA_ZIP_ID = "" Then
        Err.Raise ArmErr.CompFncFailed, "mo_Db.SQLNextID", "SQLNextID failed for: Claim_LinkedFileZip"
    End If

    'Insert the file
    Dim ls_req
    ls_req = Replace(C_REQ_ZIPFILE, "$CLA_ZIP_ID$", ls_CLA_ZIP_ID, , , vbTextCompare)
    
    If Not mo_Db.FileToBlobSQL(ls_req, as_filePath, 9) Then
        Err.Raise ArmErr.CompFncFailed, "FileToBlobSQL", mo_Db.LastErrorMessage & " Error writing blob: " & ls_req & " File: " & as_fileName
    End If
    
    ' insert file record
    ls_req = Replace(C_REQ_FILE, "$Z_Creator$", ml_UserCode, , , vbTextCompare)
    ls_req = Replace(ls_req, "$CLA_FILE_ID$", ls_CLA_FILE_ID, , , vbTextCompare)
    ls_req = Replace(ls_req, "$CLA_CODE$", SqlStr(as_CLA_code), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CLA_ZIP_ID$", ls_CLA_ZIP_ID, , , vbTextCompare)
    ls_req = Replace(ls_req, "$FILE_NAME$", SqlStr(as_fileName, 150), , , vbTextCompare)
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)

    UploadLinkedFile = ls_CLA_FILE_ID
    Exit Function
ErrHandler:
    Call ErrorMessage("UploadLinkedFile")
End Function

Private Sub DeleteLinkedFile()
Const C_REQ As String = "EXEC Claim_LinkedFile_del $CLA_FILE_ID$, $Z_Last_Upd_User$, $ICONC$"
Const C_REQ_EMLINFO As String = "EXEC Claim_LinkedEmailInfo_del $CLA_FILE_ID$, $Z_Last_Upd_User$, $ICONC$"
On Error GoTo ErrHandler

    Dim ll_i As Long
    Dim ls_req As String
    
    For ll_i = 0 To grd_linkedFiles.SelectedCount - 1
    
        ls_req = Replace(C_REQ, "$Z_Last_Upd_User$", ml_UserCode, , , vbTextCompare)
        ls_req = Replace(ls_req, "$CLA_FILE_ID$", grd_linkedFiles.SelectedKey(ll_i)(0), , , vbTextCompare)
        ls_req = Replace(ls_req, "$ICONC$", grd_linkedFiles.SelectedLine(ll_i, "iConcurrency"), , , vbTextCompare)
        
        Call ExecuteSQLSafe(mo_Db, ls_req, 1)
        
        If grd_linkedFiles.SelectedLine(ll_i, "EmailInfoIconc") <> 0 Then
            ' clear also emilInfo
            ls_req = Replace(C_REQ_EMLINFO, "$Z_Last_Upd_User$", ml_UserCode, , , vbTextCompare)
            ls_req = Replace(ls_req, "$CLA_FILE_ID$", grd_linkedFiles.SelectedKey(ll_i)(0), , , vbTextCompare)
            ls_req = Replace(ls_req, "$ICONC$", grd_linkedFiles.SelectedLine(ll_i, "EmailInfoIconc"), , , vbTextCompare)
            
            Call ExecuteSQLSafe(mo_Db, ls_req, 1)
        End If
    Next
    
    ' remove all selected lines
    Call grd_linkedFiles.DeleteSelectedLines

    Exit Sub
ErrHandler:
    Call ErrorHandler("DeleteLinkedEmails")
End Sub

Private Sub UploadOutlookEmail(ByVal as_CLA_code As String)
On Error GoTo ErrHandler
Const C_REQ As String = "Claim_LinkedEmailInfo_ins $CLA_FILE_ID$, '$EML_Subject$', '$EML_SenderEmailAddress$', '$EML_To$', '$EML_SenderName$', $EML_Attachements$, $EML_CreationTime$, $Z_Creator$"

    Dim mo_OtlSel As Object
    Dim mo_OtlExp As Object
    Dim mo_OtlApp As Object
    Dim ll_Idx As Long
    
    Set mo_OtlApp = CreateObject("Outlook.Application")
    If mo_OtlApp Is Nothing Then
        Call MsgBox("Outlook application not found!!", vbCritical)
        Exit Sub
    End If
    
    Set mo_OtlExp = mo_OtlApp.ActiveExplorer
    If mo_OtlExp Is Nothing Then
        Call MsgBox("Outlook ActiveExplorer not found!!", vbCritical)
        Set mo_OtlApp = Nothing
        Exit Sub
    End If
    
    Set mo_OtlSel = mo_OtlExp.selection
    If mo_OtlSel Is Nothing Then
        Call MsgBox("Outlook selection not found!!", vbCritical)
        Set mo_OtlExp = Nothing
        Set mo_OtlApp = Nothing
        Exit Sub
    End If
    
    Dim ll_CLA_FILE_ID As String
    Dim ls_req As String
    Dim ls_eml_file  As String
    Dim ls_Subject As String
    Dim ls_To As String
    Dim ls_SenderEmail As String
    Dim ls_SenderName As String
    Dim ld_creationTime As Date
    
    Dim ll_Attachements As Long

    For ll_Idx = 1 To mo_OtlSel.Count
        ' get info before save
        ls_Subject = mo_OtlSel.Item(ll_Idx).Subject
        ls_To = mo_OtlSel.Item(ll_Idx).To
        ll_Attachements = mo_OtlSel.Item(ll_Idx).Attachments.Count
        ls_SenderEmail = mo_OtlSel.Item(ll_Idx).SenderEmailAddress
        ls_SenderName = mo_OtlSel.Item(ll_Idx).SenderName
        ld_creationTime = mo_OtlSel.Item(ll_Idx).CreationTime
        
        'Save the file
        ls_eml_file = App.Path & "\download\Claim_Email_" & as_CLA_code & ".msg"
        Call mo_OtlSel.Item(ll_Idx).SaveAs(ls_eml_file, 3)      'olMSG
        
        ll_CLA_FILE_ID = UploadLinkedFile(ls_eml_file, "Claim_Email_" & as_CLA_code & ".msg", as_CLA_code)
        
        If ll_CLA_FILE_ID <> -1 Then
            ' insert email info record
            ls_req = Replace(C_REQ, "$Z_Creator$", ml_UserCode, , , vbTextCompare)
            ls_req = Replace(ls_req, "$CLA_FILE_ID$", ll_CLA_FILE_ID, , , vbTextCompare)
            ls_req = Replace(ls_req, "$EML_Subject$", SqlStr(ls_Subject, 150), , , vbTextCompare)
            ls_req = Replace(ls_req, "$EML_SenderEmailAddress$", SqlStr(ls_SenderEmail, 150), , , vbTextCompare)
            ls_req = Replace(ls_req, "$EML_To$", SqlStr(ls_To, 150), , , vbTextCompare)
            ls_req = Replace(ls_req, "$EML_SenderName$", SqlStr(ls_SenderName, 150), , , vbTextCompare)
            ls_req = Replace(ls_req, "$EML_Attachements$", ll_Attachements, , , vbTextCompare)
            ls_req = Replace(ls_req, "$EML_CreationTime$", SQLDateTime(ld_creationTime), , , vbTextCompare)
            Call ExecuteSQLSafe(mo_Db, ls_req)
        End If
    Next
    
    Set mo_OtlExp = Nothing
    Set mo_OtlApp = Nothing

    Exit Sub
ErrHandler:
    Call ErrorMessage("UploadOutlookEmail")
End Sub


Private Function GetArrayValue(ByRef ao_variantArray As Variant, ByVal al_Index As Long) As Variant
    If IsArray(ao_variantArray) Then
        If UBound(ao_variantArray) <= al_Index Then
            GetArrayValue = ao_variantArray(al_Index)
        Else
            GetArrayValue = 0
        End If
    Else
        GetArrayValue = 0
    End If
End Function


Private Sub SafeCtrlMove(ByRef ao_ctrl As Control, Optional ByVal al_left As Variant, Optional ByVal al_top As Variant, Optional ByVal al_width As Variant, Optional ByVal al_height As Variant)
On Error GoTo ErrHandler

    If al_left < 0 Then al_left = 0
    
    If Not IsMissing(al_top) Then
        If al_top < 0 Then al_top = 0
    End If
        
    If Not IsMissing(al_width) Then
        If al_width < 0 Then al_width = 0
    End If
    
    If Not IsMissing(al_height) Then
        If al_height < 0 Then al_height = 0
    End If
    
    If Not IsMissing(al_top) And _
        Not IsMissing(al_width) And _
        Not IsMissing(al_height) Then
        Call ao_ctrl.Move(al_left, al_top, al_width, al_height)
    ElseIf Not IsMissing(al_top) And _
            Not IsMissing(al_width) Then
        Call ao_ctrl.Move(al_left, al_top, al_width)
    ElseIf Not IsMissing(al_top) And _
            Not IsMissing(al_height) Then
        Call ao_ctrl.Move(al_left, al_top, , al_height)
    ElseIf Not IsMissing(al_width) And _
            Not IsMissing(al_height) Then
        Call ao_ctrl.Move(al_left, , al_width, al_height)
    ElseIf Not IsMissing(al_top) Then
        Call ao_ctrl.Move(al_left, al_top)
    ElseIf Not IsMissing(al_width) Then
        Call ao_ctrl.Move(al_left, , al_width)
    ElseIf Not IsMissing(al_height) Then
        Call ao_ctrl.Move(al_left, , , al_height)
    End If
    
    Exit Sub

ErrHandler:
    Call ErrorHandler("SafeCtrlMove")
End Sub


Private Sub UserControl_Resize()
On Error GoTo ErrHandler

    If ml_UserCode <> 0 Then
        Call InitCtrlSize
    End If
    
    Exit Sub
ErrHandler:
    Call ErrorMessage("UserControl_Resize")
End Sub
