VERSION 5.00
Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.1#0"; "mscomctl.ocx"
Object = "{5E9E78A0-531B-11CF-91F6-C2863C385E30}#1.0#0"; "MSFLXGRD.OCX"
Begin VB.UserControl capdly 
   ClientHeight    =   11295
   ClientLeft      =   0
   ClientTop       =   0
   ClientWidth     =   18105
   ScaleHeight     =   11295
   ScaleWidth      =   18105
   Begin VB.Frame frm_sales_rep 
      Caption         =   "#Sales by rep"
      Height          =   7500
      Left            =   8580
      TabIndex        =   144
      Tag             =   "frm_sales_rep"
      Top             =   2865
      Width           =   11340
      Begin VB.Frame frm_sales_by_rep_grouping 
         Caption         =   "#Select grouping"
         Height          =   1815
         Left            =   2280
         TabIndex        =   154
         Tag             =   "frm_sales_by_rep_grp"
         Top             =   1440
         Width           =   5175
         Begin VB.CheckBox chk_sales_by_rep_grp 
            Caption         =   "#By rep"
            Enabled         =   0   'False
            Height          =   255
            Index           =   2
            Left            =   240
            TabIndex        =   157
            Tag             =   "chk_sales_by_rep_rep"
            Top             =   1320
            Value           =   1  'Checked
            Width           =   3855
         End
         Begin VB.CheckBox chk_sales_by_rep_grp 
            Caption         =   "#By Country"
            Height          =   255
            Index           =   1
            Left            =   240
            TabIndex        =   156
            Tag             =   "chk_sales_by_rep_ct"
            Top             =   840
            Width           =   3855
         End
         Begin VB.CheckBox chk_sales_by_rep_grp 
            Caption         =   "#By Market"
            Height          =   255
            Index           =   0
            Left            =   240
            TabIndex        =   155
            Tag             =   "chk_sales_by_rep_mkt"
            Top             =   360
            Width           =   3855
         End
      End
      Begin MSFlexGridLib.MSFlexGrid grd_sales_rep 
         Height          =   4605
         Left            =   135
         TabIndex        =   145
         Top             =   225
         Visible         =   0   'False
         Width           =   7815
         _ExtentX        =   13785
         _ExtentY        =   8123
         _Version        =   393216
         Rows            =   3
         Cols            =   3
         FixedRows       =   2
         FixedCols       =   2
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   4
         AllowUserResizing=   3
      End
      Begin VB.Label lbl_salesRepCalculation 
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   12
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   1725
         Left            =   1950
         TabIndex        =   146
         Tag             =   "lbl_salesRepCalculation"
         Top             =   2220
         Visible         =   0   'False
         Width           =   6495
      End
   End
   Begin VB.Frame frm_sales 
      Caption         =   "#Sales"
      Height          =   9045
      Left            =   9810
      TabIndex        =   74
      Tag             =   "frm_sales"
      Top             =   1545
      Width           =   12450
      Begin VB.Frame frm_sales_PDF 
         Caption         =   "#Period selection"
         Height          =   1830
         Left            =   1215
         TabIndex        =   129
         Tag             =   "frm_sales_PDF"
         Top             =   1470
         Visible         =   0   'False
         Width           =   7275
         Begin VB.Frame frm_sales_PDF_Period 
            Height          =   585
            Left            =   120
            TabIndex        =   140
            Tag             =   "frm_sales_PDF_Period"
            Top             =   1095
            Visible         =   0   'False
            Width           =   3720
            Begin Project1.ArmCombobox cbo_DR_Month 
               Height          =   345
               Left            =   1530
               TabIndex        =   141
               Top             =   165
               Width           =   2055
               _ExtentX        =   3625
               _ExtentY        =   609
            End
            Begin Project1.ArmCombobox cbo_DR_Year 
               Height          =   345
               Left            =   90
               TabIndex        =   142
               Top             =   165
               Width           =   1335
               _ExtentX        =   2355
               _ExtentY        =   609
            End
         End
         Begin VB.CommandButton btn_sales_doPrint 
            Caption         =   "#Print"
            Height          =   495
            Left            =   5760
            TabIndex        =   139
            Tag             =   "btn_sales_doPrint"
            Top             =   195
            Width           =   1365
         End
         Begin VB.OptionButton opt_salesPeriod 
            Caption         =   "#Current year"
            Height          =   195
            Index           =   0
            Left            =   165
            TabIndex        =   138
            Tag             =   "opt_salesPeriodCY"
            Top             =   300
            Value           =   -1  'True
            Width           =   2595
         End
         Begin VB.OptionButton opt_salesPeriod 
            Caption         =   "#Current month"
            Height          =   195
            Index           =   1
            Left            =   165
            TabIndex        =   137
            Tag             =   "opt_salesPeriodCM"
            Top             =   555
            Width           =   2595
         End
         Begin VB.OptionButton opt_salesPeriod 
            Caption         =   "#Custom month"
            Height          =   195
            Index           =   2
            Left            =   165
            TabIndex        =   136
            Tag             =   "opt_salesPeriodCU"
            Top             =   840
            Width           =   2595
         End
         Begin VB.CommandButton btn_sales_quitPDF 
            Caption         =   "#Close"
            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            =   5760
            TabIndex        =   135
            Tag             =   "btn_sales_quitPDF"
            Top             =   780
            Width           =   1365
         End
         Begin VB.Frame frm_sales_PDF_grp 
            Caption         =   "#Grouping"
            Height          =   900
            Left            =   4005
            TabIndex        =   132
            Tag             =   "frm_sales_PDF_grp"
            Top             =   165
            Width           =   1635
            Begin VB.CheckBox chk_salesPeriodGrp 
               Caption         =   "#Market"
               Height          =   210
               Index           =   0
               Left            =   105
               TabIndex        =   134
               Tag             =   "chk_salesPeriodGrpMkt"
               Top             =   300
               Width           =   1410
            End
            Begin VB.CheckBox chk_salesPeriodGrp 
               Caption         =   "#Country"
               Height          =   210
               Index           =   1
               Left            =   105
               TabIndex        =   133
               Tag             =   "chk_salesPeriodGrpCT"
               Top             =   585
               Width           =   1410
            End
         End
         Begin VB.CheckBox chk_sales_exportGVSOnly 
            Caption         =   "#Export GSV EUR only"
            Height          =   285
            Left            =   4080
            TabIndex        =   131
            Tag             =   "exportGVSOnly"
            Top             =   1125
            Width           =   3030
         End
         Begin VB.CheckBox chk_sales_exportXLS 
            Caption         =   "#PDF export"
            Height          =   195
            Left            =   4080
            TabIndex        =   130
            Tag             =   "sales_exportXLS"
            Top             =   1455
            Value           =   1  'Checked
            Width           =   3030
         End
      End
      Begin MSFlexGridLib.MSFlexGrid grd_sales 
         Height          =   7890
         Left            =   150
         TabIndex        =   79
         Top             =   255
         Visible         =   0   'False
         Width           =   12135
         _ExtentX        =   21405
         _ExtentY        =   13917
         _Version        =   393216
         Cols            =   3
         FixedCols       =   2
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   4
         AllowUserResizing=   3
      End
      Begin MSComctlLib.TabStrip tbs_sales 
         Height          =   390
         Left            =   90
         TabIndex        =   122
         Top             =   8535
         Width           =   8070
         _ExtentX        =   14235
         _ExtentY        =   688
         MultiRow        =   -1  'True
         TabFixedWidth   =   1976
         Placement       =   1
         TabMinWidth     =   529
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   2
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#SAP sales"
               Key             =   "ALL"
               Object.Tag             =   "sales_ALL"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#SAP + MSA Sales"
               Key             =   "MSA"
               Object.Tag             =   "sales_MSA"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_sales_MSA 
         Height          =   7890
         Left            =   2490
         TabIndex        =   123
         Top             =   645
         Visible         =   0   'False
         Width           =   12135
         _ExtentX        =   21405
         _ExtentY        =   13917
         _Version        =   393216
         Cols            =   3
         FixedCols       =   2
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   4
         AllowUserResizing=   3
      End
      Begin VB.Label lbl_salesCalculation 
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   12
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   1725
         Left            =   3180
         TabIndex        =   80
         Tag             =   "lbl_salesCalculation"
         Top             =   3570
         Visible         =   0   'False
         Width           =   6495
      End
   End
   Begin VB.Frame frm_visits 
      Caption         =   "#Visits"
      Height          =   8850
      Left            =   1470
      TabIndex        =   72
      Tag             =   "frm_visits"
      Top             =   7560
      Visible         =   0   'False
      Width           =   10725
      Begin Project1.ArmGrid grd_visitCounts 
         Height          =   1995
         Index           =   2
         Left            =   90
         TabIndex        =   87
         Tag             =   "grd_visitCounts_N"
         Top             =   315
         Visible         =   0   'False
         Width           =   10455
         _ExtentX        =   18441
         _ExtentY        =   3519
      End
      Begin Project1.ArmGrid grd_visitCounts 
         Height          =   1995
         Index           =   1
         Left            =   90
         TabIndex        =   86
         Tag             =   "grd_visitCounts_O"
         Top             =   315
         Visible         =   0   'False
         Width           =   10455
         _ExtentX        =   18441
         _ExtentY        =   3519
      End
      Begin Project1.ArmGrid grd_visitDetail 
         Height          =   5985
         Index           =   2
         Left            =   90
         TabIndex        =   85
         Tag             =   "grd_visitDetail_N"
         Top             =   2370
         Visible         =   0   'False
         Width           =   10455
         _ExtentX        =   18441
         _ExtentY        =   10557
      End
      Begin Project1.ArmGrid grd_visitDetail 
         Height          =   6060
         Index           =   1
         Left            =   90
         TabIndex        =   84
         Tag             =   "grd_visitDetail_O"
         Top             =   2370
         Visible         =   0   'False
         Width           =   10455
         _ExtentX        =   18441
         _ExtentY        =   10689
      End
      Begin VB.CheckBox chk_allData 
         Alignment       =   1  'Right Justify
         Caption         =   "#Select all data"
         Height          =   270
         Left            =   8595
         TabIndex        =   81
         Tag             =   "chk_allData"
         Top             =   8490
         Width           =   1950
      End
      Begin Project1.ArmGrid grd_visitCounts 
         Height          =   1995
         Index           =   0
         Left            =   90
         TabIndex        =   75
         Tag             =   "grd_visitCounts"
         Top             =   315
         Visible         =   0   'False
         Width           =   10455
         _ExtentX        =   18441
         _ExtentY        =   3519
      End
      Begin Project1.ArmGrid grd_visitDetail 
         Height          =   6060
         Index           =   0
         Left            =   90
         TabIndex        =   76
         Tag             =   "grd_visitDetail"
         Top             =   2370
         Visible         =   0   'False
         Width           =   10455
         _ExtentX        =   18441
         _ExtentY        =   10689
      End
      Begin MSComctlLib.TabStrip tbs_visitCTType 
         Height          =   390
         Left            =   120
         TabIndex        =   77
         Top             =   8355
         Width           =   8070
         _ExtentX        =   14235
         _ExtentY        =   688
         MultiRow        =   -1  'True
         TabFixedWidth   =   1976
         Placement       =   1
         TabMinWidth     =   529
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   3
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#All customers"
               Object.Tag             =   "NULL"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Omega Only"
               Object.Tag             =   "3"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#New customers"
               Object.Tag             =   "NULL2"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin VB.Label lbl_visitCalculation 
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   9.75
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   1995
         Left            =   1830
         TabIndex        =   78
         Top             =   3540
         Visible         =   0   'False
         Width           =   6615
      End
   End
   Begin VB.Frame frm_visits2 
      Caption         =   "#Visits 2 - number"
      Height          =   8955
      Left            =   2430
      TabIndex        =   116
      Tag             =   "frm_visits2"
      Top             =   8760
      Visible         =   0   'False
      Width           =   10650
      Begin VB.Frame frm_visits2_Grouping 
         Caption         =   "#Report grouping"
         Height          =   1005
         Left            =   165
         TabIndex        =   117
         Tag             =   "frm_visits2_Grouping"
         Top             =   285
         Width           =   4335
         Begin VB.CheckBox chk_visits2_Grouping 
            Caption         =   "#by Country"
            Height          =   255
            Index           =   0
            Left            =   105
            TabIndex        =   119
            Tag             =   "chk_PS2_Grouping_CT"
            Top             =   270
            Width           =   4080
         End
         Begin VB.CheckBox chk_visits2_Grouping 
            Caption         =   "#by Sales rep"
            Height          =   255
            Index           =   1
            Left            =   105
            TabIndex        =   118
            Tag             =   "chk_PS2_Grouping_SR"
            Top             =   615
            Width           =   4080
         End
      End
      Begin MSFlexGridLib.MSFlexGrid grd_visits2 
         Height          =   8550
         Left            =   180
         TabIndex        =   120
         Top             =   1440
         Visible         =   0   'False
         Width           =   10470
         _ExtentX        =   18468
         _ExtentY        =   15081
         _Version        =   393216
         Cols            =   7
         FixedCols       =   6
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
      Begin VB.Label lbl_visits2Calculation 
         Caption         =   "Label1"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   12
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   2715
         Left            =   1710
         TabIndex        =   121
         Tag             =   "lbl_visits2Calculation"
         Top             =   2865
         Width           =   8040
      End
      Begin VB.Image img_visits2Max 
         Height          =   270
         Left            =   10275
         Picture         =   "capdly.ctx":0000
         Top             =   0
         Width           =   300
      End
      Begin VB.Image img_visits2Min 
         Height          =   255
         Left            =   10275
         Picture         =   "capdly.ctx":047A
         Top             =   0
         Visible         =   0   'False
         Width           =   300
      End
   End
   Begin VB.Frame frm_statusProjects3 
      Caption         =   "#Project status  3 - number"
      Height          =   8955
      Left            =   8655
      TabIndex        =   110
      Tag             =   "frm_statusProjects3"
      Top             =   5670
      Visible         =   0   'False
      Width           =   10650
      Begin MSFlexGridLib.MSFlexGrid grd_StatusProjects3 
         Height          =   8550
         Left            =   105
         TabIndex        =   111
         Top             =   270
         Visible         =   0   'False
         Width           =   10470
         _ExtentX        =   18468
         _ExtentY        =   15081
         _Version        =   393216
         Cols            =   5
         FixedCols       =   4
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
      Begin VB.Label lbl_statusProj3Calculation 
         Caption         =   "Label1"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   12
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   2715
         Left            =   1425
         TabIndex        =   112
         Tag             =   "lbl_statusProj3Calculation"
         Top             =   2925
         Width           =   8040
      End
      Begin VB.Image img_ps3Max 
         Height          =   270
         Left            =   10275
         Picture         =   "capdly.ctx":08B8
         Top             =   0
         Width           =   300
      End
      Begin VB.Image img_ps3Min 
         Height          =   255
         Left            =   10275
         Picture         =   "capdly.ctx":0D32
         Top             =   0
         Visible         =   0   'False
         Width           =   300
      End
   End
   Begin VB.Frame frm_statusProjects2 
      Caption         =   "#Project status  2 - number"
      Height          =   8955
      Left            =   8925
      TabIndex        =   104
      Tag             =   "frm_statusProjects2"
      Top             =   3165
      Visible         =   0   'False
      Width           =   10650
      Begin VB.Frame frm_PS2_Grouping 
         Caption         =   "#Report grouping"
         Height          =   1005
         Left            =   165
         TabIndex        =   113
         Tag             =   "frm_PS2_Grouping"
         Top             =   285
         Width           =   4335
         Begin VB.CheckBox chk_PS2_Grouping 
            Caption         =   "#by Sales rep"
            Height          =   255
            Index           =   1
            Left            =   105
            TabIndex        =   115
            Tag             =   "chk_PS2_Grouping_SR"
            Top             =   615
            Width           =   4080
         End
         Begin VB.CheckBox chk_PS2_Grouping 
            Caption         =   "#by Country"
            Height          =   255
            Index           =   0
            Left            =   105
            TabIndex        =   114
            Tag             =   "chk_PS2_Grouping_CT"
            Top             =   270
            Width           =   4080
         End
      End
      Begin MSFlexGridLib.MSFlexGrid grd_StatusProjects2 
         Height          =   8550
         Left            =   225
         TabIndex        =   105
         Top             =   2325
         Visible         =   0   'False
         Width           =   10470
         _ExtentX        =   18468
         _ExtentY        =   15081
         _Version        =   393216
         Rows            =   3
         Cols            =   7
         FixedRows       =   2
         FixedCols       =   6
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
      Begin VB.Image img_ps2Min 
         Height          =   255
         Left            =   10275
         Picture         =   "capdly.ctx":1170
         Top             =   0
         Visible         =   0   'False
         Width           =   300
      End
      Begin VB.Image img_ps2Max 
         Height          =   270
         Left            =   10275
         Picture         =   "capdly.ctx":15AE
         Top             =   0
         Width           =   300
      End
      Begin VB.Label lbl_statusProj2Calculation 
         Caption         =   "Label1"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   12
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   2715
         Left            =   1425
         TabIndex        =   106
         Tag             =   "lbl_statusProj2Calculation"
         Top             =   2925
         Width           =   8040
      End
   End
   Begin VB.Frame frm_statusProjects 
      Caption         =   "#Project status - number"
      Height          =   8955
      Left            =   5955
      TabIndex        =   101
      Tag             =   "frm_statusProjects"
      Top             =   3645
      Visible         =   0   'False
      Width           =   10650
      Begin MSFlexGridLib.MSFlexGrid grd_StatusProjects 
         Height          =   8550
         Left            =   105
         TabIndex        =   102
         Top             =   270
         Visible         =   0   'False
         Width           =   10470
         _ExtentX        =   18468
         _ExtentY        =   15081
         _Version        =   393216
         Rows            =   3
         Cols            =   5
         FixedRows       =   2
         FixedCols       =   4
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
      Begin VB.Image img_psMax 
         Height          =   270
         Left            =   10275
         Picture         =   "capdly.ctx":1A28
         Top             =   0
         Width           =   300
      End
      Begin VB.Image img_psMin 
         Height          =   255
         Left            =   10275
         Picture         =   "capdly.ctx":1EA2
         Top             =   0
         Width           =   300
      End
      Begin VB.Label lbl_statusProjCalculation 
         Caption         =   "Label1"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   12
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   2715
         Left            =   1425
         TabIndex        =   103
         Tag             =   "lbl_statusProjCalc"
         Top             =   2925
         Width           =   8040
      End
   End
   Begin VB.Frame frm_projects 
      Caption         =   "#Projects"
      Height          =   8955
      Left            =   2250
      TabIndex        =   73
      Tag             =   "frm_projects"
      Top             =   4785
      Width           =   10650
      Begin VB.Frame frm_projectCalc 
         Height          =   3180
         Left            =   705
         TabIndex        =   92
         Tag             =   "frm_projectCalc"
         Top             =   2430
         Visible         =   0   'False
         Width           =   9165
         Begin VB.Label lbl_projectCalculation 
            Alignment       =   2  'Center
            Caption         =   "#caption calculate projects"
            BeginProperty Font 
               Name            =   "MS Sans Serif"
               Size            =   12
               Charset         =   0
               Weight          =   700
               Underline       =   0   'False
               Italic          =   0   'False
               Strikethrough   =   0   'False
            EndProperty
            Height          =   2820
            Left            =   150
            TabIndex        =   93
            Tag             =   "lbl_projectCalculation"
            Top             =   240
            Width           =   8880
         End
      End
      Begin MSFlexGridLib.MSFlexGrid grd_project 
         Height          =   7550
         Index           =   7
         Left            =   225
         TabIndex        =   99
         Tag             =   "grd_ASprojectW"
         Top             =   645
         Visible         =   0   'False
         Width           =   10200
         _ExtentX        =   17992
         _ExtentY        =   13309
         _Version        =   393216
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
      Begin MSFlexGridLib.MSFlexGrid grd_project 
         Height          =   7530
         Index           =   6
         Left            =   225
         TabIndex        =   98
         Tag             =   "grd_ASprojectM"
         Top             =   645
         Visible         =   0   'False
         Width           =   10200
         _ExtentX        =   17992
         _ExtentY        =   13282
         _Version        =   393216
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
      Begin MSFlexGridLib.MSFlexGrid grd_project 
         Height          =   7695
         Index           =   5
         Left            =   225
         TabIndex        =   97
         Tag             =   "grd_projectSAW"
         Top             =   645
         Visible         =   0   'False
         Width           =   10200
         _ExtentX        =   17992
         _ExtentY        =   13573
         _Version        =   393216
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
      Begin MSFlexGridLib.MSFlexGrid grd_project 
         Height          =   7695
         Index           =   4
         Left            =   225
         TabIndex        =   96
         Tag             =   "grd_projectSAM"
         Top             =   645
         Visible         =   0   'False
         Width           =   10200
         _ExtentX        =   17992
         _ExtentY        =   13573
         _Version        =   393216
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
      Begin MSFlexGridLib.MSFlexGrid grd_project 
         Height          =   7695
         Index           =   3
         Left            =   225
         TabIndex        =   95
         Tag             =   "grd_projectSTDW"
         Top             =   645
         Visible         =   0   'False
         Width           =   10200
         _ExtentX        =   17992
         _ExtentY        =   13573
         _Version        =   393216
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
      Begin MSFlexGridLib.MSFlexGrid grd_project 
         Height          =   7695
         Index           =   2
         Left            =   225
         TabIndex        =   94
         Tag             =   "grd_projectSTDM"
         Top             =   645
         Visible         =   0   'False
         Width           =   10200
         _ExtentX        =   17992
         _ExtentY        =   13573
         _Version        =   393216
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
      Begin MSFlexGridLib.MSFlexGrid grd_project 
         Height          =   7695
         Index           =   0
         Left            =   225
         TabIndex        =   91
         Tag             =   "grd_projectM"
         Top             =   645
         Visible         =   0   'False
         Width           =   10200
         _ExtentX        =   17992
         _ExtentY        =   13573
         _Version        =   393216
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
      Begin MSFlexGridLib.MSFlexGrid grd_project 
         Height          =   7695
         Index           =   1
         Left            =   225
         TabIndex        =   89
         Tag             =   "grd_projectW"
         Top             =   645
         Visible         =   0   'False
         Width           =   10200
         _ExtentX        =   17992
         _ExtentY        =   13573
         _Version        =   393216
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
      Begin MSComctlLib.TabStrip tbs_project 
         Height          =   390
         Left            =   255
         TabIndex        =   90
         Top             =   8220
         Width           =   10200
         _ExtentX        =   17992
         _ExtentY        =   688
         MultiRow        =   -1  'True
         TabFixedWidth   =   1976
         Placement       =   1
         TabMinWidth     =   529
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   2
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Month view"
               Object.Tag             =   "MONTH"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Week view"
               Object.Tag             =   "WEEK"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin MSComctlLib.TabStrip tbs_projectType 
         Height          =   8460
         Left            =   135
         TabIndex        =   88
         Top             =   255
         Width           =   10410
         _ExtentX        =   18362
         _ExtentY        =   14923
         TabWidthStyle   =   2
         MultiRow        =   -1  'True
         TabFixedWidth   =   4057
         TabMinWidth     =   529
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   4
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#All"
               Object.Tag             =   "PRJ_ALL"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Std"
               Object.Tag             =   "PRJ_STD"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#SA"
               Object.Tag             =   "PRJ_SA"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab4 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#AS"
               Object.Tag             =   "PRJ_AS"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
   End
   Begin VB.Frame fr_report 
      Caption         =   "#Info on report shown"
      Height          =   9180
      Left            =   6195
      TabIndex        =   0
      Tag             =   "fr_report"
      Top             =   3225
      Visible         =   0   'False
      Width           =   10695
      Begin MSComctlLib.TabStrip tbs_Result 
         Height          =   375
         Index           =   6
         Left            =   90
         TabIndex        =   64
         Tag             =   "tbs_VisitAnalysis"
         Top             =   6705
         Width           =   4665
         _ExtentX        =   8229
         _ExtentY        =   661
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   2
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Visit Analysis"
               Key             =   "G6"
               Object.Tag             =   "tb_visitAnalysis"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Visit Analysis Filtered"
               Key             =   "G12"
               Object.Tag             =   "tb_visitAnalysisFilter"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin MSComctlLib.TabStrip tbs_Result 
         Height          =   375
         Index           =   7
         Left            =   5250
         TabIndex        =   65
         Tag             =   "tbs_MSCAnalysis"
         Top             =   6705
         Width           =   4665
         _ExtentX        =   8229
         _ExtentY        =   661
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   2
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#MSC Analysis"
               Key             =   "G7"
               Object.Tag             =   "tb_MSCAnalysis"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#MSC Analysis Filtered"
               Key             =   "G13"
               Object.Tag             =   "tb_MSCAnalysisFilter"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin MSComctlLib.TabStrip tbs_Result 
         Height          =   375
         Index           =   5
         Left            =   5250
         TabIndex        =   63
         Tag             =   "tbs_SemAnalysis"
         Top             =   4635
         Width           =   4665
         _ExtentX        =   8229
         _ExtentY        =   661
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   2
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Seminar Analysis"
               Key             =   "G5"
               Object.Tag             =   "tb_semAnalysis"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Seminar Analysis By User Filtered"
               Key             =   "G11"
               Object.Tag             =   "tb_semAnalysisFilter"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin MSComctlLib.TabStrip tbs_Result 
         Height          =   615
         Index           =   4
         Left            =   90
         TabIndex        =   62
         Tag             =   "tbs_Focus"
         Top             =   4380
         Width           =   4635
         _ExtentX        =   8176
         _ExtentY        =   1085
         MultiRow        =   -1  'True
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   3
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Specification By Focus Product"
               Key             =   "G4"
               Object.Tag             =   "tb_specyFocPrd"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Focus Products By User"
               Key             =   "G9"
               Object.Tag             =   "tb_focPrdByUser"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Focus Products By User Filtered"
               Key             =   "G10"
               Object.Tag             =   "tb_focPrdByUserFilter"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1695
         Index           =   9
         Left            =   90
         TabIndex        =   67
         Top             =   4995
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2990
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1695
         Index           =   1
         Left            =   5250
         TabIndex        =   2
         Top             =   690
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2990
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1635
         Index           =   6
         Left            =   120
         TabIndex        =   3
         Top             =   7080
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2884
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1635
         Index           =   7
         Left            =   5250
         TabIndex        =   4
         Top             =   7065
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2884
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1695
         Index           =   3
         Left            =   5250
         TabIndex        =   6
         Top             =   2700
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2990
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1695
         Index           =   5
         Left            =   5250
         TabIndex        =   48
         Top             =   4995
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2990
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1695
         Index           =   8
         Left            =   90
         TabIndex        =   66
         Top             =   690
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2990
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1695
         Index           =   11
         Left            =   5280
         TabIndex        =   68
         Top             =   4995
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2990
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1695
         Index           =   12
         Left            =   120
         TabIndex        =   69
         Top             =   7065
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2990
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1695
         Index           =   13
         Left            =   5280
         TabIndex        =   70
         Top             =   7065
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2990
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1695
         Index           =   10
         Left            =   90
         TabIndex        =   71
         Top             =   4995
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2990
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1695
         Index           =   0
         Left            =   90
         TabIndex        =   1
         Top             =   690
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2990
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1695
         Index           =   4
         Left            =   90
         TabIndex        =   18
         Top             =   4995
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2990
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSFlexGridLib.MSFlexGrid grd_Result 
         Height          =   1695
         Index           =   2
         Left            =   90
         TabIndex        =   5
         Top             =   2700
         Width           =   4995
         _ExtentX        =   8811
         _ExtentY        =   2990
         _Version        =   393216
         Cols            =   3
         FixedCols       =   0
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
      Begin MSComctlLib.TabStrip tbs_Result 
         Height          =   375
         Index           =   0
         Left            =   90
         TabIndex        =   61
         Tag             =   "tbs_Spec"
         Top             =   300
         Width           =   4665
         _ExtentX        =   8229
         _ExtentY        =   661
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   2
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Specification By User"
               Key             =   "G0"
               Object.Tag             =   "tb_specByUser"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Specification By User Filtered"
               Key             =   "G8"
               Object.Tag             =   "tb_specByUserFilter"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin VB.Label lbl_Title 
         Caption         =   "#Specification By Product Range"
         Height          =   255
         Index           =   3
         Left            =   5250
         TabIndex        =   7
         Tag             =   "lbl_specByRange"
         Top             =   2460
         Width           =   4095
      End
      Begin VB.Label lbl_Title 
         Caption         =   "#Specification By Material"
         Height          =   255
         Index           =   2
         Left            =   90
         TabIndex        =   8
         Tag             =   "lbl_specByMat"
         Top             =   2460
         Width           =   4095
      End
      Begin VB.Image img_Min 
         Height          =   255
         Left            =   10290
         Picture         =   "capdly.ctx":22E0
         Top             =   150
         Visible         =   0   'False
         Width           =   300
      End
      Begin VB.Image img_Max 
         Height          =   270
         Index           =   5
         Left            =   9930
         Picture         =   "capdly.ctx":271E
         Top             =   4725
         Width           =   300
      End
      Begin VB.Image img_Max 
         Height          =   270
         Index           =   7
         Left            =   9930
         Picture         =   "capdly.ctx":2B98
         Top             =   6750
         Width           =   300
      End
      Begin VB.Image img_Max 
         Height          =   270
         Index           =   6
         Left            =   4770
         Picture         =   "capdly.ctx":3012
         Top             =   6750
         Width           =   300
      End
      Begin VB.Image img_Max 
         Height          =   270
         Index           =   4
         Left            =   4770
         Picture         =   "capdly.ctx":348C
         Top             =   4725
         Width           =   300
      End
      Begin VB.Image img_Max 
         Height          =   270
         Index           =   3
         Left            =   9930
         Picture         =   "capdly.ctx":3906
         Top             =   2415
         Width           =   300
      End
      Begin VB.Image img_Max 
         Height          =   270
         Index           =   2
         Left            =   4770
         Picture         =   "capdly.ctx":3D80
         Top             =   2415
         Width           =   300
      End
      Begin VB.Image img_Max 
         Height          =   270
         Index           =   1
         Left            =   9930
         Picture         =   "capdly.ctx":41FA
         Top             =   390
         Width           =   300
      End
      Begin VB.Image img_Max 
         Height          =   270
         Index           =   0
         Left            =   4770
         Picture         =   "capdly.ctx":4674
         Top             =   390
         Width           =   300
      End
      Begin VB.Label lbl_Title 
         Caption         =   "#Seminar Analysis"
         Height          =   255
         Index           =   5
         Left            =   5280
         TabIndex        =   49
         Tag             =   "lbl_seminarAnalysis"
         Top             =   4755
         Width           =   4095
      End
      Begin VB.Label lbl_Title 
         Caption         =   "#Specification By Market"
         Height          =   255
         Index           =   0
         Left            =   120
         TabIndex        =   12
         Tag             =   "lbl_specByMarket"
         Top             =   360
         Width           =   3375
      End
      Begin VB.Label lbl_Title 
         Caption         =   "#Specification By Focus Products"
         Height          =   255
         Index           =   4
         Left            =   120
         TabIndex        =   19
         Tag             =   "lbl_specByFocPrd"
         Top             =   4740
         Width           =   4095
      End
      Begin VB.Label lbl_Title 
         Caption         =   "#Specification By Segmentation"
         Height          =   255
         Index           =   1
         Left            =   5250
         TabIndex        =   11
         Tag             =   "lbl_specBySegm"
         Top             =   360
         Width           =   3375
      End
      Begin VB.Label lbl_Title 
         Caption         =   "#Visit Analysis"
         Height          =   255
         Index           =   6
         Left            =   120
         TabIndex        =   10
         Tag             =   "lbl_visitAnalysis"
         Top             =   6825
         Width           =   3255
      End
      Begin VB.Label lbl_Title 
         Caption         =   "#MSC Analysis"
         Height          =   255
         Index           =   7
         Left            =   5280
         TabIndex        =   9
         Tag             =   "lbl_MSCAnalysis"
         Top             =   6825
         Width           =   3015
      End
      Begin VB.Label L_focus 
         Caption         =   "Focus On "
         Height          =   270
         Left            =   135
         TabIndex        =   20
         Top             =   390
         Width           =   10095
      End
   End
   Begin VB.Frame frm_top10projects 
      Caption         =   "#Top 10 Projects"
      Height          =   8955
      Left            =   7170
      TabIndex        =   100
      Tag             =   "frm_top10projects"
      Top             =   4020
      Visible         =   0   'False
      Width           =   10650
      Begin MSFlexGridLib.MSFlexGrid grd_top10Projects 
         Height          =   5760
         Left            =   180
         TabIndex        =   108
         Top             =   240
         Width           =   10125
         _ExtentX        =   17859
         _ExtentY        =   10160
         _Version        =   393216
         Cols            =   4
         FixedCols       =   3
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
   End
   Begin VB.Frame frm_top10projectsE 
      Caption         =   "#Top 10 Projects Executive"
      Height          =   8955
      Left            =   7635
      TabIndex        =   107
      Tag             =   "frm_top10projectsE"
      Top             =   3345
      Visible         =   0   'False
      Width           =   10650
      Begin MSFlexGridLib.MSFlexGrid grd_top10ProjectsE 
         Height          =   5760
         Left            =   300
         TabIndex        =   109
         Top             =   210
         Width           =   10125
         _ExtentX        =   17859
         _ExtentY        =   10160
         _Version        =   393216
         Cols            =   4
         FixedCols       =   3
         AllowBigSelection=   0   'False
         FocusRect       =   2
         MergeCells      =   1
         AllowUserResizing=   3
      End
   End
   Begin VB.Frame Fra_Processing 
      Height          =   2340
      Left            =   1680
      TabIndex        =   53
      Top             =   5835
      Visible         =   0   'False
      Width           =   4710
      Begin VB.CommandButton btn_Cancel 
         Caption         =   "#Cancel"
         Height          =   495
         Left            =   2040
         TabIndex        =   55
         Tag             =   "btn_Cancel"
         Top             =   3960
         Width           =   1455
      End
      Begin MSComctlLib.ImageList ImageList 
         Left            =   360
         Top             =   3120
         _ExtentX        =   1005
         _ExtentY        =   1005
         BackColor       =   -2147483643
         ImageWidth      =   16
         ImageHeight     =   16
         MaskColor       =   16711935
         _Version        =   393216
      End
      Begin MSComctlLib.ListView lvw_Task 
         Height          =   3135
         Left            =   195
         TabIndex        =   54
         TabStop         =   0   'False
         Top             =   690
         Width           =   5175
         _ExtentX        =   9128
         _ExtentY        =   5530
         View            =   3
         LabelEdit       =   1
         LabelWrap       =   -1  'True
         HideSelection   =   -1  'True
         HideColumnHeaders=   -1  'True
         FullRowSelect   =   -1  'True
         _Version        =   393217
         ForeColor       =   -2147483640
         BackColor       =   -2147483643
         Appearance      =   1
         NumItems        =   1
         BeginProperty ColumnHeader(1) {BDD1F052-858B-11D1-B16A-00C0F0283628} 
            Object.Width           =   8819
         EndProperty
      End
      Begin VB.Label lbl_processing 
         Caption         =   "#Processing ..."
         Height          =   255
         Left            =   240
         TabIndex        =   56
         Tag             =   "lbl_processing"
         Top             =   360
         Width           =   5055
      End
   End
   Begin VB.Frame Fra_DisplayReport 
      Height          =   2250
      Left            =   9420
      TabIndex        =   50
      Top             =   1605
      Visible         =   0   'False
      Width           =   5220
      Begin VB.CommandButton display_report 
         Caption         =   "#Display Report"
         Height          =   615
         Left            =   240
         TabIndex        =   52
         Tag             =   "display_report"
         Top             =   360
         Width           =   1335
      End
      Begin VB.CheckBox chk_GridToRun 
         Caption         =   "#Check1"
         Height          =   255
         Index           =   0
         Left            =   240
         TabIndex        =   51
         Tag             =   "chk_GridToRun"
         Top             =   1560
         Width           =   4905
      End
      Begin VB.Label lbl_selectRequest 
         Caption         =   "#Please select the requests to perform :"
         Height          =   255
         Left            =   240
         TabIndex        =   58
         Tag             =   "lbl_selectRequest"
         Top             =   1200
         Width           =   2775
      End
   End
   Begin VB.Frame fr_Views 
      Caption         =   "#Views"
      Height          =   4380
      Left            =   5295
      TabIndex        =   28
      Tag             =   "fr_Views"
      Top             =   2310
      Visible         =   0   'False
      Width           =   8970
      Begin Project1.ArmCombobox cbo_Views 
         Height          =   315
         Left            =   120
         TabIndex        =   30
         Top             =   240
         Width           =   6735
         _ExtentX        =   0
         _ExtentY        =   609
      End
      Begin VB.CommandButton cmd_FullExport 
         Caption         =   "#Export To Excel (Full)"
         Height          =   495
         Left            =   120
         TabIndex        =   47
         Tag             =   "cmd_FullExport"
         Top             =   600
         Width           =   1215
      End
      Begin Project1.ArmGrid grd_Views 
         Height          =   6945
         Left            =   120
         TabIndex        =   29
         Top             =   1200
         Width           =   14415
         _ExtentX        =   25426
         _ExtentY        =   12250
      End
   End
   Begin VB.Frame fr_Query 
      Caption         =   "#Advanced Queries"
      Height          =   6450
      Left            =   4275
      TabIndex        =   32
      Tag             =   "fr_Query"
      Top             =   1230
      Visible         =   0   'False
      Width           =   9510
      Begin Project1.ArmGrid grd_Query 
         Height          =   8100
         Left            =   120
         TabIndex        =   43
         Top             =   1605
         Width           =   10455
         _ExtentX        =   18441
         _ExtentY        =   14288
      End
      Begin Project1.ArmCombobox cbo_Query 
         Height          =   345
         Left            =   1200
         TabIndex        =   44
         Top             =   240
         Width           =   3375
         _ExtentX        =   5953
         _ExtentY        =   609
      End
      Begin VB.Label lbl_Explanation 
         Height          =   855
         Left            =   105
         TabIndex        =   46
         Top             =   675
         Width           =   10455
      End
      Begin VB.Label lbl_Query 
         Caption         =   "#Query"
         Height          =   255
         Left            =   120
         TabIndex        =   45
         Tag             =   "lbl_Query"
         Top             =   360
         Width           =   1065
      End
   End
   Begin VB.Frame fr_CMD 
      Height          =   990
      Left            =   120
      TabIndex        =   33
      Top             =   0
      Visible         =   0   'False
      Width           =   14640
      Begin VB.CommandButton btn_FocusProd 
         Caption         =   "#Focus Prod."
         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            =   13185
         TabIndex        =   60
         Tag             =   "btn_FocusProd"
         Top             =   555
         Width           =   1365
      End
      Begin VB.CommandButton cmdQuit 
         Caption         =   "#Quit"
         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            =   13185
         TabIndex        =   34
         Tag             =   "cmdQuit"
         Top             =   210
         Width           =   1365
      End
      Begin MSComctlLib.TabStrip TabStrip1 
         Height          =   750
         Left            =   120
         TabIndex        =   35
         Tag             =   "TabStrip1"
         Top             =   195
         Width           =   12930
         _ExtentX        =   22807
         _ExtentY        =   1323
         MultiRow        =   -1  'True
         Style           =   1
         TabFixedWidth   =   2170
         TabFixedHeight  =   794
         TabMinWidth     =   2646
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   13
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Specifications Analysis"
               Key             =   "REPORT"
               Object.Tag             =   "tb_report"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Views"
               Key             =   "VIEWS"
               Object.Tag             =   "tb_view"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Replication"
               Key             =   "REPLIC"
               Object.Tag             =   "tb_replication"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab4 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Queries"
               Key             =   "QUERY"
               Object.Tag             =   "tb_query"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab5 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Visits"
               Key             =   "VISIT"
               Object.Tag             =   "tb_visit"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab6 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Visits (summary)"
               Key             =   "VISIT2"
               Object.Tag             =   "tb_visit2"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab7 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Projects"
               Key             =   "PROJ"
               Object.Tag             =   "tb_project"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab8 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Sales"
               Key             =   "SALES"
               Object.Tag             =   "tb_sales"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab9 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Sales by rep"
               Key             =   "SALES_REP"
               Object.Tag             =   "tb_sales_rep"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab10 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Top 10 Prj."
               Key             =   "TOP10PROJ"
               Object.Tag             =   "tb_top10project"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab11 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Top 10 Prj. Exec"
               Key             =   "TOP10PROJE"
               Object.Tag             =   "tb_top10projectE"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab12 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Status 2"
               Key             =   "STATUSPROJ2"
               Object.Tag             =   "tb_statusProject2"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab13 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Status 3"
               Key             =   "STATUSPROJ3"
               Object.Tag             =   "tb_statusProject3"
               ImageVarType    =   2
            EndProperty
         EndProperty
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
      End
   End
   Begin VB.Frame fr_Filter 
      Height          =   8790
      Left            =   105
      TabIndex        =   13
      Top             =   1035
      Visible         =   0   'False
      Width           =   3900
      Begin VB.Frame frm_sales2Options 
         BorderStyle     =   0  'None
         Height          =   1155
         Left            =   135
         TabIndex        =   147
         Tag             =   "frm_sales2Options"
         Top             =   1080
         Visible         =   0   'False
         Width           =   3720
         Begin Project1.ArmCombobox cbo_salesCurrency 
            Height          =   345
            Left            =   1275
            TabIndex        =   148
            Top             =   425
            Width           =   2370
            _ExtentX        =   4180
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_salesDataView 
            Height          =   345
            Left            =   1275
            TabIndex        =   151
            Top             =   60
            Width           =   2370
            _ExtentX        =   4180
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_salesYear 
            Height          =   345
            Left            =   1275
            TabIndex        =   153
            Top             =   790
            Width           =   2370
            _ExtentX        =   4180
            _ExtentY        =   609
         End
         Begin VB.Label lbl_salesYear 
            Caption         =   "#Year"
            Height          =   285
            Left            =   30
            TabIndex        =   152
            Tag             =   "lbl_year"
            Top             =   875
            Width           =   1200
         End
         Begin VB.Label lbl_salesDataView 
            Caption         =   "#Data view"
            Height          =   285
            Left            =   30
            TabIndex        =   150
            Tag             =   "lbl_salesDataView"
            Top             =   90
            Width           =   1200
         End
         Begin VB.Label lbl_salesCurr 
            Caption         =   "#Currency"
            Height          =   285
            Left            =   30
            TabIndex        =   149
            Tag             =   "lbl_salesCurr"
            Top             =   495
            Width           =   1200
         End
      End
      Begin VB.Frame frm_salesOptions 
         BorderStyle     =   0  'None
         Height          =   1155
         Left            =   120
         TabIndex        =   124
         Tag             =   "frm_salesOptions"
         Top             =   1215
         Visible         =   0   'False
         Width           =   3720
         Begin VB.CheckBox chk_sales_clgMetal 
            Caption         =   "#Ceilings Metal split"
            Height          =   210
            Left            =   90
            TabIndex        =   143
            Tag             =   "chk_sales_clgMetal"
            Top             =   915
            Width           =   3450
         End
         Begin VB.CommandButton sales_pdf_print 
            Caption         =   "#Export PDF"
            Height          =   495
            Left            =   2760
            TabIndex        =   128
            Tag             =   "sales_pdf_print"
            Top             =   0
            Width           =   855
         End
         Begin VB.OptionButton opt_salesOptions 
            Caption         =   "#All sales"
            Height          =   195
            Index           =   0
            Left            =   90
            TabIndex        =   127
            Tag             =   "opt_salesOptionsAll"
            Top             =   90
            Value           =   -1  'True
            Width           =   2595
         End
         Begin VB.OptionButton opt_salesOptions 
            Caption         =   "#AS Sales Only"
            Height          =   195
            Index           =   1
            Left            =   90
            TabIndex        =   126
            Tag             =   "opt_salesOptionsAS"
            Top             =   345
            Width           =   2595
         End
         Begin VB.OptionButton opt_salesOptions 
            Caption         =   "#Non AS Sales Only"
            Height          =   195
            Index           =   2
            Left            =   90
            TabIndex        =   125
            Tag             =   "opt_salesOptionsNonAS"
            Top             =   630
            Width           =   2595
         End
      End
      Begin VB.OptionButton opt_excReps 
         Caption         =   "#Active Reps"
         Height          =   330
         Index           =   1
         Left            =   120
         Style           =   1  'Graphical
         TabIndex        =   83
         Tag             =   "opt_excReps"
         Top             =   2430
         Width           =   1800
      End
      Begin VB.OptionButton opt_excReps 
         Caption         =   "#All Reps"
         Height          =   330
         Index           =   0
         Left            =   1920
         Style           =   1  'Graphical
         TabIndex        =   82
         Tag             =   "opt_allReps"
         Top             =   2430
         Width           =   1815
      End
      Begin VB.CommandButton btn_RefreshReport 
         Caption         =   "#Refresh"
         Height          =   495
         Left            =   2880
         TabIndex        =   59
         Tag             =   "btn_RefreshReport"
         Top             =   1320
         Visible         =   0   'False
         Width           =   855
      End
      Begin VB.CommandButton btn_DiplayQuery 
         Caption         =   "#Display Report"
         Height          =   495
         Left            =   2880
         TabIndex        =   57
         Tag             =   "btn_DiplayQuery"
         Top             =   210
         Visible         =   0   'False
         Width           =   855
      End
      Begin Project1.A_calocx cal1 
         Height          =   375
         Left            =   735
         TabIndex        =   22
         Top             =   240
         Width           =   1815
         _ExtentX        =   3201
         _ExtentY        =   661
      End
      Begin Project1.A_calocx cal2 
         Height          =   375
         Left            =   735
         TabIndex        =   23
         Top             =   600
         Width           =   1815
         _ExtentX        =   3201
         _ExtentY        =   661
      End
      Begin VB.Frame fr_Budget 
         BorderStyle     =   0  'None
         Height          =   1215
         Left            =   120
         TabIndex        =   36
         Top             =   1185
         Width           =   3615
         Begin VB.CheckBox chk_YTD 
            Caption         =   "#YTD"
            Height          =   255
            Left            =   2760
            TabIndex        =   37
            Tag             =   "chk_YTD"
            Top             =   825
            Width           =   855
         End
         Begin Project1.ArmCombobox annee 
            Height          =   345
            Left            =   840
            TabIndex        =   38
            Top             =   345
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox Mois 
            Height          =   345
            Left            =   840
            TabIndex        =   39
            Top             =   705
            Width           =   1815
            _ExtentX        =   3201
            _ExtentY        =   609
         End
         Begin VB.Label lbl_budgetToUse 
            Caption         =   "#Budget to use:"
            Height          =   255
            Left            =   45
            TabIndex        =   42
            Tag             =   "lbl_budgetToUse"
            Top             =   -15
            Width           =   1215
         End
         Begin VB.Label lbl_month 
            Caption         =   "#Month / Quarter"
            Height          =   495
            Left            =   120
            TabIndex        =   41
            Tag             =   "lbl_month"
            Top             =   705
            Width           =   690
         End
         Begin VB.Label lbl_year 
            Caption         =   "#Year"
            Height          =   255
            Left            =   120
            TabIndex        =   40
            Tag             =   "lbl_year"
            Top             =   465
            Width           =   690
         End
      End
      Begin Project1.ArmCombobox cb_trw 
         Height          =   345
         Left            =   120
         TabIndex        =   31
         Top             =   2775
         Width           =   3615
         _ExtentX        =   6376
         _ExtentY        =   609
      End
      Begin VB.CommandButton export_report 
         Caption         =   "#Export Report"
         Height          =   495
         Left            =   2880
         TabIndex        =   21
         Tag             =   "export_report"
         Top             =   690
         Visible         =   0   'False
         Width           =   855
      End
      Begin MSComctlLib.TabStrip tab_prd 
         Height          =   735
         Left            =   105
         TabIndex        =   14
         Tag             =   "tab_prd"
         Top             =   7980
         Width           =   3510
         _ExtentX        =   6191
         _ExtentY        =   1296
         TabWidthStyle   =   2
         MultiRow        =   -1  'True
         Style           =   1
         TabFixedWidth   =   1976
         Placement       =   1
         TabMinWidth     =   529
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   5
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Mineral"
               Object.Tag             =   "tbs_mineral"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Soft"
               Object.Tag             =   "tb_soft"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Metal"
               Object.Tag             =   "tb_metal"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab4 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Ceilings"
               Object.Tag             =   "tb_ceilings"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab5 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Grids"
               Object.Tag             =   "tb_grids"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin Project1.ArmTreeView tv1 
         Height          =   4830
         Left            =   120
         TabIndex        =   15
         Top             =   3150
         Width           =   3615
         _ExtentX        =   6376
         _ExtentY        =   8520
      End
      Begin VB.Label l2 
         Caption         =   "#TO"
         Height          =   255
         Left            =   120
         TabIndex        =   17
         Tag             =   "l2"
         Top             =   720
         Width           =   615
      End
      Begin VB.Label l1 
         Caption         =   "#FROM"
         Height          =   255
         Left            =   120
         TabIndex        =   16
         Tag             =   "l1"
         Top             =   360
         Width           =   615
      End
   End
   Begin VB.Frame Fr_replic 
      Caption         =   "#Replication Follow up"
      Height          =   7215
      Left            =   5055
      TabIndex        =   24
      Tag             =   "Fr_replic"
      Top             =   1425
      Visible         =   0   'False
      Width           =   5655
      Begin Project1.ArmTreeView tv_replic 
         Height          =   7395
         Left            =   120
         TabIndex        =   26
         Top             =   840
         Width           =   3615
         _ExtentX        =   6376
         _ExtentY        =   13044
      End
      Begin MSComctlLib.TabStrip Tab_replic 
         Height          =   615
         Left            =   240
         TabIndex        =   25
         Tag             =   "Tab_replic"
         Top             =   240
         Width           =   3375
         _ExtentX        =   5953
         _ExtentY        =   1085
         MultiRow        =   -1  'True
         Style           =   2
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   3
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Per Week"
               Object.Tag             =   "PER_WEEK"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Per Month"
               Object.Tag             =   "PER_MONTH"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Per user"
               Object.Tag             =   "PER_USER"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin Project1.ArmGrid gr_replic 
         Height          =   8025
         Left            =   3840
         TabIndex        =   27
         Top             =   240
         Width           =   10695
         _ExtentX        =   18865
         _ExtentY        =   14155
      End
   End
End
Attribute VB_Name = "capdly"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

'what is new
'2.6.4 : Days since last update, AMC Project number (JN)
'2.6.4 bugfix: LockScreen(True) when not authorized in 'Top 10 projects', 'Top 10 projects Executive' and other Project reports (JN)
'2.6.4 bugfix: reset global ml_proj2Counts cursor for projects when date has changed (JN)
'2.6.4 bugfix: Export excell to include backgroud color of a grid cell (JN)
'2.6.6 Projects by status #3 - short version of Projects by status (during period) (JN)
'2.6.6 Speedup of export to excell for export of projects by status #2 (JN)
'2.6.7 New report: Visits (summary) (JN)
'2.6.7 Minor bugs in previous reports (JN)
'2.7.0 Non SAP sales into sales reporting (JN)
'2.7.0 All/AS/AS sales filtering option (JN)
'2.7.0 PDF print with grouping Market/Country into sales tab (JN)
'2.7.0 Exprt to excell for Sales optimization
'2.7.1 New sales by rep report (JN)
'2.7.1 New treeview type - customer level (JN)
'2.7.1 Sales report detail screen (JN)
'2.7.3 Updated rights on customer level to include owned customers
'2.7.7 Added FetchAll support for Queries part (JN)
'2.7.7 Added Grouping for Sales by rep reports (JN)
'2.8.7 Added FetchAll support for Views part (JN)




Private Declare Function LockWindowUpdate Lib "user32" (ByVal hWnd As Long) As Long

Private Const COLOR_RED As Long = &HFF
Private Const COLOR_GREEN  As Long = 43520 '&HAA00
Private Const COLOR_BLUE  As Long = &HFF0000
Private Const COLOR_GREY As Long = &HDDDDDD
Private Const COLOR_GREY2 As Long = &HAAAAAA
Private Const COLOR_GREY3 As Long = &HEEEEEE

' **************************************************************************************************
' **************************************** 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
    ErrMsgMandatoryAreEmpty = SIFYB_CM_ERROR_MESSAGE + 1
End Enum

Dim mia_WhichGridIsMax(2)           As Integer 'mia_WhichGridIsMax(index of the grid, top of the grid,left of the grid)

Dim mb_DisplayVisits                As Boolean
Dim mb_DisplayMSC                   As Boolean
Dim mb_DisplayFilterByUser          As Boolean
Dim mb_reportProcessed              As Boolean
Dim ml_visit_processed              As Long
Dim mb_visits2_processed            As Boolean
Dim ml_project_processed            As Long
Dim ml_top10project_processed       As Long
Dim ml_top10projectE_processed      As Long
Dim mb_sales_processed              As Boolean
Dim mb_sales_MSA_processed          As Boolean
Dim mb_sales_rep_processed          As Boolean
Dim mb_statusProjects_processed     As Boolean
Dim mb_statusProjects2_processed    As Boolean
Dim mb_statusProjects3_processed    As Boolean

Private WithEvents mo_projDetFrm As capdly_projDet
Attribute mo_projDetFrm.VB_VarHelpID = -1
Private WithEvents mo_salesDetFrm As capdly_salesDet
Attribute mo_salesDetFrm.VB_VarHelpID = -1

Private mc_ScreenLabels             As Long         'cursor containing screen constants for current component
Private ml_projCounts               As Long         ' cursor containing project count per market/county for project stats
Private ml_proj3Counts              As Long         ' cursor containing project count per market/county for project3 stats

Dim mb_Cancel                       As Boolean

Dim ms_ToLog                        As String

Private Const SCREEN_NAME       As String = "Capture_Reporting"
Private Const C_APPNAME         As String = "CAP_REPORTING" ' for error log

Private WithEvents mFocusProd As FocusProducts
Attribute mFocusProd.VB_VarHelpID = -1


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

Private mTreeViewInfos() As TTreeViewInfo



Private Type GRD_ColumnInfo
    Index As Long
    Name As String
    Format As String
    DB_Name As String
End Type

Private Type GRD_Info
    gTitle As String
    Cols() As GRD_ColumnInfo
End Type


Dim mo_StatusProjectsInfo As GRD_Info               ' info for grd_StatusProjects
Dim mo_StatusProjects2Info As GRD_Info              ' info for grd_StatusProjects2
Dim mo_StatusProjects3Info As GRD_Info              ' info for grd_StatusProjects3
Dim mo_top10ProjectsInfo As GRD_Info                ' info for grd_top10ProjectsInfo
Dim mo_top10ProjectsEInfo As GRD_Info               ' info for grd_top10ProjectsInfoE
Dim mo_projectInfo(7) As GRD_Info                   ' info for grd_project
Dim mo_Visits2Info As GRD_Info                      ' info for grd_Visits2
Dim mo_SalesRepInfo As GRD_Info                     ' info for grd_sales_rep



Dim ms_TheGridRequestsByLevel() As String

' USE VAL BECAUSE OF NUMERIC SEPARATOR

Dim p_da                            As Object
Dim p_DACurs                        As Long

Private Const SEP1 As String = "®"
Private Const SEP2 As String = "©"
Private Const SEP = "®©"
Private Const CH_LDELIMIT = "®©"
Private Const C_SEP As String = "@@"

Private Const G_expand_factor_h     As Integer = 5400
Private Const G_expand_factor_v     As Integer = 6400
'Dim max_lignes                      As Integer
Dim tab_selected                    As Byte
Dim Level_selected                  As Byte
Dim annee_selected                  As String 'annee_ComboItemSelected
Dim mois_selected                   As String 'mois_ComboItemSelected
Dim a_ExcelSheet1                   As Object  'export_to_excel 'Export_Grid
Dim current_displayed_node          As String
Dim current_cal1                    As String
Dim current_cal2                    As String

Dim a_ExcelApp                      As Object 'export_to_excel
Dim a_ExcelWorkBook                 As Object 'export_to_excel
Private Const xlright               As Integer = -4152 'export_to_excel
Private Const nb_row_header         As Integer = 5 'export_to_excel
Private Const nb_row_intermediate   As Integer = 2 'export_to_excel
'Private Const xlnone                As Integer = -4142
Private Const xlContinuous          As Integer = 1 'Export_Grid
Private Const xlThin                As Integer = 2 'Export_Grid
Private Const xlMedium              As Integer = -4138 'Export_Grid
Private Const xlThick               As Integer = 4 'Export_Grid
'Private Const xlAutomatic           As Integer = -4105
Private Const xlInsideVertical      As Integer = 11 'Export_Grid
Private Const xlInsideHorizontal    As Integer = 12 'Export_Grid
Private Const xlEdgeLeft            As Integer = 7 'Export_Grid
Private Const xlEdgeTop             As Integer = 8 'Export_Grid
Private Const xlEdgeBottom          As Integer = 9 'Export_Grid
Private Const xlEdgeright           As Integer = 10
'Private Const xlDiagonalDown        As Integer = 5
'Private Const xlDiagonalup          As Integer = 6


Const C_PS_C_TOTAL_COL    As Long = 4
Const C_PS_C_STATU_COL    As Long = 5
Const C_PS_C_SUM_COL    As Long = 11
Const C_PS_U_TOTAL_COL    As Long = 17
Const C_PS_U_STATU_COL    As Long = 12
Const C_PS_U_NOTACTIVE_COL As Long = 18
Const C_PS_U_SUM_COL As Long = 17

' Projects by status ( during period )
Const C_PS2_C_STATU_COL         As Long = 6
Const C_PS2_C_SUM_COL           As Long = 14
Const C_PS2_C_EARLY_PER_COL     As Long = 15
Const C_PS2_U_TOTAL_COL         As Long = 24
Const C_PS2_U_STATU_COL         As Long = 16
Const C_PS2_U_SUM_COL           As Long = 24
Const C_PS2_U_TOTAL_UNIQUE_COL  As Long = 25
Const C_PS2_U_TOTAL_PER_COL     As Long = 26
Const C_PS2_U_WON_SPEC_PER_COL  As Long = 27
Const C_PS2_U_WON_ORDER_PER_COL As Long = 28
Const C_PS2_U_TOTALACTIVE_COL   As Long = 29
Const C_PS2_U_ORDERDPRIOR_COL   As Long = 30

' Projects by status short list
Const C_PS3_C_STATU_COL         As Long = 4
Const C_PS3_C_TOTAL_COL         As Long = 5
Const C_PS3_C_PER_REP_COL       As Long = 6
Const C_PS3_C_EARLY_PER_COL     As Long = 7
Const C_PS3_U_STATU_COL         As Long = 8
Const C_PS3_U_TOTAL_UNIQUE_COL  As Long = 9
Const C_PS3_U_TOTAL_PER_COL     As Long = 10
Const C_PS3_U_WON_ORDER_PER_COL As Long = 11
Const C_PS3_U_TOTALACTIVE_COL   As Long = 12

' visits summary
Const C_VISITS2_TOTAL_COL     As Long = 6
Const C_VISITS2_VERYIMPOR_COL As Long = 7
Const C_VISITS2_IMPORTANT_COL As Long = 8
Const C_VISITS2_TOTAL_PER_COL As Long = 9



' IMPLEMENT T298.9
Private Const C_COMMENT_L2 As String = "Measures are based on all 'Complete' Visits." & C_SEP & _
                                        "Please note: 'Visits' = Appointments, Cold Calls, Seminars, Presentations and Complaint Visit" & C_SEP & _
                                        "80/20 = (Number of Visits to Specifiers + Number of Visits to Part-Specifiers)/(Total Number of Visits)" & C_SEP & _
                                        "Please note: 'Clg Contractors' = Ceiling Contractors, Builders, Main Contractors, Services Contractors, Shop Fitting Companies, and Drylining Contractor"

Private Const C_COMMENT_R2 As String = "Measures are based on members of MSC - please make sure the correct people are registered as members of MSC" & C_SEP & _
                                       "Please note: 'Visits' = Appointments, Cold Calls, Seminars, Presentations and Complaint Visit" & C_SEP & _
                                       "80/20 = (Number of Visits to Specifiers + Number of Visits to Part-Specifiers)/(Total Number of Visits)" & C_SEP & _
                                       "Please note: 'Clg Contractors' = Ceiling Contractors, Builders, Main Contractors, Services Contractors, Shop Fitting Companies, and Drylining Contractor"
' END T298.9

'Dim m_ConnectString                As String
Dim gsuser                          As String
Dim ml_U_Code                       As Long
Dim ms_Language_Code                As String       'current user interface language

'Dim use_framework_connection       As Integer
'Dim p_Connected                    As Boolean
Dim old_cal1                        As String
Dim old_cal2                        As String
Dim ml_psCounryColWidth             As Long
Dim ml_psRowHeight                  As Long
Dim ml_visits2CounryColWidth        As Long
Dim ml_visits2SalesRepColWidth      As Long
Dim ml_visits2RowHeight             As Long
Dim ml_ps2CounryColWidth            As Long
Dim ml_ps3CounryColWidth            As Long
Dim ml_ps2SalesRepColWidth          As Long
Dim ml_ps2RowHeight                 As Long
Dim ml_ps3RowHeight                 As Long
Dim ml_ActivePrj                    As Long
Dim ml_VISIT_X1                     As Long
Dim ml_TOP10DAYS_OK                 As Long

Private mFPIndBdg As Boolean


Public Event reportquit()

Private mb_Initialized As Boolean
Private mb_Initializing As Boolean

Private Enum ECapReportingTreeview
    creMarket = 1
    creArea = 2
    creMarketRep = 3
    creAreaRep = 4
    creMarketCust = 5
End Enum

Private Declare Function GetComputerName Lib "Kernel32" _
        Alias "GetComputerNameA" (ByVal lpBuffer As String, _
        nSize As Long) As Long

Private Function ComputerName() As String
On Error GoTo ErrorHandler

    Dim lsBuffer As String
    Dim llReturn As Long
    Dim lsName As String
    
    ComputerName = ""
    
    lsName = ""
    lsBuffer = SPACE$(255)
    llReturn = GetComputerName(lsBuffer, 255)
    
    If llReturn Then
          lsName = Left$(lsBuffer, InStr(lsBuffer, Chr(0)) - 1)
    End If
    
    ComputerName = lsName
    Exit Function
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".ComputerName")
End Function


'add task message and icon into task list
Private Sub lvw_Task_AddItem(ai_GridIndex As Integer, as_Text As String)
On Error GoTo ErrorHandler

    Dim lo_ListItem As ListItem

    Set lo_ListItem = lvw_Task.ListItems.Add
    lo_ListItem.Text = as_Text
    lo_ListItem.SmallIcon = 0
    lo_ListItem.Tag = ai_GridIndex
    Set lo_ListItem = Nothing
    
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".lvw_Task_AddItem")
End Sub

Private Sub lvw_Task_Initialize()
On Error GoTo ErrorHandler

    Dim li_i As Integer

    Call ImageList.ListImages.Add(, , LoadResPicture(129, vbResIcon))
    Call ImageList.ListImages.Add(, , LoadResPicture(116, vbResBitmap))
    Set lvw_Task.SmallIcons = ImageList
    lvw_Task.ListItems.Clear
    For li_i = 0 To chk_GridToRun.Count - 1
        If chk_GridToRun(li_i).Value = 1 And chk_GridToRun(li_i).Enabled = True Then
            Call lvw_Task_AddItem(li_i, chk_GridToRun(li_i).Caption)
            grd_result(li_i).Enabled = True
            lbl_Title(li_i).Enabled = True
            img_Max(li_i).Visible = True
            If IsControlLoaded(tbs_Result, li_i) Then
              tbs_Result(li_i).Visible = mb_DisplayFilterByUser
            End If
        Else
            grd_result(li_i).Enabled = False
            lbl_Title(li_i).Enabled = False
            img_Max(li_i).Visible = False
            If IsControlLoaded(tbs_Result, li_i) Then
              tbs_Result(li_i).Visible = False
            End If
        End If
    Next li_i
    
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".lvw_Task_Initialize")
End Sub

Public Property Let Visible(ByVal aVisible As Boolean)
    UserControl.Extender.Visible = aVisible
End Property
Public Property Get Visible() As Boolean
    Visible = UserControl.Extender.Visible
End Property

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

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

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

Public Property Let Width(ByVal aWidth As Single)
    UserControl.Extender.Width = aWidth
End Property
Public Property Get Width() As Single
    Width = UserControl.Extender.Width
End Property

Public Sub Move(ByVal aLeft As Single, ByVal aTop As Single, ByVal aWidth As Single, ByVal aHeight As Single)
    Call UserControl.Extender.Move(aLeft, aTop, aWidth, aHeight)
End Sub

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

Private Function CountStrings(ByVal chaine_a_chercher As String, ByVal chaine_chercher As String) As Integer
On Error GoTo ErrorHandler

    Dim Position, cpt As Integer
    Position = 1
    Do While InStr(Position, chaine_a_chercher, chaine_chercher)
        Position = InStr(Position, chaine_a_chercher, chaine_chercher) + 1
        cpt = cpt + 1
    Loop
    CountStrings = cpt

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

'Property Get ConnectString() As String
'    ConnectString = m_ConnectString
'End Property

Property Let capdly_user(AString As String)
On Error GoTo ErrorHandler
    gsuser = AString
    Exit Property
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".Property Set capdly_user")
    ' terminate app
    End
End Property

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

Property Let Language_Code(AString As String)
    ms_Language_Code = AString
End Property

Public Property Set ArmDb(ByRef local_connection As Object)
On Error GoTo ErrorHandler
    If Not (local_connection Is Nothing) Then
        Set p_da = local_connection
    End If
    Exit Property
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".Property Set ArmDb")
    ' terminate app
    End
End Property

Public Function Load_A_Com() As Boolean
Dim curs As Long
On Error GoTo ErrorHandler
    Load_A_Com = False
    curs = p_da.ExecuteSQL("cap_f_replicsequence_upd5")
    If Not (curs) Then
        MsgBox "Error in updating wk"
        Exit Function
    End If
    Call p_da.Close(curs)
    curs = 0
    
    cal1.Language = ms_Language_Code
    cal2.Language = ms_Language_Code
    
    ml_psCounryColWidth = 0
    ml_psRowHeight = 0
    ml_visits2SalesRepColWidth = 0
    ml_visits2CounryColWidth = 0
    ml_ps2CounryColWidth = 0
    ml_ps2RowHeight = 0
    ml_visits2RowHeight = 0
    ml_ps3CounryColWidth = 0
    ml_ps3RowHeight = 0
    
    ml_ps3CounryColWidth = 0
    
    gr_replic.Load_A_Com
    gr_replic.MaxRows = 10000
    Set gr_replic.ArmDb = p_da
    gr_replic.FetchAll = True
    gr_replic.Title = ""
    Set grd_Views.ArmDb = p_da
    grd_Views.Load_A_Com
    Set cbo_Views.ArmDb = p_da
    cbo_Views.Load_A_Com
    annee.FirstBlankItem = True
    Call annee.Load_A_Com
    Call Mois.Load_A_Com
    Call cbo_DR_Month.Load_A_Com
    Call cbo_DR_Year.Load_A_Com
    mia_WhichGridIsMax(0) = -1
    
    mb_Initializing = False

    mb_Initialized = True
    Load_A_Com = True
    Exit Function
    
ErrorHandler:
    If curs > 0 Then
        Call p_da.Close(curs)
        curs = 0
    End If
    Call LogMessage(App.ProductName & " exception raised. Err.Number:" & Err.Number & ", Err.Source:Load_A_Com" & SEP1 & Err.Source & ", Err.Description " & Err.Description & ".", "E", False)
End Function

Public Function Init_control()
Const C_CONFIG_REQ As String = "select  (select top 1 ID_Value From cap_f_replic_cfg where id_info = 'FPBDG' ) as ID_Value, " & _
        "(select top 1 cfg_value from a_config where cfg_key = 'RPT_PRJ_ACTIVE') as PRJ_ACTIVE, " & _
        "(select top 1 cfg_value from a_config where cfg_key = 'RPT_IT_USERS' ) as IT_USERS, " & _
        "(select top 1 cfg_value from a_config where CFG_Key='RPT_VISIT_X1' ) as VISIT_X1, " & _
        "(select top 1 cfg_value from a_config where cfg_key = 'RPT_PRJ_TOP10_DAYS_OK' ) as TOP10DAYS_OK"

Dim i As Integer
Dim res As String
On Error GoTo ErrorHandler

    mb_Initializing = True
    
    Set mFocusProd = Nothing


    mb_DisplayVisits = True
    mb_DisplayMSC = True
    mb_DisplayFilterByUser = False
    mb_reportProcessed = False
    ml_visit_processed = 0
    mb_visits2_processed = False
    mb_sales_processed = False
    mb_sales_rep_processed = False
    mb_sales_MSA_processed = False
    ml_project_processed = 0
    ml_top10project_processed = 0
    ml_top10projectE_processed = 0
    mb_statusProjects_processed = False
    mb_statusProjects2_processed = False
    mb_statusProjects3_processed = False
    

    fr_CMD.Visible = False
    fr_Filter.Visible = False
    fr_report.Visible = False
    Fr_replic.Visible = False
    fr_Views.Visible = False
    fr_Query.Visible = False
    frm_visits.Visible = False
    frm_projects.Visible = False
    frm_top10projects.Visible = False
    frm_top10projectsE.Visible = False
    frm_sales.Visible = False
    frm_sales_rep.Visible = False
    frm_statusProjects.Visible = False
    frm_statusProjects2.Visible = False
    frm_statusProjects3.Visible = False
    
    Fra_DisplayReport.Visible = False
    Fra_Processing.Visible = False
    
    L_focus.Visible = False
    
    Call fr_CMD.Move(120, 0, 14640, 990)
    Call fr_Filter.Move(120, 1035, 3900, 8790)
    Call fr_report.Move(4120, fr_Filter.Top, fr_CMD.Width - 4000, fr_Filter.Height)
    Call Fr_replic.Move(120, fr_Filter.Top, fr_CMD.Width, fr_Filter.Height)
    Call fr_Views.Move(120, fr_Filter.Top, fr_CMD.Width, fr_Filter.Height)
    Call fr_Query.Move(fr_report.Left, fr_report.Top, fr_report.Width, fr_report.Height)
    Call frm_visits.Move(fr_report.Left, fr_report.Top, fr_report.Width, fr_report.Height)
    Call frm_projects.Move(fr_report.Left, fr_report.Top, fr_report.Width, fr_report.Height)
    Call frm_top10projects.Move(fr_report.Left, fr_report.Top, fr_report.Width, fr_report.Height)
    Call frm_top10projectsE.Move(fr_report.Left, fr_report.Top, fr_report.Width, fr_report.Height)
    Call frm_sales.Move(fr_report.Left, fr_report.Top, fr_report.Width, fr_report.Height)
    Call frm_sales_rep.Move(fr_report.Left, fr_report.Top, fr_report.Width, fr_report.Height)
    Call frm_statusProjects.Move(fr_report.Left, fr_report.Top, fr_report.Width, fr_report.Height)
    Call frm_statusProjects2.Move(fr_report.Left, fr_report.Top, fr_report.Width, fr_report.Height)
    Call frm_visits2.Move(fr_report.Left, fr_report.Top, fr_report.Width, fr_report.Height)
    Call frm_statusProjects3.Move(fr_report.Left, fr_report.Top, fr_report.Width, fr_report.Height)
    Call Fra_DisplayReport.Move(fr_report.Left, fr_report.Top, fr_report.Width, fr_report.Height)
    Call Fra_Processing.Move(6800, 3500, 5655, 4695)
    
    Call frm_sales2Options.Move(frm_salesOptions.Left, frm_salesOptions.Top)
    
    gr_replic.Height = Fr_replic.Height - gr_replic.Top - 120
    tv_replic.Height = Fr_replic.Height - tv_replic.Top - 120
    grd_Query.Height = fr_Query.Height - grd_Query.Top - 120
    grd_Views.Height = fr_Views.Height - grd_Views.Top - 120
    grd_Sales.Height = frm_sales.Height - grd_Sales.Top - 520 '- tbs_sales.Height
    grd_sales_rep.Height = frm_sales_rep.Height - grd_sales_rep.Top - 120
    grd_Sales.Width = frm_sales.Width - grd_Sales.Left - 120
    grd_sales_MSA.Width = grd_Sales.Width
    grd_sales_MSA.Top = grd_Sales.Top
    grd_sales_MSA.Left = grd_Sales.Left
    grd_sales_MSA.Height = grd_Sales.Height
    grd_sales_rep.Width = frm_sales_rep.Width - grd_sales_rep.Left - 120
    
    
    
    tbs_sales.Left = grd_Sales.Left
    tbs_sales.Top = grd_Sales.Top + grd_Sales.Height
    tbs_sales.Width = grd_Sales.Width

    
    grd_StatusProjects.Left = 105
    grd_StatusProjects.Top = 270
    grd_StatusProjects.Height = frm_statusProjects.Height - grd_StatusProjects.Top - 120
    grd_StatusProjects.Width = frm_statusProjects.Width - grd_StatusProjects.Left - 120
    
    grd_StatusProjects2.Left = 105
    grd_StatusProjects2.Top = 270
    grd_StatusProjects2.Height = frm_statusProjects2.Height - grd_StatusProjects2.Top - 120
    grd_StatusProjects2.Width = frm_statusProjects2.Width - grd_StatusProjects2.Left - 120
    
    grd_StatusProjects3.Left = 105
    grd_StatusProjects3.Top = 270
    grd_StatusProjects3.Height = frm_statusProjects3.Height - grd_StatusProjects3.Top - 120
    grd_StatusProjects3.Width = frm_statusProjects3.Width - grd_StatusProjects3.Left - 120
        
    grd_visits2.Left = 105
    grd_visits2.Top = 270
    grd_visits2.Height = frm_visits2.Height - grd_visits2.Top - 120
    grd_visits2.Width = frm_visits2.Width - grd_visits2.Left - 120
    
    Call grd_top10Projects.Move(60, 240, frm_top10projects.Width - 120, frm_top10projects.Height - 320)
    Call grd_top10ProjectsE.Move(60, 240, frm_top10projectsE.Width - 120, frm_top10projectsE.Height - 320)
    
    

    cal1.Language = ms_Language_Code
    cal1.date_courte = "01/01/" & Year(Now)
    cal2.Language = ms_Language_Code
    cal2.date_courte = Format(Now, "dd/mm/yyyy")
    
    tv1.Load_A_Com
    tv_replic.Load_A_Com
    tv1.AllowCheckboxes = False
    tv_replic.AllowCheckboxes = False
        
    mia_WhichGridIsMax(0) = -1
    

    ' filter for sales by rep part
    Set cbo_salesCurrency.ArmDb = p_da
    Set cbo_salesDataView.ArmDb = p_da
    Set cbo_salesYear.ArmDb = p_da
    
    Call cbo_salesCurrency.Load_A_Com
    Call cbo_salesDataView.Load_A_Com
    Call cbo_salesYear.Load_A_Com

    
    cbo_salesCurrency.Request = "EXEC currencies_cbo2 '" & ms_Language_Code & "'"
    cbo_salesDataView.Request = "EXEC Sales_Reps_View_Assignement_cbo '" & ms_Language_Code & "'"
    cbo_salesYear.Request = "select distinct sa_shipping_year, sa_shipping_year from sa_flat_file_yoy_perday_Capture order by 1 asc"
    
    Call cbo_salesYear.AddItem(Array(Year(Date), Year(Date)), True)

   ' Initialisation of the Queries part
   Set cbo_Query.ArmDb = p_da
   cbo_Query.Load_A_Com
   
   
   cbo_Query.FirstBlankItem = False
   cbo_Query.Request = "EXEC PredefinedQueries_lst '" & gsuser & "', '" & ms_Language_Code & "', 1"
   
   Set grd_Query.ArmDb = p_da
   grd_Query.Load_A_Com
   
   grd_Query.ExportTitles = True
   grd_Query.AllowExcelExport = True
   
   grd_Views.ExportTitles = True
   grd_Views.AllowExcelExport = True
   
   gr_replic.ExportTitles = True
   gr_replic.AllowExcelExport = True
   
   Set grd_visitCounts(0).ArmDb = p_da
   grd_visitCounts(0).Load_A_Com
   grd_visitCounts(0).ExportTitles = True
   grd_visitCounts(0).AllowExcelExport = True
   grd_visitCounts(0).Title = "#Count of visits for last $CP_DAYS$ days"
   grd_visitCounts(0).FetchAll = True
   
   Set grd_visitCounts(1).ArmDb = p_da
   grd_visitCounts(1).Load_A_Com
   grd_visitCounts(1).ExportTitles = True
   grd_visitCounts(1).AllowExcelExport = True
   grd_visitCounts(1).Title = "#Count of visits for last $CP_DAYS$ days"
   grd_visitCounts(1).FetchAll = True

   Set grd_visitCounts(2).ArmDb = p_da
   grd_visitCounts(2).Load_A_Com
   grd_visitCounts(2).ExportTitles = True
   grd_visitCounts(2).AllowExcelExport = True
   grd_visitCounts(2).Title = "#Count of visits for last $CP_DAYS$ days"
   grd_visitCounts(2).FetchAll = True

    Dim la_Columns() As String
    ReDim la_Columns(5) As String
    
    la_Columns(0) = "CP_code" & CH_LDELIMIT & "0" & CH_LDELIMIT & "1" & CH_LDELIMIT & "CP_code" & CH_LDELIMIT & "CP_code"
    la_Columns(1) = "CP_DESC" & CH_LDELIMIT & "4000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CP_DESC" & CH_LDELIMIT & "#Customer priority"
    la_Columns(2) = "CP_VISITS" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "Visits" & CH_LDELIMIT & "#Number"
    la_Columns(3) = "CP_DAYS" & CH_LDELIMIT & "0" & CH_LDELIMIT & "0" & CH_LDELIMIT & "Days" & CH_LDELIMIT & "#Days" & CH_LDELIMIT & "Float"
    la_Columns(4) = "CP_TOTAL" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "TOTAL" & CH_LDELIMIT & "#Total"
    la_Columns(5) = "CP_PERCENT" & CH_LDELIMIT & "1000" & CH_LDELIMIT & "0" & CH_LDELIMIT & "PERCENT" & CH_LDELIMIT & "% of total" & CH_LDELIMIT & "Float" & CH_LDELIMIT & "0.00%"
    
    Call grd_visitCounts(0).SetColumns(la_Columns)
    Call grd_visitCounts(1).SetColumns(la_Columns)
    Call grd_visitCounts(2).SetColumns(la_Columns)

    
    Set grd_visitDetail(0).ArmDb = p_da
    grd_visitDetail(0).Load_A_Com
    grd_visitDetail(0).ExportTitles = True
    grd_visitDetail(0).AllowExcelExport = True
    grd_visitDetail(0).Title = "#Detail of last visit per customers priority"
   
    Set grd_visitDetail(1).ArmDb = p_da
    grd_visitDetail(1).Load_A_Com
    grd_visitDetail(1).ExportTitles = True
    grd_visitDetail(1).AllowExcelExport = True
    grd_visitDetail(1).Title = "#Detail of last visit per customers priority ( omega only )"
   
    Set grd_visitDetail(2).ArmDb = p_da
    grd_visitDetail(2).Load_A_Com
    grd_visitDetail(2).ExportTitles = True
    grd_visitDetail(2).AllowExcelExport = True
    grd_visitDetail(2).Title = "#Detail of last visit per customers priority ( new customers )"
    
    ReDim la_Columns(9) As String
    
    la_Columns(0) = "CCU_CAPKEY" & CH_LDELIMIT & "0" & CH_LDELIMIT & "1" & CH_LDELIMIT & "CCU_CAPKEY" & CH_LDELIMIT & "CCU_CAPKEY"
    la_Columns(1) = "CP_DESC" & CH_LDELIMIT & "1300" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CP_DESC" & CH_LDELIMIT & "#Customer priority"
    la_Columns(2) = "ACT_RaisedFor" & CH_LDELIMIT & "1100" & CH_LDELIMIT & "0" & CH_LDELIMIT & "ACT_RaisedFor" & CH_LDELIMIT & "#Rep name"
    la_Columns(3) = "CCU_DESC" & CH_LDELIMIT & "2300" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CCU_desc" & CH_LDELIMIT & "#Name"
    la_Columns(4) = "CCU_TOWN" & CH_LDELIMIT & "1100" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CCU_town" & CH_LDELIMIT & "#Town"
    la_Columns(5) = "CTY_DESC" & CH_LDELIMIT & "1200" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CTY_Desc" & CH_LDELIMIT & "#County"
    la_Columns(6) = "CCT_DESC" & CH_LDELIMIT & "1200" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CCT_desc" & CH_LDELIMIT & "#Type"
    la_Columns(7) = "VisitDate" & CH_LDELIMIT & "1100" & CH_LDELIMIT & "0" & CH_LDELIMIT & "VisitDate" & CH_LDELIMIT & "#Last visit date"
    la_Columns(8) = "DAYS" & CH_LDELIMIT & "600" & CH_LDELIMIT & "0" & CH_LDELIMIT & "DAYS" & CH_LDELIMIT & "#Number of days" & CH_LDELIMIT & "Float"
    la_Columns(9) = "CP_DAYS" & CH_LDELIMIT & "0" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CP_DAYS" & CH_LDELIMIT & "#OK days" & CH_LDELIMIT & "Float"
    
    Call grd_visitDetail(0).SetColumns(la_Columns)
    Call grd_visitDetail(1).SetColumns(la_Columns)
   
    ReDim la_Columns(8) As String
    
    la_Columns(0) = "CCU_CAPKEY" & CH_LDELIMIT & "0" & CH_LDELIMIT & "1" & CH_LDELIMIT & "CCU_CAPKEY" & CH_LDELIMIT & "CCU_CAPKEY"
    la_Columns(1) = "CP_DESC" & CH_LDELIMIT & "1300" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CP_DESC" & CH_LDELIMIT & "#Customer priority"
    la_Columns(2) = "ACT_RaisedFor" & CH_LDELIMIT & "1100" & CH_LDELIMIT & "0" & CH_LDELIMIT & "ACT_RaisedFor" & CH_LDELIMIT & "#Rep name"
    la_Columns(3) = "CCU_DESC" & CH_LDELIMIT & "2300" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CCU_desc" & CH_LDELIMIT & "#Name"
    la_Columns(4) = "CCU_TOWN" & CH_LDELIMIT & "1100" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CCU_town" & CH_LDELIMIT & "#Town"
    la_Columns(5) = "CCT_DESC" & CH_LDELIMIT & "1200" & CH_LDELIMIT & "0" & CH_LDELIMIT & "CCT_desc" & CH_LDELIMIT & "#Type"
    la_Columns(6) = "CreateDate" & CH_LDELIMIT & "1100" & CH_LDELIMIT & "0" & CH_LDELIMIT & "Z_Creation" & CH_LDELIMIT & "#Creation date"
    la_Columns(7) = "VisitDate" & CH_LDELIMIT & "1100" & CH_LDELIMIT & "0" & CH_LDELIMIT & "VisitDate" & CH_LDELIMIT & "#Last visit date"
    la_Columns(8) = "COUNT" & CH_LDELIMIT & "600" & CH_LDELIMIT & "0" & CH_LDELIMIT & "DAYS" & CH_LDELIMIT & "#Visits count" & CH_LDELIMIT & "Float"
   
    Call grd_visitDetail(2).SetColumns(la_Columns)
   
       
    Call ChangeCharset(UserControl.Controls, GetCodePageFromLanguage(p_da, ms_Language_Code))
    Call LoadLabels(p_da, Me, SCREEN_NAME, ms_Language_Code)
    
    ' init grids here, because of dependecy of labels

    ' create 8 grids for project
    ReDim la_ColumnsX(15) As Variant
    la_ColumnsX(0) = Array("GRP_DESC", GetLabel("p_GRP_DESC", "GRP_DESC"), 1600, "GRP_DESC")
    la_ColumnsX(1) = Array("MONTH", GetLabel("p_MONTH", "#Month"), 250, "MONTH", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(2) = Array("REPLICS", GetLabel("p_REPLICS", "#Repl. days"), 350, "REPLICS")
    la_ColumnsX(3) = Array("TOPTEN", GetLabel("p_TOPTEN", "#Priority"), 900, "TOPTEN")
    la_ColumnsX(4) = Array("STDProjects", GetLabel("p_STDProjects", "#STD Prj. created"), 400, "STDProjects", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(5) = Array("SAProjects", GetLabel("p_SAProjects", "#SA Prj. created"), 400, "SAProjects", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(6) = Array("ASProjects", GetLabel("p_ASProjects", "#AS Prj. created"), 400, "ASProjects", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(7) = Array("Volume", GetLabel("p_Volume", "#Prj. volume"), 1000, "Volume", flexAlignRightCenter, "##,##0")
    la_ColumnsX(8) = Array("SolutionLine", GetLabel("p_SolutionLine", "#Main solustion lines"), 450, "SolutionLine", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(9) = Array("TotalPrdVol", GetLabel("p_TotalVol", "#Total vol. (SQM)"), 800, "", flexAlignRightCenter, "##,##0")
    la_ColumnsX(10) = Array("ABPEPrdVol", GetLabel("p_ABPEPrdVol", "#ABPE vol."), 800, "ABPEPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(11) = Array("ASPrdVol", GetLabel("p_ASPrdVol", "#ABPE AS Dummy vol."), 800, "ASPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(12) = Array("SOMVol", GetLabel("p_SOMVol", "#Quoted vol."), 800, "SOMVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(13) = Array("ProjectValue", GetLabel("p_ProjectValue", "#Quoted value (EUR)"), 900, "ProjectValue", flexAlignRightCenter, "##,##0")
    la_ColumnsX(14) = Array("YEAR", "YEAR", 0, "YEAR", flexAlignLeftCenter, "####0")
    la_ColumnsX(15) = Array("BMK_CODE", "BMK_CODE", 0, "BMK_CODE")
        
    Call GRD_SetHeader(grd_project(0), mo_projectInfo(0), Array(la_ColumnsX))
    mo_projectInfo(0).gTitle = GetLabel("grd_projectM_Title", "#All Projects month view")

    
    ReDim la_ColumnsX(17) As Variant
    la_ColumnsX(0) = Array("GRP_DESC", GetLabel("p_GRP_DESC", "GRP_DESC"), 1000, "GRP_DESC")
    la_ColumnsX(1) = Array("MONTH", GetLabel("p_WEEK", "#Week"), 250, "WEEK", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(2) = Array("START", GetLabel("p_START", "#Start date"), 900, "START")
    la_ColumnsX(3) = Array("END", GetLabel("p_END", "#End date"), 900, "END")
    la_ColumnsX(4) = Array("REPLICS", GetLabel("p_REPLICS", "#Repl. days"), 350, "REPLICS")
    la_ColumnsX(5) = Array("TOPTEN", GetLabel("p_TOPTEN", "#Priority"), 650, "TOPTEN")
    la_ColumnsX(6) = Array("STDProjects", GetLabel("p_STDProjects", "#STD Prj. created"), 400, "STDProjects", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(7) = Array("SAProjects", GetLabel("p_SAProjects", "#SA Prj. created"), 400, "SAProjects", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(8) = Array("ASProjects", GetLabel("p_ASProjects", "#AS Prj. created"), 400, "ASProjects", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(9) = Array("Volume", GetLabel("p_Volume", "#Prj. volume"), 1000, "Volume", flexAlignRightCenter, "##,##0")
    la_ColumnsX(10) = Array("SolutionLine", GetLabel("p_SolutionLine", "#Main solustion lines"), 450, "SolutionLine", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(11) = Array("TotalPrdVol", GetLabel("p_TotalVol", "#Total vol. (SQM)"), 800, "", flexAlignRightCenter, "##,##0")
    la_ColumnsX(12) = Array("ABPEPrdVol", GetLabel("p_ABPEPrdVol", "#ABPE vol."), 800, "ABPEPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(13) = Array("ASPrdVol", GetLabel("p_ASPrdVol", "#ABPE AS Dummy vol."), 780, "ASPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(14) = Array("SOMVol", GetLabel("p_SOMVol", "#Quoted vol."), 780, "SOMVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(15) = Array("ProjectValue", GetLabel("p_ProjectValue", "#Quoted value (EUR)"), 850, "ProjectValue", flexAlignRightCenter, "##,##0")
    la_ColumnsX(16) = Array("YEAR", "YEAR", 0, "YEAR", flexAlignLeftCenter, "####0")
    la_ColumnsX(17) = Array("BMK_CODE", "BMK_CODE", 0, "BMK_CODE")
    
    
    Call GRD_SetHeader(grd_project(1), mo_projectInfo(1), Array(la_ColumnsX))
    mo_projectInfo(1).gTitle = GetLabel("grd_projectW_Title", "#All Projects month view")
    
    
    ReDim la_ColumnsX(11) As Variant
    la_ColumnsX(0) = Array("GRP_DESC", GetLabel("p_GRP_DESC", "GRP_DESC"), 2800, "GRP_DESC")
    la_ColumnsX(1) = Array("MONTH", GetLabel("p_MONTH", "#Month"), 350, "MONTH", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(2) = Array("REPLICS", GetLabel("p_REPLICS", "#Repl. days"), 450, "REPLICS")
    la_ColumnsX(3) = Array("TOPTEN", GetLabel("p_TOPTEN", "#Priority"), 1000, "TOPTEN")
    la_ColumnsX(4) = Array("STDProjects", GetLabel("p_STDProjects", "#STD Prj. created"), 500, "STDProjects", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(5) = Array("Volume", GetLabel("p_Volume", "#Prj. volume"), 1200, "Volume", flexAlignRightCenter, "##,##0")
    la_ColumnsX(6) = Array("SolutionLine", GetLabel("p_SolutionLine", "#Main solustion lines"), 550, "SolutionLine", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(7) = Array("TotalPrdVol", GetLabel("p_TotalVol", "#Total vol. (SQM)"), 1200, "", flexAlignRightCenter, "##,##0")
    la_ColumnsX(8) = Array("ABPEPrdVol", GetLabel("p_ABPEPrdVol", "#ABPE vol."), 900, "ABPEPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(9) = Array("ASPrdVol", GetLabel("p_ASPrdVol", "#ABPE AS Dummy vol."), 900, "ASPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(10) = Array("YEAR", "YEAR", 0, "YEAR", flexAlignLeftCenter, "####0")
    la_ColumnsX(11) = Array("BMK_CODE", "BMK_CODE", 0, "BMK_CODE")
    
    Call GRD_SetHeader(grd_project(2), mo_projectInfo(2), Array(la_ColumnsX))
    mo_projectInfo(2).gTitle = GetLabel("grd_projectSTDM_Title", "#Std Projects month view")
    
    
    ReDim la_ColumnsX(13) As Variant
    la_ColumnsX(0) = Array("GRP_DESC", GetLabel("p_GRP_DESC", "GRP_DESC"), 1850, "GRP_DESC")
    la_ColumnsX(1) = Array("MONTH", GetLabel("p_WEEK", "#Week"), 350, "WEEK", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(2) = Array("START", GetLabel("p_START", "#Start date"), 900, "START")
    la_ColumnsX(3) = Array("END", GetLabel("p_END", "#End date"), 900, "END")
    la_ColumnsX(4) = Array("REPLICS", GetLabel("p_REPLICS", "#Repl. days"), 350, "REPLICS")
    la_ColumnsX(5) = Array("TOPTEN", GetLabel("p_TOPTEN", "#Priority"), 650, "TOPTEN")
    la_ColumnsX(6) = Array("STDProjects", GetLabel("p_STDProjects", "#STD Prj. created"), 500, "STDProjects", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(7) = Array("Volume", GetLabel("p_Volume", "#Prj. volume"), 1100, "Volume", flexAlignRightCenter, "##,##0")
    la_ColumnsX(8) = Array("SolutionLine", GetLabel("p_SolutionLine", "#Main solustion lines"), 550, "SolutionLine", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(9) = Array("TotalPrdVol", GetLabel("p_TotalVol", "#Total vol. (SQM)"), 900, "", flexAlignRightCenter, "##,##0")
    la_ColumnsX(10) = Array("ABPEPrdVol", GetLabel("p_ABPEPrdVol", "#ABPE vol."), 900, "ABPEPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(11) = Array("ASPrdVol", GetLabel("p_ASPrdVol", "#ABPE AS Dummy vol."), 900, "ASPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(12) = Array("YEAR", "YEAR", 0, "YEAR", flexAlignLeftCenter, "####0")
    la_ColumnsX(13) = Array("BMK_CODE", "BMK_CODE", 0, "BMK_CODE")
    
    Call GRD_SetHeader(grd_project(3), mo_projectInfo(3), Array(la_ColumnsX))
    mo_projectInfo(3).gTitle = GetLabel("grd_projectSTDW_Title", "#Std Projects week view")
    

    ReDim la_ColumnsX(11) As Variant
    la_ColumnsX(0) = Array("GRP_DESC", GetLabel("p_GRP_DESC", "GRP_DESC"), 2700, "GRP_DESC")
    la_ColumnsX(1) = Array("MONTH", GetLabel("p_MONTH", "#Month"), 350, "MONTH", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(2) = Array("REPLICS", GetLabel("p_REPLICS", "#Repl. days"), 450, "REPLICS")
    la_ColumnsX(3) = Array("TOPTEN", GetLabel("p_TOPTEN", "#Priority"), 1000, "TOPTEN")
    la_ColumnsX(4) = Array("SAProjects", GetLabel("p_SAProjects", "#SA Prj. created"), 500, "SAProjects", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(5) = Array("Volume", GetLabel("p_Volume", "#Prj. volume"), 1200, "Volume", flexAlignRightCenter, "##,##0")
    la_ColumnsX(6) = Array("SolutionLine", GetLabel("p_SolutionLine", "#Main solustion lines"), 550, "SolutionLine", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(7) = Array("TotalPrdVol", GetLabel("p_TotalVol", "#Total vol. (SQM)"), 1200, "", flexAlignRightCenter, "##,##0")
    la_ColumnsX(8) = Array("ABPEPrdVol", GetLabel("p_ABPEPrdVol", "#ABPE vol."), 900, "ABPEPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(9) = Array("ASPrdVol", GetLabel("p_ASPrdVol", "#ABPE AS Dummy vol."), 900, "ASPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(10) = Array("YEAR", "YEAR", 0, "YEAR", flexAlignLeftCenter, "####0")
    la_ColumnsX(11) = Array("BMK_CODE", "BMK_CODE", 0, "BMK_CODE")

    Call GRD_SetHeader(grd_project(4), mo_projectInfo(4), Array(la_ColumnsX))
    mo_projectInfo(4).gTitle = GetLabel("grd_projectSAM_Title", "#SA Projects month view")
    
    
    ReDim la_ColumnsX(13) As Variant
    la_ColumnsX(0) = Array("GRP_DESC", GetLabel("p_GRP_DESC", "GRP_DESC"), 1850, "GRP_DESC")
    la_ColumnsX(1) = Array("MONTH", GetLabel("p_WEEK", "#Week"), 350, "WEEK", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(2) = Array("START", GetLabel("p_START", "#Start date"), 900, "START")
    la_ColumnsX(3) = Array("END", GetLabel("p_END", "#End date"), 900, "END")
    la_ColumnsX(4) = Array("REPLICS", GetLabel("p_REPLICS", "#Repl. days"), 350, "REPLICS")
    la_ColumnsX(5) = Array("TOPTEN", GetLabel("p_TOPTEN", "#Priority"), 650, "TOPTEN")
    la_ColumnsX(6) = Array("SAProjects", GetLabel("p_SAProjects", "#SA Prj. created"), 500, "SAProjects", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(7) = Array("Volume", GetLabel("p_Volume", "#Prj. volume"), 1100, "Volume", flexAlignRightCenter, "##,##0")
    la_ColumnsX(8) = Array("SolutionLine", GetLabel("p_SolutionLine", "#Main solustion lines"), 550, "SolutionLine", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(9) = Array("TotalPrdVol", GetLabel("p_TotalVol", "#Total vol. (SQM)"), 900, "", flexAlignRightCenter, "##,##0")
    la_ColumnsX(10) = Array("ABPEPrdVol", GetLabel("p_ABPEPrdVol", "#ABPE vol."), 900, "ABPEPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(11) = Array("ASPrdVol", GetLabel("p_ASPrdVol", "#ABPE AS Dummy vol."), 900, "ASPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(12) = Array("YEAR", "YEAR", 0, "YEAR", flexAlignLeftCenter, "####0")
    la_ColumnsX(13) = Array("BMK_CODE", "BMK_CODE", 0, "BMK_CODE")
    
    Call GRD_SetHeader(grd_project(5), mo_projectInfo(5), Array(la_ColumnsX))
    mo_projectInfo(5).gTitle = GetLabel("grd_projectSAW_Title", "#SA Projects week view")


    ReDim la_ColumnsX(12) As Variant
    la_ColumnsX(0) = Array("GRP_DESC", GetLabel("p_GRP_DESC", "GRP_DESC"), 1900, "GRP_DESC")
    la_ColumnsX(1) = Array("MONTH", GetLabel("p_MONTH", "#Month"), 500, "MONTH", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(2) = Array("REPLICS", GetLabel("p_REPLICS", "#Repl. days"), 300, "REPLICS")
    la_ColumnsX(3) = Array("TOPTEN", GetLabel("p_TOPTEN", "#Priority"), 750, "TOPTEN")
    la_ColumnsX(4) = Array("ASProjects", GetLabel("p_ASProjects", "#AS Prj. created"), 500, "ASProjects", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(5) = Array("Volume", GetLabel("p_Volume", "#Prj. volume"), 1000, "Volume", flexAlignRightCenter, "##,##0")
    la_ColumnsX(6) = Array("TotalPrdVol", GetLabel("p_TotalVol", "#Total vol. (SQM)"), 900, "", flexAlignRightCenter, "##,##0")
    la_ColumnsX(7) = Array("ABPEPrdVol", GetLabel("p_ABPEPrdVol", "#ABPE vol."), 1000, "ABPEPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(8) = Array("ASPrdVol", GetLabel("p_ASPrdVol", "#ABPE AS Dummy vol."), 1000, "ASPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(9) = Array("SOMVol", GetLabel("p_SOMVol", "#Quoted vol."), 950, "SOMVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(10) = Array("ProjectValue", GetLabel("p_ProjectValue", "#Quoted value (EUR)"), 1000, "ProjectValue", flexAlignRightCenter, "##,##0")
    la_ColumnsX(11) = Array("YEAR", "YEAR", 0, "YEAR", flexAlignLeftCenter, "####0")
    la_ColumnsX(12) = Array("BMK_CODE", "BMK_CODE", 0, "BMK_CODE")

    Call GRD_SetHeader(grd_project(6), mo_projectInfo(6), Array(la_ColumnsX))
    mo_projectInfo(6).gTitle = GetLabel("grd_ASprojectM_Title", "#AS Projects month view")
    
    
    ReDim la_ColumnsX(14) As Variant
    la_ColumnsX(0) = Array("GRP_DESC", GetLabel("p_GRP_DESC", "GRP_DESC"), 1200, "GRP_DESC")
    la_ColumnsX(1) = Array("MONTH", GetLabel("p_WEEK", "#Week"), 400, "WEEK", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(2) = Array("START", GetLabel("p_START", "#Start date"), 900, "START")
    la_ColumnsX(3) = Array("END", GetLabel("p_END", "#End date"), 900, "END")
    la_ColumnsX(4) = Array("REPLICS", GetLabel("p_REPLICS", "#Repl. days"), 300, "REPLICS")
    la_ColumnsX(5) = Array("TOPTEN", GetLabel("p_TOPTEN", "#Priority"), 650, "TOPTEN")
    la_ColumnsX(6) = Array("ASProjects", GetLabel("p_ASProjects", "#AS Prj. created"), 400, "ASProjects", flexAlignLeftCenter, "##,##0")
    la_ColumnsX(7) = Array("Volume", GetLabel("p_Volume", "#Prj. volume"), 900, "Volume", flexAlignRightCenter, "##,##0")
    la_ColumnsX(8) = Array("TotalPrdVol", GetLabel("p_TotalVol", "#Total vol. (SQM)"), 800, "", flexAlignRightCenter, "##,##0")
    la_ColumnsX(9) = Array("ABPEPrdVol", GetLabel("p_ABPEPrdVol", "#ABPE vol."), 850, "ABPEPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(10) = Array("ASPrdVol", GetLabel("p_ASPrdVol", "#ABPE AS Dummy vol."), 850, "ASPrdVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(11) = Array("SOMVol", GetLabel("p_SOMVol", "#Quoted vol."), 800, "SOMVol", flexAlignRightCenter, "##,##0")
    la_ColumnsX(12) = Array("ProjectValue", GetLabel("p_ProjectValue", "#Quoted value (EUR)"), 900, "ProjectValue", flexAlignRightCenter, "##,##0")
    la_ColumnsX(13) = Array("YEAR", "YEAR", 0, "YEAR", flexAlignLeftCenter, "####0")
    la_ColumnsX(14) = Array("BMK_CODE", "BMK_CODE", 0, "BMK_CODE")
    
    Call GRD_SetHeader(grd_project(7), mo_projectInfo(7), Array(la_ColumnsX))
    mo_projectInfo(7).gTitle = GetLabel("grd_ASprojectW_Title", "#AS Projects week view")

    Dim lo_Grid As MSFlexGrid
    For Each lo_Grid In grd_project
        lo_Grid.MergeCol(0) = True
        lo_Grid.WordWrap = True
        lo_Grid.ForeColor = vbBlack
        lo_Grid.RowHeight(0) = 1000
        lo_Grid.Height = 7550
    Next

    Call GRD_SetHeader(grd_StatusProjects2, mo_StatusProjects2Info, _
        Array(Array("", "", GetLabel("p_market", "#Market"), GetLabel("p_country", "#Country"), "", "", _
                    GetLabel("p_createdLabel", "#Projects created"), 6, 6, 6, 6, 6, 6, 6, 6, 6, _
                    GetLabel("p_updatedLabel", "#Projects updated"), 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16), _
              Array(Array("BMK_Code", "BMK_Code", 0), Array("CT_Code", "CT_Code", 0), Array("BMK_Desc", GetLabel("p_market", "#Market"), 800, "BMK_Desc", flexAlignCenterCenter), _
                    Array("CT_Desc", GetLabel("p_country", "#Country"), 1000, "CT_Desc", flexAlignCenterCenter), Array("SR_Code", "SR_Code", 0), Array("SR_Name", GetLabel("p_rep", "#Sales Rep"), 800, "SR_Name", flexAlignCenterCenter), _
                    Array("", GetLabel("p_Leads", "#Leads"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_LeadsQ", "#Qualified Leads"), 900, "", flexAlignCenterCenter), _
                    Array("", GetLabel("p_specified", "#Specified"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_tender", "#Tender"), 900, "", flexAlignCenterCenter), _
                    Array("", GetLabel("p_quotated", "#Quoted"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_others", "#Other"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_complete", "#Complete"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_ordered", "#Ordered"), 900, "", flexAlignCenterCenter), _
                    Array("totalC", GetLabel("p_total", "#Total"), 1050, "", flexAlignCenterCenter), Array("", GetLabel("p_Early", "#Projects % Created Early"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_Leads", "#Leads"), 900, "", flexAlignCenterCenter), _
                    Array("", GetLabel("p_LeadsQ", "#Qualified Leads"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_specified", "#Specified"), 900, "", flexAlignCenterCenter), _
                    Array("", GetLabel("p_tender", "#Tender"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_quotated", "#Quotated"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_others", "#Other"), 900, "", flexAlignCenterCenter), _
                    Array("", GetLabel("p_complete", "#Complete"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_ordered", "#Ordered"), 900, "", flexAlignCenterCenter), _
                    Array("totalU", GetLabel("p_total2", "#Total"), 1050, "", flexAlignCenterCenter), Array("", GetLabel("p_totalUnique", "#Total unique"), 1050, "", flexAlignCenterCenter), Array("updatedPerc", GetLabel("p_updatedPerc", "#Updated % of All Projects"), 1000, "", flexAlignCenterCenter), _
                    Array("wonSpec", GetLabel("p_wonSpec", "#Won Specs %"), 1000, "", flexAlignCenterCenter), Array("wonOrder", GetLabel("p_wonOrder", "#Won orders %"), 1000, "", flexAlignCenterCenter), _
                    Array("totalPrj", GetLabel("p_totalPrj", "#Total Active Projects"), 900, "", flexAlignCenterCenter), Array("offeredPrior", GetLabel("p_offeredPrior", "#Offered prior"), 900, "", flexAlignCenterCenter)) _
            ))
    With grd_StatusProjects2
        .MergeCol(2) = True
        .MergeCol(3) = True
        .RowHeight(1) = 1000
        .WordWrap = True
        .ForeColor = vbBlack
    End With

    Call GRD_SetHeader(grd_StatusProjects3, mo_StatusProjects3Info, _
        Array(Array( _
                Array("BMK_Code", "BMK_Code", 0), Array("CT_Code", "CT_Code", 0), Array("BMK_Desc", GetLabel("p_market", "#Market"), 800, "BMK_Desc", flexAlignCenterCenter), _
                Array("CT_Desc", GetLabel("p_country", "#Country"), 1000, "CT_Desc", flexAlignCenterCenter), _
                Array("", GetLabel("p_Early", "#Early created"), 0, "", flexAlignCenterCenter), _
                Array("totalC", GetLabel("p_total3", "#Total projects created"), 1050, "", flexAlignCenterCenter), _
                Array("", GetLabel("p_PerSalesRep", "#Projects Created Per Sales rep"), 900, "", flexAlignCenterCenter), _
                Array("", GetLabel("p_Early", "#Projects % Created Early"), 900, "", flexAlignCenterCenter), _
                Array("", GetLabel("p_Order", "#Ordered"), 0, "", flexAlignCenterCenter), _
                Array("", GetLabel("p_totalUnique", "#Total unique"), 0, "", flexAlignCenterCenter), Array("updatedPerc", GetLabel("p_updatedPerc", "#Updated % of All Projects"), 1000, "", flexAlignCenterCenter), _
                Array("wonOrder", GetLabel("p_wonOrder", "#Won orders %"), 1000, "", flexAlignCenterCenter), _
                Array("totalPrj", GetLabel("p_totalPrj", "#Total Active Projects"), 900, "", flexAlignCenterCenter)) _
            ))
    
    With grd_StatusProjects3
        .MergeCol(2) = True
        .MergeCol(3) = True
        .RowHeight(0) = 1000
        .WordWrap = True
        .ForeColor = vbBlack
    End With


    Call GRD_SetHeader(grd_sales_rep, mo_SalesRepInfo, _
       Array(Array("", GetLabel("s_grouping", "#Grouping"), GetLabel("p_nonAS", "#Non AS Revenue"), 2, 2, 2, _
                    GetLabel("p_AS", "#AS Revenue"), 6, 6, 6), _
              Array(Array("GRP_Code", "GRP_Code", 0, "GRP_Code"), Array("GRP_Desc", "", 1500, "GRP_Desc", flexAlignCenterCenter), _
                    Array("GSV_EUR_M", GetLabel("p_month", "#Month"), 900, "GSV_EUR_M", flexAlignCenterCenter, "##,##0"), Array("GSV_EUR_YTD", GetLabel("p_YTD", "#YTD"), 1150, "GSV_EUR_YTD", flexAlignCenterCenter, "##,##0"), _
                    Array("GSV_EUR_H1", GetLabel("p_H1", "#H1"), 1150, "GSV_EUR_H1", flexAlignCenterCenter, "##,##0"), Array("GSV_EUR_H2", GetLabel("p_H2", "#H2"), 1150, "GSV_EUR_H2", flexAlignCenterCenter, "##,##0"), _
                    Array("GSV_EUR_M_AS", GetLabel("p_month", "#Month"), 900, "GSV_EUR_M_AS", flexAlignCenterCenter, "##,##0"), Array("GSV_EUR_YTD_AS", GetLabel("p_YTD", "#YTD"), 1150, "GSV_EUR_YTD_AS", flexAlignCenterCenter, "##,##0"), _
                    Array("GSV_EUR_H1_AS", GetLabel("p_H1", "#H1"), 1150, "GSV_EUR_H1_AS", flexAlignCenterCenter, "##,##0"), Array("GSV_EUR_H2_AS", GetLabel("p_H2", "#H2"), 1150, "GSV_EUR_H2_AS", flexAlignCenterCenter, "##,##0")) _
            ))
    mo_SalesRepInfo.gTitle = GetLabel("grd_sales_rep_Title", "#Sales by rep")

    With grd_sales_rep
        .MergeCol(1) = True
        .RowHeight(0) = 800
        .WordWrap = True
        .ForeColor = vbBlack
    End With

'    Call GRD_SetHeader(grd_StatusProjects, mo_StatusProjectsInfo, _
        Array(Array("", "", GetLabel("p_market", "#Market"), GetLabel("p_country", "#Country"), _
                    GetLabel("p_createdLabel", "#Projects created"), 4, 4, 4, 4, 4, 4, 4, _
                    GetLabel("p_updatedLabel", "#Projects updated"), 12, 12, 12, 12, 12, 12, 12), _
              Array(Array("BMK_Code", "BMK_Code", 0), Array("CT_Code", "CT_Code", 0), Array("BMK_Desc", GetLabel("p_market", "#Market"), 800, "BMK_Desc", flexAlignCenterCenter), _
                    Array("CT_Desc", GetLabel("p_country", "#Country"), 1000, "CT_Desc", flexAlignCenterCenter), Array("", GetLabel("p_nbProj", "#No of projects entered"), 900, "", flexAlignCenterCenter), _
                    Array("", GetLabel("p_Leads", "#Leads"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_LeadsQ", "#Qualified Leads"), 900, "", flexAlignCenterCenter), _
                    Array("", GetLabel("p_specified", "#Specified"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_tender", "#Tender"), 900, "", flexAlignCenterCenter), _
                    Array("", GetLabel("p_quotated", "#Quoted"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_others", "#Other"), 900, "", flexAlignCenterCenter), _
                    Array("", GetLabel("s_total2", "#Total"), 1050, "", flexAlignCenterCenter), Array("", GetLabel("p_Leads", "#Leads"), 900, "", flexAlignCenterCenter), _
                    Array("", GetLabel("p_LeadsQ", "#Qualified Leads"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_specified", "#Specified"), 900, "", flexAlignCenterCenter), _
                    Array("", GetLabel("p_tender", "#Tender"), 900, "", flexAlignCenterCenter), Array("", GetLabel("p_quotated", "#Quotated"), 900, "", flexAlignCenterCenter), _
                    Array("", GetLabel("s_total2", "#Total"), 1050, "", flexAlignCenterCenter), Array("", GetLabel("p_updatedPerc", "#Updated % of All Projects"), 1000, "", flexAlignCenterCenter), _
                    Array("", GetLabel("p_won", "#Won %"), 1000, "", flexAlignCenterCenter), Array("WonU", "WonU", 0), Array("LostU", "LostU", 0), Array("WonC", "WonC", 0), Array("LostC", "LostC", 0)) _
            ))
'    With grd_StatusProjects
'        .MergeCol(2) = True
'        .MergeCol(3) = True
'        .RowHeight(1) = 700
'        .WordWrap = True
'        .ForeColor = vbBlack
'    End With
    
    
    ReDim la_ColumnsX(16) As Variant
    
    la_ColumnsX(0) = Array("SP_CAPKEY", "SP_CapKey", 0, "SP_CapKey")
    la_ColumnsX(1) = Array("BMK_DESC", GetLabel("p_market", "#Market"), 1000, "BMK_Desc", flexAlignCenterCenter)
    la_ColumnsX(2) = Array("CT_DESC", GetLabel("p_country", "#Country"), 1000, "CT_Desc", flexAlignCenterCenter)
    la_ColumnsX(3) = Array("SP_SAFlag", GetLabel("p_SP_SAFlag", "#SP_SAFlag"), 900, "SP_SAFlag", flexAlignCenterCenter)
    la_ColumnsX(4) = Array("SS_DESC", GetLabel("p_SS_desc", "#SS_desc"), 1250, "SS_desc", flexAlignCenterCenter)
    la_ColumnsX(5) = Array("SP_DESC", GetLabel("p_SP_Desc", "#SP_Desc"), 1250, "SP_Desc", flexAlignCenterCenter)
    la_ColumnsX(6) = Array("SP_SIZE", GetLabel("p_SP_Size", "#Prj. volume"), 1000, "SP_Size", flexAlignCenterCenter, "##,##0")
    la_ColumnsX(7) = Array("SolutionLine", GetLabel("p_SolutionLine", "#Main solustion lines"), 450, "SolutionLine", flexAlignCenterCenter, "##,##0")
    la_ColumnsX(8) = Array("ABPEPrdVol", GetLabel("p_ABPEPrdVol", "#ABPE vol."), 800, "ABPEPrdVol", flexAlignCenterCenter, "##,##0")
    la_ColumnsX(9) = Array("ASPrdVol", GetLabel("p_ASPrdVol", "#ABPE AS Dummy vol."), 800, "ASPrdVol", flexAlignCenterCenter, "##,##0")
    la_ColumnsX(10) = Array("SOMVol", GetLabel("p_SOMVol", "#Quoted vol."), 800, "SOMVol", flexAlignCenterCenter, "##,##0")
    la_ColumnsX(11) = Array("ProjectValue", GetLabel("p_Quoted_USD", "#Quoted value (USD)"), 900, "SQD_Value_USD", flexAlignCenterCenter, "##,##0")
    la_ColumnsX(12) = Array("SR_NAME", GetLabel("p_SR_Name", "#SR_Name"), 900, "SR_Name", flexAlignCenterCenter)
    la_ColumnsX(13) = Array("Z_CREATION", GetLabel("p_Z_creation", "#Z_creation"), 900, "Z_creation", flexAlignCenterCenter)
    la_ColumnsX(14) = Array("Z_last_upd", GetLabel("p_Z_last_upd", "#Z_last_upd"), 900, "Z_last_upd", flexAlignCenterCenter)
    la_ColumnsX(15) = Array("LastUpdDays", GetLabel("p_upd_days", "#Days"), 400, "Z_LastDays", flexAlignCenterCenter, "####0")
    la_ColumnsX(16) = Array("AMCProjectNum", GetLabel("p_AMC_PrjNum", "#AMC Prj. Nb."), 1200, "AMCProjectNumber", flexAlignCenterCenter)

    Call GRD_SetHeader(grd_top10Projects, mo_top10ProjectsInfo, Array(la_ColumnsX))
    mo_top10ProjectsInfo.gTitle = GetLabel("grd_top10Projects_Title", "#Top 10 projects view")

    With grd_top10Projects
        .MergeCol(1) = True
        .MergeCol(2) = True
        .RowHeight(0) = 900
        .WordWrap = True
        .ForeColor = vbBlack
    End With

    ReDim la_ColumnsX(17) As Variant
    
    la_ColumnsX(0) = Array("SP_CAPKEY", "SP_CapKey", 0, "SP_CapKey")
    la_ColumnsX(1) = Array("BMK_DESC", GetLabel("p_market", "#Market"), 1000, "BMK_Desc", flexAlignCenterCenter)
    la_ColumnsX(2) = Array("CT_DESC", GetLabel("p_country", "#Country"), 1000, "CT_Desc", flexAlignCenterCenter)
    la_ColumnsX(3) = Array("SP_SAFlag", GetLabel("p_SP_SAFlag", "#SP_SAFlag"), 900, "SP_SAFlag", flexAlignCenterCenter)
    la_ColumnsX(4) = Array("SS_DESC", GetLabel("p_SS_desc", "#SS_desc"), 1250, "SS_desc", flexAlignCenterCenter)
    la_ColumnsX(5) = Array("SP_DESC", GetLabel("p_SP_Desc", "#SP_Desc"), 1250, "SP_Desc", flexAlignCenterCenter)
    la_ColumnsX(6) = Array("SP_SIZE", GetLabel("p_SP_Size", "#Prj. volume"), 1000, "SP_Size", flexAlignCenterCenter, "##,##0")
    la_ColumnsX(7) = Array("SolutionLine", GetLabel("p_SolutionLine", "#Main solustion lines"), 450, "SolutionLine", flexAlignCenterCenter, "##,##0")
    la_ColumnsX(8) = Array("ABPEPrdVol", GetLabel("p_ABPEPrdVol", "#ABPE vol."), 800, "ABPEPrdVol", flexAlignCenterCenter, "##,##0")
    la_ColumnsX(9) = Array("ASPrdVol", GetLabel("p_ASPrdVol", "#ABPE AS Dummy vol."), 800, "ASPrdVol", flexAlignCenterCenter, "##,##0")
    la_ColumnsX(10) = Array("SOMVol", GetLabel("p_SOMVol", "#Quoted vol."), 800, "SOMVol", flexAlignCenterCenter, "##,##0")
    la_ColumnsX(11) = Array("ProjectValue", GetLabel("p_Quoted_USD", "#Quoted value (USD)"), 900, "SQD_Value_USD", flexAlignCenterCenter, "##,##0")
    la_ColumnsX(12) = Array("SR_NAME", GetLabel("p_SR_Name", "#SR_Name"), 900, "SR_Name", flexAlignCenterCenter)
    la_ColumnsX(13) = Array("Z_CREATION", GetLabel("p_Z_creation", "#Z_creation"), 900, "Z_creation", flexAlignCenterCenter)
    la_ColumnsX(14) = Array("Z_last_upd", GetLabel("p_Z_last_upd", "#Z_last_upd"), 900, "Z_last_upd", flexAlignCenterCenter)
    la_ColumnsX(15) = Array("LastUpdDays", GetLabel("p_upd_days", "#Days"), 400, "Z_LastDays", flexAlignCenterCenter, "####0")
    la_ColumnsX(16) = Array("ProjectComment", GetLabel("p_SP_Comment", "#Comment"), 900, "SP_Comment", flexAlignCenterCenter)
    la_ColumnsX(17) = Array("AMCProjectNum", GetLabel("p_AMC_PrjNum", "#AMC Prj. Nb."), 1200, "AMCProjectNumber", flexAlignCenterCenter)

    Call GRD_SetHeader(grd_top10ProjectsE, mo_top10ProjectsEInfo, Array(la_ColumnsX))
    mo_top10ProjectsEInfo.gTitle = GetLabel("grd_top10ProjectsE_Title", "#Top 10 projects executive view")

    With grd_top10ProjectsE
        .MergeCol(1) = True
        .MergeCol(2) = True
        .RowHeight(0) = 900
        .WordWrap = True
        .ForeColor = vbBlack
    End With
    
    

    Call GRD_SetHeader(grd_visits2, mo_Visits2Info, _
        Array(Array(Array("BMK_Code", "BMK_Code", 0), Array("CT_Code", "CT_Code", 0), Array("BMK_Desc", GetLabel("p_market", "#Market"), 800, "BMK_Desc", flexAlignCenterCenter), _
                    Array("CT_Desc", GetLabel("p_country", "#Country"), 1000, "CT_Desc", flexAlignCenterCenter), Array("SR_Code", "SR_Code", 0), Array("SR_Name", GetLabel("p_rep", "#Sales Rep"), 1600, "SR_Name", flexAlignCenterCenter), _
                    Array("TotalCount", GetLabel("p_totalVisits", "#Total Nr. of Visits"), 1600, "", flexAlignCenterCenter), Array("VeryImportantCount", GetLabel("p_veryImportant", "#Very Important Customers"), 1200, "", flexAlignCenterCenter), _
                    Array("ImportantCount", GetLabel("p_Important", "#Important Customers"), 1200, "", flexAlignCenterCenter), Array("", GetLabel("p_TotalPerc", "#Very Important/Important % of Total"), 1600, "", flexAlignCenterCenter)) _
            ))
    With grd_visits2
        .MergeCol(2) = True
        .MergeCol(3) = True
        .RowHeight(0) = 1000
        .WordWrap = True
        .ForeColor = vbBlack
    End With


    chk_PS2_Grouping(0).Value = vbChecked
    chk_PS2_Grouping(1).Value = vbUnchecked
    
    chk_visits2_Grouping(0).Value = vbChecked
    chk_visits2_Grouping(1).Value = vbUnchecked
    
    Fill_Views
    
    ' Create the check boxes
    Dim li_i As Integer
    For li_i = 0 To 7
    ' Only the first is created !
        If li_i <> 0 Then
            Load chk_GridToRun(li_i)
            chk_GridToRun(li_i).Top = chk_GridToRun(li_i - 1).Top + 250
            chk_GridToRun(li_i).Visible = True
            chk_GridToRun(li_i).Container = Fra_DisplayReport
        End If
            
        chk_GridToRun(li_i).Caption = lbl_Title(li_i).Caption
        chk_GridToRun(li_i).Value = 1
    Next li_i

    Dim ll_Index As Long
    For ll_Index = 0 To 7
      Call InitTab(ll_Index)
    Next
    

    If check_authorization Then
        load_combo_trw
        If cb_trw.Count > 0 Then
        Set cb_trw.SelectedItem = cb_trw.ComboItems(1)
        End If
        

        load_treeview (ECapReportingTreeview.creMarket)
        Level_selected = 0
        tab_selected = 1
        reinit_display

        'annee.Clear
        Mois.Clear

       Call cbo_DR_Month.Clear

       Call Mois.AddItem(Array(1, GetLabel("January", "#January")))
       Call Mois.AddItem(Array(2, GetLabel("February", "#February")))
       Call Mois.AddItem(Array(3, GetLabel("March", "#March")))
       Call Mois.AddItem(Array(4, GetLabel("April", "#April")))
       Call Mois.AddItem(Array(5, GetLabel("May", "#May")))
       Call Mois.AddItem(Array(6, GetLabel("June", "#June")))
       Call Mois.AddItem(Array(7, GetLabel("July", "#July")))
       Call Mois.AddItem(Array(8, GetLabel("August", "#August")))
       Call Mois.AddItem(Array(9, GetLabel("September", "#September")))
       Call Mois.AddItem(Array(10, GetLabel("October", "#October")))
       Call Mois.AddItem(Array(11, GetLabel("November", "#November")))
       Call Mois.AddItem(Array(12, GetLabel("December", "#December")))
       Call Mois.AddItem(Array(13, ""), True)
       Call Mois.AddItem(Array(14, GetLabel("Quarter_1", "#Quarter 1")))
       Call Mois.AddItem(Array(15, GetLabel("Quarter_2", "#Quarter 2")))
       Call Mois.AddItem(Array(16, GetLabel("Quarter_3", "#Quarter 3")))
       Call Mois.AddItem(Array(17, GetLabel("Quarter_4", "#Quarter 4")))

       Call cbo_DR_Month.AddItem(Array("01", GetLabel("January", "#January")))
       Call cbo_DR_Month.AddItem(Array("02", GetLabel("February", "#February")))
       Call cbo_DR_Month.AddItem(Array("03", GetLabel("March", "#March")))
       Call cbo_DR_Month.AddItem(Array("04", GetLabel("April", "#April")))
       Call cbo_DR_Month.AddItem(Array("05", GetLabel("May", "#May")))
       Call cbo_DR_Month.AddItem(Array("06", GetLabel("June", "#June")))
       Call cbo_DR_Month.AddItem(Array("07", GetLabel("July", "#July")))
       Call cbo_DR_Month.AddItem(Array("08", GetLabel("August", "#August")))
       Call cbo_DR_Month.AddItem(Array("09", GetLabel("September", "#September")))
       Call cbo_DR_Month.AddItem(Array("10", GetLabel("October", "#October")))
       Call cbo_DR_Month.AddItem(Array("11", GetLabel("November", "#November")))
       Call cbo_DR_Month.AddItem(Array("12", GetLabel("December", "#December")))


       Call annee.AddItem("", True)
       For i = 2002 To Year(Now)
           Call annee.AddItem(Array(i - 2001, i))
           Call cbo_DR_Year.AddItem(Array(i, i))
       Next i
       Call annee.AddItem(Array(i - 2001, i), False)

       tab_prd.Tabs.Item(4).Selected = True

       old_cal1 = cal1.date_courte
       old_cal2 = cal2.date_courte
    End If
    
    opt_excReps(1).Value = True
    
    fr_CMD.Visible = True
    fr_Filter.Visible = True
    Fra_DisplayReport.Visible = True

    ' Get the budget raz flag for FP
    Dim lCurs As Long
    Dim ls_IT_USERS As String
    lCurs = OpenSQLSafe(p_da, C_CONFIG_REQ)
    mFPIndBdg = (p_da.GetFields(lCurs, "ID_Value") = "yes")
    ml_ActivePrj = p_da.GetFields(lCurs, "PRJ_ACTIVE")
    ls_IT_USERS = p_da.GetFields(lCurs, "IT_USERS")
    ml_VISIT_X1 = p_da.GetFields(lCurs, "VISIT_X1")
    ml_TOP10DAYS_OK = p_da.GetFields(lCurs, "TOP10DAYS_OK")
    p_da.Close (lCurs)
    
    ' check if to display focus product button
    Dim lsa_users() As String
    lsa_users = Split(ls_IT_USERS, ",")
    btn_FocusProd.Visible = False
    For i = LBound(lsa_users) To UBound(lsa_users)
        If lsa_users(i) = ml_U_Code Then
            btn_FocusProd.Visible = True
            Exit For
        End If
    Next
    
    mb_Initializing = False

    
    Exit Function

ErrorHandler:
    If lCurs > 0 Then
        Call p_da.Close(lCurs)
        lCurs = 0
    End If
    Call ErrorHandler(Extender.Name & ".Init_control")

End Function




Private Sub btn_Cancel_Click()
On Error GoTo ErrorHandler
    mb_Cancel = True
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".btn_Cancel_Click")
End Sub

Private Sub btn_DiplayQuery_Click()
On Error GoTo ErrorHandler
    btn_DiplayQuery.Enabled = False

    Select Case TabStrip1.SelectedItem.Key
        Case "QUERY"
            Call Process_Query
        Case "VISIT"
            Call Process_Visit
        Case "VISIT2"
            If Not frm_visits2_Grouping.Visible And (Not tv1.SelectedItem Is Nothing) Then
                If tv1.SelectedItem.Tag.ml_Level = tv1.Levels - 1 Or tv1.SelectedItem.Tag.ml_Level = 0 Then
                    chk_visits2_Grouping(0).Value = vbChecked
                    chk_visits2_Grouping(1).Value = vbUnchecked
                ElseIf tv1.SelectedItem.Tag.ml_Level = tv1.Levels - 2 Then
                    chk_visits2_Grouping(0).Value = vbChecked
                    chk_visits2_Grouping(1).Value = vbChecked
                End If
            End If
            Call Process_Visit2
        Case "PROJ"
            Call Process_Project((tbs_ProjectType.SelectedItem.Index - 1) * 2 + tbs_project.SelectedItem.Index - 1)
        Case "SALES"
            Select Case tbs_sales.SelectedItem.Key
            Case "ALL"
                Call Process_Sales
            Case "MSA"
                Call Process_Sales_MSA
            End Select
        Case "SALES_REP"
            If Not cb_trw.SelectedItem Is Nothing Then
              Call reinit_sales_by_rep(cb_trw.SelectedItem.GetData(0), Level_selected, True)
            End If
        Case "TOP10PROJ"
            Call Process_Top10Project
        Case "TOP10PROJE"
            Call Process_Top10ProjectE
'        Case "STATUSPROJ"
'            Call Process_StatusProjects
        Case "STATUSPROJ2"
            If Not frm_PS2_Grouping.Visible And (Not tv1.SelectedItem Is Nothing) Then
                If tv1.SelectedItem.Tag.ml_Level = tv1.Levels - 1 Or tv1.SelectedItem.Tag.ml_Level = 0 Then
                    chk_PS2_Grouping(0).Value = vbChecked
                    chk_PS2_Grouping(1).Value = vbUnchecked
                ElseIf tv1.SelectedItem.Tag.ml_Level = tv1.Levels - 2 Then
                    chk_PS2_Grouping(0).Value = vbChecked
                    chk_PS2_Grouping(1).Value = vbChecked
                End If
            End If
            Call Process_StatusProjects2
        Case "STATUSPROJ3"
            Call Process_StatusProjects3
    End Select
    btn_DiplayQuery.Enabled = True
    Exit Sub
ErrorHandler:
    btn_DiplayQuery.Enabled = True
    Call ErrorMessage(Extender.Name & ".btn_DiplayQuery_Click")
End Sub

Private Sub btn_FocusProd_Click()
On Error GoTo ErrorHandler
    Call ShowFocusprodScreen
    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".btn_FocusProd_Click")
End Sub

Private Sub btn_RefreshReport_Click()
On Error GoTo ErrorHandler
    Call display_report_Click
    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".btn_RefreshReport_Click")
End Sub



Private Sub btn_sales_doPrint_Click()
On Error GoTo ErrorHandler
    frm_sales_PDF.Visible = False
    
    ' do the export to pdf
    
    Select Case tbs_sales.SelectedItem.Key
    Case "ALL"
        Call Process_Sales_PDF_Excel("", 15)
    Case "MSA"
        Call Process_Sales_PDF_Excel("MSA", 15)
    End Select

    fr_CMD.Enabled = True
    fr_Filter.Enabled = True
    tbs_sales.Enabled = True

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

Private Sub btn_sales_quitPDF_Click()
On Error GoTo ErrorHandler
    frm_sales_PDF.Visible = False
    fr_CMD.Enabled = True
    fr_Filter.Enabled = True
    tbs_sales.Enabled = True
    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".btn_sales_quitPDF_Click")
End Sub

Private Sub cbo_salesCurrency_ComboItemSelected()
On Error GoTo ErrorHandler
    If mb_Initializing Then Exit Sub
    Call reinit_sales_by_rep(cb_trw.SelectedItem.GetData(0), Level_selected, False)
    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".cbo_salesCurrency_ComboItemSelected")
End Sub

Private Sub cbo_salesDataView_ComboItemSelected()
On Error GoTo ErrorHandler
    If mb_Initializing Then Exit Sub
    Call reinit_sales_by_rep(cb_trw.SelectedItem.GetData(0), Level_selected, False)
    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".cbo_salesDataView_ComboItemSelected")
End Sub

Private Sub cbo_salesYear_ComboItemSelected()
On Error GoTo ErrorHandler
    If mb_Initializing Then Exit Sub
    Call reinit_sales_by_rep(cb_trw.SelectedItem.GetData(0), Level_selected, False)
    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".cbo_salesYear_ComboItemSelected")
End Sub

Private Sub chk_sales_clgMetal_Click()
On Error GoTo ErrorHandler
    Call opt_salesOptions_Click(0)
    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".btn_sales_quitPDF_Click")
End Sub


Private Sub grd_sales_DblClick()
On Error GoTo ErrorHandler
    Call ShowSalesDetailForm("", tbs_sales.SelectedItem.Caption, grd_Sales.TextMatrix(grd_Sales.Row, 0), grd_Sales.TextMatrix(grd_Sales.Row, 1))
    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".grd_sales_DblClick")
End Sub

Private Sub grd_sales_MSA_DblClick()
On Error GoTo ErrorHandler
    Call ShowSalesDetailForm("MSA", tbs_sales.SelectedItem.Caption, grd_sales_MSA.TextMatrix(grd_sales_MSA.Row, 0), grd_sales_MSA.TextMatrix(grd_sales_MSA.Row, 1))
    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".grd_sales_MSA_DblClick")
End Sub

Private Sub ShowSalesDetailForm(ByVal as_MSA As String, ByVal ls_MSA_Desc As String, ByVal as_catDef As String, ByVal as_dataDef As String)
On Error GoTo ErrorHandler
    'If Level_selected >= 3 Then Exit Sub
    
    Dim lsa_data() As String
    Dim lsa_cat() As String
    lsa_data = Split(as_dataDef, " ", , vbTextCompare)
    Dim ll_maxInd As Long
    ll_maxInd = UBound(lsa_data)
    If ll_maxInd < 2 Then Exit Sub
    
    If Not isNumeric(lsa_data(ll_maxInd)) Then Exit Sub
    
    lsa_cat = Split(as_catDef, "-", , vbTextCompare)
    
    Dim ls_CG_code As String, ls_metal As String
    
    Select Case UCase(Trim(lsa_cat(0)))
        Case "CEILINGS"
            ls_CG_code = "'C001'"
        Case "GRIDS"
            ls_CG_code = "'C002'"
        Case "OTHERS"
            ls_CG_code = "NULL"
        Case Else
            Debug.Assert (False)
            ls_CG_code = "NULL"
    End Select
    
    
    If UBound(lsa_cat) >= 1 Then
        If InStr(1, lsa_cat(1), "Non", vbTextCompare) > 1 Then
            ls_metal = "''"
        Else
            ls_metal = "'X'"
        End If
    Else
        ls_metal = "NULL"
    End If
    
    
    Dim ll_Year As Long
    Dim ls_UOM As String
    ll_Year = lsa_data(ll_maxInd)
    ls_UOM = lsa_data(ll_maxInd - 1)

    Call LockScreen(True)

    If mo_salesDetFrm Is Nothing Then
        Set mo_salesDetFrm = New capdly_salesDet
        Set mo_salesDetFrm.ArmDb = p_da
        mo_salesDetFrm.ScreenLabels = mc_ScreenLabels
        mo_salesDetFrm.Language_Code = ms_Language_Code
        
        Call mo_salesDetFrm.Load_A_Com
        Call mo_salesDetFrm.Init_control
        mo_salesDetFrm.U_Code = ml_U_Code
        
    End If
    mo_salesDetFrm.Level_selected = Level_selected
    mo_salesDetFrm.TVFilterDesc = tv1.SelectedItem.Text
    mo_salesDetFrm.ReportDesc = ls_MSA_Desc & " (" & as_catDef & ", " & lsa_data(0) & " " & ls_UOM & ")"
    
    mo_salesDetFrm.Left = frm_projects.Left + tbs_ProjectType.Left
    mo_salesDetFrm.Width = tbs_ProjectType.Width
    mo_salesDetFrm.Top = 4755
    mo_salesDetFrm.Height = 5580
    
    If UCase(lsa_data(0)) = "GSV" Then
        ' in this case we need change currency into UOM
        Select Case ls_CG_code
            Case "'C001'"
                ls_UOM = "M2"
            Case "'C002'"
                ls_UOM = "LM"
            Case Else
                ls_UOM = "NULL"
        End Select
        
    End If
    
    Call LockScreen(False)
    Call mo_salesDetFrm.Run(cb_trw.SelectedItem.GetData(0), as_MSA, UCase(lsa_data(0)), ll_Year, ls_CG_code, ls_UOM, ls_metal)

    Call mo_salesDetFrm.Unload_A_Com
    Set mo_salesDetFrm.ArmDb = Nothing
    Call Unload(mo_salesDetFrm)
    Set mo_salesDetFrm = Nothing
    
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".ShowSalesDetailForm")
End Sub

Private Sub img_ps2Max_Click()
    ' unhide all non total lines
    grd_StatusProjects2.ColWidth(3) = ml_ps2CounryColWidth
    grd_StatusProjects2.ColWidth(5) = ml_ps2SalesRepColWidth
    Dim ll_idx As Long
    For ll_idx = grd_StatusProjects2.FixedRows To grd_StatusProjects2.Rows - 1
        If grd_StatusProjects2.TextMatrix(ll_idx, 1) <> "" Or grd_StatusProjects2.TextMatrix(ll_idx, 4) <> "" Then
            grd_StatusProjects2.RowHeight(ll_idx) = ml_ps2RowHeight
        End If
    Next
    img_ps2Min.Visible = True
    img_ps2Max.Visible = False
End Sub

Private Sub img_ps2Min_Click()
    ' hide all non total lines
    ' bckup width and rowheight
    ml_ps2CounryColWidth = grd_StatusProjects2.ColWidth(3)
    ml_ps2SalesRepColWidth = grd_StatusProjects2.ColWidth(5)
    ml_ps2RowHeight = grd_StatusProjects2.RowHeight(grd_StatusProjects2.Rows - 1)
    
    grd_StatusProjects2.ColWidth(3) = 0
    grd_StatusProjects2.ColWidth(5) = 0
    
    Dim ll_idx As Long
    For ll_idx = grd_StatusProjects2.FixedRows To grd_StatusProjects2.Rows - 1
        If grd_StatusProjects2.TextMatrix(ll_idx, 1) <> "" Or grd_StatusProjects2.TextMatrix(ll_idx, 4) <> "" Then
            grd_StatusProjects2.RowHeight(ll_idx) = 0
        End If
    Next
    img_ps2Min.Visible = False
    img_ps2Max.Visible = True
End Sub

Private Sub img_ps3Max_Click()
    ' unhide all non total lines
    grd_StatusProjects3.ColWidth(3) = ml_ps3CounryColWidth
    Dim ll_idx As Long
    For ll_idx = grd_StatusProjects3.FixedRows To grd_StatusProjects3.Rows - 1
        If grd_StatusProjects3.TextMatrix(ll_idx, 1) <> "" Then
            grd_StatusProjects3.RowHeight(ll_idx) = ml_ps3RowHeight
        End If
    Next
    img_ps3Min.Visible = True
    img_ps3Max.Visible = False
End Sub

Private Sub img_ps3Min_Click()
    ' hide all non total lines
    ' bckup width and rowheight
    ml_ps3CounryColWidth = grd_StatusProjects3.ColWidth(3)
    ml_ps3RowHeight = grd_StatusProjects3.RowHeight(grd_StatusProjects3.Rows - 1)
    
    grd_StatusProjects3.ColWidth(3) = 0
    
    Dim ll_idx As Long
    For ll_idx = grd_StatusProjects3.FixedRows To grd_StatusProjects3.Rows - 1
        If grd_StatusProjects3.TextMatrix(ll_idx, 1) <> "" Then
            grd_StatusProjects3.RowHeight(ll_idx) = 0
        End If
    Next
    img_ps3Min.Visible = False
    img_ps3Max.Visible = True
End Sub

Private Sub img_psMax_Click()
    ' unhide all non total lines
    grd_StatusProjects.ColWidth(3) = ml_psCounryColWidth
    Dim ll_idx As Long
    For ll_idx = grd_StatusProjects.FixedRows To grd_StatusProjects.Rows - 1
        If grd_StatusProjects.TextMatrix(ll_idx, 1) <> "" Then
            grd_StatusProjects.RowHeight(ll_idx) = ml_psRowHeight
        End If
    Next
    img_psMin.Visible = True
    img_psMax.Visible = False
End Sub

Private Sub img_psMin_Click()
    ' hide all non total lines
    ' bckup width and rowheight
    ml_psCounryColWidth = grd_StatusProjects.ColWidth(3)
    ml_psRowHeight = grd_StatusProjects.RowHeight(grd_StatusProjects.Rows - 1)
    
    grd_StatusProjects.ColWidth(3) = 0
    
    Dim ll_idx As Long
    For ll_idx = grd_StatusProjects.FixedRows To grd_StatusProjects.Rows - 1
        If grd_StatusProjects.TextMatrix(ll_idx, 1) <> "" Then
            grd_StatusProjects.RowHeight(ll_idx) = 0
        End If
    Next
    img_psMin.Visible = False
    img_psMax.Visible = True
End Sub

Private Sub img_visits2Max_Click()
    ' unhide all non total lines
    grd_visits2.ColWidth(3) = ml_visits2CounryColWidth
    grd_visits2.ColWidth(5) = ml_visits2SalesRepColWidth
    Dim ll_idx As Long
    For ll_idx = grd_visits2.FixedRows To grd_visits2.Rows - 1
        If grd_visits2.TextMatrix(ll_idx, 1) <> "" Or grd_visits2.TextMatrix(ll_idx, 4) <> "" Then
            grd_visits2.RowHeight(ll_idx) = ml_visits2RowHeight
        End If
    Next
    img_visits2Min.Visible = True
    img_visits2Max.Visible = False
End Sub

Private Sub img_visits2Min_Click()
    ' hide all non total lines
    ' bckup width and rowheight
    ml_visits2CounryColWidth = grd_visits2.ColWidth(3)
    ml_visits2SalesRepColWidth = grd_visits2.ColWidth(5)
    ml_visits2RowHeight = grd_visits2.RowHeight(grd_visits2.Rows - 1)
    
    grd_visits2.ColWidth(3) = 0
    grd_visits2.ColWidth(5) = 0
    
    Dim ll_idx As Long
    For ll_idx = grd_visits2.FixedRows To grd_visits2.Rows - 1
        If grd_visits2.TextMatrix(ll_idx, 1) <> "" Or grd_visits2.TextMatrix(ll_idx, 4) <> "" Then
            grd_visits2.RowHeight(ll_idx) = 0
        End If
    Next
    img_visits2Min.Visible = False
    img_visits2Max.Visible = True
End Sub

Private Sub mo_projDetFrm_ReplacePlaceholders(as_str As String)
    as_str = ReplaceHolders(as_str)
End Sub

Private Sub mo_salesDetFrm_ReplacePlaceholders(as_str As String)
    as_str = ReplaceHolders(as_str)
End Sub

Private Sub opt_excReps_Click(Index As Integer)
    Call cb_trw_ComboItemSelected
End Sub

Private Sub cb_trw_ComboItemSelected()
On Error GoTo ErrorHandler

    If Not cb_trw.SelectedItem Is Nothing Then
        reinit_display
        Select Case cb_trw.SelectedItem.GetData(0)
            Case 1:
                load_treeview ECapReportingTreeview.creMarket
            Case 2:
                load_treeview ECapReportingTreeview.creArea
            Case 3:
                load_treeview ECapReportingTreeview.creMarketRep
            Case 4:
                load_treeview ECapReportingTreeview.creAreaRep
            Case 5:
                load_treeview ECapReportingTreeview.creMarketCust
        End Select
    End If
    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".cb_trw_ComboItemSelected")
End Sub


Private Sub chk_YTD_Click()
On Error GoTo ErrorHandler

    reinit_display

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


Private Sub cmdQuit_Click()
On Error GoTo ErrorHandler
    
    RaiseEvent reportquit

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

Private Function Process_Report() As Boolean
On Error GoTo ErrorHandler

    Dim ls_Text As String
    Dim ls_req  As String

    mb_Cancel = False
    Process_Report = False

    ' Apply YTD if a quarter is selected
    If Not Mois.SelectedItem Is Nothing Then
        If Mois.SelectedItem.Key >= 14 Then
            chk_YTD.Value = 1
        End If
    End If

    fr_report.Visible = False
    fr_report.Refresh
    'Screen.MousePointer = vbHourglass
    
    ' Minimize the grid if there is one maximize
    If mia_WhichGridIsMax(0) <> -1 Then
        G_popup mia_WhichGridIsMax(0), ""
    End If
            
    Dim ll_Index As Long
    For ll_Index = 0 To 7
      Call InitTab(ll_Index)
    Next
    
    If Not CheckReportAvailable() Then
        Exit Function
    End If
    
    ' Check the validity of the user's selection
    If Len(cal1.date_courte) <> 10 Then
        MsgBox MsgText(1500, ms_Language_Code, "#Enter Starting Date for the report please")
        GoTo fin
    End If
    If Len(cal2.date_courte) <> 10 Then
        MsgBox MsgText(1501, ms_Language_Code, "#Enter End Date for the report please")
        GoTo fin
    End If
    If annee.Text = "" And Mois.Text <> "" Then
        MsgBox MsgText(1502, ms_Language_Code, "#You have selected a budget month/quarter. You need to indicate the budget year to use")
        GoTo fin
    End If
    If chk_YTD And (annee.Text = "" Or Mois.Text = "") Then
        MsgBox MsgText(1503, ms_Language_Code, "#To use to YTD function, you must select one year and one month/quarter")
        GoTo fin
    End If
        
    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        GoTo fin
    End If
              
        
    Fra_Processing.Visible = True
    Fra_DisplayReport.Enabled = False
    fr_CMD.Enabled = False
    fr_Filter.Enabled = False
    fr_report.Enabled = False
    
        
    current_displayed_node = tv1.SelectedItem.FullPath
    current_cal1 = cal1.date_courte
    current_cal2 = cal2.date_courte
    
    Dim lUseBudget As Boolean
        
    ' Check which report to cal
    If chk_YTD Then ' Here it's the year to date
        If Mois.SelectedItem.Key < 13 Then
            ReDim ms_MsgInfo(5, 1)
            ms_MsgInfo(0, 0) = "$TV1$"
            ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
            ms_MsgInfo(1, 0) = "$TAB_PRD$"
            ms_MsgInfo(1, 1) = tab_prd.SelectedItem.Caption
            ms_MsgInfo(2, 0) = "$FROM$"
            ms_MsgInfo(2, 1) = cal1.date_courte
            ms_MsgInfo(3, 0) = "$TO$"
            ms_MsgInfo(3, 1) = cal2.date_courte
            ms_MsgInfo(4, 0) = "$YEAR$"
            ms_MsgInfo(4, 1) = annee.Text
            ms_MsgInfo(5, 0) = "$MONTH$"
            ms_MsgInfo(5, 1) = Mois.SelectedItem.Key
            fr_report.Caption = MsgText(1505, ms_Language_Code, "#$TV1$  $TAB_PRD$ From $FROM$ to $TO$  -  Budget from 01/01/$YEAR$ to 31/$MONTH$/$YEAR$", ms_MsgInfo)
        Else
            ReDim ms_MsgInfo(5, 1)
            ms_MsgInfo(0, 0) = "$TV1$"
            ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
            ms_MsgInfo(1, 0) = "$TAB_PRD$"
            ms_MsgInfo(1, 1) = tab_prd.SelectedItem.Caption
            ms_MsgInfo(2, 0) = "$FROM$"
            ms_MsgInfo(2, 1) = cal1.date_courte
            ms_MsgInfo(3, 0) = "$TO$"
            ms_MsgInfo(3, 1) = cal2.date_courte
            ms_MsgInfo(4, 0) = "$YEAR$"
            ms_MsgInfo(4, 1) = annee.Text
            ms_MsgInfo(5, 0) = "$QUARTER$"
            ms_MsgInfo(5, 1) = Mois.SelectedItem.Key - 13

            fr_report.Caption = MsgText(1506, ms_Language_Code, "#$TV1$  $TAB_PRD$ From $FROM$ to $TO$  -  Budget for quarter $QUARTER$ / $YEAR$", ms_MsgInfo)
        End If
        lUseBudget = True
    Else
        If annee.Text = "" And Mois.Text = "" Then  ' Here it's the report without budget
            ReDim ms_MsgInfo(3, 1)
            ms_MsgInfo(0, 0) = "$TV1$"
            ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
            ms_MsgInfo(1, 0) = "$TAB_PRD$"
            ms_MsgInfo(1, 1) = tab_prd.SelectedItem.Caption
            ms_MsgInfo(2, 0) = "$FROM$"
            ms_MsgInfo(2, 1) = cal1.date_courte
            ms_MsgInfo(3, 0) = "$TO$"
            ms_MsgInfo(3, 1) = cal2.date_courte
            fr_report.Caption = MsgText(1507, ms_Language_Code, "#$TV1$  $TAB_PRD$ From $FROM$ to $TO$", ms_MsgInfo)
            lUseBudget = False
        Else
            If annee.Text <> "" And Mois.Text = "" Then ' Here it's the report with a year budget
                ReDim ms_MsgInfo(4, 1)
                ms_MsgInfo(0, 0) = "$TV1$"
                ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
                ms_MsgInfo(1, 0) = "$TAB_PRD$"
                ms_MsgInfo(1, 1) = tab_prd.SelectedItem.Caption
                ms_MsgInfo(2, 0) = "$FROM$"
                ms_MsgInfo(2, 1) = cal1.date_courte
                ms_MsgInfo(3, 0) = "$TO$"
                ms_MsgInfo(3, 1) = cal2.date_courte
                ms_MsgInfo(4, 0) = "$YEAR$"
                ms_MsgInfo(4, 1) = annee.Text
                fr_report.Caption = MsgText(1508, ms_Language_Code, "#$TV1$  $TAB_PRD$ From $FROM$ to $TO$  -  Budget of year $YEAR$", ms_MsgInfo)
                lUseBudget = True
            Else
                ' Here it's the report with a month budget
                If Mois.SelectedItem.Key < 13 Then
                    ReDim ms_MsgInfo(5, 1)
                    ms_MsgInfo(0, 0) = "$TV1$"
                    ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
                    ms_MsgInfo(1, 0) = "$TAB_PRD$"
                    ms_MsgInfo(1, 1) = tab_prd.SelectedItem.Caption
                    ms_MsgInfo(2, 0) = "$FROM$"
                    ms_MsgInfo(2, 1) = cal1.date_courte
                    ms_MsgInfo(3, 0) = "$TO$"
                    ms_MsgInfo(3, 1) = cal2.date_courte
                    ms_MsgInfo(4, 0) = "$YEAR$"
                    ms_MsgInfo(4, 1) = annee.Text
                    ms_MsgInfo(5, 0) = "$MONTH$"
                    ms_MsgInfo(5, 1) = Mois.SelectedItem.Key
                    fr_report.Caption = MsgText(1509, ms_Language_Code, "#$TV1$  $TAB_PRD$ From $FROM$ to $TO$  -  Budget of $MONTH$ $YEAR$", ms_MsgInfo)
                Else
                    ReDim ms_MsgInfo(5, 1)
                    ms_MsgInfo(0, 0) = "$TV1$"
                    ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
                    ms_MsgInfo(1, 0) = "$TAB_PRD$"
                    ms_MsgInfo(1, 1) = tab_prd.SelectedItem.Caption
                    ms_MsgInfo(2, 0) = "$FROM$"
                    ms_MsgInfo(2, 1) = cal1.date_courte
                    ms_MsgInfo(3, 0) = "$TO$"
                    ms_MsgInfo(3, 1) = cal2.date_courte
                    ms_MsgInfo(4, 0) = "$YEAR$"
                    ms_MsgInfo(4, 1) = annee.Text
                    ms_MsgInfo(5, 0) = "$QUARTER$"
                    ms_MsgInfo(5, 1) = Mois.SelectedItem.Key - 13
        
                    fr_report.Caption = MsgText(1510, ms_Language_Code, "#$TV1$  $TAB_PRD$ From $FROM$ to $TO$  -  Budget for quarter $QUARTER$ / $YEAR$", ms_MsgInfo)
                End If
                lUseBudget = True
            End If
        End If
    End If
    
    Call Exec_Report(lUseBudget)
      
    ms_ToLog = ComputerName & SEP & gsuser & SEP & _
            Format(Date, "dd/mm/yyyy") & " " & Format(Time, "hh:mm:ss") & SEP & _
            "REPORTING" & SEP & _
            "FROM " & cal1.date_courte & " TO " & cal2.date_courte & SEP & _
            "BUDGET TO USE: YEAR = " & IIf(annee.Text <> "", annee.Text, "Nothing") & ", MONTH/QUARTER = " & IIf(Mois.Text <> "", Mois.Text, "Nothing") & ", YTD = " & IIf(chk_YTD, "True", "False") & SEP & _
            "TREEVIEW INFO: " & cb_trw.Text & SEP & _
            "TREEVIEW PATH: " & TreeviewPath & SEP & _
            "PRODUCT FILTER: " & tab_prd.SelectedItem.Caption & SEP & _
            "GRID TO RUN: "
            
                
    Dim li_i As Integer
    For li_i = 1 To lvw_Task.ListItems.Count
        ms_ToLog = ms_ToLog & lvw_Task.ListItems(li_i).Tag & ","
    Next li_i
    
    ms_ToLog = Mid(ms_ToLog, 1, Len(ms_ToLog) - 1)
    
    If mb_Cancel = False Then
        export_report.Visible = True
        btn_RefreshReport.Visible = True
        fr_report.Visible = True
        Fra_DisplayReport.Visible = False
    Else
        ms_ToLog = ms_ToLog & SEP & "CANCELED"
    End If
   
    
    Fra_Processing.Visible = False
    Fra_DisplayReport.Enabled = True
    fr_CMD.Enabled = True
    fr_Filter.Enabled = True
    fr_report.Enabled = True
    
    Screen.MousePointer = 0
    
    Process_Report = True
    Exit Function

fin:
    export_report.Visible = False
    btn_RefreshReport.Visible = False
    fr_report.Enabled = True
    fr_report.Visible = False
    
    Fra_Processing.Visible = False
    Fra_DisplayReport.Enabled = True
    fr_CMD.Enabled = True
    fr_Filter.Enabled = True
    
    
    Screen.MousePointer = 0
    Process_Report = False
    Exit Function

ErrorHandler:
    Call ErrorHandler(Extender.Name & ".Process_Report")
End Function

Private Sub Process_Query()
On Error GoTo ErrorHandler

    If cbo_Query.SelectedItem Is Nothing Then
        MsgBox MsgText(1512, ms_Language_Code, "#Please select a query to do")
        cbo_Query.SetFocus
        Exit Sub
    End If
    
    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        tv1.SetFocus
        Exit Sub
    End If
    
    Dim ls_Request As String
    ls_Request = cbo_Query.SelectedItem.GetData(3)
    
    ls_Request = ReplaceHolders(ls_Request)
    
    grd_Query.ClearGrid
    grd_Query.Requests = ls_Request
    
    grd_Query.FetchAll = (cbo_Query.SelectedItem.GetData(5) = "X")
    If grd_Query.Execute Then
        export_report.Visible = True
    Else
        MsgBox "An error occured during this query, please take a screenshot and contact IT support"
    End If
    
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".Process_Query")
End Sub

Private Sub Process_Visit()
On Error GoTo ErrorHandler
Const C_REQ_TOTAL As String = "EXEC Visit_GetCustomerVisitTotalCount '$language_code$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$, $A_Code$"
Const C_REQD As String = "EXEC Visit_GetCustomerVisitDetail '$language_code$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$, $A_Code$"
Const C_REQDF As String = "EXEC Visit_GetCustomerVisitDetail_fast '$language_code$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$, $A_Code$"
    
    If Not CheckReportAvailable() Then
        Exit Sub
    End If
    
    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        tv1.SetFocus
        Exit Sub
    End If
    
    Dim ls_Request As String
    ls_Request = ReplaceHolders(GetVisitTotalRequest(tbs_visitCTType.SelectedItem.Tag))
    ls_Request = Replace(ls_Request, "$A_Code$", tbs_visitCTType.SelectedItem.Tag, , , vbTextCompare)
    
    Dim ll_grdindex As Long
    ll_grdindex = tbs_visitCTType.SelectedItem.Index - 1
    
    Dim lo_grd As ArmGrid
    
    For Each lo_grd In grd_visitCounts
        lo_grd.Visible = False
    Next
    For Each lo_grd In grd_visitDetail
        lo_grd.Visible = False
    Next
    
    grd_visitCounts(ll_grdindex).ClearGrid
    grd_visitDetail(ll_grdindex).ClearGrid
    lbl_visitCalculation.Visible = True
    frm_visits.Visible = True
    
    ReDim ms_MsgInfo(1, 1)
    ms_MsgInfo(0, 0) = "$TV1$"
    ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
    ms_MsgInfo(1, 0) = "$TO$"
    ms_MsgInfo(1, 1) = cal2.date_courte
    frm_visits.Caption = MsgText(1511, ms_Language_Code, "#Visits $TV1$ until $TO$", ms_MsgInfo)
    
    lbl_visitCalculation.Caption = GetLabel("lbl_calcTotal", "#Calculating Totals ....")
    Call frm_visits.Refresh
    DoEvents
    
    grd_visitCounts(ll_grdindex).Requests = ls_Request
    If Not grd_visitCounts(ll_grdindex).Execute Then
        MsgBox "An error occured during this query, please take a screenshot and contact IT support"
    End If
    
    Dim ll_i As Long
    Dim ls_visitDesc As String
    Dim ls_currentDesc As String
    If tbs_visitCTType.SelectedItem.Tag = "NULL2" Then
        ls_visitDesc = GetLabel("g_visitNewDesc", "#$CP_DESC$ new customers visited in last $CP_DAYS$ days")
    Else
        ls_visitDesc = GetLabel("g_visitDesc", "#$CP_DESC$ customers visited in last $CP_DAYS$ days")
    End If
    For ll_i = 0 To grd_visitCounts(ll_grdindex).Rows - 1
        ls_currentDesc = Replace(ls_visitDesc, "$CP_DESC$", grd_visitCounts(ll_grdindex).Data(ll_i, "CP_DESC"), , , vbTextCompare)
        grd_visitCounts(ll_grdindex).Data(ll_i, "CP_DESC") = Replace(ls_currentDesc, "$CP_DAYS$", grd_visitCounts(ll_grdindex).Data(ll_i, "CP_DAYS"), , , vbTextCompare)
    Next
    
    ' modify title to put value in it
    grd_visitCounts(ll_grdindex).Title = Replace(GetLabel(grd_visitCounts(ll_grdindex).Tag & "_title", "#Count of visits for last $CP_DAYS$ days"), "$CP_DAYS$", ml_VISIT_X1, , , vbTextCompare)
    
    grd_visitCounts(ll_grdindex).Visible = True
    Call frm_visits.Refresh
    DoEvents
    
    Dim ll_cursor As Long
    ls_Request = ReplaceHolders(GetVisitTotalCountRequest(tbs_visitCTType.SelectedItem.Tag))
    ls_Request = Replace(ls_Request, "$A_Code$", tbs_visitCTType.SelectedItem.Tag, , , vbTextCompare)
    ll_cursor = OpenSQLSafe(p_da, ls_Request)
    
    
    Dim ll_total As Long
    ' LOOP the grid to update the colum 1
    
    For ll_i = 0 To grd_visitCounts(ll_grdindex).Rows - 1
        ll_total = 0
        If p_da.Find(ll_cursor, "CP_Code", grd_visitCounts(ll_grdindex).Data(ll_i, "CP_CODE")) >= 0 Then
            ll_total = p_da.GetFields(ll_cursor, "TOTAL")
        End If
        
        grd_visitCounts(ll_grdindex).Data(ll_i, "CP_TOTAL") = ll_total
        If ll_total = 0 Then
            grd_visitCounts(ll_grdindex).Data(ll_i, "CP_PERCENT") = ll_total
        Else
            grd_visitCounts(ll_grdindex).Data(ll_i, "CP_PERCENT") = grd_visitCounts(ll_grdindex).Data(ll_i, "CP_VISITS") / ll_total
        End If
    Next
    Call p_da.Close(ll_cursor)
    ll_cursor = 0
    
    lbl_visitCalculation.Caption = GetLabel("lbl_calcDetail", "#Calculating Detail ....")
    Call frm_visits.Refresh
    DoEvents

    ' load detail
    ls_Request = ReplaceHolders(GetVisitDetailRequest(tbs_visitCTType.SelectedItem.Tag, chk_allData.Value = vbChecked))
    ls_Request = Replace(ls_Request, "$A_Code$", tbs_visitCTType.SelectedItem.Tag, , , vbTextCompare)
    
    grd_visitDetail(ll_grdindex).Requests = ls_Request
    grd_visitDetail(ll_grdindex).FetchAll = (chk_allData.Value = vbUnchecked Or ll_grdindex = 2)
    
    If Not grd_visitDetail(ll_grdindex).Execute Then
        MsgBox "An error occured during this query, please take a screenshot and contact IT support"
'    Else
'        export_report.Visible = True
    End If
    grd_visitDetail(ll_grdindex).Visible = True
    lbl_visitCalculation.Caption = ""
    lbl_visitCalculation.Visible = False
    
    ml_visit_processed = ml_visit_processed Or (Choose(ll_grdindex + 1, 1, 2, 4))
    
    Exit Sub
ErrorHandler:
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
    End If
    Call ErrorHandler(Extender.Name & ".Process_Visit")
End Sub

Private Sub Process_Visit2()
On Error GoTo ErrorHandler
    Dim ls_req As String
    Dim ll_cursor As Long
    
    If Not CheckReportAvailable() Then
        Exit Sub
    End If

    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        tv1.SetFocus
        Exit Sub
    End If
    
    If chk_visits2_Grouping(0).Value = vbUnchecked And chk_visits2_Grouping(1).Value = vbUnchecked Then
        MsgBox MsgText(1516, ms_Language_Code, "#M1516 ... At least one grouping must be selected!")
        Exit Sub
    End If
    
    Call LockScreen(True)
    
    ReDim ms_MsgInfo(2, 1)
    ms_MsgInfo(0, 0) = "$TV1$"
    ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
    ms_MsgInfo(1, 0) = "$FROM$"
    ms_MsgInfo(1, 1) = cal1.date_courte
    ms_MsgInfo(2, 0) = "$TO$"
    ms_MsgInfo(2, 1) = cal2.date_courte
    
    frm_visits2.Visible = True
    frm_visits2.Caption = GetLabel(frm_visits2.Tag, "#Visits $TV1$ between $FROM$ and $TO$", ms_MsgInfo)
    
    grd_visits2.Visible = False
    frm_visits2_Grouping.Visible = False
    img_visits2Min.Visible = False
    img_visits2Max.Visible = False

    
    grd_visits2.Rows = grd_visits2.FixedRows               ' remove all data lines from grid
    grd_visits2.LeftCol = 6                                ' ensure visible part is at top left
    
    lbl_visits2Calculation.Visible = True
    
    lbl_visits2Calculation.Caption = GetLabel(lbl_visits2Calculation.Tag, "#Calculating Visits (summary) report")
    Call frm_statusProjects2.Refresh
    DoEvents
    
    Dim ll_totalDescCol As Long
    ll_totalDescCol = 3        ' Country col is containing total in listing row for market total data

    ls_req = GetVisitsGrpRequest()
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        ' manage country and sales rep columns
        If p_da.GetFields(ll_cursor, "SR_Code") = "" Then
            If grd_visits2.ColWidth(5) <> 0 Then
                ml_visits2SalesRepColWidth = 0
                grd_visits2.ColWidth(5) = 0
            End If
        Else
            If grd_visits2.ColWidth(5) = 0 Then
                ml_visits2SalesRepColWidth = IIf(ml_visits2SalesRepColWidth = 0, 1600, ml_visits2SalesRepColWidth)
                grd_visits2.ColWidth(5) = ml_visits2SalesRepColWidth
            End If
        End If
            
        If p_da.GetFields(ll_cursor, "CT_Code") = "" Then
            If grd_visits2.ColWidth(3) <> 0 Then
                ml_visits2CounryColWidth = 0
                grd_visits2.ColWidth(3) = 0
            End If
            ll_totalDescCol = 5     ' total is moved to Sales rep column
        Else
            If grd_visits2.ColWidth(3) = 0 Then
                ml_visits2CounryColWidth = IIf(ml_visits2CounryColWidth = 0, 1050, ml_visits2CounryColWidth)
                grd_visits2.ColWidth(3) = ml_visits2CounryColWidth
            End If
        End If
            
        ' fill the grid
        Call FillGridVisits(grd_visits2, ll_cursor, C_VISITS2_VERYIMPOR_COL, C_VISITS2_TOTAL_COL, C_VISITS2_TOTAL_PER_COL)
        Call p_da.Close(ll_cursor)
    End If
    
    export_report.Visible = True
    
    ' calculate totals
    Dim ll_col As Long, ll_Row As Long
    Dim ld_totalC As Double
    grd_visits2.Rows = grd_visits2.Rows + 1
    If Level_selected = 0 Then
        grd_visits2.TextMatrix(grd_visits2.Rows - 1, 2) = GetLabel("s_total", "#TOTAL")
        For ll_col = 6 To grd_visits2.Cols - 2
            ld_totalC = 0
            For ll_Row = grd_visits2.FixedRows To grd_visits2.Rows - 2
                If grd_visits2.TextMatrix(ll_Row, ll_col) <> "" Then
                    ld_totalC = ld_totalC + grd_visits2.TextMatrix(ll_Row, ll_col)
                End If
            Next
            grd_visits2.TextMatrix(grd_visits2.Rows - 1, ll_col) = FormatNumber(ld_totalC, 0)
        Next
        
        Call SetGridRowBackColor(grd_visits2, grd_visits2.Rows - 1, COLOR_GREY)
        Call SetGridRowForeColor(grd_visits2, grd_visits2.Rows - 1, vbRed)
        Call SetGridRowBold(grd_visits2, grd_visits2.Rows - 1)
    End If
    
    ' CALCULATE sub totals per market
    Dim ll_CurrentLine As Long
    Dim ll_curentRow As Long
    Dim ll_BMKstartLine As Long
    Dim ls_BMK_Code As String
    
    
    ll_CurrentLine = grd_visits2.FixedRows
    ll_BMKstartLine = -1
    ls_BMK_Code = ""
    While ll_CurrentLine <> grd_visits2.Rows
        If ls_BMK_Code <> grd_visits2.TextMatrix(ll_CurrentLine, 0) Then
            If ll_BMKstartLine <> -1 Then
                Debug.Assert (ls_BMK_Code <> "")
                ' process the lines between ll_BMKstartLine and ll_currentLine
                Call grd_visits2.AddItem(ls_BMK_Code, ll_CurrentLine)
                
                grd_visits2.TextMatrix(ll_CurrentLine, 2) = grd_visits2.TextMatrix(ll_BMKstartLine, 2)
                grd_visits2.TextMatrix(ll_CurrentLine, ll_totalDescCol) = GetLabel("s_total2", "#Total")
                
                Call SumLines(grd_visits2, ll_BMKstartLine, ll_CurrentLine - 1, 6, grd_visits2.Cols - 2)
                Call PercentVal(grd_visits2, ll_CurrentLine, CLng(grd_visits2.TextMatrix(ll_CurrentLine, C_VISITS2_VERYIMPOR_COL)) + CLng(grd_visits2.TextMatrix(ll_CurrentLine, C_VISITS2_IMPORTANT_COL)), C_VISITS2_TOTAL_PER_COL, CLng(grd_visits2.TextMatrix(ll_CurrentLine, C_VISITS2_TOTAL_COL)))
                
                Call SetGridRowBackColor(grd_visits2, ll_CurrentLine, COLOR_GREY2)
                Call SetGridRowForeColor(grd_visits2, ll_CurrentLine, vbBlue)
                Call SetGridRowBold(grd_visits2, ll_CurrentLine)

                
                ' move currentline to next line
                ll_CurrentLine = ll_CurrentLine + 1
            End If
            ll_BMKstartLine = ll_CurrentLine
            ls_BMK_Code = grd_visits2.TextMatrix(ll_CurrentLine, 0)
        End If
        
        ll_CurrentLine = ll_CurrentLine + 1
    Wend
    
    
    If Level_selected = 0 Then
        ' percent for total
        ll_curentRow = grd_visits2.Rows - 1
        Call PercentVal(grd_visits2, ll_curentRow, CLng(grd_visits2.TextMatrix(ll_curentRow, C_VISITS2_VERYIMPOR_COL)) + CLng(grd_visits2.TextMatrix(ll_curentRow, C_VISITS2_IMPORTANT_COL)), C_VISITS2_TOTAL_PER_COL, CLng(grd_visits2.TextMatrix(ll_curentRow, C_VISITS2_TOTAL_COL)))
    Else
        ' remove grand total line
        grd_visits2.Rows = grd_visits2.Rows - 1
        
    End If
    
    grd_visits2.Visible = True
    Call LockScreen(False)

    grd_visits2.Visible = True
    mb_visits2_processed = True
    
    ml_visits2RowHeight = IIf(ml_visits2RowHeight = 0, grd_visits2.RowHeight(grd_visits2.Rows - 1), ml_visits2RowHeight)
        
    Call img_visits2Max_Click

    Exit Sub
    
ErrorHandler:
    Call LockScreen(False)
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If

    Call ErrorHandler(Extender.Name & ".Process_Visit2")
End Sub


Private Function SqlDate(ByVal av_Data As Variant) As String
On Error GoTo errHandler

    SqlDate = "NULL"
    If IsNull(av_Data) Then av_Data = ""
    If (Trim(CStr(av_Data)) <> "") And (CStr(av_Data) <> "0") Then
        SqlDate = "'" & Format(av_Data, "yyyy-mm-dd") & "'"
    End If
    Exit Function
errHandler:
    Call ErrorHandler("SqlDate")
End Function
Private Sub Process_Top10Project()
On Error GoTo ErrorHandler
    Dim ls_req As String

    grd_top10Projects.Visible = False
    
    If Not CheckReportAvailable() Then
        Exit Sub
    End If

    
    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        tv1.SetFocus
        Exit Sub
    End If
    Call LockScreen(True)

    ReDim ms_MsgInfo(2, 1)
    ms_MsgInfo(0, 0) = "$TV1$"
    ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
    ms_MsgInfo(1, 0) = "$FROM$"
    ms_MsgInfo(1, 1) = cal1.date_courte
    ms_MsgInfo(2, 0) = "$TO$"
    ms_MsgInfo(2, 1) = cal2.date_courte
    frm_top10projects.Visible = True
    frm_top10projects.Caption = GetLabel(frm_top10projects.Tag, "#Top 10 projects $TV1$ between $FROM$ and $TO$", ms_MsgInfo)

    grd_top10Projects.Rows = grd_top10Projects.FixedRows        ' remove all data lines from grid
    grd_top10Projects.LeftCol = 3                                ' ensure visible part is at top left
    
    Call frm_top10projects.Refresh
    DoEvents

    ls_req = GetTop10ProjectRequest(cb_trw.SelectedItem.GetData(0), Level_selected)
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        Dim ll_cursor  As Long
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        If p_da.RowCount(ll_cursor) > 0 Then
            Call GRD_LoadData(grd_top10Projects, mo_top10ProjectsInfo, ll_cursor)
            Call GRD_addSUM(grd_top10Projects, mo_top10ProjectsInfo, ll_cursor, Array("SP_SIZE", "SolutionLine", "ABPEPrdVol", "ASPrdVol", "SOMVol", "ProjectValue"), "BMK_DESC")
            Call GRD_setColumnColor(grd_top10Projects, mo_top10ProjectsInfo, "LastUpdDays", ml_TOP10DAYS_OK, COLOR_WHITE, COLOR_RED)
            export_report.Visible = True
        Else
            export_report.Visible = False
        End If
        
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
        
    End If

    grd_top10Projects.Visible = True
    ml_top10project_processed = ml_top10project_processed Or Pow(2, 0)
    Call LockScreen(False)

    Exit Sub
ErrorHandler:
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If
    Call LockScreen(False)
    Call ErrorHandler(Extender.Name & ".Process_Top10Project")
End Sub

Private Sub Process_Top10ProjectE()
On Error GoTo ErrorHandler
    Dim ls_req As String

    grd_top10ProjectsE.Visible = False
    
    If Not CheckReportAvailable() Then
        Exit Sub
    End If

    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        tv1.SetFocus
        Exit Sub
    End If
    Call LockScreen(True)
    
    ReDim ms_MsgInfo(2, 1)
    ms_MsgInfo(0, 0) = "$TV1$"
    ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
    ms_MsgInfo(1, 0) = "$FROM$"
    ms_MsgInfo(1, 1) = cal1.date_courte
    ms_MsgInfo(2, 0) = "$TO$"
    ms_MsgInfo(2, 1) = cal2.date_courte
    frm_top10projectsE.Visible = True
    frm_top10projectsE.Caption = GetLabel(frm_top10projectsE.Tag, "#Top 10 projects executive $TV1$ between $FROM$ and $TO$", ms_MsgInfo)

    grd_top10ProjectsE.Rows = grd_top10Projects.FixedRows        ' remove all data lines from grid
    grd_top10ProjectsE.LeftCol = 3                               ' ensure visible part is at top left
    
    Call frm_top10projectsE.Refresh
    DoEvents
    
    ls_req = GetTop10ProjectRequest(cb_trw.SelectedItem.GetData(0), Level_selected)
    If ls_req <> "" Then
    
        ls_req = Replace(ls_req, "ProjectTop10", "ProjectTop10E", , , vbTextCompare)
        ls_req = ReplaceHolders(ls_req)
        Dim ll_cursor  As Long
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        If p_da.RowCount(ll_cursor) > 0 Then
            Call GRD_LoadData(grd_top10ProjectsE, mo_top10ProjectsEInfo, ll_cursor)
            Call GRD_addSUM(grd_top10ProjectsE, mo_top10ProjectsEInfo, ll_cursor, Array("SP_SIZE", "SolutionLine", "ABPEPrdVol", "ASPrdVol", "SOMVol", "ProjectValue"), "BMK_DESC")
            Call GRD_setColumnColor(grd_top10ProjectsE, mo_top10ProjectsEInfo, "LastUpdDays", ml_TOP10DAYS_OK, COLOR_WHITE, COLOR_RED)
            export_report.Visible = True
        Else
            export_report.Visible = False
        End If
        
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If

    grd_top10ProjectsE.Visible = True
    ml_top10projectE_processed = ml_top10projectE_processed Or Pow(2, 0)
    Call LockScreen(False)
    
    Exit Sub
ErrorHandler:
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If
    Call LockScreen(False)
    Call ErrorHandler(Extender.Name & ".Process_Top10ProjectE")
End Sub

Private Sub Process_Project(ByVal al_tab As Long)
On Error GoTo ErrorHandler
    
    Dim ls_req As String
    Dim ll_cursor  As Long
    Dim ll_CursorF As Long

    Dim lo_Grid As MSFlexGrid
    For Each lo_Grid In grd_project
        lo_Grid.Visible = False
    Next
    
    If Not CheckReportAvailable() Then
        Exit Sub
    End If
    
    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        tv1.SetFocus
        Exit Sub
    End If
    LockScreen (True)

    ReDim ms_MsgInfo(1, 1)
    ms_MsgInfo(0, 0) = "$TV1$"
    ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
    ms_MsgInfo(1, 0) = "$TO$"
    ms_MsgInfo(1, 1) = cal2.date_courte
    frm_projects.Visible = True
    frm_projects.Caption = GetLabel(frm_projects.Tag, "#Projects $TV1$  until $TO$", ms_MsgInfo)

    grd_project(al_tab).Rows = 1        ' clear grid
    grd_project(al_tab).LeftCol = grd_project(al_tab).FixedCols     ' ensure visible part is at top left

    frm_projectCalc.Visible = True
    
    lbl_projectCalculation.Caption = GetLabel(lbl_projectCalculation.Tag, "#Calculating Projects report ....")
    Call frm_projects.Refresh
    DoEvents
        
    ls_req = GetProjectRequest(cb_trw.SelectedItem.GetData(0), Level_selected, tbs_project.SelectedItem.Tag)
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        ls_req = Replace(ls_req, "$NOW$", SqlDate(Now()))
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        If p_da.RowCount(ll_cursor) > 0 Then
            Dim ll_StartCol  As Long
            Dim ll_ENDCol  As Long
            Dim ll_TOP10Col As Long
            
            ll_StartCol = GRD_GetColIndex(mo_projectInfo(al_tab), "START")
            ll_ENDCol = GRD_GetColIndex(mo_projectInfo(al_tab), "END")
            ll_TOP10Col = GRD_GetColIndex(mo_projectInfo(al_tab), "TOPTEN")
                
            Call GRD_LoadData(grd_project(al_tab), mo_projectInfo(al_tab), ll_cursor, COLOR_WHITE, COLOR_GREY, Array("GRP_DESC", "MONTH"), Array("ABPEPrdVol", "ASPrdVol", "SOMVol", "TotalPrdVol"))
            ll_CursorF = p_da.Filter(ll_cursor, "TOPTEN", "=", "Top 10", , False)
            If p_da.RowCount(ll_CursorF) > 0 Then
                Call GRD_addSUM(grd_project(al_tab), mo_projectInfo(al_tab), ll_CursorF, Array("STDProjects", "SAProjects", "ASProjects", "Volume", "SolutionLine", "TotalPrdVol", "ABPEPrdVol", "ASPrdVol", "SOMVol", "ProjectValue"), "GRP_DESC", Array("ABPEPrdVol", "ASPrdVol", "SOMVol", "TotalPrdVol"))
                ' fill START and END
                If ll_StartCol <> -1 Then grd_project(al_tab).TextMatrix(grd_project(al_tab).Rows - 1, mo_projectInfo(al_tab).Cols(ll_StartCol).Index) = GetColMin(ll_CursorF, mo_projectInfo(al_tab).Cols(ll_StartCol).DB_Name)
                If ll_ENDCol <> -1 Then grd_project(al_tab).TextMatrix(grd_project(al_tab).Rows - 1, mo_projectInfo(al_tab).Cols(ll_ENDCol).Index) = GetColMax(ll_CursorF, mo_projectInfo(al_tab).Cols(ll_ENDCol).DB_Name)
                grd_project(al_tab).TextMatrix(grd_project(al_tab).Rows - 1, mo_projectInfo(al_tab).Cols(ll_TOP10Col).Index) = "Top 10"
            End If
            Call p_da.Close(ll_CursorF)
            ll_CursorF = 0
            
            ll_CursorF = p_da.Filter(ll_cursor, "TOPTEN", "=", "Others", , False)
            If p_da.RowCount(ll_CursorF) > 0 Then
                Call GRD_addSUM(grd_project(al_tab), mo_projectInfo(al_tab), ll_CursorF, Array("STDProjects", "SAProjects", "ASProjects", "Volume", "SolutionLine", "TotalPrdVol", "ABPEPrdVol", "ASPrdVol", "SOMVol", "ProjectValue"), "GRP_DESC", Array("ABPEPrdVol", "ASPrdVol", "SOMVol", "TotalPrdVol"))
                ' fill START and END
                If ll_StartCol <> -1 Then grd_project(al_tab).TextMatrix(grd_project(al_tab).Rows - 1, mo_projectInfo(al_tab).Cols(ll_StartCol).Index) = GetColMin(ll_CursorF, mo_projectInfo(al_tab).Cols(ll_StartCol).DB_Name)
                If ll_ENDCol <> -1 Then grd_project(al_tab).TextMatrix(grd_project(al_tab).Rows - 1, mo_projectInfo(al_tab).Cols(ll_ENDCol).Index) = GetColMax(ll_CursorF, mo_projectInfo(al_tab).Cols(ll_ENDCol).DB_Name)
                grd_project(al_tab).TextMatrix(grd_project(al_tab).Rows - 1, mo_projectInfo(al_tab).Cols(ll_TOP10Col).Index) = "Others"
            End If
            Call p_da.Close(ll_CursorF)
            ll_CursorF = 0
            
            export_report.Visible = True
        Else
            export_report.Visible = False
        End If
        
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
        
        grd_project(al_tab).Visible = True
        lbl_projectCalculation.Caption = ""
        frm_projectCalc.Visible = False
    Else
        frm_projectCalc.Visible = False
    End If

    grd_project(al_tab).Visible = True
    ml_project_processed = ml_project_processed Or Pow(2, al_tab)
    LockScreen (False)

    Exit Sub
ErrorHandler:
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If

    LockScreen (False)
    Call ErrorHandler(Extender.Name & ".Process_Project")
End Sub


Private Function Pow(ByVal al_base As Long, ByVal al_exp As Long) As Long
On Error GoTo ErrorHandler
    If al_exp = 0 Then
        Pow = 1
        Exit Function
    End If
    
    Dim ll_i As Long
    Dim ll_retVal As Long
    ll_retVal = al_base
    For ll_i = 2 To al_exp
        ll_retVal = ll_retVal * al_base
    Next
    
    Pow = ll_retVal
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".Pow")
End Function

Private Sub GrdColumToSUMLine(ByRef ao_grd As ArmGrid, ByRef ao_sumLine As Dictionary, ByVal al_row As Long, ByVal as_colName As String)
On Error GoTo ErrorHandler
    If ao_sumLine.Exists(as_colName) Then
        ao_sumLine(as_colName) = ao_sumLine(as_colName) + ao_grd.Data(al_row, as_colName)
    End If
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GrdColumToSUMLine")
End Sub


Private Function GetTop10ProjectRequest(ByVal al_trwCode As Long, ByVal al_Level As Long) As String
On Error GoTo ErrorHandler

    Dim ls_retVal As String
    Select Case al_trwCode
        Case 1  ' Market
            Select Case al_Level
                Case 0, 1 ' All markets / Market
                    ls_retVal = "EXEC ProjectTop10_Market '$language_code$', '$date1$', '$date2$', '$BMK_Code$'"
                Case 2  ' Country
                    ls_retVal = "EXEC ProjectTop10_Country '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$'"
                Case 3  ' User
                    ls_retVal = "EXEC ProjectTop10_Creator '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
            
        Case 2  ' Area
            Select Case al_Level
                Case 0, 1 ' Area
                    ls_retVal = "EXEC ProjectTop10_RepGrp '$language_code$', '$date1$', '$date2$', $RAR_Code$"
                Case 3  ' z_creator
                    ls_retVal = "EXEC ProjectTop10_Creator '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
            
        Case 3
            Select Case al_Level
                Case 0, 1 ' All markets / Market
                    ls_retVal = "EXEC ProjectTop10_Market '$language_code$', '$date1$', '$date2$', '$BMK_Code$'"
                Case 3  ' user
                    ls_retVal = "EXEC ProjectTop10_Creator '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
        Case 4
            Select Case al_Level
                Case 0  ' All markets
                    ls_retVal = "EXEC ProjectTop10_Market '$language_code$', '$date1$', '$date2$', '$BMK_Code$'"
                Case 1, 2 ' Area
                    ls_retVal = "EXEC ProjectTop10_RepGrp '$language_code$', '$date1$', '$date2$', $RAR_Code$"
                Case 3  ' z_creator
                    ls_retVal = "EXEC ProjectTop10_Creator '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
        Case 5  ' market/ ... / customer
            Select Case al_Level
                Case 0, 1 ' All markets / Market
                    ls_retVal = "EXEC ProjectTop10_Market '$language_code$', '$date1$', '$date2$', '$BMK_Code$'"
                Case 2  ' Country
                    ls_retVal = "EXEC ProjectTop10_Country '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$'"
                Case 3, 4 ' Type/Customer
                    ls_retVal = ""
            End Select
    End Select
    
    GetTop10ProjectRequest = ls_retVal

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


Private Function GetProjectRequest(ByVal al_trwCode As Long, ByVal al_Level As Long, ByVal as_period As String) As String
On Error GoTo ErrorHandler

    Dim ls_retVal As String
    Select Case al_trwCode
        Case 1  ' Market
            Select Case al_Level
                Case 0, 1 ' All markets / Market
                    ls_retVal = "EXEC Project$TYPE$_$PERIOD$Market '$language_code$', $NOW$, '$BMK_Code$'"
                Case 2  ' Country
                    ls_retVal = "EXEC Project$TYPE$_$PERIOD$Country '$language_code$', $NOW$, '$BMK_Code$', '$CT_Code$'"
                Case 3  ' User
                    ls_retVal = "EXEC Project$TYPE$_$PERIOD$Creator '$language_code$', $NOW$, '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
            
        Case 2  ' Area
            Select Case al_Level
                Case 0, 1 ' Area
                    ls_retVal = "EXEC Project$TYPE$_$PERIOD$RepGrp '$language_code$', $NOW$, $RAR_Code$"
                Case 3  ' z_creator
                    ls_retVal = "EXEC Project$TYPE$_$PERIOD$Creator '$language_code$', $NOW$, '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
            
        Case 3
            Select Case al_Level
                Case 0, 1 ' All markets / Market
                    ls_retVal = "EXEC Project$TYPE$_$PERIOD$Market '$language_code$', $NOW$, '$BMK_Code$'"
                Case 3  ' user
                    ls_retVal = "EXEC Project$TYPE$_$PERIOD$Creator '$language_code$', $NOW$, '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
        Case 4  ' Area2
            Select Case al_Level
                Case 0  ' All markets
                    ls_retVal = "EXEC Project$TYPE$_$PERIOD$Market '$language_code$', $NOW$, '$BMK_Code$'"
                Case 1, 2 ' Area
                    ls_retVal = "EXEC Project$TYPE$_$PERIOD$RepGrp '$language_code$', $NOW$, $RAR_Code$"
                Case 3  ' z_creator
                    ls_retVal = "EXEC Project$TYPE$_$PERIOD$Creator '$language_code$', $NOW$, '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
        Case 5  ' market/ ... / customer
            Select Case al_Level
                Case 0, 1 ' All markets / Market
                    ls_retVal = "EXEC Project$TYPE$_$PERIOD$Market '$language_code$', $NOW$, '$BMK_Code$'"
                Case 2  ' Country
                    ls_retVal = "EXEC Project$TYPE$_$PERIOD$Country '$language_code$', $NOW$, '$BMK_Code$', '$CT_Code$'"
                Case 3, 4 ' Type/Customer
                    ls_retVal = ""
            End Select
    End Select
    
    ' replace $TYPE$
    Select Case tbs_ProjectType.SelectedItem.Tag
        Case "PRJ_ALL"
            ls_retVal = Replace(ls_retVal, "$TYPE$", "", , , vbTextCompare)
        Case "PRJ_STD"
            ls_retVal = Replace(ls_retVal, "$TYPE$", "STD", , , vbTextCompare)
        Case "PRJ_SA"
            ls_retVal = Replace(ls_retVal, "$TYPE$", "SA", , , vbTextCompare)
        Case "PRJ_AS"
            ls_retVal = Replace(ls_retVal, "$TYPE$", "AS", , , vbTextCompare)
    End Select
    
    'replace period
    Select Case as_period
        Case "MONTH"
            ls_retVal = Replace(ls_retVal, "$PERIOD$", "Month", , , vbTextCompare)
        Case "WEEK"
            ls_retVal = Replace(ls_retVal, "$PERIOD$", "Week", , , vbTextCompare)
    End Select
    
    
    GetProjectRequest = ls_retVal

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



Private Function GetVisitTotalRequest(ByVal as_Type As String) As String
On Error GoTo ErrorHandler
    Dim ls_retVal As String
    Select Case as_Type
        Case "NULL"     ' All
            ls_retVal = "EXEC Visit_GetCustomerVisitCount '$language_code$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
        Case "3"        ' omega
            ls_retVal = "EXEC Visit_GetCustomerAVisitCount '$language_code$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$, $A_Code$"
        Case "NULL2"    ' new created ( from - to )
            ls_retVal = "EXEC Visit_GetCustomerNVisitCount '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
    End Select
    GetVisitTotalRequest = ls_retVal

   Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetVisitTotalRequest")
End Function
Private Function GetVisitTotalCountRequest(ByVal as_Type As String) As String
On Error GoTo ErrorHandler
    Dim ls_retVal As String
    Select Case as_Type
        Case "NULL"     ' All
            ls_retVal = "EXEC Visit_GetCustomerVisitTotalCount '$language_code$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
        Case "3"        ' omega
            ls_retVal = "EXEC Visit_GetCustomerAVisitTotalCount '$language_code$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$, $A_Code$"
        Case "NULL2"    ' new created ( from - to )
            ls_retVal = "EXEC Visit_GetCustomerNVisitTotalCount '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
    End Select
    GetVisitTotalCountRequest = ls_retVal

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

Private Function GetVisitDetailRequest(ByVal as_Type As String, ByVal ab_allData As Boolean) As String
On Error GoTo ErrorHandler
    Dim ls_retVal As String
    Select Case as_Type
        Case "NULL"     ' All
            If ab_allData Then
                ls_retVal = "EXEC Visit_GetCustomerVisitDetail '$language_code$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            Else
                ls_retVal = "EXEC Visit_GetCustomerVisitDetail_fast '$language_code$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End If
        Case "3"        ' omega
            If ab_allData Then
                ls_retVal = "EXEC Visit_GetCustomerAVisitDetail '$language_code$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$, $A_Code$"
            Else
                ls_retVal = "EXEC Visit_GetCustomerAVisitDetail_fast '$language_code$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$, $A_Code$"
            End If
        Case "NULL2"    ' new created ( from - to ) - no fast version
            ls_retVal = "EXEC Visit_GetCustomerNVisitDetail '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
    End Select
    GetVisitDetailRequest = ls_retVal

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

Private Function WhichOptionIsSelected(ByRef ao_options As Object) As Long
On Error GoTo ErrorHandler
    WhichOptionIsSelected = -1
    Dim lo_opt As OptionButton
    For Each lo_opt In ao_options
        If lo_opt.Value Then
            WhichOptionIsSelected = lo_opt.Index
            Exit For
        End If
    Next
    Exit Function
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".WhichOptionIsSelected")
End Function


Private Sub Process_Sales_PDF_Excel(ByVal as_MSA As String, ByVal aHeaderColor As Long)
On Error GoTo ErrorHandler
    Dim ls_req As String
    Dim ls_ReqCG As String
    Dim ll_cursor As Long
    Dim ll_curentCol As Long
    Dim lb_ExcellOpenedNow As Boolean
    
    If Not CheckReportAvailable() Then
        Exit Sub
    End If

    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        tv1.SetFocus
        Exit Sub
    End If
    
    If Level_selected = 3 Or cb_trw.SelectedItem.GetData(0) = 2 Then
        ' not applicable in this case
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        Exit Sub
    End If
    
    If Get_A_Config("RPT_SALES_ON") <> "Y" Then
        ' not available due to a data refresh
        MsgBox GetLabel("lbl_sales_REFRESH", "#Report is not available due to a data update, please try later.")
        Exit Sub
    End If



    Call LockScreen(True)
    
    Dim ls_startP As String
    Dim ls_endP As String
    Dim ll_tmplStyle As Long
    Dim ls_Desc As String
    
    If opt_salesPeriod(0).Value Then
        ls_startP = "01/01/" & Year(Now)
        ls_endP = "31/12/" & Year(Now)
        ll_tmplStyle = 1
    ElseIf opt_salesPeriod(1).Value Then
        ls_startP = "01/" & Format(Now, "mm\/yyyy")
        ls_endP = Format(Now, "dd\/mm\/yyyy")
        ll_tmplStyle = 2
    Else
        ls_startP = "01/" & cbo_DR_Month.SelectedItem.Key & "/" & cbo_DR_Year.SelectedItem.Key
        If cbo_DR_Month.SelectedItem.Key <> "12" Then
            ls_endP = Format(CDate("01/" & cbo_DR_Month.SelectedItem.Key + 1 & "/" & cbo_DR_Year.SelectedItem.Key) - 1, "dd\/mm\/yyyy")
        Else
            ls_endP = Format(CDate("01/01" & "/" & cbo_DR_Year.SelectedItem.Key + 1) - 1, "dd\/mm\/yyyy")
        End If
        ll_tmplStyle = 2
    End If
    
    lb_ExcellOpenedNow = False
    Set a_ExcelApp = GetObject(, "Excel.Application")
    Set a_ExcelWorkBook = a_ExcelApp.Workbooks.Add
    Set a_ExcelSheet1 = a_ExcelWorkBook.Sheets.Add

    a_ExcelWorkBook.Activate
    a_ExcelSheet1.Activate
    
    a_ExcelSheet1.PageSetup.Orientation = 2
    
    a_ExcelApp.ActiveSheet.PageSetup.Zoom = 70

    If lb_ExcellOpenedNow Then
        a_ExcelApp.Application.Visible = False
    End If
    a_ExcelApp.ScreenUpdating = False
    
    With a_ExcelSheet1.cells.Interior
        .ColorIndex = 2
        .Pattern = 1
        .PatternColorIndex = -4105
    End With
    
    
    With a_ExcelSheet1
        .Columns("A").columnWidth = 9.5
        .Columns("B").columnWidth = IIf(chk_salesPeriodGrp(0).Value + chk_salesPeriodGrp(1).Value > 0, 27, 0)
        .Columns("C").columnWidth = 16
        .Columns("D").columnWidth = 9.5
        .Columns("E").columnWidth = 9.5
        .Columns("F").columnWidth = 9.5
        .Columns("G").columnWidth = 9.5
        .Columns("H").columnWidth = 9.5
        .Columns("I").columnWidth = 9.5
        .Columns("J").columnWidth = 9.5
        .Columns("K").columnWidth = 9.5
        .Columns("L").columnWidth = 9.5
        .Columns("M").columnWidth = 9.5
        .Columns("N").columnWidth = 9.5
        .Columns("O").columnWidth = 9.5
        .Columns("P").columnWidth = 11
        .Columns("Q").columnWidth = 11
        .Columns("I:I").HorizontalAlignment = xlright
        .Columns("Q:Q").HorizontalAlignment = xlright
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$salesOption$"
        Debug.Assert (WhichOptionIsSelected(opt_salesOptions) <> -1)
        ms_MsgInfo(0, 1) = opt_salesOptions(WhichOptionIsSelected(opt_salesOptions)).Caption
        .cells(2, 9).Value = GetLabel("ex_reportSales", "#Daily Sales Report ($salesOption$)", ms_MsgInfo)
        .cells(2, 9).Font.Bold = True
        
        ReDim ms_MsgInfo(3, 1)
        ms_MsgInfo(0, 0) = "$TV1$"
        ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
        ms_MsgInfo(1, 0) = "$STARTP$"
        ms_MsgInfo(1, 1) = ls_startP
        ms_MsgInfo(2, 0) = "$ENDP$"
        ms_MsgInfo(2, 1) = ls_endP
        ms_MsgInfo(3, 0) = "$tbs_sales$"
        ms_MsgInfo(3, 1) = tbs_sales.SelectedItem.Caption
        
        .cells(4, 1).Value = GetLabel(frm_sales.Tag & "PRINT", "#$tbs_sales$: $TV1$  $STARTP$-$ENDP$ vs same period previous year", ms_MsgInfo)
        .cells(4, 1).Font.Bold = True
        
            ' retrieve the last update from SAP
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$DATA_REFRESH$"
        ms_MsgInfo(0, 1) = Format(GetLastDataRefresh, "dd/mm/yy hh:mm")
        .cells(5, 1).Value = GetLabel("ex_refreshed", "#last data refresh: $DATA_REFRESH$", ms_MsgInfo)
        .cells(5, 1).Font.Size = 8
    
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$NOW$"
        ms_MsgInfo(0, 1) = Format(Now, "dd/mm/yy hh:mm:ss")
        .cells(2, 17).Value = GetLabel("ex_created", "#Created $NOW$", ms_MsgInfo)
        .cells(2, 17).Font.Italic = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$CB_TRW$"
        ms_MsgInfo(0, 1) = cb_trw.Text
        .cells(3, 17) = GetLabel("ex_trw", "#Treeview Info: $CB_TRW$", ms_MsgInfo)
        .cells(3, 17).Font.Italic = True
        .cells(3, 17).Font.Size = 8

        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$TRW_PATH$"
        ms_MsgInfo(0, 1) = TreeviewPath
        .cells(4, 17) = GetLabel("ex_trw_path", "#Treeview Path: $TRW_PATH$", ms_MsgInfo)
        .cells(4, 17).Font.Italic = True
        .cells(4, 17).Font.Size = 8
    
    
        Dim lIdxExcelRow As Long, lIdxExcelCol As Long
        Dim lRowIdx As Long
        Dim lColCount As Long
        
        lColCount = 16
        
        lIdxExcelCol = 1
        lIdxExcelRow = 5
    
        ' HEADER OF THE GRID
        ' Set the first column title and format
        lIdxExcelRow = lIdxExcelRow + 1
        
        ' Set the font format and the data Header of the grid
        .cells(lIdxExcelRow, 1).Font.Bold = True
        .cells(lIdxExcelRow, 1).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 1).Value = GetLabel("s_grouping", "#Grouping")
        
        .cells(lIdxExcelRow, 3).Font.Bold = True
        .cells(lIdxExcelRow, 3).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 3).Value = GetLabel("s_sales", "#Sales")

        .cells(lIdxExcelRow, 4).Font.Bold = True
        .cells(lIdxExcelRow, 4).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 4).Value = GetLabel("s_jan", "#Jan")

        .cells(lIdxExcelRow, 5).Font.Bold = True
        .cells(lIdxExcelRow, 5).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 5).Value = GetLabel("s_feb", "#Feb")

        .cells(lIdxExcelRow, 6).Font.Bold = True
        .cells(lIdxExcelRow, 6).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 6).Value = GetLabel("s_march", "#March")
        
        .cells(lIdxExcelRow, 7).Font.Bold = True
        .cells(lIdxExcelRow, 7).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 7).Value = GetLabel("s_april", "#April")
        
        .cells(lIdxExcelRow, 8).Font.Bold = True
        .cells(lIdxExcelRow, 8).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 8).Value = GetLabel("s_may", "#May")

        .cells(lIdxExcelRow, 9).Font.Bold = True
        .cells(lIdxExcelRow, 9).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 9).Value = GetLabel("s_jun", "#Jun")
        
        .cells(lIdxExcelRow, 10).Font.Bold = True
        .cells(lIdxExcelRow, 10).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 10).Value = GetLabel("s_july", "#July")

        .cells(lIdxExcelRow, 11).Font.Bold = True
        .cells(lIdxExcelRow, 11).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 11).Value = GetLabel("s_august", "#August")

        .cells(lIdxExcelRow, 12).Font.Bold = True
        .cells(lIdxExcelRow, 12).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 12).Value = GetLabel("s_sept", "#Sept")

        .cells(lIdxExcelRow, 13).Font.Bold = True
        .cells(lIdxExcelRow, 13).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 13).Value = GetLabel("s_oct", "#Oct")
        
        .cells(lIdxExcelRow, 14).Font.Bold = True
        .cells(lIdxExcelRow, 14).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 14).Value = GetLabel("s_nov", "#Nov")
        
        .cells(lIdxExcelRow, 15).Font.Bold = True
        .cells(lIdxExcelRow, 15).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 15).Value = GetLabel("s_dec", "#Dec")

        .cells(lIdxExcelRow, 16).Font.Bold = True
        .cells(lIdxExcelRow, 16).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 16).Value = GetLabel("s_totalYTD", "#TOTAL YTD")
    
        .cells(lIdxExcelRow, 17).Font.Bold = True
        .cells(lIdxExcelRow, 17).HorizontalAlignment = -4108
        .cells(lIdxExcelRow, 17).Value = GetLabel("s_total", "#TOTAL")
    End With
    
    Dim lva_data() As Variant
    ReDim lva_data(0 To lColCount, 0 To 0) As Variant
    Dim lva_Total() As Variant
    ReDim lva_Total(0 To lColCount, 0 To 1) As Variant
    Dim ll_Row As Long
    
    Dim ll_i As Long
    For ll_i = LBound(lva_Total, 1) To UBound(lva_Total, 1)
        lva_Total(ll_i, 0) = 0
        lva_Total(ll_i, 1) = 0
    Next ll_i
    
    
    ls_ReqCG = GetSalesRequestPrint(cb_trw.SelectedItem.GetData(0), Level_selected, "CG", chk_salesPeriodGrp(0).Value, chk_salesPeriodGrp(1).Value, as_MSA)
    If ls_ReqCG <> "" Then
        ls_ReqCG = ReplaceHolders(ls_ReqCG)
        ls_ReqCG = Replace(ls_ReqCG, "$STARTP$", ls_startP, , , vbTextCompare)
        ls_ReqCG = Replace(ls_ReqCG, "$ENDP$", ls_endP, , , vbTextCompare)
        ls_req = Replace(ls_ReqCG, "$CG_Code2$", "C001", , , vbTextCompare)
        ls_req = Replace(ls_req, "$UM_Code$", "M2", , , vbTextCompare)
        ls_req = Replace(ls_req, "$METAL_FLAG$", IIf(chk_sales_clgMetal.Value = 1, "''", "NULL"), , , vbTextCompare)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
            
        ' fill the grid
        Call FillArraySales(lva_data, ll_cursor, Year(ls_startP), False, chk_sales_exportGVSOnly.Value = 1, lva_Total)
        Call p_da.Close(ll_cursor)
        
        ' do split between ceilings to metal/non metal
        If chk_sales_clgMetal.Value = 1 Then
            ' Rename current Ceilings to Ceilings Non Metal
            For ll_Row = LBound(lva_data, 2) To UBound(lva_data, 2)
                lva_data(0, ll_Row) = lva_data(0, ll_Row) + " - Non Metal"
            Next
            ls_req = Replace(ls_ReqCG, "$CG_Code2$", "C001", , , vbTextCompare)
            ls_req = Replace(ls_req, "$UM_Code$", "M2", , , vbTextCompare)
            ls_req = Replace(ls_req, "$METAL_FLAG$", "'X'", , , vbTextCompare)
            
            ll_cursor = OpenSQLSafe(p_da, ls_req)
                
            Dim ll_bck_row As Long
            ll_bck_row = UBound(lva_data, 2) + 1
            ' fill the grid
            Call FillArraySales(lva_data, ll_cursor, Year(ls_startP), False, chk_sales_exportGVSOnly.Value = 1, lva_Total)
            Call p_da.Close(ll_cursor)
            
            For ll_Row = ll_bck_row To UBound(lva_data, 2)
                lva_data(0, ll_Row) = lva_data(0, ll_Row) + " - Metal"
            Next
        End If


        ls_req = Replace(ls_ReqCG, "$CG_Code2$", "C002", , , vbTextCompare)
        ls_req = Replace(ls_req, "$UM_Code$", "LM", , , vbTextCompare)
        ls_req = Replace(ls_req, "$METAL_FLAG$", "NULL", , , vbTextCompare)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        ' fill the grid
        Call FillArraySales(lva_data, ll_cursor, Year(ls_startP), False, chk_sales_exportGVSOnly.Value = 1, lva_Total)
        Call p_da.Close(ll_cursor)
    End If
    
    ls_req = GetSalesRequestPrint(cb_trw.SelectedItem.GetData(0), Level_selected, "OTHER", chk_salesPeriodGrp(0).Value, chk_salesPeriodGrp(1).Value, as_MSA)
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        ls_req = Replace(ls_req, "$STARTP$", ls_startP, , , vbTextCompare)
        ls_req = Replace(ls_req, "$ENDP$", ls_endP, , , vbTextCompare)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        ' fill the grid
        Call FillArraySales(lva_data, ll_cursor, Year(ls_startP), False, chk_sales_exportGVSOnly.Value = 1, lva_Total)
        Call p_da.Close(ll_cursor)
    End If
    
    ' calculate totals
    Dim lColIdx As Long, ld_total As Double, ld_total_MTD_LY As Double
    
    lva_Total(0, 0) = GetLabel("s_total", "#TOTAL")
    lva_Total(1, 0) = ""
    lva_Total(2, 0) = "GSV EUR " & Year(ls_startP)
    
    lva_Total(0, 1) = lva_Total(0, 0)
    lva_Total(1, 1) = ""
    lva_Total(2, 1) = "GSV EUR " & (Year(ls_startP) - 1)
    
    ' copy total into array
    ReDim Preserve lva_data(LBound(lva_data, 1) To UBound(lva_data, 1), LBound(lva_data, 2) To UBound(lva_data, 2) + 2) As Variant
    For ll_i = LBound(lva_Total, 1) To UBound(lva_Total, 1)
        lva_data(ll_i, UBound(lva_data, 2) - 1) = lva_Total(ll_i, 0)
        lva_data(ll_i, UBound(lva_data, 2)) = lva_Total(ll_i, 1)
    Next ll_i
    
    ld_total_MTD_LY = 0
    For ll_Row = LBound(lva_data, 2) To UBound(lva_data, 2)
        ld_total = 0
        For lColIdx = 3 To UBound(lva_data, 1) - 2
            If lva_data(lColIdx, ll_Row) <> "" Then
                ld_total = ld_total + lva_data(lColIdx, ll_Row)
            End If
        Next
        lva_data(UBound(lva_data, 1), ll_Row) = ld_total
        If lva_data(2, ll_Row) = "GSV EUR " & Year(ls_startP) Or _
            lva_data(2, ll_Row) Like "Vol * " & Year(ls_startP) Then
            ' calculate percentage into cell for current year
            If lva_data(UBound(lva_data, 1) - 1, ll_Row + 1) <> 0 And lva_data(UBound(lva_data, 1) - 1, ll_Row) > 0 Then
                lva_data(UBound(lva_data, 1) - 1, ll_Row) = lva_data(UBound(lva_data, 1) - 1, ll_Row) / lva_data(UBound(lva_data, 1) - 1, ll_Row + 1) * 100 & "%"
            Else
                lva_data(UBound(lva_data, 1) - 1, ll_Row) = "N/A"
            End If
        ElseIf lva_data(2, ll_Row) = "GSV EUR " & (Year(ls_startP) - 1) And ll_Row < UBound(lva_data, 2) - 1 Then
            ld_total_MTD_LY = ld_total_MTD_LY + lva_data(UBound(lva_data, 1) - 1, ll_Row)
        End If
    Next
    
    ' update super total values
    lva_data(UBound(lva_data, 1) - 1, UBound(lva_data, 2)) = ld_total_MTD_LY
    If ld_total_MTD_LY <> 0 And lva_data(UBound(lva_data, 1), UBound(lva_data, 2) - 1) > 0 Then
        lva_data(UBound(lva_data, 1) - 1, UBound(lva_data, 2) - 1) = lva_data(UBound(lva_data, 1), UBound(lva_data, 2) - 1) / ld_total_MTD_LY * 100 & "%"
    Else
        lva_data(UBound(lva_data, 1) - 1, UBound(lva_data, 2) - 1) = "N/A"
    End If
    
    
    
    Dim lRangeTopLeft As String, lRangeBottomRight As String, lRange As String
    Dim lRowCount As Long
    lRowCount = UBound(lva_data, 2) + 1
        
    Dim ls_oldGrouping As String
    
    Dim lv_Data As Variant
    
    With a_ExcelSheet1
        ' SET THE GRID
        lRangeTopLeft = "A6"
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlInsideVertical).Weight = xlThin
        .Range(lRange).Borders(xlInsideVertical).LineStyle = xlContinuous
        .Range(lRange).Borders(xlInsideHorizontal).Weight = xlThin
        .Range(lRange).Borders(xlInsideHorizontal).LineStyle = xlContinuous
        
        
        'export data into excell
        ReDim lv_Data(LBound(lva_data, 2) To UBound(lva_data, 2), LBound(lva_data, 1) To UBound(lva_data, 1)) As Variant
        
        For lColIdx = LBound(lva_data, 1) To UBound(lva_data, 1)
            For lRowIdx = LBound(lva_data, 2) To UBound(lva_data, 2)
                lv_Data(lRowIdx, lColIdx) = lva_data(lColIdx, lRowIdx)
            Next
        Next
        .Range(.cells(7, 1), .cells(UBound(lv_Data, 1) + 7, UBound(lv_Data, 2) + 1)).Value = lv_Data
        
        ' header
        .Range(.cells(7, 1), .cells(UBound(lv_Data, 1) + 5, 3)).Font.Bold = True
        
        ' format numbers
        .Range(.cells(7, 4), .cells(UBound(lv_Data, 1) + 7, UBound(lv_Data, 2) + 1)).NumberFormat = "#,##0"
        .Range(.cells(7, 4), .cells(UBound(lv_Data, 1) + 7, UBound(lv_Data, 2) + 1)).HorizontalAlignment = xlright
        
        For lRowIdx = LBound(lva_data, 2) To UBound(lva_data, 2)
            If lRowIdx = LBound(lva_data, 2) Then ls_oldGrouping = lva_data(LBound(lva_data, 1) + 1, lRowIdx)
            lIdxExcelRow = lIdxExcelRow + 1
            
            If InStr(1, lva_data(UBound(lva_data, 1) - 1, lRowIdx), "%", vbTextCompare) <> 0 Then
                .cells(lIdxExcelRow, 16).NumberFormat = "0.0%"
            End If
            
            
            If ls_oldGrouping <> lva_data(LBound(lva_data, 1) + 1, lRowIdx) Then
                ' add wider line after grouping
                ' BOTTOM TOTAL
                lRangeTopLeft = "A" & (lIdxExcelRow - 1)
                lRangeBottomRight = Chr(65 + lColCount) & (lIdxExcelRow - 1)
                lRange = lRangeTopLeft & ":" & lRangeBottomRight
                .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
                .Range(lRange).Borders(xlEdgeBottom).Weight = xlMedium
                ls_oldGrouping = lva_data(LBound(lva_data, 1) + 1, lRowIdx)
            End If
        Next

        ' merge headers
        With .Range("A6:B6")
            .VerticalAlignment = -4108  'xlCenter
            .MergeCells = True
        End With
        
        Call MergeRows(a_ExcelSheet1, 7, lIdxExcelRow, 1)
        Call MergeRows(a_ExcelSheet1, 7, lIdxExcelRow, 2)
        
        ' TOTAL LINE FORMAT (BOLD)
        .Range(.cells(7, 16), .cells(UBound(lva_data, 2) + 5, 17)).Font.Bold = True
        .Range(.cells(lRowCount + 5, 1), .cells(lRowCount + 6, UBound(lva_data, 1) + 1)).Font.Bold = True
                
        ' ADD THE STYLE
        
        ' SET THE HEADER
        lRangeTopLeft = "A6"
        lRangeBottomRight = Chr(65 + lColCount) & "6"
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeTop).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeTop).Weight = xlThick
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        
        lRangeTopLeft = "A7"
        lRangeBottomRight = "C" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        
        
        ' SET THE TOTAL
        lRangeTopLeft = "P6"
        lRangeBottomRight = "P" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
        ' SET THE EXTERNAL WEIGHT LINE
        ' LEFT
        lRangeTopLeft = "A6"
        lRangeBottomRight = "A" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        
        ' RIGHT
        lRangeTopLeft = Chr(65 + lColCount) & "6"
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
        ' BOTTOM
        lRangeTopLeft = "A" & (lRowCount + 6)
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
        ' BOTTOM TOTAL
        lRangeTopLeft = "A" & (lRowCount + 4)
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 4)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
    End With
    
    With a_ExcelSheet1.PageSetup
        .PrintTitleRows = a_ExcelSheet1.Rows(6).Address
        .PrintTitleColumns = ""
        .PrintArea = ""
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .PrintHeadings = False
        .PrintGridlines = False
        .CenterHorizontally = True
        .CenterVertically = False
        .Orientation = 1
        .Draft = False
        .BlackAndWhite = False
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = 100
    End With
    
    a_ExcelApp.Visible = True
    a_ExcelApp.ScreenUpdating = True
    a_ExcelApp.ActiveWindow.View = 2    'xlPageBreakPreview
    a_ExcelSheet1.DisplayPageBreaks = True
    
    ' update h page breaks to avoid split inside grouping
    Dim ll_last_row As Long
    ll_last_row = 1

    With a_ExcelSheet1
        ll_i = 1
        While ll_i <= .HPageBreaks.Count
            ' to fix known bug of microsoft
            .Range("Q" & lRowCount + 6).Select

            ll_Row = .HPageBreaks(ll_i).Location.Row
            
            While .cells(ll_Row, 2).Value = "" And ll_Row > ll_last_row
                ll_Row = ll_Row - 1
            Wend
            
            If ll_Row > ll_last_row Then
                Set .HPageBreaks(ll_i).Location = .Range("A" & ll_Row)
                ll_last_row = ll_Row
            Else
                ll_last_row = .HPageBreaks(ll_i).Location.Row
            End If
            ll_i = ll_i + 1
        Wend
        .cells(1, 1).Select
    End With
    a_ExcelApp.ActiveWindow.View = 1    'xlNormalView
        
    If chk_sales_exportXLS.Value = 0 Then
        GoTo no_pdfExport:
    End If
     ' do save into pdf
     Dim ls_Filename As String
     
     ls_Filename = prg.AppCache_Dir & "\RPTSales_$MKT_Code$_$CT_Code$_by_%PERIOD%_%GRP%_%ID%.pdf"
     
     ls_Filename = ReplaceHolders(ls_Filename)
     If opt_salesPeriod(0).Value Then
         ls_Filename = Replace(ls_Filename, "%PERIOD%", "CY", , , vbTextCompare)
     ElseIf opt_salesPeriod(1).Value Then
         ls_Filename = Replace(ls_Filename, "%PERIOD%", "CM", , , vbTextCompare)
     Else
             ls_Filename = Replace(ls_Filename, "%PERIOD%", "CU", , , vbTextCompare)
     End If
     
     If Not (chk_salesPeriodGrp(1).Value = 1) And Not (chk_salesPeriodGrp(0).Value = 1) Then
         ls_Filename = Replace(ls_Filename, "_%GRP%", "", , , vbTextCompare)
     ElseIf chk_salesPeriodGrp(1).Value Then
         ls_Filename = Replace(ls_Filename, "%GRP%", "CT", , , vbTextCompare)
     Else
         ls_Filename = Replace(ls_Filename, "%GRP%", "MKT", , , vbTextCompare)
     End If
     
     ls_Filename = Replace(ls_Filename, "%ID%", DatePart("n", Now()) * DatePart("h", Now()) * DatePart("y", Now()), , , vbTextCompare)
     
     Dim lo_FSO As Object
     Set lo_FSO = CreateObject("Scripting.FileSystemObject")
    
     If lo_FSO.FileExists(ls_Filename) Then
         Call lo_FSO.DeleteFile(ls_Filename, True)
     End If
        
     Set lo_FSO = Nothing
     ' xlTypePDF = 0
     ' xlQualityStandard = 0
     On Error GoTo no_pdfExport
     
     a_ExcelSheet1.ExportAsFixedFormat Type:=0, FileName:= _
             ls_Filename, Quality:=0, _
             IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
     
     a_ExcelWorkBook.Close SaveChanges:=False
    
    If lb_ExcellOpenedNow Then
        ' close it
        a_ExcelApp.Application.Visible = True
        a_ExcelApp.quit
    End If
        
    Set a_ExcelSheet1 = Nothing
    Set a_ExcelWorkBook = Nothing
    Set a_ExcelApp = Nothing
    
    Call LockScreen(False)

    Exit Sub
    
no_pdfExport:
On Error GoTo ErrorHandler
    Debug.Print (a_ExcelApp.Application.Version)
    
    ' leave app excell visible to see results
    a_ExcelApp.Application.Visible = True
    a_ExcelApp.ScreenUpdating = True
    
    Set a_ExcelSheet1 = Nothing
    Set a_ExcelWorkBook = Nothing
    Set a_ExcelApp = Nothing
    
    Call LockScreen(False)
    Exit Sub
    
ErrorHandler:
    If Err.Number = 429 Then
        Set a_ExcelApp = CreateObject("Excel.Application")
        lb_ExcellOpenedNow = True
        Resume Next
    ElseIf Err.Number = 1004 Then
        Debug.Print Err.Description
        Resume Next
    Else
        If Not a_ExcelApp Is Nothing Then
            a_ExcelApp.ScreenUpdating = True
            Set a_ExcelApp = Nothing
        End If
    End If
    
    Call LockScreen(False)
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If

    Call ErrorHandler(Extender.Name & ".Process_Sales_PDF_Excel")
End Sub

Private Sub Process_Sales_Rep()
On Error GoTo ErrorHandler
    Dim ls_req As String
    Dim ll_cursor As Long
    Dim ll_currYear As Long
    
    If Not CheckReportAvailable() Then
        Exit Sub
    End If
    
    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        tv1.SetFocus
        Exit Sub
    End If
    
    
    ' check if sales is available
    If Get_A_Config("RPT_SALES_ON") <> "Y" Then
        ' not available due to a data refresh
        frm_sales_rep.Caption = GetLabel(frm_sales_rep.Tag & "NODATA", "#Data not available.")
        grd_sales_rep.Visible = False
        lbl_salesRepCalculation.Caption = GetLabel("lbl_sales_REFRESH", "#Report is not available due to a data update," & vbCrLf & "please try later.")
        lbl_salesRepCalculation.Visible = True         ' bugfix JN 11.4.2013
        mb_sales_rep_processed = False
        export_report.Visible = mb_sales_rep_processed
        frm_sales_rep.Visible = True
        Call frm_sales_rep.Refresh
        DoEvents
            
        Exit Sub
    End If
    
    If cbo_salesDataView.SelectedItem Is Nothing Then
        frm_sales_rep.Caption = GetLabel(frm_sales_rep.Tag & "NODATA", "#Data not available.")
        grd_sales_rep.Visible = False
        lbl_salesRepCalculation.Caption = GetLabel("lbl_sales_NO_VIEW", "#Please select data view.")
        lbl_salesRepCalculation.Visible = True
        mb_sales_rep_processed = False
        export_report.Visible = mb_sales_rep_processed
        frm_sales_rep.Visible = True
        Call frm_sales_rep.Refresh
        DoEvents
            
        Exit Sub
    End If
    
    If cbo_salesCurrency.SelectedItem Is Nothing Then
        frm_sales_rep.Caption = GetLabel(frm_sales_rep.Tag & "NODATA", "#Data not available.")
        grd_sales_rep.Visible = False
        lbl_salesRepCalculation.Caption = GetLabel("lbl_sales_NO_CURRENCY", "#Please select currency.")
        lbl_salesRepCalculation.Visible = True
        mb_sales_rep_processed = False
        export_report.Visible = mb_sales_rep_processed
        frm_sales_rep.Visible = True
        Call frm_sales_rep.Refresh
        DoEvents
            
        Exit Sub
    End If
    
    frm_sales_by_rep_grouping.Visible = False
    Call LockScreen(True)
    
    ll_currYear = cbo_salesYear.SelectedItem.Key    ' Year(Date)
    ReDim ms_MsgInfo(3, 1)
    ms_MsgInfo(0, 0) = "$TV1$"
    ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
    ms_MsgInfo(1, 0) = "$YEAR$"
    ms_MsgInfo(1, 1) = ll_currYear
    ms_MsgInfo(2, 0) = "$CURRENCY$"
    ms_MsgInfo(2, 1) = cbo_salesCurrency.SelectedItem.DisplayText
    ms_MsgInfo(3, 0) = "$VIEW$"
    ms_MsgInfo(3, 1) = cbo_salesDataView.SelectedItem.DisplayText
    
    frm_sales_rep.Visible = True
    frm_sales_rep.Caption = GetLabel(frm_sales_rep.Tag, "#Sales by rep: $TV1$  $YEAR$ - $VIEW$ ($CURRENCY$)", ms_MsgInfo)
    
    grd_sales_rep.Visible = False
    
    Call SetGridCelBold(grd_sales_rep, 0, grd_sales_rep.Cols - 1)
    Call SetGridCelBold(grd_sales_rep, 0, grd_sales_rep.Cols - 2)
    
    lbl_salesRepCalculation.Visible = True
    
    lbl_salesRepCalculation.Caption = GetLabel(lbl_salesRepCalculation.Tag, "#Calculating Sales by reps report ....")
    Call frm_sales.Refresh
    DoEvents
    
    grd_sales_rep.Rows = grd_sales_rep.FixedRows        ' remove all data lines from grid
'    grd_SalesRep.LeftCol = 6                                 ' ensure visible part is at top left

    ls_req = GetSalesRepRequest(cb_trw.SelectedItem.GetData(0), Level_selected)
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        ls_req = Replace(ls_req, "$cyear$", ll_currYear, , , vbTextCompare)
        ls_req = Replace(ls_req, "$CURR_CODE$", cbo_salesCurrency.SelectedItem.Key, , , vbTextCompare)
        ls_req = Replace(ls_req, "$SRVA_CODE$", cbo_salesDataView.SelectedItem.Key, , , vbTextCompare)
        
        'gouping placeholders $GRP_REP_CODE$, $GRP_CT_CODE$, $GRP_MKT_CODE$
        If SalesByRepSupportGrouping(cb_trw.SelectedItem.GetData(0), Level_selected) Then
            If Level_selected = 0 Then
                ls_req = Replace(ls_req, "$GRP_MKT_CODE$", IIf(chk_sales_by_rep_grp(0).Value, "NULL", "''"), , , vbTextCompare)
            Else
                ls_req = Replace(ls_req, "$GRP_MKT_CODE$", "''", , , vbTextCompare)
            End If
            ls_req = Replace(ls_req, "$GRP_CT_CODE$", IIf(chk_sales_by_rep_grp(1).Value, "NULL", "''"), , , vbTextCompare)
        Else
            ' do not group by market/country
            ls_req = Replace(ls_req, "$GRP_MKT_CODE$", "''", , , vbTextCompare)
            ls_req = Replace(ls_req, "$GRP_CT_CODE$", "''", , , vbTextCompare)
        End If
        
        ls_req = Replace(ls_req, "$GRP_REP_CODE$", IIf(chk_sales_by_rep_grp(2).Value, "NULL", "''"), , , vbTextCompare)
        

        ' TEMPORARY SOLUTION UNTIL WE DO NOT HAVE SR_CODE INSTEAD LOGIN_NAME IN TREEVIEW
        ls_req = Replace(ls_req, "$SR_CODE$", tv1.NodeInfo(tv1.SelectedItem).GetData(3), , , vbTextCompare)

        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        ' fill the grid
        Call GRD_LoadData(grd_sales_rep, mo_SalesRepInfo, ll_cursor)
        ' add total line
        Call GRD_addSUM(grd_sales_rep, mo_SalesRepInfo, ll_cursor, Array("GSV_EUR_M", "GSV_EUR_YTD", "GSV_EUR_H1", "GSV_EUR_H2", "GSV_EUR_M_AS", "GSV_EUR_YTD_AS", "GSV_EUR_H1_AS", "GSV_EUR_H2_AS"), "GRP_Desc")

        Call p_da.Close(ll_cursor)
        
        ' UPDATE DESCRITPITON FOR 0 INTO 'UNASIGNED'
        
        Dim ll_i As Long
        Dim ls_lastNumPart As String
        
        For ll_i = grd_sales_rep.Rows - 2 To 2 Step -1
            ls_lastNumPart = GetLastNumericPart(grd_sales_rep.TextMatrix(ll_i, 0))
            If ls_lastNumPart = "0" Then
                ' put row description as unasigned
                grd_sales_rep.TextMatrix(ll_i, 1) = grd_sales_rep.TextMatrix(ll_i, 1) & " " & GetLabel("p_unasigned", "#Unasigned.")
            ElseIf ls_lastNumPart = "-3" Then
                ' put row description as NON SAP sales
                grd_sales_rep.TextMatrix(ll_i, 1) = grd_sales_rep.TextMatrix(ll_i, 1) & " " & GetLabel("p_nonSAPSales", "#AMC Sales.")
            End If
            
        Next
        
        grd_sales_rep.Visible = True
    Else
        grd_sales_rep.Visible = False
        lbl_salesRepCalculation.Caption = GetLabel("lbl_sales_NOREPORT", "#Report is not available for this tree node.")
        lbl_salesRepCalculation.Visible = True
        mb_sales_rep_processed = False
        export_report.Visible = mb_sales_rep_processed
    End If


    
    Call LockScreen(False)
    mb_sales_rep_processed = True
    export_report.Visible = mb_sales_rep_processed
    Exit Sub
    
ErrorHandler:
    Call LockScreen(False)
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If

    Call ErrorHandler(Extender.Name & ".Process_Sales_Rep")
End Sub

Private Function GetLastNumericPart(ByVal as_input As String) As String
On Error GoTo ErrorHandler
    Dim ll_len As Long
    ll_len = 1
    
    While isNumeric(right(as_input, ll_len)) And Mid(as_input, Len(as_input) - ll_len + 1, 1) <> " " And Len(as_input) > ll_len
        ll_len = ll_len + 1
    Wend
    
    If Len(as_input) = ll_len Then
        GetLastNumericPart = IIf(isNumeric(right(as_input, ll_len)), right(as_input, ll_len), "")
    Else
        GetLastNumericPart = right(as_input, ll_len - 1)
    End If
    

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




Private Function GetLastDataRefresh() As Date
    Dim ll_cursor As Long
    
    ' retrieve the last update from SAP
    ll_cursor = OpenSQLSafe(p_da, "select top 1 log_date from zlog where Application = 'METAL REFRESH' AND log_txt = 'Reports Enabled' order by log_date desc")
    GetLastDataRefresh = p_da.GetFields(ll_cursor, "log_date")
    Call p_da.Close(ll_cursor)
    ll_cursor = 0

    Exit Function
    
ErrorHandler:
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If
    Call ErrorHandler(Extender.Name & ".GetLastDataRefresh")
End Function

Private Sub Process_Sales()
On Error GoTo ErrorHandler
    Dim ls_req As String
    Dim ls_ReqCG As String
    Dim ll_cursor As Long
    Dim ll_curentCol As Long
    Dim ll_currYear As Long
    
    If Not CheckReportAvailable() Then
        Exit Sub
    End If

    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        tv1.SetFocus
        Exit Sub
    End If
    
    ' check if sales is available
    If Get_A_Config("RPT_SALES_ON") <> "Y" Then
        ' not available due to a data refresh
        tbs_sales.SelectedItem.ToolTipText = GetLabel(frm_sales.Tag & "NODATA", "#Data not available.")
        frm_sales.Caption = tbs_sales.SelectedItem.ToolTipText
        grd_Sales.Visible = False
        grd_sales_MSA.Visible = False
        lbl_salesCalculation.Caption = GetLabel("lbl_sales_REFRESH", "#Report is not available due to a data update," & vbCrLf & "please try later.")
        lbl_salesCalculation.Visible = True         ' bugfix JN 11.4.2013
        frm_sales.Visible = True
        Call frm_sales.Refresh
        DoEvents
            
        Exit Sub
    End If
    
    Call LockScreen(True)
    
'    ll_currYear = Left(cal2.date_yyyymmdd, 4)
    ll_currYear = Year(Date)
    ReDim ms_MsgInfo(3, 1)
    ms_MsgInfo(0, 0) = "$TV1$"
    ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
    ms_MsgInfo(1, 0) = "$YEAR$"
    ms_MsgInfo(1, 1) = ll_currYear
    ms_MsgInfo(2, 0) = "$PREV_YEAR$"
    ms_MsgInfo(2, 1) = ll_currYear - 1
    ms_MsgInfo(3, 0) = "$DATA_REFRESH$"
    ms_MsgInfo(3, 1) = Format(GetLastDataRefresh, "dd/mm/yy hh:mm")
    
    frm_sales.Visible = True
    tbs_sales.SelectedItem.ToolTipText = GetLabel(frm_sales.Tag, "#Sales: $TV1$  $YEAR$ vs $PREV_YEAR$ last data refresh:$DATA_REFRESH$", ms_MsgInfo)
    frm_sales.Caption = tbs_sales.SelectedItem.ToolTipText
    
    grd_Sales.Visible = False
    grd_sales_MSA.Visible = False
    
    grd_Sales.Clear
    Call RefreshScreen
    
    With grd_Sales
        .Cols = 16
        .Rows = 1
            .ColWidth(0) = 800
            .ColWidth(1) = 1500
            .ColWidth(2) = 1050
            .ColWidth(3) = 1050
            .ColWidth(4) = 1050
            .ColWidth(5) = 1050
            .ColWidth(6) = 1050
            .ColWidth(7) = 1050
            .ColWidth(8) = 1050
            .ColWidth(9) = 1050
            .ColWidth(10) = 1050
            .ColWidth(11) = 1050
            .ColWidth(12) = 1050
            .ColWidth(13) = 1050
            .ColWidth(grd_Sales.Cols - 2) = 1200
            .ColWidth(grd_Sales.Cols - 1) = 1200
            .TextMatrix(0, 0) = GetLabel("s_sales", "#Sales")
            .TextMatrix(0, 1) = GetLabel("s_sales", "#Sales")
            .TextMatrix(0, 2) = GetLabel("s_jan", "#Jan")
            .TextMatrix(0, 3) = GetLabel("s_feb", "#Feb")
            .TextMatrix(0, 4) = GetLabel("s_march", "#March")
            .TextMatrix(0, 5) = GetLabel("s_april", "#April")
            .TextMatrix(0, 6) = GetLabel("s_may", "#May")
            .TextMatrix(0, 7) = GetLabel("s_jun", "#Jun")
            .TextMatrix(0, 8) = GetLabel("s_july", "#July")
            .TextMatrix(0, 9) = GetLabel("s_august", "#August")
            .TextMatrix(0, 10) = GetLabel("s_sept", "#Sept")
            .TextMatrix(0, 11) = GetLabel("s_oct", "#Oct")
            .TextMatrix(0, 12) = GetLabel("s_nov", "#Nov")
            .TextMatrix(0, 13) = GetLabel("s_dec", "#Dec")
            .TextMatrix(0, 14) = GetLabel("s_totalYTD", "#TOTAL YTD")
            .TextMatrix(0, grd_Sales.Cols - 1) = GetLabel("s_total", "#TOTAL")
            
            .MergeRow(0) = True
            .MergeCol(0) = True
            .RowHeight(0) = 350
            .FixedAlignment(0) = 4
            .FixedAlignment(1) = 4
            .FixedAlignment(2) = 4
            .FixedAlignment(3) = 4
            .FixedAlignment(4) = 4
            .FixedAlignment(5) = 4
            .FixedAlignment(6) = 4
            .FixedAlignment(7) = 4
            .FixedAlignment(8) = 4
            .FixedAlignment(9) = 4
            .FixedAlignment(10) = 4
            .FixedAlignment(11) = 4
            .FixedAlignment(12) = 4
            .FixedAlignment(13) = 4
            .FixedAlignment(14) = 4
            .FixedAlignment(15) = 4
            .WordWrap = True
            .ForeColor = vbBlue
            .LeftCol = 2
            
            .ColAlignment(14) = flexAlignRightCenter
    End With
    Call SetGridCelBold(grd_Sales, 0, grd_Sales.Cols - 1)
    Call SetGridCelBold(grd_Sales, 0, grd_Sales.Cols - 2)
    
    lbl_salesCalculation.Visible = True
    
    lbl_salesCalculation.Caption = GetLabel(lbl_salesCalculation.Tag, "#Calculating Sales report - Ceilings....")
    Call RefreshScreen
    
    Dim ll_GSVEUR_C001 As Long
    Dim ll_GSVEUR_C001_METAL As Long
    Dim ll_GSVEUR_C002 As Long
    Dim ll_GSVEUR_OTHER As Long
    Dim ll_Row As Long
    Dim ll_oldHandle As Long
    
    ll_GSVEUR_C001 = -1
    ll_GSVEUR_C002 = -1
    ll_GSVEUR_OTHER = -1
    ll_GSVEUR_C001_METAL = -1
    
    
    ls_ReqCG = GetSalesRequest(cb_trw.SelectedItem.GetData(0), Level_selected, "CG")
    If ls_ReqCG <> "" Then
        ls_ReqCG = ReplaceHolders(ls_ReqCG)
        ls_ReqCG = Replace(ls_ReqCG, "$cyear$", ll_currYear, , , vbTextCompare)
        ls_req = Replace(ls_ReqCG, "$CG_Code2$", "C001", , , vbTextCompare)
        ls_req = Replace(ls_req, "$UM_Code$", "M2", , , vbTextCompare)
        ls_req = Replace(ls_req, "$METAL_FLAG$", IIf(chk_sales_clgMetal.Value = 1, "''", "NULL"), , , vbTextCompare)

        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
            
        ' fill the grid
        ll_GSVEUR_C001 = FillGridSales(grd_Sales, ll_cursor, ll_currYear, False)
        Call p_da.Close(ll_cursor)
        
        ' do split between ceilings to metal/non metal
        If chk_sales_clgMetal.Value = 1 Then
            ' Rename current Ceilings to Ceilings Non Metal
            If ll_GSVEUR_C001 <> -1 Then
                For ll_Row = ll_GSVEUR_C001 To grd_Sales.Rows - 1
                    grd_Sales.TextMatrix(ll_Row, 0) = grd_Sales.TextMatrix(ll_Row, 0) + " - Non Metal"
                Next
            End If
            ls_req = Replace(ls_ReqCG, "$CG_Code2$", "C001", , , vbTextCompare)
            ls_req = Replace(ls_req, "$UM_Code$", "M2", , , vbTextCompare)
            ls_req = Replace(ls_req, "$METAL_FLAG$", "'X'", , , vbTextCompare)
            
            ll_cursor = OpenSQLSafe(p_da, ls_req)
                
            ' fill the grid
            ll_GSVEUR_C001_METAL = FillGridSales(grd_Sales, ll_cursor, ll_currYear, False)
            Call p_da.Close(ll_cursor)
            
            If ll_GSVEUR_C001_METAL <> -1 Then
                For ll_Row = ll_GSVEUR_C001_METAL To grd_Sales.Rows - 1
                    grd_Sales.TextMatrix(ll_Row, 0) = grd_Sales.TextMatrix(ll_Row, 0) + " - Metal"
                Next
            End If
        End If
        
        lbl_salesCalculation.Caption = GetLabel("lbl_salesCalculation_2", "#Calculating Sales report - Grids....")
        ll_oldHandle = LockWindowUpdate(0)
        UserControl.Refresh
        Call LockWindowUpdate(ll_oldHandle)

        ls_req = Replace(ls_ReqCG, "$CG_Code2$", "C002", , , vbTextCompare)
        ls_req = Replace(ls_req, "$UM_Code$", "LM", , , vbTextCompare)
        ls_req = Replace(ls_req, "$METAL_FLAG$", "NULL", , , vbTextCompare)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        ' fill the grid
        ll_GSVEUR_C002 = FillGridSales(grd_Sales, ll_cursor, ll_currYear, False)
        Call p_da.Close(ll_cursor)
    End If
    
    lbl_salesCalculation.Caption = GetLabel("lbl_salesCalculation_3", "#Calculating Sales report - Others....")
    Call RefreshScreen
    
    ls_req = GetSalesRequest(cb_trw.SelectedItem.GetData(0), Level_selected, "OTHER")
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        ls_req = Replace(ls_req, "$cyear$", ll_currYear, , , vbTextCompare)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        ' fill the grid
        ll_GSVEUR_OTHER = FillGridSales(grd_Sales, ll_cursor, ll_currYear, False)
        Call p_da.Close(ll_cursor)
        export_report.Visible = True
        sales_pdf_print.Visible = ((Level_selected <> 3) And (cb_trw.SelectedItem.GetData(0) <> 2)) Or (cb_trw.SelectedItem.GetData(0) = 5)
    End If
    
    lbl_salesCalculation.Caption = GetLabel("lbl_salesCalculation_4", "#Calculating Sales report - Totals....")
    Call RefreshScreen
    
    ' calculate totals
    Dim ll_col As Long, ld_total As Double
    
    For ll_Row = 1 To grd_Sales.Rows - 1
        ld_total = 0
        For ll_col = 2 To grd_Sales.Cols - 3
            If grd_Sales.TextMatrix(ll_Row, ll_col) <> "" Then
                ld_total = ld_total + grd_Sales.TextMatrix(ll_Row, ll_col)
            End If
        Next
        grd_Sales.TextMatrix(ll_Row, grd_Sales.Cols - 1) = FormatNumber(ld_total, 0)
        If ll_Row = ll_GSVEUR_C001 Or ll_Row = ll_GSVEUR_C002 Or ll_Row = ll_GSVEUR_OTHER Or ll_Row = ll_GSVEUR_C001_METAL Then
            ' put the same number as total
            grd_Sales.TextMatrix(ll_Row, grd_Sales.Cols - 2) = grd_Sales.TextMatrix(ll_Row, grd_Sales.Cols - 1)
        End If
    Next
    
    ' calculate total per month
    If grd_Sales.Rows > 2 Then
        Call Sales_Add_TotalLine(grd_Sales, ll_GSVEUR_C001, ll_GSVEUR_C001_METAL, ll_GSVEUR_C002, ll_GSVEUR_OTHER, ll_currYear)
    End If
    
    ' recalc %
    For ll_Row = 1 To grd_Sales.Rows - 2
        If grd_Sales.TextMatrix(ll_Row, 1) = "GSV EUR " & ll_currYear Or _
            grd_Sales.TextMatrix(ll_Row, 1) Like "Vol * " & ll_currYear Then
            ' calculate percentage into cell for current year
            If grd_Sales.TextMatrix(ll_Row + 1, grd_Sales.Cols - 2) <> 0 And grd_Sales.TextMatrix(ll_Row, grd_Sales.Cols - 2) > 0 Then
                grd_Sales.TextMatrix(ll_Row, grd_Sales.Cols - 2) = FormatNumber(CLng(grd_Sales.TextMatrix(ll_Row, grd_Sales.Cols - 2)) / CLng(grd_Sales.TextMatrix(ll_Row + 1, grd_Sales.Cols - 2)) * 100, 1) & "%"
            Else
                grd_Sales.TextMatrix(ll_Row, grd_Sales.Cols - 2) = "N/A"
            End If
        End If
    Next
    
    Call LockScreen(False)

    grd_Sales.Visible = True
    mb_sales_processed = True
    Exit Sub
    
ErrorHandler:
    Call LockScreen(False)
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If

    Call ErrorHandler(Extender.Name & ".Process_Sales")
End Sub

Private Sub RefreshScreen()
    Dim ll_oldHandle As Long
    ll_oldHandle = LockWindowUpdate(0)
    UserControl.Refresh
    Call LockWindowUpdate(ll_oldHandle)
End Sub

Private Sub Sales_Add_TotalLine(ByRef ao_grid As MSFlexGrid, ByVal al_C001_row As Long, ByVal al_C001_row_metal As Long, ByVal al_C002_row As Long, ByVal al_OTHER_row As Long, ByVal al_CY As Long)
On Error GoTo ErrorHandler
    Dim ll_col As Long
    
    With ao_grid
    .Rows = .Rows + 2
    ' fill row header
    Call SetRowHeader(ao_grid, .Rows - 2, GetLabel("s_total", "#TOTAL"), "GSV EUR " & al_CY, 320)
    Call SetRowHeader(ao_grid, .Rows - 1, GetLabel("s_total", "#TOTAL"), "GSV EUR " & al_CY - 1, 320)
    Call SetGridCelBold(ao_grid, .Rows - 2, 0)
    Call SetGridCelBold(ao_grid, .Rows - 1, 0)
    Call SetGridCelBold(ao_grid, .Rows - 2, 1)
    Call SetGridCelBold(ao_grid, .Rows - 1, 1)
    Call SetGridCelBold(ao_grid, .Rows - 2, .Cols - 2)
    Call SetGridCelBold(ao_grid, .Rows - 1, .Cols - 2)
    Call SetGridCelBold(ao_grid, .Rows - 2, .Cols - 1)
    Call SetGridCelBold(ao_grid, .Rows - 1, .Cols - 1)

    Dim ll_totalCY As Long
    Dim ll_totalLY As Long
    
    For ll_col = 2 To .Cols - 1
    
        ll_totalCY = 0
        ll_totalLY = 0
    
        If al_C001_row <> -1 Then
            ll_totalCY = ll_totalCY + CLng(.TextMatrix(al_C001_row, ll_col))
            ll_totalLY = ll_totalLY + CLng(.TextMatrix(al_C001_row + 1, ll_col))
        End If
        If al_C001_row_metal <> -1 Then
            ll_totalCY = ll_totalCY + CLng(.TextMatrix(al_C001_row_metal, ll_col))
            ll_totalLY = ll_totalLY + CLng(.TextMatrix(al_C001_row_metal + 1, ll_col))
        End If
        If al_C002_row <> -1 Then
            ll_totalCY = ll_totalCY + CLng(.TextMatrix(al_C002_row, ll_col))
            ll_totalLY = ll_totalLY + CLng(.TextMatrix(al_C002_row + 1, ll_col))
        End If
        If al_OTHER_row <> -1 Then
            ll_totalCY = ll_totalCY + CLng(.TextMatrix(al_OTHER_row, ll_col))
            ll_totalLY = ll_totalLY + CLng(.TextMatrix(al_OTHER_row + 1, ll_col))
        End If

        .TextMatrix(.Rows - 2, ll_col) = FormatNumber(ll_totalCY, 0)
        .TextMatrix(.Rows - 1, ll_col) = FormatNumber(ll_totalLY, 0)
    Next
    Call SetGridRowBackColor(ao_grid, .Rows - 2, COLOR_GREY)
    Call SetGridRowBackColor(ao_grid, .Rows - 1, COLOR_GREY)
    
    End With
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".Sales_Add_TotalLine")
End Sub

Private Sub Process_Sales_MSA()
On Error GoTo ErrorHandler
    Dim ls_req As String
    Dim ls_ReqCG As String
    'Dim a As ARMSYSCOMLib.ArmDb
    Dim ll_cursor As Long
    Dim ll_curentCol As Long
    Dim ll_currYear As Long
    
    If Not CheckReportAvailable() Then
        Exit Sub
    End If

    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        tv1.SetFocus
        Exit Sub
    End If
    
    If Level_selected >= 3 Or cb_trw.SelectedItem.GetData(0) = 2 Then
        ' not applicable in this case
        tbs_sales.SelectedItem.ToolTipText = GetLabel(frm_sales.Tag & "MSANOT", "#SAP + MSA Sales: Not applicable")
        frm_sales.Caption = tbs_sales.SelectedItem.ToolTipText
        grd_Sales.Visible = False
        grd_sales_MSA.Visible = False
        lbl_salesCalculation.Caption = GetLabel("lbl_sales_NOMSA", "#All sales cannot be displayed at this level.")
        lbl_salesCalculation.Visible = True         ' bugfix JN 11.4.2013
        frm_sales.Visible = True
        Call frm_sales.Refresh
        DoEvents
            
        Exit Sub
    End If
    
    If Get_A_Config("RPT_SALES_ON") <> "Y" Then
        ' not available due to a data refresh
        tbs_sales.SelectedItem.ToolTipText = GetLabel(frm_sales.Tag & "NODATA", "#Data not available.")
        frm_sales.Caption = tbs_sales.SelectedItem.ToolTipText
        grd_Sales.Visible = False
        grd_sales_MSA.Visible = False
        lbl_salesCalculation.Caption = GetLabel("lbl_sales_REFRESH", "#Report is not available due to a data update," & vbCrLf & "please try later.")
        lbl_salesCalculation.Visible = True         ' bugfix JN 11.4.2013
        frm_sales.Visible = True
        Call frm_sales.Refresh
        DoEvents
            
        Exit Sub
    End If

    
    Call LockScreen(True)
    
'    ll_currYear = Left(cal2.date_yyyymmdd, 4)
    ll_currYear = Year(Date)
    ReDim ms_MsgInfo(3, 1)
    ms_MsgInfo(0, 0) = "$TV1$"
    ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
    ms_MsgInfo(1, 0) = "$YEAR$"
    ms_MsgInfo(1, 1) = ll_currYear
    ms_MsgInfo(2, 0) = "$PREV_YEAR$"
    ms_MsgInfo(2, 1) = ll_currYear - 1
    ms_MsgInfo(3, 0) = "$DATA_REFRESH$"
    ms_MsgInfo(3, 1) = Format(GetLastDataRefresh, "dd/mm/yy hh:mm")

    frm_sales.Visible = True
    tbs_sales.SelectedItem.ToolTipText = GetLabel(frm_sales.Tag & "MSA", "#SAP + MSA Sales: $TV1$  $YEAR$ vs $PREV_YEAR$ (last data refresh:$DATA_REFRESH$)", ms_MsgInfo)
    frm_sales.Caption = tbs_sales.SelectedItem.ToolTipText

    grd_Sales.Visible = False
    grd_sales_MSA.Visible = False
    
    grd_sales_MSA.Clear
    
    With grd_sales_MSA
        .Cols = 16
        .Rows = 1
            .ColWidth(0) = 800
            .ColWidth(1) = 1500
            .ColWidth(2) = 1050
            .ColWidth(3) = 1050
            .ColWidth(4) = 1050
            .ColWidth(5) = 1050
            .ColWidth(6) = 1050
            .ColWidth(7) = 1050
            .ColWidth(8) = 1050
            .ColWidth(9) = 1050
            .ColWidth(10) = 1050
            .ColWidth(11) = 1050
            .ColWidth(12) = 1050
            .ColWidth(13) = 1050
            .ColWidth(grd_sales_MSA.Cols - 2) = 1200
            .ColWidth(grd_sales_MSA.Cols - 1) = 1200
            .TextMatrix(0, 0) = GetLabel("s_sales", "#Sales")
            .TextMatrix(0, 1) = GetLabel("s_sales", "#Sales")
            .TextMatrix(0, 2) = GetLabel("s_jan", "#Jan")
            .TextMatrix(0, 3) = GetLabel("s_feb", "#Feb")
            .TextMatrix(0, 4) = GetLabel("s_march", "#March")
            .TextMatrix(0, 5) = GetLabel("s_april", "#April")
            .TextMatrix(0, 6) = GetLabel("s_may", "#May")
            .TextMatrix(0, 7) = GetLabel("s_jun", "#Jun")
            .TextMatrix(0, 8) = GetLabel("s_july", "#July")
            .TextMatrix(0, 9) = GetLabel("s_august", "#August")
            .TextMatrix(0, 10) = GetLabel("s_sept", "#Sept")
            .TextMatrix(0, 11) = GetLabel("s_oct", "#Oct")
            .TextMatrix(0, 12) = GetLabel("s_nov", "#Nov")
            .TextMatrix(0, 13) = GetLabel("s_dec", "#Dec")
            .TextMatrix(0, grd_sales_MSA.Cols - 2) = GetLabel("s_totalYTD", "#TOTAL YTD")
            .TextMatrix(0, grd_sales_MSA.Cols - 1) = GetLabel("s_total", "#TOTAL")
            
            .MergeRow(0) = True
            .MergeCol(0) = True
            .RowHeight(0) = 350
            .FixedAlignment(0) = 4
            .FixedAlignment(1) = 4
            .FixedAlignment(2) = 4
            .FixedAlignment(3) = 4
            .FixedAlignment(4) = 4
            .FixedAlignment(5) = 4
            .FixedAlignment(6) = 4
            .FixedAlignment(7) = 4
            .FixedAlignment(8) = 4
            .FixedAlignment(9) = 4
            .FixedAlignment(10) = 4
            .FixedAlignment(11) = 4
            .FixedAlignment(12) = 4
            .FixedAlignment(13) = 4
            .FixedAlignment(14) = 4
            .FixedAlignment(15) = 4
            .WordWrap = True
            .ForeColor = vbBlue
            .LeftCol = 2
            
            .ColAlignment(14) = flexAlignRightCenter
    End With
    Call SetGridCelBold(grd_sales_MSA, 0, grd_sales_MSA.Cols - 2)
    Call SetGridCelBold(grd_sales_MSA, 0, grd_sales_MSA.Cols - 1)
    
    lbl_salesCalculation.Visible = True
    
    lbl_salesCalculation.Caption = GetLabel(lbl_salesCalculation.Tag, "#Calculating Sales report - Ceilings....")
    Call frm_sales.Refresh
    DoEvents
    
    Dim ll_GSVEUR_C001 As Long
    Dim ll_GSVEUR_C002 As Long
    Dim ll_GSVEUR_OTHER As Long
    Dim ll_GSVEUR_C001_METAL As Long
    Dim ll_Row As Long
    ll_GSVEUR_C001 = -1
    ll_GSVEUR_C002 = -1
    ll_GSVEUR_OTHER = -1
    ll_GSVEUR_C001_METAL = -1

    ls_ReqCG = GetSalesRequest(cb_trw.SelectedItem.GetData(0), Level_selected, "CG", "MSA")
    If ls_ReqCG <> "" Then
        ls_ReqCG = ReplaceHolders(ls_ReqCG)
        ls_ReqCG = Replace(ls_ReqCG, "$cyear$", ll_currYear, , , vbTextCompare)
        ls_req = Replace(ls_ReqCG, "$CG_Code2$", "C001", , , vbTextCompare)
        ls_req = Replace(ls_req, "$UM_Code$", "M2", , , vbTextCompare)
        ls_req = Replace(ls_req, "$METAL_FLAG$", IIf(chk_sales_clgMetal.Value = 1, "''", "NULL"), , , vbTextCompare)

        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
            
        ' fill the grid
        ll_GSVEUR_C001 = FillGridSales(grd_sales_MSA, ll_cursor, ll_currYear, False)
        
        Call p_da.Close(ll_cursor)
        ' do split between ceilings to metal/non metal
        If chk_sales_clgMetal.Value = 1 Then
            ' Rename current Ceilings to Ceilings Non Metal
            For ll_Row = ll_GSVEUR_C001 To grd_sales_MSA.Rows - 1
                grd_sales_MSA.TextMatrix(ll_Row, 0) = grd_sales_MSA.TextMatrix(ll_Row, 0) + " - Non Metal"
            Next
            ls_req = Replace(ls_ReqCG, "$CG_Code2$", "C001", , , vbTextCompare)
            ls_req = Replace(ls_req, "$UM_Code$", "M2", , , vbTextCompare)
            ls_req = Replace(ls_req, "$METAL_FLAG$", "'X'", , , vbTextCompare)
            
            ll_cursor = OpenSQLSafe(p_da, ls_req)
                
            ' fill the grid
            ll_GSVEUR_C001_METAL = FillGridSales(grd_sales_MSA, ll_cursor, ll_currYear, False)
            Call p_da.Close(ll_cursor)
            
            For ll_Row = ll_GSVEUR_C001_METAL To grd_sales_MSA.Rows - 1
                grd_sales_MSA.TextMatrix(ll_Row, 0) = grd_sales_MSA.TextMatrix(ll_Row, 0) + " - Metal"
            Next
        End If
        
        
        lbl_salesCalculation.Caption = GetLabel("lbl_salesCalculation_2", "#Calculating Sales report - Grids....")
        Call frm_sales.Refresh
        DoEvents

        ls_req = Replace(ls_ReqCG, "$CG_Code2$", "C002", , , vbTextCompare)
        ls_req = Replace(ls_req, "$UM_Code$", "LM", , , vbTextCompare)
        ls_req = Replace(ls_req, "$METAL_FLAG$", "NULL", , , vbTextCompare)
            
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        ' fill the grid
        ll_GSVEUR_C002 = FillGridSales(grd_sales_MSA, ll_cursor, ll_currYear, False)
        Call p_da.Close(ll_cursor)
    End If
    
    lbl_salesCalculation.Caption = GetLabel("lbl_salesCalculation_3", "#Calculating Sales report - Others....")
    Call frm_sales.Refresh
    DoEvents
    
    ls_req = GetSalesRequest(cb_trw.SelectedItem.GetData(0), Level_selected, "OTHER", "MSA")
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        ls_req = Replace(ls_req, "$cyear$", ll_currYear, , , vbTextCompare)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        ' fill the grid
        ll_GSVEUR_OTHER = FillGridSales(grd_sales_MSA, ll_cursor, ll_currYear, False)
        Call p_da.Close(ll_cursor)
        export_report.Visible = True
        sales_pdf_print.Visible = (Level_selected <> 3) And (cb_trw.SelectedItem.GetData(0) <> 2)
    End If
    
    lbl_salesCalculation.Caption = GetLabel("lbl_salesCalculation_4", "#Calculating Sales report - Totals....")
    Call frm_sales.Refresh
    DoEvents
    
    ' calculate totals
    Dim ll_col As Long, ld_total As Double
    
    For ll_Row = 1 To grd_sales_MSA.Rows - 1
        ld_total = 0
        For ll_col = 2 To grd_sales_MSA.Cols - 3
            If grd_sales_MSA.TextMatrix(ll_Row, ll_col) <> "" Then
                ld_total = ld_total + grd_sales_MSA.TextMatrix(ll_Row, ll_col)
            End If
        Next
        grd_sales_MSA.TextMatrix(ll_Row, grd_sales_MSA.Cols - 1) = FormatNumber(ld_total, 0)
        If ll_Row = ll_GSVEUR_C001 Or ll_Row = ll_GSVEUR_C002 Or ll_Row = ll_GSVEUR_OTHER Or ll_Row = ll_GSVEUR_C001_METAL Then
            ' put the same number as total
            grd_sales_MSA.TextMatrix(ll_Row, grd_sales_MSA.Cols - 2) = grd_sales_MSA.TextMatrix(ll_Row, grd_sales_MSA.Cols - 1)
        End If
    
    Next
    
    ' grd_sales_MSA total per month
    If grd_sales_MSA.Rows > 2 Then
        Call Sales_Add_TotalLine(grd_sales_MSA, ll_GSVEUR_C001, ll_GSVEUR_C001_METAL, ll_GSVEUR_C002, ll_GSVEUR_OTHER, ll_currYear)
    End If
    
    ' recalc %
    For ll_Row = 1 To grd_sales_MSA.Rows - 2
        If grd_sales_MSA.TextMatrix(ll_Row, 1) = "GSV EUR " & ll_currYear Or _
            grd_sales_MSA.TextMatrix(ll_Row, 1) Like "Vol * " & ll_currYear Then
            ' calculate percentage into cell for current year
            If grd_sales_MSA.TextMatrix(ll_Row + 1, grd_sales_MSA.Cols - 2) <> 0 And grd_sales_MSA.TextMatrix(ll_Row, grd_sales_MSA.Cols - 2) > 0 Then
                grd_sales_MSA.TextMatrix(ll_Row, grd_sales_MSA.Cols - 2) = FormatNumber(CLng(grd_sales_MSA.TextMatrix(ll_Row, grd_sales_MSA.Cols - 2)) / CLng(grd_sales_MSA.TextMatrix(ll_Row + 1, grd_sales_MSA.Cols - 2)) * 100, 1) & "%"
            Else
                grd_sales_MSA.TextMatrix(ll_Row, grd_sales_MSA.Cols - 2) = "N/A"
            End If
        End If
    Next


    grd_sales_MSA.Visible = True
    'lbl_salesCalculation.Caption = ""
    'lbl_salesCalculation.Visible = False
    Call LockScreen(False)

    grd_sales_MSA.Visible = True
    mb_sales_MSA_processed = True
    Exit Sub
    
ErrorHandler:
    Call LockScreen(False)
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If

    Call ErrorHandler(Extender.Name & ".Process_Sales_MSA")
End Sub


Private Sub Process_StatusProjects()
On Error GoTo ErrorHandler
    Dim ls_req As String
    Dim ll_cursor As Long
    
    If Not CheckReportAvailable() Then
        Exit Sub
    End If

    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        tv1.SetFocus
        Exit Sub
    End If
    
    Call LockScreen(True)
    
    ReDim ms_MsgInfo(2, 1)
    ms_MsgInfo(0, 0) = "$TV1$"
    ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
    ms_MsgInfo(1, 0) = "$FROM$"
    ms_MsgInfo(1, 1) = cal1.date_courte
    ms_MsgInfo(2, 0) = "$TO$"
    ms_MsgInfo(2, 1) = cal2.date_courte
    frm_statusProjects.Visible = True
    frm_statusProjects.Caption = GetLabel(frm_statusProjects.Tag, "#Projects $TV1$ by status between $FROM$ and $TO$", ms_MsgInfo)
    
    grd_StatusProjects.Visible = False
    img_psMin.Visible = False
    img_psMax.Visible = False
    
    grd_StatusProjects.Rows = grd_StatusProjects.FixedRows        ' remove all data lines from grid
    grd_StatusProjects.LeftCol = 4                                 ' ensure visible part is at top left

    
    lbl_statusProjCalculation.Visible = True
    
    lbl_statusProjCalculation.Caption = GetLabel(lbl_statusProjCalculation.Tag, "#Calculating Status Project report - Created....")
    Call frm_statusProjects.Refresh
    DoEvents
        
    Dim ll_wonColU As Long
    Dim ll_lostColU As Long
    
    ll_wonColU = GRD_GetColIndex(mo_StatusProjectsInfo, "WonU")
    ll_wonColU = mo_StatusProjectsInfo.Cols(ll_wonColU).Index
    ll_lostColU = GRD_GetColIndex(mo_StatusProjectsInfo, "LostU")
    ll_lostColU = mo_StatusProjectsInfo.Cols(ll_lostColU).Index

    ls_req = GetStatusProjectsRequest(cb_trw.SelectedItem.GetData(0), Level_selected, "C")
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        ' fill the grid
        Call FillGridStatusProjects(grd_StatusProjects, ll_cursor, C_PS_C_STATU_COL, C_PS_C_TOTAL_COL, -1, -1, -1)
        Call p_da.Close(ll_cursor)
'        Call CalculateWonLostPercent(grd_StatusProjects, ll_wonColC, ll_lostColC, 5)
        
    End If
    
    lbl_statusProjCalculation.Caption = GetLabel("lbl_statusProjCalc_2", "#Calculating Status Project report - Updated....")
    Call frm_statusProjects.Refresh
    DoEvents
    
    ls_req = GetStatusProjectsRequest(cb_trw.SelectedItem.GetData(0), Level_selected, "U")
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        ' fill the grid
        Call FillGridStatusProjects(grd_StatusProjects, ll_cursor, C_PS_U_STATU_COL, C_PS_U_TOTAL_COL, C_PS_U_NOTACTIVE_COL, ll_wonColU, ll_lostColU)
        Call p_da.Close(ll_cursor)
        Call CalculateWonLostPercent(grd_StatusProjects, ll_wonColU, ll_lostColU, 19)
        export_report.Visible = True
    End If
    
    lbl_statusProjCalculation.Caption = GetLabel("lbl_statusProjCalc_3", "#Calculating Status Project report - Totals....")
    Call frm_statusProjects.Refresh
    DoEvents
    
    ' calculate totals
    Dim ll_col As Long, ll_Row As Long
    Dim ld_totalC As Double
    
    If ml_projCounts = 0 Then
        ml_projCounts = OpenSQLSafe(p_da, ReplaceHolders("EXEC ProjectStatT_Market"))
    End If
    
    For ll_Row = 2 To grd_StatusProjects.Rows - 1
        ' capculate percentace for Updated projects
        Dim ld_Value As Double
        If p_da.Find(ml_projCounts, Array("BMK_Code", "CT_Code"), Array(grd_StatusProjects.TextMatrix(ll_Row, 0), grd_StatusProjects.TextMatrix(ll_Row, 1))) >= 0 Then
            If grd_StatusProjects.TextMatrix(ll_Row, C_PS_U_NOTACTIVE_COL) <> "" Then
                ld_Value = CDbl(grd_StatusProjects.TextMatrix(ll_Row, C_PS_U_TOTAL_COL)) / (p_da.GetFields(ml_projCounts, "AllPrjCount") + CDbl(grd_StatusProjects.TextMatrix(ll_Row, C_PS_U_NOTACTIVE_COL))) * 100
                If ld_Value > 1 Then
                    grd_StatusProjects.TextMatrix(ll_Row, C_PS_U_NOTACTIVE_COL) = FormatNumber(ld_Value, 0) & " %"
                Else
                    grd_StatusProjects.TextMatrix(ll_Row, C_PS_U_NOTACTIVE_COL) = FormatNumber(ld_Value, 2) & " %"
                End If
            End If
        Else
            ' no active project
            grd_StatusProjects.TextMatrix(ll_Row, C_PS_U_NOTACTIVE_COL) = ""
        End If
        
        Call SumCols(grd_StatusProjects, ll_Row, C_PS_C_STATU_COL, C_PS_C_STATU_COL + 5, C_PS_C_SUM_COL)
        Call SumCols(grd_StatusProjects, ll_Row, C_PS_U_STATU_COL, C_PS_U_STATU_COL + 4, C_PS_U_SUM_COL)
    Next
    
    Call SetGridColBackColor(grd_StatusProjects, C_PS_C_SUM_COL, COLOR_GREY)
    Call SetGridColBackColor(grd_StatusProjects, C_PS_U_SUM_COL, COLOR_GREY)
    
    ' calculate totals
    grd_StatusProjects.Rows = grd_StatusProjects.Rows + 1
    grd_StatusProjects.TextMatrix(grd_StatusProjects.Rows - 1, 2) = GetLabel("s_total", "#TOTAL")
    For ll_col = 4 To grd_StatusProjects.Cols - 7
        If ll_col <> 5 Then
            ld_totalC = 0
            For ll_Row = grd_StatusProjects.FixedRows To grd_StatusProjects.Rows - 2
                If grd_StatusProjects.TextMatrix(ll_Row, ll_col) <> "" Then
                    ld_totalC = ld_totalC + grd_StatusProjects.TextMatrix(ll_Row, ll_col)
                End If
            Next
            grd_StatusProjects.TextMatrix(grd_StatusProjects.Rows - 1, ll_col) = FormatNumber(ld_totalC, 0)
        End If
    Next
    
    Call SetGridRowBackColor(grd_StatusProjects, grd_StatusProjects.Rows - 1, COLOR_GREY)
    Call SetGridRowForeColor(grd_StatusProjects, grd_StatusProjects.Rows - 1, vbRed)
    Call SetGridRowBold(grd_StatusProjects, grd_StatusProjects.Rows - 1)
    
    ' CALCULATE sub totals per market
    Dim ll_CurrentLine As Long
    Dim ll_BMKstartLine As Long
    Dim ls_BMK_Code As String
    
    ll_CurrentLine = 2
    ll_BMKstartLine = -1
    ls_BMK_Code = ""
    While ll_CurrentLine <> grd_StatusProjects.Rows
        If ls_BMK_Code <> grd_StatusProjects.TextMatrix(ll_CurrentLine, 0) Then
            If ll_BMKstartLine <> -1 Then
                Debug.Assert (ls_BMK_Code <> "")
                ' process the lines between ll_BMKstartLine and ll_currentLine
                Call grd_StatusProjects.AddItem(ls_BMK_Code, ll_CurrentLine)
                
                grd_StatusProjects.TextMatrix(ll_CurrentLine, 2) = grd_StatusProjects.TextMatrix(ll_BMKstartLine, 2)
                grd_StatusProjects.TextMatrix(ll_CurrentLine, 3) = GetLabel("s_total2", "#Total")
                
                Call SumLines(grd_StatusProjects, ll_BMKstartLine, ll_CurrentLine - 1, 4, grd_StatusProjects.Cols - 7)
'                Call SumLinesWLPercent(grd_StatusProjects, ll_BMKstartLine, ll_CurrentLine - 1, 5, ll_wonColC, ll_lostColC)
                Call SumLinesWLPercent(grd_StatusProjects, ll_BMKstartLine, ll_CurrentLine - 1, 19, ll_wonColU, ll_lostColU)
                
                Call SetGridRowBackColor(grd_StatusProjects, ll_CurrentLine, COLOR_GREY2)
                Call SetGridRowForeColor(grd_StatusProjects, ll_CurrentLine, vbBlue)
                Call SetGridRowBold(grd_StatusProjects, ll_CurrentLine)

                
                ' move currentline to next line
                ll_CurrentLine = ll_CurrentLine + 1
            End If
            ll_BMKstartLine = ll_CurrentLine
            ls_BMK_Code = grd_StatusProjects.TextMatrix(ll_CurrentLine, 0)
        End If
        
        ll_CurrentLine = ll_CurrentLine + 1
    Wend
    
    grd_StatusProjects.Visible = True
    Call LockScreen(False)

    grd_StatusProjects.Visible = True
    mb_statusProjects_processed = True
    If ml_psCounryColWidth = 0 Then
        img_psMin.Visible = True
    Else
        Call img_psMax_Click
    End If

    Exit Sub
    
ErrorHandler:
    Call LockScreen(False)
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If

    Call ErrorHandler(Extender.Name & ".Process_StatusProjects")
End Sub


Private Sub Process_StatusProjects2()
On Error GoTo ErrorHandler
    Dim ls_req As String
    Dim ll_cursor As Long
    
    If Not CheckReportAvailable() Then
        Exit Sub
    End If

    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        tv1.SetFocus
        Exit Sub
    End If
    
    If chk_PS2_Grouping(0).Value = vbUnchecked And chk_PS2_Grouping(1).Value = vbUnchecked Then
        MsgBox MsgText(1516, ms_Language_Code, "#M1516 ... At least one grouping must be selected!")
        Exit Sub
    End If
    
    Call LockScreen(True)
    
    ReDim ms_MsgInfo(3, 1)
    ms_MsgInfo(0, 0) = "$TV1$"
    ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
    ms_MsgInfo(1, 0) = "$FROM$"
    ms_MsgInfo(1, 1) = cal1.date_courte
    ms_MsgInfo(2, 0) = "$TO$"
    ms_MsgInfo(2, 1) = cal2.date_courte
    ms_MsgInfo(3, 0) = "$ACTIVEPRJ$"
    ms_MsgInfo(3, 1) = ml_ActivePrj
    
    frm_statusProjects2.Visible = True
    frm_statusProjects2.Caption = GetLabel(frm_statusProjects2.Tag, "#Projects $TV1$ by status between $FROM$ and $TO$ (Reference period for % calcualtion is past $ACTIVEPRJ$ days)", ms_MsgInfo)
    
    grd_StatusProjects2.Visible = False
    frm_PS2_Grouping.Visible = False
    img_ps2Min.Visible = False
    img_ps2Max.Visible = False

    
    grd_StatusProjects2.Rows = grd_StatusProjects2.FixedRows        ' remove all data lines from grid
    grd_StatusProjects2.LeftCol = 6                                 ' ensure visible part is at top left
    
    lbl_statusProj2Calculation.Visible = True
    
    lbl_statusProj2Calculation.Caption = GetLabel(lbl_statusProj2Calculation.Tag, "#Calculating Status Project2 report - Created....")
    Call frm_statusProjects2.Refresh
    DoEvents
    
    Dim ll_totalDescCol As Long
    ll_totalDescCol = 3        ' Country col is containing total in listing row for market total data

    ls_req = GetStatusProjectsGrpRequest(cb_trw.SelectedItem.GetData(0), Level_selected, "C2")
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        ' manage country and sales rep columns
        If p_da.GetFields(ll_cursor, "SR_Code") = "" Then
            If grd_StatusProjects2.ColWidth(5) <> 0 Then
                ml_ps2SalesRepColWidth = 0
                grd_StatusProjects2.ColWidth(5) = 0
            End If
        Else
            If grd_StatusProjects2.ColWidth(5) = 0 Then
                ml_ps2SalesRepColWidth = IIf(ml_ps2SalesRepColWidth = 0, 900, ml_ps2SalesRepColWidth)
                grd_StatusProjects2.ColWidth(5) = ml_ps2SalesRepColWidth
            End If
        End If
            
        If p_da.GetFields(ll_cursor, "CT_Code") = "" Then
            If grd_StatusProjects2.ColWidth(3) <> 0 Then
                ml_ps2CounryColWidth = 0
                grd_StatusProjects2.ColWidth(3) = 0
            End If
            ll_totalDescCol = 5     ' total is moved to Sales rep column
        Else
            If grd_StatusProjects2.ColWidth(3) = 0 Then
                ml_ps2CounryColWidth = IIf(ml_ps2CounryColWidth = 0, 1050, ml_ps2CounryColWidth)
                grd_StatusProjects2.ColWidth(3) = ml_ps2CounryColWidth
            End If
        End If
            
        ' fill the grid
        Call FillGridStatusProjects(grd_StatusProjects2, ll_cursor, C_PS2_C_STATU_COL, -1, -1, -1, -1)
        Call p_da.Close(ll_cursor)
    End If
    
    lbl_statusProj2Calculation.Caption = GetLabel("lbl_statusProj2Calc_2", "#Calculating Status Project2 report - Updated....")
    Call frm_statusProjects2.Refresh
    DoEvents
    
    ls_req = GetStatusProjectsGrpRequest(cb_trw.SelectedItem.GetData(0), Level_selected, "U2")
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        ' fill the grid
        Call FillGridStatusProjects(grd_StatusProjects2, ll_cursor, C_PS2_U_STATU_COL, C_PS2_U_TOTAL_COL, -1, -1, -1)
        Call p_da.Close(ll_cursor)
    End If
    
    lbl_statusProj2Calculation.Caption = GetLabel("lbl_statusProj2Calc_3", "#Calculating Status Project 2 report - Totals....")
    Call frm_statusProjects2.Refresh
    DoEvents
    
    ' step 3 we recalculate total + won + lost
    ls_req = GetStatusProjectsGrpRequest(cb_trw.SelectedItem.GetData(0), Level_selected, "U2T")
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        ' fill the grid
        Call FillGridStatusProjectsT(grd_StatusProjects2, ll_cursor, C_PS2_U_TOTAL_UNIQUE_COL)
        Call p_da.Close(ll_cursor)
'        Call CalculateWonLostPercent(grd_StatusProjects2, ll_wonColU, ll_lostColU, 21)
    End If
    export_report.Visible = True
    
    ' calculate totals
    Dim ll_col As Long, ll_Row As Long
    Dim ld_totalC As Double
    For ll_Row = 2 To grd_StatusProjects2.Rows - 1
        ' calculate summ
        Call SumCols(grd_StatusProjects2, ll_Row, C_PS2_C_STATU_COL, C_PS2_C_STATU_COL + 7, C_PS2_C_SUM_COL)
        Call SumCols(grd_StatusProjects2, ll_Row, C_PS2_U_STATU_COL, C_PS2_U_STATU_COL + 7, C_PS2_U_SUM_COL)
    Next

    Call SetGridColBackColor(grd_StatusProjects2, C_PS2_C_SUM_COL, COLOR_GREY)
    Call SetGridColBackColor(grd_StatusProjects2, C_PS2_U_SUM_COL, COLOR_GREY)
    
    grd_StatusProjects2.Rows = grd_StatusProjects2.Rows + 1
    If Level_selected = 0 Then
        grd_StatusProjects2.TextMatrix(grd_StatusProjects2.Rows - 1, 2) = GetLabel("s_total", "#TOTAL")
        For ll_col = 6 To grd_StatusProjects2.Cols - 5
            ld_totalC = 0
            For ll_Row = grd_StatusProjects2.FixedRows To grd_StatusProjects2.Rows - 2
                If grd_StatusProjects2.TextMatrix(ll_Row, ll_col) <> "" Then
                    ld_totalC = ld_totalC + grd_StatusProjects2.TextMatrix(ll_Row, ll_col)
                End If
            Next
            grd_StatusProjects2.TextMatrix(grd_StatusProjects2.Rows - 1, ll_col) = FormatNumber(ld_totalC, 0)
        Next
        
        Call SetGridRowBackColor(grd_StatusProjects2, grd_StatusProjects2.Rows - 1, COLOR_GREY)
        Call SetGridRowForeColor(grd_StatusProjects2, grd_StatusProjects2.Rows - 1, vbRed)
        Call SetGridRowBold(grd_StatusProjects2, grd_StatusProjects2.Rows - 1)
    End If
    
    ' CALCULATE sub totals per market
    Dim ll_CurrentLine As Long
    Dim ll_BMKstartLine As Long
    Dim ls_BMK_Code As String
    
    ll_CurrentLine = 2
    ll_BMKstartLine = -1
    ls_BMK_Code = ""
    While ll_CurrentLine <> grd_StatusProjects2.Rows
        If ls_BMK_Code <> grd_StatusProjects2.TextMatrix(ll_CurrentLine, 0) Then
            If ll_BMKstartLine <> -1 Then
                Debug.Assert (ls_BMK_Code <> "")
                ' process the lines between ll_BMKstartLine and ll_currentLine
                Call grd_StatusProjects2.AddItem(ls_BMK_Code, ll_CurrentLine)
                
                grd_StatusProjects2.TextMatrix(ll_CurrentLine, 2) = grd_StatusProjects2.TextMatrix(ll_BMKstartLine, 2)
                grd_StatusProjects2.TextMatrix(ll_CurrentLine, ll_totalDescCol) = GetLabel("s_total2", "#Total")
                
                Call SumLines(grd_StatusProjects2, ll_BMKstartLine, ll_CurrentLine - 1, 6, grd_StatusProjects2.Cols - 5)
                
                Call SetGridRowBackColor(grd_StatusProjects2, ll_CurrentLine, COLOR_GREY2)
                Call SetGridRowForeColor(grd_StatusProjects2, ll_CurrentLine, vbBlue)
                Call SetGridRowBold(grd_StatusProjects2, ll_CurrentLine)

                
                ' move currentline to next line
                ll_CurrentLine = ll_CurrentLine + 1
            End If
            ll_BMKstartLine = ll_CurrentLine
            ls_BMK_Code = grd_StatusProjects2.TextMatrix(ll_CurrentLine, 0)
        End If
        
        ll_CurrentLine = ll_CurrentLine + 1
    Wend
    
    Dim ll_proj2Counts  As Long
    ll_proj2Counts = OpenSQLSafe(p_da, ReplaceHolders(PS2_ReplaceGrouping("EXEC ProjectStatT2_$GRP1$$GRP2$_Market '$date1$', '$date2$'")))
    
    Dim ld_TotalProjects As Double
    Dim ll_earlyCreated As Long
    Dim la_searchArrayGrid() As String
    Dim ls_aux1 As String
    
    If p_da.GetFieldIndex(ll_proj2Counts, "BMK_Code") <> -1 Then
        ls_aux1 = "0"
    End If
    
    If p_da.GetFieldIndex(ll_proj2Counts, "CT_Code") <> -1 Then
        ls_aux1 = ls_aux1 & IIf(ls_aux1 = "", "", SEP) & "1"
    End If
    
    If p_da.GetFieldIndex(ll_proj2Counts, "SR_Code") <> -1 Then
        ls_aux1 = ls_aux1 & IIf(ls_aux1 = "", "", SEP) & "4"
    End If
    
    la_searchArrayGrid = Split(ls_aux1, SEP, , vbTextCompare)
    
    For ll_Row = grd_StatusProjects2.FixedRows To grd_StatusProjects2.Rows - 2
        ll_earlyCreated = 0
        If grd_StatusProjects2.TextMatrix(ll_Row, C_PS2_C_STATU_COL) <> "" Then ll_earlyCreated = grd_StatusProjects2.TextMatrix(ll_Row, C_PS2_C_STATU_COL)
        If grd_StatusProjects2.TextMatrix(ll_Row, C_PS2_C_STATU_COL + 1) <> "" Then ll_earlyCreated = ll_earlyCreated + grd_StatusProjects2.TextMatrix(ll_Row, C_PS2_C_STATU_COL + 1)
        If grd_StatusProjects2.TextMatrix(ll_Row, C_PS2_C_STATU_COL + 2) <> "" Then ll_earlyCreated = ll_earlyCreated + grd_StatusProjects2.TextMatrix(ll_Row, C_PS2_C_STATU_COL + 2)
        
        If ll_earlyCreated <> 0 And grd_StatusProjects2.TextMatrix(ll_Row, C_PS2_C_SUM_COL) <> "" Then
            Call PercentVal(grd_StatusProjects2, ll_Row, ll_earlyCreated, C_PS2_C_EARLY_PER_COL, grd_StatusProjects2.TextMatrix(ll_Row, C_PS2_C_SUM_COL))
        End If

        ' calculate percentace for Updated projects
        If grd_StatusProjects2.TextMatrix(ll_Row, 1) <> "" Or grd_StatusProjects2.TextMatrix(ll_Row, 4) <> "" Then
            If p_da.Find(ll_proj2Counts, getDBFieldsArray(ll_proj2Counts), getGridValuesArray(grd_StatusProjects2, ll_Row, la_searchArrayGrid)) >= 0 Then
                
                ' fill total info fields
                grd_StatusProjects2.TextMatrix(ll_Row, C_PS2_U_TOTALACTIVE_COL) = p_da.GetFields(ll_proj2Counts, "AllActivePrjCount")
                grd_StatusProjects2.TextMatrix(ll_Row, C_PS2_U_ORDERDPRIOR_COL) = p_da.GetFields(ll_proj2Counts, "OrderedPriorCount")
                
                ' total percent
                Call PercentCol(grd_StatusProjects2, ll_Row, C_PS2_U_TOTAL_UNIQUE_COL, C_PS2_U_TOTAL_PER_COL, p_da.GetFields(ll_proj2Counts, "AllPrjCount"))
                
                ' specified percent
                Call PercentCol(grd_StatusProjects2, ll_Row, C_PS2_U_STATU_COL + 6, C_PS2_U_WON_SPEC_PER_COL, p_da.GetFields(ll_proj2Counts, "AllPrjCount"))
                
                ' order percent
                Call PercentCol(grd_StatusProjects2, ll_Row, C_PS2_U_STATU_COL + 7, C_PS2_U_WON_ORDER_PER_COL, p_da.GetFields(ll_proj2Counts, "AllPrjCount"))
            End If
        Else
            ' fill total info fields
            grd_StatusProjects2.TextMatrix(ll_Row, C_PS2_U_TOTALACTIVE_COL) = GetDBColSUMByMarket(ll_proj2Counts, grd_StatusProjects2.TextMatrix(ll_Row, 0), "AllActivePrjCount")
            grd_StatusProjects2.TextMatrix(ll_Row, C_PS2_U_ORDERDPRIOR_COL) = GetDBColSUMByMarket(ll_proj2Counts, grd_StatusProjects2.TextMatrix(ll_Row, 0), "OrderedPriorCount")
        
            ' total per market
            ld_TotalProjects = GetDBColSUMByMarket(ll_proj2Counts, grd_StatusProjects2.TextMatrix(ll_Row, 0), "AllPrjCount")
            ' percent for total
            Call PercentCol(grd_StatusProjects2, ll_Row, C_PS2_U_TOTAL_UNIQUE_COL, C_PS2_U_TOTAL_PER_COL, ld_TotalProjects)
            ' specified percent
            Call PercentCol(grd_StatusProjects2, ll_Row, C_PS2_U_STATU_COL + 6, C_PS2_U_WON_SPEC_PER_COL, ld_TotalProjects)
            ' order percent
            Call PercentCol(grd_StatusProjects2, ll_Row, C_PS2_U_STATU_COL + 7, C_PS2_U_WON_ORDER_PER_COL, ld_TotalProjects)
        End If
    Next

    If Level_selected = 0 Then

        ll_earlyCreated = 0
        If grd_StatusProjects2.TextMatrix(grd_StatusProjects2.Rows - 1, C_PS2_C_STATU_COL) <> "" Then ll_earlyCreated = grd_StatusProjects2.TextMatrix(grd_StatusProjects2.Rows - 1, C_PS2_C_STATU_COL)
        If grd_StatusProjects2.TextMatrix(grd_StatusProjects2.Rows - 1, C_PS2_C_STATU_COL + 1) <> "" Then ll_earlyCreated = ll_earlyCreated + grd_StatusProjects2.TextMatrix(grd_StatusProjects2.Rows - 1, C_PS2_C_STATU_COL + 1)
        If grd_StatusProjects2.TextMatrix(grd_StatusProjects2.Rows - 1, C_PS2_C_STATU_COL + 2) <> "" Then ll_earlyCreated = ll_earlyCreated + grd_StatusProjects2.TextMatrix(grd_StatusProjects2.Rows - 1, C_PS2_C_STATU_COL + 2)
        
        If ll_earlyCreated <> 0 And grd_StatusProjects2.TextMatrix(grd_StatusProjects2.Rows - 1, C_PS2_C_SUM_COL) <> "" Then
            Call PercentVal(grd_StatusProjects2, grd_StatusProjects2.Rows - 1, ll_earlyCreated, C_PS2_C_EARLY_PER_COL, grd_StatusProjects2.TextMatrix(grd_StatusProjects2.Rows - 1, C_PS2_C_SUM_COL))
        End If

        ' fill total info fields
        grd_StatusProjects2.TextMatrix(grd_StatusProjects2.Rows - 1, C_PS2_U_TOTALACTIVE_COL) = GetDBColSUM(ll_proj2Counts, "AllActivePrjCount")
        grd_StatusProjects2.TextMatrix(grd_StatusProjects2.Rows - 1, C_PS2_U_ORDERDPRIOR_COL) = GetDBColSUM(ll_proj2Counts, "OrderedPriorCount")
        
        ld_TotalProjects = GetDBColSUM(ll_proj2Counts, "AllPrjCount")
        ' percent for total
        Call PercentCol(grd_StatusProjects2, grd_StatusProjects2.Rows - 1, C_PS2_U_TOTAL_UNIQUE_COL, C_PS2_U_TOTAL_PER_COL, ld_TotalProjects)
        ' specified percent
        Call PercentCol(grd_StatusProjects2, grd_StatusProjects2.Rows - 1, C_PS2_U_STATU_COL + 6, C_PS2_U_WON_SPEC_PER_COL, ld_TotalProjects)
        ' order percent
        Call PercentCol(grd_StatusProjects2, grd_StatusProjects2.Rows - 1, C_PS2_U_STATU_COL + 7, C_PS2_U_WON_ORDER_PER_COL, ld_TotalProjects)
    Else
        ' remove grand total line
        grd_StatusProjects2.Rows = grd_StatusProjects2.Rows - 1
        
    End If
    
    Call p_da.Close(ll_proj2Counts)
    ll_proj2Counts = 0
    
    grd_StatusProjects2.Visible = True
    Call LockScreen(False)

    grd_StatusProjects2.Visible = True
    mb_statusProjects2_processed = True
    
    
    ml_ps2RowHeight = IIf(ml_ps2RowHeight = 0, grd_StatusProjects2.RowHeight(grd_StatusProjects2.Rows - 1), ml_ps2RowHeight)
    Call img_ps2Max_Click

    Exit Sub
    
ErrorHandler:
    Call LockScreen(False)
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If

    If ll_proj2Counts > 0 Then
        Call p_da.Close(ll_proj2Counts)
        ll_proj2Counts = 0
    End If
    Call ErrorHandler(Extender.Name & ".Process_StatusProjects2")
End Sub

Private Function getGridValuesArray(ByRef ao_grid As MSFlexGrid, ByVal al_row As Long, ByVal ala_idx As Variant) As Variant
On Error GoTo ErrorHandler
    Dim ll_Index As Long
    Dim retval() As Variant
    
    ReDim retval(UBound(ala_idx) - LBound(ala_idx)) As Variant
    
    For ll_Index = LBound(ala_idx) To UBound(ala_idx)
        retval(ll_Index - LBound(ala_idx)) = ao_grid.TextMatrix(al_row, ala_idx(ll_Index))
    Next
    
    getGridValuesArray = retval
Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".getGridValuesArray")
End Function

Private Function getDBFieldsArray(ByVal al_Cursor As Long) As Variant
On Error GoTo ErrorHandler
    Dim retval() As Variant
    
    If p_da.GetFieldIndex(al_Cursor, "BMK_Code") <> -1 Then
        ReDim Preserve retval(0) As Variant
        retval(UBound(retval)) = "BMK_Code"
    End If
    
    If p_da.GetFieldIndex(al_Cursor, "CT_Code") <> -1 Then
        ReDim Preserve retval(SafeUbound(retval) + 1) As Variant  'MS REDIMM
        retval(UBound(retval)) = "CT_Code"
    End If
    
    If p_da.GetFieldIndex(al_Cursor, "SR_Code") <> -1 Then
        ReDim Preserve retval(SafeUbound(retval) + 1) As Variant  'MS REDIMM
        retval(UBound(retval)) = "SR_Code"
    End If
    
    getDBFieldsArray = retval
Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".getGridValuesArray")
End Function



Private Sub Process_StatusProjects3()
On Error GoTo ErrorHandler
    Dim ls_req As String
    Dim ll_cursor As Long
    
    If Not CheckReportAvailable() Then
        Exit Sub
    End If

    
    If Not CheckDataAuthorization Then
        MsgBox MsgText(1504, ms_Language_Code, "#You are not authorized to see these data")
        tv1.SetFocus
        Exit Sub
    End If
    
    Call LockScreen(True)
    
    ReDim ms_MsgInfo(3, 1)
    ms_MsgInfo(0, 0) = "$TV1$"
    ms_MsgInfo(0, 1) = tv1.SelectedItem.Text
    ms_MsgInfo(1, 0) = "$FROM$"
    ms_MsgInfo(1, 1) = cal1.date_courte
    ms_MsgInfo(2, 0) = "$TO$"
    ms_MsgInfo(2, 1) = cal2.date_courte
    ms_MsgInfo(3, 0) = "$ACTIVEPRJ$"
    ms_MsgInfo(3, 1) = ml_ActivePrj
    
    frm_statusProjects3.Visible = True
    frm_statusProjects3.Caption = GetLabel(frm_statusProjects3.Tag, "#Projects $TV1$ by status between $FROM$ and $TO$ (Reference period for % calcualtion is past $ACTIVEPRJ$ days)", ms_MsgInfo)
    
    grd_StatusProjects3.Visible = False
    img_ps3Min.Visible = False
    img_ps3Max.Visible = False

    
    grd_StatusProjects3.Rows = grd_StatusProjects3.FixedRows        ' remove all data lines from grid
    grd_StatusProjects3.LeftCol = 4                                 ' ensure visible part is at top left
    
    lbl_statusProj3Calculation.Visible = True
    
    lbl_statusProj3Calculation.Caption = GetLabel(lbl_statusProj3Calculation.Tag, "#Calculating Status Project3 report - Created....")
    Call frm_statusProjects3.Refresh
    DoEvents

    ls_req = GetStatusProjectsRequest(cb_trw.SelectedItem.GetData(0), Level_selected, "C3")
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
            
        ' fill the grid
        Call FillGridStatusProjectsEarly(grd_StatusProjects3, ll_cursor, C_PS3_C_STATU_COL, C_PS3_C_TOTAL_COL, -1, -1, -1)
        Call p_da.Close(ll_cursor)
    End If
    
    lbl_statusProj3Calculation.Caption = GetLabel("lbl_statusProj3Calc_2", "#Calculating Status Project3 report - Updated....")
    Call frm_statusProjects3.Refresh
    DoEvents
    
    ls_req = GetStatusProjectsRequest(cb_trw.SelectedItem.GetData(0), Level_selected, "U3")
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        ' fill the grid
        Call FillGridStatusProjects(grd_StatusProjects3, ll_cursor, C_PS3_U_STATU_COL - 7, -1, -1, -1, -1)
        Call p_da.Close(ll_cursor)
    End If
    
    lbl_statusProj3Calculation.Caption = GetLabel("lbl_statusProj3Calc_3", "#Calculating Status Project 3 report - Totals....")
    Call frm_statusProjects3.Refresh
    DoEvents
    
    ' step 3 we recalculate total + won + lost
    ls_req = GetStatusProjectsRequest(cb_trw.SelectedItem.GetData(0), Level_selected, "U3T")
    If ls_req <> "" Then
        ls_req = ReplaceHolders(ls_req)
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        
        ' fill the grid
        Call FillGridStatusProjectsT(grd_StatusProjects3, ll_cursor, C_PS3_U_TOTAL_UNIQUE_COL)
        Call p_da.Close(ll_cursor)
'        Call CalculateWonLostPercent(grd_StatusProjects3, ll_wonColU, ll_lostColU, 21)
    End If
    export_report.Visible = True
    
    ' calculate totals
    Dim ll_col As Long, ll_Row As Long
    Dim ld_totalC As Double
    For ll_Row = grd_StatusProjects3.FixedRows To grd_StatusProjects3.Rows - 1
        ' calculate summ
'        Call SumCols(grd_StatusProjects3, ll_Row, C_PS3_C_STATU_COL, C_PS3_C_STATU_COL, C_PS3_C_SUM_COL)
'        Call SumCols(grd_StatusProjects3, ll_Row, C_PS3_U_STATU_COL, C_PS3_U_STATU_COL, C_PS3_U_SUM_COL)
    Next

'    Call SetGridColBackColor(grd_StatusProjects3, C_PS3_C_TOTAL_COL, COLOR_GREY)
'    Call SetGridColBackColor(grd_StatusProjects3, C_PS3_U_SUM_COL, COLOR_GREY)
    
    grd_StatusProjects3.Rows = grd_StatusProjects3.Rows + 1
    If Level_selected = 0 Then
        grd_StatusProjects3.TextMatrix(grd_StatusProjects3.Rows - 1, 2) = GetLabel("s_total", "#TOTAL")
        For ll_col = 4 To grd_StatusProjects3.Cols - 4
            ld_totalC = 0
            For ll_Row = grd_StatusProjects3.FixedRows To grd_StatusProjects3.Rows - 2
                If grd_StatusProjects3.TextMatrix(ll_Row, ll_col) <> "" Then
                    ld_totalC = ld_totalC + grd_StatusProjects3.TextMatrix(ll_Row, ll_col)
                End If
            Next
            grd_StatusProjects3.TextMatrix(grd_StatusProjects3.Rows - 1, ll_col) = FormatNumber(ld_totalC, 0)
        Next
        
        Call SetGridRowBackColor(grd_StatusProjects3, grd_StatusProjects3.Rows - 1, COLOR_GREY)
        Call SetGridRowForeColor(grd_StatusProjects3, grd_StatusProjects3.Rows - 1, vbRed)
        Call SetGridRowBold(grd_StatusProjects3, grd_StatusProjects3.Rows - 1)
    End If
    
    ' CALCULATE sub totals per market
    Dim ll_CurrentLine As Long
    Dim ll_BMKstartLine As Long
    Dim ls_BMK_Code As String
    
    ll_CurrentLine = grd_StatusProjects3.FixedRows
    ll_BMKstartLine = -1
    ls_BMK_Code = ""
    While ll_CurrentLine <> grd_StatusProjects3.Rows
        If ls_BMK_Code <> grd_StatusProjects3.TextMatrix(ll_CurrentLine, 0) Then
            If ll_BMKstartLine <> -1 Then
                Debug.Assert (ls_BMK_Code <> "")
                ' process the lines between ll_BMKstartLine and ll_currentLine
                Call grd_StatusProjects3.AddItem(ls_BMK_Code, ll_CurrentLine)
                
                grd_StatusProjects3.TextMatrix(ll_CurrentLine, 2) = grd_StatusProjects3.TextMatrix(ll_BMKstartLine, 2)
                grd_StatusProjects3.TextMatrix(ll_CurrentLine, 3) = GetLabel("s_total2", "#Total")
                
                Call SumLines(grd_StatusProjects3, ll_BMKstartLine, ll_CurrentLine - 1, 4, grd_StatusProjects3.Cols - 4)
                
                Call SetGridRowBackColor(grd_StatusProjects3, ll_CurrentLine, COLOR_GREY2)
                Call SetGridRowForeColor(grd_StatusProjects3, ll_CurrentLine, vbBlue)
                Call SetGridRowBold(grd_StatusProjects3, ll_CurrentLine)

                
                ' move currentline to next line
                ll_CurrentLine = ll_CurrentLine + 1
            End If
            ll_BMKstartLine = ll_CurrentLine
            ls_BMK_Code = grd_StatusProjects3.TextMatrix(ll_CurrentLine, 0)
        End If
        
        ll_CurrentLine = ll_CurrentLine + 1
    Wend
    
    If ml_proj3Counts = 0 Then
        ml_proj3Counts = OpenSQLSafe(p_da, ReplaceHolders("EXEC ProjectStatT3_Market '$date1$', '$date2$'"))
    End If
    
    Dim ld_TotalProjects As Double
    For ll_Row = grd_StatusProjects3.FixedRows To grd_StatusProjects3.Rows - 2

        ' Percentace for early created projects
        If grd_StatusProjects3.TextMatrix(ll_Row, C_PS3_C_STATU_COL) <> "" And grd_StatusProjects3.TextMatrix(ll_Row, C_PS3_C_TOTAL_COL) <> "" Then
            Call PercentCol(grd_StatusProjects3, ll_Row, C_PS3_C_STATU_COL, C_PS3_C_EARLY_PER_COL, grd_StatusProjects3.TextMatrix(ll_Row, C_PS3_C_TOTAL_COL))
        End If
        
        ' capculate percentace for Updated projects
        If grd_StatusProjects3.TextMatrix(ll_Row, 1) <> "" Then
            If p_da.Find(ml_proj3Counts, Array("BMK_Code", "CT_Code"), Array(grd_StatusProjects3.TextMatrix(ll_Row, 0), grd_StatusProjects3.TextMatrix(ll_Row, 1))) >= 0 Then
                ' fill total info fields
                grd_StatusProjects3.TextMatrix(ll_Row, C_PS3_U_TOTALACTIVE_COL) = p_da.GetFields(ml_proj3Counts, "AllActivePrjCount")
'                grd_StatusProjects3.TextMatrix(ll_Row, C_PS3_U_ORDERDPRIOR_COL) = p_da.GetFields(ml_proj3Counts, "OrderedPriorCount")
                
                ' total percent
                Call PercentCol(grd_StatusProjects3, ll_Row, C_PS3_U_TOTAL_UNIQUE_COL, C_PS3_U_TOTAL_PER_COL, p_da.GetFields(ml_proj3Counts, "AllPrjCount"))
                
                ' specified percent
'                Call PercentCol(grd_StatusProjects3, ll_Row, C_PS3_U_STATU_COL + 6, C_PS3_U_WON_SPEC_PER_COL, p_da.GetFields(ml_proj3Counts, "AllPrjCount"))
                
                ' order percent
                Call PercentCol(grd_StatusProjects3, ll_Row, C_PS3_U_STATU_COL, C_PS3_U_WON_ORDER_PER_COL, p_da.GetFields(ml_proj3Counts, "AllPrjCount"))
            End If
        Else
            If p_da.GetFields(ml_proj3Counts, "RepsCount") <> 0 Then
                grd_StatusProjects3.TextMatrix(ll_Row, C_PS3_C_PER_REP_COL) = Format(grd_StatusProjects3.TextMatrix(ll_Row, C_PS3_C_TOTAL_COL) / p_da.GetFields(ml_proj3Counts, "RepsCount"), "#0.0")
            End If
            
            ' fill total info fields
            grd_StatusProjects3.TextMatrix(ll_Row, C_PS3_U_TOTALACTIVE_COL) = GetDBColSUMByMarket(ml_proj3Counts, grd_StatusProjects3.TextMatrix(ll_Row, 0), "AllActivePrjCount")
'            grd_StatusProjects3.TextMatrix(ll_Row, C_PS3_U_ORDERDPRIOR_COL) = GetDBColSUMByMarket(ml_proj3Counts, grd_StatusProjects3.TextMatrix(ll_Row, 0), "OrderedPriorCount")

            ' total per market
            ld_TotalProjects = GetDBColSUMByMarket(ml_proj3Counts, grd_StatusProjects3.TextMatrix(ll_Row, 0), "AllPrjCount")
            ' percent for total
            Call PercentCol(grd_StatusProjects3, ll_Row, C_PS3_U_TOTAL_UNIQUE_COL, C_PS3_U_TOTAL_PER_COL, ld_TotalProjects)
            ' specified percent
'            Call PercentCol(grd_StatusProjects3, ll_Row, C_PS3_U_STATU_COL + 6, C_PS3_U_WON_SPEC_PER_COL, ld_TotalProjects)
            ' order percent
            Call PercentCol(grd_StatusProjects3, ll_Row, C_PS3_U_STATU_COL, C_PS3_U_WON_ORDER_PER_COL, ld_TotalProjects)
        End If
    Next
    If Level_selected = 0 Then
    
        ' Percentace for early created projects
        If grd_StatusProjects3.TextMatrix(grd_StatusProjects3.Rows - 1, C_PS3_C_STATU_COL) <> "" And grd_StatusProjects3.TextMatrix(grd_StatusProjects3.Rows - 1, C_PS3_C_TOTAL_COL) <> "" Then
            Call PercentCol(grd_StatusProjects3, grd_StatusProjects3.Rows - 1, C_PS3_C_STATU_COL, C_PS3_C_EARLY_PER_COL, grd_StatusProjects3.TextMatrix(grd_StatusProjects3.Rows - 1, C_PS3_C_TOTAL_COL))
        End If
        
        Dim ll_markertsC As Long
        
        ll_markertsC = p_da.Distinct(ml_proj3Counts, Array("BMK_Code", "RepsCount"), False)
        
        Dim ll_allReps As Long
        ll_allReps = GetDBColSUM(ll_markertsC, "RepsCount")
        Call p_da.Close(ll_markertsC)
        ll_markertsC = 0
        
        If ll_allReps <> 0 Then
            grd_StatusProjects3.TextMatrix(grd_StatusProjects3.Rows - 1, C_PS3_C_PER_REP_COL) = Format(grd_StatusProjects3.TextMatrix(grd_StatusProjects3.Rows - 1, C_PS3_C_TOTAL_COL) / ll_allReps, "#0.0")
        End If
        
        ' fill total info fields
        grd_StatusProjects3.TextMatrix(grd_StatusProjects3.Rows - 1, C_PS3_U_TOTALACTIVE_COL) = GetDBColSUM(ml_proj3Counts, "AllActivePrjCount")
'        grd_StatusProjects3.TextMatrix(grd_StatusProjects3.Rows - 1, C_PS3_U_ORDERDPRIOR_COL) = GetDBColSUM(ml_proj3Counts, "OrderedPriorCount")
        
        ld_TotalProjects = GetDBColSUM(ml_proj3Counts, "AllPrjCount")
        ' percent for total
        Call PercentCol(grd_StatusProjects3, grd_StatusProjects3.Rows - 1, C_PS3_U_TOTAL_UNIQUE_COL, C_PS3_U_TOTAL_PER_COL, ld_TotalProjects)
        ' specified percent
'        Call PercentCol(grd_StatusProjects3, grd_StatusProjects3.Rows - 1, C_PS3_U_STATU_COL + 6, C_PS3_U_WON_SPEC_PER_COL, ld_TotalProjects)
        ' order percent
        Call PercentCol(grd_StatusProjects3, grd_StatusProjects3.Rows - 1, C_PS3_U_STATU_COL, C_PS3_U_WON_ORDER_PER_COL, ld_TotalProjects)
    Else
        ' remove grand total line
        grd_StatusProjects3.Rows = grd_StatusProjects3.Rows - 1
        
    End If

    grd_StatusProjects3.Visible = True
    Call LockScreen(False)

    grd_StatusProjects3.Visible = True
    mb_statusProjects3_processed = True
    If ml_ps3CounryColWidth = 0 Then
        img_ps3Min.Visible = True
        img_ps3Max.Visible = False
    Else
        Call img_ps3Max_Click
    End If

    Exit Sub
    
ErrorHandler:
    Call LockScreen(False)
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If

    Call ErrorHandler(Extender.Name & ".Process_StatusProjects3")
End Sub

Private Function GetDBColSUM(ByVal al_Cursor As Long, ByVal al_colName As String) As Double
On Error GoTo ErrorHandler
    Dim ld_retVal As Double
    ld_retVal = 0
    
    If p_da.First(al_Cursor) Then
        While Not p_da.EOF(al_Cursor)
            ld_retVal = ld_retVal + p_da.GetFields(al_Cursor, al_colName)
            Call p_da.Next(al_Cursor)
        Wend
    End If
    GetDBColSUM = ld_retVal
    Exit Function
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetDBColSUM")
End Function

Private Function GetDBColSUMByMarket(ByVal al_Cursor As Long, ByVal as_BMK_Code As String, ByVal al_colName As String) As Double
On Error GoTo ErrorHandler
    Dim ld_retVal As Double
    ld_retVal = 0
    
    Dim ll_dbRow As Long
    ll_dbRow = p_da.Find(al_Cursor, Array("BMK_Code"), Array(as_BMK_Code))
    
    While ll_dbRow >= 0
        ld_retVal = ld_retVal + p_da.GetFields(al_Cursor, al_colName)
        ll_dbRow = p_da.Find(al_Cursor, Array("BMK_Code"), Array(as_BMK_Code), ll_dbRow + 1)
    Wend
    GetDBColSUMByMarket = ld_retVal
    Exit Function
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetDBColSUMByMarket")
End Function


Private Sub PercentCol(ByRef ao_grid As MSFlexGrid, ByVal al_row As Long, ByVal al_percentCol As Long, ByVal al_resultCol As Long, ByVal ad_superValue As Double)
On Error GoTo ErrorHandler
    If ao_grid.TextMatrix(al_row, al_percentCol) <> "" Then
        Dim ld_Value As Double
        If ad_superValue = 0 Then Exit Sub
        ld_Value = CDbl(ao_grid.TextMatrix(al_row, al_percentCol)) / ad_superValue * 100
        If ld_Value > 1 Then
            ao_grid.TextMatrix(al_row, al_resultCol) = FormatNumber(ld_Value, 1) & " %"
        ElseIf ld_Value > 0 Then
            ao_grid.TextMatrix(al_row, al_resultCol) = FormatNumber(ld_Value, 2) & " %"
        Else
            ao_grid.TextMatrix(al_row, al_resultCol) = ""
        End If
    Else
        ao_grid.TextMatrix(al_row, al_resultCol) = ""
    End If

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

Private Sub PercentVal(ByRef ao_grid As MSFlexGrid, ByVal al_row As Long, ByVal ad_percentVal As Double, ByVal al_resultCol As Long, ByVal ad_superValue As Double)
On Error GoTo ErrorHandler
    
    Dim ld_Value As Double
    ld_Value = ad_percentVal / ad_superValue * 100
    If ld_Value > 1 Then
        ao_grid.TextMatrix(al_row, al_resultCol) = FormatNumber(ld_Value, 1) & " %"
    ElseIf ld_Value > 0 Then
        ao_grid.TextMatrix(al_row, al_resultCol) = FormatNumber(ld_Value, 2) & " %"
    Else
        ao_grid.TextMatrix(al_row, al_resultCol) = ""
    End If

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


Private Sub SumCols(ByRef ao_grid As MSFlexGrid, ByVal al_row As Long, ByVal al_startCol As Long, ByVal al_endCol As Long, ByVal al_sumCol As Long)
On Error GoTo ErrorHandler
    Dim ld_total As Double
    Dim ll_col As Long
    
    ld_total = 0
    For ll_col = al_startCol To al_endCol
        If ao_grid.TextMatrix(al_row, ll_col) <> "" Then
            ld_total = ld_total + ao_grid.TextMatrix(al_row, ll_col)
        End If
    Next
    ao_grid.TextMatrix(al_row, al_sumCol) = FormatNumber(ld_total, 0)

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


Private Sub SumLines(ByRef ao_grid As MSFlexGrid, ByVal al_StartRow As Long, ByVal al_EndRow As Long, ByVal al_startCol As Long, ByVal al_endCol As Long)
On Error GoTo ErrorHandler

    Dim ll_col As Long
    Dim ll_Row As Long
    Dim ld_total As Double
    Dim ld_won As Double

    For ll_col = al_startCol To al_endCol
        ld_total = 0
        For ll_Row = al_StartRow To al_EndRow
            If ao_grid.TextMatrix(ll_Row, ll_col) <> "" Then
                ld_total = ld_total + CDbl(ao_grid.TextMatrix(ll_Row, ll_col))
            End If
        Next
        ao_grid.TextMatrix(al_EndRow + 1, ll_col) = FormatNumber(ld_total, 0)
    Next
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".SumLines")
End Sub

Private Sub SumLinesWLPercent(ByRef ao_grid As MSFlexGrid, ByVal al_StartRow As Long, ByVal al_EndRow As Long, ByVal al_percentCol As Long, ByVal al_wonCol As Long, ByVal al_lostCol As Long)
On Error GoTo ErrorHandler
        
    Dim ll_Row As Long
    Dim ll_lost As Long
    Dim ll_won As Long
    
    ' won/lost percentage
    ll_won = 0
    ll_lost = 0
    For ll_Row = al_StartRow To al_EndRow
        If ao_grid.TextMatrix(ll_Row, al_wonCol) <> "" Then
            ll_won = ll_won + CLng(ao_grid.TextMatrix(ll_Row, al_wonCol))
        End If
        If ao_grid.TextMatrix(ll_Row, al_lostCol) <> "" Then
            ll_lost = ll_lost + CLng(ao_grid.TextMatrix(ll_Row, al_lostCol))
        End If
    Next
    
    If (ll_won + ll_lost) > 0 Then
        If ll_won / (ll_won + ll_lost) * 100 > 1 Then
            ao_grid.TextMatrix(al_EndRow + 1, al_percentCol) = FormatNumber((ll_won / (ll_won + ll_lost)) * 100, 0) & " %"
        Else
            ao_grid.TextMatrix(al_EndRow + 1, al_percentCol) = FormatNumber((ll_won / (ll_won + ll_lost)) * 100, 2) & " %"
        End If
    Else
        ao_grid.TextMatrix(al_EndRow + 1, al_percentCol) = ""
    End If
        
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".SumLinesWLPercent")
End Sub

Private Function GetFieldSUM(ByVal al_Cursor As Long, ByVal av_field As Variant, ByVal al_Year As Long, ByVal as_month As String) As Double
On Error GoTo ErrorHandler
    Dim ld_retVal As Double
    GetFieldSUM = 0
    Dim ll_bckPos As Long
    ll_bckPos = p_da.Position(al_Cursor)
    
    ld_retVal = 0
    If p_da.First(al_Cursor) Then
        While Not p_da.EOF(al_Cursor)
            If p_da.GetFields(al_Cursor, "yy") = al_Year And _
                p_da.GetFields(al_Cursor, "code_mm") = as_month Then
                ld_retVal = ld_retVal + p_da.GetFields(al_Cursor, av_field)
            End If
            p_da.Next (al_Cursor)
        Wend
    End If
    
    p_da.Position(al_Cursor) = ll_bckPos
    GetFieldSUM = ld_retVal
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetFieldSUM")
End Function

Private Function GetFieldGRPSUM(ByVal al_Cursor As Long, ByVal as_GRP_Desc_val As String, ByVal av_field As Variant, ByVal al_Year As Long, ByVal as_month As String) As Double
On Error GoTo ErrorHandler
    Dim ld_retVal As Double
    GetFieldGRPSUM = 0
    Dim ll_bckPos As Long
    ll_bckPos = p_da.Position(al_Cursor)
    
    ld_retVal = 0
    If p_da.First(al_Cursor) Then
        While Not p_da.EOF(al_Cursor)
            If p_da.GetFields(al_Cursor, "GRP_Desc") = as_GRP_Desc_val And _
                p_da.GetFields(al_Cursor, "yy") = al_Year And _
                p_da.GetFields(al_Cursor, "code_mm") = as_month Then
                ld_retVal = ld_retVal + p_da.GetFields(al_Cursor, av_field)
            End If
            p_da.Next (al_Cursor)
        Wend
    End If
    
    p_da.Position(al_Cursor) = ll_bckPos
    GetFieldGRPSUM = ld_retVal
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetFieldGRPSUM")
End Function

Private Function GetFieldSUM2(ByVal al_Cursor As Long, ByVal av_field As Variant, ByVal al_Year As Long, ByVal as_month As String, ByVal as_UOM As String) As Double
On Error GoTo ErrorHandler
    Dim ld_retVal As Double
    GetFieldSUM2 = 0
    Dim ll_bckPos As Long
    ll_bckPos = p_da.Position(al_Cursor)
    
    ld_retVal = 0
    If p_da.First(al_Cursor) Then
        While Not p_da.EOF(al_Cursor)
            If p_da.GetFields(al_Cursor, "yy") = al_Year And _
                p_da.GetFields(al_Cursor, "code_mm") = as_month And _
                p_da.GetFields(al_Cursor, "UOM") = as_UOM Then
                ld_retVal = ld_retVal + p_da.GetFields(al_Cursor, av_field)
            End If
            p_da.Next (al_Cursor)
        Wend
    End If
    
    p_da.Position(al_Cursor) = ll_bckPos
    GetFieldSUM2 = ld_retVal
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetFieldSUM2")
End Function

Private Sub SetRowHeader(ByRef ao_grid As MSFlexGrid, ByVal al_row As Long, ByVal as_h1 As String, ByVal as_h2 As String, Optional ByVal al_height As Long = -1)
On Error GoTo ErrorHandler
    ao_grid.TextMatrix(al_row, 0) = as_h1
    ao_grid.TextMatrix(al_row, 1) = as_h2
    If al_height <> -1 Then ao_grid.RowHeight(al_row) = 320
    Call SetGridCellForeColor(ao_grid, al_row, ao_grid.Cols - 2, vbRed)
    Call SetGridCellBackColor(ao_grid, al_row, ao_grid.Cols - 2, COLOR_GREY)
    Call SetGridCellForeColor(ao_grid, al_row, ao_grid.Cols - 1, vbRed)
    Call SetGridCellBackColor(ao_grid, al_row, ao_grid.Cols - 1, COLOR_GREY)
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".SetRowHeader")
End Sub

Private Function FillGridSales(ByRef ao_grid As MSFlexGrid, ByVal al_Cursor As Long, ll_currYear As Long, ByVal ab_showBDG As Boolean) As Long
On Error GoTo ErrorHandler

    Dim ll_cItemRow As Long
    Dim ll_headRow As Long
    Dim ls_cMonth As String
    Dim ll_curentCol As Long
    Dim ll_GSV_EUR_row As Long
     
    FillGridSales = -1
    If Not p_da.First(al_Cursor) Then Exit Function


    ' 1 row for GSV_BDG current year and 2 rows for GSV_EUR per year
    ll_cItemRow = ao_grid.Rows
    If ab_showBDG Then
        ao_grid.Rows = ao_grid.Rows + 3
        ' fill row header
        Call SetRowHeader(ao_grid, ll_cItemRow, p_da.GetFields(al_Cursor, 0), "GSV Bdg " & ll_currYear, 320)
        Call SetRowHeader(ao_grid, ll_cItemRow + 1, p_da.GetFields(al_Cursor, 0), "GSV EUR " & ll_currYear, 320)
        Call SetRowHeader(ao_grid, ll_cItemRow + 2, p_da.GetFields(al_Cursor, 0), "GSV EUR " & ll_currYear - 1, 320)
        ll_GSV_EUR_row = ll_cItemRow + 1
    Else
        ao_grid.Rows = ao_grid.Rows + 2
        ' fill row header
        Call SetRowHeader(ao_grid, ll_cItemRow, p_da.GetFields(al_Cursor, 0), "GSV EUR " & ll_currYear, 320)
        Call SetRowHeader(ao_grid, ll_cItemRow + 1, p_da.GetFields(al_Cursor, 0), "GSV EUR " & ll_currYear - 1, 320)
        ll_GSV_EUR_row = ll_cItemRow
    End If
    
    Dim ll_i As Long
    For ll_i = 2 To ao_grid.Cols - 1
        ao_grid.TextMatrix(ll_GSV_EUR_row, ll_i) = 0
        ao_grid.TextMatrix(ll_GSV_EUR_row + 1, ll_i) = 0
    Next
    FillGridSales = ll_GSV_EUR_row
    
    Dim ld_TotalMTD_LY As Double
    ld_TotalMTD_LY = 0
    
    ' Calculate
    While Not p_da.EOF(al_Cursor)
        ls_cMonth = p_da.GetFields(al_Cursor, "code_mm")
        ll_curentCol = CLng(ls_cMonth) + 1
        
        ' calculate GSV_Bdg
        If p_da.GetFields(al_Cursor, "yy") = ll_currYear And ab_showBDG Then
            ao_grid.TextMatrix(ll_cItemRow, ll_curentCol) = FormatNumber(GetFieldSUM(al_Cursor, "GSV_BDG", ll_currYear, p_da.GetFields(al_Cursor, "code_mm")), 0)
        End If
        
        ' calculate GSV_EUR
        ao_grid.TextMatrix(ll_GSV_EUR_row, ll_curentCol) = FormatNumber(GetFieldSUM(al_Cursor, "GSV_EUR", ll_currYear, p_da.GetFields(al_Cursor, "code_mm")), 0)
        ao_grid.TextMatrix(ll_GSV_EUR_row + 1, ll_curentCol) = FormatNumber(GetFieldSUM(al_Cursor, "GSV_EUR", ll_currYear - 1, p_da.GetFields(al_Cursor, "code_mm")), 0)
        
        ld_TotalMTD_LY = ld_TotalMTD_LY + GetFieldSUM(al_Cursor, "GSV_EUR_MTD_LY", ll_currYear - 1, p_da.GetFields(al_Cursor, "code_mm"))
        
        ' move to next month
        While Not p_da.EOF(al_Cursor) And ls_cMonth = p_da.GetFields(al_Cursor, "code_mm")
            Call p_da.Next(al_Cursor)
        Wend
    Wend
    
    ' put Total GSV_EUR_MTD_LY
    ao_grid.TextMatrix(ll_GSV_EUR_row + 1, ao_grid.Cols - 2) = FormatNumber(ld_TotalMTD_LY, 0)
    
    ' Calculate per UOM
    ll_headRow = ao_grid.Rows
    Dim ls_UOM As String
    
    Call p_da.First(al_Cursor)
    While Not p_da.EOF(al_Cursor)
        ls_cMonth = p_da.GetFields(al_Cursor, "code_mm")
        ls_UOM = p_da.GetFields(al_Cursor, "UOM")
        ll_curentCol = CLng(ls_cMonth) + 1

        ll_cItemRow = FindGridRow(ao_grid, ll_headRow, p_da.GetFields(al_Cursor, 0), "Vol " + ls_UOM & " " & ll_currYear, "")
        If ll_cItemRow = -1 Then
            ' create 2 new rows
            ll_cItemRow = ao_grid.Rows
            ao_grid.Rows = ao_grid.Rows + 2
            
            ' set month reports volume to 0
            For ll_i = 2 To ao_grid.Cols - 1
                ao_grid.TextMatrix(ll_cItemRow, ll_i) = 0
                ao_grid.TextMatrix(ll_cItemRow + 1, ll_i) = 0
            Next

            ' fill row header
            Call SetRowHeader(ao_grid, ll_cItemRow, p_da.GetFields(al_Cursor, 0), "Vol " + ls_UOM & " " & ll_currYear, 320)
            Call SetRowHeader(ao_grid, ll_cItemRow + 1, p_da.GetFields(al_Cursor, 0), "Vol " + ls_UOM & " " & ll_currYear - 1, 320)
        End If
        
        
        With ao_grid
            If p_da.GetFields(al_Cursor, "yy") = ll_currYear Then
                .TextMatrix(ll_cItemRow, ll_curentCol) = FormatNumber(.TextMatrix(ll_cItemRow, ll_curentCol) + p_da.GetFields(al_Cursor, "Volume"), 0)
                .TextMatrix(ll_cItemRow, ao_grid.Cols - 2) = FormatNumber(.TextMatrix(ll_cItemRow, ao_grid.Cols - 2) + p_da.GetFields(al_Cursor, "Volume"), 0)
            Else
                .TextMatrix(ll_cItemRow + 1, ll_curentCol) = FormatNumber(.TextMatrix(ll_cItemRow + 1, ll_curentCol) + p_da.GetFields(al_Cursor, "Volume"), 0)
                .TextMatrix(ll_cItemRow + 1, ao_grid.Cols - 2) = FormatNumber(.TextMatrix(ll_cItemRow + 1, ao_grid.Cols - 2) + p_da.GetFields(al_Cursor, "Volume_MTD_LY"), 0)
            End If
        End With

        Call p_da.Next(al_Cursor)
    Wend
            

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

Private Sub FillArraySales(ByRef ao_array() As Variant, ByVal al_Cursor As Long, ll_currYear As Long, ByVal ab_showBDG As Boolean, ByVal ab_GSVEUROnly As Boolean, ByRef ao_totalArray() As Variant)
On Error GoTo ErrorHandler

    Dim ll_cItemRow As Long
    Dim ls_cMonth As String
    Dim ls_cGrouping As String
    Dim ll_curentCol As Long
    Dim ll_i As Long
    Dim ll_grpRow As Long

    If Not p_da.First(al_Cursor) Then Exit Sub
    
    If ab_GSVEUROnly Then ab_showBDG = False            ' if GSV only then go without budget also

    ls_cGrouping = "#^"
    ' Calculate
    While Not p_da.EOF(al_Cursor)

        If ls_cGrouping <> p_da.GetFields(al_Cursor, "GRP_Desc") Then
            ls_cGrouping = p_da.GetFields(al_Cursor, "GRP_Desc")
            
            ' 1 row for GSV_BDG current year and 2 rows for GSV_EUR per year
            If UBound(ao_array, 2) = 0 Then
                ll_cItemRow = 0
            Else
                ll_cItemRow = UBound(ao_array, 2) + 1
            End If
            ll_grpRow = ll_cItemRow
            If ab_showBDG Then
                ReDim Preserve ao_array(LBound(ao_array, 1) To UBound(ao_array, 1), LBound(ao_array, 2) To ll_cItemRow + 2) As Variant
                
                ' fill row header
                ao_array(0, ll_cItemRow) = p_da.GetFields(al_Cursor, "CG_Desc")
                ao_array(1, ll_cItemRow) = ls_cGrouping
                ao_array(2, ll_cItemRow) = "GSV Bdg " & ll_currYear
                
                ao_array(0, ll_cItemRow + 1) = p_da.GetFields(al_Cursor, "CG_Desc")
                ao_array(1, ll_cItemRow + 1) = ls_cGrouping
                ao_array(2, ll_cItemRow + 1) = "GSV EUR " & ll_currYear
                
                ao_array(0, ll_cItemRow + 2) = p_da.GetFields(al_Cursor, "CG_Desc")
                ao_array(1, ll_cItemRow + 2) = ls_cGrouping
                ao_array(2, ll_cItemRow + 2) = "GSV EUR " & ll_currYear - 1
            Else
                ReDim Preserve ao_array(LBound(ao_array, 1) To UBound(ao_array, 1), LBound(ao_array, 2) To ll_cItemRow + 1) As Variant
                
                ' fill row header
                ao_array(0, ll_cItemRow) = p_da.GetFields(al_Cursor, "CG_Desc")
                ao_array(1, ll_cItemRow) = ls_cGrouping
                ao_array(2, ll_cItemRow) = "GSV EUR " & ll_currYear
                
                ao_array(0, ll_cItemRow + 1) = p_da.GetFields(al_Cursor, "CG_Desc")
                ao_array(1, ll_cItemRow + 1) = ls_cGrouping
                ao_array(2, ll_cItemRow + 1) = "GSV EUR " & ll_currYear - 1
            End If
        Else
            ll_cItemRow = ll_grpRow
        End If
        
    
        ls_cMonth = p_da.GetFields(al_Cursor, "code_mm")
        ll_curentCol = CLng(ls_cMonth) + 2
        
        ' calculate GSV_Bdg
        If p_da.GetFields(al_Cursor, "yy") = ll_currYear And ab_showBDG Then
            ao_array(ll_curentCol, ll_cItemRow) = GetFieldGRPSUM(al_Cursor, ls_cGrouping, "GSV_BDG", ll_currYear, p_da.GetFields(al_Cursor, "code_mm"))
        End If
        
        ' calculate GSV_EUR
        Dim ll_GSVEUR_CY As Double
        Dim ll_GSVEUR_LY As Double
        Dim ll_GSVEUR_MTD_LY As Double
        ll_GSVEUR_CY = GetFieldGRPSUM(al_Cursor, ls_cGrouping, "GSV_EUR", ll_currYear, p_da.GetFields(al_Cursor, "code_mm"))
        ll_GSVEUR_LY = GetFieldGRPSUM(al_Cursor, ls_cGrouping, "GSV_EUR", ll_currYear - 1, p_da.GetFields(al_Cursor, "code_mm"))
        ll_GSVEUR_MTD_LY = GetFieldGRPSUM(al_Cursor, ls_cGrouping, "GSV_EUR_MTD_LY", ll_currYear - 1, p_da.GetFields(al_Cursor, "code_mm"))
        
        If ab_showBDG Then
            ao_array(ll_curentCol, ll_cItemRow + 1) = ll_GSVEUR_CY
            ao_array(ll_curentCol, ll_cItemRow + 2) = ll_GSVEUR_LY
            ao_array(UBound(ao_array, 1) - 1, ll_cItemRow + 1) = ao_array(UBound(ao_array, 1) - 1, ll_cItemRow + 1) + ll_GSVEUR_CY
            ao_array(UBound(ao_array, 1) - 1, ll_cItemRow + 2) = ao_array(UBound(ao_array, 1) - 1, ll_cItemRow + 2) + ll_GSVEUR_MTD_LY
        Else
            ao_array(ll_curentCol, ll_cItemRow + 0) = ll_GSVEUR_CY
            ao_array(ll_curentCol, ll_cItemRow + 1) = ll_GSVEUR_LY
            ao_array(UBound(ao_array, 1) - 1, ll_cItemRow + 0) = ao_array(UBound(ao_array, 1) - 1, ll_cItemRow + 0) + ll_GSVEUR_CY
            ao_array(UBound(ao_array, 1) - 1, ll_cItemRow + 1) = ao_array(UBound(ao_array, 1) - 1, ll_cItemRow + 1) + ll_GSVEUR_MTD_LY
        End If
        
        ' Add GSV into TOTAL array
        ao_totalArray(ll_curentCol, 0) = ao_totalArray(ll_curentCol, 0) + ll_GSVEUR_CY
        ao_totalArray(ll_curentCol, 1) = ao_totalArray(ll_curentCol, 1) + ll_GSVEUR_LY
        
        If Not ab_GSVEUROnly Then
            Dim ls_UOM  As String
            
            ' for each UOM calculate volume
            While Not p_da.EOF(al_Cursor) And ls_cMonth = p_da.GetFields(al_Cursor, "code_mm") And ls_cGrouping = p_da.GetFields(al_Cursor, "GRP_Desc")
                ls_UOM = p_da.GetFields(al_Cursor, "UOM")
                
                ll_cItemRow = FindRowInArray(ao_array, ll_grpRow, p_da.GetFields(al_Cursor, "CG_Desc"), ls_cGrouping, "Vol " + ls_UOM & " " & ll_currYear)
                If ll_cItemRow = -1 Then
                    ll_cItemRow = UBound(ao_array, 2) + 1
                    ReDim Preserve ao_array(LBound(ao_array, 1) To UBound(ao_array, 1), LBound(ao_array, 2) To ll_cItemRow + 1) As Variant
                    
                    ao_array(0, ll_cItemRow) = p_da.GetFields(al_Cursor, "CG_Desc")
                    ao_array(1, ll_cItemRow) = ls_cGrouping
                    ao_array(2, ll_cItemRow) = "Vol " + ls_UOM & " " & ll_currYear
                    
                    ao_array(0, ll_cItemRow + 1) = p_da.GetFields(al_Cursor, "CG_Desc")
                    ao_array(1, ll_cItemRow + 1) = ls_cGrouping
                    ao_array(2, ll_cItemRow + 1) = "Vol " + ls_UOM & " " & ll_currYear - 1
                    
                    ' set month reports volume to 0
                    For ll_i = 3 To UBound(ao_array, 1)
                        ao_array(ll_i, ll_cItemRow) = 0
                        ao_array(ll_i, ll_cItemRow + 1) = 0
                    Next
                End If
                
                If p_da.GetFields(al_Cursor, "yy") = ll_currYear Then
                    ao_array(ll_curentCol, ll_cItemRow) = ao_array(ll_curentCol, ll_cItemRow) + p_da.GetFields(al_Cursor, "Volume")
                    ao_array(UBound(ao_array, 1) - 1, ll_cItemRow) = ao_array(UBound(ao_array, 1) - 1, ll_cItemRow) + p_da.GetFields(al_Cursor, "Volume")
                Else
                    ao_array(ll_curentCol, ll_cItemRow + 1) = ao_array(ll_curentCol, ll_cItemRow + 1) + p_da.GetFields(al_Cursor, "Volume")
                    ao_array(UBound(ao_array, 1) - 1, ll_cItemRow + 1) = ao_array(UBound(ao_array, 1) - 1, ll_cItemRow + 1) + p_da.GetFields(al_Cursor, "Volume_MTD_LY")
                End If
                    
                Call p_da.Next(al_Cursor)
            Wend
        Else
            ' skip UOM data for the year and grouping
            While Not p_da.EOF(al_Cursor) And ls_cMonth = p_da.GetFields(al_Cursor, "code_mm") And ls_cGrouping = p_da.GetFields(al_Cursor, "GRP_Desc")
                Call p_da.Next(al_Cursor)
            Wend
        End If
    Wend
    
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".FillArraySales")
End Sub


Private Sub FillGridVisits(ByRef ao_grid As MSFlexGrid, ByVal al_Cursor As Long, ByVal al_baseCol As Long, ByVal al_TotalCol As Long, ByVal al_total_percent_col As Long)
On Error GoTo ErrorHandler
    If Not p_da.First(al_Cursor) Then Exit Sub

    Dim ll_curentRow As Long
    
    While Not p_da.EOF(al_Cursor)
        With ao_grid
            .Rows = .Rows + 1
            ll_curentRow = .Rows - 1
            .TextMatrix(ll_curentRow, 0) = p_da.GetFields(al_Cursor, "BMK_Code")
            .TextMatrix(ll_curentRow, 1) = p_da.GetFields(al_Cursor, "CT_Code")
            .TextMatrix(ll_curentRow, 2) = p_da.GetFields(al_Cursor, "BMK_Desc")
            .TextMatrix(ll_curentRow, 3) = p_da.GetFields(al_Cursor, "CT_Desc")
            .TextMatrix(ll_curentRow, 4) = p_da.GetFields(al_Cursor, "SR_Code")
            .TextMatrix(ll_curentRow, 5) = p_da.GetFields(al_Cursor, "SR_Name")
            
            .TextMatrix(ll_curentRow, al_TotalCol) = p_da.GetFields(al_Cursor, "TotalCount")
            .TextMatrix(ll_curentRow, al_baseCol) = p_da.GetFields(al_Cursor, "VeryImportantCount")
            .TextMatrix(ll_curentRow, al_baseCol + 1) = p_da.GetFields(al_Cursor, "ImportantCount")
            
            Call PercentVal(ao_grid, ll_curentRow, p_da.GetFields(al_Cursor, "VeryImportantCount") + p_da.GetFields(al_Cursor, "ImportantCount"), C_VISITS2_TOTAL_PER_COL, p_da.GetFields(al_Cursor, "TotalCount"))

        End With

        p_da.Next (al_Cursor)
    Wend

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

Private Sub FillGridStatusProjects(ByRef ao_grid As MSFlexGrid, ByVal al_Cursor As Long, ByVal al_baseCol As Long, ByVal al_TotalCol As Long, ByVal al_notActiveCol As Long, ByVal al_wonCol As Long, ByVal al_lostCol As Long)
On Error GoTo ErrorHandler

    Dim ll_curentRow As Long
    Dim ll_col As Long
    Dim ll_ss_code As Long
    
    If Not p_da.First(al_Cursor) Then Exit Sub
    
    ' reset all existing al_wonCol, al_lostCol columns to 0
    For ll_curentRow = ao_grid.FixedRows To ao_grid.Rows - 1
        If al_wonCol <> -1 Then ao_grid.TextMatrix(ll_curentRow, al_wonCol) = "0"
        If al_lostCol <> -1 Then ao_grid.TextMatrix(ll_curentRow, al_lostCol) = "0"
        If al_TotalCol <> -1 Then ao_grid.TextMatrix(ll_curentRow, al_TotalCol) = "0"
        If al_notActiveCol <> -1 Then ao_grid.TextMatrix(ll_curentRow, al_notActiveCol) = "0"

    Next
    
    While Not p_da.EOF(al_Cursor)
        ll_curentRow = FindGridRow(ao_grid, ao_grid.FixedRows, p_da.GetFields(al_Cursor, "bmk_code"), p_da.GetFields(al_Cursor, "ct_code"), p_da.GetFields(al_Cursor, "sr_code"))
        With ao_grid
        
            If ll_curentRow = -1 Then
                ' new row
                ll_curentRow = FindGridRow_by1(ao_grid, ao_grid.FixedRows, p_da.GetFields(al_Cursor, "bmk_code"))
                If ll_curentRow = -1 Then
                    .Rows = .Rows + 1
                    ll_curentRow = .Rows - 1
                Else
                    ll_curentRow = FindNextGridRow_by1(ao_grid, ll_curentRow, 0, p_da.GetFields(al_Cursor, "BMK_Code"), 1, p_da.GetFields(al_Cursor, "CT_Code"))
                    If p_da.GetFields(al_Cursor, "SR_Code") = "" Then
                        Call .AddItem(p_da.GetFields(al_Cursor, "BMK_Code"), ll_curentRow)
                    Else
                        ' search by SR_Code
                        If ll_curentRow = -1 Then
                            ' country not found -> add next line
                            .Rows = .Rows + 1
                            ll_curentRow = .Rows - 1
                        Else
                            ' add item into block of items with the same CT_Code
                            Call .AddItem(p_da.GetFields(al_Cursor, "BMK_Code"), ll_curentRow)
                        End If
                    End If
                End If
                
                .TextMatrix(ll_curentRow, 0) = p_da.GetFields(al_Cursor, "BMK_Code")
                .TextMatrix(ll_curentRow, 1) = p_da.GetFields(al_Cursor, "CT_Code")
                .TextMatrix(ll_curentRow, 2) = p_da.GetFields(al_Cursor, "BMK_Desc")
                .TextMatrix(ll_curentRow, 3) = p_da.GetFields(al_Cursor, "CT_Desc")
                If p_da.GetFields(al_Cursor, "SR_Code") <> "" Then
                    .TextMatrix(ll_curentRow, 4) = p_da.GetFields(al_Cursor, "SR_Code")
                    .TextMatrix(ll_curentRow, 5) = p_da.GetFields(al_Cursor, "SR_Name")
                End If
                If al_TotalCol <> -1 Then .TextMatrix(ll_curentRow, al_TotalCol) = "0"
                If al_notActiveCol <> -1 Then .TextMatrix(ll_curentRow, al_notActiveCol) = "0"
                If al_wonCol <> -1 Then .TextMatrix(ll_curentRow, al_wonCol) = "0"
                If al_lostCol <> -1 Then .TextMatrix(ll_curentRow, al_lostCol) = "0"
            End If
            
            ll_ss_code = p_da.GetFields(al_Cursor, "SS_CodeX")
            
            ' calculate sum to get percentage for status completed .. last step .. use column 20 and 21
            If al_wonCol <> -1 Then .TextMatrix(ll_curentRow, al_wonCol) = CLng(.TextMatrix(ll_curentRow, al_wonCol)) + p_da.GetFields(al_Cursor, "WonCount")
            If al_lostCol <> -1 Then .TextMatrix(ll_curentRow, al_lostCol) = CLng(.TextMatrix(ll_curentRow, al_lostCol)) + p_da.GetFields(al_Cursor, "LostCount")
                
            ll_col = GetColOrder(ll_ss_code)
            If ll_col <> -1 Then
                If .TextMatrix(ll_curentRow, ll_col + al_baseCol) = "" Then
                    .TextMatrix(ll_curentRow, ll_col + al_baseCol) = p_da.GetFields(al_Cursor, "PrjCount")
                Else
                    .TextMatrix(ll_curentRow, ll_col + al_baseCol) = CLng(.TextMatrix(ll_curentRow, ll_col + al_baseCol)) + p_da.GetFields(al_Cursor, "PrjCount")
                End If
            End If
            
            If al_TotalCol <> -1 Then
                .TextMatrix(ll_curentRow, al_TotalCol) = CLng(.TextMatrix(ll_curentRow, al_TotalCol)) + p_da.GetFields(al_Cursor, "PrjCount")
            End If
            If al_notActiveCol <> -1 Then
                .TextMatrix(ll_curentRow, al_notActiveCol) = CLng(.TextMatrix(ll_curentRow, al_notActiveCol)) + p_da.GetFields(al_Cursor, "NotActiveUpd")
            End If
            
        End With

        p_da.Next (al_Cursor)
    Wend
    
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".FillGridStatusProjects")
End Sub

Private Sub FillGridStatusProjectsEarly(ByRef ao_grid As MSFlexGrid, ByVal al_Cursor As Long, ByVal al_baseCol As Long, ByVal al_TotalCol As Long, ByVal al_notActiveCol As Long, ByVal al_wonCol As Long, ByVal al_lostCol As Long)
On Error GoTo ErrorHandler

    Dim ll_curentRow As Long
    Dim ll_col As Long
    Dim ll_ss_code As Long
    
    If Not p_da.First(al_Cursor) Then Exit Sub
    
    ' reset all existing al_wonCol, al_lostCol columns to 0
    For ll_curentRow = ao_grid.FixedRows To ao_grid.Rows - 1
        If al_wonCol <> -1 Then ao_grid.TextMatrix(ll_curentRow, al_wonCol) = "0"
        If al_lostCol <> -1 Then ao_grid.TextMatrix(ll_curentRow, al_lostCol) = "0"
        If al_TotalCol <> -1 Then ao_grid.TextMatrix(ll_curentRow, al_TotalCol) = "0"
        If al_notActiveCol <> -1 Then ao_grid.TextMatrix(ll_curentRow, al_notActiveCol) = "0"

    Next
    
    While Not p_da.EOF(al_Cursor)
        ll_curentRow = FindGridRow(ao_grid, ao_grid.FixedRows, p_da.GetFields(al_Cursor, "bmk_code"), p_da.GetFields(al_Cursor, "ct_code"), "")
        With ao_grid
        
            If ll_curentRow = -1 Then
                ' new row
                ll_curentRow = FindGridRow_by1(ao_grid, 2, p_da.GetFields(al_Cursor, "bmk_code"))
                If ll_curentRow = -1 Then
                    .Rows = .Rows + 1
                    ll_curentRow = .Rows - 1
                Else
                    ll_curentRow = FindNextGridRow_by1(ao_grid, ll_curentRow, 0, p_da.GetFields(al_Cursor, "BMK_Code"), 1, p_da.GetFields(al_Cursor, "CT_Code"))
                    Call .AddItem(p_da.GetFields(al_Cursor, "BMK_Code"), ll_curentRow)
                End If
                
                .TextMatrix(ll_curentRow, 0) = p_da.GetFields(al_Cursor, "BMK_Code")
                .TextMatrix(ll_curentRow, 1) = p_da.GetFields(al_Cursor, "CT_Code")
                .TextMatrix(ll_curentRow, 2) = p_da.GetFields(al_Cursor, "BMK_Desc")
                .TextMatrix(ll_curentRow, 3) = p_da.GetFields(al_Cursor, "CT_Desc")
                If al_TotalCol <> -1 Then .TextMatrix(ll_curentRow, al_TotalCol) = "0"
                If al_notActiveCol <> -1 Then .TextMatrix(ll_curentRow, al_notActiveCol) = "0"
                If al_wonCol <> -1 Then .TextMatrix(ll_curentRow, al_wonCol) = "0"
                If al_lostCol <> -1 Then .TextMatrix(ll_curentRow, al_lostCol) = "0"
            End If
            
            ll_ss_code = p_da.GetFields(al_Cursor, "SS_CodeX")
            
            ' calculate sum to get percentage for status completed .. last step .. use column 20 and 21
            If al_wonCol <> -1 Then .TextMatrix(ll_curentRow, al_wonCol) = CLng(.TextMatrix(ll_curentRow, al_wonCol)) + p_da.GetFields(al_Cursor, "WonCount")
            If al_lostCol <> -1 Then .TextMatrix(ll_curentRow, al_lostCol) = CLng(.TextMatrix(ll_curentRow, al_lostCol)) + p_da.GetFields(al_Cursor, "LostCount")
                
            ll_col = GetColOrderEarly(ll_ss_code)
            If ll_col <> -1 Then
                If .TextMatrix(ll_curentRow, ll_col + al_baseCol) = "" Then
                    .TextMatrix(ll_curentRow, ll_col + al_baseCol) = p_da.GetFields(al_Cursor, "PrjCount")
                Else
                    .TextMatrix(ll_curentRow, ll_col + al_baseCol) = CLng(.TextMatrix(ll_curentRow, ll_col + al_baseCol)) + p_da.GetFields(al_Cursor, "PrjCount")
                End If
            End If
            
            If al_TotalCol <> -1 Then
                .TextMatrix(ll_curentRow, al_TotalCol) = CLng(.TextMatrix(ll_curentRow, al_TotalCol)) + p_da.GetFields(al_Cursor, "PrjCount")
            End If
            If al_notActiveCol <> -1 Then
                .TextMatrix(ll_curentRow, al_notActiveCol) = CLng(.TextMatrix(ll_curentRow, al_notActiveCol)) + p_da.GetFields(al_Cursor, "NotActiveUpd")
            End If
            
        End With

        p_da.Next (al_Cursor)
    Wend
    
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".FillGridStatusProjectsEarly")
End Sub


Private Sub FillGridStatusProjectsT(ByRef ao_grid As MSFlexGrid, ByVal al_Cursor As Long, ByVal al_TotalCol As Long)
On Error GoTo ErrorHandler

    Dim ll_curentRow As Long
    Dim ll_col As Long
    
    If Not p_da.First(al_Cursor) Then Exit Sub
    
    ' reset all existing 20, 21 columns to 0 won, lost
    For ll_curentRow = ao_grid.FixedRows To ao_grid.Rows - 1
        ao_grid.TextMatrix(ll_curentRow, al_TotalCol) = "0"
    Next
    
    While Not p_da.EOF(al_Cursor)
        ll_curentRow = FindGridRow(ao_grid, ao_grid.FixedRows, p_da.GetFields(al_Cursor, "bmk_code"), p_da.GetFields(al_Cursor, "ct_code"), p_da.GetFields(al_Cursor, "sr_code"))
        With ao_grid
        
            If ll_curentRow = -1 Then
                ' new row
                ll_curentRow = FindGridRow_by1(ao_grid, ao_grid.FixedRows, p_da.GetFields(al_Cursor, "bmk_code"))
                If ll_curentRow = -1 Then
                    .Rows = .Rows + 1
                    ll_curentRow = .Rows - 1
                Else
                    ll_curentRow = FindNextGridRow_by1(ao_grid, ll_curentRow, 0, p_da.GetFields(al_Cursor, "BMK_Code"), 1, p_da.GetFields(al_Cursor, "CT_Code"))
                    If p_da.GetFields(al_Cursor, "SR_Code") = "" Then
                        Call .AddItem(p_da.GetFields(al_Cursor, "BMK_Code"), ll_curentRow)
                    Else
                        ' search by SR_Code
                        If ll_curentRow = -1 Then
                            ' country not found -> add next line
                            .Rows = .Rows + 1
                            ll_curentRow = .Rows - 1
                        Else
                            ' add item into block of items with the same CT_Code
                            Call .AddItem(p_da.GetFields(al_Cursor, "BMK_Code"), ll_curentRow)
                        End If
                    End If
                End If
                
                .TextMatrix(ll_curentRow, 0) = p_da.GetFields(al_Cursor, "BMK_Code")
                .TextMatrix(ll_curentRow, 1) = p_da.GetFields(al_Cursor, "CT_Code")
                .TextMatrix(ll_curentRow, 2) = p_da.GetFields(al_Cursor, "BMK_Desc")
                .TextMatrix(ll_curentRow, 3) = p_da.GetFields(al_Cursor, "CT_Desc")
                If p_da.GetFields(al_Cursor, "SR_Code") <> "" Then
                    .TextMatrix(ll_curentRow, 4) = p_da.GetFields(al_Cursor, "SR_Code")
                    .TextMatrix(ll_curentRow, 5) = p_da.GetFields(al_Cursor, "SR_Name")
                End If

                .TextMatrix(ll_curentRow, al_TotalCol) = "0"      ' total projects created
            End If
            
            ' calculate sum to get percentage for status completed .. last step .. use column 20 and 21
            .TextMatrix(ll_curentRow, al_TotalCol) = p_da.GetFields(al_Cursor, "PrjCount")
            
        End With

        p_da.Next (al_Cursor)
    Wend
    
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".FillGridStatusProjectsT")
End Sub

Private Sub CalculateWonLostPercent(ByRef ao_grid As MSFlexGrid, ByVal al_wonCol As Long, ByVal al_lostCol As Long, ByVal al_percentCol As Long)
On Error GoTo ErrorHandler
    
    Dim ll_won As Long
    Dim ll_lost As Long
    Dim ll_curentRow  As Long
    For ll_curentRow = 2 To ao_grid.Rows - 1
        ll_won = CLng(ao_grid.TextMatrix(ll_curentRow, al_wonCol))
        ll_lost = CLng(ao_grid.TextMatrix(ll_curentRow, al_lostCol))
        If ll_won + ll_lost = 0 Then
            ao_grid.TextMatrix(ll_curentRow, al_wonCol) = ""
        Else
            If ll_won / (ll_won + ll_lost) * 100 > 1 Then
                ao_grid.TextMatrix(ll_curentRow, al_percentCol) = FormatNumber((ll_won / (ll_won + ll_lost)) * 100, 0) & " %"
            Else
                ao_grid.TextMatrix(ll_curentRow, al_percentCol) = FormatNumber((ll_won / (ll_won + ll_lost)) * 100, 2) & " %"
            End If
        End If
    Next
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".CalculateWonLostPercent")
End Sub

Private Function GetColOrder(ByVal al_SS_Code As Long) As Long
On Error GoTo ErrorHandler

    GetColOrder = -1
    
    Select Case al_SS_Code
    Case 1 ' Lead
        GetColOrder = 0
    Case 3 ' Qualified Lead
        GetColOrder = 1
    Case 5 ' Specified
        GetColOrder = 2
    Case 6 ' Tender
        GetColOrder = 3
    Case 7 ' Quoted
        GetColOrder = 4
    Case 14 ' Other
        GetColOrder = 5
    Case 13 ' Completed
        GetColOrder = 6
    Case 25 ' Ordered
        GetColOrder = 7
    Case Else
        GetColOrder = -1
    End Select

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

Private Function GetColOrderEarly(ByVal al_SS_Code As Long) As Long
On Error GoTo ErrorHandler

    GetColOrderEarly = -1
    
    Select Case al_SS_Code
    Case 1 ' Lead
        GetColOrderEarly = 0
    Case 3 ' Qualified Lead
        GetColOrderEarly = 0
    Case 5 ' Specified
        GetColOrderEarly = 0
    Case 6 ' Tender
        GetColOrderEarly = -1
    Case 7 ' Quoted
        GetColOrderEarly = -1
    Case 14 ' Other
        GetColOrderEarly = -1
    Case 13 ' Completed
        GetColOrderEarly = -1
    Case 25 ' Ordered
        GetColOrderEarly = -1
    Case Else
        GetColOrderEarly = -1
    End Select

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


Private Function FindRowInArray(ByRef ao_array() As Variant, ByVal al_startFrom As Long, ByVal as_val0 As String, ByVal as_val1 As String, ByVal as_val2 As String) As Long
On Error GoTo ErrorHandler
    FindRowInArray = -1
    For al_startFrom = al_startFrom To UBound(ao_array, 2)
        If ao_array(0, al_startFrom) = as_val0 And _
            ao_array(1, al_startFrom) = as_val1 And _
            ao_array(2, al_startFrom) = as_val2 Then
                FindRowInArray = al_startFrom
                Exit For
        End If
    Next

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

Private Function FindGridRow(ByRef ao_grid As MSFlexGrid, ByVal al_startFrom As Long, ByVal as_val0 As String, ByVal as_val1 As String, ByVal SR_Code As String) As Long
On Error GoTo ErrorHandler
    FindGridRow = -1
    For al_startFrom = al_startFrom To ao_grid.Rows - 1
        If ao_grid.TextMatrix(al_startFrom, 0) = as_val0 And _
            ao_grid.TextMatrix(al_startFrom, 1) = as_val1 Then
                If SR_Code = "" Then
                    FindGridRow = al_startFrom
                    Exit For
                Else
                    If ao_grid.TextMatrix(al_startFrom, 4) = SR_Code Then
                        FindGridRow = al_startFrom
                        Exit For
                    End If
                End If
        End If
    Next

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

Private Function FindGridRow_by1(ByRef ao_grid As MSFlexGrid, ByVal al_startFrom As Long, ByVal as_val0 As String) As Long
On Error GoTo ErrorHandler
    FindGridRow_by1 = -1
    For al_startFrom = al_startFrom To ao_grid.Rows - 1
        If ao_grid.TextMatrix(al_startFrom, 0) = as_val0 Then
            FindGridRow_by1 = al_startFrom
            Exit For
        End If
    Next
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".FindGridRow_by1")
End Function

Private Function FindNextGridRow_by1(ByRef ao_grid As MSFlexGrid, ByVal al_startFrom As Long, ByVal al_val0_idx As Long, ByVal as_val0 As String, ByVal al_val1_idx As Long, ByVal as_val1Desc As String) As Long
On Error GoTo ErrorHandler
    FindNextGridRow_by1 = al_startFrom
    While ao_grid.TextMatrix(al_startFrom, al_val0_idx) = as_val0
        If ao_grid.TextMatrix(al_startFrom, al_val1_idx) > as_val1Desc Then
            FindNextGridRow_by1 = al_startFrom
            Exit Function
        End If
        al_startFrom = al_startFrom + 1
        If al_startFrom = ao_grid.Rows Then
            FindNextGridRow_by1 = al_startFrom
            Exit Function
        End If
    Wend
    FindNextGridRow_by1 = al_startFrom
    
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".FindNextGridRow_by1")
End Function

Private Sub SetGridCelBold(ByRef ao_grid As MSFlexGrid, ByVal al_row As Long, ByVal al_Col As Long)
On Error GoTo ErrorHandler
    
    ao_grid.Row = al_row
    ao_grid.Col = al_Col
    ao_grid.CellFontBold = True
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".SetGridCelBold")
End Sub

Private Sub SetGridCellForeColor(ByRef ao_grid As MSFlexGrid, ByVal al_row As Long, ByVal al_Col As Long, ByVal al_Color As Long)
On Error GoTo ErrorHandler
    
    ao_grid.Row = al_row
    ao_grid.Col = al_Col
    ao_grid.CellForeColor = al_Color
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".SetGridCellForeColor")
End Sub

Private Sub SetGridCellBackColor(ByRef ao_grid As MSFlexGrid, ByVal al_row As Long, ByVal al_Col As Long, ByVal al_Color As Long)
On Error GoTo ErrorHandler
    
    ao_grid.Row = al_row
    ao_grid.Col = al_Col
    ao_grid.CellBackColor = al_Color
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".SetGridCellBackColor")
End Sub

Private Sub SetGridRowBold(ByRef ao_grid As MSFlexGrid, ByVal al_row As Long)
On Error GoTo ErrorHandler
    Dim ll_col  As Long
    For ll_col = 0 To ao_grid.Cols - 1
        Call SetGridCelBold(ao_grid, al_row, ll_col)
    Next
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".SetGridRowBold")
End Sub

Private Sub SetGridRowForeColor(ByRef ao_grid As MSFlexGrid, ByVal al_row As Long, ByVal al_Color As Long)
On Error GoTo ErrorHandler
    Dim ll_col  As Long
    For ll_col = ao_grid.FixedCols To ao_grid.Cols - 1
        Call SetGridCellForeColor(ao_grid, al_row, ll_col, al_Color)
    Next
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".SetGridRowForeColor")
End Sub

Private Sub SetGridRowBackColor(ByRef ao_grid As MSFlexGrid, ByVal al_row As Long, ByVal al_Color As Long)
On Error GoTo ErrorHandler
    Dim ll_col  As Long
    For ll_col = ao_grid.FixedCols To ao_grid.Cols - 1
        Call SetGridCellBackColor(ao_grid, al_row, ll_col, al_Color)
    Next
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".SetGridRowBackColor")
End Sub

Private Sub SetGridColForeColor(ByRef ao_grid As MSFlexGrid, ByVal al_Col As Long, ByVal al_Color As Long)
On Error GoTo ErrorHandler
    Dim ll_Row  As Long
    For ll_Row = ao_grid.FixedRows To ao_grid.Rows - 1
        Call SetGridCellForeColor(ao_grid, ll_Row, al_Col, al_Color)
    Next
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".SetGridColForeColor")
End Sub

Private Sub SetGridColBackColor(ByRef ao_grid As MSFlexGrid, ByVal al_Col As Long, ByVal al_Color As Long)
On Error GoTo ErrorHandler
    Dim ll_Row  As Long
    For ll_Row = ao_grid.FixedRows To ao_grid.Rows - 1
        Call SetGridCellBackColor(ao_grid, ll_Row, al_Col, al_Color)
    Next
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".SetGridColBackColor")
End Sub

Private Function GetSalesRequest(ByVal al_trwCode As Long, ByVal al_Level As Long, ByVal as_Type As String, Optional ByVal as_MSA As String = "") As String
On Error GoTo ErrorHandler
    
    Dim ls_retVal As String
    Select Case as_Type
        Case "CG"
            Select Case al_trwCode
                Case 1  ' Market
                    Select Case al_Level
                        Case 0, 1 ' All markets / Market
                            ls_retVal = "EXEC Sales_CGMarket" & as_MSA & " '$language_code$', $cyear$, '$BMK_Code$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 2  ' Country
                            ls_retVal = "EXEC Sales_CGCountry" & as_MSA & " '$language_code$', $cyear$, '$BMK_Code$', '$CT_Code$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 3  ' User
                            ls_retVal = "EXEC Sales_CGCreator '$language_code$', $cyear$, '$BMK_Code$', '$CT_Code$', '$Login_Name$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                    End Select
                    
                Case 2  ' Area
                    Select Case al_Level
                        Case 0, 1 ' Area
                            ls_retVal = "EXEC Sales_CGRepGrp '$language_code$', $cyear$, $RAR_Code$, '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 3  ' z_creator
                            ls_retVal = "EXEC Sales_CGCreator '$language_code$', $cyear$, '$BMK_Code$', '$CT_Code$', '$Login_Name$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                    End Select
                    
                Case 3
                    Select Case al_Level
                        Case 0, 1 ' All markets / Market
                            ls_retVal = "EXEC Sales_CGMarket" & as_MSA & " '$language_code$', $cyear$, '$BMK_Code$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 3  ' user
                            ls_retVal = "EXEC Sales_CGCreator '$language_code$', $cyear$, '$BMK_Code$', '$CT_Code$', '$Login_Name$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                    End Select
                    
                Case 4  ' Area2
                    Select Case al_Level
                        Case 0  ' All markets
                            ls_retVal = "EXEC Sales_CGMarket" & as_MSA & " '$language_code$', $cyear$, '$BMK_Code$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 1, 2 ' Area
                            ls_retVal = "EXEC Sales_CGRepGrp '$language_code$', $cyear$, $RAR_Code$, '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 3  ' z_creator
                            ls_retVal = "EXEC Sales_CGCreator '$language_code$', $cyear$, '$BMK_Code$', '$CT_Code$', '$Login_Name$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                    End Select
                Case 5  ' market/ ... / customer
                    Select Case al_Level
                        Case 0, 1 ' All markets / Market
                            ls_retVal = "EXEC Sales_CGMarket" & as_MSA & " '$language_code$', $cyear$, '$BMK_Code$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 2  ' Country
                            ls_retVal = "EXEC Sales_CGCountry" & as_MSA & " '$language_code$', $cyear$, '$BMK_Code$', '$CT_Code$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 3, 4 ' Type/Customer
                            ls_retVal = "EXEC Sales_CGCustomer" & as_MSA & " '$language_code$', $cyear$, '$BMK_Code$', '$CT_Code$', $CCT_Code$, $CCU_CapKey$, '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                    End Select
            End Select
        Case "OTHER"
            Select Case al_trwCode
                Case 1  ' Market
                    Select Case al_Level
                        Case 0, 1 ' All markets / Market
                            ls_retVal = "EXEC Sales_OtherMarket" & as_MSA & " '$language_code$', '$cyear$', '$BMK_Code$', $AS_FLAG$"
                        Case 2  ' Country
                            ls_retVal = "EXEC Sales_OtherCountry" & as_MSA & " '$language_code$', '$cyear$', '$BMK_Code$', '$CT_Code$', $AS_FLAG$"
                        Case 3  ' User
                            ls_retVal = "EXEC Sales_OtherCreator '$language_code$', '$cyear$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $AS_FLAG$"
                    End Select
                    
                Case 2  ' Area
                    Select Case al_Level
                        Case 0, 1 ' Area
                            ls_retVal = "EXEC Sales_OtherRepGrp '$language_code$', '$cyear$', $RAR_Code$, $AS_FLAG$"
                        Case 3  ' z_creator
                            ls_retVal = "EXEC Sales_OtherCreator '$language_code$', '$cyear$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $AS_FLAG$"
                    End Select
                    
                Case 3
                    Select Case al_Level
                        Case 0, 1 ' All markets / Market
                            ls_retVal = "EXEC Sales_OtherMarket" & as_MSA & " '$language_code$', '$cyear$', '$BMK_Code$', $AS_FLAG$"
                        Case 3  ' user
                            ls_retVal = "EXEC Sales_OtherCreator '$language_code$', '$cyear$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $AS_FLAG$"
                    End Select
            
                Case 4  ' Area
                    Select Case al_Level
                        Case 0      ' All markets
                            ls_retVal = "EXEC Sales_OtherMarket" & as_MSA & " '$language_code$', '$cyear$', '$BMK_Code$', $AS_FLAG$"
                        Case 1, 2 ' Area
                            ls_retVal = "EXEC Sales_OtherRepGrp '$language_code$', '$cyear$', $RAR_Code$, $AS_FLAG$"
                        Case 3  ' z_creator
                            ls_retVal = "EXEC Sales_OtherCreator '$language_code$', '$cyear$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $AS_FLAG$"
                    End Select
                Case 5  ' market/ ... / customer
                    Select Case al_Level
                        Case 0, 1 ' All markets / Market
                            ls_retVal = "EXEC Sales_OtherMarket" & as_MSA & " '$language_code$', '$cyear$', '$BMK_Code$', $AS_FLAG$"
                        Case 2  ' Country
                            ls_retVal = "EXEC Sales_OtherCountry" & as_MSA & " '$language_code$', '$cyear$', '$BMK_Code$', '$CT_Code$', $AS_FLAG$"
                        Case 3, 4 ' Type/Customer
                            ls_retVal = "EXEC Sales_OtherCustomer" & as_MSA & " '$language_code$', '$cyear$', '$BMK_Code$', '$CT_Code$', $CCT_Code$, $CCU_CapKey$, $AS_FLAG$"
                    End Select
            End Select
    End Select
    GetSalesRequest = ls_retVal
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetSalesRequest")
End Function


Private Function GetSalesRepRequest(ByVal al_trwCode As Long, ByVal al_Level As Long) As String
On Error GoTo ErrorHandler
    
    Dim ls_retVal As String
    Select Case al_trwCode
        Case 1  ' Market
            Select Case al_Level
                Case 0, 1, 2 ' All markets/ Market/ Country
                    ls_retVal = "EXEC Sales_Rep_Mkt '$language_code$', $cyear$, '$BMK_CODE$', '$CT_CODE$', '$CURR_CODE$', $SRVA_CODE$, $GRP_REP_CODE$, $GRP_CT_CODE$, $GRP_MKT_CODE$"
                Case 3  ' User
                    ls_retVal = "EXEC Sales_Rep_Creator '$language_code$', $cyear$, NULL, '$SR_CODE$', '$CURR_CODE$', $SRVA_CODE$, $GRP_REP_CODE$, $GRP_CT_CODE$, $GRP_MKT_CODE$"
            End Select
            
        Case 2  ' Area
            Select Case al_Level
                Case 0, 1 ' Area
                    ls_retVal = "EXEC Sales_Rep_Creator '$language_code$', $cyear$, $RAR_Code$, NULL, '$CURR_CODE$', $SRVA_CODE$, $GRP_REP_CODE$, $GRP_CT_CODE$, $GRP_MKT_CODE$"
                Case 3  ' z_creator
                    ls_retVal = "EXEC Sales_Rep_Creator '$language_code$', $cyear$, $RAR_Code$, '$SR_CODE$', '$CURR_CODE$', $SRVA_CODE$, NULL, '', ''"
            End Select
            
        Case 3
            Select Case al_Level
                Case 0, 1  ' All markets / Market
                    ls_retVal = "EXEC Sales_Rep_Mkt '$language_code$', $cyear$, '$BMK_CODE$', NULL, '$CURR_CODE$', $SRVA_CODE$, $GRP_REP_CODE$, $GRP_CT_CODE$, $GRP_MKT_CODE$"
                Case 3  ' user
                    ls_retVal = "EXEC Sales_Rep_Creator '$language_code$', $cyear$, NULL, '$SR_CODE$', '$CURR_CODE$', $SRVA_CODE$, $GRP_REP_CODE$, $GRP_CT_CODE$, $GRP_MKT_CODE$"
            End Select
    
        Case 4  ' Area2
            Select Case al_Level
                Case 0  ' All Markets by area
                    ls_retVal = "EXEC Sales_Rep_Grp '$language_code$', $cyear$, NULL, '$CURR_CODE$', $SRVA_CODE$"
                Case 1  ' Market
                    ls_retVal = "EXEC Sales_Rep_Grp '$language_code$', $cyear$, '$BMK_CODE$', '$CURR_CODE$', $SRVA_CODE$"
                Case 2 ' Area
                    ls_retVal = "EXEC Sales_Rep_Creator '$language_code$', $cyear$, $RAR_Code$, NULL, '$CURR_CODE$', $SRVA_CODE$, NULL, '', ''"
                Case 3  ' z_creator
                    ls_retVal = "EXEC Sales_Rep_Creator '$language_code$', $cyear$, $RAR_Code$, '$SR_CODE$', '$CURR_CODE$', $SRVA_CODE$, NULL, '', ''"
            End Select
        Case 5  ' market/ ... / customer
            Select Case al_Level
                Case 0, 1, 2 ' All markets/ Market/ Country
                    ls_retVal = "EXEC Sales_Rep_Mkt '$language_code$', $cyear$, '$BMK_CODE$', '$CT_CODE$', '$CURR_CODE$', $SRVA_CODE$, $GRP_REP_CODE$, $GRP_CT_CODE$, $GRP_MKT_CODE$"
                Case 3, 4 ' Type/Customer
                    ls_retVal = ""
            End Select
    End Select
    GetSalesRepRequest = ls_retVal
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetSalesRepRequest")
End Function



Private Function GetStatusProjectsRequest(ByVal al_trwCode As Long, ByVal al_Level As Long, ByVal as_Type As String) As String
On Error GoTo ErrorHandler
    
    Dim ls_retVal As String
    Select Case al_trwCode
        Case 1  ' Market
            Select Case al_Level
                Case 0, 1 ' All markets / Market
                    ls_retVal = "EXEC ProjectStat$TYPE$_Market '$language_code$', '$date1$', '$date2$', '$BMK_Code$'"
                Case 2  ' Country
                    ls_retVal = "EXEC ProjectStat$TYPE$_Country '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$'"
                Case 3  ' User
                    ls_retVal = "EXEC ProjectStat$TYPE$_Creator '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
            
        Case 2  ' Area
            Select Case al_Level
                Case 0, 1 ' Area
                    ls_retVal = "EXEC ProjectStat$TYPE$_RepGrp '$language_code$', '$date1$', '$date2$', $RAR_Code$"
                Case 3  ' z_creator
                    ls_retVal = "EXEC ProjectStat$TYPE$_Creator '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
            
        Case 3
            Select Case al_Level
                Case 0, 1 ' All markets / Market
                    ls_retVal = "EXEC ProjectStat$TYPE$_Market '$language_code$', '$date1$', '$date2$', '$BMK_Code$'"
                Case 3  ' user
                    ls_retVal = "EXEC ProjectStat$TYPE$_Creator '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
    
        Case 4  ' Area2
            Select Case al_Level
                Case 0  ' All markets
                    ls_retVal = "EXEC ProjectStat$TYPE$_Market '$language_code$', '$date1$', '$date2$', '$BMK_Code$'"
                Case 1, 2 ' Area
                    ls_retVal = "EXEC ProjectStat$TYPE$_RepGrp '$language_code$', '$date1$', '$date2$', $RAR_Code$"
                Case 3  ' z_creator
                    ls_retVal = "EXEC ProjectStat$TYPE$_Creator '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
        Case 5  ' market/ ... / customer
            Select Case al_Level
                Case 0, 1 ' All markets / Market
                    ls_retVal = "EXEC ProjectStat$TYPE$_Market '$language_code$', '$date1$', '$date2$', '$BMK_Code$'"
                Case 2  ' Country
                    ls_retVal = "EXEC ProjectStat$TYPE$_Country '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$'"
                Case 3, 4 ' Type/Customer
                    ls_retVal = ""
            End Select
    End Select
    
    ls_retVal = Replace(ls_retVal, "$TYPE$", as_Type, , , vbTextCompare)
    
    GetStatusProjectsRequest = ls_retVal
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetStatusProjectsRequest")
End Function

Private Function PS2_ReplaceGrouping(ByVal as_req As String) As String
    If chk_PS2_Grouping(0).Value = vbChecked Then
        as_req = Replace(as_req, "$GRP1$", "CT", , , vbTextCompare)
    Else
        as_req = Replace(as_req, "$GRP1$", "", , , vbTextCompare)
    End If
    If chk_PS2_Grouping(1).Value = vbChecked Then
        as_req = Replace(as_req, "$GRP2$", "SR", , , vbTextCompare)
    Else
        as_req = Replace(as_req, "$GRP2$", "", , , vbTextCompare)
    End If
    
    PS2_ReplaceGrouping = as_req
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".PS2_ReplaceGrouping")
End Function

Private Function Visits2_ReplaceGrouping(ByVal as_req As String) As String
    If chk_visits2_Grouping(0).Value = vbChecked Then
        as_req = Replace(as_req, "$GRP1$", "CT", , , vbTextCompare)
    Else
        as_req = Replace(as_req, "$GRP1$", "", , , vbTextCompare)
    End If
    If chk_visits2_Grouping(1).Value = vbChecked Then
        as_req = Replace(as_req, "$GRP2$", "SR", , , vbTextCompare)
    Else
        as_req = Replace(as_req, "$GRP2$", "", , , vbTextCompare)
    End If
    
    Visits2_ReplaceGrouping = as_req
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".Visits2_ReplaceGrouping")
End Function


Private Function GetStatusProjectsGrpRequest(ByVal al_trwCode As Long, ByVal al_Level As Long, ByVal as_Type As String) As String
On Error GoTo ErrorHandler
    
    Dim ls_retVal As String
    Select Case al_trwCode
        Case 1  ' Market
            Select Case al_Level
                Case 0, 1 ' All markets / Market
                    ls_retVal = "EXEC ProjectStat$TYPE$_$GRP1$$GRP2$_Market '$language_code$', '$date1$', '$date2$', '$BMK_Code$'"
                Case 2  ' Country
                    ls_retVal = "EXEC ProjectStat$TYPE$_$GRP1$$GRP2$_Country '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$'"
                Case 3  ' User
                    ls_retVal = "EXEC ProjectStat$TYPE$_$GRP1$$GRP2$_Creator '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
            
        Case 2  ' Area
            Select Case al_Level
                Case 0, 1 ' Area
                    ls_retVal = "EXEC ProjectStat$TYPE$_$GRP1$$GRP2$_RepGrp '$language_code$', '$date1$', '$date2$', $RAR_Code$"
                Case 3  ' z_creator
                    ls_retVal = "EXEC ProjectStat$TYPE$_$GRP1$$GRP2$_Creator '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
            
        Case 3
            Select Case al_Level
                Case 0, 1 ' All markets / Market
                    ls_retVal = "EXEC ProjectStat$TYPE$_$GRP1$$GRP2$_Market '$language_code$', '$date1$', '$date2$', '$BMK_Code$'"
                Case 3  ' user
                    ls_retVal = "EXEC ProjectStat$TYPE$_$GRP1$$GRP2$_Creator '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
    
        Case 4  ' Area2
            Select Case al_Level
                Case 0  ' All markets
                    ls_retVal = "EXEC ProjectStat$TYPE$_$GRP1$$GRP2$_Market '$language_code$', '$date1$', '$date2$', '$BMK_Code$'"
                Case 1, 2 ' Area
                    ls_retVal = "EXEC ProjectStat$TYPE$_$GRP1$$GRP2$_RepGrp '$language_code$', '$date1$', '$date2$', $RAR_Code$"
                Case 3  ' z_creator
                    ls_retVal = "EXEC ProjectStat$TYPE$_$GRP1$$GRP2$_Creator '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
            End Select
        Case 5  ' market/ ... / customer
            Select Case al_Level
                Case 0, 1 ' All markets / Market
                    ls_retVal = "EXEC ProjectStat$TYPE$_$GRP1$$GRP2$_Market '$language_code$', '$date1$', '$date2$', '$BMK_Code$'"
                Case 2  ' Country
                    ls_retVal = "EXEC ProjectStat$TYPE$_$GRP1$$GRP2$_Country '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$'"
                Case 3, 4 ' Type/Customer
                    ls_retVal = ""
            End Select
    End Select
    
    ls_retVal = Replace(ls_retVal, "$TYPE$", as_Type, , , vbTextCompare)
    ls_retVal = PS2_ReplaceGrouping(ls_retVal)
    
    GetStatusProjectsGrpRequest = ls_retVal
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetStatusProjectsGrpRequest")
End Function



Private Function GetVisitsGrpRequest() As String
On Error GoTo ErrorHandler
    Dim ls_retVal As String
    ls_retVal = "EXEC Visit2_$GRP1$$GRP2$ '$language_code$', '$date1$', '$date2$', '$BMK_Code$', '$CT_Code$', '$Login_Name$', $RAR_Code$"
    
    ls_retVal = Visits2_ReplaceGrouping(ls_retVal)
    
    GetVisitsGrpRequest = ls_retVal
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetVisitsGrpRequest")
End Function


Private Sub display_report_Click()
On Error GoTo ErrorHandler
    Dim Start
    Dim Finish
    Dim ls_req As String
    
    Start = timer
    
    If tv1.SelectedItem Is Nothing Then Exit Sub
    If tv1.Count = 0 Then Exit Sub
    
    Call init_grid(grd_result(0), 3)
    Call init_grid(grd_result(1), 3)
    Call init_grid(grd_result(2), 3)
    Call init_grid(grd_result(3), 3)
    Call init_grid(grd_result(4), 3)
    
    Call init_grid(grd_result(5), 7)
    Call init_grid(grd_result(6), 6)
    Call init_grid(grd_result(7), 10)
    
    Call init_grid(grd_result(8), 3)
    Call init_grid(grd_result(9), 3)
    Call init_grid(grd_result(10), 3)
    Call init_grid(grd_result(11), 7)
    Call init_grid(grd_result(12), 6)
    Call init_grid(grd_result(13), 10)
    
    Call lvw_Task_Initialize
    If Process_Report Then
         Finish = timer
        
         ' Log the report ask in the database
         ls_req = "INSERT INTO Cap_Rep_Trace SELECT '" & gsuser & "', '" & ms_ToLog & SEP & "TOTAL TIME: " & Finish - Start & "', '" _
             & cal1.date_courte & "', '" & cal2.date_courte & "', '" _
             & annee.Text & "', '" & Mois.Text & "', '" _
             & tv1.NodeInfo(tv1.SelectedItem).TextValue & "', '" _
             & tab_prd.SelectedItem.Caption & "', GETDATE()"
        Call ExecuteSQLSafe(p_da, ls_req)
        mb_reportProcessed = True
    End If
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".display_report_Click")
End Sub


Public Sub G_popup(ByVal ai_grdNb As Integer, ByVal as_title As String)
On Error GoTo ErrorHandler

Dim col_width   As Integer
Dim y           As Integer
Dim lo_Tab As Object
Dim ll_GridIndex As Integer

'Maximize the grid that past in parameter of the sub
    If mia_WhichGridIsMax(0) = -1 Then
        mia_WhichGridIsMax(0) = grd_result(ai_grdNb).Index
        mia_WhichGridIsMax(1) = grd_result(ai_grdNb).Top
        mia_WhichGridIsMax(2) = grd_result(ai_grdNb).Left
        
              
                        
        If mb_DisplayFilterByUser Then
            L_focus.Caption = ""
            L_focus.Visible = False
        Else
            ReDim ms_MsgInfo(0, 1)
            ms_MsgInfo(0, 0) = "$TITLE$"
            ms_MsgInfo(0, 1) = as_title
            L_focus.Caption = GetLabel("l_focus", "#Focus On $TITLE$", ms_MsgInfo)
            L_focus.Zorder 0
            L_focus.Visible = True
        End If

        Select Case ai_grdNb
            Case 0, 4, 5, 6, 7
                tbs_Result(ai_grdNb).Top = tbs_Result(0).Top
                tbs_Result(ai_grdNb).Left = tbs_Result(0).Left
                tbs_Result(ai_grdNb).Width = grd_result(0).Width + G_expand_factor_h - 240
                tbs_Result(ai_grdNb).Zorder
                
                For Each lo_Tab In tbs_Result(ai_grdNb).Tabs
                  ll_GridIndex = Mid(lo_Tab.Key, 2)
                  grd_result(ll_GridIndex).Top = grd_result(0).Top
                  grd_result(ll_GridIndex).Left = grd_result(0).Left
                  grd_result(ll_GridIndex).Width = grd_result(ll_GridIndex).Width + G_expand_factor_h
                  grd_result(ll_GridIndex).Height = grd_result(ll_GridIndex).Height + G_expand_factor_v
                  grd_result(ll_GridIndex).Zorder 0
                Next
                
            Case Else
                ReDim ms_MsgInfo(0, 1)
                ms_MsgInfo(0, 0) = "$TITLE$"
                ms_MsgInfo(0, 1) = as_title
                L_focus.Caption = GetLabel("l_focus", "#Focus On $TITLE$", ms_MsgInfo)
                L_focus.Zorder
                L_focus.Visible = True
                tbs_Result(0).Visible = False
        
                grd_result(ai_grdNb).Width = grd_result(ai_grdNb).Width + G_expand_factor_h
                grd_result(ai_grdNb).Height = grd_result(ai_grdNb).Height + G_expand_factor_v
           
                grd_result(ai_grdNb).Top = grd_result(0).Top
                grd_result(ai_grdNb).Left = grd_result(0).Left
        End Select
        
        
        
        img_Min.Visible = True
    Else
    'Minimize the grid that past in parameter of the sub
        mia_WhichGridIsMax(0) = -1

        tbs_Result(0).Visible = mb_DisplayFilterByUser
        
        Select Case ai_grdNb
            Case 0, 4, 5, 6, 7
                
                For Each lo_Tab In tbs_Result(ai_grdNb).Tabs
                  ll_GridIndex = Mid(lo_Tab.Key, 2)
                  grd_result(ll_GridIndex).Top = mia_WhichGridIsMax(1)
                  grd_result(ll_GridIndex).Left = mia_WhichGridIsMax(2)
                  grd_result(ll_GridIndex).Width = grd_result(ll_GridIndex).Width - G_expand_factor_h
                  grd_result(ll_GridIndex).Height = grd_result(ll_GridIndex).Height - G_expand_factor_v
                Next
                
                tbs_Result(ai_grdNb).Top = grd_result(ai_grdNb).Top - tbs_Result(ai_grdNb).Height
                tbs_Result(ai_grdNb).Left = grd_result(ai_grdNb).Left
                tbs_Result(ai_grdNb).Width = grd_result(ai_grdNb).Width - 330
                tbs_Result(ai_grdNb).Visible = mb_DisplayFilterByUser

                
             Case Else
                grd_result(ai_grdNb).Top = mia_WhichGridIsMax(1)
                grd_result(ai_grdNb).Left = mia_WhichGridIsMax(2)
                grd_result(ai_grdNb).Width = grd_result(ai_grdNb).Width - G_expand_factor_h
                grd_result(ai_grdNb).Height = grd_result(ai_grdNb).Height - G_expand_factor_v
                
        End Select
        
        L_focus.Visible = False
        img_Min.Visible = False
    
    End If
    
    grd_result(ai_grdNb).Zorder 0
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".G_popup")
End Sub

Private Function CheckDataAuthorization() As Boolean
On Error GoTo ErrorHandler

Dim ll_cursor   As Long
Dim ls_req      As String

    CheckDataAuthorization = False
    Select Case Level_selected
    Case 0
        ls_req = "SELECT 1 FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Markets' AND Autho_Values IS NULL"
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        If p_da.RowCount(ll_cursor) > 0 Then
            CheckDataAuthorization = True
        End If
        Call p_da.Close(ll_cursor)
        Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
        Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
        Exit Function
    Case 1
        Select Case cb_trw.SelectedItem.Key
            Case 1, 3, 5
                ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Markets'"
            Case 2
                ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Area'"
            Case 4
                ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Markets'"
        End Select
        
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        If p_da.RowCount(ll_cursor) > 0 Then
            If p_da.GetFields(ll_cursor, 0) = "" Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
            If InStr(1, p_da.GetFields(ll_cursor, 0), Trim(tv1.NodeInfo(tv1.SelectedItem).GetData(0))) > 0 Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
        End If
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    Case 2
        ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Markets'"
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        If p_da.RowCount(ll_cursor) > 0 Then
            If p_da.GetFields(ll_cursor, 0) = "" Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
            If InStr(1, p_da.GetFields(ll_cursor, 0), Trim(tv1.NodeInfo(tv1.SelectedItem.Parent).GetData(0))) > 0 Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
        End If
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
        
        ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Countries'"
        ll_cursor = p_da.OpenSQL(ls_req)
        If p_da.RowCount(ll_cursor) > 0 Then
            If InStr(1, p_da.GetFields(ll_cursor, 0), Trim(tv1.NodeInfo(tv1.SelectedItem).GetData(0))) > 0 Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
        End If
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    Case 3
        Select Case cb_trw.SelectedItem.Key
            Case 1, 3
                ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Markets'"
            Case 2, 4
                ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Area'"
            Case 5
                ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Countries'"
        End Select
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        If p_da.RowCount(ll_cursor) > 0 Then
            If p_da.GetFields(ll_cursor, 0) = "" Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
            ' Here was the bug
            If cb_trw.SelectedItem.Key = 1 Then
                If InStr(1, p_da.GetFields(ll_cursor, 0), Trim(tv1.NodeInfo(tv1.SelectedItem.Parent.Parent).GetData(0))) > 0 Then
                    CheckDataAuthorization = True
                    Call p_da.Close(ll_cursor)
                    Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                    Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                    Exit Function
                End If
            Else
                If InStr(1, p_da.GetFields(ll_cursor, 0), Trim(tv1.NodeInfo(tv1.SelectedItem.Parent).GetData(0))) > 0 Then
                    CheckDataAuthorization = True
                    Call p_da.Close(ll_cursor)
                    Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                    Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                    Exit Function
                End If
            End If
        End If
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
        
        If cb_trw.SelectedItem.Key = 1 Then
            ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Countries'"
            ll_cursor = OpenSQLSafe(p_da, ls_req)
            If p_da.RowCount(ll_cursor) > 0 Then
                If InStr(1, p_da.GetFields(ll_cursor, 0), Trim(tv1.NodeInfo(tv1.SelectedItem.Parent).GetData(0))) > 0 Then
                    CheckDataAuthorization = True
                    Call p_da.Close(ll_cursor)
                    Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                    Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                    Exit Function
                End If
            End If
            Call p_da.Close(ll_cursor)
            ll_cursor = 0
        End If
            
        ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Users'"
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        If p_da.RowCount(ll_cursor) > 0 Then
            If InStr(1, p_da.GetFields(ll_cursor, 0), Trim(tv1.NodeInfo(tv1.SelectedItem).GetData(0))) > 0 Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
        End If
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    Case 4  ' level Customer
        Debug.Assert (cb_trw.SelectedItem.Key = 5)
        ' 1. check market
        ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Markets'"
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        If p_da.RowCount(ll_cursor) > 0 Then
            If p_da.GetFields(ll_cursor, 0) = "" Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
            If InStr(1, p_da.GetFields(ll_cursor, 0), Trim(tv1.NodeInfo(tv1.SelectedItem.Parent.Parent.Parent).GetData(0))) > 0 Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
        End If
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
        ' 2. check country
        ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Countries'"
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        If p_da.RowCount(ll_cursor) > 0 Then
            If p_da.GetFields(ll_cursor, 0) = "" Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
            If InStr(1, p_da.GetFields(ll_cursor, 0), Trim(tv1.NodeInfo(tv1.SelectedItem.Parent.Parent).GetData(0))) > 0 Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
        End If
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
        ' 3. check customer
        ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Customers'"
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        If p_da.RowCount(ll_cursor) > 0 Then
            If p_da.GetFields(ll_cursor, 0) = "" Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
            If InStr(1, p_da.GetFields(ll_cursor, 0), Trim(tv1.NodeInfo(tv1.SelectedItem).GetData(0))) > 0 Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
        End If
        ' 4. check owner
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
        ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Users'"
        ll_cursor = OpenSQLSafe(p_da, ls_req)
        If p_da.RowCount(ll_cursor) > 0 Then
            If InStr(1, p_da.GetFields(ll_cursor, 0), Trim(tv1.NodeInfo(tv1.SelectedItem).GetData(3))) > 0 Then
                CheckDataAuthorization = True
                Call p_da.Close(ll_cursor)
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                Exit Function
            End If
        End If
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
        
        
    End Select

    Exit Function
    
ErrorHandler:
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If
    Call ErrorHandler(Extender.Name & ".CheckDataAuthorization")
End Function

Private Sub AddRptLog(ByVal as_User As String, ByVal as_tab As String)
On Error GoTo ErrorHandler
Dim a As ArmDb
    Call ExecuteSQLSafe(p_da, "INSERT INTO Cap_rpt_log VALUES(GETDATE(), '" & as_User & "', '" & as_tab & "')")
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".CheckDataAuthorization")
End Sub

Private Sub grd_project_DblClick(Index As Integer)
On Error GoTo ErrorHandler
    If Level_selected >= 3 Then Exit Sub
    
    Dim ll_MONTHCol As Long
    
    ll_MONTHCol = GRD_GetColIndex(mo_projectInfo(Index), "MONTH")
    Debug.Assert (ll_MONTHCol <> -1)
    
    If grd_project(Index).TextMatrix(grd_project(Index).Row, mo_projectInfo(Index).Cols(ll_MONTHCol).Index) = "" Then Exit Sub


    Dim ll_YEARCol As Long
    Dim ll_TOP10Col As Long
    Dim ll_BMK_CodeCol As Long
    ll_YEARCol = GRD_GetColIndex(mo_projectInfo(Index), "YEAR")
    ll_TOP10Col = GRD_GetColIndex(mo_projectInfo(Index), "TOPTEN")
    ll_BMK_CodeCol = GRD_GetColIndex(mo_projectInfo(Index), "BMK_CODE")
    Debug.Assert (ll_YEARCol <> -1)
    Debug.Assert (ll_TOP10Col <> -1)
    Debug.Assert (ll_BMK_CodeCol <> -1)

    Call LockScreen(True)

    If mo_projDetFrm Is Nothing Then
        Set mo_projDetFrm = New capdly_projDet
        Set mo_projDetFrm.ArmDb = p_da
        mo_projDetFrm.ScreenLabels = mc_ScreenLabels
        mo_projDetFrm.Language_Code = ms_Language_Code
        
        Call mo_projDetFrm.Load_A_Com
        Call mo_projDetFrm.Init_control
        mo_projDetFrm.U_Code = ml_U_Code
        
    End If
    mo_projDetFrm.Level_selected = Level_selected
    mo_projDetFrm.TVFilterDesc = tv1.SelectedItem.Text
    mo_projDetFrm.PeriodDesc = tbs_project.SelectedItem.Caption
    mo_projDetFrm.SP_SAFlagDesc = tbs_ProjectType.SelectedItem.Caption
    
    mo_projDetFrm.Left = frm_projects.Left + tbs_ProjectType.Left
    mo_projDetFrm.Width = tbs_ProjectType.Width
    mo_projDetFrm.Top = 4755
    mo_projDetFrm.Height = 5580
    
    Call LockScreen(False)
    Call mo_projDetFrm.Run(cb_trw.SelectedItem.GetData(0), _
                            tbs_ProjectType.SelectedItem.Tag, _
                            grd_project(Index).TextMatrix(grd_project(Index).Row, mo_projectInfo(Index).Cols(ll_MONTHCol).Index), _
                            grd_project(Index).TextMatrix(grd_project(Index).Row, mo_projectInfo(Index).Cols(ll_YEARCol).Index), _
                            Left(grd_project(Index).TextMatrix(grd_project(Index).Row, mo_projectInfo(Index).Cols(ll_TOP10Col).Index), 1) = "T", _
                            grd_project(Index).TextMatrix(grd_project(Index).Row, mo_projectInfo(Index).Cols(ll_BMK_CodeCol).Index), _
                            tbs_project.SelectedItem.Tag)

    Call mo_projDetFrm.Unload_A_Com
    Set mo_projDetFrm.ArmDb = Nothing
    Call Unload(mo_projDetFrm)
    Set mo_projDetFrm = Nothing
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".grd_project_DblClick")
End Sub


Private Sub grd_visitDetail_RowLoaded(Index As Integer, ByVal al_row As Long)
On Error GoTo ErrorHandler
    If Index = 2 Then Exit Sub      ' for new customers do not use colors
    grd_visitDetail(Index).TextColor(al_row) = IIf(grd_visitDetail(Index).Data(al_row, "DAYS") <= grd_visitDetail(Index).Data(al_row, "CP_DAYS"), COLOR_GREEN, COLOR_RED)
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".grd_visitDetail_RowLoaded")
End Sub

'Private Sub grd_Result_DblClick(Index As Integer)
'    G_popup grd_Result(Index), lbl_Title(Index)
'End Sub

Private Sub img_Max_Click(Index As Integer)
On Error GoTo ErrorHandler

'    If IsControlLoaded(tbs_Result, Index) Then
'        G_popup grd_Result(Mid(tbs_Result(Index).SelectedItem.Key, 2)), tbs_Result(Index).SelectedItem.Caption
'    Else
        G_popup Index, lbl_Title(Index)
'    End If
    
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".img_Max_Click")
End Sub

Private Sub img_Min_Click()
On Error GoTo ErrorHandler
    G_popup mia_WhichGridIsMax(0), ""
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".img_Min_Click")
End Sub

Private Sub mFocusProd_Quit()
On Error GoTo ErrorHandler
    mFocusProd.Visible = False
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".mFocusProd_Quit")
End Sub

Private Sub opt_salesOptions_Click(Index As Integer)
On Error GoTo ErrorHandler
    
    Select Case tbs_sales.SelectedItem.Key
    Case "ALL"
        Call Process_Sales
        mb_sales_MSA_processed = False
    Case "MSA"
        Call Process_Sales_MSA
        mb_sales_processed = False

    End Select

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

Private Sub opt_salesPeriod_Click(Index As Integer)
On Error GoTo ErrorHandler
    frm_sales_PDF_Period.Visible = (Index = 2)
    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".opt_salesPeriod_Click")
End Sub

Private Sub sales_pdf_print_Click()
On Error GoTo ErrorHandler
    fr_CMD.Enabled = False
    fr_Filter.Enabled = False
    tbs_sales.Enabled = False
    ' set default selections
    opt_salesPeriod(0).Value = True
    chk_salesPeriodGrp(0).Value = 0
    chk_salesPeriodGrp(1).Value = 0
    chk_sales_exportGVSOnly.Value = 0
    chk_sales_exportXLS.Value = 1
    
    cbo_DR_Year.SearchItem (Year(Now()))
    
    Set cbo_DR_Month.SelectedItem = cbo_DR_Month.ComboItems(Month(Now()) + 1)
    
    frm_sales_PDF.Visible = True
    Exit Sub
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".sales_pdf_print_Click")
End Sub

Private Sub Tab_replic_Click()
On Error GoTo ErrorHandler

    gr_replic.ClearGrid
    Select Case Tab_replic.SelectedItem.Index
    Case 1
        load_treeview_replic 1
    Case 2
        load_treeview_replic 2
    Case 3
        load_treeview_replic 3
        'load_gr_replic "cap_f_replic_log_month", 3
    End Select

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

Private Sub tbs_sales_Click()
On Error GoTo ErrorHandler
    btn_DiplayQuery.Visible = True
    btn_RefreshReport.Visible = False
    Fra_DisplayReport.Visible = False
    fr_Filter.Visible = True
    frm_sales.Visible = True
        
    fr_Budget.Visible = False
    tab_prd.Visible = False
    frm_salesOptions.Visible = True
    frm_sales2Options.Visible = False
    
    l1.Visible = False
    l2.Visible = False
    cal1.Visible = False
    cal2.Visible = False
    
    If cb_trw.SelectedItem Is Nothing Then Exit Sub
    
    Select Case tbs_sales.SelectedItem.Key
    Case "ALL"
        export_report.Visible = mb_sales_processed
        sales_pdf_print.Visible = mb_sales_processed And (Level_selected <> 3) And (cb_trw.SelectedItem.GetData(0) <> 2)
        If Not mb_sales_processed Then
            Call Process_Sales
        Else
            grd_Sales.Visible = True
            grd_sales_MSA.Visible = False
            frm_sales.Caption = tbs_sales.SelectedItem.ToolTipText
        End If
    Case "MSA"
        export_report.Visible = mb_sales_MSA_processed
        sales_pdf_print.Visible = mb_sales_MSA_processed And (Level_selected <> 3) And (cb_trw.SelectedItem.GetData(0) <> 2)
        If Not mb_sales_MSA_processed Then
            Call Process_Sales_MSA
        Else
            grd_Sales.Visible = False
            grd_sales_MSA.Visible = True
            frm_sales.Caption = tbs_sales.SelectedItem.ToolTipText
        End If
    End Select

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

Private Sub TabStrip1_Click()
On Error GoTo ErrorHandler
    
    mb_Initializing = True
    
    fr_report.Visible = False
    fr_Views.Visible = False
    Fr_replic.Visible = False
    fr_Query.Visible = False
    frm_visits.Visible = False
    frm_visits2.Visible = False
    frm_projects.Visible = False
    frm_top10projects.Visible = False
    frm_top10projectsE.Visible = False
    frm_sales.Visible = False
    frm_sales_rep.Visible = False
    frm_statusProjects.Visible = False
    frm_statusProjects2.Visible = False
    frm_statusProjects3.Visible = False


    Select Case TabStrip1.SelectedItem.Key
    Case "REPORT"
        btn_DiplayQuery.Visible = False
        export_report.Visible = mb_reportProcessed
        btn_RefreshReport.Visible = mb_reportProcessed
        Fra_DisplayReport.Visible = Not mb_reportProcessed
        fr_Filter.Visible = True
        fr_report.Visible = mb_reportProcessed
        
        fr_Budget.Visible = True
        tab_prd.Visible = True
        frm_salesOptions.Visible = False
        frm_sales2Options.Visible = False
        
        l1.Visible = True
        l2.Visible = True
        cal1.Visible = True
        cal2.Visible = True
        
    Case "VIEWS"
        btn_DiplayQuery.Visible = False
        Fra_DisplayReport.Visible = False
        fr_Filter.Visible = False
        fr_Views.Visible = True
        
        l1.Visible = True
        l2.Visible = True
        cal1.Visible = True
        cal2.Visible = True

    Case "REPLIC"
        btn_DiplayQuery.Visible = False
        Fra_DisplayReport.Visible = False
        fr_Filter.Visible = False
        Fr_replic.Visible = True
        
        l1.Visible = True
        l2.Visible = True
        cal1.Visible = True
        cal2.Visible = True

        DoEvents
        If tv_replic.Count = 0 Then
        load_treeview_replic 1
        End If
    Case "QUERY"
        btn_DiplayQuery.Visible = True
        export_report.Visible = False
        btn_RefreshReport.Visible = False
        Fra_DisplayReport.Visible = False
        
        l1.Visible = True
        l2.Visible = True
        cal1.Visible = True
        cal2.Visible = True
        
        fr_Filter.Visible = True
        fr_Query.Visible = True
            
        fr_Budget.Visible = False
        tab_prd.Visible = False
        frm_salesOptions.Visible = False
        frm_sales2Options.Visible = False
    Case "VISIT"
        btn_DiplayQuery.Visible = True
        export_report.Visible = False   ' grd_visitDetail(tbs_visitCTType.SelectedItem.Index - 1).Rows > 0
        btn_RefreshReport.Visible = False
        Fra_DisplayReport.Visible = False
        
        fr_Filter.Visible = True
        frm_visits.Visible = True
            
        fr_Budget.Visible = False
        tab_prd.Visible = False
        frm_salesOptions.Visible = False
        frm_sales2Options.Visible = False
        
        l1.Visible = tbs_visitCTType.SelectedItem.Tag = "NULL2"
        l2.Visible = True
        cal1.Visible = tbs_visitCTType.SelectedItem.Tag = "NULL2"
        cal2.Visible = True
        
        If (ml_visit_processed And Choose(tbs_visitCTType.SelectedItem.Index, 1, 2, 4)) = 0 Then Call Process_Visit
    Case "VISIT2"
        btn_DiplayQuery.Visible = True
        export_report.Visible = mb_visits2_processed

        btn_RefreshReport.Visible = False
        Fra_DisplayReport.Visible = False
        
        fr_Filter.Visible = True
        frm_visits2.Visible = True
            
        fr_Budget.Visible = False
        tab_prd.Visible = False
        frm_salesOptions.Visible = False
        frm_sales2Options.Visible = False
        
        l1.Visible = True
        l2.Visible = True
        cal1.Visible = True
        cal2.Visible = True
        
        If Not mb_visits2_processed Then
            If Level_selected = 1 Then
                grd_visits2.Visible = False
                frm_visits2_Grouping.Visible = True
                img_visits2Min.Visible = False
                img_visits2Max.Visible = False
                lbl_visits2Calculation.Visible = False
                frm_visits2.Caption = ""
            Else
                If Not frm_visits2_Grouping.Visible Then
                    If Level_selected = tv1.Levels - 1 Or Level_selected = 0 Then
                        chk_visits2_Grouping(0).Value = vbChecked
                        chk_visits2_Grouping(1).Value = vbUnchecked
                    ElseIf Level_selected = tv1.Levels - 2 Then
                        chk_visits2_Grouping(0).Value = vbChecked
                        chk_visits2_Grouping(1).Value = vbChecked
                    End If
                End If

                Call Process_Visit2
            End If
        End If
    Case "PROJ"
        btn_DiplayQuery.Visible = True
        export_report.Visible = (ml_project_processed And Pow(2, (tbs_ProjectType.SelectedItem.Index - 1) * 2 + tbs_project.SelectedItem.Index - 1) <> 0)

        btn_RefreshReport.Visible = False
        Fra_DisplayReport.Visible = False
        
        fr_Filter.Visible = True
        frm_projects.Visible = True
            
        fr_Budget.Visible = False
        tab_prd.Visible = False
        frm_salesOptions.Visible = False
        frm_sales2Options.Visible = False
        
        l1.Visible = False
        l2.Visible = False
        cal1.Visible = False
        cal2.Visible = False
        
        If (ml_project_processed And Pow(2, (tbs_ProjectType.SelectedItem.Index - 1) * 2 + tbs_project.SelectedItem.Index - 1)) = 0 Then
            Call Process_Project((tbs_ProjectType.SelectedItem.Index - 1) * 2 + tbs_project.SelectedItem.Index - 1)
        Else
            ' reset total counters
            If ml_projCounts <> 0 Then p_da.Close (ml_projCounts)
            ml_projCounts = 0
        End If
    Case "SALES"
        Call tbs_sales_Click
    Case "SALES_REP"
        btn_DiplayQuery.Visible = True
        export_report.Visible = mb_sales_rep_processed
        btn_RefreshReport.Visible = False
        Fra_DisplayReport.Visible = False
        fr_Filter.Visible = True
        frm_sales_rep.Visible = True
            
        fr_Budget.Visible = False
        tab_prd.Visible = False
        frm_salesOptions.Visible = False
        frm_sales2Options.Visible = True
        
        l1.Visible = False
        l2.Visible = False
        cal1.Visible = False
        cal2.Visible = False
        
        If cbo_salesCurrency.SelectedItem Is Nothing Then
            Call cbo_salesCurrency.Load
            Call cbo_salesCurrency.SearchItem("EUR")
        End If
        
        If cbo_salesDataView.SelectedItem Is Nothing Then
            Call cbo_salesDataView.Load
            Call cbo_salesDataView.SearchItem(2)                ' Standard view
        End If
        
        If Not mb_sales_rep_processed And Not cb_trw.SelectedItem Is Nothing Then
            Call reinit_sales_by_rep(cb_trw.SelectedItem.GetData(0), Level_selected, False)
        End If
    
    Case "TOP10PROJ"
        btn_DiplayQuery.Visible = True
        export_report.Visible = (ml_top10project_processed And 1) = 1

        btn_RefreshReport.Visible = False
        Fra_DisplayReport.Visible = False
        
        fr_Filter.Visible = True
        frm_top10projects.Visible = True
            
        fr_Budget.Visible = False
        tab_prd.Visible = False
        frm_salesOptions.Visible = False
        frm_sales2Options.Visible = False
        
        l1.Visible = True
        l2.Visible = True
        cal1.Visible = True
        cal2.Visible = True
        
        If (ml_top10project_processed And 1) = 0 Then
            Call Process_Top10Project
        End If
    Case "TOP10PROJE"
        btn_DiplayQuery.Visible = True
        export_report.Visible = (ml_top10projectE_processed And 1) = 1

        btn_RefreshReport.Visible = False
        Fra_DisplayReport.Visible = False
        
        fr_Filter.Visible = True
        frm_top10projectsE.Visible = True
            
        fr_Budget.Visible = False
        tab_prd.Visible = False
        frm_salesOptions.Visible = False
        frm_sales2Options.Visible = False
        
        l1.Visible = True
        l2.Visible = True
        cal1.Visible = True
        cal2.Visible = True
        
        If (ml_top10projectE_processed And 1) = 0 Then
            Call Process_Top10ProjectE
        End If
'    Case "STATUSPROJ"
'        btn_DiplayQuery.Visible = True
'        export_report.Visible = mb_statusProjects_processed

'        btn_RefreshReport.Visible = False
'        Fra_DisplayReport.Visible = False
        
'        fr_Filter.Visible = True
'        frm_statusProjects.Visible = True
            
'        fr_Budget.Visible = False
'        tab_prd.Visible = False
'        frm_salesOptions.Visible  = False
'        frm_sales2Options.Visible = False
        
'        l1.Visible = True
'        l2.Visible = True
'        cal1.Visible = True
'        cal2.Visible = True
        
'        If Not mb_statusProjects_processed Then Call Process_StatusProjects
    
    Case "STATUSPROJ2"
        btn_DiplayQuery.Visible = True
        export_report.Visible = mb_statusProjects2_processed

        btn_RefreshReport.Visible = False
        Fra_DisplayReport.Visible = False
        
        fr_Filter.Visible = True
        frm_statusProjects2.Visible = True
            
        fr_Budget.Visible = False
        tab_prd.Visible = False
        frm_salesOptions.Visible = False
        frm_sales2Options.Visible = False
        
        l1.Visible = True
        l2.Visible = True
        cal1.Visible = True
        cal2.Visible = True
        
        If Not mb_statusProjects2_processed Then
            If Level_selected = 1 Then
                grd_StatusProjects2.Visible = False
                frm_PS2_Grouping.Visible = True
                img_ps2Min.Visible = False
                img_ps2Max.Visible = False
                lbl_statusProj2Calculation.Visible = False
                frm_statusProjects2.Caption = ""
            Else
                If Not frm_PS2_Grouping.Visible Then
                    If Level_selected = tv1.Levels - 1 Or Level_selected = 0 Then
                        chk_PS2_Grouping(0).Value = vbChecked
                        chk_PS2_Grouping(1).Value = vbUnchecked
                    ElseIf Level_selected = tv1.Levels - 2 Then
                        chk_PS2_Grouping(0).Value = vbChecked
                        chk_PS2_Grouping(1).Value = vbChecked
                    End If
                End If

                Call Process_StatusProjects2
            End If
        End If

    Case "STATUSPROJ3"
        btn_DiplayQuery.Visible = True
        export_report.Visible = mb_statusProjects3_processed

        btn_RefreshReport.Visible = False
        Fra_DisplayReport.Visible = False
        
        fr_Filter.Visible = True
        frm_statusProjects3.Visible = True
            
        fr_Budget.Visible = False
        tab_prd.Visible = False
        frm_salesOptions.Visible = False
        frm_sales2Options.Visible = False
        
        l1.Visible = True
        l2.Visible = True
        cal1.Visible = True
        cal2.Visible = True
        
        If Not mb_statusProjects3_processed Then Call Process_StatusProjects3
        
    
    End Select
    mb_Initializing = False
    Exit Sub
    
ErrorHandler:
    mb_Initializing = False
    Call ErrorMessage(Extender.Name & ".TabStrip1_Click")
End Sub

Private Function SalesByRepSupportGrouping(ByVal al_trwCode As Long, ByVal al_Level As Long) As Boolean
On Error GoTo ErrorHandler
            Select Case al_trwCode
                Case 1, 3, 5  ' Market
                    SalesByRepSupportGrouping = al_Level < 2  ' for sales rep and country level we supress grouping / use only rep grouping
                Case 2, 4 ' Area
                    SalesByRepSupportGrouping = False
            End Select

    Exit Function
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".SalesByRepSupportGrouping")
End Function

Private Sub ShowFocusprodScreen()
On Error GoTo ErrorHandler

    If mFocusProd Is Nothing Then
      Set mFocusProd = UserControl.Controls.Add("Project1.FocusProducts", "FocusProd")
      mFocusProd.Visible = False
      Call mFocusProd.Move(120, 0, fr_Filter.Width + fr_report.Width + 100, fr_Filter.Height + fr_CMD.Height)
      
      Set mFocusProd.Db = p_da
      mFocusProd.Language_Code = ms_Language_Code
      mFocusProd.LoginName = gsuser
      
      If Not mFocusProd.Load_A_Com Then
          'debug.print "Unable to initialize Focus Products"
          End
      End If
    End If
    
    mFocusProd.Zorder
    mFocusProd.Visible = True
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".ShowFocusprodScreen")
End Sub


Private Sub tbs_project_Click()
On Error GoTo ErrorHandler
    Dim lo_Grid As MSFlexGrid
    For Each lo_Grid In grd_project
        lo_Grid.Visible = False
    Next
    
    Dim ll_i As Long
    ll_i = (tbs_ProjectType.SelectedItem.Index - 1) * 2 + tbs_project.SelectedItem.Index - 1

    grd_project(ll_i).Visible = True
    If (ml_project_processed And Pow(2, ll_i)) = 0 Then
        Call Process_Project(ll_i)
    End If
'    export_report.Visible = grd_project(ll_i).Rows > 0
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".tbs_project_Click")
End Sub

Private Sub tbs_ProjectType_Click()
    Call tbs_project_Click
End Sub

Private Sub tbs_Result_Click(Index As Integer)
On Error GoTo ErrorHandler
Dim lo_Tab As Object
Dim ll_GridIndex As Long

    For Each lo_Tab In tbs_Result(Index).Tabs
    
        ll_GridIndex = Mid(lo_Tab.Key, 2)
        grd_result(ll_GridIndex).Visible = False
    Next
  
  ll_GridIndex = Mid(tbs_Result(Index).SelectedItem.Key, 2)
    
'  If mia_WhichGridIsMax(0) <> -1 Then
'        L_focus.Visible = False
'        grd_Result(ll_GridIndex).top = 750
'        grd_Result(ll_GridIndex).left = 120
'        grd_Result(ll_GridIndex).Width = grd_Result(ll_GridIndex).Width + G_expand_factor_h
'        grd_Result(ll_GridIndex).Height = grd_Result(ll_GridIndex).Height + G_expand_factor_v
'        grd_Result(ll_GridIndex).Visible = True
'        grd_Result(ll_GridIndex).ZOrder 0
'
'        grd_Result(mia_WhichGridIsMax(0)).Visible = False
'        grd_Result(mia_WhichGridIsMax(0)).top = mia_WhichGridIsMax(1)
'        grd_Result(mia_WhichGridIsMax(0)).left = mia_WhichGridIsMax(2)
'        grd_Result(mia_WhichGridIsMax(0)).Height = grd_Result(mia_WhichGridIsMax(0)).Height - G_expand_factor_v
'        grd_Result(mia_WhichGridIsMax(0)).Width = grd_Result(mia_WhichGridIsMax(0)).Width - G_expand_factor_h
'
'
'        'grd_Result(mia_WhichGridIsMax(0)).Visible = True
'
'
'        mia_WhichGridIsMax(0) = ll_GridIndex
'
'
'  Else
    grd_result(ll_GridIndex).Visible = True
    grd_result(ll_GridIndex).Zorder 0
'  End If
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".tbs_Result_Click")
End Sub


Private Sub tbs_visitCTType_Click()
On Error GoTo ErrorHandler
    l1.Visible = tbs_visitCTType.SelectedItem.Tag = "NULL2"
    cal1.Visible = tbs_visitCTType.SelectedItem.Tag = "NULL2"
    
    Dim lo_Grid As ArmGrid
    For Each lo_Grid In grd_visitCounts
        lo_Grid.Visible = False
    Next
    For Each lo_Grid In grd_visitDetail
        lo_Grid.Visible = False
    Next

    If (ml_visit_processed And Choose(tbs_visitCTType.SelectedItem.Index, 1, 2, 4)) = 0 Then
        Call Process_Visit
    Else
        grd_visitCounts(tbs_visitCTType.SelectedItem.Index - 1).Visible = True
        grd_visitDetail(tbs_visitCTType.SelectedItem.Index - 1).Visible = True
    End If
'    export_report.Visible = grd_visitDetail(tbs_visitCTType.SelectedItem.Index - 1).Rows > 0
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".tbs_visitCTType_Click")
End Sub

Private Sub tv_replic_Click()
On Error GoTo ErrorHandler
Dim ls_req As String
Dim ll_cursor As Long
Dim lb_IsAutho As Boolean

    lb_IsAutho = False
    
    If tv_replic.SelectedItem Is Nothing Then
        gr_replic.ClearGrid
    Else
        If tv_replic.SelectedItem.children = 0 Then
            ls_req = "SELECT 1 FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Markets' AND Autho_Values IS NULL"
            ll_cursor = OpenSQLSafe(p_da, ls_req)
            If p_da.RowCount(ll_cursor) > 0 Then
                lb_IsAutho = True
            End If
            Call p_da.Close(ll_cursor)
            ll_cursor = 0
            
            ls_req = "SELECT Autho_Values FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "' AND Autho_Level = 'Markets'"
            ll_cursor = OpenSQLSafe(p_da, ls_req)
            If p_da.RowCount(ll_cursor) > 0 Then
                If p_da.GetFields(ll_cursor, 0) = "" Then
                    lb_IsAutho = True
                End If
                If Tab_replic.SelectedItem.Index = 3 Then
                    If InStr(1, p_da.GetFields(ll_cursor, 0), tv_replic.NodeInfo(tv_replic.SelectedItem.Parent).GetData(0)) > 0 Then
                        lb_IsAutho = True
                    End If
                Else
                    If InStr(1, p_da.GetFields(ll_cursor, 0), tv_replic.NodeInfo(tv_replic.SelectedItem.Parent.Parent).GetData(0)) > 0 Then
                        lb_IsAutho = True
                    End If
                End If
            End If
            Call p_da.Close(ll_cursor)
            ll_cursor = 0
        
            If lb_IsAutho Then
                Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
                Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
                
                Select Case Tab_replic.SelectedItem.Index
                Case 2
                    load_gr_replic "cap_replic_log_month '" & tv_replic.NodeInfo(tv_replic.SelectedItem.Parent).GetData(1) & "','" & tv_replic.NodeInfo(tv_replic.SelectedItem).GetData(0) & "','" & tv_replic.NodeInfo(tv_replic.SelectedItem.Parent.Parent).GetData(0) & "'", 2
                Case 1
                    load_gr_replic "cap_replic_log_week '" & tv_replic.NodeInfo(tv_replic.SelectedItem.Parent).GetData(1) & "','" & tv_replic.NodeInfo(tv_replic.SelectedItem).GetData(0) & "','" & tv_replic.NodeInfo(tv_replic.SelectedItem.Parent.Parent).GetData(0) & "'", 2
                Case 3
                    load_gr_replic "cap_replic_log_user '" & tv_replic.NodeInfo(tv_replic.SelectedItem).GetData(0) & "'", 3
                End Select
            Else
                MsgBox "Access Denied"
            End If
        Else
            gr_replic.ClearGrid
        End If
    End If
    Exit Sub
    
ErrorHandler:
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If
    Call ErrorMessage(Extender.Name & ".tv_replic_Click")
End Sub

Private Function LevelFromPath(ByVal al_trwCode As Long, ByVal as_nodePath As String) As Long
    
    Dim al_retVal As Long
    
    Select Case al_trwCode
        Case 1:
            Select Case CountStrings(as_nodePath, "\")
                Case 0: al_retVal = 0
                Case 1: al_retVal = 1
                Case 2: al_retVal = 2
                Case 3: al_retVal = 3
            End Select
        
        Case 2:
            Select Case CountStrings(as_nodePath, "\")
                Case 0: al_retVal = 1
                Case 1: al_retVal = 3
            End Select
        Case 3:
            Select Case CountStrings(as_nodePath, "\")
                Case 0: al_retVal = 0
                Case 1: al_retVal = 1
                Case 2: al_retVal = 3
            End Select
        Case 4:
            Select Case CountStrings(as_nodePath, "\")
                Case 0: al_retVal = 0
                Case 1: al_retVal = 1
                Case 2: al_retVal = 2
                Case 3: al_retVal = 3
            End Select
        Case 5:
            Select Case CountStrings(as_nodePath, "\")
                Case 0: al_retVal = 0
                Case 1: al_retVal = 1
                Case 2: al_retVal = 2
                Case 3: al_retVal = 3
                Case 4: al_retVal = 4
            End Select
    End Select
    LevelFromPath = al_retVal
    Exit Function
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".LevelFromPath")
End Function


Private Sub tv1_Click()
On Error GoTo ErrorHandler
    If cb_trw.SelectedItem Is Nothing Then Exit Sub
    If tv1.Count = 0 Then Exit Sub
    
    Level_selected = LevelFromPath(cb_trw.SelectedItem.GetData(0), tv1.SelectedItem.FullPath)
    
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".tv1_Click")
End Sub

Private Function GetLabel(ByVal as_Tag As String, ByVal as_DefaultValue As String, Optional ByVal aInfo As Variant) As String
    
    If p_da.Find(mc_ScreenLabels, "FIELD_NAME", as_Tag, , 1) >= 0 Then
        as_DefaultValue = p_da.GetFields(mc_ScreenLabels, "LOCAL_TEXT")
    End If
    
    Dim li_idx As Integer
    If Not IsMissing(aInfo) Then
        For li_idx = 0 To UBound(aInfo)
            as_DefaultValue = Replace(as_DefaultValue, aInfo(li_idx, 0), aInfo(li_idx, 1), , , vbTextCompare)
        Next li_idx
    End If
    
    
    GetLabel = as_DefaultValue

End Function

Private Sub tv1_NodeClick(ByVal Node As MSComctlLib.Node)
On Error GoTo ErrorHandler
    If Node Is Nothing Then Exit Sub
    
    If Node.FullPath <> current_displayed_node Then
        reinit_display
    End If
    
    ' define labels and grids available for each treeview

    mb_DisplayVisits = True
    mb_DisplayMSC = True
    mb_DisplayFilterByUser = False
    
    lbl_Title(6).Caption = GetLabel(lbl_Title(6).Tag, "#Visit Analysis")
    chk_GridToRun(6).Enabled = True
    chk_GridToRun(7).Enabled = True
    chk_GridToRun(6).Caption = lbl_Title(6).Caption

    
    'tbs_Result(0).Visible = False
    ' this will remember state of tabstrip in case we want play with query checkboxes
    'tbs_Result(0).Enabled = False
    Select Case cb_trw.SelectedItem.GetData(0)
        Case ECapReportingTreeview.creMarket
            Select Case tv1.SelectedItem.Tag.ml_Level
                Case 0
                    lbl_Title(0).Caption = GetLabel(lbl_Title(0).Tag, "#Specification By Market")
                    chk_GridToRun(0).Caption = lbl_Title(0).Caption
                Case 1
                    lbl_Title(0).Caption = GetLabel("lbl_specByCountry", "#Specification By Country")
                    chk_GridToRun(0).Caption = lbl_Title(0).Caption
                Case 2
                    lbl_Title(0).Caption = GetLabel("tb_specByUser", "#Specification By User")
                    chk_GridToRun(0).Caption = lbl_Title(0).Caption
                    'tbs_Result(0).Visible = True
                    'tbs_Result(0).Enabled = True
                    mb_DisplayFilterByUser = True

                Case 3
                    lbl_Title(0).Caption = GetLabel("tb_specByUser", "#Specification By User")
                    chk_GridToRun(0).Caption = lbl_Title(0).Caption
                    'tbs_Result(0).Visible = True
                    'tbs_Result(0).Enabled = True
                    mb_DisplayFilterByUser = True
                    
                    ' Don't understand ??
                    Select Case Left(tv1.NodeInfo(tv1.SelectedItem).GetData(0), 4)
                        Case "    " ' Seems to be rep
                            mb_DisplayVisits = True
                            mb_DisplayMSC = False
                            chk_GridToRun(7).Enabled = False

                        Case Else ' and here MSC
                            lbl_Title(6).Enabled = False
                            mb_DisplayVisits = False
                            mb_DisplayMSC = True
                            chk_GridToRun(6).Enabled = False
                    End Select
            End Select
        
        Case ECapReportingTreeview.creArea

            Select Case tv1.SelectedItem.Tag.ml_Level
                Case 0
                    lbl_Title(0).Caption = GetLabel("lbl_specByGroup", "#Specification By Groups")
                    chk_GridToRun(0).Caption = lbl_Title(0).Caption
                    mb_DisplayFilterByUser = True
                Case 1
                    lbl_Title(0).Caption = GetLabel("lbl_specByPerName", "#Specification By Person Name ")
                    chk_GridToRun(0).Caption = lbl_Title(0).Caption
                    mb_DisplayFilterByUser = True
                    'tbs_Result(0).Visible = True
                    'tbs_Result(0).Enabled = True
            End Select

            mb_DisplayVisits = True
            chk_GridToRun(6).Enabled = True
            Select Case Left(tv1.NodeInfo(tv1.SelectedItem).GetData(0), 4)
                Case "    "
                    mb_DisplayMSC = False
                    chk_GridToRun(7).Enabled = False
                Case Else
                    mb_DisplayMSC = True
                    chk_GridToRun(7).Enabled = True
            End Select
            
        Case ECapReportingTreeview.creMarketRep
            Select Case tv1.SelectedItem.Tag.ml_Level
                Case 0
                    lbl_Title(0).Caption = GetLabel("lbl_specByMarket", "#Specification By Market")
                    chk_GridToRun(0).Caption = lbl_Title(0).Caption
                Case 1
                    lbl_Title(0).Caption = GetLabel("tb_specByUser", "#Specification By User")
                    chk_GridToRun(0).Caption = lbl_Title(0).Caption
                    mb_DisplayFilterByUser = True
                    'tbs_Result(0).Visible = True
                    'tbs_Result(0).Enabled = True
                Case 2
                    lbl_Title(0).Caption = GetLabel("tb_specByUser", "#Specification By User")
                    chk_GridToRun(0).Caption = lbl_Title(0).Caption
                    mb_DisplayFilterByUser = True
                    'tbs_Result(0).Visible = True
                    'tbs_Result(0).Enabled = True
                    ' Don't understand ??
                    Select Case Left(tv1.NodeInfo(tv1.SelectedItem).GetData(0), 4)
                        Case "    " ' Seems to be rep
                            mb_DisplayVisits = True
                            mb_DisplayMSC = False
                            chk_GridToRun(7).Enabled = False
                        Case Else ' and here MSC
                            mb_DisplayVisits = False
                            mb_DisplayMSC = True
                            chk_GridToRun(6).Enabled = False
                    End Select
            End Select
            
    End Select

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

Private Sub reinit_display()
On Error GoTo ErrorHandler
    Select Case TabStrip1.SelectedItem.Key
    Case "REPORT"
            fr_report.Visible = False
'            export_report.Visible = False
'            btn_RefreshReport.Visible = False
            Fra_DisplayReport.Visible = True
    Case "QUERY"
        grd_Query.ClearGrid
    Case "VISIT"
        Dim lo_grd As ArmGrid
        For Each lo_grd In grd_visitCounts
            Call lo_grd.ClearGrid
        Next
        For Each lo_grd In grd_visitDetail
            Call lo_grd.ClearGrid
        Next
        frm_visits.Visible = False
    Case "VISIT2"
        
        If Not tv1.SelectedItem Is Nothing Then
            If tv1.SelectedItem.Tag.ml_Level = 1 Then
        
                grd_visits2.Visible = False
                frm_visits2_Grouping.Visible = True
                img_visits2Min.Visible = False
                img_visits2Max.Visible = False
                lbl_visits2Calculation.Visible = False
                frm_visits2.Caption = ""
                frm_visits2.Visible = True
            Else
                frm_visits2.Visible = False
            End If
        Else
            frm_visits2.Visible = False
        End If
        
    Case "PROJ"
        grd_project((tbs_ProjectType.SelectedItem.Index - 1) * 2 + tbs_project.SelectedItem.Index - 1).Rows = 1
        frm_projects.Visible = False
    Case "SALES"
'        Call Process_Sales
        frm_sales.Visible = False
    Case "SALES_REP"
        ' we cannot use Level_selected as this value is not set yet
        Dim ll_Level As Long
        
        If Not tv1.SelectedItem Is Nothing Then
            ll_Level = LevelFromPath(cb_trw.SelectedItem.GetData(0), tv1.SelectedItem.FullPath)
        Else
            ll_Level = Level_selected
        End If

        If Not SalesByRepSupportGrouping(cb_trw.SelectedItem.GetData(0), ll_Level) Then
            frm_sales_rep.Visible = False
        Else
            frm_sales_rep.Visible = True
            grd_sales_rep.Visible = False
            frm_sales_by_rep_grouping.Visible = True
            lbl_salesRepCalculation.Visible = False
            chk_sales_by_rep_grp(0).Visible = (ll_Level = 0)
            chk_sales_by_rep_grp(1).Visible = (ll_Level <= 1)
        End If
    Case "TOP10PROJ"
        grd_top10Projects.Rows = 1
        frm_top10projects.Visible = False
    Case "TOP10PROJE"
        grd_top10ProjectsE.Rows = 1
        frm_top10projectsE.Visible = False
'    Case "STATUSPROJ"
'        frm_statusProjects.Visible = False
    Case "STATUSPROJ2"
        
        If Not tv1.SelectedItem Is Nothing Then
            If tv1.SelectedItem.Tag.ml_Level = 1 Then
        
                grd_StatusProjects2.Visible = False
                frm_PS2_Grouping.Visible = True
                img_ps2Min.Visible = False
                img_ps2Max.Visible = False
                lbl_statusProj2Calculation.Visible = False
                frm_statusProjects2.Caption = ""
                frm_statusProjects2.Visible = True
            Else
                frm_statusProjects2.Visible = False
            End If
        Else
            frm_statusProjects2.Visible = False
        End If
        
        
    Case "STATUSPROJ3"
        frm_statusProjects3.Visible = False
    End Select
    ml_project_processed = 0
    mb_reportProcessed = False
    ml_visit_processed = 0
    mb_visits2_processed = False
    mb_sales_processed = False
    mb_sales_rep_processed = False
    mb_sales_MSA_processed = False
    mb_statusProjects_processed = False
    mb_statusProjects2_processed = False
    mb_statusProjects3_processed = False
    
    
    fr_CMD.Visible = True
    export_report.Visible = False
    sales_pdf_print.Visible = False
    btn_RefreshReport.Visible = False
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".reinit_display")
End Sub

Private Sub reinit_sales_by_rep(ByVal al_trwCode As Long, ByVal al_Level As Long, ByVal ab_process As Boolean)
On Error GoTo ErrorHandler
    If Not SalesByRepSupportGrouping(al_trwCode, al_Level) Then
        frm_sales_by_rep_grouping.Visible = False
        Call Process_Sales_Rep
    Else
        If ab_process And Not mb_sales_rep_processed Then
            Call Process_Sales_Rep
        Else
            mb_sales_rep_processed = False
            grd_sales_rep.Visible = False
            frm_sales_by_rep_grouping.Visible = True
            lbl_salesRepCalculation.Visible = False
            chk_sales_by_rep_grp(0).Visible = (al_Level = 0)
            chk_sales_by_rep_grp(1).Visible = (al_Level <= 1)
        End If
    End If

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

Private Sub init_grid(ByRef g As MSFlexGrid, ByVal nb_cols As Byte)
On Error GoTo ErrorHandler

Dim i As Integer

    With g
        .Clear
        .Rows = 2
        .FixedRows = 1
        .AllowUserResizing = flexResizeColumns
        .Row = 0
        .Cols = nb_cols
        .ColWidth(0) = 0
        For i = 1 To g.Cols - 1
            .ColAlignment(i) = flexAlignRightCenter
        Next i
        
        Select Case nb_cols
        Case 2
            .ColWidth(0) = 2950
            .ColWidth(1) = 1200
            .TextMatrix(0, 1) = GetLabel("g_nbOfContacts", "   #nb of contacts")
            
        Case 3
            .ColWidth(0) = 2950
            .ColWidth(1) = 950
            .ColWidth(2) = 750
            .ColAlignment(2) = flexAlignRightCenter
            .TextMatrix(0, 1) = GetLabel("g_actual", "   #Actual")
            .TextMatrix(0, 2) = "    %"
        Case 4
            If .Index = 0 Or .Index = 8 Then
                .ColWidth(0) = 1900
                .ColWidth(1) = 950
                .ColWidth(2) = 1000
                .ColWidth(3) = 750
                .ColAlignment(3) = flexAlignRightCenter
                .TextMatrix(0, 1) = GetLabel("g_actual", "   #Actual")
                .TextMatrix(0, 2) = GetLabel("g_exlBasic", "#Exclud Basic")
                .TextMatrix(0, 3) = "    %"
            Else
                .ColWidth(0) = 2000
                .ColWidth(1) = 950
                .ColWidth(2) = 950
                .ColWidth(3) = 750
                .ColAlignment(3) = flexAlignRightCenter
                .TextMatrix(0, 1) = GetLabel("g_actual", "   #Actual")
                .TextMatrix(0, 2) = GetLabel("g_budget", "   #Budget")
                .TextMatrix(0, 3) = "    %"
            End If
        
        Case 5
            .ColWidth(0) = 1900
            .ColWidth(1) = 950
            .ColWidth(2) = 1000
            .ColWidth(3) = 950
            .ColWidth(4) = 750
            .ColAlignment(3) = flexAlignRightCenter
            .TextMatrix(0, 1) = GetLabel("g_actual", "   #Actual")
            .TextMatrix(0, 2) = GetLabel("g_exlBasic", "#Exclud Basic")
            .TextMatrix(0, 3) = GetLabel("g_budget", "   #Budget")
            .TextMatrix(0, 4) = "    %"
        Case 6
            .ColWidth(0) = 2200
            .ColWidth(1) = 1500
            .ColWidth(2) = 1500
            .ColWidth(3) = 1500
            .ColWidth(4) = 1500
            .ColWidth(5) = 1500
            .TextMatrix(0, 1) = GetLabel("g_allVisits", "#All Visits")
            .TextMatrix(0, 2) = GetLabel("g_toSpec", "#To specs")
            .TextMatrix(0, 3) = GetLabel("g_toClgContractor", "#To clg Contractors")
            .TextMatrix(0, 4) = GetLabel("g_toDistrib", "#To distributors")
            .TextMatrix(0, 5) = "80/20%"
        
        Case 7
            .ColWidth(0) = 2200
            .ColWidth(1) = 1500
            .ColWidth(2) = 1500
            .ColWidth(3) = 1500
            .ColWidth(4) = 1500
            .ColWidth(5) = 1500
            .ColWidth(6) = 1500
            .TextMatrix(0, 1) = GetLabel("g_nbContact", "#N° of Contacts")
            .TextMatrix(0, 2) = GetLabel("g_know", "#Know")
            .TextMatrix(0, 3) = GetLabel("g_specs", "#Specs")
' IMPLEMENT PROCESS T298.9.PR_001
            .TextMatrix(0, 4) = GetLabel("g_clgContractor", "#Clg Contractors")
' END PROCESS T298.9.PR_001
            .TextMatrix(0, 5) = GetLabel("g_distrib", "#Distributors")
            .TextMatrix(0, 6) = "80/20%"
        
        Case 10
            .ColWidth(0) = 2200
            .ColWidth(1) = 1500
            .ColWidth(2) = 1500
            .ColWidth(3) = 1500
            .ColWidth(4) = 1500
            .ColWidth(5) = 1500
            .ColWidth(6) = 1500
            .ColWidth(7) = 1500
            .ColWidth(8) = 1500
            .ColWidth(9) = 1500
            .TextMatrix(0, 1) = GetLabel("g_totalNbAct", "#Total nb of actions")
            .TextMatrix(0, 2) = GetLabel("g_toSpec", "#To specs")
' IMPLEMENT PROCESS T298.9.PR_001
            .TextMatrix(0, 3) = GetLabel("g_toClgContractor", "#To clg Contractors")
' END PROCESS T298.9.PR_001
            .TextMatrix(0, 4) = GetLabel("g_toDistrib", "#To distributors")
            .TextMatrix(0, 5) = "80/20%"
            .TextMatrix(0, 6) = GetLabel("g_appoint", "#Appointments")
            .TextMatrix(0, 7) = GetLabel("g_followUp", "#Follow up")
            .TextMatrix(0, 8) = GetLabel("g_m2Discussed", "#M2 discussed")
            .TextMatrix(0, 9) = GetLabel("g_m2Specified", "#M2 specified")
        Case Else
            .ColWidth(0) = 2200
            .ColWidth(1) = 1200
            .ColWidth(2) = 1200
            .TextMatrix(0, 1) = GetLabel("g_actual", "   #Actual")
        End Select
        .Highlight = flexHighlightNever
    End With

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

Private Sub Exec_Report(ByVal aUseBudget As Boolean)

On Error GoTo ErrorHandler

    Dim lReqL1Lst As String, lReqL1Value As String, lReqL1ValueBasic As String, lReqL1Budget As String
    Dim lReqL2Lst As String, lReqL2Value As Variant, lReqL2Buffer As String
    Dim lReqR2Lst As String, lReqR2Value As Variant, lReqR2Buffer As String
    Dim lReqR4Lst As String, lReqR4Value As Variant, lReqR4Buffer As String
    
    
    ReDim lReqL2Value(4)
    ReDim lReqR2Value(8)
    ReDim lReqR4Value(5)
    
    Dim ls_C_REQ As Variant
    ls_C_REQ = Split(ms_TheGridRequestsByLevel(tv1.SelectedItem.Tag.ml_Level), SEP)
        
    If LCase(ls_C_REQ(0)) Like "*_users_*" Then
        lReqL1Lst = Replace(ls_C_REQ(0), "$filters$", "0", , , vbTextCompare)
        lReqL2Lst = Replace(ls_C_REQ(0), "$filters$", "1", , , vbTextCompare)
        lReqR4Lst = Replace(ls_C_REQ(0), "$filters$", "0", , , vbTextCompare)
        lReqR2Lst = Replace(ls_C_REQ(0), "$filters$", "2", , , vbTextCompare)
    Else
        lReqL1Lst = ls_C_REQ(0)
        lReqL2Lst = ls_C_REQ(0)
        lReqR4Lst = ls_C_REQ(0)
        lReqR2Lst = ls_C_REQ(4)
    End If
    lReqL1Value = ls_C_REQ(1)
    
    '-----------------
    lReqL1ValueBasic = ls_C_REQ(22)
    '-----------------
    
    
    lReqL1Budget = ls_C_REQ(2)

    lReqL2Buffer = ls_C_REQ(3)

    lReqR4Value(0) = ls_C_REQ(8)
    lReqR4Buffer = ls_C_REQ(9)

    lReqR2Buffer = ls_C_REQ(7)
    lReqR2Value(7) = ls_C_REQ(5)
    lReqR2Value(8) = ls_C_REQ(6)
    
    
    Dim lIdx As Long, lCount As Long
    lCount = UBound(lReqL2Value)
    For lIdx = 0 To lCount
        lReqL2Value(lIdx) = Replace(lReqL2Buffer, "$ccfilter$", lIdx, , , vbTextCompare)
    Next
    
    For lIdx = 0 To 6
        lReqR2Value(lIdx) = Replace(lReqR2Buffer, "$filter$", lIdx, , , vbTextCompare)
    Next
    lReqR2Value(4) = "" ' Reserved for specific calcul
    
    lCount = UBound(lReqR4Value) - 1
    For lIdx = 1 To lCount
        lReqR4Value(lIdx) = Replace(lReqR4Buffer, "$ccfilter$", lIdx - 1, , , vbTextCompare)
    Next
    
    Dim C_REQ_SG_LIST As String, C_REQ_SG_VALUE As String, C_REQ_SG_BUDGET As String
    Dim C_REQ_MT_LIST As String, C_REQ_MT_VALUE As String, C_REQ_MT_BUDGET As String
    Dim C_REQ_PR_LIST As String, C_REQ_PR_VALUE As String, C_REQ_PR_BUDGET As String
    Dim C_REQ_FP_LIST As String, C_REQ_FP_VALUE As String, C_REQ_FP_BUDGET As String
    Dim C_REQ_FP_USER_VALUE As String, C_REQ_FP_USER_BUDGET As String
    
    C_REQ_SG_LIST = ls_C_REQ(10)
    C_REQ_SG_VALUE = ls_C_REQ(11)
    C_REQ_SG_BUDGET = ls_C_REQ(12)
    
    C_REQ_MT_LIST = ls_C_REQ(13)
    C_REQ_MT_VALUE = ls_C_REQ(14)
    C_REQ_MT_BUDGET = ls_C_REQ(15)
    
    C_REQ_PR_LIST = ls_C_REQ(16)
    C_REQ_PR_VALUE = ls_C_REQ(17)
    C_REQ_PR_BUDGET = ls_C_REQ(18)
    
    C_REQ_FP_LIST = ls_C_REQ(19)
    C_REQ_FP_VALUE = ls_C_REQ(20)
    C_REQ_FP_BUDGET = ls_C_REQ(21)
    
    
    
    Dim lc_LeavedPersons As Long
    Dim ls_req As String
    ls_req = "GetCapRptExcludeUsers"
        
    ls_req = ReplaceHolders(ls_req)
    lc_LeavedPersons = OpenSQLSafe(p_da, ls_req)

    Dim li_i As Integer
    For li_i = 1 To lvw_Task.ListItems.Count
        lvw_Task.ListItems(li_i).SmallIcon = 2
        Select Case lvw_Task.ListItems(li_i).Tag
            Case 0
                Call FillGrid(grd_result(0), lReqL1Lst, Array(lReqL1Value, lReqL1ValueBasic), lReqL1Budget, aUseBudget, True, grd_result(8), lc_LeavedPersons)
            Case 1
                Call FillGrid(grd_result(1), C_REQ_SG_LIST, C_REQ_SG_VALUE, C_REQ_SG_BUDGET, aUseBudget, True)
            Case 2
                Call FillGrid(grd_result(2), C_REQ_MT_LIST, C_REQ_MT_VALUE, C_REQ_MT_BUDGET, aUseBudget, True)
            Case 3
                Call FillGrid(grd_result(3), C_REQ_PR_LIST, C_REQ_PR_VALUE, C_REQ_PR_BUDGET, aUseBudget, True)
            Case 4
                Call FillGrid(grd_result(4), C_REQ_FP_LIST, C_REQ_FP_VALUE, C_REQ_FP_BUDGET, aUseBudget, True)
                If (Not mFPIndBdg) And aUseBudget Then
                    If mb_Cancel Then Exit For
                    Call GridBdgReset(grd_result(4), True)
                End If
                
                C_REQ_FP_USER_VALUE = ls_C_REQ(23)
                C_REQ_FP_USER_BUDGET = ls_C_REQ(24)
                If C_REQ_FP_USER_VALUE <> "" And C_REQ_FP_USER_BUDGET <> "" Then
                    Call FillGrid(grd_result(9), lReqL1Lst, C_REQ_FP_USER_VALUE, C_REQ_FP_USER_BUDGET, aUseBudget, True, grd_result(10), lc_LeavedPersons)
                End If
                
            Case 5
                Call FillGrid(grd_result(5), lReqR4Lst, lReqR4Value, "", False, False, grd_result(11), lc_LeavedPersons)
                If mb_Cancel Then Exit For
                Call Calcul_Special1(grd_result(5), 2, 3, 4, 6)
                Call Calcul_Special1(grd_result(11), 2, 3, 4, 6)
            Case 6
                If mb_DisplayVisits Then
                    Call FillGrid(grd_result(6), lReqL2Lst, lReqL2Value, "", False, False, grd_result(12), lc_LeavedPersons)
                    If mb_Cancel Then Exit For
                    Call Calcul_Special1(grd_result(6), 1, 2, 3, 5)
                    Call Calcul_Special1(grd_result(12), 1, 2, 3, 5)
                End If
            Case 7
                If mb_DisplayMSC Then
                    Call FillGrid(grd_result(7), lReqR2Lst, lReqR2Value, "", False, False, grd_result(13), lc_LeavedPersons)
                    If mb_Cancel Then Exit For
                    Call Calcul_Special1(grd_result(7), 1, 2, 3, 5)
                    Call Calcul_Special1(grd_result(13), 1, 2, 3, 5)
                End If
        End Select
        If mb_Cancel Then Exit For
        lvw_Task.ListItems(li_i).SmallIcon = 1
    Next li_i
    
    Call p_da.Close(lc_LeavedPersons)
    Exit Sub
    
ErrorHandler:
    If lc_LeavedPersons > 0 Then
        Call p_da.Close(lc_LeavedPersons)
        lc_LeavedPersons = 0
    End If
    Call ErrorHandler(Extender.Name & ".Exec_Report")
End Sub



Private Sub GridBdgReset(ByRef aGrid As MSFlexGrid, ByVal aPercent As Boolean)
On Error GoTo ErrorHandler

    Dim lRowIdx As Long, lRowCount As Long, lColIdx As Long
    lColIdx = aGrid.Cols - 1
    If aPercent Then lColIdx = lColIdx - 1
    
    lRowCount = aGrid.Rows - 2 ' Title and total
    For lRowIdx = 1 To lRowCount ' don't touch the title, start from 1
        aGrid.TextMatrix(lRowIdx, lColIdx) = "0"
        If aPercent Then
            aGrid.TextMatrix(lRowIdx, lColIdx + 1) = "0.00%"
        End If
    Next

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


Private Sub Calcul_Special1(ByRef aGrid As MSFlexGrid, ByVal aColAll As Byte, ByVal aColSpec As Byte, ByVal aColPartSpec As Byte, ByVal aColDest As Byte)
On Error GoTo ErrorHandler

    Dim lIdx As Long, lCount As Long, lBuffer As String, lResult As Single, lAll As Single
    lCount = aGrid.Rows - 1
    
    For lIdx = 1 To lCount  ' Don't process the title !
        lBuffer = aGrid.TextMatrix(lIdx, aColAll)
        lAll = Val(lBuffer)
        
        If lAll = 0 Then
            lResult = 0
        Else
            lBuffer = aGrid.TextMatrix(lIdx, aColPartSpec)
            lResult = IIf(lBuffer = "", 0, Val(lBuffer))
            lBuffer = aGrid.TextMatrix(lIdx, aColSpec)
            lResult = (lResult + IIf(lBuffer = "", 0, Val(lBuffer))) / lAll
        End If
        
        aGrid.TextMatrix(lIdx, aColDest) = Format(lResult, "#0.00%")
    Next

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



Private Sub export_to_excel()
On Error GoTo ErrorHandler

Dim p As String
Dim break1 As Integer
Dim break2 As Integer
Dim break3 As Integer
Dim break4 As Integer
Dim lv_Tot As Variant

    Screen.MousePointer = 11
    
    Set a_ExcelApp = GetObject(, "Excel.Application")
    Set a_ExcelWorkBook = a_ExcelApp.Workbooks.Add
    Set a_ExcelSheet1 = a_ExcelWorkBook.Sheets.Add

    a_ExcelWorkBook.Activate
    a_ExcelSheet1.Activate
    
    a_ExcelSheet1.PageSetup.Orientation = 1

    If grd_result(0).Rows >= grd_result(1).Rows Then
        break1 = nb_row_header + grd_result(0).Rows + nb_row_intermediate
    Else
        break1 = nb_row_header + grd_result(1).Rows + nb_row_intermediate
    End If
    
    
    If grd_result(2).Rows >= grd_result(3).Rows Then
        break2 = nb_row_intermediate + break1 + grd_result(2).Rows
    Else
        break2 = nb_row_intermediate + break1 + grd_result(3).Rows
    End If
    break3 = nb_row_intermediate + break2 + IIf(grd_result(4).Rows > grd_result(5).Rows, grd_result(4).Rows, grd_result(5).Rows)
    
    If lbl_Title(6).Enabled Then
        break4 = nb_row_intermediate + break3 + grd_result(6).Rows + 3
    Else
        break4 = break3
    End If
    
    a_ExcelApp.ActiveSheet.PageSetup.Zoom = 70

    a_ExcelApp.Application.Visible = -1
    a_ExcelSheet1.Application.Visible = -1
    
    With a_ExcelSheet1.cells.Interior
        .ColorIndex = 2
        .Pattern = 1
        .PatternColorIndex = -4105
    End With
    
    With a_ExcelSheet1
        .Columns("A").columnWidth = 30
        .Columns("B").columnWidth = 23
        .Columns("B:B").HorizontalAlignment = xlright
        .Columns("C").columnWidth = 15
        .Columns("C:C").HorizontalAlignment = xlright
        .Columns("D").columnWidth = 15
        .Columns("D:D").HorizontalAlignment = xlright

        .Columns("E").columnWidth = 13

        .Columns("F").columnWidth = 13
        .Columns("G").columnWidth = 35
        .Columns("H").columnWidth = 13
        .Columns("H:H").HorizontalAlignment = xlright
        .Columns("I").columnWidth = 14
        .Columns("I:I").HorizontalAlignment = xlright
        .Columns("J").columnWidth = 14
        .Columns("J:J").HorizontalAlignment = xlright
        
        .cells(2, 3).Value = GetLabel("ex_report", "#CAPTURE REPORT")
        .cells(2, 3).Font.Bold = True
        .cells(4, 1).Value = fr_report.Caption
        .cells(4, 1).Font.Bold = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$NOW$"
        ms_MsgInfo(0, 1) = Format(Now, "dd/mm/yy hh:mm:ss")
        .cells(2, 9).Value = GetLabel("ex_created", "#Created $NOW$", ms_MsgInfo)
        .cells(2, 9).Font.Italic = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$CB_TRW$"
        ms_MsgInfo(0, 1) = cb_trw.Text
        .cells(3, 9) = GetLabel("ex_trw", "#Treeview Info: $CB_TRW$", ms_MsgInfo)
        .cells(3, 9).Font.Italic = True
        .cells(3, 9).Font.Size = 8

        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$TRW_PATH$"
        ms_MsgInfo(0, 1) = TreeviewPath
        .cells(4, 9) = GetLabel("ex_trw_path", "#Treeview Path: $TRW_PATH$", ms_MsgInfo)
        .cells(4, 9).Font.Italic = True
        .cells(4, 9).Font.Size = 8
    End With
    
    If grd_result(0).Visible Then
        Call Export_Grid(1, nb_row_header, grd_result(0), IIf(mb_DisplayFilterByUser, tbs_Result(0).SelectedItem.Caption, lbl_Title(0).Caption), 6)
    End If
    
    If grd_result(8).Visible Then
        Call Export_Grid(1, nb_row_header, grd_result(8), tbs_Result(0).SelectedItem.Caption, 6)
    End If
    
    Call Export_Grid(7, nb_row_header, grd_result(1), lbl_Title(1).Caption, 35)
    Call Export_Grid(1, break1, grd_result(2), lbl_Title(2).Caption, 38)
    Call Export_Grid(7, break1, grd_result(3), lbl_Title(3).Caption, 38)
    
    
    
    If grd_result(4).Visible And Not mb_DisplayFilterByUser Then
        Call Export_Grid(1, break2, grd_result(4), lbl_Title(4).Caption, 38)
    End If
    
    If (grd_result(4).Visible Or grd_result(10).Visible) And mb_DisplayFilterByUser Then
        Call Export_Grid(1, break2, grd_result(4), tbs_Result(4).Tabs(1).Caption, 38)
        Call Export_Grid(1, break3, grd_result(10), tbs_Result(4).Tabs(3).Caption, 38)
        break3 = break3 + grd_result(10).Rows + 2
        break4 = break4 + grd_result(10).Rows + 2
    End If
    
    If grd_result(9).Visible Then
        Call Export_Grid(1, break2, grd_result(4), tbs_Result(4).Tabs(1).Caption, 38)
        Call Export_Grid(1, break3, grd_result(9), tbs_Result(4).Tabs(2).Caption, 38)
        break3 = break3 + grd_result(9).Rows + 2
        break4 = break4 + grd_result(9).Rows + 2
    End If
               
    If grd_result(5).Visible Then
        Call Export_Grid(7, break2, grd_result(5), IIf(mb_DisplayFilterByUser, tbs_Result(5).SelectedItem.Caption, lbl_Title(5).Caption), 43)
    End If
    
    If grd_result(11).Visible Then
        Call Export_Grid(7, break2, grd_result(11), tbs_Result(5).SelectedItem.Caption, 43)
    End If
    
    If grd_result(6).Visible Then
        Call Export_Grid(1, break3, grd_result(6), IIf(mb_DisplayFilterByUser, tbs_Result(6).SelectedItem.Caption, lbl_Title(6).Caption), 43, Split(C_COMMENT_L2, C_SEP))
    End If
    
    If grd_result(12).Visible Then
        Call Export_Grid(1, break3, grd_result(12), tbs_Result(6).SelectedItem.Caption, 43, Split(C_COMMENT_L2, C_SEP))
    End If
    
    
    If grd_result(7).Visible Then
        Call Export_Grid(1, break4, grd_result(7), IIf(mb_DisplayFilterByUser, tbs_Result(7).SelectedItem.Caption, lbl_Title(7).Caption), 43, Split(C_COMMENT_R2, C_SEP))
    End If
    
    If grd_result(13).Visible Then
        Call Export_Grid(1, break4, grd_result(13), tbs_Result(7).SelectedItem.Caption, 43, Split(C_COMMENT_R2, C_SEP))
    End If
    
    
    With a_ExcelSheet1.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
        .PrintArea = ""
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .PrintHeadings = False
        .PrintGridlines = False
        .CenterHorizontally = True
        .CenterVertically = False
        .Orientation = 1
        .Draft = False
        .BlackAndWhite = False
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = 1
    End With
        
        
    Set a_ExcelSheet1 = Nothing
    Set a_ExcelWorkBook = Nothing
    Set a_ExcelApp = Nothing
    Screen.MousePointer = 0
          
    MsgBox MsgText(108, ms_Language_Code, "#Press ALT+TAB to switch to the Excel application.")
    Exit Sub
    
ErrorHandler:
    If Err.Number = 429 Then
        Set a_ExcelApp = CreateObject("Excel.Application")
        Resume Next
    Else
        If Err.Number = 1004 Then
            'debug.print Err.Description
            Resume Next
        Else
            Screen.MousePointer = 0
            Set a_ExcelApp = Nothing
            Screen.MousePointer = 0
        End If
    End If
    
    Call ErrorHandler(Extender.Name & ".export_to_excel")
End Sub

Private Function TreeviewPath() As String
On Error GoTo ErrorHandler
    Dim ls_NodePath As String, lo_Node As MSComctlLib.Node
    
    Set lo_Node = tv1.SelectedItem
    ls_NodePath = ""
    While Not lo_Node Is Nothing
        ls_NodePath = lo_Node.Text & "/" & ls_NodePath
        Set lo_Node = lo_Node.Parent
    Wend
    Set lo_Node = Nothing
    
    TreeviewPath = Mid(ls_NodePath, 1, Len(ls_NodePath) - 1)
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".TreeviewPath")
End Function


Private Sub Export_Grid(ByVal aStartVCell As Integer, ByVal aStartHCell As Integer, ByRef aGrid As MSFlexGrid, ByVal aFirstColTitle As String, ByVal aHeaderColor As Long, Optional ByVal aComment As Variant = "")
On Error GoTo ErrorHandler
    Dim lIdxExcelRow As Long, lIdxExcelCol As Long
    Dim lRowIdx As Long, lRowCount As Long
    Dim lColIdx As Long, lColCount As Long
    
    lRowCount = aGrid.Rows - 1
    lColCount = aGrid.Cols - 1
    
    lIdxExcelCol = aStartVCell
    lIdxExcelRow = aStartHCell
    

    With a_ExcelSheet1
        ' HEADER OF THE GRID
        ' Set the first column title and format
        lIdxExcelRow = lIdxExcelRow + 1
        .cells(lIdxExcelRow, lIdxExcelCol).Value = aFirstColTitle
        .cells(lIdxExcelRow, lIdxExcelCol).Font.Bold = True
        
        ' Set the font format and the data Header of the grid
        For lColIdx = 1 To lColCount ' first col is already done
            .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Font.Bold = True
            .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).HorizontalAlignment = -4108
            .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = Trim(aGrid.TextMatrix(0, lColIdx))
        Next
        
        Dim lValue
        
        ' CONTENTS
        For lRowIdx = 1 To lRowCount  ' Title line is already processed
            lIdxExcelRow = lIdxExcelRow + 1
            For lColIdx = 0 To lColCount
                If lColIdx = 0 Then ' Value is for a string
                    .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = "'" & aGrid.TextMatrix(lRowIdx, lColIdx)
                Else    ' Value is a number
                    If InStr(1, aGrid.TextMatrix(lRowIdx, lColIdx), "%", vbTextCompare) = 0 Then ' Value
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = Val(aGrid.TextMatrix(lRowIdx, lColIdx))
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).NumberFormat = "#,##0"
                    Else    ' % Percent
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = aGrid.TextMatrix(lRowIdx, lColIdx)
                    End If
                End If
                .cells(lIdxExcelRow, lIdxExcelCol + lColIdx + 1).HorizontalAlignment = -4152
            Next
        Next
        
        ' TOTAL LINE FORMAT (BOLD)
        For lColIdx = 0 To lColCount
            .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Font.Bold = True
        Next
        
        ' Add the comment
        Dim lComment As Variant
        Dim lIdx As Long, lCount As Long
        
        If IsArray(aComment) Then
            lComment = aComment
        Else
            ReDim lComment(0)
            lComment(0) = aComment
        End If
        
        lCount = UBound(lComment)
        For lIdx = 0 To lCount
            lIdxExcelRow = lIdxExcelRow + 1
            .cells(lIdxExcelRow, lIdxExcelCol).Value = lComment(lIdx)
        Next
        
        
        ' ADD THE STYLE
        Dim lRangeTopLeft As String, lRangeBottomRight As String, lRange As String
        
        ' SET THE GRID
        lRangeTopLeft = Chr(64 + aStartVCell) & (aStartHCell + 1)
        lRangeBottomRight = Chr(64 + aStartVCell + lColCount) & (aStartHCell + lRowCount + 1)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlInsideVertical).Weight = xlThin
        .Range(lRange).Borders(xlInsideVertical).LineStyle = xlContinuous
        .Range(lRange).Borders(xlInsideHorizontal).Weight = xlThin
        .Range(lRange).Borders(xlInsideHorizontal).LineStyle = xlContinuous
        
        ' SET THE HEADER
        lRangeTopLeft = Chr(64 + aStartVCell) & (aStartHCell + 1)
        lRangeBottomRight = Chr(64 + aStartVCell + lColCount) & (aStartHCell + 1)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeTop).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeTop).Weight = xlThick
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        
        ' SET THE TOTAL
        lRangeTopLeft = Chr(64 + aStartVCell) & (aStartHCell + lRowCount + 1)
        lRangeBottomRight = Chr(64 + aStartVCell + lColCount) & (aStartHCell + lRowCount + 1)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeTop).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeTop).Weight = xlThick
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
        ' SET THE EXTERNAL WEIGHT LINE
        ' LEFT
        lRangeTopLeft = Chr(64 + aStartVCell) & (aStartHCell + 1)
        lRangeBottomRight = Chr(64 + aStartVCell) & (aStartHCell + lRowCount + 1)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        
        ' RIGHT
        lRangeTopLeft = Chr(64 + aStartVCell + lColCount) & (aStartHCell + 1)
        lRangeBottomRight = Chr(64 + aStartVCell + lColCount) & (aStartHCell + lRowCount + 1)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
    End With
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".Export_Grid")
End Sub

Private Sub Export_Grid_StatPrj(ByRef aGrid As MSFlexGrid, ByVal aHeaderColor As Long, ByVal as_reporCaption As String)
On Error GoTo ErrorHandler
    Set a_ExcelApp = GetObject(, "Excel.Application")
    Set a_ExcelWorkBook = a_ExcelApp.Workbooks.Add
    Set a_ExcelSheet1 = a_ExcelWorkBook.Sheets.Add

    a_ExcelWorkBook.Activate
    a_ExcelSheet1.Activate
    
    a_ExcelSheet1.PageSetup.Orientation = 2
    
    a_ExcelApp.ActiveSheet.PageSetup.Zoom = 70

    a_ExcelApp.Application.Visible = -1
    a_ExcelSheet1.Application.Visible = -1
    
    With a_ExcelSheet1.cells.Interior
        .ColorIndex = 2
        .Pattern = 1
        .PatternColorIndex = -4105
    End With
    
    
    With a_ExcelSheet1
        .Columns("A").columnWidth = 9
        .Columns("B").columnWidth = IIf(aGrid.ColWidth(3) > 0, 14, 0)
        .Columns("C").columnWidth = 10
        .Columns("D").columnWidth = 10
        .Columns("E").columnWidth = 10
        .Columns("F").columnWidth = 10
        .Columns("G").columnWidth = 10
        .Columns("H").columnWidth = 10
        .Columns("I").columnWidth = 10
        .Columns("J").columnWidth = 10
        .Columns("K").columnWidth = 10
        .Columns("L").columnWidth = 10
        .Columns("M").columnWidth = 10
        .Columns("N").columnWidth = 10
        .Columns("O").columnWidth = 13
        .Columns("J:J").HorizontalAlignment = xlright
        .Columns("R:R").HorizontalAlignment = xlright
        
        .cells(2, 10).Value = GetLabel("ex_report", "#CAPTURE REPORT")
        .cells(2, 10).Font.Bold = True
        .cells(4, 1).Value = as_reporCaption
        .cells(4, 1).Font.Bold = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$NOW$"
        ms_MsgInfo(0, 1) = Format(Now, "dd/mm/yy hh:mm:ss")
        .cells(2, 18).Value = GetLabel("ex_created", "#Created $NOW$", ms_MsgInfo)
        .cells(2, 18).Font.Italic = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$CB_TRW$"
        ms_MsgInfo(0, 1) = cb_trw.Text
        .cells(3, 18) = GetLabel("ex_trw", "#Treeview Info: $CB_TRW$", ms_MsgInfo)
        .cells(3, 18).Font.Italic = True
        .cells(3, 18).Font.Size = 8

        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$TRW_PATH$"
        ms_MsgInfo(0, 1) = TreeviewPath
        .cells(4, 18) = GetLabel("ex_trw_path", "#Treeview Path: $TRW_PATH$", ms_MsgInfo)
        .cells(4, 18).Font.Italic = True
        .cells(4, 18).Font.Size = 8
    End With
    
    
    Dim lIdxExcelRow As Long, lIdxExcelCol As Long
    Dim lRowIdx As Long, lRowCount As Long
    Dim lColIdx As Long, lColCount As Long
    
'    For lColIdx = 0 To 58
'        a_ExcelSheet1.cells(1, lColIdx + 1).Interior.ColorIndex = lColIdx
'        a_ExcelSheet1.cells(1, lColIdx + 1).value = lColIdx
'    Next
    
    lRowCount = aGrid.Rows - 1
    lColCount = aGrid.Cols - 7
    
    lIdxExcelCol = 1
    lIdxExcelRow = 5
    

    With a_ExcelSheet1
        ' HEADER OF THE GRID
        ' Set the first column title and format
        ' Set the font format and the data Header of the grid
        For lRowIdx = 0 To aGrid.FixedRows - 1
            lIdxExcelRow = lIdxExcelRow + 1
        
            For lColIdx = 0 To lColCount ' first col is already done
                .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Font.Bold = True
                .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).HorizontalAlignment = -4108
                .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = Trim(aGrid.TextMatrix(lRowIdx, lColIdx + 2))
            Next
        Next
        
        Dim lValue
        Dim lRangeTopLeft As String, lRangeBottomRight As String, lRange As String

        ' CONTENTS
        For lRowIdx = aGrid.FixedRows To aGrid.Rows - 1  ' Title line is already processed
            If aGrid.RowHeight(lRowIdx) <> 0 Then
                lIdxExcelRow = lIdxExcelRow + 1
                For lColIdx = 0 To lColCount
                    If lColIdx < 2 Then ' Value is for a string
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Font.Bold = True
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = "'" & aGrid.TextMatrix(lRowIdx, lColIdx + 2)
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).HorizontalAlignment = -4131    'xlLeft
                    Else    ' Value is a number
                        If InStr(1, aGrid.TextMatrix(lRowIdx, lColIdx + 2), "%", vbTextCompare) = 0 Then ' Value
                            If aGrid.TextMatrix(lRowIdx, lColIdx + 2) = "" Then
                                .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = ""
                            Else
                                .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = CDbl(aGrid.TextMatrix(lRowIdx, lColIdx + 2))
                                .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).NumberFormat = "#,##0"
                            End If
                        Else    ' % Percent
                            .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = Replace(aGrid.TextMatrix(lRowIdx, lColIdx + 2), "%", "") / 100
                        End If
                    End If
                    .cells(lIdxExcelRow, lIdxExcelCol + lColIdx + 1).HorizontalAlignment = -4152
                Next
            Else
                lRowCount = lRowCount - 1
            End If
            ' if line is total then do line
            If aGrid.TextMatrix(lRowIdx, 0) = "" Then
                'total
                lRangeTopLeft = "C" & (lIdxExcelRow)
                lRangeBottomRight = Chr(65 + lColCount) & (lIdxExcelRow)
                lRange = lRangeTopLeft & ":" & lRangeBottomRight
                .Range(lRange).Interior.ColorIndex = 4  '12
                .Range(lRange).Interior.Pattern = 1
                .Range(lRange).Interior.PatternColorIndex = -4105
                .Range(lRange).Font.Bold = True
                
            ElseIf aGrid.TextMatrix(lRowIdx, 1) = "" Then
                ' subtotal
                lRangeTopLeft = "C" & (lIdxExcelRow)
                lRangeBottomRight = Chr(65 + lColCount) & (lIdxExcelRow)
                lRange = lRangeTopLeft & ":" & lRangeBottomRight
                .Range(lRange).Interior.ColorIndex = 6
                .Range(lRange).Interior.Pattern = 1
                .Range(lRange).Interior.PatternColorIndex = -4105
                .Range(lRange).Font.Bold = True
            End If
        Next
        
        Call MergeRows(a_ExcelSheet1, 6, aGrid.FixedRows + 5, 2)
        Call MergeRows(a_ExcelSheet1, 6, lIdxExcelRow, 1)
        Call MergeCols(a_ExcelSheet1, 3, lColCount + 1, 6)
        
        ' TOTAL LINE FORMAT (BOLD)
        For lRowIdx = 0 To lRowCount
            .cells(lIdxExcelRow - lRowIdx, lIdxExcelCol + lColCount - 2).Font.Bold = True
            .cells(lIdxExcelRow - lRowIdx, lIdxExcelCol + 9).Font.Bold = True
        Next
        
        
        ' ADD THE STYLE
        
        lRangeTopLeft = "Q8"
        lRangeBottomRight = "R" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).NumberFormat = "0%"
        
        ' SET THE GRID
        lRangeTopLeft = "A6"
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlInsideVertical).Weight = xlThin
        .Range(lRange).Borders(xlInsideVertical).LineStyle = xlContinuous
        .Range(lRange).Borders(xlInsideHorizontal).Weight = xlThin
        .Range(lRange).Borders(xlInsideHorizontal).LineStyle = xlContinuous
        
        ' SET THE HEADER
        lRangeTopLeft = "A6"
        lRangeBottomRight = Chr(65 + lColCount) & "7"
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeTop).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeTop).Weight = xlThick
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        
        lRangeTopLeft = "A8"
        lRangeBottomRight = "B" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        
        
        ' SET THE TOTAL
        lRangeTopLeft = "J6"
        lRangeBottomRight = "J" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
        lRangeTopLeft = "P7"
        lRangeBottomRight = "P" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
        
        ' SET THE EXTERNAL WEIGHT LINE
        ' LEFT
        lRangeTopLeft = "A6"
        lRangeBottomRight = "A" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        
        ' RIGHT
        lRangeTopLeft = Chr(65 + lColCount) & "6"
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
        ' BOTTOM
        lRangeTopLeft = "A" & (lRowCount + 6)
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
        ' BOTTOM
        lRangeTopLeft = "A" & (lRowCount + 5)
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 5)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
        
        For lRowIdx = aGrid.FixedRows To lRowCount  ' Title line is already processed
            ' if line is total then do line
            If aGrid.TextMatrix(lRowIdx, 1) = "" Then
                ' BOTTOM
                lRangeTopLeft = "A" & (lRowIdx + 6)
                lRangeBottomRight = Chr(65 + lColCount) & (lRowIdx + 6)
                lRange = lRangeTopLeft & ":" & lRangeBottomRight
                .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
                .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
            End If
        Next
        
    End With
    
    With a_ExcelSheet1.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
        .PrintArea = ""
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .PrintHeadings = False
        .PrintGridlines = False
        .CenterHorizontally = True
        .CenterVertically = False
        .Orientation = 1
        .Draft = False
        .BlackAndWhite = False
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = 1
    End With
        
        
    Set a_ExcelSheet1 = Nothing
    Set a_ExcelWorkBook = Nothing
    Set a_ExcelApp = Nothing
    Screen.MousePointer = 0
          
    MsgBox MsgText(108, ms_Language_Code, "#Press ALT+TAB to switch to the Excel application.")
    Exit Sub
    
ErrorHandler:
    If Err.Number = 429 Then
        Set a_ExcelApp = CreateObject("Excel.Application")
        Resume Next
    Else
        If Err.Number = 1004 Then
            'debug.print Err.Description
            Resume Next
        Else
            Screen.MousePointer = 0
            Set a_ExcelApp = Nothing
            Screen.MousePointer = 0
        End If
    End If

    Call ErrorHandler(Extender.Name & ".Export_Grid_StatPrj")
End Sub

Private Sub Export_Grid_StatPrj2(ByRef aGrid As MSFlexGrid, ByVal aHeaderColor As Long, ByVal as_reporCaption As String)
On Error GoTo ErrorHandler
    Set a_ExcelApp = GetObject(, "Excel.Application")
    Set a_ExcelWorkBook = a_ExcelApp.Workbooks.Add
    Set a_ExcelSheet1 = a_ExcelWorkBook.Sheets.Add

    a_ExcelWorkBook.Activate
    a_ExcelSheet1.Activate
    
    a_ExcelSheet1.PageSetup.Orientation = 2
    
    a_ExcelApp.ActiveSheet.PageSetup.Zoom = 70

    a_ExcelApp.Application.Visible = -1
    a_ExcelSheet1.Application.Visible = -1
    
    With a_ExcelSheet1.cells.Interior
        .ColorIndex = 2
        .Pattern = 1
        .PatternColorIndex = -4105
    End With
    
    
    With a_ExcelSheet1
        .Columns("A").columnWidth = 9
        .Columns("B").columnWidth = IIf(aGrid.ColWidth(3) > 0, 14, 0)
        .Columns("C").columnWidth = 0
        .Columns("D").columnWidth = IIf(aGrid.ColWidth(5) > 0, 10, 0)
        .Columns("E").columnWidth = 8
        .Columns("F").columnWidth = 8
        .Columns("G").columnWidth = 8
        .Columns("H").columnWidth = 8
        .Columns("I").columnWidth = 8
        .Columns("J").columnWidth = 8
        .Columns("K").columnWidth = 8
        .Columns("L").columnWidth = 8
        .Columns("M").columnWidth = 8
        .Columns("N").columnWidth = 10
        .Columns("O").columnWidth = 8
        .Columns("P").columnWidth = 8
        .Columns("Q").columnWidth = 8
        .Columns("R").columnWidth = 8
        .Columns("S").columnWidth = 8
        .Columns("T").columnWidth = 8
        .Columns("U").columnWidth = 8
        .Columns("V").columnWidth = 8
        .Columns("W").columnWidth = 8
        .Columns("X").columnWidth = 8
        .Columns("Y").columnWidth = 10
        .Columns("Z").columnWidth = 10
        .Columns("AA").columnWidth = 10
        .Columns("AB").columnWidth = 8
        .Columns("AC").columnWidth = 8
        .Columns("O").HorizontalAlignment = xlright
        .Columns("AC:AC").HorizontalAlignment = xlright
        
        .cells(2, 15).Value = GetLabel("ex_report", "#CAPTURE REPORT")
        .cells(2, 15).Font.Bold = True
        .cells(4, 1).Value = as_reporCaption
        .cells(4, 1).Font.Bold = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$NOW$"
        ms_MsgInfo(0, 1) = Format(Now, "dd/mm/yy hh:mm:ss")
        .cells(2, 29).Value = GetLabel("ex_created", "#Created $NOW$", ms_MsgInfo)
        .cells(2, 29).Font.Italic = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$CB_TRW$"
        ms_MsgInfo(0, 1) = cb_trw.Text
        .cells(3, 29) = GetLabel("ex_trw", "#Treeview Info: $CB_TRW$", ms_MsgInfo)
        .cells(3, 29).Font.Italic = True
        .cells(3, 29).Font.Size = 8

        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$TRW_PATH$"
        ms_MsgInfo(0, 1) = TreeviewPath
        .cells(4, 29) = GetLabel("ex_trw_path", "#Treeview Path: $TRW_PATH$", ms_MsgInfo)
        .cells(4, 29).Font.Italic = True
        .cells(4, 29).Font.Size = 8
    End With
    
    
    Dim lIdxExcelRow As Long, lIdxExcelCol As Long
    Dim lRowIdx As Long, lRowCount As Long
    Dim lColIdx As Long, lColCount As Long
    
    lRowCount = aGrid.Rows - 1
    lColCount = aGrid.Cols - 3
    
    lIdxExcelCol = 1
    lIdxExcelRow = 5
    

    Dim lv_Data As Variant
    
    With a_ExcelSheet1
        ' HEADER OF THE GRID
        ' Set the first column title and format
        ' Set the font format and the data Header of the grid
        For lRowIdx = 0 To aGrid.FixedRows - 1
            lIdxExcelRow = lIdxExcelRow + 1
            
            Call FillGridRowData(lv_Data, aGrid, lRowIdx, 2, lColCount + 2)
            .Range(.cells(lIdxExcelRow, lIdxExcelCol), .cells(lIdxExcelRow, lIdxExcelCol + UBound(lv_Data))) = lv_Data
            
            With .Range(.cells(lIdxExcelRow, lIdxExcelCol), .cells(lIdxExcelRow, lIdxExcelCol + UBound(lv_Data)))
                .Font.Bold = True
                .HorizontalAlignment = -4108
                .VerticalAlignment = -4108  'xlVAlignCenter
                .WrapText = aGrid.WordWrap
            End With
        Next
        .Rows(7).RowHeight = 720 / (240 / 12.75)    ' height of header row
        
        Dim lValue
        Dim lRangeTopLeft As String, lRangeBottomRight As String, lRange As String

        ' CONTENTS
        For lRowIdx = aGrid.FixedRows To aGrid.Rows - 1  ' Title line is already processed
            If aGrid.RowHeight(lRowIdx) <> 0 Then
                lIdxExcelRow = lIdxExcelRow + 1
                
                ReDim lv_Data(lColCount) As Variant
                
                For lColIdx = 0 To lColCount
                    If lColIdx < aGrid.FixedCols - 2 Then  ' Value for cols A ... D is for a string
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Font.Bold = True
                        lv_Data(lColIdx) = "'" & aGrid.TextMatrix(lRowIdx, lColIdx + 2)
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).HorizontalAlignment = -4131    'xlLeft
                    Else    ' Value is a number
                        If InStr(1, aGrid.TextMatrix(lRowIdx, lColIdx + 2), "%", vbTextCompare) = 0 Then ' Value
                            If aGrid.TextMatrix(lRowIdx, lColIdx + 2) = "" Then
                                lv_Data(lColIdx) = ""
                            Else
                                lv_Data(lColIdx) = CDbl(aGrid.TextMatrix(lRowIdx, lColIdx + 2))
                                .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).NumberFormat = "#,##0"
                            End If
                        Else    ' % Percent
                            lv_Data(lColIdx) = Replace(aGrid.TextMatrix(lRowIdx, lColIdx + 2), "%", "") / 100
                        End If
                    End If
                    .cells(lIdxExcelRow, lIdxExcelCol + lColIdx + 1).HorizontalAlignment = -4152
                Next
                .Range(.cells(lIdxExcelRow, lIdxExcelCol), .cells(lIdxExcelRow, lIdxExcelCol + UBound(lv_Data))) = lv_Data
            Else
                lRowCount = lRowCount - 1
            End If
            ' if line is total then do line
            If aGrid.TextMatrix(lRowIdx, 0) = "" Then
                'total
                lRangeTopLeft = "E" & (lIdxExcelRow)
                lRangeBottomRight = "AC" & (lIdxExcelRow)
                lRange = lRangeTopLeft & ":" & lRangeBottomRight
                .Range(lRange).Interior.ColorIndex = 4 '12
                .Range(lRange).Interior.Pattern = 1
                .Range(lRange).Interior.PatternColorIndex = -4105
                .Range(lRange).Font.Bold = True
                
            ElseIf aGrid.TextMatrix(lRowIdx, 1) = "" And aGrid.TextMatrix(lRowIdx, 4) = "" Then
                ' subtotal
                lRangeTopLeft = "E" & (lIdxExcelRow)
                lRangeBottomRight = "AC" & (lIdxExcelRow)
                lRange = lRangeTopLeft & ":" & lRangeBottomRight
                .Range(lRange).Interior.ColorIndex = 6
                .Range(lRange).Interior.Pattern = 1
                .Range(lRange).Interior.PatternColorIndex = -4105
                .Range(lRange).Font.Bold = True
            End If
        Next
        
        Call MergeRows(a_ExcelSheet1, 6, lIdxExcelRow, 2)
        Call MergeRows(a_ExcelSheet1, 6, lIdxExcelRow, 1)
        Call MergeCols(a_ExcelSheet1, 5, lColCount + 1, 6)
        
        ' TOTAL LINE FORMAT (BOLD)
        For lRowIdx = 0 To lRowCount
            .cells(lIdxExcelRow - lRowIdx, lIdxExcelCol + lColCount - 2).Font.Bold = True
            .cells(lIdxExcelRow - lRowIdx, lIdxExcelCol + 11).Font.Bold = True
        Next
        
        
        ' ADD THE STYLE
        
        lRangeTopLeft = "Y8"
        lRangeBottomRight = "AA" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).NumberFormat = "0.0%"
        
        lRangeTopLeft = "N8"
        lRangeBottomRight = "N" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).NumberFormat = "0.0%"
        
        ' SET THE GRID
        lRangeTopLeft = "A6"
        lRangeBottomRight = "AC" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlInsideVertical).Weight = xlThin
        .Range(lRange).Borders(xlInsideVertical).LineStyle = xlContinuous
        .Range(lRange).Borders(xlInsideHorizontal).Weight = xlThin
        .Range(lRange).Borders(xlInsideHorizontal).LineStyle = xlContinuous
        
        ' SET THE HEADER
        lRangeTopLeft = "A6"
        lRangeBottomRight = "AC" & "7"
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeTop).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeTop).Weight = xlThick
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        
        lRangeTopLeft = "A8"
        lRangeBottomRight = "B" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        
        
        ' SET THE TOTAL
        lRangeTopLeft = "M6"
        lRangeBottomRight = "M" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
        lRangeTopLeft = "W7"
        lRangeBottomRight = "W" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
        
        ' SET THE EXTERNAL WEIGHT LINE
        ' LEFT
        lRangeTopLeft = "A6"
        lRangeBottomRight = "A" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        
        ' RIGHT
        lRangeTopLeft = "AC" & "6"
        lRangeBottomRight = "AC" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
        ' BOTTOM
        lRangeTopLeft = "A" & (lRowCount + 6)
        lRangeBottomRight = "AC" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
        ' BOTTOM
        lRangeTopLeft = "A" & (lRowCount + 5)
        lRangeBottomRight = "AC" & (lRowCount + 5)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
        
        For lRowIdx = aGrid.FixedRows To lRowCount  ' Title line is already processed
            ' if line is total then do line
            If aGrid.TextMatrix(lRowIdx, 1) = "" Then
                ' BOTTOM
                lRangeTopLeft = "A" & (lRowIdx + 6)
                lRangeBottomRight = "AC" & (lRowIdx + 6)
                lRange = lRangeTopLeft & ":" & lRangeBottomRight
                .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
                .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
            End If
        Next
        
    End With
    
    With a_ExcelSheet1.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
        .PrintArea = ""
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .PrintHeadings = False
        .PrintGridlines = False
        .CenterHorizontally = True
        .CenterVertically = False
        .Orientation = 1
        .Draft = False
        .BlackAndWhite = False
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = 1
    End With
        
        
    Set a_ExcelSheet1 = Nothing
    Set a_ExcelWorkBook = Nothing
    Set a_ExcelApp = Nothing
    Screen.MousePointer = 0
          
    MsgBox MsgText(108, ms_Language_Code, "#Press ALT+TAB to switch to the Excel application.")
    Exit Sub
    
ErrorHandler:
    If Err.Number = 429 Then
        Set a_ExcelApp = CreateObject("Excel.Application")
        Resume Next
    Else
        If Err.Number = 1004 Then
            'debug.print Err.Description
            Resume Next
        Else
            Screen.MousePointer = 0
            Set a_ExcelApp = Nothing
            Screen.MousePointer = 0
        End If
    End If

    Call ErrorHandler(Extender.Name & ".Export_Grid_StatPrj2")
End Sub



Private Sub Export_Grid_StatPrj3(ByRef aGrid As MSFlexGrid, ByVal aHeaderColor As Long, ByVal as_reporCaption As String)
On Error GoTo ErrorHandler
    Set a_ExcelApp = GetObject(, "Excel.Application")
    Set a_ExcelWorkBook = a_ExcelApp.Workbooks.Add
    Set a_ExcelSheet1 = a_ExcelWorkBook.Sheets.Add

    a_ExcelWorkBook.Activate
    a_ExcelSheet1.Activate
    
    a_ExcelSheet1.PageSetup.Orientation = 2
    
    a_ExcelApp.ActiveSheet.PageSetup.Zoom = 70

    a_ExcelApp.Application.Visible = -1
    a_ExcelSheet1.Application.Visible = -1
    
    With a_ExcelSheet1.cells.Interior
        .ColorIndex = 2
        .Pattern = 1
        .PatternColorIndex = -4105
    End With
    
    
    With a_ExcelSheet1
        .Columns("A").columnWidth = 18
        .Columns("B").columnWidth = IIf(aGrid.ColWidth(3) > 0, 18, 0)
        .Columns("C").columnWidth = 0
        .Columns("D").columnWidth = 12
        .Columns("E").columnWidth = 12
        .Columns("F").columnWidth = 14
        .Columns("G").columnWidth = 0
        .Columns("H").columnWidth = 0
        .Columns("I").columnWidth = 14
        .Columns("J").columnWidth = 14
        .Columns("K").columnWidth = 14
        
        .Columns("F").HorizontalAlignment = xlright
        .Columns("K:K").HorizontalAlignment = xlright
        
        .cells(2, 6).Value = GetLabel("ex_report", "#CAPTURE REPORT")
        .cells(2, 6).Font.Bold = True
        .cells(4, 1).Value = as_reporCaption
        .cells(4, 1).Font.Bold = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$NOW$"
        ms_MsgInfo(0, 1) = Format(Now, "dd/mm/yy hh:mm:ss")
        .cells(2, 11).Value = GetLabel("ex_created", "#Created $NOW$", ms_MsgInfo)
        .cells(2, 11).Font.Italic = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$CB_TRW$"
        ms_MsgInfo(0, 1) = cb_trw.Text
        .cells(3, 11) = GetLabel("ex_trw", "#Treeview Info: $CB_TRW$", ms_MsgInfo)
        .cells(3, 11).Font.Italic = True
        .cells(3, 11).Font.Size = 8

        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$TRW_PATH$"
        ms_MsgInfo(0, 1) = TreeviewPath
        .cells(4, 11) = GetLabel("ex_trw_path", "#Treeview Path: $TRW_PATH$", ms_MsgInfo)
        .cells(4, 11).Font.Italic = True
        .cells(4, 11).Font.Size = 8
    End With
    
    
    Dim lIdxExcelRow As Long, lIdxExcelCol As Long
    Dim lRowIdx As Long, lRowCount As Long
    Dim lColIdx As Long, lColCount As Long
    
    lRowCount = aGrid.Rows - 1
    lColCount = aGrid.Cols - 3
    
    lIdxExcelCol = 1
    lIdxExcelRow = 5
    

    Dim lv_Data As Variant
    
    With a_ExcelSheet1
        ' HEADER OF THE GRID
        ' Set the first column title and format
        ' Set the font format and the data Header of the grid
        For lRowIdx = 0 To aGrid.FixedRows - 1
            lIdxExcelRow = lIdxExcelRow + 1
            
            Call FillGridRowData(lv_Data, aGrid, lRowIdx, 2, lColCount + 2)
            .Range(.cells(lIdxExcelRow, lIdxExcelCol), .cells(lIdxExcelRow, lIdxExcelCol + UBound(lv_Data))) = lv_Data
            
            With .Range(.cells(lIdxExcelRow, lIdxExcelCol), .cells(lIdxExcelRow, lIdxExcelCol + UBound(lv_Data)))
                .Font.Bold = True
                .HorizontalAlignment = -4108
                .VerticalAlignment = -4108  'xlVAlignCenter
                .WrapText = aGrid.WordWrap
            End With
        Next
        
        Dim lValue
        Dim lRangeTopLeft As String, lRangeBottomRight As String, lRange As String

        ' CONTENTS
        For lRowIdx = aGrid.FixedRows To aGrid.Rows - 1  ' Title line is already processed
            If aGrid.RowHeight(lRowIdx) <> 0 Then
                lIdxExcelRow = lIdxExcelRow + 1
                
                ReDim lv_Data(lColCount) As Variant
                
                For lColIdx = 0 To lColCount
                    If lColIdx < aGrid.FixedCols - 2 Then  ' Value for cols A ... D is for a string
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Font.Bold = True
                        lv_Data(lColIdx) = "'" & aGrid.TextMatrix(lRowIdx, lColIdx + 2)
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).HorizontalAlignment = -4131    'xlLeft
                    Else    ' Value is a number
                        If InStr(1, aGrid.TextMatrix(lRowIdx, lColIdx + 2), "%", vbTextCompare) = 0 Then ' Value
                            If aGrid.TextMatrix(lRowIdx, lColIdx + 2) = "" Then
                                lv_Data(lColIdx) = ""
                            Else
                                lv_Data(lColIdx) = CDbl(aGrid.TextMatrix(lRowIdx, lColIdx + 2))
                                .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).NumberFormat = "#,##0"
                            End If
                        Else    ' % Percent
                            lv_Data(lColIdx) = Replace(aGrid.TextMatrix(lRowIdx, lColIdx + 2), "%", "") / 100
                        End If
                    End If
                    .cells(lIdxExcelRow, lIdxExcelCol + lColIdx + 1).HorizontalAlignment = -4152
                Next
                .Range(.cells(lIdxExcelRow, lIdxExcelCol), .cells(lIdxExcelRow, lIdxExcelCol + UBound(lv_Data))) = lv_Data
            Else
                lRowCount = lRowCount - 1
            End If
            ' if line is total then do line
            If aGrid.TextMatrix(lRowIdx, 0) = "" Then
                'total
                lRangeTopLeft = "D" & (lIdxExcelRow)
                lRangeBottomRight = "K" & (lIdxExcelRow)
                lRange = lRangeTopLeft & ":" & lRangeBottomRight
                .Range(lRange).Interior.ColorIndex = 4 '12
                .Range(lRange).Interior.Pattern = 1
                .Range(lRange).Interior.PatternColorIndex = -4105
                .Range(lRange).Font.Bold = True
                
            ElseIf aGrid.TextMatrix(lRowIdx, 1) = "" Then
                ' subtotal
                lRangeTopLeft = "D" & (lIdxExcelRow)
                lRangeBottomRight = "K" & (lIdxExcelRow)
                lRange = lRangeTopLeft & ":" & lRangeBottomRight
                .Range(lRange).Interior.ColorIndex = 6
                .Range(lRange).Interior.Pattern = 1
                .Range(lRange).Interior.PatternColorIndex = -4105
                .Range(lRange).Font.Bold = True
            End If
        Next
        
        Call MergeRows(a_ExcelSheet1, 6, aGrid.FixedRows + 5, 2)
        Call MergeRows(a_ExcelSheet1, 6, lIdxExcelRow, 1)
'        Call MergeCols(a_ExcelSheet1, 5, lColCount + 1, 6)
        
        ' TOTAL LINE FORMAT (BOLD)
        For lRowIdx = 0 To lRowCount
            .cells(lIdxExcelRow - lRowIdx, lIdxExcelCol + lColCount - 2).Font.Bold = True
            .cells(lIdxExcelRow - lRowIdx, lIdxExcelCol + 11).Font.Bold = True
        Next
        
        
        ' ADD THE STYLE
        
        lRangeTopLeft = "I7"
        lRangeBottomRight = "J" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).NumberFormat = "0.0%"
        
        lRangeTopLeft = "F7"
        lRangeBottomRight = "F" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).NumberFormat = "0.0%"
        
        ' SET THE GRID
        lRangeTopLeft = "A6"
        lRangeBottomRight = "K" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlInsideVertical).Weight = xlThin
        .Range(lRange).Borders(xlInsideVertical).LineStyle = xlContinuous
        .Range(lRange).Borders(xlInsideHorizontal).Weight = xlThin
        .Range(lRange).Borders(xlInsideHorizontal).LineStyle = xlContinuous
        
        ' SET THE HEADER
        lRangeTopLeft = "A6"
        lRangeBottomRight = "K" & "6"
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeTop).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeTop).Weight = xlThick
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        
        lRangeTopLeft = "A7"
        lRangeBottomRight = "B" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        
        
        ' SET THE EXTERNAL WEIGHT LINE
        ' LEFT
        lRangeTopLeft = "A6"
        lRangeBottomRight = "A" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        
        ' RIGHT
        lRangeTopLeft = "K" & "6"
        lRangeBottomRight = "K" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
        ' BOTTOM
        lRangeTopLeft = "A" & (lRowCount + 6)
        lRangeBottomRight = "K" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
        ' BOTTOM
        lRangeTopLeft = "A" & (lRowCount + 5)
        lRangeBottomRight = "K" & (lRowCount + 5)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
        
        For lRowIdx = aGrid.FixedRows To lRowCount  ' Title line is already processed
            ' if line is total then do line
            If aGrid.TextMatrix(lRowIdx, 1) = "" Then
                ' BOTTOM
                lRangeTopLeft = "A" & (lRowIdx + 6)
                lRangeBottomRight = "K" & (lRowIdx + 6)
                lRange = lRangeTopLeft & ":" & lRangeBottomRight
                .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
                .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
            End If
        Next
        
    End With
    
    With a_ExcelSheet1.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
        .PrintArea = ""
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .PrintHeadings = False
        .PrintGridlines = False
        .CenterHorizontally = True
        .CenterVertically = False
        .Orientation = 1
        .Draft = False
        .BlackAndWhite = False
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = 1
    End With
        
        
    Set a_ExcelSheet1 = Nothing
    Set a_ExcelWorkBook = Nothing
    Set a_ExcelApp = Nothing
    Screen.MousePointer = 0
          
    MsgBox MsgText(108, ms_Language_Code, "#Press ALT+TAB to switch to the Excel application.")
    Exit Sub
    
ErrorHandler:
    If Err.Number = 429 Then
        Set a_ExcelApp = CreateObject("Excel.Application")
        Resume Next
    Else
        If Err.Number = 1004 Then
            'debug.print Err.Description
            Resume Next
        Else
            Screen.MousePointer = 0
            Set a_ExcelApp = Nothing
            Screen.MousePointer = 0
        End If
    End If

    Call ErrorHandler(Extender.Name & ".Export_Grid_StatPrj3")
End Sub


Private Sub Export_Grid_Visits2(ByRef aGrid As MSFlexGrid, ByVal aHeaderColor As Long, ByVal as_reporCaption As String)
On Error GoTo ErrorHandler
    Set a_ExcelApp = GetObject(, "Excel.Application")
    Set a_ExcelWorkBook = a_ExcelApp.Workbooks.Add
    Set a_ExcelSheet1 = a_ExcelWorkBook.Sheets.Add

    a_ExcelWorkBook.Activate
    a_ExcelSheet1.Activate
    
    a_ExcelSheet1.PageSetup.Orientation = 2
    
    a_ExcelApp.ActiveSheet.PageSetup.Zoom = 70

    a_ExcelApp.Application.Visible = -1
    a_ExcelSheet1.Application.Visible = -1
    
    With a_ExcelSheet1.cells.Interior
        .ColorIndex = 2
        .Pattern = 1
        .PatternColorIndex = -4105
    End With
    
    
    With a_ExcelSheet1
        .Columns("A").columnWidth = 18
        .Columns("B").columnWidth = IIf(aGrid.ColWidth(3) > 0, 18, 0)
        .Columns("C").columnWidth = 0
        .Columns("D").columnWidth = IIf(aGrid.ColWidth(5) > 0, 22, 0)
        .Columns("E").columnWidth = 12
        .Columns("F").columnWidth = 14
        .Columns("G").columnWidth = 14
        .Columns("H").columnWidth = 16
        
        .Columns("E").HorizontalAlignment = xlright
        .Columns("H:H").HorizontalAlignment = xlright
        
        .cells(2, 5).Value = GetLabel("ex_report", "#CAPTURE REPORT")
        .cells(2, 5).Font.Bold = True
        .cells(4, 1).Value = as_reporCaption
        .cells(4, 1).Font.Bold = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$NOW$"
        ms_MsgInfo(0, 1) = Format(Now, "dd/mm/yy hh:mm:ss")
        .cells(2, 8).Value = GetLabel("ex_created", "#Created $NOW$", ms_MsgInfo)
        .cells(2, 8).Font.Italic = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$CB_TRW$"
        ms_MsgInfo(0, 1) = cb_trw.Text
        .cells(3, 8) = GetLabel("ex_trw", "#Treeview Info: $CB_TRW$", ms_MsgInfo)
        .cells(3, 8).Font.Italic = True
        .cells(3, 8).Font.Size = 8

        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$TRW_PATH$"
        ms_MsgInfo(0, 1) = TreeviewPath
        .cells(4, 8) = GetLabel("ex_trw_path", "#Treeview Path: $TRW_PATH$", ms_MsgInfo)
        .cells(4, 8).Font.Italic = True
        .cells(4, 8).Font.Size = 8
    End With
    
    
    Dim lIdxExcelRow As Long, lIdxExcelCol As Long
    Dim lRowIdx As Long, lRowCount As Long
    Dim lColIdx As Long, lColCount As Long
    
    lRowCount = aGrid.Rows - 1
    lColCount = aGrid.Cols - 1
    
    lIdxExcelCol = 1
    lIdxExcelRow = 5
    

    Dim lv_Data As Variant
    
    With a_ExcelSheet1
        ' HEADER OF THE GRID
        ' Set the first column title and format
        ' Set the font format and the data Header of the grid
        For lRowIdx = 0 To aGrid.FixedRows - 1
            lIdxExcelRow = lIdxExcelRow + 1
            
            Call FillGridRowData(lv_Data, aGrid, lRowIdx, 2, lColCount)
            .Range(.cells(lIdxExcelRow, lIdxExcelCol), .cells(lIdxExcelRow, lIdxExcelCol + UBound(lv_Data))) = lv_Data
            
            With .Range(.cells(lIdxExcelRow, lIdxExcelCol), .cells(lIdxExcelRow, lIdxExcelCol + UBound(lv_Data)))
                .Font.Bold = True
                .HorizontalAlignment = -4108
                .VerticalAlignment = -4108  'xlVAlignCenter
                .WrapText = aGrid.WordWrap
            End With
        Next
        
        Dim lValue
        Dim lRangeTopLeft As String, lRangeBottomRight As String, lRange As String

        ' CONTENTS
        For lRowIdx = aGrid.FixedRows To aGrid.Rows - 1  ' Title line is already processed
            If aGrid.RowHeight(lRowIdx) <> 0 Then
                lIdxExcelRow = lIdxExcelRow + 1
                
                ReDim lv_Data(lColCount) As Variant
                
                For lColIdx = 0 To lColCount - 2
                    If lColIdx < aGrid.FixedCols - 2 Then  ' Value for cols A ... D is for a string
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Font.Bold = True
                        lv_Data(lColIdx) = "'" & aGrid.TextMatrix(lRowIdx, lColIdx + 2)
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).HorizontalAlignment = -4131    'xlLeft
                    Else    ' Value is a number
                        If InStr(1, aGrid.TextMatrix(lRowIdx, lColIdx + 2), "%", vbTextCompare) = 0 Then ' Value
                            If aGrid.TextMatrix(lRowIdx, lColIdx + 2) = "" Then
                                lv_Data(lColIdx) = ""
                            Else
                                lv_Data(lColIdx) = CDbl(aGrid.TextMatrix(lRowIdx, lColIdx + 2))
                                .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).NumberFormat = "#,##0"
                            End If
                        Else    ' % Percent
                            lv_Data(lColIdx) = Replace(aGrid.TextMatrix(lRowIdx, lColIdx + 2), "%", "") / 100
                        End If
                    End If
                    .cells(lIdxExcelRow, lIdxExcelCol + lColIdx + 1).HorizontalAlignment = -4152
                Next
                .Range(.cells(lIdxExcelRow, lIdxExcelCol), .cells(lIdxExcelRow, lIdxExcelCol + UBound(lv_Data))) = lv_Data
            Else
                lRowCount = lRowCount - 1
            End If
            ' if line is total then do line
            If aGrid.TextMatrix(lRowIdx, 0) = "" Then
                'total
                lRangeTopLeft = "D" & (lIdxExcelRow)
                lRangeBottomRight = "H" & (lIdxExcelRow)
                lRange = lRangeTopLeft & ":" & lRangeBottomRight
                .Range(lRange).Interior.ColorIndex = 4 '12
                .Range(lRange).Interior.Pattern = 1
                .Range(lRange).Interior.PatternColorIndex = -4105
                .Range(lRange).Font.Bold = True
                
            ElseIf aGrid.TextMatrix(lRowIdx, 1) = "" And aGrid.TextMatrix(lRowIdx, 4) = "" Then
                ' subtotal
                lRangeTopLeft = "D" & (lIdxExcelRow)
                lRangeBottomRight = "H" & (lIdxExcelRow)
                lRange = lRangeTopLeft & ":" & lRangeBottomRight
                .Range(lRange).Interior.ColorIndex = 6
                .Range(lRange).Interior.Pattern = 1
                .Range(lRange).Interior.PatternColorIndex = -4105
                .Range(lRange).Font.Bold = True
            End If
        Next
        
        
        Call MergeRows(a_ExcelSheet1, 6, lIdxExcelRow, 2)
        Call MergeRows(a_ExcelSheet1, 6, lIdxExcelRow, 1)
'        Call MergeCols(a_ExcelSheet1, 5, lColCount + 1, 6)
        
'        Call MergeRows(a_ExcelSheet1, 6, aGrid.FixedRows + 5, 2)
'        Call MergeRows(a_ExcelSheet1, 6, lIdxExcelRow, 1)
'        Call MergeCols(a_ExcelSheet1, 5, lColCount + 1, 6)
        
        ' TOTAL LINE FORMAT (BOLD)
        For lRowIdx = 0 To lRowCount
            .cells(lIdxExcelRow - lRowIdx, lIdxExcelCol + lColCount - 2).Font.Bold = True
            .cells(lIdxExcelRow - lRowIdx, lIdxExcelCol + 11).Font.Bold = True
        Next
        
        
        ' ADD THE STYLE
        
        lRangeTopLeft = "H7"
        lRangeBottomRight = "H" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).NumberFormat = "0.0%"
        
        ' SET THE GRID
        lRangeTopLeft = "A6"
        lRangeBottomRight = "H" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlInsideVertical).Weight = xlThin
        .Range(lRange).Borders(xlInsideVertical).LineStyle = xlContinuous
        .Range(lRange).Borders(xlInsideHorizontal).Weight = xlThin
        .Range(lRange).Borders(xlInsideHorizontal).LineStyle = xlContinuous
        
        ' SET THE HEADER
        lRangeTopLeft = "A6"
        lRangeBottomRight = "H" & "6"
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeTop).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeTop).Weight = xlThick
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        
        lRangeTopLeft = "A7"
        lRangeBottomRight = "B" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        
        
        ' SET THE EXTERNAL WEIGHT LINE
        ' LEFT
        lRangeTopLeft = "A6"
        lRangeBottomRight = "A" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        
        ' RIGHT
        lRangeTopLeft = "H" & "6"
        lRangeBottomRight = "H" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
        ' BOTTOM
        lRangeTopLeft = "A" & (lRowCount + 6)
        lRangeBottomRight = "H" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
        ' BOTTOM
        lRangeTopLeft = "A" & (lRowCount + 5)
        lRangeBottomRight = "H" & (lRowCount + 5)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
        
        For lRowIdx = aGrid.FixedRows To lRowCount  ' Title line is already processed
            ' if line is total then do line
            If aGrid.TextMatrix(lRowIdx, 1) = "" Then
                ' BOTTOM
                lRangeTopLeft = "A" & (lRowIdx + 6)
                lRangeBottomRight = "H" & (lRowIdx + 6)
                lRange = lRangeTopLeft & ":" & lRangeBottomRight
                .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
                .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
            End If
        Next
        
    End With
    
    With a_ExcelSheet1.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
        .PrintArea = ""
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .PrintHeadings = False
        .PrintGridlines = False
        .CenterHorizontally = True
        .CenterVertically = False
        .Orientation = 1
        .Draft = False
        .BlackAndWhite = False
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = 1
    End With
        
        
    Set a_ExcelSheet1 = Nothing
    Set a_ExcelWorkBook = Nothing
    Set a_ExcelApp = Nothing
    Screen.MousePointer = 0
          
    MsgBox MsgText(108, ms_Language_Code, "#Press ALT+TAB to switch to the Excel application.")
    Exit Sub
    
ErrorHandler:
    If Err.Number = 429 Then
        Set a_ExcelApp = CreateObject("Excel.Application")
        Resume Next
    Else
        If Err.Number = 1004 Then
            'debug.print Err.Description
            Resume Next
        Else
            Screen.MousePointer = 0
            Set a_ExcelApp = Nothing
            Screen.MousePointer = 0
        End If
    End If

    Call ErrorHandler(Extender.Name & ".Export_Grid_Visits2")
End Sub


Private Sub FillGridRowDataEx(ByRef av_Data As Variant, ByRef ao_grid As MSFlexGrid, ByVal al_row As Long, ByVal al_startCol As Long, ByVal al_endCol As Long)
On Error GoTo ErrorHandler
    ReDim av_Data(al_endCol - al_startCol) As Variant
    
    Dim ll_i As Long
    For ll_i = al_startCol To al_endCol
        If isNumeric(ao_grid.TextMatrix(al_row, ll_i)) Then
            av_Data(ll_i - al_startCol) = CDbl(ao_grid.TextMatrix(al_row, ll_i))
        Else
            av_Data(ll_i - al_startCol) = ao_grid.TextMatrix(al_row, ll_i)
        End If
    Next
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".FillGridRowDataEx")
End Sub


Private Sub FillGridRowData(ByRef av_Data As Variant, ByRef ao_grid As MSFlexGrid, ByVal al_row As Long, ByVal al_startCol As Long, ByVal al_endCol As Long)
On Error GoTo ErrorHandler
    ReDim av_Data(al_endCol - al_startCol) As Variant
    
    Dim ll_i As Long
    For ll_i = al_startCol To al_endCol
        av_Data(ll_i - al_startCol) = ao_grid.TextMatrix(al_row, ll_i)
    Next
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".FillGridRowData")
End Sub


Private Sub Export_Grid_Full(ByRef aGrid As MSFlexGrid, ByVal aHeaderColor As Long, ByVal as_reporCaption As String)
On Error GoTo ErrorHandler
    Set a_ExcelApp = GetObject(, "Excel.Application")
    Set a_ExcelWorkBook = a_ExcelApp.Workbooks.Add
    Set a_ExcelSheet1 = a_ExcelWorkBook.Sheets.Add

    a_ExcelWorkBook.Activate
    a_ExcelSheet1.Activate
    
    a_ExcelSheet1.PageSetup.Orientation = 2
    
    a_ExcelApp.ActiveSheet.PageSetup.Zoom = 70

    a_ExcelApp.Application.Visible = -1
    a_ExcelSheet1.Application.Visible = -1
    
    a_ExcelApp.ScreenUpdating = False
    
    With a_ExcelSheet1.cells.Interior
        .ColorIndex = 2
        .Pattern = 1
        .PatternColorIndex = -4105
    End With
    
    
    With a_ExcelSheet1
        .Columns("A").columnWidth = 9
        .Columns("B").columnWidth = 14
        .Columns("C").columnWidth = 10
        .Columns("D").columnWidth = 10
        .Columns("E").columnWidth = 10
        .Columns("F").columnWidth = 10
        .Columns("G").columnWidth = 10
        .Columns("H").columnWidth = 10
        .Columns("I").columnWidth = 10
        .Columns("J").columnWidth = 10
        .Columns("K").columnWidth = 10
        .Columns("L").columnWidth = 10
        .Columns("M").columnWidth = 10
        .Columns("N").columnWidth = 10
        .Columns("O").columnWidth = 13
        .Columns("P").columnWidth = 13
        .Columns("I:I").HorizontalAlignment = xlright
        .Columns("P:P").HorizontalAlignment = xlright
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$salesOption$"
        Debug.Assert (WhichOptionIsSelected(opt_salesOptions) <> -1)
        ms_MsgInfo(0, 1) = opt_salesOptions(WhichOptionIsSelected(opt_salesOptions)).Caption
        .cells(2, 9).Value = GetLabel("ex_reportSales", "#Daily Sales Report ($salesOption$)", ms_MsgInfo)
        .cells(2, 9).Font.Bold = True
        
        .cells(4, 1).Value = as_reporCaption
        .cells(4, 1).Font.Bold = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$NOW$"
        ms_MsgInfo(0, 1) = Format(Now, "dd/mm/yy hh:mm:ss")
        .cells(2, 16).Value = GetLabel("ex_created", "#Created $NOW$", ms_MsgInfo)
        .cells(2, 16).Font.Italic = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$CB_TRW$"
        ms_MsgInfo(0, 1) = cb_trw.Text
        .cells(3, 16) = GetLabel("ex_trw", "#Treeview Info: $CB_TRW$", ms_MsgInfo)
        .cells(3, 16).Font.Italic = True
        .cells(3, 16).Font.Size = 8

        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$TRW_PATH$"
        ms_MsgInfo(0, 1) = TreeviewPath
        .cells(4, 16) = GetLabel("ex_trw_path", "#Treeview Path: $TRW_PATH$", ms_MsgInfo)
        .cells(4, 16).Font.Italic = True
        .cells(4, 16).Font.Size = 8
    End With
    
    
    Dim lIdxExcelRow As Long, lIdxExcelCol As Long
    Dim lRowIdx As Long, lRowCount As Long
    Dim lColIdx As Long, lColCount As Long
    
    lRowCount = aGrid.Rows - 1
    lColCount = aGrid.Cols - 1
    
    lIdxExcelCol = 1
    lIdxExcelRow = 5
    

    With a_ExcelSheet1
        ' HEADER OF THE GRID
        ' Set the first column title and format
        lIdxExcelRow = lIdxExcelRow + 1
        
        ' Set the font format and the data Header of the grid
        Dim ls_lastHeaderText As String
        ls_lastHeaderText = ""
        For lColIdx = 0 To lColCount ' first col is already done
            .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Font.Bold = True
            .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).HorizontalAlignment = -4108
            If ls_lastHeaderText <> Trim(aGrid.TextMatrix(0, lColIdx)) Then
                ls_lastHeaderText = Trim(aGrid.TextMatrix(0, lColIdx))
                .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = ls_lastHeaderText
            Else
                .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = ""
            End If
        Next
        
        Dim lv_Data As Variant
        
        ' CONTENTS
        For lRowIdx = 1 To lRowCount  ' Title line is already processed
            lIdxExcelRow = lIdxExcelRow + 1
            
            Call FillGridRowDataEx(lv_Data, aGrid, lRowIdx, 0, lColCount)
            .Range(.cells(lIdxExcelRow, lIdxExcelCol), .cells(lIdxExcelRow, lIdxExcelCol + UBound(lv_Data))) = lv_Data
            ' format numbers
            .Range(.cells(lIdxExcelRow, lIdxExcelCol), .cells(lIdxExcelRow, lIdxExcelCol + UBound(lv_Data))).NumberFormat = "#,##0"
            
            If InStr(1, lv_Data(UBound(lv_Data) - 1), "%", vbTextCompare) <> 0 Then
                .cells(lIdxExcelRow, 15).NumberFormat = "0.0%"
            End If
        Next
        
        ' header
        .Range(.cells(7, 1), .cells(lIdxExcelRow, 2)).Font.Bold = True
        
        .Range(.cells(7, 3), .cells(lIdxExcelRow, lColCount + 2)).HorizontalAlignment = xlright
         
        ' merge headers
        With .Range("A6:B6")
            .VerticalAlignment = -4108  'xlCenter
            .MergeCells = True
        End With
        
        Call MergeRows(a_ExcelSheet1, 7, lIdxExcelRow, 1)
        
        ' TOTAL LINE FORMAT (BOLD)
        .Range(.cells(7, 15), .cells(lIdxExcelRow, 16)).Font.Bold = True
        .Range(.cells(lIdxExcelRow - 1, 3), .cells(lIdxExcelRow, 14)).Font.Bold = True

        
        ' ADD THE STYLE
        Dim lRangeTopLeft As String, lRangeBottomRight As String, lRange As String
        
        ' SET THE GRID
        lRangeTopLeft = "A6"
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlInsideVertical).Weight = xlThin
        .Range(lRange).Borders(xlInsideVertical).LineStyle = xlContinuous
        .Range(lRange).Borders(xlInsideHorizontal).Weight = xlThin
        .Range(lRange).Borders(xlInsideHorizontal).LineStyle = xlContinuous
        
        ' SET THE HEADER
        lRangeTopLeft = "A6"
        lRangeBottomRight = Chr(65 + lColCount) & "6"
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeTop).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeTop).Weight = xlThick
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        
        lRangeTopLeft = "A7"
        lRangeBottomRight = "B" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        
        
        ' SET THE TOTAL
        lRangeTopLeft = "O6"
        lRangeBottomRight = "O" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
        ' SET THE EXTERNAL WEIGHT LINE
        ' LEFT
        lRangeTopLeft = "A6"
        lRangeBottomRight = "A" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        
        ' RIGHT
        lRangeTopLeft = Chr(65 + lColCount) & "6"
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
        ' BOTTOM
        lRangeTopLeft = "A" & (lRowCount + 6)
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
        ' TOTAL at BOTTOM
        lRangeTopLeft = "A" & (lRowCount + 4)
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 4)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
    End With
    
    With a_ExcelSheet1.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
        .PrintArea = ""
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .PrintHeadings = False
        .PrintGridlines = False
        .CenterHorizontally = True
        .CenterVertically = False
        .Orientation = 1
        .Draft = False
        .BlackAndWhite = False
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = 100
    End With
        
    a_ExcelApp.ScreenUpdating = True

    Set a_ExcelSheet1 = Nothing
    Set a_ExcelWorkBook = Nothing
    Set a_ExcelApp = Nothing
    Screen.MousePointer = 0
          
    MsgBox MsgText(108, ms_Language_Code, "#Press ALT+TAB to switch to the Excel application.")
    Exit Sub
    
ErrorHandler:
    If Err.Number = 429 Then
        Set a_ExcelApp = CreateObject("Excel.Application")
        Resume Next
    Else
        If Err.Number = 1004 Then
            'debug.print Err.Description
            Resume Next
        Else
            Screen.MousePointer = 0
            If Not a_ExcelApp Is Nothing Then
                a_ExcelApp.ScreenUpdating = True
            End If
            Set a_ExcelApp = Nothing
            Screen.MousePointer = 0
        End If
    End If

    Call ErrorHandler(Extender.Name & ".Export_Grid_Full")
End Sub

Private Sub MergeRows(ByRef ao_Sheet As Object, ByVal al_StartRow As Long, ByVal al_EndRow As Long, ByVal al_Col As Long)
On Error GoTo ErrorHandler
    Dim lv_prevVal As Variant
    Dim ll_mergeStartRow As Long
    ll_mergeStartRow = al_StartRow
    lv_prevVal = Empty
    With ao_Sheet
        While al_StartRow <= al_EndRow
            If lv_prevVal <> .cells(al_StartRow, al_Col).Value Then
                If al_StartRow - ll_mergeStartRow > 1 Then
                    ' do merge
                    With .Range(Chr(64 + al_Col) & ll_mergeStartRow & ":" & Chr(64 + al_Col) & al_StartRow - 1)
                        .VerticalAlignment = -4108      'xlCenter
                        .MergeCells = True
                        .WrapText = True
                    End With
                End If
                lv_prevVal = .cells(al_StartRow, al_Col).Value
                ll_mergeStartRow = al_StartRow
            Else
                .cells(al_StartRow, al_Col).Value = ""
            End If
            al_StartRow = al_StartRow + 1
        Wend
        If al_StartRow - ll_mergeStartRow > 1 Then
            ' do merge
            With .Range(Chr(64 + al_Col) & ll_mergeStartRow & ":" & Chr(64 + al_Col) & al_StartRow - 1)
                .VerticalAlignment = -4108  'xlCenter
                .MergeCells = True
            End With
        End If
    End With
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".MergeRows")
End Sub

Private Sub MergeCols(ByRef ao_Sheet As Object, ByVal al_startCol As Long, ByVal al_endCol As Long, ByVal al_row As Long)
On Error GoTo ErrorHandler
    Dim lv_prevVal As Variant
    Dim ll_mergeStartCol As Long
    ll_mergeStartCol = al_startCol
    lv_prevVal = Empty
    With ao_Sheet
        While al_startCol <= al_endCol
            If lv_prevVal <> .cells(al_row, al_startCol).Value Then
                If al_startCol - ll_mergeStartCol > 1 Then
                    ' do merge
                    With .Range(.cells(al_row, ll_mergeStartCol), .cells(al_row, al_startCol - 1))
                        .VerticalAlignment = -4108      'xlCenter
                        .MergeCells = True
                    End With
                End If
                lv_prevVal = .cells(al_row, al_startCol).Value
                ll_mergeStartCol = al_startCol
            Else
                .cells(al_row, al_startCol).Value = ""
            End If
            al_startCol = al_startCol + 1
        Wend
        If al_startCol - ll_mergeStartCol > 1 Then
            ' do merge
            With .Range(.cells(al_row, ll_mergeStartCol), .cells(al_row, al_startCol - 1))
                .VerticalAlignment = -4108      'xlCenter
                .MergeCells = True
            End With
        End If
    End With
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".MergeCols")
End Sub


Private Sub load_treeview(ByVal aTypeOfTreeview As ECapReportingTreeview)
On Error GoTo ErrorHandler
    
    Set tv1.ArmDb = p_da
    tv1.Clear
    
    ReDim mTreeViewInfos(0)

    Call LoadTreeView(tv1, GetTreeViewInfo(mTreeViewInfos, SCREEN_NAME, "tv" & aTypeOfTreeview))
    If tv1.Count > 0 Then
        tv1.Nodes(1).Selected = -1
    End If
    Call tv1_Click
    Call tv1_NodeClick(tv1.SelectedItem)
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".load_treeview")
End Sub

Private Function LoadTreeView(ByRef aTV As ArmTreeView, ByRef aTreeViewInfo As TTreeViewInfo, Optional ByRef aGrid As ArmGrid = Nothing) As Boolean
On Error GoTo ErrorHandler

    aTV.Clear
    
    Dim lsa_NodeRequest() As String
    lsa_NodeRequest = aTreeViewInfo.NodeRequest
    lsa_NodeRequest(aTreeViewInfo.Levels - 1) = Replace(lsa_NodeRequest(aTreeViewInfo.Levels - 1), "$EXC$", IIf(opt_excReps(1).Value, "N", "Y"), , , vbTextCompare)
    Dim ll_i As Long
    For ll_i = LBound(lsa_NodeRequest) To UBound(lsa_NodeRequest)
        lsa_NodeRequest(ll_i) = Replace(lsa_NodeRequest(ll_i), "$Language_code$", ms_Language_Code, , , vbTextCompare)
    Next

    aTV.Levels = aTreeViewInfo.Levels
    aTV.StartDemandLevel = 1
    aTV.SelectedImages = aTreeViewInfo.SelectedImages
    aTV.Images = aTreeViewInfo.Images
    aTV.NodeRequests = lsa_NodeRequest
    
    
    If Not aTV.LoadTree(LoadTypeChildsDemand) Then
        'ERROR
        LoadTreeView = False
    End If
    
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".LoadTreeView")
End Function

Private Function GetTreeViewInfo(ByRef aTVInfos() As TTreeViewInfo, ByVal AScreenName As String, ByVal aTVCode As String) As TTreeViewInfo
On Error GoTo ErrorHandler
    Dim lIdx As Long, lCount As Long
    Dim lTreeView As TTreeViewInfo, lFound As Boolean
    
    ' Search in the array
'    lCount = UBound(aTVInfos)
'    lFound = False
'    For lIdx = 0 To lCount
'        If aTVInfos(lIdx).TreeViewCode = aTVCode Then
'            aTVInfos(lIdx).Loaded = False
'            If Not aTVInfos(lIdx).Loaded Then
                aTVInfos(0) = GetTreeViewInfoFromDB(AScreenName, aTVCode)
'            End If
            lTreeView = aTVInfos(0)
'            lFound = True
'            Exit For
'        End If
'    Next
    
    If Not lFound Then
        'ERROR
    End If
    
    GetTreeViewInfo = lTreeView
    
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetTreeViewInfo")
End Function

Private Function GetTreeViewInfoFromDB(ByVal AScreenName As String, ByVal aTVCode As String) As TTreeViewInfo
On Error GoTo ErrorHandler
    Dim lTreeView As TTreeViewInfo
    Dim lRequest As String
    Dim lCurs As Long, lIdx As Long, lCount As Long
    
    ' Get the data from the DB
    lRequest = "EXEC Treeview_Parameters_lst '" & AScreenName & "', '" & aTVCode & "'"
    lCurs = OpenSQLSafe(p_da, lRequest)
    
    lCount = p_da.RowCount(lCurs) - 1
    
    If lCount = -1 Then
        'debug.print "ERROR GetTreeViewInfoFromDB"
    End If
    
    ReDim lTreeView.NodeRequest(lCount)
    ReDim lTreeView.GridRequest(lCount)
    ReDim lTreeView.ExcelRequest(lCount)
    ReDim lTreeView.FindRequest(lCount)
    ReDim lTreeView.CountRequest(lCount)
    ReDim lTreeView.Images(lCount)
    ReDim lTreeView.SelectedImages(lCount)
    ReDim ms_TheGridRequestsByLevel(lCount)
    
    Dim lLevel As Long
    For lIdx = 0 To lCount
        lLevel = p_da.GetFields(lCurs, "TV_Level")
        lTreeView.NodeRequest(lLevel) = p_da.GetFields(lCurs, "TV_NodeRequest")
        ms_TheGridRequestsByLevel(lLevel) = p_da.GetFields(lCurs, "TV_GridRequest")
        lTreeView.Images(lLevel) = p_da.GetFields(lCurs, "TV_Images")
        lTreeView.SelectedImages(lLevel) = p_da.GetFields(lCurs, "TV_SelectedImages")
        p_da.Next (lCurs)
    Next
    
    lTreeView.TreeViewCode = aTVCode
    lTreeView.Levels = lCount + 1
    lTreeView.Loaded = True
    GetTreeViewInfoFromDB = lTreeView
    
    Call p_da.Close(lCurs)
    Exit Function
    
ErrorHandler:
    If lCurs > 0 Then
        Call p_da.Close(lCurs)
        lCurs = 0
    End If
    Call ErrorHandler(Extender.Name & ".GetTreeViewInfoFromDB")
End Function

Private Sub load_combo_trw()
On Error GoTo ErrorHandler

'cb_trw.Left = 120
'cb_trw.Top = 3000

    cb_trw.Load_A_Com
    Set cb_trw.ArmDb = p_da
    cb_trw.Request = "SELECT TV_Order+1 as TV_code, TV_Desc, TV_Default FROM TREEVIEW_VIEW WHERE TV_Module = 'Capture_Reporting' AND Language_code='" & ms_Language_Code & "' ORDER BY TV_Order"
    
    '"select trw_code, trw_desc from cap_rpt_trw_model order by trw_code"
    cb_trw.Load
    
    ' TODO : REMOVE LINE FROM LIVE!!!! (JN)
    'Call cb_trw.AddItem(Array(creMarketCust, "Europe, Markets, Countries, Type, Buying Customer"))

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


Private Sub load_treeview_replic(ByVal choix As Byte)
On Error GoTo ErrorHandler

    Set tv_replic.ArmDb = p_da
   
    tv_replic.UseImages = True
    
    Select Case choix
    Case 1
        tv_replic.Levels = 3
        tv_replic.Images = Array(1, 1, 1)
        tv_replic.SelectedImages = Array(2, 2, 2)
        tv_replic.NodeRequests = Array("cap_replic_trw_week")
    Case 2
        tv_replic.Levels = 3
        tv_replic.Images = Array(1, 1, 1)
        tv_replic.SelectedImages = Array(2, 2, 2)
        tv_replic.NodeRequests = Array("cap_replic_trw_month")
    Case 3
        tv_replic.Levels = 2
        tv_replic.Images = Array(1, 1)
        tv_replic.SelectedImages = Array(2, 2)
        tv_replic.NodeRequests = Array("cap_replic_trw_user")
    End Select
    Call tv_replic.LoadTree(LoadTypeTree)
    
    If tv_replic.Count > 0 Then
        tv_replic.Nodes(1).Selected = -1
    End If

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


Private Sub annee_ComboItemSelected()
On Error GoTo ErrorHandler

    If annee.Text <> annee_selected Then
        annee_selected = annee.Text
        reinit_display
    End If
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".annee_ComboItemSelected")
End Sub

Private Sub cal1_datechangee()
On Error GoTo ErrorHandler

    If cal1.date_dt() > cal2.date_dt() Then
        MsgBox MsgText(1514, ms_Language_Code, "#Starting Date cannot be after Ending Date of a period!")
        cal1.date_courte = old_cal1
        Exit Sub
    End If
    If current_cal1 <> cal1.date_courte Then
        reinit_display
    End If
    
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".cal1_datechangee")
End Sub

Private Sub cal1_LostFocus()
On Error GoTo ErrorHandler

    If old_cal1 <> cal1.date_courte Then
        reinit_display
        ' reset total counters
        If ml_proj3Counts <> 0 Then Call p_da.Close(ml_proj3Counts)
        ml_proj3Counts = 0
    End If
    old_cal1 = cal1.date_courte
    
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".cal1_LostFocus")
End Sub

Private Sub cal2_datechangee()
On Error GoTo ErrorHandler

    If Not TabStrip1.SelectedItem Is Nothing Then
        If TabStrip1.SelectedItem.Key <> "VISIT" Then
            If cal2.date_dt() < cal1.date_dt() Then
                MsgBox MsgText(1515, ms_Language_Code, "#Ending Date cannot be before Starting Date of a period!")
                cal2.date_courte = old_cal2
                Exit Sub
            End If
        Else
            If cal2.date_dt() < cal1.date_dt() Then
                cal1.date_courte = cal2.date_courte
                old_cal1 = cal1.date_courte
            End If
        End If
    End If

    If current_cal2 <> cal2.date_courte Then
        reinit_display
    End If
    
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".cal2_datechangee")
End Sub

Private Sub cal2_LostFocus()
On Error GoTo ErrorHandler

    If old_cal2 <> cal2.date_courte Then
        reinit_display
        ' reset total counters
        If ml_proj3Counts <> 0 Then Call p_da.Close(ml_proj3Counts)
        ml_proj3Counts = 0
    End If
    
    old_cal2 = cal2.date_courte
    
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".cal2_LostFocus")
End Sub

Private Sub export_report_Click()
On Error GoTo ErrorHandler
    
    If TabStrip1.SelectedItem Is Nothing Then Exit Sub
    
    Select Case TabStrip1.SelectedItem.Key
    Case "REPORT"
        export_to_excel
    Case "QUERY"
        Call grd_Query.ExportToExcel
'    Case "VISIT"
'        Dim ll_grdindex As Long
'        ll_grdindex = tbs_visitCTType.SelectedItem.Index - 1
'        Call grd_visitCounts(ll_grdindex).ExportToExcel
'        Call grd_visitDetail(ll_grdindex).ExportToExcel
    Case "VISIT2"
        Call Export_Grid_Visits2(grd_visits2, 15, frm_visits2.Caption)
    Case "PROJ"
        Call GRD_ExcelExport(grd_project((tbs_ProjectType.SelectedItem.Index - 1) * 2 + tbs_project.SelectedItem.Index - 1), mo_projectInfo((tbs_ProjectType.SelectedItem.Index - 1) * 2 + tbs_project.SelectedItem.Index - 1), frm_projects.Caption, Array(1, 4))
    Case "SALES"
        Select Case tbs_sales.SelectedItem.Key
        Case "ALL"
            Call Export_Grid_Full(grd_Sales, 15, frm_sales.Caption)
        Case "MSA"
            Call Export_Grid_Full(grd_sales_MSA, 15, frm_sales.Caption)
        End Select
    Case "SALES_REP"
        Call GRD_ExcelExport(grd_sales_rep, mo_SalesRepInfo, frm_sales_rep.Caption, Array())
    Case "TOP10PROJ"
        Call GRD_ExcelExport(grd_top10Projects, mo_top10ProjectsInfo, frm_top10projects.Caption, Array(0, 4, 1, 6))
    Case "TOP10PROJE"
        Call GRD_ExcelExport(grd_top10ProjectsE, mo_top10ProjectsEInfo, frm_top10projectsE.Caption, Array(0, 4, 1, 6))
'    Case "STATUSPROJ"
'        Call Export_Grid_StatPrj(grd_StatusProjects, 15, frm_statusProjects.Caption)
    Case "STATUSPROJ2"
        Call Export_Grid_StatPrj2(grd_StatusProjects2, 15, frm_statusProjects2.Caption)
    Case "STATUSPROJ3"
        Call Export_Grid_StatPrj3(grd_StatusProjects3, 15, frm_statusProjects3.Caption)
    End Select

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

Private Sub mois_ComboItemSelected()
On Error GoTo ErrorHandler

    If Mois.Text <> mois_selected Then
        mois_selected = Mois.Text
        If Mois.SelectedItem.Key >= 14 Then
            chk_YTD.Value = 1
        End If
        reinit_display
    End If

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

Private Sub tab_prd_Click()
On Error GoTo ErrorHandler

    If tab_selected <> (tab_prd.SelectedItem.Index) Then reinit_display
    tab_selected = tab_prd.SelectedItem.Index

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

Private Function insert_date_in_sql(ByVal REQ As String) As String
On Error GoTo ErrorHandler
        
    insert_date_in_sql = Replace(REQ, "date1", "'" & cal1.date_us & "'")
    insert_date_in_sql = Replace(insert_date_in_sql, "date2", "'" & cal2.date_us & "'")

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

Public Sub Unload_A_Com()
On Error GoTo ErrorHandler
    
    Call gr_replic.Unload_A_Com
    Call grd_Views.Unload_A_Com
    Call cbo_Views.Unload_A_Com
    Call grd_Query.Unload_A_Com
    Call grd_visitDetail(0).Unload_A_Com
    Call grd_visitDetail(1).Unload_A_Com
    Call grd_visitDetail(2).Unload_A_Com
    Call grd_visitCounts(0).Unload_A_Com
    Call grd_visitCounts(1).Unload_A_Com
    Call grd_visitCounts(2).Unload_A_Com
    
    Call cbo_Query.Unload_A_Com
    Call cb_trw.Unload_A_Com
    Call Mois.Unload_A_Com
    Call annee.Unload_A_Com
    
    Call tv1.Unload_A_Com
    Call tv_replic.Unload_A_Com
    
    If mc_ScreenLabels <> 0 Then p_da.Close (mc_ScreenLabels)
    mc_ScreenLabels = 0
    
    If ml_projCounts <> 0 Then p_da.Close (ml_projCounts)
    ml_projCounts = 0
    If ml_proj3Counts <> 0 Then p_da.Close (ml_proj3Counts)
    ml_proj3Counts = 0

    Set p_da = Nothing
    mb_Initialized = False
    Exit Sub
    
ErrorHandler:
    Call LogMessage(App.ProductName & " exception raised. Err.Number:" & Err.Number & ", Err.Source:Unload_A_Com" & SEP1 & Err.Source & ", Err.Description " & Err.Description & ".", "E", False)
End Sub

Private Function check_authorization() As Boolean
On Error GoTo ErrorHandler

    Dim ll_cursor   As Long
    Dim ls_req      As String

    check_authorization = False
    ls_req = "SELECT 1 FROM Cap_Rep_Login WHERE Login_Name = '" & gsuser & "'"
    ll_cursor = OpenSQLSafe(p_da, ls_req)
    If p_da.RowCount(ll_cursor) > 0 Then
        check_authorization = True
    End If
    Call p_da.Close(ll_cursor)

    Exit Function
    
ErrorHandler:
    If ll_cursor > 0 Then
        Call p_da.Close(ll_cursor)
        ll_cursor = 0
    End If
    Call ErrorHandler(Extender.Name & ".check_authorization")
End Function

Private Sub load_gr_replic(ByVal ls_req As String, ByVal cas As String)
On Error GoTo ErrorHandler

    Select Case cas
    Case 1
        Call gr_replic.SetColumns(Array( _
        Join(Array("replic_id1", 2000, 1, "login_name", ""), SEP), _
        Join(Array("Sequence_id1", 2000, 0, "nb_replic", ""), SEP)))
        Call gr_replic.LoadConstants(ptStatic, GetLabel("gr_replic_1", _
        Join(Array("#User", "#Number of Replication"), SEP)), ctColumns)
    Case 2
        Call gr_replic.SetColumns(Array( _
        Join(Array("replic_id1", 2000, 1, "login_name", ""), SEP), _
        Join(Array("Sequence_id1", 2000, 0, "nb_replic", ""), SEP)))
        Call gr_replic.LoadConstants(ptStatic, GetLabel("gr_replic_1", _
        Join(Array("#User", "#Number of Replication"), SEP)), ctColumns)
    Case 3
        Call gr_replic.SetColumns(Array( _
        Join(Array("Replication Date", 2000, 1, "server_record_date", ""), SEP), _
        Join(Array("Download Duration", 2000, 1, "time_download", "", "", "0.00"), SEP), _
        Join(Array("Total Duration", 2000, 1, "time_mn", "", "", "0.00"), SEP), _
        Join(Array("Replication Type", 2000, 1, "replic_submitted", ""), SEP)))
        Call gr_replic.LoadConstants(ptStatic, GetLabel("gr_replic_3_Title", "#Replication Type: A =Full, N=Normal" & SEP & "Left"), ctTopGrid)
        Call gr_replic.LoadConstants(ptStatic, GetLabel("gr_replic_3", _
        Join(Array("#Replication Date", "#Download Duration", "#Total Duration", "#Replication Type"), SEP)), ctColumns)
    End Select
    Call gr_replic.Load(Array(ls_req), True, 100)
 
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".load_gr_replic")
End Sub

Private Sub Fill_Views()
On Error GoTo ErrorHandler

    cbo_Views.Request = "EXEC Cap_Rpt_ViewRights_Lst2 '" & gsuser & "', '" & ms_Language_Code & "'"
    Call cbo_Views.Load
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".Fill_Views")
End Sub

Private Sub cbo_Views_ComboItemSelected()
On Error GoTo ErrorHandler
    Dim la_Columns() As String
    Dim i As Integer
    
    Dim lv_Key As Variant
    Dim ls_Cols() As String
    Dim ls_Size() As String
    Dim ls_SP_Name As String
    
    ' Devrait normalement être cbo_Views.ListIndex...
    
    If Not (cbo_Views.SelectedItem Is Nothing) Then
        Debug.Assert (Not TabStrip1.SelectedItem Is Nothing)
        Call AddRptLog(gsuser, TabStrip1.SelectedItem.Caption)
        
        grd_Views.ResetGrid
        grd_Views.Title = cbo_Views.SelectedItem.DisplayText  'ms_Views(0, li_Index)
        
        lv_Key = cbo_Views.SelectedItem.Key
        grd_Views.FetchAll = (cbo_Views.GetItemData(lv_Key, "Fetch_all") = "X")
        ls_Cols = Split(cbo_Views.GetItemData(lv_Key, "Col_Titles"), SEP)
        ls_Size = Split(cbo_Views.GetItemData(lv_Key, "Col_Size"), SEP)
        ls_SP_Name = cbo_Views.GetItemData(lv_Key, "SP_Name")
        
        ReDim la_Columns(UBound(ls_Cols))
        For i = 0 To UBound(la_Columns)
            la_Columns(i) = "COL" & i & SEP & ls_Size(i) & SEP & "0" & SEP & ls_Cols(i) & SEP & "COL" & i & SEP & "string"
        Next i
        
        grd_Views.SetColumns la_Columns
        grd_Views.LoadConstants ptStatic, Join(ls_Cols, SEP), ctColumns
        
        '   Correct the bug of newsletter cis but need to be approved
        Select Case ls_SP_Name
            Case "Newsletter_SMCIS", "Newsletter_SMCE", "Newsletter"
        
                Dim l_Idx As Long, l_Count As Long, l_Curs As Long
                Dim l_fIdx As Long, l_fCount As Long
        
                l_Curs = OpenSQLSafe(p_da, ls_SP_Name)
        
                l_Count = p_da.RowCount(l_Curs)
                l_Count = p_da.RowCount(l_Curs)
                l_fCount = UBound(la_Columns)
        
                Dim l_CodePage As Long
                grd_Views.Font.Name = "Arial"
                Select Case ls_SP_Name
                    Case "Newsletter_SMCIS"
                        l_CodePage = 1251
                    Case "Newsletter_SMCE"
                        l_CodePage = 1250
                End Select
        
                grd_Views.Font.Charset = GetCharSetFromCodePage(l_CodePage)
                grd_Views.LocalID = GetLCIDFromCodePage(l_CodePage)
        
                grd_Views.Rows = l_Count
        
                For l_Idx = 0 To l_Count
                    For l_fIdx = 0 To l_fCount
                        grd_Views.Data(l_Idx, l_fIdx) = ConvertCodePageFromUnicode(p_da.GetFields(l_Curs, l_fIdx), l_CodePage)
                    Next
                    p_da.Next (l_Curs)
                Next
                grd_Views.LastLine
                grd_Views.FirstLine
        
                Call p_da.Close(l_Curs)
                l_Curs = 0
        
            Case Else
                grd_Views.Requests = ls_SP_Name 'ms_Views(1, li_Index)
                grd_Views.Execute
        End Select
    End If
    Exit Sub
    
ErrorHandler:
    If l_Curs > 0 Then
        Call p_da.Close(l_Curs)
        l_Curs = 0
    End If
    Call ErrorMessage(Extender.Name & ".cbo_Views_ComboItemSelected")
End Sub

Private Sub cbo_Query_ComboItemSelected()
On Error GoTo ErrorHandler

    ' UPDATE explanation(2)
    lbl_Explanation.Caption = cbo_Query.SelectedItem.GetData(2)
        
    ' Update grids, clear and load labels (3)
    Call grd_Query.ClearGrid
    ' Load the labels
    grd_Query.SetColumns (Split(cbo_Query.SelectedItem.GetData(4), "®©®©"))
    grd_Query.Title = cbo_Query.SelectedItem.DisplayText
    
    export_report.Visible = False
    btn_RefreshReport.Visible = False
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".cbo_Query_ComboItemSelected")
End Sub


Private Function ReplaceHolders(ByVal aReq As String) As String
On Error GoTo ErrorHandler

    Dim lReq As String, lRar_Code As String, lmkt_Code As String, lct_Code As String, lz_Creator As String, lcg_Code As String
    Dim lsbm_code As String, lyear As String, lmonth As String, lytd As String
    Dim ls_CCT_Code As String, ls_CCU_Capkey As String
    
    ' Treeview level
    lRar_Code = "null"
    lmkt_Code = "null"
    lct_Code = "null"
    lz_Creator = "null"
    ls_CCT_Code = "null"
    ls_CCU_Capkey = "null"
    
    Select Case cb_trw.SelectedItem.GetData(0)
        Case 1  ' Market
            lRar_Code = "null"
            Select Case Level_selected
                Case 0  ' All markets
                    ' Nothing to do
                Case 1  ' Market
                    lmkt_Code = "'" & tv1.NodeInfo(tv1.SelectedItem).GetData(0) & "'"
                Case 2  ' Country
                    lmkt_Code = "'" & tv1.NodeInfo(tv1.SelectedItem.Parent).GetData(0) & "'"
                    lct_Code = "'" & tv1.NodeInfo(tv1.SelectedItem).GetData(0) & "'"
                Case 3  ' User
                    lmkt_Code = "'" & tv1.NodeInfo(tv1.SelectedItem.Parent.Parent).GetData(0) & "'"
                    lct_Code = "'" & tv1.NodeInfo(tv1.SelectedItem.Parent).GetData(0) & "'"
                    lz_Creator = "'" & Trim(tv1.NodeInfo(tv1.SelectedItem).GetData(2)) & "'"
                    
            End Select
            
        Case 2  ' Area
            Select Case Level_selected
                Case 1  ' Area
                    lRar_Code = tv1.NodeInfo(tv1.SelectedItem).GetData(0)
                Case 3  ' z_creator
                    lRar_Code = tv1.NodeInfo(tv1.SelectedItem.Parent).GetData(0)
                    lz_Creator = "'" & Trim(tv1.NodeInfo(tv1.SelectedItem).GetData(2)) & "'"
            End Select
            
        Case 3
            lRar_Code = "null"
            Select Case Level_selected
                Case 0  ' All markets
                    ' Nothing to do
                Case 1  ' Market
                    lmkt_Code = "'" & tv1.NodeInfo(tv1.SelectedItem).GetData(0) & "'"
                Case 3  ' Country
                    lmkt_Code = "'" & tv1.NodeInfo(tv1.SelectedItem.Parent).GetData(0) & "'"
                    lct_Code = "null"
                    lz_Creator = "'" & Trim(tv1.NodeInfo(tv1.SelectedItem).GetData(2)) & "'"
            End Select
        Case 4  ' Area2
            Select Case Level_selected
                Case 1  ' Market
                    lmkt_Code = "'" & tv1.NodeInfo(tv1.SelectedItem).GetData(0) & "'"
                Case 2  ' Area
                    lmkt_Code = "'" & tv1.NodeInfo(tv1.SelectedItem.Parent).GetData(0) & "'"
                    lRar_Code = tv1.NodeInfo(tv1.SelectedItem).GetData(0)
                Case 3  ' z_creator
                    lmkt_Code = "'" & tv1.NodeInfo(tv1.SelectedItem.Parent.Parent).GetData(0) & "'"
                    lRar_Code = tv1.NodeInfo(tv1.SelectedItem.Parent).GetData(0)
                    lz_Creator = "'" & Trim(tv1.NodeInfo(tv1.SelectedItem).GetData(2)) & "'"
            End Select
        Case 5  ' Market ... Customer
            lRar_Code = "null"
            Select Case Level_selected
                Case 0  ' All markets
                    ' Nothing to do
                Case 1  ' Market
                    lmkt_Code = "'" & tv1.NodeInfo(tv1.SelectedItem).GetData(0) & "'"
                Case 2  ' Country
                    lmkt_Code = "'" & tv1.NodeInfo(tv1.SelectedItem.Parent).GetData(0) & "'"
                    lct_Code = "'" & tv1.NodeInfo(tv1.SelectedItem).GetData(0) & "'"
                Case 3  ' Type
                    lmkt_Code = "'" & tv1.NodeInfo(tv1.SelectedItem.Parent.Parent).GetData(0) & "'"
                    lct_Code = "'" & tv1.NodeInfo(tv1.SelectedItem.Parent).GetData(0) & "'"
                    ls_CCT_Code = "'" & tv1.NodeInfo(tv1.SelectedItem).GetData(0) & "'"
                Case 4  ' Customer
                    lmkt_Code = "'" & tv1.NodeInfo(tv1.SelectedItem.Parent.Parent.Parent).GetData(0) & "'"
                    lct_Code = "'" & tv1.NodeInfo(tv1.SelectedItem.Parent.Parent).GetData(0) & "'"
                    ls_CCT_Code = "'" & tv1.NodeInfo(tv1.SelectedItem.Parent).GetData(0) & "'"
                    ls_CCU_Capkey = "'" & tv1.NodeInfo(tv1.SelectedItem).GetData(0) & "'"
            End Select
    End Select
    
    ' Filters
    lcg_Code = "null"
    lsbm_code = "null"
    Select Case tab_selected
        Case 1  ' Mineral
            lcg_Code = "'c001'"
            lsbm_code = "M001"
        Case 2  ' Soft
            lcg_Code = "'c001'"
            lsbm_code = "M002"
        Case 3  ' Metal
            lcg_Code = "'c001'"
            lsbm_code = "M003"
        Case 4  ' C001
            lcg_Code = "'c001'"
        Case 5  ' C002
            lcg_Code = "'c002'"
    End Select
    
    lyear = IIf(annee.Text <> "", annee.Text, "null")
    lmonth = IIf(Mois.Text <> "", Mois.SelectedItem.Key, "null")
    'lmonth = IIf(Mois.Text <> "", Mois.Text, "null")
    lytd = IIf(chk_YTD.Value, "y", "''")
    
    lReq = Replace(aReq, "$date1$", cal1.date_us, , , vbTextCompare)
    lReq = Replace(lReq, "$date2$", cal2.date_us, , , vbTextCompare)
    lReq = Replace(lReq, "$rar_code$", lRar_Code, , , vbTextCompare)
    lReq = Replace(lReq, "$mkt_code$", lmkt_Code, , , vbTextCompare)
    lReq = Replace(lReq, "$cct_code$", ls_CCT_Code, , , vbTextCompare)
    lReq = Replace(lReq, "$ccu_capkey$", ls_CCU_Capkey, , , vbTextCompare)
    
    lReq = Replace(lReq, "'$ct_code$'", lct_Code, , , vbTextCompare)
    
    lReq = Replace(lReq, "$ct_code$", lct_Code, , , vbTextCompare)
    lReq = Replace(lReq, "$z_creator$", lz_Creator, , , vbTextCompare)
    lReq = Replace(lReq, "$cg_code$", lcg_Code, , , vbTextCompare)
    lReq = Replace(lReq, "$sbm_code$", lsbm_code, , , vbTextCompare)
    lReq = Replace(lReq, "$year$", lyear, , , vbTextCompare)
    lReq = Replace(lReq, "$month$", lmonth, , , vbTextCompare)
    lReq = Replace(lReq, "$ytd$", lytd, , , vbTextCompare)

    lReq = Replace(lReq, "$language_code$", ms_Language_Code, , , vbTextCompare)

    lReq = Replace(lReq, "'$bmk_code$'", lmkt_Code, , , vbTextCompare)
    lReq = Replace(lReq, "'$Login_Name$'", lz_Creator, , , vbTextCompare)
    
    lReq = Replace(lReq, "$AS_FLAG$", IIf(opt_salesOptions(0).Value, "NULL", IIf(opt_salesOptions(1).Value, "'X'", "''")), , , vbTextCompare)

    ReplaceHolders = lReq
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".ReplaceHolders")
End Function

' NOT FINISH YET
' MISSING : Errors managing
' Percent is always the last col
' Budget is always the before last col
' Percent always calculated with last value column
' aReqValue must be an array !
Private Sub FillGrid(ByRef aGrid As MSFlexGrid, ByVal aReqReference As String, ByRef aReqValue As Variant, ByVal aReqBudget As String, ByVal aUseBudget As Boolean, ByVal aCalculPercent As Boolean, Optional ByRef ao_FilterGrid As MSFlexGrid = Nothing, Optional ByVal ac_LeavedPersons As Long = 0)
On Error GoTo ErrorHandler

    DoEvents
    
    'TODO : manage error
    Dim lUseBudget As Boolean
    lUseBudget = aUseBudget And (aReqBudget <> "")
    
    ' Initialize the grid ???
    Dim lColCount As Long
    
    Dim lReqReference As String, lReqValue() As String, lReqBudget As String
    Dim lb_FilterRecord As Boolean
    
    lReqReference = ReplaceHolders(aReqReference)
    

    If IsArray(aReqValue) Then
        ReDim lReqValue(UBound(aReqValue))
        Dim lVIdx As Long, lVCount As Long
        lVCount = UBound(aReqValue)
        If lVCount < 0 Then lVCount = 0
        For lVIdx = 0 To lVCount
            lReqValue(lVIdx) = ReplaceHolders(aReqValue(lVIdx))
        Next
    Else
        ReDim lReqValue(0)
        lReqValue(lVIdx) = ReplaceHolders(aReqValue)
        lVCount = 0
    End If
    
    If lUseBudget Then
        lReqBudget = ReplaceHolders(aReqBudget)
    End If

    lColCount = 1 + (UBound(lReqValue) + 1)
    
    If aCalculPercent Then lColCount = lColCount + 1
    If lUseBudget Then lColCount = lColCount + 1
    
    init_grid aGrid, lColCount
    If Not ao_FilterGrid Is Nothing Then init_grid ao_FilterGrid, lColCount
    
    Dim lCursRef As Long, lCursValue() As Long, lCursBudget As Long
    ReDim lCursValue(-1 To -1)
    
    DoEvents
    lCursRef = OpenSQLSafe(p_da, lReqReference)
'>>>>
    If mb_Cancel = True Then GoTo CleanUp
    'MS REDIMM
    Call SafeRedimPreserve(lCursValue, SafeUbound(lReqValue))
    'ReDim lCursValue(UBound(lReqValue))
    For lVIdx = 0 To lVCount
        If lReqValue(lVIdx) <> "" Then
            DoEvents
            lCursValue(lVIdx) = OpenSQLSafe(p_da, lReqValue(lVIdx))
'>>>>
            If mb_Cancel = True Then GoTo CleanUp
        Else
            lCursValue(lVIdx) = -1
        End If
    Next
    
    lUseBudget = aUseBudget And (lReqBudget <> "")
    If lUseBudget Then
        DoEvents
        lCursBudget = OpenSQLSafe(p_da, lReqBudget)
'>>>>
        If mb_Cancel = True Then GoTo CleanUp
    End If
    
    Dim lTotalValue() As Double, lTotalBudget As Double, lTotalPercent As Double
    
    ReDim lTotalValue(UBound(lCursValue))
    
    Dim lIdx As Long, lCount As Long, lCountFiltered As Long
    lCountFiltered = 0
    lCount = p_da.RowCount(lCursRef)
    aGrid.Rows = lCount + 2 ' Don't forget the total and the title!
    
    For lIdx = 1 To lCount
        lb_FilterRecord = False
        ' Set the name, always COL 0
        aGrid.TextMatrix(lIdx, 0) = Trim(p_da.GetFields(lCursRef, 1)) ' Set the name
        
        
        ' Set the value, always from COL 1 TO COL 1 + lVCount
        For lVIdx = 0 To lVCount
            If lCursValue(lVIdx) <> 0 Then
                If p_da.Find(lCursValue(lVIdx), 0, p_da.GetFields(lCursRef, 0)) >= 0 Then
                    aGrid.TextMatrix(lIdx, 1 + lVIdx) = Format(p_da.GetFields(lCursValue(lVIdx), 1), "# ### ##0")
                    lTotalValue(lVIdx) = lTotalValue(lVIdx) + p_da.GetFields(lCursValue(lVIdx), 1)
                    If p_da.GetFields(lCursValue(lVIdx), 1) > 0 Then lb_FilterRecord = True
                Else
                    aGrid.TextMatrix(lIdx, 1 + lVIdx) = 0
                End If
                
            Else
                aGrid.TextMatrix(lIdx, 1 + lVIdx) = ""
                lTotalValue(lVIdx) = -1
            End If
            
        Next
        
        ' Set the budget, always ColCount - 2
        If lUseBudget Then
            If p_da.FindBinary(lCursBudget, 0, p_da.GetFields(lCursRef, 0)) >= 0 Then
                aGrid.TextMatrix(lIdx, lColCount - 2) = Format(p_da.GetFields(lCursBudget, 1), "# ### ##0")
                If p_da.GetFields(lCursBudget, 1) > 0 Then lb_FilterRecord = True
            Else
                aGrid.TextMatrix(lIdx, lColCount - 2) = 0
            End If
        End If
        
        
        ' Calcul the percent of the budget
        If aCalculPercent And lUseBudget Then
            lTotalBudget = lTotalBudget + Val(aGrid.TextMatrix(lIdx, lColCount - 2))
            If Val(aGrid.TextMatrix(lIdx, lColCount - 2)) <> 0 Then
                aGrid.TextMatrix(lIdx, lColCount - 1) = Format(Val(aGrid.TextMatrix(lIdx, lColCount - 3)) / Val(aGrid.TextMatrix(lIdx, lColCount - 2)), "#0.00%")
            Else
                aGrid.TextMatrix(lIdx, lColCount - 1) = "0.00%"
            End If
        End If
        
        If mb_DisplayFilterByUser Then
          ' check if record with zero value represent person which leave company
          If (Not lb_FilterRecord) And (ac_LeavedPersons <> 0) Then
            If p_da.Find(ac_LeavedPersons, 0, aGrid.TextMatrix(lIdx, 0), 0) < 0 Then
              ' person did not leave company
              lb_FilterRecord = True
            End If
          End If
          ' record should be filtered and displayed in filtered tab
          If lb_FilterRecord And (Not ao_FilterGrid Is Nothing) Then
            ao_FilterGrid.Rows = ao_FilterGrid.Rows + 1
            lCountFiltered = lCountFiltered + 1
            For lVIdx = 0 To aGrid.Cols - 1
              ao_FilterGrid.TextMatrix(ao_FilterGrid.Rows - 2, lVIdx) = aGrid.TextMatrix(lIdx, lVIdx)
            Next
            
          End If
        End If
        Call p_da.Next(lCursRef)
    Next

    ' Close the cursors
    Call p_da.Close(lCursRef)
    For lVIdx = 0 To lVCount
        Call p_da.Close(lCursValue(lVIdx))
        lCursValue(lVIdx) = 0
    Next
    If lUseBudget Then
        Call p_da.Close(lCursBudget)
    End If

    ' Calcul the percent when we don't want the budget, percent is always for COLCOUNT - 2
    If aCalculPercent And Not lUseBudget Then
        For lIdx = 1 To lCount
            If Val(aGrid.TextMatrix(lIdx, lColCount - 2)) <> 0 Then
                aGrid.TextMatrix(lIdx, lColCount - 1) = Format(Val(aGrid.TextMatrix(lIdx, lColCount - 2)) / lTotalValue(UBound(lTotalValue)), "#0.00%")
            Else
              aGrid.TextMatrix(lIdx, lColCount - 1) = "0.00%"
            End If
        Next
        
        If mb_DisplayFilterByUser And (Not ao_FilterGrid Is Nothing) Then
          For lIdx = 1 To lCountFiltered
              If Val(ao_FilterGrid.TextMatrix(lIdx, lColCount - 2)) <> 0 Then
                  ao_FilterGrid.TextMatrix(lIdx, lColCount - 1) = Format(Val(ao_FilterGrid.TextMatrix(lIdx, lColCount - 2)) / lTotalValue(UBound(lTotalValue)), "#0.00%")
              Else
                ao_FilterGrid.TextMatrix(lIdx, lColCount - 1) = "0.00%"
              End If
          Next
        End If
    
    End If
    
    ' Write the total value
    aGrid.TextMatrix(lCount + 1, 0) = GetLabel("s_total2", "#Total")
    
    'put the background of the Total line in color
    aGrid.Row = lCount + 1
    Dim li_i As Integer
    For li_i = 0 To lColCount - 1
        aGrid.Col = li_i
        aGrid.CellBackColor = &HC0FFFF
        
    Next li_i
    
    If Not (ao_FilterGrid Is Nothing) And mb_DisplayFilterByUser Then
      ' Write the total value
      ao_FilterGrid.TextMatrix(lCountFiltered + 1, 0) = GetLabel("s_total2", "#Total")
      'put the background of the Total line in color
      ao_FilterGrid.Row = lCountFiltered + 1
      For li_i = 0 To lColCount - 1
          ao_FilterGrid.Col = li_i
          ao_FilterGrid.CellBackColor = &HC0FFFF
      Next li_i
    End If
    
    aGrid.Row = 1
    aGrid.Col = 0

    For lVIdx = 0 To lVCount
        If lTotalValue(lVIdx) <> -1 Then
            aGrid.TextMatrix(lCount + 1, 1 + lVIdx) = Format(lTotalValue(lVIdx), "# ### ##0")
        End If
    Next
    
    If Not (ao_FilterGrid Is Nothing) And mb_DisplayFilterByUser Then
      ao_FilterGrid.Row = 1
      ao_FilterGrid.Col = 0
  
      For lVIdx = 0 To lVCount
          If lTotalValue(lVIdx) <> -1 Then
              ao_FilterGrid.TextMatrix(lCountFiltered + 1, 1 + lVIdx) = Format(lTotalValue(lVIdx), "# ### ##0")
          End If
      Next
    End If
    
    If aCalculPercent And Not lUseBudget Then
        If Val(aGrid.TextMatrix(lCount + 1, lColCount - 2)) = 0 Then
            aGrid.TextMatrix(lCount + 1, lColCount - 1) = "0.00%"
        Else
            aGrid.TextMatrix(lCount + 1, lColCount - 1) = "100.00%"
        End If
    
        If Not (ao_FilterGrid Is Nothing) And mb_DisplayFilterByUser Then
          If Val(ao_FilterGrid.TextMatrix(lCountFiltered + 1, lColCount - 2)) = 0 Then
              ao_FilterGrid.TextMatrix(lCountFiltered + 1, lColCount - 1) = "0.00%"
          Else
              ao_FilterGrid.TextMatrix(lCountFiltered + 1, lColCount - 1) = "100.00%"
          End If
        End If
    End If
    
    If lUseBudget Then
        aGrid.TextMatrix(lCount + 1, lColCount - 2) = Format(lTotalBudget, "# ### ##0")
        
        If aCalculPercent Then
            If lTotalBudget <> 0 Then
                aGrid.TextMatrix(lCount + 1, lColCount - 1) = Format(Val(aGrid.TextMatrix(lCount + 1, lColCount - 3)) / lTotalBudget, "#0.00%")
            Else
                aGrid.TextMatrix(lCount + 1, lColCount - 1) = "0.00%"
            End If
        End If
    
        If Not (ao_FilterGrid Is Nothing) And mb_DisplayFilterByUser Then
          ao_FilterGrid.TextMatrix(lCountFiltered + 1, lColCount - 2) = Format(lTotalBudget, "# ### ##0")
          
          If aCalculPercent Then
              If lTotalBudget <> 0 Then
                  ao_FilterGrid.TextMatrix(lCountFiltered + 1, lColCount - 1) = Format(Val(ao_FilterGrid.TextMatrix(lCountFiltered + 1, lColCount - 3)) / lTotalBudget, "#0.00%")
              Else
                  ao_FilterGrid.TextMatrix(lCountFiltered + 1, lColCount - 1) = "0.00%"
              End If
          End If
        End If
    End If
    
    
CleanUp:
    Call p_da.Close(lCursRef)
    Call p_da.Close(lCursBudget)
    For li_i = 0 To UBound(lCursValue)
        Call p_da.Close(lCursValue(li_i))
        lCursValue(li_i) = 0
    Next li_i
    Exit Sub
    
ErrorHandler:
    If lCursRef > 0 Then
        Call p_da.Close(lCursRef)
        lCursRef = 0
    End If
    If lCursBudget > 0 Then
        Call p_da.Close(lCursBudget)
        lCursBudget = 0
    End If
    For li_i = 0 To UBound(lCursValue)
        If lCursValue(li_i) > 0 Then
            Call p_da.Close(lCursValue(li_i))
            lCursValue(li_i) = 0
        End If
    Next li_i
    Call ErrorHandler(Extender.Name & ".FillGrid")
    
End Sub

Private Sub cmd_FullExport_Click()
On Error GoTo ErrorHandler
    grd_Views.LastLine
    grd_Views.ExportToExcel (True)
    Exit Sub
    
ErrorHandler:
    Call ErrorMessage(Extender.Name & ".cmd_FullExport_Click")
End Sub

Private Sub InitTab(ByVal al_Index As Long)
On Error GoTo ErrorHandler

    If IsControlLoaded(tbs_Result, al_Index) Then
        tbs_Result(al_Index).Tabs(1).Selected = True
    End If
    Exit Sub
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".InitTab")
End Sub

Private Function IsControlLoaded(ByRef ao_ControlArray As Object, ByVal al_Index As Long) As Boolean

On Error GoTo NotLoaded
  'this will raise excpetion if control with index don't exists
  IsControlLoaded = ao_ControlArray(al_Index).Index = al_Index
  Exit Function
NotLoaded:
  IsControlLoaded = False
End Function


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

' ************************************************************************************
' ************************************************************************************
' **************************** 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

' 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


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

Private Function GetCodePageFromLanguage(ByRef ao_Armdb As Object, ByVal as_Language As String) As Long
On Error GoTo errHandler
Const C_REQ As String = "SELECT Code_Page FROM Language WHERE Language_Code = '$Language_Code$'"
    Dim ls_req As String
    Dim ll_cursor As Long
    Dim ll_CodePage As Long
    
    ls_req = Replace(C_REQ, "$Language_Code$", as_Language, , , vbTextCompare)
    
    ll_cursor = OpenSQLSafe(ao_Armdb, ls_req)
    Debug.Assert (ll_cursor <> 0)
    
    ll_CodePage = CLng(ao_Armdb.GetFields(ll_cursor, "Code_Page"))
    Call ao_Armdb.Close(ll_cursor)
    GetCodePageFromLanguage = ll_CodePage
    Exit Function
    
errHandler:
    If ll_cursor <> 0 Then Call ao_Armdb.Close(ll_cursor)
    Call ErrorHandler("GetCodePageFromLanguage()")
End Function

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

On Error GoTo errHandler

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

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

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

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

    On Error GoTo CleanUp   'not all controls support Container property
    HasContainer = False
    While Not (lo_control Is Nothing)
        If lo_control.Container Is lo_Container Then
            HasContainer = True
            Exit Function
        End If
        Set lo_control = lo_control.Container
    Wend

CleanUp:

End Function

' Load the labels of a containers
Private Sub LoadLabels(ByRef ao_Armdb As ArmDb, ByRef ao_Container As Object, ByVal as_ScreenName As String, ByVal as_Language As String)
Dim lo_control As Control   ' A control of the container
Dim li_idx As Integer, li_Count As Integer
Dim li_Label As Integer      ' A label idx
Dim ls_Request As String
Dim lc_Labels As Long
Dim lsa_ControlTag() As String
    
    On Error GoTo Trace_Err

    If mc_ScreenLabels = 0 Then
        ls_Request = "exec screen_csts '" & as_ScreenName & "','" & as_Language & "'"
        mc_ScreenLabels = OpenSQLSafe(ao_Armdb, ls_Request)
    End If
    lc_Labels = mc_ScreenLabels
    
    If lc_Labels = 0 Then
        Exit Sub
    End If
    
    On Error GoTo WithoutTag
    If ao_Container.Tag <> "" Then
        li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", ao_Container.Tag, , 1)
        If li_Label >= 0 Then
            ao_Container.Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
        End If
    End If
WithoutTag:
    
    On Error GoTo Trace_Err
    
    ' Iterate the container for loading the label of each element which has defined a tag
    For Each lo_control In UserControl.Controls
        
        If HasContainer(lo_control, ao_Container) Or _
          ((ao_Container Is Me) And (UCase(TypeName(lo_control)) = "MENU")) Then
            Select Case UCase(TypeName(lo_control))
                Case UCase("TabStrip") ' Component is a tabstrip, we load the caption of each tab defined
                    Dim lo_Tbs
                    Set lo_Tbs = lo_control ' Cast for use of intellisense
                    li_Count = lo_Tbs.Tabs.Count
                    For li_idx = 1 To li_Count
                        If lo_Tbs.Tabs(li_idx).Tag <> "" Then
                            li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_Tbs.Tabs(li_idx).Tag, , 1)
                            If li_Label >= 0 Then
                                lo_Tbs.Tabs(li_idx).Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                            End If
                        End If
                    Next
                    Set lo_Tbs = Nothing
                
                Case UCase("ListView") ' Component is a listview, we load the caption of each columns
                    Dim lo_ListView As ListView
                    Set lo_ListView = lo_control
                    li_Count = lo_ListView.ColumnHeaders.Count
                    For li_idx = 1 To li_Count
                        If lo_ListView.ColumnHeaders(li_idx).Tag <> "" Then
                            li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_ListView.ColumnHeaders(li_idx).Tag, , 1)
                            If li_Label >= 0 Then
                                lo_ListView.ColumnHeaders(li_idx).Text = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                            End If
                        End If
                    Next
                    Set lo_ListView = Nothing
            
                Case UCase("TextBox")  ' Component is a textbox
                    Dim lo_TextBox As TextBox
                    Set lo_TextBox = lo_control
                    If lo_TextBox.Tag <> "" Then
                        lsa_ControlTag = Split(lo_control.Tag, SEP)
                        li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lsa_ControlTag(0), , 1)
                        If li_Label >= 0 Then
                            lo_TextBox.Text = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                        End If
                    End If
                    Set lo_TextBox = Nothing
                
                Case UCase("Label"), UCase("Frame"), UCase("CommandButton"), UCase("CheckBox"), UCase("OptionButton")
                    If lo_control.Tag <> "" Then
                        lsa_ControlTag = Split(lo_control.Tag, SEP)
                        li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lsa_ControlTag(0), , 1)
                        If li_Label >= 0 Then
                            lo_control.Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                        End If
                    End If
                Case UCase("ArmGrid")
                    li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_control.Tag, , 1)
                    If li_Label >= 0 Then
                      Call lo_control.LoadConstants(ptStatic, ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT"), ctColumns)
                    End If
                    li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_control.Tag & "_Title", , 1)
                    If li_Label >= 0 Then
                      lo_control.Title = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                    End If
                Case UCase("Menu")
                    If lo_control.Tag <> "" Then
                        li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_control.Tag, , 1)
                        If li_Label >= 0 Then
                            lo_control.Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                        End If
                    End If
            End Select
        End If
    Next
        
Trace_End:
    Exit Sub
    
Trace_Err:
      
End Sub


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, , , vbTextCompare)
    lRequest = Replace(lRequest, "$lang$", aLang, , , vbTextCompare)
    Dim lData As Long
    
    lData = OpenSQLSafe(p_da, lRequest)
    
    Dim lBuffer As String
    lBuffer = p_da.GetFields(lData, "message_text")
    p_da.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:
    Call p_da.Close(lData)
    Call MsgBox("Connection failure accessing message information.", vbCritical, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision)
    MsgText = aDefault
End Function

Private Sub LockScreen(ByVal ab_lock As Boolean)

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

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

' initalize header of a grid
' 0 .. Name, 1.. label, 2.. width, 3... DB_Field_Name, 4... allign, 5... format
Private Sub GRD_SetHeader(ByRef ao_grid As MSFlexGrid, ByRef ao_GRDInfo As GRD_Info, ByRef av_colDef As Variant)
On Error GoTo ErrorHandler
    Debug.Assert (IsArray(av_colDef))
    
    Dim ll_ColIdx As Long
    Dim ll_ColBase As Long
    Dim ll_RowIdx As Long
    
    ReDim ao_GRDInfo.Cols(0) As GRD_ColumnInfo
    
    If ao_grid.Rows <= UBound(av_colDef) Then ao_grid.Rows = UBound(av_colDef) + 1
    
    ll_ColBase = 0
    For ll_RowIdx = LBound(av_colDef) To UBound(av_colDef)
        Debug.Assert (IsArray(av_colDef(ll_RowIdx)))
        
        ReDim Preserve ao_GRDInfo.Cols(ll_ColBase + UBound(av_colDef(ll_RowIdx))) As GRD_ColumnInfo
        
        If ao_grid.Cols <= UBound(av_colDef(ll_RowIdx)) Then ao_grid.Cols = UBound(av_colDef(ll_RowIdx)) + 1

        For ll_ColIdx = LBound(av_colDef(ll_RowIdx)) To UBound(av_colDef(ll_RowIdx))
            If IsArray(av_colDef(ll_RowIdx)(ll_ColIdx)) Then
                Debug.Assert (UBound(av_colDef(ll_RowIdx)(ll_ColIdx)) >= 1)        ' at least name and label must be specified
    
                ao_GRDInfo.Cols(ll_ColIdx + ll_ColBase).Index = ll_ColIdx
                ao_GRDInfo.Cols(ll_ColIdx + ll_ColBase).Name = av_colDef(ll_RowIdx)(ll_ColIdx)(0)
                If TypeName(av_colDef(ll_RowIdx)(ll_ColIdx)(1)) = "String" Then
                    ao_grid.TextMatrix(ll_RowIdx, ll_ColIdx) = av_colDef(ll_RowIdx)(ll_ColIdx)(1)
                Else
                    ao_grid.TextMatrix(ll_RowIdx, ll_ColIdx) = av_colDef(ll_RowIdx)(ll_ColIdx)(av_colDef(ll_RowIdx)(ll_ColIdx)(1))(1)
                End If
                If UBound(av_colDef(ll_RowIdx)(ll_ColIdx)) >= 2 Then ao_grid.ColWidth(ll_ColIdx) = av_colDef(ll_RowIdx)(ll_ColIdx)(2)
                If UBound(av_colDef(ll_RowIdx)(ll_ColIdx)) >= 3 Then ao_GRDInfo.Cols(ll_ColIdx + ll_ColBase).DB_Name = av_colDef(ll_RowIdx)(ll_ColIdx)(3)
                If UBound(av_colDef(ll_RowIdx)(ll_ColIdx)) >= 4 Then ao_grid.FixedAlignment(ll_ColIdx) = av_colDef(ll_RowIdx)(ll_ColIdx)(4)
                If UBound(av_colDef(ll_RowIdx)(ll_ColIdx)) >= 5 Then ao_GRDInfo.Cols(ll_ColIdx + ll_ColBase).Format = av_colDef(ll_RowIdx)(ll_ColIdx)(5)
            Else
                ' only label
                If TypeName(av_colDef(ll_RowIdx)(ll_ColIdx)) = "String" Then
                    ao_grid.TextMatrix(ll_RowIdx, ll_ColIdx) = av_colDef(ll_RowIdx)(ll_ColIdx)
                Else
                    If IsArray(av_colDef(ll_RowIdx)(av_colDef(ll_RowIdx)(ll_ColIdx))) Then
                        ao_grid.TextMatrix(ll_RowIdx, ll_ColIdx) = av_colDef(ll_RowIdx)(av_colDef(ll_RowIdx)(ll_ColIdx))(1)
                    Else
                        ao_grid.TextMatrix(ll_RowIdx, ll_ColIdx) = av_colDef(ll_RowIdx)(av_colDef(ll_RowIdx)(ll_ColIdx))
                    End If
                End If
                
            End If
            
        Next ll_ColIdx
        ll_ColBase = ll_ColBase + ll_ColIdx
        ao_grid.MergeRow(ll_RowIdx) = True
    Next ll_RowIdx
    
    
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GRD_SetHeader")
End Sub

Private Sub GRD_LoadData(ByRef ao_grid As MSFlexGrid, ByRef ao_GRDInfo As GRD_Info, ByVal al_Cursor As Long, Optional ByVal al_color1 As Long = COLOR_WHITE, Optional ByVal al_color2 As Long = COLOR_WHITE, Optional ByRef ava_GroupedLines As Variant, Optional ByRef ava_TotalCols As Variant)
On Error GoTo ErrorHandler
    Dim lb_line As Boolean
    Dim ll_curentRow As Long
    Dim ll_col As Long
    Dim ll_idx As Long

    If Not p_da.First(al_Cursor) Then Exit Sub
    
    ao_grid.Rows = p_da.RowCount(al_Cursor) + ao_grid.FixedRows
    ll_curentRow = ao_grid.FixedRows
    lb_line = True
    
    While Not p_da.EOF(al_Cursor)
        For ll_col = LBound(ao_GRDInfo.Cols) To UBound(ao_GRDInfo.Cols)
            If ao_GRDInfo.Cols(ll_col).DB_Name <> "" Then
                If ao_GRDInfo.Cols(ll_col).Format <> "" Then
                    ao_grid.TextMatrix(ll_curentRow, ao_GRDInfo.Cols(ll_col).Index) = Format(p_da.GetFields(al_Cursor, ao_GRDInfo.Cols(ll_col).DB_Name), ao_GRDInfo.Cols(ll_col).Format, vbUseSystemDayOfWeek, vbUseSystem)
                Else
                    ao_grid.TextMatrix(ll_curentRow, ao_GRDInfo.Cols(ll_col).Index) = p_da.GetFields(al_Cursor, ao_GRDInfo.Cols(ll_col).DB_Name)
                End If
            End If
        Next ll_col
        '
        If Not IsMissing(ava_GroupedLines) Then
            If p_da.Position(al_Cursor) > 0 Then
                Dim lb_isEqual As Boolean
                lb_isEqual = True
                For ll_idx = LBound(ava_GroupedLines) To UBound(ava_GroupedLines)
                    ll_col = GRD_GetColIndex(ao_GRDInfo, ava_GroupedLines(ll_idx))
                    Debug.Assert (ll_col <> -1)
                    If p_da.GetFields(al_Cursor, ao_GRDInfo.Cols(ll_col).DB_Name) <> p_da.GetFieldsAt(al_Cursor, p_da.Position(al_Cursor) - 1, ao_GRDInfo.Cols(ll_col).DB_Name) Then
                        lb_isEqual = False
                        Exit For
                    End If
                Next ll_idx
                If Not lb_isEqual Then lb_line = Not lb_line
            End If
        Else
            lb_line = Not lb_line
        End If
        
        Call SetGridRowBackColor(ao_grid, ll_curentRow, IIf(lb_line, al_color1, al_color2))
        
        If Not IsMissing(ava_TotalCols) Then
            ' calculate total
            Dim ld_total As Double
            ld_total = 0
            For ll_idx = LBound(ava_TotalCols) To UBound(ava_TotalCols) - 1
                ld_total = ld_total + p_da.GetFields(al_Cursor, ava_TotalCols(ll_idx))
            Next ll_idx
            
            ll_col = GRD_GetColIndex(ao_GRDInfo, ava_TotalCols(UBound(ava_TotalCols)))
            Debug.Assert (ll_col <> -1)
            If ao_GRDInfo.Cols(ll_col).Format <> "" Then
                ao_grid.TextMatrix(ll_curentRow, ao_GRDInfo.Cols(ll_col).Index) = Format(ld_total, ao_GRDInfo.Cols(ll_col).Format, vbUseSystemDayOfWeek, vbUseSystem)
            Else
                ao_grid.TextMatrix(ll_curentRow, ao_GRDInfo.Cols(ll_col).Index) = ld_total
            End If
            Call SetGridCellBackColor(ao_grid, ll_curentRow, ao_GRDInfo.Cols(ll_col).Index, COLOR_GREY3)
        End If
        
        ll_curentRow = ll_curentRow + 1
        p_da.Next (al_Cursor)
    Wend
            
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GRD_LoadData")
End Sub

Private Function GRD_GetColIndex(ByRef ao_GRDInfo As GRD_Info, ByVal as_colName As String) As Long
On Error GoTo ErrorHandler
    
    Dim ll_col As Long
    GRD_GetColIndex = -1
    
    For ll_col = LBound(ao_GRDInfo.Cols) To UBound(ao_GRDInfo.Cols)
        If ao_GRDInfo.Cols(ll_col).Name = as_colName Then
            GRD_GetColIndex = ll_col
            Exit For
        End If
    Next ll_col

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

Private Function GRD_GetColIndex2(ByRef ao_GRDInfo As GRD_Info, ByVal al_ColIdx As Long) As Long
On Error GoTo ErrorHandler
    
    Dim ll_col As Long
    GRD_GetColIndex2 = -1
    
    For ll_col = UBound(ao_GRDInfo.Cols) To LBound(ao_GRDInfo.Cols) Step -1
        If ao_GRDInfo.Cols(ll_col).Index = al_ColIdx Then
            GRD_GetColIndex2 = ll_col
            Exit For
        End If
    Next ll_col

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


Private Sub GRD_addSUM(ByRef ao_grid As MSFlexGrid, ByRef ao_GRDInfo As GRD_Info, ByVal al_Cursor As Long, ByRef ao_SUMCols As Variant, ByVal as_totalColName As String, Optional ByRef ava_TotalCols As Variant)
On Error GoTo ErrorHandler

    Dim ll_curentRow As Long
    Dim ll_col As Long
    Dim ll_idx As Long
    
    ' add row
    ao_grid.Rows = ao_grid.Rows + 1
    ll_curentRow = ao_grid.Rows - 1
    
    ' put description
    ll_col = GRD_GetColIndex(ao_GRDInfo, as_totalColName)
    Debug.Assert (ll_col <> -1)
    ao_grid.TextMatrix(ll_curentRow, ao_GRDInfo.Cols(ll_col).Index) = GetLabel("s_total", "#TOTAL")
    
    ' some formating
    Call SetGridRowBackColor(ao_grid, ll_curentRow, COLOR_GREY2)
    Call SetGridRowForeColor(ao_grid, ll_curentRow, COLOR_BLUE)
    Call SetGridRowBold(ao_grid, ll_curentRow)
    
    ' calculate sum for each col
    For ll_idx = LBound(ao_SUMCols) To UBound(ao_SUMCols)
        ll_col = GRD_GetColIndex(ao_GRDInfo, ao_SUMCols(ll_idx))
        If ll_col <> -1 Then
            If ao_GRDInfo.Cols(ll_col).Format <> "" Then
                ao_grid.TextMatrix(ll_curentRow, ao_GRDInfo.Cols(ll_col).Index) = Format(GetColSUM(al_Cursor, ao_GRDInfo.Cols(ll_col).DB_Name), ao_GRDInfo.Cols(ll_col).Format, vbUseSystemDayOfWeek, vbUseSystem)
            Else
                ao_grid.TextMatrix(ll_curentRow, ao_GRDInfo.Cols(ll_col).Index) = GetColSUM(al_Cursor, ao_GRDInfo.Cols(ll_col).DB_Name)
            End If
        End If
    Next ll_idx
    
    If Not IsMissing(ava_TotalCols) Then
        ' calculate total
        Dim ld_total As Double
        ld_total = 0
        For ll_idx = LBound(ava_TotalCols) To UBound(ava_TotalCols) - 1
            ld_total = ld_total + GetColSUM(al_Cursor, ava_TotalCols(ll_idx))
        Next ll_idx
        
        ll_col = GRD_GetColIndex(ao_GRDInfo, ava_TotalCols(UBound(ava_TotalCols)))
        Debug.Assert (ll_col <> -1)
        If ao_GRDInfo.Cols(ll_col).Format <> "" Then
            ao_grid.TextMatrix(ll_curentRow, ao_GRDInfo.Cols(ll_col).Index) = Format(ld_total, ao_GRDInfo.Cols(ll_col).Format, vbUseSystemDayOfWeek, vbUseSystem)
        Else
            ao_grid.TextMatrix(ll_curentRow, ao_GRDInfo.Cols(ll_col).Index) = ld_total
        End If
    End If
    
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GRD_addSUM")
End Sub

Private Sub GRD_setColumnColor(ByRef ao_grid As MSFlexGrid, ByRef ao_GRDInfo As GRD_Info, ByVal as_colName As String, ByVal al_edge As Long, ByVal al_colorOK As Long, ByVal al_colorKO As Long)
On Error GoTo ErrorHandler

    Dim ll_col As Long
    Dim ll_idx As Long
    
    ' put description
    ll_col = GRD_GetColIndex(ao_GRDInfo, as_colName)
    Debug.Assert (ll_col <> -1)
    
    For ll_idx = ao_grid.FixedRows To ao_grid.Rows - 1
        If isNumeric(ao_grid.TextMatrix(ll_idx, ll_col)) Then
            If Val(ao_grid.TextMatrix(ll_idx, ll_col)) <= al_edge Then
                Call SetGridCellBackColor(ao_grid, ll_idx, ll_col, al_colorOK)
            Else
                Call SetGridCellBackColor(ao_grid, ll_idx, ll_col, al_colorKO)
            End If
        End If
    Next ll_idx
    
    Exit Sub
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GRD_setColumnColor")
End Sub

Private Function GetColSUM(ByVal al_Cursor As Long, ByVal as_col As String) As Variant
On Error GoTo ErrorHandler
    Dim ld_retVal As Variant
    ld_retVal = 0
    
    If p_da.First(al_Cursor) Then
        While Not p_da.EOF(al_Cursor)
            ld_retVal = ld_retVal + p_da.GetFields(al_Cursor, as_col)
            Call p_da.Next(al_Cursor)
        Wend
    End If

    GetColSUM = ld_retVal
    Exit Function
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetColSUM")
End Function

Private Function GetColMin(ByVal al_Cursor As Long, ByVal as_col As String) As Variant
On Error GoTo ErrorHandler
    Dim lv_retVal As Variant
    lv_retVal = 0
    
    If p_da.First(al_Cursor) Then
        lv_retVal = p_da.GetFields(al_Cursor, as_col)
        Call p_da.Next(al_Cursor)
        
        While Not p_da.EOF(al_Cursor)
            If p_da.GetFields(al_Cursor, as_col) < lv_retVal Then lv_retVal = p_da.GetFields(al_Cursor, as_col)
            Call p_da.Next(al_Cursor)
        Wend
    End If

    GetColMin = lv_retVal
    Exit Function
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetColMin")
End Function

Private Function GetColMax(ByVal al_Cursor As Long, ByVal as_col As String) As Variant
On Error GoTo ErrorHandler
    Dim lv_retVal As Variant
    lv_retVal = 0
    
    If p_da.First(al_Cursor) Then
        lv_retVal = p_da.GetFields(al_Cursor, as_col)
        Call p_da.Next(al_Cursor)
        
        While Not p_da.EOF(al_Cursor)
            If p_da.GetFields(al_Cursor, as_col) > lv_retVal Then lv_retVal = p_da.GetFields(al_Cursor, as_col)
            Call p_da.Next(al_Cursor)
        Wend
    End If

    GetColMax = lv_retVal
    Exit Function
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetColMax")
End Function

Private Sub GRD_ExcelExport(ByRef ao_grid As MSFlexGrid, ByRef ao_GRDInfo As GRD_Info, ByVal as_GridDesc As String, ByRef ava_Totals As Variant)
On Error GoTo ErrorHandler
    Dim lRowIdx As Long, lRowCount As Long
    Dim lColIdx As Long, lColCount As Long
    Dim ll_col As Long
    Dim lRangeTopLeft As String, lRangeBottomRight As String, lRange As String
    Dim lRangeTopLeftL0 As String
    lRangeTopLeftL0 = ""

    Set a_ExcelApp = GetObject(, "Excel.Application")
    Set a_ExcelWorkBook = a_ExcelApp.Workbooks.Add
    Set a_ExcelSheet1 = a_ExcelWorkBook.Sheets.Add

    a_ExcelWorkBook.Activate
    a_ExcelSheet1.Activate
    
    a_ExcelSheet1.PageSetup.Orientation = 2
    a_ExcelApp.ActiveSheet.PageSetup.Zoom = 70

    a_ExcelApp.Application.Visible = -1
    a_ExcelSheet1.Application.Visible = -1
    
    With a_ExcelSheet1.cells.Interior
        .ColorIndex = 2
        .Pattern = 1
        .PatternColorIndex = -4105
    End With
    
    lRowCount = ao_grid.Rows - 1
    lColCount = ao_grid.Cols - 1
    
    Dim ll_FirstVisibleCol As Long
    Dim ll_LastVisibleCol As Long
    
    ll_FirstVisibleCol = -1

    With a_ExcelSheet1
        ' create standard report header

        ' set width of columns
        For lColIdx = 0 To lColCount
            .Columns(Chr(65 + lColIdx)).columnWidth = ao_grid.ColWidth(lColIdx) / 80
            If ao_grid.ColWidth(lColIdx) > 0 Then ll_LastVisibleCol = lColIdx + 1
            If ll_FirstVisibleCol = -1 Then
                If ao_grid.ColWidth(lColIdx) > 0 Then ll_FirstVisibleCol = lColIdx + 1
            End If
        Next
        
        Dim ll_midCell As Long
        ll_midCell = Round((ll_LastVisibleCol - ll_FirstVisibleCol + 1) / 2, 0)
        
        .cells(2, ll_midCell).Value = GetLabel("ex_report", "#CAPTURE REPORT") & " : " & ao_GRDInfo.gTitle
        .cells(2, ll_midCell).Font.Bold = True
        .cells(2, ll_midCell).HorizontalAlignment = -4108           'xlCenter
        
        .cells(4, ll_FirstVisibleCol).Value = as_GridDesc
        .cells(4, ll_FirstVisibleCol).Font.Bold = True
        .Columns(Chr(65 + ll_midCell) & ":" & Chr(65 + ll_midCell)).HorizontalAlignment = xlright
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$NOW$"
        ms_MsgInfo(0, 1) = Format(Now, "dd/mm/yy hh:mm:ss")
        .cells(2, ll_LastVisibleCol).Value = GetLabel("ex_created", "#Created $NOW$", ms_MsgInfo)
        .cells(2, ll_LastVisibleCol).Font.Italic = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$CB_TRW$"
        ms_MsgInfo(0, 1) = cb_trw.Text
        .cells(3, ll_LastVisibleCol) = GetLabel("ex_trw", "#Treeview Info: $CB_TRW$", ms_MsgInfo)
        .cells(3, ll_LastVisibleCol).Font.Italic = True
        .cells(3, ll_LastVisibleCol).Font.Size = 8

        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$TRW_PATH$"
        ms_MsgInfo(0, 1) = TreeviewPath
        .cells(4, ll_LastVisibleCol) = GetLabel("ex_trw_path", "#Treeview Path: $TRW_PATH$", ms_MsgInfo)
        .cells(4, ll_LastVisibleCol).Font.Italic = True
        .cells(4, ll_LastVisibleCol).Font.Size = 8
        .Columns(Chr(65 + ll_LastVisibleCol) & ":" & Chr(65 + 8)).HorizontalAlignment = xlright
        


        ' export data
        Dim lIdxExcelRow As Long, lIdxExcelCol As Long

        lIdxExcelRow = 6
        lIdxExcelCol = 1
        
        ' CONTENTS
        For lRowIdx = 0 To lRowCount
            For lColIdx = 0 To lColCount
                ll_col = GRD_GetColIndex2(ao_GRDInfo, lColIdx)
                Debug.Assert (ll_col <> -1)
                
                If lRowIdx < ao_grid.FixedRows Or lColIdx < ao_grid.FixedCols Then
                    .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Font.Bold = True
                    .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).HorizontalAlignment = -4108        'xlCenter
                    .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).VerticalAlignment = -4108          'xlVAlignCenter
                    .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).WrapText = ao_grid.WordWrap
                    .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = "'" & ao_grid.TextMatrix(lRowIdx, lColIdx)
                ElseIf ao_GRDInfo.Cols(ll_col).Format = "" Then ' Value is for a string
                    .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).WrapText = ao_grid.WordWrap
                    .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = "'" & ao_grid.TextMatrix(lRowIdx, lColIdx)
                Else    ' Value is a number
                    If InStr(1, ao_grid.TextMatrix(lRowIdx, lColIdx), "%", vbTextCompare) = 0 Then  ' Value
                        If ao_grid.TextMatrix(lRowIdx, lColIdx) = "" Then
                            .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = ""
                        Else
                            .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = CDbl(ao_grid.TextMatrix(lRowIdx, lColIdx))
                            .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).NumberFormat = "#,##0"
                        End If
                    Else    ' % Percent
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Value = Replace(ao_grid.TextMatrix(lRowIdx, lColIdx), "%", "") / 100
'                        cells(lIdxExcelRow, lIdxExcelCol + lColIdx).NumberFormat = "0%"
                        
                    End If
                    ao_grid.Row = lRowIdx
                    ao_grid.Col = lColIdx
                    If ao_grid.CellBackColor <> COLOR_WHITE Then
                        .cells(lIdxExcelRow, lIdxExcelCol + lColIdx).Interior.Color = ao_grid.CellBackColor
                    End If
                End If
                .cells(lIdxExcelRow, lIdxExcelCol + lColIdx + 1).HorizontalAlignment = -4152
            Next
            ' if line is total then do line
            Dim ll_idx As Long
            For ll_idx = LBound(ava_Totals) To UBound(ava_Totals) Step 2
                If ao_grid.TextMatrix(lRowIdx, ava_Totals(ll_idx)) = "" Then
                    'total
                    lRangeTopLeft = Chr(65 + ao_grid.FixedCols - 1) & (lIdxExcelRow)
                    lRangeBottomRight = Chr(65 + lColCount) & (lIdxExcelRow)
                    lRange = lRangeTopLeft & ":" & lRangeBottomRight
                    .Range(lRange).Interior.ColorIndex = ava_Totals(ll_idx + 1)
                    .Range(lRange).Interior.Pattern = 1
                    .Range(lRange).Interior.PatternColorIndex = -4105
                    .Range(lRange).Font.Bold = True
                    
                    If ll_idx = 0 And lRangeTopLeftL0 = "" Then
                        lRangeTopLeftL0 = lRangeTopLeft
                    End If
                    Exit For
                End If
            Next
            
            If ao_grid.MergeRow(lRowIdx) Then
                Call MergeCols(a_ExcelSheet1, 1, lColCount + 1, lIdxExcelRow)
            End If
            
            ' set rowheight
            .Rows(lIdxExcelRow).RowHeight = ao_grid.RowHeight(lRowIdx) / (240 / 12.75)

            
            lIdxExcelRow = lIdxExcelRow + 1
        Next
        
        
        For lColIdx = 0 To lColCount
            If ao_grid.MergeCol(lColIdx) Then
                Call MergeRows(a_ExcelSheet1, 6, lRowCount + 6, lColIdx + 1)
            End If
        Next
        
    
    
        ' add formating
        If lRowCount > 0 Then
            lRangeTopLeft = "A6"
            lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 6)
            lRange = lRangeTopLeft & ":" & lRangeBottomRight
            .Range(lRange).Borders(xlInsideVertical).Weight = xlThin
            .Range(lRange).Borders(xlInsideVertical).LineStyle = xlContinuous
            .Range(lRange).Borders(xlInsideHorizontal).Weight = xlThin
            .Range(lRange).Borders(xlInsideHorizontal).LineStyle = xlContinuous
        End If
        
        ' SET THE HEADER
        lRangeTopLeft = "A6"
        lRangeBottomRight = Chr(65 + lColCount) & (6 + ao_grid.FixedRows - 1)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeTop).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeTop).Weight = xlThick
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = 15  'aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        .Range(lRange).Font.Bold = True
        .Range(lRange).HorizontalAlignment = -4108      'xlCenter
                
        lRangeTopLeft = "A7"
        lRangeBottomRight = Chr(65 + ao_grid.FixedCols - 1) & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        .Range(lRange).Interior.ColorIndex = 15 'aHeaderColor
        .Range(lRange).Interior.Pattern = 1
        .Range(lRange).Interior.PatternColorIndex = -4105
        .Range(lRange).Font.Bold = True
        .Range(lRange).HorizontalAlignment = -4131      'xlLeft
        
        
        ' SET THE TOTAL
        
        ' SET THE EXTERNAL WEIGHT LINE
        ' LEFT
        lRangeTopLeft = "A6"
        lRangeBottomRight = "A" & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeLeft).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeLeft).Weight = xlThick
        
        ' RIGHT
        lRangeTopLeft = Chr(65 + lColCount) & "6"
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeright).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeright).Weight = xlThick
        
        ' BOTTOM
        lRangeTopLeft = "A" & (lRowCount + 6)
        lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 6)
        lRange = lRangeTopLeft & ":" & lRangeBottomRight
        .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
        
        If lRangeTopLeftL0 <> "" Then
            ' BOTTOM
            lRangeTopLeft = lRangeTopLeftL0
            lRangeBottomRight = Chr(65 + lColCount) & (lRowCount + 6)
            lRange = lRangeTopLeft & ":" & lRangeBottomRight
            .Range(lRange).Borders(xlEdgeTop).LineStyle = xlContinuous
            .Range(lRange).Borders(xlEdgeTop).Weight = xlThick
        End If
        
        
        For lRowIdx = 0 To lRowCount - 1 ' Title line is already processed
            ' if line is total then do line
            If ao_grid.TextMatrix(lRowIdx, 0) = "" Then
                'total
'                lRangeTopLeft = "D" & (lRowIdx + 7)
'                lRangeBottomRight = Chr(65 + lColCount) & (lRowIdx + 7)
'                lRange = lRangeTopLeft & ":" & lRangeBottomRight
'                .Range(lRange).Interior.ColorIndex = 12
'                .Range(lRange).Interior.Pattern = 1
'                .Range(lRange).Interior.PatternColorIndex = -4105
'                .Range(lRange).Font.Bold = True
                
            ElseIf ao_grid.TextMatrix(lRowIdx, 1) = "" Then
                ' BOTTOM
                
'                lRangeTopLeft = "D" & (lRowIdx + 7)
'                lRangeBottomRight = Chr(65 + lColCount) & (lRowIdx + 7)
'                lRange = lRangeTopLeft & ":" & lRangeBottomRight
'                .Range(lRange).Interior.ColorIndex = 6
'                .Range(lRange).Interior.Pattern = 1
'                .Range(lRange).Interior.PatternColorIndex = -4105
'                .Range(lRange).Font.Bold = True
                
'                lRangeTopLeft = "A" & (lRowIdx + 7)
'                lRangeBottomRight = Chr(65 + lColCount) & (lRowIdx + 7)
'                lRange = lRangeTopLeft & ":" & lRangeBottomRight
'                .Range(lRange).Borders(xlEdgeBottom).LineStyle = xlContinuous
'                .Range(lRange).Borders(xlEdgeBottom).Weight = xlThick
            End If
        Next
        
        .Range("A1:A1").Select
    
    End With
        
    Set a_ExcelSheet1 = Nothing
    Set a_ExcelWorkBook = Nothing
    Set a_ExcelApp = Nothing
    Screen.MousePointer = 0
          
    MsgBox MsgText(108, ms_Language_Code, "#Press ALT+TAB to switch to the Excel application.")
    Exit Sub
ErrorHandler:
    If Err.Number = 429 Then
        Set a_ExcelApp = CreateObject("Excel.Application")
        Resume Next
    Else
        If Err.Number = 1004 Then
            'debug.print Err.Description
            Resume Next
        Else
            Screen.MousePointer = 0
            Set a_ExcelApp = Nothing
            Screen.MousePointer = 0
        End If
    End If
    Call ErrorMessage(Extender.Name & ".GRD_ExcelExport")
End Sub


Private Function GetSalesRequestPrint(ByVal al_trwCode As Long, ByVal al_Level As Long, ByVal as_Type As String, ByVal ab_GrpMKT As Boolean, ByVal ab_GrpCT As Boolean, Optional ByVal as_MSA As String = "") As String
On Error GoTo ErrorHandler
    
    Dim ls_retVal As String
    GetSalesRequestPrint = ""
    Select Case as_Type
        Case "CG"
            Select Case al_trwCode
                Case 1  ' Market
                    Select Case al_Level
                        Case 0 ' All markets
                            ls_retVal = "EXEC Sales_CG_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 1 '/ Market
                            ls_retVal = "EXEC Sales_CGMarket_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$bmk_code$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 2  ' Country
                            ls_retVal = "EXEC Sales_CGCountry_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$bmk_code$', $CT_Code$, '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$, NULL, NULL"
                        Case 3  ' User
                            ls_retVal = ""
                    End Select
                    
                Case 2, 4 ' Area
                    Select Case al_Level
                        Case 0, 1 ' Area
                            ls_retVal = ""
                        Case 3  ' z_creator
                            ls_retVal = ""
                    End Select
                    
                Case 3
                    Select Case al_Level
                        Case 0  ' All markets
                            ls_retVal = "EXEC Sales_CG_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 1 ' Market
                            ls_retVal = "EXEC Sales_CGMarket_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$bmk_code$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 3  ' user
                            ls_retVal = ""
                    End Select
                Case 4  ' Area2
                    Select Case al_Level
                        Case 0  ' All markets
                            ls_retVal = "EXEC Sales_CG_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 1, 2 ' Area
                            ls_retVal = ""
                        Case 3  ' z_creator
                            ls_retVal = ""
                    End Select
                Case 5  ' market/ ... / customer
                    Select Case al_Level
                        Case 0 ' All markets
                            ls_retVal = "EXEC Sales_CG_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 1 '/ Market
                            ls_retVal = "EXEC Sales_CGMarket_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$bmk_code$', '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$"
                        Case 2, 3, 4 ' Country/Type/Customer
                            ls_retVal = "EXEC Sales_CGCountry_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$bmk_code$', $CT_Code$, '$CG_Code2$', '$UM_Code$', $AS_FLAG$, $METAL_FLAG$, $CCT_Code$, $CCU_CapKey$"
                    End Select

            End Select
        Case "OTHER"
            Select Case al_trwCode
                Case 1  ' Market
                    Select Case al_Level
                        Case 0  ' All markets
                            ls_retVal = "EXEC Sales_Other_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', $AS_FLAG$"
                        Case 1 ' Market
                            ls_retVal = "EXEC Sales_OtherMarket_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$bmk_code$', $AS_FLAG$"
                        Case 2  ' Country
                            ls_retVal = "EXEC Sales_OtherCountry_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$bmk_code$', $CT_Code$, $AS_FLAG$, NULL, NULL"
                        Case 3  ' User
                            ls_retVal = ""
                    End Select
                    
                Case 2, 4 ' Area
                    Select Case al_Level
                        Case 0, 1 ' Area
                            ls_retVal = ""
                        Case 3  ' z_creator
                            ls_retVal = ""
                    End Select
                    
                Case 3
                    Select Case al_Level
                        Case 0  ' All markets
                            ls_retVal = "EXEC Sales_Other_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', $AS_FLAG$"
                        Case 1 ' Market
                            ls_retVal = "EXEC Sales_OtherMarket_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$bmk_code$', $AS_FLAG$"
                        Case 3  ' user
                            ls_retVal = ""
                    End Select
                Case 4  ' Area
                    Select Case al_Level
                        Case 0      ' All markets
                            ls_retVal = "EXEC Sales_Other_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', $AS_FLAG$"
                        Case 1, 2 ' Area
                            ls_retVal = ""
                        Case 3  ' z_creator
                            ls_retVal = ""
                    End Select
                Case 5  ' market/ ... / customer
                    Select Case al_Level
                        Case 0 ' All markets
                            ls_retVal = "EXEC Sales_Other_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', $AS_FLAG$"
                        Case 1 ' Market
                            ls_retVal = "EXEC Sales_OtherMarket_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$bmk_code$', $AS_FLAG$"
                        Case 2, 3, 4  ' Country/Type/Customer
                            ls_retVal = "EXEC Sales_OtherCountry_%MKT%%CT%_Print" & as_MSA & " '$language_code$', '$STARTP$', '$ENDP$', '$bmk_code$', $CT_Code$, $AS_FLAG$, $CCT_Code$, $CCU_CapKey$"
                    End Select
            End Select
    End Select
    If Not ab_GrpCT And Not ab_GrpMKT Then
        ls_retVal = Replace(ls_retVal, "%MKT%%CT%_", "", , , vbTextCompare)
    Else
        ls_retVal = Replace(ls_retVal, "%MKT%", IIf(ab_GrpMKT, "MKT", ""), , , vbTextCompare)
        ls_retVal = Replace(ls_retVal, "%CT%", IIf(ab_GrpCT, "CT", ""), , , vbTextCompare)
    
    End If
    
    GetSalesRequestPrint = ls_retVal
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetSalesRequestPrint")
End Function



Private Function Get_A_Config(ByVal TheKey As String) As String
On Error GoTo Get_A_Config_er
Dim curs As Long
Dim ls_req As String

Get_A_Config = ""
ls_req = "select cfg_value from A_config where cfg_Key ='" & UCase(TheKey) & "'"
curs = p_da.OpenSQL(ls_req)
    If curs = 0 Then
        Err.Raise CompFncFailed, "CapPrdValOf.Get_A_Config", "Error executing " & ls_req & p_da.LastErrorCode & "  " & p_da.LastErrorMessage
    Else
        If p_da.RowCount(curs) <> 1 Then
            p_da.Close (curs)
            curs = 0
            Err.Raise CompFncFailed, "Get_A_Config", "Executing " & ls_req & " returned " & p_da.RowCount(curs) & " record(s) while one was expected"
        Else
            Get_A_Config = p_da.GetFields(curs, 0)
            Call p_da.Close(curs)
            curs = 0
        End If
    End If
Exit Function
Get_A_Config_er:
    If curs > 0 Then
        Call p_da.Close(curs)
        curs = 0
    End If
    Call ErrorHandler("Get_A_Config()")
End Function

Private Function CheckReportAvailable() As Boolean
On Error GoTo ErrorHandler
    CheckReportAvailable = True
    
    If Not cb_trw.SelectedItem Is Nothing Then
    
      If cb_trw.SelectedItem.GetData(0) <= 4 Then Exit Function ' all markets/market/country or area/rep are available for every report
    
      If Level_selected < 3 Then Exit Function ' Market/country/level of treeview 5 is aslo available
    
      If TabStrip1.SelectedItem.Key = "SALES" Then Exit Function ' level 4,5 available only for sales

    End If
    
    Call MsgBox(MsgText(1517, ms_Language_Code, "#Report is not available."), vbOKOnly)
    
    CheckReportAvailable = False
    Exit Function
    
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".CheckReportAvailable")
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


