VERSION 5.00
Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.1#0"; "mscomctl.ocx"
Object = "{F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0"; "COMDLG32.OCX"
Begin VB.UserControl CapSOMQuote 
   ClientHeight    =   11235
   ClientLeft      =   0
   ClientTop       =   0
   ClientWidth     =   18945
   ScaleHeight     =   11235
   ScaleWidth      =   18945
   Begin VB.Frame fraItem 
      Height          =   10395
      Left            =   0
      TabIndex        =   59
      Top             =   0
      Width           =   16455
      Begin VB.Frame fraItemTop 
         Height          =   8250
         Left            =   1380
         TabIndex        =   0
         Top             =   570
         Width           =   15045
         Begin VB.Frame fraSubItemMain 
            Height          =   5445
            Index           =   1
            Left            =   10875
            TabIndex        =   44
            Tag             =   "DOCS"
            Top             =   5805
            Width           =   13335
            Begin VB.Frame fraDocUpload 
               Height          =   4080
               Left            =   2100
               TabIndex        =   48
               Top             =   600
               Width           =   10335
               Begin VB.TextBox txt_fileTitle 
                  Height          =   345
                  Left            =   2055
                  MaxLength       =   50
                  TabIndex        =   52
                  Top             =   1335
                  Width           =   8100
               End
               Begin VB.CommandButton cmd_File 
                  Caption         =   "..."
                  Height          =   345
                  Left            =   9765
                  TabIndex        =   54
                  Top             =   1830
                  Width           =   375
               End
               Begin VB.TextBox txt_filePath 
                  Height          =   345
                  Left            =   2055
                  Locked          =   -1  'True
                  MaxLength       =   1024
                  TabIndex        =   53
                  TabStop         =   0   'False
                  Top             =   1845
                  Width           =   7635
               End
               Begin VB.TextBox txt_fileDesc 
                  Height          =   1650
                  Left            =   2040
                  MaxLength       =   500
                  MultiLine       =   -1  'True
                  ScrollBars      =   2  'Vertical
                  TabIndex        =   55
                  Top             =   2310
                  Width           =   8100
               End
               Begin VB.TextBox txt_nodeDesc 
                  BeginProperty Font 
                     Name            =   "MS Sans Serif"
                     Size            =   8.25
                     Charset         =   0
                     Weight          =   700
                     Underline       =   0   'False
                     Italic          =   0   'False
                     Strikethrough   =   0   'False
                  EndProperty
                  Height          =   345
                  Left            =   2100
                  Locked          =   -1  'True
                  MaxLength       =   128
                  TabIndex        =   49
                  TabStop         =   0   'False
                  Top             =   255
                  Width           =   8100
               End
               Begin VB.TextBox txt_fileID 
                  Height          =   345
                  Left            =   8655
                  Locked          =   -1  'True
                  MaxLength       =   128
                  TabIndex        =   51
                  TabStop         =   0   'False
                  Top             =   855
                  Width           =   1530
               End
               Begin VB.TextBox txt_fileName 
                  Height          =   345
                  Left            =   2055
                  Locked          =   -1  'True
                  MaxLength       =   128
                  TabIndex        =   50
                  TabStop         =   0   'False
                  Top             =   870
                  Width           =   4740
               End
               Begin VB.TextBox txt_nodeID 
                  BeginProperty Font 
                     Name            =   "MS Sans Serif"
                     Size            =   8.25
                     Charset         =   0
                     Weight          =   700
                     Underline       =   0   'False
                     Italic          =   0   'False
                     Strikethrough   =   0   'False
                  EndProperty
                  Height          =   345
                  Left            =   1410
                  Locked          =   -1  'True
                  MaxLength       =   128
                  TabIndex        =   65
                  Top             =   255
                  Visible         =   0   'False
                  Width           =   585
               End
               Begin VB.TextBox txt_fileZipID 
                  Height          =   345
                  Left            =   7395
                  Locked          =   -1  'True
                  MaxLength       =   128
                  TabIndex        =   64
                  Top             =   825
                  Visible         =   0   'False
                  Width           =   420
               End
               Begin MSComDlg.CommonDialog dlg_Common 
                  Left            =   60
                  Top             =   45
                  _ExtentX        =   847
                  _ExtentY        =   847
                  _Version        =   393216
               End
               Begin VB.Label lbl_fileTitle 
                  Caption         =   "#File 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            =   135
                  TabIndex        =   71
                  Tag             =   "lbl_fileTitle"
                  Top             =   1410
                  Width           =   1830
               End
               Begin VB.Label lbl_filePath 
                  Caption         =   "#File path"
                  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            =   135
                  TabIndex        =   70
                  Tag             =   "lbl_filePath"
                  Top             =   1905
                  Width           =   1830
               End
               Begin VB.Label lbl_fileDesc 
                  Caption         =   "#Description"
                  Height          =   255
                  Left            =   105
                  TabIndex        =   69
                  Tag             =   "lbl_fileDesc"
                  Top             =   2325
                  Width           =   1830
               End
               Begin VB.Label lbl_fileNode 
                  Caption         =   "#Tree node"
                  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            =   150
                  TabIndex        =   68
                  Tag             =   "lbl_fileNode"
                  Top             =   270
                  Width           =   1830
               End
               Begin VB.Label lbl_fileID 
                  Alignment       =   1  'Right Justify
                  Caption         =   "#File ID"
                  Height          =   255
                  Left            =   7005
                  TabIndex        =   67
                  Tag             =   "lbl_fileID"
                  Top             =   915
                  Width           =   1545
               End
               Begin VB.Line Line1 
                  X1              =   135
                  X2              =   10200
                  Y1              =   690
                  Y2              =   690
               End
               Begin VB.Label lbl_fileName 
                  Caption         =   "#File name"
                  BeginProperty Font 
                     Name            =   "MS Sans Serif"
                     Size            =   8.25
                     Charset         =   0
                     Weight          =   700
                     Underline       =   0   'False
                     Italic          =   0   'False
                     Strikethrough   =   0   'False
                  EndProperty
                  Height          =   255
                  Left            =   150
                  TabIndex        =   66
                  Tag             =   "lbl_fileName"
                  Top             =   885
                  Width           =   1830
               End
            End
            Begin Project1.ArmTreeView trw_doc 
               Height          =   4545
               Left            =   150
               TabIndex        =   45
               Top             =   270
               Width           =   4365
               _ExtentX        =   7699
               _ExtentY        =   8017
            End
            Begin Project1.ArmGrid grd_doc 
               Height          =   3630
               Left            =   4890
               TabIndex        =   46
               TabStop         =   0   'False
               Tag             =   "grd_Quote"
               Top             =   270
               Width           =   5505
               _ExtentX        =   9710
               _ExtentY        =   6403
            End
            Begin Project1.ToolBr pbDoc 
               Height          =   4920
               Left            =   12630
               TabIndex        =   47
               Top             =   180
               Width           =   570
               _ExtentX        =   1005
               _ExtentY        =   9155
            End
         End
         Begin VB.TextBox txt_Revision 
            Height          =   345
            Left            =   765
            TabIndex        =   102
            TabStop         =   0   'False
            Top             =   1245
            Visible         =   0   'False
            Width           =   615
         End
         Begin VB.TextBox txt_QuoteRef 
            Height          =   345
            Left            =   720
            TabIndex        =   101
            TabStop         =   0   'False
            Top             =   870
            Visible         =   0   'False
            Width           =   615
         End
         Begin VB.TextBox txt_comment 
            Height          =   750
            Left            =   1620
            MaxLength       =   5000
            MultiLine       =   -1  'True
            ScrollBars      =   2  'Vertical
            TabIndex        =   5
            Top             =   1035
            Width           =   8445
         End
         Begin VB.TextBox txt_SP_Desc 
            Height          =   345
            Left            =   1620
            TabIndex        =   1
            TabStop         =   0   'False
            Top             =   195
            Width           =   8445
         End
         Begin VB.Frame fraSubItemMain 
            Height          =   5565
            Index           =   0
            Left            =   510
            TabIndex        =   20
            Tag             =   "ITEMS"
            Top             =   2655
            Width           =   14145
            Begin VB.Frame fra_Detail 
               Appearance      =   0  'Flat
               BeginProperty Font 
                  Name            =   "Arial"
                  Size            =   8.25
                  Charset         =   238
                  Weight          =   700
                  Underline       =   0   'False
                  Italic          =   0   'False
                  Strikethrough   =   0   'False
               EndProperty
               ForeColor       =   &H80000008&
               Height          =   1095
               Left            =   45
               TabIndex        =   21
               Tag             =   "fra_STD"
               Top             =   195
               Width           =   13695
               Begin VB.TextBox txt_PrimeMarg 
                  Alignment       =   1  'Right Justify
                  BackColor       =   &H00C0FFFF&
                  Height          =   345
                  Left            =   12000
                  Locked          =   -1  'True
                  TabIndex        =   29
                  TabStop         =   0   'False
                  Tag             =   "###0.00"
                  Text            =   "STD_Quote_PrimeMargin®©Num®©0.00"
                  Top             =   630
                  Width           =   1560
               End
               Begin VB.TextBox txt_ValueCHF 
                  Alignment       =   1  'Right Justify
                  BackColor       =   &H00C0FFFF&
                  Height          =   345
                  Left            =   7695
                  Locked          =   -1  'True
                  TabIndex        =   28
                  TabStop         =   0   'False
                  Text            =   "STD_Quote_Value_CHF®©Num®©0"
                  Top             =   630
                  Width           =   1560
               End
               Begin VB.TextBox txt_DB 
                  Alignment       =   1  'Right Justify
                  Height          =   345
                  Left            =   5475
                  MaxLength       =   8
                  TabIndex        =   27
                  Text            =   "1000"
                  Top             =   630
                  Width           =   795
               End
               Begin VB.TextBox txt_ValueLC 
                  Alignment       =   1  'Right Justify
                  Height          =   345
                  Left            =   3195
                  MaxLength       =   10
                  TabIndex        =   26
                  Text            =   "99,999,999"
                  Top             =   630
                  Width           =   1095
               End
               Begin VB.TextBox txt_Area 
                  Alignment       =   1  'Right Justify
                  Height          =   345
                  Left            =   9480
                  MaxLength       =   9
                  TabIndex        =   24
                  Text            =   "9,999,999"
                  Top             =   225
                  Width           =   1065
               End
               Begin Project1.ArmCombobox cbo_System 
                  Height          =   345
                  Left            =   5490
                  TabIndex        =   23
                  Top             =   225
                  Width           =   2505
                  _ExtentX        =   4419
                  _ExtentY        =   609
               End
               Begin Project1.ArmCombobox cbo_UM 
                  Height          =   345
                  Left            =   11085
                  TabIndex        =   25
                  Top             =   225
                  Width           =   2475
                  _ExtentX        =   4366
                  _ExtentY        =   609
               End
               Begin Project1.ArmCombobox cbo_SQD_Type 
                  Height          =   345
                  Left            =   1230
                  TabIndex        =   22
                  Top             =   225
                  Width           =   3060
                  _ExtentX        =   5398
                  _ExtentY        =   609
               End
               Begin VB.Label lbl_label 
                  Alignment       =   1  'Right Justify
                  Caption         =   "#Prime margin"
                  Height          =   225
                  Index           =   14
                  Left            =   9615
                  TabIndex        =   85
                  Tag             =   "lbl_PrimeMargin"
                  Top             =   720
                  Width           =   2325
               End
               Begin VB.Label lbl_label 
                  Alignment       =   1  'Right Justify
                  Caption         =   "#Value CHF"
                  Height          =   225
                  Index           =   15
                  Left            =   6360
                  TabIndex        =   84
                  Tag             =   "lbl_ValueCHF"
                  Top             =   720
                  Width           =   1245
               End
               Begin VB.Label lbl_label 
                  Alignment       =   1  'Right Justify
                  Caption         =   "#DB %"
                  Height          =   225
                  Index           =   16
                  Left            =   4305
                  TabIndex        =   83
                  Tag             =   "lbl_DB"
                  Top             =   720
                  Width           =   1095
               End
               Begin VB.Label lbl_label 
                  Caption         =   "#Value quotation currency"
                  Height          =   225
                  Index           =   17
                  Left            =   90
                  TabIndex        =   82
                  Tag             =   "lbl_ValueLC"
                  Top             =   720
                  Width           =   3060
               End
               Begin VB.Label lbl_label 
                  Alignment       =   2  'Center
                  Caption         =   "#in"
                  Height          =   225
                  Index           =   19
                  Left            =   10590
                  TabIndex        =   81
                  Tag             =   "lbl_in"
                  Top             =   285
                  Width           =   450
               End
               Begin VB.Label lbl_label 
                  Alignment       =   1  'Right Justify
                  Caption         =   "#Area"
                  Height          =   225
                  Index           =   21
                  Left            =   8100
                  TabIndex        =   80
                  Tag             =   "lbl_Area"
                  Top             =   285
                  Width           =   1305
               End
               Begin VB.Label lbl_label 
                  Alignment       =   1  'Right Justify
                  Caption         =   "#System"
                  Height          =   225
                  Index           =   23
                  Left            =   4350
                  TabIndex        =   79
                  Tag             =   "lbl_system"
                  Top             =   285
                  Width           =   1050
               End
               Begin VB.Label lbl_label 
                  Caption         =   "#Type"
                  Height          =   225
                  Index           =   18
                  Left            =   90
                  TabIndex        =   78
                  Tag             =   "lbl_Type"
                  Top             =   285
                  Width           =   1035
               End
            End
            Begin VB.Frame fra_TOT 
               Appearance      =   0  'Flat
               Caption         =   "#Total"
               BeginProperty Font 
                  Name            =   "Arial"
                  Size            =   8.25
                  Charset         =   238
                  Weight          =   700
                  Underline       =   0   'False
                  Italic          =   0   'False
                  Strikethrough   =   0   'False
               EndProperty
               ForeColor       =   &H80000008&
               Height          =   660
               Left            =   83
               TabIndex        =   32
               Tag             =   "fra_TOT"
               Top             =   4800
               Width           =   13935
               Begin VB.TextBox txt_TOT_ValueLC 
                  Alignment       =   1  'Right Justify
                  BackColor       =   &H00C0FFFF&
                  Height          =   345
                  Left            =   3195
                  TabIndex        =   33
                  TabStop         =   0   'False
                  Text            =   "TOT_Quote_Value_LC®©Num®©0"
                  Top             =   210
                  Width           =   1065
               End
               Begin VB.TextBox txt_TOT_DB 
                  Alignment       =   1  'Right Justify
                  BackColor       =   &H00C0FFFF&
                  Height          =   345
                  Left            =   5475
                  TabIndex        =   34
                  TabStop         =   0   'False
                  Text            =   "TOT_Quote_DB®©Num®©0"
                  Top             =   210
                  Width           =   795
               End
               Begin VB.TextBox txt_TOT_ValueCHF 
                  Alignment       =   1  'Right Justify
                  BackColor       =   &H00C0FFFF&
                  Height          =   345
                  Left            =   7695
                  TabIndex        =   35
                  TabStop         =   0   'False
                  Text            =   "TOT_Quote_Value_CHF®©Num®©0"
                  Top             =   210
                  Width           =   1650
               End
               Begin VB.TextBox txt_TOT_PrimeMarg 
                  Alignment       =   1  'Right Justify
                  BackColor       =   &H00C0FFFF&
                  Height          =   345
                  Left            =   12000
                  TabIndex        =   36
                  TabStop         =   0   'False
                  Tag             =   "###0.00"
                  Text            =   "TOT_Quote_PrimeMargin®©Num®©0.00"
                  Top             =   210
                  Width           =   1575
               End
               Begin VB.Label lbl_label 
                  Caption         =   "#Total value quotation currency"
                  Height          =   225
                  Index           =   61
                  Left            =   90
                  TabIndex        =   77
                  Tag             =   "lbl_TOT_ValueLC"
                  Top             =   285
                  Width           =   3060
               End
               Begin VB.Label lbl_label 
                  Alignment       =   1  'Right Justify
                  Caption         =   "#DB %"
                  Height          =   225
                  Index           =   38
                  Left            =   4305
                  TabIndex        =   76
                  Tag             =   "lbl_TOT_DB"
                  Top             =   285
                  Width           =   1095
               End
               Begin VB.Label lbl_label 
                  Alignment       =   1  'Right Justify
                  Caption         =   "#Value CHF"
                  Height          =   225
                  Index           =   39
                  Left            =   6360
                  TabIndex        =   75
                  Tag             =   "lbl_TOT_ValueCHF"
                  Top             =   285
                  Width           =   1245
               End
               Begin VB.Label lbl_label 
                  Alignment       =   1  'Right Justify
                  Caption         =   "#Prime margin"
                  Height          =   225
                  Index           =   40
                  Left            =   9615
                  TabIndex        =   74
                  Tag             =   "lbl_TOT_PrimeMargin"
                  Top             =   285
                  Width           =   2325
               End
            End
            Begin Project1.ArmGrid grd_Quote 
               Height          =   3105
               Left            =   90
               TabIndex        =   30
               TabStop         =   0   'False
               Tag             =   "grd_Quote"
               Top             =   1695
               Width           =   13260
               _ExtentX        =   23389
               _ExtentY        =   5477
            End
            Begin Project1.ToolBr pbSubitem 
               Height          =   4920
               Left            =   13455
               TabIndex        =   31
               Top             =   195
               Width           =   570
               _ExtentX        =   1005
               _ExtentY        =   9155
            End
         End
         Begin VB.TextBox txt_Quot_ID 
            Height          =   345
            Left            =   735
            TabIndex        =   73
            TabStop         =   0   'False
            Top             =   435
            Visible         =   0   'False
            Width           =   615
         End
         Begin VB.Frame fra_include 
            Caption         =   "#Include"
            BeginProperty Font 
               Name            =   "Arial"
               Size            =   8.25
               Charset         =   238
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   720
            Left            =   4770
            TabIndex        =   11
            Tag             =   "fra_include"
            Top             =   1905
            Width           =   2625
            Begin VB.OptionButton opt_include 
               Caption         =   "#Multiple"
               Height          =   195
               Index           =   1
               Left            =   1320
               TabIndex        =   13
               Tag             =   "2®©Incl_Multiple"
               Top             =   315
               Width           =   1095
            End
            Begin VB.OptionButton opt_include 
               Caption         =   "#Active"
               Height          =   195
               Index           =   0
               Left            =   180
               TabIndex        =   12
               Tag             =   "1®©Incl_Active"
               Top             =   315
               Width           =   1095
            End
         End
         Begin VB.Frame fra_type 
            Caption         =   "#Type"
            BeginProperty Font 
               Name            =   "Arial"
               Size            =   8.25
               Charset         =   238
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   720
            Left            =   150
            TabIndex        =   8
            Tag             =   "fra_type"
            Top             =   1905
            Width           =   4485
            Begin VB.OptionButton opt_type 
               Caption         =   "#Material and installation"
               Height          =   255
               Index           =   1
               Left            =   1845
               TabIndex        =   10
               Tag             =   "2®©Type_mat_inst"
               Top             =   315
               Width           =   2505
            End
            Begin VB.OptionButton opt_type 
               Caption         =   "#Material"
               Height          =   255
               Index           =   0
               Left            =   135
               TabIndex        =   9
               Tag             =   "1®©Type_mat"
               Top             =   315
               Value           =   -1  'True
               Width           =   1650
            End
         End
         Begin VB.TextBox txt_FreightCost 
            Alignment       =   1  'Right Justify
            Height          =   345
            Left            =   8895
            MaxLength       =   11
            TabIndex        =   14
            Text            =   "99,999,999"
            Top             =   1860
            Width           =   930
         End
         Begin VB.TextBox txt_FreightCostCHF 
            ForeColor       =   &H000000FF&
            Height          =   315
            Left            =   120
            TabIndex        =   72
            Text            =   "Quote_FRGHTCost_CHF®©Text"
            Top             =   1515
            Visible         =   0   'False
            Width           =   690
         End
         Begin VB.TextBox txt_SQT_Reference 
            Height          =   345
            Left            =   12075
            TabIndex        =   2
            TabStop         =   0   'False
            Top             =   210
            Width           =   2865
         End
         Begin Project1.A_calocx cal_ValidUntil 
            Height          =   345
            Left            =   13095
            TabIndex        =   16
            Top             =   1860
            Width           =   1845
            _ExtentX        =   3254
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_FreightCurr 
            Height          =   345
            Left            =   10410
            TabIndex        =   15
            Top             =   1860
            Width           =   1245
            _ExtentX        =   2196
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_realisation 
            Height          =   345
            Left            =   14145
            TabIndex        =   18
            Top             =   2265
            Visible         =   0   'False
            Width           =   795
            _ExtentX        =   1402
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_BO 
            Height          =   345
            Left            =   12075
            TabIndex        =   7
            Top             =   1455
            Width           =   2865
            _ExtentX        =   5054
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_Customer 
            Height          =   345
            Left            =   1620
            TabIndex        =   3
            Top             =   615
            Width           =   8445
            _ExtentX        =   14896
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_Status 
            Height          =   345
            Left            =   12075
            TabIndex        =   4
            TabStop         =   0   'False
            Top             =   615
            Width           =   2865
            _ExtentX        =   5054
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_currencies 
            Height          =   345
            Left            =   10410
            TabIndex        =   17
            Top             =   2265
            Width           =   1245
            _ExtentX        =   2196
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_SalesRep 
            Height          =   345
            Left            =   12075
            TabIndex        =   6
            Top             =   1035
            Width           =   2865
            _ExtentX        =   5054
            _ExtentY        =   609
         End
         Begin MSComctlLib.TabStrip tbs_quoteDetail 
            Height          =   5355
            Left            =   90
            TabIndex        =   19
            Top             =   2715
            Width           =   405
            _ExtentX        =   714
            _ExtentY        =   9446
            TabWidthStyle   =   2
            MultiRow        =   -1  'True
            Placement       =   2
            TabMinWidth     =   1235
            _Version        =   393216
            BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
               NumTabs         =   2
               BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
                  Caption         =   "#Items"
                  Key             =   "ITEMS"
                  Object.Tag             =   "ITEMS"
                  ImageVarType    =   2
               EndProperty
               BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
                  Caption         =   "#Documents"
                  Key             =   "DOCS"
                  Object.Tag             =   "DOCS"
                  ImageVarType    =   2
               EndProperty
            EndProperty
         End
         Begin VB.Label lbl_label 
            Caption         =   "#Sales rep"
            BeginProperty Font 
               Name            =   "Arial"
               Size            =   8.25
               Charset         =   238
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   225
            Index           =   4
            Left            =   10170
            TabIndex        =   98
            Tag             =   "lbl_SalesRep"
            Top             =   1080
            Width           =   1875
         End
         Begin VB.Label lbl_label 
            Caption         =   "#Customer"
            BeginProperty Font 
               Name            =   "Arial"
               Size            =   8.25
               Charset         =   238
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   255
            Index           =   1
            Left            =   120
            TabIndex        =   97
            Tag             =   "lbl_customer"
            Top             =   675
            Width           =   1470
         End
         Begin VB.Label lbl_label 
            Caption         =   "#Comment"
            Height          =   255
            Index           =   2
            Left            =   120
            TabIndex        =   96
            Tag             =   "lbl_comment"
            Top             =   1050
            Width           =   1470
         End
         Begin VB.Label lbl_label 
            Caption         =   "#Project"
            Height          =   255
            Index           =   0
            Left            =   120
            TabIndex        =   95
            Tag             =   "lbl_Project"
            Top             =   255
            Width           =   1470
         End
         Begin VB.Label lbl_label 
            Caption         =   "#Status"
            BeginProperty Font 
               Name            =   "Arial"
               Size            =   8.25
               Charset         =   238
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   270
            Index           =   5
            Left            =   10170
            TabIndex        =   94
            Tag             =   "lbl_Status"
            Top             =   660
            Width           =   1875
         End
         Begin VB.Label lbl_label 
            Alignment       =   1  'Right Justify
            Caption         =   "#Quote currency"
            BeginProperty Font 
               Name            =   "Arial"
               Size            =   8.25
               Charset         =   238
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   255
            Index           =   20
            Left            =   8070
            TabIndex        =   93
            Tag             =   "lbl_Quote_Currency"
            Top             =   2325
            Width           =   1935
         End
         Begin VB.Label lbl_label 
            Caption         =   "#Id"
            BeginProperty Font 
               Name            =   "Arial"
               Size            =   8.25
               Charset         =   238
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   255
            Index           =   22
            Left            =   10170
            TabIndex        =   92
            Tag             =   "lbl_SQT_ID"
            Top             =   255
            Width           =   1875
         End
         Begin VB.Label lbl_label 
            Caption         =   "#Back office person"
            BeginProperty Font 
               Name            =   "Arial"
               Size            =   8.25
               Charset         =   238
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   225
            Index           =   3
            Left            =   10170
            TabIndex        =   91
            Tag             =   "lbl_BO"
            Top             =   1485
            Width           =   1875
         End
         Begin VB.Label lbl_label 
            Alignment       =   1  'Right Justify
            Caption         =   "#Realisation %"
            BeginProperty Font 
               Name            =   "Arial"
               Size            =   8.25
               Charset         =   238
               Weight          =   400
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   225
            Index           =   6
            Left            =   11775
            TabIndex        =   90
            Tag             =   "lbl_Realisation"
            Top             =   2355
            Visible         =   0   'False
            Width           =   2055
         End
         Begin VB.Label lbl_label 
            Alignment       =   1  'Right Justify
            Caption         =   "#in"
            Height          =   225
            Index           =   7
            Left            =   9840
            TabIndex        =   89
            Tag             =   "lbl_Freight_in"
            Top             =   1935
            Width           =   390
         End
         Begin VB.Label lbl_label 
            Alignment       =   1  'Right Justify
            Caption         =   "#Freight cost"
            Height          =   225
            Index           =   8
            Left            =   7515
            TabIndex        =   88
            Tag             =   "lbl_FreightCostLC"
            Top             =   1935
            Width           =   1260
         End
         Begin VB.Label lbl_label 
            Caption         =   "#Valid until"
            BeginProperty Font 
               Name            =   "Arial"
               Size            =   8.25
               Charset         =   238
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   225
            Index           =   9
            Left            =   11805
            TabIndex        =   87
            Tag             =   "lbl_ValidUntil"
            Top             =   1935
            Width           =   1110
         End
         Begin VB.Label lbl_label 
            Caption         =   "#Documents"
            Height          =   255
            Index           =   24
            Left            =   150
            TabIndex        =   86
            Tag             =   "DOCS"
            Top             =   1500
            Visible         =   0   'False
            Width           =   585
         End
      End
      Begin VB.Frame fraItemBottom 
         Height          =   585
         Left            =   1440
         TabIndex        =   37
         Top             =   9720
         Width           =   13950
         Begin VB.TextBox txt_updatedBy 
            Enabled         =   0   'False
            Height          =   330
            Left            =   8595
            TabIndex        =   41
            TabStop         =   0   'False
            Top             =   165
            Width           =   1875
         End
         Begin VB.TextBox txt_createdBy 
            Enabled         =   0   'False
            Height          =   330
            Left            =   3375
            TabIndex        =   38
            TabStop         =   0   'False
            Top             =   150
            Width           =   1875
         End
         Begin VB.TextBox txt_dateEntered 
            Alignment       =   2  'Center
            Enabled         =   0   'False
            Height          =   330
            Left            =   1275
            TabIndex        =   39
            TabStop         =   0   'False
            Top             =   165
            Width           =   1100
         End
         Begin VB.TextBox txt_dateUpdated 
            Alignment       =   2  'Center
            Enabled         =   0   'False
            Height          =   330
            Left            =   6495
            TabIndex        =   40
            TabStop         =   0   'False
            Top             =   165
            Width           =   1100
         End
         Begin VB.CheckBox chk_DropFlag 
            Alignment       =   1  'Right Justify
            Caption         =   "#Drop flag"
            Enabled         =   0   'False
            Height          =   255
            Left            =   10590
            TabIndex        =   42
            TabStop         =   0   'False
            Tag             =   "chk_DropFlag"
            Top             =   240
            Width           =   1845
         End
         Begin VB.TextBox txt_DropDate 
            Alignment       =   2  'Center
            Enabled         =   0   'False
            Height          =   330
            Left            =   12480
            Locked          =   -1  'True
            TabIndex        =   43
            TabStop         =   0   'False
            Top             =   150
            Width           =   1400
         End
         Begin VB.Label lbl_label 
            Caption         =   "#By"
            Enabled         =   0   'False
            Height          =   255
            Index           =   13
            Left            =   7635
            TabIndex        =   63
            Tag             =   "lbl_updatedBy"
            Top             =   210
            Width           =   900
         End
         Begin VB.Label lbl_label 
            Caption         =   "#By"
            Enabled         =   0   'False
            Height          =   255
            Index           =   12
            Left            =   2400
            TabIndex        =   62
            Tag             =   "lbl_createdBy"
            Top             =   210
            Width           =   900
         End
         Begin VB.Label lbl_label 
            Caption         =   "#Last Updated"
            Enabled         =   0   'False
            Height          =   255
            Index           =   11
            Left            =   5295
            TabIndex        =   61
            Tag             =   "lbl_lastUpdated"
            Top             =   210
            Width           =   1140
         End
         Begin VB.Label lbl_label 
            Caption         =   "#Date Entered"
            Enabled         =   0   'False
            Height          =   255
            Index           =   10
            Left            =   75
            TabIndex        =   60
            Tag             =   "lbl_dateEntered"
            Top             =   210
            Width           =   1140
         End
      End
      Begin Project1.ToolBr pbitem 
         Height          =   855
         Left            =   120
         TabIndex        =   99
         Top             =   180
         Width           =   1695
         _ExtentX        =   2990
         _ExtentY        =   1508
      End
      Begin MSComctlLib.TabStrip tbsEmbedded 
         Height          =   375
         Left            =   120
         TabIndex        =   100
         Top             =   9360
         Width           =   1695
         _ExtentX        =   2990
         _ExtentY        =   661
         Placement       =   1
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   1
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
   End
   Begin VB.Frame fraList 
      Height          =   4935
      Left            =   15
      TabIndex        =   56
      Top             =   0
      Width           =   9015
      Begin Project1.ArmGrid grdlst 
         Height          =   2775
         Left            =   240
         TabIndex        =   57
         Tag             =   "grdlst"
         Top             =   1200
         Width           =   5175
         _ExtentX        =   9128
         _ExtentY        =   4895
      End
      Begin Project1.ToolBr pblst 
         Height          =   495
         Left            =   240
         TabIndex        =   58
         Top             =   240
         Width           =   2955
         _ExtentX        =   5212
         _ExtentY        =   1296
      End
   End
End
Attribute VB_Name = "CapSOMQuote"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

'what is new
'2.6.4 bugfix: Customer cbo was enabled in list mode (JN)

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

Private Const SIFYB_CM_ERROR_MESSAGE = 2400                 ' const for base of error messages ids

Private Enum ErrMsg
    ErrMsgNone = 0
    ErrMsgNoPrinter = 135
    ErrMsgAddMemos_Q = 49
    ErrMsgMandatoryAreEmpty = SIFYB_CM_ERROR_MESSAGE + 1
    WarMsgDoYouRemove = SIFYB_CM_ERROR_MESSAGE + 2
    ErrMsgIConcurency = SIFYB_CM_ERROR_MESSAGE + 3
    WarMsgSelectRow = SIFYB_CM_ERROR_MESSAGE + 4
    ErrMsgNumericRequired = SIFYB_CM_ERROR_MESSAGE + 5
    WarMsgItemExists = SIFYB_CM_ERROR_MESSAGE + 6
    ErrMsgAtLeastOneItemChecked = SIFYB_CM_ERROR_MESSAGE + 7
    ErrMsgFileDoesntExists = SIFYB_CM_ERROR_MESSAGE + 8
    ErrMsgBadValue = SIFYB_CM_ERROR_MESSAGE + 9
    ErrMsgNoValidRateExists = SIFYB_CM_ERROR_MESSAGE + 10
    ErrMsgTotalClaimsTooLarge = SIFYB_CM_ERROR_MESSAGE + 11
    ErrMsgCannotDeleteRecord = SIFYB_CM_ERROR_MESSAGE + 12
    ErrMsgOnlyNumericIsValid = SIFYB_CM_ERROR_MESSAGE + 13
    ErrMsgRecordDeleted = SIFYB_CM_ERROR_MESSAGE + 14
    ErrMsgMandatoryByFilter = SIFYB_CM_ERROR_MESSAGE + 15
    WarMsgItemNotFound = SIFYB_CM_ERROR_MESSAGE + 16
    WarMsgResetFilters = SIFYB_CM_ERROR_MESSAGE + 17
    WarNodeNotSelected = 2146
    WarNoRecordData = 2147
    WarMsgNoASProject = SIFYB_CM_ERROR_MESSAGE + 28
    WarMsgCustomer = SIFYB_CM_ERROR_MESSAGE + 29
    WarMsgNoAMCProject = SIFYB_CM_ERROR_MESSAGE + 30
    WarMsgNoProjectStatus = SIFYB_CM_ERROR_MESSAGE + 31
End Enum

Private Const SCREEN_NAME As String = "CapSOMQuote"
Private Const C_APPNAME         As String = "CAPSOMQUOTE" ' for error log
Private Const CL_COLOR_ENABLED  As Long = &H80000005
Private Const CL_COLOR_DISABLED As Long = &H8000000F
Private Const CL_COLOR_Expired  As Long = 10066414          ' # EE9999
Private Const CL_COLOR_Requested    As Long = 10066414      ' # EE9999
Private Const CL_COLOR_Delivered    As Long = 10088089      ' # 99EE99

Private Const C_ERROR_FILES_DIR As String = "Bad_Files"

' SOM_Quote copy - begin
Private Const LOCALE_USER_DEFAULT = &H400
Private ms_DecimalSeparator  As String
Private ms_ThousandSeparator As String
Private ml_useGrouping As VbTriState
Private Declare Function GetLocaleInfo Lib "kernel32" Alias "GetLocaleInfoA" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long
'Private Declare Function GetSystemDefaultLCID Lib "kernel32" () As Long
Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long

Private Const LOCALE_SDECIMAL = &HE ' Decimal separator
Private Const LOCALE_STHOUSAND = &HF ' Thousand separator
' SOM_Quote copy - end

'******** Curseur de connexion
#If LIVE = 1 Then
    Dim mo_ArmDb As Object
#Else
    Dim mo_ArmDb As ARMSYSCOMLib.ArmDb
#End If
#If LIVE = 1 Then
    Dim mo_FSO As Object
#Else
    Dim mo_FSO As Scripting.FileSystemObject
#End If

#If ENV = LIVE Then
    Dim mo_ZIP As Object
#Else
    Dim mo_ZIP As ARMSYSCOMLib.ArmZip
#End If

Private Const SEP1 As String = "®"
Private Const SEP2 As String = "©"

Private mb_Created As Boolean
Dim mb_use_framework_connection As Boolean
Private ms_ConnectString As String
Private ms_UID As String
Private ml_U_code As Long
Private mb_FileChanged As Boolean
Private ms_SR_Code As String                ' sales rep (customer type) or a project

Private mt_CstValues As Type_CstValues         ' Structure which contains constants value
Private mi_DisplayMode As Variant       ' Current display mode
Private ml_DisplayModeSubItem As Long   ' Current display mode for subitem
Private mi_DisplayModeDoc As Long       ' Current display mode for document tab
Private mi_OldDisplayMode As Variant    ' Old display mode, need for know parameters
Private mi_EmbeddedIn As Integer        ' Indicates the tag  of the component which embed this component
Private mi_EmbedTag As Integer          ' Indicates the tag of the last component embedded
Private mi_CptTag As Integer            ' Tag of the component type
Private mb_Root As Boolean              ' Indicates if the component is the focus of the user

'******** Clé en cours (enreg. en cours de visu ou modif ou delete
Private m_CurrentKey1 As String
Private m_CurrentKey2 As String
Private m_CurrentKey3 As String

Private m_Language As String

'******** iConccurency of current Record
Private p_iCon As Integer
Private p_dociCon As Long                       ' iConc for opened document
Private prj_iConc As Long                       ' iConc of project - valid after ViewInitFields and AddInitFields
Private m_projectStatus As Long

'******** Type de l'objet (1=Normal, liste longue; 2=Liste courte)
Private mi_TypeList As Integer
Private mi_TypeParam As Integer

Private m_Project As String 'For the property .Project, display in ShortList
Private m_Contact As String 'For the property .Contact, display in ShortList
Private m_Customer As String 'For the property .Customer, display in ShortList
Private m_Action As String 'For the property .Action, display in ShortList
Private m_Product As String 'For the property .Product, display in ShortList
Private mb_EmbeddedIsDropped As Boolean '298.2

'Ask the application to change the size of component
Public Event SwitchToView(ByVal li_View As Integer)
' Ask the application to simulate encapsulation of a component by resizing it and push it to front
Public Event Catch(ByVal li_TagEmbedded As Integer, ByVal ls_Param As String)
' Ask the application to release the encapsulation : hide the component embedded
Public Event Release()
Public Event quit()
Public Event HideGrid(AParentID As Integer)
Public Event Updated() ' Indicates if user update date when it's embedded

Public Event ProjectStatusChanged(ByVal as_project As String, ByVal ae_newStatus As Variant)

Private p_DefaultValues(MAX_VALUE) As DefaultValue
Private p_DefaultValuesCount As Integer
Private p_DefaultValuesLoaded As Boolean
Dim ms_DocumentServerDir As String
Dim mo_WshNetwork As Object
Dim msa_MapNetworkDrive() As String
Dim ms_NetworkPath As String
Dim ms_NetworkDrive As String
Dim ms_NetworkUser As String
Dim ms_NetworkPassword As String
Dim mb_AppCreatedMappedDrive As Boolean



Private mb_InternalInit As Boolean

Private Const VALUE_FORMAT As String = "###0.00"
Private Const MONEY_FORMAT As String = "###0.00"

Private Enum eQuoteStatus
    qsWon = 1
    qsLost = 2
    qsDuplicated = 3
    qsCanceled = 4
    qsActive = 5
End Enum

Private Enum eQuoteType
    qtStandard = 1
    qtSemi = 2
    qtCustom = 3
End Enum

Public Property Let U_Code(ByVal al_U_Code As Long)
On Error GoTo ErrorHandler
    ml_U_code = al_U_Code
    Exit Property
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".Property Set ArmDb")
    ' terminate app
    End
End Property

Public Property Set ArmDb(ByRef ao_local_connection As Object)
On Error GoTo ErrorHandler
    If Not (ao_local_connection Is Nothing) Then
        Set mo_ArmDb = ao_local_connection
        mb_use_framework_connection = True
        
       
        Set grdlst.ArmDb = mo_ArmDb
        Set grd_quote.ArmDb = mo_ArmDb
        Set grd_doc.ArmDb = mo_ArmDb
        
        Set trw_doc.ArmDb = mo_ArmDb
        
        Set pblst.ArmDb = mo_ArmDb
        Set pbItem.ArmDb = mo_ArmDb
        Set pbSubitem.ArmDb = mo_ArmDb
        Set pbDoc.ArmDb = mo_ArmDb
        Set cbo_customer.ArmDb = mo_ArmDb
        Set cbo_System.ArmDb = mo_ArmDb
        Set cbo_SQD_Type.ArmDb = mo_ArmDb
        Set cbo_UM.ArmDb = mo_ArmDb
        Set cbo_SalesRep.ArmDb = mo_ArmDb
        Set cbo_BO.ArmDb = mo_ArmDb
        Set cbo_Status.ArmDb = mo_ArmDb
        Set cbo_currencies.ArmDb = mo_ArmDb
        Set cbo_FreightCurr.ArmDb = mo_ArmDb
        Set cbo_realisation.ArmDb = mo_ArmDb
    End If
    Exit Property
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".Property Set ArmDb")
    ' terminate app
    End
End Property

Property Let ConnectString(as_ConnectString As String)
On Error GoTo errHandler
    ms_UID = ConnectionStringValidation(as_ConnectString)
    If ms_UID = "" Then Call Err.Raise(InvalidArgument, "", "Invalid connectionString:" & as_ConnectString)
    
    ms_ConnectString = as_ConnectString
    
    'Affectation aux objets
    grdlst.ConnectString = ms_ConnectString
    grd_quote.ConnectString = ms_ConnectString
    grd_doc.ConnectString = ms_ConnectString
    trw_doc.ConnectString = ms_ConnectString
    pblst.ConnectString = ms_ConnectString
    pbItem.ConnectString = ms_ConnectString
    pbSubitem.ConnectString = ms_ConnectString
    pbDoc.ConnectString = ms_ConnectString
    cbo_customer.ConnectString = ms_ConnectString
    cbo_System.ConnectString = ms_ConnectString
    cbo_SQD_Type.ConnectString = ms_ConnectString
    cbo_UM.ConnectString = ms_ConnectString
    cbo_SalesRep.ConnectString = ms_ConnectString
    cbo_BO.ConnectString = ms_ConnectString
    cbo_Status.ConnectString = ms_ConnectString
    Exit Property
errHandler:
    Call ErrorMessage(Extender.Name & ".Property Let ConnectString")
    ' terminate app
    End
End Property

Public Property Let Language(as_Language As String)
On Error GoTo errHandler
    m_Language = as_Language
    
    pbItem.Language = m_Language
    pbSubitem.Language = m_Language
    pbDoc.Language = m_Language
    pblst.Language = m_Language
    cal_ValidUntil.Language = m_Language
    Exit Property
errHandler:
    Call ErrorMessage(Extender.Name & ".Property Let Language")
    ' terminate app
    End
End Property

Public Sub GoToTab1()
On Error GoTo Trace_Err
    
    If UserControl.tbsEmbedded.Tabs.Count > 0 Then
        UserControl.tbsEmbedded.Tabs(1).Selected = True
    End If
    
    Exit Sub
Trace_Err:
    Call ErrorMessage(Extender.Name & ".GoToTab1()")
End Sub

Private Sub Add_Resize()
On Error GoTo Trace_Err
    
    With UserControl
        
        .fraItem.Left = mt_CstValues.Frm_Spacing
        .fraItem.Top = mt_CstValues.Frm_Spacing
        .fraItem.Width = .Width - .fraItem.Left - (2 * mt_CstValues.Frm_Spacing)
        .fraItem.Height = .Height - .fraItem.Top - (2 * mt_CstValues.Frm_Spacing)
        
        .pbItem.Height = mt_CstValues.View_ToolBar_Height
        .pbItem.Top = mt_CstValues.Frm_Spacing * 4
        .pbItem.Left = mt_CstValues.Frm_Spacing
        .pbItem.Width = .fraItem.Width - .pbItem.Left - (2 * mt_CstValues.Frm_Spacing)
        .pbItem.Refresh
        
        .tbsEmbedded.Visible = False
        
        .fraItemTop.Left = mt_CstValues.Frm_Spacing
        .fraItemTop.Top = mt_CstValues.Frm_Spacing + .pbItem.Top + .pbItem.Height
        .fraItemTop.Width = .fraItem.Width - .fraItemTop.Left - mt_CstValues.Frm_Spacing
        
        .tbsEmbedded.Top = .fraItem.Height - .tbsEmbedded.Height - mt_CstValues.Frm_Spacing
        .tbsEmbedded.Left = mt_CstValues.Frm_Spacing
        .tbsEmbedded.Width = .fraItem.Width - .tbsEmbedded.Left - mt_CstValues.Frm_Spacing
        
        .fraItemBottom.Width = .fraItem.Width - .tbsEmbedded.Left - mt_CstValues.Frm_Spacing
        '.fraItemBottom.Height = mt_CstValues.Cpt_View_Emb_Height
        .fraItemBottom.Top = .fraItem.Height - .fraItemBottom.Height - mt_CstValues.Frm_Spacing
        .fraItemBottom.Left = mt_CstValues.Frm_Spacing
        
        .fraItem.Visible = True
        .fraItemTop.BorderStyle = 0
        .fraItemBottom.Visible = True
        .fraItemBottom.BorderStyle = 0
        
    End With

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".Add_Resize()")
End Sub

Private Sub AddDisplay()
On Error GoTo Trace_Err
    
    RaiseEvent SwitchToView(mt_CstValues.View_Full)
    
    'If the component was on short list, it does appear now in long list
    InitControl 4
    
    BlankFields
    Add_Enablecontrols
    Add_Resize
    AddInitFields
    
    Call SwapToDisplayModeSubitem(mt_CstValues.DisplayMode_List)
    Call SwapToDisplayModeDoc(mt_CstValues.DisplayMode_List)
    
    cbo_customer.SetFocus
    
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".AddDisplay()")
End Sub

Private Sub Delete_Resize()
On Error GoTo Trace_Err
    With UserControl
        
        .fraItem.Left = mt_CstValues.Frm_Spacing
        .fraItem.Top = mt_CstValues.Frm_Spacing
        .fraItem.Width = .Width - .fraItem.Left - (2 * mt_CstValues.Frm_Spacing)
        .fraItem.Height = .Height - .fraItem.Top - (2 * mt_CstValues.Frm_Spacing)
        
        .pbItem.Height = mt_CstValues.View_ToolBar_Height
        .pbItem.Top = mt_CstValues.Frm_Spacing * 4
        .pbItem.Left = mt_CstValues.Frm_Spacing
        .pbItem.Width = .fraItem.Width - .pbItem.Left - (2 * mt_CstValues.Frm_Spacing)
        .pbItem.Refresh
        
        .tbsEmbedded.Visible = False
        
        .fraItemTop.Top = mt_CstValues.Frm_Spacing + .pbItem.Top + .pbItem.Height
        .fraItemTop.Left = mt_CstValues.Frm_Spacing
        .fraItemTop.Width = .fraItem.Width - .fraItemTop.Left - mt_CstValues.Frm_Spacing
        
        .tbsEmbedded.Top = .fraItem.Height - .tbsEmbedded.Height - mt_CstValues.Frm_Spacing
        .tbsEmbedded.Left = mt_CstValues.Frm_Spacing
        .tbsEmbedded.Width = .fraItem.Width - .tbsEmbedded.Left - mt_CstValues.Frm_Spacing
        
        .fraItemBottom.Width = .fraItem.Width - .tbsEmbedded.Left - mt_CstValues.Frm_Spacing
        '.fraItemBottom.Height = mt_CstValues.Cpt_View_Emb_Height
        .fraItemBottom.Top = .fraItem.Height - .fraItemBottom.Height - mt_CstValues.Frm_Spacing
        .fraItemBottom.Left = mt_CstValues.Frm_Spacing
        
        .fraItem.Visible = True
        .fraItemTop.Visible = True
        .fraItemBottom.Visible = True
        .fraItemTop.BorderStyle = 0
        .fraItemBottom.BorderStyle = 0
    End With
    
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".Delete_Resize()")
End Sub

Private Sub DeleteDisplay()
On Error GoTo Trace_Err
    
    RaiseEvent SwitchToView(mt_CstValues.View_Full)
    
    'If the component was on short list, it does appear now in long list
    InitControl 4
    
    BlankFields
    Delete_EnableControls
    Delete_Resize
    ViewInitFields
    Call SwapToDisplayModeSubitem(mt_CstValues.DisplayMode_List)
    Call SwapToDisplayModeDoc(mt_CstValues.DisplayMode_List)

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".DeleteDisplay()")
End Sub

Private Sub Delete_EnableControls()
On Error GoTo Trace_Err
    
    ControlsEnable UserControl.Controls, fraItemTop, False
    ControlsEnable UserControl.Controls, fraItemBottom, False
    
    txt_Comment.Enabled = True
    txt_Comment.Locked = True
    txt_Comment.BackColor = CL_COLOR_DISABLED
    
    pbSubitem.Enabled = True
    pbDoc.Enabled = True
    grd_quote.Enabled = True
    fraSubItemMain(0).Enabled = True
    fraSubItemMain(1).Enabled = True
    tbs_quoteDetail.Enabled = True

    
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".Delete_EnableControls()")
End Sub

Private Sub Update_Resize()
On Error GoTo Trace_Err
    
    With UserControl
    
        .fraItem.Left = mt_CstValues.Frm_Spacing
        .fraItem.Top = mt_CstValues.Frm_Spacing
        .fraItem.Width = .Width - .fraItem.Left - (2 * mt_CstValues.Frm_Spacing)
        .fraItem.Height = .Height - .fraItem.Top - (2 * mt_CstValues.Frm_Spacing)
        
        .pbItem.Height = mt_CstValues.View_ToolBar_Height
        .pbItem.Top = mt_CstValues.Frm_Spacing * 4
        .pbItem.Left = mt_CstValues.Frm_Spacing
        .pbItem.Width = .fraItem.Width - .pbItem.Left - (2 * mt_CstValues.Frm_Spacing)
        .pbItem.Refresh
        
        .fraItemTop.Left = mt_CstValues.Frm_Spacing
        .fraItemTop.Top = mt_CstValues.Frm_Spacing + .pbItem.Top + .pbItem.Height
        .fraItemTop.Width = .fraItem.Width - .fraItemTop.Left - mt_CstValues.Frm_Spacing
        
        .tbsEmbedded.Top = .fraItem.Height - .tbsEmbedded.Height - mt_CstValues.Frm_Spacing
        .tbsEmbedded.Left = mt_CstValues.Frm_Spacing
        .tbsEmbedded.Width = .fraItem.Width - .tbsEmbedded.Left - mt_CstValues.Frm_Spacing
        
        .fraItemBottom.Width = .fraItem.Width - .tbsEmbedded.Left - mt_CstValues.Frm_Spacing
        '.fraItemBottom.Height = mt_CstValues.Cpt_View_Emb_Height
        .fraItemBottom.Top = .fraItem.Height - .fraItemBottom.Height - mt_CstValues.Frm_Spacing
        .fraItemBottom.Left = mt_CstValues.Frm_Spacing
        
        .tbsEmbedded.Visible = False
        
        .fraItem.Visible = True
        .fraItemTop.BorderStyle = 0
        .fraItemBottom.Visible = True
        .fraItemBottom.BorderStyle = 0
    
    End With

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".Update_Resize()")
End Sub

Private Sub UpdateDisplay()
On Error GoTo Trace_Err
    
    RaiseEvent SwitchToView(mt_CstValues.View_Full)
    
    'If the component was on short list, it does appear now in long list
    InitControl 4
    
    If mi_OldDisplayMode <> mt_CstValues.DisplayMode_View Then BlankFields
    If mi_OldDisplayMode <> mt_CstValues.DisplayMode_View Then
        UpdateInitFields
    End If
    Update_EnableControls
    Update_Resize
    
    Call SwapToDisplayModeSubitem(mt_CstValues.DisplayMode_List)
    Call SwapToDisplayModeDoc(mt_CstValues.DisplayMode_List)
    If txt_Comment.Visible Then txt_Comment.SetFocus
    
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".UpdateDisplay()")
End Sub

Function RecordCheck() As Boolean
On Error GoTo Trace_Err
    RecordCheck = False
    
    ' iterate products on Quote if some product is after expiration
    If grd_quote.Rows = 0 Then
        Call ASC_SendMessage(mo_ArmDb, m_Language, 2148, "#Add product to Quote, please.")
        Set tbs_quoteDetail.SelectedItem = tbs_quoteDetail.Tabs("ITEMS")
        Exit Function
    End If
    
        ' 1. check mandatory
    If Not cbo_IsFilled(cbo_customer) Then
        Call ShowErrMessage(2120, lbl_Label(1).Caption)
        cbo_customer.SetFocus
        Exit Function
    End If

    If Not cbo_IsFilled(cbo_SalesRep) Then
        Call ShowErrMessage(2120, lbl_Label(4).Caption)
        cbo_SalesRep.SetFocus
        Exit Function
    End If

    If Not cbo_IsFilled(cbo_BO) Then
        Call ShowErrMessage(2120, lbl_Label(3).Caption)
        cbo_BO.SetFocus
        Exit Function
    End If

     If cal_ValidUntil.date_courte = "" Then
        Call ShowErrMessage(2120, lbl_Label(9).Caption)
        cal_ValidUntil.SetFocus
        Exit Function
    End If


    If Not cbo_IsFilled(cbo_currencies) Then
        Call ShowErrMessage(2120, lbl_Label(20).Caption)
        cbo_currencies.SetFocus
        Exit Function
    End If
    
'    If Not cbo_IsFilled(cbo_realisation) Then
'        Call ShowErrMessage(2120, lbl_Label(6).Caption)
'        cbo_realisation.SetFocus
'        Exit Function
'    End If
    
    If Not opt_IsFilled(opt_Type) Then
        Call ShowErrMessage(2120, fra_type.Caption)
        opt_Type(0).SetFocus
        opt_Type(0).Value = False
        Exit Function
    End If
    
    If Not opt_IsFilled(opt_include) Then
        Call ShowErrMessage(2120, fra_include.Caption)
        opt_include(0).SetFocus
        opt_include(0).Value = False
        Exit Function
    End If
    
    

    ' 2. check content
    If cbo_IsFilled(cbo_FreightCurr) Then
        If Not CheckNumericBeforeCalculation(txt_FreightCost, 8, 0, 1, 99999999) Then
            Exit Function
        End If
        
        If cbo_FreightCurr.SelectedItem.GetData(2) = 0 Then
            Call ShowErrMessage(3064, lbl_Label(8).Caption)
            cbo_FreightCurr.SetFocus
            Exit Function
        End If
    Else
        If txt_FreightCost.Text <> "0" And txt_FreightCost.Text <> "" Then
            Call ShowErrMessage(10000, lbl_Label(8).Caption)
            cbo_FreightCurr.SetFocus
            Exit Function
        End If
    End If
    
'    If Not CheckNumericBeforeCalculation(txt_TOT_ValueCHF, 39, 0, 1, 999999999) Then
'        Exit Function
'    End If

    If cbo_currencies.SelectedItem.GetData(2) = 0 Then
        Call ShowErrMessage(3064, lbl_Label(20).Caption)
        cbo_currencies.SetFocus
        Exit Function
    End If
    


    RecordCheck = True
    Exit Function
Trace_Err:
    Call ErrorHandler(Extender.Name & ".RecordCheck()")
End Function

Function RecordAdd() As Boolean
On Error GoTo Trace_Err
Const C_TRAN_BEGIN As String = "BEGIN TRAN QuoteAdd"
Const C_TRAN_COMMIT As String = "COMMIT TRAN QuoteAdd"
Const C_TRAN_ROLLBACK As String = "ROLLBACK TRAN QuoteAdd"
Const C_REQ_INS As String = "EXEC Cap_SOM_Quote_ins $SQT_ID$, $SQT_Ref$, $SP_Capkey$, $CCU_Capkey$, 'E', $SQT_Revision$, $SQT_Include$, $CURR_code$, $SQT_Type$, $SQT_Status$, NULL, $RL_Code$, $FRGHTCostLC$, $FRGHT_CURR_Code$, $SQT_FRGHTCost_CHF$, $SQT_ValidToDate$, $SQT_Comment$, $SR_code$, $BO_SSR_Code$, $Z_creator$"
Const C_REQ_NEXTREF As String = "SELECT ISNULL(MAX(SQT_Ref),100) + 1 AS NextRef FROM Cap_SOM_Quote WHERE SP_CapKey=$SP_Capkey$"
Dim ls_Request  As String
Dim ll_cursor As Long
Dim ll_i        As Long
Dim lb_InTrans  As Boolean
    
    RecordAdd = False
    
    lb_InTrans = False
    
    'check all Quote detail
    If Not RecordCheck() Then Exit Function
    
    Dim ll_TemplateID As Long
    
    
    If Not ASC_ConnectToDB(mo_ArmDb, ms_ConnectString, mb_Created) Then Exit Function
    
    m_CurrentKey1 = mo_ArmDb.SQLNextID("Cap_SOM_Quote")
    
    If m_CurrentKey1 = "" Then Call Err.Raise(SQLFailure, "", "SQL Error: mo_ArmDb.SQLNextID(""Cap_SOM_Quote"") return nothing.")
    
    ' get next reference number
    If txt_QuoteRef.Text = "" Then
        ls_Request = ReplacePlaceholders(C_REQ_NEXTREF)
        ll_cursor = OpenSQLSafe(mo_ArmDb, ls_Request)
        txt_QuoteRef.Text = mo_ArmDb.GetFields(ll_cursor, "NextRef")
        Call mo_ArmDb.Close(ll_cursor)
        ll_cursor = 0
    Else
        If txt_Revision.Text = "" Then txt_Revision.Text = "X"
    End If
    
    'Construct the request
    ls_Request = ReplacePlaceholders(C_REQ_INS)
    
    Call FillDetailID(grd_quote, "SQD_ID", "Cap_SOM_QuoteDetail")
    
    Call ExecuteSQLSafe(mo_ArmDb, C_TRAN_BEGIN)
    lb_InTrans = True

    Call ExecuteSQLSafe(mo_ArmDb, ls_Request)
    
    For ll_i = 0 To grd_quote.Rows - 1
        Debug.Assert (grd_quote.Data(ll_i, "iConcurrency") = 0)
        Debug.Assert (grd_quote.Data(ll_i, "UPD_ACTION") = "A")
        Call SubRecordAddDB(grd_quote, ll_i)
    Next
    
    ' JN 20.3.2012 update z_last_upd for a project
    Call UpdateProjectLastUpdate(m_Project)
    
    ' change status of project to psQuote
    ' user add the first product
    Call ExecuteSQLSafe(mo_ArmDb, C_TRAN_COMMIT)
    lb_InTrans = False
    
    ' update local data
    txt_Quot_ID.Text = m_CurrentKey1
    p_iCon = 1
    For ll_i = 0 To grd_quote.Rows - 1
        grd_quote.Data(ll_i, "iConcurrency") = 1
        grd_quote.Data(ll_i, "UPD_ACTION") = ""
    Next
    

    'The data has been inserted
    RaiseEvent Updated
    RecordAdd = True
    
    Exit Function
    
Trace_Err:
    If ll_cursor > 0 Then
        Call mo_ArmDb.Close(ll_cursor)
        ll_cursor = 0
    End If
    If lb_InTrans Then
        Call UpdateError(True)
        Call ExecuteSQLSafe(mo_ArmDb, C_TRAN_ROLLBACK)
        lb_InTrans = False
        Call UpdateError(False)
    End If
    Call ErrorHandler(Extender.Name & ".RecordAdd()")
End Function

' genereate new ID for added lines in the grid
Private Sub FillDetailID(ByRef ao_grid As ArmGrid, ByVal as_IDFieldName As String, ByVal as_A_ID_KEY As String)
On Error GoTo Trace_Err
    Dim ll_i As Long
    Dim ls_newID As String
    For ll_i = 0 To ao_grid.Rows - 1
        If ao_grid.Data(ll_i, "UPD_ACTION") = "A" Then
            ls_newID = mo_ArmDb.SQLNextID(as_A_ID_KEY)
            If ls_newID = "" Then Call Err.Raise(SQLFailure, "", "SQL Error: mo_ArmDb.SQLNextID(""" & as_A_ID_KEY & """) return nothing.")
            ao_grid.Data(ll_i, as_IDFieldName) = ls_newID
        End If
    Next

    Exit Sub
    
Trace_Err:
    Call ErrorHandler(Extender.Name & ".FillDetaiID()")
End Sub

' masr all items as new
Private Sub ResetDetailID(ByRef ao_grid As ArmGrid)
On Error GoTo Trace_Err
    Dim ll_i As Long
    For ll_i = 0 To ao_grid.Rows - 1
        ao_grid.Data(ll_i, "UPD_ACTION") = "A"
        ao_grid.Data(ll_i, "iConcurrency") = 0
    Next
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".ResetDetailID()")
End Sub



Private Function ReplacePlaceholders(ByVal as_str As String) As String
On Error GoTo Trace_Err
    'Construct the request
    as_str = Replace(as_str, "$SQT_ID$", m_CurrentKey1, , , vbTextCompare)                                          ' @SQT_ID             AS INT,
    as_str = Replace(as_str, "$SQT_Ref$", SQLNum(txt_QuoteRef.Text), , , vbTextCompare)                             ' @SQT_Ref            AS INT,
    as_str = Replace(as_str, "$SP_Capkey$", SQLStr(m_Project, 16, True), , , vbTextCompare)                         ' @SP_Capkey          AS CHAR(16),
    as_str = Replace(as_str, "$CCU_Capkey$", SQLStr(cbo_customer.SelectedItem.Key, 16, True), , , vbTextCompare)    ' @CCU_Capkey         AS CHAR(16),
    as_str = Replace(as_str, "$Language_code$", SQLStr(m_Language, 1, True), , , vbTextCompare)
    as_str = Replace(as_str, "$SQT_Revision$", IIf(txt_Revision.Text = "", "''", "'X'"), , , vbTextCompare)                                                ' @SQT_Revision       AS CHAR(1),
    as_str = Replace(as_str, "$SQT_Include$", SQLOptionButtonValue(opt_include), , , vbTextCompare)                 ' @SQT_Include        AS SMALLINT,
    as_str = Replace(as_str, "$CURR_code$", SQLStr(cbo_currencies.SelectedItem.Key, 5, True), , , vbTextCompare)    ' @CURR_code          AS CHAR(5),
    as_str = Replace(as_str, "$SQT_Type$", SQLOptionButtonValue(opt_Type), , , vbTextCompare)                       ' @SQT_Type           AS SMALLINT,
    as_str = Replace(as_str, "$SQT_Status$", cbo_Status.SelectedItem.Key, , , vbTextCompare)                        ' @SQT_Status         AS SMALLINT,
    as_str = Replace(as_str, "$SQT_StatusDate$", "NULL", , , vbTextCompare)                                         ' @SQT_StatusDate     AS DATETIME,
    as_str = Replace(as_str, "$RL_Code$", cbo_realisation.SelectedItem.Key, , , vbTextCompare)                      ' @RL_Code            AS INT,
    as_str = Replace(as_str, "$FRGHTCostLC$", SQLNum(IIf(Trim(txt_FreightCost.Text) = "", "0", txt_FreightCost.Text)), , , vbTextCompare) ' @FRGHTCostLC        AS REAL,
    as_str = Replace(as_str, "$FRGHT_CURR_Code$", SQLStr(cbo_Value(cbo_FreightCurr), 5, True), , , vbTextCompare)   ' @FRGHT_CURR_Code    AS CHAR(5),
    as_str = Replace(as_str, "$SQT_FRGHTCost_CHF$", IIf(Trim(txt_FreightCostCHF.Text) = "", "0", txt_FreightCostCHF.Text), , , vbTextCompare) ' @SQT_FRGHTCost_CHF  AS INT,
    as_str = Replace(as_str, "$SQT_ValidToDate$", "'" & cal_ValidUntil.date_sql & "'", , , vbTextCompare)           ' @SQT_ValidToDate    AS DATETIME,
    as_str = Replace(as_str, "$SQT_Comment$", SQLStr(txt_Comment.Text, 5000, False), , , vbTextCompare)             ' @SQT_Comment        AS VARCHAR(5000),
    as_str = Replace(as_str, "$SR_code$", SQLStr(cbo_SalesRep.SelectedItem.Key, 6, True), , , vbTextCompare)        ' @SR_code            AS CHAR(6),
    as_str = Replace(as_str, "$BO_SSR_Code$", cbo_BO.SelectedItem.Key, , , vbTextCompare)                           ' @BO_SSR_Code        AS INT,
    as_str = Replace(as_str, "$Z_creator$", ml_U_code, , , vbTextCompare)                                           ' @Z_creator          AS INT
    as_str = Replace(as_str, "$iConcurrency$", p_iCon, , , vbTextCompare)                                           ' @iConcurrency       AS SMALLINT
    
    ReplacePlaceholders = as_str
    Exit Function
Trace_Err:
    Call ErrorHandler(Extender.Name & ".ReplacePlaceholders()")
End Function

Private Function DocReplacePlaceholders(ByVal as_str As String) As String
On Error GoTo Trace_Err
    'Construct the request
    as_str = Replace(as_str, "$SQT_ID$", m_CurrentKey1, , , vbTextCompare)                              ' @SQT_ID             AS INT,
    as_str = Replace(as_str, "$nodeID$", txt_nodeID.Text, , , vbTextCompare)                            ' @nodeID       AS INT,
    as_str = Replace(as_str, "$fileTitle$", SQLStr(txt_fileTitle.Text, 50, True), , , vbTextCompare)    ' @fileTitle    AS VARCHAR(50),
    as_str = Replace(as_str, "$fileDesc$", SQLStr(txt_fileDesc.Text, 500, False), , , vbTextCompare)     ' @fileDesc     AS VARCHAR(500),
    as_str = Replace(as_str, "$fileName$", SQLStr(txt_FileName.Text, 128, True), , , vbTextCompare)     ' @fileName     AS VARCAHR(128)
    as_str = Replace(as_str, "$filePath$", SQLStr(txt_filePath, 1024, True), , , vbTextCompare)         ' @filePath     AS VARCHAR(1024),
    as_str = Replace(as_str, "$Z_creator$", ml_U_code, , , vbTextCompare)                               ' @Z_creator    AS INT
    as_str = Replace(as_str, "$iConcurrency$", p_dociCon, , , vbTextCompare)                            ' @iConcurrency AS SMALLINT
    
    DocReplacePlaceholders = as_str
    Exit Function
Trace_Err:
    Call ErrorHandler(Extender.Name & ".DocReplacePlaceholders()")
End Function

Function RecordUpdate(ACode As String) As Boolean
On Error GoTo Trace_Err
Const C_TRAN_BEGIN      As String = "BEGIN TRAN QuoteUpdate"
Const C_TRAN_COMMIT     As String = "COMMIT TRAN QuoteUpdate"
Const C_TRAN_ROLLBACK   As String = "ROLLBACK TRAN QuoteUpdate"
Const C_REQ_UPD As String = "EXEC Cap_SOM_Quote_upd $SQT_ID$, $CCU_CapKey$, $SQT_Include$, $CURR_code$, $SQT_Type$, $SQT_Status$, $RL_Code$, $FRGHTCostLC$, $FRGHT_CURR_Code$, $SQT_FRGHTCost_CHF$, $SQT_ValidToDate$, $SQT_Comment$, $SR_code$, $BO_SSR_Code$, $Z_creator$, $iConcurrency$"
Dim ls_Request  As String
Dim ll_i        As Long
Dim lb_InTrans  As Boolean
    
    RecordUpdate = False
    lb_InTrans = False
    
    'check all Quote detail
    If Not RecordCheck() Then Exit Function

    If Trim$(ACode) = "" Then Call Err.Raise(InvalidArgument, "", "ACode is empty.")
    
    'Construct the request
    ls_Request = ReplacePlaceholders(C_REQ_UPD)
    
    If Not ASC_ConnectToDB(mo_ArmDb, ms_ConnectString, mb_Created) Then Exit Function
    
    Call FillDetailID(grd_quote, "SQD_ID", "Cap_SOM_QuoteDetail")
    
    Call ExecuteSQLSafe(mo_ArmDb, C_TRAN_BEGIN)
    lb_InTrans = True

    Call ExecuteSQLSafe(mo_ArmDb, ls_Request, 1)
    
    ' save Quote detail from grid
    Dim ls_SQD_ID As String
    For ll_i = 0 To grd_quote.Rows - 1
        If grd_quote.Data(ll_i, "UPD_ACTION") = "A" Then
            Debug.Assert (grd_quote.Data(ll_i, "iConcurrency") = 0)
            Call SubRecordAddDB(grd_quote, ll_i)
        ElseIf grd_quote.Data(ll_i, "UPD_ACTION") = "U" Then
            Call SubRecordUpdateDB(grd_quote, ll_i)
        End If
        ls_SQD_ID = IIf(ls_SQD_ID = "", "", ls_SQD_ID & ",") & grd_quote.Data(ll_i, "SQD_ID")
    Next
    
    Call SubRecordDeleteUnusedDB(ACode, ls_SQD_ID)
    
    ' JN 20.3.2012 update z_last_upd for a project
    Call UpdateProjectLastUpdate(m_Project)

    If lb_InTrans Then
        Call ExecuteSQLSafe(mo_ArmDb, C_TRAN_COMMIT)
        lb_InTrans = False
    End If

    'The data has been updated
    RaiseEvent Updated
    RecordUpdate = True
    
    Exit Function
    
Trace_Err:
    If lb_InTrans Then
        Call UpdateError(True)
        Call ExecuteSQLSafe(mo_ArmDb, C_TRAN_ROLLBACK)
        lb_InTrans = False
        Call UpdateError(False)
    End If
    Call ErrorHandler(Extender.Name & ".RecordUpdate()")
End Function

Function RecordDelete(ACode As String) As Boolean
On Error GoTo Trace_Err
Const C_TRAN_BEGIN As String = "BEGIN TRAN QuoteDelete"
Const C_TRAN_COMMIT As String = "COMMIT TRAN QuoteDelete"
Const C_TRAN_ROLLBACK As String = "ROLLBACK TRAN QuoteDelete"
Const C_REQ_DEL As String = "EXEC Cap_SOM_Quote_del $SQT_ID$, $Z_creator$, $iConcurrency$"
Dim ls_Request  As String
Dim lb_InTrans  As Boolean

    RecordDelete = False
    lb_InTrans = False
    
    If Trim$(ACode) = "" Then Call Err.Raise(InvalidArgument, "", "ACode is empty.")
    
    If DeleteConfirmation(mo_ArmDb, m_Language) = False Then Exit Function
    
    If Not ASC_ConnectToDB(mo_ArmDb, ms_ConnectString, mb_Created) Then Exit Function
    
    Call ExecuteSQLSafe(mo_ArmDb, C_TRAN_BEGIN)
    lb_InTrans = True
    
    ls_Request = ReplacePlaceholders(C_REQ_DEL)
    
    Call ExecuteSQLSafe(mo_ArmDb, ls_Request, 1)
    
    ' save Quote detail from grid
    Dim ls_SQD_ID As String
    Dim ll_i As Long
    For ll_i = 0 To grd_quote.Rows - 1
        ls_SQD_ID = IIf(ls_SQD_ID = "", "", ls_SQD_ID & ",") & grd_quote.Data(ll_i, "SQD_ID")
    Next
    
    Call SubRecordDeleteUnusedDB(ACode, ls_SQD_ID)
    
    ' JN 20.3.2012 update z_last_upd for a project
    Call UpdateProjectLastUpdate(m_Project)

    Call ExecuteSQLSafe(mo_ArmDb, C_TRAN_COMMIT)
    lb_InTrans = False
    
    'The data has been deleted
    RaiseEvent Updated
    RecordDelete = True
    
    Exit Function
    
Trace_Err:
    If lb_InTrans Then
        Call UpdateError(True)
        Call ExecuteSQLSafe(mo_ArmDb, C_TRAN_ROLLBACK)
        lb_InTrans = False
        Call UpdateError(False)
    End If
    Call ErrorHandler(Extender.Name & ".RecordDelete()")
End Function

Private Sub ViewDisplay()
    On Error GoTo Trace_Err
    
    If mi_EmbeddedIn = -1 Then
        RaiseEvent SwitchToView(mt_CstValues.View_Full)
    Else
        RaiseEvent SwitchToView(mt_CstValues.View_Full)
    End If
    
    'If the component was on short list, it doues appear now in long list
    InitControl 3
    
    BlankFields
    View_EnableControls
    ViewLoad
    View_Resize
    ViewInitFields
    
    Call SwapToDisplayModeSubitem(mt_CstValues.DisplayMode_List)
    Call SwapToDisplayModeDoc(mt_CstValues.DisplayMode_List)

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".ViewDisplay()")
End Sub

Private Sub View_Resize()
On Error GoTo Trace_Err
    
    With UserControl
        
        If mi_EmbeddedIn = -1 And Not mb_Root Then
        
            .fraItem.Left = mt_CstValues.Frm_Spacing
            
            .tbsEmbedded.Visible = False 'true
            .tbsEmbedded.Zorder 0
            
        Else
            .fraItem.Left = mt_CstValues.Frm_Spacing
            
            .tbsEmbedded.Visible = False 'true
            .tbsEmbedded.Zorder 0
            
        End If
        
        .fraItem.Top = mt_CstValues.Frm_Spacing
        .fraItem.Width = .Width - .fraItem.Left - (2 * mt_CstValues.Frm_Spacing)
        .fraItem.Height = .Height - .fraItem.Top - (2 * mt_CstValues.Frm_Spacing)
        
        .pbItem.Height = mt_CstValues.View_ToolBar_Height
        .pbItem.Top = mt_CstValues.Frm_Spacing * 4
        .pbItem.Left = mt_CstValues.Frm_Spacing
        .pbItem.Width = .fraItem.Width - .pbItem.Left - (2 * mt_CstValues.Frm_Spacing)
        .pbItem.Refresh
        
        .fraItemTop.Top = mt_CstValues.Frm_Spacing + .pbItem.Top + .pbItem.Height
        .fraItemTop.Left = mt_CstValues.Frm_Spacing
        .fraItemTop.Width = .fraItem.Width - .fraItemTop.Left - mt_CstValues.Frm_Spacing
        
        .tbsEmbedded.Top = .fraItem.Height - .tbsEmbedded.Height - mt_CstValues.Frm_Spacing
        .tbsEmbedded.Left = mt_CstValues.Frm_Spacing
        .tbsEmbedded.Width = .fraItem.Width - .tbsEmbedded.Left - mt_CstValues.Frm_Spacing
        
        .fraItemBottom.Width = .fraItem.Width - .tbsEmbedded.Left - mt_CstValues.Frm_Spacing
        '.fraItemBottom.Height = mt_CstValues.Cpt_View_Emb_Height
        .fraItemBottom.Top = .fraItem.Height - .fraItemBottom.Height - mt_CstValues.Frm_Spacing
        .fraItemBottom.Left = mt_CstValues.Frm_Spacing
        
        .fraItemBottom.Visible = True
        
        .fraItem.Visible = True
        .fraItemTop.BorderStyle = 0
        .fraItemBottom.BorderStyle = 0
        
    End With

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".View_Resize()")
End Sub

Public Property Get UserControlWidth() As Long
On Error GoTo ErrorHandler
    UserControlWidth = UserControl.Width
    Exit Property
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".Property Get UserControlWidth()")
End Property

Public Property Get CurrentKey(Optional APart As Integer = 0) As String
On Error GoTo ErrorHandler
    If APart = 0 Then
        CurrentKey = m_CurrentKey1 & CH_LDELIMIT & m_CurrentKey2
    ElseIf APart = 1 Then
        CurrentKey = m_CurrentKey1
    ElseIf APart = 2 Then
        CurrentKey = m_CurrentKey2
    Else
        CurrentKey = ""
    End If
    Exit Property
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".Property Get CurrentKey()")
End Property

Public Property Let CurrentKey(Optional APart As Integer = 0, AKeyValue As String)
On Error GoTo ErrorHandler
    If APart = 0 Then
        m_CurrentKey1 = AKeyValue
        m_CurrentKey2 = ""
        m_CurrentKey3 = ""
    ElseIf APart = 1 Then
        m_CurrentKey1 = AKeyValue
    ElseIf APart = 2 Then
        m_CurrentKey2 = AKeyValue
    Else
        CurrentKey = ""
    End If
    Exit Property
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".Property Get CurrentKey()")
End Property

Public Property Let TypeList(AType As Integer)
On Error GoTo ErrorHandler
    
    mi_TypeList = AType

    Exit Property
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".Property Let TypeList()")
End Property

Property Get TypeList() As Integer
On Error GoTo ErrorHandler
    
    TypeList = mi_TypeList
    
    Exit Property
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".Property Get TypeList()")
End Property

Private Sub ShortList_Resize()
On Error GoTo Trace_Err
    
    With UserControl
    
        .fraList.Left = mt_CstValues.Frm_Spacing
        .fraList.Top = mt_CstValues.Frm_Spacing
        .fraList.Width = .Width - .fraList.Left - (2 * mt_CstValues.Frm_Spacing)
        .fraList.Height = .Height - .fraList.Top - (2 * mt_CstValues.Frm_Spacing)
   
        .pblst.Height = mt_CstValues.View_ToolBar_Height
        .pblst.Top = mt_CstValues.Frm_Spacing * 4
        .pblst.Left = mt_CstValues.Frm_Spacing
        .pblst.Width = .fraList.Width - .pblst.Left - (2 * mt_CstValues.Frm_Spacing)
        .pblst.Refresh
        
        .grdlst.Top = mt_CstValues.Frm_Spacing + .pblst.Top + .pblst.Height
        .grdlst.Left = mt_CstValues.Frm_Spacing
        .grdlst.Width = .fraList.Width - .grdlst.Left - mt_CstValues.Frm_Spacing
        .grdlst.Height = .fraList.Height - .pblst.Height - .pblst.Top - (2 * mt_CstValues.Frm_Spacing)
        
        .fraList.Visible = True
        
    End With
    
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".ShortList_Resize()")
End Sub

' Called when application must resize the current view
Public Sub Resize()
On Error GoTo Trace_Err
    
    Call DisplayMode_None
    
    Select Case DisplayMode
        Case mt_CstValues.DisplayMode_List
               Call ShortList_Resize
    End Select
    
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".Resize()")
End Sub

Sub UnCatch()
    mi_EmbeddedIn = -1
End Sub

Public Property Let product(AProductKey As String)

    ' no product-quote navigation
End Property

Public Property Let action(AActionKey As String)

    ' no action-quote navigation
End Property

Public Property Let contact(AKey As String)

    ' no contact-quote navigation
End Property
 
Public Property Let Customer(AKey As String)

    ' no customer-quote navigation
End Property

Public Property Let project(AKey As String)
On Error GoTo Trace_Err
    Dim TheKeys     As Variant
'    Dim ls_CT_Code  As String
    
    'AKey represents the concatenation of several keys separated by '@'
    If AKey = "" Then Call Err.Raise(InvalidArgument, "", "AKey is empty.")

    ' First, we hide all elements
    DisplayMode_None
    
    If (Not mb_Root) And (mi_TypeList <> 1) Then
        mi_EmbedTag = -1
    End If
    
    TheKeys = Split(AKey, CH_LDELIMIT)
    Debug.Assert (UBound(TheKeys) = 3)
    
    m_Customer = ""
    m_Contact = ""
    m_Project = CStr(TheKeys(0))
    m_projectStatus = CLng(TheKeys(3))
'    ls_CT_Code = "GB" 'TheKeys(3)

    InitControl 2
    
    mi_EmbeddedIn = mt_CstValues.Tag_Project

    mb_EmbeddedIsDropped = False
    
'    Call searchCBO(GetDefaultConfigDesc("Product_Cfg", "CURRLock"), ls_CT_Code, cbo_currencies, "SELECT CURR_code, CURR_desc FROM currencies WHERE language_code = '" & m_Language & "' AND CURR_Code IN( $ITEMS$ ) AND drop_Flag <> 'X' ORDER BY CURR_desc")
    
    cbo_customer.Request = "exec Cap_OfferCompany_cbo '" & m_Project & "','" & m_Language & "'"
    cbo_SalesRep.Request = "EXEC Sales_reps_GEMA_cbo '" & CStr(TheKeys(2)) & "', '" & m_Language & "'"
    ListProjectOf CStr(TheKeys(0)), CStr(TheKeys(1))
    
    SwapToDisplayMode mt_CstValues.DisplayMode_List
    
    Exit Property
Trace_Err:
    Call ErrorMessage(Extender.Name & ".Property Let project()")
End Property

Public Property Let projectFinalization(AKey As String)
On Error GoTo Trace_Err
    Dim TheKeys     As Variant
    
    'AKey represents the concatenation of several keys separated by '@'
    If AKey = "" Then Call Err.Raise(InvalidArgument, "", "AKey is empty.")

    ' First, we hide all elements
    DisplayMode_None
    
    If (Not mb_Root) And (mi_TypeList <> 1) Then
        mi_EmbedTag = -1
    End If
    
    TheKeys = Split(AKey, CH_LDELIMIT)
    Debug.Assert (UBound(TheKeys) = 3)
    
    m_Customer = ""
    m_Contact = ""
    m_Project = CStr(TheKeys(0))
    m_projectStatus = CLng(TheKeys(3))
'    ls_CT_Code = "GB" 'TheKeys(3)

'    InitControl 2
    
    mi_EmbeddedIn = -1

    mb_EmbeddedIsDropped = False
    
'    Call searchCBO(GetDefaultConfigDesc("Product_Cfg", "CURRLock"), ls_CT_Code, cbo_currencies, "SELECT CURR_code, CURR_desc FROM currencies WHERE language_code = '" & m_Language & "' AND CURR_Code IN( $ITEMS$ ) AND drop_Flag <> 'X' ORDER BY CURR_desc")
    
    cbo_customer.Request = "exec Cap_OfferCompany_cbo '" & m_Project & "','" & m_Language & "'"
    cbo_SalesRep.Request = "EXEC Sales_reps_GEMA_cbo '" & CStr(TheKeys(2)) & "', '" & m_Language & "'"
'    ListProjectOf CStr(TheKeys(0)), CStr(TheKeys(1))
    
    SwapToDisplayMode mt_CstValues.DisplayMode_None
    
    Exit Property
Trace_Err:
    Call ErrorMessage(Extender.Name & ".Property Let project()")
End Property

Private Sub cal_ValidUntil_changeposition(y As Integer)
On Error GoTo ErrorHandler
    cal_ValidUntil.Zorder 0
    cal_ValidUntil.Top = cal_ValidUntil.Top + y
    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".cal_ValidUntil_changeposition()")
End Sub

Private Sub cbo_BO_ComboDropDown()
On Error GoTo errHandler

    cbo_BO.AutoDroppedWidth
    
    Exit Sub
    
errHandler:
    
    Select Case Err.Number
    Case Else
        Call LogMessage("cbo_BO_ComboDropDown: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub


Private Sub cbo_currencies_ComboDropDown()
On Error GoTo errHandler
    
    cbo_currencies.AutoDroppedWidth
    
    Exit Sub
    
errHandler:
    
    Select Case Err.Number
    
    Case Else
        Call LogMessage("cbo_currencies_ComboDropDown: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub

Private Sub cbo_currencies_ComboItemSelected()
On Error GoTo errHandler

    
    If mb_InternalInit Then Exit Sub
    
    If mi_DisplayMode = mt_CstValues.DisplayMode_View _
        Or mi_DisplayMode = mt_CstValues.DisplayMode_Delete Then Exit Sub
    
    If cbo_currencies.SelectedItem.GetData(2) = 0 Then
        Err.Raise 3064, C_APPNAME, "The exchange rate is 0 :: " & cbo_currencies.SelectedItem.GetData(0)
    End If

    ' update txt_ValueLC for all items on the quote
    Dim ll_i As Long
    For ll_i = 0 To grd_quote.Rows - 1
        grd_quote.Data(ll_i, "SQD_Value_CHF") = GetValueInCHF(grd_quote.Data(ll_i, "SQD_ValueLC"), cbo_currencies)
        grd_quote.Data(ll_i, "SQD_PrimeMargin") = Replace(Format((grd_quote.Data(ll_i, "SQD_Value_CHF") / 100) * (grd_quote.Data(ll_i, "SQD_DB")), "0.00"), ms_DecimalSeparator, ".", , , vbTextCompare)
    Next
    
    ' recalc TOTal values
    Call CalculationTOT(ml_DisplayModeSubItem)
    
    Exit Sub
errHandler:
    
    Select Case Err.Number
    
    Case 3064
        Call LogMessage("cbo_quote_curr_ComboItemSelected: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox(MsgText(3064, m_Language, "#The currency you choose is not valide. Choose an other one."), vbInformation)
    
    Case Else
        Call LogMessage("cbo_quote_curr_ComboItemSelected: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub

Private Sub cbo_FreightCurr_ComboDropDown()
On Error GoTo errHandler
    cbo_FreightCurr.AutoDroppedWidth
    Exit Sub
    
errHandler:
    
    Select Case Err.Number
    Case Else
        Call LogMessage("cbo_FreightCurr_ComboDropDown: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub

Private Sub cbo_FreightCurr_ComboItemSelected()
On Error GoTo errHandler

    If mb_InternalInit Then Exit Sub
    
    If mi_DisplayMode = mt_CstValues.DisplayMode_View _
        Or mi_DisplayMode = mt_CstValues.DisplayMode_Delete Then Exit Sub
    
    If Not cbo_IsFilled(cbo_FreightCurr) Then
        txt_FreightCostCHF.Text = 0
        Exit Sub
    End If
    
    If cbo_FreightCurr.SelectedItem.GetData(2) = 0 Then
        Err.Raise 3064, C_APPNAME, "The exchange rate is 0 :: " & cbo_currencies.SelectedItem.GetData(0)
    End If

    Call txt_FreightCost_Change

    Exit Sub
errHandler:
    
    Select Case Err.Number
    
    Case 3064
        Call LogMessage("cbo_FreightCurr_ComboItemSelected: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox(MsgText(3064, m_Language, "#The currency you choose is not valide. Choose an other one."), vbInformation)
    
    Case Else
        Call LogMessage("cbo_FreightCurr_ComboItemSelected: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub

Private Sub cbo_SalesRep_ComboItemSelected()
On Error GoTo errHandler
    If mb_InternalInit Then Exit Sub
    
    If cbo_SalesRep.SelectedItem Is Nothing Then Exit Sub
    
    ' check if selected rep is rep of a project
    If cbo_SalesRep.SelectedItem.Key <> ms_SR_Code Then
        Call MsgBox(MsgText(2436, m_Language, "#Warning 2436:Sales representative selected is not the same as sales rep of a project!"), vbInformation)
    End If
    
    Exit Sub
errHandler:
        Call ErrorMessage("cbo_SalesRep_ComboItemSelected")
End Sub

Private Sub cbo_System_ComboDropDown()
On Error GoTo errHandler
    
    cbo_System.AutoDroppedWidth
    Exit Sub
    
errHandler:
    
    Select Case Err.Number
    Case Else
        Call LogMessage("cbo_System_ComboDropDown: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub

Private Sub cbo_UM_ComboDropDown()
On Error GoTo errHandler

    cbo_UM.AutoDroppedWidth
    Exit Sub
    
errHandler:
    
    Select Case Err.Number
    Case Else
        Call LogMessage("cbo_UM_ComboDropDown: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub




Private Sub cmd_File_Click()
On Error GoTo errHandler

Dim ll_Index As Long
Dim lsa_path() As String

    ll_Index = InStrRev(txt_filePath.Text, "\")
    If ll_Index > 0 Then
        dlg_Common.InitDir = Left(txt_filePath.Text, ll_Index - 1)
        dlg_Common.FileName = txt_filePath.Text
    Else
        dlg_Common.InitDir = ""
        dlg_Common.FileName = ""
    End If
    dlg_Common.Filter = "Excell, Word or PDF files|*.xls;*.pdf;*.doc;*.docx;*.xlsx|All files|*.*"
    dlg_Common.flags = cdlOFNFileMustExist
    dlg_Common.CancelError = True
    Call dlg_Common.ShowOpen
    If dlg_Common.FileName <> "" Then
        txt_filePath.Text = dlg_Common.FileName
        lsa_path = Split(dlg_Common.FileName, "\")
        txt_FileName.Text = lsa_path(UBound(lsa_path))
        mb_FileChanged = True
    End If
    Exit Sub
errHandler:
    ' check if error is not raised from common dialog cancel button
    If Err.Number = 32755 Then
        Exit Sub
    End If
    Call ErrorMessage("cmd_File_Click")
End Sub

Private Sub grd_doc_ItemSelected()
On Error GoTo errHandler
    If mb_InternalInit Then Exit Sub
    
    Call pbDoc_action("Media")
    Exit Sub
errHandler:
    Call ErrorMessage(Extender.Name & ".grd_doc_ItemSelected()")
End Sub

Private Sub grd_doc_RowLoaded(ByVal al_Row As Long)
On Error GoTo errHandler
    If grd_doc.Data(al_Row, "fileZipID") = "0" Then
        grd_doc.LineColor(al_Row) = CL_COLOR_Expired
    End If
    Exit Sub
errHandler:
    Call ErrorMessage(Extender.Name & ".grd_doc_RowLoaded()")
End Sub

Private Sub grd_quote_ItemSelected()
On Error GoTo errHandler
    
    Call CapMouseOff
    If ml_DisplayModeSubItem = mt_CstValues.DisplayMode_List Then
        Select Case mi_DisplayMode
        Case mt_CstValues.DisplayMode_Add, mt_CstValues.DisplayMode_Update
            Call pbSubitem_action("Update")
        Case Else
            If grd_quote.SelectedCount = 1 Then
                Call ViewDisplaySubItem
            Else
                Call ASC_SendMessage(mo_ArmDb, m_Language, WarMsgSelectRow, "#Please select a row.")
            End If
        End Select
    End If
    Call CapMouseOn
    Exit Sub
errHandler:
    Call ErrorMessage(Extender.Name & ".grd_Quote_ItemSelected()")
    Call CapMouseOn
End Sub

Private Sub grdLst_ItemSelected()
On Error GoTo errHandler
    
    Call CapMouseOff
    If (grdlst.SelectedCount = 1) Then
'        If grdlst.SelectedLine(0, "DROP_FLAG") <> "X" Then
            m_CurrentKey1 = grdlst.CurrentKey(0)
            DisplayMode = mt_CstValues.DisplayMode_View
'        End If
    End If
    Call CapMouseOn
    Exit Sub
errHandler:
    Call ErrorMessage(Extender.Name & ".grdLst_ItemSelected()")
    Call CapMouseOn
End Sub

' Initialization of the component
Public Sub Load_A_Com(ab_root As Boolean)
On Error GoTo Trace_Err
    
    VerifyInitialization mo_ArmDb, ms_ConnectString, m_Language, Me
    
    mi_EmbeddedIn = -1  '   Component is not embedded by someone
    mi_EmbedTag = -1    '   Component embed none component

    mb_Root = False     ' Component is not the default focus
    mb_InternalInit = False
    
    Set mo_FSO = CreateObject("Scripting.FileSystemObject")

    'to handle Decimal with the local settings
    Dim sBuffer As String
    Dim nBufferLen As Long

    ms_DecimalSeparator = Format(0, ".")

    nBufferLen = 255
    sBuffer = String$(nBufferLen, vbNullChar)
    nBufferLen = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, sBuffer, nBufferLen)
    If nBufferLen > 0 Then
        ms_ThousandSeparator = Left$(sBuffer, nBufferLen - 1)
    End If
    
    ml_useGrouping = IIf(ms_DecimalSeparator = ms_ThousandSeparator, vbFalse, vbUseDefault)
    
#If ENV = LIVE Then
    Set mo_ZIP = CreateObject("ArmSYSCOM.ArmZip")
#Else
    Set mo_ZIP = New ARMSYSCOMLib.ArmZip
#End If
    
    ms_NetworkPath = ""         ' indicate not configured for documents
    
    cal_ValidUntil.opening_toward_top = 1

    grdlst.Load_A_Com
    grdlst.MultiSelect = False
    Dim la_Columns(8) As String
    la_Columns(0) = "SQT_Id" & CH_LDELIMIT & "0" & CH_LDELIMIT & "1" & CH_LDELIMIT & "SQT_Id" & CH_LDELIMIT & "#SQT_Id"
    la_Columns(1) = "SQT_Reference" & CH_LDELIMIT & "2000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SQT_Reference" & CH_LDELIMIT & "#Reference"
    la_Columns(2) = "CCU_Desc" & CH_LDELIMIT & "3200" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CCU_Desc" & CH_LDELIMIT & "#CCU_Desc"
    la_Columns(3) = "CCU_town" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CCU_town" & CH_LDELIMIT & "#CCU_town"
    la_Columns(4) = "Z_Creation" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "Z_Creation" & CH_LDELIMIT & "#Quote date"
    la_Columns(5) = "SQT_StatusDesc" & CH_LDELIMIT & "0" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SQT_Status_Desc" & CH_LDELIMIT & "#Status"
    la_Columns(6) = "SQT_IncludeDesc" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SQT_Include_Desc" & CH_LDELIMIT & "#Include"
    la_Columns(7) = "SQT_ValidToDate" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SQT_ValidToDate" & CH_LDELIMIT & "#Valid to"
    la_Columns(8) = "Z_Creator" & CH_LDELIMIT & "1300" & CH_LDELIMIT & "0" & CH_LDELIMIT & "Z_Creator" & CH_LDELIMIT & "#Z_Creator"
    grdlst.SetColumns la_Columns
    grdlst.LoadConstants ptSQL, "EXEC screen_csts_lst2 'CapSOMQuoteOfProject_Short', 'grid', '" & m_Language & "'", ctColumns

    
    Call cbo_currencies.Load_A_Com
    cbo_currencies.FirstBlankItem = False
    cbo_currencies.Request = "exec  SOM_Currencies_cbo '" & m_Language & "'"

    Call cbo_FreightCurr.Load_A_Com
    cbo_FreightCurr.FirstBlankItem = True
    cbo_FreightCurr.Request = "exec  SOM_Currencies_cbo '" & m_Language & "'"

    Call cbo_realisation.Load_A_Com
    cbo_realisation.FirstBlankItem = False
    cbo_realisation.Request = "exec SOM_Realisation_cbo '" & m_Language & "'"
    
    cbo_customer.Load_A_Com
    cbo_SalesRep.Load_A_Com
    cbo_BO.Load_A_Com
    
    cbo_Status.Load_A_Com
    cbo_Status.Request = "EXEC A_References_ML_Lst 53, '" & m_Language & "'"
    Call cbo_Status.InitColumnNames(Array("RF_code", "RF_Desc"))
    
'    cbo_SalesRep.Request = "exec SOM_Sales_Reps_cbo 1"
    cbo_BO.Request = "exec SOM_Sales_Reps_cbo 2"
    
    Call cal_ValidUntil.reinit_cal


    pblst.Load_A_Com
    pbItem.Load_A_Com
    pbSubitem.Load_A_Com
    pbDoc.Load_A_Com
    pblst.DrivenByCapture = True
    pbItem.DrivenByCapture = True
    pbSubitem.DrivenByCapture = True
    
    Call InitSubitem
    'Screen csts
    LoadLabels mo_ArmDb, UserControl.Controls, SCREEN_NAME, m_Language
    Call ChangeCharset(UserControl.Controls, gl_CodePage)
    
    ' clear label for tab frames
    fraSubItemMain(0).Caption = ""
    fraSubItemMain(1).Caption = ""
    
    txt_ValueCHF.Locked = True
    txt_PrimeMarg.Locked = True

    
    Exit Sub
Trace_Err:
    Call ErrorMessage(Extender.Name & ".Load_A_Com()")
    ' terminate app
    End
End Sub

Private Sub InitNetworkDrive()
On Error GoTo errHandler

    ' BEGIN document upload environment creations
    Dim ls_MapNetworkDrive As String
    ls_MapNetworkDrive = GetAConfigDataByCountry(mo_ArmDb, "QUOT_Doc_MapNetworkDrive")
    
    If ls_MapNetworkDrive = "" Then
        Err.Raise 666, "", "Configuration for user is missing document upload directory."
    End If
    msa_MapNetworkDrive = Split(ls_MapNetworkDrive, SEP)

    Set mo_WshNetwork = CreateObject("WScript.Network")
    
    ms_NetworkPath = msa_MapNetworkDrive(0)
    ms_NetworkUser = msa_MapNetworkDrive(1)
    ms_NetworkPassword = msa_MapNetworkDrive(2)
    ms_NetworkDrive = msa_MapNetworkDrive(3)
    mb_AppCreatedMappedDrive = False
    
    If Trim(ms_NetworkDrive) = "" Then
        ' in this case we upload using direct network path
        ms_DocumentServerDir = ms_NetworkPath
    Else
        ms_DocumentServerDir = ms_NetworkDrive & "\"
        ' check if C_MAPPED_DRIVE is mapped
        If Not NetworkDriveExists(mo_WshNetwork, ms_NetworkDrive) Then
            mb_AppCreatedMappedDrive = MapNetworkDrive(mo_WshNetwork, ms_NetworkDrive, msa_MapNetworkDrive(0), msa_MapNetworkDrive(1), msa_MapNetworkDrive(2))
        End If
    End If
    
    If (ms_DocumentServerDir <> "") And right(ms_DocumentServerDir, 1) <> "\" Then ms_DocumentServerDir = ms_DocumentServerDir & "\"
    
    If Not mo_FSO.FolderExists(ms_DocumentServerDir) Then
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$PATH$"
        ms_MsgInfo(0, 1) = ms_DocumentServerDir
        Call MsgBox(MsgText(2439, m_Language, "Upload folder '$PATH$' is not accessible or you do not have rights, please contact IT.", ms_MsgInfo))
        ms_NetworkPath = ""
        ms_NetworkUser = ""
        ms_NetworkPassword = ""
        ms_NetworkDrive = ""
    Else
        ' test if curently mapped drive points to service dir on the other side
        If Not mo_FSO.FolderExists(ms_DocumentServerDir & C_ERROR_FILES_DIR) Then
            ' drive is not propably pointing ok
            Call MsgBox(MsgText(666, m_Language, "Existing mapped drive is propably not configured correctly!. Upload for documents may not work."))
            ms_NetworkPath = ""
            ms_NetworkUser = ""
            ms_NetworkPassword = ""
            ms_NetworkDrive = ""
        End If
    End If
    ' END document upload environment creations
    Exit Sub
errHandler:
    Call ErrorMessage(Extender.Name & ".InitNetworkDrive()")
End Sub
' Get the root state
Public Property Get Root() As Boolean
On Error GoTo ErrorHandler
    
    Root = mb_Root

    Exit Property
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".Property Get Root()")
End Property

Public Property Let Root(ByVal ab_root As Boolean)
On Error GoTo ErrorHandler
    
    mb_Root = ab_root
    If mb_Root = True Then
        mi_EmbeddedIn = -1
    End If

    Exit Property
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".Property Let Root()")
End Property

Private Sub pbDoc_action(ByVal as_ActionType As String)
On Error GoTo Trace_Err
    CapMouseOff
    Select Case UCase$(as_ActionType)
        Case UCase$("Add")
            If trw_doc.SelectedItem Is Nothing Then
                Call ASC_SendMessage(mo_ArmDb, m_Language, WarNodeNotSelected, "#Please select node for file first.")
            Else
                ' check if network drive is mapped
                If ms_NetworkPath = "" Then
                    Call InitNetworkDrive
                End If
                
                ' do we have it?
                If ms_NetworkPath <> "" Then
                    ' check if we are in add quote mode
                    If DisplayMode = mt_CstValues.DisplayMode_Add Then
                        
                        ' first we save the quote
                        If Not RecordAdd Then
                            CapMouseOn
                            Exit Sub
                        End If
                        Call grdlst.Refresh
                        Call grdlst.SearchKey(True, m_CurrentKey1)
                        
                        ' now we can open update mode
                        mi_DisplayMode = mt_CstValues.DisplayMode_Update
                        trw_doc.GridRequests = Array( _
                            "EXEC Cap_SOM_Doc_file_lst " & m_CurrentKey1 & ", $0$, '" & m_Language & "'", _
                            "EXEC Cap_SOM_Doc_file_lst " & m_CurrentKey1 & ", $0$, '" & m_Language & "'", _
                            "EXEC Cap_SOM_Doc_file_lst " & m_CurrentKey1 & ", $0$, '" & m_Language & "'", _
                            "EXEC Cap_SOM_Doc_file_lst " & m_CurrentKey1 & ", $0$, '" & m_Language & "'")
                        Call trw_doc_NodeClick(trw_doc.SelectedItem)
                        Update_EnableControls
                        Update_Resize
                        
                    End If
                    Call AddDisplayDoc(trw_doc.SelectedItem.Tag.IDValue)
                End If
            End If
        Case UCase$("Update")
            If grd_doc.SelectedCount > 0 Then
                ' check if network drive is mapped
                If ms_NetworkPath = "" Then
                    Call InitNetworkDrive
                End If
                
                ' do we have it?
                If ms_NetworkPath <> "" Then
                   Call UpdateDisplayDoc(grd_doc.SelectedKey(0)(0))
                End If
            Else
                Call ASC_SendMessage(mo_ArmDb, m_Language, WarMsgSelectRow, "#Please select a row.")
            End If
    
        Case UCase$("Delete")
            If grd_doc.SelectedCount > 0 Then
                Call DeleteDisplayDoc(grd_doc.SelectedKey(0)(0))
            Else
                Call ASC_SendMessage(mo_ArmDb, m_Language, WarMsgSelectRow, "#Please select a row.")
            End If
        Case UCase$("Refresh")
            grd_doc.Refresh
        Case UCase$("Quit")
            Call SwapToDisplayModeDoc(mt_CstValues.DisplayMode_List)
'            If DisplayMode = mt_CstValues.DisplayMode_Add Then
'                Call Add_Enablecontrols
'            End If

        Case UCase$("Valid")
            Dim lb_Result As Boolean
            lb_Result = False

            Select Case mi_DisplayModeDoc
                Case mt_CstValues.DisplayMode_Add
                    lb_Result = DocRecordAdd()
                Case mt_CstValues.DisplayMode_Update
                    Debug.Assert (grd_doc.SelectedCount <> 0)
                    lb_Result = DocRecordUpdate()
                Case mt_CstValues.DisplayMode_Delete
                    Debug.Assert (grd_doc.SelectedCount <> 0)
                    lb_Result = DocRecordDelete()
            End Select
            If lb_Result Then
                Call SwapToDisplayModeDoc(mt_CstValues.DisplayMode_List)
                ' refresh grid
                Call grd_doc.Refresh
            End If
        Case UCase$("Undo")
            Select Case mi_DisplayModeDoc
                Case mt_CstValues.DisplayMode_Add
                    Debug.Assert (Not trw_doc.SelectedItem Is Nothing)
                    Call AddDisplayDoc(trw_doc.SelectedItem.Tag.IDValue)
                Case mt_CstValues.DisplayMode_Update
                    Debug.Assert (grd_doc.SelectedCount <> 0)
                    Call UpdateDisplayDoc(grd_doc.SelectedKey(0)(0))
                Case Else
                    Debug.Assert (False)
            End Select
        Case UCase$("Media")
            If grd_doc.SelectedCount > 0 Then
                If grd_doc.SelectedLine(0, "fileZipID") <> 0 Then
                    Call Download_File(grd_doc.SelectedKey(0)(0))
                    Call Launch_File(grd_doc.SelectedKey(0)(0))
                Else
                    Call ASC_SendMessage(mo_ArmDb, m_Language, WarNoRecordData, "#Record do not containt data.")
                End If
            Else
                Call ASC_SendMessage(mo_ArmDb, m_Language, WarMsgSelectRow, "#Please select a row.")
            End If
        Case UCase$("Save")
            If grd_doc.SelectedCount > 0 Then
                If grd_doc.SelectedLine(0, "fileZipID") <> 0 Then
                    dlg_Common.FileName = grd_doc.SelectedLine(0, "fileName")
                    Dim ls_ext As String
                    Dim lsa_exta() As String
                    lsa_exta = Split(grd_doc.SelectedLine(0, "fileName"), ".")
                    If UBound(lsa_exta) = 0 Then
                        ls_ext = "All files|*.*"
                    Else
                        ls_ext = lsa_exta(UBound(lsa_exta)) & " files|*." & lsa_exta(UBound(lsa_exta))
                    End If
                    
                    dlg_Common.Filter = ls_ext
                    dlg_Common.flags = cdlOFNOverwritePrompt
                    dlg_Common.CancelError = True
                    Call dlg_Common.ShowSave
                    DoEvents
                    If dlg_Common.FileName <> "" Then
                        Dim ls_TempDir As String
                        ls_TempDir = Download_File(grd_doc.SelectedKey(0)(0))
                        If ls_TempDir <> "" Then
                            ' copy file into dest folder
                            Dim lo_Fld As Object
                            Dim lo_File As Object
                            Set lo_Fld = mo_FSO.GetFolder(ls_TempDir)
                            For Each lo_File In lo_Fld.Files
                                Call lo_File.Copy(dlg_Common.FileName, True)
                            Next
                        End If
                    End If
                Else
                    Call ASC_SendMessage(mo_ArmDb, m_Language, WarNoRecordData, "#Record do not containt data.")
                End If
            Else
                Call ASC_SendMessage(mo_ArmDb, m_Language, WarMsgSelectRow, "#Please select a row.")
            End If

    End Select
    
    CapMouseOn
    Exit Sub
Trace_Err:
    Select Case Err.Number
    Case ArmErr.SQLBadRowExpectedCount
        Call ASC_SendMessage(mo_ArmDb, m_Language, 2138, "#The record you try to open has been deleted by an other user. Please refresh the grid.", , vbInformation)
        CapMouseOn
        Exit Sub
    Case ArmErr.SQLBadRowAffectedCount
        Call ASC_SendMessage(mo_ArmDb, m_Language, 916, "#This data has been updated by another user. Data will be reloaded. Please check the data and try again.", , vbInformation)
        Call ViewInitFieldsDoc(txt_fileID.Text)
        CapMouseOn
        Exit Sub
    Case 32755      ' cancel was selected in common dialog
        CapMouseOn
        Exit Sub
    End Select

    Call ErrorMessage(Extender.Name & ".pbDoc_action()")
    CapMouseOn
End Sub

Private Sub pbItem_action(ByVal as_ActionType As String)
On Error GoTo Trace_Err
    Dim lb_Result   As Boolean
    Dim ls_auxStr   As String
    Dim ls_serialStr As String

    CapMouseOff
    
    Select Case UCase$(as_ActionType)
        Case UCase$("Add")
            If CanAddQuote(m_Project) Then
                CurrentKey = ""
                DisplayMode = mt_CstValues.DisplayMode_Add
            End If
        
        Case UCase$("Update")
            If m_CurrentKey1 <> "" Then
                If CanUpdateQuote(m_Project) Then
                    DisplayMode = mt_CstValues.DisplayMode_Update
                End If
            End If
        
        Case UCase$("Delete")
            If m_CurrentKey1 <> "" Then
                If CanUpdateQuote(m_Project) Then
                    DisplayMode = mt_CstValues.DisplayMode_Delete
                End If
            End If
        
        Case UCase$("Print")
            If m_CurrentKey1 <> "" Then
                Debug.Assert (Not cbo_Status.SelectedItem Is Nothing)
                'If CanSendQuote(m_CurrentKey1, cbo_Status.SelectedItem.Key) Then
                    Call PrintQuote(m_CurrentKey1, cbo_Status.SelectedItem.Key, False)
                'End If
            End If
        Case UCase$("Mail")
            If m_CurrentKey1 <> "" Then
                Debug.Assert (Not cbo_Status.SelectedItem Is Nothing)
                'If CanSendQuote(m_CurrentKey1, cbo_Status.SelectedItem.Key) Then
                    If StrComp(PrintQuotePreview(m_CurrentKey1, False, ls_serialStr), "Valid", vbTextCompare) = 0 Then
                        Call MailQuote(m_CurrentKey1, cbo_Status.SelectedItem.Key, ls_serialStr, False)
                    End If
                'End If
            End If
        Case UCase$("Fax")
            If m_CurrentKey1 <> "" Then
                Debug.Assert (Not cbo_Status.SelectedItem Is Nothing)
                'If CanSendQuote(m_CurrentKey1, cbo_Status.SelectedItem.Key) Then
                    If StrComp(PrintQuotePreview(m_CurrentKey1, False, ls_serialStr), "Valid", vbTextCompare) = 0 Then
                        Call FaxQuote(m_CurrentKey1, cbo_Status.SelectedItem.Key, ls_serialStr, False)
                    End If
                'End If
            End If
        
        Case UCase$("Patent")
            If m_CurrentKey1 <> "" Then
                Debug.Assert (Not cbo_Status.SelectedItem Is Nothing)
                'If CanSendQuoteConfirmation(m_CurrentKey1, cbo_Status.SelectedItem.Key) Then
                    Select Case UCase(PrintQuotePreview(m_CurrentKey1, True, ls_serialStr))
                    Case "MAIL"
                        Call MailQuote(m_CurrentKey1, cbo_Status.SelectedItem.Key, ls_serialStr, True)
                    Case "FAX"
                        Call FaxQuote(m_CurrentKey1, cbo_Status.SelectedItem.Key, ls_serialStr, True)
                    Case "PRINT"
                        Call PrintQuote(m_CurrentKey1, cbo_Status.SelectedItem.Key, True)
                    Case Else
                    End Select
                'End If
            End If

        Case UCase$("Copy")
            If m_CurrentKey1 <> "" And CanUpdateQuote(m_Project) Then
                Call CopyQuote(m_CurrentKey1, False)
            End If
        
        Case UCase$("New")      ' Revision
            If m_CurrentKey1 <> "" And CanUpdateQuote(m_Project) Then
                Call CopyQuote(m_CurrentKey1, True)
            End If
    
        Case UCase$("Quit")
            If mi_EmbedTag <> -1 Then
                RaiseEvent Release
                mi_EmbedTag = -1
            End If
            
            If mi_EmbeddedIn <> -1 Then
                DisplayMode = mt_CstValues.DisplayMode_List
            Else
                RaiseEvent quit
            End If
            
        Case UCase$("Valid")
        
            lb_Result = False
            Select Case DisplayMode
                Case mt_CstValues.DisplayMode_Add
                    lb_Result = RecordAdd
                Case mt_CstValues.DisplayMode_Update
                    lb_Result = RecordUpdate(m_CurrentKey1)
                Case mt_CstValues.DisplayMode_Delete
                    lb_Result = RecordDelete(m_CurrentKey1)
            End Select
            If lb_Result Then
                If mi_EmbeddedIn <> -1 Then
                    Call RefreshGridSafe(grdlst)
                    If DisplayMode = mt_CstValues.DisplayMode_Add Then
                        Call grdlst.SearchKey(True, m_CurrentKey1)
                    End If
                    DisplayMode = mt_CstValues.DisplayMode_List
                End If
            End If
            
        Case UCase$("Undo")
            BlankFields
            'DisplayMode = mt_CstValues.DisplayMode_List
            If mi_DisplayMode = mt_CstValues.DisplayMode_Add Then
                AddInitFields
            Else
                ViewInitFields
            End If
            
        Case UCase$("Previous")
            If grdlst.Row = 0 Then
                Call ASC_SendMessage(mo_ArmDb, m_Language, 927, "#No more previous item.")
            Else
                grdlst.Row = grdlst.Row - 1
                m_CurrentKey1 = grdlst.CurrentKey(0)
                BlankFields
                ViewInitFields
            End If
        
        Case UCase$("Next")
            If grdlst.Row = grdlst.Rows - 1 And grdlst.AllDataLoaded = True Then
                Call ASC_SendMessage(mo_ArmDb, m_Language, 928, "#No more next item.")
            Else
                grdlst.Row = grdlst.Row + 1
                m_CurrentKey1 = grdlst.CurrentKey(0)
                BlankFields
                ViewInitFields
            End If
        Case Else
            Call ASC_SendMessage(mo_ArmDb, m_Language, 929, "#Invalid option :", as_ActionType)
    
    End Select

    CapMouseOn
    Exit Sub
Trace_Err:
    Select Case Err.Number
    Case ArmErr.SQLBadRowExpectedCount
        Call ASC_SendMessage(mo_ArmDb, m_Language, 2138, "#The record you try to open has been deleted by an other user. Please refresh the grid.", , vbInformation)
        CapMouseOn
        Exit Sub
    Case ArmErr.SQLBadRowAffectedCount
        Call ASC_SendMessage(mo_ArmDb, m_Language, 916, "#This data has been updated by another user. Data will be reloaded. Please check the data and try again.", , vbInformation)
        ViewInitFields
        CapMouseOn
        Exit Sub
    End Select

    Call ErrorMessage(Extender.Name & ".pbItem_action()")
    CapMouseOn
End Sub

Private Sub pbLst_Action(ByVal as_ActionType As String)
On Error GoTo Trace_Err

Dim ls_serialStr As String

    CapMouseOff
    
    ' TASK 298.2
    Select Case UCase$(as_ActionType)
    
        Case UCase$("Add")
            If CanAddQuote(m_Project) Then
                CurrentKey = ""
                DisplayMode = mt_CstValues.DisplayMode_Add
            End If
            
        Case UCase$("Update")
            If (grdlst.SelectedCount = 1) Then
                If grdlst.CurrentKey(0) <> "" Then
                    CurrentKey = grdlst.CurrentKey(0)
                    If CanUpdateQuote(m_Project) Then
                        DisplayMode = mt_CstValues.DisplayMode_Update
                    End If
                End If
            End If
            
        Case UCase$("Delete")
            If (grdlst.SelectedCount = 1) Then
                If grdlst.CurrentKey(0) <> "" Then
                    m_CurrentKey1 = grdlst.CurrentKey(0)
                    If CanUpdateQuote(m_Project) Then
                        DisplayMode = mt_CstValues.DisplayMode_Delete
                    End If
                End If
            End If
        
        Case UCase$("Refresh")
            grdlst.Refresh
            
        Case UCase$("Print")
            If (grdlst.SelectedCount = 1) Then
                If (grdlst.CurrentKey(0) <> "") Then
                    'If CanSendQuote(grdlst.CurrentKey(0), grdlst.SelectedLine(0, "STATUS")) Then
                        Call PrintQuote(grdlst.CurrentKey(0), grdlst.SelectedLine(0, "STATUS"), False)
                    'End If
                End If
            End If
        Case UCase$("Mail")
            If (grdlst.SelectedCount = 1) Then
                If (grdlst.CurrentKey(0) <> "") Then
                    'If CanSendQuote(grdlst.CurrentKey(0), grdlst.SelectedLine(0, "STATUS")) Then
                        If StrComp(PrintQuotePreview(grdlst.CurrentKey(0), False, ls_serialStr), "Valid", vbTextCompare) = 0 Then
                            Call MailQuote(grdlst.CurrentKey(0), grdlst.SelectedLine(0, "STATUS"), ls_serialStr, False)
                        End If
                    'End If
                End If
            End If
        Case UCase$("Fax")
            If (grdlst.SelectedCount = 1) Then
                If (grdlst.CurrentKey(0) <> "") Then
                    'If CanSendQuote(grdlst.CurrentKey(0), grdlst.SelectedLine(0, "STATUS")) Then
                        If StrComp(PrintQuotePreview(grdlst.CurrentKey(0), False, ls_serialStr), "Valid", vbTextCompare) = 0 Then
                            Call FaxQuote(grdlst.CurrentKey(0), grdlst.SelectedLine(0, "STATUS"), ls_serialStr, False)
                        End If
                    'End If
                End If
            End If
        
        Case UCase$("Patent")
            If (grdlst.SelectedCount = 1) Then
                If (grdlst.CurrentKey(0) <> "") Then
                    'If CanSendQuoteConfirmation(grdlst.CurrentKey(0), grdlst.SelectedLine(0, "STATUS")) Then
                        Select Case UCase(PrintQuotePreview(grdlst.CurrentKey(0), True, ls_serialStr))
                        Case "MAIL"
                            Call MailQuote(grdlst.CurrentKey(0), grdlst.SelectedLine(0, "STATUS"), ls_serialStr, True)
                        Case "FAX"
                            Call FaxQuote(grdlst.CurrentKey(0), grdlst.SelectedLine(0, "STATUS"), ls_serialStr, True)
                        Case "PRINT"
                            Call PrintQuote(grdlst.CurrentKey(0), grdlst.SelectedLine(0, "STATUS"), True)
                        Case Else
                        End Select
                    'End If
                End If
            End If
        
        Case UCase$("Copy")
            If (grdlst.SelectedCount = 1) Then
                If (grdlst.CurrentKey(0) <> "") Then
                    If CanUpdateQuote(m_Project) Then
                        Call CopyQuote(grdlst.CurrentKey(0), False)
                    End If
                End If
            End If
        
        Case UCase$("New")      ' Revision
            If (grdlst.SelectedCount = 1) Then
                If (grdlst.CurrentKey(0) <> "") Then
                    If CanUpdateQuote(m_Project) Then
                        Call CopyQuote(grdlst.CurrentKey(0), True)
                    End If
                End If
            End If

        Case UCase$("Quit")
            RaiseEvent quit
        
        Case Else
            Call ASC_SendMessage(mo_ArmDb, m_Language, 929, "#Invalid option :", as_ActionType)
    
    End Select

    CapMouseOn
    Exit Sub
    
Trace_Err:
    Call ErrorMessage(Extender.Name & ".pbLst_Action()")
    CapMouseOn
End Sub

Sub View_EnableControls()
On Error GoTo Trace_Err
    
    Call ControlsEnable(UserControl.Controls, fraItemTop, False)
    Call ControlsEnable(UserControl.Controls, fraItemBottom, False)
    Call ControlsEnable(UserControl.Controls, fra_TOT, False)

    txt_SP_Desc.Locked = True
    txt_SP_Desc.BackColor = CL_COLOR_DISABLED
    txt_SP_Desc.Enabled = True
    
    txt_SQT_Reference.Locked = True
    txt_SQT_Reference.BackColor = CL_COLOR_DISABLED
    txt_SQT_Reference.Enabled = True
    
    txt_DateEntered.Locked = True
    txt_DateEntered.BackColor = CL_COLOR_DISABLED
    txt_DateEntered.Enabled = True
    
    txt_dateUpdated.Locked = True
    txt_dateUpdated.BackColor = CL_COLOR_DISABLED
    txt_dateUpdated.Enabled = True
    
    txt_CreatedBy.Locked = True
    txt_CreatedBy.BackColor = CL_COLOR_DISABLED
    txt_CreatedBy.Enabled = True
    
    txt_updatedBy.Locked = True
    txt_updatedBy.BackColor = CL_COLOR_DISABLED
    txt_updatedBy.Enabled = True
    
    txt_dropDate.Locked = True
    txt_dropDate.BackColor = CL_COLOR_DISABLED
    txt_dropDate.Enabled = True
    
    txt_Comment.Locked = True
    txt_Comment.BackColor = CL_COLOR_DISABLED
    txt_Comment.Enabled = True
    
    fraSubItemMain(0).Enabled = True
    fraSubItemMain(1).Enabled = True
    
    grd_quote.Enabled = True
    pbSubitem.Enabled = True
    pbDoc.Enabled = True
    tbs_quoteDetail.Enabled = True
    
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".View_EnableControls()")
End Sub

Sub Add_Enablecontrols()
On Error GoTo Trace_Err
    
    Call ControlsEnable(UserControl.Controls, fraItemTop, True)
    Call ControlsEnable(UserControl.Controls, fraItemBottom, True)
    Call ControlsEnable(UserControl.Controls, fra_TOT, False)
    
    txt_SP_Desc.Locked = True
    txt_SP_Desc.BackColor = CL_COLOR_DISABLED
    txt_SQT_Reference.Locked = True
    txt_SQT_Reference.BackColor = CL_COLOR_DISABLED
    
    txt_DateEntered.Locked = True
    txt_DateEntered.BackColor = CL_COLOR_DISABLED
    txt_dateUpdated.Locked = True
    txt_dateUpdated.BackColor = CL_COLOR_DISABLED
    txt_CreatedBy.Locked = True
    txt_CreatedBy.BackColor = CL_COLOR_DISABLED
    txt_updatedBy.Locked = True
    txt_updatedBy.BackColor = CL_COLOR_DISABLED
    txt_dropDate.Locked = True
    txt_dropDate.BackColor = CL_COLOR_DISABLED
    chk_dropFlag.Enabled = False
    
    txt_Comment.Locked = False
    txt_Comment.BackColor = CL_COLOR_ENABLED
    cbo_Status.Enabled = False
    
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".Add_Enablecontrols()")
End Sub

Sub Update_EnableControls()
On Error GoTo Trace_Err
    
    Call ControlsEnable(UserControl.Controls, fraItemTop, True)
    Call ControlsEnable(UserControl.Controls, fraItemBottom, True)
    Call ControlsEnable(UserControl.Controls, fra_TOT, False)
    
    txt_SP_Desc.Locked = True
    txt_SP_Desc.BackColor = CL_COLOR_DISABLED
    txt_SQT_Reference.Locked = True
    txt_SQT_Reference.BackColor = CL_COLOR_DISABLED
    
    txt_DateEntered.Locked = True
    txt_DateEntered.BackColor = CL_COLOR_DISABLED
    txt_dateUpdated.Locked = True
    txt_dateUpdated.BackColor = CL_COLOR_DISABLED
    txt_CreatedBy.Locked = True
    txt_CreatedBy.BackColor = CL_COLOR_DISABLED
    txt_updatedBy.Locked = True
    txt_updatedBy.BackColor = CL_COLOR_DISABLED
    txt_dropDate.Locked = True
    txt_dropDate.BackColor = CL_COLOR_DISABLED
    chk_dropFlag.Enabled = False
    
    txt_Comment.Locked = False
    txt_Comment.BackColor = CL_COLOR_ENABLED
    cbo_Status.Enabled = False
    cbo_currencies.Enabled = False
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".Update_EnableControls()")
End Sub

Sub UpdateInitFields()
On Error GoTo Trace_Err
    
    'idem
    ViewInitFields
    
    ' update UI according to selected data

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".UpdateInitFields()")
End Sub


Private Sub InitControl(Optional aMode As Integer = 0)
On Error GoTo Trace_Err
    Dim ConnectData As Variant
    
    If Not ASC_ConnectToDB(mo_ArmDb, ms_ConnectString, mb_Created) Then Exit Sub
    
    Select Case aMode
        Case 0
    'If No mode then exit
            Exit Sub
   
        Case 1
    'If already initialized then exit
        If mi_TypeList <> 1 Then
            mi_TypeList = 1
        Else
            pblst.PictureDisplayed = "P_Quit=-1"
            Exit Sub
        End If
        Case 2
        If mi_TypeList <> 1 And mi_TypeList <> 2 Then
            mi_TypeList = 2
        End If
    End Select
   
    UserControl.ScaleMode = 1
    
    'Object unvisble
    ObjectVisible False
    
    Select Case aMode
        Case 2
        'Pour la liste courte
        
        'Grille
'        grdlst.ResetGrid
        
        'Pour liste longue : Initialisation toolbar
        pblst.ClearAllIcons
        pblst.TableName = "Cap_SOM_Quote"
        pblst.PictureDisplayed = "P_Copy=4 P_New=5 P_Refresh=6"
'        pblst.PictureDisplayed = "P_Refresh=6 P_Mail=8 P_Fax=9 P_Print=10 P_Copy=11 P_Patent=12"
        
        Case 3
    
            pbItem.ClearAllIcons
            pbItem.TableName = ""
            pbItem.PictureDisplayed = "P_Update=2 P_Previous=4 P_Next=5 P_Quit=-1"
'            pbItem.PictureDisplayed = "P_Update=2 P_Previous=4 P_Next=5 P_Mail=8 P_Fax=9 P_Print=10 P_Copy=11 P_Patent=12 P_Lost=-4 P_FrameContract=-3 P_Quit=-1"
    
        Case 4
    
        'Toolbar
        pbItem.ClearAllIcons
        pbItem.PictureDisplayed = "P_Valid=1 P_UnDo=2 P_Quit=-1"
    End Select
    
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".InitControl()")
End Sub
Private Sub ObjectVisible(Optional aVisible As Boolean = True)
On Error GoTo Trace_Err
    
    UserControl.fraItem.Visible = aVisible
    UserControl.fraList.Visible = aVisible

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".ObjectVisible()")
End Sub

Public Sub FrameWorkInit(ByRef lt_CstValues As Type_CstValues, ByVal ls_InstanceName As String, Optional ATypeList As Integer = 0)
On Error GoTo Trace_Err
    
    'Restriction of initialsation
    mi_TypeParam = ATypeList
        
    Set mt_CstValues = lt_CstValues
    
    
    mi_CptTag = mt_CstValues.Tag_CapSOMQuote
    
    ' Add the tabulation for the embedded controls
    With UserControl
        .ScaleMode = 1
        .tbsEmbedded.Tabs.Clear
        .tbsEmbedded.TabFixedWidth = 150
        Dim lt_Tab As Object
        Set lt_Tab = .tbsEmbedded.Tabs.Add(.tbsEmbedded.Tabs.Count + 1, "Project", "#Project")
        lt_Tab.Tag = mt_CstValues.Tag_Project
        Set lt_Tab = Nothing
        Set lt_Tab = .tbsEmbedded.Tabs.Add(.tbsEmbedded.Tabs.Count + 1, "Action", "#Action")
        lt_Tab.Tag = mt_CstValues.Tag_Action
        Set lt_Tab = Nothing
        Set lt_Tab = .tbsEmbedded.Tabs.Add(.tbsEmbedded.Tabs.Count + 1, "Customer", "#Customer")
        lt_Tab.Tag = mt_CstValues.Tag_Customer
        Set lt_Tab = Nothing
        Set lt_Tab = .tbsEmbedded.Tabs.Add(.tbsEmbedded.Tabs.Count + 1, "Contact", "#Contact")
        lt_Tab.Tag = mt_CstValues.Tag_Contact
        Set lt_Tab = Nothing
        Set lt_Tab = .tbsEmbedded.Tabs.Add(.tbsEmbedded.Tabs.Count + 1, "Product", "#Product")
        lt_Tab.Tag = mt_CstValues.Tag_Product
        Set lt_Tab = Nothing
        Set lt_Tab = .tbsEmbedded.Tabs.Add(.tbsEmbedded.Tabs.Count + 1, "Memo", "#Memo")
        lt_Tab.Tag = mt_CstValues.Tag_Memo
        Set lt_Tab = Nothing
    End With
    
    mi_DisplayMode = mt_CstValues.DisplayMode_None
    mi_OldDisplayMode = mi_DisplayMode
    
    Exit Sub
Trace_Err:
    Call ErrorMessage(Extender.Name & ".FrameWorkInit()")
    ' terminate app
    End
End Sub

' Release the memory used
Public Sub Unload_A_Com()
On Error GoTo Trace_Err
    
    grdlst.Unload_A_Com
    grd_quote.Unload_A_Com
    grd_doc.Unload_A_Com
    trw_doc.Unload_A_Com
    
    pblst.Unload_A_Com
    pbItem.Unload_A_Com
    pbSubitem.Unload_A_Com
    pbDoc.Unload_A_Com
    
    cbo_customer.Unload_A_Com
    cbo_System.Unload_A_Com
    cbo_SQD_Type.Unload_A_Com
    cbo_BO.Unload_A_Com
    cbo_SalesRep.Unload_A_Com
    cbo_Status.Unload_A_Com
    Call cbo_currencies.Unload_A_Com
    Call cbo_FreightCurr.Unload_A_Com
    Call cbo_realisation.Unload_A_Com
    
    ' Unmap Drive
    If (ms_NetworkDrive <> "") And Not (mo_WshNetwork Is Nothing) And mb_AppCreatedMappedDrive Then
        Call mo_WshNetwork.RemoveNetworkDrive(ms_NetworkDrive)
    End If
    Set mo_WshNetwork = Nothing
    Set mo_FSO = Nothing
    Set mo_ZIP = Nothing
    Exit Sub
Trace_Err:
    Call ErrorMessage(Extender.Name & ".Unload_A_Com()")
    ' terminate app
    End
End Sub

' Properties for let application access to critical data
Public Property Get CptTag()
    
    CptTag = mi_CptTag
End Property

' Give the tag of the component which embed this instance
Public Property Get EmbeddedIn() As Integer
    
    EmbeddedIn = mi_EmbeddedIn
End Property

' Give the tag of the component embed by this
Public Property Get EmbedTag() As Integer
    
    EmbedTag = mi_EmbedTag
End Property

' Give the actual display mode
Public Property Get DisplayMode() As Integer
    
    DisplayMode = mi_DisplayMode
End Property

' Change the actual display mode
Public Property Let DisplayMode(ByVal li_DisplayMode As Integer)
    
    SwapToDisplayMode li_DisplayMode
End Property

' when a component embed this instance
Public Sub CatchBy(ByVal li_TagCaller, ByVal ls_Params As String)
On Error GoTo Trace_Err
    
    mi_EmbeddedIn = li_TagCaller
    mb_Root = False
    mi_EmbedTag = -1
    
    If mi_EmbeddedIn <> -1 Then
        ' When a component is embedded, it always appears in short list
        SwapToDisplayMode mt_CstValues.DisplayMode_List, ls_Params
    End If
    
    Exit Sub
Trace_Err:
    Call ErrorMessage(Extender.Name & ".CatchBy()")
End Sub

Private Function WithParent() As Boolean
On Error GoTo Trace_Err
    
    If m_Project = "" And m_Customer = "" And m_Contact = "" And m_Product = "" And m_Action = "" Then
        WithParent = False
    Else
        WithParent = True
    End If

    Exit Function
Trace_Err:
    Call ErrorHandler(Extender.Name & ".WithParent()")
End Function

' Change the display mode
Private Sub SwapToDisplayMode(li_DisplayMode As Integer, Optional ls_Params As String = "")
On Error GoTo Trace_Err
    mb_InternalInit = True
    
    mi_OldDisplayMode = mi_DisplayMode
   
    'When a component is root, it can't select the list mode
    If mb_Root And (li_DisplayMode = mt_CstValues.DisplayMode_List) And (EmbeddedIn = -1) Then
        li_DisplayMode = mt_CstValues.DisplayMode_View
    End If
    mi_DisplayMode = li_DisplayMode
   
    'We should hide all graphics frames before resize and move it
    DisplayMode_None
    
    Select Case mi_DisplayMode
        Case mt_CstValues.DisplayMode_List
            'the component is embedded
            ShortListDisplay ls_Params
        
        Case mt_CstValues.DisplayMode_View
                ViewDisplay
            
        Case mt_CstValues.DisplayMode_Update
                UpdateDisplay
            
        Case mt_CstValues.DisplayMode_Add
                AddDisplay
            
        Case mt_CstValues.DisplayMode_Delete
                DeleteDisplay
    End Select
    
    mb_InternalInit = False
    Exit Sub
    
Trace_Err:
    mb_InternalInit = False
    Call ErrorHandler(Extender.Name & ".SwapToDisplayMode()")
End Sub

' Hide all graphics elements
Private Sub DisplayMode_None()
On Error GoTo Trace_Err
    
   With UserControl
        .fraItem.Visible = False
        .fraList.Visible = False
    End With
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".DisplayMode_None()")
End Sub

Private Sub ViewLoad()
End Sub

Private Sub ShortListDisplay(ByVal ls_Params As String)
On Error GoTo Trace_Err
    
    RaiseEvent SwitchToView(mt_CstValues.View_Embedded)
   
    ShortList_Resize
        
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".ShortListDisplay()")
End Sub


Private Sub pbSubitem_action(ByVal as_ActionType As String)
On Error GoTo Trace_Err
    Dim lb_Result As Boolean

    CapMouseOff
    
    Select Case UCase$(as_ActionType)

        Case UCase$("Add")
            Call AddDisplaySubItem("", qtStandard)
            
        Case UCase$("Update")
            If grd_quote.SelectedCount = 1 Then
                Call UpdateDisplaySubItem
            Else
                Call ASC_SendMessage(mo_ArmDb, m_Language, WarMsgSelectRow, "#Please select a row.")
            End If
        
        Case UCase$("Delete")
            If grd_quote.SelectedCount = 1 Then
                Call DeleteDisplaySubItem
            Else
                Call ASC_SendMessage(mo_ArmDb, m_Language, WarMsgSelectRow, "#Please select a row.")
            End If
            
        Case UCase$("Quit")
            Call SwapToDisplayModeSubitem(mt_CstValues.DisplayMode_List)
            If DisplayMode = mt_CstValues.DisplayMode_Add Then
                Call Add_Enablecontrols
            End If

        Case UCase$("Refresh")
            Call grd_quote.Refresh
            
        Case UCase$("Valid")
            lb_Result = False

            Select Case ml_DisplayModeSubItem
                Case mt_CstValues.DisplayMode_Add
                    lb_Result = SubRecordAdd()
                Case mt_CstValues.DisplayMode_Update
                    If grd_quote.SelectedCount = 1 Then
                        lb_Result = SubRecordUpdate(grd_quote.CurrentKey(0))
                    End If
                Case mt_CstValues.DisplayMode_Delete
                    If grd_quote.SelectedCount = 1 Then
                        lb_Result = SubRecordDelete(grd_quote.CurrentKey(0))
                    End If
            End Select
            If lb_Result Then
                Call SwapToDisplayModeSubitem(mt_CstValues.DisplayMode_List)
            End If
        Case UCase$("Undo")
            ' 22.5.2008 JN fix reload data
            Select Case ml_DisplayModeSubItem
                Case mt_CstValues.DisplayMode_Add
                    Debug.Assert (Not cbo_customer.SelectedItem Is Nothing)
                    Call AddDisplaySubItem(cbo_customer.SelectedItem.Key, qtStandard)
                Case mt_CstValues.DisplayMode_Update
                    Debug.Assert (grd_quote.SelectedCount = 1)
                    Call UpdateDisplaySubItem
                Case Else
                    Debug.Assert (False)
            End Select
    End Select
    CapMouseOn
    Exit Sub
Trace_Err:
    Select Case Err.Number
    Case ArmErr.SQLBadRowExpectedCount
        Call ASC_SendMessage(mo_ArmDb, m_Language, 2138, "#The record you try to open has been deleted by an other user. Please refresh the grid.", , vbInformation)
        CapMouseOn
        Exit Sub
    Case ArmErr.SQLBadRowAffectedCount
        Call ASC_SendMessage(mo_ArmDb, m_Language, 916, "#This data has been updated by another user. Data will be reloaded. Please check the data and try again.", , vbInformation)
        Dim lv_Key As Variant
        lv_Key = grd_quote.SelectedKey(0)
        Call grd_quote.Refresh
        If grd_quote.SearchKey(True, lv_Key) Then
            Call ViewInitFieldsSubItem(ml_DisplayModeSubItem)
        Else
            Call SwapToDisplayModeSubitem(mt_CstValues.DisplayMode_List)
        End If
        CapMouseOn
        Exit Sub
    End Select

    Call ErrorMessage(Extender.Name & ".pbSubitem_action()")
    CapMouseOn
End Sub

Private Sub tbs_quoteDetail_Click()
On Error GoTo Trace_Err
    If mb_InternalInit Then Exit Sub
    
    CapMouseOff
    
    Dim lo_Frm As Frame
    For Each lo_Frm In fraSubItemMain
        lo_Frm.Visible = (lo_Frm.Tag = tbs_quoteDetail.SelectedItem.Tag)
    Next

    CapMouseOn
    Exit Sub
Trace_Err:
    Call ErrorMessage(Extender.Name & ".tbsEmbedded_Click()")
    CapMouseOn
End Sub

' Embed a component
Private Sub tbsEmbedded_Click()
On Error GoTo Trace_Err
    
    If mi_EmbedTag = UserControl.tbsEmbedded.SelectedItem.Tag Then Exit Sub
    
    CapMouseOff
    With UserControl
        
        If mi_EmbedTag <> -1 Then
            RaiseEvent Release
            mi_EmbedTag = -1
        End If
        
        If .tbsEmbedded.SelectedItem.Index = 1 Then
            If mi_EmbeddedIn <> -1 Then
                 RaiseEvent SwitchToView(mt_CstValues.View_Medium)
            End If
            .fraItemBottom.Visible = True
        Else
            .fraItemBottom.Visible = False
            If mi_EmbeddedIn <> -1 Then
                If .tbsEmbedded.SelectedItem.Tag = mt_CstValues.Tag_Memo Then
                     RaiseEvent SwitchToView(mt_CstValues.View_Medium)
                Else
                    RaiseEvent SwitchToView(mt_CstValues.View_Full)
                End If
            End If
            mi_EmbedTag = .tbsEmbedded.SelectedItem.Tag
            RaiseEvent Catch(mi_EmbedTag, m_CurrentKey1 & CH_LDELIMIT & m_CurrentKey2)
        End If
    End With

    CapMouseOn
    Exit Sub
Trace_Err:
    Call ErrorMessage(Extender.Name & ".tbsEmbedded_Click()")
    CapMouseOn
End Sub


Private Sub AddInitFields()
On Error GoTo Trace_Err
    Dim ls_Request As String
    Dim ll_cursor As Long
    Dim ll_Ref As Long
    Dim ls_AMCPrjNo As String
    

    
    If Not cbo_Status.SearchItem(eQuoteStatus.qsActive, "RF_Code", 1) Then
        Call cbo_Status.Load
        Call cbo_Status.SearchItem(eQuoteStatus.qsActive, "RF_Code", 1)
    End If
    
    ls_Request = "SELECT SP.sp_desc, PR.SR_Code, SP.iConcurrency, (SELECT ISNULL(MAX(CSQ.SQT_Ref),100) + 1 FROM Cap_SOM_Quote CSQ WHERE CSQ.SP_CapKey=SP.SP_Capkey) AS NextRef, SPAMC.AMCProjectNumber " & _
                "FROM sales_project SP " & _
                "   LEFT JOIN Sales_ProjectAMC SPAMC ON SPAMC.SP_CapKey=SP.SP_Capkey AND SPAMC.Language_code='E'" & _
                "   LEFT JOIN Cap_ProjectRep PR ON PR.SP_CapKey = SP.SP_Capkey AND PR.RR_code=2 AND PR.Language_code='E' AND PR.drop_flag<>'X' " & _
                "WHERE SP.sp_Capkey='" & m_Project & "'"
    
    ll_cursor = OpenSQLSafe(mo_ArmDb, ls_Request)

    txt_SP_Desc.Text = mo_ArmDb.GetFields(ll_cursor, "SP_Desc")
    prj_iConc = mo_ArmDb.GetFields(ll_cursor, "iConcurrency")
    ms_SR_Code = mo_ArmDb.GetFields(ll_cursor, "SR_Code")
    ll_Ref = mo_ArmDb.GetFields(ll_cursor, "NextRef")
    ls_AMCPrjNo = mo_ArmDb.GetFields(ll_cursor, "AMCProjectNumber")
    
    If Not cbo_SalesRep.SearchItem(ms_SR_Code) Then
        Call cbo_SalesRep.Load
        Call cbo_SalesRep.SearchItem(ms_SR_Code)
    End If
    Call mo_ArmDb.Close(ll_cursor)
    ll_cursor = 0
    
    txt_Quot_ID.Text = "NEW"
    txt_SQT_Reference.Text = ls_AMCPrjNo & "." & ll_Ref

    txt_CreatedBy.Text = ms_UID
    txt_updatedBy.Text = ms_UID
    txt_DateEntered.Text = Format(Date, "dd\/mm\/yyyy")
    txt_dateUpdated.Text = Format(Date, "dd\/mm\/yyyy")
    
    Call cbo_currencies.Load
    If Not cbo_currencies.SearchItem("CHF", "CURR_Code", 1) Then
        Call cbo_currencies.AddItem(Array("CHF", "CHF", 1, 0), True)
    End If
    
'    Call cbo_FreightCurr.Load
 '   If cbo_FreightCurr.Count > 0 Then
 '       Set cbo_FreightCurr.SelectedItem = cbo_FreightCurr.ComboItems(1)
 '   End If
    
'    Call cbo_realisation.Load
'    If cbo_realisation.Count > 0 Then
'        Set cbo_realisation.SelectedItem = cbo_realisation.ComboItems(1)
'    End If
    
    chk_dropFlag.Visible = False
    txt_dropDate.Visible = False

    ' for add mode we do not have docs tab
    Call trw_doc.Clear
    Call grd_doc.ClearGrid
    grd_doc.Requests = ""

    trw_doc.GridRequests = Array("", "", "", "")        ' 31.1.2012 JN bug - not all requests are removed when assign "" only
'    Array( _
'        "EXEC Cap_SOM_Doc_file_lst NULL, $0$, '" & m_Language & "'", _
'        "EXEC Cap_SOM_Doc_file_lst NULL, $0$, '" & m_Language & "'", _
'        "EXEC Cap_SOM_Doc_file_lst NULL, $0$, '" & m_Language & "'")

    If Not trw_doc.LoadTree(LoadTypeChildsDemand) Then
        Err.Raise CompFncFailed, "trw_doc.LoadTree", "Treeview of items cannot be loaded."
    End If


    DisplayDefaultValues
    
    Exit Sub
    
Trace_Err:
    If ll_cursor > 0 Then
        Call mo_ArmDb.Close(ll_cursor)
        ll_cursor = 0
    End If
    Call ErrorHandler(Extender.Name & ".AddInitFields()")
End Sub

Private Sub BlankFields()
On Error GoTo Trace_Err
    Dim TheRequest As String
    
    mb_InternalInit = True

    txt_SQT_Reference.Text = ""
    txt_QuoteRef.Text = ""
    txt_Revision.Text = ""
    txt_SP_Desc.Text = ""
    txt_Comment.Text = ""
    txt_FreightCost.Text = ""
    txt_FreightCostCHF.Text = ""

    txt_TOT_ValueLC.Text = ""
    txt_TOT_DB.Text = ""
    txt_TOT_ValueCHF.Text = ""
    txt_TOT_PrimeMarg.Text = ""
    
    Call cbo_customer.Clear
    Call cbo_BO.Clear
    Call cbo_SalesRep.Clear
    Set cbo_Status.SelectedItem = Nothing
    Call cbo_currencies.Clear
    Call cbo_FreightCurr.Clear
    Call cbo_realisation.Clear
    
    opt_Type(0).Value = False
    opt_Type(1).Value = False

    opt_include(0).Value = False
    opt_include(1).Value = False

    cal_ValidUntil.reinit_cal
    chk_dropFlag.Value = 0
    txt_dropDate.Text = ""
    
    Call grd_quote.ClearGrid
    
    Set tbs_quoteDetail.SelectedItem = tbs_quoteDetail.Tabs("ITEMS")
    fraSubItemMain(0).Visible = True
    fraSubItemMain(1).Visible = False
    
    p_iCon = 0
    
    mb_InternalInit = False
    Exit Sub
Trace_Err:
    mb_InternalInit = False
    Call ErrorHandler(Extender.Name & ".BlankFields()")
End Sub

Private Sub DisplayDefaultValues()
On Error GoTo Trace_Err
    Dim i As Integer
    Dim TheControl As Control
    Dim TheControlName As String
    
    mb_InternalInit = True

    
    If p_DefaultValuesLoaded = False Then
        p_DefaultValuesCount = GetScreenDefaultValues(mo_ArmDb, ms_UID, m_Language, "Cap_Quote_Detail", p_DefaultValues)
        p_DefaultValuesLoaded = True
    End If
    DisplayScreenDefaultValues UserControl.Controls, p_DefaultValues, p_DefaultValuesCount
    
    mb_InternalInit = False

    Exit Sub
Trace_Err:
    mb_InternalInit = False
    Call ErrorHandler(Extender.Name & ".DisplayDefaultValues()")
End Sub

Private Sub ViewInitFields()
On Error GoTo Trace_Err
Const C_REQ_SEL As String = "EXEC Cap_SOM_Quote_sel $SQT_ID$, '$Language_code$'"
Const C_REQ_ITEMS_LST As String = "EXEC Cap_SOM_QuoteDetail_lst $SQT_ID$, '$Language_code$'"
    Dim ls_Request As String
    Dim ll_cursor As Long

    'Si pas de clé en cours, ie pas de ligne en grille sélectionnée alors bye
    If m_CurrentKey1 = "" Then Exit Sub
    
    mb_InternalInit = True
    
    txt_Quot_ID.Text = m_CurrentKey1
    
    ls_Request = ReplaceString(C_REQ_SEL, "$SQT_ID$", m_CurrentKey1)
    ls_Request = ReplaceString(ls_Request, "$Language_code$", m_Language)
    ll_cursor = OpenSQLSafe(mo_ArmDb, ls_Request)
    
    txt_SQT_Reference.Text = mo_ArmDb.GetFields(ll_cursor, "SQT_Reference")
    txt_QuoteRef.Text = mo_ArmDb.GetFields(ll_cursor, "SQT_Ref")
    txt_Revision.Text = mo_ArmDb.GetFields(ll_cursor, "SQT_Revision")
    txt_SP_Desc.Text = mo_ArmDb.GetFields(ll_cursor, "SP_Desc")
    txt_Comment.Text = mo_ArmDb.GetFields(ll_cursor, "SQT_Comment")
    txt_FreightCost.Text = mo_ArmDb.GetFields(ll_cursor, "FRGHTCostLC")
    txt_FreightCostCHF.Text = mo_ArmDb.GetFields(ll_cursor, "SQT_FRGHTCost_CHF")
    
    Call cbo_customer.AddItem(Array(mo_ArmDb.GetFields(ll_cursor, "CCU_CapKey"), mo_ArmDb.GetFields(ll_cursor, "CCU_Desc")), True)
    Call cbo_SalesRep.AddItem(Array(mo_ArmDb.GetFields(ll_cursor, "SR_code"), mo_ArmDb.GetFields(ll_cursor, "SR_name")), True)
    Call cbo_BO.AddItem(Array(mo_ArmDb.GetFields(ll_cursor, "BO_SSR_Code"), mo_ArmDb.GetFields(ll_cursor, "BO_SSR_desc")), True)
    
    Call cbo_Status.AddItem(Array(mo_ArmDb.GetFields(ll_cursor, "SQT_Status"), mo_ArmDb.GetFields(ll_cursor, "SQT_Status_Desc")), True)
    
    Call cbo_currencies.AddItem(Array(CStr(mo_ArmDb.GetFields(ll_cursor, "CURR_code")), mo_ArmDb.GetFields(ll_cursor, "CURR_code"), mo_ArmDb.GetFields(ll_cursor, "CURR_Q_EXCH_rate"), mo_ArmDb.GetFields(ll_cursor, "CURR_Q_iConcurrency")), True)
    Call cbo_FreightCurr.AddItem(Array(CStr(mo_ArmDb.GetFields(ll_cursor, "FRGHT_CURR_Code")), mo_ArmDb.GetFields(ll_cursor, "FRGHT_CURR_Code"), mo_ArmDb.GetFields(ll_cursor, "CURR_FRGH_EXCH_rate"), mo_ArmDb.GetFields(ll_cursor, "CURR_FRGH_iConcurrency")), True)
    Call cbo_realisation.AddItem(Array(CStr(mo_ArmDb.GetFields(ll_cursor, "RL_Code")), mo_ArmDb.GetFields(ll_cursor, "RL_Desc")), True)
    
    If mo_ArmDb.GetFields(ll_cursor, "SQT_Include") = GetStringItem(opt_include(0).Tag, 0) Then
        opt_include(0).Value = True
    ElseIf mo_ArmDb.GetFields(ll_cursor, "SQT_Include") = GetStringItem(opt_include(1).Tag, 0) Then
        opt_include(1).Value = True
    End If
    
    If mo_ArmDb.GetFields(ll_cursor, "SQT_Type") = GetStringItem(opt_Type(0).Tag, 0) Then
        opt_Type(0).Value = True
    ElseIf mo_ArmDb.GetFields(ll_cursor, "SQT_Type") = GetStringItem(opt_Type(1).Tag, 0) Then
        opt_Type(1).Value = True
    End If
    
    If mo_ArmDb.GetFields(ll_cursor, "SQT_ValidToDate") <> 0 Then
        cal_ValidUntil.date_courte = Format(mo_ArmDb.GetFields(ll_cursor, "SQT_ValidToDate"), "dd\/mm\/yyyy")
    Else
        Call cal_ValidUntil.reinit_cal
    End If
  
    txt_DateEntered.Text = CDate(Int(mo_ArmDb.GetFields(ll_cursor, "Z_Creation")))
    txt_dateUpdated.Text = CDate(Int(mo_ArmDb.GetFields(ll_cursor, "Z_Last_Upd")))
    txt_CreatedBy.Text = mo_ArmDb.GetFields(ll_cursor, "Z_Creator")
    txt_updatedBy.Text = mo_ArmDb.GetFields(ll_cursor, "Z_Last_Upd_User")

    p_iCon = mo_ArmDb.GetFields(ll_cursor, "iConcurrency")
    ms_SR_Code = mo_ArmDb.GetFields(ll_cursor, "PR_SR_Code")
    
    chk_dropFlag.Value = IIf(mo_ArmDb.GetFields(ll_cursor, "drop_flag") = "X", 1, 0)
    txt_dropDate.Text = Cap_FormatDate(mo_ArmDb.GetFields(ll_cursor, "drop_date"))

    Call mo_ArmDb.Close(ll_cursor)
    ll_cursor = 0
    
    chk_dropFlag.Visible = chk_dropFlag.Value
    txt_dropDate.Visible = chk_dropFlag.Value

    
    ls_Request = Replace(C_REQ_ITEMS_LST, "$SQT_ID$", m_CurrentKey1, , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$Language_code$", m_Language, , , vbTextCompare)
    
    If Not grd_quote.Load(ls_Request, True) Then
        Call Err.Raise(CompFncFailed, "", "grd_Quote.Load failed.")
    End If
    Call grd_doc.ClearGrid
    grd_doc.Requests = ""

    trw_doc.GridRequests = Array( _
        "EXEC Cap_SOM_Doc_file_lst " & m_CurrentKey1 & ", $0$, '" & m_Language & "'", _
        "EXEC Cap_SOM_Doc_file_lst " & m_CurrentKey1 & ", $0$, '" & m_Language & "'", _
        "EXEC Cap_SOM_Doc_file_lst " & m_CurrentKey1 & ", $0$, '" & m_Language & "'", _
        "EXEC Cap_SOM_Doc_file_lst " & m_CurrentKey1 & ", $0$, '" & m_Language & "'")

    If Not trw_doc.LoadTree(LoadTypeChildsDemand) Then
        Err.Raise CompFncFailed, "trw_doc.LoadTree", "Treeview of items cannot be loaded."
    End If

    ' recalc TOTal values
    Call CalculationTOT(mt_CstValues.DisplayMode_View)  ' allways look as view
    
    mb_InternalInit = False
    Exit Sub
    
Trace_Err:
    mb_InternalInit = False
    If ll_cursor > 0 Then
        Call mo_ArmDb.Close(ll_cursor)
        ll_cursor = 0
    End If
    Call ErrorHandler(Extender.Name & ".ViewInitFields()")
End Sub

Private Sub ListProjectOf(ByVal AProjectKey1 As String, ByVal AProjectKey2 As String)
On Error GoTo Trace_Err
Const C_REQ As String = "EXEC Cap_SOM_Quote_lst '$SP_Capkey$', '$Language_code$'"

    If Not (AProjectKey1 <> "" And AProjectKey2 <> "") Then Exit Sub
    Call grdlst.ClearGrid
    
    Dim ls_Request As String
    
    ls_Request = ReplaceString(C_REQ, "$Language_Code$", m_Language, rt_string)
    ls_Request = ReplaceString(ls_Request, "$SP_Capkey$", m_Project, rt_string)
    
    If Not grdlst.Load(ls_Request, True) Then
        Call Err.Raise(CompFncFailed, "", "grdlst.Load failed.")
    End If

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".ListProjectOf()")
End Sub

Private Sub ListCustomerOf(ACustomerkey1 As String, ACustomerkey2 As String)
    ' no Customer - Quote navigation link
End Sub

Private Sub ListContactOf(AContactKey1 As String, AContactKey2 As String, AContactKey3 As String)
    ' no Contact - Quote navigation link
End Sub

' This function is called by the application when the component embedded is updated
Public Sub Embedded_Updated()
' DO NOTHING
End Sub

Private Sub SwapToDisplayModeDoc(ByVal al_Mode As Long)
On Error GoTo Trace_Err
    If al_Mode = mt_CstValues.DisplayMode_None Then
        fraSubItemMain(1).Visible = False
        ' remove "DOCS" tab from tbs_quoteDetail
'        If TabExists(tbs_quoteDetail, "DOCS") Then
'            Call tbs_quoteDetail.Tabs.Remove("DOCS")
'        End If
        
        mi_DisplayModeDoc = al_Mode
        Exit Sub
    End If
    
    'update toolbar
    Select Case al_Mode
        Case mt_CstValues.DisplayMode_View
            pbDoc.ClearAllIcons
            pbDoc.PictureDisplayed = "P_Refresh=5 P_Save=-2 P_Media=-1"
            fraDocUpload.Visible = True
            trw_doc.Visible = False
            grd_doc.Visible = False
        Case mt_CstValues.DisplayMode_List
            pbDoc.ClearAllIcons
            Select Case mi_DisplayMode
                Case mt_CstValues.DisplayMode_View
                    pbDoc.PictureDisplayed = "P_Refresh=5 P_Save=-2 P_Media=-1"
                Case mt_CstValues.DisplayMode_Delete
                    pbDoc.PictureDisplayed = "P_Refresh=5"
                Case Else
                    pbDoc.PictureDisplayed = "P_Add=1 P_Update=2 P_Delete=3 P_Refresh=5 P_Save=-2 P_Media=-1"
            End Select
            fraDocUpload.Visible = False
            trw_doc.Visible = True
            grd_doc.Visible = True
            
            ' add "DOCS" tab from tbs_quoteDetail
'            If Not TabExists(tbs_quoteDetail, "DOCS") Then
'                tbs_quoteDetail.Tabs.Add(, "DOCS", lbl_label(24).Caption).Tag = "DOCS"
'            End If
            
        Case mt_CstValues.DisplayMode_Delete
            pbDoc.ClearAllIcons
            pbDoc.PictureDisplayed = "P_Valid=1 P_Quit=-1"
'            pbDoc.PictureDisplayed = "P_Refresh=5 P_Save=-2 P_Media=-1"
            fraDocUpload.Visible = True
            trw_doc.Visible = False
            grd_doc.Visible = False
        Case mt_CstValues.DisplayMode_Add, mt_CstValues.DisplayMode_Update
            pbDoc.ClearAllIcons
            pbDoc.PictureDisplayed = "P_Valid=1 P_UnDo=2 P_Quit=-1"
            fraDocUpload.Visible = True
            trw_doc.Visible = False
            grd_doc.Visible = False
    End Select
    
    fraSubItemMain(1).Left = tbs_quoteDetail.Left + tbs_quoteDetail.Width
    fraSubItemMain(1).Top = tbs_quoteDetail.Top - 2 * mt_CstValues.Frm_Margin
    fraSubItemMain(1).Width = fraItem.Width - fraSubItemMain(1).Left - 2 * mt_CstValues.Frm_Margin
    fraSubItemMain(1).Height = tbs_quoteDetail.Height + 2 * mt_CstValues.Frm_Margin

    pbDoc.Left = fraSubItemMain(1).Width - pbDoc.Width - mt_CstValues.Frm_Margin
    pbDoc.Top = 3 * mt_CstValues.Frm_Margin
    pbDoc.Height = fraSubItemMain(1).Height - 4 * mt_CstValues.Frm_Margin
    
    trw_doc.Left = mt_CstValues.Frm_Margin
    trw_doc.Top = 3 * mt_CstValues.Frm_Margin
    trw_doc.Height = fraSubItemMain(1).Height - 4 * mt_CstValues.Frm_Margin
    
    grd_doc.Left = trw_doc.Left + trw_doc.Width
    grd_doc.Top = trw_doc.Top
    grd_doc.Width = fraSubItemMain(1).Width - grd_doc.Left - mt_CstValues.Frm_Margin - pbDoc.Width
    grd_doc.Height = fraSubItemMain(1).Height - grd_doc.Top
    
    fraDocUpload.Top = pbDoc.Top
    fraDocUpload.Left = pbDoc.Left - fraDocUpload.Width - mt_CstValues.Frm_Margin
    
    mi_DisplayModeDoc = al_Mode

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".SwapToDisplayModeSubitem()")
End Sub

Private Function TabExists(ByRef ao_TabStrip As MSComctlLib.TabStrip, ByVal as_TabKey As String) As Boolean
On Error GoTo Trace_Err
    Dim lo_Tab As MSComctlLib.Tab
    
    TabExists = False
    
    For Each lo_Tab In ao_TabStrip.Tabs
        If lo_Tab.Key = as_TabKey Then
            TabExists = True
            Exit Function
        End If
    Next

    Exit Function
Trace_Err:
    Call ErrorHandler(Extender.Name & ".TabExists()")
End Function

Private Sub SwapToDisplayModeSubitem(ByVal al_Mode As Long)
On Error GoTo Trace_Err

    If al_Mode = mt_CstValues.DisplayMode_None Then
        fraSubItemMain(0).Visible = False
    End If

    'update toolbar
    Select Case al_Mode
        Case mt_CstValues.DisplayMode_View
            pbSubitem.ClearAllIcons
            pbSubitem.PictureDisplayed = "P_Quit=-1"
        Case mt_CstValues.DisplayMode_List
            pbSubitem.ClearAllIcons
            pbSubitem.TableName = ""
            Select Case mi_DisplayMode
                Case mt_CstValues.DisplayMode_View
                    pbSubitem.PictureDisplayed = "P_Refresh=5"  ' P_FrameContract=-1"
                Case mt_CstValues.DisplayMode_Delete
                    pbSubitem.PictureDisplayed = "P_Refresh=5"
                Case Else
                    pbSubitem.PictureDisplayed = "P_Add=1 P_Update=2 P_Delete=3"    ' P_Refresh=5"
            End Select
        Case mt_CstValues.DisplayMode_Delete
            pbSubitem.ClearAllIcons
            pbSubitem.PictureDisplayed = "P_Valid=1 P_Quit=-1"
        Case mt_CstValues.DisplayMode_Add, mt_CstValues.DisplayMode_Update
            pbSubitem.ClearAllIcons
            pbSubitem.PictureDisplayed = "P_Valid=1 P_UnDo=2 P_Quit=-1"
    End Select
    
    fraSubItemMain(0).Left = tbs_quoteDetail.Left + tbs_quoteDetail.Width
    fraSubItemMain(0).Top = tbs_quoteDetail.Top - 2 * mt_CstValues.Frm_Margin
    fraSubItemMain(0).Width = fraItem.Width - fraSubItemMain(0).Left - 2 * mt_CstValues.Frm_Margin
    fraSubItemMain(0).Height = tbs_quoteDetail.Height + 2 * mt_CstValues.Frm_Margin
    
    
    pbSubitem.Left = fraSubItemMain(0).Width - pbSubitem.Width - mt_CstValues.Frm_Margin
    pbSubitem.Top = 3 * mt_CstValues.Frm_Margin
    pbSubitem.Height = fraSubItemMain(0).Height - 4 * mt_CstValues.Frm_Margin
    
    
    fra_TOT.Left = mt_CstValues.Frm_Margin
    fra_TOT.Top = fraSubItemMain(0).Height - fra_TOT.Height - mt_CstValues.Frm_Margin
    fra_TOT.Width = fraSubItemMain(0).Width - pbSubitem.Width - 3 * mt_CstValues.Frm_Margin
    
    
    ' update subitem frame
    Select Case al_Mode
        Case mt_CstValues.DisplayMode_List
            fra_Detail.Visible = False
            Call grd_quote.Move(mt_CstValues.Frm_Margin, pbSubitem.Top, fra_TOT.Width + mt_CstValues.Frm_Margin, pbSubitem.Height - fra_TOT.Height)
            pbItem.Enabled = True
            grd_quote.Enabled = True
'            cbo_customer.Enabled = (al_Mode = mt_CstValues.DisplayMode_List)       ' JN14/06/2012 why is this line here?

        Case mt_CstValues.DisplayMode_Add, mt_CstValues.DisplayMode_Update, mt_CstValues.DisplayMode_Delete, mt_CstValues.DisplayMode_View
            Call fra_Detail.Move(mt_CstValues.Frm_Margin, 3 * mt_CstValues.Frm_Margin, fra_TOT.Width)
            Call grd_quote.Move(mt_CstValues.Frm_Margin, fra_Detail.Top + fra_Detail.Height, fra_TOT.Width + mt_CstValues.Frm_Margin, pbSubitem.Height - fra_TOT.Height - fra_Detail.Height)
            fra_Detail.Visible = True
            pbItem.Enabled = False
            grd_quote.Enabled = False
    End Select
    ml_DisplayModeSubItem = al_Mode
    Call fraSubItemMain(0).Refresh
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".SwapToDisplayModeSubitem()")
End Sub

Private Sub InitSubitem()
On Error GoTo Trace_Err
Dim la_Columns() As String

    grd_quote.Load_A_Com
    grd_quote.ResetGrid
    grd_quote.MultiSelect = False
    grd_quote.AllowSort = False
    
    ReDim la_Columns(14)
    la_Columns(0) = "SQD_ID" & CH_LDELIMIT & "0" & CH_LDELIMIT & "1" & CH_LDELIMIT & "SQD_ID" & CH_LDELIMIT & "#SQD_ID"
    la_Columns(1) = "SS_Code" & CH_LDELIMIT & "0" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SS_Code" & CH_LDELIMIT & "#SS_Code"
    la_Columns(2) = "SS_Desc" & CH_LDELIMIT & "4900" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SS_Desc" & CH_LDELIMIT & "#System"
    la_Columns(3) = "SQD_Type" & CH_LDELIMIT & "0" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SQD_Type" & CH_LDELIMIT & "#Type code"
    la_Columns(4) = "SQD_Type_Desc" & CH_LDELIMIT & "1300" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SQD_Type_Desc" & CH_LDELIMIT & "#Type"
    la_Columns(5) = "SQD_Area" & CH_LDELIMIT & "900" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SQD_Area" & CH_LDELIMIT & "#SQD_Area" & CH_LDELIMIT & "INT"
    la_Columns(6) = "UM_Code" & CH_LDELIMIT & "0" & CH_LDELIMIT & "0" & CH_LDELIMIT & "UM_Code" & CH_LDELIMIT & "#UM_Code"
    la_Columns(7) = "UM_Desc" & CH_LDELIMIT & "1300" & CH_LDELIMIT & "0" & CH_LDELIMIT & "UM_Desc" & CH_LDELIMIT & "#UoM"
    la_Columns(8) = "SQD_ValueLC" & CH_LDELIMIT & "1500" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SQD_ValueLC" & CH_LDELIMIT & "#Value quot" & CH_LDELIMIT & "INT"
    la_Columns(9) = "SQD_DB" & CH_LDELIMIT & "1200" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SQD_DB" & CH_LDELIMIT & "#DB %"
    la_Columns(10) = "SQD_Value_CHF" & CH_LDELIMIT & "1200" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SQD_Value_CHF" & CH_LDELIMIT & "#Value CHF" & CH_LDELIMIT & "INT"
    la_Columns(11) = "SQD_PrimeMargin" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SQD_PrimeMargin" & CH_LDELIMIT & "#Prime margin" & CH_LDELIMIT & "FLOAT" & CH_LDELIMIT & MONEY_FORMAT
    la_Columns(12) = "SQD_TypeOld" & CH_LDELIMIT & "0" & CH_LDELIMIT & "0" & CH_LDELIMIT & "SQD_Type" & CH_LDELIMIT & "#Type code"
    la_Columns(13) = "UPD_ACTION" & CH_LDELIMIT & "0" & CH_LDELIMIT & "0" & CH_LDELIMIT & "UPD_ACTION" & CH_LDELIMIT & "#UpdAction"
    la_Columns(14) = "iConcurrency" & CH_LDELIMIT & "0" & CH_LDELIMIT & "0" & CH_LDELIMIT & "iConcurrency" & CH_LDELIMIT & "#iConcurrency"
    grd_quote.SetColumns la_Columns
    grd_quote.LoadConstants ptSQL, "EXEC screen_csts_lst2 'CapSOMQuoteItems_grid', 'grid', '" & m_Language & "'", ctColumns

    grd_doc.Load_A_Com
    grd_doc.ResetGrid
    grd_doc.MultiSelect = False
    grd_doc.AllowSort = False
    grd_doc.Title = ""
    
    ReDim la_Columns(7)
    la_Columns(0) = "fileID" & CH_LDELIMIT & "0" & CH_LDELIMIT & "1" & CH_LDELIMIT & "fileID" & CH_LDELIMIT & "#fileID" & CH_LDELIMIT & "INT"
    la_Columns(1) = "FileTitle" & CH_LDELIMIT & "2300" & CH_LDELIMIT & "0" & CH_LDELIMIT & "FileTitle" & CH_LDELIMIT & "#FileTitle"
    la_Columns(2) = "FileName" & CH_LDELIMIT & "2100" & CH_LDELIMIT & "0" & CH_LDELIMIT & "FileName" & CH_LDELIMIT & "#FileName"
    la_Columns(3) = "Z_Creation" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "Z_Creation" & CH_LDELIMIT & "#Z_Creation"
    la_Columns(4) = "Z_Creator" & CH_LDELIMIT & "1200" & CH_LDELIMIT & "0" & CH_LDELIMIT & "Z_Creator" & CH_LDELIMIT & "#Z_Creator"
    la_Columns(5) = "Z_Last_Upd" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "Z_Last_Upd" & CH_LDELIMIT & "#Z_Last_Upd"
    la_Columns(6) = "Z_Last_Upd_User" & CH_LDELIMIT & "1200" & CH_LDELIMIT & "0" & CH_LDELIMIT & "Z_Last_Upd_User" & CH_LDELIMIT & "#Z_Last_Upd_User"
    la_Columns(7) = "fileZipID" & CH_LDELIMIT & "0" & CH_LDELIMIT & "0" & CH_LDELIMIT & "fileZipID" & CH_LDELIMIT & "#fileZipID" & CH_LDELIMIT & "INT"
    grd_doc.SetColumns la_Columns
    grd_doc.LoadConstants ptSQL, "EXEC screen_csts_lst2 'CapSOMQuoteDocs_grid', 'grid', '" & m_Language & "'", ctColumns
    
    
    trw_doc.Load_A_Com
    trw_doc.Language = m_Language
    trw_doc.Levels = 4
    trw_doc.StartDemandLevel = 1
    trw_doc.UseImages = True
    trw_doc.Images = Array(1, 1, 1, 1)
    trw_doc.SelectedImages = Array(2, 2, 2, 2)
    trw_doc.RemoveNodeDuplicity = True
    
    trw_doc.NodeRequests = Array( _
        "SELECT nodeID, parentID, nodeDesc FROM Cap_SOM_Doc_tree WHERE ParentID IS NULL AND Language_code = '" & m_Language & "' AND drop_flag=''", _
        "SELECT nodeID, parentID, nodeDesc FROM Cap_SOM_Doc_tree WHERE ParentID=$0$ AND Language_code = '" & m_Language & "' AND drop_flag=''", _
        "SELECT nodeID, parentID, nodeDesc FROM Cap_SOM_Doc_tree WHERE ParentID=$0$ AND Language_code = '" & m_Language & "' AND drop_flag=''", _
        "SELECT nodeID, parentID, nodeDesc FROM Cap_SOM_Doc_tree WHERE ParentID=$0$ AND Language_code = '" & m_Language & "' AND drop_flag=''")

    cbo_System.Load_A_Com
    cbo_System.FirstBlankItem = False
    cbo_System.Request = "exec SOM_System_cbo '" & m_Language & "'"
    
    cbo_UM.Load_A_Com
    cbo_UM.FirstBlankItem = False
    cbo_UM.Request = "exec SOM_UM_cbo '" & m_Language & "'"
    
    cbo_SQD_Type.Load_A_Com
    cbo_SQD_Type.FirstBlankItem = False
    cbo_SQD_Type.Request = "EXEC A_References_ML_Lst 56, '" & m_Language & "'"

    
    Call SwapToDisplayModeSubitem(mt_CstValues.DisplayMode_None)
    Call SwapToDisplayModeDoc(mt_CstValues.DisplayMode_None)

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".InitSubitem()")
End Sub


Private Sub AddDisplaySubItem(ByVal ls_CCU_Capkey As String, ByVal ae_QuoteType As eQuoteType)
On Error GoTo Trace_Err
    
    BlankFieldsSubItem
    
    Call ControlsEnable(UserControl.Controls, fra_Detail, True)
    
    Set cbo_System.SelectedItem = Nothing
    
    Call grd_quote.DeselectRow
    
    Call SwapToDisplayModeSubitem(mt_CstValues.DisplayMode_Add)
    
    cbo_SQD_Type.SetFocus
    
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".AddDisplaySubItem()")
End Sub

Private Sub AddDisplayDoc(ByVal al_nodeID As Long)
On Error GoTo Trace_Err
    
    BlankFieldsDoc
    Call ControlsEnable(UserControl.Controls, fraDocUpload, True)
    
    ' disable non editable fields
    txt_fileID.Locked = True
    txt_fileID.BackColor = CL_COLOR_DISABLED
    
    txt_filePath.Locked = True
    txt_filePath.BackColor = CL_COLOR_DISABLED
    
    txt_FileName.Locked = True
    txt_FileName.BackColor = CL_COLOR_DISABLED
    
    txt_nodeDesc.Locked = True
    txt_nodeDesc.BackColor = CL_COLOR_DISABLED
    
    Call grd_doc.DeselectRow
    
    ' init treeview node field
    If trw_doc.SelectedItem Is Nothing Then
        Call Err.Raise(ArmErr.InvalidArgument, "trw_doc node not selected")
    End If
    txt_nodeID.Text = al_nodeID
    txt_nodeDesc.Text = getNodePath(trw_doc.SelectedItem, 2)
    txt_fileZipID.Text = "0"
    
    Call SwapToDisplayModeDoc(mt_CstValues.DisplayMode_Add)
    
    txt_fileTitle.SetFocus

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".AddDisplayDoc()")
End Sub

Private Function getNodePath(ao_Node As MSComctlLib.Node, ByVal li_Index As Integer) As String
On Error GoTo errHandler
    If Not ao_Node Is Nothing Then
        getNodePath = getNodePath(ao_Node.Parent, li_Index) & "/" & ao_Node.Tag.GetData(li_Index)
    End If
    Exit Function
errHandler:
    Call ErrorMessage(Extender.Name & ".getNodePath")
End Function

Private Sub UpdateDisplayDoc(ByVal al_fileID As Long)
On Error GoTo Trace_Err
    
    BlankFieldsDoc
    
    Call ControlsEnable(UserControl.Controls, fraDocUpload, True)
    
    ' disable non editable fields
    txt_fileID.Locked = True
    txt_fileID.BackColor = CL_COLOR_DISABLED
    
    txt_filePath.Locked = True
    txt_filePath.BackColor = CL_COLOR_DISABLED

    txt_FileName.Locked = True
    txt_FileName.BackColor = CL_COLOR_DISABLED

    txt_nodeDesc.Locked = True
    txt_nodeDesc.BackColor = CL_COLOR_DISABLED

    Call ViewInitFieldsDoc(al_fileID)
    
    Call SwapToDisplayModeDoc(mt_CstValues.DisplayMode_Update)
    
    txt_fileDesc.SetFocus
    
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".UpdateDisplayDoc()")
End Sub

Private Sub DeleteDisplayDoc(ByVal al_fileID As Long)
On Error GoTo Trace_Err
    
    BlankFieldsDoc
    
    Call ControlsEnable(UserControl.Controls, fraDocUpload, False)

    Call ViewInitFieldsDoc(al_fileID)
    
    Call SwapToDisplayModeDoc(mt_CstValues.DisplayMode_Delete)

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".DeleteDisplayDoc()")
End Sub

Private Sub ViewInitFieldsDoc(ByVal al_fileID As Long)
On Error GoTo Trace_Err
Const C_REQ_SEL As String = "EXEC Cap_SOM_Doc_file_sel $fileID$"
Const C_REQ_PATH As String = "EXEC Cap_SOM_Doc_Tree_GetPath $nodeID$, '$LANG$'"
    Dim ls_Request As String
    Dim ll_cursor As Long

    If al_fileID = 0 Then Exit Sub
    
    mb_InternalInit = True
    
    txt_fileID.Text = al_fileID
    
    ls_Request = Replace(C_REQ_SEL, "$fileID$", al_fileID, , , vbTextCompare)
    ll_cursor = OpenSQLSafe(mo_ArmDb, ls_Request)
    
    txt_fileTitle.Text = mo_ArmDb.GetFields(ll_cursor, "FileTitle")
    txt_fileDesc.Text = mo_ArmDb.GetFields(ll_cursor, "FileDesc")
    txt_FileName.Text = mo_ArmDb.GetFields(ll_cursor, "FileName")
    txt_filePath.Text = mo_ArmDb.GetFields(ll_cursor, "FilePath")
    txt_nodeID.Text = mo_ArmDb.GetFields(ll_cursor, "nodeID")
    txt_fileZipID.Text = mo_ArmDb.GetFields(ll_cursor, "fileZipID")
    
    p_dociCon = mo_ArmDb.GetFields(ll_cursor, "iConcurrency")
    
    Call mo_ArmDb.Close(ll_cursor)
    
    ' get node path from DB
    ls_Request = Replace(C_REQ_PATH, "$nodeID$", txt_nodeID.Text, , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$LANG$", m_Language, , , vbTextCompare)
    ll_cursor = OpenSQLSafe(mo_ArmDb, ls_Request)
    
    txt_nodeDesc.Text = mo_ArmDb.GetFields(ll_cursor, "nodePath")
    
    Call mo_ArmDb.Close(ll_cursor)
    ll_cursor = 0
    
    mb_InternalInit = False
    Exit Sub
    
Trace_Err:
    mb_InternalInit = False
    If ll_cursor > 0 Then
        Call mo_ArmDb.Close(ll_cursor)
        ll_cursor = 0
    End If
    Call ErrorHandler(Extender.Name & ".ViewInitFieldsDoc()")
End Sub

Private Sub RefreshGridSafe(ByRef ao_grd As ArmGrid)
On Error GoTo Trace_Err
    Dim lv_Key As Variant
    If ao_grd.SelectedCount > 0 Then
        lv_Key = ao_grd.SelectedKey(0)
    Else
        lv_Key = Empty
    End If
    Call ao_grd.Refresh
    If Not IsEmpty(lv_Key) Then
        Call ao_grd.SearchKey(True, lv_Key)
    End If
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".RefreshGridSafe()")
End Sub

Private Sub BlankFieldsDoc()
On Error GoTo Trace_Err
    mb_InternalInit = True
    
    txt_nodeDesc.Text = ""
    txt_fileTitle.Text = ""
    txt_filePath.Text = ""
    cmd_File.Tag = ""
    txt_fileDesc.Text = ""
    txt_fileID.Text = ""
    txt_nodeID.Text = ""
    txt_FileName.Text = ""
    txt_fileZipID.Text = ""
    mb_FileChanged = False

    mb_InternalInit = False
    Exit Sub
Trace_Err:
    mb_InternalInit = False
    Call ErrorHandler(Extender.Name & ".BlankFieldsDoc()")
End Sub

Private Sub BlankFieldsSubItem()
On Error GoTo Trace_Err
    mb_InternalInit = True
    
    Call cbo_System.Clear
    Call cbo_SQD_Type.Clear
    Call cbo_UM.Clear
    
    txt_Area.Text = ""
    txt_ValueLC.Text = ""
    txt_DB.Text = ""
    txt_ValueCHF.Text = ""
    txt_PrimeMarg.Text = ""
    
    p_dociCon = 0
    
    mb_InternalInit = False
    Exit Sub
Trace_Err:
    mb_InternalInit = False
    Call ErrorHandler(Extender.Name & ".BlankFieldsSubItem()")
End Sub

Private Sub ViewInitFieldsSubItem(ByVal al_displayMode As Long)
On Error GoTo Trace_Err

    mb_InternalInit = True
    Call cbo_System.AddItem(Array(grd_quote.SelectedLine(0, "SS_Code"), grd_quote.SelectedLine(0, "SS_Desc")), True)
    Call cbo_SQD_Type.AddItem(Array(grd_quote.SelectedLine(0, "SQD_Type"), grd_quote.SelectedLine(0, "SQD_Type_Desc")), True)
    Call cbo_UM.AddItem(Array(grd_quote.SelectedLine(0, "UM_Code"), grd_quote.SelectedLine(0, "UM_Desc")), True)

    Select Case al_displayMode
    Case mt_CstValues.DisplayMode_Add, mt_CstValues.DisplayMode_Update
        txt_Area.Text = grd_quote.SelectedLine(0, "SQD_Area")
        txt_ValueLC.Text = grd_quote.SelectedLine(0, "SQD_ValueLC")
        txt_DB.Text = grd_quote.SelectedLine(0, "SQD_DB")
        txt_ValueCHF.Text = Replace(Format(grd_quote.SelectedLine(0, "SQD_Value_CHF")), ms_DecimalSeparator, ".")
        txt_PrimeMarg.Text = Replace(Format(grd_quote.SelectedLine(0, "SQD_PrimeMargin"), MONEY_FORMAT), ms_DecimalSeparator, ".")
    Case Else
        txt_Area.Text = FormatNumber(grd_quote.SelectedLine(0, "SQD_Area"), 0, , , ml_useGrouping)
        txt_ValueLC.Text = FormatNumber(grd_quote.SelectedLine(0, "SQD_ValueLC"), 0, , , ml_useGrouping)
        txt_DB.Text = FormatNumber(grd_quote.SelectedLine(0, "SQD_DB"), 0, , , ml_useGrouping)
        txt_ValueCHF.Text = FormatNumber(grd_quote.SelectedLine(0, "SQD_Value_CHF"), 0, , , ml_useGrouping)
        txt_PrimeMarg.Text = FormatNumber(grd_quote.SelectedLine(0, "SQD_PrimeMargin"), 2, , , ml_useGrouping)
    End Select


    mb_InternalInit = False
    Exit Sub
Trace_Err:
    mb_InternalInit = False
    Call ErrorHandler(Extender.Name & ".ViewInitFieldsSubItem()")
End Sub

Private Sub UpdateDisplaySubItem()
On Error GoTo Trace_Err
    
    BlankFieldsSubItem
    
    Call ControlsEnable(UserControl.Controls, fra_Detail, True)
    
    Call ViewInitFieldsSubItem(mt_CstValues.DisplayMode_Update)
    
    Call SwapToDisplayModeSubitem(mt_CstValues.DisplayMode_Update)
    
    txt_ValueLC.SetFocus
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".UpdateDisplaySubItem()")
End Sub

Private Sub ViewDisplaySubItem()
On Error GoTo Trace_Err
    
    BlankFieldsSubItem
    
    Call ControlsEnable(UserControl.Controls, fra_Detail, False)
    
    Call ViewInitFieldsSubItem(mt_CstValues.DisplayMode_View)
    
    Call SwapToDisplayModeSubitem(mt_CstValues.DisplayMode_View)
    
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".ViewDisplaySubItem()")
End Sub

Private Sub DeleteDisplaySubItem()
On Error GoTo Trace_Err
    
    BlankFieldsSubItem
    
    Call ControlsEnable(UserControl.Controls, fra_Detail, False)

    Call ViewInitFieldsSubItem(mt_CstValues.DisplayMode_Delete)
    
    Call SwapToDisplayModeSubitem(mt_CstValues.DisplayMode_Delete)

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".DeleteDisplaySubItem()")
End Sub

Function SubRecordCheck() As Boolean
On Error GoTo Trace_Err
    SubRecordCheck = False
    
    ' 1. check mandatory
    If Not cbo_IsFilled(cbo_SQD_Type) Then
        Call ShowErrMessage(2120, lbl_Label(18).Caption)
        cbo_SQD_Type.SetFocus
        Exit Function
    End If
    If Not cbo_IsFilled(cbo_System) Then
        Call ShowErrMessage(2120, lbl_Label(23).Caption)
        cbo_System.SetFocus
        Exit Function
    End If

    If Not cbo_IsFilled(cbo_UM) Then
        Call ShowErrMessage(2120, lbl_Label(19).Caption)
        cbo_UM.SetFocus
        Exit Function
    End If

    If Trim(txt_Area.Text) = "" Then
        Call ShowErrMessage(2120, lbl_Label(21).Caption)
        txt_Area.SetFocus
        Exit Function
    End If
    
    If Trim(txt_ValueLC.Text) = "" Then
        Call ShowErrMessage(2120, lbl_Label(17).Caption)
        txt_ValueLC.SetFocus
        Exit Function
    End If
    
    If Trim(txt_DB.Text) = "" Then
        Call ShowErrMessage(2120, lbl_Label(16).Caption)
        txt_DB.SetFocus
        Exit Function
    End If
    
    ' 2. check content
    
    If Not CheckNumericBeforeCalculation(txt_Area, 21, 0, 1, 9999999) Then
        Exit Function
    End If
    
    If Not CheckNumericBeforeCalculation(txt_ValueLC, 17, 0, 1, 99999999) Then
        Exit Function
    End If
    
    If Not CheckNumericBeforeCalculation(txt_DB, 16, 0, 1, 1000) Then
        Exit Function
    End If
    
    SubRecordCheck = True
    Exit Function
Trace_Err:
    Call ErrorHandler(Extender.Name & ".SubRecordCheck()")
End Function

Function DocRecordCheck() As Boolean
On Error GoTo Trace_Err
    DocRecordCheck = False
    
    ' 1. check mandatory
    If Trim(txt_nodeID.Text) = "" Then
        Call ShowErrMessage(2120, lbl_fileNode.Caption)
        Exit Function
    End If
    
    If Trim(txt_FileName.Text) = "" Then
        Call ShowErrMessage(2120, lbl_fileName.Caption)
        txt_FileName.SetFocus
        Exit Function
    End If
    
    If Trim(txt_fileTitle.Text) = "" Then
        Call ShowErrMessage(2120, lbl_fileTitle.Caption)
        txt_fileTitle.SetFocus
        Exit Function
    End If
    
    If Trim(txt_filePath.Text) = "" Then
        Call ShowErrMessage(2120, lbl_filePath.Caption)
        txt_filePath.SetFocus
        Exit Function
    End If
    
    ' 2. check content
    If CheckNumericField(txt_nodeID, 0, 1, 9999999) <> 0 Then
        Call ShowErrMessage(2131, lbl_fileNode.Caption, "0", "9999999")
        Exit Function
    End If
    
    DocRecordCheck = True
    Exit Function
Trace_Err:
    Call ErrorHandler(Extender.Name & ".DocRecordCheck()")
End Function


Private Sub ShowErrMessage(ByVal al_err_code, ByVal as_caption As String, Optional ByVal as_min As String = "", Optional ByVal as_max As String = "")
On Error GoTo Trace_Err
    Dim lv_MsgReplaceInfo(2, 1) As String
    lv_MsgReplaceInfo(0, 0) = "$LabelCaption$"
    lv_MsgReplaceInfo(0, 1) = as_caption
    lv_MsgReplaceInfo(1, 0) = "$Min$"
    lv_MsgReplaceInfo(1, 1) = as_min
    lv_MsgReplaceInfo(2, 0) = "$Max$"
    lv_MsgReplaceInfo(2, 1) = as_max
    
    Dim ls_defaultMsg As String
    Select Case al_err_code
        Case 2120
            ls_defaultMsg = "#The field $LabelCaption$ is mandatory."
        Case 2131
            ls_defaultMsg = "#The field $LabelCaption$ must be numeric."
        Case 2134
            ls_defaultMsg = "#The field $LabelCaption$ does not accept decimal number."
        Case 2132
            ls_defaultMsg = "#The field $LabelCaption$ must be a number between $Min$ and $Max$."
        Case 3064
            ls_defaultMsg = "#The currency you choose is not valide. Choose an other one."
        Case 10000
            ls_defaultMsg = "#The field $LabelCaption$ is not 0 please select  a currencie or set the $LabelCaption$ to 0."
    End Select

    Call MsgBox(MsgText(al_err_code, m_Language, ls_defaultMsg, lv_MsgReplaceInfo), vbInformation)
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".ShowErrMessage()")
End Sub

Function DocRecordAdd() As Boolean
On Error GoTo Trace_Err
Const C_REQ_INS As String = "EXEC Cap_SOM_Doc_File_ins $fileID$, 'E', $SQT_ID$, $nodeID$, $fileTitle$, $fileDesc$, $fileName$, $filePath$, $Z_creator$"
'Const C_REQ_ZIP As String = "INSERT INTO Cap_SOM_Doc_FileZip (fileID, fileZip) VALUES ($fileID$, ?)"
Dim ls_Request  As String
    
    DocRecordAdd = False
    
    'check all Quote detail
    If Not DocRecordCheck() Then Exit Function
    
    If Not ASC_ConnectToDB(mo_ArmDb, ms_ConnectString, mb_Created) Then Exit Function
    
    Dim ls_fileID As String
    ls_fileID = mo_ArmDb.SQLNextID("Cap_SOM_Doc_File")
    
    If ls_fileID = "" Then Call Err.Raise(SQLFailure, "", "SQL Error: mo_ArmDb.SQLNextID(""Cap_SOM_Doc_File"") return nothing.")
    
    'Construct the request
    ls_Request = DocReplacePlaceholders(Replace(C_REQ_INS, "$fileID$", ls_fileID, , , vbTextCompare))
    
    Call ExecuteSQLSafe(mo_ArmDb, ls_Request)
    
    ' upload the zip
    Debug.Assert (txt_fileZipID.Text = "0")
    Dim ls_serverFile As String
    ls_serverFile = Document_Save(txt_filePath.Text, ms_DocumentServerDir, ls_fileID)
    
    ' rename file on the server so service can start to upload into SQL
    Call Document_Rename(ls_serverFile, ls_fileID & "_1.zip")
    
    
'    ls_Request = Replace(C_REQ_ZIP, "$fileID$", ls_fileID, , , vbTextCompare)
    
'    If Not mo_ArmDb.FileToBlobSQL(ls_Request, txt_filePath.Text, 9) Then
'        Err.Raise ArmErr.SQLFailure, "FileToBlobSQL", mo_ArmDb.LastErrorMessage & " Error writing blob: " & ls_Request & " File: " & txt_filePath.Text
'    End If

    DocRecordAdd = True
    
    Exit Function
    
Trace_Err:
    Call ErrorHandler(Extender.Name & ".DocRecordAdd()")
End Function


Function DocRecordUpdate() As Boolean
On Error GoTo Trace_Err
Const C_REQ_UPD As String = "EXEC Cap_SOM_Doc_File_upd $fileID$, $fileTitle$, $fileDesc$, $fileName$, $filePath$, $Z_creator$, $iConcurrency$"
'Const C_REQ_ZIP_INS As String = "INSERT INTO Cap_SOM_Doc_FileZip (fileID, fileZip) VALUES ($fileID$, ?)"
'Const C_REQ_ZIP_UPD As String = "UPDATE Cap_SOM_Doc_FileZip SET fileZip = ? WHERE fileID = $fileID$"
Dim ls_Request  As String
    
    DocRecordUpdate = False
    
    'check all Quote detail
    If Not DocRecordCheck() Then Exit Function
    
    If Not ASC_ConnectToDB(mo_ArmDb, ms_ConnectString, mb_Created) Then Exit Function
    
    'Construct the request
    ls_Request = DocReplacePlaceholders(Replace(C_REQ_UPD, "$fileID$", txt_fileID.Text, , , vbTextCompare))
    
    Call ExecuteSQLSafe(mo_ArmDb, ls_Request)
    
    ' if file is changed then do upload
    If mb_FileChanged Then
        Dim ls_serverFile As String
        ls_serverFile = Document_Save(txt_filePath.Text, ms_DocumentServerDir, txt_fileID.Text)
    
        ' rename file on the server so service can start to upload into SQL
        Call Document_Rename(ls_serverFile, txt_fileID.Text & "_1.zip")

'        ls_Request = Replace(IIf(txt_fileZipID.Text = "0", C_REQ_ZIP_INS, C_REQ_ZIP_UPD), "$fileID$", txt_fileID.Text, , , vbTextCompare)
        
'        If Not mo_ArmDb.FileToBlobSQL(ls_Request, txt_filePath.Text, 9) Then
'            Err.Raise ArmErr.SQLFailure, "FileToBlobSQL", mo_ArmDb.LastErrorMessage & " Error writing blob: " & ls_Request & " File: " & txt_filePath.Text
'        End If
    End If

    DocRecordUpdate = True
    
    Exit Function
    
Trace_Err:
    Call ErrorHandler(Extender.Name & ".DocRecordUpdate()")
End Function



Function DocRecordDelete() As Boolean
On Error GoTo Trace_Err
Const C_REQ_DEL As String = "EXEC Cap_SOM_Doc_File_del $fileID$, $Z_creator$, $iConcurrency$"
Dim ls_Request  As String
    
    DocRecordDelete = False
    
    If Not ASC_ConnectToDB(mo_ArmDb, ms_ConnectString, mb_Created) Then Exit Function
    
    'Construct the request
    ls_Request = DocReplacePlaceholders(Replace(C_REQ_DEL, "$fileID$", txt_fileID.Text, , , vbTextCompare))
    
    Call ExecuteSQLSafe(mo_ArmDb, ls_Request)
    
    DocRecordDelete = True
    
    Exit Function
    
Trace_Err:
    Call ErrorHandler(Extender.Name & ".DocRecordDelete()")
End Function


Private Function SubRecordAdd() As Boolean
On Error GoTo Trace_Err
    SubRecordAdd = False
    
    If Not SubRecordCheck() Then Exit Function
    
    ReDim lv_Data(grd_quote.Cols - 1)
    lv_Data(0) = ""         ' this is new
    If Not grd_quote.AddLine(lv_Data) Then Exit Function
    
    
    grd_quote.SelectedLine(0, "SS_Code") = cbo_System.SelectedItem.Key
    grd_quote.SelectedLine(0, "SS_Desc") = cbo_System.SelectedItem.DisplayText
    grd_quote.SelectedLine(0, "SQD_Area") = txt_Area.Text
    grd_quote.SelectedLine(0, "SQD_Type") = cbo_SQD_Type.SelectedItem.Key
    grd_quote.SelectedLine(0, "SQD_Type_Desc") = cbo_SQD_Type.SelectedItem.DisplayText
    grd_quote.SelectedLine(0, "UM_Code") = cbo_UM.SelectedItem.Key
    grd_quote.SelectedLine(0, "UM_Desc") = cbo_UM.SelectedItem.DisplayText
    grd_quote.SelectedLine(0, "SQD_ValueLC") = txt_ValueLC.Text
    grd_quote.SelectedLine(0, "SQD_DB") = txt_DB.Text
    grd_quote.SelectedLine(0, "SQD_Value_CHF") = txt_ValueCHF.Text
    grd_quote.SelectedLine(0, "SQD_PrimeMargin") = Replace(txt_PrimeMarg.Text, ".", ms_DecimalSeparator)
    grd_quote.SelectedLine(0, "UPD_ACTION") = "A"
    grd_quote.SelectedLine(0, "iConcurrency") = 0
    

    txt_updatedBy.Text = ms_UID
    txt_dateUpdated.Text = Format(Date, "dd\/mm\/yyyy")
    
    ' recalc TOTal values
    Call CalculationTOT(mt_CstValues.DisplayMode_View)
    
    SubRecordAdd = True
    Exit Function
    
Trace_Err:
    Call ErrorHandler(Extender.Name & ".SubRecordAdd()")
End Function

Private Sub SubRecordAddDB(ByRef ao_grd As ArmGrid, ByVal al_line As Long)
On Error GoTo Trace_Err
Const C_REQ As String = "EXEC Cap_SOM_QuoteDetail_ins $SQD_ID$,$SQT_ID$,$SQD_Type$,$SS_Code$,$SQD_Area$,'$UM_Code$',$SQD_ValueLC$,$SQD_Value_CHF$,$SQD_DB$,$SQD_PrimeMargin$,$Z_CREATOR$"
    Dim ls_Req As String
    
    ls_Req = Replace(C_REQ, "$SQD_ID$", ao_grd.Data(al_line, "SQD_ID"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQT_ID$", m_CurrentKey1, , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_Type$", ao_grd.Data(al_line, "SQD_Type"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SS_Code$", ao_grd.Data(al_line, "SS_Code"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_Area$", ao_grd.Data(al_line, "SQD_Area"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$UM_Code$", ao_grd.Data(al_line, "UM_Code"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_ValueLC$", ao_grd.Data(al_line, "SQD_ValueLC"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_Value_CHF$", ao_grd.Data(al_line, "SQD_Value_CHF"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_DB$", ao_grd.Data(al_line, "SQD_DB"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_PrimeMargin$", Replace(ao_grd.Data(al_line, "SQD_PrimeMargin"), ms_DecimalSeparator, "."), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$Z_CREATOR$", ml_U_code, , , vbTextCompare)
    
    Call ExecuteSQLSafe(mo_ArmDb, ls_Req)
    
    ' UPDATE iConcurrency data
    ao_grd.Data(al_line, "iConcurrency") = ao_grd.Data(al_line, "iConcurrency") + 1
    
    ' update project Metal product counter which depends on cbo_SQD_Type
    Call UpdateProjectCounters(m_Project, ao_grd.Data(al_line, "SQD_Type"), 1)

    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".SubRecordAddDB()")
End Sub


Private Sub SubRecordUpdateDB(ByRef ao_grd As ArmGrid, ByVal al_line As Long)
On Error GoTo Trace_Err
Const C_REQ As String = "EXEC Cap_SOM_QuoteDetail_upd $SQD_ID$,$SQD_Type$,$SS_Code$,$SQD_Area$,'$UM_Code$',$SQD_ValueLC$,$SQD_Value_CHF$,$SQD_DB$,$SQD_PrimeMargin$,$Z_CREATOR$,$ICONCURRENCY$"
    Dim ls_Req As String
    
    ls_Req = Replace(C_REQ, "$SQD_ID$", ao_grd.Data(al_line, "SQD_ID"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_Type$", ao_grd.Data(al_line, "SQD_Type"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SS_Code$", ao_grd.Data(al_line, "SS_Code"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_Area$", ao_grd.Data(al_line, "SQD_Area"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$UM_Code$", ao_grd.Data(al_line, "UM_Code"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_ValueLC$", ao_grd.Data(al_line, "SQD_ValueLC"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_Value_CHF$", ao_grd.Data(al_line, "SQD_Value_CHF"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_DB$", ao_grd.Data(al_line, "SQD_DB"), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_PrimeMargin$", Replace(ao_grd.Data(al_line, "SQD_PrimeMargin"), ms_DecimalSeparator, "."), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$Z_CREATOR$", ml_U_code, , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$ICONCURRENCY$", ao_grd.Data(al_line, "iConcurrency"), , , vbTextCompare)
    
    Call ExecuteSQLSafe(mo_ArmDb, ls_Req, 1)
    
    If ao_grd.Data(al_line, "SQD_Type") <> ao_grd.Data(al_line, "SQD_TypeOld") Then
        ' update sales _project counters
        ' 1. decrement old counter
        Call UpdateProjectCounters(m_Project, ao_grd.Data(al_line, "SQD_TypeOld"), -1)

        ' 2. increment new counter
        Call UpdateProjectCounters(m_Project, ao_grd.Data(al_line, "SQD_Type"), 1)
        
    End If
    
    ' UPDATE iConcurrency data
    ao_grd.Data(al_line, "iConcurrency") = ao_grd.Data(al_line, "iConcurrency") + 1
    Exit Sub
    
Trace_Err:
    Call ErrorHandler(Extender.Name & ".SubRecordUpdateDB()")
End Sub

Private Sub UpdateProjectCounters(ByVal as_SP_Capkey As String, ByVal al_SQD_Type As Long, ByVal al_value As Long)
On Error GoTo ErrorHandler
    Dim ls_Req As String
    ls_Req = ""
    Select Case al_SQD_Type
        Case 1  ' standard / Level 1
                ls_Req = "Exec Sales_Project_ASProductCounterUpdate $SP_Capkey$, $Counter$"
        Case 2  ' semi standard / Level 2
                ls_Req = "Exec Sales_Project_ASProductCounter2Update $SP_Capkey$, $Counter$"
        Case 3  ' Custom / Level 3 & 4
                ls_Req = "Exec Sales_Project_ASProductCounter3Update $SP_Capkey$, $Counter$"
        Case Else
            Debug.Assert (False)
    End Select
    If ls_Req <> "" Then
        ls_Req = Replace(ls_Req, "$SP_Capkey$", SQLStr(as_SP_Capkey, 16, True), , , vbTextCompare)
        ls_Req = Replace(ls_Req, "$Counter$", al_value, , , vbTextCompare)
        
        Call ExecuteSQLSafe(mo_ArmDb, ls_Req)
    End If

    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".UpdateProjectCounters()")
End Sub

' JN 20.3.2012 update z_last_upd for a project
Private Sub UpdateProjectLastUpdate(ByVal as_SP_Capkey As String)
Const C_REQ As String = "EXEC Sales_Project_LastUpd '$SP_CAPKEY$'"
On Error GoTo errHandler
    Call ExecuteSQLSafe(mo_ArmDb, Replace(C_REQ, "$SP_CAPKEY$", as_SP_Capkey), 1)
    Exit Sub
errHandler:
    Call ErrorHandler(Extender.Name & ".UpdateProjectLastUpdate()")
End Sub

Private Function SubRecordUpdate(ByVal ACode As String) As Boolean
On Error GoTo Trace_Err
    SubRecordUpdate = False
    
    If Trim$(ACode) = "" And grd_quote.SelectedLine(0, "UPD_ACTION") <> "A" Then Call Err.Raise(InvalidArgument, "", "ACode is empty.")
    
    If Not SubRecordCheck() Then Exit Function
    
    ' update grid from detail
    grd_quote.SelectedLine(0, "SS_Code") = cbo_System.SelectedItem.Key
    grd_quote.SelectedLine(0, "SS_Desc") = cbo_System.SelectedItem.DisplayText
    grd_quote.SelectedLine(0, "SQD_Area") = txt_Area.Text
    grd_quote.SelectedLine(0, "SQD_Type") = cbo_SQD_Type.SelectedItem.Key
    grd_quote.SelectedLine(0, "SQD_Type_Desc") = cbo_SQD_Type.SelectedItem.DisplayText
    grd_quote.SelectedLine(0, "UM_Code") = cbo_UM.SelectedItem.Key
    grd_quote.SelectedLine(0, "UM_Desc") = cbo_UM.SelectedItem.DisplayText
    grd_quote.SelectedLine(0, "SQD_ValueLC") = txt_ValueLC.Text
    grd_quote.SelectedLine(0, "SQD_DB") = txt_DB.Text
    grd_quote.SelectedLine(0, "SQD_Value_CHF") = txt_ValueCHF.Text
    grd_quote.SelectedLine(0, "SQD_PrimeMargin") = Replace(txt_PrimeMarg.Text, ".", ms_DecimalSeparator)
    If grd_quote.SelectedLine(0, "UPD_ACTION") = "" Then grd_quote.SelectedLine(0, "UPD_ACTION") = "U"

    ' recalc TOTal values
    Call CalculationTOT(mt_CstValues.DisplayMode_View)

    txt_updatedBy.Text = ms_UID
    txt_dateUpdated.Text = Format(Date, "dd\/mm\/yyyy")
    
    SubRecordUpdate = True
    Exit Function
    
Trace_Err:
    Call ErrorHandler(Extender.Name & ".SubRecordUpdate()")
End Function

Private Function SubRecordDelete(ByVal ACode As String) As Boolean
On Error GoTo Trace_Err
    SubRecordDelete = False
    
    If Trim$(ACode) = "" And grd_quote.SelectedLine(0, "UPD_ACTION") <> "A" Then Call Err.Raise(InvalidArgument, "", "ACode is empty.")
    
    If DeleteConfirmation(mo_ArmDb, m_Language) = False Then Exit Function
    
    If Not grd_quote.DeleteSelectedLines() Then
        Exit Function
    End If
    
    txt_updatedBy.Text = ms_UID
    txt_dateUpdated.Text = Format(Date, "dd\/mm\/yyyy")

    ' recalc TOTal values
    Call CalculationTOT(mt_CstValues.DisplayMode_View)

    SubRecordDelete = True
    Exit Function
    
Trace_Err:
    Call ErrorHandler(Extender.Name & ".SubRecordDelete()")
End Function

Private Sub SubRecordDeleteUnusedDB(ByVal ACode As String, ByVal as_SQD_VisibleIDs As String)
On Error GoTo Trace_Err
Const C_REQ_DET_SEL As String = "SELECT SQD_ID, SQD_Type FROM Cap_SOM_QuoteDetail WHERE SQT_ID=$SQT_ID$ AND NOT SQD_ID IN($SQD_ID$) AND drop_flag<>'X'"
Const C_REQ_DET_DEL As String = "UPDATE Cap_SOM_QuoteDetail SET drop_flag='X', drop_date=GETDATE(), Z_last_upd_user=$Z_CREATOR$ WHERE SQT_ID=$SQT_ID$ AND NOT SQD_ID IN($SQD_ID$) AND drop_flag<>'X'"

    If as_SQD_VisibleIDs = "" Then as_SQD_VisibleIDs = "0"
    Dim ls_Req As String
    Dim ll_cursor As Long
    
    ' 1. update project counters
    ls_Req = Replace(C_REQ_DET_SEL, "$SQT_ID$", ACode, , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_ID$", as_SQD_VisibleIDs, , , vbTextCompare)
    
    ll_cursor = OpenSQLSafe(mo_ArmDb, ls_Req)
    While Not mo_ArmDb.EOF(ll_cursor)
        
        ' update project Metal product counter which depends on SQD_Type
        Call UpdateProjectCounters(m_Project, mo_ArmDb.GetFields(ll_cursor, "SQD_Type"), -1)
        
        Call mo_ArmDb.Next(ll_cursor)
    Wend
    
    
    ' 2. delete unused records
    ls_Req = Replace(C_REQ_DET_DEL, "$SQT_ID$", ACode, , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$SQD_ID$", as_SQD_VisibleIDs, , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$Z_CREATOR$", ml_U_code, , , vbTextCompare)

    Call ExecuteSQLSafe(mo_ArmDb, ls_Req)
    

    Exit Sub
    
Trace_Err:
    If ll_cursor <> 0 Then
        Call mo_ArmDb.Close(ll_cursor)
        ll_cursor = 0
    End If
    Call ErrorHandler(Extender.Name & ".SubRecordDeleteUnusedDB()")
End Sub

Private Function CopyQuote(ByVal as_CurrentKey As String, ByVal ab_revision As Boolean) As Boolean
On Error GoTo errHandler

    CurrentKey = ""
    DisplayMode = mt_CstValues.DisplayMode_Add
    
    Dim ll_SQT_Status As Long
    Debug.Assert (Not cbo_Status.SelectedItem Is Nothing)
    ll_SQT_Status = cbo_Status.SelectedItem.Key
    
    CurrentKey = as_CurrentKey
    Call UpdateInitFields
    
    ' reset status
    cbo_Status.SearchItem (ll_SQT_Status)
    
    
    If ab_revision Then
        ' reset reference
        txt_SQT_Reference.Text = "Rev. of " & txt_SQT_Reference.Text
    Else
        ' reset reference
        txt_SQT_Reference.Text = "Copy of " & txt_SQT_Reference.Text
        
        ' reset ref as new
        txt_QuoteRef.Text = ""
        
        ' if copy then reset revision
        txt_Revision.Text = ""
    
    End If
    
    'reset Include (Offer data countable) option button
    opt_include(0).Value = False
    opt_include(1).Value = False

    'reset items
    Call ResetDetailID(grd_quote)

    Exit Function
errHandler:
    Call ErrorHandler(Extender.Name & ".CopyQuote()")
End Function

Private Sub PrintQuote(ByVal as_COF_ID As String, ByVal al_status As eQuoteStatus, ByVal ab_QuoteConfirmation As Boolean)
On Error GoTo Trace_Err
    
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".PrintQuote()")
End Sub

Private Function PrintQuotePreview(ByVal as_COF_ID As String, ByVal ab_QuoteConfirmation As Boolean, ByRef as_serialString As String) As String
On Error GoTo Trace_Err
    PrintQuotePreview = ""
    Exit Function
Trace_Err:
    Call ErrorHandler(Extender.Name & ".PrintQuotePreview()")
End Function

Private Sub MailQuote(ByVal as_COF_ID As String, ByVal al_status As eQuoteStatus, ByVal as_serialStr As String, ByVal ab_QuoteConfirmation As Boolean)
On Error GoTo Trace_Err
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".MailQuote()")
End Sub

Private Sub FaxQuote(ByVal as_COF_ID As String, ByVal al_status As eQuoteStatus, ByVal as_serialStr As String, ByVal ab_QuoteConfirmation As Boolean)
On Error GoTo Trace_Err
    Exit Sub
Trace_Err:
    Call ErrorHandler(Extender.Name & ".FaxQuote()")
End Sub

Private Function RecordCopy(ByVal as_CurrentKeySrc As String, ByRef as_CurrentKeyDst As String) As Boolean
On Error GoTo Trace_Err
    Exit Function
Trace_Err:
    Call ErrorHandler(Extender.Name & ".RecordCopy()")
End Function


' ************************************************************************************
' **************************** DB-ACCESS FUNCTIONS ***********************************
' ************************************************************************************
#If LIVE = 1 Then
Private Sub ExecuteSQLSafe(ByVal ao_DB As Object, ByVal as_Request As String, Optional ByVal al_RowAffectedCount = -1, Optional ab_DuplicityCheck As Boolean = False)
#Else
Private Sub ExecuteSQLSafe(ByVal ao_DB As ARMSYSCOMLib.ArmDb, ByVal as_Request As String, Optional ByVal al_RowAffectedCount = -1, Optional ab_DuplicityCheck As Boolean = False)
#End If
On Error GoTo errHandler

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

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

errHandler:
    Call ErrorHandler(Extender.Name & ".ExecuteSQLSafe")
End Sub

#If LIVE = 1 Then
Private Function OpenSQLSafe(ByVal ao_DB As Object, ByVal as_Request As String, Optional ByVal al_RowExpectedCount = -1) As Long
#Else
Private Function OpenSQLSafe(ByVal ao_DB As ARMSYSCOMLib.ArmDb, ByVal as_Request As String, Optional ByVal al_RowExpectedCount = -1) As Long
#End If
On Error GoTo errHandler
    Dim lc_Data As Long
    lc_Data = ao_DB.OpenSQL(as_Request)
    
    If lc_Data = 0 Then
        Err.Raise ArmErr.SQLFailure, "SQL : " & as_Request, Join(ao_DB.SQLErrorCodes, SEP2) & SEP1 & Join(ao_DB.SQLErrorMessages, SEP2)
    End If
'    Debug.Print 1 / 0
    If al_RowExpectedCount <> -1 Then
        ' Then check the rowcount
        If ao_DB.RowCount(lc_Data) <> al_RowExpectedCount Then
            Err.Raise ArmErr.SQLBadRowExpectedCount, "SQL : " & as_Request, al_RowExpectedCount & "<>" & ao_DB.RowCount(lc_Data)
        End If
    End If

    OpenSQLSafe = lc_Data
    Exit Function
errHandler:
    Call ErrorHandler("OpenSQLSafe")
End Function

Private Function SQLOptionButtonValue(ByRef ao_options As Object) As String
On Error GoTo errHandler
    SQLOptionButtonValue = ""
    Dim opt_obj As OptionButton
    For Each opt_obj In ao_options
        If opt_obj.Value Then
            SQLOptionButtonValue = GetStringItem(opt_obj.Tag, 0)
            Exit For
        End If
    Next
    Exit Function
errHandler:
    Call ErrorHandler(Extender.Name & ".SQLOptionButtonValue")
End Function

Private Function GetStringItem(ByVal as_SString As String, ByVal al_Index As Long, Optional ByVal as_SEP As String = SEP) As String
On Error GoTo errHandler
    Dim lsa_vals() As String
    lsa_vals = Split(as_SString, as_SEP, , vbTextCompare)
    Debug.Assert (UBound(lsa_vals) >= al_Index)
    GetStringItem = lsa_vals(al_Index)
    Exit Function
errHandler:
    Call ErrorHandler(Extender.Name & ".GetStringItem")
End Function

' translate string to sql format
' Params:
' as_Value (String)
' ab_EmptyNULL (Boolean = False)
Private Function SQLStr(ByVal as_Value As String, Optional ByVal al_MaxLen As Long = 8000, Optional ByVal ab_EmptyNULL As Boolean = False) As String
    If as_Value = "" And ab_EmptyNULL Then
        SQLStr = "NULL"
    Else
        SQLStr = "'" & Replace(Left(as_Value, IIf(Len(as_Value) <= al_MaxLen, Len(as_Value), al_MaxLen)), "'", "''") & "'"
    End If
End Function

Private Function SQLNum(ByVal as_str As String) As String
    SQLNum = Replace(as_str, ",", ".")
End Function

Private Sub ChangeCharset(ByRef ao_Container As Object, Optional ByVal aCodePage As Long)
On Error GoTo errHandler
   
    Dim lc_Control As Control
    Dim ll_Charset As Long
     
    On Error Resume Next
    ll_Charset = GetCharSetFromCodePage(aCodePage)
    
    For Each lc_Control In ao_Container
        Select Case UCase(TypeName(lc_Control))
        Case "TABSTRIP", "TEXTBOX", "LABEL", "FRAME", "COMMANDBUTTON", _
              "LISTVIEW", "CHECKBOX", "OPTIONBUTTON", _
              "ARMCHECKVIEW", "ARMTREEVIEW", "ARMGRID", "ARMCOMBOBOX", "ARMCHECKVIEW0"
             lc_Control.Font.Name = "Arial"
             lc_Control.Font.Charset = ll_Charset
         Case "A_SEEK", "A_SRCHTXT"
             lc_Control.Charset = ll_Charset
         End Select
     Next
     
     Exit Sub
errHandler:
    Call ErrorHandler(Extender.Name & ".ChangeCharset()")
End Sub

Private Function CanApproveQuote(ByVal as_Login As String) As Boolean
On Error GoTo errHandler
Const C_REQ As String = ""
    CanApproveQuote = False
    
    CanApproveQuote = True
    Exit Function
errHandler:
    Call ErrorHandler(Extender.Name & ".CanApproveQuote()")
End Function

Private Function CanAddQuote(ByVal as_SP_Capkey As String) As Boolean
On Error GoTo errHandler
    CanAddQuote = False
    ' check if project type is AS
Const C_REQ_PRJ As String = "SELECT SP.SP_SAFlag, SPAMC.AMCProjectNumber FROM Sales_project SP LEFT JOIN Sales_projectAMC SPAMC ON SPAMC.SP_CapKey = SP.SP_CapKey WHERE SP.SP_CapKey = '$SP_CapKey$'"
Const C_REQ_CUS As String = "SELECT COUNT(*) AS CUS_COUNT FROM Cap_ProjectCompany WHERE SP_Capkey = '$SP_CapKey$' AND drop_flag <> 'X'"
    Dim ll_cursor As Long
    Dim ls_SAFlag As String
    Dim ls_AMCPrjNo As String
    
    ' quotation AS, Specification AS
    If m_projectStatus <> 27 And _
       m_projectStatus <> 23 _
    Then
        Call MsgBox(MsgText(WarMsgNoProjectStatus, m_Language, "#Cannot update quote. Project status must be Specification or Quotation!"), vbInformation)
        Exit Function
    End If

    ll_cursor = OpenSQLSafe(mo_ArmDb, Replace(C_REQ_PRJ, "$SP_CapKey$", as_SP_Capkey, , , vbTextCompare))
    ls_SAFlag = mo_ArmDb.GetFields(ll_cursor, "SP_SAFlag")
    ls_AMCPrjNo = mo_ArmDb.GetFields(ll_cursor, "AMCProjectNumber")
    Call mo_ArmDb.Close(ll_cursor)
    ll_cursor = 0
    
    If ls_SAFlag <> "A" Then
        ' msgbox
        Call MsgBox(MsgText(WarMsgNoASProject, m_Language, "#Cannot create quote. Project type must be AS Project!"), vbInformation)
        Exit Function
    End If
    
    If ls_AMCPrjNo = "" Then
        Call MsgBox(MsgText(WarMsgNoAMCProject, m_Language, "#Cannot create quote. Project type must be AMC Project!"), vbInformation)
        Exit Function
    End If
    
    ' CHECK if there is a customer linked
    Dim ll_cusCOunt As Long
    ll_cursor = OpenSQLSafe(mo_ArmDb, Replace(C_REQ_CUS, "$SP_CapKey$", as_SP_Capkey, , , vbTextCompare))
    ll_cusCOunt = mo_ArmDb.GetFields(ll_cursor, "CUS_COUNT")
    Call mo_ArmDb.Close(ll_cursor)
    ll_cursor = 0
    If ll_cusCOunt = 0 Then
        Call MsgBox(MsgText(WarMsgCustomer, m_Language, "#Cannot create quote. No customer linked to the Project!"), vbInformation)
        Exit Function
    End If
    CanAddQuote = True
    Exit Function
errHandler:
    If ll_cursor <> 0 Then
        Call mo_ArmDb.Close(ll_cursor)
        ll_cursor = 0
    End If
    Call ErrorHandler(Extender.Name & ".CanAddQuote()")
End Function

Private Function CanUpdateQuote(ByVal as_SP_Capkey As String) As Boolean
On Error GoTo errHandler
    CanUpdateQuote = False
    
    ' quotation AS, Specification AS
    If m_projectStatus <> 27 And _
       m_projectStatus <> 23 _
    Then
        Call MsgBox(MsgText(WarMsgNoProjectStatus, m_Language, "#Cannot update quote. Project status must be Specification or Quotation!"), vbInformation)
        Exit Function
    End If
    
    CanUpdateQuote = True
    Exit Function
errHandler:
    Call ErrorHandler(Extender.Name & ".CanUpdateQuote()")
End Function

Private Function CanSendQuote(ByVal as_COF_ID As String, ByVal al_QuoteStatus As eQuoteStatus) As Boolean
On Error GoTo errHandler
    CanSendQuote = True
    Exit Function
errHandler:
    Call ErrorHandler(Extender.Name & ".CanSendQuote()")
End Function

Private Function CanSendQuoteConfirmation(ByVal as_COF_ID As String, ByVal al_QuoteStatus As eQuoteStatus) As Boolean
On Error GoTo errHandler
    
    CanSendQuoteConfirmation = True
    Exit Function
errHandler:
    Call ErrorHandler(Extender.Name & ".CanSendQuoteConfirmation()")
End Function

Private Function IsTelNum(ByVal as_telNum As String) As Boolean
On Error GoTo ErrorMessage
    Dim ll_i  As Long
    IsTelNum = False
    ' must start with 00XXY
    If Len(as_telNum) < 5 Then Exit Function
    If Left(as_telNum, 2) <> "00" Then Exit Function
    
    ' tel number must containt only digits 0..9
    For ll_i = 1 To Len(as_telNum)
        If Mid(as_telNum, ll_i, 1) < "0" Then Exit Function
        If Mid(as_telNum, ll_i, 1) > "9" Then Exit Function
    Next
    IsTelNum = True
    Exit Function
ErrorMessage:
    Call ErrorHandler(Extender.Name & ".IsTelNum()")
End Function

Private Sub searchCBO(ByVal as_cfgVal As String, ByVal as_filterIndex As String, ByRef cbo_Cbo As ArmCombobox, ByVal as_req As String, Optional ByVal as_Data As String = "")
On Error GoTo ErrorHandler
    Dim lsa_Lock() As String
    Dim lv_Data As Variant
    Dim li_Index As Long
    Dim ll_Index2 As Long
    
    lsa_Lock = Split(as_cfgVal, SEP, , vbTextCompare)
    For li_Index = LBound(lsa_Lock) To UBound(lsa_Lock)
        lv_Data = Split(lsa_Lock(li_Index), SEP1, , vbTextCompare)
        If UBound(lv_Data) >= 1 Then
            If lv_Data(0) = as_filterIndex Then
                For ll_Index2 = LBound(lv_Data) + 1 To UBound(lv_Data)
                    as_Data = IIf(as_Data = "", "", as_Data & ",") & "'" & lv_Data(ll_Index2) & "'"
                Next
            End If
        End If
    Next
    
    ' assign new request
    cbo_Cbo.Clear
    If as_Data <> "" Then
        cbo_Cbo.Request = Replace(as_req, "$ITEMS$", as_Data, , , vbTextCompare)
        cbo_Cbo.Load
        If Not cbo_Cbo.ComboItems(1) Is Nothing Then Set cbo_Cbo.SelectedItem = cbo_Cbo.ComboItems(1)
    End If
    cbo_Cbo.Enabled = (cbo_Cbo.Count > 1)

    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".searchCBO()")
End Sub

' ************************************************************************************
' ********************** 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:
    Call ErrorHandler(Extender.Name & ".GetDbError()")
End Function

' Standard error handler
Private Sub ErrorHandler(ByVal as_Fct As String)
    Call Err.Raise(Err.Number, as_Fct & SEP1 & Err.Source, Err.Description)
End Sub

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


Private Sub LogMessage(ByVal as_logMsg As String, Optional ByVal as_logType As String = "I", Optional ab_throwException As Boolean = True)
On Error GoTo errHandler
Const InsertReq As String = "INSERT INTO A_Log (U_code, Z_creation_date, Source , Log_type, Log_Msg ) VALUES ($UCODE$, GETDATE(), $APP$, $LOGTYPE$, $MSG$)"
    Dim ls_Req As String
    Dim ll_cursor As Long
    
    ls_Req = Replace(InsertReq, "$UCODE$", CStr(ml_U_code))
    ls_Req = Replace(ls_Req, "$APP$", SQLStr(C_APPNAME & " " & App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision, 50))
    ls_Req = Replace(ls_Req, "$MSG$", SQLStr(as_logMsg, 4000))
    ls_Req = Replace(ls_Req, "$LOGTYPE$", SQLStr(as_logType), 1)
    
    Call ExecuteSQLSafe(mo_ArmDb, ls_Req)
    
    Exit Sub
errHandler:
    If ab_throwException Then Call ErrorHandler("LogMessage()")
End Sub

' 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
    
    If ab_saveError Then
        ls_ErrDesc = Err.Description
        ls_ErrSource = Err.Source
        ll_errnum = Err.Number
    Else
        Err.Description = ls_ErrDesc
        Err.Source = ls_ErrSource
        Err.Number = ll_errnum
    End If
End Sub
' ************************************************************************************

Private Sub RecordUpdateStatus(ByVal ACode As String, ByVal al_newStatus As eQuoteStatus)
On Error GoTo ErrorHandler
Const C_REQ As String = "exec u"

    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".RecordUpdateStatus()")
End Sub



Private Sub trw_doc_NodeClick(ByVal Node As MSComctlLib.Node)
On Error GoTo errHandler
    If mb_InternalInit Then Exit Sub
    
    If Not grd_doc.Load(trw_doc.SelectedNodeRequest(), False, , , trw_doc.SelectedItem.Tag.ml_Level < 2) Then
        Call Err.Raise(CompFncFailed, "grd_doc.Load")
    End If

    Exit Sub
errHandler:
    ErrorMessage ("trw_doc_NodeClick")
End Sub

Private Sub txt_Area_GotFocus()
On Error GoTo errHandler

    If ml_DisplayModeSubItem = mt_CstValues.DisplayMode_View _
        Or ml_DisplayModeSubItem = mt_CstValues.DisplayMode_Delete Then Exit Sub

    Call SelectTextBoxContents(txt_Area)
    
    Exit Sub
    
errHandler:
    
    Select Case Err.Number
    
    Case Else
        Call LogMessage("txt_STD_Area_GotFocus: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub

Private Sub txt_DB_Change()
On Error GoTo errHandler
    
    If mb_InternalInit Then Exit Sub
    
    
    If Not CheckNumericBeforeCalculation(txt_DB, 16, 0, 1, 1000) Then
        txt_PrimeMarg.Text = "0"
        mb_InternalInit = False
        Exit Sub
    End If
       
    Call Calculation(txt_ValueLC, txt_ValueCHF, txt_DB, txt_PrimeMarg, ml_DisplayModeSubItem)
    
    
    Exit Sub
    
errHandler:
    
    Select Case Err.Number
    Case 3064
        Call LogMessage("txt_STD_DB_Change: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox(MsgText(3064, m_Language, "#The currency you choose is not valide. Choose an other one."), vbInformation)
    Case Else
        Call LogMessage("txt_STD_DB_Change: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub

Private Sub txt_DB_GotFocus()
On Error GoTo errHandler

    If ml_DisplayModeSubItem = mt_CstValues.DisplayMode_View _
        Or ml_DisplayModeSubItem = mt_CstValues.DisplayMode_Delete Then Exit Sub

    Call SelectTextBoxContents(txt_DB)
    
    Exit Sub
    
errHandler:
    
    Select Case Err.Number
    
    Case Else
        Call LogMessage("txt_STD_DB_GotFocus: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub

Private Sub txt_DB_LostFocus()
On Error GoTo errHandler
    
    If mb_InternalInit Then Exit Sub
    
    If UCase(TypeName(UserControl.ActiveControl)) = UCase("ToolbarControl") Then Exit Sub
    
    mb_InternalInit = True
    
    If ml_DisplayModeSubItem = mt_CstValues.DisplayMode_View _
        Or ml_DisplayModeSubItem = mt_CstValues.DisplayMode_Delete Then Exit Sub
    
    If txt_DB.Locked = True Then Exit Sub
        
    If Not CheckNumericBeforeCalculation(txt_DB, 16, 0, 1, 1000, True) Then
        txt_PrimeMarg.Text = "0"
        mb_InternalInit = False
        Exit Sub
    End If
       
    Call Calculation(txt_ValueLC, txt_ValueCHF, txt_DB, txt_PrimeMarg, ml_DisplayModeSubItem)
    
    mb_InternalInit = False
    
    Exit Sub
    
errHandler:
    mb_InternalInit = False
    
    Select Case Err.Number
    Case 3064
        Call LogMessage("txt_STD_DB_LostFocus: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox(MsgText(3064, m_Language, "#The currency you choose is not valide. Choose an other one."), vbInformation)
    Case Else
        Call LogMessage("txt_STD_DB_LostFocus: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub

Private Sub txt_FreightCost_Change()
On Error GoTo errHandler
    
    If mb_InternalInit Then Exit Sub
    
    If Not cbo_IsFilled(cbo_FreightCurr) Then Exit Sub

    If IsEmpty(cbo_FreightCurr.SelectedItem.Key) Then Exit Sub

    If Not CheckNumericBeforeCalculation(txt_FreightCost, 8, 0, 1, 99999999) Then
        Exit Sub
    End If
    
    If Not ConvertToCHF(txt_FreightCost, cbo_FreightCurr, txt_FreightCostCHF, mi_DisplayMode) Then Exit Sub
    
    Exit Sub
    
errHandler:
    
    Select Case Err.Number
    Case 3064
        Call LogMessage("txt_FreightCost_Change: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox(MsgText(3064, m_Language, "#The currency you choose is not valide. Choose an other one."), vbInformation)
    Case Else
        Call LogMessage("txt_FreightCost_Change: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select

End Sub

Private Sub txt_FreightCost_GotFocus()
On Error GoTo errHandler

    If mi_DisplayMode = mt_CstValues.DisplayMode_View _
        Or mi_DisplayMode = mt_CstValues.DisplayMode_Delete Then Exit Sub

    Call SelectTextBoxContents(txt_FreightCost)
    
    Exit Sub
    
errHandler:
    
    Select Case Err.Number
    
    Case Else
        Call LogMessage("txt_FreightCost_GotFocus: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub

Private Sub txt_ValueLC_Change()
On Error GoTo errHandler
    
    If mb_InternalInit Then Exit Sub
    
    
    Debug.Print "txt_STD_ValueLC_Change"
    If cbo_IsFilled(cbo_System) Then
        If Not CheckNumericBeforeCalculation(txt_ValueLC, 17, 0, 1, 99999999) Then
            txt_ValueCHF.Text = "0"
            txt_PrimeMarg.Text = "0"
            mb_InternalInit = False
            Exit Sub
        End If
    End If
    
    
    Call Calculation(txt_ValueLC, txt_ValueCHF, txt_DB, txt_PrimeMarg, ml_DisplayModeSubItem)
    
    
    Exit Sub
    
errHandler:
    Select Case Err.Number
    Case 3064
        Call LogMessage("txt_ValueLC_Change: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox(MsgText(3064, m_Language, "#The currency you choose is not valide. Choose an other one."), vbInformation)
    
    Case Else
        Call LogMessage("txt_ValueLC_Change: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub

Private Sub txt_ValueLC_GotFocus()
On Error GoTo errHandler

    If ml_DisplayModeSubItem = mt_CstValues.DisplayMode_View _
        Or ml_DisplayModeSubItem = mt_CstValues.DisplayMode_Delete Then Exit Sub

    Call SelectTextBoxContents(txt_ValueLC)
    
    Exit Sub
    
errHandler:
    
    Select Case Err.Number
    
    Case Else
        Call LogMessage("txt_SEM_ValueLC_GotFocus: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub

Private Sub txt_ValueLC_LostFocus()
On Error GoTo errHandler
    
    If mb_InternalInit Then Exit Sub
    
    If UCase(TypeName(UserControl.ActiveControl)) = UCase("ToolbarControl") Then Exit Sub
    
    mb_InternalInit = True
    
    If ml_DisplayModeSubItem = mt_CstValues.DisplayMode_View _
        Or ml_DisplayModeSubItem = mt_CstValues.DisplayMode_Delete Then Exit Sub
    
    If txt_ValueLC.Locked = True Then Exit Sub
    
    If Not CheckNumericBeforeCalculation(txt_ValueLC, 17, 0, 1, 99999999, True) Then
        txt_ValueCHF.Text = "0"
        txt_PrimeMarg.Text = "0"
        mb_InternalInit = False
        Exit Sub
    End If
        
    Call Calculation(txt_ValueLC, txt_ValueCHF, txt_DB, txt_PrimeMarg, ml_DisplayModeSubItem)
    
    mb_InternalInit = False
    
    Exit Sub
    
errHandler:
    
    mb_InternalInit = False
    
    Select Case Err.Number
    Case 3064
        Call LogMessage("txt_SEM_ValueLC_LostFocus: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox(MsgText(3064, m_Language, "#The currency you choose is not valide. Choose an other one."), vbInformation)
    Case Else
        Call LogMessage("txt_SEM_ValueLC_LostFocus: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E")
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select
End Sub

Private Sub SelectTextBoxContents(ByVal ao_Source As TextBox)
On Error GoTo errHandler
    
    If ao_Source.Locked = True Then Exit Sub
    
    ao_Source.SelStart = 0
    ao_Source.SelLength = Len(ao_Source.Text)
    
    Exit Sub
    
errHandler:
    Call ErrorHandler("SelectTextBoxContents")
End Sub
Private Function CheckNumericBeforeCalculation(ByVal ao_Source As TextBox, ByVal al_SrcLabelIdx As Long, ByVal ai_NbDecimal As Integer, ByVal av_Min As Variant, ByVal av_Max As Variant, Optional ByVal ab_Verbose = True) As Boolean
On Error GoTo errHandler

    Dim ll_IsNum As Long
    
    If ao_Source.Text Like "+" Or ao_Source.Text Like "-" Then Exit Function
    
    ll_IsNum = CheckNumericField(ao_Source, ai_NbDecimal, av_Min, av_Max)
    If ll_IsNum <> 0 Then
        If Not ab_Verbose Then
            Exit Function
        End If
        
        Call ShowErrMessage(ll_IsNum, lbl_Label(al_SrcLabelIdx).Caption, FormatNumber(av_Min, ai_NbDecimal, , , ml_useGrouping), FormatNumber(av_Max, ai_NbDecimal, , , ml_useGrouping))
        
        If ao_Source.Visible And ao_Source.Enabled Then
            Debug.Print "Before"
            Call ao_Source.SetFocus
            DoEvents
            Debug.Print "After"
        End If
        
        Exit Function
    End If
    
    CheckNumericBeforeCalculation = True
    Exit Function
    
errHandler:
    Call ErrorHandler("CheckNumericBeforeCalculation")

End Function

Private Function SummLines(ByRef ao_grid As ArmGrid, ByVal as_Field As String) As Double
On Error GoTo errHandler
    Dim ll_i As Long
    Dim ld_retVal As Double
    
    SummLines = 0
    ld_retVal = 0
    If ao_grid.Rows = 0 Then Exit Function
    
    For ll_i = 0 To ao_grid.Rows - 1
        ld_retVal = ld_retVal + CDbl(IIf(ao_grid.Data(ll_i, as_Field) = "", 0, ao_grid.Data(ll_i, as_Field)))
    Next
    
    SummLines = ld_retVal
    Exit Function
errHandler:
    Call ErrorHandler("SummLines")
End Function

Private Sub Calculation(ByRef ao_ValueLC As TextBox, ByRef ao_ValueCHF As TextBox, ByRef ao_DB As TextBox, ByRef ao_PrimeMarg As TextBox, ByVal al_displayMode As Long)
On Error GoTo errHandler

    If Not ConvertToCHF(ao_ValueLC, cbo_currencies, ao_ValueCHF, ml_DisplayModeSubItem) Then Exit Sub
    
    Select Case al_displayMode
    Case mt_CstValues.DisplayMode_Add, mt_CstValues.DisplayMode_Update
        ao_PrimeMarg.Text = Replace(Format((CDbl(IIf(ao_ValueCHF.Text = "", 0, ao_ValueCHF.Text)) / 100) * (CDbl(Replace(IIf(ao_DB.Text = "", 0, ao_DB.Text), ".", ms_DecimalSeparator))), MONEY_FORMAT), ms_DecimalSeparator, ".", , , vbTextCompare)
    Case Else
        ao_PrimeMarg.Text = FormatNumber((CDbl(IIf(ao_ValueCHF.Text = "", 0, ao_ValueCHF.Text)) / 100) * (CDbl(Replace(IIf(ao_DB.Text = "", 0, ao_DB.Text), ".", ms_DecimalSeparator))), 2, , , ml_useGrouping)
    End Select
    
    Exit Sub
    
errHandler:
    Call ErrorHandler("Calculation")
End Sub

Private Sub CalculationTOT(ByVal al_displayMode As Long)
On Error GoTo errHandler

    Dim ll_ValueCHF As Long
    Dim ll_ValueLC As Long
    Dim ld_PrimeMarg As Double
    
    ' sum al lines in the grid
    ll_ValueCHF = Round(SummLines(grd_quote, "SQD_Value_CHF"), 0)
    ld_PrimeMarg = SummLines(grd_quote, "SQD_PrimeMargin")
    ll_ValueLC = Round(SummLines(grd_quote, "SQD_ValueLC"), 0)
    
    Select Case al_displayMode
    Case mt_CstValues.DisplayMode_Add, mt_CstValues.DisplayMode_Update
        txt_TOT_ValueCHF.Text = Replace(Format(ll_ValueCHF), ms_DecimalSeparator, ".")
        txt_TOT_PrimeMarg.Text = Replace(Format(ld_PrimeMarg, MONEY_FORMAT), ms_DecimalSeparator, ".")
        txt_TOT_ValueLC.Text = Replace(Format(ll_ValueLC), ms_DecimalSeparator, ".")
    Case Else
        txt_TOT_ValueCHF.Text = FormatNumber(ll_ValueCHF, 0, , , ml_useGrouping)
        txt_TOT_PrimeMarg.Text = FormatNumber(ld_PrimeMarg, 2, , , ml_useGrouping)
        txt_TOT_ValueLC.Text = FormatNumber(ll_ValueLC, 0, , , ml_useGrouping)
    End Select
    
    If ld_PrimeMarg = 0 Or _
        ll_ValueCHF = 0 Then
        txt_TOT_DB.Text = "0"
    Else
        Select Case al_displayMode
        Case mt_CstValues.DisplayMode_Add, mt_CstValues.DisplayMode_Update
            txt_TOT_DB.Text = Replace(Format(ld_PrimeMarg / ll_ValueCHF * 100, MONEY_FORMAT), ms_DecimalSeparator, ".")
        Case Else
            txt_TOT_DB.Text = FormatNumber(ld_PrimeMarg / ll_ValueCHF * 100, 2, , , ml_useGrouping)
        End Select
    End If
    
    If ll_ValueCHF > 999999999 Then
        ReDim lv_MsgReplaceInfo(2, 1)
        lv_MsgReplaceInfo(0, 0) = "$LabelCaption$"
        lv_MsgReplaceInfo(0, 1) = fra_TOT.Caption & " " & lbl_Label(39)
        lv_MsgReplaceInfo(1, 0) = "$Min$"
        lv_MsgReplaceInfo(1, 1) = FormatNumber(0, 0, , , ml_useGrouping)
        lv_MsgReplaceInfo(2, 0) = "$Max$"
        lv_MsgReplaceInfo(2, 1) = FormatNumber(999999999, 0, , , ml_useGrouping)

        Call MsgBox(MsgText(3063, m_Language, "#The " & lv_MsgReplaceInfo(0, 1) & " cannot be greater than" & lv_MsgReplaceInfo(2, 1) & ".", lv_MsgReplaceInfo), vbInformation)
    End If
    
    Exit Sub
    
errHandler:
    Call ErrorHandler("CalculationTOT")
End Sub

Private Function cbo_IsFilled(ByVal ao_Combo As ArmCombobox) As Boolean
On Error GoTo errHandler

    cbo_IsFilled = cbo_Value(ao_Combo) <> ""
    
    Exit Function
errHandler:
    Call ErrorHandler("cbo_IsFilled")

End Function

Private Function cbo_Value(ByRef ao_Combo As ArmCombobox) As String
On Error GoTo errHandler
    cbo_Value = ""
    If ao_Combo.SelectedItem Is Nothing Then Exit Function
    cbo_Value = ao_Combo.SelectedItem.Key
    Exit Function
errHandler:
    Call ErrorHandler("cbo_value")
End Function

Private Function opt_IsFilled(ByRef ao_options As Object) As Boolean
On Error GoTo errHandler
    opt_IsFilled = False
    
    Dim opt_obj As OptionButton
    For Each opt_obj In ao_options
        If opt_obj.Value Then
            opt_IsFilled = True
            Exit For
        End If
    Next

    Exit Function
errHandler:
    Call ErrorHandler("cbo_IsFilled")
End Function

Private Function CheckNumericField(ByVal ao_value As TextBox, ByVal ai_NbDecimal As Integer, ByVal av_Min As Variant, ByVal av_Max As Variant) As Long
On Error GoTo errHandler
    Dim ls_value As Variant
    
    ls_value = Replace(ao_value.Text, ".", ms_DecimalSeparator, , , vbTextCompare)
    
    
    On Error Resume Next
    Dim ld_Number As Double
    Dim ll_errnum As Long
    ld_Number = CDbl(ls_value)
    ll_errnum = Err.Number
    Err.Clear
    On Error GoTo errHandler
    If ll_errnum <> 0 Then
        CheckNumericField = 2131
        GoTo BackToControl
    End If

    If InStr(1, ls_value, "e", vbTextCompare) Or InStr(1, ls_value, ms_ThousandSeparator, vbTextCompare) Then
        CheckNumericField = 2131
        GoTo BackToControl
    End If
    
    
    If ai_NbDecimal = 0 And InStr(1, ls_value, ms_DecimalSeparator) Then
        CheckNumericField = 2134
        GoTo BackToControl
    End If
    
    If Not (ld_Number >= av_Min And ld_Number <= av_Max) Then
        CheckNumericField = 2132
        GoTo BackToControl
    End If

    CheckNumericField = 0
    
    Exit Function

BackToControl:
    ao_value.SelStart = 0
    ao_value.SelLength = Len(ao_value.Text)
    If ao_value.Visible And ao_value.Enabled Then
        ao_value.SetFocus
        DoEvents
    End If
    
    Exit Function

errHandler:
    Call ErrorHandler("CheckNumericField")
   
End Function

Private Function MsgText(ByVal aID As Long, ByVal aLang As String, ByVal aDefault As String, Optional ByVal aInfo As Variant) As String

On Error GoTo errHandler

Const DB_REQ As String = "SELECT message_text FROM error_message WHERE msgid = $id$ AND Language_code = '$lang$'"

    MsgText = ""
    
    Dim lRequest As String
    lRequest = Replace(DB_REQ, "$id$", aID)
    lRequest = Replace(lRequest, "$lang$", aLang)
    Dim lData As Long
    
    lData = OpenSQLSafe(mo_ArmDb, lRequest)
    
    Dim lBuffer As String
    lBuffer = mo_ArmDb.GetFields(lData, "message_text")
    mo_ArmDb.Close (lData)
    If lBuffer = "" Then lBuffer = aDefault
    
    Dim li_Idx As Integer
    If Not IsMissing(aInfo) Then
        For li_Idx = 0 To UBound(aInfo)
            lBuffer = Replace(lBuffer, aInfo(li_Idx, 0), aInfo(li_Idx, 1), , , vbTextCompare)
        Next li_Idx
    End If
    
    
    MsgText = lBuffer
    Exit Function
errHandler:
    mo_ArmDb.Close (lData)
    Call ErrorHandler("MsgText")
   
End Function


Private Function ConvertToCHF(ByRef ao_Source As TextBox, ByRef ao_Currency As ArmCombobox, ByRef ao_Destination As TextBox, ByVal al_displayMode As Long) As Boolean ', ByVal al_SrcLabelIdx As Long, ByVal al_DestLabelIdx As Long, ByVal ai_NbDecimal As Integer, ByVal av_Min As Variant, ByVal av_Max As Variant, Optional ByVal ab_Verbose = True) As Boolean
On Error GoTo errHandler

    Dim ld_valueCH As Double
    Dim lc_rate As Long
    Dim lv_MsgReplaceInfo As Variant
    Dim lValues As Variant
    
    ' Check if reference data are selected
    If Not cbo_IsFilled(ao_Currency) Then
        ao_Destination.Text = "0"
        Exit Function
    End If
    
    ld_valueCH = Round(GetValueInCHF(CDbl(IIf(ao_Source.Text = "", 0, ao_Source.Text)), ao_Currency), 0)
    
    If ao_Destination.Tag <> "" Then
        Select Case al_displayMode
        Case mt_CstValues.DisplayMode_Add, mt_CstValues.DisplayMode_Update
            ao_Destination.Text = Replace(Format(ld_valueCH, ao_Destination.Tag), ms_DecimalSeparator, ".")
        Case Else
            ao_Destination.Text = FormatNumber(ld_valueCH, 2, , , ml_useGrouping)
        End Select
        
    Else
        ao_Destination.Text = Format(ld_valueCH, "0")
    End If
    
    ConvertToCHF = True
    Exit Function

errHandler:
    Call ErrorHandler("ConvertToCHF")

End Function

Private Function GetValueInCHF(ByVal ad_Value, ByRef ao_Currency As ArmCombobox) As Double
On Error GoTo errHandler

    Dim ld_rate As Double
    Dim lc_rate As Long
    Dim lv_MsgReplaceInfo As Variant
    Dim lValues As Variant
    
    GetValueInCHF = 0
    ' Check if reference data are selected
    If Not cbo_IsFilled(ao_Currency) Then Exit Function
    
    ' If the money is CHF, no conversion needed
    If ao_Currency.SelectedItem.GetData(0) = "CHF" Then
        GetValueInCHF = ad_Value
        Exit Function
    End If
    
    ld_rate = ao_Currency.SelectedItem.GetData(2)
    
    If ld_rate = 0 Then
        Err.Raise 3064, C_APPNAME, "The exchange rate is 0 :: " & ao_Currency.SelectedItem.GetData(0)
    End If
    
    GetValueInCHF = ad_Value / ld_rate
    Exit Function

errHandler:
    Call ErrorHandler("GetValueInCHF")

End Function

Private Function Download_File(ByVal al_fileID As Long) As String
Dim ls_ZipDir As String
Dim ls_Request As String
Dim ls_dir As String

On Error GoTo errHandler
    Download_File = ""
    
    ls_dir = GetTempDir & "\CapSOMDoc"
    If Not mo_FSO.FolderExists(ls_dir) Then
      Call mo_FSO.CreateFolder(ls_dir)
    End If
    ls_ZipDir = ls_dir & "\" & al_fileID
    If Not mo_FSO.FolderExists(ls_ZipDir) Then
      Call mo_FSO.CreateFolder(ls_ZipDir)
    End If
    
    Dim lo_folder As Folder
    Set lo_folder = mo_FSO.GetFolder(ls_ZipDir)
    If lo_folder.Files.Count = 0 Then
        ls_Request = "SELECT fileZip FROM Cap_SOM_Doc_FileZip WHERE fileID = " & al_fileID
        If Not mo_ArmDb.BlobToFileSQL(ls_Request, ls_ZipDir, True, True) Then
            Call Err.Raise(ArmErr.CompFncFailed, "BlobToFileSQL", mo_ArmDb.LastErrorMessage & " ls_Request=" & ls_Request & ",ls_ZipDir=" & ls_ZipDir)
        End If
    End If
    Download_File = ls_ZipDir
  Exit Function
errHandler:
  Call ErrorHandler("Download_File:" & al_fileID)
End Function

Private Sub Launch_File(ByVal al_fileID As Long)
Dim ls_TempDir As String
Dim lo_Fld As Object
Dim lo_File As Object
Dim lo_shell As Object

On Error GoTo errHandler
    If al_fileID = "0" Then Exit Sub
    
    ls_TempDir = GetTempDir & "\CapSOMDoc\" & al_fileID
    Set lo_shell = CreateObject("Shell.Application")
    
    Set lo_Fld = mo_FSO.GetFolder(ls_TempDir)
    For Each lo_File In lo_Fld.Files
        Call lo_shell.ShellExecute(lo_File.Path, "", "", "open", 1)
    Next
    Set lo_shell = Nothing
    Exit Sub
errHandler:
    Set lo_shell = Nothing
    Call ErrorHandler("Launch_Report_File:" & al_fileID)
End Sub

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

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

Private Function GetAConfigDataByCountry(ByRef ao_DB As ArmDb, ByVal as_Key As String) As String
On Error GoTo errHandler

    GetAConfigDataByCountry = ""
    
    Const C_REQ As String = "SELECT A.CFG_Value" & vbCrLf & _
                            "FROM security_identity SI" & vbCrLf & _
                            " INNER JOIN A_Config A ON CFG_Key='$KEY$'+'_' + SI.CT_code" & vbCrLf & _
                            "WHERE SI.login_Name = '$LOGIN$'"
    Dim ll_cursor As Long
    Dim ls_Req As String
    
    ls_Req = Replace(C_REQ, "$KEY$", as_Key, , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$LOGIN$", ms_UID, , , vbTextCompare)
    
    ll_cursor = OpenSQLSafe(ao_DB, ls_Req)
    
    If ao_DB.RowCount(ll_cursor) = 1 Then
        GetAConfigDataByCountry = ao_DB.GetFields(ll_cursor, "CFG_Value")
    End If
    Call ao_DB.Close(ll_cursor)
    
    Exit Function
errHandler:
    Call ao_DB.Close(ll_cursor)
    Call ErrorHandler("GetAConfigDataByCountry")
End Function

Private Function MapNetworkDrive(ByRef ao_WshNetwork As Object, ByVal as_drive As String, ByVal as_remotePath As String, ByVal as_User As String, ByVal as_pass As String) As Boolean
On Error GoTo ErrorHandler
    If Trim(as_User) = "" Then
        Call mo_WshNetwork.MapNetworkDrive(as_drive, as_remotePath, False)
    Else
        Call mo_WshNetwork.MapNetworkDrive(as_drive, as_remotePath, False, as_User, as_pass)
    End If
    MapNetworkDrive = True
    Exit Function
ErrorHandler:
    ' mapping failed
    ReDim ms_MsgInfo(2, 1)
    ms_MsgInfo(0, 0) = "$DRIVE$"
    ms_MsgInfo(0, 1) = as_drive
    ms_MsgInfo(1, 0) = "$PATH$"
    ms_MsgInfo(1, 1) = as_remotePath
    ms_MsgInfo(2, 0) = "$ERROR$"
    ms_MsgInfo(2, 1) = Err.Number & " - " & Err.Description
    Call MsgBox(MsgText(666, m_Language, "Application cannot map drive $DRIVE$ to $PATH$." & vbCrLf & "$ERROR$" & vbCrLf & "Try it manually or call application support please.", ms_MsgInfo))
End Function


Private Function NetworkDriveExists(ByRef ao_WshNetwork As Object, ByVal as_drive As String) As Boolean
On Error GoTo ErrorHandler

    Dim lo_Drives As Object
    Dim ll_Index As Long
    NetworkDriveExists = False
    
    Set lo_Drives = ao_WshNetwork.EnumNetworkDrives
    For ll_Index = 0 To lo_Drives.Count - 1 Step 2
        If lo_Drives.Item(ll_Index) = as_drive Then
            ' drive exists
            NetworkDriveExists = True
            Exit Function
        End If
    Next

    Exit Function
ErrorHandler:
    Call ErrorHandler("NetworkDriveExists")
End Function

Private Sub Document_Move(ByVal as_SourceFile As String, ByVal as_DestFile As String)
On Error GoTo errHandler
    
    If mo_FSO.FileExists(as_SourceFile) Then
        Call mo_FSO.MoveFile(as_SourceFile, as_DestFile)
    Else
        Err.Raise 2512, "as_SourceFile", "File do not exists: " & as_SourceFile
    End If
    Exit Sub
errHandler:
    Call ErrorHandler("Document_Move from '" & as_SourceFile & "'" & " to '" & as_DestFile & "'")
End Sub

Private Sub Document_Rename(ByVal as_FileName As String, ByVal as_NewFileName As String)
On Error GoTo errHandler
    
    Dim lo_File As Object
    
    Set lo_File = mo_FSO.GetFile(as_FileName)
    If lo_File Is Nothing Then
        Err.Raise ArmErr.CompFncFailed, "GetFile", "Cannot get file: " & as_FileName
    End If
    Dim a As File
    
    lo_File.Name = as_NewFileName
    Set lo_File = Nothing
    Exit Sub
errHandler:
    Call ErrorHandler("Document_Rename")
End Sub

Private Function Document_Save(ByVal as_originalFilePath As String, ByVal as_documentServer As String, ByVal as_fileID As String) As String
On Error GoTo errHandler
    Document_Save = ""

    ' 1. zip the file
    Dim ls_zipFile As String
    Dim ls_ZipDir As String
    
    ls_ZipDir = GetTempDir & "\CapSOMDocUpload"
    If Not mo_FSO.FolderExists(ls_ZipDir) Then
      Call mo_FSO.CreateFolder(ls_ZipDir)
    End If
    
    ls_zipFile = ls_ZipDir & "\" & as_fileID & "_0.zip"
    Call mo_ZIP.CompressFile(as_originalFilePath, ls_zipFile, 9, -1)
    
    ' 2. move to server
    Dim ls_serverFile As String
    ls_serverFile = as_documentServer & as_fileID & "_0.zip"
    
    Call Document_Move(ls_zipFile, ls_serverFile)
    Document_Save = ls_serverFile

    Exit Function
errHandler:
    Call ErrorHandler("Document_Save")
End Function

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


