VERSION 5.00
Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.1#0"; "mscomctl.OCX"
Object = "{5E9E78A0-531B-11CF-91F6-C2863C385E30}#1.0#0"; "MSFlxGrd.ocx"
Begin VB.UserControl DC_Report 
   ClientHeight    =   7695
   ClientLeft      =   0
   ClientTop       =   0
   ClientWidth     =   17370
   ScaleHeight     =   7695
   ScaleWidth      =   17370
   Begin VB.Frame frm_status 
      BorderStyle     =   0  'None
      Height          =   420
      Left            =   600
      TabIndex        =   45
      Top             =   7200
      Width           =   15525
      Begin MSComctlLib.ProgressBar prg_progres 
         Height          =   180
         Left            =   4560
         TabIndex        =   46
         Top             =   135
         Width           =   10815
         _ExtentX        =   19076
         _ExtentY        =   318
         _Version        =   393216
         Appearance      =   0
      End
      Begin VB.Label lbl_action 
         BorderStyle     =   1  'Fixed Single
         Caption         =   "Main screen"
         Height          =   270
         Left            =   150
         TabIndex        =   47
         Top             =   90
         Width           =   4140
      End
   End
   Begin VB.Frame frm_tab 
      Height          =   6255
      Index           =   3
      Left            =   600
      TabIndex        =   32
      Tag             =   "STAT"
      Top             =   5880
      Visible         =   0   'False
      Width           =   16155
      Begin Project1.ArmCheckView ckv_STAT_Carrier 
         Height          =   3735
         Left            =   13920
         TabIndex        =   42
         Top             =   1680
         Width           =   1935
         _ExtentX        =   3413
         _ExtentY        =   6588
      End
      Begin Project1.A_calocx cal_STAT_To 
         Height          =   300
         Left            =   7200
         TabIndex        =   41
         Top             =   960
         Width           =   1860
         _ExtentX        =   3466
         _ExtentY        =   529
      End
      Begin Project1.A_calocx cal_STAT_From 
         Height          =   300
         Left            =   4620
         TabIndex        =   40
         Top             =   960
         Width           =   1860
         _ExtentX        =   3466
         _ExtentY        =   529
      End
      Begin VB.Frame frm_filters 
         Caption         =   "#Filters"
         Height          =   720
         Index           =   3
         Left            =   210
         TabIndex        =   33
         Tag             =   "lbl_filters"
         Top             =   720
         Width           =   15165
         Begin Project1.ArmCombobox cbo_STAT_DC_Code 
            Height          =   345
            Left            =   1320
            TabIndex        =   34
            Tag             =   "DC_Code"
            Top             =   200
            Width           =   2115
            _ExtentX        =   3731
            _ExtentY        =   609
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#To"
            Height          =   255
            Index           =   12
            Left            =   6480
            TabIndex        =   39
            Tag             =   "lbl_end_date"
            Top             =   270
            Width           =   540
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#Distr. centre"
            Height          =   255
            Index           =   11
            Left            =   120
            TabIndex        =   36
            Tag             =   "lbl_Dist_centre"
            Top             =   270
            Width           =   1005
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#From"
            Height          =   255
            Index           =   10
            Left            =   3840
            TabIndex        =   35
            Tag             =   "lbl_start_date"
            Top             =   270
            Width           =   750
         End
      End
      Begin MSFlexGridLib.MSFlexGrid grd_STAT_Report 
         Height          =   2910
         Left            =   495
         TabIndex        =   37
         Top             =   1905
         Width           =   9420
         _ExtentX        =   16616
         _ExtentY        =   5133
         _Version        =   393216
         Cols            =   6
         FixedCols       =   5
         AllowBigSelection=   0   'False
         FocusRect       =   2
         SelectionMode   =   1
         MergeCells      =   4
         AllowUserResizing=   3
      End
      Begin Project1.ToolbarControl tlb_main 
         Height          =   690
         Index           =   3
         Left            =   120
         TabIndex        =   38
         TabStop         =   0   'False
         Tag             =   "STAT"
         Top             =   75
         Width           =   7125
         _ExtentX        =   12568
         _ExtentY        =   1217
      End
      Begin Project1.ArmCheckView ckv_STAT_CT_Code 
         Height          =   3735
         Left            =   12480
         TabIndex        =   43
         Top             =   1920
         Width           =   1935
         _ExtentX        =   3413
         _ExtentY        =   6588
      End
      Begin Project1.ArmCheckView ckv_STAT_Carrier_Tender 
         Height          =   3735
         Left            =   10920
         TabIndex        =   44
         Top             =   2280
         Width           =   1935
         _ExtentX        =   3413
         _ExtentY        =   6588
      End
   End
   Begin VB.Frame frm_tab 
      Height          =   3975
      Index           =   2
      Left            =   720
      TabIndex        =   22
      Tag             =   "SUP"
      Top             =   3960
      Visible         =   0   'False
      Width           =   16635
      Begin Project1.A_calocx cal_SUP_INV_To 
         Height          =   300
         Left            =   14700
         TabIndex        =   59
         Top             =   960
         Width           =   1860
         _ExtentX        =   3281
         _ExtentY        =   529
      End
      Begin Project1.A_calocx cal_SUP_INV_From 
         Height          =   300
         Left            =   12120
         TabIndex        =   58
         Top             =   960
         Width           =   1860
         _ExtentX        =   3281
         _ExtentY        =   529
      End
      Begin VB.Frame frm_filters 
         Caption         =   "#Filters"
         Height          =   720
         Index           =   2
         Left            =   210
         TabIndex        =   23
         Tag             =   "lbl_filters"
         Top             =   750
         Width           =   16485
         Begin Project1.ArmCombobox cbo_SUP_DC_Code 
            Height          =   345
            Left            =   1245
            TabIndex        =   24
            Tag             =   "DC_Code"
            Top             =   225
            Width           =   2115
            _ExtentX        =   3731
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_SUP_Carrier_code 
            Height          =   345
            Left            =   4380
            TabIndex        =   25
            Tag             =   "CARRIER_Code"
            Top             =   225
            Width           =   2115
            _ExtentX        =   3731
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_SUP_Supplier_code 
            Height          =   345
            Left            =   8040
            TabIndex        =   26
            Tag             =   "DC_Code"
            Top             =   225
            Width           =   3060
            _ExtentX        =   5398
            _ExtentY        =   609
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#To"
            Height          =   255
            Index           =   17
            Left            =   13920
            TabIndex        =   55
            Tag             =   "lbl_end_date"
            Top             =   270
            Width           =   540
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#From"
            Height          =   255
            Index           =   16
            Left            =   11280
            TabIndex        =   54
            Tag             =   "lbl_start_date"
            Top             =   270
            Width           =   750
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#Supplier"
            Height          =   255
            Index           =   8
            Left            =   6645
            TabIndex        =   29
            Tag             =   "lbl_supplier"
            Top             =   270
            Width           =   1410
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#Carrier"
            Height          =   255
            Index           =   7
            Left            =   3525
            TabIndex        =   28
            Tag             =   "lbl_Carrier"
            Top             =   270
            Width           =   780
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#Distr. centre"
            Height          =   255
            Index           =   6
            Left            =   120
            TabIndex        =   27
            Tag             =   "lbl_Dist_centre"
            Top             =   270
            Width           =   1005
         End
      End
      Begin MSFlexGridLib.MSFlexGrid grd_SUP_Invoice 
         Height          =   2910
         Left            =   495
         TabIndex        =   30
         Top             =   1905
         Width           =   9420
         _ExtentX        =   16616
         _ExtentY        =   5133
         _Version        =   393216
         Cols            =   6
         FixedCols       =   5
         AllowBigSelection=   0   'False
         FocusRect       =   2
         SelectionMode   =   1
         MergeCells      =   4
         AllowUserResizing=   3
      End
      Begin Project1.ToolbarControl tlb_main 
         Height          =   690
         Index           =   2
         Left            =   120
         TabIndex        =   31
         TabStop         =   0   'False
         Tag             =   "SUP"
         Top             =   75
         Width           =   7125
         _ExtentX        =   12568
         _ExtentY        =   1217
      End
   End
   Begin VB.Frame frm_tab 
      Height          =   3975
      Index           =   1
      Left            =   1035
      TabIndex        =   2
      Tag             =   "INT"
      Top             =   2595
      Visible         =   0   'False
      Width           =   16380
      Begin Project1.A_calocx cal_INT_INV_To 
         Height          =   300
         Left            =   14700
         TabIndex        =   57
         Top             =   960
         Width           =   1860
         _ExtentX        =   3281
         _ExtentY        =   529
      End
      Begin Project1.A_calocx cal_INT_INV_From 
         Height          =   300
         Left            =   12120
         TabIndex        =   56
         Top             =   960
         Width           =   1860
         _ExtentX        =   3281
         _ExtentY        =   529
      End
      Begin VB.Frame frm_filters 
         Caption         =   "#Filters"
         Height          =   720
         Index           =   1
         Left            =   210
         TabIndex        =   11
         Tag             =   "lbl_filters"
         Top             =   750
         Width           =   16125
         Begin Project1.ArmCombobox cbo_INT_DC_Code 
            Height          =   345
            Left            =   1245
            TabIndex        =   12
            Tag             =   "DC_Code"
            Top             =   225
            Width           =   2115
            _ExtentX        =   3731
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_INT_Carrier_code 
            Height          =   345
            Left            =   4380
            TabIndex        =   13
            Tag             =   "CARRIER_Code"
            Top             =   225
            Width           =   2115
            _ExtentX        =   3731
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_INT_ShipFromDC_code 
            Height          =   345
            Left            =   8040
            TabIndex        =   14
            Tag             =   "DC_Code"
            Top             =   225
            Width           =   3060
            _ExtentX        =   5398
            _ExtentY        =   609
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#To"
            Height          =   255
            Index           =   15
            Left            =   13920
            TabIndex        =   53
            Tag             =   "lbl_end_date"
            Top             =   270
            Width           =   540
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#From"
            Height          =   255
            Index           =   14
            Left            =   11280
            TabIndex        =   52
            Tag             =   "lbl_start_date"
            Top             =   270
            Width           =   750
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#Distr. centre"
            Height          =   255
            Index           =   5
            Left            =   120
            TabIndex        =   17
            Tag             =   "lbl_Dist_centre"
            Top             =   270
            Width           =   1005
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#Carrier"
            Height          =   255
            Index           =   4
            Left            =   3525
            TabIndex        =   16
            Tag             =   "lbl_Carrier"
            Top             =   270
            Width           =   780
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#Ship from DC"
            Height          =   255
            Index           =   2
            Left            =   6555
            TabIndex        =   15
            Tag             =   "lbl_ShipFromDC"
            Top             =   270
            Width           =   1410
         End
      End
      Begin MSFlexGridLib.MSFlexGrid grd_INT_Invoice 
         Height          =   2910
         Left            =   495
         TabIndex        =   18
         Top             =   1905
         Width           =   9420
         _ExtentX        =   16616
         _ExtentY        =   5133
         _Version        =   393216
         Cols            =   6
         FixedCols       =   5
         AllowBigSelection=   0   'False
         FocusRect       =   2
         SelectionMode   =   1
         MergeCells      =   4
         AllowUserResizing=   3
      End
      Begin Project1.ToolbarControl tlb_main 
         Height          =   690
         Index           =   1
         Left            =   120
         TabIndex        =   21
         TabStop         =   0   'False
         Tag             =   "INT"
         Top             =   75
         Width           =   7125
         _ExtentX        =   12568
         _ExtentY        =   1217
      End
   End
   Begin VB.Frame frm_tab 
      Height          =   6015
      Index           =   0
      Left            =   450
      TabIndex        =   1
      Tag             =   "CUS"
      Top             =   585
      Visible         =   0   'False
      Width           =   16950
      Begin Project1.A_calocx cal_INV_DC_From 
         Height          =   300
         Left            =   12360
         TabIndex        =   51
         Top             =   1260
         Width           =   1860
         _ExtentX        =   3281
         _ExtentY        =   529
      End
      Begin Project1.A_calocx cal_INV_DC_To 
         Height          =   300
         Left            =   14940
         TabIndex        =   50
         Top             =   1260
         Width           =   1860
         _ExtentX        =   3281
         _ExtentY        =   529
      End
      Begin VB.Frame frm_filters 
         Caption         =   "#Filters"
         Height          =   720
         Index           =   0
         Left            =   300
         TabIndex        =   3
         Tag             =   "lbl_filters"
         Top             =   975
         Width           =   16635
         Begin VB.CheckBox chk_wool 
            Alignment       =   1  'Right Justify
            Caption         =   "#Wool only"
            Height          =   285
            Left            =   9870
            TabIndex        =   19
            Tag             =   "chk_wool"
            Top             =   285
            Width           =   1425
         End
         Begin Project1.ArmCombobox cbo_DC_Code 
            Height          =   345
            Left            =   1245
            TabIndex        =   4
            Tag             =   "DC_Code"
            Top             =   225
            Width           =   2115
            _ExtentX        =   3731
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_CARRIER_Code 
            Height          =   345
            Left            =   4380
            TabIndex        =   5
            Tag             =   "CARRIER_Code"
            Top             =   225
            Width           =   2115
            _ExtentX        =   3731
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_CT_Code 
            Height          =   345
            Left            =   7650
            TabIndex        =   6
            Tag             =   "DC_Code"
            Top             =   225
            Width           =   2115
            _ExtentX        =   3731
            _ExtentY        =   609
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#From"
            Height          =   255
            Index           =   13
            Left            =   11460
            TabIndex        =   49
            Tag             =   "lbl_start_date"
            Top             =   315
            Width           =   750
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#To"
            Height          =   255
            Index           =   9
            Left            =   14100
            TabIndex        =   48
            Tag             =   "lbl_end_date"
            Top             =   315
            Width           =   540
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#Country"
            Height          =   255
            Index           =   3
            Left            =   6555
            TabIndex        =   9
            Tag             =   "lbl_Country"
            Top             =   270
            Width           =   1005
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#Carrier"
            Height          =   255
            Index           =   1
            Left            =   3525
            TabIndex        =   8
            Tag             =   "lbl_Carrier"
            Top             =   270
            Width           =   780
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#Distr. centre"
            Height          =   255
            Index           =   0
            Left            =   120
            TabIndex        =   7
            Tag             =   "lbl_Dist_centre"
            Top             =   270
            Width           =   1005
         End
      End
      Begin MSFlexGridLib.MSFlexGrid grd_DC_Invoice 
         Height          =   4935
         Left            =   390
         TabIndex        =   10
         Top             =   1020
         Width           =   11055
         _ExtentX        =   19500
         _ExtentY        =   8705
         _Version        =   393216
         Cols            =   6
         FixedCols       =   5
         AllowBigSelection=   0   'False
         FocusRect       =   2
         SelectionMode   =   1
         MergeCells      =   4
         AllowUserResizing=   3
      End
      Begin Project1.ToolbarControl tlb_main 
         Height          =   690
         Index           =   0
         Left            =   75
         TabIndex        =   20
         TabStop         =   0   'False
         Tag             =   "CUS"
         Top             =   180
         Width           =   7125
         _ExtentX        =   12568
         _ExtentY        =   1217
      End
   End
   Begin MSComctlLib.TabStrip tbs_main 
      Height          =   6930
      Left            =   480
      TabIndex        =   0
      Tag             =   "tbs_main"
      Top             =   120
      Width           =   17220
      _ExtentX        =   30374
      _ExtentY        =   12224
      _Version        =   393216
      BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
         NumTabs         =   4
         BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
            Caption         =   "#Pending invoices"
            Key             =   "CUS"
            Object.Tag             =   "lbl_CUS_Tab"
            Object.ToolTipText     =   "Invoices for customer shippments to be sent by carriers"
            ImageVarType    =   2
         EndProperty
         BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
            Caption         =   "#Intercompany invoices"
            Key             =   "INT"
            Object.Tag             =   "lbl_INT_Tab"
            Object.ToolTipText     =   "Invoices for intercompany shippments to be sent by carriers"
            ImageVarType    =   2
         EndProperty
         BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
            Caption         =   "#Supplier invoices"
            Key             =   "SUP"
            Object.Tag             =   "lbl_SUP_Tab"
            Object.ToolTipText     =   "Invoices for supplier shippments to be sent by carriers"
            ImageVarType    =   2
         EndProperty
         BeginProperty Tab4 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
            Caption         =   "#Statistics"
            Key             =   "STAT"
            Object.Tag             =   "lbl_STAT_Tab"
            Object.ToolTipText     =   "Statistics of shipments"
            ImageVarType    =   2
         EndProperty
      EndProperty
   End
End
Attribute VB_Name = "DC_Report"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

Private Const SCREEN_NAME As String = "DCInvoiceReport"


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

Const C_REQ_CARRIER As String = "EXEC DC_Carrier_lst $DC_CODE$, 0"
Const C_REQ_CARRIER2 As String = "EXEC DC_Carrier_cbo2 $DC_CODE$, $TenderCarrier$"
Const C_REQ_CT_Code As String = "EXEC DC_Countries_cbo $DC_CODE$, $CARRIER_CODE$, $Language_code$"
Const C_REQ_CT_Code2 As String = "EXEC DC_Countries_cbo2 $DC_CODE$, $CARRIER_CODE$, $Language_code$"

Private Const SEP = "®©"
Private Const SEP1 As String = "®"
Private Const SEP2 As String = "©"
Private Const SEPu As String = "ú"
Private Const CL_COLOR_ENABLED As Long = &H80000005
Private Const CL_COLOR_DISABLED As Long = &H8000000F

Private Const C_TOOLBAR_ID As Long = 3000
Private Const C_TOOLBARFACE_ITEM_LST As String = "0"

Private Const VALUE_FORMAT As String = "###0.00"
Private Const MONEY_FORMAT As String = "###0.00"
Private mb_eventRunning As Boolean
Private mb_Initialized As Boolean
#If LIVE = 1 Then
    Dim mo_Db As Object
    Dim mo_scriptObj As Object
#Else
    Dim mo_Db As ARMSYSCOMLib.ArmDb
    Dim mo_scriptObj As MSScriptControl.ScriptControl       ' to calculate the price list formula
#End If

    
Private ms_Language_Code As String

Private mb_STAT_CARRIERS_upd As Boolean
Private mb_STAT_COUNTRIES_upd As Boolean

Private Const C_LEADING_INTRECO_TRAN As Long = 0
Const QTY_FOR_TRANSPORT As Boolean = True
Const QTY_FOR_COST As Boolean = False

Private Type tTenderCost
    TRANS_Code As Long
    DC_Cost As Double
    DC_DropOffCost As Double
    CURR_Code As String
    UOM_Code As String
End Type

Private Type tCarrierTender
    CARRIER_code As String
    TenderCosts() As tTenderCost
    TenderCostsCount As Long
    TenderDCCost As Double               ' temporary value to calculate ranging per dc grouping
End Type

Private Type tDCSurcharge_cost
    DCS_Code As String
    DCS_quantity As Double
    DCS_Price As Double
    SurchargeFormula As String
End Type

Private Type tDCTransport_cost
    TRANS_Code As Long
    UOM_Code As String
    Quantity As Double
    Quantity_loaded As Double
'    DCS_quantity As Double
    DCPL_Code As Long
    DCPLLI_code As Long
    DCPLLI_Price As Double
    DCPLLI_CURR_Code As String
'    DCS_Price As Double
    Manual_Cost As Double
    Surcharge_Cost As Double
    DCPLL_Full_Truck_Price As Double
    DCPLL_Full_Truck_Min As Double
    DCPLL_Full_Truck_Max As Double
    DCPLL_Trailer_min As Double
  
    PriceFormula As String
    FullTruckPriceFormula As String
'    SurchargeFormula As String
    
    SurchargeInfo() As tDCSurcharge_cost
End Type

Dim moa_DCTransport_cost() As tDCTransport_cost         ' to generate tender costs

Private mc_ScreenLabels As Long
Private ml_U_Code As Long
Private ms_LoginName As String
Private ml_iConcurrency As Long                   ' iconcurrency

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

Private Type GRD_Info
    gCsts_prefix As String
    gTitle As String
    gDC_Desc As String
    gCARRIER_Name As String
    gFilterA As String
    gFilterB As String
    Cols() As GRD_ColumnInfo
End Type


Dim mo_DC_ReportCustomerInfo As GRD_Info               ' info for Report for customer shipments
Dim mo_DC_ReportIntercomapnyInfo As GRD_Info           ' info for Report for intercomapny shipments
Dim mo_DC_ReportSupplierInfo As GRD_Info               ' info for Report for suppier shipments
Dim mo_DC_ReportStatisticsInfo As GRD_Info

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


Public Event quit()


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


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 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)
    Call Resize
End Sub

Property Let Language_Code(AString As String)
On Error GoTo errhandler

  ms_Language_Code = AString
  Exit Property
errhandler:
  Call ErrorMessage("Language_Code.Let")
End Property

Property Let U_Code(ByVal al_U_Code As Long)
On Error GoTo errhandler

  ml_U_Code = al_U_Code
  Exit Property
errhandler:
  Call ErrorMessage("U_Code.Let")
End Property

Public Property Let LoginName(ByVal as_loginName As String)
On Error GoTo errhandler
    
    ms_LoginName = as_loginName
    Exit Property
errhandler:
    Call ErrorMessage(Extender.Name & ".LoginName(Let)")
End Property

Public Property Set ArmDb(ByRef lo_Db As Object)
On Error GoTo errhandler
  
  Set mo_Db = lo_Db
  Exit Property
errhandler:
  Call ErrorHandler("ArmDb.Set")
End Property


Public Sub Load_A_COM()
    
On Error GoTo errhandler

    If mb_Initialized Then Exit Sub
    
    mb_Initialized = True
    
    mb_eventRunning = True
    
    Dim lo_Control As Object
    Dim lo_ToolTip As Object
    
      For Each lo_Control In Controls
        Select Case UCase(TypeName(lo_Control))
        Case "ARMCOMBOBOX"
          Set lo_Control.ArmDb = mo_Db
          Call lo_Control.Load_A_COM
        Case "ARMPICKER"
          Set lo_Control.ArmDb = mo_Db
          Call lo_Control.Load_A_COM
        Case "TOOLBARCONTROL"
          lo_Control.Language = ms_Language_Code
'          Set lo_Control.ArmDb = mo_Db
          Call lo_Control.Load_A_COM
        Case "ARMGRID"
          Set lo_Control.ArmDb = mo_Db
          Call lo_Control.Load_A_COM
        Case "ARMTREEVIEW"
          Set lo_Control.ArmDb = mo_Db
          lo_Control.Language = ms_Language_Code
          Call lo_Control.Load_A_COM
        Case "ARMCHECKVIEW", "ARMCHECKVIEW0"
          Set lo_Control.ArmDb = mo_Db
          Call lo_Control.Load_A_COM
        Case "A_CALOCX"
          lo_Control.Language = ms_Language_Code
          Call lo_Control.reinit_cal
        Case "TOOLBR"
          Set lo_Control.ArmDb = mo_Db
          Call lo_Control.Load_A_COM
        End Select
      Next
    
#If LIVE = 1 Then
    Set mo_scriptObj = CreateObject("MSScriptControl.ScriptControl")
#Else
    Set mo_scriptObj = New MSScriptControl.ScriptControl
#End If

    mo_scriptObj.Language = "VBScript"
    
    
        ' init toolbar
    Dim ll_Cursor As Long
    
    ll_Cursor = OpenSQLSafe(mo_Db, "exec Toolbar_sel 'DC Load Plan'")
    
    If mo_Db.Find(ll_Cursor, "Id", C_TOOLBAR_ID) < 0 Then
        Err.Raise 1, tlb_Main(0).Name, "Toolbar not found in toolbars_definitions ID:" & C_TOOLBAR_ID
    End If

    Dim ls_ToolbarInfo  As String
    ls_ToolbarInfo = mo_Db.GetFields(ll_Cursor, "info")
    
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    Dim lo_ctrl As ToolbarControl
    For Each lo_ctrl In tlb_Main
        Call lo_ctrl.SetToolbarInfoStringParameters(ls_ToolbarInfo, Left(ls_ToolbarInfo, 3))
        Call lo_ctrl.DisplayFace(C_TOOLBARFACE_ITEM_LST)
    Next

    ' INIT COMBOBOXES
    cbo_DC_Code.FirstBlankItem = True
    cbo_DC_Code.Request = "EXEC DC_cbo"
    cal_INV_DC_From.opening_toward_top = 1
    cal_INV_DC_To.opening_toward_top = 1
    
    cal_INT_INV_From.opening_toward_top = 1
    cal_INT_INV_To.opening_toward_top = 1
    
    cal_SUP_INV_From.opening_toward_top = 1
    cal_SUP_INV_To.opening_toward_top = 1
    
    cbo_INT_DC_Code.FirstBlankItem = True
    cbo_INT_DC_Code.Request = "EXEC DC_cbo"
    
    cbo_SUP_DC_Code.FirstBlankItem = True
    cbo_SUP_DC_Code.Request = "EXEC DC_cbo"
    
    cbo_STAT_DC_Code.FirstBlankItem = True
    cbo_STAT_DC_Code.Request = "EXEC DC_cbo"
    
    cbo_INT_ShipFromDC_code.FirstBlankItem = True
    cbo_INT_ShipFromDC_code.Request = "EXEC DC_cbo"
    
    cbo_CARRIER_Code.FirstBlankItem = True
    cbo_CARRIER_Code.Request = "EXEC DC_Carrier_cbo "
    
    cbo_INT_CARRIER_Code.FirstBlankItem = True
    cbo_INT_CARRIER_Code.Request = "EXEC DC_Carrier_cbo "
    
    cbo_SUP_CARRIER_Code.FirstBlankItem = True
    cbo_SUP_CARRIER_Code.Request = "EXEC DC_Carrier_cbo "
    
    cbo_SUP_Supplier_code.FirstBlankItem = True
    cbo_SUP_Supplier_code.Request = "EXEC DC_Supplier_cbo '" & ms_Language_Code & "'"
    
    ckv_STAT_Carrier.Driven_By = "DC_Carrier"
    ckv_STAT_Carrier_Tender.Driven_By = "DC_Carrier"
    ckv_STAT_CT_Code.Driven_By = "Countries"
    
    ckv_STAT_Carrier.Common_List_Load = True
    ckv_STAT_Carrier.Type_Of_Key = tkDependant
    ckv_STAT_Carrier.Calling_Key_Fields = "DC_Code"
    ckv_STAT_Carrier.Calling_Key_Values = "NULL"
    ckv_STAT_Carrier.Link_Key_Fields = ""
    
    ckv_STAT_Carrier_Tender.Common_List_Load = True
    ckv_STAT_Carrier_Tender.Type_Of_Key = tkDependant
    ckv_STAT_Carrier_Tender.Calling_Key_Fields = "DC_Code"
    ckv_STAT_Carrier_Tender.Calling_Key_Values = "NULL"
    ckv_STAT_Carrier_Tender.Link_Key_Fields = ""
    
    
    ckv_STAT_Carrier.RoleCount = 2
    
    Dim la_DC_RoleMain As Variant, la_DC_RoleEdit As Variant
    
    la_DC_RoleMain = Array("MAIN", "VIEW", "", "", "Main view", "CARRIER_Code®©CARRIER_Name", "CARRIER_Name", "3000", "CARRIER_Code", "", "", "", True, 2, False, True, 0, 0)
    la_DC_RoleEdit = Array("EDIT", "EDIT", "", "", "Edit view", "CARRIER_Code®©CARRIER_Name", "CARRIER_Name", "3000", "CARRIER_Code", Replace(C_REQ_CARRIER2, "$TenderCarrier$", 0, , , vbTextCompare), "", "", False, 2, False, True, 3, 0)

    If Not ckv_STAT_Carrier.SetRoleList(Array(la_DC_RoleMain, la_DC_RoleEdit)) Then
        Call SendMessage(932, "#Critical error, please contact it", gut_LangLogin.Code)
        End
    End If
    
    ckv_STAT_Carrier.Synchronize_View = False
    ckv_STAT_Carrier.HideColumnHeaders = False
    ckv_STAT_Carrier.LoadConstants CVptStatic, "CARRIER_Name" & CH_LDELIMIT & "CARRIER", CVctColumns
    
'    Call ckv_STAT_Carrier.LoadList
    
    Call ckv_STAT_Carrier.SetVisibleList("EDIT")
    
    
    ckv_STAT_Carrier_Tender.RoleCount = 2
    
    la_DC_RoleMain = Array("MAIN", "VIEW", "", "", "Main view", "CARRIER_Code®©CARRIER_Name", "CARRIER_Name", "3000", "CARRIER_Code", "", "", "", True, 2, False, True, 0, 0)
    la_DC_RoleEdit = Array("EDIT", "EDIT", "", "", "Edit view", "CARRIER_Code®©CARRIER_Name", "CARRIER_Name", "3000", "CARRIER_Code", Replace(C_REQ_CARRIER2, "$TenderCarrier$", 1, , , vbTextCompare), "", "", False, 2, False, True, 3, 0)

    If Not ckv_STAT_Carrier_Tender.SetRoleList(Array(la_DC_RoleMain, la_DC_RoleEdit)) Then
        Call SendMessage(932, "#Critical error, please contact it", gut_LangLogin.Code)
        End
    End If
    
    ckv_STAT_Carrier_Tender.Synchronize_View = False
    ckv_STAT_Carrier_Tender.HideColumnHeaders = False
    ckv_STAT_Carrier_Tender.LoadConstants CVptStatic, "CARRIER_Name" & CH_LDELIMIT & "Tender Carrier", CVctColumns
    
'    Call ckv_STAT_Carrier.LoadList
    
    Call ckv_STAT_Carrier_Tender.SetVisibleList("EDIT")
    
    
    ckv_STAT_CT_Code.Common_List_Load = True
    ckv_STAT_CT_Code.Type_Of_Key = tkDependant
    ckv_STAT_CT_Code.Calling_Key_Fields = "DC_Code" & SEP & "CARRIER_Code"
    ckv_STAT_CT_Code.Calling_Key_Values = "NULL" & SEP & "NULL"
    ckv_STAT_CT_Code.Link_Key_Fields = ""
    
    ckv_STAT_CT_Code.RoleCount = 2
    
    la_DC_RoleMain = Array("MAIN", "VIEW", "Language_code", ms_Language_Code, "Main view", "CT_Code®©CT_Desc", "CT_Desc", "3000", "CT_Code", "", "", "", True, 2, False, True, 0, 0)
    la_DC_RoleEdit = Array("EDIT", "EDIT", "Language_code", ms_Language_Code, "Edit view", "CT_Code®©CT_Desc", "CT_Desc", "3000", "CT_Code", C_REQ_CT_Code2, "", "", False, 2, False, True, 3, 0)

    If Not ckv_STAT_CT_Code.SetRoleList(Array(la_DC_RoleMain, la_DC_RoleEdit)) Then
        Call SendMessage(932, "#Critical error, please contact it", gut_LangLogin.Code)
        End
    End If
    
    ckv_STAT_CT_Code.Synchronize_View = False
    ckv_STAT_CT_Code.HideColumnHeaders = False
    ckv_STAT_CT_Code.LoadConstants CVptStatic, "CT_Desc" & CH_LDELIMIT & "Country", CVctColumns
    
'    Call ckv_STAT_CT_Code.LoadList
    
    Call ckv_STAT_CT_Code.SetVisibleList("EDIT")
    
    cbo_CT_Code.FirstBlankItem = True
    
    cal_STAT_From.opening_toward_top = 1
    cal_STAT_To.opening_toward_top = 1
    
    cal_STAT_From.date_courte = Format(Now() - Day(Now()) + 1, "dd\/mm\/yyyy")
    cal_STAT_To.date_courte = Format(Now(), "dd\/mm\/yyyy")
    
    cal_INV_DC_From.date_courte = "01/01/" & Year(Now())
    cal_INT_INV_From.date_courte = "01/01/" & Year(Now())
    cal_SUP_INV_From.date_courte = "01/01/" & Year(Now())
    
    Call LoadLabels(UserControl.Controls, SCREEN_NAME, ms_Language_Code)
    Call ChangeCharset(UserControl.Controls, GetCodePageFromLanguage(mo_Db, ms_Language_Code))

    Call tbs_Main_Click
    
    mb_eventRunning = False
    
    Exit Sub
    
errhandler:
    
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    
    Call ErrorHandler("Load_A_COM")
    
End Sub


Public Sub Unload_A_COM()
    
On Error GoTo errhandler
    mb_Initialized = False
    
    Dim lo_Control As Object

    For Each lo_Control In Controls
      Select Case UCase(TypeName(lo_Control))
      Case "ARMCOMBOBOX"
        Call lo_Control.Unload_A_COM
      Case "ARMPICKER"
        Call lo_Control.Unload_A_COM
      Case "TOOLBARCONTROL"
        Call lo_Control.Unload_A_COM
      Case "ARMGRID"
        Call lo_Control.Unload_A_COM
      Case "ARMTREEVIEW"
        Call lo_Control.Unload_A_COM
      Case "ARMCHECKVIEW"
        Call lo_Control.Unload_A_COM
      Case "TOOLBR"
        Call lo_Control.Unload_A_COM
      End Select
    Next
    
    Set mo_scriptObj = Nothing
        
    If mc_ScreenLabels <> 0 Then
        Call mo_Db.Close(mc_ScreenLabels)
        mc_ScreenLabels = 0
    End If
    
    Exit Sub
    
errhandler:
    
    If mc_ScreenLabels <> 0 Then
        Call mo_Db.Close(mc_ScreenLabels)
        mc_ScreenLabels = 0
    End If
    
    Call ErrorHandler("UnLoad_A_Com")
    
End Sub

Public Sub Resize()
    Call InitCtrlSize
End Sub

Private Sub InitCtrlSize()
On Error GoTo errhandler
    If UserControl.Extender.Width < 11910 Then
        Exit Sub
    End If
    
    If UserControl.Extender.Height < 5500 Then
        Exit Sub
    End If
    
    Const SPACE As Long = 60
    
    Call tbs_Main.Move(0, 0, UserControl.Extender.Width, UserControl.Extender.Height - frm_status.Height - SPACE)
    
    Call frm_status.Move(0, tbs_Main.Top + tbs_Main.Height + SPACE, tbs_Main.Width)
    lbl_action.Left = 0
    prg_progres.Left = lbl_action.Left + lbl_action.Width + SPACE
    prg_progres.Width = frm_status.Width - prg_progres.Left - SPACE
    
    Dim lo_ctrl As Control
    
    For Each lo_ctrl In frm_tab
        Call lo_ctrl.Move(tbs_Main.clientLeft, tbs_Main.clientTop, tbs_Main.clientWidth, tbs_Main.clientHeight)
    Next
    
    For Each lo_ctrl In tlb_Main
        Call lo_ctrl.Move(SPACE, SPACE + 100, tbs_Main.clientWidth - 2 * SPACE)
    Next
        
    For Each lo_ctrl In frm_filters
        Call lo_ctrl.Move(SPACE, tlb_Main(0).Top + tlb_Main(0).Height + SPACE, tbs_Main.clientWidth - 2 * SPACE)
    Next
    
    cal_STAT_From.Left = frm_filters(3).Left + lbl_labels(10).Left + lbl_labels(10).Width
    cal_STAT_From.Top = frm_filters(3).Top + lbl_labels(10).Top - 25
    
    cal_STAT_To.Left = frm_filters(3).Left + lbl_labels(12).Left + lbl_labels(12).Width
    cal_STAT_To.Top = frm_filters(3).Top + lbl_labels(12).Top - 25
    
    cal_INV_DC_From.Left = frm_filters(0).Left + lbl_labels(13).Left + lbl_labels(13).Width
    cal_INV_DC_From.Top = frm_filters(0).Top + lbl_labels(13).Top - 25
    
    cal_INV_DC_To.Left = frm_filters(0).Left + lbl_labels(9).Left + lbl_labels(9).Width
    cal_INV_DC_To.Top = frm_filters(0).Top + lbl_labels(9).Top - 25
    
    cal_INT_INV_From.Left = frm_filters(1).Left + lbl_labels(14).Left + lbl_labels(14).Width
    cal_INT_INV_From.Top = frm_filters(1).Top + lbl_labels(14).Top - 25
    
    cal_INT_INV_To.Left = frm_filters(1).Left + lbl_labels(15).Left + lbl_labels(15).Width
    cal_INT_INV_To.Top = frm_filters(1).Top + lbl_labels(15).Top - 25
    
    cal_SUP_INV_From.Left = frm_filters(2).Left + lbl_labels(16).Left + lbl_labels(16).Width
    cal_SUP_INV_From.Top = frm_filters(2).Top + lbl_labels(16).Top - 25
    
    cal_SUP_INV_To.Left = frm_filters(2).Left + lbl_labels(17).Left + lbl_labels(17).Width
    cal_SUP_INV_To.Top = frm_filters(2).Top + lbl_labels(17).Top - 25
    
    Call grd_DC_Invoice.Move(SPACE, frm_filters(0).Top + frm_filters(0).Height + SPACE, frm_filters(0).Width)
    grd_DC_Invoice.Height = tbs_Main.clientHeight - grd_DC_Invoice.Top - SPACE
    
    Call grd_INT_Invoice.Move(grd_DC_Invoice.Left, grd_DC_Invoice.Top, grd_DC_Invoice.Width, grd_DC_Invoice.Height)
    Call grd_SUP_Invoice.Move(grd_DC_Invoice.Left, grd_DC_Invoice.Top, grd_DC_Invoice.Width, grd_DC_Invoice.Height)
    Call grd_STAT_Report.Move(grd_DC_Invoice.Left, grd_DC_Invoice.Top, grd_DC_Invoice.Width - ckv_STAT_Carrier.Width - 2 * SPACE, grd_DC_Invoice.Height)
    
    ckv_STAT_Carrier.Top = grd_STAT_Report.Top
    ckv_STAT_Carrier.Left = grd_STAT_Report.Left + grd_STAT_Report.Width + SPACE
    ckv_STAT_Carrier.Height = grd_STAT_Report.Height / 3 - 2 * SPACE
    
    ckv_STAT_Carrier_Tender.Top = ckv_STAT_Carrier.Top + ckv_STAT_Carrier.Height + SPACE
    ckv_STAT_Carrier_Tender.Left = ckv_STAT_Carrier.Left
    ckv_STAT_Carrier_Tender.Height = ckv_STAT_Carrier.Height
    
    ckv_STAT_CT_Code.Top = ckv_STAT_Carrier_Tender.Top + ckv_STAT_Carrier.Height + SPACE
    ckv_STAT_CT_Code.Left = ckv_STAT_Carrier.Left
    ckv_STAT_CT_Code.Height = ckv_STAT_Carrier.Height
    
    
    Exit Sub
errhandler:
    Call ErrorHandler("InitCtrlSize")
End Sub


'*********************************** support functions ******************************************
' display standard error message
Private Sub ErrorMessage(ByVal as_Fct As String)
    Dim ls_ErrSource As String
    Dim ls_errDescription As String
    Dim ls_Message As String
    
    ls_ErrSource = as_Fct & SEP1 & Err.Source
    ls_errDescription = Err.Description
    ls_Message = SCREEN_NAME & " exception. Nr:" & Err.Number & ",Desc: " & ls_errDescription & ",Src:" & ls_ErrSource & "@"
    Call LogMessage(ls_Message, "E")
    Call MsgBox("Error occured, please contact IT. Application will now shutdown." & vbCrLf & ls_ErrSource & vbCrLf & "Description: " & ls_errDescription, vbCritical, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision)
    End
End Sub

' Standard error handler
Private Sub ErrorHandler(ByVal as_Fct As String)
    Err.Raise Err.Number, UserControl.Name & "." & UserControl.Ambient.DisplayName & "::" & as_Fct & SEP1 & Err.Source, Err.Description
End Sub

' logs message to database
Private Sub LogMessage(ByVal as_LogMsg As String, Optional ByVal as_LogType As String = "E", Optional ab_ExitOnException As Boolean = False)
    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$", SqlStr(as_LogType))
    ls_req = Replace(ls_req, "$MSG$", SqlStr(Trim(ls_Msg), 4000), , , vbTextCompare)
    ls_req = Replace(ls_req, "$APP$", SqlStr(Trim(ls_Source), 50), , , vbTextCompare)
    
    Call ExecuteSQLSafe(mo_Db, ls_req)
    
    Err.Number = ll_errNumber
    Err.Description = ls_errDescription
    Err.Source = ls_ErrSource
    Exit Sub
    
errhandler:
    If ab_ExitOnException Then
        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, vbCritical, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision)
        End
    End If
    Err.Number = ll_errNumber
    Err.Description = ls_errDescription
    Err.Source = ls_ErrSource
End Sub

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

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

    SqlDate = "NULL"
    If IsNull(av_Data) Then av_Data = ""
    If (Trim(CStr(av_Data)) <> "") And (CStr(av_Data) <> "0") Then
        SqlDate = "'" & Format(av_Data, "yyyy-mm-dd") & "'"
    End If
    Exit Function
errhandler:
End Function


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

Private Function GetCboKey(ByRef ao_cbo As ArmCombobox) As String
On Error GoTo errhandler
    GetCboKey = ""
    If Not ao_cbo.SelectedItem Is Nothing Then
        GetCboKey = ao_cbo.SelectedItem.Key
    End If
    Exit Function
errhandler:
     Call ErrorHandler("GetCboKey()")
End Function

Private Function GetCboText(ByRef ao_cbo As ArmCombobox, Optional ByVal as_Default As String = "") As String
On Error GoTo errhandler
    GetCboText = as_Default
    If Not ao_cbo.SelectedItem Is Nothing Then
        If ao_cbo.SelectedItem.DisplayText <> "" Then GetCboText = ao_cbo.SelectedItem.DisplayText
    End If
    Exit Function
errhandler:
     Call ErrorHandler("GetCboText()")
End Function

Private Function GetCboValue(ByRef ao_cbo As ArmCombobox, ByVal av_field As Variant) As String
On Error GoTo errhandler
    GetCboValue = ""
    If Not ao_cbo.SelectedItem Is Nothing Then
        GetCboValue = ao_cbo.GetItemData(ao_cbo.SelectedItem.Key, av_field)
    End If
    Exit Function
errhandler:
     Call ErrorHandler("GetCboValue()")
End Function

Private Function SetCboKey(ByRef ao_cbo As ArmCombobox, ByVal as_Key As String) As Boolean
On Error GoTo ErrorHandler
    SetCboKey = True
    If Not ao_cbo.SearchItem(as_Key) Then
        Call ao_cbo.Load
        SetCboKey = ao_cbo.SearchItem(as_Key)
    End If
    Exit Function
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".SetCboKey")
End Function

Private Sub LockScreen(ByVal ab_lock As Boolean)

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

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

Private Function OpenSQLSafe(ByVal ao_Db As ARMSYSCOMLib.ArmDb, ByVal as_Request As String, Optional ByVal al_RowExpectedCount = -1) As Long
On Error GoTo errhandler
    Dim lc_Data As Long
    lc_Data = ao_Db.OpenSQL(as_Request)
    If lc_Data = 0 Then
        Call Err.Raise(1, "ao_Db.OpenSQL - " & "SQL : " & as_Request, "SQL Error: " & GetDbError(ao_Db))
    End If
    
    If al_RowExpectedCount <> -1 Then
        ' Then check the rowcount
        If ao_Db.RowCount(lc_Data) <> al_RowExpectedCount Then
            Call Err.Raise(2, "SQL : " & as_Request, al_RowExpectedCount & "<>" & ao_Db.RowCount(lc_Data))
        End If
    End If
    OpenSQLSafe = lc_Data
    Exit Function
errhandler:
    Call ErrorHandler("OpenSQLSafe")
End Function

Private Sub ExecuteSQLSafe(ByVal ao_Db As ARMSYSCOMLib.ArmDb, ByVal as_Request As String, Optional ByVal al_RowAffectedCount = -1, Optional ab_DuplicityCheck As Boolean = False)
On Error GoTo errhandler

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

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

errhandler:
    Call ErrorHandler("ExecuteSQLSafe")
End Sub

Private Function GetDbError(ByVal lo_Db As ARMSYSCOMLib.ArmDb) As String
On Error GoTo errhandler
    If IsArray(lo_Db.SQLErrorMessages) Then
        Debug.Assert (IsArray(lo_Db.SQLErrorCodes))
        ' Display errors msgBox
        GetDbError = Join(lo_Db.SQLErrorCodes, ",") & vbCrLf & Join(lo_Db.SQLErrorMessages, vbCrLf)
    Else
        ' ExecuteSQL failed but no error message?
        GetDbError = "Unknown error"
    End If
    Exit Function
errhandler:
    Call ErrorHandler("GetDbError()")
End Function

Function MsgText(ByVal aID As Long, ByVal aLang As String, ByVal aDefault As String, Optional ByVal aInfo As Variant) As String
On Error GoTo errhandler

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

    MsgText = ""
    
    Dim lRequest As String
    lRequest = Replace(DB_REQ, "$id$", aID, , , vbTextCompare)
    lRequest = Replace(lRequest, "$lang$", aLang, , , vbTextCompare)
    Dim lData As Long
    
    lData = OpenSQLSafe(mo_Db, lRequest)
    
    Dim lBuffer As String
    lBuffer = mo_Db.GetFields(lData, "message_text")
    mo_Db.Close (lData)
    If lBuffer = "" Then lBuffer = aDefault
    
    Dim li_idx As Integer
    If Not IsMissing(aInfo) Then
        For li_idx = 0 To UBound(aInfo)
            lBuffer = Replace(lBuffer, aInfo(li_idx, 0), aInfo(li_idx, 1), , , vbTextCompare)
        Next li_idx
    End If
    
    
    MsgText = lBuffer
    Exit Function
errhandler:
    mo_Db.Close (lData)
    Call MsgBox("Connection failure accessing message information.")
    MsgText = aDefault
End Function

' 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
    Dim lControl As Control

    mc_ScreenLabels = OpenSQLSafe(mo_Db, "exec Screen_Csts '" & as_ScreenName & "','" & as_Language & "'")
    Debug.Assert (mc_ScreenLabels <> 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(mc_ScreenLabels, "FIELD_NAME", lControl.Tag, , 1) >= 0 Then
                            lControl.Caption = mo_Db.GetFields(mc_ScreenLabels, "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(mc_ScreenLabels, "FIELD_NAME", lControl.Tag, , 1) >= 0 Then
                      Call lControl.LoadConstants(ptStatic, mo_Db.GetFields(mc_ScreenLabels, "LOCAL_TEXT"), ctColumns)
                        End If
                    If mo_Db.Find(mc_ScreenLabels, "FIELD_NAME", lControl.Tag & "_Title", , 1) >= 0 Then
                      lControl.Title = mo_Db.GetFields(mc_ScreenLabels, "LOCAL_TEXT")
                    End If
                Case "TABSTRIP"
                    If mo_Db.Find(mc_ScreenLabels, "FIELD_NAME", lControl.Tag, , 1) >= 0 Then
                        Dim lsa_TextArr() As String
                        Dim ll_Index As Long
                        
                        lsa_TextArr = Split(mo_Db.GetFields(mc_ScreenLabels, "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
    
    Exit Sub

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

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

Private Sub 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 FILTER_ReplacePlaceholders(ByVal as_req As String) As String
On Error GoTo errhandler
    
    as_req = Replace(as_req, "$DC_CODE$", SqlStr(GetCboKey(cbo_DC_Code), 4, True))
    
    as_req = Replace(as_req, "$CARRIER_CODE$", SqlStr(GetCboKey(cbo_CARRIER_Code), 10, True))
    
    as_req = Replace(as_req, "$CT_CODE$", SqlStr(GetCboKey(cbo_CT_Code), 4, True))
    
    as_req = Replace(as_req, "$FROM_DATE$", SqlDate(cal_INV_DC_From.date_dt))
    
    as_req = Replace(as_req, "$TO_DATE$", SqlDate(cal_INV_DC_To.date_dt))
    
    as_req = Replace(as_req, "$Language_code$", SqlStr(ms_Language_Code, 1))
    
    FILTER_ReplacePlaceholders = as_req
    Exit Function
errhandler:
    Call ErrorHandler(Extender.Name & ".FILTER_ReplacePlaceholders")
End Function

Private Function INT_FILTER_ReplacePlaceholders(ByVal as_req As String) As String
On Error GoTo errhandler
    
    as_req = Replace(as_req, "$DC_CODE$", SqlStr(GetCboKey(cbo_INT_DC_Code), 4, True))
    
    as_req = Replace(as_req, "$CARRIER_CODE$", SqlStr(GetCboKey(cbo_INT_CARRIER_Code), 10, True))
    
    as_req = Replace(as_req, "$FROM_DC_CODE$", SqlStr(GetCboKey(cbo_INT_ShipFromDC_code), 4, True))
    
    as_req = Replace(as_req, "$Language_code$", SqlStr(ms_Language_Code, 1))
    
    as_req = Replace(as_req, "$FROM_DATE$", SqlDate(cal_INT_INV_From.date_dt))
    
    as_req = Replace(as_req, "$TO_DATE$", SqlDate(cal_INT_INV_To.date_dt))
    
    INT_FILTER_ReplacePlaceholders = as_req
    Exit Function
errhandler:
    Call ErrorHandler(Extender.Name & ".INT_FILTER_ReplacePlaceholders")
End Function

Private Function SUP_FILTER_ReplacePlaceholders(ByVal as_req As String) As String
On Error GoTo errhandler
    
    as_req = Replace(as_req, "$DC_CODE$", SqlStr(GetCboKey(cbo_SUP_DC_Code), 4, True))
    
    as_req = Replace(as_req, "$CARRIER_CODE$", SqlStr(GetCboKey(cbo_SUP_CARRIER_Code), 10, True))
    
    as_req = Replace(as_req, "$SP_CODE$", SqlStr(GetCboKey(cbo_SUP_Supplier_code), 12, True))
    
    as_req = Replace(as_req, "$Language_code$", SqlStr(ms_Language_Code, 1))
    
    as_req = Replace(as_req, "$FROM_DATE$", SqlDate(cal_SUP_INV_From.date_dt))
    
    as_req = Replace(as_req, "$TO_DATE$", SqlDate(cal_SUP_INV_To.date_dt))
    
    SUP_FILTER_ReplacePlaceholders = as_req
    Exit Function
errhandler:
    Call ErrorHandler(Extender.Name & ".SUP_FILTER_ReplacePlaceholders")
End Function

Private Function STAT_FILTER_ReplacePlaceholders(ByVal as_req As String) As String
On Error GoTo errhandler
    
    as_req = Replace(as_req, "$DC_CODE$", SqlStr(GetCboKey(cbo_STAT_DC_Code), 4, True))
    
    as_req = Replace(as_req, "$CARRIER_CODE$", SqlStr(GetCkvSelection(ckv_STAT_Carrier), 2500, True))
    
    as_req = Replace(as_req, "$CARRIER_CODE_TENDER$", SqlStr(GetCkvSelection(ckv_STAT_Carrier_Tender), 2500, True))
    
    as_req = Replace(as_req, "$CT_CODE$", SqlStr(GetCkvSelection(ckv_STAT_CT_Code), 4, True))
    
    as_req = Replace(as_req, "$FROM_DATE$", SqlDate(cal_STAT_From.date_dt))
    
    as_req = Replace(as_req, "$TO_DATE$", SqlDate(cal_STAT_To.date_dt))
    
    as_req = Replace(as_req, "$Language_code$", SqlStr(ms_Language_Code, 1))
    
    STAT_FILTER_ReplacePlaceholders = as_req
    Exit Function
errhandler:
    Call ErrorHandler(Extender.Name & ".STAT_FILTER_ReplacePlaceholders")
End Function

Private Sub cal_INT_INV_From_changeposition(y As Integer)
    cal_INT_INV_From.Zorder
End Sub

Private Sub cal_INT_INV_From_datechangee()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Clear_INT_Invoice
    
    Exit Sub
errhandler:
     Call ErrorMessage("cal_INT_INV_From_datechangee()")
End Sub

Private Sub cal_INT_INV_To_changeposition(y As Integer)
    cal_INT_INV_To.Zorder
End Sub

Private Sub cal_INT_INV_To_datechangee()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Clear_INT_Invoice
    
    Exit Sub
errhandler:
     Call ErrorMessage("cal_INT_INV_To_datechangee()")
End Sub

Private Sub cal_INV_DC_From_datechangee()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Clear_DC_Invoice
    
    Exit Sub
errhandler:
     Call ErrorMessage("cal_INV_DC_From_datechangee()")
End Sub

Private Sub cal_INV_DC_To_datechangee()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Clear_DC_Invoice
    
    Exit Sub
errhandler:
     Call ErrorMessage("cal_INV_DC_To_datechangee()")
End Sub

Private Sub cal_SUP_INV_From_changeposition(y As Integer)
    cal_SUP_INV_From.Zorder
End Sub

Private Sub cal_SUP_INV_From_datechangee()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Clear_SUP_Invoice
    
    Exit Sub
errhandler:
     Call ErrorMessage("cal_SUP_INV_From_datechangee()")
End Sub

Private Sub cal_SUP_INV_To_changeposition(y As Integer)
    cal_SUP_INV_To.Zorder
End Sub

Private Sub cal_SUP_INV_To_datechangee()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Clear_SUP_Invoice
    
    Exit Sub
errhandler:
     Call ErrorMessage("cal_SUP_INV_To_datechangee()")
End Sub

Private Sub cal_INV_DC_From_changeposition(y As Integer)
    cal_INV_DC_From.Zorder
End Sub

Private Sub cal_INV_DC_To_changeposition(y As Integer)
    cal_INV_DC_To.Zorder
End Sub

Private Sub cal_STAT_From_changeposition(y As Integer)
    cal_STAT_From.Zorder
'    cal_STAT_From.Top = cal_STAT_From.Top + y
End Sub

Private Sub cal_STAT_From_datechangee()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Clear_STAT_Report
    
    Exit Sub
errhandler:
     Call ErrorMessage("cal_STAT_From_datechangee()")
End Sub

Private Sub cal_STAT_To_changeposition(y As Integer)
    cal_STAT_To.Zorder
'    cal_STAT_To.Top = cal_STAT_To.Top + y
End Sub


Private Sub cal_STAT_To_datechangee()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Clear_STAT_Report
    
    Exit Sub
errhandler:
     Call ErrorMessage("cal_STAT_To_datechangee()")
End Sub

Private Sub cbo_CARRIER_Code_ComboItemSelected()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    cbo_CT_Code.Clear
    Set cbo_CT_Code.SelectedItem = Nothing
    cbo_CT_Code.Request = FILTER_ReplacePlaceholders(C_REQ_CT_Code)
    
    Call Process_DC_Invoice
    Exit Sub
errhandler:
     Call ErrorMessage("cbo_CARRIER_Code_ComboItemSelected()")
End Sub

Private Sub cbo_CT_Code_ComboItemSelected()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Process_DC_Invoice
    
    Exit Sub
errhandler:
     Call ErrorMessage("cbo_CT_Code_ComboItemSelected()")
End Sub

Private Sub cbo_SUP_CARRIER_Code_ComboItemSelected()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Process_SUP_Invoice
    
    Exit Sub
errhandler:
     Call ErrorMessage("cbo_SUP_Carrier_code_ComboItemSelected()")
End Sub

Private Sub cbo_SUP_DC_Code_ComboItemSelected()
On Error GoTo errhandler
    
    If mb_eventRunning Then Exit Sub
    
    mb_eventRunning = True
    
    Dim ls_oldCarrier_code As String
    ls_oldCarrier_code = GetCboKey(cbo_SUP_CARRIER_Code)
    
    Call cbo_SUP_CARRIER_Code.Clear
    Set cbo_SUP_CARRIER_Code.SelectedItem = Nothing
    
    Dim ls_DC_Code As String
    ls_DC_Code = GetCboKey(cbo_SUP_DC_Code)
    
    If ls_DC_Code = "" Then
        cbo_SUP_CARRIER_Code.Request = "EXEC DC_Carrier_cbo "
    Else
        cbo_SUP_CARRIER_Code.Request = Replace(C_REQ_CARRIER, "$DC_CODE$", SqlStr(ls_DC_Code, 4, True))
    End If
   
    If ls_oldCarrier_code <> "" Then
        Call SetCboKey(cbo_SUP_CARRIER_Code, ls_oldCarrier_code)
    End If


    Call Process_SUP_Invoice
    
    mb_eventRunning = False

    Exit Sub
errhandler:
    mb_eventRunning = False
     Call ErrorMessage("cbo_SUP_DC_Code_ComboItemSelected()")
End Sub

Private Sub cbo_SUP_Supplier_code_ComboItemSelected()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Process_SUP_Invoice
    
    Exit Sub
errhandler:
     Call ErrorMessage("cbo_SUP_Supplier_code_ComboItemSelected()")
End Sub

Private Function GetCkvSelection(ByRef lo_Control As ArmCheckView) As String
On Error GoTo errhandler

    Dim ll_Idx As Long
    
    Dim ls_selCodes As String
    ls_selCodes = ""
    
    If lo_Control.CheckedCount("EDIT") > 0 Then
        For ll_Idx = 1 To lo_Control.RoleList("EDIT").Count
            If lo_Control.RoleList("EDIT").Items(ll_Idx).CurrentChecked Then
                ls_selCodes = ls_selCodes & SEPu & lo_Control.RoleList("EDIT").Items(ll_Idx).GetData(0)
            End If
        Next
        ls_selCodes = ls_selCodes & SEPu
    End If
    
    GetCkvSelection = ls_selCodes
    Exit Function
errhandler:
     Call ErrorHandler("GetCkvSelection()")
End Function

Private Sub SetCkvSelection(ByRef ao_Control As ArmCheckView, ByVal as_Keys As String)
On Error GoTo errhandler

    Dim ll_Idx As Long
    
    For ll_Idx = 1 To ao_Control.RoleList("EDIT").Count
        If InStr(1, as_Keys, SEPu & ao_Control.RoleList("EDIT").Items(ll_Idx).GetData(0) & SEPu, vbTextCompare) > 0 Then
            Call ao_Control.RoleList("EDIT").ChangeItemValue(ao_Control.RoleList("EDIT").Items(ll_Idx), True, False)
        End If
    Next
    
    Exit Sub
errhandler:
     Call ErrorHandler("SetCkvSelection()")
End Sub

Private Function GetCkvText(ByRef lo_Control As ArmCheckView, Optional as_defaultAll As String = "") As String
On Error GoTo errhandler

    Dim ll_Idx As Long
    
    Dim ls_selDesc As String
    ls_selDesc = as_defaultAll
    
    If lo_Control.CheckedCount("EDIT") > 0 Then
        For ll_Idx = 1 To lo_Control.RoleList("EDIT").Count
            If lo_Control.RoleList("EDIT").Items(ll_Idx).CurrentChecked Then
                ls_selDesc = IIf(ls_selDesc = as_defaultAll, "", ls_selDesc & ",") & lo_Control.RoleList("EDIT").Items(ll_Idx).GetData(1)
            End If
        Next
    End If
    
    GetCkvText = ls_selDesc
    Exit Function
errhandler:
     Call ErrorHandler("GetCkvText()")
End Function

Private Sub cbo_STAT_DC_Code_ComboItemSelected()

On Error GoTo errhandler
    
    If mb_eventRunning Then Exit Sub
    
    LockScreen (True)
    
    mb_eventRunning = True
    
    Dim ll_Idx As Long
    
    Dim ls_oldCT_Code As String
    ls_oldCT_Code = GetCkvSelection(ckv_STAT_CT_Code)
    
    Dim ls_oldCarrier_code As String
    ls_oldCarrier_code = GetCkvSelection(ckv_STAT_Carrier)
    
    Dim ls_oldTenderCarrier_code As String
    ls_oldTenderCarrier_code = GetCkvSelection(ckv_STAT_Carrier_Tender)
    
    Dim ls_DC_Code As String
    ls_DC_Code = GetCboKey(cbo_STAT_DC_Code)
    
    If ls_DC_Code = "" Then
        ckv_STAT_Carrier.Calling_Key_Values = "NULL"
        ckv_STAT_Carrier_Tender.Calling_Key_Values = "NULL"
    Else
        ckv_STAT_Carrier.Calling_Key_Values = ls_DC_Code
        ckv_STAT_Carrier_Tender.Calling_Key_Values = ls_DC_Code
    End If
    
    ' refresh carriers list
    Call ckv_STAT_Carrier.LoadEditLists
    Call ckv_STAT_Carrier.RoleList("MAIN").UpdateViewList(ckv_STAT_Carrier.RoleList("EDIT"))
    If ls_oldCarrier_code <> "" Then
        Call SetCkvSelection(ckv_STAT_Carrier, ls_oldCarrier_code)
    End If
    
    ' refresh also tenders carriers list
    Call ckv_STAT_Carrier_Tender.LoadEditLists
    Call ckv_STAT_Carrier_Tender.RoleList("MAIN").UpdateViewList(ckv_STAT_Carrier_Tender.RoleList("EDIT"))
    If ls_oldTenderCarrier_code <> "" Then
        Call SetCkvSelection(ckv_STAT_Carrier_Tender, ls_oldTenderCarrier_code)
    End If
    
    ' refresh countries
    ckv_STAT_CT_Code.Calling_Key_Values = IIf(ls_DC_Code = "", "NULL", ls_DC_Code) & SEP & IIf(ls_oldCarrier_code = "", "NULL", ls_oldCarrier_code)
    Call ckv_STAT_CT_Code.LoadEditLists
    Call ckv_STAT_CT_Code.RoleList("MAIN").UpdateViewList(ckv_STAT_CT_Code.RoleList("EDIT"))
     If ls_oldCT_Code <> "" Then
        Call SetCkvSelection(ckv_STAT_CT_Code, ls_oldCT_Code)
    End If
    
    ' clear the grid
    Call Clear_STAT_Report
    
    LockScreen (False)
    
    mb_eventRunning = False

    Exit Sub
errhandler:
    LockScreen (False)
    mb_eventRunning = False
     Call ErrorMessage("cbo_STAT_DC_Code_ComboItemSelected()")
End Sub

Private Sub ckv_STAT_Carrier_GotFocus()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    mb_STAT_CARRIERS_upd = False
    
    Exit Sub
errhandler:
     Call ErrorMessage("ckv_STAT_Carrier_GotFocus()")
End Sub

Private Sub ckv_STAT_Carrier_ItemCheck(ByVal Item As MSComctlLib.ListItem)
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    mb_STAT_CARRIERS_upd = True

    Exit Sub
errhandler:
     Call ErrorMessage("ckv_STAT_Carrier_ItemCheck()")
End Sub

Private Sub ckv_STAT_Carrier_LostFocus()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    If Not mb_STAT_CARRIERS_upd Then Exit Sub

    Dim ls_oldCT_Code As String
    ls_oldCT_Code = GetCkvSelection(ckv_STAT_CT_Code)
    
    Dim ls_DC_Code As String
    ls_DC_Code = GetCboKey(cbo_STAT_DC_Code)
    
    Dim ls_CARRIER_Code As String
    ls_CARRIER_Code = GetCkvSelection(ckv_STAT_Carrier)
    
    ckv_STAT_CT_Code.Calling_Key_Values = IIf(ls_DC_Code = "", "NULL", ls_DC_Code) & SEP & IIf(ls_CARRIER_Code = "", "NULL", ls_CARRIER_Code)
    Call ckv_STAT_CT_Code.LoadEditLists
    Call ckv_STAT_CT_Code.RoleList("MAIN").UpdateViewList(ckv_STAT_CT_Code.RoleList("EDIT"))
     
     If ls_oldCT_Code <> "" Then
        Call SetCkvSelection(ckv_STAT_CT_Code, ls_oldCT_Code)
    End If
    
    Call Clear_STAT_Report
    
    Exit Sub
errhandler:
     Call ErrorMessage("ckv_STAT_Carrier_LostFocus()")
End Sub


Private Sub ckv_STAT_CT_Code_GotFocus()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    mb_STAT_COUNTRIES_upd = False
    
    Exit Sub
errhandler:
     Call ErrorMessage("ckv_STAT_CT_Code_GotFocus()")
End Sub

Private Sub ckv_STAT_CT_Code_ItemCheck(ByVal Item As MSComctlLib.ListItem)
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    mb_STAT_COUNTRIES_upd = True

    Exit Sub
errhandler:
     Call ErrorMessage("ckv_STAT_CT_Code_ItemCheck()")
End Sub

Private Sub ckv_STAT_CT_Code_LostFocus()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    If Not mb_STAT_COUNTRIES_upd Then Exit Sub
    
    Call Clear_STAT_Report
    
    Exit Sub
errhandler:
     Call ErrorMessage("ckv_STAT_CT_Code_LostFocus()")

End Sub


Private Sub chk_wool_Click()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Process_DC_Invoice
    
    Exit Sub
errhandler:
     Call ErrorMessage("chk_wool_Click()")
End Sub

Private Sub cbo_DC_Code_ComboItemSelected()
On Error GoTo errhandler
    
    If mb_eventRunning Then Exit Sub
    
    mb_eventRunning = True
    
    Dim ls_oldCarrier_code As String
    ls_oldCarrier_code = GetCboKey(cbo_CARRIER_Code)
    
    Dim ls_oldCT_Code As String
    ls_oldCT_Code = GetCboKey(cbo_CT_Code)
    
    Call cbo_CARRIER_Code.Clear
    Set cbo_CARRIER_Code.SelectedItem = Nothing
    
    Dim ls_DC_Code As String
    ls_DC_Code = GetCboKey(cbo_DC_Code)
    
    If ls_DC_Code = "" Then
        cbo_CARRIER_Code.Request = "EXEC DC_Carrier_cbo "
        cbo_CT_Code.Request = ""
    Else
        cbo_CARRIER_Code.Request = Replace(C_REQ_CARRIER, "$DC_CODE$", SqlStr(ls_DC_Code, 4, True))
        cbo_CT_Code.Request = FILTER_ReplacePlaceholders(C_REQ_CT_Code)
    End If
    
    If ls_oldCarrier_code <> "" Then
        Call SetCboKey(cbo_CARRIER_Code, ls_oldCarrier_code)
    End If
    
    If ls_oldCT_Code <> "" Then
        Call SetCboKey(cbo_CT_Code, ls_oldCT_Code)
    End If
    
    Call Process_DC_Invoice
    
    mb_eventRunning = False

    Exit Sub
errhandler:
    mb_eventRunning = False
     Call ErrorMessage("cbo_DC_Code_ComboItemSelected()")
End Sub

Private Sub cbo_INT_CARRIER_Code_ComboItemSelected()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Process_INT_Invoice
    
    Exit Sub
errhandler:
     Call ErrorMessage("cbo_INT_Carrier_code_ComboItemSelected()")
End Sub

Private Sub cbo_INT_DC_Code_ComboItemSelected()
On Error GoTo errhandler
    
    If mb_eventRunning Then Exit Sub
    
    mb_eventRunning = True
    
    Dim ls_oldCarrier_code As String
    ls_oldCarrier_code = GetCboKey(cbo_INT_CARRIER_Code)
    
    Call cbo_INT_CARRIER_Code.Clear
    Set cbo_INT_CARRIER_Code.SelectedItem = Nothing
    
    Dim ls_DC_Code As String
    ls_DC_Code = GetCboKey(cbo_INT_DC_Code)
    
    If ls_DC_Code = "" Then
        cbo_INT_CARRIER_Code.Request = "EXEC DC_Carrier_cbo "
    Else
        cbo_INT_CARRIER_Code.Request = Replace(C_REQ_CARRIER, "$DC_CODE$", SqlStr(ls_DC_Code, 4, True))
    End If
   
    If ls_oldCarrier_code <> "" Then
        Call SetCboKey(cbo_INT_CARRIER_Code, ls_oldCarrier_code)
    End If


    Call Process_INT_Invoice
    
    mb_eventRunning = False

    Exit Sub
errhandler:
    mb_eventRunning = False
     Call ErrorMessage("cbo_INT_DC_Code_ComboItemSelected()")
End Sub

Private Sub cbo_INT_ShipFromDC_code_ComboItemSelected()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call Process_INT_Invoice
    
    Exit Sub
errhandler:
     Call ErrorMessage("cbo_INT_ShipFromDC_code_ComboItemSelected()")
End Sub


Private Sub tbs_Main_Click()
On Error GoTo errhandler

    If tbs_Main.SelectedItem Is Nothing Then Exit Sub
    
    LockScreen (True)
    
    Dim lo_ctrl As Control
    
    For Each lo_ctrl In frm_tab
        lo_ctrl.Visible = False
    Next
    
    Select Case tbs_Main.SelectedItem.Key
        Case "CUS"
        
            If grd_DC_Invoice.Rows = 2 And grd_DC_Invoice.Cols = 6 Then
                Call Process_DC_Invoice
            End If
            
        Case "INT"
            If grd_INT_Invoice.Rows = 2 And grd_INT_Invoice.Cols = 6 Then
                Call Process_INT_Invoice
            End If
    
        Case "SUP"
            If grd_SUP_Invoice.Rows = 2 And grd_SUP_Invoice.Cols = 6 Then
                Call Process_SUP_Invoice
            End If
            
        Case "STAT"
            If grd_STAT_Report.Rows = 2 And grd_STAT_Report.Cols = 6 Then
                Call Process_STAT_Report
            End If
    End Select
    
    frm_tab(tbs_Main.SelectedItem.Index - 1).Visible = True

    LockScreen (False)
    
    Exit Sub

errhandler:
    LockScreen (False)
    Call ErrorMessage(Extender.Name & ".tbs_Main_Click")
End Sub

Private Sub Clear_DC_Invoice()
On Error GoTo errhandler
    If grd_DC_Invoice.Rows = 2 And grd_DC_Invoice.Cols = 6 Then
        Exit Sub
    End If
    
    grd_DC_Invoice.Rows = 1
    grd_DC_Invoice.Cols = 5
    
    Exit Sub
errhandler:
    Call ErrorHandler(Extender.Name & ".Clear_STAT_Report")
End Sub

Private Sub Process_DC_Invoice()
On Error GoTo errhandler
Const C_REQ As String = "EXEC DC_Report_Cust_Invoice_lst $DC_CODE$, $CARRIER_CODE$, $CT_CODE$, $FROM_DATE$, $TO_DATE$, $Language_code$"
Const C_REQ_wool As String = "EXEC DC_Report_Wool_Invoice_lst $DC_CODE$, $CARRIER_CODE$, $CT_CODE$, $FROM_DATE$, $TO_DATE$, $Language_code$"

Const C_DC_CODE_COL As Long = 0
Const C_CARRIER_CODE_COL As Long = 2
Const C_CT_CODE_COL As Long = 4
Const C_DATA_CODE_COL As Long = 5



    Call LockScreen(True)
    
    grd_DC_Invoice.Clear
    
    ' 1. define standard columns for DC and Carrier
    With grd_DC_Invoice
        .Cols = 5
        .Rows = 1
        .ColWidth(0) = 800
        .ColWidth(1) = 1500
        .ColWidth(2) = 2000
        .ColWidth(3) = 2100
        .ColWidth(4) = 1050
            
        .TextMatrix(0, 0) = GetLabel("s_DC_Code", "#DC_Code")
        .TextMatrix(0, 1) = GetLabel("s_DC_Name", "#DC_Name")
        .TextMatrix(0, 2) = GetLabel("s_CARRIER_Code", "#CARRIER_Code")
        .TextMatrix(0, 3) = GetLabel("s_CARRIER_Name", "#CARRIER_Name")
        .TextMatrix(0, 4) = GetLabel("s_CT_Code", "#CT_Code")
            
        .MergeCells = flexMergeRestrictColumns
        .MergeCol(1) = True
        .MergeCol(2) = False
        .MergeCol(3) = True
        .MergeCol(4) = True
        
        .RowHeight(0) = 750
        
        .FixedAlignment(0) = flexAlignCenterCenter
        .FixedAlignment(1) = flexAlignCenterCenter
        .FixedAlignment(2) = flexAlignCenterCenter
        .FixedAlignment(3) = flexAlignCenterCenter
        .FixedAlignment(4) = flexAlignCenterCenter
        
        .ColAlignment(2) = flexAlignCenterCenter
        
        .WordWrap = True
        .ForeColor = vbBlue
            
    End With
    
    Dim ls_req As String
    Dim ll_Cursor As Long
    
    If chk_wool.Value = vbChecked Then
        ls_req = FILTER_ReplacePlaceholders(C_REQ_wool)
    Else
        ls_req = FILTER_ReplacePlaceholders(C_REQ)
    End If
    
    ll_Cursor = OpenSQLSafe(mo_Db, ls_req)
    
    If mo_Db.EOF(ll_Cursor) Then
        Call LockScreen(False)
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
        MsgBox (MsgText(5280, ms_Language_Code, "#No data to display!"))
        Exit Sub
    End If
    
    Dim ls_oldRow As String
    Dim ls_colDef  As String
    
    Dim ls_DC_Code As String
    Dim ls_CARRIER_Code As String
    Dim ls_CT_Code As String
    Dim ls_CURR_Code_List As String
    
    Dim ll_itemRow As Long
    Dim ll_itemCol As Long

    ls_oldRow = ""
    ll_itemRow = 0
    ls_CURR_Code_List = ""
    
    mo_Db.SortFields(ll_Cursor) = Array("DC_Year", "DC_Month", "CURR_Code")
    ' generate the columns for months
    While Not mo_Db.EOF(ll_Cursor)
        
        ls_colDef = mo_Db.GetFields(ll_Cursor, "DC_Year") & SEP & mo_Db.GetFields(ll_Cursor, "DC_Month") & SEP & mo_Db.GetFields(ll_Cursor, "CURR_Code")
        
        ll_itemCol = FindGridCol(grd_DC_Invoice, 0, C_DATA_CODE_COL, ls_colDef)
        
        ' write the cost
        If ll_itemCol = -1 Then
            
            ll_itemCol = grd_DC_Invoice.Cols
            
            grd_DC_Invoice.Cols = grd_DC_Invoice.Cols + 1
            
            grd_DC_Invoice.TextMatrix(0, ll_itemCol) = ls_colDef
            
        End If
        
        Call mo_Db.Next(ll_Cursor)
    Wend
    
    mo_Db.SortFields(ll_Cursor) = Array("DC_Desc", "CARRIER_Name", "Ship_To_CT_Code")
    Call mo_Db.First(ll_Cursor)
    
    While Not mo_Db.EOF(ll_Cursor)
        ls_DC_Code = mo_Db.GetFields(ll_Cursor, "DC_Code")
        ls_CARRIER_Code = mo_Db.GetFields(ll_Cursor, "CARRIER_Code")
        ls_CT_Code = mo_Db.GetFields(ll_Cursor, "Ship_To_CT_Code")
        
        If ls_oldRow <> ls_DC_Code & SEP & ls_CARRIER_Code & SEP & ls_CT_Code Then
            ls_oldRow = ls_DC_Code & SEP & ls_CARRIER_Code & SEP & ls_CT_Code
            
            ll_itemRow = ll_itemRow + 1
            grd_DC_Invoice.Rows = ll_itemRow + 1
            
            ' insert new line
            grd_DC_Invoice.TextMatrix(ll_itemRow, C_DC_CODE_COL) = ls_DC_Code
            grd_DC_Invoice.TextMatrix(ll_itemRow, C_DC_CODE_COL + 1) = mo_Db.GetFields(ll_Cursor, "DC_Desc")
            grd_DC_Invoice.TextMatrix(ll_itemRow, C_CARRIER_CODE_COL) = ls_CARRIER_Code
            grd_DC_Invoice.TextMatrix(ll_itemRow, C_CARRIER_CODE_COL + 1) = mo_Db.GetFields(ll_Cursor, "CARRIER_Name")
            grd_DC_Invoice.TextMatrix(ll_itemRow, C_CT_CODE_COL) = ls_CT_Code
            
        End If
        
        If InStr(1, ls_CURR_Code_List, mo_Db.GetFields(ll_Cursor, "CURR_Code"), vbTextCompare) = 0 Then
            ls_CURR_Code_List = ls_CURR_Code_List & SEP & mo_Db.GetFields(ll_Cursor, "CURR_Code")
        End If
        
        ls_colDef = mo_Db.GetFields(ll_Cursor, "DC_Year") & SEP & mo_Db.GetFields(ll_Cursor, "DC_Month") & SEP & mo_Db.GetFields(ll_Cursor, "CURR_Code")
        
        ll_itemCol = FindGridCol(grd_DC_Invoice, 0, C_DATA_CODE_COL, ls_colDef)
        Debug.Assert (ll_itemCol <> -1)
        
        grd_DC_Invoice.TextMatrix(ll_itemRow, ll_itemCol) = mo_Db.GetFields(ll_Cursor, "DC_Cost")
        
        Call mo_Db.Next(ll_Cursor)
    Wend
    
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    ' add a summary row
    Dim ld_total As Double
    
    grd_DC_Invoice.Rows = grd_DC_Invoice.Rows + 1
    For ll_itemCol = C_DATA_CODE_COL To grd_DC_Invoice.Cols - 1
        ld_total = 0
        For ll_itemRow = 1 To grd_DC_Invoice.Rows - 2
            If grd_DC_Invoice.TextMatrix(ll_itemRow, ll_itemCol) <> "" Then ld_total = ld_total + grd_DC_Invoice.TextMatrix(ll_itemRow, ll_itemCol)
        Next
        
        grd_DC_Invoice.TextMatrix(grd_DC_Invoice.Rows - 1, ll_itemCol) = ld_total
        Call SetGridCelBold(grd_DC_Invoice, grd_DC_Invoice.Rows - 1, ll_itemCol)
    Next
    
    ' calculate total cols
    Dim ll_maxCols As Long
    Dim ll_curr_ind  As Long
    ll_maxCols = grd_DC_Invoice.Cols - 1
    
    Dim lsa_CURR_Code() As String
    
    lsa_CURR_Code = Split(ls_CURR_Code_List, SEP)
    
    
    For ll_itemRow = 1 To grd_DC_Invoice.Rows - 1
        
        For ll_curr_ind = 1 To UBound(lsa_CURR_Code)
            ld_total = 0
            For ll_itemCol = C_DATA_CODE_COL To ll_maxCols
            
                If right(grd_DC_Invoice.TextMatrix(0, ll_itemCol), Len(lsa_CURR_Code(ll_curr_ind))) = lsa_CURR_Code(ll_curr_ind) Then
                
                    If grd_DC_Invoice.TextMatrix(ll_itemRow, ll_itemCol) <> "" Then
                        ld_total = ld_total + Val(grd_DC_Invoice.TextMatrix(ll_itemRow, ll_itemCol))
                    Else
                        grd_DC_Invoice.TextMatrix(ll_itemRow, ll_itemCol) = 0
                    End If
                    
                End If
            Next
            
            ' add a total
            ll_itemCol = FindGridCol(grd_DC_Invoice, 0, ll_maxCols + 1, lsa_CURR_Code(ll_curr_ind))
            
            ' write total cost
            If ll_itemCol = -1 Then
                
                ll_itemCol = grd_DC_Invoice.Cols
                
                grd_DC_Invoice.Cols = grd_DC_Invoice.Cols + 1
                
                grd_DC_Invoice.TextMatrix(0, ll_itemCol) = lsa_CURR_Code(ll_curr_ind)
                
            End If
            
            grd_DC_Invoice.TextMatrix(ll_itemRow, ll_itemCol) = ld_total
            Call SetGridCelBold(grd_DC_Invoice, ll_itemRow, ll_itemCol)
        Next
    Next
    
    ' update column headers for month names
    Dim lsa_months() As String
    For ll_itemCol = C_DATA_CODE_COL To ll_maxCols
    
        lsa_months = Split(grd_DC_Invoice.TextMatrix(0, ll_itemCol), SEP)
        Debug.Assert (UBound(lsa_months) = 2)
        
        grd_DC_Invoice.TextMatrix(0, ll_itemCol) = GetLabel("s_month_" & lsa_months(1), "#Month " & lsa_months(1)) & vbCrLf & lsa_months(0) & vbCrLf & "(" & lsa_months(2) & ")"
        
    Next
    
    ' update column headers for total
    For ll_itemCol = ll_maxCols + 1 To grd_DC_Invoice.Cols - 1
        grd_DC_Invoice.TextMatrix(0, ll_itemCol) = GetLabel("s_total", "#Total") & vbCrLf & "(" & grd_DC_Invoice.TextMatrix(0, ll_itemCol) & ")"
        Call SetGridCelBold(grd_DC_Invoice, 0, ll_itemCol)
    Next
    
    grd_DC_Invoice.MergeRow(grd_DC_Invoice.Rows - 1) = True
    grd_DC_Invoice.TextMatrix(grd_DC_Invoice.Rows - 1, 0) = GetLabel("s_total", "#Total")
    Call SetGridCelBold(grd_DC_Invoice, grd_DC_Invoice.Rows - 1, 0)
    
    ' formating
    grd_DC_Invoice.LeftCol = C_DATA_CODE_COL
    
    
    ' generate header for export to excell
    Dim lsa_colsArray() As Variant
    ReDim lsa_colsArray(grd_DC_Invoice.Cols - 1) As Variant
    
    For ll_itemCol = 0 To grd_DC_Invoice.Cols - 1
        If ll_itemCol < C_DATA_CODE_COL Then
            lsa_colsArray(ll_itemCol) = grd_DC_Invoice.TextMatrix(0, ll_itemCol)
        Else
            lsa_colsArray(ll_itemCol) = Array("", grd_DC_Invoice.TextMatrix(0, ll_itemCol), grd_DC_Invoice.ColWidth(ll_itemCol), "", flexAlignRightCenter, "##,##0")
        End If
    Next
    
    Call GRD_SetHeader(grd_DC_Invoice, mo_DC_ReportCustomerInfo, Array(lsa_colsArray))
    mo_DC_ReportCustomerInfo.gCsts_prefix = tbs_Main.SelectedItem.Key
    mo_DC_ReportCustomerInfo.gTitle = tbs_Main.SelectedItem.Caption
    mo_DC_ReportCustomerInfo.gDC_Desc = GetCboText(cbo_DC_Code, GetLabel("lbl_all", "#All"))
    mo_DC_ReportCustomerInfo.gCARRIER_Name = GetCboText(cbo_CARRIER_Code, GetLabel("lbl_all", "#All"))
    mo_DC_ReportCustomerInfo.gFilterA = GetCboText(cbo_CT_Code, GetLabel("lbl_all", "#All"))
    mo_DC_ReportCustomerInfo.gFilterB = IIf(chk_wool.Value = vbChecked, GetLabel("lbl_yes", "#Yes"), GetLabel("lbl_no", "#No"))
    

    Call LockScreen(False)

    Exit Sub

errhandler:
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    
    Call LockScreen(False)
    Call ErrorHandler(Extender.Name & ".Process_DC_Invoice")
End Sub

Private Sub Clear_INT_Invoice()
On Error GoTo errhandler
    If grd_INT_Invoice.Rows = 2 And grd_INT_Invoice.Cols = 6 Then
        Exit Sub
    End If
    
    grd_INT_Invoice.Rows = 1
    grd_INT_Invoice.Cols = 5
    
    Exit Sub
errhandler:
    Call ErrorHandler(Extender.Name & ".Clear_INT_Invoice")
End Sub

Private Sub Process_INT_Invoice()
On Error GoTo errhandler
Const C_REQ As String = "EXEC DC_Report_Interco_Invoice_lst $DC_CODE$, $CARRIER_CODE$, $FROM_DC_CODE$, $FROM_DATE$, $TO_DATE$, $Language_code$"
Const C_DC_CODE_COL As Long = 0
Const C_CARRIER_CODE_COL As Long = 2
Const C_FROM_DC_CODE_COL As Long = 4
Const C_DATA_CODE_COL As Long = 5



    Call LockScreen(True)
    
    grd_INT_Invoice.Clear
    
    ' 1. define standard columns for DC and Carrier
    With grd_INT_Invoice
        .Cols = 5
        .Rows = 1
        .ColWidth(0) = 800
        .ColWidth(1) = 1500
        .ColWidth(2) = 2000
        .ColWidth(3) = 2100
        .ColWidth(4) = 1050
            
        .TextMatrix(0, 0) = GetLabel("s_DC_Code", "#DC_Code")
        .TextMatrix(0, 1) = GetLabel("s_DC_Name", "#DC_Name")
        .TextMatrix(0, 2) = GetLabel("s_CARRIER_Code", "#CARRIER_Code")
        .TextMatrix(0, 3) = GetLabel("s_CARRIER_Name", "#CARRIER_Name")
        .TextMatrix(0, 4) = GetLabel("s_FROM_DC_Code", "#Ship from DC")
            
        .MergeCells = flexMergeRestrictColumns
        .MergeCol(1) = True
        .MergeCol(2) = False
        .MergeCol(3) = True
        .MergeCol(4) = True

                                    
        .RowHeight(0) = 750
        
        .FixedAlignment(0) = flexAlignCenterCenter
        .FixedAlignment(1) = flexAlignCenterCenter
        .FixedAlignment(2) = flexAlignCenterCenter
        .FixedAlignment(3) = flexAlignCenterCenter
        .FixedAlignment(4) = flexAlignCenterCenter
        
        .ColAlignment(2) = flexAlignCenterCenter
        
        .WordWrap = True
        .ForeColor = vbBlue
            
    End With
    
    Dim ls_req As String
    Dim ll_Cursor As Long
    
    ls_req = INT_FILTER_ReplacePlaceholders(C_REQ)
    
    ll_Cursor = OpenSQLSafe(mo_Db, ls_req)
    
    If mo_Db.EOF(ll_Cursor) Then
        Call LockScreen(False)
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
        MsgBox (MsgText(5280, ms_Language_Code, "#No data to display!"))
        Exit Sub
    End If
    
    Dim ls_oldRow As String
    Dim ls_colDef  As String
    
    Dim ls_DC_Code As String
    Dim ls_CARRIER_Code As String
    Dim ls_FROM_DC_Code As String
    Dim ls_CURR_Code_List As String
    
    Dim ll_itemRow As Long
    Dim ll_itemCol As Long

    ls_oldRow = ""
    ll_itemRow = 0
    ls_CURR_Code_List = ""
    
    Dim ld_minMonth As Date
    Dim lm_maxMonth As Date
    
    
    mo_Db.SortFields(ll_Cursor) = Array("DC_Year", "DC_Month", "CURR_Code")
    ' generate the columns for months
    While Not mo_Db.EOF(ll_Cursor)
        
        ls_colDef = mo_Db.GetFields(ll_Cursor, "DC_Year") & SEP & mo_Db.GetFields(ll_Cursor, "DC_Month") & SEP & mo_Db.GetFields(ll_Cursor, "CURR_Code")
        
        ll_itemCol = FindGridCol(grd_INT_Invoice, 0, C_DATA_CODE_COL, ls_colDef)
        
        ' write the cost
        If ll_itemCol = -1 Then
            
            ll_itemCol = grd_INT_Invoice.Cols
            
            grd_INT_Invoice.Cols = grd_INT_Invoice.Cols + 1
            
            grd_INT_Invoice.TextMatrix(0, ll_itemCol) = ls_colDef
            
        End If
        
        Call mo_Db.Next(ll_Cursor)
    Wend
    
    mo_Db.SortFields(ll_Cursor) = Array("DC_Desc", "CARRIER_Name", "Supplier_Name")
    Call mo_Db.First(ll_Cursor)
    
    While Not mo_Db.EOF(ll_Cursor)
        ls_DC_Code = mo_Db.GetFields(ll_Cursor, "Receiving_DC")
        ls_CARRIER_Code = mo_Db.GetFields(ll_Cursor, "CARRIER_Code")
        ls_FROM_DC_Code = mo_Db.GetFields(ll_Cursor, "Supplier_Name")
        
        If ls_oldRow <> ls_DC_Code & SEP & ls_CARRIER_Code & SEP & ls_FROM_DC_Code Then
            ls_oldRow = ls_DC_Code & SEP & ls_CARRIER_Code & SEP & ls_FROM_DC_Code
            
            ll_itemRow = ll_itemRow + 1
            grd_INT_Invoice.Rows = ll_itemRow + 1
            
            ' insert new line
            grd_INT_Invoice.TextMatrix(ll_itemRow, C_DC_CODE_COL) = ls_DC_Code
            grd_INT_Invoice.TextMatrix(ll_itemRow, C_DC_CODE_COL + 1) = mo_Db.GetFields(ll_Cursor, "DC_Desc")
            grd_INT_Invoice.TextMatrix(ll_itemRow, C_CARRIER_CODE_COL) = ls_CARRIER_Code
            grd_INT_Invoice.TextMatrix(ll_itemRow, C_CARRIER_CODE_COL + 1) = mo_Db.GetFields(ll_Cursor, "CARRIER_Name")
            grd_INT_Invoice.TextMatrix(ll_itemRow, C_FROM_DC_CODE_COL) = ls_FROM_DC_Code
            
        End If
        
        If InStr(1, ls_CURR_Code_List, mo_Db.GetFields(ll_Cursor, "CURR_Code"), vbTextCompare) = 0 Then
            ls_CURR_Code_List = ls_CURR_Code_List & SEP & mo_Db.GetFields(ll_Cursor, "CURR_Code")
        End If
        
        ls_colDef = mo_Db.GetFields(ll_Cursor, "DC_Year") & SEP & mo_Db.GetFields(ll_Cursor, "DC_Month") & SEP & mo_Db.GetFields(ll_Cursor, "CURR_Code")
        
        ll_itemCol = FindGridCol(grd_INT_Invoice, 0, C_DATA_CODE_COL, ls_colDef)
        Debug.Assert (ll_itemCol <> -1)
        
        grd_INT_Invoice.TextMatrix(ll_itemRow, ll_itemCol) = mo_Db.GetFields(ll_Cursor, "DC_Cost")
        
        Call mo_Db.Next(ll_Cursor)
    Wend
    
    
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    ' add a summary row
    Dim ld_total As Double
    
    grd_INT_Invoice.Rows = grd_INT_Invoice.Rows + 1
    For ll_itemCol = C_DATA_CODE_COL To grd_INT_Invoice.Cols - 1
        ld_total = 0
        For ll_itemRow = 1 To grd_INT_Invoice.Rows - 2
            If grd_INT_Invoice.TextMatrix(ll_itemRow, ll_itemCol) <> "" Then ld_total = ld_total + grd_INT_Invoice.TextMatrix(ll_itemRow, ll_itemCol)
        Next
        
        grd_INT_Invoice.TextMatrix(grd_INT_Invoice.Rows - 1, ll_itemCol) = ld_total
        Call SetGridCelBold(grd_INT_Invoice, grd_INT_Invoice.Rows - 1, ll_itemCol)
    Next
    
    ' calculate total
    Dim ll_maxCols As Long
    Dim ll_curr_ind  As Long
    ll_maxCols = grd_INT_Invoice.Cols - 1
    
    Dim lsa_CURR_Code() As String
    
    lsa_CURR_Code = Split(ls_CURR_Code_List, SEP)
    
    
    For ll_itemRow = 1 To grd_INT_Invoice.Rows - 1
        
        For ll_curr_ind = 1 To UBound(lsa_CURR_Code)
            ld_total = 0
            For ll_itemCol = C_DATA_CODE_COL To ll_maxCols
            
                If right(grd_INT_Invoice.TextMatrix(0, ll_itemCol), Len(lsa_CURR_Code(ll_curr_ind))) = lsa_CURR_Code(ll_curr_ind) Then
                
                    If grd_INT_Invoice.TextMatrix(ll_itemRow, ll_itemCol) <> "" Then
                        ld_total = ld_total + Val(grd_INT_Invoice.TextMatrix(ll_itemRow, ll_itemCol))
                    Else
                        grd_INT_Invoice.TextMatrix(ll_itemRow, ll_itemCol) = 0
                    End If
                    
                End If
            Next
            
            ' add a total
            ll_itemCol = FindGridCol(grd_INT_Invoice, 0, ll_maxCols + 1, lsa_CURR_Code(ll_curr_ind))
            
            ' write total cost
            If ll_itemCol = -1 Then
                
                ll_itemCol = grd_INT_Invoice.Cols
                
                grd_INT_Invoice.Cols = grd_INT_Invoice.Cols + 1
                
                grd_INT_Invoice.TextMatrix(0, ll_itemCol) = lsa_CURR_Code(ll_curr_ind)
                
            End If
            
            grd_INT_Invoice.TextMatrix(ll_itemRow, ll_itemCol) = ld_total
            Call SetGridCelBold(grd_INT_Invoice, ll_itemRow, ll_itemCol)
        Next
    Next
    
    ' update column headers for month names
    Dim lsa_months() As String
    For ll_itemCol = C_DATA_CODE_COL To ll_maxCols
    
        lsa_months = Split(grd_INT_Invoice.TextMatrix(0, ll_itemCol), SEP)
        Debug.Assert (UBound(lsa_months) = 2)
        
        grd_INT_Invoice.TextMatrix(0, ll_itemCol) = GetLabel("s_month_" & lsa_months(1), "#Month " & lsa_months(1)) & vbCrLf & lsa_months(0) & vbCrLf & "(" & lsa_months(2) & ")"
        
    Next
    
    ' update column headers for total
    For ll_itemCol = ll_maxCols + 1 To grd_INT_Invoice.Cols - 1
        grd_INT_Invoice.TextMatrix(0, ll_itemCol) = GetLabel("s_total", "#Total") & vbCrLf & "(" & grd_INT_Invoice.TextMatrix(0, ll_itemCol) & ")"
        Call SetGridCelBold(grd_INT_Invoice, 0, ll_itemCol)
    Next
    
    grd_INT_Invoice.MergeRow(grd_INT_Invoice.Rows - 1) = True
    grd_INT_Invoice.TextMatrix(grd_INT_Invoice.Rows - 1, 0) = GetLabel("s_total", "#Total")
    Call SetGridCelBold(grd_INT_Invoice, grd_INT_Invoice.Rows - 1, 0)
    
    ' formating
    grd_INT_Invoice.LeftCol = C_DATA_CODE_COL
    
    ' generate header for export to excell
    Dim lsa_colsArray() As Variant
    ReDim lsa_colsArray(grd_INT_Invoice.Cols - 1) As Variant
    
    For ll_itemCol = 0 To grd_INT_Invoice.Cols - 1
        If ll_itemCol < C_DATA_CODE_COL Then
            lsa_colsArray(ll_itemCol) = grd_INT_Invoice.TextMatrix(0, ll_itemCol)
        Else
            lsa_colsArray(ll_itemCol) = Array("", grd_INT_Invoice.TextMatrix(0, ll_itemCol), grd_INT_Invoice.ColWidth(ll_itemCol), "", flexAlignRightCenter, "##,##0")
        End If
    Next
    
    Call GRD_SetHeader(grd_INT_Invoice, mo_DC_ReportIntercomapnyInfo, Array(lsa_colsArray))
    mo_DC_ReportIntercomapnyInfo.gCsts_prefix = tbs_Main.SelectedItem.Key
    mo_DC_ReportIntercomapnyInfo.gTitle = tbs_Main.SelectedItem.Caption
    mo_DC_ReportIntercomapnyInfo.gDC_Desc = GetCboText(cbo_INT_DC_Code, GetLabel("lbl_all", "#All"))
    mo_DC_ReportIntercomapnyInfo.gCARRIER_Name = GetCboText(cbo_INT_CARRIER_Code, GetLabel("lbl_all", "#All"))
    mo_DC_ReportIntercomapnyInfo.gFilterA = GetCboText(cbo_INT_ShipFromDC_code, GetLabel("lbl_all", "#All"))
    mo_DC_ReportIntercomapnyInfo.gFilterB = ""

    Call LockScreen(False)

    Exit Sub

errhandler:
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    
    Call LockScreen(False)
    Call ErrorHandler(Extender.Name & ".Process_INT_Invoice")
End Sub


Private Sub Clear_SUP_Invoice()
On Error GoTo errhandler
    If grd_SUP_Invoice.Rows = 2 And grd_SUP_Invoice.Cols = 6 Then
        Exit Sub
    End If
    
    grd_SUP_Invoice.Rows = 1
    grd_SUP_Invoice.Cols = 5
    
    Exit Sub
errhandler:
    Call ErrorHandler(Extender.Name & ".Clear_SUP_Invoice")
End Sub

Private Sub Process_SUP_Invoice()
On Error GoTo errhandler
Const C_REQ As String = "EXEC DC_Report_Supplier_Invoice_lst $DC_CODE$, $CARRIER_CODE$, $SP_CODE$, $FROM_DATE$, $TO_DATE$, $Language_code$"
Const C_DC_CODE_COL As Long = 0
Const C_CARRIER_CODE_COL As Long = 2
Const C_SUPPLIER_CODE_COL As Long = 4
Const C_DATA_CODE_COL As Long = 5



    Call LockScreen(True)
    
    grd_SUP_Invoice.Clear
    
    ' 1. define standard columns for DC and Carrier
    With grd_SUP_Invoice
        .Cols = 5
        .Rows = 1
        .ColWidth(0) = 800
        .ColWidth(1) = 1500
        .ColWidth(2) = 2000
        .ColWidth(3) = 2100
        .ColWidth(4) = 1050
            
        .TextMatrix(0, 0) = GetLabel("s_DC_Code", "#DC_Code")
        .TextMatrix(0, 1) = GetLabel("s_DC_Name", "#DC_Name")
        .TextMatrix(0, 2) = GetLabel("s_CARRIER_Code", "#CARRIER_Code")
        .TextMatrix(0, 3) = GetLabel("s_CARRIER_Name", "#CARRIER_Name")
        .TextMatrix(0, 4) = GetLabel("s_SUPPLIER_Code", "#Supplier")
            
        .MergeCells = flexMergeRestrictColumns
        .MergeCol(1) = True
        .MergeCol(2) = False
        .MergeCol(3) = True
        .MergeCol(4) = True

                                    
        .RowHeight(0) = 750
        
        .FixedAlignment(0) = flexAlignCenterCenter
        .FixedAlignment(1) = flexAlignCenterCenter
        .FixedAlignment(2) = flexAlignCenterCenter
        .FixedAlignment(3) = flexAlignCenterCenter
        .FixedAlignment(4) = flexAlignCenterCenter
        
        .ColAlignment(2) = flexAlignCenterCenter
        
        .WordWrap = True
        .ForeColor = vbBlue
            
    End With
    
    Dim ls_req As String
    Dim ll_Cursor As Long
    
    ls_req = SUP_FILTER_ReplacePlaceholders(C_REQ)
    
    ll_Cursor = OpenSQLSafe(mo_Db, ls_req)
    
    If mo_Db.EOF(ll_Cursor) Then
        Call LockScreen(False)
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
        MsgBox (MsgText(5280, ms_Language_Code, "#No data to display!"))
        Exit Sub
    End If
    
    Dim ls_oldRow As String
    Dim ls_colDef  As String
    
    Dim ls_DC_Code As String
    Dim ls_CARRIER_Code As String
    Dim ls_SP_Code As String
    Dim ls_CURR_Code_List As String
    
    Dim ll_itemRow As Long
    Dim ll_itemCol As Long

    ls_oldRow = ""
    ll_itemRow = 0
    ls_CURR_Code_List = ""
    
    Dim ld_minMonth As Date
    Dim lm_maxMonth As Date
    
    
    mo_Db.SortFields(ll_Cursor) = Array("DC_Year", "DC_Month", "CURR_Code")
    ' generate the columns for months
    While Not mo_Db.EOF(ll_Cursor)
        
        ls_colDef = mo_Db.GetFields(ll_Cursor, "DC_Year") & SEP & mo_Db.GetFields(ll_Cursor, "DC_Month") & SEP & mo_Db.GetFields(ll_Cursor, "CURR_Code")
        
        ll_itemCol = FindGridCol(grd_SUP_Invoice, 0, C_DATA_CODE_COL, ls_colDef)
        
        ' write the cost
        If ll_itemCol = -1 Then
            
            ll_itemCol = grd_SUP_Invoice.Cols
            
            grd_SUP_Invoice.Cols = grd_SUP_Invoice.Cols + 1
            
            grd_SUP_Invoice.TextMatrix(0, ll_itemCol) = ls_colDef
            
        End If
        
        Call mo_Db.Next(ll_Cursor)
    Wend
    
    mo_Db.SortFields(ll_Cursor) = Array("DC_Desc", "CARRIER_Name", "Supplier_code")
    Call mo_Db.First(ll_Cursor)
    
    While Not mo_Db.EOF(ll_Cursor)
        ls_DC_Code = mo_Db.GetFields(ll_Cursor, "Receiving_DC")
        ls_CARRIER_Code = mo_Db.GetFields(ll_Cursor, "CARRIER_Code")
        ls_SP_Code = mo_Db.GetFields(ll_Cursor, "Supplier_code")
        
        If ls_oldRow <> ls_DC_Code & SEP & ls_CARRIER_Code & SEP & ls_SP_Code Then
            ls_oldRow = ls_DC_Code & SEP & ls_CARRIER_Code & SEP & ls_SP_Code
            
            ll_itemRow = ll_itemRow + 1
            grd_SUP_Invoice.Rows = ll_itemRow + 1
            
            ' insert new line
            grd_SUP_Invoice.TextMatrix(ll_itemRow, C_DC_CODE_COL) = ls_DC_Code
            grd_SUP_Invoice.TextMatrix(ll_itemRow, C_DC_CODE_COL + 1) = mo_Db.GetFields(ll_Cursor, "DC_Desc")
            grd_SUP_Invoice.TextMatrix(ll_itemRow, C_CARRIER_CODE_COL) = ls_CARRIER_Code
            grd_SUP_Invoice.TextMatrix(ll_itemRow, C_CARRIER_CODE_COL + 1) = mo_Db.GetFields(ll_Cursor, "CARRIER_Name")
            grd_SUP_Invoice.TextMatrix(ll_itemRow, C_SUPPLIER_CODE_COL) = ls_SP_Code
            
        End If
        
        If InStr(1, ls_CURR_Code_List, mo_Db.GetFields(ll_Cursor, "CURR_Code"), vbTextCompare) = 0 Then
            ls_CURR_Code_List = ls_CURR_Code_List & SEP & mo_Db.GetFields(ll_Cursor, "CURR_Code")
        End If
        
        ls_colDef = mo_Db.GetFields(ll_Cursor, "DC_Year") & SEP & mo_Db.GetFields(ll_Cursor, "DC_Month") & SEP & mo_Db.GetFields(ll_Cursor, "CURR_Code")
        
        ll_itemCol = FindGridCol(grd_SUP_Invoice, 0, C_DATA_CODE_COL, ls_colDef)
        Debug.Assert (ll_itemCol <> -1)
        
        grd_SUP_Invoice.TextMatrix(ll_itemRow, ll_itemCol) = mo_Db.GetFields(ll_Cursor, "DC_Cost")
        
        Call mo_Db.Next(ll_Cursor)
    Wend
    
    
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    ' add a summary row
    Dim ld_total As Double
    
    grd_SUP_Invoice.Rows = grd_SUP_Invoice.Rows + 1
    For ll_itemCol = C_DATA_CODE_COL To grd_SUP_Invoice.Cols - 1
        ld_total = 0
        For ll_itemRow = 1 To grd_SUP_Invoice.Rows - 2
            If grd_SUP_Invoice.TextMatrix(ll_itemRow, ll_itemCol) <> "" Then ld_total = ld_total + grd_SUP_Invoice.TextMatrix(ll_itemRow, ll_itemCol)
        Next
        
        grd_SUP_Invoice.TextMatrix(grd_SUP_Invoice.Rows - 1, ll_itemCol) = ld_total
        Call SetGridCelBold(grd_SUP_Invoice, grd_SUP_Invoice.Rows - 1, ll_itemCol)
    Next
    
    ' calculate total
    Dim ll_maxCols As Long
    Dim ll_curr_ind  As Long
    ll_maxCols = grd_SUP_Invoice.Cols - 1
    
    Dim lsa_CURR_Code() As String
    
    lsa_CURR_Code = Split(ls_CURR_Code_List, SEP)
    
    
    For ll_itemRow = 1 To grd_SUP_Invoice.Rows - 1
        
        For ll_curr_ind = 1 To UBound(lsa_CURR_Code)
            ld_total = 0
            For ll_itemCol = C_DATA_CODE_COL To ll_maxCols
            
                If right(grd_SUP_Invoice.TextMatrix(0, ll_itemCol), Len(lsa_CURR_Code(ll_curr_ind))) = lsa_CURR_Code(ll_curr_ind) Then
                
                    If grd_SUP_Invoice.TextMatrix(ll_itemRow, ll_itemCol) <> "" Then
                        ld_total = ld_total + Val(grd_SUP_Invoice.TextMatrix(ll_itemRow, ll_itemCol))
                    Else
                        grd_SUP_Invoice.TextMatrix(ll_itemRow, ll_itemCol) = 0
                    End If
                    
                End If
            Next
            
            ' add a total
            ll_itemCol = FindGridCol(grd_SUP_Invoice, 0, ll_maxCols + 1, lsa_CURR_Code(ll_curr_ind))
            
            ' write total cost
            If ll_itemCol = -1 Then
                
                ll_itemCol = grd_SUP_Invoice.Cols
                
                grd_SUP_Invoice.Cols = grd_SUP_Invoice.Cols + 1
                
                grd_SUP_Invoice.TextMatrix(0, ll_itemCol) = lsa_CURR_Code(ll_curr_ind)
                
            End If
            
            grd_SUP_Invoice.TextMatrix(ll_itemRow, ll_itemCol) = ld_total
            Call SetGridCelBold(grd_SUP_Invoice, ll_itemRow, ll_itemCol)
        Next
    Next
    
    ' update column headers for month names
    Dim lsa_months() As String
    For ll_itemCol = C_DATA_CODE_COL To ll_maxCols
    
        lsa_months = Split(grd_SUP_Invoice.TextMatrix(0, ll_itemCol), SEP)
        Debug.Assert (UBound(lsa_months) = 2)
        
        grd_SUP_Invoice.TextMatrix(0, ll_itemCol) = GetLabel("s_month_" & lsa_months(1), "#Month " & lsa_months(1)) & vbCrLf & lsa_months(0) & vbCrLf & "(" & lsa_months(2) & ")"
        
    Next
    
    ' update column headers for total
    For ll_itemCol = ll_maxCols + 1 To grd_SUP_Invoice.Cols - 1
        grd_SUP_Invoice.TextMatrix(0, ll_itemCol) = GetLabel("s_total", "#Total") & vbCrLf & "(" & grd_SUP_Invoice.TextMatrix(0, ll_itemCol) & ")"
        Call SetGridCelBold(grd_SUP_Invoice, 0, ll_itemCol)
    Next
    
    grd_SUP_Invoice.MergeRow(grd_SUP_Invoice.Rows - 1) = True
    grd_SUP_Invoice.TextMatrix(grd_SUP_Invoice.Rows - 1, 0) = GetLabel("s_total", "#Total")
    Call SetGridCelBold(grd_SUP_Invoice, grd_SUP_Invoice.Rows - 1, 0)
    
    ' formating
    grd_SUP_Invoice.LeftCol = C_DATA_CODE_COL
    
    ' generate header for export to excell
    Dim lsa_colsArray() As Variant
    ReDim lsa_colsArray(grd_SUP_Invoice.Cols - 1) As Variant
    
    For ll_itemCol = 0 To grd_SUP_Invoice.Cols - 1
        If ll_itemCol < C_DATA_CODE_COL Then
            lsa_colsArray(ll_itemCol) = grd_SUP_Invoice.TextMatrix(0, ll_itemCol)
        Else
            lsa_colsArray(ll_itemCol) = Array("", grd_SUP_Invoice.TextMatrix(0, ll_itemCol), grd_SUP_Invoice.ColWidth(ll_itemCol), "", flexAlignRightCenter, "##,##0")
        End If
    Next
    
    Call GRD_SetHeader(grd_SUP_Invoice, mo_DC_ReportSupplierInfo, Array(lsa_colsArray))
    mo_DC_ReportSupplierInfo.gCsts_prefix = tbs_Main.SelectedItem.Key
    mo_DC_ReportSupplierInfo.gTitle = tbs_Main.SelectedItem.Caption
    mo_DC_ReportSupplierInfo.gDC_Desc = GetCboText(cbo_INT_DC_Code, GetLabel("lbl_all", "#All"))
    mo_DC_ReportSupplierInfo.gCARRIER_Name = GetCboText(cbo_INT_CARRIER_Code, GetLabel("lbl_all", "#All"))
    mo_DC_ReportSupplierInfo.gFilterA = GetCboText(cbo_INT_ShipFromDC_code, GetLabel("lbl_all", "#All"))
    mo_DC_ReportSupplierInfo.gFilterB = ""

    Call LockScreen(False)

    Exit Sub

errhandler:
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    
    Call LockScreen(False)
    Call ErrorHandler(Extender.Name & ".Process_INT_Invoice")
End Sub

Private Function RoundUp(ByVal ad_val As Double) As Long
On Error GoTo errhandler
    If Int(ad_val) <> ad_val Then
        RoundUp = Int(ad_val) + 1
    Else
        RoundUp = Int(ad_val)
    End If
    Exit Function
errhandler:
End Function

Private Function STAT_FindRecord(ByRef aoa_tenderCarrier As tCarrierTender, ByVal al_TRAN_Code As Long) As Long
On Error GoTo errhandler
    Dim ll_i As Long
    
    STAT_FindRecord = -1
    
    For ll_i = 0 To aoa_tenderCarrier.TenderCostsCount - 1
        If aoa_tenderCarrier.TenderCosts(ll_i).TRANS_Code = al_TRAN_Code Then
            STAT_FindRecord = ll_i
            Exit For
        End If
    Next
    
    Exit Function
errhandler:
    Call ErrorHandler(Extender.Name & ".STAT_FindRecord")
End Function

Private Sub Clear_STAT_Report()
On Error GoTo errhandler
    If grd_STAT_Report.Rows = 2 And grd_STAT_Report.Cols = 6 Then
        Exit Sub
    End If
    
    grd_STAT_Report.Rows = 1
    
    Exit Sub
errhandler:
    Call ErrorHandler(Extender.Name & ".Clear_STAT_Report")
End Sub

Private Sub Process_STAT_Report()
On Error GoTo errhandler
Const C_REQ As String = "EXEC DC_Report_Stats_lst $DC_CODE$, $FROM_DATE$, $TO_DATE$, $CT_CODE$, $Language_code$"
Const C_DC_CODE_COL As Long = 0
Const C_CT_CODE_COL As Long = 2
Const C_ZIP_CODE_COL As Long = 4
Const C_DATA_CODE_COL As Long = 5
Const C_CURR_CODE_COL As Long = 12


    Call LockScreen(True)
    
    ProgressAction = MsgText(5282, ms_Language_Code, "Preparing process.")
    Progress = 0
    prg_progres.Max = 1

    
    Dim ll_fullTruckPallets As Long
    
    ll_fullTruckPallets = CLng(Get_A_Config("DC_STAT_TruckPal", "18"))
    
    ' get count of tender carriers to make space for tender data
    Dim ll_tenderCount As Long
    ll_tenderCount = ckv_STAT_Carrier_Tender.CheckedCount("EDIT")
    
    Dim loa_tenderCosts() As tCarrierTender
    If ll_tenderCount > 0 Then
        ReDim loa_tenderCosts(ll_tenderCount - 1) As tCarrierTender
    End If
    
    Dim ll_i As Long
    
    grd_STAT_Report.Clear
    
    ' 1. define standard columns for DC and Carrier
    With grd_STAT_Report
        .Cols = 13 + ll_tenderCount * 2
        .Rows = 1
        .ColWidth(0) = 800
        .ColWidth(1) = 1500
        .ColWidth(2) = 2000
        .ColWidth(3) = 2100
        .ColWidth(4) = 1050
        .ColWidth(5) = 1050
        .ColWidth(6) = 1050
        .ColWidth(7) = 1250
        .ColWidth(8) = 1050
        .ColWidth(9) = 1050
        .ColWidth(10) = 1050
        .ColWidth(11) = 1050
        For ll_i = 0 To ll_tenderCount - 1
            .ColWidth(12 + ll_i * 2) = 1050
            .ColWidth(13 + ll_i * 2) = 1050
        Next
        .ColWidth(12 + ll_tenderCount * 2) = 1050
                        
        .TextMatrix(0, 0) = GetLabel("s_DC_Code", "#DC_Code")
        .TextMatrix(0, 1) = GetLabel("s_DC_Name", "#DC_Name")
        .TextMatrix(0, 2) = GetLabel("s_CT_Code", "#CT_Code")
        .TextMatrix(0, 3) = GetLabel("s_CT_Code", "#CT_Name")
        .TextMatrix(0, 4) = GetLabel("s_ZIP_Code", "#Post code")
        .TextMatrix(0, 5) = GetLabel("s_Nb_Shipments", "#Shipments")
        .TextMatrix(0, 6) = GetLabel("s_Avg_pallets", "#Avg pallets")
        .TextMatrix(0, 7) = Replace(GetLabel("s_Full_Trucks_pal", "#Full Trucks by Pallets ($PAL$ PAL)"), "$PAL$", ll_fullTruckPallets, , , vbTextCompare)
        .TextMatrix(0, 8) = GetLabel("s_Full_Trucks_cmb", "#Full trucks Co-loaded")
        .TextMatrix(0, 9) = GetLabel("s_Drop_offs", "#Drop offs")
        .TextMatrix(0, 10) = GetLabel("s_Total_Cost", "#Total cost")
        .TextMatrix(0, 11) = GetLabel("s_Drop_off_Cost", "#Drop off cost")
        For ll_i = 0 To ll_tenderCount - 1
            .TextMatrix(0, 12 + ll_i * 2) = GetLabelCheckview(ckv_STAT_Carrier_Tender, ll_i) & vbCrLf & GetLabel("s_Total_Cost", "#Total cost")
            .TextMatrix(0, 13 + ll_i * 2) = GetLabelCheckview(ckv_STAT_Carrier_Tender, ll_i) & vbCrLf & GetLabel("s_Drop_off_Cost", "#Drop off cost")
        Next
        .TextMatrix(0, 12 + ll_tenderCount * 2) = GetLabel("s_CURR_Code", "#Currency")
         
        .MergeCells = flexMergeRestrictColumns
        .MergeCol(0) = True
        .MergeCol(1) = True
        .MergeCol(2) = True
        .MergeCol(3) = True


        .RowHeight(0) = 750
        
        .FixedAlignment(0) = flexAlignCenterCenter
        .FixedAlignment(1) = flexAlignCenterCenter
        .FixedAlignment(2) = flexAlignCenterCenter
        .FixedAlignment(3) = flexAlignCenterCenter
        .FixedAlignment(4) = flexAlignCenterCenter
        .FixedAlignment(5) = flexAlignCenterCenter
        .FixedAlignment(6) = flexAlignCenterCenter
        .FixedAlignment(7) = flexAlignCenterCenter
        .FixedAlignment(8) = flexAlignCenterCenter
        .FixedAlignment(9) = flexAlignCenterCenter
        .FixedAlignment(10) = flexAlignCenterCenter
        .FixedAlignment(11) = flexAlignCenterCenter
        For ll_i = 0 To ll_tenderCount - 1
            .FixedAlignment(12 + ll_i * 2) = flexAlignCenterCenter
            .FixedAlignment(13 + ll_i * 2) = flexAlignCenterCenter
        Next
        .FixedAlignment(12 + ll_tenderCount * 2) = flexAlignCenterCenter
        
        .ColAlignment(2) = flexAlignCenterCenter
        
        .WordWrap = True
        .ForeColor = vbBlue
            
    End With
    
    Dim ls_req As String
    Dim ll_Cursor As Long
    
    ls_req = STAT_FILTER_ReplacePlaceholders(C_REQ)
    
    ProgressAction = MsgText(5283, ms_Language_Code, "Selecting data.")
    
    ll_Cursor = OpenSQLSafe(mo_Db, ls_req)
    
    If mo_Db.EOF(ll_Cursor) Then
        Call LockScreen(False)
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
        ProgressAction = MsgText(5280, ms_Language_Code, "No data to display!")
        Exit Sub
    End If
    
    ProgressAction = MsgText(5281, ms_Language_Code, "Transactions found:") & mo_Db.RowCount(ll_Cursor)
    
    Dim ls_oldRow As String
    Dim ls_oldRow_grp As String         ' totals per DC_COde/CT_Code
    Dim ls_oldRow_grp_dc As String      ' totals per DC_Code
    Dim ll_old_TRANS_Code As Long

    Dim ls_DC_Code As String
    Dim ls_CT_Code As String
    Dim ls_ZIP_Code As String
    Dim ls_CURR_Code As String
    Dim ls_CURR_Code_prev As String
    
    Dim ll_nbTrans As Long
    Dim ll_nbTransExcl As Long
    Dim ll_paletes As Long
    Dim ld_Cost As Double
    Dim ld_DropOffCost As Double
    Dim ll_fullTrucks As Long
    Dim ll_fullTrucks_cmb As Long
    Dim ll_DropOffs As Long
    
    Dim ls_TRANS_Codes_grp As String
    Dim ll_nbTrans_grp As Long
    Dim ll_nbTransExcl_grp As Long
    Dim ll_paletes_grp As Long
    Dim ld_Cost_grp As Double
    Dim ld_DropOffCost_grp As Double
    Dim ll_fullTrucks_grp As Long
    Dim ll_fullTrucks_cmb_grp As Long
    Dim ll_DropOffs_grp As Long
    
    Dim ls_TRANS_Codes_grp_dc As String
    Dim ll_nbTrans_grp_dc As Long
    Dim ll_nbTransExcl_grp_dc As Long
    Dim ll_paletes_grp_dc As Long
    Dim ld_Cost_grp_dc As Double
    Dim ld_DropOffCost_grp_dc As Double
    Dim ll_fullTrucks_grp_dc As Long
    Dim ll_fullTrucks_cmb_grp_dc As Long
    Dim ll_DropOffs_grp_dc As Long
    
    Dim ll_itemRow As Long
    
    Dim ll_currentRanking As Long
    Dim ll_X As Long
    Dim lb_calcFound As Boolean
    
    ls_oldRow = ""
    ls_oldRow_grp = ""
    ls_oldRow_grp_dc = ""
    ll_old_TRANS_Code = 0
    ll_itemRow = 0
    ls_CURR_Code_prev = ""
    
    
    ll_nbTrans = 0
    ll_nbTransExcl = 0
    ll_paletes = 0
    ld_Cost = 0
    ld_DropOffCost = 0
    ll_fullTrucks = 0
    ll_fullTrucks_cmb = 0
    ll_DropOffs = 0
    
    ll_nbTrans_grp = 0
    ll_nbTransExcl_grp = 0
    ll_paletes_grp = 0
    ld_Cost_grp = 0
    ld_DropOffCost_grp = 0
    ll_fullTrucks_grp = 0
    ll_fullTrucks_cmb_grp = 0
    ll_DropOffs_grp = 0
    
    ll_nbTrans_grp_dc = 0
    ll_nbTransExcl_grp_dc = 0
    ll_paletes_grp_dc = 0
    ld_Cost_grp_dc = 0
    ld_DropOffCost_grp_dc = 0
    ll_fullTrucks_grp_dc = 0
    ll_fullTrucks_cmb_grp_dc = 0
    ll_DropOffs_grp_dc = 0

    mo_Db.SortFields(ll_Cursor) = Array("DC_Code", "Ship_To_CT_Code", "Ship_To_Zip_Code", "CURR_Code")
    Call mo_Db.First(ll_Cursor)
    
    Dim ls_CARRIERS As String
    ls_CARRIERS = GetCkvSelection(ckv_STAT_Carrier)
    
    Dim ls_COUNTRIES As String
    ls_COUNTRIES = GetCkvSelection(ckv_STAT_CT_Code)
    
    Dim ls_TRANS_Codes As String
    Dim ll_TRANS_Codes As Long
    ll_TRANS_Codes = mo_Db.Distinct(ll_Cursor, Array("Master_TRANS_Code", "Ship_To_CT_Code"), False)
    
    If Not mo_Db.EOF(ll_TRANS_Codes) Then
        ls_TRANS_Codes = mo_Db.GetFields(ll_TRANS_Codes, "Master_TRANS_Code")
        Call mo_Db.Next(ll_TRANS_Codes)
        
        While Not mo_Db.EOF(ll_TRANS_Codes)
            If ls_COUNTRIES <> "" Then
                If InStr(1, ls_COUNTRIES, SEPu & mo_Db.GetFields(ll_TRANS_Codes, "Ship_To_CT_Code") & SEPu, vbTextCompare) = 0 Then GoTo nextRowTran
            End If
            ls_TRANS_Codes = ls_TRANS_Codes & "," & mo_Db.GetFields(ll_TRANS_Codes, "Master_TRANS_Code")
nextRowTran:
            Call mo_Db.Next(ll_TRANS_Codes)
        Wend
    End If
    
    Call mo_Db.Close(ll_TRANS_Codes)
    ll_TRANS_Codes = 0
    
    ' for each tender carrier calculate the cost
    For ll_i = 0 To ll_tenderCount - 1
        ProgressAction = MsgText(5284, ms_Language_Code, "Calculating tender carrier #") & (ll_i + 1)
        loa_tenderCosts(ll_i).CARRIER_code = GetLabelCheckview(ckv_STAT_Carrier_Tender, ll_i, 0)
        Call CalculateTenderPrices(ls_TRANS_Codes, loa_tenderCosts(ll_i))
    Next

    ProgressAction = MsgText(5285, ms_Language_Code, "Generating data.")
    Progress = 0
    prg_progres.Max = mo_Db.RowCount(ll_Cursor)
    
    ls_TRANS_Codes = ""
    ls_TRANS_Codes_grp = ""
    
    While Not mo_Db.EOF(ll_Cursor)
    
        Progress = mo_Db.Position(ll_Cursor) + 1
    
        If ls_CARRIERS <> "" Then
            If InStr(1, ls_CARRIERS, SEPu & mo_Db.GetFields(ll_Cursor, "CARRIER_Code") & SEPu, vbTextCompare) = 0 Then GoTo nextRow
        End If
        
        If ls_COUNTRIES <> "" Then
            If InStr(1, ls_COUNTRIES, SEPu & mo_Db.GetFields(ll_Cursor, "Ship_To_CT_Code") & SEPu, vbTextCompare) = 0 Then GoTo nextRow
        End If
    
        ls_DC_Code = mo_Db.GetFields(ll_Cursor, "DC_Code")
        ls_CT_Code = mo_Db.GetFields(ll_Cursor, "Ship_To_CT_Code")
        ls_ZIP_Code = mo_Db.GetFields(ll_Cursor, "Ship_To_Zip_Code")
        ls_CURR_Code = mo_Db.GetFields(ll_Cursor, "CURR_Code")
        If ls_CURR_Code <> "" And ls_CURR_Code_prev = "" And ls_oldRow <> "" Then
            If ls_oldRow = ls_DC_Code & SEP & ls_CT_Code & SEP & ls_ZIP_Code & SEP Then
                ls_oldRow = ls_oldRow & ls_CURR_Code
                ls_CURR_Code_prev = ls_CURR_Code
                ' update currency
                grd_STAT_Report.TextMatrix(ll_itemRow, C_CURR_CODE_COL + ll_tenderCount * 2) = ls_CURR_Code
            End If
        End If
        
        If ls_oldRow <> ls_DC_Code & SEP & ls_CT_Code & SEP & ls_ZIP_Code & SEP & ls_CURR_Code Then

            
            If ls_oldRow <> "" Then
                
                ' we have to update data for previouse grouping
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL) = ll_nbTrans
                If ll_nbTrans - ll_nbTransExcl > 0 Then
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 1) = RoundUp(ll_paletes / (ll_nbTrans - ll_nbTransExcl))
                Else
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 1) = "-"
                End If
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 2) = ll_fullTrucks
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 3) = ll_fullTrucks_cmb
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 4) = ll_DropOffs
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 5) = Format(ld_Cost, "00.00")
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 6) = Format(ld_DropOffCost, "00.00")
                
                ' BOLD INTO COST CELL
                grd_STAT_Report.Row = ll_itemRow
                grd_STAT_Report.Col = C_DATA_CODE_COL + 5
                grd_STAT_Report.CellFontBold = True
                
                
                ' add tender costs
                Dim lsa_trans_codes() As String
                lsa_trans_codes = Split(ls_TRANS_Codes, ",")
                
                Dim ls_TRANS_Code As Variant
                Dim ld_CostSum As Double
                Dim ld_dropOffCostSUM As Double
                    
                For ll_i = 0 To ll_tenderCount - 1
                
                    ld_CostSum = 0
                    ld_dropOffCostSUM = 0
                    lb_calcFound = False
                    
                    For Each ls_TRANS_Code In lsa_trans_codes
                        ' summarize the costs and dropoff costs for each carrier
                        Dim ll_recordIdx As Long
                        
                        ll_recordIdx = STAT_FindRecord(loa_tenderCosts(ll_i), CLng(ls_TRANS_Code))
                        If ll_recordIdx <> -1 Then
                            ld_CostSum = ld_CostSum + loa_tenderCosts(ll_i).TenderCosts(ll_recordIdx).DC_Cost
                            ld_dropOffCostSUM = ld_dropOffCostSUM + loa_tenderCosts(ll_i).TenderCosts(ll_recordIdx).DC_DropOffCost
                            lb_calcFound = True
                        End If
                    Next
                    
                    If lb_calcFound Then
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = Format(ld_CostSum, "00.00")
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 8 + 2 * ll_i) = Format(ld_dropOffCostSUM, "00.00")
                    
                        grd_STAT_Report.Row = ll_itemRow
                        grd_STAT_Report.Col = C_DATA_CODE_COL + 7 + 2 * ll_i
                        If ld_CostSum + ld_dropOffCostSUM < ld_Cost + ld_DropOffCost Then
                            grd_STAT_Report.CellBackColor = RGB(0, 200, 0)
                        ElseIf ld_CostSum + ld_dropOffCostSUM > ld_Cost + ld_DropOffCost Then
                            grd_STAT_Report.CellBackColor = RGB(255, 170, 170)
                        End If
                    Else
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = ""
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 8 + 2 * ll_i) = ""
                    End If
                    
                Next
                
                ' add for TOTALS
                ll_nbTrans_grp = ll_nbTrans_grp + ll_nbTrans
                ll_nbTransExcl_grp = ll_nbTransExcl_grp + ll_nbTransExcl
                ll_paletes_grp = ll_paletes_grp + ll_paletes
                ld_Cost_grp = ld_Cost_grp + ld_Cost
                ld_DropOffCost_grp = ld_DropOffCost_grp + ld_DropOffCost
                ll_fullTrucks_grp = ll_fullTrucks_grp + ll_fullTrucks
                ll_fullTrucks_cmb_grp = ll_fullTrucks_cmb_grp + ll_fullTrucks_cmb
                ll_DropOffs_grp = ll_DropOffs_grp + ll_DropOffs
                ls_TRANS_Codes_grp = IIf(ls_TRANS_Codes_grp = "", "", ls_TRANS_Codes_grp & ",") & ls_TRANS_Codes
            
                ll_old_TRANS_Code = 0
                ll_nbTrans = 0
                ll_nbTransExcl = 0
                ll_paletes = 0
                ld_Cost = 0
                ld_DropOffCost = 0
                ll_fullTrucks = 0
                ll_fullTrucks_cmb = 0
                ll_DropOffs = 0
                ls_TRANS_Codes = ""
            End If
            
            ' add totals per DC_Code/CT_Code
            If ls_oldRow_grp <> ls_DC_Code & SEP & ls_CT_Code Then
            
                If ls_oldRow_grp <> "" Then
                
                    ll_itemRow = ll_itemRow + 1
                    grd_STAT_Report.Rows = ll_itemRow + 1
                    
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_DC_CODE_COL)
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL + 1) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_DC_CODE_COL + 1)
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_CT_CODE_COL)
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL + 1) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_CT_CODE_COL + 1)
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_ZIP_CODE_COL) = GetLabel("s_total", "#Total")
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_CURR_CODE_COL + ll_tenderCount * 2) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_CURR_CODE_COL + ll_tenderCount * 2)
            
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL) = ll_nbTrans_grp
                    If ll_nbTrans_grp - ll_nbTransExcl_grp > 0 Then
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 1) = RoundUp(ll_paletes_grp / (ll_nbTrans_grp - ll_nbTransExcl_grp))
                    Else
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 1) = "-"
                    End If
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 2) = ll_fullTrucks_grp
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 3) = ll_fullTrucks_cmb_grp
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 4) = ll_DropOffs_grp
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 5) = Format(ld_Cost_grp, "00.00")
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 6) = Format(ld_DropOffCost_grp, "00.00")
                    
                    ' BOLD INTO COST CELL
                    grd_STAT_Report.Row = ll_itemRow
                    grd_STAT_Report.Col = C_ZIP_CODE_COL
                    grd_STAT_Report.ColSel = C_CURR_CODE_COL + ll_tenderCount * 2
                    grd_STAT_Report.FillStyle = flexFillRepeat
                    grd_STAT_Report.CellFontBold = True
                    grd_STAT_Report.CellBackColor = RGB(230, 230, 230)
                
                    ' add total tender costs
                    lsa_trans_codes = Split(ls_TRANS_Codes_grp, ",")
                    
                    For ll_i = 0 To ll_tenderCount - 1
                    
                        ld_CostSum = 0
                        ld_dropOffCostSUM = 0
                        lb_calcFound = False
                        
                        For Each ls_TRANS_Code In lsa_trans_codes
                            ' summarize the costs and dropoff costs for each carrier
                            
                            ll_recordIdx = STAT_FindRecord(loa_tenderCosts(ll_i), CLng(ls_TRANS_Code))
                            If ll_recordIdx <> -1 Then
                                ld_CostSum = ld_CostSum + loa_tenderCosts(ll_i).TenderCosts(ll_recordIdx).DC_Cost
                                ld_dropOffCostSUM = ld_dropOffCostSUM + loa_tenderCosts(ll_i).TenderCosts(ll_recordIdx).DC_DropOffCost
                                lb_calcFound = True
                            End If
                        Next
                        
                        If lb_calcFound Then
                            grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = Format(ld_CostSum, "00.00")
                            grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 8 + 2 * ll_i) = Format(ld_dropOffCostSUM, "00.00")
                        
                            grd_STAT_Report.Row = ll_itemRow
                            grd_STAT_Report.Col = C_DATA_CODE_COL + 7 + 2 * ll_i
                            If ld_CostSum + ld_dropOffCostSUM < ld_Cost_grp + ld_DropOffCost_grp Then
                                grd_STAT_Report.CellBackColor = RGB(0, 200, 0)
                            ElseIf ld_CostSum + ld_dropOffCostSUM > ld_Cost_grp + ld_DropOffCost_grp Then
                                grd_STAT_Report.CellBackColor = RGB(255, 170, 170)
                            End If
                        Else
                            grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = ""
                            grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 8 + 2 * ll_i) = ""
                        End If
                    
                    Next
                    
                End If
                
                ' add for TOTALS for DC
                ll_nbTrans_grp_dc = ll_nbTrans_grp_dc + ll_nbTrans_grp
                ll_nbTransExcl_grp_dc = ll_nbTransExcl_grp_dc + ll_nbTransExcl_grp
                ll_paletes_grp_dc = ll_paletes_grp_dc + ll_paletes_grp
                ld_Cost_grp_dc = ld_Cost_grp_dc + ld_Cost_grp
                ld_DropOffCost_grp_dc = ld_DropOffCost_grp_dc + ld_DropOffCost_grp
                ll_fullTrucks_grp_dc = ll_fullTrucks_grp_dc + ll_fullTrucks_grp
                ll_fullTrucks_cmb_grp_dc = ll_fullTrucks_cmb_grp_dc + ll_fullTrucks_cmb_grp
                ll_DropOffs_grp_dc = ll_DropOffs_grp_dc + ll_DropOffs_grp
                ls_TRANS_Codes_grp_dc = IIf(ls_TRANS_Codes_grp_dc = "", "", ls_TRANS_Codes_grp_dc & ",") & ls_TRANS_Codes_grp
                
                ll_nbTrans_grp = 0
                ll_nbTransExcl_grp = 0
                ll_paletes_grp = 0
                ld_Cost_grp = 0
                ld_DropOffCost_grp = 0
                ll_fullTrucks_grp = 0
                ll_fullTrucks_cmb_grp = 0
                ll_DropOffs_grp = 0
                ls_TRANS_Codes_grp = ""
                
                If ls_oldRow_grp_dc <> ls_DC_Code Then
                
                    If ls_oldRow_grp_dc <> "" Then
                    
                        ' ADD LINE WITH TOTALS PER DC
                        ll_itemRow = ll_itemRow + 1
                        grd_STAT_Report.Rows = ll_itemRow + 1
                        
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_DC_CODE_COL)
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL + 1) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_DC_CODE_COL + 1)
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL) = GetLabel("s_total", "#Total")
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL + 1) = ""
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_ZIP_CODE_COL) = ""
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_CURR_CODE_COL + ll_tenderCount * 2) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_CURR_CODE_COL + ll_tenderCount * 2)
                
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL) = ll_nbTrans_grp_dc
                        If ll_nbTrans_grp_dc - ll_nbTransExcl_grp_dc > 0 Then
                            grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 1) = RoundUp(ll_paletes_grp_dc / (ll_nbTrans_grp_dc - ll_nbTransExcl_grp_dc))
                        Else
                            grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 1) = "-"
                        End If
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 2) = ll_fullTrucks_grp_dc
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 3) = ll_fullTrucks_cmb_grp_dc
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 4) = ll_DropOffs_grp_dc
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 5) = Format(ld_Cost_grp_dc, "00.00")
                        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 6) = Format(ld_DropOffCost_grp_dc, "00.00")
                        
                        ' BOLD INTO COST CELL
                        grd_STAT_Report.Row = ll_itemRow
                        grd_STAT_Report.Col = C_CT_CODE_COL
                        grd_STAT_Report.ColSel = C_CURR_CODE_COL + ll_tenderCount * 2
                        grd_STAT_Report.FillStyle = flexFillRepeat
                        grd_STAT_Report.CellFontBold = True
                        grd_STAT_Report.CellBackColor = RGB(230, 230, 230)
                    
                        ' add total tender costs
                        lsa_trans_codes = Split(ls_TRANS_Codes_grp_dc, ",")
                        
                        ' clear costs for rankings
                        For ll_i = 0 To ll_tenderCount - 1
                            loa_tenderCosts(ll_i).TenderDCCost = 0
                        Next
                        
                        For ll_i = 0 To ll_tenderCount - 1
                        
                            ld_CostSum = 0
                            ld_dropOffCostSUM = 0
                            lb_calcFound = False
                            
                            For Each ls_TRANS_Code In lsa_trans_codes
                                ' summarize the costs and dropoff costs for each carrier
                                
                                ll_recordIdx = STAT_FindRecord(loa_tenderCosts(ll_i), CLng(ls_TRANS_Code))
                                If ll_recordIdx <> -1 Then
                                    ld_CostSum = ld_CostSum + loa_tenderCosts(ll_i).TenderCosts(ll_recordIdx).DC_Cost
                                    ld_dropOffCostSUM = ld_dropOffCostSUM + loa_tenderCosts(ll_i).TenderCosts(ll_recordIdx).DC_DropOffCost
                                    lb_calcFound = True
                                End If
                            Next
                            
                            If lb_calcFound Then
                                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = Format(ld_CostSum, "00.00")
                                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 8 + 2 * ll_i) = Format(ld_dropOffCostSUM, "00.00")
                                
                                grd_STAT_Report.Row = ll_itemRow
                                grd_STAT_Report.Col = C_DATA_CODE_COL + 7 + 2 * ll_i
                                If ld_CostSum + ld_dropOffCostSUM < ld_Cost_grp_dc + ld_DropOffCost_grp_dc Then
                                    grd_STAT_Report.CellBackColor = RGB(0, 200, 0)
                                ElseIf ld_CostSum + ld_dropOffCostSUM > ld_Cost_grp_dc + ld_DropOffCost_grp_dc Then
                                    grd_STAT_Report.CellBackColor = RGB(255, 170, 170)
                                End If
                                
                                ' update ranking cost
                                loa_tenderCosts(ll_i).TenderDCCost = ld_CostSum + ld_dropOffCostSUM
                            Else
                                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = ""
                                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 8 + 2 * ll_i) = ""
                            End If
                        
                        Next
                        
                        If ll_tenderCount > 0 Then
                        
                            ' ADD LINE WITH TENDER RANKING
                            ll_itemRow = ll_itemRow + 1
                            grd_STAT_Report.Rows = ll_itemRow + 1
                            grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_DC_CODE_COL)
                            grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL + 1) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_DC_CODE_COL + 1)
                            grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL) = GetLabel("s_ranking", "#Ranking")
                            grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL + 1) = ""
                            grd_STAT_Report.TextMatrix(ll_itemRow, C_ZIP_CODE_COL) = ""
                            
                            For ll_i = 0 To ll_tenderCount - 1
                                If loa_tenderCosts(ll_i).TenderDCCost <> 0 Then
                                    ll_currentRanking = 1
                                    For ll_X = 0 To ll_tenderCount - 1
                                        If ll_X <> ll_i And loa_tenderCosts(ll_X).TenderDCCost <> 0 And loa_tenderCosts(ll_i).TenderDCCost > loa_tenderCosts(ll_X).TenderDCCost Then
                                            ll_currentRanking = ll_currentRanking + 1
                                        End If
                                    Next
                                    grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = ll_currentRanking
                                End If
                            Next
                            
                            ' bold and grey bkg
                            grd_STAT_Report.Row = ll_itemRow
                            grd_STAT_Report.Col = C_CT_CODE_COL
                            grd_STAT_Report.ColSel = C_CURR_CODE_COL + ll_tenderCount * 2
                            grd_STAT_Report.FillStyle = flexFillRepeat
                            grd_STAT_Report.CellFontBold = True
                            grd_STAT_Report.CellBackColor = RGB(230, 230, 230)
                        End If
                    End If
                    

                    
                    ll_nbTrans_grp_dc = 0
                    ll_nbTransExcl_grp_dc = 0
                    ll_paletes_grp_dc = 0
                    ld_Cost_grp_dc = 0
                    ld_DropOffCost_grp_dc = 0
                    ll_fullTrucks_grp_dc = 0
                    ll_fullTrucks_cmb_grp_dc = 0
                    ll_DropOffs_grp_dc = 0
                    ls_TRANS_Codes_grp_dc = ""
                    
                    ls_oldRow_grp_dc = ls_DC_Code
                End If
                
                ls_oldRow_grp = ls_DC_Code & SEP & ls_CT_Code
            End If
            
            ls_oldRow = ls_DC_Code & SEP & ls_CT_Code & SEP & ls_ZIP_Code & SEP & ls_CURR_Code
            ls_CURR_Code_prev = ls_CURR_Code
            
            ll_itemRow = ll_itemRow + 1
            grd_STAT_Report.Rows = ll_itemRow + 1
            
            ' insert new line
            grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL) = ls_DC_Code
            grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL + 1) = mo_Db.GetFields(ll_Cursor, "DC_Desc")
            grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL) = ls_CT_Code
            grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL + 1) = mo_Db.GetFields(ll_Cursor, "CT_desc")
            grd_STAT_Report.TextMatrix(ll_itemRow, C_ZIP_CODE_COL) = ls_ZIP_Code
            grd_STAT_Report.TextMatrix(ll_itemRow, C_CURR_CODE_COL + ll_tenderCount * 2) = ls_CURR_Code
            
        End If
        
        If ll_old_TRANS_Code <> mo_Db.GetFields(ll_Cursor, "Master_TRANS_Code") Then
            ll_nbTrans = ll_nbTrans + 1
            ll_old_TRANS_Code = mo_Db.GetFields(ll_Cursor, "Master_TRANS_Code")
        End If
        
        ll_paletes = ll_paletes + mo_Db.GetFields(ll_Cursor, "Palletes")
        If mo_Db.GetFields(ll_Cursor, "UOM_code") = "TRCK" And ll_paletes = 0 Then
            '1. UOM = "TRCK"
            ll_fullTrucks = ll_fullTrucks + 1
            '2. exclude from average calculation
            ll_nbTransExcl = ll_nbTransExcl + 1
        ElseIf mo_Db.GetFields(ll_Cursor, "IsCombined") = 0 Then
            '2. single transaction based on palletes
            If mo_Db.GetFields(ll_Cursor, "Palletes") >= ll_fullTruckPallets Then ll_fullTrucks = ll_fullTrucks + 1
        ElseIf mo_Db.GetFields(ll_Cursor, "IsMaster") = 1 Then
            '3. combined master transaction
            ll_fullTrucks_cmb = ll_fullTrucks_cmb + 1
        End If
        
        If mo_Db.GetFields(ll_Cursor, "DC_DropOffCost") > 0 Then
            ll_DropOffs = ll_DropOffs + 1
        End If
        
        ld_Cost = ld_Cost + mo_Db.GetFields(ll_Cursor, "DC_Cost")
        ld_DropOffCost = ld_DropOffCost + mo_Db.GetFields(ll_Cursor, "DC_DropOffCost")
        
        ls_TRANS_Codes = ls_TRANS_Codes & IIf(ls_TRANS_Codes = "", "", ",") & mo_Db.GetFields(ll_Cursor, "TRANS_Code")
        
nextRow:
        
        Call mo_Db.Next(ll_Cursor)
    Wend
    
    
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    If ls_oldRow <> "" Then
        ' we have to update data for previouse grouping
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL) = ll_nbTrans
        If ll_nbTrans - ll_nbTransExcl > 0 Then
            grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 1) = RoundUp(ll_paletes / (ll_nbTrans - ll_nbTransExcl))
        Else
            grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 1) = "-"
        End If
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 2) = ll_fullTrucks
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 3) = ll_fullTrucks_cmb
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 4) = ll_DropOffs
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 5) = Format(ld_Cost, "00.00")
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 6) = Format(ld_DropOffCost, "00.00")
        
        ' BOLD INTO COST CELL
        grd_STAT_Report.Row = ll_itemRow
        grd_STAT_Report.Col = C_DATA_CODE_COL + 5
        grd_STAT_Report.CellFontBold = True
        
        ' add tender costs
        lsa_trans_codes = Split(ls_TRANS_Codes, ",")
        
        For ll_i = 0 To ll_tenderCount - 1
        
            ld_CostSum = 0
            ld_dropOffCostSUM = 0
            lb_calcFound = False
            
            For Each ls_TRANS_Code In lsa_trans_codes
                ' summarize the costs and dropoff costs for each carrier
                
                ll_recordIdx = STAT_FindRecord(loa_tenderCosts(ll_i), CLng(ls_TRANS_Code))
                If ll_recordIdx <> -1 Then
                    ld_CostSum = ld_CostSum + loa_tenderCosts(ll_i).TenderCosts(ll_recordIdx).DC_Cost
                    ld_dropOffCostSUM = ld_dropOffCostSUM + loa_tenderCosts(ll_i).TenderCosts(ll_recordIdx).DC_DropOffCost
                    lb_calcFound = True
                End If
            Next
            
            If lb_calcFound Then
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = Format(ld_CostSum, "00.00")
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 8 + 2 * ll_i) = Format(ld_dropOffCostSUM, "00.00")
                
                grd_STAT_Report.Row = ll_itemRow
                grd_STAT_Report.Col = C_DATA_CODE_COL + 7 + 2 * ll_i
                If ld_CostSum + ld_dropOffCostSUM < ld_Cost + ld_DropOffCost Then
                    grd_STAT_Report.CellBackColor = RGB(0, 200, 0)
                ElseIf ld_CostSum + ld_dropOffCostSUM > ld_Cost + ld_DropOffCost Then
                    grd_STAT_Report.CellBackColor = RGB(255, 170, 170)
                End If
            Else
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = ""
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 8 + 2 * ll_i) = ""
            End If
        
        Next

        ' add for TOTALS
        ll_nbTrans_grp = ll_nbTrans_grp + ll_nbTrans
        ll_nbTransExcl_grp = ll_nbTransExcl_grp + ll_nbTransExcl
        ll_paletes_grp = ll_paletes_grp + ll_paletes
        ld_Cost_grp = ld_Cost_grp + ld_Cost
        ld_DropOffCost_grp = ld_DropOffCost_grp + ld_DropOffCost
        ll_fullTrucks_grp = ll_fullTrucks_grp + ll_fullTrucks
        ll_fullTrucks_cmb_grp = ll_fullTrucks_cmb_grp + ll_fullTrucks_cmb
        ll_DropOffs_grp = ll_DropOffs_grp + ll_DropOffs
        ls_TRANS_Codes_grp = IIf(ls_TRANS_Codes_grp = "", "", ls_TRANS_Codes_grp & ",") & ls_TRANS_Codes
        
        ll_old_TRANS_Code = 0
        ll_nbTrans = 0
        ll_nbTransExcl = 0
        ll_paletes = 0
        ld_Cost = 0
        ll_fullTrucks = 0
        ll_fullTrucks_cmb = 0
        
        ' add totals per DC_Code/CT_Code
        ll_itemRow = ll_itemRow + 1
        grd_STAT_Report.Rows = ll_itemRow + 1
        
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_DC_CODE_COL)
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL + 1) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_DC_CODE_COL + 1)
        grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_CT_CODE_COL)
        grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL + 1) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_CT_CODE_COL + 1)
        grd_STAT_Report.TextMatrix(ll_itemRow, C_ZIP_CODE_COL) = GetLabel("s_total", "#Total")
        grd_STAT_Report.TextMatrix(ll_itemRow, C_CURR_CODE_COL + ll_tenderCount * 2) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_CURR_CODE_COL + ll_tenderCount * 2)

        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL) = ll_nbTrans_grp
        If ll_nbTrans_grp - ll_nbTransExcl_grp > 0 Then
            grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 1) = RoundUp(ll_paletes_grp / (ll_nbTrans_grp - ll_nbTransExcl_grp))
        Else
            grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 1) = "-"
        End If
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 2) = ll_fullTrucks_grp
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 3) = ll_fullTrucks_cmb_grp
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 4) = ll_DropOffs_grp
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 5) = Format(ld_Cost_grp, "00.00")
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 6) = Format(ld_DropOffCost_grp, "00.00")
        
        ' BOLD INTO COST CELL
        grd_STAT_Report.Row = ll_itemRow
        grd_STAT_Report.Col = C_ZIP_CODE_COL
        grd_STAT_Report.ColSel = C_CURR_CODE_COL + ll_tenderCount * 2
        grd_STAT_Report.FillStyle = flexFillRepeat
        grd_STAT_Report.CellFontBold = True
        grd_STAT_Report.CellBackColor = RGB(230, 230, 230)
    
        ' add total tender costs
        lsa_trans_codes = Split(ls_TRANS_Codes_grp, ",")
        
        For ll_i = 0 To ll_tenderCount - 1
        
            ld_CostSum = 0
            ld_dropOffCostSUM = 0
            lb_calcFound = False
            
            For Each ls_TRANS_Code In lsa_trans_codes
                ' summarize the costs and dropoff costs for each carrier
                
                ll_recordIdx = STAT_FindRecord(loa_tenderCosts(ll_i), CLng(ls_TRANS_Code))
                If ll_recordIdx <> -1 Then
                    ld_CostSum = ld_CostSum + loa_tenderCosts(ll_i).TenderCosts(ll_recordIdx).DC_Cost
                    ld_dropOffCostSUM = ld_dropOffCostSUM + loa_tenderCosts(ll_i).TenderCosts(ll_recordIdx).DC_DropOffCost
                    lb_calcFound = True
                End If
            Next
            
            If lb_calcFound Then
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = Format(ld_CostSum, "00.00")
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 8 + 2 * ll_i) = Format(ld_dropOffCostSUM, "00.00")
            
                grd_STAT_Report.Row = ll_itemRow
                grd_STAT_Report.Col = C_DATA_CODE_COL + 7 + 2 * ll_i
                If ld_CostSum + ld_dropOffCostSUM < ld_Cost_grp + ld_DropOffCost_grp Then
                    grd_STAT_Report.CellBackColor = RGB(0, 200, 0)
                ElseIf ld_CostSum + ld_dropOffCostSUM > ld_Cost_grp + ld_DropOffCost_grp Then
                    grd_STAT_Report.CellBackColor = RGB(255, 170, 170)
                End If
            Else
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = ""
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 8 + 2 * ll_i) = ""
            End If
        
        Next
        
        ' add for TOTALS for DC
        ll_nbTrans_grp_dc = ll_nbTrans_grp_dc + ll_nbTrans_grp
        ll_nbTransExcl_grp_dc = ll_nbTransExcl_grp_dc + ll_nbTransExcl_grp
        ll_paletes_grp_dc = ll_paletes_grp_dc + ll_paletes_grp
        ld_Cost_grp_dc = ld_Cost_grp_dc + ld_Cost_grp
        ld_DropOffCost_grp_dc = ld_DropOffCost_grp_dc + ld_DropOffCost_grp
        ll_fullTrucks_grp_dc = ll_fullTrucks_grp_dc + ll_fullTrucks_grp
        ll_fullTrucks_cmb_grp_dc = ll_fullTrucks_cmb_grp_dc + ll_fullTrucks_cmb_grp
        ll_DropOffs_grp_dc = ll_DropOffs_grp_dc + ll_DropOffs_grp
        ls_TRANS_Codes_grp_dc = IIf(ls_TRANS_Codes_grp_dc = "", "", ls_TRANS_Codes_grp_dc & ",") & ls_TRANS_Codes_grp
                
        ll_nbTrans_grp = 0
        ll_nbTransExcl_grp = 0
        ll_paletes_grp = 0
        ld_Cost_grp = 0
        ld_DropOffCost_grp = 0
        ll_fullTrucks_grp = 0
        ll_fullTrucks_cmb_grp = 0
        ll_DropOffs_grp = 0
        ls_TRANS_Codes_grp = ""
        
        ' ADD LINE WITH TOTALS PER DC
        ll_itemRow = ll_itemRow + 1
        grd_STAT_Report.Rows = ll_itemRow + 1
        
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_DC_CODE_COL)
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL + 1) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_DC_CODE_COL + 1)
        grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL) = GetLabel("s_total", "#Total")
        grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL + 1) = ""
        grd_STAT_Report.TextMatrix(ll_itemRow, C_ZIP_CODE_COL) = ""
        grd_STAT_Report.TextMatrix(ll_itemRow, C_CURR_CODE_COL + ll_tenderCount * 2) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_CURR_CODE_COL + ll_tenderCount * 2)

        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL) = ll_nbTrans_grp_dc
        If ll_nbTrans_grp_dc - ll_nbTransExcl_grp_dc > 0 Then
            grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 1) = RoundUp(ll_paletes_grp_dc / (ll_nbTrans_grp_dc - ll_nbTransExcl_grp_dc))
        Else
            grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 1) = "-"
        End If
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 2) = ll_fullTrucks_grp_dc
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 3) = ll_fullTrucks_cmb_grp_dc
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 4) = ll_DropOffs_grp_dc
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 5) = Format(ld_Cost_grp_dc, "00.00")
        grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 6) = Format(ld_DropOffCost_grp_dc, "00.00")
        
        ' BOLD INTO COST CELL
        grd_STAT_Report.Row = ll_itemRow
        grd_STAT_Report.Col = C_CT_CODE_COL
        grd_STAT_Report.ColSel = C_CURR_CODE_COL + ll_tenderCount * 2
        grd_STAT_Report.FillStyle = flexFillRepeat
        grd_STAT_Report.CellFontBold = True
        grd_STAT_Report.CellBackColor = RGB(230, 230, 230)
    
        ' add total tender costs
        lsa_trans_codes = Split(ls_TRANS_Codes_grp_dc, ",")
        
        ' clear costs for rankings
        For ll_i = 0 To ll_tenderCount - 1
            loa_tenderCosts(ll_i).TenderDCCost = 0
        Next
                        
        For ll_i = 0 To ll_tenderCount - 1
        
            ld_CostSum = 0
            ld_dropOffCostSUM = 0
            lb_calcFound = False
            
            For Each ls_TRANS_Code In lsa_trans_codes
                ' summarize the costs and dropoff costs for each carrier
                
                ll_recordIdx = STAT_FindRecord(loa_tenderCosts(ll_i), CLng(ls_TRANS_Code))
                If ll_recordIdx <> -1 Then
                    ld_CostSum = ld_CostSum + loa_tenderCosts(ll_i).TenderCosts(ll_recordIdx).DC_Cost
                    ld_dropOffCostSUM = ld_dropOffCostSUM + loa_tenderCosts(ll_i).TenderCosts(ll_recordIdx).DC_DropOffCost
                    lb_calcFound = True
                End If
            Next
            
            If lb_calcFound Then
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = Format(ld_CostSum, "00.00")
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 8 + 2 * ll_i) = Format(ld_dropOffCostSUM, "00.00")
                
                grd_STAT_Report.Row = ll_itemRow
                grd_STAT_Report.Col = C_DATA_CODE_COL + 7 + 2 * ll_i
                If ld_CostSum + ld_dropOffCostSUM < ld_Cost_grp_dc + ld_DropOffCost_grp_dc Then
                    grd_STAT_Report.CellBackColor = RGB(0, 200, 0)
                ElseIf ld_CostSum + ld_dropOffCostSUM > ld_Cost_grp_dc + ld_DropOffCost_grp_dc Then
                    grd_STAT_Report.CellBackColor = RGB(255, 170, 170)
                End If
                            
                ' update ranking cost
                loa_tenderCosts(ll_i).TenderDCCost = ld_CostSum + ld_dropOffCostSUM
            Else
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = ""
                grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 8 + 2 * ll_i) = ""
            End If

        Next
        
        If ll_tenderCount > 0 Then

            ' ADD LINE WITH TENDER RANKING
            ll_itemRow = ll_itemRow + 1
            grd_STAT_Report.Rows = ll_itemRow + 1
            grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_DC_CODE_COL)
            grd_STAT_Report.TextMatrix(ll_itemRow, C_DC_CODE_COL + 1) = grd_STAT_Report.TextMatrix(ll_itemRow - 1, C_DC_CODE_COL + 1)
            grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL) = GetLabel("s_ranking", "#Ranking")
            grd_STAT_Report.TextMatrix(ll_itemRow, C_CT_CODE_COL + 1) = ""
            grd_STAT_Report.TextMatrix(ll_itemRow, C_ZIP_CODE_COL) = ""
            
            For ll_i = 0 To ll_tenderCount - 1
                If loa_tenderCosts(ll_i).TenderDCCost <> 0 Then
                    ll_currentRanking = 1
                    For ll_X = 0 To ll_tenderCount - 1
                        If ll_X <> ll_i And loa_tenderCosts(ll_X).TenderDCCost <> 0 And loa_tenderCosts(ll_i).TenderDCCost > loa_tenderCosts(ll_X).TenderDCCost Then
                            ll_currentRanking = ll_currentRanking + 1
                        End If
                    Next
                    grd_STAT_Report.TextMatrix(ll_itemRow, C_DATA_CODE_COL + 7 + 2 * ll_i) = ll_currentRanking
                End If
            Next
            
            ' bold and grey bkg
            grd_STAT_Report.Row = ll_itemRow
            grd_STAT_Report.Col = C_CT_CODE_COL
            grd_STAT_Report.ColSel = C_CURR_CODE_COL + ll_tenderCount * 2
            grd_STAT_Report.FillStyle = flexFillRepeat
            grd_STAT_Report.CellFontBold = True
            grd_STAT_Report.CellBackColor = RGB(230, 230, 230)
        
        End If
        
        ll_nbTrans_grp_dc = 0
        ll_nbTransExcl_grp_dc = 0
        ll_paletes_grp_dc = 0
        ld_Cost_grp_dc = 0
        ld_DropOffCost_grp_dc = 0
        ll_fullTrucks_grp_dc = 0
        ll_fullTrucks_cmb_grp_dc = 0
        ll_DropOffs_grp_dc = 0
        ls_TRANS_Codes_grp_dc = ""
        
    End If
    
    ' formating
    grd_STAT_Report.LeftCol = C_DATA_CODE_COL
    
    ' generate header for export to excell
    Dim lsa_colsArray() As Variant
    ReDim lsa_colsArray(grd_STAT_Report.Cols - 1) As Variant
    
    Dim ll_itemCol As Long
    
    For ll_itemCol = 0 To grd_STAT_Report.Cols - 1
        If ll_itemCol < C_DATA_CODE_COL Then
            lsa_colsArray(ll_itemCol) = grd_STAT_Report.TextMatrix(0, ll_itemCol)
        Else
            lsa_colsArray(ll_itemCol) = Array("", grd_STAT_Report.TextMatrix(0, ll_itemCol), grd_STAT_Report.ColWidth(ll_itemCol), "", flexAlignRightCenter, "##,##0")
        End If
    Next
    
    Call GRD_SetHeader(grd_STAT_Report, mo_DC_ReportStatisticsInfo, Array(lsa_colsArray))
    mo_DC_ReportStatisticsInfo.gCsts_prefix = tbs_Main.SelectedItem.Key
    mo_DC_ReportStatisticsInfo.gTitle = tbs_Main.SelectedItem.Caption
    mo_DC_ReportStatisticsInfo.gDC_Desc = GetCboText(cbo_STAT_DC_Code, GetLabel("lbl_all", "#All"))
    mo_DC_ReportStatisticsInfo.gCARRIER_Name = GetCkvText(ckv_STAT_Carrier, GetLabel("lbl_all", "#All"))
    mo_DC_ReportStatisticsInfo.gFilterA = GetCkvText(ckv_STAT_CT_Code, GetLabel("lbl_all", "#All"))
    mo_DC_ReportStatisticsInfo.gFilterB = IIf(cal_STAT_From.date_courte = "", "until ", cal_STAT_From.date_courte & " - ") & IIf(cal_STAT_To.date_courte = "", Now(), cal_STAT_To.date_courte)

    ProgressAction = MsgText(5286, ms_Language_Code, "Finished")
    Progress = 0

    Call LockScreen(False)

    Exit Sub

errhandler:
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    
    If ll_TRANS_Codes > 0 Then
        Call mo_Db.Close(ll_TRANS_Codes)
        ll_TRANS_Codes = 0
    End If
    
    Call LockScreen(False)
    Call ErrorHandler(Extender.Name & ".Process_STAT_Report")
End Sub

Private Function FindGridCol(ByRef ao_grid As MSFlexGrid, ByVal al_Row As Long, ByVal al_StartCol As Long, ByVal as_Value As String)
On Error GoTo errhandler
    FindGridCol = -1

    For al_StartCol = al_StartCol To ao_grid.Cols - 1
        If ao_grid.TextMatrix(al_Row, al_StartCol) = as_Value Then
            FindGridCol = al_StartCol
            Exit For
        End If
    Next

    Exit Function

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

Private Function GetLabel(ByVal as_Tag As String, ByVal as_DefaultValue As String, Optional ByVal aInfo As Variant) As String
On Error GoTo ErrorHandler
    
    If mo_Db.Find(mc_ScreenLabels, "FIELD_NAME", as_Tag, , 1) >= 0 Then
        as_DefaultValue = mo_Db.GetFields(mc_ScreenLabels, "LOCAL_TEXT")
    End If
    
    Dim li_idx As Integer
    If Not IsMissing(aInfo) Then
        For li_idx = 0 To UBound(aInfo)
            as_DefaultValue = Replace(as_DefaultValue, aInfo(li_idx, 0), aInfo(li_idx, 1), , , vbTextCompare)
        Next li_idx
    End If
    
    
    GetLabel = as_DefaultValue
    
    Exit Function
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetLabel")
End Function

Private Function GetLabelCheckview(ByRef ao_ckv As ArmCheckView, ByVal al_orderItem As Long, Optional ByVal ll_DataIndex As Long = 1) As String
On Error GoTo ErrorHandler
    Dim as_desc As String
    Dim ll_i As Long
    
    Dim ao_List As ArmCheckList
    Set ao_List = ao_ckv.RoleList("EDIT")
    
    Dim ao_info As ArmItemInfo
    For ll_i = 1 To ao_List.Count
        Set ao_info = ao_List.Items(ll_i)
        If ao_info.CurrentChecked Then
            If al_orderItem = 0 Then
                as_desc = ao_info.GetData(ll_DataIndex)
                Exit For
            End If
            al_orderItem = al_orderItem - 1
        End If
        
    Next
    
    GetLabelCheckview = as_desc
    
    Exit Function
ErrorHandler:
    Call ErrorHandler(Extender.Name & ".GetLabelCheckview")
End Function

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

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

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

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

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

    With a_ExcelSheet1
        ' create standard report header

        ' set width of columns
        For lColIdx = 0 To lColCount
            .Columns(ExcellColName(lColIdx)).columnWidth = ao_grid.ColWidth(lColIdx) / 80
            If ao_grid.ColWidth(lColIdx) > 0 Then ll_LastVisibleCol = lColIdx + 1
            If ll_FirstVisibleCol = -1 Then
                If ao_grid.ColWidth(lColIdx) > 0 Then ll_FirstVisibleCol = lColIdx + 1
            End If
        Next
        
        Dim ll_midCell As Long
        ll_midCell = Round((ll_LastVisibleCol - ll_FirstVisibleCol + 1) / 2, 0)
        
        .cells(2, ll_FirstVisibleCol).Value = GetLabel("ex_report", "#DC REPORT") & " : " & ao_GRDInfo.gTitle
        .cells(2, ll_FirstVisibleCol).Font.Bold = True
        .cells(2, ll_FirstVisibleCol).HorizontalAlignment = xlleft
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$NOW$"
        ms_MsgInfo(0, 1) = Format(Now, "dd/mm/yy hh:mm:ss")
        .cells(2, ll_LastVisibleCol).Value = GetLabel("ex_created", "#Created $NOW$", ms_MsgInfo)
        .cells(2, ll_LastVisibleCol).Font.Italic = True
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$DC_Desc$"
        ms_MsgInfo(0, 1) = ao_GRDInfo.gDC_Desc
        .cells(3, ll_FirstVisibleCol) = GetLabel("ex_dc", "#Distribution centre: $DC_Desc$", ms_MsgInfo)
        .cells(3, ll_FirstVisibleCol).Font.Italic = True
        .cells(3, ll_FirstVisibleCol).Font.Size = 8

        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$CARRIER_Name$"
        ms_MsgInfo(0, 1) = ao_GRDInfo.gCARRIER_Name
        .cells(4, ll_FirstVisibleCol) = GetLabel("ex_carrier", "#Carrier: $CARRIER_Name$", ms_MsgInfo)
        .cells(4, ll_FirstVisibleCol).Font.Italic = True
        .cells(4, ll_FirstVisibleCol).Font.Size = 8
        
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$A$"
        ms_MsgInfo(0, 1) = ao_GRDInfo.gFilterA
        .cells(3, ll_LastVisibleCol) = GetLabel("ex_" & ao_GRDInfo.gCsts_prefix & "_filterA", "#Country/DC: $A$", ms_MsgInfo)
        .cells(3, ll_LastVisibleCol).Font.Italic = True
        .cells(3, ll_LastVisibleCol).Font.Size = 8

        If ao_GRDInfo.gFilterB <> "" Then
            ReDim ms_MsgInfo(0, 1)
            ms_MsgInfo(0, 0) = "$B$"
            ms_MsgInfo(0, 1) = ao_GRDInfo.gFilterB
            .cells(4, ll_LastVisibleCol) = GetLabel("ex_" & ao_GRDInfo.gCsts_prefix & "_filterB", "#Wool: $B$", ms_MsgInfo)
            .cells(4, ll_LastVisibleCol).Font.Italic = True
            .cells(4, ll_LastVisibleCol).Font.Size = 8
        End If
        
        .Columns(ExcellColName(ll_LastVisibleCol - 1) & ":" & ExcellColName(ll_LastVisibleCol - 1)).HorizontalAlignment = xlright


        ' export data
        Dim lIdxExcelRow As Long, lIdxExcelCol As Long

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

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

Private Function ExcellColName(ByVal al_Col As Long) As String
On Error GoTo errhandler
    Dim ls_letter As String
    
    ls_letter = ""
    Do While al_Col >= 0
        ls_letter = Chr(65 + (al_Col Mod 26)) & ls_letter
        al_Col = Int(al_Col / 26) - 1
    Loop
    
    
    ExcellColName = ls_letter
    Exit Function
        
errhandler:
    Call ErrorMessage("ExcellColName")
End Function
Private Function GRD_GetColIndex2(ByRef ao_GRDInfo As GRD_Info, ByVal al_ColIdx As Long) As Long
On Error GoTo ErrorHandler
    
    Dim ll_col As Long
    GRD_GetColIndex2 = -1
    
    For ll_col = UBound(ao_GRDInfo.Cols) To LBound(ao_GRDInfo.Cols) Step -1
        If ao_GRDInfo.Cols(ll_col).Index = al_ColIdx Then
            GRD_GetColIndex2 = ll_col
            Exit For
        End If
    Next ll_col

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

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

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

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

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

Private Sub tlb_Main_action(Index As Integer, ByVal as_Role As String, as_Language As String)
On Error GoTo errhandler
    Call LockScreen(True)
    mb_eventRunning = True

    Select Case as_Role
    Case "L"        ' refresh grid
        Select Case tlb_Main(Index).Tag
        Case "CUS"
            Call Process_DC_Invoice
        Case "INT"
            Call Process_INT_Invoice
        Case "SUP"
            Call Process_SUP_Invoice
        Case "STAT"
            Call Process_STAT_Report
        End Select
            
    Case "G"

        Select Case tlb_Main(Index).Tag
        Case "CUS"
            Call GRD_ExcelExport(grd_DC_Invoice, mo_DC_ReportCustomerInfo, Array())
        Case "INT"
            Call GRD_ExcelExport(grd_INT_Invoice, mo_DC_ReportIntercomapnyInfo, Array())
        Case "SUP"
            Call GRD_ExcelExport(grd_SUP_Invoice, mo_DC_ReportSupplierInfo, Array())
        Case "STAT"
            Call GRD_ExcelExport(grd_STAT_Report, mo_DC_ReportStatisticsInfo, Array())
        End Select
    Case "T"
        RaiseEvent quit
    End Select

    Call LockScreen(False)
    mb_eventRunning = False
    Exit Sub
errhandler:
    Call LockScreen(False)
    mb_eventRunning = False
    Call ErrorMessage("tlb_main_action")
End Sub

Private Function Get_A_Config(ByVal TheKey As String, Optional ByVal as_Default As String = "") As String
On Error GoTo Get_A_Config_er
Dim curs As Long
Dim ls_req As String

    Get_A_Config = as_Default
    ls_req = "select cfg_value from A_config where cfg_Key ='" & UCase(TheKey) & "'"
    curs = OpenSQLSafe(mo_Db, ls_req, 1)
    
    Get_A_Config = mo_Db.GetFields(curs, 0)
    Call mo_Db.Close(curs)
    curs = 0
    
Exit Function
Get_A_Config_er:
    If curs > 0 Then
        Call mo_Db.Close(curs)
        curs = 0
    End If
    Call ErrorHandler("Get_A_Config()")
End Function

Private Property Let ProgressAction(ByVal as_Value As String)
On Error GoTo errhandler
    LockWindowUpdate 0
    lbl_action.Caption = Format(Now, "hh:mm:ss :") & as_Value & " ..."
    lbl_action.Refresh
    LockWindowUpdate UserControl.hwnd
    Exit Property
errhandler:
    Call ErrorHandler(Extender.Name & ".Let ProgressAction")
End Property

Private Property Let Progress(ByVal ai_Value As Integer)
On Error GoTo errhandler
    LockWindowUpdate 0
    prg_progres.Value = ai_Value
    prg_progres.Refresh
    LockWindowUpdate UserControl.hwnd
    Exit Property
errhandler:
    Call ErrorHandler(Extender.Name & ".Let Progress")
End Property

Private Sub CalculateTenderPrices(ByVal as_trans_Codes As String, ByRef aoa_tenderCarrier As tCarrierTender)
On Error GoTo errhandler
Const C_R_X As String = "SELECT DISTINCT T.Master_TRANS_Code, T.TT_Code, DCPL.DCPL_Code, DCPL.DropOff_Cost, DCPL.FullTruckCalculation " & _
                        "FROM DC_Transaction T " & _
                        "   INNER JOIN DC_Carrier_link L1 ON L1.DC_CARRIER_Code = T.DC_CARRIER_Code AND L1.Drop_Flag <> 'X'" & _
                        "        INNER JOIN DC_Carrier_link L2 ON L2.DC_Code = L1.DC_Code AND L2.CARRIER_Code = $CARRIER_Code$ AND L2.Drop_Flag <> 'X' " & _
                        "    INNER JOIN DC_PriceListHeader DCPL ON   DCPL.DC_CARRIER_Code = L2.DC_CARRIER_Code AND " & _
                        "                                            DCPL.TT_Code         = T.TT_code AND " & _
                        "                                            DCPL.UOM_Code        = T.UOM_Code AND " & _
                        "                                            T.TRANS_Date        BETWEEN DCPL.Validity_Start AND ISNULL(DCPL.Validity_End, T.TRANS_Date) AND " & _
                        "                                            DCPL.Drop_Flag       <> 'X' " & _
                        "WHERE " & _
                        "    T.Master_TRANS_Code IN ($TRANS_Codes$) AND " & _
                        "    EXISTS ( SELECT DCPLL.CT_Code FROM DC_PriceListLine DCPLL WHERE DCPLL.DCPL_Code=DCPL.DCPL_Code AND DCPLL.CT_Code=T.Ship_To_CT_Code AND DCPLL.DCPLL_Zip_Code=T.Ship_To_Zip_Code AND DCPLL.Drop_Flag='' )"

                        
    Dim ll_Cursor As Long
    Dim ls_req As String
    
    Dim ls_TRANS_Codes As String
    Dim ll_Pos As Long
    
    aoa_tenderCarrier.TenderCostsCount = 0
    
    Do
        If Len(as_trans_Codes) < 5000 Then
            ls_TRANS_Codes = as_trans_Codes
            as_trans_Codes = ""
        Else
            
            ll_Pos = InStr(5000, as_trans_Codes, ",", vbTextCompare)
            
            If ll_Pos = 0 Then
                ls_TRANS_Codes = as_trans_Codes
                as_trans_Codes = ""
            Else
                ls_TRANS_Codes = Left(as_trans_Codes, ll_Pos - 1)
                as_trans_Codes = Mid(as_trans_Codes, ll_Pos + 1)
            End If
        
        End If
        
        ls_req = Replace(C_R_X, "$CARRIER_Code$", SqlStr(aoa_tenderCarrier.CARRIER_code), , , vbTextCompare)
        ls_req = Replace(ls_req, "$TRANS_Codes$", ls_TRANS_Codes, , , vbTextCompare)
        ll_Cursor = OpenSQLSafe(mo_Db, ls_req)
        
        If mo_Db.RowCount(ll_Cursor) > 0 Then
    
            Progress = 0
            prg_progres.Max = mo_Db.RowCount(ll_Cursor)
            
            ' alocate enough space for transaction costs. It will be slightly more thant master transactions so we increase the space by 10%
            ReDim Preserve aoa_tenderCarrier.TenderCosts(aoa_tenderCarrier.TenderCostsCount + mo_Db.RowCount(ll_Cursor) + Math.Round(mo_Db.RowCount(ll_Cursor) / 10 + 0.5)) As tTenderCost
            
            While Not mo_Db.EOF(ll_Cursor)
                Progress = mo_Db.Position(ll_Cursor) + 1
                Select Case mo_Db.GetFields(ll_Cursor, "TT_Code")
                Case "C"
                    Call UpdateCustomerShipmentPrice(mo_Db.GetFields(ll_Cursor, "Master_TRANS_Code"), mo_Db.GetFields(ll_Cursor, "DCPL_Code"), mo_Db.GetFields(ll_Cursor, "DropOff_Cost"), mo_Db.GetFields(ll_Cursor, "FullTruckCalculation"), aoa_tenderCarrier)
                Case "I"
                    Call UpdateIntercoShipmentPrice(mo_Db.GetFields(ll_Cursor, "Master_TRANS_Code"), mo_Db.GetFields(ll_Cursor, "DCPL_Code"), aoa_tenderCarrier)
                Case "R"
                    Call UpdateSupplierShipmentPrice(mo_Db.GetFields(ll_Cursor, "Master_TRANS_Code"), mo_Db.GetFields(ll_Cursor, "DCPL_Code"), aoa_tenderCarrier)
                End Select
                
                Call mo_Db.Next(ll_Cursor)
            Wend
            
        End If
        
        
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    
    Loop Until as_trans_Codes = ""


    Exit Sub
errhandler:
    If ll_Cursor <> 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    Call ErrorHandler(Extender.Name & ".CalculateTenderPrices")
End Sub

Private Sub UpdateCustomerShipmentPrice(ByVal al_masterTransCode As Long, ByVal al_DCPL_Code As Long, ByVal ad_DropOff_Cost As Double, ByVal as_FullTruckCalculation As String, ByRef aoa_tenderCarrier As tCarrierTender)
On Error GoTo errhandler
    
    If InitTransportCost(al_masterTransCode, al_DCPL_Code) Then
    
        Call UpdateTransportCost_all(ad_DropOff_Cost, as_FullTruckCalculation, aoa_tenderCarrier.TenderCosts, aoa_tenderCarrier.TenderCostsCount)
    
    End If
    
    Exit Sub
errhandler:
    Call ErrorHandler(Extender.Name & ".UpdateCustomerShipmentPrice")
End Sub


Private Sub UpdateIntercoShipmentPrice(ByVal al_masterTransCode As Long, ByVal al_DCPL_Code As Long, ByRef aoa_tenderCarrier As tCarrierTender)
On Error GoTo errhandler
    
    If InitTransportCost(al_masterTransCode, al_DCPL_Code) Then
        
        ' propagate pricelist related values into return transaction for round trip
        Dim ll_i As Long
        For ll_i = LBound(moa_DCTransport_cost) + 1 To UBound(moa_DCTransport_cost)
            moa_DCTransport_cost(ll_i).DCPL_Code = moa_DCTransport_cost(C_LEADING_INTRECO_TRAN).DCPL_Code
            moa_DCTransport_cost(ll_i).DCPLLI_code = moa_DCTransport_cost(C_LEADING_INTRECO_TRAN).DCPLLI_code
            moa_DCTransport_cost(ll_i).DCPLLI_Price = moa_DCTransport_cost(C_LEADING_INTRECO_TRAN).DCPLLI_Price
            moa_DCTransport_cost(ll_i).DCPLLI_CURR_Code = moa_DCTransport_cost(C_LEADING_INTRECO_TRAN).DCPLLI_CURR_Code
'            moa_DCTransport_cost(ll_i).DCS_Price = moa_DCTransport_cost(C_LEADING_INTRECO_TRAN).DCS_Price
            moa_DCTransport_cost(ll_i).DCPLL_Full_Truck_Price = moa_DCTransport_cost(C_LEADING_INTRECO_TRAN).DCPLL_Full_Truck_Price
            moa_DCTransport_cost(ll_i).DCPLL_Full_Truck_Min = moa_DCTransport_cost(C_LEADING_INTRECO_TRAN).DCPLL_Full_Truck_Min
            moa_DCTransport_cost(ll_i).DCPLL_Full_Truck_Max = moa_DCTransport_cost(C_LEADING_INTRECO_TRAN).DCPLL_Full_Truck_Max
            moa_DCTransport_cost(ll_i).DCPLL_Trailer_min = moa_DCTransport_cost(C_LEADING_INTRECO_TRAN).DCPLL_Trailer_min
            moa_DCTransport_cost(ll_i).PriceFormula = moa_DCTransport_cost(C_LEADING_INTRECO_TRAN).PriceFormula
            moa_DCTransport_cost(ll_i).FullTruckPriceFormula = moa_DCTransport_cost(C_LEADING_INTRECO_TRAN).FullTruckPriceFormula
'            moa_DCTransport_cost(ll_i).SurchargeFormula = moa_DCTransport_cost(C_LEADING_INTRECO_TRAN).SurchargeFormula

        Next
    
'        Call UpdateTransportCost_Interco
    
    End If
    
    Exit Sub
errhandler:
    Call ErrorHandler(Extender.Name & ".UpdateIntercoShipmentPrice")
End Sub

Private Sub UpdateSupplierShipmentPrice(ByVal al_masterTransCode As Long, ByVal al_DCPL_Code As Long, ByRef aoa_tenderCarrier As tCarrierTender)
On Error GoTo errhandler
    
    If InitTransportCost(al_masterTransCode, al_DCPL_Code) Then
    
'        Call UpdateTransportCost_Supplier
    
    End If
    
    Exit Sub
errhandler:
    Call ErrorHandler(Extender.Name & ".UpdateSupplierShipmentPrice")
End Sub

' ************************************* TRANSACTION COST RECALC SUPPORT **************************************

Private Function UniqueTransactions(ByVal al_Cursor As Long) As Long
On Error GoTo errhandler
    
    Call mo_Db.First(al_Cursor)
    
    Dim ll_oldTran As Long
    ll_oldTran = 0
    
    Dim ll_tranCount As Long
    ll_tranCount = 0
    
    While Not mo_Db.EOF(al_Cursor)
        If ll_oldTran <> mo_Db.GetFields(al_Cursor, "TRANS_Code") Then
            ll_oldTran = mo_Db.GetFields(al_Cursor, "TRANS_Code")
            ll_tranCount = ll_tranCount + 1
        End If
        Call mo_Db.Next(al_Cursor)
    Wend

    UniqueTransactions = ll_tranCount
    Exit Function
errhandler:
    Call ErrorHandler(".UniqueTransactions()")
End Function

Private Function UniqueSurcharges(ByVal al_Cursor As Long) As Long
On Error GoTo errhandler

    Dim ll_TRANS_Code As Long
    ll_TRANS_Code = mo_Db.GetFields(al_Cursor, "TRANS_code")
    
    Dim ll_surchCount As Long
    ll_surchCount = 0
    
    Dim ll_oldPos As Long
    ll_oldPos = mo_Db.Position(al_Cursor)
    
    While Not mo_Db.EOF(al_Cursor)
        If ll_TRANS_Code = mo_Db.GetFields(al_Cursor, "TRANS_Code") Then
            ll_surchCount = ll_surchCount + 1
        End If
        Call mo_Db.Next(al_Cursor)
    Wend
    
    mo_Db.Position(al_Cursor) = ll_oldPos
    
    UniqueSurcharges = ll_surchCount
    Exit Function
errhandler:
    Call ErrorHandler(".UniqueSurcharges()")
End Function

Private Function InitTransportCost(ByVal al_masterTran As Long, ByVal al_DCPL_Code As Long) As Boolean
On Error GoTo errhandler
Const C_REQ As String = "EXEC DC_PriceListPrice_lst $DCPL_Code$, $MASTER_TRANS_code$, NULL"
    
    InitTransportCost = False
    
    Dim ll_Cursor As Long
    Dim ll_Rows As Long
    ll_Rows = 0
    
    Dim ll_surchRows As Long
    Dim ll_i As Long
    Dim ll_i_surch As Long
    
    Dim ls_req As String

    ls_req = Replace(C_REQ, "$DCPL_Code$", SQLNum(al_DCPL_Code), , , vbTextCompare)
    ls_req = Replace(ls_req, "$MASTER_TRANS_code$", SQLNum(al_masterTran), , vbTextCompare)

    ll_Cursor = OpenSQLSafe(mo_Db, ls_req)
    ll_Rows = UniqueTransactions(ll_Cursor)
        
    If ll_Rows > 0 Then

        ReDim moa_DCTransport_cost(ll_Rows - 1) As tDCTransport_cost
    
        ll_i = LBound(moa_DCTransport_cost)
        Call mo_Db.First(ll_Cursor)

        Dim ll_oldTran As Long
        ll_oldTran = 0
            
        While Not mo_Db.EOF(ll_Cursor)
            If ll_oldTran <> mo_Db.GetFields(ll_Cursor, "TRANS_Code") Then
                ll_oldTran = mo_Db.GetFields(ll_Cursor, "TRANS_Code")
                    
                moa_DCTransport_cost(ll_i).DCPL_Code = al_DCPL_Code
                moa_DCTransport_cost(ll_i).TRANS_Code = mo_Db.GetFields(ll_Cursor, "TRANS_code")
                moa_DCTransport_cost(ll_i).UOM_Code = mo_Db.GetFields(ll_Cursor, "UOM_code")
                moa_DCTransport_cost(ll_i).Quantity = mo_Db.GetFields(ll_Cursor, "Quantity")
                moa_DCTransport_cost(ll_i).Quantity_loaded = mo_Db.GetFields(ll_Cursor, "Quantity_loaded")
            
                moa_DCTransport_cost(ll_i).DCPLLI_code = mo_Db.GetFields(ll_Cursor, "DCPLLI_Code")
                moa_DCTransport_cost(ll_i).DCPLLI_Price = mo_Db.GetFields(ll_Cursor, "DCPLLI_Price")
                moa_DCTransport_cost(ll_i).DCPLLI_CURR_Code = mo_Db.GetFields(ll_Cursor, "DCPLLI_CURR_Code")
                moa_DCTransport_cost(ll_i).Manual_Cost = mo_Db.GetFields(ll_Cursor, "Manual_Cost")
                moa_DCTransport_cost(ll_i).Surcharge_Cost = mo_Db.GetFields(ll_Cursor, "Surcharge_Cost")
                
                moa_DCTransport_cost(ll_i).DCPLL_Full_Truck_Price = mo_Db.GetFields(ll_Cursor, "DCPLL_Full_Truck_Price")
            
                If mo_Db.GetFields(ll_Cursor, "DCPLL_Full_Truck_min") <> 0 Then
                    moa_DCTransport_cost(ll_i).DCPLL_Full_Truck_Min = mo_Db.GetFields(ll_Cursor, "DCPLL_Full_Truck_min")
                Else
                    moa_DCTransport_cost(ll_i).DCPLL_Full_Truck_Min = GetTranQty(ll_i, QTY_FOR_TRANSPORT)
                End If
            
                If mo_Db.GetFields(ll_Cursor, "DCPLL_Full_Truck_max") <> 0 Then
                    moa_DCTransport_cost(ll_i).DCPLL_Full_Truck_Max = mo_Db.GetFields(ll_Cursor, "DCPLL_Full_Truck_max")
                Else
                    moa_DCTransport_cost(ll_i).DCPLL_Full_Truck_Max = GetTranQty(ll_i, QTY_FOR_COST)
                End If
                moa_DCTransport_cost(ll_i).DCPLL_Trailer_min = mo_Db.GetFields(ll_Cursor, "DCPLL_Trailer_min")
        
                moa_DCTransport_cost(ll_i).PriceFormula = mo_Db.GetFields(ll_Cursor, "PriceFormula")
                moa_DCTransport_cost(ll_i).FullTruckPriceFormula = mo_Db.GetFields(ll_Cursor, "FullTruckPriceFormula")
                    
                ' dimension for surcharge info
                ll_surchRows = UniqueSurcharges(ll_Cursor)
                ReDim moa_DCTransport_cost(ll_i).SurchargeInfo(ll_surchRows - 1) As tDCSurcharge_cost
                ll_i_surch = LBound(moa_DCTransport_cost(ll_i).SurchargeInfo)
                
                moa_DCTransport_cost(ll_i).SurchargeInfo(ll_i_surch).DCS_Code = mo_Db.GetFields(ll_Cursor, "DCS_Code")
                moa_DCTransport_cost(ll_i).SurchargeInfo(ll_i_surch).SurchargeFormula = mo_Db.GetFields(ll_Cursor, "SurchargeFormula")
                moa_DCTransport_cost(ll_i).SurchargeInfo(ll_i_surch).DCS_Price = mo_Db.GetFields(ll_Cursor, "DCS_Price")
                moa_DCTransport_cost(ll_i).SurchargeInfo(ll_i_surch).DCS_quantity = mo_Db.GetFields(ll_Cursor, "DCS_quantity")

                ll_i_surch = ll_i_surch + 1
                ll_i = ll_i + 1
            Else
                ' only load next surcharge
                moa_DCTransport_cost(ll_i - 1).SurchargeInfo(ll_i_surch).DCS_Code = mo_Db.GetFields(ll_Cursor, "DCS_Code")
                moa_DCTransport_cost(ll_i - 1).SurchargeInfo(ll_i_surch).SurchargeFormula = mo_Db.GetFields(ll_Cursor, "SurchargeFormula")
                moa_DCTransport_cost(ll_i - 1).SurchargeInfo(ll_i_surch).DCS_Price = mo_Db.GetFields(ll_Cursor, "DCS_Price")
                moa_DCTransport_cost(ll_i - 1).SurchargeInfo(ll_i_surch).DCS_quantity = mo_Db.GetFields(ll_Cursor, "DCS_quantity")
                ll_i_surch = ll_i_surch + 1
            End If
            
            Call mo_Db.Next(ll_Cursor)
        Wend
        InitTransportCost = True
    Else
        ReDim moa_DCTransport_cost(0) As tDCTransport_cost
        ReDim moa_DCTransport_cost(0).SurchargeInfo(0) As tDCSurcharge_cost

        moa_DCTransport_cost(0).SurchargeInfo(0).DCS_Code = ""       ' to indicate no surchage
    End If

    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    Exit Function
errhandler:
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    Call ErrorHandler(Extender.Name & ".InitTransportCost()")
End Function


Private Function GetTranQty(ByVal al_Idx As Long, ByVal ab_forTransport As Boolean) As Double
On Error GoTo errhandler
    
    Dim ld_orderQty As Double
    Dim ld_realQty As Double
    
    ld_orderQty = moa_DCTransport_cost(al_Idx).Quantity
    
    ld_realQty = moa_DCTransport_cost(al_Idx).Quantity_loaded
    
    If ab_forTransport Then
        GetTranQty = IIf(ld_realQty = 0, ld_orderQty, ld_realQty)
    Else
        GetTranQty = Max(ld_orderQty, ld_realQty)
    End If
    
    Exit Function
errhandler:
    Call ErrorHandler(Extender.Name & ".GetTranQty()")
End Function

Private Function Max(ByVal ad_val1 As Double, ByVal ad_val2 As Double) As Double
On Error GoTo errhandler

    Max = IIf(ad_val1 > ad_val2, ad_val1, ad_val2)

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


Private Sub UpdateTransportCost_all(ByVal ad_dropOffCost As Double, ByVal as_FullTruckCalculation As String, ByRef aoa_exportData() As tTenderCost, ByRef al_currentPos As Long)
On Error GoTo errhandler
    
    Dim lb_isFullTruck As Boolean
    Dim lb_isFullTruckCost As Boolean
    Dim lb_overLoaded As Boolean
    Dim lb_overLoadedCost As Boolean
    Dim lb_mixedUOM As Boolean
    Dim lb_isTrailer As Boolean
    
    Call CheckTransportCost(ad_dropOffCost, as_FullTruckCalculation, lb_isFullTruck, lb_overLoaded, lb_overLoadedCost, lb_mixedUOM, lb_isFullTruckCost, lb_isTrailer)
    
    Debug.Assert (Not lb_overLoaded)
    Debug.Assert (Not lb_mixedUOM)
    
    Dim ll_mostExpensiveLine As Long
    ll_mostExpensiveLine = GetMostExpensiveTransportLine()
    
Const C_REQ_INS As String = "EXEC DC_Cost_ins $TRANS_Code$,$DCC_type$,$DCPLLI_Code$,$CURR_code$,$DC_Cost$,$DC_Comment$, $Z_Creator$"

    ' update the transport cost for each transaction
    Dim ld_qtyCost As Double
    ld_qtyCost = GetTotalQty(QTY_FOR_COST)
    
    Dim ll_i As Long
    For ll_i = LBound(moa_DCTransport_cost) To UBound(moa_DCTransport_cost)
    
        Dim ll_TRANS_Code As Long
        ll_TRANS_Code = moa_DCTransport_cost(ll_i).TRANS_Code
        
        'DELETE EXISTING PRICES
        ' GET INDEX FOR TRANS_CODE
        Dim ll_transPos As Long
        
        Dim ll_X As Long
        For ll_X = 0 To al_currentPos
            If aoa_exportData(ll_X).TRANS_Code = ll_TRANS_Code Then
                ' record found
                ll_transPos = ll_X
                Exit For
            ElseIf aoa_exportData(ll_X).TRANS_Code = 0 Then
                ' record not found so we have to define one
                ll_transPos = ll_X
                aoa_exportData(ll_X).TRANS_Code = ll_TRANS_Code
                al_currentPos = al_currentPos + 1
                If UBound(aoa_exportData) < al_currentPos Then
                    ' safely extend the range
                    ReDim Preserve aoa_exportData(al_currentPos + Round(al_currentPos / 10 + 0.5)) As tTenderCost
                End If
                Exit For
            End If
        Next
        
        Dim ls_DCC_type As String
        ls_DCC_type = ""
    
        Dim ld_transportCost As Double
        ld_transportCost = 0
        
        If lb_isFullTruckCost Then
            ' if we are not in master transaction then generate dropoff cost
            If ll_mostExpensiveLine = ll_i Then
                If moa_DCTransport_cost(ll_i).DCPLLI_code <> 0 Then
                    ' insert full truck transport cost for most expensive transport
                    ls_DCC_type = "T"
                    
                    If lb_isTrailer Then
                        ' have to go into database for specific trailer cost
                        Call UpdatePriceTrailer_tran(moa_DCTransport_cost(ll_i), ld_qtyCost)
                    End If
                    
                    ld_transportCost = GetPriceFullTruck(moa_DCTransport_cost(ll_i), ld_qtyCost)
                Else
                    ' cancel creation of transport cost
                    ls_DCC_type = ""
                End If
            Else
                ' generate dropoff cost
                ld_transportCost = ad_dropOffCost
                ls_DCC_type = "D"
            End If
        Else
            ' generate the transport cost
            If moa_DCTransport_cost(ll_i).DCPLLI_code <> 0 Then
                ld_transportCost = GetPrice(moa_DCTransport_cost(ll_i))
                ls_DCC_type = "T"
            Else
                ' cancel creation of transport cost
                ls_DCC_type = ""
            End If
        End If
        
        If ls_DCC_type <> "" Then
            ' type of cost is synchronized with sp : DC_Report_Stats_lst
            If ls_DCC_type = "D" Then
                aoa_exportData(ll_transPos).DC_DropOffCost = aoa_exportData(ll_transPos).DC_DropOffCost + ld_transportCost
            Else
                aoa_exportData(ll_transPos).DC_Cost = aoa_exportData(ll_transPos).DC_Cost + ld_transportCost
            End If
            
            aoa_exportData(ll_transPos).CURR_Code = moa_DCTransport_cost(ll_i).DCPLLI_CURR_Code
        End If
        
        ' generate surcharge if there is some price
        aoa_exportData(ll_transPos).DC_Cost = aoa_exportData(ll_transPos).DC_Cost + UpdateSurchargeCost(moa_DCTransport_cost(ll_i), ld_transportCost)
    
    Next
    
    Exit Sub
errhandler:
    Call ErrorHandler(Extender.Name & ".UpdateTransportCost_all()")
End Sub

Private Function UpdateSurchargeCost(ByRef ao_cost As tDCTransport_cost, ByVal ad_transportCost As Double) As Double
On Error GoTo errhandler

    UpdateSurchargeCost = 0
    
    ' generate surcharge if there is some price
    Debug.Assert (UBound(ao_cost.SurchargeInfo) >= 0)
    
    If ao_cost.SurchargeInfo(0).DCS_Code <> "" Then

        ao_cost.Surcharge_Cost = 0
        
        Dim ll_surchI As Long
        For ll_surchI = 0 To UBound(ao_cost.SurchargeInfo)
            ao_cost.Surcharge_Cost = ao_cost.Surcharge_Cost + GetSurchargePrice(ao_cost.SurchargeInfo(ll_surchI), ad_transportCost)
        Next
        
        UpdateSurchargeCost = ao_cost.Surcharge_Cost
    End If
    Exit Function
errhandler:
    Call ErrorHandler(Extender.Name & ".UpdateSurchargeCost()")
End Function


Private Function GetSurchargePrice(ByRef ao_priceData As tDCSurcharge_cost, ByVal ad_tansportCost As Double) As Double
On Error GoTo errhandler
    
    Call VBScriptReset
        
    Call mo_scriptObj.AddCode("Price=" & Replace(ao_priceData.DCS_Price, DecimalSeparator, ".") & vbCrLf & "Quantity=" & Replace(ao_priceData.DCS_quantity, DecimalSeparator, ".") & vbCrLf & "Cost=" & Replace(ad_tansportCost, DecimalSeparator, "."))
    
    GetSurchargePrice = mo_scriptObj.Eval(ao_priceData.SurchargeFormula)
    
    Exit Function
    
errhandler:
    Call ErrorHandler("GetSurchargePrice code:" & "Price=" & Replace(ao_priceData.DCS_Price, DecimalSeparator, ".") & vbCrLf & "Quantity=" & Replace(ao_priceData.DCS_quantity, DecimalSeparator, "."))
End Function

Private Sub CheckTransportCost(ByVal as_dropOffCost As Double, ByVal as_FullTruckCalculation As String, ByRef ab_isFullTruck As Boolean, ByRef ab_overLoaded As Boolean, ByRef ab_overLoadedCost As Boolean, ByRef ab_mixedUOM As Boolean, ByRef ab_isFullTruckCost As Boolean, ByRef ab_isTrailer As Boolean)
On Error GoTo errhandler
    
    Debug.Assert (UBound(moa_DCTransport_cost) >= 0)
    
    ab_isFullTruck = False
    ab_overLoaded = False
    ab_overLoadedCost = False
    ab_mixedUOM = False
    ab_isFullTruckCost = False
    ab_isTrailer = False
    
    Dim ls_UOM_Code As String
    ls_UOM_Code = moa_DCTransport_cost(LBound(moa_DCTransport_cost)).UOM_Code
    
    
    Dim ll_mostExpensiveLine As Long
    ll_mostExpensiveLine = GetMostExpensiveTransportLine()

    Dim ll_i As Long
    
    For ll_i = LBound(moa_DCTransport_cost) + 1 To UBound(moa_DCTransport_cost)
     
        If ls_UOM_Code <> moa_DCTransport_cost(ll_i).UOM_Code Then
            ab_mixedUOM = True
        End If
    
    Next
    
    Dim ld_QtyTotalCost As Double
    ld_QtyTotalCost = GetTotalQty(QTY_FOR_COST)

    If moa_DCTransport_cost(ll_mostExpensiveLine).DCPLLI_code <> 0 Then
        ' if we have some cost -> we calculate overloaded truck
    
        Dim ld_QtyTotal As Double
        ld_QtyTotal = GetTotalQty(QTY_FOR_TRANSPORT)
        
        If ld_QtyTotal >= moa_DCTransport_cost(ll_mostExpensiveLine).DCPLL_Full_Truck_Min Then
            
            If ld_QtyTotal <= moa_DCTransport_cost(ll_mostExpensiveLine).DCPLL_Full_Truck_Max Then
                ab_isFullTruck = True
                If moa_DCTransport_cost(ll_mostExpensiveLine).DCPLL_Trailer_min > 0 And _
                    ld_QtyTotal >= moa_DCTransport_cost(ll_mostExpensiveLine).DCPLL_Trailer_min _
                Then
                    ab_isTrailer = True
                End If
            Else
                'overloaded
                ab_overLoaded = True
            End If
            
        End If
        
        If ld_QtyTotalCost > moa_DCTransport_cost(ll_mostExpensiveLine).DCPLL_Full_Truck_Max Then
            ab_overLoadedCost = True
        End If
    End If
    
    If as_FullTruckCalculation = "N" Then
        ' if the drop off cost is zero then we count each delivery
        If as_dropOffCost = 0 Then
            ab_isFullTruckCost = False
        ElseIf UBound(moa_DCTransport_cost) <> LBound(moa_DCTransport_cost) Then
            ' if there is some dropoff and more than 1 transaction we count as full truck
            ab_isFullTruckCost = True
        End If
    Else
        ' calculate from real qty
        If ld_QtyTotalCost >= moa_DCTransport_cost(ll_mostExpensiveLine).DCPLL_Full_Truck_Min Then
            ab_isFullTruckCost = True
        End If
    End If

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

Private Function GetMostExpensiveTransportLine() As Long
On Error GoTo errhandler
    Dim ll_expensiveTransport As Long
    
    Dim ll_i As Long
    
    Dim ld_mostExpensiveCost As Double
    Dim ld_currentCost As Double
    
    Debug.Assert (UBound(moa_DCTransport_cost) >= 0)
    
    ll_expensiveTransport = 0
    ld_mostExpensiveCost = GetPriceFullTruck(moa_DCTransport_cost(0), moa_DCTransport_cost(0).DCPLL_Full_Truck_Min)
    
    For ll_i = LBound(moa_DCTransport_cost) + 1 To UBound(moa_DCTransport_cost)
    
        ld_currentCost = GetPriceFullTruck(moa_DCTransport_cost(ll_i), moa_DCTransport_cost(ll_i).DCPLL_Full_Truck_Min)
        
        If ld_currentCost > ld_mostExpensiveCost Then
            
            ll_expensiveTransport = ll_i
            ld_mostExpensiveCost = ld_currentCost
            
        ElseIf ld_currentCost = ld_mostExpensiveCost Then
            If GetTranQty(ll_i, QTY_FOR_COST) > GetTranQty(ll_expensiveTransport, QTY_FOR_COST) Then
                ll_expensiveTransport = ll_i
            End If
        End If
    Next

    GetMostExpensiveTransportLine = ll_expensiveTransport
    Exit Function
errhandler:
    Call ErrorHandler(Extender.Name & ".GetMostExpensiveTransportLine()")
End Function


Private Function GetTotalQty(ByVal ab_forTransport As Boolean) As Double
On Error GoTo errhandler
    Dim ld_TotalQty As Double
    Dim ll_i As Long
    
    ld_TotalQty = 0
    For ll_i = LBound(moa_DCTransport_cost) To UBound(moa_DCTransport_cost)
        If ab_forTransport Then
            ld_TotalQty = ld_TotalQty + IIf(moa_DCTransport_cost(ll_i).Quantity_loaded = 0, moa_DCTransport_cost(ll_i).Quantity, moa_DCTransport_cost(ll_i).Quantity_loaded)
        Else
            ld_TotalQty = ld_TotalQty + Max(moa_DCTransport_cost(ll_i).Quantity, moa_DCTransport_cost(ll_i).Quantity_loaded)
        End If
    Next

    GetTotalQty = ld_TotalQty
    Exit Function
errhandler:
    Call ErrorHandler(Extender.Name & ".GetTotalQty()")
End Function

Private Sub UpdatePriceTrailer_tran(ByRef ao_priceData As tDCTransport_cost, ByVal ad_Qty As Double)
On Error GoTo errhandler
Const C_REQ As String = "EXEC DC_Transaction_sel $TRANS_Code$"

    Dim ll_Cursor  As Long
    ll_Cursor = OpenSQLSafe(mo_Db, Replace(C_REQ, "$TRANS_Code$", SQLNum(ao_priceData.TRANS_Code), , , vbTextCompare))
    
    If Not mo_Db.EOF(ll_Cursor) Then
    
        Call UpdatePriceTrailer(ao_priceData, ad_Qty, mo_Db.GetFields(ll_Cursor, "Ship_To_CT_Code"), mo_Db.GetFields(ll_Cursor, "Ship_To_Zip_Code"))
    
    End If
    
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    Exit Sub
    
errhandler:
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    
    Call ErrorHandler("UpdatePriceTrailer_tran")
End Sub

Private Sub UpdatePriceTrailer(ByRef ao_priceData As tDCTransport_cost, ByVal ad_Qty As Double, ByVal as_CT_Code As String, ByVal as_zip_code As String)
On Error GoTo errhandler
Const C_REQ As String = "EXEC DC_PriceListPriceTrailer_sel $DCPL_Code$, $Ship_To_CT_Code$, $Ship_To_Zip_Code$, $Quantity_for_cost$"

    Dim ls_req As String
    ls_req = Replace(C_REQ, "$DCPL_Code$", SQLNum(ao_priceData.DCPL_Code), , , vbTextCompare)
    ls_req = Replace(ls_req, "$Quantity_for_cost$", SQLNum(ad_Qty), , vbTextCompare)
    ls_req = Replace(ls_req, "$Ship_To_CT_Code$", SqlStr(as_CT_Code, 4, True), , vbTextCompare)
    ls_req = Replace(ls_req, "$Ship_To_Zip_Code$", SqlStr(Trim(as_zip_code), 20, True), , vbTextCompare)
    
    Dim ll_Cursor  As Long
    ll_Cursor = OpenSQLSafe(mo_Db, ls_req)
    
    If Not mo_Db.EOF(ll_Cursor) Then
        
        ao_priceData.DCPLLI_code = mo_Db.GetFields(ll_Cursor, "DCPLLI_Code")
        ao_priceData.DCPLL_Full_Truck_Price = mo_Db.GetFields(ll_Cursor, "DCPLLI_Price")
        ao_priceData.FullTruckPriceFormula = mo_Db.GetFields(ll_Cursor, "PriceFormula")

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

Private Function GetPrice(ByRef ao_priceData As tDCTransport_cost) As Double
On Error GoTo errhandler
    
    Call VBScriptReset
    
    Call mo_scriptObj.AddCode("Price=" & Replace(ao_priceData.DCPLLI_Price, DecimalSeparator, ".") & vbCrLf & "Quantity=" & Replace(Max(ao_priceData.Quantity, ao_priceData.Quantity_loaded), DecimalSeparator, "."))
    
    GetPrice = mo_scriptObj.Eval(ao_priceData.PriceFormula)
    
    Exit Function
    
errhandler:
    Call ErrorHandler("GetPrice code:" & "Price=" & Replace(ao_priceData.DCPLLI_Price, DecimalSeparator, ".") & vbCrLf & "Quantity=" & Replace(Max(ao_priceData.Quantity, ao_priceData.Quantity_loaded), DecimalSeparator, "."))
End Function

Private Function GetPriceFullTruck(ByRef ao_priceData As tDCTransport_cost, ByVal ad_Qty As Double) As Double
On Error GoTo errhandler
    
    Call VBScriptReset
    
    Call mo_scriptObj.AddCode("Price=" & Replace(ao_priceData.DCPLL_Full_Truck_Price, DecimalSeparator, ".") & vbCrLf & "Quantity=" & Replace(ad_Qty, DecimalSeparator, "."))
    
    GetPriceFullTruck = mo_scriptObj.Eval(ao_priceData.FullTruckPriceFormula)
    
    Exit Function
    
errhandler:
    Call ErrorHandler("GetPriceFullTruck code:" & "Price=" & Replace(ao_priceData.DCPLL_Full_Truck_Price, DecimalSeparator, ".") & vbCrLf & "Quantity=" & Replace(ad_Qty, DecimalSeparator, ".") & vbCrLf & ao_priceData.FullTruckPriceFormula)
End Function

Private Sub VBScriptReset()
On Error GoTo errhandler

    Call mo_scriptObj.Reset
    
    Call mo_scriptObj.AddCode("Function IIf(bClause, sTrue, sFalse) " & vbCrLf & _
                              "If CBool(bClause) Then " & vbCrLf & _
                              "IIf = sTrue " & vbCrLf & _
                              "    Else " & vbCrLf & _
                              "IIf = sFalse " & vbCrLf & _
                              "End If " & vbCrLf & _
                              "End Function")
    
    Exit Sub
errhandler:
    Call ErrorHandler("VBScriptReset")
End Sub

' ************************************************************************************************************


