VERSION 5.00
Begin VB.UserControl DC_Sample 
   ClientHeight    =   9120
   ClientLeft      =   0
   ClientTop       =   0
   ClientWidth     =   10365
   ScaleHeight     =   9120
   ScaleWidth      =   10365
   Begin DSWMGR.ArmCombobox cbo_currency 
      Height          =   345
      Left            =   7695
      TabIndex        =   69
      Tag             =   "CUST_FC_Currency"
      Top             =   4335
      Visible         =   0   'False
      Width           =   2505
      _ExtentX        =   4419
      _ExtentY        =   609
   End
   Begin DSWMGR.ArmCombobox cbo_UOM 
      Height          =   345
      Left            =   3750
      TabIndex        =   68
      Top             =   3795
      Width           =   1755
      _ExtentX        =   3096
      _ExtentY        =   609
   End
   Begin DSWMGR.ArmCombobox cbo_Equipement 
      Height          =   345
      Left            =   6720
      TabIndex        =   67
      Tag             =   "EQ_Code"
      Top             =   1365
      Width           =   3495
      _ExtentX        =   6165
      _ExtentY        =   609
   End
   Begin DSWMGR.ArmCombobox cbo_country 
      Height          =   345
      Left            =   5790
      TabIndex        =   66
      Tag             =   "Ship_To_CT_Code"
      Top             =   1875
      Width           =   1935
      _ExtentX        =   3413
      _ExtentY        =   609
   End
   Begin DSWMGR.ArmCombobox cbo_carrier 
      Height          =   345
      Left            =   1590
      TabIndex        =   65
      Tag             =   "CARRIER_Code"
      Top             =   1365
      Visible         =   0   'False
      Width           =   3150
      _ExtentX        =   5556
      _ExtentY        =   609
   End
   Begin DSWMGR.ArmCombobox cbo_masterTran 
      Height          =   345
      Left            =   6075
      TabIndex        =   64
      Tag             =   "Master_TRANS_Code"
      Top             =   540
      Width           =   4140
      _ExtentX        =   7303
      _ExtentY        =   609
   End
   Begin VB.TextBox txt_CLSOrderNb 
      Height          =   288
      Left            =   1590
      MaxLength       =   20
      TabIndex        =   42
      Tag             =   "Order_Number"
      Top             =   2790
      Width           =   1530
   End
   Begin VB.TextBox txt_CLSShipNb 
      Height          =   288
      Left            =   8655
      MaxLength       =   20
      TabIndex        =   41
      Tag             =   "Shipment_Number"
      Top             =   2790
      Width           =   1530
   End
   Begin VB.TextBox txt_DeliveryDate 
      ForeColor       =   &H00000000&
      Height          =   288
      Left            =   1590
      Locked          =   -1  'True
      TabIndex        =   40
      TabStop         =   0   'False
      Tag             =   "Delivery_Date"
      Top             =   3345
      Width           =   1212
   End
   Begin VB.TextBox txt_RSRequire 
      CausesValidation=   0   'False
      Height          =   525
      Left            =   1605
      MaxLength       =   240
      MultiLine       =   -1  'True
      TabIndex        =   39
      Tag             =   "Remark"
      Top             =   4860
      Width           =   8600
   End
   Begin VB.TextBox txt_ShipDate 
      ForeColor       =   &H00000000&
      Height          =   288
      Left            =   1560
      Locked          =   -1  'True
      TabIndex        =   38
      TabStop         =   0   'False
      Tag             =   "TRANS_Date"
      Top             =   975
      Width           =   1635
   End
   Begin VB.TextBox txt_ShipAdd 
      Height          =   288
      Left            =   1590
      MaxLength       =   80
      TabIndex        =   37
      Tag             =   "Ship_To_Address"
      Top             =   2340
      Width           =   8600
   End
   Begin VB.TextBox txt_QuantityWeight 
      Height          =   288
      Left            =   1605
      MaxLength       =   6
      TabIndex        =   36
      Tag             =   "Quantity"
      Top             =   3870
      Width           =   960
   End
   Begin VB.TextBox txt_COSContact 
      Height          =   288
      Left            =   1605
      MaxLength       =   15
      TabIndex        =   35
      Tag             =   "COS_Contact"
      Top             =   4365
      Width           =   2772
   End
   Begin VB.TextBox txt_ShipFromDC 
      Height          =   288
      Left            =   1560
      Locked          =   -1  'True
      MaxLength       =   30
      TabIndex        =   34
      Tag             =   "DC_Name"
      Text            =   "Pontarlier"
      Top             =   615
      Width           =   2772
   End
   Begin VB.TextBox txt_CustName 
      Height          =   288
      Left            =   1590
      MaxLength       =   80
      TabIndex        =   33
      Tag             =   "CUSTN1"
      Text            =   "Text1"
      Top             =   1905
      Width           =   3120
   End
   Begin VB.CommandButton SSShipDate 
      Height          =   276
      Left            =   3270
      Style           =   1  'Graphical
      TabIndex        =   32
      Top             =   1020
      Width           =   252
   End
   Begin VB.CommandButton SSDeliveryDate 
      Height          =   276
      Left            =   2910
      Style           =   1  'Graphical
      TabIndex        =   31
      Top             =   3345
      Width           =   252
   End
   Begin VB.CommandButton ssp_quit 
      CausesValidation=   0   'False
      Height          =   615
      Left            =   9435
      Style           =   1  'Graphical
      TabIndex        =   30
      Top             =   8415
      Width           =   615
   End
   Begin VB.CommandButton spp_save 
      Height          =   615
      Left            =   8745
      Style           =   1  'Graphical
      TabIndex        =   29
      Top             =   8415
      Width           =   615
   End
   Begin VB.Frame Fr_Schedule 
      Caption         =   "Schedule"
      Height          =   1095
      Left            =   165
      TabIndex        =   19
      Top             =   5430
      Width           =   9975
      Begin VB.OptionButton Opt_No 
         Caption         =   "No"
         Height          =   192
         Left            =   7860
         TabIndex        =   24
         Top             =   360
         Value           =   -1  'True
         Width           =   972
      End
      Begin VB.OptionButton Opt_Yes 
         Caption         =   "Yes"
         Height          =   192
         Left            =   6960
         TabIndex        =   23
         Top             =   360
         Width           =   852
      End
      Begin VB.TextBox txt_LoadPlanEndTime 
         Height          =   288
         Left            =   6960
         MaxLength       =   5
         TabIndex        =   22
         Tag             =   "Load_Planned_Ending_Time"
         Top             =   720
         Width           =   2172
      End
      Begin VB.TextBox txt_LoadPlanStartTime 
         Height          =   288
         Left            =   2160
         MaxLength       =   5
         TabIndex        =   21
         Tag             =   "Load_Planned_Starting_Time"
         Top             =   720
         Width           =   2052
      End
      Begin VB.TextBox txt_HaulierBookNb 
         Height          =   288
         Left            =   2160
         MaxLength       =   15
         TabIndex        =   20
         Tag             =   "Haulier_Booking_Number"
         Top             =   360
         Width           =   2052
      End
      Begin VB.Label lbl_StandTrailers 
         Caption         =   "Stand trailers"
         Height          =   255
         Left            =   4800
         TabIndex        =   28
         Top             =   360
         Width           =   1335
      End
      Begin VB.Label lbl_LoadPlanEndTime 
         Caption         =   "Load planned ending time"
         Height          =   255
         Left            =   4800
         TabIndex        =   27
         Top             =   720
         Width           =   2175
      End
      Begin VB.Label lbl_LoadPlanStartTime 
         Caption         =   "Load planned starting time"
         Height          =   255
         Left            =   120
         TabIndex        =   26
         Top             =   720
         Width           =   2055
      End
      Begin VB.Label lbl_HaulierBookNb 
         Caption         =   "Haulier bookin n°"
         Height          =   255
         Left            =   120
         TabIndex        =   25
         Top             =   360
         Width           =   2055
      End
   End
   Begin VB.Frame Fr_Actual 
      Caption         =   "Actual"
      Height          =   1545
      Left            =   165
      TabIndex        =   8
      Top             =   6615
      Width           =   9975
      Begin VB.TextBox txt_LoadEndTime 
         Height          =   288
         Left            =   7005
         MaxLength       =   5
         TabIndex        =   13
         Tag             =   "Load_Ending_Time"
         Top             =   720
         Width           =   2172
      End
      Begin VB.TextBox txt_TrailerNb 
         Height          =   288
         Left            =   7005
         MaxLength       =   15
         TabIndex        =   12
         Tag             =   "Trailer_Number"
         Top             =   330
         Width           =   2172
      End
      Begin VB.TextBox txt_LoadBy 
         Height          =   288
         Left            =   1440
         MaxLength       =   15
         TabIndex        =   11
         Tag             =   "Load_By"
         Top             =   1080
         Width           =   2772
      End
      Begin VB.TextBox txt_LoadStartTime 
         Height          =   288
         Left            =   2160
         MaxLength       =   5
         TabIndex        =   10
         Tag             =   "Load_Starting_Time"
         Top             =   720
         Width           =   2052
      End
      Begin VB.TextBox txt_ArrivalTime 
         Height          =   288
         Left            =   2160
         MaxLength       =   5
         TabIndex        =   9
         Tag             =   "Load_Arrival_Time"
         Top             =   330
         Width           =   2052
      End
      Begin VB.Label lbl_LoadEndTime 
         Caption         =   "Load ending time"
         Height          =   255
         Left            =   4635
         TabIndex        =   18
         Top             =   720
         Width           =   2175
      End
      Begin VB.Label lbl_TrailerNb 
         Caption         =   "Trailer n°"
         Height          =   255
         Left            =   4635
         TabIndex        =   17
         Top             =   330
         Width           =   2175
      End
      Begin VB.Label lbl_LoadBy 
         Caption         =   "Load by"
         Height          =   255
         Left            =   120
         TabIndex        =   16
         Top             =   1080
         Width           =   1935
      End
      Begin VB.Label lbl_LoadStartTime 
         Caption         =   "Load starting time"
         Height          =   255
         Left            =   120
         TabIndex        =   15
         Top             =   720
         Width           =   2055
      End
      Begin VB.Label lbl_ArrivalTime 
         Caption         =   "Arrival time"
         Height          =   255
         Left            =   120
         TabIndex        =   14
         Top             =   330
         Width           =   2055
      End
   End
   Begin VB.TextBox txt_paidByCustomer 
      Height          =   288
      Left            =   6705
      MaxLength       =   6
      TabIndex        =   7
      Tag             =   "CUST_Freight_Cost"
      Top             =   4395
      Visible         =   0   'False
      Width           =   795
   End
   Begin VB.TextBox txt_tranOrder 
      ForeColor       =   &H00000000&
      Height          =   288
      Left            =   6075
      TabIndex        =   6
      Tag             =   "TRANS_Order"
      Top             =   990
      Width           =   1635
   End
   Begin VB.TextBox txt_totalQty 
      Height          =   288
      Left            =   9270
      TabIndex        =   5
      TabStop         =   0   'False
      Tag             =   "Total_qty"
      Top             =   3870
      Visible         =   0   'False
      Width           =   915
   End
   Begin VB.ComboBox cbo_delivery 
      Height          =   315
      ItemData        =   "DC_Sample.ctx":0000
      Left            =   5160
      List            =   "DC_Sample.ctx":0002
      TabIndex        =   4
      Tag             =   "Delivery_Number"
      Top             =   2790
      Width           =   1875
   End
   Begin VB.CheckBox chk_manualPrice 
      Alignment       =   1  'Right Justify
      Caption         =   "#Manual country/zip"
      Height          =   255
      Left            =   8055
      TabIndex        =   3
      Top             =   1065
      Visible         =   0   'False
      Width           =   2070
   End
   Begin VB.ComboBox cbo_postCode 
      Height          =   315
      ItemData        =   "DC_Sample.ctx":0004
      Left            =   8745
      List            =   "DC_Sample.ctx":0006
      TabIndex        =   2
      Tag             =   "Ship_To_Zip_Code"
      Text            =   "cbo_postCode"
      Top             =   1905
      Width           =   1455
   End
   Begin VB.TextBox txt_RealQuantity 
      Height          =   288
      Left            =   7425
      MaxLength       =   6
      TabIndex        =   1
      Tag             =   "Quantity_loaded"
      Top             =   3870
      Visible         =   0   'False
      Width           =   960
   End
   Begin VB.CheckBox chk_isReturn 
      Caption         =   "#Is return"
      Height          =   255
      Left            =   3435
      TabIndex        =   0
      Tag             =   "chk_isReturn"
      Top             =   3345
      Visible         =   0   'False
      Width           =   2070
   End
   Begin VB.Label lbl_caption 
      Caption         =   "Opened action desc"
      BeginProperty Font 
         Name            =   "MS Sans Serif"
         Size            =   9.75
         Charset         =   0
         Weight          =   700
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      Height          =   255
      Left            =   105
      TabIndex        =   70
      Top             =   135
      Width           =   10155
   End
   Begin VB.Label lbl_ShipFromDC 
      Caption         =   "Ship from DC"
      Height          =   255
      Left            =   105
      TabIndex        =   63
      Top             =   600
      Width           =   1455
   End
   Begin VB.Label lbl_ShipDate 
      Caption         =   "Shipping date"
      Height          =   255
      Left            =   120
      TabIndex        =   62
      Top             =   990
      Width           =   1455
   End
   Begin VB.Label lbl_CarrierCpy 
      Caption         =   "Carrier company"
      Height          =   255
      Left            =   135
      TabIndex        =   61
      Top             =   1455
      Visible         =   0   'False
      Width           =   1455
   End
   Begin VB.Label lbl_Equipement 
      Caption         =   "Equipement"
      Height          =   255
      Left            =   5010
      TabIndex        =   60
      Top             =   1455
      Width           =   1695
   End
   Begin VB.Label lbl_CLSOrderNb 
      Caption         =   "CLS Order n°"
      Height          =   255
      Left            =   150
      TabIndex        =   59
      Top             =   2835
      Width           =   1455
   End
   Begin VB.Label lbl_CLSShipNb 
      Caption         =   "CLS Shipment n°"
      Height          =   255
      Left            =   7080
      TabIndex        =   58
      Top             =   2835
      Width           =   1410
   End
   Begin VB.Label lbl_DeliveryDate 
      Caption         =   "Delivery date"
      Height          =   255
      Left            =   150
      TabIndex        =   57
      Top             =   3345
      Width           =   1455
   End
   Begin VB.Label lbl_RSRequire 
      Caption         =   "R/S requirements"
      Height          =   255
      Left            =   165
      TabIndex        =   56
      Top             =   4860
      Width           =   1455
   End
   Begin VB.Label lbl_CustName 
      Caption         =   "Customer name"
      Height          =   255
      Left            =   150
      TabIndex        =   55
      Top             =   1935
      Width           =   1455
   End
   Begin VB.Label lbl_ShipAdd 
      Caption         =   "Ship to address"
      Height          =   255
      Left            =   150
      TabIndex        =   54
      Top             =   2340
      Width           =   1455
   End
   Begin VB.Label lbl_QuantityWeight 
      Caption         =   "Quantity/Weight"
      Height          =   255
      Left            =   150
      TabIndex        =   53
      Top             =   3885
      Width           =   1335
   End
   Begin VB.Label lbl_COSContact 
      Caption         =   "COS Contact"
      Height          =   255
      Left            =   165
      TabIndex        =   52
      Top             =   4365
      Width           =   1395
   End
   Begin VB.Label lbl_UOM 
      Alignment       =   1  'Right Justify
      Caption         =   "UOM"
      Height          =   255
      Left            =   2700
      TabIndex        =   51
      Top             =   3900
      Width           =   765
   End
   Begin VB.Label lbl_country 
      Caption         =   "Country"
      Height          =   255
      Left            =   4800
      TabIndex        =   50
      Top             =   1935
      Width           =   930
   End
   Begin VB.Label lbl_postCode 
      Caption         =   "Post Code"
      Height          =   255
      Left            =   7770
      TabIndex        =   49
      Top             =   1935
      Width           =   885
   End
   Begin VB.Label lbl_CLSDeliveryNb 
      Caption         =   "CLS Delivery  n°"
      Height          =   255
      Left            =   3690
      TabIndex        =   48
      Top             =   2835
      Width           =   1455
   End
   Begin VB.Label lbl_masterTran 
      Caption         =   "Master tran."
      Height          =   255
      Left            =   4890
      TabIndex        =   47
      Top             =   615
      Width           =   1155
   End
   Begin VB.Label lbl_paidByCustomer 
      Caption         =   "Customer Freight cost"
      Height          =   255
      Left            =   4950
      TabIndex        =   46
      Top             =   4410
      Visible         =   0   'False
      Width           =   1695
   End
   Begin VB.Label lbl_transactionOrder 
      Caption         =   "Transaction order"
      Height          =   255
      Left            =   4515
      TabIndex        =   45
      Top             =   990
      Width           =   1545
   End
   Begin VB.Label lbl_totalQty 
      Caption         =   "Total"
      Height          =   255
      Left            =   8550
      TabIndex        =   44
      Top             =   3885
      Visible         =   0   'False
      Width           =   675
   End
   Begin VB.Label lbl_RealQuantity 
      Caption         =   "Real Quantity loaded"
      Height          =   255
      Left            =   5685
      TabIndex        =   43
      Top             =   3885
      Visible         =   0   'False
      Width           =   1650
   End
End
Attribute VB_Name = "DC_Sample"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

'what is new
'2.6.9 : fixed bug to synchronize behaviour in add action when executed first time and next time(JN)
'2.9.5 : armsyscom support into the control
'2.9.5 : Price list support
'3.0.5 : Surcharges into pricelist support

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

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

Dim ms_MsgInfo As Variant

#If LIVE = 1 Then
    Dim mo_Sys As Object
    Dim mo_Db As Object
    Dim mo_sapXML As Object
'    Dim mo_scriptObj As Object
#Else
    Dim mo_Sys As ARMSYSCOMLib.ArmSYS
    Dim mo_Db As ARMSYSCOMLib.ArmDb
    Dim mo_sapXML As MSXML2.DOMDocument
'    Dim mo_scriptObj As MSScriptControl.ScriptControl       ' to calculate the price list formula
#End If


' screen constants for title
Private ms_Title As String
Private ms_titleA As String
Private ms_titleU As String
Private ms_titleD As String

Private ml_U_Code As Long
Private ms_LoginName As String
Private mb_Initialized As Boolean
Private ms_reconnectServer As String
Private ms_reconnectDB As String
Private ms_reconnectUser As String
Private ms_reconnectPassword As String
Private ms_reconnectApp As String
Private ms_Language_Code As String
Private mb_eventRunning As Boolean
Private mb_PL_STYLE_ENABLED As Boolean
Private ms_inTranName As String

Private ms_UrlWebService As String

Private ms_DC_Code As String
Private ms_DC_Name As String
Private md_shippingDay As Date
Private ms_CARRIER_Code As String

' line data
Private ms_custname As String
Private ms_CT_Code As String
Private ms_postCode As String
Private ms_address As String

Dim ml_d As Long
Dim ml_prevMasterTran As Long
Dim md_manualCost As Double
Dim mb_synchLoadedQty As Boolean
Dim ml_iConcurrency As Long

Const QTY_FOR_TRANSPORT As Boolean = True
Const QTY_FOR_COST As Boolean = False

Public Event RowAdded(ByVal av_Data As Variant)
Public Event RowUpdated(ByVal av_Data As Variant)
Public Event RowDeleted(ByVal av_Key As Variant)
Public Event quit()

Public Sub SetReconnectParams(ByVal as_Server As String, ByVal as_Db As String, ByVal as_User As String, ByVal as_Password As String, ByVal as_App As String)
On Error GoTo errhandler
    ms_reconnectServer = as_Server
    ms_reconnectDB = as_Db
    ms_reconnectUser = as_User
    ms_reconnectPassword = as_Password
    ms_reconnectApp = as_App
    Exit Sub
errhandler:
    Call ErrorMessage("SetReconnectParams")
End Sub

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

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(UserControl.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 Property Let DC_Code(ByVal as_DC_Code As String)
    ms_DC_Code = as_DC_Code
End Property

Public Property Let DC_name(ByVal as_DC_Name As String)
    ms_DC_Name = as_DC_Name
End Property

Public Property Let DC_Carrier(ByVal as_CARRIER_Code As String)
    ms_CARRIER_Code = as_CARRIER_Code
End Property

Public Property Let CUSTN1(ByVal as_CUSTN1 As String)
    ms_custname = as_CUSTN1
End Property

Public Property Let Ship_To_CT_Code(ByVal as_val As String)
    ms_CT_Code = as_val
End Property

Public Property Let Ship_To_Address(ByVal as_val As String)
    ms_address = as_val
End Property

Public Property Let Ship_To_Zip_Code(ByVal as_val As String)
    ms_postCode = as_val
End Property

Public Property Let ShippingDay(ByVal ad_shippingDay As Date)
    md_shippingDay = ad_shippingDay
End Property

Public Property Let TRANS_Code(ByVal al_Code As Long)
    ml_d = al_Code
End Property

Private Sub AddDay()
Dim ll_Cursor As Long
Dim li_Day As Long
Dim ls_req As String
Dim ld_AddDate As Date

On Error GoTo errhandler

    ls_req = "EXEC DC_AddDay_sel 'Customer', '" & ms_DC_Code & "', ''"
    
    ll_Cursor = OpenSQLSafe(mo_Db, ls_req)
    
    If Not mo_Db.EOF(ll_Cursor) Then
        li_Day = mo_Db.GetFields(ll_Cursor, "DaysToAdd")
    End If
    
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0

    ld_AddDate = StringToDate(right(txt_ShipDate, 10))
    txt_DeliveryDate = DateToString(DateAdd("d", li_Day, ld_AddDate))
    
    Exit Sub

errhandler:
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    
    Call errorHandler("AddDay")
End Sub

Private Function ControlOver()
Dim ls_req As String
Dim ll_Cursor As Long

Dim gs_message As String

ControlOver = KO
    gs_message = "Customer Calendar Max quantity exceeded !" & Chr(10) & "Confirm ?"

On Error GoTo suite

    ls_req = "EXEC DC_WFCustomer " _
        & SqlStr(ms_DC_Code) & ", " _
        & SqlDate(md_shippingDay)
    
    ll_Cursor = OpenSQLSafe(mo_Db, ls_req)
    
    Dim ls_OverDCFrom  As String
    ls_OverDCFrom = mo_Db.GetFields(ll_Cursor, "OverDCFrom")
    
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    If ls_OverDCFrom = "Y" Then
        If MsgBox(gs_message, vbQuestion + vbYesNo, "Over Load") = vbNo Then
            ssp_quit.SetFocus
            Exit Function
        End If
    End If
    
    If ls_OverDCFrom = "Y" Then
        ls_req = "EXEC Workflow_DCLoadPlan " _
            & SqlStr(ms_DC_Code) & ", " _
            & SqlDate(txt_ShipDate) _
            & ", 'Customer', ' Customer. Date : '"
            
        Call ExecuteSQLSafe(mo_Db, ls_req)
        
    End If
    ControlOver = OK
Exit Function

suite:
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    
    Call errorHandler("ControlOver")
End Function


Private Sub RefreshMasterTran(ByVal ab_keepSelection As Boolean)
On Error GoTo errhandler
        
    Dim ls_oldTran As String
    ls_oldTran = ""
    If ab_keepSelection Then
        ls_oldTran = GetCboKey(cbo_masterTran)
    Else
        ls_oldTran = ml_d
    End If
        
    Call cbo_masterTran.Clear
        
    cbo_masterTran.Request = "EXEC DC_MasterTrans_cbo_SAMPLE " & SqlStr(ms_DC_Code, 4, True) & ", " & SqlStr(GetCboKey(cbo_carrier), 10, True) & ", 'C', " & SqlDate(md_shippingDay) & ", " & SQLNum(ls_oldTran)

    If ab_keepSelection Then
        Call SetComboItemValue(cbo_masterTran, ls_oldTran)
    End If

    Exit Sub
errhandler:
    Call errorHandler("RefreshMasterTran")
End Sub

Private Sub RefreshCTInfo(ByVal ab_keepSelection As Boolean)
On Error GoTo errhandler

    Dim ls_prevUOM_Code As String
    Dim ls_prevCT_Code As String
    Dim ls_prevPostCode As String
    
    If ab_keepSelection Then
        ls_prevCT_Code = GetCboKey(cbo_country)
        ls_prevUOM_Code = GetCboKey(cbo_UOM)
        ls_prevPostCode = cbo_postCode.Text
    End If
    
    If SupportPriceList Then
        ' we can fill list the countries based on DC/Carrier/Shipping date
        
        cbo_country.Clear
        cbo_UOM.Clear
        
        If chk_manualPrice.value = vbChecked Then
            
            cbo_country.Request = "EXEC countries_cbo " & SqlStr(ms_Language_Code, 1)
            cbo_UOM.Request = "EXEC DC_PriceListUOM_cbo_all " & SQLNum(GetCboValue(cbo_carrier, "DC_CARRIER_Code")) & ", 'C', " & SqlDate(md_shippingDay) & "," & SqlStr(ms_Language_Code, 1)
        
        Else
            
            cbo_country.Request = "EXEC DC_PriceListCountries_cbo " & SQLNum(GetCboValue(cbo_carrier, "DC_CARRIER_Code")) & ", 'C', " & SqlDate(md_shippingDay) & "," & SqlStr(ms_Language_Code, 1)
            cbo_UOM.Request = "EXEC DC_PriceListUOM_cbo_all " & SQLNum(GetCboValue(cbo_carrier, "DC_CARRIER_Code")) & ", 'C', " & SqlDate(md_shippingDay) & "," & SqlStr(ms_Language_Code, 1)
'            cbo_UOM.Request = "EXEC DC_PriceListUOM_cbo " & SQLNum(GetCboValue(cbo_carrier, "DC_CARRIER_Code")) & ", 'C', " & SqlDate(md_shippingDay) & "," & SQLStr(ms_Language_Code, 1)
            
            If ab_keepSelection Then
                ' try to see if there is only one line in cbo_UOM and pick it
                Call cbo_UOM.Load
                If cbo_UOM.Count = 1 Then
                    'we pick it
                    ls_prevUOM_Code = cbo_UOM.ComboItems(1).Key
                End If
            End If
        
        End If
        
        If ab_keepSelection Then
            If ls_prevCT_Code <> "" Then
                If SetComboItemValue(cbo_country, ls_prevCT_Code) Then
                    Call RefreshZIPInfo(ab_keepSelection)
                Else
                    cbo_postCode.Clear
                End If
            End If
            
            If ls_prevUOM_Code <> "" Then
                Call SetComboItemValue(cbo_UOM, ls_prevUOM_Code)
            End If
            
        Else
            Call cbo_postCode.Clear
        End If
    
    Else
        
        cbo_country.Clear
        cbo_postCode.Clear
        
        If chk_manualPrice.value = vbChecked Then
            
            cbo_country.Request = "EXEC countries_cbo " & SqlStr(ms_Language_Code, 1)
        
            If ab_keepSelection Then
                
                If ls_prevCT_Code <> "" Then
                    Call SetComboItemValue(cbo_country, ls_prevCT_Code)
                End If
                
                cbo_postCode.Text = ls_prevPostCode
                
            End If
        Else
            
            cbo_country.Request = ""
        
        End If
        
        cbo_UOM.Clear
        cbo_UOM.Request = "EXEC DC_UOM_cbo2"
        
        If ab_keepSelection Then
            
            If ls_prevUOM_Code <> "" Then
                Call SetComboItemValue(cbo_UOM, ls_prevUOM_Code)
            End If
        
        End If

    End If
    Exit Sub
errhandler:
    Call errorHandler("RefreshCTInfo")
End Sub

Private Sub RefreshZIPInfo(ByVal ab_keepSelection As Boolean)
On Error GoTo errhandler

    If SupportPriceList And GetCboKey(cbo_country) <> "" Then
        ' we can fill list the post codes based on DC/Carrier/Shipping date/CT_Code
        Dim ls_prevZip_Code As String
        If ab_keepSelection Then
            ls_prevZip_Code = cbo_postCode.Text             ' GetCboKey(cbo_postCode)
        End If
        
        Call FillPostCombo(GetCboValue(cbo_carrier, "DC_CARRIER_Code"), md_shippingDay, GetCboKey(cbo_country), ls_prevZip_Code)
        
    Else
        Call cbo_postCode.Clear
    End If
    Exit Sub
errhandler:
    Call errorHandler("RefreshZIPInfo")
End Sub

Private Sub FillPostCombo(ByVal al_DC_CARRIER_Code As Long, ad_Date As Date, ByVal as_CT_Code As String, ByVal as_value As String)
On Error GoTo errhandler
Const C_REQ As String = "EXEC DC_PriceListZipCode_cbo $DC_CARRIER_Code$, 'C', $TRANS_Date$, $CT_Code$, $LANGUAGE_CODE$"
    
    Dim ls_req As String
    Dim ll_Cursor As Long
    
    ls_req = Replace(C_REQ, "$DC_CARRIER_Code$", al_DC_CARRIER_Code, , , vbTextCompare)
    ls_req = Replace(ls_req, "$TRANS_Date$", SqlDate(ad_Date), , , vbTextCompare)
    ls_req = Replace(ls_req, "$CT_Code$", SqlStr(as_CT_Code, 4), , , vbTextCompare)
    ls_req = Replace(ls_req, "$LANGUAGE_CODE$", SqlStr(ms_Language_Code, 1), , , vbTextCompare)
    
    ll_Cursor = OpenSQLSafe(mo_Db, ls_req)
    
    Call cbo_postCode.Clear
    
    While Not mo_Db.EOF(ll_Cursor)
    
        cbo_postCode.AddItem (mo_Db.GetFields(ll_Cursor, "DCPLL_Zip_Code"))
        cbo_postCode.ItemData(cbo_postCode.ListCount - 1) = mo_Db.GetFields(ll_Cursor, "DCPLL_Code")
        
        Call mo_Db.Next(ll_Cursor)
    Wend
    
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    cbo_postCode.Text = as_value

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

Private Sub FillMasterTrans(ByVal al_TRANS_Code As Long)
On Error GoTo errhandler

Const C_REQ As String = "EXEC DC_MasterTrans_sel $TRANS_Code$"

Dim ll_Cursor As Long
    ll_Cursor = OpenSQLSafe(mo_Db, Replace(C_REQ, "$TRANS_Code$", al_TRANS_Code))

    txt_tranOrder = mo_Db.GetFields(ll_Cursor, "TRANS_Order") + 1
    txt_COSContact = mo_Db.GetFields(ll_Cursor, "COS_Contact")
    txt_TrailerNb = mo_Db.GetFields(ll_Cursor, "Trailer_Number")
    txt_HaulierBookNb = mo_Db.GetFields(ll_Cursor, "Haulier_Booking_Number")
    txt_LoadBy = mo_Db.GetFields(ll_Cursor, "Load_By")
    
    Call SetComboItemValue(cbo_carrier, mo_Db.GetFields(ll_Cursor, "CARRIER_Code"))
    Call RefreshCTInfo(True)
    Call SetComboItemValue(cbo_Equipement, mo_Db.GetFields(ll_Cursor, "EQ_code"))
'    Call SetComboItemValue(cbo_country, mo_Db.GetFields(ll_cursor, "Ship_To_CT_Code"))
    Call RefreshZIPInfo(True)
'    cbo_postCode.Text = mo_Db.GetFields(ll_cursor, "Ship_To_Zip_Code")
    Call SetComboItemValue(cbo_UOM, mo_Db.GetFields(ll_Cursor, "UOM_code"))
    Call SetComboItemValue(cbo_currency, mo_Db.GetFields(ll_Cursor, "CUST_FC_Currency"))
    
    If mo_Db.GetFields(ll_Cursor, "Stand_Trailer") = "Y" Then
        Opt_Yes.value = True
    Else
        Opt_No.value = True
    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("FillMasterTrans")
End Sub



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

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

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


Private Function SQLNum(ByVal as_str As String) As String
    If as_str = "" Then
        SQLNum = "NULL"
    Else
        SQLNum = Replace(as_str, ",", ".")
    End If
End Function




Private Sub cbo_Carrier_ComboItemSelected()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    mb_eventRunning = True
    
    Call LockScreen(True)
    
    Call RefreshMasterTran(True)
    
    Call RefreshCTInfo(True)
    
    Call UpdatePriceListUI
    
    mb_eventRunning = False
    
    Call LockScreen(False)
    
    Exit Sub
errhandler:
    Call LockScreen(False)
    mb_eventRunning = False
    ErrorMessage ("cbo_carrier_ComboItemSelected")
End Sub


Private Sub cbo_country_ComboItemSelected()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    mb_eventRunning = True
    
    Call LockScreen(True)
    
    Call RefreshZIPInfo(cbo_postCode.ListIndex = -1)
    
    mb_eventRunning = False
    
    Call LockScreen(False)
    
    Exit Sub
errhandler:
    Call LockScreen(False)
    mb_eventRunning = False
    Call ErrorMessage("cbo_country_ComboItemSelected")
End Sub

Private Sub cbo_delivery_Click()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    mb_eventRunning = True
        
    Call LockScreen(True)

    Dim lsa_Array() As String
    
    lsa_Array = Split(cbo_delivery.Text, "/", , vbTextCompare)
    Debug.Assert (UBound(lsa_Array) >= 0)
    
    Call LockScreen(False)
    mb_eventRunning = False
    Exit Sub
errhandler:
    Call LockScreen(False)
    mb_eventRunning = False
    Call ErrorMessage("cbo_delivery_Change")
End Sub

Private Function ReturnNonAlpha(ByVal as_str As String) As String
On Error GoTo errhandler
    ReturnNonAlpha = ""
    
    Dim ls_retVal As String
    ls_retVal = ""
    
    Dim ll_i As Long
    For ll_i = 1 To Len(as_str)
        If IsNumeric(Mid(as_str, ll_i, 1)) Then
            ls_retVal = ls_retVal & Mid(as_str, ll_i, 1)
        End If
    Next
    
    ReturnNonAlpha = ls_retVal
    Exit Function
errhandler:
    Call errorHandler("ReturnNonAlpha")
End Function


Private Sub cbo_masterTran_ComboItemSelected()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    mb_eventRunning = True

    Call LockScreen(True)
    
    If GetCboKey(cbo_masterTran) <> "" Then
        Call FillMasterTrans(cbo_masterTran.SelectedItem.Key)
    Else
        txt_tranOrder.Text = "1"
    End If
    
    Call UpdatePriceListUI

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


Private Sub chk_manualPrice_Click()
On Error GoTo errhandler

    cbo_Carrier_ComboItemSelected

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


Private Sub Form_Activate()
On Error GoTo errhandler
    
    If gs_Action = "Delete" Then
        spp_save.SetFocus
    ElseIf gs_Action = "MoreInfo" Then
        ssp_quit.SetFocus
    Else
        txt_QuantityWeight.SetFocus
    End If
    
    Exit Sub
errhandler:
    Call ErrorMessage("Form_Activate")
End Sub

Private Sub spp_save_Click()
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    Call UserControl.ValidateControls
    
    mb_eventRunning = True
    Call LockScreen(True)
    gb_Return = OK
    Select Case gs_Action
    Case "Add":
        If Add_Table Then
            Call LockScreen(False)
            RaiseEvent quit
            mb_eventRunning = False
            Exit Sub
        End If
    Case "Update":
        If Upd_Table Then
            Call LockScreen(False)
            RaiseEvent quit
            mb_eventRunning = False
            Exit Sub
        End If
    Case "Delete":
        If Dlt_Table Then
            Call LockScreen(False)
            RaiseEvent quit
            mb_eventRunning = False
            Exit Sub
        End If
    End Select
    
    Call LockScreen(False)
    UserControl.Refresh
    DoEvents
    mb_eventRunning = False
    Exit Sub
errhandler:
    If Err.Number = 380 Then        ' validation failed
        Exit Sub
    End If
    
    Call LockScreen(False)
    mb_eventRunning = False
    Call ErrorMessage("spp_save_Click")
End Sub




Private Sub SSDeliveryDate_Click()
On Error GoTo suite
    Call LockScreen(True)
    gb_Return = KO
    gs_Date = txt_DeliveryDate
    Dates.Show 1
    If gb_Return Then
        txt_DeliveryDate = gs_Date
    End If
    Call LockScreen(False)
    Exit Sub
suite:
    Call LockScreen(False)
    Call ErrorMessage("SSDeliveryDate_Click")
End Sub


Private Sub ssp_quit_Click()
    RaiseEvent quit
End Sub


Private Sub SSShipDate_Click()
On Error GoTo suite
    Call LockScreen(True)
    gb_Return = KO
    gs_Date = txt_ShipDate
    Dates.Show 1
    If gb_Return Then
        txt_ShipDate = gs_Date
        md_shippingDay = gs_Date
        
        Call RefreshMasterTran(True)
        
    End If
    Call LockScreen(False)
Exit Sub
suite:
    Call LockScreen(False)
    Call ErrorMessage("SSShipDate_Click")
End Sub

Private Sub txt_ArrivalTime_GotFocus()
On Error GoTo errhandler
    Call LockScreen(True)
    
    If Len(txt_ArrivalTime) = 5 Then
        txt_ArrivalTime = Left(txt_ArrivalTime, 2) & right(txt_ArrivalTime, 2)
    End If

    txt_ArrivalTime.SelStart = 0
    txt_ArrivalTime.SelLength = Len(txt_ArrivalTime)

    Call LockScreen(False)
    Exit Sub
errhandler:
    Call LockScreen(False)
    Call ErrorMessage("txt_ArrivalTime_GotFocus")
End Sub


Private Sub txt_ArrivalTime_LostFocus()
On Error GoTo errhandler
    Call LockScreen(True)
    
    If Len(txt_ArrivalTime) = 5 And Mid(txt_ArrivalTime, 3, 1) = ":" Then
        txt_ArrivalTime = Left(txt_ArrivalTime, 2) & right(txt_ArrivalTime, 2)
    End If

    If Not CheckNumericValue(txt_ArrivalTime) Then
        SendMessage 5130, "Only numeric field is valid !", ms_Language_Code
        txt_ArrivalTime.SetFocus
        Call LockScreen(False)
        Exit Sub
    End If

    If Len(txt_ArrivalTime) <> 4 Then
        SendMessage 5140, "Wrong time format !", ms_Language_Code
        txt_ArrivalTime.SetFocus
        Call LockScreen(False)
        Exit Sub
    Else
        If Left(txt_ArrivalTime, 2) > 23 Or right(txt_ArrivalTime, 2) > 59 Then
            SendMessage 5140, "Wrong time format !", ms_Language_Code
            txt_ArrivalTime.SetFocus
        Else
            txt_ArrivalTime = Left(txt_ArrivalTime, 2) & ":" & right(txt_ArrivalTime, 2)
        End If
    End If

    Call LockScreen(False)

    Exit Sub
errhandler:
    Call LockScreen(False)
    Call ErrorMessage("txt_ArrivalTime_LostFocus")
End Sub


Private Sub txt_deliverydate_Change()
On Error GoTo errhandler
    If txt_DeliveryDate = "" Then Exit Sub
    
    If mb_eventRunning Then Exit Sub
    
    Call LockScreen(True)

    If DateDiff("d", StringToDate(txt_DeliveryDate), StringToDate(txt_ShipDate)) > 0 Then
        SendMessage 5150, "The delivery date must be greater" & Chr(10) & "than the shipping date", ms_Language_Code
        txt_DeliveryDate.SetFocus
    End If
    
    Call LockScreen(False)
    Exit Sub
errhandler:
    Call LockScreen(False)
    Call ErrorMessage("txt_deliverydate_Change")
End Sub

Private Sub txt_LoadEndTime_GotFocus()
On Error GoTo errhandler
    Call LockScreen(True)
    
    If Len(txt_LoadEndTime) = 5 Then
        txt_LoadEndTime = Left(txt_LoadEndTime, 2) & right(txt_LoadEndTime, 2)
    End If

    txt_LoadEndTime.SelStart = 0
    txt_LoadEndTime.SelLength = Len(txt_LoadEndTime)

    Call LockScreen(False)
    Exit Sub
errhandler:
    Call LockScreen(False)
    Call ErrorMessage("txt_LoadEndTime_GotFocus")
End Sub


Private Sub txt_LoadEndTime_LostFocus()
On Error GoTo errhandler
    Call LockScreen(True)

    If Len(txt_LoadEndTime) = 5 And Mid(txt_LoadEndTime, 3, 1) = ":" Then
        txt_LoadEndTime = Left(txt_LoadEndTime, 2) & right(txt_LoadEndTime, 2)
    End If

    If Not CheckNumericValue(txt_LoadEndTime) Then
        SendMessage 5130, "Only numeric field is valid !", ms_Language_Code
        txt_LoadEndTime.SetFocus
        Call LockScreen(False)
        Exit Sub
    End If

    If Len(txt_LoadEndTime) <> 4 Then
        SendMessage 5140, "Wrong time format !", ms_Language_Code
        txt_LoadEndTime.SetFocus
        Call LockScreen(False)
        Exit Sub
    Else
        If Left(txt_LoadEndTime, 2) > 23 Or right(txt_LoadEndTime, 2) > 59 Then
            SendMessage 5140, "Wrong time format !", ms_Language_Code
            txt_LoadEndTime.SetFocus
        Else
            txt_LoadEndTime = Left(txt_LoadEndTime, 2) & ":" & right(txt_LoadEndTime, 2)
        End If
    End If

    Call LockScreen(False)
    Exit Sub
errhandler:
    Call LockScreen(False)
    Call ErrorMessage("txt_LoadEndTime_GotFocus")
End Sub


Private Sub txt_LoadPlanEndTime_GotFocus()
On Error GoTo errhandler
    Call LockScreen(True)
    
    If Len(txt_LoadPlanEndTime) = 5 Then
        txt_LoadPlanEndTime = Left(txt_LoadPlanEndTime, 2) & right(txt_LoadPlanEndTime, 2)
    End If

    txt_LoadPlanEndTime.SelStart = 0
    txt_LoadPlanEndTime.SelLength = Len(txt_LoadPlanEndTime)

    Call LockScreen(False)
    Exit Sub
errhandler:
    Call LockScreen(False)
    Call ErrorMessage("txt_LoadEndTime_GotFocus")
End Sub


Private Sub txt_LoadPlanEndTime_LostFocus()
On Error GoTo errhandler
    Call LockScreen(True)

    If Len(txt_LoadPlanEndTime) = 5 And Mid(txt_LoadPlanEndTime, 3, 1) = ":" Then
        txt_LoadPlanEndTime = Left(txt_LoadPlanEndTime, 2) & right(txt_LoadPlanEndTime, 2)
    End If

    If Not CheckNumericValue(txt_LoadPlanEndTime) Then
        SendMessage 5130, "Only numeric field is valid !", ms_Language_Code
        txt_LoadPlanEndTime.SetFocus
        Call LockScreen(False)
        Exit Sub
    End If

    If Len(txt_LoadPlanEndTime) <> 4 Then
        SendMessage 5140, "Wrong time format !", ms_Language_Code
        txt_LoadPlanEndTime.SetFocus
        Call LockScreen(False)
        Exit Sub
    Else
        If Left(txt_LoadPlanEndTime, 2) > 23 Or right(txt_LoadPlanEndTime, 2) > 59 Then
            SendMessage 5140, "Wrong time format !", ms_Language_Code
            txt_LoadPlanEndTime.SetFocus
        Else
            txt_LoadPlanEndTime = Left(txt_LoadPlanEndTime, 2) & ":" & right(txt_LoadPlanEndTime, 2)
        End If
    End If

    Call LockScreen(False)
    Exit Sub
errhandler:
    Call LockScreen(False)
    Call ErrorMessage("txt_LoadEndTime_GotFocus")

End Sub


Private Sub txt_LoadPlanStartTime_GotFocus()
On Error GoTo errhandler
    Call LockScreen(True)

    If Len(txt_LoadPlanStartTime) = 5 Then
        txt_LoadPlanStartTime = Left(txt_LoadPlanStartTime, 2) & right(txt_LoadPlanStartTime, 2)
    End If

    txt_LoadPlanStartTime.SelStart = 0
    txt_LoadPlanStartTime.SelLength = Len(txt_LoadPlanStartTime)

    Call LockScreen(False)
    Exit Sub
errhandler:
    Call LockScreen(False)
    Call ErrorMessage("txt_LoadEndTime_GotFocus")
End Sub


Private Sub txt_LoadPlanStartTime_LostFocus()
On Error GoTo errhandler
    Call LockScreen(True)

    If Len(txt_LoadPlanStartTime) = 5 And Mid(txt_LoadPlanStartTime, 3, 1) = ":" Then
        txt_LoadPlanStartTime = Left(txt_LoadPlanStartTime, 2) & right(txt_LoadPlanStartTime, 2)
    End If

    If Not CheckNumericValue(txt_LoadPlanStartTime) Then
        SendMessage 5130, "Only numeric field is valid !", ms_Language_Code
        txt_LoadPlanStartTime.SetFocus
        Call LockScreen(False)
        Exit Sub
    End If

    If Len(txt_LoadPlanStartTime) <> 4 Then
        SendMessage 5140, "Wrong time format !", ms_Language_Code
        txt_LoadPlanStartTime.SetFocus
        Call LockScreen(False)
        Exit Sub
    Else
        If Left(txt_LoadPlanStartTime, 2) > 23 Or right(txt_LoadPlanStartTime, 2) > 59 Then
            SendMessage 5140, "Wrong time format !", ms_Language_Code
            txt_LoadPlanStartTime.SetFocus
        Else
            txt_LoadPlanStartTime = Left(txt_LoadPlanStartTime, 2) & ":" & right(txt_LoadPlanStartTime, 2)
        End If
    End If

    Call LockScreen(False)
    Exit Sub
errhandler:
    Call LockScreen(False)
    Call ErrorMessage("txt_LoadEndTime_GotFocus")

End Sub

Private Function FormatTime(ByVal as_Time As String) As String
On Error GoTo errhandler
    If Len(as_Time) = 4 Then
        FormatTime = Left(txt_LoadPlanStartTime, 2) & ":" & right(txt_LoadPlanStartTime, 2)
    Else
        FormatTime = as_Time
    End If

    Exit Function
errhandler:
    Call errorHandler("FormatTime")
End Function

Private Sub txt_LoadStartTime_GotFocus()
On Error GoTo errhandler
    Call LockScreen(True)

    If Len(txt_LoadStartTime) = 5 Then
        txt_LoadStartTime = Left(txt_LoadStartTime, 2) & right(txt_LoadStartTime, 2)
    End If

    txt_LoadStartTime.SelStart = 0
    txt_LoadStartTime.SelLength = Len(txt_LoadStartTime)

    Call LockScreen(False)
    Exit Sub
errhandler:
    Call LockScreen(False)
    Call ErrorMessage("txt_LoadEndTime_GotFocus")
End Sub


Private Sub txt_LoadStartTime_LostFocus()
On Error GoTo errhandler
    Call LockScreen(True)

    If Len(txt_LoadStartTime) = 5 And Mid(txt_LoadStartTime, 3, 1) = ":" Then
        txt_LoadStartTime = Left(txt_LoadStartTime, 2) & right(txt_LoadStartTime, 2)
    End If

    If Not CheckNumericValue(txt_LoadStartTime) Then
        SendMessage 5130, "Only numeric field is valid !", ms_Language_Code
        txt_LoadStartTime.SetFocus
        Call LockScreen(False)
        Exit Sub
    End If

    If Len(txt_LoadStartTime) <> 4 Then
        SendMessage 5140, "Wrong time format !", ms_Language_Code
        txt_LoadStartTime.SetFocus
        Call LockScreen(False)
        Exit Sub
    Else
        If Left(txt_LoadStartTime, 2) > 23 Or right(txt_LoadStartTime, 2) > 59 Then
            SendMessage 5140, "Wrong time format !", ms_Language_Code
            txt_LoadStartTime.SetFocus
        Else
            txt_LoadStartTime = Left(txt_LoadStartTime, 2) & ":" & right(txt_LoadStartTime, 2)
        End If
    End If

    Call LockScreen(False)
    Exit Sub
errhandler:
    Call LockScreen(False)
    Call ErrorMessage("txt_LoadEndTime_GotFocus")
End Sub



Private Function Control() As Boolean
On Error GoTo errhandler
    Control = KO
    
    If GetCboKey(cbo_carrier) = "" Then
        cbo_carrier.SetFocus
        SendMessage 8, "Value must be filled in", ms_Language_Code
        Exit Function
    End If
    If GetCboKey(cbo_Equipement) = "" Then
        cbo_Equipement.SetFocus
        SendMessage 8, "Value must be filled in", ms_Language_Code
        Exit Function
    End If
    If txt_CustName = "" Then
        txt_CustName.SetFocus
        SendMessage 8, "Value must be filled in", ms_Language_Code
        Exit Function
    End If
    If txt_ShipAdd = "" Then
        txt_ShipAdd.SetFocus
        SendMessage 8, "Value must be filled in", ms_Language_Code
        Exit Function
    End If
    If txt_CLSOrderNb = "" Then
        txt_CLSOrderNb.SetFocus
        SendMessage 8, "Value must be filled in", ms_Language_Code
        Exit Function
    End If
    If txt_DeliveryDate = "" Then
        txt_DeliveryDate.SetFocus
        SendMessage 8, "Value must be filled in", ms_Language_Code
        Exit Function
    End If
    If DateDiff("d", StringToDate(txt_DeliveryDate), StringToDate(txt_ShipDate)) > 0 Then
        SendMessage 8, "The delivery date must be greater" & Chr(10) & "than the shipping date", ms_Language_Code
        txt_DeliveryDate.SetFocus
        Exit Function
    End If
    If txt_QuantityWeight = "" Then
        txt_QuantityWeight.SetFocus
        SendMessage 8, "Value must be filled in", ms_Language_Code
        Exit Function
    End If
    If Not CheckNumericValue(txt_QuantityWeight) Then
        SendMessage 8, "Value must be a numeric", ms_Language_Code
        Call SetTextBoxFocus(txt_QuantityWeight)
        Exit Function
    End If
    
    If txt_RealQuantity = "" Then
        txt_RealQuantity.SetFocus
        SendMessage 8, "Value must be filled in", ms_Language_Code
        Exit Function
    End If
    If Not CheckNumericValue(txt_RealQuantity) Then
        SendMessage 8, "Value must be a numeric", ms_Language_Code
        Call SetTextBoxFocus(txt_RealQuantity)
        Exit Function
    End If
    
    If GetCboKey(cbo_UOM) = "" Then
        SendMessage 8, "Value must be filled in", ms_Language_Code
        cbo_UOM.SetFocus
        Exit Function
    End If

    If txt_tranOrder.Text = "" Then
        txt_tranOrder.SetFocus
        SendMessage 8, "Value must be filled in", ms_Language_Code
        Exit Function
    End If
    
    If Not CheckNumericValue(txt_tranOrder) Then
        SendMessage 8, "Value must be a numeric", ms_Language_Code
        Call SetTextBoxFocus(txt_tranOrder)
        Exit Function
    End If

    If txt_paidByCustomer.Text = "" Then
        txt_paidByCustomer.SetFocus
        SendMessage 8, "Value must be filled in", ms_Language_Code
        Exit Function
    End If

    If Not CheckNumericValue(txt_paidByCustomer) Then
        SendMessage 8, "Value must be a numeric", ms_Language_Code
        Call SetTextBoxFocus(txt_paidByCustomer)
        Exit Function
    End If

    If Val(txt_paidByCustomer.Text) <> 0# And cbo_currency.SelectedItem Is Nothing Then
        SendMessage 8, "Value must be filled in", ms_Language_Code
        cbo_UOM.SetFocus
        Exit Function
    End If
    
    
    If SupportPriceList Then
    
        
        If GetCboKey(cbo_country) = "" Then
            SendMessage 8, "Value must be filled in", ms_Language_Code
            cbo_country.SetFocus
            Exit Function
        End If
        
        If cbo_postCode.Text = "" Then
            SendMessage 8, "Value must be filled in", ms_Language_Code
            cbo_postCode.SetFocus
            Exit Function
        End If
        
    Else
        If chk_manualPrice.value = vbChecked Then
            If GetCboKey(cbo_country) = "" Then
                SendMessage 8, "Value must be filled in", ms_Language_Code
                cbo_country.SetFocus
                Exit Function
            End If
            
            If cbo_postCode.Text = "" Then
                SendMessage 8, "Value must be filled in", ms_Language_Code
                cbo_postCode.SetFocus
                Exit Function
            End If
        End If
    End If
    
    Control = OK
    Exit Function
errhandler:
    Call errorHandler("Control")
End Function

Private Sub Customer_constants()
On Error GoTo errhandler

Dim ll_Cursor As Long
Dim ls_Text As String
    
    ll_Cursor = OpenSQLSafe(mo_Db, "EXEC Screen_Csts 'mtnc_DC_Customer' , " & SqlStr(ms_Language_Code, 1))

    Do While Not mo_Db.EOF(ll_Cursor)

        ls_Text = mo_Db.GetFields(ll_Cursor, "local_text")
        Select Case mo_Db.GetFields(ll_Cursor, "field_name")
            Case "title": ms_Title = ls_Text
            Case "titleA": ms_titleA = ls_Text
            Case "titleU": ms_titleU = ls_Text
            Case "titleD": ms_titleD = ls_Text
            Case "lbl_ShipFromDC": lbl_ShipFromDC = ls_Text
            Case "lbl_ShipDate": lbl_ShipDate = ls_Text
            Case "lbl_CarrierCpy": lbl_CarrierCpy = ls_Text
            Case "lbl_Equipement": lbl_Equipement = ls_Text
            Case "lbl_CustName": lbl_CustName = ls_Text
            Case "lbl_ShipAdd": lbl_ShipAdd = ls_Text
            Case "lbl_CLSOrderNb": lbl_CLSOrderNb = ls_Text
            Case "lbl_CLSShipNb": lbl_CLSShipNb = ls_Text
            Case "lbl_DeliveryDate": lbl_DeliveryDate = ls_Text
            Case "lbl_QuantityWeight": lbl_QuantityWeight = ls_Text
            Case "lbl_RealQuantity": lbl_RealQuantity = ls_Text
            Case "lbl_UOM": lbl_UOM = ls_Text
            Case "lbl_COSContact": lbl_COSContact = ls_Text
            Case "lbl_RSRequire": lbl_RSRequire = ls_Text
            Case "Fr_Schedule": Fr_Schedule.Caption = ls_Text
            Case "lbl_HaulierBookNb": lbl_HaulierBookNb = ls_Text
            Case "lbl_StandTrailers": lbl_StandTrailers = ls_Text
            Case "lbl_LoadPlanStartTim": lbl_LoadPlanStartTime = ls_Text
            Case "lbl_LoadPlanEndTime": lbl_LoadPlanEndTime = ls_Text
            Case "Fr_Actual": Fr_Actual.Caption = ls_Text
            Case "lbl_ArrivalTime": lbl_ArrivalTime = ls_Text
            Case "lbl_TrailerNb": lbl_TrailerNb = ls_Text
            Case "lbl_LoadStartTime": lbl_LoadStartTime = ls_Text
            Case "lbl_LoadEndTime": lbl_LoadEndTime = ls_Text
            Case "lbl_LoadBy": lbl_LoadBy = ls_Text
            
            Case "lbl_paidByCustomer": lbl_paidByCustomer = ls_Text
            Case "lbl_masterTran": lbl_masterTran = ls_Text
            Case "lbl_transactionOrder": lbl_transactionOrder = ls_Text
            Case "lbl_CLSDeliveryNb": lbl_CLSDeliveryNb = ls_Text
            Case "lbl_totalQty": lbl_totalQty = ls_Text
            Case "lbl_country": lbl_country = ls_Text
            Case "lbl_postCode": lbl_postCode = ls_Text
            Case "chk_manualPrice":
                chk_manualPrice.Caption = ls_Text
            Case "lbl_RealQuantity": lbl_RealQuantity = ls_Text
        End Select
        
        Call mo_Db.Next(ll_Cursor)
    Loop
    
    Call mo_Db.Close(ll_Cursor)

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

Private Function Add_Table() As Boolean
Const C_REQ As String = "EXEC DC_Samples_ins $TRANS_code$,$DC_CARRIER_Code$,$TRANS_Date$,$MASTER_TRANS_code$,$TRANS_Order$,$Supplier_Name$,$EQ_code$,$CUSTN1$,$Ship_To_CT_Code$,$Ship_To_Zip_Code$,$Ship_To_Address$,$Order_Number$,$Shipment_Number$,$Delivery_Number$,$Delivery_Date$,$Quantity$,$Quantity_loaded$,$UOM_code$,$Stand_Trailer$,$COS_Contact$,$Remark$,$Haulier_Booking_Number$,$Load_Planned_Starting_Time$,$Load_Planned_Ending_Time$,$Load_Arrival_Time$,$Trailer_Number$,$Load_Starting_Time$,$Load_Ending_Time$,$Load_By$,$CUST_Freight_Cost$,$CUST_FC_Currency$,$Receiving_DC$"
    Dim ls_req As String

On Error GoTo errhandler

    Dim lb_InTran As Boolean
    lb_InTran = False
    
    Add_Table = KO
    
    If Control Then
        If ControlOver Then
            Dim ls_newID As String
            
            ls_newID = mo_Db.SQLNextID("TRANS_code")
            If ls_newID = "" Then
                Call Err.Raise(1, "SQLNextID", "Missing definition for new ID:TRANS_code")
            End If
            
            ml_d = Val(ls_newID)
            
            ls_req = Replace(C_REQ, "$TRANS_code$", ml_d, , , vbTextCompare)
            Call Item_ReplacePlaceholders(ls_req)
            
            Call BeginTran("DC_TRANSACTION")
            lb_InTran = True
            
            Call ExecuteSQLSafe(mo_Db, ls_req, 1)
            
            Call CommitTran("DC_TRANSACTION")
            lb_InTran = False
            
            Dim ll_masterTran As Long
            ll_masterTran = Val(GetCboKey(cbo_masterTran))
            Call ReorderTransaction(ll_masterTran, Val(txt_tranOrder.Text))
            
            RaiseEvent RowAdded(Array(ml_d, ml_d & "/" & txt_tranOrder.Text, "", IIf(GetCboKey(cbo_masterTran) = CStr(ml_d), 1, 0), 1, 1, FormatTime(txt_LoadPlanStartTime.Text), txt_CustName.Text, txt_DeliveryDate.Text, GetCboKey(cbo_country), txt_ShipAdd.Text, txt_QuantityWeight.Text, txt_CLSShipNb.Text, GetCboKey(cbo_carrier), GetCboValue(cbo_carrier, "CARRIER_Name"), txt_RSRequire.Text, "", "S", "Sample Shipment", IIf(ll_masterTran = 0, ml_d, ll_masterTran)))
            Add_Table = OK
            
        End If
    End If
    
Exit Function

errhandler:
    If lb_InTran Then
        Call RollbackTran("DC_TRANSACTION")
        lb_InTran = False
    End If
    Call errorHandler("Add_Table")
End Function

Private Function Dlt_Table() As Boolean

Const C_REQ As String = "EXEC DC_Customer_del $TRANS_code$,$iConc$"

On Error GoTo errhandler
    Dim ls_req As String
    Dim lb_InTran As Boolean
    Dim ll_Cursor As Long
    
    lb_InTran = False
    Dlt_Table = KO

    Call LockScreen(False)
    If SendMessage(5, "Delete record ?", ms_Language_Code, vbQuestion + vbYesNo, "Delete ") = vbYes Then
        Call LockScreen(True)
        
        ' check if the transaction is master and if there is some other transaction linked
        Debug.Assert (GetCboKey(cbo_masterTran) <> "")
        
        If CStr(ml_d) = GetCboKey(cbo_masterTran) Then
            ' this is master transaction
            
            Dim ll_Count As Long
            
            ll_Cursor = OpenSQLSafe(mo_Db, "SELECT COUNT(TRANS_Code) AS transCount FROM DC_Transaction WHERE Master_TRANS_Code=" & SQLNum(ml_d))
            ll_Count = mo_Db.GetFields(ll_Cursor, "transCount")
            
            Call mo_Db.Close(ll_Cursor)
            ll_Cursor = 0
            
            If ll_Count >= 2 Then
                ReDim ms_MsgInfo(0, 1)
                ms_MsgInfo(0, 0) = "$TRAN_COUNT$"
                ms_MsgInfo(0, 1) = ll_Count - 1
                Call MsgBox(MsgText(5090, ms_Language_Code, "#Master transaction cannot be deleted when linked transaction exists : $TRAN_COUNT$", ms_MsgInfo), vbCritical Or vbOKOnly)
                Exit Function
            End If
            
        End If
        
        txt_QuantityWeight.Text = "0"
        mb_synchLoadedQty = True
        
        mb_eventRunning = False
        Dim lb_cancel As Boolean
        lb_cancel = False
        Call txt_QuantityWeight_Validate(lb_cancel)
        Debug.Assert (Not lb_cancel)
        mb_eventRunning = True
        
        Call BeginTran("DC_TRANSACTION")
        lb_InTran = True
        
'        DCCost1.GridDelete
        
        ls_req = Replace(C_REQ, "$TRANS_code$", SQLNum(ml_d), , , vbTextCompare)
        ls_req = Replace(ls_req, "$iConc$", SQLNum(ml_iConcurrency), , , vbTextCompare)
        
        Call ExecuteSQLSafe(mo_Db, ls_req, 1)
        
        Call CommitTran("DC_TRANSACTION")
        lb_InTran = False
        
        Call ReorderTransaction(Val(GetCboKey(cbo_masterTran)), Val(txt_tranOrder.Text))
        
        RaiseEvent RowDeleted(Array(ml_d))
        Dlt_Table = OK
    Else
        Call LockScreen(True)
    End If
    Exit Function
errhandler:
    Call LockScreen(False)
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    If lb_InTran Then
        Call RollbackTran("DC_TRANSACTION")
        lb_InTran = False
    End If

    Call errorHandler("Dlt_Table")
End Function

Private Function Upd_Table() As Boolean
Const C_REQ As String = "EXEC DC_Customer_upd $TRANS_code$,$iConc$,$DC_CARRIER_Code$,$TRANS_Date$,$MASTER_TRANS_code$,$TRANS_Order$,$Supplier_Name$,$EQ_code$,$CUSTN1$,$Ship_To_CT_Code$,$Ship_To_Zip_Code$,$Ship_To_Address$,$Order_Number$,$Shipment_Number$,$Delivery_Number$,$Delivery_Date$,$Quantity$,$Quantity_loaded$,$UOM_code$,$Stand_Trailer$,$COS_Contact$,$Remark$,$Haulier_Booking_Number$,$Load_Planned_Starting_Time$,$Load_Planned_Ending_Time$,$Load_Arrival_Time$,$Trailer_Number$,$Load_Starting_Time$,$Load_Ending_Time$,$Load_By$,$CUST_Freight_Cost$,$CUST_FC_Currency$,$Receiving_DC$"
Const C_REQ_END As String = "EXEC DC_Cust_End_upd $TRANS_code$,$iConc$,$Stand_Trailer$,$Haulier_Booking_Number$,$Load_Planned_Starting_Time$,$Load_Planned_Ending_Time$,$Load_Arrival_Time$,$Trailer_Number$,$Load_Starting_Time$,$Load_Ending_Time$,$Load_By$,$Quantity_loaded$"



On Error GoTo errhandler
    
    Dim ls_req As String
    Dim lb_InTran As Boolean
    Dim ll_Cursor As Long
    
    lb_InTran = False
    Upd_Table = KO


    If Control Then
    
        ls_req = Replace(C_REQ, "$TRANS_code$", SQLNum(ml_d), , , vbTextCompare)
        ls_req = Replace(ls_req, "$iConc$", SQLNum(ml_iConcurrency), , , vbTextCompare)
        Call Item_ReplacePlaceholders(ls_req)
        
        Call BeginTran("DC_TRANSACTION")
        lb_InTran = True
        
        Call ExecuteSQLSafe(mo_Db, ls_req, 1)
        
        Call CommitTran("DC_TRANSACTION")
        lb_InTran = False
        
        Dim ll_masterTran As Long
        ll_masterTran = Val(GetCboKey(cbo_masterTran))
        Call ReorderTransaction(ll_masterTran, Val(txt_tranOrder.Text))
        
        RaiseEvent RowUpdated(Array(ml_d, ml_d & "/" & txt_tranOrder.Text, "", IIf(GetCboKey(cbo_masterTran) = CStr(ml_d), 1, 0), 1, 1, FormatTime(txt_LoadPlanStartTime.Text), txt_CustName.Text, txt_DeliveryDate.Text, GetCboKey(cbo_country), txt_ShipAdd.Text, txt_QuantityWeight.Text, txt_CLSShipNb.Text, GetCboKey(cbo_carrier), GetCboValue(cbo_carrier, "CARRIER_Name"), txt_RSRequire.Text, "", "S", "Sample Shipment", IIf(ll_masterTran = 0, ml_d, ll_masterTran)))
        Upd_Table = OK
    End If
    Exit Function

errhandler:
    If lb_InTran Then
        Call RollbackTran("DC_TRANSACTION")
        lb_InTran = False
    End If
    
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    
    Call errorHandler("Upd_Table")
End Function

Private Sub ReorderTransaction(ByVal al_masterTran As Long, ByVal al_currentTranOrder As Long)
On Error GoTo errhandler
    Dim ll_Cursor As Long
    Dim ls_req As String
    
    If al_masterTran = 0 Then Exit Sub
    
    ' out of databae transaction we reorder the lines on the truck to keep current TRANS_Order as it is

Const C_TRAN_REQ_LST As String = "SELECT TRANS_Code, TRANS_Order FROM DC_Transaction WHERE Master_TRANS_Code=$MASTER_TRANS_code$ ORDER BY TRANS_Order, Z_last_upd DESC"
Const C_TRAN_REQ_UPD As String = "EXEC DC_Transaction_OrderUpd $TRANS_code$, $TRANS_Order$"
Const C_TRAN_REQ_UPD_MASTER As String = "EXEC DC_Transaction_MasterUpd $MASTER_TRANS_code$, $NEW_MASTER_TRANS_code$"
    
    ls_req = Replace(C_TRAN_REQ_LST, "$MASTER_TRANS_code$", SQLNum(al_masterTran), , , vbTextCompare)
    ll_Cursor = OpenSQLSafe(mo_Db, ls_req)
    
    Dim ll_correctOrder As Long
    ll_correctOrder = 1
    
    Dim ll_newMasterTran As Long
    ll_newMasterTran = 0
    
    While Not mo_Db.EOF(ll_Cursor)
        If ll_correctOrder <> mo_Db.GetFields(ll_Cursor, "TRANS_Order") Then
        
            ' if order to put is the same as our transaction we move to next
            If ll_correctOrder = al_currentTranOrder Then
                ll_correctOrder = ll_correctOrder + 1
            End If
            
            ' correct order if it is not current transaction
            If mo_Db.GetFields(ll_Cursor, "TRANS_Code") <> ml_d Then
                ls_req = Replace(C_TRAN_REQ_UPD, "$TRANS_code$", SQLNum(mo_Db.GetFields(ll_Cursor, "TRANS_Code")), , , vbTextCompare)
                ls_req = Replace(ls_req, "$TRANS_Order$", SQLNum(ll_correctOrder), , , vbTextCompare)
            
                Call ExecuteSQLSafe(mo_Db, ls_req)
                
                ' if we are updating first transaction in the truck -> it will become master
                If ll_correctOrder = 1 Then
                    ll_newMasterTran = mo_Db.GetFields(ll_Cursor, "TRANS_Code")
                End If
                
                ll_correctOrder = ll_correctOrder + 1
            End If
        Else
            If ll_correctOrder = 1 And al_currentTranOrder = 1 Then
                ll_newMasterTran = mo_Db.GetFields(ll_Cursor, "TRANS_Code")
            End If
            ll_correctOrder = ll_correctOrder + 1
        End If
    
        Call mo_Db.Next(ll_Cursor)
    Wend
    
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    If ll_newMasterTran <> 0 Then
        ' record new master transaction
        If Val(GetCboKey(cbo_masterTran)) <> ll_newMasterTran Then
            ls_req = Replace(C_TRAN_REQ_UPD_MASTER, "$MASTER_TRANS_code$", SQLNum(al_masterTran), , , vbTextCompare)
            ls_req = Replace(ls_req, "$NEW_MASTER_TRANS_code$", SQLNum(ll_newMasterTran), , , vbTextCompare)
            ls_req = Item_ReplacePlaceholders(ls_req)
            Call ExecuteSQLSafe(mo_Db, ls_req)
        End If
    End If

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

Private Function DateFormat(datedeb As String) As String

If Len(datedeb) = 5 Then
    DateFormat = Left(datedeb, 2) + right(datedeb, 2)
Else
    DateFormat = datedeb
End If

End Function

Private Sub Item_Load(ByVal al_TRANS_Code As Long)
Dim ll_Cursor As Long

On Error GoTo errhandler
    ml_d = al_TRANS_Code
    mb_synchLoadedQty = True
    
    If al_TRANS_Code = 0 Then
        md_manualCost = 0
        ml_prevMasterTran = 0
        chk_manualPrice.value = vbUnchecked
        txt_ShipFromDC = ms_DC_Name
        txt_ShipDate = DateToString(md_shippingDay)
        AddDay
        txt_LoadPlanStartTime = "0000"
        txt_LoadPlanEndTime = "0000"
        txt_LoadStartTime = "0000"
        txt_LoadEndTime = "0000"
        txt_ArrivalTime = "0000"
        txt_tranOrder = "1"
        txt_paidByCustomer = "0"
        txt_RealQuantity = "0"
        ' default currency based on market of a user
        ll_Cursor = OpenSQLSafe(mo_Db, "EXEC currencies_sel1 '" & ms_LoginName & "','" & ms_Language_Code & "'")
            Call SetComboItemValue(cbo_currency, mo_Db.GetFields(ll_Cursor, "curr_code"))
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0

'        DCCost1.TransCode = 0
        
        Call RefreshMasterTran(False)
        Call RefreshCTInfo(False)
    Else

        ll_Cursor = OpenSQLSafe(mo_Db, "EXEC Dc_Customer_dtl " & al_TRANS_Code)
        
        ' global vars
        DC_Code = mo_Db.GetFields(ll_Cursor, "DC_Code")
        DC_name = mo_Db.GetFields(ll_Cursor, "Supplier_Name")
        ShippingDay = mo_Db.GetFields(ll_Cursor, "TRANS_Date")
        ml_iConcurrency = mo_Db.GetFields(ll_Cursor, "iConcurrency")
        ml_prevMasterTran = mo_Db.GetFields(ll_Cursor, "Master_TRANS_Code")
        
        ' ui data
        txt_ShipFromDC.Text = ms_DC_Name
        txt_ShipDate.Text = DateToString(md_shippingDay)
        Call SetComboItemValue(cbo_carrier, mo_Db.GetFields(ll_Cursor, "CARRIER_Code"))
                
        chk_manualPrice.value = vbUnchecked
        
        Call RefreshMasterTran(False)
        Call RefreshCTInfo(False)
        
        If mo_Db.GetFields(ll_Cursor, "Ship_To_CT_Code") <> "" Then
            If Not SetComboItemValue(cbo_country, mo_Db.GetFields(ll_Cursor, "Ship_To_CT_Code")) Then
                ' country not found with the support of pricelist
                chk_manualPrice.value = vbChecked
                Call RefreshCTInfo(False)
                If Not SetComboItemValue(cbo_country, mo_Db.GetFields(ll_Cursor, "Ship_To_CT_Code")) Then
                    Call MsgBox(MsgText(5100, ms_Language_Code, "#Difficulties to load the country!"), vbInformation Or vbOKOnly)
                End If
            End If
        End If
        
        Call SetComboItemValue(cbo_Equipement, mo_Db.GetFields(ll_Cursor, "EQ_code"))
        If Not SetComboItemValue(cbo_UOM, mo_Db.GetFields(ll_Cursor, "UOM_Code")) And chk_manualPrice.value = vbUnchecked Then
            ' UOM not found with the support of pricelist
            chk_manualPrice.value = vbChecked
            Call RefreshCTInfo(True)
            If Not SetComboItemValue(cbo_UOM, mo_Db.GetFields(ll_Cursor, "UOM_Code")) Then
                 Call MsgBox(MsgText(5101, ms_Language_Code, "#Difficulties to load the UOM!"), vbInformation Or vbOKOnly)
            End If
        End If
        
        Call SetComboItemValue(cbo_currency, mo_Db.GetFields(ll_Cursor, "CUST_FC_Currency"))
        
        Call RefreshZIPInfo(False)
        cbo_postCode.Text = mo_Db.GetFields(ll_Cursor, "Ship_To_Zip_Code")
        
        
        Call SetComboItemValue(cbo_masterTran, mo_Db.GetFields(ll_Cursor, "Master_TRANS_Code"))
        
        txt_CustName.Text = mo_Db.GetFields(ll_Cursor, "CUSTN1")
        txt_ShipAdd = mo_Db.GetFields(ll_Cursor, "Ship_To_Address")
        txt_CLSOrderNb = mo_Db.GetFields(ll_Cursor, "Order_Number")
        txt_CLSShipNb = mo_Db.GetFields(ll_Cursor, "Shipment_Number")
        cbo_delivery.Text = mo_Db.GetFields(ll_Cursor, "Delivery_Number")
        txt_DeliveryDate = DateToString(mo_Db.GetFields(ll_Cursor, "Delivery_Date"))
        txt_QuantityWeight = mo_Db.GetFields(ll_Cursor, "Quantity")
        txt_RealQuantity = mo_Db.GetFields(ll_Cursor, "Quantity_loaded")
        chk_isReturn.value = IIf(mo_Db.GetFields(ll_Cursor, "Receiving_DC") = "", vbUnchecked, vbChecked)
        
        If mo_Db.GetFields(ll_Cursor, "Stand_Trailer") = "Y" Then
            Opt_Yes.value = OK
        Else
            Opt_No.value = OK
        End If
        txt_COSContact = mo_Db.GetFields(ll_Cursor, "COS_Contact")
        txt_RSRequire = mo_Db.GetFields(ll_Cursor, "remark")
        txt_HaulierBookNb = mo_Db.GetFields(ll_Cursor, "Haulier_Booking_Number")
        txt_LoadPlanStartTime = mo_Db.GetFields(ll_Cursor, "Load_Planned_Starting_Time")
        txt_LoadPlanEndTime = mo_Db.GetFields(ll_Cursor, "Load_Planned_Ending_Time")
        txt_ArrivalTime = mo_Db.GetFields(ll_Cursor, "Load_Arrival_Time")
        txt_TrailerNb = mo_Db.GetFields(ll_Cursor, "Trailer_Number")
        txt_LoadStartTime = mo_Db.GetFields(ll_Cursor, "Load_Starting_Time")
        txt_LoadEndTime = mo_Db.GetFields(ll_Cursor, "Load_Ending_Time")
        txt_LoadBy = mo_Db.GetFields(ll_Cursor, "Load_By")
        txt_tranOrder.Text = mo_Db.GetFields(ll_Cursor, "TRANS_Order")
        txt_paidByCustomer.Text = mo_Db.GetFields(ll_Cursor, "CUST_Freight_Cost")
        md_manualCost = mo_Db.GetFields(ll_Cursor, "Total_Cost_Manual")
        
        If al_TRANS_Code = mo_Db.GetFields(ll_Cursor, "Master_TRANS_Code") Then
            ' we are editing the master transaction that is inUse
            If Val(GetCboValue(cbo_masterTran, "InUse")) > 0 Then
                cbo_masterTran.Enabled = False
            End If
        End If
        
        If mo_Db.GetFields(ll_Cursor, "Quantity") <> mo_Db.GetFields(ll_Cursor, "Quantity_loaded") Then
            mb_synchLoadedQty = False
        End If
        
        Call mo_Db.Close(ll_Cursor)
        
    End If
    
    Call UpdatePriceListUI
    
    Call UpdateMasterTransUI
    
    Exit Sub

errhandler:
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
    End If
    Call errorHandler("Item_load")
End Sub

Private Sub Item_Clear()
On Error GoTo errhandler
    Dim lo_Control As Control
    For Each lo_Control In Controls
        If lo_Control.Tag <> "" Then
            Select Case UCase(TypeName(lo_Control))
            Case "ARMCOMBOBOX"
                Call lo_Control.Clear
            Case "COMBOBOX"
                Call lo_Control.Clear
            Case "ARMPICKER"
            Case "TOOLBARCONTROL"
            Case "ARMGRID"
            Case "ARMTREEVIEW"
            Case "ARMCHECKVIEW"
            Case "A_CALOCX"
            Case "TOOLBR"
            Case "TEXTBOX"
                lo_Control.Text = ""
            Case "CHECKBOX"
                lo_Control.value = vbUnchecked
            End Select
        End If
    Next
    
    Opt_No.value = True
      
    Exit Sub
errhandler:
    Call errorHandler("Item_Clear()")
End Sub

' 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(mo_Db, ml_U_Code, SCREEN_NAME, 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

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
    
      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"
          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
    
    Call ChangeCharset(Me, GetCodePageFromLanguage(mo_Db, ms_Language_Code))

#If LIVE = 1 Then
    Set mo_Sys = CreateObject("ArmSYSCOM.ArmSys")
    Set mo_sapXML = CreateObject("MSXML2.DOMDocument")
'    Set mo_scriptObj = CreateObject("MSScriptControl.ScriptControl")
#Else
    Set mo_Sys = New ARMSYSCOMLib.ArmSYS
    Set mo_sapXML = New MSXML2.DOMDocument
'    Set mo_scriptObj = New MSScriptControl.ScriptControl
#End If

'    mo_scriptObj.Language = "VBScript"
    
    spp_save.Picture = LoadResPicture(RES_OK, vbResIcon)
    ssp_quit.Picture = LoadResPicture(RES_QUIT, vbResIcon)
    SSShipDate.Picture = LoadResPicture(RES_DOWN2, vbResIcon)
    SSDeliveryDate.Picture = LoadResPicture(RES_DOWN2, vbResIcon)

    If Not mo_Db.IsConnected Then
        Call ReconnectSafe
    End If
    
'    DCCost1.dc_user = ms_LoginName
'    Set DCCost1.ArmDb = mo_Db
'    Call DCCost1.SetReconnectParams(ms_reconnectServer, ms_reconnectDB, ms_reconnectUser, ms_reconnectPassword, ms_reconnectApp)
'    DCCost1.Lang = ms_Language_Code
'    DCCost1.U_Code = ml_U_Code
'    Call DCCost1.Load_A_COM

    Call Customer_constants
    
    cbo_carrier.FirstBlankItem = False
    cbo_country.FirstBlankItem = False
    cbo_masterTran.FirstBlankItem = True

    cbo_currency.FirstBlankItem = True
    cbo_currency.Request = "EXEC DC_currencies_cbo " & SqlStr(ms_Language_Code, 1)
    
    cbo_Equipement.FirstBlankItem = False
    cbo_Equipement.Request = "EXEC DC_Equipement_cbo"
    
    cbo_UOM.FirstBlankItem = False
    cbo_UOM.Request = "EXEC DC_UOM_cbo2"
    
    mb_eventRunning = False
    
    Exit Sub
    
errhandler:
    
    ' called from outside of the form
    Call ErrorMessage("Load_A_COM")
    
End Sub

Public Sub InitControl()
On Error GoTo errhandler
    mb_eventRunning = True
    
    Dim lsa_PLs() As String
    lsa_PLs = Split(Get_A_Config("DC_PL_STYLE"), SEP)
    
    Dim ll_i As Long
    mb_PL_STYLE_ENABLED = False
    For ll_i = LBound(lsa_PLs) To UBound(lsa_PLs)
        If lsa_PLs(ll_i) = ms_DC_Code Then
            mb_PL_STYLE_ENABLED = True
            Exit For
        End If
    Next
    
    ms_UrlWebService = Get_A_Config("DC_WEBSERVICE_ORDER_DATA")
    
    Call Item_Clear
    
    cbo_carrier.Request = "EXEC DC_Carrier_lst2 " & SqlStr(ms_DC_Code, 4) & ", 'C'," & SqlDate(md_shippingDay) & ", NULL"
    
    Call UpdateUI(gs_Action)
    
    If gs_Action = "Add" Then
        lbl_caption = ms_Title & " - " & ms_titleA
    ElseIf gs_Action = "Update" Then
        lbl_caption = ms_Title & " - " & ms_titleU
    ElseIf gs_Action = "Delete" Then
        lbl_caption = ms_Title & " - " & ms_titleD
    Else
        lbl_caption = ms_Title
    End If

    
    If gs_Action = "Add" Then
        Dim ll_oldTran As Long
        ll_oldTran = ml_d
        Call Item_Load(0)
        
        If ll_oldTran > 0 Then
            mb_eventRunning = False
            Call SetComboItemValue(cbo_masterTran, ll_oldTran)
            mb_eventRunning = True
            
            ' fill address, country, post code
            Call SetComboItemValue(cbo_country, ms_CT_Code)
            cbo_postCode.Text = ms_postCode
            txt_CustName.Text = ms_custname
            txt_ShipAdd.Text = ms_address
            
        Else
            ' assign default carrier
            mb_eventRunning = False
            Call SetComboItemValue(cbo_carrier, ms_CARRIER_Code)
            mb_eventRunning = True

        End If
        
        'default value
        txt_CLSOrderNb.Text = "0"
        
    Else
        Call Item_Load(ml_d)
'        DCCost1.Enabled = (gs_Action = "Update")
    End If
    
    mb_eventRunning = False
    
    ' set focus dependent of action
    Call Form_Activate

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

Private Property Get SupportPriceList() As Boolean
On Error GoTo errhandler
    SupportPriceList = mb_PL_STYLE_ENABLED And Val(GetCboValue(cbo_carrier, "DCPL_Count")) > 0 And txt_ShipDate.Text <> ""
    Exit Property
errhandler:
    Call errorHandler("SupportPriceList()")
End Property

Private Sub UpdatePriceListUI()
On Error GoTo errhandler
    Dim lb_supportPL As Boolean
    lb_supportPL = SupportPriceList

    If lb_supportPL Or chk_manualPrice.value = vbChecked Then
        ' OK we have a price list
        txt_CustName.Width = cbo_carrier.Width
        cbo_country.Visible = True
        lbl_country.Visible = True
        
        cbo_postCode.Visible = True
        lbl_postCode.Visible = True
        
    Else
        ' no pricelist available
        txt_CustName.Width = txt_ShipAdd.Width
        cbo_country.Visible = False
        lbl_country.Visible = False
        
        cbo_postCode.Visible = False
        lbl_postCode.Visible = False
        
    End If
    
    Dim lb_supportSurcharge As Boolean
    lb_supportSurcharge = Val(GetCboValue(cbo_carrier, "DCS_Count")) > 0
    
    Exit Sub
errhandler:
    Call errorHandler("UpdatePriceListUI()")
End Sub

Private Sub UpdateMasterTransUI()
On Error GoTo errhandler
    If (gs_Action <> "Add" And gs_Action <> "Update") Then Exit Sub
    
    If Val(GetCboKey(cbo_masterTran)) = ml_d Then
        Call EnableControl(cbo_carrier, True)
        Call EnableControl(cbo_Equipement, True)
    Else
        Call EnableControl(cbo_carrier, False)
        Call EnableControl(cbo_Equipement, False)
    End If
    Exit Sub
errhandler:
    Call errorHandler("UpdateMasterTransUI()")
End Sub

Private Sub UpdateUI(ByVal as_Mode As String)
On Error GoTo errhandler
    Select Case as_Mode
        
        Case "Add"
            Call SetEnabled(UserControl.Controls, True)
            Call EnableControl(txt_RealQuantity, False)
            Call EnableControl(txt_ShipFromDC, False)
            Call EnableControl(txt_totalQty, False)
            
            SSShipDate.Visible = False
            spp_save.Visible = True
        Case "Update"
            Call SetEnabled(UserControl.Controls, True)
            Call EnableControl(txt_RealQuantity, False)
            Call EnableControl(txt_ShipFromDC, False)
            Call EnableControl(txt_totalQty, False)
            
            SSShipDate.Visible = True
            spp_save.Visible = True
        Case "Delete"
            Call SetEnabled(UserControl.Controls, False)
            SSShipDate.Visible = False
            spp_save.Visible = True
            Call EnableControl(spp_save, True)
            Call EnableControl(ssp_quit, True)
        Case "MoreInfo"
            Call SetEnabled(UserControl.Controls, False)
            SSShipDate.Visible = False
            spp_save.Visible = False
            Call EnableControl(ssp_quit, True)
    End Select
    
    ' allways locked
    txt_ShipDate.Locked = True
    txt_DeliveryDate.Locked = True
    
    Exit Sub
errhandler:
    Call errorHandler("UpdateUI()")
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
    
'    Call DCCost1.Unload_A_COM
    
    Set mo_Sys = Nothing
    
'    Set mo_scriptObj = Nothing
    
    Exit Sub
    
errhandler:
    
    Call errorHandler("UnLoad_A_Com")
    
End Sub


Private Function ReconnectSafe() As Boolean
On Error GoTo errhandler

    ReconnectSafe = False
    
    Dim ll_Counter As Long
    ll_Counter = 3              ' try 3 times to connect
    
    If IsLostConnection(mo_Db) Then
    
        Call mo_Db.Disconnect
        
        Do While ll_Counter > 0
        
            If mo_Db.Connect(ms_reconnectServer, ms_reconnectDB, ms_reconnectUser, ms_reconnectPassword, ms_reconnectApp) Then
                ReconnectSafe = True
                Exit Do
            End If
            
            ll_Counter = ll_Counter - 1
        Loop
        
    End If
    
    Exit Function
errhandler:
     Call errorHandler("ReconnectSafe()")
End Function

Private Function IsLostConnection(ByRef ao_Armdb As ArmDb) As Boolean
On Error GoTo errhandler
    
    IsLostConnection = Not ao_Armdb.IsConnected
    
    If IsArray(ao_Armdb.SQLErrorCodes) Then
        Dim lv_ErrCode As Variant
        Dim ll_Index As Long
        
        lv_ErrCode = ao_Armdb.SQLErrorCodes
        
        For ll_Index = LBound(lv_ErrCode) To UBound(lv_ErrCode)
            If lv_ErrCode(ll_Index) = 11 Then       '[DBNETLIB][ConnectionWrite (send()).]General network error. Check your network documentation.
                IsLostConnection = True
                Exit For
            End If
        Next

    End If
    
    Exit Function
errhandler:
     Call errorHandler("IsLostConnection()")
End Function


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
tryAgain:
    lc_Data = ao_db.OpenSQL(as_Request)
    If lc_Data = 0 Then
        
        MsgBox ("Execution failed")
        
        Dim ls_ErrMsg As String
        ls_ErrMsg = "SQL Error: " & GetDbError(ao_db)
        
        If ReconnectSafe() Then
            GoTo tryAgain
        End If
        
        Call Err.Raise(1, "ao_Db.OpenSQL - " & "SQL : " & as_Request, ls_ErrMsg)
    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(UserControl.Name & ".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

tryAgain:
    ' First execute the request
    If Not ao_db.ExecuteSQL(as_Request) Then
        MsgBox ("Execution failed")
        
        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
        
        Dim ls_ErrMsg As String
        ls_ErrMsg = Join(ao_db.SQLErrorCodes, SEP2) & SEP1 & Join(ao_db.SQLErrorMessages, SEP2)
        
        If ReconnectSafe() Then
            GoTo tryAgain
        End If
        
        Err.Raise 1, "SQL : " & as_Request, ls_ErrMsg
    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(UserControl.Name & ".ExecuteSQLSafe")
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 Function Get_A_Config(ByVal TheKey As String) As String
On Error GoTo Get_A_Config_er
Dim curs As Long
Dim ls_req As String

    Get_A_Config = ""
    ls_req = "select cfg_value from A_config where cfg_Key ='" & UCase(TheKey) & "'"
    curs = 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 Function Item_ReplacePlaceholders(ls_retVal As String) As String
On Error GoTo errhandler

    ls_retVal = Replace(ls_retVal, "$DC_CARRIER_Code$", SQLNum(GetCboValue(cbo_carrier, "DC_CARRIER_Code")), , , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$TRANS_Date$", SqlDate(StringToDate(txt_ShipDate.Text)), , , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$MASTER_TRANS_code$", SQLNum(GetCboKey(cbo_masterTran)), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$TRANS_Order$", SQLNum(txt_tranOrder.Text), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Supplier_Name$", SqlStr(txt_ShipFromDC.Text, 80), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$EQ_code$", SqlStr(cbo_Equipement.Text, 30, True), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$CUSTN1$", SqlStr(txt_CustName.Text, 80), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Ship_To_CT_Code$", SqlStr(GetCboKey(cbo_country), 4, True), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Ship_To_Zip_Code$", SqlStr(Trim(cbo_postCode.Text), 20, True), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Ship_To_Address$", SqlStr(txt_ShipAdd.Text, 80), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Order_Number$", SqlStr(txt_CLSOrderNb.Text, 20), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Shipment_Number$", SqlStr(txt_CLSShipNb.Text, 20), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Delivery_Number$", SqlStr(cbo_delivery.Text, 20), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Delivery_Date$", SqlDate(StringToDate(txt_DeliveryDate.Text)), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Quantity$", SQLNum(txt_QuantityWeight.Text), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Quantity_loaded$", SQLNum(txt_RealQuantity.Text), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$UOM_code$", SqlStr(cbo_UOM.Text, 4, True), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Stand_Trailer$", SqlStr(IIf(Opt_Yes.value, "Y", "N")), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$COS_Contact$", SqlStr(txt_COSContact.Text, 15), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Remark$", SqlStr(txt_RSRequire.Text, 240), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Haulier_Booking_Number$", SqlStr(txt_HaulierBookNb, 15), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Load_Planned_Starting_Time$", SqlStr(DateFormat(txt_LoadPlanStartTime.Text), 4), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Load_Planned_Ending_Time$", SqlStr(DateFormat(txt_LoadPlanEndTime.Text), 4), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Load_Arrival_Time$", SqlStr(DateFormat(txt_ArrivalTime.Text), 4), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Trailer_Number$", SqlStr(txt_TrailerNb, 15), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Load_Starting_Time$", SqlStr(DateFormat(txt_LoadStartTime.Text), 4), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Load_Ending_Time$", SqlStr(DateFormat(txt_LoadEndTime.Text), 4), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Load_By$", SqlStr(txt_LoadBy.Text, 15), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$CUST_Freight_Cost$", SQLNum(txt_paidByCustomer.Text), , , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$CUST_FC_Currency$", SqlStr(GetCboKey(cbo_currency), 5, True), , vbTextCompare)
    ls_retVal = Replace(ls_retVal, "$Receiving_DC$", SqlStr(IIf(chk_isReturn.value = vbChecked, ms_DC_Code, ""), 4, True), , vbTextCompare)

    ls_retVal = Replace(ls_retVal, "$DCS_quantity$", SQLNum(1), , vbTextCompare)
    

    Item_ReplacePlaceholders = ls_retVal
    Exit Function
errhandler:
    Call errorHandler(UserControl.Name & ".Item_ReplacePlaceholders")
End Function

Private Sub EnableControl(ByVal ao_Control As Control, ByVal ab_Enabled As Boolean)
On Error GoTo errhandler

    Select Case UCase(TypeName(ao_Control))
        Case "FRAME", "LABEL", "MSFLEXGRID", "SHAPE", "ARMGRID", "ARMCHECKVIEW", "TABSTRIP"
            ao_Control.Enabled = ab_Enabled
            ' Do nothing !
        Case "LISTVIEW"
            ' Do nothing !
        Case "TEXTBOX"
            ao_Control.Locked = Not ab_Enabled
            ao_Control.BackColor = IIf(ab_Enabled, CL_COLOR_ENABLED, CL_COLOR_DISABLED)
            ao_Control.TabStop = ab_Enabled
        Case "OPTIONBUTTON"
            ao_Control.Enabled = ab_Enabled
        Case "ARMCOMBOBOX", "A_CALOCX", "OPTIONBUTTON", "ARMTREEVIEW", "LISTBOX", "CHECKBOX", "COMBOBOX", "PICTUREBOX", "COMMANDBUTTON", "TOOLBARCONTROL"
            ao_Control.Enabled = ab_Enabled
            ao_Control.TabStop = ab_Enabled
        Case "DCCOST"
            ao_Control.Enabled = ab_Enabled
            ao_Control.TabStop = ab_Enabled
        Case Else
          Debug.Print ao_Control.Name
    End Select
  Exit Sub
errhandler:
  Call errorHandler("EnableControl")
End Sub

Private Sub SetEnabled(ByVal ao_srcCtrl As Object, ByVal ab_Value As Boolean)
On Error GoTo errhandler
    Dim lo_ctrl As Object
    For Each lo_ctrl In ao_srcCtrl
        Call EnableControl(lo_ctrl, ab_Value)
    Next
    Exit Sub
errhandler:
     Call errorHandler(UserControl.Name & ".SetEnabled()")
End Sub

Private Function GetContainedControlsChain(ByVal ao_parent As Object) As Collection
On Error GoTo errhandler
    Dim lo_retCollection As New Collection
    Dim lo_Control As Object
    
    For Each lo_Control In Controls
        If Not TypeOf lo_Control.Container Is DC_Sample Then
            If ao_parent.hwnd = lo_Control.Container.hwnd Then
                If TypeOf lo_Control Is frame Then
                    Dim lo_aux_collection As New Collection
                    Dim ll_i As Long
                    Set lo_aux_collection = GetContainedControlsChain(lo_Control)
                    For ll_i = 1 To lo_aux_collection.Count
                        lo_retCollection.add (lo_aux_collection.Item(ll_i))
                    Next
                Else
                    Call lo_retCollection.add(lo_Control)
                End If
            End If
        End If
    Next
    Set GetContainedControlsChain = lo_retCollection
    Exit Function
errhandler:
    Call errorHandler(UserControl.Name & ".GetContainedControlsChain()")
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(UserControl.Name & ".Max()")
End Function

Private Function GetCurrentQty(ByVal ab_forTransport As Boolean) As Double
On Error GoTo errhandler
    
    Dim ld_orderQty As Double
    Dim ld_realQty As Double
    
    If txt_QuantityWeight.Text <> "" And IsNumericValue(txt_QuantityWeight.Text) Then
        ld_orderQty = Val(txt_QuantityWeight.Text)
    Else
        ld_orderQty = 0
    End If
    
    If txt_RealQuantity.Text <> "" And IsNumericValue(txt_RealQuantity.Text) Then
        ld_realQty = Val(txt_RealQuantity.Text)
    Else
        ld_realQty = 0
    End If
    
    If ab_forTransport Then
        GetCurrentQty = IIf(ld_realQty = 0, ld_orderQty, ld_realQty)
    Else
        GetCurrentQty = Max(ld_orderQty, ld_realQty)
    End If
    
    Exit Function
errhandler:
    Call errorHandler(UserControl.Name & ".GetCurrentQty()")
End Function


Private Sub txt_QuantityWeight_Validate(Cancel As Boolean)
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub
    
    If Not CheckNumericValue(txt_QuantityWeight.Text) Then
        Cancel = True
        txt_QuantityWeight.SelStart = 0
        txt_QuantityWeight.SelLength = Len(txt_QuantityWeight.Text)
        Exit Sub
    End If
    
    If mb_synchLoadedQty Then
        
        txt_RealQuantity.Text = txt_QuantityWeight.Text
    
    End If
    
    Exit Sub
errhandler:
    Call ErrorMessage(UserControl.Name & ".txt_QuantityWeight_Validate()")
End Sub

Private Sub txt_RealQuantity_Validate(Cancel As Boolean)
On Error GoTo errhandler
    If mb_eventRunning Then Exit Sub

    If Not CheckNumericValue(txt_RealQuantity.Text) Then
        Cancel = True
        txt_RealQuantity.SelStart = 0
        txt_RealQuantity.SelLength = Len(txt_RealQuantity.Text)
        Exit Sub
    End If
    
    Exit Sub
errhandler:
    Call ErrorMessage(UserControl.Name & ".txt_RealQuantity_Validate()")
End Sub

Private Function BeginTran(as_Tran As String) As Boolean

On Error GoTo errhandler
    BeginTran = False
    
    If ms_inTranName <> "" Then
        MsgBox ("Already in transaction!!!!! " & ms_inTranName)
        Exit Function
    End If
    
    ExecuteSQLSafe mo_Db, "BEGIN TRANSACTION " & as_Tran
    
    ms_inTranName = as_Tran

    BeginTran = True
    Exit Function
    
errhandler:
    'try to log error
'    Call LogMessage("BeginTran: " & as_Tran)
    Call mo_Db.Disconnect
    Set mo_Db = Nothing
    MsgBox "A Fatal error occured in " & SCREEN_NAME & ".BeginTran, your application will be close. Please contact your IT support", , App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
    End
End Function

Private Function CommitTran(as_Tran As String) As Boolean

On Error GoTo errhandler
    CommitTran = False
    
    If ms_inTranName <> as_Tran Then
        Call MsgBox("Warning!!! Commit transaction name does not match!!! " & as_Tran & "<>" & ms_inTranName, vbCritical)
    End If
    
    ExecuteSQLSafe mo_Db, "COMMIT TRANSACTION " & as_Tran

    ms_inTranName = ""
    CommitTran = True
    Exit Function
    
errhandler:
    'try to log error
'    Call LogMessage("CommitTran: " & as_Tran)
    Call mo_Db.Disconnect
    Set mo_Db = Nothing
    MsgBox "A Fatal error occured in " & SCREEN_NAME & ".CommitTran, your application will be close. Please contact your IT support", , App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
    End

End Function

Private Function RollbackTran(as_Tran As String) As Boolean
    
    Dim ll_errNumber As Long, ls_ErrSource As String, ls_ErrDesc As String
    ll_errNumber = Err.Number
    ls_ErrSource = Err.Source
    ls_ErrDesc = Err.Description

On Error GoTo errhandler
    RollbackTran = False
    
    If ms_inTranName <> as_Tran Then
        Call MsgBox("Warning!!! Rollback transaction name does not match!!! " & as_Tran & "<>" & ms_inTranName, vbCritical)
    End If
    
    ExecuteSQLSafe mo_Db, "ROLLBACK TRANSACTION " & as_Tran
    ms_inTranName = ""


    Err.Number = ll_errNumber
    Err.Source = ls_ErrSource
    Err.Description = ls_ErrDesc

    RollbackTran = True
    Exit Function
    
errhandler:
    'try to log error
'    Call LogMessage("RollbackTran: " & as_Tran)
    Call mo_Db.Disconnect
    Set mo_Db = Nothing
    MsgBox "A Fatal error occured in " & SCREEN_NAME & ".RollbackTran, your application will be close. Please contact your IT support", , App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
    End
End Function

Private Sub SetTextBoxFocus(ByRef ao_tb As TextBox)
On Error GoTo errhandler
    
    ao_tb.SelStart = 0
    ao_tb.SelLength = Len(ao_tb.Text)
    Call ao_tb.SetFocus

    Exit Sub
errhandler:
    Call errorHandler(UserControl.Name & ".SetTextBoxFocus")
End Sub

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



