VERSION 5.00
Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0"; "MSCOMCTL.OCX"
Begin VB.UserControl cpTstMan 
   ClientHeight    =   14835
   ClientLeft      =   0
   ClientTop       =   0
   ClientWidth     =   19080
   ScaleHeight     =   14835
   ScaleWidth      =   19080
   Begin VB.Frame fraItem 
      Height          =   14055
      Left            =   60
      TabIndex        =   21
      Top             =   60
      Width           =   16575
      Begin VB.Frame fraItemDocuments 
         Height          =   5655
         Left            =   9000
         TabIndex        =   61
         Top             =   8280
         Visible         =   0   'False
         Width           =   8415
         Begin Project1.ArmGrid grItemDoc 
            Height          =   4815
            Left            =   120
            TabIndex        =   35
            Top             =   240
            Width           =   7095
            _ExtentX        =   12515
            _ExtentY        =   8493
         End
      End
      Begin VB.Frame fraItemDocumentMtnc 
         Height          =   7005
         Left            =   60
         TabIndex        =   79
         Top             =   6600
         Width           =   10215
         Begin Project1.A_calocx caValidityEndDate 
            Height          =   375
            Left            =   6060
            TabIndex        =   117
            Tag             =   "caValidityEndDate"
            Top             =   4200
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   661
         End
         Begin Project1.A_calocx caValidityStartDate 
            Height          =   375
            Left            =   2100
            TabIndex        =   115
            Tag             =   "caValidityStartDate"
            Top             =   4200
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   661
         End
         Begin Project1.ArmCombobox cbo_access 
            Height          =   345
            Left            =   2100
            TabIndex        =   123
            Top             =   5040
            Width           =   1935
            _ExtentX        =   3413
            _ExtentY        =   609
         End
         Begin VB.TextBox txt_spare2 
            Height          =   315
            Left            =   6120
            TabIndex        =   122
            Text            =   "Text1"
            Top             =   5100
            Visible         =   0   'False
            Width           =   1455
         End
         Begin VB.TextBox txt_spare1 
            Height          =   315
            Left            =   6120
            TabIndex        =   121
            Text            =   "Text1"
            Top             =   4800
            Visible         =   0   'False
            Width           =   1455
         End
         Begin VB.CheckBox chk_internet 
            Caption         =   "#Internet flag"
            Height          =   255
            Left            =   1200
            TabIndex        =   114
            Tag             =   "lbl_Int"
            Top             =   5760
            Visible         =   0   'False
            Width           =   1575
         End
         Begin Project1.ArmCombobox cbo_DocumentLanguage 
            Height          =   345
            Left            =   2520
            TabIndex        =   39
            Top             =   960
            Width           =   4575
            _ExtentX        =   8070
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_Ext 
            Height          =   345
            Left            =   2520
            TabIndex        =   37
            Top             =   600
            Width           =   4575
            _ExtentX        =   8070
            _ExtentY        =   609
         End
         Begin VB.DriveListBox drv_Full 
            Height          =   315
            Left            =   120
            TabIndex        =   40
            Top             =   1320
            Width           =   3615
         End
         Begin VB.DirListBox dir_Full 
            Height          =   2115
            Left            =   120
            TabIndex        =   42
            Top             =   1680
            Width           =   3615
         End
         Begin VB.FileListBox fil_Full 
            Height          =   2430
            Left            =   3840
            TabIndex        =   43
            Top             =   1320
            Width           =   3255
         End
         Begin VB.TextBox txt_File 
            Height          =   312
            Left            =   2520
            Locked          =   -1  'True
            TabIndex        =   44
            Top             =   3840
            Width           =   4575
         End
         Begin VB.TextBox txt_Title 
            Height          =   312
            Left            =   2520
            MaxLength       =   80
            TabIndex        =   36
            Top             =   240
            Width           =   4575
         End
         Begin VB.Label lb_labels 
            Caption         =   "#Access type :"
            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
            Left            =   120
            TabIndex        =   124
            Tag             =   "lbl_accessType"
            Top             =   5160
            Width           =   2055
         End
         Begin VB.Label lb_spare2 
            Caption         =   "spare2"
            Height          =   255
            Left            =   4980
            TabIndex        =   120
            Tag             =   "lb_spare2"
            Top             =   5100
            Visible         =   0   'False
            Width           =   975
         End
         Begin VB.Label lb_spare1 
            Caption         =   "spare1"
            Height          =   255
            Left            =   4980
            TabIndex        =   119
            Tag             =   "lb_spare1"
            Top             =   4800
            Visible         =   0   'False
            Width           =   975
         End
         Begin VB.Label lbl_ValidityEndDate 
            Caption         =   "#Validity end date :"
            Height          =   255
            Left            =   4080
            TabIndex        =   118
            Tag             =   "lbl_ValidityEndDate"
            Top             =   4320
            Width           =   1935
         End
         Begin VB.Label lbl_ValidityStartDate 
            Caption         =   "#Validity start date :"
            Height          =   255
            Left            =   120
            TabIndex        =   116
            Tag             =   "lbl_ValidityStartDate"
            Top             =   4320
            Width           =   1935
         End
         Begin VB.Label lbl_DocumentLanguage 
            Caption         =   "#Document 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
            Left            =   120
            TabIndex        =   83
            Tag             =   "lbl_DocLanguage"
            Top             =   960
            Width           =   2055
         End
         Begin VB.Label lbl_Current 
            Caption         =   "#Current attachment"
            Height          =   195
            Left            =   120
            TabIndex        =   82
            Tag             =   "lbl_DocFile"
            Top             =   3960
            Width           =   2355
         End
         Begin VB.Label lbl_Ext 
            Caption         =   "#Extension :"
            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
            Left            =   120
            TabIndex        =   81
            Tag             =   "lbl_DocExt"
            Top             =   720
            Width           =   1335
         End
         Begin VB.Label lbl_Title 
            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
            Left            =   120
            TabIndex        =   80
            Tag             =   "lbl_DocTitle"
            Top             =   360
            Width           =   1455
         End
      End
      Begin VB.Frame fraItemGeneral 
         Height          =   8655
         Left            =   840
         TabIndex        =   38
         Top             =   1440
         Width           =   9495
         Begin Project1.A_calocx caStartDate 
            Height          =   375
            Left            =   3000
            TabIndex        =   15
            Tag             =   "caStartDate"
            Top             =   4080
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   661
         End
         Begin Project1.A_calocx caEndDate 
            Height          =   375
            Left            =   3000
            TabIndex        =   17
            Tag             =   "caEndDate"
            Top             =   4560
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   661
         End
         Begin Project1.A_calocx caOldDate 
            Height          =   375
            Left            =   3000
            TabIndex        =   19
            Tag             =   "caOldDate"
            Top             =   5040
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   661
         End
         Begin Project1.A_calocx caDropDate 
            Height          =   375
            Left            =   3000
            TabIndex        =   20
            Tag             =   "caDropDate"
            Top             =   5520
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   661
         End
         Begin Project1.ArmCheckView acvCountries 
            Height          =   1575
            Left            =   3240
            TabIndex        =   108
            Tag             =   "acvCountries"
            Top             =   6240
            Width           =   2895
            _ExtentX        =   5106
            _ExtentY        =   2778
         End
         Begin Project1.ArmCheckView acvMarkets 
            Height          =   1575
            Left            =   120
            TabIndex        =   107
            Tag             =   "acvMarkets"
            Top             =   6240
            Width           =   2895
            _ExtentX        =   5106
            _ExtentY        =   2778
         End
         Begin VB.TextBox txt_IndicTestNumber 
            Height          =   285
            Left            =   3000
            Locked          =   -1  'True
            MaxLength       =   30
            TabIndex        =   14
            Tag             =   "txt_IndicTestNumber"
            Top             =   3600
            Width           =   6375
         End
         Begin VB.TextBox txt_FullTestNumber 
            Height          =   285
            Left            =   3000
            Locked          =   -1  'True
            MaxLength       =   30
            TabIndex        =   13
            Tag             =   "txt_FullTestNumber"
            Top             =   3120
            Width           =   6375
         End
         Begin VB.TextBox txt_MotherTest 
            Height          =   285
            Left            =   3000
            Locked          =   -1  'True
            TabIndex        =   12
            Tag             =   "txt_MotherTest"
            Top             =   2640
            Width           =   6375
         End
         Begin VB.CheckBox chk_Int 
            Caption         =   "#Internet flag"
            Enabled         =   0   'False
            Height          =   252
            Left            =   5040
            TabIndex        =   18
            Tag             =   "lbl_Int"
            Top             =   4680
            Width           =   1695
         End
         Begin VB.CommandButton cmd_Memo 
            Caption         =   "#Test memo..."
            Height          =   435
            Left            =   5040
            TabIndex        =   16
            Tag             =   "cmd_Memo"
            Top             =   4080
            Width           =   1695
         End
         Begin Project1.ArmCombobox cbo_ivgTestManager 
            Height          =   345
            Left            =   3000
            TabIndex        =   11
            Tag             =   "cbo_ivgTestManager"
            Top             =   2160
            Width           =   6375
            _ExtentX        =   11245
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_ivgSalesOffice 
            Height          =   345
            Left            =   3000
            TabIndex        =   10
            Tag             =   "cbo_ivgSalesOffice"
            Top             =   1680
            Width           =   6375
            _ExtentX        =   11245
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_ivgTestHouse 
            Height          =   345
            Left            =   3000
            TabIndex        =   9
            Tag             =   "cbo_ivgTestHouse"
            Top             =   1200
            Width           =   6375
            _ExtentX        =   11245
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_ivgStandard 
            Height          =   345
            Left            =   3000
            TabIndex        =   8
            Tag             =   "cbo_ivgStandard"
            Top             =   720
            Width           =   6375
            _ExtentX        =   11245
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_ivgCategory 
            Height          =   345
            Left            =   3000
            TabIndex        =   7
            Tag             =   "cbo_ivgCategory"
            Top             =   240
            Width           =   6375
            _ExtentX        =   11245
            _ExtentY        =   609
         End
         Begin VB.Label lblMarkets 
            Caption         =   "#Markets"
            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
            Left            =   120
            TabIndex        =   109
            Tag             =   "lblMarkets"
            Top             =   6000
            Width           =   1455
         End
         Begin VB.Label lbl_Category 
            Caption         =   "#Category :"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   195
            Left            =   120
            TabIndex        =   55
            Tag             =   "lbl_Category"
            Top             =   360
            Width           =   2475
         End
         Begin VB.Label lbl_TestManager 
            Caption         =   "#Test Manager :"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   195
            Left            =   120
            TabIndex        =   54
            Tag             =   "lbl_TestManager"
            Top             =   2280
            Width           =   2475
         End
         Begin VB.Label lbl_TestHouse 
            Caption         =   "#Test House :"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   195
            Left            =   120
            TabIndex        =   53
            Tag             =   "lbl_TestHouse"
            Top             =   1320
            Width           =   2475
         End
         Begin VB.Label lbl_Standard 
            Caption         =   "#Standard :"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   195
            Left            =   120
            TabIndex        =   52
            Tag             =   "lbl_Standard"
            Top             =   840
            Width           =   2475
         End
         Begin VB.Label lbl_Drop 
            Caption         =   "#Drop date :"
            Height          =   255
            Left            =   120
            TabIndex        =   51
            Tag             =   "lbl_Drop"
            Top             =   5640
            Width           =   2475
         End
         Begin VB.Label lbl_MotherTest 
            Caption         =   "#Mother Test :"
            Height          =   195
            Left            =   120
            TabIndex        =   50
            Tag             =   "lbl_MotherTest"
            Top             =   2760
            Width           =   2475
         End
         Begin VB.Label lbl_IndicTestNumber 
            Caption         =   "#Indicative Number :"
            Height          =   255
            Left            =   120
            TabIndex        =   49
            Tag             =   "lbl_IndicTestNumber"
            Top             =   3720
            Width           =   2475
         End
         Begin VB.Label lbl_FullTestNumber 
            Caption         =   "#Full Test Number :"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   195
            Left            =   120
            TabIndex        =   48
            Tag             =   "lbl_FullTestNumber"
            Top             =   3240
            Width           =   2475
         End
         Begin VB.Label lbl_StartDate 
            Caption         =   "#Start 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
            Left            =   120
            TabIndex        =   47
            Tag             =   "lbl_StartDate"
            Top             =   4200
            Width           =   2475
         End
         Begin VB.Label lbl_EndDate 
            Caption         =   "#End date :"
            Height          =   255
            Left            =   120
            TabIndex        =   46
            Tag             =   "lbl_EndDate"
            Top             =   4680
            Width           =   2475
         End
         Begin VB.Label lbl_TestOffice 
            Caption         =   "#Sales Office :"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   195
            Left            =   120
            TabIndex        =   45
            Tag             =   "lbl_TestOffice"
            Top             =   1800
            Width           =   2475
         End
         Begin VB.Label lbl_olddate 
            Caption         =   "#Old but still relevant :"
            Height          =   255
            Left            =   120
            TabIndex        =   41
            Tag             =   "lbl_olddate"
            Top             =   5160
            Width           =   2475
         End
         Begin VB.Label lblCountries 
            Caption         =   "#Countries exceptions"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            ForeColor       =   &H000000FF&
            Height          =   255
            Left            =   3240
            TabIndex        =   110
            Tag             =   "lblCountries"
            Top             =   6000
            Width           =   3375
         End
      End
      Begin VB.Frame fraItemReminder 
         Height          =   2655
         Left            =   7080
         TabIndex        =   96
         Top             =   720
         Width           =   9495
         Begin VB.TextBox txtRmTMg 
            BackColor       =   &H80000018&
            Height          =   345
            Left            =   3000
            Locked          =   -1  'True
            TabIndex        =   106
            Top             =   2160
            Width           =   6375
         End
         Begin VB.TextBox txtRmSO 
            BackColor       =   &H80000018&
            Height          =   345
            Left            =   3000
            Locked          =   -1  'True
            TabIndex        =   105
            Top             =   1680
            Width           =   6375
         End
         Begin VB.TextBox txtRmTHo 
            BackColor       =   &H80000018&
            Height          =   345
            Left            =   3000
            Locked          =   -1  'True
            TabIndex        =   104
            Top             =   1200
            Width           =   6375
         End
         Begin VB.TextBox txtRmStd 
            BackColor       =   &H80000018&
            Height          =   345
            Left            =   3000
            Locked          =   -1  'True
            TabIndex        =   103
            Top             =   720
            Width           =   6375
         End
         Begin VB.TextBox txtRmCat 
            BackColor       =   &H80000018&
            Height          =   345
            Left            =   3000
            Locked          =   -1  'True
            TabIndex        =   102
            Top             =   240
            Width           =   6375
         End
         Begin VB.Label lblRmSO 
            Caption         =   "#Sales Office :"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   195
            Left            =   120
            TabIndex        =   101
            Tag             =   "lbl_TestOffice"
            Top             =   1800
            Width           =   2475
         End
         Begin VB.Label lblRmStd 
            Caption         =   "#Standard :"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   195
            Left            =   120
            TabIndex        =   100
            Tag             =   "lbl_Standard"
            Top             =   840
            Width           =   2475
         End
         Begin VB.Label lblRmTHo 
            Caption         =   "#Test House :"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   195
            Left            =   120
            TabIndex        =   99
            Tag             =   "lbl_TestHouse"
            Top             =   1320
            Width           =   2475
         End
         Begin VB.Label lblRmTMg 
            Caption         =   "#Test Manager :"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   195
            Left            =   120
            TabIndex        =   98
            Tag             =   "lbl_TestManager"
            Top             =   2280
            Width           =   2475
         End
         Begin VB.Label lblRmCat 
            Caption         =   "#Category :"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   8.25
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   195
            Left            =   120
            TabIndex        =   97
            Tag             =   "lbl_Category"
            Top             =   360
            Width           =   2475
         End
      End
      Begin VB.ListBox lst_on_what5 
         Height          =   1035
         ItemData        =   "cpTstMan.ctx":0000
         Left            =   11520
         List            =   "cpTstMan.ctx":0002
         TabIndex        =   89
         Tag             =   "SSTRlst_On_What5"
         Top             =   3360
         Visible         =   0   'False
         Width           =   1860
      End
      Begin VB.Frame fraItemConditionsMtnc 
         Height          =   7455
         Left            =   1200
         TabIndex        =   73
         Top             =   6240
         Width           =   7695
         Begin VB.TextBox txt_Cnd 
            Height          =   375
            Left            =   120
            MaxLength       =   30
            TabIndex        =   78
            Top             =   1440
            Width           =   5055
         End
         Begin VB.ListBox lst_Cnd 
            Height          =   5520
            ItemData        =   "cpTstMan.ctx":0004
            Left            =   120
            List            =   "cpTstMan.ctx":000B
            TabIndex        =   76
            Top             =   1440
            Width           =   7095
         End
         Begin Project1.ArmCombobox cbo_TypeCnd 
            Height          =   345
            Left            =   120
            TabIndex        =   75
            Top             =   480
            Width           =   3495
            _ExtentX        =   6165
            _ExtentY        =   609
         End
         Begin VB.Label lbl_dtlcnd 
            Caption         =   "lbl_dtlcnd"
            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
            Left            =   120
            TabIndex        =   77
            Tag             =   "lbl_dtlcnd"
            Top             =   1080
            Width           =   1695
         End
         Begin VB.Label lbl_typcnd 
            Caption         =   "lbl_typcnd"
            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
            Left            =   120
            TabIndex        =   74
            Tag             =   "lbl_typcnd"
            Top             =   240
            Width           =   1695
         End
      End
      Begin VB.ListBox lst_on_what4 
         Height          =   1035
         ItemData        =   "cpTstMan.ctx":0018
         Left            =   11520
         List            =   "cpTstMan.ctx":001A
         TabIndex        =   86
         Tag             =   "SSTRlst_On_What4"
         Top             =   2880
         Visible         =   0   'False
         Width           =   1860
      End
      Begin Project1.ToolbarControl tcItem 
         Height          =   4770
         Left            =   13320
         TabIndex        =   72
         Top             =   1200
         Width           =   690
         _ExtentX        =   1217
         _ExtentY        =   8414
      End
      Begin VB.ListBox lst_On_What 
         Height          =   1035
         ItemData        =   "cpTstMan.ctx":001C
         Left            =   11520
         List            =   "cpTstMan.ctx":001E
         TabIndex        =   71
         Tag             =   "SSTRlst_On_What"
         Top             =   2880
         Visible         =   0   'False
         Width           =   1860
      End
      Begin VB.ListBox lst_On_What2 
         Height          =   1035
         ItemData        =   "cpTstMan.ctx":0020
         Left            =   11520
         List            =   "cpTstMan.ctx":0022
         TabIndex        =   70
         Tag             =   "SSTRlst_On_What2"
         Top             =   3360
         Visible         =   0   'False
         Width           =   1860
      End
      Begin VB.Frame fraItemFullNumber 
         Height          =   855
         Left            =   4800
         TabIndex        =   63
         Top             =   120
         Width           =   5535
         Begin VB.TextBox txt_ItemFullNumber 
            Height          =   285
            Left            =   1680
            TabIndex        =   6
            Top             =   450
            Width           =   3615
         End
         Begin VB.Label lbl_TestType 
            Caption         =   "#Test type"
            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
            Left            =   120
            TabIndex        =   88
            Top             =   150
            Width           =   5055
         End
         Begin VB.Label lbl_TestFullNumber 
            Caption         =   "#Test full number"
            Height          =   255
            Left            =   120
            TabIndex        =   64
            Tag             =   "lbl_TestFullNumber"
            Top             =   480
            Width           =   1335
         End
      End
      Begin MSComctlLib.TabStrip tabCmd 
         Height          =   735
         Left            =   120
         TabIndex        =   5
         Tag             =   "tabCmd"
         Top             =   240
         Width           =   5280
         _ExtentX        =   9313
         _ExtentY        =   1296
         TabWidthStyle   =   2
         MultiRow        =   -1  'True
         Style           =   1
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   6
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#General"
               Key             =   "k0"
               Object.Tag             =   "tbs_general"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Conditions"
               Key             =   "k1"
               Object.Tag             =   "tbs_condition"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Results"
               Key             =   "k2"
               Object.Tag             =   "tbs_result"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab4 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Products"
               Key             =   "k3"
               Object.Tag             =   "tbs_product"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab5 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Documents"
               Key             =   "k4"
               Object.Tag             =   "tbs_document"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab6 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Dependancies"
               Key             =   "k5"
               Object.Tag             =   "tbs_Tree"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin VB.Frame fraItemTree 
         Height          =   7095
         Left            =   1920
         TabIndex        =   111
         Top             =   4080
         Width           =   6375
         Begin Project1.ArmCombobox cbo_ItemTreeViews 
            Height          =   345
            Left            =   120
            TabIndex        =   113
            Top             =   240
            Width           =   3975
            _ExtentX        =   7011
            _ExtentY        =   609
         End
         Begin Project1.ArmTreeView tvItemTree 
            Height          =   6135
            Left            =   120
            TabIndex        =   112
            Top             =   600
            Width           =   3975
            _ExtentX        =   7011
            _ExtentY        =   10821
         End
      End
      Begin VB.Frame fraItemProducts 
         Height          =   12135
         Left            =   720
         TabIndex        =   59
         Top             =   4440
         Visible         =   0   'False
         Width           =   7215
         Begin Project1.ArmGrid grItemProd 
            Height          =   6615
            Left            =   120
            TabIndex        =   85
            Tag             =   "grItemProd"
            Top             =   1080
            Width           =   6495
            _ExtentX        =   11456
            _ExtentY        =   11668
         End
         Begin VB.Frame fraProductsType 
            Height          =   615
            Left            =   120
            TabIndex        =   60
            Top             =   240
            Width           =   10455
            Begin VB.OptionButton opt_ProdView 
               Caption         =   "#Associated products"
               Height          =   255
               Index           =   1
               Left            =   3360
               TabIndex        =   34
               Tag             =   "opt_ProdAsso"
               Top             =   240
               Width           =   2175
            End
            Begin VB.OptionButton opt_ProdView 
               Caption         =   "#Tested products"
               Height          =   255
               Index           =   0
               Left            =   120
               TabIndex        =   33
               Tag             =   "opt_ProdTest"
               Top             =   240
               Value           =   -1  'True
               Width           =   1695
            End
         End
      End
      Begin VB.Frame fraItemResults 
         Height          =   4335
         Left            =   360
         TabIndex        =   58
         Top             =   2880
         Visible         =   0   'False
         Width           =   7815
         Begin VB.CommandButton cmd_Result 
            Caption         =   "..."
            Height          =   375
            Index           =   4
            Left            =   8520
            TabIndex        =   32
            Tag             =   "cmd_result"
            Top             =   2280
            Width           =   375
         End
         Begin VB.TextBox txt_Result 
            Height          =   375
            Index           =   4
            Left            =   3000
            TabIndex        =   31
            Tag             =   "txt_Result"
            Top             =   2280
            Width           =   5415
         End
         Begin VB.CommandButton cmd_Result 
            Caption         =   "..."
            Height          =   375
            Index           =   3
            Left            =   8520
            TabIndex        =   30
            Tag             =   "cmd_result"
            Top             =   1800
            Width           =   375
         End
         Begin VB.TextBox txt_Result 
            Height          =   375
            Index           =   3
            Left            =   3000
            TabIndex        =   29
            Tag             =   "txt_Result"
            Top             =   1800
            Width           =   5415
         End
         Begin VB.CommandButton cmd_Result 
            Caption         =   "..."
            Height          =   375
            Index           =   2
            Left            =   8520
            TabIndex        =   28
            Tag             =   "cmd_result"
            Top             =   1320
            Width           =   375
         End
         Begin VB.TextBox txt_Result 
            Height          =   375
            Index           =   2
            Left            =   3000
            TabIndex        =   27
            Tag             =   "txt_Result"
            Top             =   1320
            Width           =   5415
         End
         Begin VB.CommandButton cmd_Result 
            Caption         =   "..."
            Height          =   375
            Index           =   1
            Left            =   8520
            TabIndex        =   26
            Tag             =   "cmd_result"
            Top             =   840
            Width           =   375
         End
         Begin VB.TextBox txt_Result 
            Height          =   375
            Index           =   1
            Left            =   3000
            TabIndex        =   25
            Tag             =   "txt_Result"
            Top             =   840
            Width           =   5415
         End
         Begin VB.TextBox txt_Result 
            Height          =   375
            Index           =   0
            Left            =   3000
            TabIndex        =   23
            Tag             =   "txt_Result"
            Top             =   360
            Width           =   5415
         End
         Begin VB.CommandButton cmd_Result 
            Caption         =   "..."
            Height          =   375
            Index           =   0
            Left            =   8520
            TabIndex        =   24
            Tag             =   "cmd_result"
            Top             =   360
            Width           =   375
         End
         Begin VB.Label lbl_Res 
            Caption         =   "#Result 5"
            Height          =   255
            Index           =   4
            Left            =   240
            TabIndex        =   69
            Tag             =   "lbl_Result5"
            Top             =   2400
            Width           =   2415
         End
         Begin VB.Label lbl_Res 
            Caption         =   "#Result 4"
            Height          =   255
            Index           =   3
            Left            =   240
            TabIndex        =   68
            Tag             =   "lbl_Result4"
            Top             =   1920
            Width           =   2415
         End
         Begin VB.Label lbl_Res 
            Caption         =   "#Result 3"
            Height          =   255
            Index           =   2
            Left            =   240
            TabIndex        =   67
            Tag             =   "lbl_Result3"
            Top             =   1440
            Width           =   2415
         End
         Begin VB.Label lbl_Res 
            Caption         =   "#Result 2"
            Height          =   255
            Index           =   1
            Left            =   240
            TabIndex        =   66
            Tag             =   "lbl_Result2"
            Top             =   960
            Width           =   2415
         End
         Begin VB.Label lbl_Res 
            Caption         =   "#Result 1"
            Height          =   255
            Index           =   0
            Left            =   240
            TabIndex        =   65
            Tag             =   "lbl_Result1"
            Top             =   480
            Width           =   2415
         End
      End
      Begin VB.Frame fraItemConditions 
         Height          =   7455
         Left            =   6480
         TabIndex        =   57
         Top             =   6600
         Visible         =   0   'False
         Width           =   10215
         Begin Project1.ArmGrid grItemCnd 
            Height          =   5295
            Left            =   240
            TabIndex        =   22
            Tag             =   "grItemCnd"
            Top             =   240
            Width           =   8415
            _ExtentX        =   14843
            _ExtentY        =   9340
         End
      End
   End
   Begin VB.Frame fraList 
      Height          =   10935
      Left            =   3000
      TabIndex        =   62
      Top             =   3960
      Width           =   12735
      Begin VB.ListBox lst_On_What3 
         Height          =   840
         ItemData        =   "cpTstMan.ctx":0024
         Left            =   120
         List            =   "cpTstMan.ctx":0026
         TabIndex        =   84
         Tag             =   "SSTRlst_On_What3"
         Top             =   960
         Width           =   2295
      End
      Begin Project1.ArmGrid grList 
         Height          =   12375
         Left            =   120
         TabIndex        =   4
         Tag             =   "grList"
         Top             =   1200
         Width           =   13815
         _ExtentX        =   24368
         _ExtentY        =   21828
      End
      Begin Project1.ToolbarControl tcGrid 
         Height          =   690
         Left            =   120
         TabIndex        =   3
         Top             =   240
         Width           =   12495
         _ExtentX        =   22040
         _ExtentY        =   1217
      End
   End
   Begin VB.Frame fraFilters 
      Height          =   13815
      Left            =   1080
      TabIndex        =   2
      Top             =   840
      Width           =   4215
      Begin Project1.A_calocx calFiltersMin 
         Height          =   375
         Left            =   120
         TabIndex        =   94
         Top             =   1680
         Width           =   1815
         _ExtentX        =   3201
         _ExtentY        =   661
      End
      Begin Project1.A_calocx calfiltersMax 
         Height          =   375
         Left            =   2040
         TabIndex        =   95
         Top             =   1680
         Width           =   1815
         _ExtentX        =   3201
         _ExtentY        =   661
      End
      Begin VB.Frame fraFiltersDate 
         Caption         =   "#Date range"
         Height          =   735
         Left            =   120
         TabIndex        =   90
         Tag             =   "fraFiltersDate"
         Top             =   360
         Width           =   3735
         Begin VB.OptionButton optFiltersDate 
            Caption         =   "#Between"
            Height          =   375
            Index           =   1
            Left            =   1800
            TabIndex        =   92
            Tag             =   "optFiltersDate_Between"
            Top             =   240
            Width           =   1455
         End
         Begin VB.OptionButton optFiltersDate 
            Caption         =   "#All"
            Height          =   375
            Index           =   0
            Left            =   120
            TabIndex        =   91
            Tag             =   "optFiltersDate_All"
            Top             =   240
            Value           =   -1  'True
            Width           =   1455
         End
      End
      Begin Project1.ArmTreeView TVTest 
         Height          =   10215
         Left            =   120
         TabIndex        =   1
         Top             =   2760
         Width           =   3855
         _ExtentX        =   6800
         _ExtentY        =   18018
      End
      Begin Project1.ArmCombobox cbo_Views 
         Height          =   345
         Left            =   120
         TabIndex        =   0
         Top             =   2400
         Width           =   3375
         _ExtentX        =   5953
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_FiltersDate 
         Height          =   345
         Left            =   120
         TabIndex        =   93
         Top             =   1200
         Width           =   3735
         _ExtentX        =   6588
         _ExtentY        =   609
      End
      Begin VB.Label lbl_Views 
         Caption         =   "#Views"
         Height          =   255
         Left            =   120
         TabIndex        =   56
         Tag             =   "lbl_Views"
         Top             =   2160
         Width           =   2055
      End
   End
   Begin Project1.armItemSel ItemSel 
      Height          =   4695
      Left            =   0
      TabIndex        =   87
      Top             =   0
      Width           =   5775
      _ExtentX        =   10186
      _ExtentY        =   8281
   End
End
Attribute VB_Name = "cpTstMan"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit
' Need to redo InitResult and GetCode !
' TODO : see for the error connection

Private Const C_SCREENNAME As String = "Test_Manager"

Private Const C_INTERNETFLAG_YES As String = "X"
Private Const C_INTERNETFLAG_NO As String = ""

Private Const C_TOOLBARFACE_ITEM_NOUPDATE As String = "5"
Private Const C_TOOLBARFACE_ITEM_GENERAL As String = "0"
Private Const C_TOOLBARFACE_ITEM_CONDITION As String = "1"
Private Const C_TOOLBARFACE_ITEM_RESULT As String = "2"
Private Const C_TOOLBARFACE_ITEM_PRODUCTS As String = "3"
Private Const C_TOOLBARFACE_ITEM_DOCUMENTS As String = "4"

Private Const C_TOOLBARFACE_LIST_NOUPDATE As String = "0"
Private Const C_TOOLBARFACE_LIST_UPDATE As String = "1"

Private Const C_TOOLBARFACE_ITEM_ADD As String = "6"
Private Const C_TOOLBARFACE_ITEM_DEL As String = "7"
Private Const C_TOOLBARFACE_ITEM_UPD As String = "8"

Const C_REQUEST_CBO_STANDARD = "EXEC Test_Standard_cbo '$cg_code$', '$lang$'"
Const C_REQUEST_CBO_TESTMANAGER = "EXEC Test_Manager_cbo  '$so_code$', '$lang$'"

Private mInitialized As Boolean
Private mLoginName As String
Private mLanguage_Code As String
Private mU_Code As Long

Private Enum eTestType
    ettReal = TEST_REAL ' = 1
    ettAssessment = TEST_ASSESSMENT ' = 2
    ettOpinionOnReal = TEST_OPINION_ONREAL ' = 3
    ettOpinionOnAssessment = TEST_OPINION_ONASSESSMENT ' = 4
    ettOpinionOnNothing = TEST_OPINION_ONNOTHING ' = 5
End Enum

Private Enum eTestModes
    etmList = 0
    etmItem = 1
End Enum
Private mTestMode As eTestModes

Private Enum ArmErr
    CompFncFailed = C_ERRORRAISE + 161          ' when component function fail
End Enum

Private Enum eTestCndTypeOfValue
    etcString = 1
    etcInteger = 2
End Enum

Private Enum eTestViews
    etvGeneral = 0
    etvConditions = 1
    etvResult = 2
    etvProducts = 3
    etvDocuments = 4
    etvTree = 5
End Enum

Private mSelectedView As eTestViews

Private Enum eTestProductLink
    etplItem = 0
    etplCriteria = 1
End Enum

Private mTestTypeDesc(4) As String

#If LIVE Then
Private mDb As Object
#Else
Private mDb As ArmDb
#End If

#If LIVE Then
Private mDbErr As Object
#Else
Private mDbErr As ArmDb
#End If

Private Enum eTestCategory
    etcHumidityRes = 3
    etcFireReaction = 4
    etcSoundAbsorption = 5
    etcLightReflectance = 7
    etcThermalCond = 9
    etcHygienePerf = 10
    etcWashability = 11
    etcFireRest = 15
    etcSoundAttenuation = 16
    etcSoundReduction = 17
    etcScrubality = 18
    etcHealthSafety = 19
    etcMiscellaneous = 20
End Enum


Private Type TTreeViewInfo
    Levels As Long
    NodeRequest() As String
    GridRequest() As String
    ExcelRequest() As String
    CountRequest() As String
    FindRequest() As String
    Images() As Integer
    SelectedImages() As Integer
    TreeViewCode As String
    Loaded As Boolean
End Type
Private mTreeViewInfos() As TTreeViewInfo
Private mTreeViewInfosItemTree() As TTreeViewInfo

Private Enum eTLPType
    etlWithProduct = 1
    etlWithCriteria = 2
End Enum

Private Type TProductView
    Loaded As Boolean
    Data As Variant
    isValid() As Long
    Type As String
End Type

Private Enum eProductViews
    epvTested = 0
    epvAssociated = 1
End Enum
Private mSelectedProductView As eProductViews
Private mItemProdSelRow As Long

Private mToolBarFaceViews(5) As Long

Private Type TTestViewGeneral
    CAT_Code As Long                ' Category
    CAT_Desc As String
    STD_Code As Long                ' Standard
    STD_Desc As String
    THO_Code As Long                ' Test house
    THO_Desc As String
    SO_Code As String               ' Test office
    SO_Desc As String
    TMNG_Code As Long               ' Test manager
    TMNG_Desc As String
    MotherFTN As String             ' Mother test
    FullTestNumber As String        ' Full test number
    IndicativeTestNumber As String  ' Indicative Number
    StartDate As String             ' Start date
    EndDate As String               ' End date
    olddate As String               ' Old but still relevant
    DropDate As String              ' Drop date
    InternetFlag As String          ' Internet flag
    MemoCount As Long               ' Memo count
    Type As eTestType               ' Type de test
    iConcurrency As Long            ' IConcurrency du test
End Type

Private Type TTest
    TestCode As String
    FullNumber As String
    Type As eTestType
    Category As eTestCategory
    ViewInitialized(5) As Boolean
    Loaded As Boolean
    ProductViews(1) As TProductView
    MarketsLoaded As Boolean
    CountriesLoaded As Boolean
    ViewGeneral As TTestViewGeneral
    Sales_Office As String
End Type

Private mSelectedTest As TTest

Private mCmdMemoCaption As String

Private mTransItemNumber As Variant

Private Type TTestCnd
    Type As String
    TypeOfValue As eTestCndTypeOfValue
    value As String
    Valid As Boolean
End Type
Private mSelectedTestCnd As TTestCnd

Private Enum eBusinessFunction
    ebfLaunchTestManager = 1
    ebfViewAProductTest = 2
    ebfAddAProductTest = 3
    ebfDeleteAProductTest = 4
    ebfUpdateAProductTest = 5
    ebfTreeviewGTest_Manager_TV1 = 6
    ebfTreeviewGTest_Manager_TV2 = 7
    ebfTreeviewGTest_Manager_TV3 = 8
    ebfTreeviewGTest_Manager_TV4 = 9
    ebfTreeviewGTest_Manager_TV5 = 10
    ebfTreeviewGTest_Manager_TV6 = 11
    ebfTreeviewGTest_Manager_TV7 = 12
End Enum

Private Enum eTestAction
    etaView = 0
    etaAdd = 1
    etaDelete = 2
    etaUpdate = 3
End Enum

Private mTestAction As eTestAction
Private mTestActionType As eTestType

Private Type TTestMediaLink
    TST_code As Integer
    MD_Code As String
    Zip_code As Integer
End Type
Private mLinks() As TTestMediaLink


Public Event Unload()

Private Type TTestDocument
    MD_Code As String
    Zip_code As String
    MD_Language_Code As String
    MD_Language_Desc As String
    PT_Title As String
    SRC_Size As Long
    CPR_Size As Long
    FE_Desc As String
    FileName As String
    FE_Code As String
    MediaConcurrency As Long
    Access_type As String
    Access_type_desc As String
    Validity_StartDate As Date
    Validity_EndDate As Date
    Internet_Flag As String
    Spare1 As String
    Spare2 As String
End Type
Private mSelTestDocument As TTestDocument

Private mZipMaxSize As Long
Private mLblTestProducts
Private mLblAssProducts

Private mSlOffAuthorized As Long ' list of sales on which the user have an update rigths
Private mCanUpdateMedia As Long

Private mNumber As Long
Private mSource As String
Private mDesc As String
Private mla_TYTTranslate(4) As Long       ' task 462 used to translate index->tyt_code in GetCode()

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

Public Property Let Top(ByVal aTop As Single)
    UserControl.Extender.Top = aTop
End Property
Public Property Get Top() As Single
    Top = UserControl.Extender.Top
End Property

Public Property Let Height(ByVal aHeight As Single)
    UserControl.Extender.Height = aHeight
End Property
Public Property Get Height() As Single
    Height = UserControl.Extender.Height
End Property

Public Property Let Left(ByVal aLeft As Single)
    UserControl.Extender.Left = aLeft
End Property
Public Property Get Left() As Single
    Left = UserControl.Extender.Left
End Property

Public Property Let Width(ByVal aWidth As Single)
    UserControl.Extender.Width = aWidth
End Property
Public Property Get Width() As Single
    Width = UserControl.Extender.Width
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 U_Code(ByVal a_U_Code As Long)
    mU_Code = a_U_Code
End Property


Public Function Load_A_Com() As Boolean

    Const CL_REQUEST_TB As String = "SELECT Info FROM Toolbars_Definitions WHERE ID=$id$"
    
    ' TODO : Put here all initializing code
    ' TODO : Manage error
    
    fraFilters.Visible = False
    fraItem.Visible = False
    fraList.Visible = False
    fraItemConditionsMtnc.Visible = False
    fraItemDocumentMtnc.Visible = False
    ItemSel.Visible = False
    
    Call MaxZipSize
    
    mToolBarFaceViews(eTestViews.etvGeneral) = C_TOOLBARFACE_ITEM_GENERAL
    mToolBarFaceViews(eTestViews.etvConditions) = C_TOOLBARFACE_ITEM_CONDITION
    mToolBarFaceViews(eTestViews.etvDocuments) = C_TOOLBARFACE_ITEM_DOCUMENTS
    mToolBarFaceViews(eTestViews.etvProducts) = C_TOOLBARFACE_ITEM_PRODUCTS
    mToolBarFaceViews(eTestViews.etvResult) = C_TOOLBARFACE_ITEM_RESULT
    
    Call Test.GetTestSecurity
    
    Call LoadLabels(mDb, Controls, C_SCREENNAME, mLanguage_Code)
    
    calFiltersMin.Language = mLanguage_Code
    calFiltersMin.ZOrder
    calfiltersMax.Language = mLanguage_Code
    calfiltersMax.ZOrder
    
    calFiltersMin.Visible = False
    calfiltersMax.Visible = False
    cbo_FiltersDate.Visible = False
    
    Dim lTransItemNumber As String
    lTransItemNumber = lbl_FullTestNumber.Caption
    mTransItemNumber = Split(lTransItemNumber, CH_LDELIMIT)
    'Assume defaults values when screen contants are missing
    If UBound(mTransItemNumber) <> 4 Then
        mTransItemNumber = Array("#Full Test Number", "#Assessment Number", "#Opinion Number", "#Opinion Number", "#Opinion Number")
    End If
    
    lst_On_What.Visible = False
    lst_On_What2.Visible = False
    lst_On_What3.Visible = False
    lst_on_what4.Visible = False
    lst_on_what5.Visible = False
    
    If lst_On_What.ListCount <> 3 Then
        lst_On_What.Clear
        Call lst_On_What.AddItem("#Assessment")
        Call lst_On_What.AddItem("#Opinion on real test")
        Call lst_On_What.AddItem("#Opinion on assessment")
    End If
    lst_On_What.ItemData(0) = eTestType.ettAssessment
    lst_On_What.ItemData(1) = eTestType.ettOpinionOnReal
    lst_On_What.ItemData(2) = eTestType.ettOpinionOnAssessment

    If lst_On_What2.ListCount <> 2 Then
        lst_On_What2.Clear
        Call lst_On_What2.AddItem("#Test")
        Call lst_On_What2.AddItem("#Market")
    End If

    If lst_On_What3.ListCount <> 2 Then
        lst_On_What3.Clear
        Call lst_On_What3.AddItem("#Real test")
        Call lst_On_What3.AddItem("#Opinion")
    End If
    lst_On_What3.ItemData(0) = eTestType.ettReal
    lst_On_What3.ItemData(1) = eTestType.ettOpinionOnNothing

    If lst_on_what4.ListCount <> 2 Then
        lst_on_what4.Clear
        Call lst_on_what4.AddItem("#Product")
        Call lst_on_what4.AddItem("#Criteria")
    End If
    
    If lst_on_what5.ListCount <> 3 Then
        lst_on_what5.Clear
        Call lst_on_what5.AddItem("#Conditions type")
        Call lst_on_what5.AddItem("#Conditions detail")
    End If

    mCmdMemoCaption = cmd_Memo.Caption
    
    Call InitCtrlSize
    
    Call EnableFrame(UserControl.Controls, fraItemFullNumber, False)
    
    ' the treeview
    Set TVTest.ArmDb = mDb
    TVTest.Language = mLanguage_Code
    TVTest.AllowCheckboxes = True
    TVTest.UseImages = False
    Call TVTest.Load_A_Com
    
    
    Set tvItemTree.ArmDb = mDb
    tvItemTree.Language = mLanguage_Code
    tvItemTree.AllowCheckboxes = False
    tvItemTree.UseImages = False
    Call tvItemTree.Load_A_Com
    
    ' Init access type combo
    Set cbo_access.ArmDb = mDb
    Call cbo_access.Load_A_Com
    cbo_access.FirstBlankItem = False
    Call cbo_access.Clear
    cbo_access.Request = "SELECT RF_code, RF_desc FROM A_References_ML WHERE GR_code=1 and Language_code='" & mLanguage_Code & "'"
    cbo_access.Load
    
    ' Initializing the view combo
    Set cbo_Views.ArmDb = mDb
    Call cbo_Views.Load_A_Com
    Call cbo_Views.Clear
    cbo_Views.FirstBlankItem = False
    cbo_Views.Request = "exec TreeView_View_t_lst '" & C_SCREENNAME & "'," & "'" & mLanguage_Code & "'"
    cbo_Views.Load
    If cbo_Views.Count = 0 Then
        ' TODO ERROR FATAL
        Exit Function
    End If
    'cbo_Views.DroppedWith = cbo_Views.Width * 2
    
    Dim lIdx As Long, lCount As Long
    lCount = cbo_Views.Count - 1
    ReDim mTreeViewInfos(lCount)
    For lIdx = 0 To lCount
        mTreeViewInfos(lIdx).Loaded = False
        mTreeViewInfos(lIdx).TreeViewCode = cbo_Views.ComboItems(lIdx + 1).Key
    Next
    cbo_Views.SearchItem "X", "TV_Default", 0
    
    
    ' Initializing the view combo
    Set cbo_ItemTreeViews.ArmDb = mDb
    Call cbo_ItemTreeViews.Load_A_Com
    Call cbo_ItemTreeViews.Clear
    cbo_ItemTreeViews.FirstBlankItem = False
    cbo_ItemTreeViews.Request = "exec TreeView_View_t_lst 'TSMITEMTREE'," & "'" & mLanguage_Code & "'"
    cbo_ItemTreeViews.Load
    
    lCount = cbo_ItemTreeViews.Count - 1
    ReDim mTreeViewInfosItemTree(lCount)
    For lIdx = 0 To lCount
        mTreeViewInfosItemTree(lIdx).Loaded = False
        mTreeViewInfosItemTree(lIdx).TreeViewCode = cbo_ItemTreeViews.ComboItems(lIdx + 1).Key
    Next
    cbo_ItemTreeViews.SearchItem "X", "TV_Default", 0
    
    
    Dim lData As Long, lLabels As Variant
    lData = mDb.OpenSQL("SELECT Field_Name, Local_Text FROM Screen_Constants WHERE Screen_Name = '" & C_SCREENNAME & "' AND Field_Name LIKE 'gr%'")
    
    Dim lColumns() As String
    ' Initialize the grid
    Set grList.ArmDb = mDb
    grList.Load_A_Com
    grList.AllowExcelExport = True
    grList.ExportTitles = True
    grList.MultiSelect = False
    
    
    lIdx = mDb.Find(lData, "Field_Name", "grList")
    lLabels = Split(mDb.GetFieldsAt(lData, lIdx, "Local_Text"), CH_LDELIMIT)
    lLabels = Split(mDb.GetFieldsAt(lData, lIdx, "Local_Text"), CH_LDELIMIT)
    If UBound(lLabels) <> 9 Then
        lLabels = Array("#tst_code", "#language_code", "#Reference number", "#Dependance number", "#Test House", "#Test category", "#Test_Type", "#Start Date", "#Expiry date", "#Old date")
        'lLabels = Array("#tst_code", "#language_code", "#FULL_TEST_NUMBER", "#Categories", "#Sales office", "#Test manager", "#Type")
    End If
    ReDim lColumns(9)
    lColumns(0) = "tst_code" & CH_LDELIMIT & "0" & CH_LDELIMIT & "1" & CH_LDELIMIT & "tst_code" & CH_LDELIMIT & lLabels(0)
    lColumns(1) = "language_code" & CH_LDELIMIT & "0" & CH_LDELIMIT & "2" & CH_LDELIMIT & "language_code" & CH_LDELIMIT & lLabels(1)
    lColumns(2) = "FULL_TEST_NUMBER" & CH_LDELIMIT & "1500" & CH_LDELIMIT & "0" & CH_LDELIMIT & "FULL_TEST_NUMBER" & CH_LDELIMIT & lLabels(2)
    lColumns(3) = "MOTHER_TEST_NUMBER" & CH_LDELIMIT & "1500" & CH_LDELIMIT & "0" & CH_LDELIMIT & "MOTHER_TEST_NUMBER" & CH_LDELIMIT & lLabels(3)
    lColumns(4) = "THO_Desc" & CH_LDELIMIT & "2000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "THO_Desc" & CH_LDELIMIT & lLabels(4)
    lColumns(5) = "CAT_desc" & CH_LDELIMIT & "2000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CAT_desc" & CH_LDELIMIT & lLabels(5)
    lColumns(6) = "TT_desc" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "TT_desc" & CH_LDELIMIT & lLabels(6)
    lColumns(7) = "START_Date" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "START_Date" & CH_LDELIMIT & lLabels(7)
    lColumns(8) = "END_Date" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "END_Date" & CH_LDELIMIT & lLabels(8)
    lColumns(9) = "OLD_DATE" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "OLD_DATE" & CH_LDELIMIT & lLabels(9)
        
    grList.SetColumns lColumns
    grList.Title = optFiltersDate(0).Caption
    
    Set grItemCnd.ArmDb = mDb
    grItemCnd.Load_A_Com
    grItemCnd.AllowExcelExport = True
    grItemCnd.ExportTitles = True
    grItemCnd.MultiSelect = False
    
    lIdx = mDb.Find(lData, "Field_Name", "grItemCnd")
    lLabels = Split(mDb.GetFieldsAt(lData, lIdx, "Local_Text"), CH_LDELIMIT)
    If UBound(lLabels) <> 2 Then
        lLabels = Array("#TYPCND_TYPE", "#Condition", "#Value")
    End If
    ReDim lColumns(2)
    lColumns(0) = "TYPCND_TYPE" & CH_LDELIMIT & "0" & CH_LDELIMIT & "1" & CH_LDELIMIT & "TYPCND_TYPE" & CH_LDELIMIT & lLabels(0)
    lColumns(1) = "TYPCND_Desc" & CH_LDELIMIT & "3000" & CH_LDELIMIT & "2" & CH_LDELIMIT & "TYPCND_Desc" & CH_LDELIMIT & lLabels(1)
    lColumns(2) = "Value" & CH_LDELIMIT & "3000" & CH_LDELIMIT & "3" & CH_LDELIMIT & "Value" & CH_LDELIMIT & lLabels(2)
    grItemCnd.SetColumns lColumns
    
    Set grItemDoc.ArmDb = mDb
    grItemDoc.Load_A_Com
    grItemDoc.AllowExcelExport = True
    grItemDoc.ExportTitles = True
    grItemDoc.MultiSelect = False
    
    lIdx = mDb.Find(lData, "Field_Name", "grItemDoc")
    lLabels = Split(mDb.GetFieldsAt(lData, lIdx, "Local_Text"), CH_LDELIMIT)
    If UBound(lLabels) <> 7 Then
        lLabels = Array("#MD_code", "#Zip_Code", "#iconcurrency", "#Language", "#Title", "#Size in byte", "#File type", "#Access type")
    End If
    ReDim lColumns(7)
    lColumns(0) = "MD_code" & CH_LDELIMIT & "0" & CH_LDELIMIT & "1" & CH_LDELIMIT & "MD_code" & CH_LDELIMIT & lLabels(0)
    lColumns(1) = "Zip_Code" & CH_LDELIMIT & "0" & CH_LDELIMIT & "2" & CH_LDELIMIT & "Zip_Code" & CH_LDELIMIT & lLabels(1)
    lColumns(2) = "iconcurrency" & CH_LDELIMIT & "0" & CH_LDELIMIT & "3" & CH_LDELIMIT & "iconcurrency" & CH_LDELIMIT & lLabels(2)
    lColumns(3) = "Language_Desc" & CH_LDELIMIT & "3000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "Language_Desc" & CH_LDELIMIT & lLabels(3)
    lColumns(4) = "PT_Title" & CH_LDELIMIT & "3000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "PT_Title" & CH_LDELIMIT & lLabels(4)
    lColumns(5) = "SRC_Size" & CH_LDELIMIT & "3000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SRC_Size" & CH_LDELIMIT & lLabels(5)
    lColumns(6) = "FE_Desc" & CH_LDELIMIT & "2000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "FE_Desc" & CH_LDELIMIT & lLabels(6)
    lColumns(7) = "Access_type" & CH_LDELIMIT & "2000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "Access_type" & CH_LDELIMIT & lLabels(7)
    
    grItemDoc.SetColumns lColumns
    
    Set grItemProd.ArmDb = mDb
    grItemProd.Load_A_Com
    grItemProd.AllowExcelExport = True
    grItemProd.MultiSelect = False
    grItemProd.ExportTitles = True
    lIdx = mDb.Find(lData, "Field_Name", "grItemProdTest")
    lLabels = Split(mDb.GetFieldsAt(lData, lIdx, "Local_Text"), CH_LDELIMIT)
    If UBound(lLabels) <> 17 Then
        lLabels = Array("#TLP_Code", "#TLP_Type", "#iConcurrency", "#MFGP_Code", "#BI SAP Code", "#Short Code", "#Plant/Supplier", "#Surface", "#Module", "#Thickness", "#Segmentation", "#Edge detail", "#Colour", "#Family", "#Shape", "#Category", "#Base material", "#Pattern")
    End If
    ReDim lColumns(17)
    lColumns(0) = "TLP_code" & CH_LDELIMIT & "0" & CH_LDELIMIT & "1" & CH_LDELIMIT & "TLP_code" & CH_LDELIMIT & lLabels(0)
    lColumns(1) = "TLP_TYPE" & CH_LDELIMIT & "0" & CH_LDELIMIT & "2" & CH_LDELIMIT & "TLP_TYPE" & CH_LDELIMIT & lLabels(1)
    lColumns(2) = "IConcurrency" & CH_LDELIMIT & "0" & CH_LDELIMIT & "3" & CH_LDELIMIT & "IConcurrency" & CH_LDELIMIT & lLabels(2)
    lColumns(3) = "MFGP_Code" & CH_LDELIMIT & "0" & CH_LDELIMIT & "0" & CH_LDELIMIT & "MFGP_Code" & CH_LDELIMIT & lLabels(3)
    lColumns(4) = "BI_SAP_CODE" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "BI_SAP_CODE" & CH_LDELIMIT & lLabels(4)
    lColumns(5) = "BI_Short_Code" & CH_LDELIMIT & "800" & CH_LDELIMIT & "0" & CH_LDELIMIT & "BI_Short_Code" & CH_LDELIMIT & lLabels(5)
    lColumns(6) = "MFGP_Desc" & CH_LDELIMIT & "1200" & CH_LDELIMIT & "0" & CH_LDELIMIT & "MFGP_Desc" & CH_LDELIMIT & lLabels(6)
    lColumns(7) = "SF_Desc" & CH_LDELIMIT & "1100" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SF_Desc" & CH_LDELIMIT & lLabels(7)
    lColumns(8) = "PM_Desc" & CH_LDELIMIT & "1200" & CH_LDELIMIT & "0" & CH_LDELIMIT & "PM_Desc" & CH_LDELIMIT & lLabels(8)
    lColumns(9) = "BI_Thickness" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "BI_Thickness" & CH_LDELIMIT & lLabels(9)
    lColumns(10) = "PS_Desc" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "PS_Desc" & CH_LDELIMIT & lLabels(10)
    lColumns(11) = "PE_Desc" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "PE_Desc" & CH_LDELIMIT & lLabels(11)
    lColumns(12) = "COLOUR_Desc" & CH_LDELIMIT & "900" & CH_LDELIMIT & "0" & CH_LDELIMIT & "COLOUR_Desc" & CH_LDELIMIT & lLabels(12)
    lColumns(13) = "PF_Desc" & CH_LDELIMIT & "1300" & CH_LDELIMIT & "0" & CH_LDELIMIT & "PF_Desc" & CH_LDELIMIT & lLabels(13)
    lColumns(14) = "SH_Desc" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SH_Desc" & CH_LDELIMIT & lLabels(14)
    lColumns(15) = "CG_Desc" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CG_Desc" & CH_LDELIMIT & lLabels(15)
    lColumns(16) = "BML_Desc" & CH_LDELIMIT & "1200" & CH_LDELIMIT & "0" & CH_LDELIMIT & "BML_Desc" & CH_LDELIMIT & lLabels(16)
    lColumns(17) = "PP_Desc" & CH_LDELIMIT & "1300" & CH_LDELIMIT & "0" & CH_LDELIMIT & "PP_Desc" & CH_LDELIMIT & lLabels(17)
    grItemProd.SetColumns lColumns
    
    mDb.Close (lData)
    
    ' The calendars
    caStartDate.Language = mLanguage_Code
    caEndDate.Language = mLanguage_Code
    caOldDate.Language = mLanguage_Code
    caDropDate.Language = mLanguage_Code
    caValidityStartDate.Language = mLanguage_Code
    caValidityEndDate.Language = mLanguage_Code
    
    mSlOffAuthorized = mDb.OpenSQL("Test_Security_SO_UPDRight_sel")
    
    mSelectedView = eTestViews.etvGeneral
    
    fraFilters.Visible = True
    fraFilters.ZOrder
    'Initialize the toolbar
    
    Dim lCursTB As Long
    
    tcGrid.Load_A_Com
    tcGrid.Language = "E"
    lCursTB = mDb.OpenSQL(Replace(CL_REQUEST_TB, "$id$", 34))
    Call tcGrid.SetToolbarInfoStringParameters(mDb.GetFields(lCursTB, "info"), "005")
    
    Call tcGrid.DisplayFace(IIf(mDb.RowCount(mSlOffAuthorized) > 0, C_TOOLBARFACE_LIST_UPDATE, C_TOOLBARFACE_LIST_NOUPDATE))
    mDb.Close (lCursTB)
    
    tcItem.Load_A_Com
    tcItem.Language = "E"
    lCursTB = mDb.OpenSQL(Replace(CL_REQUEST_TB, "$id$", 55))
    Call tcItem.SetToolbarInfoStringParameters(mDb.GetFields(lCursTB, "info"), "006")
    Call tcItem.DisplayFace(C_TOOLBARFACE_ITEM_NOUPDATE)
    mDb.Close (lCursTB)
    
    ' The conditions maintenance
    Set cbo_TypeCnd.ArmDb = mDb
    Call cbo_TypeCnd.Load_A_Com
    cbo_TypeCnd.Request = "exec Test_Typ_Condition_cbo3 '" & mLanguage_Code & "'"
    
    ' the general maintenance
    Set cbo_ivgCategory.ArmDb = mDb
    cbo_ivgCategory.Load_A_Com
    cbo_ivgCategory.Request = "Exec Test_Category_cbo3 '" & mLanguage_Code & "'"
    
    Set cbo_ivgStandard.ArmDb = mDb
    cbo_ivgStandard.Load_A_Com
    cbo_ivgStandard.Request = "" ' Depends of category
    
    Set cbo_ivgTestHouse.ArmDb = mDb
    cbo_ivgTestHouse.Load_A_Com
    cbo_ivgTestHouse.Request = "Exec Test_House_cbo '" & mLanguage_Code & "'"
    
    Set cbo_ivgSalesOffice.ArmDb = mDb
    cbo_ivgSalesOffice.Load_A_Com
    cbo_ivgSalesOffice.Request = "Exec Sales_Office_cbo3 '" & mLanguage_Code & "'"
    
    
    Set cbo_ivgTestManager.ArmDb = mDb
    cbo_ivgTestManager.Load_A_Com
    cbo_ivgTestManager.Request = "" ' Depends of sales offices
    
    ' the document maintenance
    Set cbo_DocumentLanguage.ArmDb = mDb
    cbo_DocumentLanguage.Load_A_Com
    cbo_DocumentLanguage.Request = "Media_Language_cbo"
    
    Set cbo_Ext.ArmDb = mDb
    cbo_Ext.Load_A_Com
    cbo_Ext.Request = "media_File_Ext_cbo"
    
    Set cbo_FiltersDate.ArmDb = mDb
    cbo_FiltersDate.Load_A_Com
    cbo_FiltersDate.Request = "exec captv_date_cbo 'TSM_List','" & mLanguage_Code & "'"
    cbo_FiltersDate.Load
    cbo_FiltersDate.SearchItem "1", 2, 0
    
    drv_Full.Drive = "C:\"
    dir_Full.Path = "C:\"
    fil_Full.Path = "C:\"
    fil_Full.Refresh
    
    ' Check rights for view Document
    lData = mDb.OpenSQL("Alias_Media_path_lst")
    lCount = mDb.RowCount(lData)
    For lIdx = 0 To lCount
        If ((mDb.GetFields(lData, 1) And 2) = 2) Then
            mCanUpdateMedia = True
            Exit For
        End If
        mDb.Next (lData)
    Next
    mDb.Close (lData)
    
    acvMarkets.Load_A_Com
    Set acvMarkets.ArmDb = mDb
    
    
    acvCountries.Load_A_Com
    Set acvCountries.ArmDb = mDb
    
    Dim lRequest As String
    Dim lTTDesc As Long
    lRequest = "SELECT TT_DESC FROM Test_Class WHERE Language_Code = '" & mLanguage_Code & "' ORDER BY TT_TYPE"
    lTTDesc = mDb.OpenSQL(lRequest)
    lCount = mDb.RowCount(lTTDesc) - 1
    For lIdx = 0 To lCount
        mTestTypeDesc(lIdx) = mDb.GetFields(lTTDesc, 0)
        mDb.Next (lTTDesc)
    Next
    mDb.Close (lTTDesc)
    
    SetMode (eTestModes.etmList)
    
    Call LogActivty(mDb, mU_Code, ebfLaunchTestManager)
    
    mInitialized = True
    Load_A_Com = True
       
End Function


Public Function Unload_A_Com() As Boolean

    mDb.Close (mSlOffAuthorized)

    Call acvCountries.Unload_A_Com
    Call acvMarkets.Unload_A_Com

    ' TODO : Release here all ressources
    Call cbo_Views.Unload_A_Com
    Call TVTest.Unload_A_Com
    Call grList.Unload_A_Com
    Call grItemCnd.Unload_A_Com
    Call grItemDoc.Unload_A_Com
    Call grItemProd.Unload_A_Com
    
    Call cbo_ivgCategory.Unload_A_Com
    Call cbo_ivgStandard.Unload_A_Com
    Call cbo_ivgTestHouse.Unload_A_Com
    Call cbo_ivgSalesOffice.Unload_A_Com
    Call cbo_ivgTestManager.Unload_A_Com
    
    Call cbo_DocumentLanguage.Unload_A_Com
    Call cbo_Ext.Unload_A_Com
    Call cbo_FiltersDate.Unload_A_Com
    Call cbo_access.Unload_A_Com
    
    Call tcItem.Unload_A_Com
    Call tcGrid.Unload_A_Com
    Call tvItemTree.Unload_A_Com
    
    Set mDb = Nothing
    Set mDbErr = Nothing
    
    mInitialized = False
    
    Unload_A_Com = True
    
End Function


#If LIVE Then
Public Property Set Db(ByRef ADB As Object)
#Else
Public Property Set Db(ByRef ADB As ArmDb)
#End If
    Set mDb = ADB

End Property


#If LIVE Then
Public Property Set DbErr(ByRef ADB As Object)
#Else
Public Property Set DbErr(ByRef ADB As ArmDb)
#End If
    Set mDbErr = ADB
End Property



Public Property Get Initialized() As Boolean
    Initialized = mInitialized
End Property

Public Property Let LoginName(ByVal aLoginName As String)
    ' TODO : manage here blank string (different when initialized)
    mLoginName = aLoginName
End Property

Public Property Let Language_code(ByVal aLanguage_Code As String)
    mLanguage_Code = aLanguage_Code
End Property

Private Function GetTreeViewInfoFromDB(ByVal AScreenName As String, ByVal aTVCode As String) As TTreeViewInfo

    Dim lTreeView As TTreeViewInfo
    Dim lRequest As String
    Dim lCurs As Long, lIdx As Long, lCount As Long
    
    ' Get the data from the DB
    lRequest = "EXEC Treeview_Parameters_lst '" & AScreenName & "', '" & aTVCode & "'"
    lCurs = mDb.OpenSQL(lRequest)
    
    lCount = mDb.RowCount(lCurs) - 1
    
    ReDim lTreeView.NodeRequest(lCount)
    ReDim lTreeView.GridRequest(lCount)
    ReDim lTreeView.ExcelRequest(lCount)
    ReDim lTreeView.FindRequest(lCount)
    ReDim lTreeView.CountRequest(lCount)
    ReDim lTreeView.Images(lCount)
    ReDim lTreeView.SelectedImages(lCount)
    
    Dim lLevel As Long
    For lIdx = 0 To lCount
        lLevel = mDb.GetFields(lCurs, "TV_Level")
        lTreeView.NodeRequest(lLevel) = ReplaceHolders(mDb.GetFields(lCurs, "TV_NodeRequest"))
        lTreeView.GridRequest(lLevel) = ReplaceHolders(mDb.GetFields(lCurs, "TV_GridRequest"))
        lTreeView.ExcelRequest(lLevel) = ReplaceHolders(mDb.GetFields(lCurs, "TV_ExcelRequest"))
        lTreeView.FindRequest(lLevel) = ReplaceHolders(mDb.GetFields(lCurs, "TV_FindRequest"))
        lTreeView.CountRequest(lLevel) = ReplaceHolders(mDb.GetFields(lCurs, "TV_CountRequest"))
        lTreeView.Images(lLevel) = mDb.GetFields(lCurs, "TV_Images")
        lTreeView.SelectedImages(lLevel) = mDb.GetFields(lCurs, "TV_SelectedImages")
        mDb.Next (lCurs)
    Next
    
    lTreeView.TreeViewCode = aTVCode
    lTreeView.Levels = lCount + 1
    lTreeView.Loaded = True
    GetTreeViewInfoFromDB = lTreeView
    
    mDb.Close (lCurs)
    
End Function



Private Sub calfiltersMax_LostFocus()
Screen.MousePointer = vbHourglass
    
    Call OnFilterChange
    If calfiltersMax.date_courte <> "" And calFiltersMin.date_courte <> "" Then
        If CDate(calfiltersMax.date_courte) < CDate(calFiltersMin.date_courte) Then
            calfiltersMax.SetFocus
            Call SendMessage(969, "End date cannot be less than Start date", mLanguage_Code)
        End If
   End If
    
    Screen.MousePointer = 0
End Sub

Private Sub cbo_Ext_ComboItemSelected()
    If Not cbo_Ext.SelectedItem Is Nothing Then fil_Full.Pattern = "*." & cbo_Ext.SelectedItem.DisplayText
End Sub


Private Sub cbo_ItemTreeViews_ComboItemSelected()
    If mInitialized Then
        If Not cbo_ItemTreeViews.SelectedItem Is Nothing Then
            Call LoadTreeView(tvItemTree, GetTreeViewInfo(mTreeViewInfosItemTree, "TSMITEMTREE", cbo_ItemTreeViews.SelectedItem.Key))
        End If
    End If
End Sub

Private Sub cbo_Views_ComboItemSelected()
    If Not cbo_Views.SelectedItem Is Nothing Then
            Call LogActivty(mDb, mU_Code, ebfTreeviewGTest_Manager_TV1 + cbo_Views.GetIndex)
            Call LoadTreeView(TVTest, GetTreeViewInfo(mTreeViewInfos, C_SCREENNAME, cbo_Views.SelectedItem.Key), grList)
        
            Dim lRight As Boolean
            If InStr(1, cbo_Views.SelectedItem.GetData(2), "plant", vbTextCompare) > 0 Then
                lRight = False
            Else
                lRight = mDb.RowCount(mSlOffAuthorized) > 0
            End If
        tcGrid.DisplayFace (IIf(lRight, C_TOOLBARFACE_LIST_UPDATE, C_TOOLBARFACE_LIST_NOUPDATE))
    End If
End Sub


Private Function GetTreeViewInfo(ByRef aTVInfos() As TTreeViewInfo, ByVal AScreenName As String, ByVal aTVCode As String) As TTreeViewInfo
    
    Dim lIdx As Long, lCount As Long
    Dim lTreeView As TTreeViewInfo, lFound As Boolean
    
    ' Search in the array
    lCount = UBound(aTVInfos)
    lFound = False
    For lIdx = 0 To lCount
        If aTVInfos(lIdx).TreeViewCode = aTVCode Then
            ' REMOVE THIS AFTER TEST !
            'aTVInfos(lIdx).Loaded = False
            If Not aTVInfos(lIdx).Loaded Then
                aTVInfos(lIdx) = GetTreeViewInfoFromDB(AScreenName, aTVCode)
            End If
            lTreeView = aTVInfos(lIdx)
            lFound = True
            Exit For
        End If
    Next
    
    If Not lFound Then
        'ERROR
    End If
    
    GetTreeViewInfo = lTreeView
    
End Function


Private Function LoadTreeView(ByRef aTV As ArmTreeView, ByRef aTreeViewInfo As TTreeViewInfo, Optional ByRef aGrid As ArmGrid = Nothing) As Boolean
    
    'aTV.Visible = True

    aTV.Clear
    ' Clearing the associated grid
    If Not aGrid Is Nothing Then
        aGrid.Requests = ""
        Call aGrid.ClearGrid
    End If

    aTV.Levels = aTreeViewInfo.Levels
    aTV.StartDemandLevel = 1
    aTV.SelectedImages = aTreeViewInfo.SelectedImages
    aTV.Images = aTreeViewInfo.Images
    aTV.NodeRequests = aTreeViewInfo.NodeRequest
    aTV.GridRequests = aTreeViewInfo.GridRequest
    aTV.FindRequests = aTreeViewInfo.FindRequest
    aTV.CountRequests = aTreeViewInfo.CountRequest
    
    If Not aTV.LoadTree(LoadTypeChildsDemand) Then
        'ERROR
        LoadTreeView = False
    End If
    
    'aTV.Visible = True
    
End Function


Private Function ReplaceHolders(ByVal aRequest As String) As String
    
    Dim lBuffer As String
    lBuffer = Replace(aRequest, "$lang$", mLanguage_Code, , , vbTextCompare)
    lBuffer = Replace(lBuffer, "$login$", mLoginName, , , vbTextCompare)
    lBuffer = Replace(lBuffer, "$test_code$", mSelectedTest.TestCode, , , vbTextCompare)
    
    ReplaceHolders = lBuffer
    
End Function


Private Sub cmd_Memo_Click()
    Call Item_ViewMemo
End Sub

Private Sub cmd_result_Click(Index As Integer)
    Call Item_ViewCndCurve(Index + 1)
End Sub


Private Sub dir_Full_Change()
    fil_Full.Path = dir_Full.Path
    txt_File.Text = ""
End Sub

Private Sub drv_Full_Change()
On Error GoTo Err_DrvChange

    dir_Full.Path = drv_Full.Drive
'    fil_Full.Path = ""
    txt_File.Text = ""
    Exit Sub
    
Err_DrvChange:
End Sub



Private Sub fil_Full_Click()
    If Len(dir_Full.Path) > 3 Then
        txt_File.Text = dir_Full.Path & "\" & fil_Full.FileName
    Else
        txt_File.Text = dir_Full.Path & fil_Full.FileName
    End If
End Sub

Private Sub fil_Full_PathChange()
    'txt_File.Text = dir_Full.Path & "\" & fil_Full.FileName
End Sub



Private Sub grList_ItemSelected()

    If grList.SelectedCount <> 0 Then
        Call Item_Load(grList.CurrentKey(0))
    End If
    
End Sub



Private Sub tabCmd_Click()
    
    
    Screen.MousePointer = vbHourglass
    
    If tabCmd.SelectedItem Is Nothing Then
        Screen.MousePointer = 0
        Exit Sub
    End If
    
    If mTestAction = etaAdd Then
        Screen.MousePointer = 0
        Exit Sub
    End If
    
    If right(tabCmd.SelectedItem.Key, 1) = mSelectedView Then
        Screen.MousePointer = 0
        Exit Sub
    End If
    
    Call SetView(right(tabCmd.SelectedItem.Key, 1))
    
    Screen.MousePointer = 0
    
End Sub


Private Sub TVTest_CheckboxesChange(Checkboxes As Boolean)
    grList.Requests = ""
    Call grList.ClearGrid
End Sub

Private Sub TVTest_NodeClick(ByVal Node As MSComctlLib.Node)

    Screen.MousePointer = vbHourglass
    ' Clear the grids
    grList.Requests = ""
    Call grList.ClearGrid


    If TVTest.Checkboxes Then
        Screen.MousePointer = 0
        Exit Sub
    End If


    ' If the selected node is on the last level, we have to load the grids
    
    If TVTest.NodeInfo(Node).ml_Level = TVTest.Levels - 1 Then
        
        grList.Requests = ApplyTVFilters(TVTest.SelectedNodeRequest)
        If grList.Execute = False Then
            'ERROR
        End If
    End If

    Screen.MousePointer = 0

End Sub


Private Function SetMode(ByVal aMode As eTestModes)

    Screen.MousePointer = vbHourglass

    fraItem.Visible = False
    fraList.Visible = False
    
    Select Case aMode
        Case eTestModes.etmList
            Call EnableFrame(UserControl.Controls, fraFilters, True)
            Call EnableFrame(UserControl.Controls, fraFiltersDate, True)
            fraList.Visible = True
            fraList.ZOrder
        Case eTestModes.etmItem
            Call EnableFrame(UserControl.Controls, fraFilters, False)
            Call EnableFrame(UserControl.Controls, fraFiltersDate, False)
            fraItem.Visible = True
            fraItem.ZOrder
    End Select

    Screen.MousePointer = 0

End Function


' Apply default value on a screen
Private Sub EnableFrame(ByRef aControls As Variant, ByRef aContainer As Object, ByVal aEnabled As Boolean)
    
    Const CL_COLOR_ENABLED As Long = &H80000005
    Const CL_COLOR_DISABLED As Long = &H8000000F
    
    Dim lIdx As Long, lCount As Long
    Dim lControl As Control
    
    lCount = aControls.Count - 1
    For lIdx = 0 To lCount
        Set lControl = aControls.Item(lIdx)
        
        If HasContainer(lControl, aContainer) Then
            Select Case UCase(TypeName(lControl))
                Case "FRAME", "LABEL", "MSFLEXGRID"
                    ' Do nothing !
                Case "TEXTBOX"
                    lControl.Locked = Not aEnabled
                    lControl.BackColor = IIf(aEnabled, CL_COLOR_ENABLED, CL_COLOR_DISABLED)
                Case "ARMGRID", "COMMANDBUTTON", "ARMCHECKVIEW"
                Case "ARMCOMBOBOX"
                    lControl.Enabled = aEnabled
                Case Else
                    lControl.Enabled = aEnabled
                
            End Select
        End If
        
        Set lControl = Nothing
    Next

End Sub



Private Function HasContainer(ByRef lo_Control As Control, ByRef lo_Container As Object) As Boolean
    
    Dim ll_Index As Long
    Dim lo_Object As Object

    HasContainer = False
    While Not (lo_Control Is Nothing)
        On Error GoTo NotFound
        If lo_Control.Container Is lo_Container Then
            HasContainer = True
            Exit Function
        End If
        Set lo_Control = lo_Control.Container
    Wend

NotFound:
    HasContainer = False

End Function



Private Function GetItemInfoFromDB(ByVal aTestCode As Long) As TTest

    Const CL_REQUEST As String = "Exec Test_Sel2 $test_code$, '$language_code$'"

    Dim lTest As TTest
    
    ' TODO : Check if the test exists
    Dim lRequest As String
    lRequest = Replace(CL_REQUEST, "$test_Code$", aTestCode, , , vbTextCompare)
    lRequest = Replace(lRequest, "$language_code$", mLanguage_Code, , , vbTextCompare)
    
    Dim lData As Long
    lData = mDb.OpenSQL(lRequest)
    
    lTest.FullNumber = mDb.GetFields(lData, "Full_Test_Number")
    lTest.Type = mDb.GetFields(lData, "TT_Type")
    lTest.Category = mDb.GetFields(lData, "CAT_CODE")
    lTest.Sales_Office = mDb.GetFields(lData, "SO_CODE")
    lbl_TestType.Caption = mDb.GetFields(lData, "TT_Desc")
    mDb.Close (lData)
   
    lTest.TestCode = aTestCode
       
    Dim lIdx As Long, lCount As Long
    lCount = UBound(lTest.ViewInitialized)
    For lIdx = 0 To lCount
        lTest.ViewInitialized(lIdx) = False
    Next
    
    lTest.Loaded = True
    
    GetItemInfoFromDB = lTest

End Function


Private Function Item_Load(ByVal aTestCode As Long) As Boolean
    
    ' Get the information about the new Test
    mSelectedTest = GetItemInfoFromDB(aTestCode)
    
    mSelectedTest.ProductViews(0).Type = "T"
    mSelectedTest.ProductViews(1).Type = "A"
    
    ReDim mSelectedTest.ProductViews(0).Data(0, 0)
    ReDim mSelectedTest.ProductViews(1).Data(0, 0)
    
    
    mTestAction = etaView
    tabCmd.Enabled = True
    
    If Not mSelectedTest.Loaded Then
        Exit Function
    End If
    
    Call LogActivty(mDb, mU_Code, ebfViewAProductTest)
    
    ' Compatibility
    Call SetTestCode(aTestCode)
    Call Test_UpdateCommonInformation
   
    txt_ItemFullNumber.Text = mSelectedTest.FullNumber
    
    ' We initialize the view
    Call SetView(mSelectedView)

    If mSelectedView = etvGeneral Then
        Call Item_LoadReminderFromViewGen
    Else
        Call Item_LoadReminderFromDB
    End If

    SetMode (etmItem)
    
    
End Function

Private Sub Item_LoadReminderFromViewGen()
    txtRmCat.Text = cbo_ivgCategory.Text
    txtRmSO.Text = cbo_ivgSalesOffice.Text
    txtRmStd.Text = cbo_ivgStandard.Text
    txtRmTHo.Text = cbo_ivgTestHouse.Text
    txtRmTMg.Text = cbo_ivgTestManager.Text
End Sub


Private Sub Item_LoadReminderFromDB()
    
    Const C_REQUEST As String = "test_sel3 '$lang$', $test_code$"
    
    Dim lRequest As String
    lRequest = ReplaceHolders(C_REQUEST)
    Dim lCurs As Long
    lCurs = mDb.OpenSQL(lRequest)
    txtRmCat.Text = mDb.GetFields(lCurs, "CAT_DESC")
    txtRmSO.Text = mDb.GetFields(lCurs, "SO_Desc")
    txtRmStd.Text = mDb.GetFields(lCurs, "STD_Desc")
    txtRmTHo.Text = mDb.GetFields(lCurs, "THO_Desc")
    txtRmTMg.Text = mDb.GetFields(lCurs, "TMNG_Desc")
    mDb.Close (lCurs)

End Sub

'From Eddy 17/6/5
Private Sub SetView(ByVal aView As eTestViews)

    Screen.MousePointer = vbHourglass
    
    fraItemGeneral.Visible = False
    fraItemConditions.Visible = False
    fraItemProducts.Visible = False
    fraItemResults.Visible = False
    fraItemDocuments.Visible = False
    fraItemReminder.Visible = False
    fraItemTree.Visible = False

    ' Initialize if need
    If Not mSelectedTest.ViewInitialized(aView) Then
        Select Case aView
            Case eTestViews.etvGeneral
                Select Case mTestAction
                    Case eTestAction.etaAdd
                    Case Else
                        Call Item_LoadDBViewGeneral
                End Select
                Call ItemMtncInit_Gen
                
            Case eTestViews.etvConditions
                Call Item_LoadViewConditions
            Case eTestViews.etvDocuments
                Call Item_LoadViewDocuments
            Case eTestViews.etvProducts
                Call Item_LoadViewProducts
            Case eTestViews.etvResult
                Call Item_LoadViewResult
            Case eTestViews.etvTree
                Call Item_LoadViewTree
        End Select
        mSelectedTest.ViewInitialized(aView) = True
    End If
   
    Select Case aView
        Case eTestViews.etvGeneral
            fraItemGeneral.Visible = True
            fraItemGeneral.ZOrder
            Call EnableFrame(UserControl.Controls, fraItemGeneral, False)
        Case eTestViews.etvConditions
            fraItemConditions.Visible = True
            fraItemConditions.ZOrder
            fraItemReminder.Visible = True
            fraItemReminder.ZOrder
            Call EnableFrame(UserControl.Controls, fraItemConditions, False)
        Case eTestViews.etvDocuments
            fraItemReminder.Visible = True
            fraItemDocuments.Visible = True
            fraItemDocuments.ZOrder
            fraItemReminder.ZOrder
            Call EnableFrame(UserControl.Controls, fraItemDocuments, False)
        Case eTestViews.etvProducts
            fraItemReminder.Visible = True
            fraItemProducts.Visible = True
            fraItemProducts.ZOrder
            fraItemReminder.ZOrder
            Call EnableFrame(UserControl.Controls, fraItemProducts, False)
        Case eTestViews.etvResult
            fraItemReminder.Visible = True
            fraItemResults.Visible = True
            fraItemResults.ZOrder
            fraItemReminder.ZOrder
            Call EnableFrame(UserControl.Controls, fraItemResults, False)
        Case eTestViews.etvTree
            fraItemReminder.Visible = True
            fraItemTree.Visible = True
            fraItemTree.ZOrder
            fraItemReminder.ZOrder
            
    End Select
    
    Call UpdateCurrentViewToolbar(aView)
    
    mSelectedView = aView
    Screen.MousePointer = 0
    
End Sub

Private Sub SetSubView(ByVal as_Type As String)
    Select Case as_Type
        Case "EditGen"
            fraItemDocuments.Visible = False
            fraItemDocumentMtnc.Visible = False
        Case "EditDoc"
            fraItemDocuments.Visible = False
            fraItemDocumentMtnc.Visible = True
            cbo_Ext.Enabled = False
            txt_File.Enabled = False
            dir_Full.Enabled = False
            fil_Full.Enabled = False
        Case "AddDoc"
            fraItemDocuments.Visible = False
            fraItemDocumentMtnc.Visible = True
            cbo_Ext.Enabled = True
            txt_File.Enabled = True
            dir_Full.Enabled = True
            fil_Full.Enabled = True
    End Select
End Sub

Private Sub UpdateCurrentViewToolbar(ByVal aView As eTestViews)
    
    Dim lRight As Boolean
    Select Case aView
        Case eTestViews.etvGeneral
            If InStr(1, cbo_Views.SelectedItem.GetData(2), "plant", vbTextCompare) > 0 Then
                lRight = False
            Else
                lRight = (mDb.Find(mSlOffAuthorized, "SO_Code", mSelectedTest.Sales_Office) > -1)
            End If
            
        Case eTestViews.etvConditions, eTestViews.etvProducts, eTestViews.etvResult
            lRight = (mDb.Find(mSlOffAuthorized, "SO_Code", mSelectedTest.Sales_Office) > -1)
            
        Case eTestViews.etvDocuments
            lRight = mCanUpdateMedia
    End Select
    
    tcItem.Visible = False
    tcItem.DisplayFace (IIf(lRight, mToolBarFaceViews(aView), C_TOOLBARFACE_ITEM_NOUPDATE))
'    tcItem.ButtonVisible("E") = True

    tcItem.Visible = True
End Sub



Private Sub Item_LoadViewConditions()
    
    Const CL_REQUEST As String = "Test_lst_Conditions_t_lst2 $test_code$, '$lang$'"

    Dim lRequest As String
    lRequest = ReplaceHolders(CL_REQUEST)
    
    grItemCnd.Requests = lRequest
    If Not grItemCnd.Execute Then
        ' TODO Error
    End If
  

End Sub

Private Sub Item_LoadDBViewGeneral()
    
    Const CL_REQUEST As String = "EXEC Test_SelViewGen '$lang$', $test_code$"
    
    Dim lRequest As String
    lRequest = ReplaceHolders(CL_REQUEST)
    
    Dim lData As Long
    lData = mDb.OpenSQL(lRequest)
    
    With mSelectedTest.ViewGeneral
        .CAT_Code = mDb.GetFields(lData, "CAT_Code")
        .CAT_Desc = mDb.GetFields(lData, "CAT_Desc")
        .STD_Code = mDb.GetFields(lData, "STD_Code")
        .STD_Desc = mDb.GetFields(lData, "STD_Desc")
        .TMNG_Code = mDb.GetFields(lData, "TMNG_Code")
        .TMNG_Desc = mDb.GetFields(lData, "TMNG_Desc")
        .MotherFTN = mDb.GetFields(lData, "MotherFTN")
        .THO_Code = mDb.GetFields(lData, "THO_Code")
        .THO_Desc = mDb.GetFields(lData, "THO_Desc")
        .SO_Code = mDb.GetFields(lData, "SO_Code")
        .SO_Desc = mDb.GetFields(lData, "SO_Desc")
        .FullTestNumber = mDb.GetFields(lData, "Full_Test_Number")
        .IndicativeTestNumber = mDb.GetFields(lData, "Indicative_Test_Number")
        .StartDate = mDb.GetFields(lData, "Start_Date")
        .EndDate = mDb.GetFields(lData, "End_Date")
        .olddate = mDb.GetFields(lData, "Old_Date")
        .DropDate = mDb.GetFields(lData, "Drop_Date")
        .InternetFlag = mDb.GetFields(lData, "Internet_Flag")
        .MemoCount = mDb.GetFields(lData, "CountMemo")
        .Type = mSelectedTest.Type
        .iConcurrency = mDb.GetFields(lData, "iConcurrency")
    End With
 '   Call ItemLoadMarket
'    Call ItemLoadCountries(False)

    'Call Item_LoadViewGeneral(mSelectedTest.ViewGeneral)
    mSelectedTest.MarketsLoaded = False
    mSelectedTest.CountriesLoaded = False
    
End Sub

Private Sub Item_LoadViewDocuments()
    
    Const CL_REQUEST As String = "EXEC Test_Media_Lst2 $test_code$, 0"
    
    Dim lRequest As String
    lRequest = ReplaceHolders(CL_REQUEST)
    
    grItemDoc.ClearGrid
    grItemDoc.Requests = lRequest
    
    If Not grItemDoc.Execute Then
        ' TODO Error
    End If

End Sub



' Don't have the time to redo it, need to think to a real programmation
Private Sub Item_LoadViewResult()

    Const CL_REQUEST = "EXEC Test_Result_t_lst $test_code$, $lang$"

    Dim lIdx As Long, lCount As Long, lResIdx As Long
    lCount = txt_Result.Count - 1
    For lIdx = 0 To lCount
        txt_Result(lIdx).Text = ""
        txt_Result(lIdx).Visible = False
        cmd_result(lIdx).Visible = False
        lbl_Res(lIdx).Visible = False
        mla_TYTTranslate(lIdx) = 0              ' task 462 JN
    Next

    Call InitResult(mSelectedTest.Category)

    ' Load the labels
    ' Need to improve the system...
    Call LoadRSLabel(UserControl.Controls, fraItemResults)

    Dim lRequest As String
    lRequest = ReplaceHolders(CL_REQUEST)
    Dim lData As Long
    
    lData = mDb.OpenSQL(lRequest)
    
    lCount = mDb.RowCount(lData)
    For lIdx = 1 To lCount
        lResIdx = mDb.GetFields(lData, 0)
        gv_result(lResIdx, 1) = lResIdx
        gv_result(lResIdx, 3) = mDb.GetFields(lData, 1)
        gv_result(lResIdx, 4) = mDb.GetFields(lData, 2)
        gv_result(lResIdx, 5) = mDb.GetFields(lData, 3)
        mDb.Next (lData)
    Next
    mDb.Close (lData)
    
    
    lCount = gi_nbresult
    For lIdx = 1 To lCount
        txt_Result(lIdx - 1).Text = gv_result(GetCode(lIdx), 4)
        Select Case gv_result(GetCode(lIdx), 2)
            Case 3, 4
                cmd_result(lIdx - 1).Visible = True
                cmd_result(lIdx - 1).Enabled = True
        End Select
        txt_Result(lIdx - 1).Visible = True
        lbl_Res(lIdx - 1).Visible = True
    Next

End Sub

' task462 B
Private Sub InitResult(ByVal as_catCode As String)
    Const C_REQ As String = "EXEC Test_Result_info_lst $CAT_CODE$"

    Dim ls_req As String
    Dim ll_Cursor As Long
    Dim ll_resIdx  As Long
    ls_req = Replace(C_REQ, "$CAT_CODE$", as_catCode)

    ll_Cursor = mDb.OpenSQL(ls_req)
    gi_nbresult = mDb.RowCount(ll_Cursor)
    While Not mDb.EOF(ll_Cursor)
        ll_resIdx = mDb.GetFields(ll_Cursor, "TYT_CODE")
        gv_result(ll_resIdx, 1) = ll_resIdx
        gv_result(ll_resIdx, 2) = mDb.GetFields(ll_Cursor, "TYPE_FIELD")
        gv_result(ll_resIdx, 3) = 1
        gv_result(ll_resIdx, 4) = ""
        mla_TYTTranslate(mDb.GetFields(ll_Cursor, "NUM_FIELD") - 1) = ll_resIdx
        Call mDb.Next(ll_Cursor)
    Wend
    Call mDb.Close(ll_Cursor)

End Sub



Private Function GetCode(ByVal li_indexchamp As Integer) As Integer
'------------------------------------------------------------------
' Name : GetCode
'
' Purpose : return the code of the field according to test category
'
' Parameters : li_indexchamp : field index
'
' Return values : (integer) the code of field
'
' review : 04/20/1999 by D. Pozzera
'------------------------------------------------------------------

    GetCode = mla_TYTTranslate(li_indexchamp - 1)
    
End Function


' Apply default value on a screen
Private Sub LoadRSLabel(ByRef aControls As Variant, ByRef aContainer As Object)
    
    Const CL_REQUEST  As String = "Exec Screen_Csts 'TestRs$count$', $lang$"
    
    Dim lRequest As String
    lRequest = ReplaceHolders(CL_REQUEST)
    lRequest = Replace(lRequest, "$count$", mSelectedTest.Category, , , vbTextCompare)
    
    Dim lCurs As Long
    lCurs = mDb.OpenSQL(lRequest)
    
    Dim lIdx As Long, lCount As Long, lIdxLbl As Long
    Dim lControl As Control
    
    lCount = aControls.Count - 1
    For lIdx = 0 To lCount
        Set lControl = aControls.Item(lIdx)
        If HasContainer(lControl, aContainer) Then
            Select Case UCase(TypeName(lControl))
                Case "LABEL"
                If lControl.Tag <> "" Then
                    lIdxLbl = mDb.Find(lCurs, "FIELD_NAME", lControl.Tag, , 1)
                    If lIdxLbl >= 0 Then
                        lControl.Caption = mDb.GetFields(lCurs, "LOCAL_TEXT")
                    End If
                End If
            End Select
        End If
        
        Set lControl = Nothing
    Next

    mDb.Close (lCurs)

End Sub


Private Sub Item_LoadViewProducts()

    Dim lIdx As Long, lCount As Long, lSelIdx As Long
    lCount = opt_ProdView.Count - 1
    For lIdx = 0 To lCount
        If opt_ProdView(lIdx).value Then
            lSelIdx = lIdx
            Exit For
        End If
    Next
    Call LoadViewProducts(lSelIdx)

End Sub


Private Sub opt_ProdView_Click(Index As Integer)
    Screen.MousePointer = vbHourglass
    Call LoadViewProducts(Index)
    Screen.MousePointer = 0
End Sub


Private Sub LoadProductLst(ByVal aTLPCode As Long, ByVal aTLPTYPE As eTLPType, ByVal aBISAPCode As String)

'    Const CL_REQUEST As String = "Test_Link_Products_t_Lst5 $tlp_code$"
'
'
'    Select Case aTLPTYPE
'        Case eTLPType.etlWithCriteria
'            Dim lRequest As String
'            lRequest = Replace(CL_REQUEST, "$tlp_code$", aTLPCode, , , vbTextCompare)
'            grItemProdLst.Requests = lRequest
'            If Not grItemProdLst.Execute Then
'                ' ERROR
'            End If
'
'        Case eTLPType.etlWithProduct
'            ' Read from the grid
'            grItemProdLst.AddLine (aBISAPCode)
'            'grItemProdLst.AddLine (Array(grItemProd.CurrentLine(IIf(mSelectedProductView = epvTested, 0, 2))))
'    End Select
'    grItemProdLst.Visible = True

End Sub

'Private Sub cmd_Country_Click()
'    If Not mSelectedTest.CountriesLoaded Then
'        Call ItemLoadCountry
'    End If
'    mSelectedTest.CountriesLoaded = Not mSelectedTest.CountriesLoaded
'    lst_Country.Visible = mSelectedTest.CountriesLoaded
'
'End Sub

Private Sub lst_On_What_Click()
    If lst_On_What.ListIndex <> -1 Then
        mTestActionType = lst_On_What.ItemData(lst_On_What.ListIndex)
        Call ItemMtncAdd_Gen
    End If
End Sub

Private Sub lst_On_What_LostFocus()
    lst_On_What.Visible = False
End Sub


Private Sub lst_On_What3_Click()
    'OPTION DEPRECATED
    If lst_On_What3.ListIndex <> -1 Then
        lst_On_What3.Visible = False
        SetMode (etmItem)
        mTestActionType = lst_On_What3.ItemData(lst_On_What3.ListIndex)
        mTestAction = etaAdd
        tabCmd.Tabs.Item(1).Selected = True
        Call ItemMtncAdd_Gen
    End If
End Sub

Private Sub Item_GrdAdd(ByVal AType As eTestType)
    SetMode (etmItem)
    mTestActionType = AType
    mTestAction = etaAdd
    tabCmd.Tabs.Item(1).Selected = True
    Call SetView(right(tabCmd.SelectedItem.Key, 1))
    Call ItemMtncAdd_Gen
End Sub


Private Sub lst_On_What3_LostFocus()
    lst_On_What3.Visible = False
End Sub


Private Sub lst_On_What2_Click()
    Call Item_GenUpd
End Sub
Private Sub lst_On_What2_LostFocus()
    lst_On_What2.Visible = False
End Sub


Private Sub lst_On_What4_Click()
    Call ItemMtncAdd_Prod
End Sub
Private Sub lst_On_What4_LostFocus()
    lst_on_what4.Visible = False
End Sub

Private Sub Item_GenUpd()
    ' DEPRECATED
    gs_Action = "Update"
    lst_On_What2.Visible = False
    Select Case lst_On_What2.ListIndex
        Case 0
            Call ItemMtncUpd_Gen
        Case 1
            gb_Return = False
            TestMar2.show 1
            If gb_Return Then
                If mSelectedTest.MarketsLoaded Then
                    'Call ItemLoadMarket
                End If
                
                If mSelectedTest.CountriesLoaded Then
                    'Call ItemLoadCountry
                End If
            End If
        
        Case Else
            ' ERROR
    End Select

End Sub


Private Sub Item_ResUpd()

    gs_Action = "Update"
    
    Dim lo_dlg As TestRes_mtnc
    Set lo_dlg = New TestRes_mtnc
    
    Dim ll_i As Long
    For ll_i = LBound(mla_TYTTranslate) To UBound(mla_TYTTranslate)
        lo_dlg.TYTtranslate(ll_i) = mla_TYTTranslate(ll_i)
    Next
    
    Call lo_dlg.show(1)
    
    Call Item_RefreshCurrentView

End Sub



Private Sub Item_RefreshCurrentView()
    mSelectedTest.ViewInitialized(mSelectedView) = False
    
    If mSelectedView = etvProducts Then
        mSelectedTest.ProductViews(0).Loaded = False
        mSelectedTest.ProductViews(1).Loaded = False
    End If
    
    SetView (mSelectedView)
End Sub




Private Sub grItemDoc_ItemSelected()
    
    Dim ls_MediaCode As String
    Dim lKey As Variant
    
    lKey = grItemDoc.CurrentKey

    If IsEmpty(lKey) Then Exit Sub ' nothing selected
    
    On Error GoTo onError
    
    MouseOff
    
    ls_MediaCode = lKey(0)
    Debug.Assert (ls_MediaCode <> "")
    
    Call DisplayMedia(mDb, ls_MediaCode)
    
    Call MouseOn
    Exit Sub
    
onError:
    Call UpdateError(True)
    
    ' save error into DB
    Call UploadSQLError(mDb, adb_err, "/grItemDoc_ItemSelected")
    
    Call UpdateError(False)
    
    ' display error
    Call StdError
    
    Call MouseOn
End Sub



Private Sub Item_ViewMemo()

    gs_TableName = "Test_Memo"
    gut_Param.Str1 = mSelectedTest.TestCode
    gut_Param.Str2 = "Memo"
    gut_Param.Str3 = ""
    gut_Param.Str4 = "EXEC Test_Memo_Ins"
    gut_Param.Str5 = "EXEC Test_Memo_Lst"
    gut_Param.Str6 = "EXEC Test_Memo_Del"
    gut_Param.Str7 = "EXEC Test_Memo_Upd"
    
    
    gut_Param.Str8 = IIf(mTestAction = eTestAction.etaUpdate, "1", "0")
    Memo_mtnc.show 1
    If mTestAction = eTestAction.etaUpdate Then
        mSelectedTest.ViewGeneral.MemoCount = GetTestMemoCount
        cmd_Memo.Caption = mCmdMemoCaption & "(" & mSelectedTest.ViewGeneral.MemoCount & ")"
    End If

End Sub


Private Sub Item_ViewCndCurve(ByVal Index As Long)
    
    'iconcurrency
    gut_Param.Str25 = gv_result(GetCode(Index), 3)
    'field code
    gut_Param.Str26 = gv_result(GetCode(Index), 1)
    'test code
    gut_Param.Str27 = CStr(gi_TestCode)
    'concatenated field
    gut_Param.Str28 = gv_result(GetCode(Index), 4)
    'curve ID
    gut_Param.Str29 = gv_result(GetCode(Index), 5)
    
    If gv_result(GetCode(Index), 2) = 3 Then
        'curve with 6 items
        gs_ParamReqIns = "exec Test_Value_Curve_ins1"
        gs_ParamReqUpd = "exec Test_Value_Curve_upd1"
        gut_Param.Str1 = "Test_6"
        gut_Param.Str23 = "exec Screen_Csts 'mtnc_Curve_6v'"
    ElseIf gv_result(GetCode(Index), 2) = 4 Then
        'curve with 18 items
        gs_ParamReqIns = "exec Test_Value_Curve_ins2"
        gs_ParamReqUpd = "exec Test_Value_Curve_upd2"
        gut_Param.Str1 = "Test_18"
        gut_Param.Str23 = "exec Screen_Csts 'mtnc_Curve_18v'"
    End If
    
    gs_Action = "MoreInfo"
    Tech_Value_Curve.show 1

    MouseOn

End Sub


Private Sub tcGrid_action(ByVal as_Role As String, as_Language As String)
    
    Screen.MousePointer = vbHourglass
    lst_On_What3.Visible = False
    Select Case as_Role
        Case "A"    ' Add
            'Call DisplayMenu_ListGenAdd
            Call Item_GrdAdd(ettReal)
        Case "L"    ' Load treeview
            Call LoadCurrentTVSelection
            
        Case "F"    ' Refresh (treeview and grid)
            Call RefreshList
            
        Case "T"    ' Exit from test manager
            RaiseEvent Unload
    End Select
    Screen.MousePointer = 0
End Sub


Private Sub tcItem_Action(ByVal as_Role As String, as_Language As String)
    
On Error GoTo Err_tcItem
    
    Screen.MousePointer = vbHourglass
    
    lst_On_What.Visible = False
    lst_On_What2.Visible = False
    lst_on_what4.Visible = False
    
    Select Case as_Role
        ' Common
        Case "J"    ' Previous item
            Call GotoPreviousItem
            
        Case "K"    ' Next Item
            Call GotoNextItem
            
        Case "F"    ' Refresh current view
            Call Item_RefreshCurrentView
            
        Case "T"    ' Exit from Item Mode
            SetMode (etmList)
            
        ' Specific to view General, Face 0 and 1
        Case "A"    ' Add a test
            Call DisplayMenu_ItemGenAdd
        Case "B"    ' Edit a test
            'Call DisplayMenu_ItemGenUpd
            Call ItemMtncUpd_Gen
        Case "C"    ' Delete a test
            Call ItemMtncDel_Gen
        
        ' Specific to view Conditions
        Case "G"    ' Add a condition
            Call ItemMtncAdd_Cnd
        Case "H"    ' Delete a condition
            Call ItemMtncDel_Cnd
        Case "E"    ' Conditions maintenance
            Call DisplayMenu_ItemMtncCnd
        
        ' Specific to view result
        Case "I"    ' Update a result
           Call Item_ResUpd
        
        ' Specific to view Products
        Case "L" ' Update products
            'Call Item_PrdUpd
        Case "V"
            'Call DisplayMenu_ItemPrdAdd
            Call ItemMtncAdd_ProdProduct
        Case "U"
            Call ItemMtncDel_Prd
        
        ' Specific to view Document
        Case "M"    ' Add a document
            Call ItemMtncAdd_Doc
        Case "O"    ' Delete a document
            Call ItemMtncDel_Doc
        Case "N"    ' Edit a document
            Call ItemMtncUpd_Doc
        
        ' Specific to add mode
        Case "P"    ' Add item
            Call Item_Add
        Case "R"    ' ?
            Call ItemMtncMore
        Case "S"    ' Reset
            Call ItemMtncAddClear
        
        ' Specific to Del mode
        Case "D"
            Call Item_Del
        
        ' Specific to Update mode
        Case "Z"
           Call Item_Upd
        
        Case "W"    ' Exit from add/update/delete mode
            Call Item_MtncExit
        
    End Select
    
    Screen.MousePointer = 0
    Exit Sub
    
Err_tcItem:
    Screen.MousePointer = 0
    
    Select Case mNumber - C_ERRORRAISE
    Case 195
        SendMessage 195, "Unable to save the test.", mLanguage_Code
    Case 196
        SendMessage 196, "Unable to delete the test.", mLanguage_Code
    Case 197
        SendMessage 197, "Unable to save the conditions of this test.", mLanguage_Code
    Case 198
        SendMessage 198, "Unable to delete the conditions of this test.", mLanguage_Code
    Case 199
        SendMessage 199, "Impossible to delete products linh to this test.", mLanguage_Code
    Case 155
        Call SendFieldErrMsg(964, mZipMaxSize / 1024, txt_File)
'        MsgBox "This file is bigger than :" & mZipMaxSize / 1024 & " Ko avec compression and will overload the network. Please select a lower one."
    Case 159
        SendMessage 159, "Error while saving media association. Please contact your IT support.", mLanguage_Code
    Case 156
        SendMessage 159, "Error while saving media association. Please contact your IT support.", mLanguage_Code
    Case Else
        MsgBox "unexpected error : " & Err.Number & "," & Err.Description
    End Select
End Sub

Private Sub DisplayMenu_ItemGenUpd()
    
    Screen.MousePointer = vbHourglass
    
    lst_On_What.Visible = False
    If Not lst_On_What2.Visible Then
        lst_On_What2.ZOrder
        lst_On_What2.ListIndex = -1
        lst_On_What2.Visible = True
        lst_On_What2.SetFocus
    Else
        lst_On_What2.Visible = False
    End If
    
    Screen.MousePointer = 0
        
End Sub


Private Sub DisplayMenu_ItemPrdAdd()
    
    If Not lst_on_what4.Visible Then
        lst_on_what4.ZOrder
        lst_on_what4.ListIndex = -1
        lst_on_what4.Visible = True
        lst_on_what4.SetFocus
    Else
        lst_on_what4.Visible = False
    End If
    
End Sub



Private Sub DisplayMenu_ItemGenAdd()
    
    lst_On_What2.Visible = False
    If Not lst_On_What.Visible Then
        lst_On_What.ZOrder
        lst_On_What.ListIndex = -1
        lst_On_What.Visible = True
        lst_On_What.SetFocus
    Else
        lst_On_What.Visible = False
    End If
    
End Sub


Private Sub DisplayMenu_ListGenAdd()
    
    If Not lst_On_What3.Visible Then
        lst_On_What3.ZOrder
        lst_On_What3.ListIndex = -1
        lst_On_What3.Visible = True
        lst_On_What3.SetFocus
    Else
        lst_On_What3.Visible = False
    End If
    
End Sub

Private Sub LoadCurrentTVSelection()
    If TVTest.Checkboxes = True Then
        grList.Requests = ApplyTVFilters(TVTest.CheckedNodesRequests)
    Else
        grList.Requests = ApplyTVFilters(TVTest.SelectedNodeRequest)
    End If
    If grList.Execute = False Then
        'Error
    End If
End Sub


Private Sub GotoPreviousItem()
    If Not grList.PreviousItem Then
        Call SendMessage(927, "#No more previous item", mLanguage_Code)
    End If
End Sub

Private Sub GotoNextItem()
    If Not grList.NextItem Then
        Call SendMessage(928, "#No more next item", mLanguage_Code)
    End If
End Sub



Private Sub RefreshList()

    TVTest.Refresh
    If TVTest.Checkboxes = True Or grList.Row > 0 Then
        Call LoadCurrentTVSelection
    End If
End Sub


Private Sub Item_Add()
    
On Error GoTo Err_Item_Add
    
    Select Case mSelectedView
        Case eTestViews.etvConditions
            Call ItemAdd_Cnd
        Case eTestViews.etvGeneral
            Call ItemAdd_Gen
        Case eTestViews.etvDocuments
            Call ItemAdd_Doc
    End Select
    Exit Sub

Err_Item_Add:
    Err.Raise mNumber, mSource, mDesc
End Sub



Private Sub cbo_TypeCnd_ComboItemSelected()
    If cbo_TypeCnd.SelectedItem Is Nothing Then Exit Sub
    Call LoadCndLst(cbo_TypeCnd.SelectedItem.Key, cbo_TypeCnd.SelectedItem.GetData(2))
End Sub


Private Sub LoadCndLst(ByVal AType As Long, ByVal aValueType As Long)

    Select Case aValueType
        Case eTestCndTypeOfValue.etcString
            txt_Cnd.Visible = False
            
            lst_Cnd.Visible = True
            ' LOAD IT !
            Const CL_REQUEST As String = "Exec Test_dtl_Condition_cbo $type_cnd$, $lang$"
            Dim lRequest As String
            lRequest = ReplaceHolders(CL_REQUEST)
            lRequest = Replace(lRequest, "$type_cnd$", AType, , , vbTextCompare)
            Dim lData As Long
            lData = mDb.OpenSQL(lRequest)
            Dim lIdx As Long, lCount As Long
            lCount = mDb.RowCount(lData) - 1
            lst_Cnd.Clear
            For lIdx = 0 To lCount
                Call lst_Cnd.AddItem(mDb.GetFields(lData, "DTLCND_desc"))
                lst_Cnd.ItemData(lIdx) = mDb.GetFields(lData, "DTLCND_code")
                mDb.Next (lData)
            Next
            
        Case eTestCndTypeOfValue.etcInteger
            txt_Cnd.Text = ""
            txt_Cnd.Visible = True
            lst_Cnd.Visible = False
            
    End Select


End Sub

Private Sub Item_MtncExit()
    
    Select Case mSelectedView
        Case eTestViews.etvConditions
            Call ItemMtncExit_Cnd
        Case eTestViews.etvGeneral
            Select Case mTestActionType
                Case eTestType.ettReal, eTestType.ettOpinionOnNothing
                    If mTestAction = etaAdd Then
                        Call ItemMtncExit_GenFromList
                        SetMode (etmList)
                        tabCmd.Enabled = True
                    Else
                        mTestAction = etaView
                        Call ItemMtncExit_Gen
                    End If
                Case Else
                mTestAction = etaView
                    Call ItemMtncExit_Gen
            End Select
        Case eTestViews.etvDocuments
            mTestAction = etaView
            Call ItemMtncExit_Doc
        Case eTestViews.etvProducts
            mTestAction = etaView
            Call ItemMtncExit_Prod
    End Select
    mTestAction = etaView
     
    tabCmd.Enabled = True
    Call UpdateCurrentViewToolbar(mSelectedView)
    
End Sub


Private Sub ItemMtncExit_Cnd()
    ' Clear the Add screen To release memory and be sure that no glitch occured
    fraItemConditionsMtnc.Visible = False
    Call ItemMtncClear_Cnd
End Sub

Private Sub ItemMtncAddClear()
    Select Case mSelectedView
        Case eTestViews.etvConditions
            Call ItemMtncClear_Cnd
        Case eTestViews.etvGeneral
            Call ItemMtncInit_Gen
        Case eTestViews.etvDocuments
            Call ItemMtncClear_Doc
            Call ItemMtncFill_Doc(mSelTestDocument)
    End Select
End Sub

Private Sub ItemMtncAdd_Cnd()
    mTestAction = etaAdd
    Call EnableFrame(UserControl.Controls, fraItemConditionsMtnc, True)
    tabCmd.Enabled = False
    ItemMtncClear_Cnd
    tcItem.DisplayFace (C_TOOLBARFACE_ITEM_ADD)
    tcItem.ButtonVisible("E") = True
    fraItemConditionsMtnc.Visible = True
    fraItemConditionsMtnc.ZOrder
    cbo_TypeCnd.SetFocus
    
End Sub


Private Sub ItemMtncMore()
    Select Case mSelectedView
        Case eTestViews.etvConditions
            Call ItemMtncMore_Cnd
    End Select
End Sub


Private Sub ItemMtncMore_Cnd()
    ' TODO
End Sub


Private Sub SendFieldErrMsg(ByVal aMsgID As Long, ByVal aCaption As String, ByRef AField As Object)

    Dim lBuffer As String
    Dim lMsgID As Integer
    lMsgID = aMsgID ' @!#'@@ of byref argument !
    lBuffer = MsgText(lMsgID, mLanguage_Code)
    lBuffer = Replace(lBuffer, "$field$", aCaption)
    
    AField.SetFocus
    Call MsgBox(lBuffer, vbOKOnly + vbCritical)

End Sub




Private Function ItemMtncAddCtrl_Cnd() As Boolean

    ItemMtncAddCtrl_Cnd = False
    
    ' Check if the form is completed
    
    Dim lMsg As String
    
    If cbo_TypeCnd.SelectedItem Is Nothing Then
        Call SendFieldErrMsg(966, lbl_typcnd.Caption, cbo_TypeCnd)
        Exit Function
    End If
    
    Dim lValueType As eTestCndTypeOfValue
    lValueType = cbo_TypeCnd.SelectedItem.GetData(2)
    Select Case lValueType
        Case eTestCndTypeOfValue.etcString
            If lst_Cnd.Text = "" Then
                Call SendFieldErrMsg(966, lbl_dtlcnd.Caption, lst_Cnd)
                Exit Function
            End If
        
        Case eTestCndTypeOfValue.etcInteger
            If txt_Cnd.Text = "" Then
                Call SendFieldErrMsg(966, lbl_dtlcnd.Caption, txt_Cnd)
                Exit Function
            End If
            If Not CheckNumericValue(txt_Cnd.Text) Then
                Call SendFieldErrMsg(962, lbl_dtlcnd.Caption, txt_Cnd)
                Exit Function
            End If
    
    End Select
    
    ' Check if the data not already exists
    
    If cbo_TypeCnd.SelectedItem.GetData(2) = eTestCndTypeOfValue.etcString Then
    
        Dim lData As Long
        Const C_DB_REQUEST As String = "exec Test_Lst_CONDITION_Sel $test_code$, $TypCND_Code$, $DTLCND_Code$"
        Dim lRequest As String
        lRequest = ReplaceHolders(C_DB_REQUEST)
        lRequest = Replace(lRequest, "$TypCND_Code$", cbo_TypeCnd.SelectedItem.Key)
        lRequest = Replace(lRequest, "$DTLCND_Code$", Replace(lst_Cnd.ItemData(lst_Cnd.ListIndex), "'", "''", , , vbTextCompare), , , vbTextCompare)
        lData = mDb.OpenSQL(lRequest)
        If mDb.GetFields(lData, "TST_CODE") = mSelectedTest.TestCode Then
            mDb.Close (lData)
            Call SendMessage(963, "This condition already exists", mLanguage_Code)
        End If
        mDb.Close (lData)
    End If
        
    ItemMtncAddCtrl_Cnd = True
    
End Function


Private Sub ItemAdd_Cnd()
    
On Error GoTo Err_ItemAdd_Cnd
    
    ' STEP 1 - Check the validity of the form
    If Not ItemMtncAddCtrl_Cnd Then
        Exit Sub
    End If
    
    ' STEP 2 - Add the data to the database
    If Not ItemDBAdd_Cnd Then
        Err.Raise mNumber, mSource, mDesc
    End If
    
    'STEP 3 - Update local data
     ItemLocalAdd_Cnd
     
     Call Item_MtncExit
     Exit Sub
     
Err_ItemAdd_Cnd:
    Err.Raise mNumber, mSource, mDesc
End Sub


Private Function ItemDBAdd_Cnd() As Boolean
    
On Error GoTo err_ItemDBAdd_Cnd
    ItemDBAdd_Cnd = False
    
    Const C_REQUEST_STR As String = "Test_lst_Conditions_ins1 $test_code$, $lang$, '$type$', '$value$'"
    Const C_REQUEST_INT As String = "Test_lst_Conditions_ins2 $test_code$, $lang$, '$type$', '$value$'"

    Dim lRequest As String
    Dim lValueType As eTestCndTypeOfValue
    lValueType = cbo_TypeCnd.SelectedItem.GetData(2)
    Select Case lValueType
        Case eTestCndTypeOfValue.etcString
            lRequest = ReplaceHolders(C_REQUEST_STR)
            lRequest = Replace(lRequest, "$value$", Replace(lst_Cnd.Text, "'", "''", , , vbTextCompare), , , vbTextCompare)
        Case eTestCndTypeOfValue.etcInteger
            lRequest = ReplaceHolders(C_REQUEST_INT)
            lRequest = Replace(lRequest, "$value$", Replace(txt_Cnd.Text, "'", "''", , , vbTextCompare), , , vbTextCompare)
    End Select
    lRequest = Replace(lRequest, "$type$", Replace(cbo_TypeCnd.SelectedItem.GetData(1), "'", "''", , , vbTextCompare), , , vbTextCompare)

    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 197
        mSource = C_SCREENNAME & "/ItemDBAdd_Cnd :"
        mDesc = "Unable to save the conditions of the test."
        Err.Raise mNumber, mSource, mDesc
    End If
   
    
    ItemDBAdd_Cnd = (mDb.SQLRowsAffected = 1)
    Exit Function
    
err_ItemDBAdd_Cnd:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Sub ItemLocalAdd_Cnd()
    
    Dim lCndType As String, lCndDesc As String, lCndValue As String
    lCndType = cbo_TypeCnd.SelectedItem.GetData(2)
    lCndDesc = cbo_TypeCnd.SelectedItem.GetData(1)
    Select Case lCndType
        Case eTestCndTypeOfValue.etcString
            lCndValue = lst_Cnd.Text
        Case eTestCndTypeOfValue.etcInteger
            lCndValue = txt_Cnd.Text
    End Select
    
    grItemCnd.AddLine (Array(lCndType, lCndDesc, lCndValue))
    ' Check error and don't full refresh if needed

End Sub


Private Function ItemCnd_Selected() As TTestCnd
    
    Dim lSelCondition As Variant
    Dim lSelDesc As String, lSelCdtl As String, lSelValue As String
    
    Dim tSelectedTestCnd As TTestCnd
    
    Dim lKey As Variant
    lKey = grItemCnd.CurrentKey
    
    If IsEmpty(lKey) Then
        ' TODO : select an item
        Exit Function
    End If
    
    tSelectedTestCnd.TypeOfValue = grItemCnd.CurrentKey(0)
    tSelectedTestCnd.Type = grItemCnd.CurrentKey(1)
    tSelectedTestCnd.value = grItemCnd.CurrentKey(2)
    tSelectedTestCnd.Valid = True
    ItemCnd_Selected = tSelectedTestCnd
    
End Function


Private Sub ItemMtncDel_Cnd()
    
    mSelectedTestCnd = ItemCnd_Selected
    
    If Not mSelectedTestCnd.Valid Then
        ' TODO Choose an item please
        Exit Sub
    End If
    
    fraItemConditionsMtnc.Visible = False
    
    Call ItemMtncFill_Cnd(mSelectedTestCnd)
    Call EnableFrame(UserControl.Controls, fraItemConditionsMtnc, False)
    tabCmd.Enabled = False
    tcItem.DisplayFace (C_TOOLBARFACE_ITEM_DEL)
    fraItemConditionsMtnc.Visible = True
    fraItemConditionsMtnc.ZOrder
    
    
End Sub


Private Sub ItemMtncFill_Cnd(ByRef aTestCnd As TTestCnd)

    Call ItemMtncClear_Cnd
    If Not aTestCnd.Valid Then Exit Sub
    
    Call cbo_TypeCnd.AddItem(Array(aTestCnd.Type, aTestCnd.Type), True)
    
    lst_Cnd.Visible = False
    txt_Cnd.Visible = True
    txt_Cnd.Text = aTestCnd.value
    
End Sub


Private Sub ItemMtncClear_Cnd()
    Set cbo_TypeCnd.SelectedItem = Nothing
    lst_Cnd.Clear
    txt_Cnd.Text = ""
    txt_Cnd.Visible = False
    lst_Cnd.Visible = False
End Sub


Private Function ItemMtncDelCtrl_Cnd() As Boolean
    
    ItemMtncDelCtrl_Cnd = False
    
    Dim lUserConfirm As Boolean
    lUserConfirm = SendMessage(5, "Delete record ?", gut_LangLogin.Code, vbQuestion + vbYesNo, "Delete ") = vbYes
    
    If Not lUserConfirm Then Exit Function
    
    ' TODO : Check here if we can really delete the item because of linked entity
    
    ItemMtncDelCtrl_Cnd = True
    
End Function



Private Sub Item_Del()

On Error GoTo Err_Item_Del
    
    Select Case mSelectedView
        Case eTestViews.etvConditions
            Call Item_CndDel
        Case eTestViews.etvGeneral
            Call ItemDel_Gen
    End Select
    Exit Sub

Err_Item_Del:
    Err.Raise mNumber, mSource, mDesc
End Sub

Private Sub Item_CndDel()
    
On Error GoTo Err_Item_CndDel
    
    ' STEP 1 - Check if it's possible to delete
    If Not ItemMtncDelCtrl_Cnd Then
        Exit Sub
    End If
    
    ' STEP 2 - Del the data to the database
    If Not ItemDBDel_Cnd Then
        Err.Raise mNumber, mSource, mDesc
    End If
    
    'STEP 3 - Update local data
     ItemLocalDel_Cnd
     
     ' Make the cleaning..
     mSelectedTestCnd.Valid = False
     
     Call Item_MtncExit
     Exit Sub
     
Err_Item_CndDel:
    Err.Raise mNumber, mSource, mDesc
End Sub

Private Function ItemDBDel_Cnd() As Boolean
    
On Error GoTo Err_ItemDBDel_Cnd
    ItemDBDel_Cnd = False
    
    Const C_REQUEST_STR As String = "Test_lst_Conditions_Del1 $test_code$, $lang$, '$type$', '$value$'"
    Const C_REQUEST_INT As String = "Test_lst_Conditions_Del2 $test_code$, $lang$, '$type$', '$value$'"

    Dim lRequest As String
    Select Case mSelectedTestCnd.TypeOfValue
        Case eTestCndTypeOfValue.etcString
            lRequest = ReplaceHolders(C_REQUEST_STR)
        Case eTestCndTypeOfValue.etcInteger
            lRequest = ReplaceHolders(C_REQUEST_INT)
    End Select
    
    lRequest = Replace(lRequest, "$value$", Replace(txt_Cnd.Text, "'", "''", , , vbTextCompare), , , vbTextCompare)
    lRequest = Replace(lRequest, "$type$", Replace(cbo_TypeCnd.SelectedItem.GetData(1), "'", "''", , , vbTextCompare), , , vbTextCompare)

    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 198
        mSource = C_SCREENNAME & "/ItemDBDel_Cnd :"
        mDesc = "Unable to delete the conditions of the test."
        Err.Raise mNumber, mSource, mDesc
    End If
        
    If mDb.SQLRowsAffected = 0 Then
        Err.Raise mNumber, mSource, mDesc
    End If
    
    ItemDBDel_Cnd = True
    Exit Function
    
Err_ItemDBDel_Cnd:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Sub ItemLocalDel_Cnd()
    Call grItemCnd.DeleteLine(Array(mSelectedTestCnd.TypeOfValue, mSelectedTestCnd.Type, mSelectedTestCnd.value))
    ' Check error and don't full refresh if needed
End Sub



' Apply default value on a screen
Private Sub ClearForm(ByRef aControls As Variant, ByRef aContainer As Object)
    
    Dim lIdx As Long, lCount As Long, lControl As Object
    lCount = aControls.Count - 1
    For lIdx = 0 To lCount
        Set lControl = aControls.Item(lIdx)
        If HasContainer(lControl, aContainer) Then
            Select Case UCase(TypeName(lControl))
                Case "TEXTBOX"
                    lControl.Text = ""
                Case "ARMCOMBOBOX"
                    Set lControl.SelectedItem = Nothing
                Case "A_CALOCX"
                    lControl.reinit_cal
                Case "CHECKBOX"
                    lControl.value = False
                Case "ARMCHECKVIEW"
                    'lControl.Reset
            End Select
        End If
        
        Set lControl = Nothing
    Next

End Sub


Private Sub Item_LoadViewGeneral(ByRef aTest As TTestViewGeneral)
    
    Call ClearForm(UserControl.Controls, fraItemGeneral)
    
    With aTest
        
        cbo_ivgStandard.Clear
        cbo_ivgTestManager.Clear
        
        If Not cbo_ivgCategory.SearchItem(.CAT_Code, 0) Then Call cbo_ivgCategory.AddItem(Array(.CAT_Code, .CAT_Desc), True)
        If Not cbo_ivgTestHouse.SearchItem(.THO_Code, 0) Then Call cbo_ivgTestHouse.AddItem(Array(.THO_Code, .THO_Desc), True)
        If Not cbo_ivgSalesOffice.SearchItem(.SO_Code, 0) Then Call cbo_ivgSalesOffice.AddItem(Array(.SO_Code, .SO_Desc), True)
        
        Call cbo_ivgStandard.AddItem(Array(.STD_Code, .STD_Desc), True)
        Call cbo_ivgTestManager.AddItem(Array(.TMNG_Code, .TMNG_Desc), True)

        txt_MotherTest.Text = .MotherFTN
        txt_FullTestNumber.Text = .FullTestNumber
        txt_IndicTestNumber.Text = .IndicativeTestNumber

        caStartDate.date_courte = .StartDate
        caEndDate.date_courte = .EndDate
        caOldDate.date_courte = .olddate
        caDropDate.date_courte = .DropDate

        chk_Int.value = IIf((.InternetFlag = C_INTERNETFLAG_YES), 1, 0)

        cmd_Memo.Caption = mCmdMemoCaption & "(" & .MemoCount & ")"
        cmd_Memo.Enabled = (.MemoCount > 0)
    
        Call ItemMtncFieldsDisplay_Gen(aTest.Type)
    
        'lst_Market.Visible = False
        'lst_Market.Clear
        'cmd_Market.Enabled = True
    
        'lst_Country.Visible = False
        'lst_Country.Clear
        'cmd_Country.Enabled = True
        
        lbl_TestType.Caption = mTestTypeDesc(.Type - 1)
        txt_ItemFullNumber.Text = .FullTestNumber
        
    End With

End Sub

Private Sub ItemMtncFieldsDisplay_Gen(ByVal aTestType As eTestType)
        
    Select Case aTestType
        Case eTestType.ettReal
            lbl_MotherTest.Visible = False
            txt_MotherTest.Visible = False
            txt_MotherTest.Enabled = False
        
        Case eTestType.ettAssessment
            lbl_MotherTest.Visible = True
            txt_MotherTest.Visible = True
            txt_MotherTest.Enabled = True
        
        Case eTestType.ettOpinionOnReal, eTestType.ettOpinionOnAssessment
            lbl_MotherTest.Visible = True
            txt_MotherTest.Visible = True
            txt_MotherTest.Enabled = True
    
        Case eTestType.ettOpinionOnNothing
            lbl_MotherTest.Visible = False
            txt_MotherTest.Visible = False
            txt_MotherTest.Enabled = False
        Case Else
            Debug.Assert (False)                ' unsuported testType
    End Select
    lbl_FullTestNumber.Caption = mTransItemNumber(aTestType - 1)

End Sub


Private Sub ItemMtncAdd_Gen()

    mTestAction = etaAdd
    'mSelectedTest.TestCode = 0
    
    ' Check the validity
    Select Case mTestActionType
        Case eTestType.ettAssessment, eTestType.ettOpinionOnReal
            If mSelectedTest.Type <> eTestType.ettReal Then
                lst_On_What.SetFocus
                SendMessage 116, "Action impossible on this type of test.", mLanguage_Code
                Exit Sub
            End If
        
        Case eTestType.ettOpinionOnAssessment
            If mSelectedTest.Type <> eTestType.ettAssessment Then
                lst_On_What.SetFocus
                SendMessage 116, "Action impossible on this type of test.", mLanguage_Code
                Exit Sub
            End If
    End Select
    
    lst_On_What.Visible = False
    fraItemGeneral.Visible = False
    tabCmd.Enabled = False
    
    ' Create the data if needed
    Call EnableFrame(UserControl.Controls, fraItemGeneral, True)
    Call ItemMtncInit_Gen
    
    ' Disable dependant combo
    'cbo_ivgStandard.Enabled = False
    'cbo_ivgTestManager.Enabled = False
    lbl_FullTestNumber.Caption = mTransItemNumber(mTestActionType - 1)

    Call ItemMtncFieldsDisplay_Gen(mTestActionType)
    'fraIItemGeneralMarkets.Visible = False
    cmd_Memo.Visible = False
    
    tcItem.DisplayFace (C_TOOLBARFACE_ITEM_ADD)
    tcItem.ButtonVisible("E") = False
    fraItemGeneral.Visible = True
    fraItemGeneral.ZOrder
    cbo_ivgCategory.SetFocus

End Sub


Private Sub ItemMtncInit_Gen()
    
    fraItemGeneral.Visible = False
    
    Select Case mTestAction
        Case eTestAction.etaAdd
            Select Case mTestActionType
                Case eTestType.ettReal, eTestType.ettOpinionOnNothing
                    Call ClearForm(UserControl.Controls, fraItemGeneral)
                    cbo_ivgStandard.Enabled = False
                    cbo_ivgTestManager.Enabled = False
                Case eTestType.ettAssessment, eTestType.ettOpinionOnAssessment, eTestType.ettOpinionOnReal
                    Call Item_LoadViewGeneral(mSelectedTest.ViewGeneral)
                    txt_MotherTest.Text = txt_FullTestNumber.Text
                    txt_FullTestNumber = ""
                    Call ItemMtncFieldsDisplay_Gen(mTestActionType)
                    cbo_ivgStandard.Enabled = True
                    cbo_ivgTestManager.Enabled = True
            End Select
            Call ItemLoadMarket
            Call ItemLoadCountries(False)
            Call acvCountries.SetVisibleList("UPD")
            Call acvMarkets.SetVisibleList("UPD")
            
            lbl_TestType.Caption = mTestTypeDesc(mTestActionType - 1)
            txt_ItemFullNumber.Text = ""

        
        Case eTestAction.etaDelete
            Call Item_LoadViewGeneral(mSelectedTest.ViewGeneral)
            Call acvCountries.SetVisibleList("MAIN")
            Call acvMarkets.SetVisibleList("MAIN")
        
        Case eTestAction.etaUpdate
            Call Item_LoadViewGeneral(mSelectedTest.ViewGeneral)
            cbo_ivgCategory.Enabled = False
            cmd_Memo.Enabled = True
            Call acvCountries.SetVisibleList("UPD")
            Call acvMarkets.SetVisibleList("UPD")
        
        Case eTestAction.etaView
            Call Item_LoadViewGeneral(mSelectedTest.ViewGeneral)
            Call ItemLoadMarket
            Call ItemLoadCountries(False)
            Call acvCountries.SetVisibleList("MAIN")
            Call acvMarkets.SetVisibleList("MAIN")
    End Select
  

    fraItemGeneral.Visible = True
    fraItemGeneral.ZOrder
    
    Select Case mTestAction
        Case eTestAction.etaUpdate
            If cbo_ivgStandard.Visible Then cbo_ivgStandard.SetFocus
        Case Else
            If cbo_ivgCategory.Visible Then cbo_ivgCategory.SetFocus
    End Select
    
    
    txt_MotherTest.Locked = True
    
End Sub


Private Sub ItemMtncExit_Gen()
    
    fraItemGeneral.Visible = False
    
    Call ClearForm(UserControl.Controls, fraItemGeneral)
    
    Call EnableFrame(UserControl.Controls, fraItemGeneral, False)
    Call Item_LoadViewGeneral(mSelectedTest.ViewGeneral)
    ItemMtncInit_Gen
'    Call EnableFrame(UserControl.Controls, fraItemGeneral, False)
    
    'fraIItemGeneralMarkets.Visible = True
    cmd_Memo.Visible = True
    fraItemGeneral.Visible = True
    fraItemGeneral.ZOrder
    
End Sub



Private Sub ItemMtncExit_GenFromList()
    fraItemGeneral.Visible = False
    Call ClearForm(UserControl.Controls, fraItemGeneral)
    Call EnableFrame(UserControl.Controls, fraItemGeneral, False)
    'fraIItemGeneralMarkets.Visible = True
    cmd_Memo.Visible = True
    fraItemGeneral.Visible = True
    fraItemGeneral.ZOrder
End Sub


Private Sub ItemAdd_Gen()
    
On Error GoTo Err_ItemAdd_Gen

    ' STEP 1 - Check the validity of the form
    If Not ItemMtncAddCtrl_Gen Then
        Exit Sub
    End If
    
     Dim lTestCode As Long
     lTestCode = ItemDBAdd_Gen
     If lTestCode <= 0 Then
        ' TODO: Error
        Err.Raise mNumber, mSource, mDesc
'        Call MsgBox("Unable to save the item")
'        Exit Sub
     End If
     
    Call LogActivty(mDb, mU_Code, ebfAddAProductTest)
     
    'STEP 3 - Update local data
    Dim lJump As Boolean
    lJump = ItemLocalAdd_Gen(lTestCode)
     
     Call Item_MtncExit
     If lJump Then
        Call grList_ItemSelected
     End If
     
     Exit Sub

Err_ItemAdd_Gen:
    Err.Raise mNumber, mSource, mDesc
End Sub


Private Function ItemMtncAddCtrl_Gen() As Boolean

    ItemMtncAddCtrl_Gen = False
    
    If cbo_ivgCategory.SelectedItem Is Nothing Then
        Call SendFieldErrMsg(966, lbl_Category.Caption, cbo_ivgCategory)
        Exit Function
    End If
    
    If cbo_ivgStandard.SelectedItem Is Nothing Then
        Call SendFieldErrMsg(966, lbl_Standard.Caption, cbo_ivgStandard)
        Exit Function
    End If
    
    If cbo_ivgSalesOffice.SelectedItem Is Nothing Then
        Call SendFieldErrMsg(966, lbl_TestOffice.Caption, cbo_ivgSalesOffice)
        Exit Function
    End If
    
    If cbo_ivgTestHouse.SelectedItem Is Nothing Then
        Call SendFieldErrMsg(966, lbl_TestHouse.Caption, cbo_ivgTestHouse)
        Exit Function
    End If
    
    If cbo_ivgTestManager.SelectedItem Is Nothing Then
        Call SendFieldErrMsg(966, lbl_TestManager.Caption, cbo_ivgTestManager)
        Exit Function
    End If

    ' Mother test depends of the type of test
    Select Case mTestActionType
        Case eTestType.ettReal, eTestType.ettOpinionOnNothing
            ' Mother test not needed
        Case Else
            ' Mother test needed
            If txt_MotherTest.Text = "" Then
                Call SendFieldErrMsg(966, lbl_MotherTest.Caption, txt_MotherTest)
                Exit Function
            End If
    End Select

    If txt_FullTestNumber.Text = "" Then
        Call SendFieldErrMsg(966, lbl_FullTestNumber.Caption, txt_FullTestNumber)
        Exit Function
    End If
    
    
    ' Full test number must be unique
    
    Dim lTstCode As Long
    lTstCode = GetTstCodeFromTestNumber(txt_FullTestNumber.Text)
    
    If lTstCode <> 0 Then
        Dim lWrong As Boolean
        Select Case mTestAction
            Case eTestAction.etaAdd
                lWrong = True
            Case eTestAction.etaUpdate
                lWrong = lTstCode <> Val(mSelectedTest.TestCode)
        End Select
        If lWrong Then
            txt_FullTestNumber.SetFocus
            Call SendMessage(967, "This test number already exists", mLanguage_Code)
            Exit Function
        End If
    End If
    
    If (mTestAction = eTestAction.etaUpdate) And (txt_FullTestNumber.Text <> mSelectedTest.FullNumber) Then
            Dim lBuffer As String
            lBuffer = MsgText(5, gut_LangLogin.Code)
            If lBuffer = "" Then lBuffer = "#Do you confirm the change of the test number ?"
            If MsgBox(lBuffer, vbQuestion + vbYesNo, "Confirm ") = vbNo Then
                txt_FullTestNumber.Text = mSelectedTest.FullNumber
            End If
    End If

    If (caStartDate.date_courte = "") Then
        caStartDate.SetFocus
        SendMessage 171, "Starting date must be filled.", gut_LangLogin.Code
        Exit Function
    End If
    If (caEndDate.date_courte <> "") Then
        If DateDiff("d", caStartDate.date_courte, caEndDate.date_courte) < 1 Then
            caEndDate.SetFocus
            SendMessage 172, "Ending date must be greather than starting date", gut_LangLogin.Code
            Exit Function
        End If
    End If
    If (caOldDate.date_courte <> "") Then
        If (caEndDate.date_courte = "") Then
            caEndDate.SetFocus
            SendMessage 173, "Ending date must be filled.", gut_LangLogin.Code
            Exit Function
        End If
        If DateDiff("d", caEndDate.date_courte, caOldDate.date_courte) < 1 Then
            caOldDate.SetFocus
            SendMessage 174, "Old date must be greather than ending date.", gut_LangLogin.Code
            Exit Function
        End If
    End If
    If (caDropDate.date_courte <> "") Then
        If DateDiff("d", caStartDate.date_courte, caDropDate.date_courte) < 1 Then
            caDropDate.SetFocus
            SendMessage 175, "Dropped date must be greather than starting date.", gut_LangLogin.Code
            Exit Function
        End If
    End If
    
    ' At least one market is needed
    If acvMarkets.CheckedCount("UPD") = 0 Then
        'TODO :
        acvMarkets.SetFocus
        MsgBox ("At least one market must be checked !")
        Exit Function
    End If
    
    ItemMtncAddCtrl_Gen = True

End Function

Private Function GetTstCodeFromTestNumber(ByVal aFullTestNumber) As Long
    
    Const L_REQUEST = "GetTstCode '$Full_Test_Number$'"
    Dim lRequest As String
    lRequest = Replace(L_REQUEST, "$Full_Test_Number$", aFullTestNumber, , , vbTextCompare)
    
    Dim lCurs As Long
    lCurs = mDb.OpenSQL(lRequest)
    GetTstCodeFromTestNumber = mDb.GetFields(lCurs, "TST_CODE")
    mDb.Close (lCurs)
    
    
End Function



Private Sub cbo_ivgCategory_ComboItemSelected()
    
    If Not cbo_ivgCategory.SelectedItem Is Nothing And (mTestAction = etaAdd Or mTestAction = etaUpdate) Then
        cbo_ivgStandard.Enabled = True
        cbo_ivgStandard.Clear
        Dim lBuffer As String
        lBuffer = ReplaceHolders(C_REQUEST_CBO_STANDARD)
        lBuffer = Replace(lBuffer, "$cg_code$", cbo_ivgCategory.SelectedItem.Key)
        cbo_ivgStandard.Request = lBuffer
        Call ItemLoadMarket
        Call ItemLoadCountries(False)
    End If
    
End Sub


Private Sub cbo_ivgSalesOffice_ComboItemSelected()
    If Not cbo_ivgSalesOffice.SelectedItem Is Nothing And (mTestAction = etaAdd Or mTestAction = etaUpdate) Then
        cbo_ivgTestManager.Enabled = True
        cbo_ivgTestManager.Clear
        Dim lBuffer As String
        lBuffer = ReplaceHolders(C_REQUEST_CBO_TESTMANAGER)
        lBuffer = Replace(lBuffer, "$so_code$", cbo_ivgSalesOffice.SelectedItem.Key)
        cbo_ivgTestManager.Request = lBuffer
    End If

End Sub

Private Function ItemDBAdd_Gen() As Long

    Const C_DB_REQUEST As String = "Exec Test_ins $tt_type$, $cat_code$, $std_code$, $tmng_code$, $mother$, $tho_code$, '$so_code$', '$start_date$','$end_date$', '$old_date$', '$full_test_number$', '$indicative$', '$old_flag$', '$published$', '$internet$', '$drop$', '$drop_date$'"
    
On Error GoTo Err_ItemDBAdd_Gen

    ItemDBAdd_Gen = 0
    
    Dim lRequest As String
    
    lRequest = ReplaceHolders(C_DB_REQUEST)
    lRequest = Replace(lRequest, "$tt_type$", mTestActionType)
    lRequest = Replace(lRequest, "$cat_code$", cbo_ivgCategory.SelectedItem.Key)
    lRequest = Replace(lRequest, "$std_code$", cbo_ivgStandard.SelectedItem.Key)
    lRequest = Replace(lRequest, "$tmng_code$", cbo_ivgTestManager.SelectedItem.Key)
    
    Dim lBuffer As String
    Select Case mTestActionType
        Case eTestType.ettAssessment, eTestType.ettOpinionOnAssessment, eTestType.ettOpinionOnReal
            lBuffer = "'" & Replace(txt_MotherTest.Text, "'", "''", , , vbTextCompare) & "'"
        Case Else
            lBuffer = "null"
    End Select
    lRequest = Replace(lRequest, "$mother$", lBuffer)
    
    lRequest = Replace(lRequest, "$tho_code$", cbo_ivgTestHouse.SelectedItem.Key)
    lRequest = Replace(lRequest, "$so_code$", cbo_ivgSalesOffice.SelectedItem.Key)
    lRequest = Replace(lRequest, "$start_date$", caStartDate.date_us)
    lRequest = Replace(lRequest, "$end_date$", caEndDate.date_us)
    lRequest = Replace(lRequest, "$old_date$", caOldDate.date_us)
    lRequest = Replace(lRequest, "$full_test_number$", Replace(txt_FullTestNumber.Text, "'", "''", , , vbTextCompare))
    lRequest = Replace(lRequest, "$indicative$", Replace(txt_IndicTestNumber.Text, "'", "''", , , vbTextCompare))
    
    ' TODO : check if the following flags are correct
    lRequest = Replace(lRequest, "$old_flag$", IIf(caOldDate.date_us = "", "", "X"))
    lRequest = Replace(lRequest, "$published$", "")
    
    lRequest = Replace(lRequest, "$internet$", IIf(chk_Int.value = 1, "X", ""))
    lRequest = Replace(lRequest, "$drop$", IIf(caDropDate.date_us = "", "", "X"))
    lRequest = Replace(lRequest, "$drop_date$", caDropDate.date_us)

    Dim lResult As Long
    lResult = mDb.OpenSQL(lRequest)
    If lResult <= 0 Then
        mNumber = C_ERRORRAISE + 195
        mSource = C_SCREENNAME & "/ItemDBAdd_Gen :"
        mDesc = "Unable to save the test"
        Err.Raise mNumber, mSource, mDesc
    End If
    
    Dim lTestCode As Long
    lTestCode = mDb.GetFields(lResult, 0)
    mDb.Close (lResult)

    acvMarkets.Calling_Key_Values = lTestCode & "®©" & cbo_ivgCategory.SelectedItem.Key
    If Not acvMarkets.SaveList Then
        ' TODO Manage error
    End If
    ' Don't need the list for saving, i hope
    acvCountries.Calling_Key_Values = lTestCode & "®©" & "null"
    If Not acvCountries.SaveList Then
        ' TODO Manage error
    End If

    ItemDBAdd_Gen = lTestCode
    
    Exit Function
    
Err_ItemDBAdd_Gen:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    mDb.Close lResult
    Err.Raise mNumber, mSource, mDesc
End Function


Private Function GetItemInfoFromForm(ByVal aTestCode) As TTest

    Dim lTest As TTest
    
    Const CL_REQUEST As String = "Exec Test_Sel2 $test_code$"
    
    lTest.ProductViews(0).Type = "T"
    lTest.ProductViews(1).Type = "A"
    
    With lTest
        .Category = cbo_ivgCategory.SelectedItem.Key
        .CountriesLoaded = False
        .FullNumber = txt_FullTestNumber.Text
        .MarketsLoaded = False
        .TestCode = aTestCode
        .Type = mTestActionType
        .Sales_Office = cbo_ivgSalesOffice.SelectedItem.Key
        With .ViewGeneral
            .CAT_Code = cbo_ivgCategory.SelectedItem.Key
            .CAT_Desc = cbo_ivgCategory.SelectedItem.DisplayText
            .DropDate = caDropDate.date_courte
            .EndDate = caEndDate.date_courte
            .FullTestNumber = txt_FullTestNumber.Text
            .IndicativeTestNumber = txt_IndicTestNumber.Text
            .InternetFlag = IIf(chk_Int.value = 1, "X", "")
            .MemoCount = 0
            .MotherFTN = txt_MotherTest.Text
            .olddate = caOldDate.date_courte
            .SO_Code = cbo_ivgSalesOffice.SelectedItem.Key
            .SO_Desc = cbo_ivgSalesOffice.SelectedItem.DisplayText
            .StartDate = caStartDate.date_courte
            .STD_Code = cbo_ivgStandard.SelectedItem.Key
            .STD_Desc = cbo_ivgStandard.SelectedItem.DisplayText
            .THO_Code = cbo_ivgTestHouse.SelectedItem.Key
            .THO_Desc = cbo_ivgTestHouse.SelectedItem.DisplayText
            .TMNG_Code = cbo_ivgTestManager.SelectedItem.Key
            .TMNG_Desc = cbo_ivgTestManager.SelectedItem.DisplayText
            .Type = mTestActionType
        End With
        .ViewInitialized(eTestViews.etvGeneral) = True
        
        .Loaded = True
    End With
        
    GetItemInfoFromForm = lTest

End Function


Private Sub fil_Full_KeyUp(KeyCode As Integer, Shift As Integer)
    If KeyCode = 116 Then
        fil_Full.Refresh
        txt_File.Text = ""
    End If
    
End Sub



Private Sub dir_Full_KeyUp(KeyCode As Integer, Shift As Integer)
    If KeyCode = 116 Then
        dir_Full.Refresh
        fil_Full.Refresh
    End If
    
End Sub


Private Sub drv_Full_KeyUp(KeyCode As Integer, Shift As Integer)

    If KeyCode = 116 Then
        drv_Full.Refresh
    End If
    
End Sub



Private Sub ItemAdd_Doc()

On Error GoTo Err_ItemAdd_Doc

    ' STEP 1 - Check the validity of the form
    If Not ItemMtncAddCtrl_Doc Then
        Exit Sub
    End If
    
     If Not ItemDBAdd_Doc Then
        If Err.Number <> 53 Then
            Err.Raise mNumber, mSource, mDesc
        Else
            Exit Sub
        End If
     End If
     
     'STEP 3 - Update local data
     Call ItemLocalAdd_Doc
     
     Call Item_MtncExit
     Exit Sub

Err_ItemAdd_Doc:
    Err.Raise mNumber, mSource, mDesc
End Sub

Private Sub ItemMtncAdd_Doc()

    tabCmd.Enabled = False
    fraItemDocuments.Visible = False
    
    Call SetSubView("AddDoc")
    
    Dim lTestDocument As TTestDocument
    mSelTestDocument = lTestDocument

    ' Clear
    Call ItemMtncClear_Doc
    
    fraItemDocumentMtnc.Visible = True
    fraItemDocumentMtnc.ZOrder
    txt_Title.SetFocus
    tcItem.DisplayFace (C_TOOLBARFACE_ITEM_ADD)
    tcItem.ButtonVisible("E") = False


End Sub

Private Sub ItemMtncUpd_Doc()

    Dim lKey As Variant
    lKey = grItemDoc.CurrentKey
    
    If IsEmpty(lKey) Then
        ' TODO : select an item
        Exit Sub
    End If
    
    Call SetSubView("EditDoc")
    
    ' Clear
    Call ItemMtncClear_Doc
    
    Dim lTestDocument As TTestDocument
    mSelTestDocument = lTestDocument
    mSelTestDocument.MD_Code = lKey(0)
    mSelTestDocument.Zip_code = lKey(1)
    mSelTestDocument.MediaConcurrency = lKey(2)
    
    tabCmd.Enabled = False
    fraItemDocuments.Visible = False
    
    ' fill structure
    Call ItemDBFill_Doc(mSelTestDocument)
    
    ' Fill
    Call ItemMtncFill_Doc(mSelTestDocument)
    

    txt_Title.SetFocus
    tcItem.DisplayFace (C_TOOLBARFACE_ITEM_UPD)
    tcItem.ButtonVisible("E") = False


End Sub

Private Sub ItemMtncFill_Doc(ByRef aTestDoc As TTestDocument)

    If aTestDoc.FE_Code <> "" Then
        If Not cbo_Ext.SearchItem(aTestDoc.FE_Code, 0) Then Call cbo_Ext.AddItem(Array(aTestDoc.FE_Code, aTestDoc.FE_Desc), True)
        fil_Full.Pattern = aTestDoc.FE_Desc
    End If
    
    If aTestDoc.MD_Language_Code <> "" Then
        If Not cbo_DocumentLanguage.SearchItem(aTestDoc.MD_Language_Code, 0) Then Call cbo_DocumentLanguage.AddItem(Array(aTestDoc.MD_Language_Code, aTestDoc.MD_Language_Desc), True)
    End If
    
    If aTestDoc.Access_type <> "" Then
        If Not cbo_access.SearchItem(aTestDoc.Access_type, 0) Then Call cbo_access.AddItem(Array(aTestDoc.Access_type, aTestDoc.Access_type_desc), True)
    End If
    txt_File.Text = aTestDoc.FileName
    txt_Title.Text = aTestDoc.PT_Title
    If aTestDoc.Validity_StartDate <> 0 Then
        caValidityStartDate.date_courte = Format(aTestDoc.Validity_StartDate, "dd\/mm\/yyyy")
    Else
        caValidityStartDate.date_courte = ""
    End If
    If aTestDoc.Validity_EndDate <> 0 Then
        caValidityEndDate.date_courte = Format(aTestDoc.Validity_EndDate, "dd\/mm\/yyyy")
    Else
        caValidityEndDate.date_courte = ""
    End If
    chk_internet.value = IIf(aTestDoc.Internet_Flag = "X", vbChecked, vbUnchecked)
    txt_spare1.Text = aTestDoc.Spare1
    txt_spare2.Text = aTestDoc.Spare2
End Sub

Public Function ItemMtncAddCtrl_Doc() As Boolean

    If txt_Title.Text = "" Then
        txt_Title.SetFocus
        Call SendFieldErrMsg(966, lbl_Title.Caption, txt_Title)
        Exit Function
    End If
    
    If cbo_Ext.SelectedItem Is Nothing Then
        cbo_Ext.SetFocus
        Call SendFieldErrMsg(966, Lbl_ext.Caption, cbo_Ext)
        Exit Function
    End If


    If cbo_DocumentLanguage.SelectedItem Is Nothing Then
        cbo_DocumentLanguage.SetFocus
        Call SendFieldErrMsg(966, lbl_DocumentLanguage.Caption, cbo_DocumentLanguage)
        Exit Function
    End If


    If txt_File.Text = "" Then
        txt_File.SetFocus
        Call SendFieldErrMsg(966, lbl_Current.Caption, txt_File)
        Exit Function
    End If
    
    
    If cbo_access.SelectedItem Is Nothing Then
        cbo_access.SetFocus
        Call SendFieldErrMsg(966, lb_labels.Caption, cbo_access)
        Exit Function
    End If
    
    
    If (caValidityStartDate.date_dt <> 0 And caValidityEndDate.date_dt <> 0) Then
        If DateDiff("d", caValidityStartDate.date_dt, caValidityEndDate.date_dt) < 1 Then
            caValidityEndDate.SetFocus
            SendMessage 172, "Ending date must be greather than starting date", gut_LangLogin.Code
            Exit Function
        End If
    End If

    Dim lTestDocument As TTestDocument  ' To clear it
    mSelTestDocument = lTestDocument

    With mSelTestDocument
        .FE_Desc = cbo_Ext.SelectedItem.DisplayText
        .FE_Code = cbo_Ext.SelectedItem.Key
        .MD_Language_Code = cbo_DocumentLanguage.SelectedItem.Key
        .MD_Language_Desc = cbo_DocumentLanguage.SelectedItem.DisplayText
        .PT_Title = txt_Title.Text
        .MediaConcurrency = 1
        .Access_type = cbo_access.SelectedItem.Key
        .Access_type_desc = cbo_access.SelectedItem.DisplayText
        .Validity_StartDate = caValidityStartDate.date_dt
        .Validity_EndDate = caValidityEndDate.date_dt
        .Internet_Flag = IIf(chk_internet.value = 1, "X", "")
        .Spare1 = txt_spare1
        .Spare2 = txt_spare2
    End With

    ItemMtncAddCtrl_Doc = True

End Function

Public Function ItemMtncClear_Doc()
    Call ClearForm(UserControl.Controls, fraItemDocumentMtnc)
    drv_Full.Refresh
    dir_Full.Refresh
    fil_Full.Refresh
End Function

Public Sub ItemMtncExit_Doc()
    ' Clear the Add screen To release memory and be sure that no glitch occured
    fraItemDocumentMtnc.Visible = False
    Call ItemMtncClear_Doc
    fraItemDocuments.Visible = True
    fraItemDocuments.ZOrder
End Sub

Public Function ItemLocalAdd_Doc() As Boolean
    With mSelTestDocument
        Call grItemDoc.AddLine(Array(.MD_Code, .Zip_code, .MediaConcurrency, .MD_Language_Desc, .PT_Title, .SRC_Size, .FE_Desc))
    End With
End Function


Public Function ItemDBAdd_Doc() As Boolean
  
    On Error GoTo Err_SaveTestMedia
  
    Const C_MSG As String = "Error while saving association between Test & document. Please contact your IT support."
    Dim lb_TranOpened As Boolean
    Dim lb_BlobCreated As Boolean

  
    Dim lMD_code As String
    If Not GetMaxMDCode(lMD_code) Then Err.Raise mNumber, mSource, mDesc
    
    mSelTestDocument.MD_Code = lMD_code
    
    Dim lPos As Long
    lPos = InStrRev(fil_Full.FileName, ".")
    mSelTestDocument.FileName = Mid(fil_Full.FileName, 1, lPos - 1)
    mSelTestDocument.CPR_Size = -1 'as the file is not localy compressed anymore we cannot get the size
    mSelTestDocument.SRC_Size = FileLen(txt_File.Text) - 1
        
 
    If Not SendToBlob Then
        mNumber = C_ERRORRAISE + 159
        If Err.Number <> 53 Then
            Err.Raise C_ERRORRAISE + 160, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Failed to compress. Test_Media/Zipfile #1"
        Else
            ItemDBAdd_Doc = False
            Exit Function
        End If
    End If
    
    
    lb_BlobCreated = True

    If Not BeginTran("Test_Media") Then Err.Raise C_ERRORRAISE + 159, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & C_MSG
    lb_TranOpened = True
    If Not Insert_Media Then Err.Raise C_ERRORRAISE + 159, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & C_MSG
    If Not Insert_MediaTestLink Then Err.Raise C_ERRORRAISE + 159, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & C_MSG
    If Not Insert_MediaBlobLink(mSelTestDocument.Zip_code, "F", mSelTestDocument.SRC_Size, mSelTestDocument.CPR_Size) Then Err.Raise C_ERRORRAISE + 159, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & C_MSG
    If CommitTran("Test_Media") Then
        lb_TranOpened = False
    Else
        Err.Raise C_ERRORRAISE + 159, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & C_MSG
    End If
    ItemDBAdd_Doc = True
    Exit Function
    
Err_SaveTestMedia:
    If lb_TranOpened Then
        If Not (RollbackTran("Test_Media")) Then
            UploadSQLError mDb, mDbErr, "Test_Media/ssp_save_click/Err_SaveTestMedia # 2"
            mDb.Disconnect
            mDbErr.Disconnect
            End
        End If
    End If
    If lb_BlobCreated Then
        If Not DeleteBlob(mSelTestDocument.Zip_code) Then
            Err.Raise C_ERRORRAISE + 156, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Delete blob failed after problems on links. Test_Media/ssp_save_click/Err_SaveTestMedia"
            UploadSQLError mDb, mDbErr, "Test_Media/ssp_save_click/Err_SaveTestMedia # 1"
        End If
    End If

'    Select Case Err.Number - C_ERRORRAISE
'    Case 155
'        MsgBox "This file is bigger than :" & mZipMaxSize / 1024 & " Ko avec compression and will overload the network. Please select a lower one."
'    Case Else
'        SendMessage 159, "Server may be too busy. Please try again before contacting your IT support.", gut_LangLogin.Code
'    End Select
    mNumber = Err.Number
    mSource = C_SCREENNAME & "/ItemDBAdd_Doc :"
    If Err.Number - C_ERRORRAISE = 155 Then
        mDesc = "This file is bigger than :" & mZipMaxSize / 1024 & " Ko avec compression and will overload the network. Please select a lower one."
    Else
        mDesc = "Server may be too busy. Please try again before contacting your IT support."
    End If
    Err.Raise mNumber, mSource, mDesc
    
End Function



Private Function MaxZipSize() As Boolean
Dim ls_req As String
Dim ll_Cursor As Long

On Error GoTo Err_MaxZipSize

MaxZipSize = False
mZipMaxSize = 0

ls_req = "SELECT DFT_Code FROM Cap_DefaultValue WHERE DFT_ScreenName ='frm_techinfofile' " _
    & " AND DFT_FieldName ='MaxZipSize' AND Language_code ='E' AND CT_code='GB'"

ll_Cursor = mDb.OpenSQL(ls_req, -1, 0)
If ll_Cursor <= 0 Then
    Err.Raise C_ERRORRAISE + 155, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf
End If

mZipMaxSize = Val(mDb.GetFields(ll_Cursor, 0))

MaxZipSize = True
mDb.Close ll_Cursor
Exit Function

Err_MaxZipSize:
    mDb.Close ll_Cursor
    UploadSQLError mDb, mDbErr, "Test_Media/MaxZipSize: " & ls_req
End Function

Private Function GetMaxMDCode(ByRef aMD_code As String) As Boolean
Dim ls_req As String
Dim ll_Cursor As Long, l_Key As Long

On Error GoTo Err_MaxCode

GetMaxMDCode = False
aMD_code = ""

If Not GetNextKey("Media_Test", l_Key) Then
    Err.Raise mNumber, mSource, mDesc
Else
    aMD_code = "T" & Format(l_Key, "0000000")
End If

GetMaxMDCode = True
Exit Function

Err_MaxCode:
    UploadSQLError mDb, mDbErr, mSource & ls_req
    Err.Raise mNumber, mSource, mDesc
End Function


Private Function SendToBlob() As Boolean

On Error GoTo Err_SendToBlob

SendToBlob = False

    Dim lKey As Long
    If Not GetNextKey("Media_Zip", lKey) Then Err.Raise C_ERRORRAISE + 149, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Send to blob for Test_Media failed for Test_Media/sendToBlob"
    mSelTestDocument.Zip_code = lKey
    
    If Send_File(mSelTestDocument.Zip_code, txt_File.Text) Then
        SendToBlob = True
    Else
        Err.Raise C_ERRORRAISE + 149, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Send to blob for Test_Media failed for Test_Media/sendToBlob"
    End If

    Exit Function

Err_SendToBlob:
    UploadSQLError mDb, mDbErr, "Test_Media/SendToBlob "
    Err.Raise C_ERRORRAISE + 149, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Send to blob for Test_Media failed for Test_Media/sendToBlob"
End Function



Private Function Send_File(ByVal as_ZipCode As String, ByVal as_file As String) As Boolean   'ByVal as_TypeOfView, ByVal as_DirZip As String, ByVal as_FileZipped As String, ByVal as_Extension As String) As Boolean
    Dim ll_try     As Byte

On Error GoTo Err_SendFile
Send_File = False
  
'ALLOWS SOME RETRY IN CASE THERE IS COMS ISSUES TAHT AN BE RECOVERED BY A RETRY
For ll_try = 1 To 3
    If mDb.FileToBlobSQL("exec Media_Zip_ins '" & as_ZipCode & "',?", as_file, 9, mZipMaxSize) Then
        Send_File = True
        Exit For
    End If
Next

Exit Function
    
Err_SendFile:
    UploadSQLError mDb, mDbErr, "Send_File: FileToBlobSQL Error"
End Function


Private Function RollbackTran(as_Tran As String) As Boolean

On Error GoTo Err_RollBackTran

RollbackTran = False

If Not mDb.ExecuteSQL("ROLLBACK TRANSACTION " & as_Tran) Then
    Err.Raise C_ERRORRAISE + 153, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "RollBack transaction failed for Test_Media/CommitTran"
End If

RollbackTran = True
Exit Function

Err_RollBackTran:
    UploadSQLError mDb, mDbErr, "Test_Media/RollbackTran "
    Err.Raise C_ERRORRAISE + 153, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "RollBack transaction failed for Test_Media/CommitTran"
End Function

Private Function CommitTran(as_Tran As String) As Boolean

On Error GoTo Err_CommitTran
CommitTran = False

If Not mDb.ExecuteSQL("COMMIT TRANSACTION " & as_Tran) Then
    Err.Raise C_ERRORRAISE + 152, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Commit transaction failed for Test_Media/CommitTran"
End If

CommitTran = True
Exit Function

Err_CommitTran:
    UploadSQLError mDb, mDbErr, "Test_Media/CommitTran"
    Err.Raise C_ERRORRAISE + 152, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Commit transaction failed for Test_Media/CommitTran"
End Function

Private Function BeginTran(as_Tran As String) As Boolean
Dim ls_req As String

On Error GoTo Err_BeginTran
BeginTran = False

ls_req = "BEGIN TRANSACTION " & as_Tran
If Not mDb.ExecuteSQL(ls_req) Then
    Err.Raise C_ERRORRAISE + 151, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Begin transaction failed for Test_Media/BeginTran"
End If

BeginTran = True
Exit Function

Err_BeginTran:
    UploadSQLError mDb, mDbErr, "Test_Media/BeginTran: " & ls_req
    Err.Raise C_ERRORRAISE + 151, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Begin transaction failed for Test_Media/BeginTran"
End Function



' Give the nextkey of an DB table
' NOTICE : MUSTN'T BE CALLED INTO A ACID TRANSACTION BECAUSE DISPLAY ERROR MESSAGE !
Private Function GetNextKey(ByVal as_TableName, ByRef al_Key As Long, Optional ByVal al_TryCount As Integer = 5) As Boolean

On Error GoTo onError
    
Dim ls_Request As String

ls_Request = "SELECT Table_Key FROM SYS_TablesKeys WHERE Table_Name = '" & as_TableName & "'"

' STEP 1 - Read the current key
Dim lc_Cursor As Long, ll_CurrentKey As Long, ll_NewKey As Long
lc_Cursor = mDb.OpenSQL(ls_Request)
If mDb.RowCount(lc_Cursor) = 0 Then
    Err.Raise C_ERRORRAISE + 158, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Error in Test_Media, GetNextKey, #1"
End If

' STEP 2 - Calculate the new
ll_CurrentKey = mDb.GetFields(lc_Cursor, 0)
mDb.Close (lc_Cursor)
ll_NewKey = ll_CurrentKey + 1
    
    
' STEP 3 - Try to register the new key
ls_Request = "UPDATE SYS_TablesKeys SET Table_Key = " & ll_NewKey & vbCrLf & _
            "WHERE Table_Name = '" & as_TableName & "' AND Table_Key = " & ll_CurrentKey

If Not mDb.ExecuteSQL(ls_Request) Then
    Err.Raise C_ERRORRAISE + 158, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Error in Test_Media, GetNextKey, #2"
End If

If mDb.SQLRowsAffected = 1 Then
    ' That's all folks !
    al_Key = ll_NewKey
    GetNextKey = True
Else
    ' No luck, try again !
    If al_TryCount = 0 Then ' Too much tries, server should busy...
        GetNextKey = False
    Else
        GetNextKey = GetNextKey(as_TableName, al_Key, al_TryCount - 1)
    End If
End If

Exit Function

onError:
    mDb.Close (lc_Cursor)
    UploadSQLError mDb, mDbErr, "Test_Media/GetNextKey: " & ls_Request
    
    GetNextKey = False
    
    Err.Raise C_ERRORRAISE + 158, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Error in Test_Media, GetNextKey"
End Function



Private Function Insert_Media() As Boolean

Dim ls_req As String
Const INS_REQ As String = "EXEC Media_ins4 '$MD_Code$','$FE_Code$','$FILE$','$PT_Title$', '$LANG_CODE$', '$ACCES_TYPE$', $VALSTARTDATE$, $VALENDDATE$, '$INTFLAG$', '$SPARE1$', '$SPARE2$'"
On Error GoTo Err_Insert_Media

Insert_Media = KO
ls_req = Replace(INS_REQ, "$MD_Code$", mSelTestDocument.MD_Code)
ls_req = Replace(ls_req, "$FE_Code$", QuoteParam(mSelTestDocument.FE_Code))
ls_req = Replace(ls_req, "$FILE$", QuoteParam(txt_File.Text))
ls_req = Replace(ls_req, "$PT_Title$", QuoteParam(mSelTestDocument.PT_Title))
ls_req = Replace(ls_req, "$LANG_CODE$", mSelTestDocument.MD_Language_Code)
ls_req = Replace(ls_req, "$ACCES_TYPE$", mSelTestDocument.Access_type)
ls_req = Replace(ls_req, "$VALSTARTDATE$", SQLDateTime(mSelTestDocument.Validity_StartDate))
ls_req = Replace(ls_req, "$VALENDDATE$", SQLDateTime(mSelTestDocument.Validity_EndDate))
ls_req = Replace(ls_req, "$INTFLAG$", mSelTestDocument.Internet_Flag)
ls_req = Replace(ls_req, "$SPARE1$", QuoteParam(mSelTestDocument.Spare1))
ls_req = Replace(ls_req, "$SPARE2$", QuoteParam(mSelTestDocument.Spare2))

If Not mDb.ExecuteSQL(ls_req) Then
    Err.Raise C_ERRORRAISE + 148, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Insert in table Media failed"
End If

Insert_Media = True
Exit Function

Err_Insert_Media:
    UploadSQLError mDb, mDbErr, "Test_Media/Insert_Media: " & ls_req
    Err.Raise C_ERRORRAISE + 148, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Insert in table Media failed"
End Function

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:

End Function


Private Function Insert_MediaTestLink() As Boolean
Dim ls_req As String

On Error GoTo Err_Insert_MediaTestLink

Insert_MediaTestLink = KO

ls_req = "EXEC Test_Medialink_ins " & mSelectedTest.TestCode & ",'" & mSelTestDocument.MD_Code & "'"
If Not mDb.ExecuteSQL(ls_req) Then
    Err.Raise C_ERRORRAISE + 150, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Insert_MediaTestLink"
End If

Insert_MediaTestLink = True
Exit Function

Err_Insert_MediaTestLink:
    UploadSQLError mDb, mDbErr, "Test_Media/Insert_MediaTestLink: " & ls_req
    Err.Raise C_ERRORRAISE + 150, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Insert_MediaTestLink"
End Function


Private Function Insert_MediaBlobLink(ByVal aZipCode As Integer, ByVal AType As String, ByVal asource As Long, ByVal aZipped As Long) As Boolean
Dim ls_req As String

On Error GoTo Err_Insert_MediaBlobLink

Insert_MediaBlobLink = KO

ls_req = "EXEC Media_BlobLink_ins '" & mSelTestDocument.MD_Code & "'," & aZipCode & ",'" & AType & "'," & asource & "," & aZipped
If Not mDb.ExecuteSQL(ls_req) Then
    Err.Raise C_ERRORRAISE + 150, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Insert_MediaBlobLink"
End If

Insert_MediaBlobLink = True
Exit Function

Err_Insert_MediaBlobLink:
    UploadSQLError mDb, mDbErr, "Test_Media/Insert_MediaBlobLink: " & ls_req
    Err.Raise C_ERRORRAISE + 150, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Insert_MediaBlobLink"
End Function



Private Function DeleteBlob(ByVal aZipCode As Integer) As Boolean
Dim ls_req As String

On Error GoTo Err_DeleteBlob

DeleteBlob = False

ls_req = "EXEC Media_Zip_del '" & aZipCode & "'"

If Not mDb.ExecuteSQL(ls_req) Then
    mNumber = C_ERRORRAISE + 156
    mSource = C_SCREENNAME & "/DeleteBlob :"
    mDesc = "Unable to delete Blob"
    Err.Raise mNumber, mSource, mDesc
End If


If mDb.SQLRowsAffected <= 0 Then
    Err.Raise mNumber, mSource, mDesc
End If

DeleteBlob = True
Exit Function

Err_DeleteBlob:
    UploadSQLError mDb, mDbErr, mSource & ls_req
    Err.Raise mNumber, mSource, mDesc
End Function


Private Sub ItemMtncDel_Doc()
    
On Error GoTo Err_ItemMtncDel_Doc
    
    Dim lKey As Variant
    lKey = grItemDoc.CurrentKey
    
    If IsEmpty(lKey) Then
        ' TODO : select an item
        Exit Sub
    End If
    
    Dim lTestDocument As TTestDocument
    mSelTestDocument = lTestDocument
    mSelTestDocument.MD_Code = lKey(0)
    mSelTestDocument.Zip_code = lKey(1)
    mSelTestDocument.MediaConcurrency = lKey(2)
    
   
    If Not ItemMtncDelCtrl_Doc Then Exit Sub
    
    ' STEP 2 - Del the data to the database
    If Not ItemDBDel_Doc Then
        Err.Raise mNumber, mSource, mDesc
    End If
    
    'STEP 3 - Update local data
     ItemLocalDel_Doc
    Exit Sub
   
Err_ItemMtncDel_Doc:
    Err.Raise mNumber, mSource, mDesc
End Sub

Private Function ItemMtncDelCtrl_Doc() As Boolean
    
    ItemMtncDelCtrl_Doc = False
    
    Dim lUserConfirm As Boolean
    lUserConfirm = SendMessage(5, "Delete record ?", gut_LangLogin.Code, vbQuestion + vbYesNo, "Delete ") = vbYes
    
    If Not lUserConfirm Then Exit Function
    
    ' TODO : Check here if we can really delete the item because of linked entity
    
    ItemMtncDelCtrl_Doc = True
    
End Function


Private Function ItemDBDel_Doc() As Boolean

On Error GoTo Err_ItemDBDel_Doc
    ItemDBDel_Doc = False
    
    If Not Delete_Media Then
        Err.Raise mNumber, mSource, mDesc
    End If
    
    If Not DeleteBlob(mSelTestDocument.Zip_code) Then
        Err.Raise mNumber, mSource, mDesc
    End If
    
    ItemDBDel_Doc = True
    Exit Function
    
Err_ItemDBDel_Doc:
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function ItemDBFill_Doc(ByRef as_testDoc As TTestDocument) As Boolean
On Error GoTo ErrorHandler
    ItemDBFill_Doc = False
    Dim ll_Cursor As Long
    Dim ls_req As String
    
    'Media_Title_Sel4
    ls_req = "EXEC Media_Sel4 '" & mSelTestDocument.MD_Code & "','" & mLanguage_Code & "'"
    ll_Cursor = mDb.OpenSQL(ls_req)
    If ll_Cursor = 0 Then
        mNumber = C_ERRORRAISE + 159
        mSource = C_SCREENNAME & "/Update_Media_Doc :"
        mDesc = "Unable to select test"
        Err.Raise mNumber, mSource, mDesc
    End If
    
    If mDb.First(ll_Cursor) Then
        mSelTestDocument.FE_Code = mDb.GetFields(ll_Cursor, "FE_code")
        mSelTestDocument.FE_Desc = mDb.GetFields(ll_Cursor, "FE_Desc")
        mSelTestDocument.FileName = mDb.GetFields(ll_Cursor, "MD_SourceFile")
        mSelTestDocument.MD_Language_Code = mDb.GetFields(ll_Cursor, "MD_Language_Code")
        mSelTestDocument.MD_Language_Desc = mDb.GetFields(ll_Cursor, "Language_desc")
        mSelTestDocument.PT_Title = mDb.GetFields(ll_Cursor, "PT_title")
        mSelTestDocument.Access_type = mDb.GetFields(ll_Cursor, "Access_type")
        mSelTestDocument.Access_type_desc = mDb.GetFields(ll_Cursor, "Access_type_desc")
        
        mSelTestDocument.Validity_StartDate = GetDate(mDb.GetFields(ll_Cursor, "Validity_StartDate"))
        mSelTestDocument.Validity_EndDate = GetDate(mDb.GetFields(ll_Cursor, "Validity_EndDate"))
        mSelTestDocument.Internet_Flag = mDb.GetFields(ll_Cursor, "internet_flag")
        mSelTestDocument.Spare1 = mDb.GetFields(ll_Cursor, "Spare1")
        mSelTestDocument.Spare2 = mDb.GetFields(ll_Cursor, "Spare2")
    Else
        mNumber = C_ERRORRAISE + 159
        mSource = C_SCREENNAME & "/Update_Media_Doc :"
        mDesc = "Unable to select test"
        Err.Raise mNumber, mSource, mDesc
    End If
    
    ItemDBFill_Doc = True
    Exit Function
    
ErrorHandler:
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function GetDate(ByVal av_Date As Variant) As Date
    If av_Date <> "" Then
        GetDate = av_Date
    Else
        GetDate = 0
    End If
End Function
Private Function Delete_Media() As Boolean
Dim ls_req As String

On Error GoTo Err_DltMedia

Delete_Media = False

ls_req = "EXEC Test_Media_del '" & mSelTestDocument.MD_Code & "', " & mSelTestDocument.MediaConcurrency
If Not mDb.ExecuteSQL(ls_req) Then
    mNumber = C_ERRORRAISE + 159
    mSource = C_SCREENNAME & "/Delete_Media :"
    mDesc = "Unable to delete test & links"
    Err.Raise mNumber, mSource, mDesc
End If

Delete_Media = True
Exit Function

Err_DltMedia:
    UploadSQLError mDb, mDbErr, mSource & ls_req
    Err.Raise mNumber, mSource, mDesc
End Function

Private Sub ItemLocalDel_Doc()
    With mSelTestDocument
        Call grItemDoc.DeleteLine(Array(.MD_Code, .Zip_code, .MediaConcurrency))
    End With
End Sub

Private Sub ItemMtncUpd_Gen()
    
    mTestAction = etaUpdate
    mTestActionType = mSelectedTest.Type
    lst_On_What2.Visible = False
    fraItemGeneral.Visible = False
    tabCmd.Enabled = False
    
    ' Create the data if needed
    Call EnableFrame(UserControl.Controls, fraItemGeneral, True)
    Call ItemMtncInit_Gen
    'Call Item_LoadViewGeneral(mSelectedTest.ViewGeneral)

    'fraIItemGeneralMarkets.Visible = False
    'cmd_Memo.Visible = False
    
    tcItem.DisplayFace (C_TOOLBARFACE_ITEM_UPD)
    fraItemGeneral.Visible = True
    fraItemGeneral.ZOrder
    cbo_ivgCategory.SetFocus

End Sub


Private Sub Item_Upd()
    
On Error GoTo Err_Item_Upd

    Select Case mSelectedView
        Case eTestViews.etvGeneral
            Call ItemUpd_Gen
        Case eTestViews.etvDocuments
            Call ItemUpd_Doc
    End Select
    Exit Sub

Err_Item_Upd:
    Err.Raise mNumber, mSource, mDesc
End Sub

Private Sub ItemUpd_Doc()
On Error GoTo ErrorHandler
    
    ' STEP 1 - Check the validity of the form
    If Not ItemMtncAddCtrl_Doc Then
       Exit Sub
    End If
    
    Dim lKey As Variant
    lKey = grItemDoc.CurrentKey
    
    If IsEmpty(lKey) Then
        ' TODO : select an item
        Exit Sub
    End If
    
    mSelTestDocument.MD_Code = lKey(0)
    mSelTestDocument.Zip_code = lKey(1)
    mSelTestDocument.MediaConcurrency = lKey(2)


    If Not ItemDBUpd_Doc Then
       If Err.Number <> 53 Then
           Err.Raise mNumber, mSource, mDesc
       Else
           Exit Sub
       End If
    End If
    
    'STEP 3 - Update local data
    Call ItemLocalUpd_Doc(mSelTestDocument)
    
    Call Item_MtncExit
    Exit Sub
    
    Exit Sub
ErrorHandler:
    Err.Raise mNumber, mSource, mDesc
End Sub


Public Function ItemDBUpd_Doc() As Boolean
  
    On Error GoTo ErrorHandler
  
    Const C_DB_REQUEST As String = "EXEC Media_upd4 '$MD_Code$', $iConc$, '$FE_Code$','$FILE$','$PT_Title$', '$LANG_CODE$', '$ACCES_TYPE$', $VALSTARTDATE$, $VALENDDATE$, '$INTFLAG$', '$SPARE1$', '$SPARE2$'"
    On Error GoTo ErrorHandler
    Dim ls_req As String
    
    ItemDBUpd_Doc = KO
    ls_req = Replace(C_DB_REQUEST, "$MD_Code$", mSelTestDocument.MD_Code)
    ls_req = Replace(ls_req, "$iConc$", mSelTestDocument.MediaConcurrency)
    ls_req = Replace(ls_req, "$FE_Code$", QuoteParam(mSelTestDocument.FE_Code))
    ls_req = Replace(ls_req, "$FILE$", QuoteParam(txt_File.Text))
    ls_req = Replace(ls_req, "$PT_Title$", QuoteParam(mSelTestDocument.PT_Title))
    ls_req = Replace(ls_req, "$LANG_CODE$", mSelTestDocument.MD_Language_Code)
    ls_req = Replace(ls_req, "$ACCES_TYPE$", mSelTestDocument.Access_type)
    ls_req = Replace(ls_req, "$VALSTARTDATE$", SQLDateTime(mSelTestDocument.Validity_StartDate))
    ls_req = Replace(ls_req, "$VALENDDATE$", SQLDateTime(mSelTestDocument.Validity_EndDate))
    ls_req = Replace(ls_req, "$INTFLAG$", mSelTestDocument.Internet_Flag)
    ls_req = Replace(ls_req, "$SPARE1$", QuoteParam(mSelTestDocument.Spare1))
    ls_req = Replace(ls_req, "$SPARE2$", QuoteParam(mSelTestDocument.Spare2))
    
    If Not mDb.ExecuteSQL(ls_req) Then
        Err.Raise C_ERRORRAISE + 148, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & "Update in table Media_Title failed"
    End If

    If mDb.SQLRowsAffected = 0 Then
        Err.Raise mNumber, mSource, mDesc
    End If
    
    acvMarkets.Calling_Key_Values = mSelectedTest.TestCode & "®©" & cbo_ivgCategory.SelectedItem.Key
    If Not acvMarkets.SaveList Then
        ' TODO Manage error
    End If

    ' Don't need the list for saving, i hope
    acvCountries.Calling_Key_Values = mSelectedTest.TestCode & "®©" & "null"
    If Not acvCountries.SaveList Then
        ' TODO Manage error
    End If
    
    
    ItemDBUpd_Doc = True
    mSelTestDocument.MediaConcurrency = mSelTestDocument.MediaConcurrency + 1
    Exit Function
    
ErrorHandler:
    UploadSQLError mDb, mDbErr, mSource & ls_req
    Err.Raise mNumber, mSource, mDesc
End Function




Private Sub ItemUpd_Gen()
    
On Error GoTo Err_ItemUpd_Gen
    
    ' STEP 1 - Check the validity of the form
    If Not ItemMtncAddCtrl_Gen Then
        Exit Sub
    End If
    
     If Not ItemDBUpd_Gen Then
        Err.Raise mNumber, mSource, mDesc
     End If
     
     Call LogActivty(mDb, mU_Code, ebfUpdateAProductTest)
     
     'STEP 3 - Update local data
     ItemLocalUpd_Gen (mSelectedTest.TestCode)
     
     Call Item_MtncExit
    Exit Sub

Err_ItemUpd_Gen:
    Err.Raise mNumber, mSource, mDesc
End Sub


Private Function ItemDBUpd_Gen() As Boolean
    
On Error GoTo Err_ItemDBUpd_Gen
    ItemDBUpd_Gen = False
    
    Const C_DB_REQUEST As String = "Exec Test_upd $test_code$, $Iconcurrency$, $std_code$, $tmng_code$, '$full_test_number$', $tho_code$, '$so_code$', '$start_date$','$end_date$', '$old_date$', '$indicative$', '$old_flag$', '$published$', '$internet$', '$drop$', '$drop_date$'"

    Dim lRequest As String
    
    lRequest = ReplaceHolders(C_DB_REQUEST)
    lRequest = Replace(lRequest, "$Iconcurrency$", mSelectedTest.ViewGeneral.iConcurrency)
    lRequest = Replace(lRequest, "$std_code$", cbo_ivgStandard.SelectedItem.Key)
    lRequest = Replace(lRequest, "$tmng_code$", cbo_ivgTestManager.SelectedItem.Key)
    lRequest = Replace(lRequest, "$tho_code$", cbo_ivgTestHouse.SelectedItem.Key)
    lRequest = Replace(lRequest, "$so_code$", cbo_ivgSalesOffice.SelectedItem.Key)
    lRequest = Replace(lRequest, "$start_date$", caStartDate.date_us)
    lRequest = Replace(lRequest, "$end_date$", caEndDate.date_us)
    lRequest = Replace(lRequest, "$old_date$", caOldDate.date_us)
    lRequest = Replace(lRequest, "$full_test_number$", Replace(txt_FullTestNumber.Text, "'", "''", , , vbTextCompare))
    lRequest = Replace(lRequest, "$indicative$", Replace(txt_IndicTestNumber.Text, "'", "''", , , vbTextCompare))
    
    ' TODO : check if the following flags are correct
    lRequest = Replace(lRequest, "$old_flag$", IIf(caOldDate.date_us = "", "", "X"))
    lRequest = Replace(lRequest, "$published$", "")
    
    lRequest = Replace(lRequest, "$internet$", IIf(chk_Int.value = 1, "X", ""))
    lRequest = Replace(lRequest, "$drop$", IIf(caDropDate.date_us = "", "", "X"))
    lRequest = Replace(lRequest, "$drop_date$", caDropDate.date_us)

    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 195
        mSource = C_SCREENNAME & "/ItemDBUpd_Gen :"
        mDesc = "Unable to save the test"
        Err.Raise mNumber, mSource, mDesc
    End If

    If mDb.SQLRowsAffected = 0 Then
        Err.Raise mNumber, mSource, mDesc
    End If
    
    acvMarkets.Calling_Key_Values = mSelectedTest.TestCode & "®©" & cbo_ivgCategory.SelectedItem.Key
    If Not acvMarkets.SaveList Then
        ' TODO Manage error
    End If

    ' Don't need the list for saving, i hope
    acvCountries.Calling_Key_Values = mSelectedTest.TestCode & "®©" & "null"
    If Not acvCountries.SaveList Then
        ' TODO Manage error
    End If
    
    
    ItemDBUpd_Gen = True
    mSelectedTest.ViewGeneral.iConcurrency = mSelectedTest.ViewGeneral.iConcurrency + 1
    Exit Function
    
Err_ItemDBUpd_Gen:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function


Private Sub ItemMtncDel_Gen()
    
    mTestAction = etaDelete
    mTestActionType = mSelectedTest.Type
    lst_On_What2.Visible = False
    fraItemGeneral.Visible = False
    tabCmd.Enabled = False
    
    ' Create the data if needed
    Call EnableFrame(UserControl.Controls, fraItemGeneral, False)
    Call ItemMtncInit_Gen
    'Call Item_LoadViewGeneral(mSelectedTest.ViewGeneral)

    'fraIItemGeneralMarkets.Visible = False
    'cmd_Memo.Visible = False
    
    tcItem.DisplayFace (C_TOOLBARFACE_ITEM_DEL)
    fraItemGeneral.Visible = True
    fraItemGeneral.ZOrder

End Sub


Private Function ItemMtncDelCtrl_Gen() As Boolean
    
    Const C_DB_REQUEST As String = "Exec Test_Dependancies '$lang$', $test_code$"
    Const C_MSG As String = ""
    ItemMtncDelCtrl_Gen = False
    
    ' Check if we can really delete the item because of linked entity, like an opinion...
    Dim lRequest As String
    lRequest = ReplaceHolders(C_DB_REQUEST)
    Dim lDepends As Long
    lDepends = mDb.OpenSQL(lRequest)
    If mDb.RowCount(lDepends) Then
        ' Some dependancies are founded, user cannot delete this item
        Dim lBuffer As String, lMsg As String
        Dim lIdx As Long, lCount As Long
        lCount = mDb.RowCount(lDepends) - 1
        For lIdx = 0 To lCount
            lBuffer = lBuffer & vbCrLf & mDb.GetFieldsAt(lDepends, lIdx, "TT_Desc") & ", " & mDb.GetFieldsAt(lDepends, lIdx, "FULL_TEST_NUMBER")
        Next
        lMsg = MsgText(970, mLanguage_Code)
        If lMsg = "" Then lMsg = "#You cannot delete this test before delete the following test: "
        Call MsgBox(lMsg & lBuffer, vbCritical)
        Exit Function
    End If
    
    
    
    Dim lUserConfirm As Boolean
    lUserConfirm = SendMessage(5, "Delete record ?", gut_LangLogin.Code, vbQuestion + vbYesNo, "Delete ") = vbYes
    
    If Not lUserConfirm Then Exit Function
    
    ItemMtncDelCtrl_Gen = True
    
End Function


Private Sub ItemDel_Gen()
    
On Error GoTo Err_ItemDel_Gen
    
    ' STEP 1 - Check if it's possible to delete
    If Not ItemMtncDelCtrl_Gen Then
        Exit Sub
    End If
    
    ' STEP 2 - Del the data to the database
    If Not ItemDBDel_Gen Then
        Err.Raise mNumber, mSource, mDesc
    End If
    
    Call LogActivty(mDb, mU_Code, ebfDeleteAProductTest)
    
    'STEP 3 - Update local data
     ItemLocalDel_Gen
     
     ' Make the cleaning..
     mSelectedTestCnd.Valid = False
     
     'Call Item_MtncExit
     SetMode (etmList)
     Exit Sub
     
Err_ItemDel_Gen:
    Err.Raise mNumber, mSource, mDesc
End Sub



Private Sub ItemLocalDel_Gen()
    If Not grList.DeleteLine(Array(mSelectedTest.TestCode, "E")) Then
        ' Error ?
    End If
    
    'TVTest.Refresh
End Sub


Private Function GetTestMemoCount() As Long
    Const C_REQUEST = "exec Test_Memo_Count $test_code$"
    Dim lRequest As String
    lRequest = ReplaceHolders(C_REQUEST)
    Dim lData As Long
    lData = mDb.OpenSQL(lRequest)
    Dim lMemoCount As Long
    lMemoCount = mDb.GetFields(lData, 0)
    mDb.Close (lData)
    GetTestMemoCount = lMemoCount
End Function




Private Sub InitCtrlSize()

    Const C_FRAME_HSPACE As Long = 120
    Const C_FRAME_VSPACE As Long = 120
    
    Const C_FRAME_FILTERS_WIDTH As Long = 4500
    
    Dim lFrameMaxHeight As Long, lBuffer As Long
    lFrameMaxHeight = UserControl.Height - (2 * C_FRAME_VSPACE)
    
    ' the filters frame
    Call fraFilters.Move(C_FRAME_HSPACE, C_FRAME_VSPACE, C_FRAME_FILTERS_WIDTH, lFrameMaxHeight)
    Call cbo_Views.Move(C_FRAME_HSPACE, 2400, C_FRAME_FILTERS_WIDTH - (2 * C_FRAME_HSPACE), 345)
    lBuffer = 2760
    Call TVTest.Move(C_FRAME_HSPACE, lBuffer, C_FRAME_FILTERS_WIDTH - (2 * C_FRAME_HSPACE), lFrameMaxHeight - lBuffer - C_FRAME_VSPACE)
    
    ' the list frame
    Dim lfraItem_Width As Long
    lfraItem_Width = UserControl.Width - C_FRAME_FILTERS_WIDTH - (C_FRAME_HSPACE * 4)
    Call fraList.Move(fraFilters.Left + fraFilters.Width + C_FRAME_HSPACE, C_FRAME_VSPACE, lfraItem_Width, lFrameMaxHeight)
    lBuffer = 1000
    Call grList.Move(C_FRAME_HSPACE, lBuffer, lfraItem_Width - (2 * C_FRAME_HSPACE), lFrameMaxHeight - lBuffer - C_FRAME_HSPACE)
    
    ' The item frame, same as List
    Call fraItem.Move(fraList.Left, fraList.Top, fraList.Width, fraList.Height)
    
    ' The sub frames and the controls
    
    Dim lItemFrameTop As Long, lItemFrameMaxHeight As Long, lItemFrameWidth As Long
    lItemFrameTop = 1000
    lItemFrameMaxHeight = fraList.Height - lItemFrameTop - (1 * C_FRAME_VSPACE)
    lItemFrameWidth = lfraItem_Width - (3 * C_FRAME_HSPACE) - tcItem.Width
    
    Call tcItem.Move(fraItem.Width - tcItem.Width - C_FRAME_HSPACE, lItemFrameTop, tcItem.Width, tcItem.Height)
    lst_On_What.Left = tcItem.Left - lst_On_What.Width
    lst_on_what4.Left = tcItem.Left - lst_on_what4.Width
    lst_On_What2.Left = tcItem.Left - lst_On_What2.Width
    lst_on_what5.Left = tcItem.Left - lst_on_what5.Width
    
    lBuffer = tabCmd.Left + tabCmd.Width + C_FRAME_HSPACE
    Call fraItemFullNumber.Move(tabCmd.Left + tabCmd.Width + C_FRAME_HSPACE, C_FRAME_VSPACE, fraItem.Width - lBuffer - C_FRAME_HSPACE, fraItemFullNumber.Height)
    txt_ItemFullNumber.Width = fraItemFullNumber.Width - C_FRAME_HSPACE - txt_ItemFullNumber.Left
    
    ' View General
    Call fraItemGeneral.Move(C_FRAME_HSPACE, lItemFrameTop, lItemFrameWidth, lItemFrameMaxHeight)
    
    ' Reminder
    Call fraItemReminder.Move(C_FRAME_HSPACE, lItemFrameTop, lItemFrameWidth, 2655)
    
    lItemFrameMaxHeight = lItemFrameMaxHeight - fraItemReminder.Height
    lItemFrameTop = lItemFrameTop + fraItemReminder.Height
    
    ' View condition
    Call fraItemConditions.Move(C_FRAME_HSPACE, lItemFrameTop, lItemFrameWidth, lItemFrameMaxHeight)
    Call fraItemConditionsMtnc.Move(C_FRAME_HSPACE, lItemFrameTop, lItemFrameWidth, lItemFrameMaxHeight)
    Call grItemCnd.Move(C_FRAME_HSPACE, C_FRAME_HSPACE * 2, fraItemConditions.Width - (C_FRAME_HSPACE * 2), fraItemConditions.Height - (C_FRAME_VSPACE * 3))
    
    ' View Results
    Call fraItemResults.Move(C_FRAME_HSPACE, lItemFrameTop, lItemFrameWidth, lItemFrameMaxHeight)
    
    ' View products
    Call fraItemProducts.Move(C_FRAME_HSPACE, lItemFrameTop, lItemFrameWidth, lItemFrameMaxHeight)
    Call fraProductsType.Move(C_FRAME_HSPACE, C_FRAME_VSPACE, fraItemProducts.Width - (C_FRAME_HSPACE * 2), fraProductsType.Height)
    Call grItemProd.Move(C_FRAME_HSPACE, 960, fraItemProducts.Width - (C_FRAME_HSPACE * 2), fraItemProducts.Height - (C_FRAME_VSPACE) - 960)
    
    ' View Document
    Call fraItemDocuments.Move(C_FRAME_HSPACE, lItemFrameTop, lItemFrameWidth, lItemFrameMaxHeight)
    Call fraItemDocumentMtnc.Move(C_FRAME_HSPACE, lItemFrameTop, lItemFrameWidth, lItemFrameMaxHeight)
    Call grItemDoc.Move(C_FRAME_HSPACE, C_FRAME_HSPACE * 2, fraItemDocuments.Width - (C_FRAME_HSPACE * 2), fraItemDocuments.Height - (C_FRAME_VSPACE * 3))
    
    ' View Tree
    Call fraItemTree.Move(C_FRAME_HSPACE, lItemFrameTop, lItemFrameWidth, lItemFrameMaxHeight)
    
    ' The item sel component
    
    
End Sub


Private Function ItemLocalAdd_Gen(ByVal aTestCode As Long) As Boolean
   
    'If SendMessage(666, "Would you like to jump to the new item ?", mLanguage_Code, vbYesNo) = vbYes Then
    mSelectedTest = GetItemInfoFromForm(aTestCode)
    Dim lPath As String
    lPath = GetCurrentPath(UserControl.Controls, fraItemGeneral, cbo_Views.SelectedItem.GetData(2))
    If Not FindInTreeView(lPath) Then
        ' ERROR
    End If
    If Not grList.SearchKey(True, Array(aTestCode, "E")) Then
        ' ERROR
    End If
    
    'Call Item_LoadReminderFromViewGen
    
    ItemLocalAdd_Gen = True
    'End If
    
End Function


Private Function FindInTreeView(ByVal aPath As String) As Boolean
    Dim lValues As Variant
    lValues = Split(aPath, CH_LDELIMIT)

    Dim lIdx As Long, lCount As Long, lFoundedCount As Long
    lCount = UBound(lValues)

    If Not TVTest.Find(lValues(0), 0, , 0) Then
        FindInTreeView = False
        Exit Function
    End If
    lFoundedCount = 1
    Call TVTest.ExpandNode(TVTest.SelectedItem)

    For lIdx = 1 To lCount
        If Not TVTest.Find(lValues(lIdx), 0, TVTest.SelectedItem, lIdx) Then
            Exit For
        End If
        Call TVTest.ExpandNode(TVTest.SelectedItem)
        lFoundedCount = lFoundedCount + 1
    Next

    If TVTest.Checkboxes = True Then LoadCurrentTVSelection

    FindInTreeView = (lFoundedCount = (lCount + 1))

End Function



Private Sub ItemMtncDel_Prd()

On Error GoTo Err_ItemMtncDel_Prd

    'Dim lKey As Variant
    If grItemProd.SelectedCount = 0 Then Exit Sub
    
    Dim lTLPCode As Long, liConcurrency As Long
    lTLPCode = grItemProd.CurrentKey(0)
    liConcurrency = grItemProd.CurrentKey(1)
    
    If Not ItemMtncDelCtrl_Prod(lTLPCode) Then Exit Sub
    
    ' STEP 2 - Del the data to the database
    If Not ItemDBDel_Prod(lTLPCode, liConcurrency) Then
        Err.Raise mNumber, mSource, mDesc
    End If
    
    'STEP 3 - Update local data
     ItemLocalDel_Prod
     Exit Sub
     
Err_ItemMtncDel_Prd:
    Err.Raise mNumber, mSource, mDesc
End Sub


Private Function ItemMtncDelCtrl_Prod(ByVal aTLPCode As Long) As Boolean
    
    ItemMtncDelCtrl_Prod = False
    
    Dim lUserConfirm As Boolean
    lUserConfirm = SendMessage(5, "Delete record ?", gut_LangLogin.Code, vbQuestion + vbYesNo, "Delete ") = vbYes
    
    If Not lUserConfirm Then Exit Function
    
    ' TODO : Check here if we can really delete the item because of linked entity
    
    ItemMtncDelCtrl_Prod = True
    
End Function


Private Function ItemDBDel_Prod(ByVal aTLPCode As Long, ByVal AiConc As Long) As Boolean

On Error GoTo Err_ItemDBDel_Prod

    Const C_DB_REQUEST As String = "Test_Link_Products_del $tlp_code$, $iconc$"
    
    ItemDBDel_Prod = False
    
    Dim lRequest As String
    lRequest = Replace(C_DB_REQUEST, "$tlp_code$", aTLPCode, , , vbTextCompare)
    lRequest = Replace(lRequest, "$iconc$", AiConc, , , vbTextCompare)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 199
        mSource = C_SCREENNAME & "/ItemDBDel_Prod :"
        mDesc = "Unable to save the test"
        Err.Raise mNumber, mSource, mDesc
    End If
    If mDb.SQLRowsAffected = 0 Then
        Err.Raise mNumber, mSource, mDesc
    End If
    
    ItemDBDel_Prod = True
    Exit Function
    
Err_ItemDBDel_Prod:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function



Private Sub ItemMtncAdd_Prod()

    lst_on_what4.Visible = False
    Select Case lst_on_what4.ListIndex
        Case eTestProductLink.etplCriteria
            Call ItemMtncAdd_ProdCriteria
        Case eTestProductLink.etplItem
            Call ItemMtncAdd_ProdProduct
    End Select

End Sub



Private Sub ItemMtncAdd_ProdProduct()

    If Not ItemSel.Initialized Then
        Call ItemSel.Move(120, 120, UserControl.Width - 240, UserControl.Height - 240)
        Set ItemSel.Db = mDb
        ItemSel.Language_code = mLanguage_Code
        If Not ItemSel.Load_A_Com Then
            ' TODO : check error
        End If
    Else
        Call ItemSel.Reinit
    End If
    
    ' Add the static Keys
    Dim lIdx As Long, lCount As Long, lRow As Variant, lColIdx
    ReDim lRow(14)
    lCount = grItemProd.Rows - 1
    For lIdx = 0 To lCount
        For lColIdx = 0 To UBound(lRow)
            lRow(lColIdx) = grItemProd.Data(lIdx, lColIdx + 3)
        Next
        ItemSel.AddStaticItem (lRow)
    Next
    
    ItemSel.ZOrder
    ItemSel.Visible = True
    tabCmd.Enabled = False

End Sub

' this function is called for each item return by the item selector to check if the item is not already linked as tested product to the current test
Private Function IsProductTested(ByVal aBISAPCode) As Boolean
    
    Dim lIdx As Long, lViewId As Long
    lViewId = IIf(opt_ProdView(0).value = True, 0, 1)
    If Not IsArray(mSelectedTest.ProductViews(lViewId).Data) Then Exit Function
    
    Dim lCount As Long
    lCount = UBound(mSelectedTest.ProductViews(lViewId).Data)
    For lIdx = 0 To lCount
        If mSelectedTest.ProductViews(lViewId).Data(lIdx, 4) = aBISAPCode And mSelectedTest.ProductViews(lViewId).isValid(lIdx) Then
            IsProductTested = True
            Exit Function
        End If
    Next
    
End Function

Private Sub ItemSel_Quit()
    Call Item_MtncExit
End Sub


Private Sub ItemMtncExit_Prod()
    ItemSel.Visible = False
End Sub



Private Sub ItemMtncAdd_ProdCriteria()
    gs_Action = "add"
    gut_Param.Str1 = "Test Link Products choice"
    gs_ParamReqCsts = "EXEC Screen_Csts 'mtnc_lk_prod '"
    gs_TableName = "Test_Link_Products"
    gut_Param.Str22 = mSelectedTest.TestCode
    frm_mtnc_cwpr.show 1
    Call Item_RefreshCurrentView
End Sub


Private Function ItemLocalUpd_Gen(ByVal aTestCode As Long) As Boolean
   
    Dim iConc As Long
    iConc = mSelectedTest.ViewGeneral.iConcurrency
    mSelectedTest = GetItemInfoFromForm(aTestCode)
    mSelectedTest.ViewGeneral.iConcurrency = iConc
    Dim lPath As String
    lPath = GetCurrentPath(UserControl.Controls, fraItemGeneral, cbo_Views.SelectedItem.GetData(2))
    If Not FindInTreeView(lPath) Then
        ' TODO ERROR
    End If
    If Not grList.SearchKey(True, Array(aTestCode, "E")) Then
        ' TODO ERROR
    End If
    Item_LoadReminderFromViewGen
    
End Function

Private Function ItemLocalUpd_Doc(ByRef aTestDoc As TTestDocument) As Boolean
   
    ItemLocalUpd_Doc = False
    If grItemDoc.SearchKey(True, Array(aTestDoc.MD_Code, aTestDoc.Zip_code, aTestDoc.MediaConcurrency - 1)) Then
    
        grItemDoc.SelectedLine(0, "PT_Title") = aTestDoc.PT_Title
        grItemDoc.SelectedLine(0, "Language_Desc") = aTestDoc.MD_Language_Desc
        grItemDoc.SelectedLine(0, "FE_Desc") = aTestDoc.FE_Desc
        grItemDoc.SelectedLine(0, "iconcurrency") = aTestDoc.MediaConcurrency
        grItemDoc.SelectedLine(0, "ACCESS_TYPE") = aTestDoc.Access_type_desc
    
    End If
   
    ItemLocalUpd_Doc = True
End Function


Private Function GetCurrentPath(ByRef aControls As Variant, ByRef aContainer As Object, ByVal aPattern As String) As String


    Dim lPattern() As String
    lPattern = Split(aPattern, CH_LDELIMIT)
    
    Dim lPath() As String
    lPath = lPattern
    
    Dim lIdxPattern As Long, lCountPattern As Long, lIdxPath As Long
    Dim lIdx As Long, lCount As Long, lIdxLbl As Long
    Dim lControl As Control

    lCountPattern = UBound(lPattern)
    lCount = aControls.Count - 1
    For lIdx = 0 To lCount
        Set lControl = aControls.Item(lIdx)
        If HasContainer(lControl, aContainer) Then
            lIdxPath = -1
            For lIdxPattern = 0 To lCountPattern
                If UCase(lControl.Tag) = UCase(lPattern(lIdxPattern)) Then
                    Select Case UCase(TypeName(lControl))
                        Case "TEXTBOX"
                            lPath(lIdxPattern) = lControl.Text
                        Case "ARMCOMBOBOX"
                            lPath(lIdxPattern) = lControl.SelectedItem.Key
                        Case "ARMCHECKVIEW"
                            If UCase(lControl.Tag) = "ACVCOUNTRIES" Then
                                Dim a As Long, b As Long
                                Dim TMK As String
                                TMK = Trim(acvMarkets.RoleList(acvMarkets.GetVisibleList).CheckedKeys(0)(0))
                                b = acvCountries.RoleList(lControl.GetVisibleList).Items.Count
                                For a = 1 To b
                                    If Trim(acvCountries.RoleList(acvCountries.GetVisibleList).Items.Item(a).GetData(2)) = TMK Then
                                        If Not acvCountries.RoleList(acvCountries.GetVisibleList).Items.Item(a).CurrentChecked Then
                                            lPath(lIdxPattern) = acvCountries.RoleList(acvCountries.GetVisibleList).Items.Item(a).GetData(0)
                                            Exit For
                                        End If
                                    End If
                                Next
                                
                            Else
                                If lControl.RoleList(lControl.GetVisibleList).CheckedCount Then
                                    lPath(lIdxPattern) = Trim(acvMarkets.RoleList(acvMarkets.GetVisibleList).CheckedKeys(0)(0))
                                Else
                                    lPath(lIdxPattern) = ""
                                End If
                            End If
                    End Select
                Exit For
                End If
            Next
        End If
        Set lControl = Nothing
    Next
        
    GetCurrentPath = Replace(Join(lPath, CH_LDELIMIT), "TT_Type", mSelectedTest.Type, , , vbTextCompare)

End Function

   
Private Sub DisplayMenu_ItemMtncCnd()

    Screen.MousePointer = vbHourglass
    If Not lst_on_what5.Visible Then
        lst_on_what5.ZOrder
        lst_on_what5.ListIndex = -1
        lst_on_what5.Visible = True
        lst_on_what5.SetFocus
    Else
        lst_on_what5.Visible = False
    End If
    Screen.MousePointer = 0
    
End Sub


Private Sub lst_On_What5_Click()
    Call ItemMtnc_Cnd(lst_on_what5.ListIndex)
End Sub
Private Sub lst_On_What5_LostFocus()
    lst_on_what5.Visible = False
End Sub


' 0 is Typ_Condition
' 1 is detail conditon
Private Sub ItemMtnc_Cnd(ByVal aIdx As Long)

    lst_on_what5.Visible = False
    Select Case aIdx
        Case 0
            Call ItemMtcn_Cnd_TypeCnd
        Case 1
            Call ItemMtcn_Cnd_Detail
    End Select
End Sub


Private Sub ItemMtcn_Cnd_TypeCnd()

    gs_TableName = "Test_Typ_Condition"
    gs_ParamReq1 = "EXEC Test_Typ_Condition_t_lst '"
    gs_ParamReq2 = "EXEC Screen_Csts 'main_Tst_TypCnd', '" & mLanguage_Code & "'"
    gs_ParamReq3 = "EXEC Check_Security 'Test_Typ_Condition', " & mLoginName
    gi_TranslateType = 1
    gi_GridWidth(0) = 1
    gi_GridWidth(1) = 1
    gi_GridWidth(2) = 2000
    gi_GridWidth(3) = 2000
    gi_GridWidth(4) = 1200
    gi_GridWidth(5) = 1
    Dim i As Integer
    For i = 6 To 29
        gi_GridWidth(i) = 1
    Next i
    ' columns of the internet flag
    gi_ColumnIFlag = 1
    C_main.show 1
    
    ' ]@€ bug of mouse in the old framework !!!
    Screen.MousePointer = 0

    ' refresh the combo
    cbo_TypeCnd.Clear
    ItemMtncClear_Cnd

End Sub


Private Sub ItemMtcn_Cnd_Detail()

    Dim i As Integer
    gs_TableName = "Test_Dtl_Condition"
    gs_ParamReq1 = "EXEC Test_Dtl_Condition_t_lst '"
    gs_ParamReq2 = "EXEC Screen_Csts 'main_Tst_Dtlcnd', '" & gut_LangLogin.Code & "'"
    gs_ParamReq3 = "EXEC Check_Security 'Test_Dtl_Condition', " & prg.LoginName
    gi_TranslateType = 1
    gi_GridWidth(0) = 1
    gi_GridWidth(1) = 1
    gi_GridWidth(2) = 1
    gi_GridWidth(3) = 2000
    gi_GridWidth(4) = 2000
    gi_GridWidth(5) = 1200
    gi_GridWidth(6) = 1
    gi_GridWidth(7) = 1200
    
    For i = 8 To 29
        gi_GridWidth(i) = 1
    Next i
    gi_ColumnIFlag = 2
    C_main.show 1
    
    ' ]@€ bug of mouse in the old framework !!!
    Screen.MousePointer = 0

    ' Refresh the current data
    If Not cbo_TypeCnd.SelectedItem Is Nothing Then
        Call LoadCndLst(cbo_TypeCnd.SelectedItem.Key, cbo_TypeCnd.SelectedItem.GetData(2))
    End If

End Sub


Private Sub optFiltersDate_Click(Index As Integer)
    Screen.MousePointer = vbHourglass
    Call SelectDateFilters(Index)
    Screen.MousePointer = 0
End Sub


Private Sub SelectDateFilters(ByVal aIndex As Long)
    ' Show/Hide the range
    Dim lShow As Boolean
    lShow = (aIndex = 1)
    calFiltersMin.Visible = lShow
    calfiltersMax.Visible = lShow
    cbo_FiltersDate.Visible = lShow
    Call OnFilterChange
End Sub

Private Sub pctTvReset_Click()
'
End Sub


Private Sub cbo_FiltersDate_ComboItemSelected()
    Screen.MousePointer = vbHourglass
    Call OnFilterChange
    Screen.MousePointer = 0
'    reload_treeview.Visible = -1
'    fill_all_record.Visible = False
'    grdlst.ClearGrid
'    grdlst.Requests = ""
'    tvitems.Visible = 0

End Sub


Private Sub calFiltersMin_datechangee()
    Screen.MousePointer = vbHourglass
    If calFiltersMin.date_courte <> "" And calfiltersMax.date_courte <> "" Then
        If CDate(calFiltersMin.date_courte) > CDate(calfiltersMax.date_courte) Then
            calFiltersMin.SetFocus
            Call SendMessage(968, "Start date cannot be greater than End date", mLanguage_Code)
        End If
   End If
   Call OnFilterChange
    
    Screen.MousePointer = 0
End Sub

Private Sub calFiltersMax_datechangee()
    Screen.MousePointer = vbHourglass
    If calfiltersMax.date_courte <> "" And calFiltersMin.date_courte <> "" Then
        If CDate(calfiltersMax.date_courte) < CDate(calFiltersMin.date_courte) Then
            calfiltersMax.SetFocus
            Call SendMessage(969, "End date cannot be less than Start date", mLanguage_Code)
        End If
    End If
    Call OnFilterChange
    Screen.MousePointer = 0
End Sub


Private Sub OnFilterChange()
    ' Treeview don't need to be clear because all things are displayed in the treeview
    Dim lFilters As String
    If optFiltersDate(0).value Then
        lFilters = optFiltersDate(0).Caption
    End If
    
    If optFiltersDate(1).value Then
        If Not cbo_FiltersDate.SelectedItem Is Nothing Then
            lFilters = cbo_FiltersDate.SelectedItem.DisplayText & " " & optFiltersDate(1).Caption & " " & IIf(calFiltersMin.date_courte <> "", calFiltersMin.date_courte, "-") & " && " & IIf(calfiltersMax.date_courte <> "", calfiltersMax.date_courte, "-")
        Else
            lFilters = "-"
        End If
    End If
    
    
    ' Clear the grid
    grList.Requests = ""
    grList.ClearGrid
    grList.Title = lFilters
    
    ' Clear the treeview sel
    Set TVTest.SelectedItem = Nothing
    
End Sub

Private Function ApplyTVFilters(ByVal aRequest As Variant) As Variant
    Dim lRequests As Variant
    If IsArray(aRequest) Then
        ReDim lRequests(UBound(aRequest))
        Dim lIdx As Long, lCount As Long
        lCount = UBound(lRequests)
        For lIdx = 0 To lCount
            lRequests(lIdx) = ReplaceTVFiltersHolders(aRequest(lIdx))
        Next
    Else
        ReDim lRequests(0)
        lRequests(0) = ReplaceTVFiltersHolders(aRequest)
    End If

    ApplyTVFilters = lRequests
End Function



Private Function ReplaceTVFiltersHolders(ByVal aRequest As String) As String

    ' For date, there is three params
    Dim lRequest As String
    Dim lDateType As String, lDateMin As String, lDateMax As String

    If optFiltersDate(0).value Then
        lDateType = 0
        lDateMin = "null"
        lDateMax = "null"
    End If
    
    If optFiltersDate(1).value Then
        lDateType = cbo_FiltersDate.SelectedItem.GetData(0)
        lDateMin = IIf(calFiltersMin.date_us <> "", "'" & calFiltersMin.date_us & "'", "null")
        lDateMax = IIf(calfiltersMax.date_us <> "", "'" & calfiltersMax.date_us & "'", "null")
    End If

    lRequest = Replace(aRequest, "$datetype$", lDateType, , , vbTextCompare)
    lRequest = Replace(lRequest, "$datemin$", lDateMin, , , vbTextCompare)
    lRequest = Replace(lRequest, "$datemax$", lDateMax, , , vbTextCompare)

    ReplaceTVFiltersHolders = lRequest

End Function


'Private Sub cmd_Market_Click()
'    If Not mSelectedTest.MarketsLoaded Then
'       Call ItemLoadMarket
'    End If
'    mSelectedTest.MarketsLoaded = Not mSelectedTest.MarketsLoaded
'    lst_Market.Visible = mSelectedTest.MarketsLoaded
'End Sub


Private Sub ItemLoadMarket()
    
    'lst_Market.Clear
    'FillLstSingle "Exec Test_link_Markets_t_lst " & CStr(mSelectedTest.TestCode) & ",'" & mLanguage_Code & "'", lst_Market
    'Exit Sub
    
    acvMarkets.Reset
    
    If cbo_ivgCategory.SelectedItem Is Nothing Then
        Exit Sub
    End If
    
    acvMarkets.Common_List_Load = True
    acvMarkets.Type_Of_Key = tkDependant
    acvMarkets.Calling_Key_Fields = "TST_CODE®©CAT_CODE"
    acvMarkets.Link_Key_Fields = "TMK_Code"
    acvMarkets.RoleCount = 2
    
    acvMarkets.Synchronize_View = True
    acvMarkets.HideColumnHeaders = True
    acvMarkets.Common_List_Load = True
    
    acvMarkets.Visible = False
    
    
    Dim lTestCode As String
    lTestCode = mSelectedTest.TestCode
    If mTestAction = etaAdd Then
        If mTestActionType = ettReal Then
            lTestCode = "null"
        End If
    End If
    acvMarkets.Calling_Key_Values = lTestCode & "®©" & cbo_ivgCategory.SelectedItem.Key
    
    Dim lRoleView As Variant, lRoleUpdate As Variant
    lRoleView = Array("MAIN", "VIEW", "", "", "Main view", "TMK_Code®©TMK_Desc®©LOCKED", "TMK_Desc®©LOCKED", "1500®©0", "TMK_Code", "exec TEST_Link_markets_t_lst3 '" & mLanguage_Code & "', $TST_CODE$ ", "", "", True, 2, True, True, 0, 0)
    lRoleUpdate = Array("UPD", "EDIT", "", "", "Main view", "TMK_Code®©TMK_Desc®©LOCKED", "TMK_Desc®©LOCKED", "1500®©00", "TMK_Code", "exec TEST_Link_markets_t_lst4 '" & mLanguage_Code & "', $CAT_CODE$, $TST_CODE$ ", "EXEC Test_link_Markets_Ins2 $TST_CODE$, $TMK_CODE$, '" & mLoginName & "'", "EXEC Test_link_Markets_Del2 $TST_CODE$, $TMK_CODE$", False, 2, True, True, 0, 0)
    If Not acvMarkets.SetRoleList(Array(lRoleView, lRoleUpdate)) Then
        'debug.print "Err SetRoleList"
    End If
    If Not acvMarkets.LoadList Then
        'debug.print "err LoadList"
    End If
    
    ' Lock the markets with countries exceptions
    Dim lIdx As Long, lCount As Long
    lCount = acvMarkets.RoleList("UPD").Items.Count
    For lIdx = 1 To lCount
        acvMarkets.RoleList("UPD").Items.Item(lIdx).ReadOnly = acvMarkets.RoleList("UPD").Items.Item(lIdx).GetData(2) = "Y"
    Next
    
    acvMarkets.Visible = True
    
    Select Case mTestAction
        Case eTestAction.etaAdd, eTestAction.etaUpdate
            acvMarkets.SetVisibleList ("UPD")
        Case Else
            acvMarkets.SetVisibleList ("MAIN")
    End Select
    
End Sub

Private Sub acvMarkets_ItemCheck(ByVal Item As MSComctlLib.ListItem)
    Call ItemLoadCountries(True)
End Sub


Private Sub ItemLoadCountries(ByVal aSave As Boolean)

    Const C_DB_GETCOUNTRIES As String = "SELECT  CT.CT_Code, " & vbCrLf & _
                                        "        CT.CT_Desc," & vbCrLf & _
                                        "        'X' 'CHECKED'," & vbCrLf & _
                                        "        TMC.TMK_Code" & vbCrLf & _
                                        "FROM Countries CT" & vbCrLf & _
                                        "INNER JOIN TEST_Market_Contains TMC ON TMC.CT_Code = CT.CT_Code AND TMC.TMK_Code IN ($TMK_CODE_LST$)" & vbCrLf & _
                                        "INNER JOIN TEST_COUNTRIES_EXCEPTION TCE ON TCE.CT_Code = TMC.CT_Code AND TCE.Tst_Code = $TST_CODE$" & vbCrLf & _
                                        "WHERE CT.Language_Code = '$lang$'" & vbCrLf & _
                                        "ORDER BY CT.CT_Desc" & vbCrLf

    Const C_DB_GETCOUNTRIES2 As String = "SELECT  CT.CT_Code, " & vbCrLf & _
                                         "        CT.CT_Desc," & vbCrLf & _
                                         "        CASE" & vbCrLf & _
                                         "           WHEN TCE.TST_Code IS NULL THEN ''" & vbCrLf & _
                                         "           Else 'X'" & vbCrLf & _
                                         "        End 'CHECKED'," & vbCrLf & _
                                         "        TMC.TMK_Code" & vbCrLf & _
                                         "FROM Countries CT" & vbCrLf & _
                                         "INNER JOIN TEST_Market_Contains TMC ON TMC.CT_Code = CT.CT_Code AND TMC.TMK_Code IN ($TMK_CODE_LST$)" & vbCrLf & _
                                         "LEFT OUTER JOIN TEST_COUNTRIES_EXCEPTION TCE ON TCE.CT_Code = TMC.CT_Code AND TCE.Tst_Code = $TST_CODE$" & vbCrLf & _
                                         "WHERE CT.Language_Code = '$lang$'" & vbCrLf & _
                                         "ORDER BY CT.CT_Desc" & vbCrLf
    Dim lCount As Long, lIdx As Long
    If aSave Then
        Dim lCTCodeLst As String
        lCTCodeLst = ""
        lCount = acvCountries.CheckedCount("UPD") - 1
        For lIdx = 0 To lCount
            lCTCodeLst = lCTCodeLst & acvCountries.CheckedKeys("UPD")(lIdx)(0) & ","
        Next
        If lCount >= 0 Then
            lCTCodeLst = Left(lCTCodeLst, Len(lCTCodeLst) - 1)
        End If
    End If
    
    acvCountries.Reset
    
    Dim lMarketCount As Long
    lMarketCount = acvMarkets.CheckedCount("UPD") - 1
    
    If lMarketCount < 0 Then
        Exit Sub
    End If
    
    acvCountries.Common_List_Load = True
    acvCountries.Type_Of_Key = tkDependant
    acvCountries.Calling_Key_Fields = "TST_CODE®©TMK_CODE_LST"
    acvCountries.Link_Key_Fields = "CT_Code"
    acvCountries.RoleCount = 2
    
    acvCountries.Synchronize_View = True
    acvCountries.HideColumnHeaders = True
    acvCountries.Common_List_Load = True
    
    Dim lRequest1 As String, lRequest2 As String
    lRequest1 = Replace(C_DB_GETCOUNTRIES, "$lang$", mLanguage_Code, , , vbTextCompare)
    lRequest2 = Replace(C_DB_GETCOUNTRIES2, "$lang$", mLanguage_Code, , , vbTextCompare)
    
    acvCountries.Visible = False
    Dim lTMKList As String
    lCount = acvMarkets.CheckedCount("UPD") - 1
    
    For lIdx = 0 To lCount
        lTMKList = lTMKList & acvMarkets.CheckedKeys("UPD")(lIdx)(0) & ","
    Next
    If lCount >= 0 Then
        lTMKList = Left(lTMKList, Len(lTMKList) - 1)
    End If
    
    Dim lTestCode As String
    lTestCode = mSelectedTest.TestCode
    If mTestAction = etaAdd Then
        If mTestActionType = ettReal Then
            lTestCode = "null"
        End If
    End If
    If aSave Then lTestCode = "NULL"
    acvCountries.Calling_Key_Values = lTestCode & "®©" & lTMKList
    
    Dim lRoleView As Variant, lRoleUpdate As Variant
    lRoleView = Array("MAIN", "VIEW", "", "", "Main view", "CT_CODE®©CT_DESC®©TMK_CODE", "CT_Desc®©TMK_CODE", "2000®©0", "CT_Code", lRequest1, "", "", True, 2, True, True, 0, 0)
    lRoleUpdate = Array("UPD", "EDIT", "", "", "Main view", "CT_Code®©CT_Desc®©TMK_CODE", "CT_Desc®©TMK_CODE", "2000®©0", "CT_Code", lRequest2, "EXEC TEST_COUNTRIES_EXCEPTION_ins2 $TST_CODE$, '$CT_CODE$', '" & mLoginName & "'", "EXEC TEST_COUNTRIES_EXCEPTION_Del2 $TST_CODE$, '$CT_CODE$'", False, 2, True, True, 0, 0)
    If Not acvCountries.SetRoleList(Array(lRoleView, lRoleUpdate)) Then
        'debug.print "Err SetRoleList"
    End If
    If Not acvCountries.LoadList Then
        'debug.print "err LoadList"
    End If

    If aSave Then
        Dim larrCT As Variant
        larrCT = Split(lCTCodeLst, ",", , vbTextCompare)
        lCount = UBound(larrCT)
        For lIdx = 0 To lCount
            acvCountries.RoleList("UPD").GetItem(Array(larrCT(lIdx))).CurrentChecked = True
        Next
        
    End If
    
    Select Case mTestAction
        Case eTestAction.etaAdd, eTestAction.etaUpdate
            acvCountries.SetVisibleList ("UPD")
        Case Else
            acvCountries.SetVisibleList ("MAIN")
    End Select
    acvCountries.Visible = True

End Sub



Private Sub acvCountries_ItemCheck(ByVal Item As MSComctlLib.ListItem)
    
    Dim lTMKCode As Long, lCTUncheckedCount As Long, lCTCheckedCount As Long
    
    lTMKCode = Item.Tag.GetData(2)
    
    Dim lIdx As Long, lCount As Long, lFound As Long
    lCount = acvCountries.RoleList("UPD").Count
    lCTUncheckedCount = 0
    lCTCheckedCount = 0
    For lIdx = 1 To lCount
        If acvCountries.RoleList("UPD").Items(lIdx).GetData(2) = lTMKCode Then
            If (acvCountries.RoleList("UPD").Items(lIdx).CurrentChecked = False) Then
                lCTUncheckedCount = lCTUncheckedCount + 1
            Else
                lCTCheckedCount = lCTCheckedCount + 1
            End If
        End If
    Next

    ' RULE 1 - If the country is checked, we checked if at least one country of the market need to be not checked
    If Item.Checked And lCTUncheckedCount = 0 Then
        ' TODO : !!!!!!
        MsgBox "You cannot set all the countries of this market in exceptions !"
        Item.Checked = False
        Item.Tag.CurrentChecked = False
        Exit Sub
    End If
    
    
    ' RULE 2 - If the country is checked, we set the market as readonly
    If Item.Checked Then
        acvMarkets.RoleList("UPD").GetItem(Array(lTMKCode)).ReadOnly = True
        acvMarkets.SetVisibleList ("UPD")
    End If
    
    ' RULE 3 - If the country is unchecked, we checked if we need to unset readonly the market
    If (Not Item.Checked) And (lCTCheckedCount = 0) Then
        acvMarkets.RoleList("UPD").GetItem(Array(lTMKCode)).ReadOnly = False
        acvMarkets.SetVisibleList ("UPD")
    End If
    
End Sub



Public Function ItemDBDel_Gen() As Boolean
Const C_MSG As String = "Error while saving association between Test & document. Please contact your IT support."
Dim lb_TranOpened As Boolean
Dim lIdx As Integer
Dim l_Req As String
Dim lCursor As Long
  
On Error GoTo Err_SaveTestMedia

    ItemDBDel_Gen = False
    
    'Fill links array between Test & Media
    l_Req = "exec Test_MediaLink_lst3 " & mSelectedTest.TestCode
    lCursor = mDb.OpenSQL(l_Req, -1, 0)
    If lCursor <= 0 Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/ItemDBDel_Gen/Test_MediaLink_lst3:"
        mDesc = "Unable to read in Test_MediaLink."
        Err.Raise mNumber, mSource, mDesc
    Else
        ReDim mLinks(1)
        lIdx = 1
        
        While Not mDb.EOF(lCursor)
            ReDim Preserve mLinks(lIdx)
            mLinks(lIdx).TST_code = Val(mDb.GetFields(lCursor, 0))
            mLinks(lIdx).MD_Code = mDb.GetFields(lCursor, 1)
            mLinks(lIdx).Zip_code = mDb.GetFields(lCursor, 2)
            
            Call mDb.Next(lCursor)
            lIdx = lIdx + 1
        Wend
    End If
    mDb.Close lCursor

    If Not BeginTran("TEST_DEL") Then Err.Raise C_ERRORRAISE + 159, mDb.LastErrorCode & " : " & mDb.LastErrorMessage & ", " & vbCrLf & C_MSG
    lb_TranOpened = True
    
    If Not DBDel_Test_Value_Curve Then Err.Raise mNumber, mSource, mDesc
    If Not DBDel_Test_Result Then Err.Raise mNumber, mSource, mDesc
    If Not DBDel_Test_Countries_Exception Then Err.Raise mNumber, mSource, mDesc
    If Not DBDel_Test_Link_Markets Then Err.Raise mNumber, mSource, mDesc
    If Not DBDel_Test_Lst_Conditions Then Err.Raise mNumber, mSource, mDesc
    If Not DBDel_Test_Dtl_Condition Then Err.Raise mNumber, mSource, mDesc
    If Not DBDel_Test_Link_Products Then Err.Raise mNumber, mSource, mDesc
    If Not DBDel_Test_Memo Then Err.Raise mNumber, mSource, mDesc
    
    'Read links array for deleting media after media
'    If mSelTestDocument.MD_Code <> "" Then
    Dim lMax As Integer
    lMax = UBound(mLinks)
    For lIdx = 1 To lMax
        If mLinks(lIdx).MD_Code <> "" Then
            If Not DBDel_Media_Memo(mLinks(lIdx).MD_Code) Then Err.Raise mNumber, mSource, mDesc
            If Not DBDel_Media_Title(mLinks(lIdx).MD_Code) Then Err.Raise mNumber, mSource, mDesc
            If Not DBDel_Test_MediaLink(mLinks(lIdx).MD_Code) Then Err.Raise mNumber, mSource, mDesc
            If Not DBDel_Media_BlobLink(mLinks(lIdx).MD_Code) Then Err.Raise mNumber, mSource, mDesc
            If Not DBDel_Media(mLinks(lIdx).MD_Code) Then Err.Raise mNumber, mSource, mDesc
        End If
    Next lIdx

    If Not DBDel_Test Then Err.Raise mNumber, mSource, mDesc
  
    If CommitTran("TEST_DEL") Then
        lb_TranOpened = False
    Else
        mSource = C_SCREENNAME & "/ItemDBDel_Gen :"
        Err.Raise mNumber, mSource, mDesc
    End If
    
    'Blob part if exists
    For lIdx = 1 To lMax
        If mLinks(lIdx).Zip_code > 0 Then
'            If mLinks(lIdx).Zip_code <> "" Then
                If Not DeleteBlob(mLinks(lIdx).Zip_code) Then Err.Raise mNumber, mSource, mDesc
'            End If
        End If
    Next lIdx
    
    ItemDBDel_Gen = True
    Exit Function
    
Err_SaveTestMedia:
    If lb_TranOpened Then
        If Not (RollbackTran("TEST_DEL")) Then
            UploadSQLError mDb, mDbErr, C_SCREENNAME & "/ItemDBDel_Gen : RollbackTran()"
            mDb.Disconnect
            mDbErr.Disconnect
            End
        End If
    End If

    Err.Raise mNumber, mSource, mDesc
    
End Function

Private Function DBDel_Test_Value_Curve() As Boolean

Const C_REQUEST As String = "Test_Value_Curve_del $test_code$"
Dim lRequest As String

On Error GoTo Err_Del_TVC

    DBDel_Test_Value_Curve = False
    
    lRequest = ReplaceHolders(C_REQUEST)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Test_Value_Curve :"
        mDesc = "Unable to delete in Test_Value_Curve."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Test_Value_Curve = True
    Exit Function

Err_Del_TVC:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Test_Result() As Boolean

Const C_REQUEST As String = "Test_Result_del2 $test_code$"
Dim lRequest As String

On Error GoTo Err_Del_TR

    DBDel_Test_Result = False
    
    lRequest = ReplaceHolders(C_REQUEST)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Test_Result :"
        mDesc = "Unable to delete in Test_Result."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Test_Result = True
    Exit Function

Err_Del_TR:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Test_Countries_Exception() As Boolean

Const C_REQUEST As String = "Test_Countries_Exception_del3 $test_code$"
Dim lRequest As String

On Error GoTo Err_Del_TCE

    DBDel_Test_Countries_Exception = False
    
    lRequest = ReplaceHolders(C_REQUEST)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Test_Countries_Exception :"
        mDesc = "Unable to delete in Test_Countries_Exception."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Test_Countries_Exception = True
    Exit Function

Err_Del_TCE:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Test_Link_Markets() As Boolean

Const C_REQUEST As String = "Test_Link_Markets_del3 $test_code$"
Dim lRequest As String

On Error GoTo Err_Del_TLM

    DBDel_Test_Link_Markets = False
    
    lRequest = ReplaceHolders(C_REQUEST)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Test_Link_Markets :"
        mDesc = "Unable to delete in Test_Link_Markets."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Test_Link_Markets = True
    Exit Function

Err_Del_TLM:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Test_Lst_Conditions() As Boolean

Const C_REQUEST As String = "Test_Lst_Conditions_del $test_code$"
Dim lRequest As String

On Error GoTo Err_Del_TLCND

    DBDel_Test_Lst_Conditions = False
    
    lRequest = ReplaceHolders(C_REQUEST)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Test_Lst_Conditions :"
        mDesc = "Unable to delete in Test_Lst_Conditions."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Test_Lst_Conditions = True
    Exit Function

Err_Del_TLCND:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Test_Dtl_Condition() As Boolean

Const C_REQUEST As String = "Test_Dtl_Condition_del2 $test_code$"
Dim lRequest As String

On Error GoTo Err_Del_DTLCND

    DBDel_Test_Dtl_Condition = False
    
    lRequest = ReplaceHolders(C_REQUEST)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Test_Dtl_Condition :"
        mDesc = "Unable to delete in Test_Dtl_Condition."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Test_Dtl_Condition = True
    Exit Function

Err_Del_DTLCND:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Test_Link_Products() As Boolean

Const C_REQUEST As String = "Test_Link_Products_del2 $test_code$"
Dim lRequest As String

On Error GoTo Err_Del_TLP

    DBDel_Test_Link_Products = False
    
    lRequest = ReplaceHolders(C_REQUEST)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Test_Link_Products :"
        mDesc = "Unable to delete in Test_Link_Products."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Test_Link_Products = True
    Exit Function

Err_Del_TLP:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Test_Memo() As Boolean

Const C_REQUEST As String = "Test_Memo_del2 $test_code$"
Dim lRequest As String

On Error GoTo Err_Del_TMEM

    DBDel_Test_Memo = False
    
    lRequest = ReplaceHolders(C_REQUEST)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Test_Memo :"
        mDesc = "Unable to delete in Test_Memo."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Test_Memo = True
    Exit Function

Err_Del_TMEM:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Test() As Boolean

Const C_REQUEST As String = "Test_del2 $test_code$, $iconcurrency$"
Dim lRequest As String

On Error GoTo Err_Del_Test

    DBDel_Test = False
    
    lRequest = ReplaceHolders(C_REQUEST)
    lRequest = Replace(lRequest, "$iconcurrency$", mSelectedTest.ViewGeneral.iConcurrency)

    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Test :"
        mDesc = "Unable to delete in Test."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    If mDb.SQLRowsAffected = 0 Then
        mDesc = "Unable to delete in Test/Concurrency ?."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Test = True
    Exit Function

Err_Del_Test:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Doc() As Boolean

On Error GoTo Err_ItemDBDel_Doc
    DBDel_Doc = False
    
    If Not Delete_Media Then
        Err.Raise mNumber, mSource, mDesc
    End If
    
    If Not DeleteBlob(mSelTestDocument.Zip_code) Then
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Doc = True
    Exit Function
    
Err_ItemDBDel_Doc:
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Media_Memo(ByRef aMD_code As String) As Boolean

Const C_REQUEST As String = "media_memo_del2 '$MD_code$'"
Dim lRequest As String

On Error GoTo Err_Del_MMEM

    DBDel_Media_Memo = False
    
    lRequest = Replace(C_REQUEST, "$MD_code$", aMD_code)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Media_Memo :"
        mDesc = "Unable to delete in Media_Memo."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Media_Memo = True
    Exit Function

Err_Del_MMEM:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Media_Title(ByRef aMD_code As String) As Boolean

Const C_REQUEST As String = "media_title_del '$MD_code$'"
Dim lRequest As String

On Error GoTo Err_Del_MTitle

    DBDel_Media_Title = False
    
    lRequest = Replace(C_REQUEST, "$MD_code$", aMD_code)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Media_Title :"
        mDesc = "Unable to delete in Media_Title."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Media_Title = True
    Exit Function

Err_Del_MTitle:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Test_MediaLink(ByRef aMD_code As String) As Boolean

Const C_REQUEST As String = "Test_MediaLink_del $test_code$, '$MD_code$'"
Dim lRequest As String

On Error GoTo Err_Del_TML

    DBDel_Test_MediaLink = False
    
    lRequest = ReplaceHolders(C_REQUEST)
    lRequest = Replace(lRequest, "$MD_code$", aMD_code)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Test_MediaLink :"
        mDesc = "Unable to delete in Test_MediaLink."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Test_MediaLink = True
    Exit Function

Err_Del_TML:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Media_BlobLink(ByRef aMD_code As String) As Boolean

Const C_REQUEST As String = "Media_BlobLink_del '$MD_code$'"
Dim lRequest As String

On Error GoTo Err_Del_MBL

    DBDel_Media_BlobLink = False
    
    lRequest = Replace(C_REQUEST, "$MD_code$", aMD_code)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Media_BlobLink :"
        mDesc = "Unable to delete in Media_BlobLink."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Media_BlobLink = True
    Exit Function

Err_Del_MBL:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function

Private Function DBDel_Media(ByRef aMD_code As String) As Boolean

Const C_REQUEST As String = "Media_del2 '$MD_code$'"
Dim lRequest As String

On Error GoTo Err_Del_Media

    DBDel_Media = False
    
    lRequest = Replace(C_REQUEST, "$MD_code$", aMD_code)
    If Not mDb.ExecuteSQL(lRequest) Then
        mNumber = C_ERRORRAISE + 196
        mSource = C_SCREENNAME & "/DBDel_Media :"
        mDesc = "Unable to delete in Media."
        Err.Raise mNumber, mSource, mDesc
    End If
    
    DBDel_Media = True
    Exit Function

Err_Del_Media:
    UploadSQLError mDb, mDbErr, mSource & lRequest
    Err.Raise mNumber, mSource, mDesc
End Function



Private Sub Item_LoadViewTree()
    Call LoadTreeView(tvItemTree, GetTreeViewInfo(mTreeViewInfosItemTree, "TSMITEMTREE", cbo_ItemTreeViews.SelectedItem.Key))
    Dim lIdx As Long, lCount As Long
    lCount = UBound(mTreeViewInfosItemTree)
    For lIdx = 0 To lCount
        mTreeViewInfosItemTree(lIdx).Loaded = False
    Next
End Sub



Private Sub GetItemViewProductsFromDB(ByRef aProductView As TProductView)

    Const CL_REQUEST_VIEWPRODUCT As String = "Test_Link_Products_t_lst6 $test_code$, '$lang$', '$type$'"

    Dim lData As Long
    Dim lRequest As String
    lRequest = ReplaceHolders(CL_REQUEST_VIEWPRODUCT)
    lRequest = Replace(lRequest, "$type$", aProductView.Type, , , vbTextCompare)
    
    lData = mDb.OpenSQL(lRequest)
    
    Dim lRowIdx As Long, lColIdx As Long, lRowCount As Long, lColCount As Long
    lRowCount = mDb.RowCount(lData) - 1
    lColCount = mDb.FieldCount(lData) - 1
    
    If lRowCount < 0 Then
        aProductView.Data = 0
        ReDim aProductView.isValid(0)
    Else
        ReDim aProductView.Data(lRowCount, lColCount)
        ReDim aProductView.isValid(lRowCount)
    End If
    
    If lRowCount >= 0 Then
        For lRowIdx = 0 To lRowCount
            For lColIdx = 0 To lColCount
                aProductView.Data(lRowIdx, lColIdx) = mDb.GetFields(lData, lColIdx)
            Next
            aProductView.isValid(lRowIdx) = True
            mDb.Next (lData)
        Next
    End If
    mDb.Close (lData)
    aProductView.Loaded = True

End Sub


Private Sub LoadViewProducts(ByVal aViewIdx As Long)
    
    grItemProd.Visible = False
    grItemProd.ClearGrid
    mItemProdSelRow = -1
    'mSelectedTest.ProductViews(aViewIdx).Loaded = False
    If Not mSelectedTest.ProductViews(aViewIdx).Loaded Then
        Call GetItemViewProductsFromDB(mSelectedTest.ProductViews(aViewIdx))
    End If

    Dim lIdx As Long, lCount As Long, lBuffer As String

    Dim lColIdx As Long, lColCount As Long, lRow As Variant
    If IsArray(mSelectedTest.ProductViews(aViewIdx).Data) Then
        lColCount = UBound(mSelectedTest.ProductViews(aViewIdx).Data, 2)
        lCount = UBound(mSelectedTest.ProductViews(aViewIdx).Data, 1)
        ReDim lRow(lColCount)
        For lIdx = 0 To lCount
            If mSelectedTest.ProductViews(aViewIdx).isValid(lIdx) Then
                For lColIdx = 0 To lColCount
                    lRow(lColIdx) = mSelectedTest.ProductViews(aViewIdx).Data(lIdx, lColIdx)
                Next
                Call grItemProd.AddLine(lRow)
            End If
        Next
        grItemProd.LastLine
        grItemProd.FirstLine
    End If

    grItemProd.Visible = True

    mSelectedProductView = aViewIdx
    
End Sub


Private Sub ItemLocalDel_Prod()
    
    Dim lTLPCode As Long, lViewIdx As Long
    lTLPCode = grItemProd.CurrentKey(0)
    
    lViewIdx = IIf(opt_ProdView(0).value = True, 0, 1)
    Dim lIdx As Long, lCount As Long
    lCount = UBound(mSelectedTest.ProductViews(lViewIdx).Data, 1)
    For lIdx = 0 To lCount
        If mSelectedTest.ProductViews(lViewIdx).Data(lIdx, 0) = lTLPCode Then
            mSelectedTest.ProductViews(lViewIdx).isValid(lIdx) = False
        End If
    Next
    grItemProd.DeleteLine (grItemProd.CurrentKey)
    grItemProd.DeselectRow
    
End Sub


'BI_SAP_Code, Short_Code, Plant
Private Sub ItemSel_SelectItems(aItems() As String, ByRef aRows() As Boolean)
    
    Const C_DB_REQUEST As String = "Exec Test_Link_Products_ins1 $test_code$, '$bi_sap_code$', '$mfgp_code$', '$linktype$'"

    Dim lMousePointer As Long
    lMousePointer = Screen.MousePointer
    Screen.MousePointer = vbHourglass
    
    Dim lIdx As Long, lCount As Long, lBuffer As Variant, lBISapCode As String, lPlant As String
    Dim lRequest As String, lError As String, lRow As Variant, lTLPCode As Long
    
    ReDim lRow(UBound(aItems))
        
    lCount = UBound(aItems)
    For lIdx = 0 To lCount
        lBuffer = Split(aItems(lIdx), CH_LDELIMIT)
        lBISapCode = lBuffer(1)
        lPlant = lBuffer(0)
        
        lRequest = ReplaceHolders(C_DB_REQUEST)
        lRequest = Replace(lRequest, "$bi_sap_code$", Replace(lBISapCode, "'", "''"), , , vbTextCompare)
        lRequest = Replace(lRequest, "$mfgp_code$", Replace(lPlant, "'", "''"), , , vbTextCompare)
        lRequest = Replace(lRequest, "$linktype$", IIf(opt_ProdView(0).value = True, "T", "A"), , , vbTextCompare)
        
        If Not IsProductTested(lBISapCode) Then
            lTLPCode = mDb.OpenSQL(lRequest)
            If mDb.RowCount(lTLPCode) = 0 Then
                ' ERROR !
                'debug.print "Cannot add product"
            Else
                lRow(lIdx) = mDb.GetFields(lTLPCode, 0) & CH_LDELIMIT & "1" & CH_LDELIMIT & "1" & CH_LDELIMIT & aItems(lIdx)
                aRows(lIdx) = True
                mDb.Close (lTLPCode)
            End If
        Else
            aRows(lIdx) = True
        End If
NextOne:
    Next
    
    grItemProd.Visible = False
    Dim lLine As Variant

    Dim lViewIdx As Long
    
    lViewIdx = IIf(opt_ProdView(0).value = True, 0, 1)
    For lIdx = 0 To lCount
        If lRow(lIdx) <> "" Then
            lLine = Split(lRow(lIdx), CH_LDELIMIT)
            grItemProd.AddLine (lLine)
        End If
    Next
    
    Dim lCountData As Long, lIdxData As Long, lIdxCol As Long, lCountCol As Long
    lCountData = grItemProd.Rows - 1
    lCountCol = grItemProd.Cols - 1
    ReDim mSelectedTest.ProductViews(lViewIdx).Data(lCountData, lCountCol)
    ReDim mSelectedTest.ProductViews(lViewIdx).isValid(lCountData)
    For lIdxData = 0 To lCountData
        For lIdxCol = 0 To lCountCol
            mSelectedTest.ProductViews(lViewIdx).Data(lIdxData, lIdxCol) = grItemProd.Data(lIdxData, lIdxCol)
            mSelectedTest.ProductViews(lViewIdx).isValid(lIdxData) = True
        Next
    Next
    
    
    grItemProd.Visible = True
End Sub


#If LIVE Then
Private Sub LogActivty(ByRef ADB As Object, ByVal aU_Code As Long, aBusinessFunction As eBusinessFunction)
#Else
Private Sub LogActivty(ByRef ADB As ArmDb, ByVal aU_Code As Long, aBusinessFunction As eBusinessFunction)
#End If

    Const C_REQ_UPDATE As String = "exec Gen_Systems_Users_Activities_Upd $u_code$, $f_code$"
    Const C_REQ_ADD As String = "exec Gen_Systems_Users_Activities_Ins $u_code$, $f_code$"

    Dim lRequest As String
    lRequest = Replace(C_REQ_UPDATE, "$u_code$", aU_Code, , , vbTextCompare)
    lRequest = Replace(lRequest, "$f_code$", aBusinessFunction, , , vbTextCompare)

    If Not ADB.ExecuteSQL(lRequest) Then
        'debug.print "error lrequest : " & lRequest
    End If
    
    If ADB.SQLRowsAffected = 0 Then
        lRequest = Replace(C_REQ_ADD, "$u_code$", aU_Code, , , vbTextCompare)
        lRequest = Replace(lRequest, "$f_code$", aBusinessFunction, , , vbTextCompare)
        Call ADB.ExecuteSQL(lRequest)
    End If

End Sub

' **************************************************************************************************
' ************************************* DISPLAY MEDIA FUNCTIONS ************************************
' **************************************************************************************************

#If LIVE Then
Private Sub DisplayMedia(ByVal ao_Armdb As Object, ByVal as_MD_code As String)
#Else
Private Sub DisplayMedia(ByVal ao_Armdb As ARMSYSCOMLib.ArmDb, ByVal as_MD_code As String)
#End If

Const MEDIA_SEL_REQ = "SELECT MBL.Zip_code, MF.FE_desc" & vbCrLf & _
                      "FROM Media M" & vbCrLf & _
                      "  INNER JOIN Media_File_Ext MF ON MF.FE_code=M.FE_code and MF.Language_code='E'" & vbCrLf & _
                      "  INNER JOIN Media_BlobLink MBL ON M.MD_Code=MBL.MD_Code and MBL.Language_code='E'" & vbCrLf & _
                      "WHERE M.MD_code = '$MD_CODE$'"

Dim ls_req As String
Dim ll_Cursor As Long
Dim ls_ext As String
Dim ll_ZipCode As Long
Dim ls_mediaFile As String
Dim ls_Command As String


On Error GoTo ErrorHandler

    ' Get extension and zip_code of the media
    ls_req = Replace(MEDIA_SEL_REQ, "$MD_CODE$", SqlStr(as_MD_code))
    
    ll_Cursor = OpenSQLSafe(ao_Armdb, ls_req)
    Debug.Assert (ll_Cursor <> 0)
    
    ' only one zip per media
    If ao_Armdb.RowCount(ll_Cursor) <> 1 Then
        Call Err.Raise(CompFncFailed, "RowCount", "Invalid media link")
    End If
    
    ll_ZipCode = CLng(ao_Armdb.GetFields(ll_Cursor, "Zip_code"))
    ls_ext = LCase(ao_Armdb.GetFields(ll_Cursor, "FE_desc"))
    
    ' close cursor
    Call ao_Armdb.Close(ll_Cursor)
    
    ' download media file
    ls_mediaFile = DownloadMediaFile(ao_Armdb, ll_ZipCode, ls_ext)
    Debug.Assert (ls_mediaFile <> "")
    
    ' create shell object to access Registry and Runtime
    Dim lo_shell As Object
    Set lo_shell = CreateObject("WSCript.Shell")
    If lo_shell Is Nothing Then
        Call Err.Raise(CompFncFailed, "CreateObject()", "Cannot create WSCript.Shell.")
    End If
    
    ' get command defined for extension
    Dim ls_DDEExec As String, ls_Application As String, ls_topic As String
    ls_Command = GetCommand(ls_ext, ls_DDEExec, ls_Application, ls_topic, lo_shell)
    
    If ls_Command = "" Then
        ' TODO: Manage status: no associate application found
        ' TODO: here we can try explorer.exe to display media
        Call Err.Raise(CompFncFailed, "", "No Application associated with file.")
    End If
    
    ' anyway, to execute document we don't need ls_command
    Call lo_shell.Run("""" & ls_mediaFile & """")
    
    Set lo_shell = Nothing
    
Exit Sub

ErrorHandler:
    If ll_Cursor <> 0 Then ao_Armdb.Close ll_Cursor
    If Not lo_shell Is Nothing Then Set lo_shell = Nothing
    Call Err.Raise(Err.Number, "DisplayMedia" & CH_LDELIMIT & Err.Source, Err.Description, Err.HelpFile, Err.HelpContext)
End Sub

#If LIVE Then
Private Function DownloadMediaFile(ByVal ao_Armdb As Object, ByVal al_zipCode As Long, ByVal as_ext As String) As String
#Else
Private Function DownloadMediaFile(ByVal ao_Armdb As ARMSYSCOMLib.ArmDb, ByVal al_zipCode As Long, ByVal as_ext As String) As String
#End If
On Error GoTo ErrHandler
    
Const MEDIA_BLOB_REQ = "EXEC Media_Zip_sel $ZIP_CODE$"
    
    Dim ls_req As String
    Dim ls_path As String
    Dim ls_fileName As String
    Dim lo_Fso As Object
    
    Set lo_Fso = CreateObject("Scripting.FileSystemObject")
    If lo_Fso Is Nothing Then
        Call Err.Raise(CompFncFailed, "CreateObject()", "Cannot create Scripting.FileSystemObject.")
    End If
    
    ls_path = App.Path & REP_DOWNLOAD & al_zipCode & "\"
    
    ' check if file exists in local temporary directory
    ls_fileName = GetFirstFileName(lo_Fso, ls_path, as_ext)
    If ls_fileName <> "" Then
        DownloadMediaFile = ls_fileName
        Set lo_Fso = Nothing
        Exit Function
    End If
    
    If Not lo_Fso.FolderExists(ls_path) Then
        Call CreateDirStruct(ls_path, lo_Fso)
        Debug.Assert (lo_Fso.FolderExists(ls_path))     ' folder Download must exists
    End If
    
    ' download media from SQL server and decompress
    ls_req = Replace(MEDIA_BLOB_REQ, "$ZIP_CODE$", CStr(al_zipCode))
    If Not ao_Armdb.BlobToFileSQL(ls_req, ls_path, True, True) Then
        ' some issue with decompression
        Call Err.Raise(CompFncFailed, "BlobToFileSQL()", "Cannot download blob." & vbCrLf & GetDbError(ao_Armdb))
    End If

    DownloadMediaFile = GetFirstFileName(lo_Fso, ls_path, as_ext)
    
    Set lo_Fso = Nothing
Exit Function
ErrHandler:
    If Not lo_Fso Is Nothing Then Set lo_Fso = Nothing
    Call Err.Raise(Err.Number, "DownloadMediaFile" & CH_LDELIMIT & Err.Source, Err.Description, Err.HelpFile, Err.HelpContext)
End Function

Private Function GetFirstFileName(ByVal ao_FSO As Object, ByVal as_path As String, ByVal as_ext As String) As String

On Error GoTo ErrorHandler
    Dim lo_folder As Object, lo_File As Object
    
    GetFirstFileName = ""
    If ao_FSO.FolderExists(as_path) Then
        Set lo_folder = ao_FSO.GetFolder(as_path)
        If Not lo_folder Is Nothing Then
            For Each lo_File In lo_folder.Files
                If Len(lo_File.Name) > Len(as_ext) Then
                    If StrComp(right(lo_File.Name, Len(as_ext)), as_ext, vbTextCompare) = 0 Then
                        GetFirstFileName = lo_File.Path
                        Exit For
                    End If
                End If
            Next
        End If
    End If

    Set lo_File = Nothing
    Set lo_folder = Nothing
Exit Function
ErrorHandler:
    If Not lo_File Is Nothing Then Set lo_File = Nothing
    If Not lo_folder Is Nothing Then Set lo_folder = Nothing
    Call Err.Raise(Err.Number, "GetFirstFileName" & CH_LDELIMIT & Err.Source, Err.Description, Err.HelpFile, Err.HelpContext)
End Function


' return command to be executed to open file with specific extension
Private Function GetCommand(ByVal as_ext As String, ByRef as_DDEExec As String, ByRef as_Application As String, ByRef as_Topic As String, ByVal ao_shell As Object) As String

Dim ls_defValue As String
Dim lo_Registry As New Registry

    GetCommand = ""

    On Error GoTo exitFnc
    ls_defValue = ao_shell.RegRead("HKCR\." & as_ext & "\")
    If ls_defValue = "" Then
        Call Err.Raise(CompFncFailed, "", "File extension is not supported.")
    End If
    
    Dim ls_cmd As String
    
    ls_cmd = ao_shell.RegRead("HKCR\" & ls_defValue & "\shell\Open\command\")
    If ls_cmd = "" Then
        Call Err.Raise(CompFncFailed, "", "Open command not defined.")
    End If
    GetCommand = ls_cmd
        
    ' try to locate DDEExec, if not exception is rised
    as_DDEExec = ao_shell.RegRead("HKCR\" & ls_defValue & "\shell\Open\ddeexec\")
    as_Application = ao_shell.RegRead("HKCR\" & ls_defValue & "\shell\Open\ddeexec\application\")
    as_Topic = ao_shell.RegRead("HKCR\" & ls_defValue & "\shell\Open\ddeexec\topic\")

    Exit Function
exitFnc:
End Function
' **************************************************************************************************

' ************************************************************************************
' **************************** DB-ACCESS FUNCTIONS ***********************************
' ************************************************************************************
#If LIVE = 1 Then
Private Sub ExecuteSQLSafe(ByVal ao_Db As Object, ByVal as_req As String)
#Else
Private Sub ExecuteSQLSafe(ByVal ao_Db As ARMSYSCOMLib.ArmDb, ByVal as_req As String)
#End If

    If Not ao_Db.ExecuteSQL(as_req) Then
        Call Err.Raise(CompFncFailed, "ExecuteSQLSafe", "SQL Error: " & GetDbError(ao_Db))
    End If

End Sub

#If LIVE = 1 Then
Private Function OpenSQLSafe(ByVal ao_Db As Object, ByVal as_req As String) As Long
#Else
Private Function OpenSQLSafe(ByVal ao_Db As ARMSYSCOMLib.ArmDb, ByVal as_req As String) As Long
#End If

    OpenSQLSafe = ao_Db.OpenSQL(as_req)
    
    If OpenSQLSafe = 0 Then Call Err.Raise(CompFncFailed, "OpenSQLSafe", "SQL Error: " & GetDbError(ao_Db))

End Function

Private Function SqlStr(ByVal as_Str As String) As String
    SqlStr = Replace(as_Str, "'", "''")
End Function

' ************************************************************************************
' ********************** ERROR-HANDLING SUPPORT FUNCTIONS ****************************
' ************************************************************************************
#If LIVE = 1 Then
Private Function GetDbError(ByVal lo_Db As Object) As String
#Else
Private Function GetDbError(ByVal lo_Db As ARMSYSCOMLib.ArmDb) As String
#End If
On Error GoTo ErrHandler
    If IsArray(lo_Db.SQLErrorMessages) Then
        Debug.Assert (IsArray(lo_Db.SQLErrorCodes))
        ' Display errors msgBox
        GetDbError = Join(lo_Db.SQLErrorCodes, ",") & vbCrLf & Join(lo_Db.SQLErrorMessages, vbCrLf)
    Else
        ' ExecuteSQL failed but no error message?
        GetDbError = "Unknown error"
    End If
    Exit Function
ErrHandler:
End Function

' procedure save/restore err object
Private Sub UpdateError(Optional ab_saveError As Boolean = False)
Static ls_errDesc As String
Static ls_errSource As String
Static ll_errNum As Long
Static ls_errHelpFile As String
Static ls_errHelpContext As String

    If ab_saveError Then
        ls_errDesc = Err.Description
        ls_errSource = Err.Source
        ll_errNum = Err.Number
        ls_errHelpContext = Err.HelpContext
        ls_errHelpFile = Err.HelpFile
    Else
        Err.Description = ls_errDesc
        Err.Source = ls_errSource
        Err.Number = ll_errNum
        Err.HelpContext = ls_errHelpContext
        Err.HelpFile = ls_errHelpFile
    End If
End Sub

' *******************************************************************************
' ************************ DISK IO FUNCTIONS ************************************
' *******************************************************************************
' create directory if not exist
Private Function CreateDirStruct(ByVal strPath As String, ByVal ao_FSO As Object) As Boolean

On Error GoTo Create_Dir_Struct_Errors
    Dim intIndex    As Integer
    Dim strTmpPath  As String
    
    If Len(Trim$(strPath)) = 0 Then
        ' if we specify wrong path it is error
        CreateDirStruct = False
        Exit Function
    End If
    
    If right$(strPath, 1) <> "\" Then strPath = strPath & "\"
    intIndex = 0
    
    Do
        ' get the next path chunk
        intIndex = InStr(intIndex + 1, strPath, "\")
        
        If intIndex > 0 Then
            strTmpPath = Left$(strPath, intIndex - 1)
        Else
            Exit Do
        End If
        
        ' see if this folder exists
        If Not ao_FSO.FolderExists(strTmpPath) Then
            ' Create this folder.
            ' If there is an error, it will be trapped bellow
            ao_FSO.CreateFolder strTmpPath
            intIndex = 1
        End If
    Loop
    CreateDirStruct = True
    Exit Function

Create_Dir_Struct_Errors:
    CreateDirStruct = False
End Function

