VERSION 5.00
Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.1#0"; "mscomctl.ocx"
Object = "{65E121D4-0C60-11D2-A9FC-0000F8754DA1}#2.0#0"; "MSCHRT20.OCX"
Begin VB.UserControl MetalSalesAnalysis 
   ClientHeight    =   9225
   ClientLeft      =   0
   ClientTop       =   0
   ClientWidth     =   18840
   ScaleHeight     =   9225
   ScaleWidth      =   18840
   Begin VB.Frame fra_ReportSummary 
      Height          =   7815
      Left            =   7320
      TabIndex        =   21
      Top             =   840
      Width           =   11415
      Begin VB.CheckBox chk_LegendPosition 
         Caption         =   "Show Legend"
         Height          =   255
         Left            =   5760
         TabIndex        =   45
         Tag             =   "lbl_LegendPosition"
         Top             =   4560
         Width           =   1815
      End
      Begin Project1.ArmGrid grd_SalesSummaryTotal 
         Height          =   1095
         Left            =   120
         TabIndex        =   43
         Tag             =   "grd_SalesSummaryTotal"
         Top             =   3120
         Width           =   11175
         _ExtentX        =   19711
         _ExtentY        =   1931
      End
      Begin Project1.ArmCombobox cbo_ChartType 
         Height          =   345
         Left            =   1320
         TabIndex        =   39
         Top             =   4440
         Width           =   4215
         _ExtentX        =   7435
         _ExtentY        =   609
      End
      Begin MSChart20Lib.MSChart mch_SalesSummary 
         Height          =   2775
         Left            =   120
         OleObjectBlob   =   "MetalSalesAnalysis.ctx":0000
         TabIndex        =   23
         Top             =   4920
         Visible         =   0   'False
         Width           =   11175
      End
      Begin Project1.ArmGrid grd_SalesSummary 
         Height          =   2775
         Left            =   120
         TabIndex        =   22
         Top             =   240
         Width           =   11175
         _ExtentX        =   19711
         _ExtentY        =   4895
      End
      Begin Project1.ArmCombobox cbo_LegendPosition 
         Height          =   345
         Left            =   7680
         TabIndex        =   44
         Top             =   4440
         Width           =   3615
         _ExtentX        =   6376
         _ExtentY        =   609
      End
      Begin VB.Label lbl_ChartType 
         Caption         =   "#Type of Chart"
         Height          =   255
         Left            =   120
         TabIndex        =   38
         Tag             =   "lbl_ChartType"
         Top             =   4560
         Width           =   1335
      End
   End
   Begin VB.Frame fra_DailyReport 
      Caption         =   "#Daily Report"
      Height          =   3375
      Left            =   -465
      TabIndex        =   25
      Tag             =   "fra_DailyReport"
      Top             =   4380
      Width           =   8055
      Begin VB.Frame fra_DR_ReportType 
         Caption         =   "Report Type"
         Height          =   2055
         Left            =   3120
         TabIndex        =   35
         Top             =   360
         Width           =   3735
         Begin Project1.ArmCombobox cbo_DR_Month 
            Height          =   345
            Left            =   1560
            TabIndex        =   42
            Top             =   1560
            Width           =   2055
            _ExtentX        =   3625
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_DR_Year 
            Height          =   345
            Left            =   120
            TabIndex        =   41
            Top             =   1560
            Width           =   1335
            _ExtentX        =   2355
            _ExtentY        =   609
         End
         Begin VB.OptionButton opt_DR_ReportType 
            Caption         =   "#Custom Date"
            Height          =   375
            Index           =   2
            Left            =   120
            TabIndex        =   40
            Tag             =   "opt_DR_ReportType_Custom"
            Top             =   1200
            Width           =   1575
         End
         Begin VB.OptionButton opt_DR_ReportType 
            Caption         =   "#Current Month"
            Height          =   375
            Index           =   1
            Left            =   120
            TabIndex        =   37
            Tag             =   "opt_DR_ReportType_Month"
            Top             =   720
            Width           =   1575
         End
         Begin VB.OptionButton opt_DR_ReportType 
            Caption         =   "#Current Year"
            Height          =   255
            Index           =   0
            Left            =   120
            TabIndex        =   36
            Tag             =   "opt_DR_ReportType_Year"
            Top             =   360
            Width           =   1455
         End
      End
      Begin VB.Frame fra_DR_SalesType 
         Caption         =   "#Report Sales Type"
         Height          =   1575
         Left            =   120
         TabIndex        =   31
         Tag             =   "fra_DR_SalesType"
         Top             =   1200
         Width           =   2895
         Begin VB.OptionButton opt_DR_SalesType 
            Caption         =   "#Trade Sales"
            Height          =   255
            Index           =   2
            Left            =   120
            TabIndex        =   34
            Tag             =   "opt_DR_SalesType_Trade"
            Top             =   1080
            Width           =   1335
         End
         Begin VB.OptionButton opt_DR_SalesType 
            Caption         =   "#All Sales"
            Height          =   255
            Index           =   0
            Left            =   120
            TabIndex        =   33
            Tag             =   "opt_DR_SalesType_All"
            Top             =   360
            Value           =   -1  'True
            Width           =   1215
         End
         Begin VB.OptionButton opt_DR_SalesType 
            Caption         =   "#Interco"
            Height          =   255
            Index           =   1
            Left            =   120
            TabIndex        =   32
            Tag             =   "opt_DR_SalesType_Interco"
            Top             =   720
            Width           =   1095
         End
      End
      Begin VB.Frame fra_DR_Currency 
         Caption         =   "#Report Currency"
         Height          =   735
         Left            =   120
         TabIndex        =   28
         Tag             =   "fra_Currency"
         Top             =   360
         Width           =   2895
         Begin VB.OptionButton opt_DR_Currency 
            Caption         =   "#Dollar"
            Height          =   255
            Index           =   1
            Left            =   1560
            TabIndex        =   30
            Tag             =   "opt_DR_Currency_Dollar"
            Top             =   360
            Width           =   1095
         End
         Begin VB.OptionButton opt_DR_Currency 
            Caption         =   "#Euro"
            Height          =   255
            Index           =   0
            Left            =   120
            TabIndex        =   29
            Tag             =   "opt_DR_Currency_Euro"
            Top             =   360
            Value           =   -1  'True
            Width           =   855
         End
      End
      Begin VB.CommandButton cmd_DR_Quit 
         Caption         =   "#Exit"
         Height          =   615
         Left            =   3960
         Style           =   1  'Graphical
         TabIndex        =   27
         Top             =   2520
         Width           =   855
      End
      Begin VB.CommandButton cmd_DR_Export 
         Caption         =   "#Export"
         Height          =   615
         Left            =   6960
         Style           =   1  'Graphical
         TabIndex        =   26
         Top             =   960
         Width           =   855
      End
   End
   Begin VB.CommandButton cmd_DailyReport 
      Caption         =   "#Daily Report"
      Height          =   615
      Left            =   4320
      Style           =   1  'Graphical
      TabIndex        =   24
      Tag             =   "cmd_DailyReport"
      Top             =   120
      Width           =   855
   End
   Begin VB.Frame fra_ReportDetail 
      Height          =   7815
      Left            =   7320
      TabIndex        =   12
      Top             =   840
      Width           =   11415
      Begin VB.Frame fra_SUM 
         BorderStyle     =   0  'None
         Height          =   495
         Left            =   3480
         TabIndex        =   14
         Top             =   7200
         Width           =   7815
         Begin VB.TextBox txt_InvoiceAmountSUM 
            Alignment       =   1  'Right Justify
            BackColor       =   &H80000011&
            Height          =   375
            Left            =   5640
            Locked          =   -1  'True
            TabIndex        =   16
            Tag             =   "AmountMultipleCurrency"
            Top             =   0
            Width           =   2175
         End
         Begin VB.TextBox txt_TotalQuantity 
            Alignment       =   1  'Right Justify
            BackColor       =   &H80000011&
            Height          =   375
            Left            =   1200
            Locked          =   -1  'True
            TabIndex        =   15
            Tag             =   "AmountMultipleCurrency"
            Top             =   0
            Width           =   2175
         End
         Begin VB.Label lbl_InvoiceAmount 
            Caption         =   "#Invoice Amount:"
            Height          =   255
            Left            =   3960
            TabIndex        =   18
            Tag             =   "lbl_InvoiceAmount"
            Top             =   120
            Width           =   1455
         End
         Begin VB.Label lbl_TotalQuantity 
            Caption         =   "#Quantity"
            Height          =   255
            Left            =   120
            TabIndex        =   17
            Tag             =   "lbl_TotalQuantity"
            Top             =   120
            Width           =   1095
         End
      End
      Begin Project1.ArmGrid grd_Sales 
         Height          =   6855
         Left            =   120
         TabIndex        =   13
         Tag             =   "grd_Sales"
         Top             =   240
         Width           =   11175
         _ExtentX        =   19711
         _ExtentY        =   12091
      End
      Begin VB.Label lbl_AmountMultipleCurrency 
         Caption         =   "#Multiple currency"
         Height          =   255
         Left            =   240
         TabIndex        =   20
         Tag             =   "lbl_AmountMultipleCurrency"
         Top             =   7200
         Visible         =   0   'False
         Width           =   1815
      End
      Begin VB.Label lbl_MultipleUoM 
         Caption         =   "#Multiple UoM"
         Height          =   375
         Left            =   1200
         TabIndex        =   19
         Tag             =   "lbl_MultipleUoM"
         Top             =   7080
         Visible         =   0   'False
         Width           =   1815
      End
   End
   Begin MSComctlLib.TabStrip tbs_Report 
      Height          =   375
      Left            =   7320
      TabIndex        =   11
      Tag             =   "tbs_Report"
      Top             =   8640
      Width           =   11415
      _ExtentX        =   20135
      _ExtentY        =   661
      TabWidthStyle   =   2
      MultiRow        =   -1  'True
      Placement       =   1
      _Version        =   393216
      BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
         NumTabs         =   2
         BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
            Caption         =   "#Summary"
            Key             =   "S"
            ImageVarType    =   2
         EndProperty
         BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
            Caption         =   "#Detail"
            Key             =   "D"
            ImageVarType    =   2
         EndProperty
      EndProperty
   End
   Begin VB.CommandButton cmd_Load 
      Caption         =   "#Load"
      Height          =   615
      Left            =   7320
      Style           =   1  'Graphical
      TabIndex        =   9
      Tag             =   "cmd_Load"
      Top             =   120
      Width           =   855
   End
   Begin VB.CommandButton cmd_Quit 
      Caption         =   "#Quit"
      Height          =   615
      Left            =   17880
      Style           =   1  'Graphical
      TabIndex        =   8
      Tag             =   "cmd_Quit"
      Top             =   120
      Width           =   855
   End
   Begin VB.Frame fra_Currency 
      Caption         =   "#Report Currency"
      Height          =   735
      Left            =   120
      TabIndex        =   5
      Tag             =   "fra_Currency"
      Top             =   0
      Width           =   4095
      Begin VB.OptionButton opt_Currency 
         Caption         =   "#Local"
         Height          =   255
         Index           =   2
         Left            =   2520
         TabIndex        =   7
         Tag             =   "opt_Currency_Local"
         Top             =   360
         Width           =   1335
      End
      Begin VB.OptionButton opt_Currency 
         Caption         =   "#Euro"
         Height          =   255
         Index           =   1
         Left            =   120
         TabIndex        =   1
         Tag             =   "opt_Currency_Euro"
         Top             =   360
         Value           =   -1  'True
         Width           =   855
      End
      Begin VB.OptionButton opt_Currency 
         Caption         =   "#Dollar"
         Height          =   255
         Index           =   0
         Left            =   1200
         TabIndex        =   6
         Tag             =   "opt_Currency_Dollar"
         Top             =   360
         Width           =   1095
      End
   End
   Begin VB.Frame frm_Tree 
      Height          =   8295
      Left            =   120
      TabIndex        =   0
      Top             =   840
      Width           =   6975
      Begin MSComctlLib.TabStrip tbs_Interco 
         Height          =   375
         Left            =   120
         TabIndex        =   10
         Tag             =   "tbs_Interco"
         Top             =   7800
         Width           =   6735
         _ExtentX        =   11880
         _ExtentY        =   661
         TabWidthStyle   =   2
         Style           =   2
         Placement       =   1
         _Version        =   393216
         BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
            NumTabs         =   3
            BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#All sales"
               Key             =   "A"
               Object.Tag             =   "NULL"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Interco"
               Key             =   "Yes"
               Object.Tag             =   "'X'"
               ImageVarType    =   2
            EndProperty
            BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
               Caption         =   "#Trades Sales"
               Key             =   "N"
               Object.Tag             =   "''"
               ImageVarType    =   2
            EndProperty
         EndProperty
      End
      Begin Project1.ArmCombobox cbo_Views 
         Height          =   345
         Left            =   1200
         TabIndex        =   4
         Top             =   240
         Width           =   5655
         _ExtentX        =   9975
         _ExtentY        =   609
      End
      Begin Project1.ArmTreeView trv_Tree 
         Height          =   7095
         Left            =   120
         TabIndex        =   2
         Top             =   720
         Width           =   6735
         _ExtentX        =   11880
         _ExtentY        =   12515
      End
      Begin VB.Label lbl_View 
         Caption         =   "#View"
         Height          =   255
         Left            =   120
         TabIndex        =   3
         Tag             =   "lbl_View"
         Top             =   360
         Width           =   975
      End
   End
End
Attribute VB_Name = "MetalSalesAnalysis"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit
'what is new
'2.7.1 bugfix: export excell for months with more than 24 working days (JN)

Private Declare Function LockWindowUpdate Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function GetLocaleInfo Lib "kernel32" Alias "GetLocaleInfoA" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long
Private Declare Function GetSystemDefaultLCID Lib "kernel32" () As Long

Private Const LOCALE_USER_DEFAULT = &H400

Private Const LOCALE_SDECIMAL = &HE ' Decimal separator
Private Const LOCALE_STHOUSAND = &HF ' Thousand separator

Private ms_MonthNames(1 To 12) As String
Private Const SCREEN_NAME = "MSA_Main"

Private Const C_RPT_PER_YEAR As String = "Y"        ' Summary Report for a Year (so in month)
Private Const C_RPT_PER_MONTH As String = "M"       ' Summary Report for a Month (so in days)
Private Const C_RPT_PER_NEXTLEVEL As String = "L"   ' Summary Report for Next Level
Private Const C_RPT_NONE As String = "N"            ' No Summary Report


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 xlMedium              As Integer = -4138
Private Const xlThin                As Integer = 2 '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

Private Type TTreeViewInfo
    TreeViewCode As String
    TreeViewDesc As String

    Loaded As Boolean
    
    Levels As Long
    NodeRequest() As String
    GridDetailRequest() As String
    ExcelRequest() As String
    CountRequest() As String
    FindRequest() As String
    Images() As Integer
    SelectedImages() As Integer
    AsCurrency As Boolean
End Type

Private mo_TreeViewInfos() As TTreeViewInfo

Private ms_DecimalSeparator  As String
Private ms_ThousandSeparator As String

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

Private mb_Initialized As Boolean   ' Indicate if the Module has been initialized
Private mo_Db As ARMSYSCOMLib.ArmDb
Private ms_Language_Code As String
Private ml_U_Code As Long
Private ms_LoginName As String

Private mb_Internal As Boolean

Private mb_ShowSummary As Boolean   ' Indicate if we are showing the summary report

Private Const C_COL_QTY_NAME As String = "Quantity"
Private Const C_COL_UOM_NAME As String = "Unit_Of_Measure"
Private Const C_COL_CURRENCY_NAME As String = "CURR_Code"
Private Const C_COL_CURRENCY_WIDTH  As Long = 800
Private Const C_COL_AMOUNT_NAME As String = "Amount_Invoice"

Private Const C_COL_BITCODE_NAME As String = "BIT_Code"
Private Const C_COL_BITDESC_NAME As String = "BIT_Desc"
Private Const C_COL_ORCODE_NAME As String = "OR_Code"
Private Const C_COL_ORDESC_NAME As String = "OR_Desc"
Private Const C_COL_BILLING_NAME As String = "Billing"

Private Const C_SUMMARY_COL_ID As String = "ID"
Private Const C_SUMMARY_COL_DESC As String = "Desc"
Private Const C_SUMMARY_COL_STDCURR As String = 3
Private Const C_SUMMARY_COL_SEL As String = "SEL"
Private Const C_SUMMARY_TOKEN_SEL As String = "*"

Private mb_UseLocalCurrency As Boolean ' Indicate if the report use the local currency of the transaction

Private Const C_TABS_TRADESALES As Integer = 3

Private Enum ArmErr
    DBCnxFailed = C_ERRORRAISE + 1             ' Unable to connect to the database
    CPTAlreadyInitialized = C_ERRORRAISE + 2   ' We try to initialize a component that is already initialized
    CPTNotInitialized = C_ERRORRAISE + 3       ' We try to use or free that is not initialized yet
    InvalidArgument = C_ERRORRAISE + 4
    PropertyNotSet = C_ERRORRAISE + 5
    SQLFailure = C_ERRORRAISE + 6               ' A SQL runtime error has occured : syntax wrong....
    SQLBadRowAffectedCount = C_ERRORRAISE + 7   ' A SQL request has not affected the expected rowcount (ex: one Update do nothing)
    SQLBadRowExpectedCount = C_ERRORRAISE + 8   ' A SQL request does not return the expected rowcount : select an item return nothing...
    DrivingError = C_ERRORRAISE + 9
    CompFncFailed = C_ERRORRAISE + 10           ' when component function fail
    GridLoadFailed = C_ERRORRAISE + 11          ' load function failed ... bad sql
    InvalidValue = C_ERRORRAISE + 12          ' load function failed ... bad sql
End Enum


Private Enum DailyReportType
    drtYear = 1
    drtMonth = 2
End Enum

Private Type TDailyReportRequest
    Title As String
    Colour As Long
    Request As String
    ReportType As DailyReportType
End Type

Private ml_LastSummaryRowSel As Long

Private mo_DailyReportRequests() As TDailyReportRequest

'**********************************************************************************************************************************
'**********************************************************************************************************************************
' FRAMEWORK EVENTS
'**********************************************************************************************************************************
'**********************************************************************************************************************************

Public Event quit()

'**********************************************************************************************************************************
'**********************************************************************************************************************************
' FRAMEWORK INTERFACE AND PROPERTIES
' please DO NOT change anything in this part of code
'**********************************************************************************************************************************
'**********************************************************************************************************************************
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

Public Property Let U_Code(ByVal al_U_Code As Long)
On Error GoTo ErrHandler
    
    If Initialized Then Call Err.Raise(ArmErr.CPTAlreadyInitialized)
    
    ml_U_Code = al_U_Code
    Exit Property
ErrHandler:
    Call ErrorHandler("U_Code(Let)")
End Property

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

Public Property Let Language_Code(as_Language_Code As String)
On Error GoTo ErrHandler
    
    If Initialized Then Call Err.Raise(ArmErr.CPTAlreadyInitialized)
    If Len(as_Language_Code) <> 1 Then Call Err.Raise(ArmErr.InvalidArgument, "", "Language_code must contains only 1 char")
    
    ms_Language_Code = as_Language_Code
    Exit Property
    
ErrHandler:
    Call ErrorHandler("Language(Let)")
End Property

Public Property Set DB(ByRef ao_Db As ArmDb)
On Error GoTo ErrHandler
    
    If Initialized Then Call Err.Raise(ArmErr.CPTAlreadyInitialized)
    If ao_Db Is Nothing Then Call Err.Raise(ArmErr.InvalidArgument)
    
    Set mo_Db = ao_Db
    Exit Property
ErrHandler:
    Call ErrorHandler("Db(Set)")
End Property


' 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


Public Sub Unload_A_COM()
On Error GoTo ErrHandler
    
    Set mo_Db = Nothing
    Exit Sub

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


Public Sub Load_A_COM()

On Error GoTo ErrHandler

    ms_MonthNames(1) = "January"
    ms_MonthNames(2) = "February"
    ms_MonthNames(3) = "March"
    ms_MonthNames(4) = "April"
    ms_MonthNames(5) = "May"
    ms_MonthNames(6) = "June"
    ms_MonthNames(7) = "July"
    ms_MonthNames(8) = "August"
    ms_MonthNames(9) = "September"
    ms_MonthNames(10) = "October"
    ms_MonthNames(11) = "November"
    ms_MonthNames(12) = "December"

    mb_Internal = True
    
    fra_ReportDetail.Visible = False
    fra_ReportSummary.Visible = False
    
    mb_ShowSummary = True
    
    Set tbs_Interco.SelectedItem = tbs_Interco.Tabs(C_TABS_TRADESALES)

    Dim ls_Buffer As String
    Dim ll_BufferLen As Long
    Dim ll_LCID As Long

    ll_LCID = GetSystemDefaultLCID
    
    ms_DecimalSeparator = Format(0, ".")

    ll_BufferLen = 255
    ls_Buffer = String$(ll_BufferLen, vbNullChar)
    ll_BufferLen = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, ls_Buffer, ll_BufferLen)
    If ll_BufferLen > 0 Then
        ms_ThousandSeparator = Left$(ls_Buffer, ll_BufferLen - 1)
    End If

    ' Initialize Grid
    Set grd_Sales.ArmDb = mo_Db
    grd_Sales.Load_A_COM
    grd_Sales.AllowExcelExport = True
    grd_Sales.ExportTitles = True
    grd_Sales.AllowSort = True
    grd_Sales.AllowMultiSort = True
    grd_Sales.ExportOnlyVisibleColumns = True
    
    Dim lv_Columns As Variant
    ReDim lv_Columns(16)
    
    lv_Columns(0) = Join(Array("MSA_ID", 0, 1, "MSA_ID", "#MSA_ID"), SEP)
    lv_Columns(1) = Join(Array("Document_Number", 1500, 1, "Document_Number", "#Document_Number"), SEP)
    lv_Columns(2) = Join(Array("CT_Name", 2000, 0, "CT_Name", "#Country"), SEP)
    lv_Columns(3) = Join(Array("COMP_Desc", 2000, 0, "COMP_Desc", "#Selling Company"), SEP)
    lv_Columns(4) = Join(Array("Customer_Name", 3000, 0, "Customer_Name", "#Customer"), SEP)
    lv_Columns(5) = Join(Array("Document_Date", 1500, 0, "Document_Date", "#Date"), SEP)
    lv_Columns(6) = Join(Array("Material_Number", 2000, 0, "Material_Number", "#Material Number"), SEP)
    lv_Columns(7) = Join(Array("Material_Desc", 2000, 0, "Material_Desc", "#Material"), SEP)
    lv_Columns(8) = Join(Array(C_COL_CURRENCY_NAME, C_COL_CURRENCY_WIDTH, 0, "CURR_Code", "#Currency"), SEP)
    lv_Columns(9) = Join(Array(C_COL_AMOUNT_NAME, 1500, 0, "Amount_Invoice", "#Amount Invoice", "FLOAT", "###,###,##0.00"), SEP)
    lv_Columns(10) = Join(Array(C_COL_UOM_NAME, 800, 0, "Unit_Of_Measure", "#UOM"), SEP)
    lv_Columns(11) = Join(Array(C_COL_QTY_NAME, 1500, 0, "Quantity", "#Quantity"), SEP)
    lv_Columns(12) = Join(Array(C_COL_BILLING_NAME, 2500, 0, "", "Billing"), SEP)
    lv_Columns(13) = Join(Array(C_COL_BITCODE_NAME, 0, 0, "BIT_CODE", ""), SEP)
    lv_Columns(14) = Join(Array(C_COL_BITDESC_NAME, 0, 0, "BIT_Desc", ""), SEP)
    lv_Columns(15) = Join(Array(C_COL_ORCODE_NAME, 0, 0, "OR_Code", ""), SEP)
    lv_Columns(16) = Join(Array(C_COL_ORDESC_NAME, 0, 0, "OR_Desc", ""), SEP)
    
    If Not grd_Sales.SetColumns(lv_Columns) Then
        Call MsgBox("Unable to Load the columns of the Grid")
        Call Unload_A_COM
        End
    End If
    
    
    Set grd_SalesSummary.ArmDb = mo_Db
    grd_SalesSummary.Load_A_COM
    grd_SalesSummary.AllowExcelExport = True
    grd_SalesSummary.ExportTitles = True
    grd_SalesSummary.AllowSort = True
    grd_SalesSummary.AllowMultiSort = True
    grd_SalesSummary.ExportOnlyVisibleColumns = True
    grd_SalesSummary.UnBound = True
    
    Set grd_SalesSummaryTotal.ArmDb = mo_Db
    grd_SalesSummaryTotal.Load_A_COM
    grd_SalesSummaryTotal.AllowExcelExport = False
    grd_SalesSummaryTotal.UnBound = True
    
    
    mb_UseLocalCurrency = False
    
    ' Initializing the treeview
    Set trv_Tree.ArmDb = mo_Db
    trv_Tree.Language = ms_Language_Code
    trv_Tree.AllowCheckboxes = False
    trv_Tree.UseImages = False
    trv_Tree.Load_A_COM
    
    ' Initializing the view combo
    Set cbo_Views.ArmDb = mo_Db
    Call cbo_Views.Load_A_COM
    Call cbo_Views.Clear
    cbo_Views.FirstBlankItem = False
    
    
    ' Get The treeview list
    Dim ls_Request As String
    ls_Request = "exec TreeView_View_t_lst '" & SCREEN_NAME & "'," & "'" & ms_Language_Code & "'"
    
    Dim lc_Views As Long
    lc_Views = mo_Db.OpenSQL(ls_Request)
    
    
    Dim ll_Idx As Long, ll_Count As Long
    ll_Count = mo_Db.RowCount(lc_Views)
    
    
    Dim ls_DefaultView As String
    ReDim mo_TreeViewInfos(ll_Count - 1)
    For ll_Idx = 0 To ll_Count - 1
        mo_TreeViewInfos(ll_Idx).Loaded = False
        mo_TreeViewInfos(ll_Idx).TreeViewCode = mo_Db.GetFields(lc_Views, "TV_Code")
        mo_TreeViewInfos(ll_Idx).TreeViewDesc = mo_Db.GetFields(lc_Views, "TV_Desc")
        If mo_Db.GetFields(lc_Views, "TV_Default") = "X" Then ls_DefaultView = mo_TreeViewInfos(ll_Idx).TreeViewCode
       
        mo_Db.Next (lc_Views)
    Next
    
    mo_Db.Close (lc_Views)
    
    opt_Currency(1).Value = True
    Call ApplyCurrency

    Call LoadLabels(UserControl.Controls, SCREEN_NAME, ms_Language_Code)
    Call ChangeCharset(UserControl.Controls, GetCodePageFromLanguage(mo_Db, ms_Language_Code))
    
    txt_InvoiceAmountSUM.Text = ""
    txt_TotalQuantity.Text = ""
    
    cmd_Load.Picture = LoadResPicture(RES_FILLGRID, 1)
    cmd_Load.Caption = ""
    cmd_Quit.Picture = LoadResPicture(RES_QUIT, 1)
    cmd_Quit.Caption = ""

    cmd_DR_Export.Caption = ""
    cmd_DR_Export.Picture = LoadResPicture(RES_EXCEL, 1)
    
    cmd_DR_Quit.Caption = ""
    cmd_DR_Quit.Picture = LoadResPicture(RES_QUIT, 1)

    cmd_DailyReport.Caption = ""
    cmd_DailyReport.Picture = LoadResPicture(58, 1)
  

    fra_DailyReport.Visible = False

    mb_Internal = False
    Call cbo_Views.SearchItem(ls_DefaultView, 0, , True)
    
    Call LoadDailyReportRequests
    
    cbo_DR_Year.Load_A_COM
    Set cbo_DR_Year.ArmDb = mo_Db
    
    Dim lc_DRYearBound As Long
    lc_DRYearBound = mo_Db.OpenSQL("MSA_GetDailyReportYearBound")
    
    Dim ll_YearMin As Integer, ll_YearMax As Long, ll_YearCurrent
    ll_YearMin = mo_Db.GetFields(lc_DRYearBound, 0)
    ll_YearMax = mo_Db.GetFields(lc_DRYearBound, 1)
    ll_YearCurrent = Year(Date)
    
    mo_Db.Close (lc_DRYearBound)
    
    For ll_Idx = ll_YearMin To ll_YearMax
        Call cbo_DR_Year.AddItem(Array(ll_Idx, ll_Idx), ll_Idx = ll_YearCurrent)
    Next
    
    
    cbo_DR_Month.Load_A_COM
    Set cbo_DR_Month.ArmDb = mo_Db
    
    Call cbo_DR_Month.AddItem(Array(0, ""))

    Dim ll_MonthCurrent As Long
    ll_MonthCurrent = Month(Date)
    For ll_Idx = 1 To 12
        Call cbo_DR_Month.AddItem(Array(ll_Idx, ms_MonthNames(ll_Idx)))
    Next
    
    cbo_ChartType.Load_A_COM
    Set cbo_ChartType.ArmDb = mo_Db
    cbo_ChartType.Request = "A_References_ML_LST 3101, '" & ms_Language_Code & "'"
    cbo_ChartType.Load
    Call cbo_ChartType.SearchItem(1, 0, , True)
    
    cbo_LegendPosition.Load_A_COM
    Set cbo_LegendPosition.ArmDb = mo_Db
    cbo_LegendPosition.Request = "A_References_ML_LST 3102, '" & ms_Language_Code & "'"
    cbo_LegendPosition.Load
    Call cbo_LegendPosition.SearchItem(VtChLocationTypeBottomLeft, 0, , True)
    
    'mch_SalesSummary.Legend.Location.LocationType = VtChLocationTypeBottomLeft
    
    mb_Initialized = True

    Exit Sub

ErrHandler:
    mo_Db.Close (lc_DRYearBound)
    LogErrorMessage ("Load_A_Com")
    Call ErrorHandler(Extender.Name & ".Load_A_Com")
End Sub




Private Sub LoadDailyReportRequests()

On Error GoTo ErrHandler:
    Const C_REQUEST As String = "MSA_GetDailyReportRequest"
    
    Dim lc_ReportRequests As Long
    lc_ReportRequests = mo_Db.OpenSQL(C_REQUEST)
    lc_ReportRequests = mo_Db.Sort(lc_ReportRequests, Array("DRR_ReportType", "Z_Order"), , True)
    
    Dim ll_Idx As Long, ll_Count As Long
    ll_Count = mo_Db.RowCount(lc_ReportRequests) - 1
    ReDim mo_DailyReportRequests(ll_Count)
    For ll_Idx = 0 To ll_Count
        mo_DailyReportRequests(ll_Idx).Title = mo_Db.GetFields(lc_ReportRequests, "DRR_Title")
        mo_DailyReportRequests(ll_Idx).Colour = mo_Db.GetFields(lc_ReportRequests, "DRR_Colour")
        mo_DailyReportRequests(ll_Idx).Request = mo_Db.GetFields(lc_ReportRequests, "DRR_Request")
        mo_DailyReportRequests(ll_Idx).ReportType = IIf(mo_Db.GetFields(lc_ReportRequests, "DRR_ReportType") = 1, DailyReportType.drtYear, DailyReportType.drtMonth)
        mo_Db.Next (lc_ReportRequests)
    Next

    mo_Db.Close (lc_ReportRequests)
    lc_ReportRequests = 0

    Exit Sub
ErrHandler:
    If (lc_ReportRequests <> 0) Then Call mo_Db.Close(lc_ReportRequests)
    Call ErrorHandler(Extender.Name & ".LoadDailyReportRequests")
End Sub

' Occured when the user select a new view for the treeview
Private Sub cbo_Views_ComboItemSelected()
On Error GoTo ErrHandler

    If mb_Internal Then Exit Sub
    
    Dim ab_lock As Boolean
    ab_lock = LockScreen(True)
    
    If cbo_Views.SelectedItem Is Nothing Then Exit Sub
    
    Call LoadTreeView(GetTreeViewInfo(cbo_Views.SelectedItem.Key))

    ab_lock = LockScreen(False)
    
    Exit Sub

ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("cbo_Views_ComboItemSelected")

End Sub


Private Sub chk_LegendPosition_Click()
On Error GoTo ErrHandler
    mch_SalesSummary.ShowLegend = (chk_LegendPosition.Value = 1)
    Exit Sub
ErrHandler:
    Call LogErrorMessage("cmd_Quit_Click")
End Sub

' Occured when the user press the click button
Private Sub cmd_Quit_Click()
On Error GoTo ErrHandler
    
    RaiseEvent quit
    Exit Sub

ErrHandler:
    Call LogErrorMessage("cmd_Quit_Click")
End Sub


' Load the Views of the treeviews
Private Sub LoadViews(ByVal as_SelectedID As String)
On Error GoTo ErrHandler

    Dim lb_Internal As Boolean
    lb_Internal = mb_Internal
    mb_Internal = True

    cbo_Views.Clear
    
    Dim ll_Index As Long, ll_Count As Long
    ll_Count = UBound(mo_TreeViewInfos)
    
    For ll_Index = 0 To ll_Count
        Dim lo_ID As String
        Dim lo_desc As String
        lo_ID = mo_TreeViewInfos(ll_Index).TreeViewCode
        If (Not mb_UseLocalCurrency) Then
            Dim lv_Levels As Variant
            lv_Levels = Split(mo_TreeViewInfos(ll_Index).TreeViewDesc, ", ", , vbTextCompare)
            ReDim Preserve lv_Levels(UBound(lv_Levels) - 1)
            lo_desc = Join(lv_Levels, ", ")
        Else
        
            lo_desc = mo_TreeViewInfos(ll_Index).TreeViewDesc
        End If
        
        Call cbo_Views.AddItem(Array(lo_ID, lo_desc), lo_ID = as_SelectedID)
    Next
    
    
    If Not (cbo_Views.SelectedItem Is Nothing) Then
        Call LoadTreeView(GetTreeViewInfo(cbo_Views.SelectedItem.Key))
    End If
    
    mb_Internal = lb_Internal
    Exit Sub

ErrHandler:
        Call ErrorHandler(Extender.Name & ".LoadViews")

End Sub




' Return the Treeview information
Private Function GetTreeViewInfo(ByVal as_TVCode As String) As TTreeViewInfo
On Error GoTo ErrHandler

    Dim ll_Idx As Long, ll_Count As Long
    Dim lo_TreeView As TTreeViewInfo, lb_Found As Boolean
    
    ' Search in the array
    ll_Count = UBound(mo_TreeViewInfos)
    lb_Found = False
    For ll_Idx = 0 To ll_Count
        If mo_TreeViewInfos(ll_Idx).TreeViewCode = as_TVCode Then
            mo_TreeViewInfos(ll_Idx).Loaded = False
            If Not mo_TreeViewInfos(ll_Idx).Loaded Then
                Call LoadTreeViewInfoFromDB(mo_TreeViewInfos(ll_Idx))
            End If
            lo_TreeView = mo_TreeViewInfos(ll_Idx)
            lb_Found = True
            Exit For
        End If
    Next
    
    If Not lb_Found Then
        Err.Raise -1, "GetTreeViewInfo", "The Treeview " & as_TVCode & " is not found"
    End If
    
    GetTreeViewInfo = lo_TreeView
    Exit Function

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



' Load the informations of a treeview from the DB
Private Sub LoadTreeViewInfoFromDB(ByRef ao_TreeviewInfo As TTreeViewInfo)
On Error GoTo ErrHandler

    Dim ls_Request As String
    Dim lc_Curs As Long, ll_Idx As Long, ll_Count As Long
    
    ' Get the data from the DB
    ls_Request = "EXEC Treeview_Parameters_lst '" & SCREEN_NAME & "', '" & ao_TreeviewInfo.TreeViewCode & "'"
    lc_Curs = mo_Db.OpenSQL(ls_Request)
    
    ll_Count = mo_Db.RowCount(lc_Curs) - 1
    
    If ll_Count = -1 Then
        Err.Raise -1, "LoadTreeViewInfoFromDB", "The Treeview " & ao_TreeviewInfo.TreeViewCode & " is not defined in the DB for the screen " & SCREEN_NAME
    End If
    
    ReDim ao_TreeviewInfo.NodeRequest(ll_Count)
    ReDim ao_TreeviewInfo.GridDetailRequest(ll_Count)
    ReDim ao_TreeviewInfo.ExcelRequest(ll_Count)
    ReDim ao_TreeviewInfo.FindRequest(ll_Count)
    ReDim ao_TreeviewInfo.CountRequest(ll_Count)
    ReDim ao_TreeviewInfo.Images(ll_Count)
    ReDim ao_TreeviewInfo.SelectedImages(ll_Count)
    
    Dim ll_Level As Long, lv_GridRequest As Variant
    For ll_Idx = 0 To ll_Count
        ll_Level = mo_Db.GetFields(lc_Curs, "TV_Level")
        ao_TreeviewInfo.NodeRequest(ll_Level) = mo_Db.GetFields(lc_Curs, "TV_NodeRequest")
        ao_TreeviewInfo.GridDetailRequest(ll_Level) = mo_Db.GetFields(lc_Curs, "TV_GridRequest")
        ao_TreeviewInfo.ExcelRequest(ll_Level) = mo_Db.GetFields(lc_Curs, "TV_ExcelRequest")
        ao_TreeviewInfo.FindRequest(ll_Level) = mo_Db.GetFields(lc_Curs, "TV_FindRequest")
        ao_TreeviewInfo.CountRequest(ll_Level) = mo_Db.GetFields(lc_Curs, "TV_CountRequest")
        ao_TreeviewInfo.Images(ll_Level) = mo_Db.GetFields(lc_Curs, "TV_Images")
        ao_TreeviewInfo.SelectedImages(ll_Level) = mo_Db.GetFields(lc_Curs, "TV_SelectedImages")
        mo_Db.Next (lc_Curs)
    Next
    
    ao_TreeviewInfo.Levels = ll_Count + 1
    ao_TreeviewInfo.Loaded = True
    
    mo_Db.Close (lc_Curs)

    Exit Sub

ErrHandler:
    Call ErrorHandler(Extender.Name & ".LoadTreeViewInfoFromDB")
End Sub


Private Function GetSelectedCurrencySuffix() As String
On Error GoTo ErrHandler

    Dim ll_Idx As Long, ll_Count As Long
    ll_Count = opt_Currency.UBound
    
    For ll_Idx = opt_Currency.LBound To opt_Currency.UBound
        If VarType(opt_Currency(ll_Idx)) = vbObject Then GoTo NextItem
        If opt_Currency(ll_Idx).Value Then
            Select Case ll_Idx
                Case 0:
                    GetSelectedCurrencySuffix = "Dollar"
                Case 1:
                    GetSelectedCurrencySuffix = "Euro"
                Case 2:
                    GetSelectedCurrencySuffix = "Currency"
            End Select
            Exit Function
        End If
NextItem:
    Next
    
    GetSelectedCurrencySuffix = ""
 Exit Function

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



Private Function ReplacePlaceholders(ByVal as_Request As String, Optional ByVal as_Suffix As String = SEP) As String
        
        Dim ls_Request As String, ls_Suffix As String
        
        If as_Suffix = SEP Then
            ls_Suffix = GetSelectedCurrencySuffix()
        Else
            ls_Suffix = as_Suffix
        End If
        
        ls_Request = as_Request
        ls_Request = Replace(ls_Request, "$Interco$", tbs_Interco.SelectedItem.Tag, , , vbTextCompare)
        ls_Request = Replace(ls_Request, "$CURR$", ls_Suffix, , , vbTextCompare)
        ReplacePlaceholders = ls_Request

End Function


Private Function ReplacePlaceholdersInList(ByVal ao_Requests As Variant) As Variant

    Dim ls_Requests As Variant
    ls_Requests = ao_Requests
    Dim ls_GridRequestSuffix As String
    ls_GridRequestSuffix = GetSelectedCurrencySuffix()
    
    Dim ll_Index As Long, ll_Count As Long, ls_Request As String
    ll_Count = UBound(ao_Requests)
    For ll_Index = 0 To ll_Count
        ls_Request = ls_Requests(ll_Index)
        ls_Request = Replace(ls_Request, "$Interco$", tbs_Interco.SelectedItem.Tag, , , vbTextCompare)
        ls_Request = Replace(ls_Request, "$CURR$", ls_GridRequestSuffix, , , vbTextCompare)
        ls_Requests(ll_Index) = ReplacePlaceholders(ls_Requests(ll_Index), ls_GridRequestSuffix)
    Next
    
    ReplacePlaceholdersInList = ls_Requests
    

End Function



' Load A treeview
Private Function LoadTreeView(ByRef ao_TreeviewInfo As TTreeViewInfo) As Boolean
On Error GoTo ErrHandler

    Dim lb_Internal As Boolean
    lb_Internal = mb_Internal
    mb_Internal = True
    
    trv_Tree.Clear
    ClearReport

    Dim ll_LevelCount As Long
    Dim ll_Idx As Long, ll_Count As Long

    ll_LevelCount = IIf(mb_UseLocalCurrency, ao_TreeviewInfo.Levels, ao_TreeviewInfo.Levels - 1)
    trv_Tree.Levels = ll_LevelCount
    trv_Tree.StartDemandLevel = 1
    trv_Tree.SelectedImages = ao_TreeviewInfo.SelectedImages
    trv_Tree.Images = ao_TreeviewInfo.Images
    trv_Tree.NodeRequests = ReplacePlaceholdersInList(ao_TreeviewInfo.NodeRequest)
    trv_Tree.GridRequests = ReplacePlaceholdersInList(ao_TreeviewInfo.GridDetailRequest)
    
    trv_Tree.FindRequests = ReplacePlaceholdersInList(ao_TreeviewInfo.FindRequest)
    trv_Tree.CountRequests = ReplacePlaceholdersInList(ao_TreeviewInfo.CountRequest)
    
    If Not trv_Tree.LoadTree(LoadTypeChildsDemand) Then
        LoadTreeView = False
    End If
    
    
    LoadTreeView = True
    
    mb_Internal = lb_Internal
    
    Exit Function

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



Private Sub ClearReport()
    On Error GoTo ErrHandler
    
    grd_Sales.Requests = ""
    Call grd_Sales.ClearGrid
    txt_InvoiceAmountSUM.Text = ""
    txt_TotalQuantity.Text = ""
    
    grd_SalesSummary.Requests = ""
    Call grd_SalesSummaryTotal.ClearGrid
    Call grd_SalesSummary.ClearGrid
    ml_LastSummaryRowSel = -1
    
    mch_SalesSummary.Visible = False
    
    Exit Sub

ErrHandler:
    Call ErrorHandler(Extender.Name & ".ClearGrid")

End Sub



Private Sub cmd_Load_Click()
    
    On Error GoTo ErrHandler
    
    Dim ab_lock As Boolean
    
    ab_lock = LockScreen(True)
    
    If mb_ShowSummary Then
        Call LaunchSummaryReport
    Else
        Call LaunchDetailReport
    End If
    
    ab_lock = LockScreen(False)
    
Exit Sub

ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("cmd_Load_Click")

End Sub


Private Sub LaunchSummaryReport()
    
    On Error GoTo ErrHandler
    
    fra_ReportSummary.Visible = False
    
    If trv_Tree.SelectedItem Is Nothing Then Exit Sub
    
    Dim lb_IsLastLevel As Boolean
    lb_IsLastLevel = (trv_Tree.NodeInfo(trv_Tree.SelectedItem).ml_Level = trv_Tree.Levels - 1)
            
    'If lb_IsLastLevel Then Exit Sub
        
    Dim ls_Request As Variant
    ls_Request = GetSummaryReportRequest(trv_Tree.SelectedNodeRequest)
        
    If UBound(ls_Request) < 0 Then Exit Sub
    If Len(ls_Request(0)) = 0 Then Exit Sub

    Dim ls_ReportType As String
    ls_ReportType = trv_Tree.NodeInfo(trv_Tree.SelectedItem).GetData(3)

    Call LoadSummaryReport(ls_Request(0), ls_ReportType)
    
    fra_ReportSummary.Visible = ls_ReportType <> C_RPT_NONE
    
    Exit Sub

ErrHandler:
    Call LogErrorMessage("LaunchSummaryReport")

End Sub



Private Sub LaunchDetailReport()
    On Error GoTo ErrHandler
    
    If (trv_Tree.Checkboxes) Then
        Call grd_Sales.Load(GetDetailReportRequest(trv_Tree.CheckedNodesRequests), True, , False, False)
    Else
        If Not (trv_Tree.SelectedItem Is Nothing) Then
            Call grd_Sales.Load(GetDetailReportRequest(trv_Tree.SelectedNodeRequest), True, , False, False)
        End If
    End If
        
    Exit Sub

ErrHandler:
    Call LogErrorMessage("LaunchDetailReport")
        
End Sub





Private Sub grd_SalesSummary_SelChange()
On Error GoTo ErrHandler
    If mb_Internal Then Exit Sub
    mb_Internal = True
    If ml_LastSummaryRowSel <> -1 Then
      
        grd_SalesSummary.Data(ml_LastSummaryRowSel, C_SUMMARY_COL_SEL) = ""
        ml_LastSummaryRowSel = -1
    End If

    If Not mb_UseLocalCurrency And grd_SalesSummary.Row > -1 Then
            
        Dim ll_Idx As Long
        ll_Idx = grd_SalesSummary.Row + 1
        Call grd_SalesSummary.DeselectRow
        
        grd_SalesSummary.Data(ll_Idx - 1, C_SUMMARY_COL_SEL) = C_SUMMARY_TOKEN_SEL
        ml_LastSummaryRowSel = ll_Idx - 1
        Call mch_SalesSummary.SetFocus
        mch_SalesSummary.Plot.SeriesCollection(ll_Idx).Select
    End If
    
    mb_Internal = False
    Exit Sub
ErrHandler:
    Call LogErrorMessage("mch_SalesSummary_SeriesSelected")
    
End Sub

Private Sub mch_SalesSummary_SeriesSelected(Series As Integer, MouseFlags As Integer, Cancel As Integer)
On Error GoTo ErrHandler
    
   If mb_Internal Then Exit Sub
   mb_Internal = True
   
   If ml_LastSummaryRowSel <> -1 Then
        grd_SalesSummary.Data(ml_LastSummaryRowSel, C_SUMMARY_COL_SEL) = ""
       
        ml_LastSummaryRowSel = -1
    End If
    
    grd_SalesSummary.Row = Series - 1
    
    grd_SalesSummary.Data(Series - 1, C_SUMMARY_COL_SEL) = C_SUMMARY_TOKEN_SEL
    grd_SalesSummary.DeselectRow
    ml_LastSummaryRowSel = Series - 1
    
    mb_Internal = False
    
    Exit Sub
ErrHandler:
    Call LogErrorMessage("mch_SalesSummary_SeriesSelected")
    
End Sub

Private Sub opt_DR_ReportType_Click(Index As Integer)
    On Error GoTo ErrHandler
    If mb_Internal Then Exit Sub
    
    Dim ab_lock As Boolean
    ab_lock = LockScreen(True)

    Select Case Index
        Case 0:
            Call cbo_DR_Year.SearchItem(Year(Date), 0, , True)
            Call cbo_DR_Month.SearchItem(0, 0, , True)
            
            cbo_DR_Month.Enabled = False
            cbo_DR_Year.Enabled = False
            cbo_DR_Month.Visible = False
            cbo_DR_Year.Visible = False
        
        Case 1:
            Call cbo_DR_Year.SearchItem(Year(Date), 0, , True)
            Call cbo_DR_Month.SearchItem(Month(Date), 0, , True)
            cbo_DR_Month.Enabled = False
            cbo_DR_Year.Enabled = False
            cbo_DR_Month.Visible = False
            cbo_DR_Year.Visible = False
        
        Case 2:
            cbo_DR_Month.Enabled = True
            cbo_DR_Year.Enabled = True
            cbo_DR_Month.Visible = True
            cbo_DR_Year.Visible = True
    End Select
    

    ab_lock = LockScreen(False)
    Exit Sub
    
ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("trv_Tree_CheckboxesChange")

End Sub


Private Sub trv_Tree_CheckboxesChange(Checkboxes As Boolean)
    
    On Error GoTo ErrHandler
    
    If mb_Internal Then Exit Sub
    
    Dim ab_lock As Boolean
    ab_lock = LockScreen(True)
    
    Call ClearReport
    
    If trv_Tree.Checkboxes Then
        tbs_Report.Enabled = False
    Else
        If Not trv_Tree.SelectedItem Is Nothing Then
            Call grd_Sales.Load(GetDetailReportRequest(trv_Tree.SelectedNodeRequest), True, , False, trv_Tree.NodeInfo(trv_Tree.SelectedItem).ml_Level <> trv_Tree.Levels - 1)
        End If
        tbs_Report.Enabled = True
    End If
    
    ab_lock = LockScreen(False)
    Exit Sub
    
ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("trv_Tree_CheckboxesChange")

End Sub

Private Sub trv_Tree_NodeCheck(ByVal Node As MSComctlLib.Node)
    
    On Error GoTo ErrHandler
    
    Dim ab_lock As Boolean
    ab_lock = LockScreen(True)
    Call ClearReport
    ab_lock = LockScreen(False)
    Exit Sub
    
ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("trv_Tree_NodeCheck")

End Sub


Private Sub trv_Tree_NodeClick(ByVal Node As MSComctlLib.Node)
On Error GoTo ErrHandler
    If trv_Tree.Checkboxes Then Exit Sub
    If mb_Internal Then Exit Sub
    
    Dim ab_lock As Boolean
    
    ab_lock = LockScreen(True)
    
    Call ClearReport
    
    Dim lb_IsLastLevel As Boolean
    lb_IsLastLevel = (trv_Tree.NodeInfo(Node).ml_Level = trv_Tree.Levels - 1)
    
    Dim lv_DetailReportRequest As Variant, lv_SummaryReportRequest
    Call FillReportRequest(trv_Tree.SelectedNodeRequest, lv_DetailReportRequest, lv_SummaryReportRequest)
    
    Call grd_Sales.Load(lv_DetailReportRequest, True, , False, (Not lb_IsLastLevel) Or mb_ShowSummary)
    
    If mb_ShowSummary Then
        If Not trv_Tree.SelectedItem.Expanded Then
            Call trv_Tree.ExpandNode(trv_Tree.SelectedItem)
        End If
        Call LaunchSummaryReport
    End If
    
    ab_lock = LockScreen(False)
    
    Exit Sub
    
ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("trv_Tree_NodeClick")


End Sub





' Occured when the User select a new currency
Private Sub opt_Currency_Click(Index As Integer)
On Error GoTo ErrHandler

    If mb_Internal Then Exit Sub
    Dim ab_lock As Boolean
    
    ab_lock = LockScreen(True)

    mb_UseLocalCurrency = Index = 2
    Call ApplyCurrency
    
    ab_lock = LockScreen(False)
    
    Exit Sub
    
ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("opt_Currency_Click")
   
End Sub


Private Sub ApplyCurrency()

On Error GoTo ErrHandler

    Dim ls_SelectedView As String
    If Not (cbo_Views.SelectedItem Is Nothing) Then
        ls_SelectedView = cbo_Views.SelectedItem.Key
    End If
    grd_Sales.Columns(C_COL_CURRENCY_NAME).Width = IIf(mb_UseLocalCurrency, C_COL_CURRENCY_WIDTH, 0)
    
    LoadViews (ls_SelectedView)
    Exit Sub
    
ErrHandler:

    Call ErrorHandler(Extender.Name & ".ApplyCurrency")

End Sub


Private Sub grd_Sales_DataLoaded(ByVal ab_FullDataLoaded As Boolean)
On Error GoTo ErrHandler

    Dim ab_lock As Boolean
    ab_lock = LockScreen(True)

    If (ab_FullDataLoaded) Then CalculateSUM
    
    ab_lock = LockScreen(False)

    Exit Sub

ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("grd_Sales_DataLoaded")
End Sub


Private Sub grd_Sales_RowLoaded(ByVal al_Row As Long)
On Error GoTo ErrHandler

    If (al_Row < 0) Then Exit Sub

    Dim ab_lock As Boolean
    ab_lock = LockScreen(True)

    Dim ls_Billing As String
    Dim ls_BIT_Code As String, ls_BIT_Desc As String, ls_OR_Code As String, ls_OR_Desc As String
    
    ls_BIT_Code = Trim(grd_Sales.Data(al_Row, C_COL_BITCODE_NAME))
    ls_BIT_Desc = Trim(grd_Sales.Data(al_Row, C_COL_BITDESC_NAME))
    ls_OR_Code = Trim(grd_Sales.Data(al_Row, C_COL_ORCODE_NAME))
    ls_OR_Desc = Trim(grd_Sales.Data(al_Row, C_COL_ORDESC_NAME))
    
    If Len(ls_BIT_Desc) <> 0 Then
        ls_Billing = ls_BIT_Desc
    End If
    
    If Len(ls_BIT_Code) <> 0 Then
        ls_Billing = LTrim(ls_Billing & " ") & "(" & ls_BIT_Code & ")"
    End If
    
    If (Len(ls_Billing) > 0) And (Len(ls_OR_Code) <> 0 Or Len(ls_OR_Desc) <> 0) Then
        ls_Billing = ls_Billing & " \ "
    End If
        
    If Len(ls_OR_Desc) <> 0 Then
        ls_Billing = ls_Billing & ls_OR_Desc
    End If
    
    If Len(ls_OR_Code) <> 0 Then
        ls_Billing = LTrim(ls_Billing & " ") & "(" & ls_OR_Code & ")"
    End If
    
    grd_Sales.Data(al_Row, C_COL_BILLING_NAME) = ls_Billing

    ab_lock = LockScreen(False)
    
    Exit Sub
    
ErrHandler:
    
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("grd_Sales_RowLoaded")

End Sub



Private Function HasUniqueData(ByVal as_Column As String)

    If grd_Sales.Rows = 0 Then
        HasUniqueData = True
        Exit Function
    End If
    
    Dim ll_Idx As Long, ll_Count As Long, ls_Curr As String
    ll_Count = grd_Sales.Rows - 1
    ls_Curr = grd_Sales.Data(0, as_Column)
    For ll_Idx = 1 To ll_Count
        If CStr(grd_Sales.Data(ll_Idx, as_Column)) <> ls_Curr Then
            HasUniqueData = False
            Exit Function
        End If
    Next
    HasUniqueData = True
End Function



Private Function HasUniqueCurrency() As Boolean

On Error GoTo ErrHandler
    
    If Not opt_Currency(2).Value Then
        HasUniqueCurrency = True
        Exit Function
    End If
    
    HasUniqueCurrency = HasUniqueData(C_COL_CURRENCY_NAME)
    
    Exit Function

ErrHandler:
    Call ErrorHandler(Extender.Name & ".HasUniqueCurrency")

End Function


Private Sub CalculateSUM()
    
On Error GoTo ErrHandler

    txt_InvoiceAmountSUM.Text = "0"
    txt_TotalQuantity.Text = "0"
    
    If grd_Sales.Rows = 0 Then
        Exit Sub
    End If
    
    If Not HasUniqueCurrency() Then
        txt_InvoiceAmountSUM.Text = lbl_AmountMultipleCurrency.Caption
    Else
        txt_InvoiceAmountSUM.Text = FormatNumber(grd_Sales.GridFunction("SUM", C_COL_AMOUNT_NAME), 2, vbDefault, vbUseDefault, vbTrue)
    End If
    
    If Not HasUniqueData(C_COL_UOM_NAME) Then
        txt_TotalQuantity.Text = lbl_MultipleUoM.Caption
    Else
        txt_TotalQuantity.Text = FormatNumber(grd_Sales.GridFunction("SUM", C_COL_QTY_NAME), 2, vbDefault, vbUseDefault, vbTrue)
    End If
    
    Exit Sub
    
ErrHandler:
    Call ErrorHandler(Extender.Name & ".CalculateSUM")
    
End Sub

Private Sub UserControl_Resize()
   
    On Error GoTo ErrHandler
   
    Dim ab_lock As Boolean
    ab_lock = LockScreen(True)
    
    frm_Tree.Height = Me.Height - frm_Tree.Top - 100
        tbs_Interco.Top = frm_Tree.Height - tbs_Interco.Height - 100
        trv_Tree.Height = frm_Tree.Height - trv_Tree.Top - tbs_Interco.Height - 100
    
   
    tbs_Report.Top = Me.Height - tbs_Report.Height - 100
    tbs_Report.Width = Me.Width - tbs_Report.Left - 200
   
    cmd_Quit.Left = Me.Width - cmd_Quit.Width - 200
      
    fra_ReportSummary.Height = tbs_Report.Top - fra_ReportSummary.Top
    fra_ReportSummary.Width = Me.Width - fra_ReportSummary.Left - 200
        grd_SalesSummary.Width = fra_ReportSummary.Width - grd_SalesSummary.Left - 80
        grd_SalesSummaryTotal.Width = grd_SalesSummary.Width
        grd_SalesSummaryTotal.Top = grd_SalesSummary.Top + grd_SalesSummary.Height + 50
        mch_SalesSummary.Width = fra_ReportSummary.Width - mch_SalesSummary.Left - 80
        
        Dim ll_height As Long
        ll_height = fra_ReportSummary.Height - mch_SalesSummary.Top - 50
        mch_SalesSummary.Height = IIf(ll_height < 0, 0, ll_height)
        
        
    

    fra_ReportDetail.Height = tbs_Report.Top - fra_ReportDetail.Top
    fra_ReportDetail.Width = Me.Width - fra_ReportDetail.Left - 200
        grd_Sales.Width = fra_ReportDetail.Width - grd_Sales.Left - 80
        fra_SUM.Left = grd_Sales.Left + grd_Sales.Width - fra_SUM.Width - 80
        fra_SUM.Top = fra_ReportDetail.Height - fra_SUM.Height - 30
        grd_Sales.Height = fra_SUM.Top - grd_Sales.Top
        
   
   
   fra_DailyReport.Left = (Me.Width - fra_DailyReport.Width) / 2
   fra_DailyReport.Top = (Me.Height - fra_DailyReport.Height) / 2 - fra_DailyReport.Height
   
   If fra_DailyReport.Top < 0 Then fra_DailyReport.Top = 100
   
    
    ab_lock = LockScreen(False)
    
    Exit Sub
    
ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("UserControl_Resize")
End Sub




' Load the labels of a containers
Private Sub LoadLabels(ByRef aControls As Variant, ByVal as_ScreenName As String, ByVal as_Language As String)

On Error GoTo ErrHandler

    Dim lIdx As Long, lCount As Long, lLabels As Long
    Dim lControl As Control
    
    lLabels = mo_Db.OpenSQL("exec Screen_Csts '" & as_ScreenName & "','" & as_Language & "'")
    Debug.Assert (lLabels <> 0)
    
    lCount = aControls.Count - 1
    
    For lIdx = 0 To lCount
        Set lControl = aControls.Item(lIdx)
            Select Case UCase(TypeName(lControl))
                Case "LABEL", "FRAME", "COMMANDBUTTON", "OPTIONBUTTON", "MENU", "CHECKBOX"
                    If lControl.Tag <> "" Then
                        If mo_Db.Find(lLabels, "FIELD_NAME", lControl.Tag, , 1) >= 0 Then
                            lControl.Caption = mo_Db.GetFields(lLabels, "LOCAL_TEXT")
                        End If
                        ' once translation is done and control is not in array CLEAR tag
                        If Not TypeOf lControl Is Frame And Not TypeOf lControl Is Label Then
                            lControl.Tag = ""
                        End If
                    End If
                Case "ARMGRID"
                    If mo_Db.Find(lLabels, "FIELD_NAME", lControl.Tag, , 1) >= 0 Then
                      Call lControl.LoadConstants(ptStatic, mo_Db.GetFields(lLabels, "LOCAL_TEXT"), ctColumns)
                        End If
                    If mo_Db.Find(lLabels, "FIELD_NAME", lControl.Tag & "_Title", , 1) >= 0 Then
                      lControl.Title = mo_Db.GetFields(lLabels, "LOCAL_TEXT")
                    End If
                Case "TABSTRIP"
                    If mo_Db.Find(lLabels, "FIELD_NAME", lControl.Tag, , 1) >= 0 Then
                        Dim lsa_TextArr() As String
                        Dim ll_Index As Long
                        
                        lsa_TextArr = Split(mo_Db.GetFields(lLabels, "LOCAL_TEXT"), SEP)
                        
                        For ll_Index = LBound(lsa_TextArr, 1) To UBound(lsa_TextArr, 1)
                            lControl.Tabs(ll_Index + 1).Caption = lsa_TextArr(ll_Index)
                        Next
                    End If
                    ' once translation is done and control is not in array CLEAR tag
                    lControl.Tag = ""
                Case "MSFLEXGRID", "TOOLBARCONTROL", "TEXTBOX", "ARMCHECKVIEW", "ARMCOMBOBOX", "A_CALOCX", "OPTIONBUTTON", "ARMTREEVIEW", "LISTBOX", "PICTUREBOX", "TOOLBR", "SPINBUTTON"
                    ' Do nothing !
                Case Else
                    'debug.print "LoadLabels " & UCase(TypeName(lControl))
            End Select
        Set lControl = Nothing
    Next
    
    Call mo_Db.Close(lLabels)

    Exit Sub

ErrHandler:
    If lLabels > 0 Then
        Call mo_Db.Close(lLabels)
    End If
    Call ErrorHandler(Extender.Name & ".LoadLabels")
End Sub


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

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

ErrHandler:
    Call ErrorHandler(Extender.Name & ".ChangeCharset")
End Sub



Private Function LockScreen(ByVal ab_lock As Boolean) 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
        UserControl.Enabled = False
        lb_Locked = True
        
        
        
    End If
    
    ' Unlock
    If ll_Count = 0 Then
        DoEvents ' Flush events
        LockWindowUpdate 0
        UserControl.Refresh ' Repaint immediately
        Screen.MousePointer = ll_Mousepointer
        UserControl.Enabled = True
        lb_Locked = False
    End If
    
    Err.Number = ll_errNumber
    Err.Source = ls_ErrSrc
    Err.Description = ls_ErrDesc
    
    LockScreen = lb_Locked
    
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".LockScreen")
End Function




' logs message to database
Private Sub LogErrorMessage(ByVal as_logMsg As String)
    Dim ll_errNumber As Long
    Dim ls_errDescription As String, ls_ErrSource As String
    
    ll_errNumber = Err.Number
    ls_errDescription = Err.Description
    ls_ErrSource = Err.Source

On Error GoTo ErrHandler

Const LOG_REQUEST As String = "EXEC A_log_ins $UCODE$,$LOGTYPE$,$MSG$,$APP$"
    Dim ls_req As String
    Dim ll_Cursor As Long
    Dim ls_Source As String, ls_Msg As String
    
    ls_Source = SCREEN_NAME & " " & App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
    ls_Msg = as_logMsg & SEP1 & ll_errNumber & " : " & ls_errDescription & " - " & ls_ErrSource
    
    ls_req = Replace(LOG_REQUEST, "$UCODE$", CStr(ml_U_Code))
    ls_req = Replace(ls_req, "$LOGTYPE$", "E")
    ls_req = Replace(ls_req, "$MSG$", Left(Trim(SQLStr(ls_Msg)), 4000))
    ls_req = Replace(ls_req, "$APP$", Left(Trim(SQLStr(ls_Source)), 50))
    
    mo_Db.ExecuteSQL (ls_req)
    
    Err.Number = ll_errNumber
    Err.Description = ls_errDescription
    Err.Source = ls_ErrSource
    
    Dim ls_Message As String
    ls_Message = "The following error occured and has been logged into the database, the application will be close." & vbCrLf
    ls_Message = ls_Message & "Number:" & Err.Number & vbCrLf & "Description:" & Err.Description
    
    Debug.Print (ls_Message)
    
    Call MsgBox(ls_Message, vbCritical, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision)
    
    Debug.Assert (False)
    
    End
    
    Exit Sub
    
ErrHandler:
        Call MsgBox("A fatal error occured. Unable to log error into database, the application will be close. Please report the following message to your IT support: " & vbCrLf & _
            "Number:" & Err.Number & vbCrLf & "Description:" & Err.Description, , App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision)
        End
End Sub


Private Function SQLStr(ByVal as_Data As String) As String
On Error GoTo ErrHandler

    SQLStr = "'" & Replace(as_Data, "'", "''") & "'"
    Exit Function
ErrHandler:
    Call ErrorHandler("SqlStr")
End Function


Private Sub tbs_Interco_Click()
On Error GoTo ErrHandler

 If mb_Internal Then Exit Sub
    
    Dim ab_lock As Boolean
    ab_lock = LockScreen(True)
    
    If cbo_Views.SelectedItem Is Nothing Then Exit Sub
    Call LoadTreeView(GetTreeViewInfo(cbo_Views.SelectedItem.Key))

    ab_lock = LockScreen(False)
    
    Exit Sub

ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("tbs_Interco_Click")
    ab_lock = LockScreen(False)
    
    Exit Sub

End Sub

Private Sub tbs_Report_Click()
On Error GoTo ErrHandler

    If mb_Internal Then Exit Sub
    
    Dim ab_lock As Boolean
    ab_lock = LockScreen(True)
    
    If tbs_Report.SelectedItem.Index = 1 And Not mb_ShowSummary Then
        mb_ShowSummary = True
        fra_ReportDetail.Visible = False
        trv_Tree.AllowCheckboxes = False
        Call LaunchSummaryReport
        
    End If
    
    If tbs_Report.SelectedItem.Index = 2 And mb_ShowSummary Then
        mb_ShowSummary = False
        fra_ReportSummary.Visible = False
        trv_Tree.AllowCheckboxes = True
        fra_ReportDetail.Visible = True
    End If
    
    LockScreen (False)
    
    Exit Sub
    
ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("tbs_Report_Click")
    ab_lock = LockScreen(False)

End Sub



Private Function GetDetailReportRequest(ByVal ao_Requests) As Variant
On Error GoTo ErrHandler
    Dim lo_Requests As Variant, lo_Dummy As Variant
    Call FillReportRequest(ao_Requests, lo_Requests, lo_Dummy)
    GetDetailReportRequest = lo_Requests
        Exit Function
ErrHandler:
    Call ErrorHandler("GetDetailReportRequest")
End Function

Private Function GetSummaryReportRequest(ByVal ao_Requests) As Variant
On Error GoTo ErrHandler
    Dim lo_Requests As Variant, lo_Dummy As Variant
    Call FillReportRequest(ao_Requests, lo_Dummy, lo_Requests)
    GetSummaryReportRequest = lo_Requests
        Exit Function
ErrHandler:
    Call ErrorHandler("GetSummaryReportRequest")
End Function



Private Sub FillReportRequest(ByVal ao_Requests As Variant, ByRef ao_DetailRequests As Variant, ByRef ao_SummaryRequests As Variant)
On Error GoTo ErrHandler
    Dim lo_Requests As Variant

    Dim ll_Idx As Long, ll_Count As Long

    If Not IsArray(ao_Requests) Then
        ReDim lo_Requests(0)
        lo_Requests(0) = ao_Requests
    Else
        
        'lo_Requests = ao_Requests
        ll_Count = UBound(ao_Requests)
        
        ReDim lo_Requests(ll_Count)
        Dim ll_ReqIdx As Long
        ll_ReqIdx = 0
        For ll_Idx = 0 To ll_Count
            If (ao_Requests(ll_Idx) = Empty) Then GoTo NextItem
            lo_Requests(ll_ReqIdx) = ao_Requests(ll_Idx)
            ll_ReqIdx = ll_ReqIdx + 1
NextItem:
        Next
        ReDim Preserve lo_Requests(ll_ReqIdx - 1)
    End If


    
    ll_Count = UBound(lo_Requests)
    
    ReDim ao_DetailRequests(ll_Count)
    ReDim ao_SummaryRequests(ll_Count)
    
    Dim lo_Request As Variant
    For ll_Idx = 0 To ll_Count
        lo_Request = Split(lo_Requests(ll_Idx), SEP, , vbTextCompare)
        ao_DetailRequests(ll_Idx) = lo_Request(0)
        If UBound(lo_Request) > 0 Then
            ao_SummaryRequests(ll_Idx) = lo_Request(1)
        Else
            ao_SummaryRequests(ll_Idx) = ""
        End If
    Next
    Exit Sub
ErrHandler:
    Call ErrorHandler("FillReportRequest")
End Sub



Private Sub LoadSummaryReport(ByVal as_Request As Variant, ByVal as_ReportType As String)

On Error GoTo ErrHandler
    
    ' Check Report Validity
    Select Case as_ReportType
        Case C_RPT_PER_YEAR, C_RPT_PER_MONTH, C_RPT_PER_NEXTLEVEL
            '
        Case C_RPT_NONE
            Exit Sub
        Case Else
           Call Err.Raise(-1, , "Unknown Report Type")
    End Select

    
    ' Get Data
    Dim lc_ReportData As Long
    lc_ReportData = mo_Db.OpenSQL(as_Request)
    
    ' Extract list of currencies (will be one column per currencies)
    Dim lc_Currencies As Long
    lc_Currencies = mo_Db.Distinct(lc_ReportData, 2)

    Dim ll_CurrenciesCount As Long
    ll_CurrenciesCount = mo_Db.RowCount(lc_Currencies)

    'Configure Grid Columns (Title + One per Currencies
    Dim lv_Columns As Variant
    ReDim lv_Columns(ll_CurrenciesCount + 2)
     
    lv_Columns(0) = Join(Array(C_SUMMARY_COL_ID, 0, 1, "", "", "", "", ""), SEP)
    lv_Columns(1) = Join(Array(C_SUMMARY_COL_SEL, 200, 0, "", "", "", "", ""), SEP)
    lv_Columns(2) = Join(Array(C_SUMMARY_COL_DESC, 2000, 0, "", "", "", "", ""), SEP)
    
    
    Dim ll_Idx As Long, ll_Count As Long, ls_ColumnName As String
    ll_Count = ll_CurrenciesCount + 2
    mo_Db.First (lc_Currencies)
    For ll_Idx = 3 To ll_Count
        ls_ColumnName = mo_Db.GetFields(lc_Currencies, 0)
        lv_Columns(ll_Idx) = Join(Array(ls_ColumnName, 1500, 0, "", ls_ColumnName, "FLOAT", "###,###,##0.00", "CENTER"), SEP)
        mo_Db.Next (lc_Currencies)
    Next
    
    grd_SalesSummary.SetColumns (lv_Columns)
    
    grd_SalesSummaryTotal.SetColumns (lv_Columns)
    
    mo_Db.Close (ll_CurrenciesCount)
    
    ' Prepare empty line
    Select Case as_ReportType
        Case C_RPT_PER_YEAR
            Call InitializeGridSummaryForYears
        Case C_RPT_PER_MONTH
            'Call InitializeGridSummaryForMonth
            Call InitializeGridSummaryForNextLevel(lc_ReportData)
        Case C_RPT_PER_NEXTLEVEL
            Call InitializeGridSummaryForNextLevel(lc_ReportData)
        Case C_RPT_NONE
            '
        Case Else
           Call Err.Raise(-1, , "Unknown Report Type")
    End Select

    ' Load Data
    Dim ll_IdxCol As Long, ll_CountCol As Long
    Dim ls_Key As String, ls_Currency As String
    ll_CountCol = ll_CurrenciesCount + 2
    ll_Count = grd_SalesSummary.Rows - 1
    For ll_Idx = 0 To ll_Count
        ls_Key = grd_SalesSummary.Data(ll_Idx, C_SUMMARY_COL_ID)
        For ll_IdxCol = 3 To ll_CountCol
            ls_Currency = grd_SalesSummary.Columns(ll_IdxCol).Name
            
            If mo_Db.Find(lc_ReportData, Array(0, 2), Array(ls_Key, ls_Currency)) >= 0 Then
                grd_SalesSummary.Data(ll_Idx, ll_IdxCol) = mo_Db.GetFields(lc_ReportData, 3)
            Else
                grd_SalesSummary.Data(ll_Idx, ll_IdxCol) = "0"
            End If
        Next
    Next
    mo_Db.Close (lc_ReportData)
    
    If (ll_CurrenciesCount <> 1) Then
        mch_SalesSummary.Visible = False
    Else
        ' Format Chart
        mch_SalesSummary.columnCount = grd_SalesSummary.Rows
        mch_SalesSummary.RowCount = 1
        For ll_Idx = 1 To mch_SalesSummary.Plot.axis(1).Labels.Count
            mch_SalesSummary.Plot.axis(VtChAxisIdY).Labels.Item(ll_Idx).Format = "###" & ms_ThousandSeparator & "###" & ms_ThousandSeparator & "###"
            mch_SalesSummary.Plot.axis(VtChAxisIdY2).Labels.Item(ll_Idx).Format = "###" & ms_ThousandSeparator & "###" & ms_ThousandSeparator & "###"
        Next
        
        ' Fill Chart
        ll_Count = grd_SalesSummary.Rows - 1
        For ll_Idx = 0 To ll_Count
            mch_SalesSummary.Row = 1
            mch_SalesSummary.Column = ll_Idx + 1
            mch_SalesSummary.Data = grd_SalesSummary.Data(ll_Idx, C_SUMMARY_COL_STDCURR)
            mch_SalesSummary.ColumnLabel = grd_SalesSummary.Data(ll_Idx, C_SUMMARY_COL_DESC)
            Dim ll_Red As Long, ll_Green As Long, ll_Blue As Long
            ll_Red = mch_SalesSummary.Plot.SeriesCollection.Item(ll_Idx + 1).DataPoints(-1).Brush.FillColor.Red
            ll_Green = mch_SalesSummary.Plot.SeriesCollection.Item(ll_Idx + 1).DataPoints(-1).Brush.FillColor.Green
            ll_Blue = mch_SalesSummary.Plot.SeriesCollection.Item(ll_Idx + 1).DataPoints(-1).Brush.FillColor.BLUE
            grd_SalesSummary.LineColor(ll_Idx) = RGB(ll_Red, ll_Green, ll_Blue)
            

            If IsLightColor(ll_Red, ll_Green, ll_Blue) Then
                grd_SalesSummary.TextColor(ll_Idx - 1) = vbWhite
            Else
                grd_SalesSummary.TextColor(ll_Idx - 1) = vbBlack
            End If
        Next
        mch_SalesSummary.Visible = True
    End If
    
    
    ' Add total
    
    Dim ll_TotalRow As Long
    'grd_SalesSummary.Rows = grd_SalesSummary.Rows + 1
    'll_TotalRow = grd_SalesSummary.Rows - 1
    grd_SalesSummaryTotal.Rows = 1
    grd_SalesSummaryTotal.LineColor(0) = 10088089
    grd_SalesSummaryTotal.BoldLine (0)
    
    For ll_IdxCol = 3 To ll_CountCol
        grd_SalesSummaryTotal.Data(0, ll_IdxCol) = grd_SalesSummary.GridFunction("SUM", ll_IdxCol)
    Next
    
Exit Sub

ErrHandler:
    mo_Db.Close (lc_ReportData)
    mo_Db.Close (ll_CurrenciesCount)
    Call ErrorHandler("LoadSummaryReport")

End Sub


Function Min(ByVal ll_Left As Long, ll_Right As Long) As Long
On Error GoTo ErrHandler
    Min = IIf(ll_Left < ll_Right, ll_Left, ll_Right)
    Exit Function

ErrHandler:
    Call ErrorHandler("Min")
End Function

Function Max(ByVal ll_Left As Long, ll_Right As Long)
    On Error GoTo ErrHandler
    
    Max = IIf(ll_Left < ll_Right, ll_Right, ll_Left)
    Exit Function
    
ErrHandler:
    Call ErrorHandler("Max")
End Function

Function GetColorDifference(ByVal al_Red1 As Long, ByVal al_Green1 As Long, ByVal al_Blue1 As Long, ByVal al_Red2 As Long, ByVal al_Green2 As Long, ByVal al_Blue2 As Long) As Long
On Error GoTo ErrHandler
    GetColorDifference = (Max(al_Red1, al_Red2) - Min(al_Red1, al_Red2)) + (Max(al_Green1, al_Green2) - Min(al_Green1, al_Green2)) + (Max(al_Blue1, al_Blue2) - Min(al_Blue1, al_Blue2))
    Exit Function
    
ErrHandler:
    Call ErrorHandler("GetColorDifference")
End Function


Function IsLightColor(ByVal al_Red As Long, ByVal al_Green As Long, ByVal al_Blue As Long) As Boolean
On Error GoTo ErrHandler
    
    Dim ll_WhiteDiff As Long, ll_BlackDiff As Long
    ll_WhiteDiff = GetColorDifference(al_Red, al_Green, al_Blue, 255, 255, 255)
    ll_BlackDiff = GetColorDifference(al_Red, al_Green, al_Blue, 0, 0, 0)
   
   IsLightColor = ll_WhiteDiff > ll_BlackDiff
Exit Function
    
ErrHandler:
    Call ErrorHandler("IsLightColor")
End Function




Private Sub InitializeGridSummaryForYears()
On Error GoTo ErrHandler

    grd_SalesSummary.Rows = 12
    grd_SalesSummary.Data(0, C_SUMMARY_COL_ID) = "1"
    grd_SalesSummary.Data(0, C_SUMMARY_COL_DESC) = "January"
    
    grd_SalesSummary.Data(1, C_SUMMARY_COL_ID) = "2"
    grd_SalesSummary.Data(1, C_SUMMARY_COL_DESC) = "February"
    
    grd_SalesSummary.Data(2, C_SUMMARY_COL_ID) = "3"
    grd_SalesSummary.Data(2, C_SUMMARY_COL_DESC) = "March"
    
    grd_SalesSummary.Data(3, C_SUMMARY_COL_ID) = "4"
    grd_SalesSummary.Data(3, C_SUMMARY_COL_DESC) = "April"
    
    grd_SalesSummary.Data(4, C_SUMMARY_COL_ID) = "5"
    grd_SalesSummary.Data(4, C_SUMMARY_COL_DESC) = "May"
    
    grd_SalesSummary.Data(5, C_SUMMARY_COL_ID) = "6"
    grd_SalesSummary.Data(5, C_SUMMARY_COL_DESC) = "June"
    
    grd_SalesSummary.Data(6, C_SUMMARY_COL_ID) = "7"
    grd_SalesSummary.Data(6, C_SUMMARY_COL_DESC) = "July"
    
    grd_SalesSummary.Data(7, C_SUMMARY_COL_ID) = "8"
    grd_SalesSummary.Data(7, C_SUMMARY_COL_DESC) = "August"
    
    grd_SalesSummary.Data(8, C_SUMMARY_COL_ID) = "9"
    grd_SalesSummary.Data(8, C_SUMMARY_COL_DESC) = "September"
    
    grd_SalesSummary.Data(9, C_SUMMARY_COL_ID) = "10"
    grd_SalesSummary.Data(9, C_SUMMARY_COL_DESC) = "October"
    
    grd_SalesSummary.Data(10, C_SUMMARY_COL_ID) = "11"
    grd_SalesSummary.Data(10, C_SUMMARY_COL_DESC) = "November"
    
    grd_SalesSummary.Data(11, C_SUMMARY_COL_ID) = "12"
    grd_SalesSummary.Data(11, C_SUMMARY_COL_DESC) = "December"
    
    Exit Sub
    
ErrHandler:
    Call ErrorHandler("InitializeGridSummaryForYears")
   
End Sub

Private Sub InitializeGridSummaryForMonth()
On Error GoTo ErrHandler

    Exit Sub

ErrHandler:
    Call ErrorHandler("InitializeGridSummaryForMonth")

End Sub

Private Sub InitializeGridSummaryForNextLevel(ByVal ac_ReportData As Long)
On Error GoTo ErrHandler

    Dim lc_Items As Long
    lc_Items = mo_Db.Distinct(ac_ReportData, Array(0, 1))
    Call mo_Db.Sort(lc_Items, 1, , True)
    
    Dim ll_Index As Long, ll_Count As Long
    ll_Count = mo_Db.RowCount(lc_Items) - 1
    grd_SalesSummary.Rows = ll_Count + 1
    mo_Db.First (lc_Items)
    For ll_Index = 0 To ll_Count
        grd_SalesSummary.Data(ll_Index, C_SUMMARY_COL_ID) = mo_Db.GetFields(lc_Items, 0)
        grd_SalesSummary.Data(ll_Index, C_SUMMARY_COL_DESC) = mo_Db.GetFields(lc_Items, 1)
        mo_Db.Next (lc_Items)
    Next
    
    mo_Db.Close (lc_Items)
    
    Exit Sub
    
ErrHandler:
    mo_Db.Close (lc_Items)
    Call ErrorHandler("InitializeGridSummaryForNextLevel")

End Sub


Private Sub cmd_DailyReport_Click()
    
On Error GoTo ErrHandler
    Dim ab_lock As Boolean
    ab_lock = LockScreen(True)
    
    If opt_Currency(0).Value Then
        opt_DR_Currency(1).Value = True
    Else
        opt_DR_Currency(0).Value = True
    End If
    
    
    opt_DR_SalesType(tbs_Interco.SelectedItem.Index - 1).Value = True
    opt_DR_ReportType(0).Value = True
    
    Call EnableMain(False)
    fra_DailyReport.Visible = True
    fra_DailyReport.Zorder (0)
       
    LockScreen (False)
    Exit Sub
    
ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("cmd_DailyReport_Click")
    ab_lock = LockScreen(False)
    
End Sub


Private Sub EnableMain(ByVal ab_lock As Boolean)
On Error GoTo ErrHandler
    fra_Currency.Enabled = ab_lock
    frm_Tree.Enabled = ab_lock
    fra_ReportSummary.Enabled = ab_lock
    cmd_Load.Enabled = ab_lock
    cmd_DailyReport.Enabled = ab_lock
    
    Exit Sub
    
ErrHandler:
    Call ErrorHandler("EnableMain")

End Sub


Private Sub cmd_DR_Quit_Click()

On Error GoTo ErrHandler
    Dim ab_lock As Boolean
    ab_lock = LockScreen(True)
    
    Call EnableMain(True)
    fra_DailyReport.Visible = False
    
    LockScreen (False)
    Exit Sub
    
ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("cmd_DR_Quit_Click")
    ab_lock = LockScreen(False)
    
 End Sub



Private Function GetDailyReportType(ByRef al_Year As Long, ByRef al_Month As Long) As DailyReportType
On Error GoTo ErrHandler
    
    al_Year = cbo_DR_Year.SelectedItem.Key
    al_Month = cbo_DR_Month.SelectedItem.Key


    Select Case GetSelectedOptionButton(opt_DR_ReportType).Index
        Case 0:
            GetDailyReportType = drtYear
        Case 1:
            GetDailyReportType = drtMonth
        
        Case 2:
           GetDailyReportType = IIf(al_Month = 0, drtYear, drtMonth)
            
        Case Else
            GetDailyReportType = drtYear
    End Select
    
    
Exit Function
ErrHandler:
    Call LogErrorMessage("GetDailyReportType")
       
End Function


Private Sub cmd_DR_Export_Click()
On Error GoTo ErrHandler

    #If LIVE Then
        Dim lo_ExcelWorkSheet As Object
    #Else
        Dim lo_ExcelWorkSheet As Object
    #End If
    Set lo_ExcelWorkSheet = GetWorkSheet
    
    
    Dim ll_RowIdx As Long, ll_ColIdx As Long
    ll_RowIdx = 1
    ll_ColIdx = 1
    
    Call WriteDailyReportHeader(lo_ExcelWorkSheet, ll_RowIdx, ll_ColIdx)
    
    Dim ll_FirstGridRow As Long, ll_CurrentColumn As Long, ll_NextColumn As Long
    ll_FirstGridRow = ll_RowIdx
    
    
    Dim ll_Idx As Long, ll_Count As Long
    ll_Count = UBound(mo_DailyReportRequests)
    
    Dim lo_ReportType As DailyReportType
    Dim ll_Month As Long, ll_Year As Long
    
    lo_ReportType = GetDailyReportType(ll_Year, ll_Month)
    Dim ls_Interco As String, ls_Currency As String
    
    Select Case GetSelectedOptionButton(opt_DR_SalesType).Index
        Case 0:
            ls_Interco = "null"
        Case 1:
            ls_Interco = "'X'"
        Case 2:
            ls_Interco = "''"
        Case Else
            ls_Interco = "null"
    End Select
    
    Select Case GetSelectedOptionButton(opt_DR_Currency).Index
        Case 0:
            ls_Currency = "Euro"
        Case 1:
            ls_Currency = "Dollar"
        Case Else
            ls_Currency = "Euro"
    End Select
    
    Dim lc_Data As Long
    ll_CurrentColumn = ll_ColIdx
    
    For ll_Idx = 0 To ll_Count
        
        If mo_DailyReportRequests(ll_Idx).ReportType <> lo_ReportType Then GoTo NextItem
        
        
        ' Check here if row must be reset and grid move to a new colums !!
        If ll_RowIdx >= 50 Then
            ll_RowIdx = ll_FirstGridRow
            ll_CurrentColumn = ll_NextColumn + 2
        End If
        
        ll_ColIdx = ll_CurrentColumn
        Dim ls_Request As String
        ls_Request = mo_DailyReportRequests(ll_Idx).Request
        ls_Request = Replace(ls_Request, "$Year$", ll_Year, , , vbTextCompare)
        ls_Request = Replace(ls_Request, "$Month$", ll_Month, , , vbTextCompare)
        ls_Request = Replace(ls_Request, "$Curr$", ls_Currency, , , vbTextCompare)
        ls_Request = Replace(ls_Request, "$Interco$", ls_Interco, , , vbTextCompare)
        
        lc_Data = mo_Db.OpenSQL(ls_Request)
        Call WriteDailyReportRequest(lo_ExcelWorkSheet, ll_RowIdx, ll_ColIdx, lc_Data, mo_DailyReportRequests(ll_Idx).Title, mo_DailyReportRequests(ll_Idx).Colour)
        mo_Db.Close (lc_Data)
        
        If (ll_ColIdx > ll_NextColumn) Then
            ll_NextColumn = ll_ColIdx
        End If
        
        ll_RowIdx = ll_RowIdx + 2

NextItem:
    Next

    Exit Sub
ErrHandler:
    Call LogErrorMessage("cmd_DR_Export_Click")
   
End Sub

#If LIVE Then
Private Function GetWorkSheet() As Object
#Else
Private Function GetWorkSheet() As Object
#End If
    On Error GoTo ErrHandler

#If LIVE Then
    Dim lo_ExcelApplication As Object
    Dim lo_ExcelWorkBook As Object
    Dim lo_ExcelWorkSheet As Object
#Else
    Dim lo_ExcelApplication As Object
    Dim lo_ExcelWorkBook As Object
    Dim lo_ExcelWorkSheet As Object
#End If
    
    Set lo_ExcelApplication = CreateObject("Excel.Application")
    
    Set lo_ExcelWorkBook = lo_ExcelApplication.Workbooks.Add
    Set lo_ExcelWorkSheet = lo_ExcelWorkBook.ActiveSheet
    
    While lo_ExcelWorkBook.Worksheets.Count > 1
        lo_ExcelWorkBook.Worksheets(2).Delete
        lo_ExcelWorkBook.Worksheets(2).Delete
    Wend
    
    lo_ExcelWorkBook.Activate
    lo_ExcelWorkSheet.Activate
    
    lo_ExcelWorkSheet.PageSetup.Orientation = 1
    
    lo_ExcelApplication.Visible = True
    
    Set GetWorkSheet = lo_ExcelWorkSheet
    
    Exit Function
ErrHandler:
    Call LogErrorMessage("cmd_DR_Quit_Click")
End Function

#If LIVE Then
Private Sub WriteDailyReportHeader(ByVal ao_ExcelWorkSheet As Object, ByRef al_RowIdx As Long, ByRef al_ColIdx As Long)
#Else
Private Sub WriteDailyReportHeader(ByVal ao_ExcelWorkSheet As Object, ByRef al_RowIdx As Long, ByRef al_ColIdx As Long)
#End If
    On Error GoTo ErrHandler
    
    Const C_REPORT_DETAIL = "$ReportType$ Report from $Start$ To $End$ in $CURR$ for $SalesType$ (done the $Now$)"
    
    
    Dim ll_RowIdx As Long, ll_ColIdx As Long
    ll_ColIdx = al_ColIdx
    ll_RowIdx = al_RowIdx
    
    ao_ExcelWorkSheet.cells(ll_RowIdx, ll_ColIdx).Value = "Metal Sales Analysis"
    ao_ExcelWorkSheet.cells(ll_RowIdx, ll_ColIdx).Font.Bold = True
    ao_ExcelWorkSheet.cells(ll_RowIdx, ll_ColIdx).Font.Size = 16
    
    ll_RowIdx = ll_RowIdx + 1
    
    
    Dim lo_ReportType As DailyReportType, ll_Year As Long, ll_Month As Long
    lo_ReportType = GetDailyReportType(ll_Year, ll_Month)
    
    Dim StartDate As Date, EndDate As Date, ls_Caption As String
    
    If lo_ReportType = drtYear Then
        ls_Caption = opt_DR_ReportType(0).Caption
        StartDate = DateSerial(ll_Year, 1, 1)
        EndDate = DateSerial(ll_Year, 12, 31)
    Else
        ls_Caption = opt_DR_ReportType(1).Caption
        StartDate = DateSerial(ll_Year, ll_Month, 1)
        EndDate = DateSerial(ll_Year, ll_Month, Day(DateSerial(ll_Year, ll_Month + 1, 0)))
    End If
    
    Dim ls_ReportDetail As String
    ls_ReportDetail = C_REPORT_DETAIL
    ls_ReportDetail = Replace(ls_ReportDetail, "$ReportType$", ls_Caption, , , vbTextCompare)
    ls_ReportDetail = Replace(ls_ReportDetail, "$Start$", StartDate, , , vbTextCompare)
    ls_ReportDetail = Replace(ls_ReportDetail, "$End$", EndDate, , , vbTextCompare)
    ls_ReportDetail = Replace(ls_ReportDetail, "$Curr$", GetSelectedOptionButton(opt_DR_Currency).Caption, , , vbTextCompare)
    ls_ReportDetail = Replace(ls_ReportDetail, "$SalesType$", GetSelectedOptionButton(opt_DR_SalesType).Caption, , , vbTextCompare)
    ls_ReportDetail = Replace(ls_ReportDetail, "$Now$", Date, , , vbTextCompare)
    
    ao_ExcelWorkSheet.cells(ll_RowIdx, ll_ColIdx).Value = ls_ReportDetail
    ao_ExcelWorkSheet.cells(ll_RowIdx, ll_ColIdx).Font.Italic = True
    ll_RowIdx = ll_RowIdx + 2
    
    al_RowIdx = ll_RowIdx
    al_ColIdx = ll_ColIdx
    
    With ao_ExcelWorkSheet.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
    
    Exit Sub
    
ErrHandler:
    Call LogErrorMessage("cmd_DR_Quit_Click")
End Sub


Private Function GetSelectedOptionButton(ao_OptionButton As Variant) As OptionButton
On Error GoTo ErrHandler
    Dim ll_Index As Long, ll_Count As Long
    ll_Count = ao_OptionButton.UBound
    
    For ll_Index = ao_OptionButton.LBound To ll_Count
        If VarType(ao_OptionButton(ll_Index)) <> vbObject Then
            If ao_OptionButton(ll_Index).Value Then
                Set GetSelectedOptionButton = ao_OptionButton(ll_Index)
                Exit Function
            End If
        End If
    Next
    Set GetSelectedOptionButton = ao_OptionButton(ao_OptionButton.LBound)
    
    Exit Function
ErrHandler:
    Call LogErrorMessage("GetSelectedOptionButton")

End Function



#If LIVE Then
Private Function WriteDailyReportRequest(ByRef ao_ExcelWorkSheet As Object, ByRef al_RowIdx As Long, ByRef al_ColIdx As Long, ByVal ac_Data As Long, ByVal as_Title As String, ByVal al_Color As Long)
#Else
Private Function WriteDailyReportRequest(ByRef ao_ExcelWorkSheet As Object, ByRef al_RowIdx As Long, ByRef al_ColIdx As Long, ByVal ac_Data As Long, ByVal as_Title As String, ByVal al_Color As Long)
#End If
On Error GoTo ErrHandler
        Dim lc_Row As Long, lc_Column As Long
        lc_Row = mo_Db.Distinct(ac_Data, Array(0, 1), 0)
        lc_Row = mo_Db.Sort(lc_Row, 1, , True)
        
        lc_Column = mo_Db.Distinct(ac_Data, 2, 0)
        lc_Column = mo_Db.Sort(lc_Column, 0, , True)


        Dim ll_RowCount As Long, ll_ColCount As Long
        
        ll_RowCount = mo_Db.RowCount(lc_Row)
        ll_ColCount = mo_Db.RowCount(lc_Column)
        

        'Add title
        ao_ExcelWorkSheet.cells(al_RowIdx, al_ColIdx).Value = as_Title
        ao_ExcelWorkSheet.cells(al_RowIdx, al_ColIdx).Font.Bold = True
        ao_ExcelWorkSheet.cells(al_RowIdx, al_ColIdx).Font.Size = 14
        ao_ExcelWorkSheet.cells(al_RowIdx, al_ColIdx).Interior.ColorIndex = al_Color
        ao_ExcelWorkSheet.cells(al_RowIdx, al_ColIdx).HorizontalAlignment = -4108
                
        Dim ll_Idx  As Long, ll_Count As Long
        
        'Add Rows
        ll_Count = al_RowIdx + 1 + ll_RowCount
        mo_Db.First (lc_Row)
        For ll_Idx = al_RowIdx + 2 To ll_Count
            ao_ExcelWorkSheet.cells(ll_Idx, al_ColIdx).Value = mo_Db.GetFields(lc_Row, 1)
            mo_Db.Next (lc_Row)
        Next
        
        
        'Add column
        Dim ll_ColumnRow As Long
        ll_ColumnRow = al_RowIdx + 1
        ll_Count = al_ColIdx + ll_ColCount
        mo_Db.First (lc_Column)
        For ll_Idx = al_ColIdx + 1 To ll_Count
            ao_ExcelWorkSheet.cells(ll_ColumnRow, ll_Idx).Value = mo_Db.GetFields(lc_Column, 0)
            mo_Db.Next (lc_Column)
        Next
        
        ' Add values
        Dim ll_IdxRow As Long, ll_IdxCol As Long, ld_value As Double, ld_TotalRow As Double, ld_TotalColumns() As Double
        ReDim ld_TotalColumns(ll_ColCount + 1)
        For ll_IdxCol = 0 To ll_ColCount
            ld_TotalColumns(ll_IdxCol) = 0
        Next
        
        
        For ll_IdxRow = 0 To ll_RowCount - 1
            ld_TotalRow = 0
            For ll_IdxCol = 0 To ll_ColCount - 1
                If mo_Db.Find(ac_Data, Array(0, 2), Array(mo_Db.GetFieldsAt(lc_Row, ll_IdxRow, 0), mo_Db.GetFieldsAt(lc_Column, ll_IdxCol, 0))) >= 0 Then
                    ld_value = mo_Db.GetFields(ac_Data, 3)
                Else
                    ld_value = 0
                End If
                
                ld_TotalRow = ld_TotalRow + ld_value
                ao_ExcelWorkSheet.cells(al_RowIdx + 2 + ll_IdxRow, al_ColIdx + 1 + ll_IdxCol).Value = ld_value
                ld_TotalColumns(ll_IdxCol) = ld_TotalColumns(ll_IdxCol) + ld_value
            Next
            ao_ExcelWorkSheet.cells(al_RowIdx + 2 + ll_IdxRow, al_ColIdx + 1 + ll_ColCount).Value = ld_TotalRow
            ld_TotalColumns(ll_ColCount) = ld_TotalColumns(ll_ColCount) + ld_TotalRow
        Next
        
        ' Add total
        For ll_IdxCol = 0 To ll_ColCount
            ao_ExcelWorkSheet.cells(al_RowIdx + 2 + ll_RowCount, al_ColIdx + 1 + ll_IdxCol).Value = ld_TotalColumns(ll_IdxCol)
        Next
        
                
        mo_Db.Close (lc_Row)
        mo_Db.Close (lc_Column)
        
        
        ' Add formating
        Dim ls_Range As String
        
        ls_Range = GetExcellRange(al_ColIdx, al_RowIdx, ll_ColCount + al_ColIdx + 1, al_RowIdx + 1 + ll_RowCount)               ' 01.08.2013 JN fixing 2 letters columns bug
'        ls_Range = Chr(64 + al_ColIdx) & al_RowIdx & ":" & Chr(64 + ll_ColCount + al_ColIdx + 1) & (al_RowIdx + 1 + ll_RowCount)
        
        ' Grid Formatting
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlInsideVertical).Weight = xlThin
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlInsideVertical).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlInsideHorizontal).Weight = xlThin
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlInsideHorizontal).LineStyle = xlContinuous
        
        ls_Range = GetExcellRange(al_ColIdx + 1, al_RowIdx + 2, ll_ColCount + al_ColIdx + 1, al_RowIdx + 2 + ll_RowCount)               ' 01.08.2013 JN fixing 2 letters columns bug
'        ls_Range = Chr(64 + al_ColIdx + 1) & (al_RowIdx + 2) & ":" & Chr(64 + ll_ColCount + al_ColIdx + 1) & (al_RowIdx + 2 + ll_RowCount)
        ao_ExcelWorkSheet.Range(ls_Range).NumberFormat = "#,##0.00"
        
        'Left border
        ls_Range = GetExcellRange(al_ColIdx, al_RowIdx, al_ColIdx + 1, al_RowIdx + 1 + ll_RowCount)                 ' 01.08.2013 JN fixing 2 letters columns bug
'        ls_Range = Chr(64 + al_ColIdx) & al_RowIdx & ":" & Chr(64 + al_ColIdx + 1) & (al_RowIdx + 1 + ll_RowCount)
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeLeft).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeLeft).Weight = xlThick

        'Right Border
        ls_Range = GetExcellRange(al_ColIdx + ll_ColCount + 1, al_RowIdx, ll_ColCount + al_ColIdx + 1, al_RowIdx + 1 + ll_RowCount)                 ' 01.08.2013 JN fixing 2 letters columns bug
'        ls_Range = Chr(64 + al_ColIdx + ll_ColCount + 1) & al_RowIdx & ":" & Chr(64 + ll_ColCount + al_ColIdx + 1) & (al_RowIdx + 1 + ll_RowCount)
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeright).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeright).Weight = xlThick

        ' Bottom
        ls_Range = GetExcellRange(al_ColIdx, al_RowIdx + 1 + ll_RowCount, ll_ColCount + al_ColIdx + 1, al_RowIdx + 1 + ll_RowCount)                 ' 01.08.2013 JN fixing 2 letters columns bug
'        ls_Range = Chr(64 + al_ColIdx) & (al_RowIdx + 1 + ll_RowCount) & ":" & Chr(64 + ll_ColCount + al_ColIdx + 1) & (al_RowIdx + 1 + ll_RowCount)
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeBottom).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeBottom).Weight = xlThick

        'Top
        ls_Range = GetExcellRange(al_ColIdx, al_RowIdx, ll_ColCount + al_ColIdx + 1, al_RowIdx)                   ' 01.08.2013 JN fixing 2 letters columns bug
'        ls_Range = Chr(64 + al_ColIdx) & (al_RowIdx) & ":" & Chr(64 + ll_ColCount + al_ColIdx + 1) & (al_RowIdx)
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeTop).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeTop).Weight = xlThick
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeBottom).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeBottom).Weight = xlThick
            
        Call ao_ExcelWorkSheet.Range(ls_Range).Merge
    
        
        ' Row
        ls_Range = GetExcellRange(al_ColIdx, al_RowIdx + 2, al_ColIdx, al_RowIdx + 1 + ll_RowCount)                  ' 01.08.2013 JN fixing 2 letters columns bug
'        ls_Range = Chr(64 + al_ColIdx) & (al_RowIdx + 2) & ":" & Chr(64 + al_ColIdx) & (al_RowIdx + 1 + ll_RowCount)
        ao_ExcelWorkSheet.Range(ls_Range).Interior.ColorIndex = 19
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeright).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeright).Weight = -4138       'xlMedium
        
    
        ' Column
        ls_Range = GetExcellRange(al_ColIdx + 1, al_RowIdx + 1, ll_ColCount + al_ColIdx + 1, al_RowIdx + 1)                  ' 01.08.2013 JN fixing 2 letters columns bug
'        ls_Range = Chr(64 + al_ColIdx + 1) & (al_RowIdx + 1) & ":" & Chr(64 + ll_ColCount + al_ColIdx + 1) & (al_RowIdx + 1)
        ao_ExcelWorkSheet.Range(ls_Range).Interior.ColorIndex = 19
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeBottom).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeBottom).Weight = -4138          'xlMedium
        ao_ExcelWorkSheet.Range(ls_Range).HorizontalAlignment = -4108
        
        ' Total
        ls_Range = GetExcellRange(ll_ColCount + 1 + al_ColIdx, al_RowIdx + 2, ll_ColCount + 1 + al_ColIdx, al_RowIdx + 1 + ll_RowCount)                  ' 01.08.2013 JN fixing 2 letters columns bug
'        ls_Range = Chr(64 + ll_ColCount + 1 + al_ColIdx) & (al_RowIdx + 2) & ":" & Chr(64 + ll_ColCount + 1 + al_ColIdx) & (al_RowIdx + 1 + ll_RowCount)
        ao_ExcelWorkSheet.Range(ls_Range).Font.Italic = True
        ao_ExcelWorkSheet.Range(ls_Range).Font.Bold = True
        ao_ExcelWorkSheet.Range(ls_Range).Interior.ColorIndex = 36
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeLeft).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeLeft).Weight = -4138        'xlMedium
         
        ao_ExcelWorkSheet.cells(al_RowIdx + 1, al_ColIdx + ll_ColCount + 1).Borders(xlEdgeLeft).LineStyle = xlContinuous
        ao_ExcelWorkSheet.cells(al_RowIdx + 1, al_ColIdx + ll_ColCount + 1).Borders(xlEdgeLeft).Weight = xlMedium
        ao_ExcelWorkSheet.cells(al_RowIdx + 1, al_ColIdx).Interior.ColorIndex = 15
        ao_ExcelWorkSheet.cells(al_RowIdx + 1, al_ColIdx + ll_ColCount + 1).Value = "Total"
        ao_ExcelWorkSheet.cells(al_RowIdx + 1, al_ColIdx + ll_ColCount + 1).Font.Bold = True
        ao_ExcelWorkSheet.cells(al_RowIdx + 1, al_ColIdx + ll_ColCount + 1).Font.Size = 13
 
        ao_ExcelWorkSheet.Columns(Chr(64 + al_ColIdx)).columnWidth = 30
   
        ' Row Total
        ls_Range = GetExcellRange(1 + al_ColIdx, al_RowIdx + 2 + ll_RowCount, ll_ColCount + 1 + al_ColIdx, al_RowIdx + 2 + ll_RowCount)                  ' 01.08.2013 JN fixing 2 letters columns bug
'        ls_Range = Chr(64 + 1 + al_ColIdx) & (al_RowIdx + 2 + ll_RowCount) & ":" & Chr(64 + ll_ColCount + 1 + al_ColIdx) & (al_RowIdx + 2 + ll_RowCount)
        ao_ExcelWorkSheet.Range(ls_Range).Interior.ColorIndex = 36
        ao_ExcelWorkSheet.Range(ls_Range).Font.Italic = True
        ao_ExcelWorkSheet.Range(ls_Range).Font.Bold = True
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeLeft).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeLeft).Weight = xlThick
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeright).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeright).Weight = xlThick
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeBottom).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeBottom).Weight = xlThick
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeTop).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeTop).Weight = xlMedium
        
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlInsideVertical).Weight = xlThin
        If ll_RowCount > 0 Then ao_ExcelWorkSheet.Range(ls_Range).Borders(xlInsideVertical).LineStyle = xlContinuous    '1.8.2013 JN not possible to set insideVertical border if the range containt 1 column
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlInsideHorizontal).Weight = xlThin
'        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlInsideHorizontal).LineStyle = xlContinuous         ' 1.8.2013 JN not possible to set insideHorizontal border if the range containt 1 row
        
        ls_Range = GetExcellRange(ll_ColCount + 1 + al_ColIdx, al_RowIdx + 2 + ll_RowCount, ll_ColCount + 1 + al_ColIdx, al_RowIdx + 2 + ll_RowCount)   ' 01.08.2013 JN fixing 2 letters columns bug
'        ls_Range = Chr(64 + ll_ColCount + 1 + al_ColIdx) & (al_RowIdx + 2 + ll_RowCount) & ":" & Chr(64 + ll_ColCount + 1 + al_ColIdx) & (al_RowIdx + 2 + ll_RowCount)
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeLeft).LineStyle = xlContinuous
        ao_ExcelWorkSheet.Range(ls_Range).Borders(xlEdgeLeft).Weight = xlMedium

        al_RowIdx = al_RowIdx + ll_RowCount + 2
        al_ColIdx = ll_ColCount + al_ColIdx + 1
        Exit Function
        
ErrHandler:
    Call LogErrorMessage("WriteDailyReportRequest")
End Function

Private Function GetExcellRange(ByVal al_startCol As Long, ByVal al_StartRow As Long, ByVal al_endCol As Long, ByVal al_EndRow As Long) As String
On Error GoTo ErrHandler
    Dim ls_StartLetter As String
    Dim ls_EndLetter As String
    
    al_startCol = al_startCol - 1
    al_endCol = al_endCol - 1
    
    ls_StartLetter = ""
    Do While al_startCol >= 0
        ls_StartLetter = Chr(65 + (al_startCol Mod 26)) & ls_StartLetter
        al_startCol = Int(al_startCol / 26) - 1
    Loop
    
    ls_EndLetter = ""
    Do While al_endCol >= 0
        ls_EndLetter = Chr(65 + (al_endCol Mod 26)) & ls_EndLetter
        al_endCol = Int(al_endCol / 26) - 1
    Loop
    
    GetExcellRange = ls_StartLetter & al_StartRow & ":" & ls_EndLetter & al_EndRow
    Exit Function
        
ErrHandler:
    Call LogErrorMessage("GetExcellRange")
End Function

Private Sub cbo_ChartType_ComboItemSelected()
On Error GoTo ErrHandler
    Dim ab_lock As Boolean
    ab_lock = LockScreen(True)
    
    
    If Not cbo_ChartType.SelectedItem Is Nothing Then
        mch_SalesSummary.chartType = cbo_ChartType.SelectedItem.Key
    End If
    
    LockScreen (False)
    Exit Sub
    
ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("cbo_ChartType_ComboItemSelected")
    ab_lock = LockScreen(False)
    

End Sub


Private Sub cbo_LegendPosition_ComboItemSelected()
On Error GoTo ErrHandler
    Dim ab_lock As Boolean
    ab_lock = LockScreen(True)
    
    
    If Not cbo_ChartType.SelectedItem Is Nothing Then
        mch_SalesSummary.Legend.Location.LocationType = cbo_LegendPosition.SelectedItem.Key
    End If

    
    LockScreen (False)
    Exit Sub
    
ErrHandler:
    If (ab_lock) Then LockScreen (False)
    Call LogErrorMessage("cbo_LegendPosition_ComboItemSelected")
    ab_lock = LockScreen(False)
End Sub
